diff --git a/.agents/skills/README.md b/.agents/skills/README.md new file mode 100644 index 00000000..993e75f3 --- /dev/null +++ b/.agents/skills/README.md @@ -0,0 +1,9 @@ +# Project skills + +Grok loads these from `.agents/skills/` (repo scope). + +| Skill | Use when | +| --- | --- | +| `rust-quality-coding` | 写或审查 Rust 时先做设计判断:所有权、领域类型、trait 拆分、错误与 async 边界 | + +`rust-quality-coding` 从 `../im/.agents/skills/rust-quality-coding` 复用。写公共 API、模块边界或后续 `RenderDocumentHandle` 这类所有权变化时先读它。 diff --git a/.agents/skills/rust-quality-coding/SKILL.md b/.agents/skills/rust-quality-coding/SKILL.md new file mode 100644 index 00000000..eb316f41 --- /dev/null +++ b/.agents/skills/rust-quality-coding/SKILL.md @@ -0,0 +1,111 @@ +--- +name: rust-quality-coding +description: Design and review idiomatic Rust around ownership, domain types, API and trait boundaries, errors, and concurrency. Use when a Rust change needs a design decision or a compiler error suggests the model is wrong; not for a lint-only or security-only review. +--- + +# Rust Quality Coding + +写 Rust 时,先让数据的流向和约束变得清楚,再让代码通过编译。这个 skill 提供的是设计顺序和取舍标准,不是一份把所有代码压成同一形状的禁令表。 + +Rust 的难处通常不在语法。一个 `borrow of moved value`、难以写出的 trait bound,或必须处处加 `Arc>`,往往说明数据的所有者、状态的边界或扩展点还没有决定好。把这些决定补上,编译器的限制会成为设计的校验,而不是需要绕过的障碍。 + +## 适用范围 + +在新增或改动类型、公共 API、trait、错误路径、并发代码、模块边界时使用。普通的局部表达式、命名或 clippy 风格问题不需要把本 skill 当成流程。 + +| 需要解决的问题 | 使用的资料 | +| --- | --- | +| 所有权、借用、领域类型、错误或生命周期 | [core.md](references/core.md) | +| trait、泛型、`impl Trait`、`dyn Trait`、标准 trait | [traits.md](references/traits.md) | +| async、任务、共享状态、channel、Axum 或协议解析 | [async-design.md](references/async-design.md) | + +`rust-strict` 负责安全审计;`rust-skills` 负责细粒度的惯例和工具使用。本 skill 负责在写之前和审查时做架构判断。涉及 unsafe、密钥、权限或并发安全时,同时遵从更严格的安全要求。 + +## 从问题到代码 + +先用几句话写出下面五件事。它们可以是注释、草稿或直接体现在类型和签名中;不用为此创建额外文档。 + +1. **值从哪里来,到哪里去。** 谁创建、谁最终释放?调用者只是在看、要修改,还是要接管它? +2. **哪些状态真的存在。** 哪些组合应当根本无法构造,哪些失败需要留给调用者处理? +3. **哪些边界需要稳定。** 是本模块内部的具体实现,还是跨 crate、替换实现、测试替身或运行时异质集合? +4. **哪里会等待或并发。** I/O、CPU 工作、共享状态和取消分别在哪里发生? +5. **错误在哪里转换成面向人的结果。** 底层需要保留什么信息,入口又需要怎样记录和呈现? + +按这个顺序落地,而不是先挑 `Arc`、泛型或 trait。 + +### 1. 先让类型排除错误状态 + +- 同一时刻只会是其中一种状态时,用带数据的 `enum`;让 `match` 覆盖所有业务分支。 +- 聚合一个实体或一组彼此同时存在的数据时,用 `struct`。 +- 两个值底层表示相同、却不能混用时,用 newtype,例如 `UserId` 和 `ProjectId`。 +- `Option` 表示缺失,`Result` 表示可以恢复的失败。不要把空字符串、零值或某个特殊整数同时当作正常值和“没有”。 + +不要为了“类型化”制造没有业务含义的包装。类型应该消除实际会发生的误用,或者把读者需要知道的单位、状态和权限放在签名里。 + +### 2. 再定所有权 + +函数签名先表达权限,再考虑少一次分配: + +| 调用者与函数的关系 | 常见签名 | +| --- | --- | +| 函数只读取 | `&T`、`&str`、`&[T]` | +| 函数原地修改 | `&mut T` | +| 函数接管、存储或异步转交 | `T` | +| 返回调用者独立持有的结果 | `T` | + +业务对象通常应拥有它的字段。这样对象能独立移动、放进集合和交给 task;只有确实需要借用输入、并且生命周期是 API 本身的一部分时,才让结构体携带引用。`String`/`Vec` 的只读参数写成 `&str`/`&[T]`,而不是 `&String`/`&Vec`。 + +当编译器拒绝借用时,先检查借用是否跨越了真正需要的范围、函数是否错误地接管了值、或状态是否该由一个任务独占。`.clone()` 是合理的所有权决策,但应能说清楚新副本由谁使用、为何不能借用。不要用随意的 `'static`、泄漏内存或散落的 `unsafe` 来让模型闭嘴。 + +### 3. 抽象只服务于一个边界 + +模块内部先用具体类型和普通函数。出现以下真实需求后,再引入 trait:调用方需要替换实现、核心逻辑需要测试替身、库要允许外部实现,或运行时确实要装下不同实现。 + +- 已知且封闭的变体,用 `enum`。它把每个分支交给穷尽匹配检查。 +- 调用方选择实现、每次调用只有一种具体类型,用泛型或参数位置的 `impl Trait`。 +- 实现方隐藏一种固定的具体返回类型,用返回位置的 `impl Trait`。 +- 需要运行时选择或异质集合,才用 `dyn Trait`;先验证对象安全和所有权(借用用 `&dyn Trait`,需要持有才用 `Box` 或 `Arc`)。 + +trait 描述一项可替换的能力,不是带字段的父类。把构造、存储、网络和业务操作塞进同一个 trait,会让实现者被迫依赖无关能力,也使替换变难。关联类型适合“一个实现对应一个输出类型”;trait 类型参数适合“同一实现需要与多种右侧类型交互”。细节和例子见 [traits.md](references/traits.md)。 + +### 4. 让错误沿着架构边界流动 + +在失败发生处保留足够的信息,并用 `?` 交给能做出决定的上一层。库和可复用模块通常需要让调用者区分错误;应用入口、HTTP handler 或命令行入口则可以补充上下文、记录日志并映射成退出码或响应。 + +是否采用 `thiserror`、`anyhow` 或项目现有错误类型取决于边界和仓库约定。不要为了统一而把所有错误提前转成 `String`,也不要把用户输入、网络、文件和数据库失败当作不变量而 `unwrap()`。 + +### 5. 把并发放在资源边界 + +只有等待 I/O、协调多个独立任务或同时服务多个请求时,才让调用链进入 async。纯计算保持同步;重计算或不可避免的同步库在 async 运行时中应移到专门的阻塞执行路径。 + +跨 task 传递一个值,优先转移所有权;多个 task 共享只读数据用 `Arc`;共享可变状态时,先问能否让一个 task 独占状态并通过 channel 接收命令。确实需要共享时,再选择合适的锁或原子类型。锁的临界区应短,并且不能不经思考地跨 `.await` 保存 guard。 + +不要因为文件里出现 `async` 就引入 Tokio,也不要因为项目使用 Tokio 就把纯函数改成 `async fn`。沿用仓库已有的运行时和框架;新增运行时是架构选择,需要明确理由。详见 [async-design.md](references/async-design.md)。 + +## 编译器报错时如何回到设计 + +先读完整错误和涉及的签名,不要立即加 bound 或 clone。常见症状对应的检查方向: + +| 症状 | 先检查 | +| --- | --- | +| moved value | 哪一层本应拥有值?该参数是否本该借用,或是否需要一个有明确用途的副本? | +| borrow 冲突 | 两次访问是否真的需要重叠?能否缩短借用、拆字段、先收集信息再修改? | +| lifetime 迅速传播 | 数据是否应在边界转为拥有型?引用是否确实要成为返回值或结构体字段? | +| trait bound 变得很长 | 抽象是否放得太早?能力是否被混在一个 trait 中?是否应改为具体类型、关联类型或 `where` 子句? | +| `Send` / `Sync` 或 spawn 失败 | task 是否持有了借用、非线程安全类型或锁 guard?数据的所有权该如何跨 task 转移? | +| `dyn Trait` 不可用 | 是否真的需要动态分发?若需要,能否把构造/泛型/`Self` 相关方法移到 `Self: Sized` 的扩展 trait 或独立构造器? | + +在修复前先选择一条能解释业务关系的路径;能编译但把资源生命周期、错误或可变性藏起来的补丁不算完成。 + +## 提交前的设计复核 + +只检查本次改动触及的部分: + +- 类型是否表达了真实的状态、单位和失败,而不是依赖哨兵值或注释? +- 每个跨函数或跨 task 的值,是否有清晰的所有者和可变性? +- 公共 API 是否只暴露调用者确实需要的类型、trait 和生命周期? +- trait 是否来自实际替换需求,且每个方法都属于同一项能力? +- 错误是否能到达处理边界,保留排查所需的来源和上下文? +- async 代码是否避免阻塞运行时,并有明确的状态共享、背压和退出方式? + +高质量 Rust 的标志不是零个 `clone`、零个 trait 或所有类型都泛型化,而是读者能沿签名看出值如何流动、哪些状态可能发生,以及失败在哪里被处理。 diff --git a/.agents/skills/rust-quality-coding/references/async-design.md b/.agents/skills/rust-quality-coding/references/async-design.md new file mode 100644 index 00000000..85903960 --- /dev/null +++ b/.agents/skills/rust-quality-coding/references/async-design.md @@ -0,0 +1,50 @@ +# Async、并发与服务边界 + +async 的价值是让等待 I/O 的任务互不堵塞,不是把每个函数都改成 `async fn`。先画出任务、资源和消息的关系,再选 runtime、锁和 channel。项目已有运行时与框架时,优先遵循其约定;新引入 Tokio、Axum 或其他运行时属于架构决策。 + +## 划出 async 边界 + +让网络、文件、数据库、timer 和外部 RPC 等等待点位于 async 调用链中。领域计算、验证、格式化和纯数据转换保持同步,除非它们本身要等待。长时间 CPU 计算或无法替换的阻塞库不能直接占用 async worker;将它们移到运行时提供的 blocking executor 或专用线程,并让调用者能处理执行结果。 + +`spawn` 表示独立生命周期:task 可能比创建它的栈帧活得久。把 task 所需的拥有值移进去,或 clone 一个明确的共享句柄;不要让 task 借用局部变量。若 task 的结果、错误或退出时机重要,就保留并 await `JoinHandle`;丢弃 handle 不是取消策略。 + +## 共享状态前先选择所有权模型 + +| 状态关系 | 首选设计 | +| --- | --- | +| 一个 task 可以独占状态,其他人发请求 | task 持有状态,使用 channel 传命令和回复 | +| 多 task 只读同一份数据 | `Arc` | +| 多 task 短暂读写同一对象 | `Arc>` 或 `Arc>`,按访问模式选锁 | +| 简单计数或标志 | 合适的原子类型,并说明所需内存序 | + +锁只能保护一个清晰的不变量。持锁区间内完成必须原子完成的读、校验和写,然后释放 guard,再执行网络、sleep、channel 等待或重计算。异步 mutex 可以技术上跨 `.await`,但这会串行化其他使用者并放大死锁与延迟风险;只有设计明确要求时才这样做。同步 mutex 在 async 代码中并非一律错误,但它必须非常短,且 guard 绝不能跨 `.await`。 + +## Channel 表达拓扑与背压 + +选择 channel 应由消息如何流动决定: + +| 关系 | 常见选择 | +| --- | --- | +| 多生产者,一个处理者 | `mpsc` | +| 一次请求,一次回复 | `oneshot`,常作为 mpsc 消息的一部分 | +| 每个订阅者都应看到事件 | `broadcast` | +| 消费者只关心当前最新值 | `watch` | + +队列容量是产品语义的一部分:有界队列把生产过快变成可等待或可拒绝的背压;无界队列把风险变成内存增长。为关闭定义协议:谁停止发送、谁丢弃 sender、谁处理 `recv() == None` 和发送失败。并发等待所有任务时用 join/收集 handles;只要第一个完成或多个事件中任意一个时用 `select!`,并明确其余工作是否取消、继续还是需要清理。 + +## 网络和协议 + +TCP 是字节流,不提供消息边界。协议层必须定义长度前缀、分隔符、固定长度或其他 framing;业务 handler 接收完整消息,而不是猜测一次 `read` 是否恰好读全。收到 EOF 表示对端关闭写端,应走连接关闭逻辑。 + +解析结构化文本或二进制时,先把输入、剩余输入、成功值和错误类型写进小 parser 的签名,再组合它们。是否选 nom、手写 parser 或 serde 取决于协议和已有依赖;关键是解析失败不能悄悄变成默认业务值,并且各层都有可测的边界。 + +## HTTP 服务中的边界 + +以 Axum 为例,router 把 URL 和中间件组织成模块;handler 负责提取 HTTP 输入、调用领域服务并转换响应。请求 DTO、领域模型和存储记录可相同,也可不同;当它们的校验、字段暴露或演进速度不同,就应分开。 + +- body 只能消费一次,因此会读取 body 的 extractor(如 `Json`)需要放在其他 extractor 之后。 +- `AppState` 持有明确共享的依赖,例如连接池和配置,并通过框架 state 注入。避免 handler 隐式读取可变全局。 +- 统一错误响应时,为领域错误实现到 HTTP 响应的映射;不要在每个 handler 里复制 `match` 或 `unwrap`。 +- 使用项目已有的结构化日志与 request tracing。日志记录边界事件、失败上下文和相关标识,避免把敏感输入当调试文本输出。 + +服务代码的可维护性来自边界清楚:transport 处理协议,应用层协调用例,领域层维护不变量,基础设施实现 I/O。它们不必为形式上的分层创建空壳模块,但不应让 HTTP、SQL 或 runtime 细节渗入所有业务类型。 diff --git a/.agents/skills/rust-quality-coding/references/core.md b/.agents/skills/rust-quality-coding/references/core.md new file mode 100644 index 00000000..161e7a48 --- /dev/null +++ b/.agents/skills/rust-quality-coding/references/core.md @@ -0,0 +1,100 @@ +# 所有权、领域类型与错误边界 + +这份参考在你已经遇到所有权、类型或错误设计问题时使用。它不是“禁止清单”;每个选择都应该能回答数据为何要以这种形式存在。 + +## 所有权是资源生命周期 + +一个非 `Copy` 值在赋值、传参和返回时默认移动。移动不是复制失败,而是所有权从一个名字交给另一个名字;所有者离开作用域时,资源按 RAII 释放。 + +先从权限选择 API: + +```rust +fn render(name: &str) -> String { format!("hello, {name}") } +fn normalize(name: &mut String) { *name = name.trim().to_owned(); } +fn enqueue(job: Job) { /* 保存或交给另一个 task */ } +``` + +`&T` 可以并存,`&mut T` 必须独占。这条规则把“谁能在何时修改”写进类型。遇到借用冲突时,优先缩小引用的活跃范围、先提取所需信息、或把互不相关的状态拆开;不要把整个对象包进一个锁来掩盖边界。 + +### 借用与拥有的常见边界 + +| 目的 | 优先选择 | 原因 | +| --- | --- | --- | +| 读取文本或序列 | `&str`、`&[T]` | 接受更多输入,且不承诺保存它 | +| 需要长期保存输入 | `String`、`Vec`、`PathBuf` | 保存者拥有数据,生命周期不会传给调用者 | +| 递归数据或稳定堆地址 | `Box` | 一个拥有者,堆分配是结构需要而非共享手段 | +| 单线程共享可变 | 先重划所有权;必要时 `Rc>` | 运行时检查借用,不能跨线程 | +| 跨线程/任务共享只读 | `Arc` | 共享所有权,不自动提供可变性 | +| 跨线程/任务共享可变 | 单一所有者 + channel;必要时 `Arc>` / `Arc>` | 先选择状态协调模型,再选择同步原语 | + +`Clone` 表示创建另一份值,通常比让结构体早早携带引用更容易保持边界清楚。它也可能很贵,因此应当让调用点说明意图。`Copy` 则意味着赋值隐式复制,只适用于复制语义自然、字段也都可复制的小值。不要为了少写 `.clone()` 而让一个有资源语义的类型变成 `Copy`。 + +## 类型应承担不变量 + +`struct` 用于同时存在的数据,`enum` 用于互斥的状态。先把状态空间列出来,再选类型: + +```rust +enum Upload { + Pending { bytes: Vec }, + InFlight { id: RequestId }, + Complete { location: Url }, + Failed { reason: UploadError }, +} +``` + +这里不可能同时处在 `Pending` 和 `Complete`,因此不需要 `status: String` 加多个可空字段。反过来,若字段确实可独立存在,硬塞进 enum 会使正常更新变得别扭。 + +当 `String`、`u64` 或 `Duration` 的“底层一样”会导致领域混用时,使用 newtype: + +```rust +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +struct UserId(u64); +``` + +newtype 应该表示边界、单位或权限,而不是为每个原始字段增加一层名字。为输入建立构造器或 `TryFrom`,把验证放在值进入领域模型的位置;这样内部代码不必重复检查。 + +### 字符串、路径和字节 + +- 拥有且可修改的 UTF-8 文本用 `String`;临时只读视图用 `&str`。 +- 文件路径用 `Path`/`PathBuf`,操作系统字符串用 `OsStr`/`OsString`,C 边界用 `CStr`/`CString`。 +- 网络帧、哈希和二进制协议优先建模为字节;不要假定它们是 UTF-8。 +- Rust 不允许按整数索引 `str`,因为 UTF-8 是变长编码。需要按 Unicode scalar value 遍历用 `.chars()`;需要字节则明确使用 `.as_bytes()`。 + +`&String` 和 `&Vec` 很少表达额外语义,通常应改为 `&str` 和 `&[T]`。若 API 必须保存调用者交来的数据,可用 `impl Into` 等入口转换;不要在每一层都把泛型转换参数继续传播。 + +## Option、Result 与错误层次 + +`Option` 只回答“值有没有”。`Result` 还说明“为什么没有”。在这两者之间转换时,先确认是否愿意丢失错误信息。 + +```rust +fn read_config(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(ConfigError::Read)?; + toml::from_str(&text).map_err(ConfigError::Parse) +} +``` + +错误类型的粒度由谁要做决定决定: + +- 可复用模块或库需要调用者恢复、重试或匹配错误时,保留结构化错误(常见为枚举)。 +- 应用边界通常应附加动作相关的上下文,再记录或转换为 CLI/HTTP/UI 的错误。`anyhow` 很适合许多应用内部的“向上带上下文”,但不是所有项目必须采用的统一类型。 +- `panic!`、`unwrap()`、`expect()` 留给已经由程序不变量保证的情况或测试。`expect` 信息应说明哪条不变量被违反,而不是重复“unwrap failed”。 + +不要在底层把错误格式化为字符串后再传递,那会失去来源、类型和可匹配性。若错误跨越抽象层,使用项目的转换约定、`From`、`map_err` 或 `#[from]` 保留因果关系。 + +## 生命周期是借用关系的一部分 + +生命周期不是延长对象寿命的开关,而是编译器验证引用不会悬垂的关系。函数返回引用时,返回值必须来自仍然有效的输入或 `self`;结构体存放引用时,生命周期自然成为它类型的一部分。 + +```rust +fn first_word(input: &str) -> &str { + input.split_whitespace().next().unwrap_or("") +} +``` + +如果生命周期参数从一个小结构体一路蔓延到任务、缓存和公共 API,先确认是否把短暂借用误当成了长期数据。边界处持有 `String`、`Vec` 或 `Arc` 往往更直接;但零拷贝解析器、视图类型和高性能库的公共引用 API 也完全正当。选择取决于调用者需要什么,不是单纯为了躲开 `'a`。 + +## unsafe 是需要证明的边界 + +安全代码把内存规则交给编译器;unsafe 代码由作者承担证明义务。把 unsafe 缩在很小的模块或函数内,对外提供能维持不变量的安全 API,并在 unsafe 紧邻处写清楚:指针来自哪里、对齐与有效范围如何保证、别名规则如何满足、以及析构责任归谁。 + +不要把 `unsafe`、`from_utf8_unchecked`、`get_unchecked`、`static mut` 或伪造的 `'static` 当作借用检查器的逃生门。它们只能在已证明前置条件的狭窄场景下出现,并应同时接受专门的安全审查。 diff --git a/.agents/skills/rust-quality-coding/references/traits.md b/.agents/skills/rust-quality-coding/references/traits.md new file mode 100644 index 00000000..47df6ae6 --- /dev/null +++ b/.agents/skills/rust-quality-coding/references/traits.md @@ -0,0 +1,83 @@ +# Trait 与公共接口的取舍 + +trait 是一份能力协议:它让泛型代码能要求某些操作,也让不同实现能在一个明确边界上互换。它不是类层级,也不是所有模块都应先抽出的接口。 + +## 先判断是否需要抽象 + +从具体类型开始通常最便宜。出现以下任一需求时,trait 才有稳定的理由:调用方应能提供实现、核心逻辑需要测试替身、多个实现共享同一操作、或插件需要在运行时进入集合。 + +若变体有限且由当前 crate 控制,用 `enum` 往往更好:每种状态可携带不同数据,新增变体会迫使所有 `match` 重新审视。trait 则把扩展权交给实现者,调用方不能穷尽列举具体类型。 + +```rust +// 封闭:所有状态属于这个协议本身。 +enum RetryPolicy { Never, Fixed(Duration), Exponential } + +// 开放:调用方可以定义新的实现。 +trait Clock { + fn now(&self) -> Instant; +} +``` + +一个 trait 的方法应共同描述一项能力。把“如何创建”“如何持久化”“如何序列化”和“核心业务操作”组合成一个大 trait,通常意味着使用方被迫依赖不需要的方法。构造可放在具体类型、自由函数或另一个明确的工厂协议中。 + +## 泛型、`impl Trait` 与 `dyn Trait` + +它们都能表示“满足某项能力”,但绑定时间不同: + +| 形式 | 谁选择具体类型 | 适合什么场景 | +| --- | --- | --- | +| `fn f(value: T)` | 调用方;每次调用可不同 | 需要静态分发,函数会持有或返回 `T` | +| `fn f(value: impl Trait)` | 同上,是简单泛型参数的写法 | 只需写清输入能力 | +| `fn f() -> impl Trait` | 实现方;所有返回路径是同一个隐藏类型 | 隐藏实现细节,不需要动态切换 | +| `&dyn Trait` | 运行时;调用方保有对象 | 临时借用的动态分发 | +| `Box` / `Arc` | 运行时;容器或结构体持有对象 | 异质集合、插件或延迟选择实现 | + +返回 `impl Trait` 不是“返回任意实现”。一个函数仍然只能选择一种具体返回类型;如果分支需要产生不同实现,先问是否应使用 enum,只有确实需要开放扩展或异质存储时才用 trait object。 + +### 对象安全是接口设计反馈 + +准备以 `dyn Trait` 使用的 trait,方法应能通过一个未知大小的对象调用。实例方法通常以 `&self` 或 `&mut self` 为 receiver;构造函数、返回 `Self` 的方法或泛型方法不应混进这个动态接口。若它们仍有价值,可写成具体类型的关联函数,或在 trait 中加 `where Self: Sized`,使其不属于 trait object 的可调用表面。 + +原生 `async fn` in trait 对静态分发很方便,但它不直接给你一个可对象化的 trait。需要 `dyn` 异步接口时,明确选择盒装 future 的签名或项目已采用的宏/库方案,并接受相应的分配、`Send` 和生命周期语义;不要在两种模型之间含混切换。 + +## 关联类型和 trait 类型参数 + +关联类型表示“某个实现确定一种关联结果”: + +```rust +trait Decode { + type Output; + fn decode(&self, input: &[u8]) -> Result; +} +``` + +同一个类型通常只应有一种 `Output`。若某类型要分别处理多种右侧操作数,类型参数更合适,例如 `Add` 可以针对不同的 `Rhs` 提供实现。选择的关键不是少写尖括号,而是实现者是否必须固定结果类型。 + +复杂 bound 用 `where` 排版,让约束紧挨着它约束的关联类型;不要为了短签名把不相关的类型参数传过整条调用链。 + +## 标准 trait 表达已有语义 + +只实现行为符合类型含义的标准 trait: + +| 需要的能力 | 选择 | 注意点 | +| --- | --- | --- | +| 开发者可诊断表示 | `Debug` | 大多数公共数据类型可 `derive(Debug)` | +| 面向用户的稳定文本 | `Display` | 手写格式;实现后自动获得 `ToString`,不要单独实现它 | +| 合理的空/初始值 | `Default` | 不要把“凑出的零值”伪装成业务默认值 | +| 相等或哈希 key | `PartialEq`,必要时 `Eq`/`Hash` | 浮点 NaN 不满足 `Eq`;语义相等应稳定 | +| 总排序或 BTree key | `Ord` 与相应比较 trait | 排序顺序应是领域认可的总序 | +| 明确复制 | `Clone` | 复制成本和语义应在调用处可见 | +| 隐式廉价复制 | `Copy` + `Clone` | 仅用于复制自然、所有字段也 `Copy` 的小值 | +| 无损拥有转换 | `From` | 实现 `From` 即可得到 `Into` | +| 可能失败的转换 | `TryFrom` | 不要把截断或校验失败藏在 `as` 中 | +| 解析文本 | `FromStr` | 让 `parse()` 成为一致入口 | +| 显式借用视图 | `AsRef`/`AsMut` | 可用于泛化入口;避免无意义的泛型传播 | +| 智能指针式透明访问 | `Deref`/`DerefMut` | 不要用作继承或给包装类型偷偷扩大 API | + +派生不是默认任务。它会把类型承诺给调用者:例如 `Clone` 允许复制,`Ord` 宣称排序有业务意义,`Default` 宣称无参数构造合理。按实际使用 derive,并让字段的行为与整体语义一致。 + +## coherence、方法冲突与模块边界 + +孤儿规则要求 `impl Trait for Type` 中的 trait 或类型至少一个属于当前 crate。不能实现外部 trait 到外部类型时,newtype 是有意的适配边界,而不是绕规则的技巧。 + +为某 trait 写 blanket implementation 前,先看它是否会占掉未来更具体的实现空间。方法同名时,Rust 不存在“子类覆盖”;使用 UFCS(`::method(...)`)说明调用哪个协议。只有调用方必须看见的协议才 `pub`,其余实现细节留在模块内。 diff --git a/AGENTS.md b/AGENTS.md index e4f47536..045c161d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,8 +10,10 @@ fire/ docs/ knowledge/ architecture/ - fire-native-workspace.md + fire-native-architecture.md + 2026-09-25-module-boundaries.md feedback-and-crash-reporting.md + release/ apps/ ios-app/ android-app/ diff --git a/README.md b/README.md index 11aebb36..855af04a 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ fire/ docs/ knowledge/ architecture/ - fire-native-workspace.md + release/ apps/ ios-app/ android-app/ diff --git a/apps/android-app/README.md b/apps/android-app/README.md index b8aaee22..03c8f617 100644 --- a/apps/android-app/README.md +++ b/apps/android-app/README.md @@ -91,7 +91,11 @@ the shared Rust core at build time. `TopicDetailActivity` now loads Rust-owned `TopicDetailPageState` from the combined topic-detail page path, where the source snapshot carries the full posts and the slim tree presentation carries only post id / number plus -hierarchy metadata plus the optional first-unread-root suggestion. It renders a +hierarchy metadata plus the optional first-unread-root suggestion. The Activity +type stays one host: lifecycle, fields, launchers, adapters, and +`TopicDetailRoute` live in `TopicDetailActivity.kt`; observe / scrolling / +search / composer / post management / bookmarks / reactions / topic voting / +user info / routing are same-package `internal` extensions. It renders a `ConcatAdapter` made of the topic header, original post, reply rows, and a loading footer. Load-more is driven only by the Rust source cursor over raw `post_stream.stream`, not by host-managed row windows. diff --git a/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelActivity.kt b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelActivity.kt index 1a99dedf..b5847fd9 100644 --- a/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelActivity.kt +++ b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelActivity.kt @@ -4,13 +4,9 @@ import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle -import android.view.LayoutInflater import android.view.View -import android.view.ViewGroup import android.widget.EditText import android.widget.ImageButton -import android.widget.ImageView -import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast @@ -22,26 +18,13 @@ import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.fire.app.R -import com.fire.app.core.image.FireAvatarUrls -import com.fire.app.core.image.FireImageLoader import com.fire.app.messagebus.FireMessageBusCoordinator -import com.fire.app.richtext.FireRenderPresentation -import com.fire.app.richtext.FireRichTextBlock -import com.fire.app.richtext.FireRichTextView -import com.fire.app.richtext.FireSpannableBuilder -import com.fire.app.session.FireSessionStore import com.fire.app.session.FireSessionStoreRepository import com.fire.app.ui.profile.FireUserCardSheet import com.google.android.material.appbar.MaterialToolbar import kotlinx.coroutines.Job import kotlinx.coroutines.launch -import uniffi.fire_uniffi_chat.ChatBusEventState -import uniffi.fire_uniffi_chat.ChatMessageReactionState import uniffi.fire_uniffi_chat.ChatMessageState -import uniffi.fire_uniffi_chat.ChatMessagesQueryState -import uniffi.fire_uniffi_chat.ChatReactionActionState -import uniffi.fire_uniffi_chat.SendChatMessageRequestState -import uniffi.fire_uniffi_messagebus.MessageBusEventState import uniffi.fire_uniffi_topics.UploadImageRequestState import java.util.UUID @@ -55,19 +38,12 @@ class ChatChannelActivity : AppCompatActivity() { private lateinit var attachButton: ImageButton private lateinit var sendButton: ImageButton private lateinit var adapter: ChatMessageAdapter + private lateinit var session: ChatChannelSession private var channelId: ULong = 0u private var threadId: ULong? = null - private var threadingEnabled = false - private var messages: List = emptyList() - private var pins: List = emptyList() - private var canLoadMorePast = false - private var isLoading = false + private var snapshot: ChatChannelSession.Snapshot? = null private var busJob: Job? = null - private val ownerToken = "chat-channel-activity" - private var busChannelName: String = "" - private var currentUserId: ULong? = null - private var chatBaseUrl: String = "https://linux.do" private val imagePicker = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> uri?.let { uploadAndSend(it) } @@ -79,9 +55,13 @@ class ChatChannelActivity : AppCompatActivity() { setContentView(R.layout.activity_chat_channel) channelId = intent.getLongExtra(EXTRA_CHANNEL_ID, 0L).toULong() + if (channelId == 0uL) { + finish() + return + } threadId = intent.getLongExtra(EXTRA_THREAD_ID, 0L).takeIf { it > 0 }?.toULong() val title = intent.getStringExtra(EXTRA_TITLE).orEmpty() - threadingEnabled = intent.getBooleanExtra(EXTRA_THREADING_ENABLED, false) + val threadingEnabled = intent.getBooleanExtra(EXTRA_THREADING_ENABLED, false) toolbar = findViewById(R.id.chat_channel_toolbar) pinBanner = findViewById(R.id.chat_pin_banner) @@ -117,141 +97,86 @@ class ChatChannelActivity : AppCompatActivity() { sendButton.setOnClickListener { sendMessage() } attachButton.setOnClickListener { imagePicker.launch("image/*") } pinBanner.setOnClickListener { - pins.firstOrNull()?.let { pin -> - val index = messages.indexOfFirst { it.id == pin.id } + snapshot?.pins?.firstOrNull()?.let { pin -> + val index = snapshot?.messages.orEmpty().indexOfFirst { it.id == pin.id } if (index >= 0) recyclerView.scrollToPosition(index) } } - busChannelName = threadId?.let { "/chat/$channelId/thread/$it" } ?: "/chat/$channelId" - lifecycleScope.launch { loadInitial() } busJob = lifecycleScope.launch { val store = FireSessionStoreRepository.get(this@ChatChannelActivity) - FireMessageBusCoordinator(store).chatEvents().collect { event -> - handleBusEvent(event) + session = ChatChannelSession( + store = store, + channelId = channelId, + threadId = threadId, + initialTitle = title, + initialThreadingEnabled = threadingEnabled, + ) + session.onChange = { next, change -> applySnapshot(next, change) } + session.onError = { error -> + Toast.makeText( + this@ChatChannelActivity, + error.message ?: getString(R.string.chat_load_failed), + Toast.LENGTH_LONG, + ).show() + } + launch { + FireMessageBusCoordinator(store).chatEvents().collect { event -> + session.handleBusEvent(event) + } } + session.open() } } override fun onDestroy() { busJob?.cancel() - lifecycleScope.launch { - val store = FireSessionStoreRepository.get(this@ChatChannelActivity) - store.unsubscribeMessageBusChannel(busChannelName, ownerToken) + if (::session.isInitialized) { + val openSession = session + lifecycleScope.launch { openSession.close() } } super.onDestroy() } - private suspend fun loadInitial() { - if (channelId == 0uL) { - finish() - return + private fun applySnapshot( + next: ChatChannelSession.Snapshot, + change: ChatChannelSession.Change, + ) { + snapshot = next + adapter.submit(next.messages, next.chatBaseUrl) + loadingView.visibility = if (next.isLoading && next.messages.isEmpty()) { + View.VISIBLE + } else { + View.GONE } - isLoading = true - try { - val store = FireSessionStoreRepository.get(this) - val bootstrap = store.snapshot().bootstrap - currentUserId = bootstrap.currentUserId - chatBaseUrl = bootstrap.baseUrl.ifBlank { "https://linux.do" } - store.cachedChatMessages(channelId, threadId)?.messages?.takeIf { it.isNotEmpty() }?.let { cached -> - messages = cached - adapter.submit(messages) - loadingView.visibility = View.GONE - } ?: run { loadingView.visibility = View.VISIBLE } - if (threadId == null) { - val channel = store.fetchChatChannel(channelId) - threadingEnabled = channel.threadingEnabled - toolbar.title = channel.displayTitle - pins = store.fetchChatChannelPins(channelId) - updatePinBanner() - if (pins.isNotEmpty()) { - runCatching { store.markChatChannelPinsRead(channelId) } - } - } - val query = ChatMessagesQueryState( - channelId = channelId, - direction = null, - targetMessageId = null, - fetchFromLastRead = true, - pageSize = 50u, - ) - val page = if (threadId != null) { - store.fetchChatThreadMessages(channelId, threadId!!, query).also { - runCatching { store.markChatThreadRead(channelId, threadId!!) } - } - } else { - store.fetchChatMessages(query) - } - messages = page.messages - canLoadMorePast = page.canLoadMorePast - adapter.submit(messages) - recyclerView.scrollToPosition((messages.size - 1).coerceAtLeast(0)) - page.messages.lastOrNull()?.id?.let { latest -> - if (threadId == null) { - runCatching { store.markChatChannelRead(channelId, latest) } - } - } - store.subscribeMessageBusChannel( - channel = busChannelName, - ownerToken = ownerToken, - lastMessageId = null, - ) - } catch (error: Exception) { - Toast.makeText(this, error.message ?: getString(R.string.chat_load_failed), Toast.LENGTH_LONG).show() - } finally { - isLoading = false - loadingView.visibility = View.GONE + if (threadId == null && next.title.isNotBlank()) { + toolbar.title = next.title + } + updatePinBanner() + when (change) { + ChatChannelSession.Change.Initial, + ChatChannelSession.Change.Latest, + -> recyclerView.scrollToPosition((next.messages.size - 1).coerceAtLeast(0)) + else -> Unit } } private fun loadMorePast() { - if (!canLoadMorePast || isLoading) return - val oldest = messages.firstOrNull() ?: return + if (!::session.isInitialized) return lifecycleScope.launch { - isLoading = true - try { - val store = FireSessionStoreRepository.get(this@ChatChannelActivity) - val query = ChatMessagesQueryState( - channelId = channelId, - direction = "past", - targetMessageId = oldest.id, - fetchFromLastRead = false, - pageSize = 50u, - ) - val page = if (threadId != null) { - store.fetchChatThreadMessages(channelId, threadId!!, query) - } else { - store.fetchChatMessages(query) - } - messages = page.messages + messages - canLoadMorePast = page.canLoadMorePast - adapter.submit(messages) - } catch (_: Exception) { - } finally { - isLoading = false - } + runCatching { session.command(ChatChannelSession.Command.LoadMorePast) } } } private fun sendMessage(textOverride: String? = null, uploadIds: List = emptyList()) { + if (!::session.isInitialized) return val text = textOverride ?: input.text?.toString()?.trim().orEmpty() if (text.isEmpty() && uploadIds.isEmpty()) return sendButton.isEnabled = false lifecycleScope.launch { try { - val store = FireSessionStoreRepository.get(this@ChatChannelActivity) - store.sendChatMessage( - SendChatMessageRequestState( - channelId = channelId, - message = text, - stagedId = UUID.randomUUID().toString(), - inReplyToId = null, - threadId = threadId, - uploadIds = uploadIds, - ), - ) + session.command(ChatChannelSession.Command.Send(text, uploadIds)) if (textOverride == null) input.setText("") - softRefreshLatest(store) } catch (error: Exception) { Toast.makeText( this@ChatChannelActivity, @@ -281,7 +206,6 @@ class ChatChannelActivity : AppCompatActivity() { if (uploadId != null && uploadId > 0uL) { sendMessage(textOverride = "", uploadIds = listOf(uploadId)) } else { - // Fallback: embed Discourse short URL markdown when id is absent. val alt = result.originalFilename?.takeIf { it.isNotBlank() } ?: "image" val markdown = "![${alt}](${result.shortUrl})" sendMessage(textOverride = markdown) @@ -296,30 +220,6 @@ class ChatChannelActivity : AppCompatActivity() { } } - private suspend fun softRefreshLatest(store: FireSessionStore) { - val query = ChatMessagesQueryState( - channelId = channelId, - direction = null, - targetMessageId = null, - fetchFromLastRead = false, - pageSize = 50u, - ) - val page = if (threadId != null) { - store.fetchChatThreadMessages(channelId, threadId!!, query) - } else { - store.fetchChatMessages(query) - } - messages = page.messages - canLoadMorePast = page.canLoadMorePast - adapter.submit(messages) - recyclerView.scrollToPosition((messages.size - 1).coerceAtLeast(0)) - page.messages.lastOrNull()?.id?.let { latest -> - if (threadId == null) { - runCatching { store.markChatChannelRead(channelId, latest) } - } - } - } - private fun showUserCard(username: String) { lifecycleScope.launch { val store = FireSessionStoreRepository.get(this@ChatChannelActivity) @@ -327,96 +227,8 @@ class ChatChannelActivity : AppCompatActivity() { } } - private fun handleBusEvent(event: MessageBusEventState) { - if (event.channel != busChannelName) return - val type = event.detailEventType ?: event.messageType - when (type) { - "sent" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { - upsertMessage(it, preferAppend = true) - } - "edit", "processed", "refresh", "restore", - "thread_created", "update_thread_original_message", - -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { - upsertMessage(it, preferAppend = false) - } - "delete" -> { - val deleted = FireChatBusPayload.event(event, channelId, chatBaseUrl) - as? ChatBusEventState.MessageDeleted - ?: return - val next = messages.filterNot { it.id == deleted.id } - if (next.size != messages.size) { - messages = next - adapter.submit(messages) - } - } - "reaction" -> applyReaction(event) - "pin" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { message -> - pins = listOf(message) + pins.filterNot { it.id == message.id } - updatePinBanner() - } - "unpin" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { message -> - pins = pins.filterNot { it.id == message.id } - updatePinBanner() - } - } - } - - private fun upsertMessage(message: ChatMessageState, preferAppend: Boolean) { - val index = messages.indexOfFirst { it.id == message.id } - messages = if (index >= 0) { - messages.toMutableList().also { it[index] = message } - } else if (preferAppend) { - messages + message - } else { - return - } - adapter.submit(messages) - } - - private fun applyReaction(event: MessageBusEventState) { - val parsed = FireChatBusPayload.event(event, channelId, chatBaseUrl) - as? ChatBusEventState.Reaction - ?: return - val index = messages.indexOfFirst { it.id == parsed.messageId } - if (index < 0) return - val message = messages[index] - val isAdd = parsed.action == ChatReactionActionState.ADD - val reactions = message.reactions.toMutableList() - val existing = reactions.indexOfFirst { it.emoji == parsed.emoji } - if (existing >= 0) { - val current = reactions[existing] - val nextCount = if (isAdd) current.count + 1u else current.count.saturatingDec() - val reacted = if (isAdd) { - current.reacted || parsed.actorId == currentUserId - } else { - false - } - if (nextCount == 0u) { - reactions.removeAt(existing) - } else { - reactions[existing] = ChatMessageReactionState( - emoji = parsed.emoji, - count = nextCount, - reacted = reacted, - users = current.users, - ) - } - } else if (isAdd) { - reactions += ChatMessageReactionState( - emoji = parsed.emoji, - count = 1u, - reacted = true, - users = emptyList(), - ) - } - messages = messages.toMutableList().also { it[index] = message.copy(reactions = reactions) } - adapter.submit(messages) - } - - private fun UInt.saturatingDec(): UInt = if (this == 0u) 0u else this - 1u - private fun updatePinBanner() { - val pin = pins.firstOrNull() + val pin = snapshot?.pins?.firstOrNull() if (pin == null || threadId != null) { pinBanner.visibility = View.GONE return @@ -429,6 +241,7 @@ class ChatChannelActivity : AppCompatActivity() { } private fun showMessageActions(message: ChatMessageState) { + val threadingEnabled = snapshot?.threadingEnabled == true val emojis = listOf("heart", "tada", "laughing", "+1", "eyes") val labels = emojis.map { emoji -> val reacted = message.reactions.any { it.emoji == emoji && it.reacted } @@ -445,15 +258,21 @@ class ChatChannelActivity : AppCompatActivity() { which < emojis.size -> toggleReaction(message, emojis[which]) labels[which] == getString(R.string.chat_open_thread) -> openThread(message) labels[which] == getString(R.string.chat_pin) -> lifecycleScope.launch { - runCatching { - FireSessionStoreRepository.get(this@ChatChannelActivity) - .pinChatMessage(channelId, message.id) + if (::session.isInitialized) { + runCatching { + session.command( + ChatChannelSession.Command.SetPinned(message.id, pinned = true), + ) + } } } labels[which] == getString(R.string.chat_unpin) -> lifecycleScope.launch { - runCatching { - FireSessionStoreRepository.get(this@ChatChannelActivity) - .unpinChatMessage(channelId, message.id) + if (::session.isInitialized) { + runCatching { + session.command( + ChatChannelSession.Command.SetPinned(message.id, pinned = false), + ) + } } } } @@ -462,26 +281,20 @@ class ChatChannelActivity : AppCompatActivity() { } private fun toggleReaction(message: ChatMessageState, emoji: String) { - val reacted = message.reactions.any { it.emoji == emoji && it.reacted } + if (!::session.isInitialized) return lifecycleScope.launch { runCatching { - FireSessionStoreRepository.get(this@ChatChannelActivity).reactChatMessage( - channelId = channelId, - messageId = message.id, - emoji = emoji, - reactAction = if (reacted) "remove" else "add", - ) + session.command(ChatChannelSession.Command.ToggleReaction(message.id, emoji)) } } } private fun openThread(message: ChatMessageState) { + if (!::session.isInitialized) return lifecycleScope.launch { try { - val store = FireSessionStoreRepository.get(this@ChatChannelActivity) - val id = message.threadId - ?: message.thread?.id - ?: store.createChatThread(channelId, message.id) + val result = session.command(ChatChannelSession.Command.ResolveThread(message.id)) + val id = (result as? ChatChannelSession.CommandResult.ThreadId)?.id ?: return@launch startActivity( intent( this@ChatChannelActivity, @@ -518,213 +331,3 @@ class ChatChannelActivity : AppCompatActivity() { } } } - -private class ChatMessageAdapter( - private val onClick: (ChatMessageState) -> Unit, - private val onThreadClick: (ChatMessageState) -> Unit, - private val onAuthorClick: (String) -> Unit, - private val baseUrl: String = "https://linux.do", -) : RecyclerView.Adapter() { - private var items: List = emptyList() - - fun submit(messages: List) { - items = messages - notifyDataSetChanged() - } - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { - val view = LayoutInflater.from(parent.context) - .inflate(R.layout.item_chat_message, parent, false) - return Holder(view, onClick, onThreadClick, onAuthorClick, baseUrl) - } - - override fun onBindViewHolder(holder: Holder, position: Int) { - val previous = items.getOrNull(position - 1) - holder.bind(items[position], previous) - } - - override fun getItemCount(): Int = items.size - - class Holder( - itemView: View, - private val onClick: (ChatMessageState) -> Unit, - private val onThreadClick: (ChatMessageState) -> Unit, - private val onAuthorClick: (String) -> Unit, - private val baseUrl: String, - ) : RecyclerView.ViewHolder(itemView) { - private val avatarContainer: View = itemView.findViewById(R.id.message_avatar_container) - private val avatar: ImageView = itemView.findViewById(R.id.message_avatar) - private val monogram: TextView = itemView.findViewById(R.id.message_avatar_monogram) - private val header: View = itemView.findViewById(R.id.message_header) - private val author: TextView = itemView.findViewById(R.id.message_author) - private val time: TextView = itemView.findViewById(R.id.message_time) - private val bodyContainer: LinearLayout = itemView.findViewById(R.id.message_body_container) - private val meta: TextView = itemView.findViewById(R.id.message_meta) - private val thread: TextView = itemView.findViewById(R.id.message_thread) - - fun bind(message: ChatMessageState, previous: ChatMessageState?) { - val username = message.user?.username ?: "user" - val grouped = shouldGroup(previous, message) - author.text = username - time.text = formatTime(message.createdAt) - bindBody(message) - bindMeta(message) - bindThread(message) - bindAvatar(username, message.user?.avatarTemplate, grouped) - - itemView.setPadding( - itemView.paddingLeft, - if (grouped) dp(2) else dp(8), - itemView.paddingRight, - itemView.paddingBottom, - ) - itemView.setOnClickListener { onClick(message) } - avatar.setOnClickListener { onAuthorClick(username) } - author.setOnClickListener { onAuthorClick(username) } - } - - private fun bindBody(message: ChatMessageState) { - bodyContainer.removeAllViews() - val contentId = "chat:${message.id}:${message.presentation?.checksum() ?: 0uL}" - if (message.isDeleted) { - bodyContainer.addView( - TextView(itemView.context).apply { - text = itemView.context.getString(R.string.chat_message_deleted) - setTextColor(itemView.context.getColor(R.color.fire_text_secondary)) - setTypeface(typeface, android.graphics.Typeface.ITALIC) - textSize = 15f - }, - ) - return - } - - val presentation = message.presentation - if (presentation != null) { - val blocks = FireRenderPresentation.blocks(presentation) - if (blocks.isNotEmpty()) { - blocks.forEachIndexed { index, block -> - when (block) { - is FireRichTextBlock.Text -> { - val spannable = FireSpannableBuilder.build( - nodes = block.nodes, - context = itemView.context, - onLinkClicked = null, - ) - if (spannable.isNotBlank()) { - val textView = FireRichTextView(itemView.context).apply { - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) - setTextColor(itemView.context.getColor(R.color.fire_text_primary)) - setTextIsSelectable(false) - setContent("$contentId:text:$index", spannable) - } - bodyContainer.addView(textView) - } - } - is FireRichTextBlock.Image -> { - val imageView = ImageView(itemView.context).apply { - adjustViewBounds = true - maxHeight = dp(220) - scaleType = ImageView.ScaleType.CENTER_CROP - layoutParams = LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - LinearLayout.LayoutParams.WRAP_CONTENT, - ).apply { - if (index > 0) topMargin = dp(6) - } - } - FireImageLoader.load(block.image.url, imageView) - bodyContainer.addView(imageView) - } - } - } - if (bodyContainer.childCount > 0) return - } - val plain = presentation.plainText().trim() - if (plain.isNotEmpty()) { - bodyContainer.addView(plainTextView(plain)) - return - } - } - - val plain = when { - message.message.isNotBlank() -> message.message - message.uploads.isNotEmpty() -> itemView.context.getString(R.string.chat_image_attachment) - else -> message.previewText - } - bodyContainer.addView(plainTextView(plain)) - } - - private fun plainTextView(textValue: String): TextView { - return TextView(itemView.context).apply { - text = textValue - setTextColor(itemView.context.getColor(R.color.fire_text_primary)) - textSize = 15f - } - } - - private fun bindMeta(message: ChatMessageState) { - val parts = buildList { - if (message.edited) add(itemView.context.getString(R.string.chat_edited)) - if (message.pinned) add(itemView.context.getString(R.string.chat_pinned_message)) - if (message.reactions.isNotEmpty()) { - add(message.reactions.joinToString(" ") { ":${it.emoji}: ${it.count}" }) - } - } - if (parts.isEmpty()) { - meta.visibility = View.GONE - } else { - meta.visibility = View.VISIBLE - meta.text = parts.joinToString(" · ") - } - } - - private fun bindThread(message: ChatMessageState) { - val replyCount = message.thread?.replyCount ?: 0u - if (replyCount > 0u) { - thread.visibility = View.VISIBLE - thread.text = itemView.context.getString(R.string.chat_thread_replies, replyCount.toInt()) - thread.setOnClickListener { onThreadClick(message) } - } else { - thread.visibility = View.GONE - thread.setOnClickListener(null) - } - } - - private fun bindAvatar(username: String, avatarTemplate: String?, grouped: Boolean) { - if (grouped) { - header.visibility = View.GONE - avatarContainer.visibility = View.INVISIBLE - return - } - header.visibility = View.VISIBLE - avatarContainer.visibility = View.VISIBLE - monogram.text = username.take(1).uppercase() - monogram.visibility = View.VISIBLE - avatar.setImageDrawable(null) - // Avatar ImageView sits above monogram; successful Coil loads cover it. - FireAvatarUrls.build(avatarTemplate, baseUrl = baseUrl)?.let { url -> - FireImageLoader.load(url, avatar) - } - } - - private fun dp(value: Int): Int = - (value * itemView.resources.displayMetrics.density).toInt() - - private fun formatTime(value: String?): String { - if (value.isNullOrBlank()) return "" - return value - .removeSuffix("Z") - .substringAfter('T') - .take(5) - .ifBlank { value.takeLast(5) } - } - - private fun shouldGroup(previous: ChatMessageState?, current: ChatMessageState): Boolean { - if (previous == null) return false - if (previous.user?.id == null || previous.user?.id != current.user?.id) return false - val prev = previous.createdAt ?: return false - val curr = current.createdAt ?: return false - return prev.take(16) == curr.take(16) || prev.take(13) == curr.take(13) - } - } -} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelSession.kt b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelSession.kt new file mode 100644 index 00000000..37767240 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelSession.kt @@ -0,0 +1,353 @@ +package com.fire.app.ui.chat + +import com.fire.app.session.FireSessionStore +import uniffi.fire_uniffi_chat.ChatBusEventState +import uniffi.fire_uniffi_chat.ChatMessageReactionState +import uniffi.fire_uniffi_chat.ChatMessageState +import uniffi.fire_uniffi_chat.ChatMessagesQueryState +import uniffi.fire_uniffi_chat.ChatReactionActionState +import uniffi.fire_uniffi_chat.SendChatMessageRequestState +import uniffi.fire_uniffi_messagebus.MessageBusEventState +import java.util.UUID + +class ChatChannelSession( + private val store: FireSessionStore, + private val channelId: ULong, + private val threadId: ULong?, + initialTitle: String, + initialThreadingEnabled: Boolean, +) { + data class Snapshot( + val title: String, + val threadingEnabled: Boolean, + val messages: List, + val pins: List, + val canLoadMorePast: Boolean, + val isLoading: Boolean, + val chatBaseUrl: String, + ) + + enum class Change { + Cached, + Initial, + Older, + Latest, + MessageInserted, + MessageUpdated, + MessageDeleted, + Pins, + Loading, + } + + sealed class Command { + data object LoadMorePast : Command() + data class Send( + val message: String, + val uploadIds: List = emptyList(), + ) : Command() + data class ToggleReaction( + val messageId: ULong, + val emoji: String, + ) : Command() + data class SetPinned( + val messageId: ULong, + val pinned: Boolean, + ) : Command() + data class ResolveThread( + val messageId: ULong, + ) : Command() + } + + sealed class CommandResult { + data object None : CommandResult() + data class ThreadId(val id: ULong) : CommandResult() + } + + var onChange: ((Snapshot, Change) -> Unit)? = null + var onError: ((Exception) -> Unit)? = null + + private val ownerToken = "chat-channel-activity" + private val busChannelName = threadId?.let { "/chat/$channelId/thread/$it" } ?: "/chat/$channelId" + + private var title: String = initialTitle + private var threadingEnabled: Boolean = initialThreadingEnabled + private var messages: List = emptyList() + private var pins: List = emptyList() + private var canLoadMorePast = false + private var isLoading = false + private var isSending = false + private var isOpen = false + private var currentUserId: ULong? = null + private var chatBaseUrl: String = "https://linux.do" + + fun snapshot(): Snapshot { + return Snapshot( + title = title, + threadingEnabled = threadingEnabled, + messages = messages, + pins = pins, + canLoadMorePast = canLoadMorePast, + isLoading = isLoading, + chatBaseUrl = chatBaseUrl, + ) + } + + suspend fun open() { + if (isOpen || channelId == 0uL) return + isOpen = true + isLoading = true + try { + val bootstrap = store.snapshot().bootstrap + currentUserId = bootstrap.currentUserId + chatBaseUrl = bootstrap.baseUrl.ifBlank { "https://linux.do" } + store.cachedChatMessages(channelId, threadId)?.messages?.takeIf { it.isNotEmpty() }?.let { cached -> + messages = cached + emit(Change.Cached) + } ?: emit(Change.Loading) + if (threadId == null) { + val channel = store.fetchChatChannel(channelId) + threadingEnabled = channel.threadingEnabled + title = channel.displayTitle + pins = store.fetchChatChannelPins(channelId) + emit(Change.Pins) + if (pins.isNotEmpty()) { + runCatching { store.markChatChannelPinsRead(channelId) } + } + } + val page = fetchMessages(fetchFromLastRead = true) + messages = page.messages + canLoadMorePast = page.canLoadMorePast + val currentThreadId = threadId + if (currentThreadId != null) { + runCatching { store.markChatThreadRead(channelId, currentThreadId) } + } else { + page.messages.lastOrNull()?.id?.let { latest -> + runCatching { store.markChatChannelRead(channelId, latest) } + } + } + store.subscribeMessageBusChannel( + channel = busChannelName, + ownerToken = ownerToken, + lastMessageId = null, + ) + emit(Change.Initial) + } catch (error: Exception) { + if (isOpen) onError?.invoke(error) + } finally { + isLoading = false + emit(Change.Loading) + } + } + + suspend fun close() { + isOpen = false + store.unsubscribeMessageBusChannel(busChannelName, ownerToken) + } + + suspend fun command(command: Command): CommandResult { + return when (command) { + Command.LoadMorePast -> { + loadMorePast() + CommandResult.None + } + is Command.Send -> { + send(command.message, command.uploadIds) + CommandResult.None + } + is Command.ToggleReaction -> { + toggleReaction(command.messageId, command.emoji) + CommandResult.None + } + is Command.SetPinned -> { + if (command.pinned) { + store.pinChatMessage(channelId, command.messageId) + } else { + store.unpinChatMessage(channelId, command.messageId) + } + CommandResult.None + } + is Command.ResolveThread -> { + val message = messages.firstOrNull { it.id == command.messageId } + ?: error("消息已不存在") + val id = message.threadId + ?: message.thread?.id + ?: store.createChatThread(channelId, message.id) + CommandResult.ThreadId(id) + } + } + } + + fun handleBusEvent(event: MessageBusEventState) { + if (!isOpen || event.channel != busChannelName) return + val type = event.detailEventType ?: event.messageType + when (type) { + "sent" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { + upsertMessage(it, preferAppend = true) + } + "edit", "processed", "refresh", "restore", + "thread_created", "update_thread_original_message", + -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { + upsertMessage(it, preferAppend = false) + } + "delete" -> { + val deleted = FireChatBusPayload.event(event, channelId, chatBaseUrl) + as? ChatBusEventState.MessageDeleted + ?: return + val next = messages.filterNot { it.id == deleted.id } + if (next.size != messages.size) { + messages = next + emit(Change.MessageDeleted) + } + } + "reaction" -> applyReaction(event) + "pin" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { message -> + pins = listOf(message) + pins.filterNot { it.id == message.id } + emit(Change.Pins) + } + "unpin" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { message -> + pins = pins.filterNot { it.id == message.id } + emit(Change.Pins) + } + } + } + + private suspend fun loadMorePast() { + if (!canLoadMorePast || isLoading) return + val oldest = messages.firstOrNull() ?: return + isLoading = true + try { + val query = ChatMessagesQueryState( + channelId = channelId, + direction = "past", + targetMessageId = oldest.id, + fetchFromLastRead = false, + pageSize = 50u, + ) + val page = fetchMessages(query) + messages = page.messages + messages + canLoadMorePast = page.canLoadMorePast + emit(Change.Older) + } finally { + isLoading = false + } + } + + private suspend fun send(text: String, uploadIds: List) { + if (isSending) return + if (text.isEmpty() && uploadIds.isEmpty()) return + isSending = true + try { + store.sendChatMessage( + SendChatMessageRequestState( + channelId = channelId, + message = text, + stagedId = UUID.randomUUID().toString(), + inReplyToId = null, + threadId = threadId, + uploadIds = uploadIds, + ), + ) + refreshLatest() + } finally { + isSending = false + } + } + + private suspend fun toggleReaction(messageId: ULong, emoji: String) { + val message = messages.firstOrNull { it.id == messageId } ?: return + val reacted = message.reactions.any { it.emoji == emoji && it.reacted } + store.reactChatMessage( + channelId = channelId, + messageId = message.id, + emoji = emoji, + reactAction = if (reacted) "remove" else "add", + ) + } + + private suspend fun refreshLatest() { + val page = fetchMessages(fetchFromLastRead = false) + messages = page.messages + canLoadMorePast = page.canLoadMorePast + if (threadId == null) { + page.messages.lastOrNull()?.id?.let { latest -> + runCatching { store.markChatChannelRead(channelId, latest) } + } + } + emit(Change.Latest) + } + + private suspend fun fetchMessages(fetchFromLastRead: Boolean) = fetchMessages( + ChatMessagesQueryState( + channelId = channelId, + direction = null, + targetMessageId = null, + fetchFromLastRead = fetchFromLastRead, + pageSize = 50u, + ), + ) + + private suspend fun fetchMessages(query: ChatMessagesQueryState) = + if (threadId != null) { + store.fetchChatThreadMessages(channelId, threadId, query) + } else { + store.fetchChatMessages(query) + } + + private fun upsertMessage(message: ChatMessageState, preferAppend: Boolean) { + val index = messages.indexOfFirst { it.id == message.id } + messages = if (index >= 0) { + messages.toMutableList().also { it[index] = message } + } else if (preferAppend) { + messages + message + } else { + return + } + emit(if (index >= 0) Change.MessageUpdated else Change.MessageInserted) + } + + private fun applyReaction(event: MessageBusEventState) { + val parsed = FireChatBusPayload.event(event, channelId, chatBaseUrl) + as? ChatBusEventState.Reaction + ?: return + val index = messages.indexOfFirst { it.id == parsed.messageId } + if (index < 0) return + val message = messages[index] + val isAdd = parsed.action == ChatReactionActionState.ADD + val reactions = message.reactions.toMutableList() + val existing = reactions.indexOfFirst { it.emoji == parsed.emoji } + if (existing >= 0) { + val current = reactions[existing] + val nextCount = if (isAdd) current.count + 1u else current.count.saturatingDec() + val reacted = if (isAdd) { + current.reacted || parsed.actorId == currentUserId + } else { + false + } + if (nextCount == 0u) { + reactions.removeAt(existing) + } else { + reactions[existing] = ChatMessageReactionState( + emoji = parsed.emoji, + count = nextCount, + reacted = reacted, + users = current.users, + ) + } + } else if (isAdd) { + reactions += ChatMessageReactionState( + emoji = parsed.emoji, + count = 1u, + reacted = true, + users = emptyList(), + ) + } + messages = messages.toMutableList().also { it[index] = message.copy(reactions = reactions) } + emit(Change.MessageUpdated) + } + + private fun emit(change: Change) { + onChange?.invoke(snapshot(), change) + } + + private fun UInt.saturatingDec(): UInt = if (this == 0u) 0u else this - 1u +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatMessageAdapter.kt b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatMessageAdapter.kt new file mode 100644 index 00000000..ddc4d2e0 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatMessageAdapter.kt @@ -0,0 +1,227 @@ +package com.fire.app.ui.chat + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import com.fire.app.R +import com.fire.app.core.image.FireAvatarUrls +import com.fire.app.core.image.FireImageLoader +import com.fire.app.richtext.FireRenderPresentation +import com.fire.app.richtext.FireRichTextBlock +import com.fire.app.richtext.FireRichTextView +import com.fire.app.richtext.FireSpannableBuilder +import uniffi.fire_uniffi_chat.ChatMessageState + +class ChatMessageAdapter( + private val onClick: (ChatMessageState) -> Unit, + private val onThreadClick: (ChatMessageState) -> Unit, + private val onAuthorClick: (String) -> Unit, + private var baseUrl: String = "https://linux.do", +) : RecyclerView.Adapter() { + private var items: List = emptyList() + + fun submit(messages: List, baseUrl: String = this.baseUrl) { + this.baseUrl = baseUrl + items = messages + notifyDataSetChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.item_chat_message, parent, false) + return Holder(view, onClick, onThreadClick, onAuthorClick, baseUrl) + } + + override fun onBindViewHolder(holder: Holder, position: Int) { + val previous = items.getOrNull(position - 1) + holder.bind(items[position], previous) + } + + override fun getItemCount(): Int = items.size + + class Holder( + itemView: View, + private val onClick: (ChatMessageState) -> Unit, + private val onThreadClick: (ChatMessageState) -> Unit, + private val onAuthorClick: (String) -> Unit, + private val baseUrl: String, + ) : RecyclerView.ViewHolder(itemView) { + private val avatarContainer: View = itemView.findViewById(R.id.message_avatar_container) + private val avatar: ImageView = itemView.findViewById(R.id.message_avatar) + private val monogram: TextView = itemView.findViewById(R.id.message_avatar_monogram) + private val header: View = itemView.findViewById(R.id.message_header) + private val author: TextView = itemView.findViewById(R.id.message_author) + private val time: TextView = itemView.findViewById(R.id.message_time) + private val bodyContainer: LinearLayout = itemView.findViewById(R.id.message_body_container) + private val meta: TextView = itemView.findViewById(R.id.message_meta) + private val thread: TextView = itemView.findViewById(R.id.message_thread) + + fun bind(message: ChatMessageState, previous: ChatMessageState?) { + val username = message.user?.username ?: "user" + val grouped = shouldGroup(previous, message) + author.text = username + time.text = formatTime(message.createdAt) + bindBody(message) + bindMeta(message) + bindThread(message) + bindAvatar(username, message.user?.avatarTemplate, grouped) + + itemView.setPadding( + itemView.paddingLeft, + if (grouped) dp(2) else dp(8), + itemView.paddingRight, + itemView.paddingBottom, + ) + itemView.setOnClickListener { onClick(message) } + avatar.setOnClickListener { onAuthorClick(username) } + author.setOnClickListener { onAuthorClick(username) } + } + + private fun bindBody(message: ChatMessageState) { + bodyContainer.removeAllViews() + val contentId = "chat:${message.id}:${message.presentation?.checksum() ?: 0uL}" + if (message.isDeleted) { + bodyContainer.addView( + TextView(itemView.context).apply { + text = itemView.context.getString(R.string.chat_message_deleted) + setTextColor(itemView.context.getColor(R.color.fire_text_secondary)) + setTypeface(typeface, android.graphics.Typeface.ITALIC) + textSize = 15f + }, + ) + return + } + + val presentation = message.presentation + if (presentation != null) { + val blocks = FireRenderPresentation.blocks(presentation) + if (blocks.isNotEmpty()) { + blocks.forEachIndexed { index, block -> + when (block) { + is FireRichTextBlock.Text -> { + val spannable = FireSpannableBuilder.build( + nodes = block.nodes, + context = itemView.context, + onLinkClicked = null, + ) + if (spannable.isNotBlank()) { + val textView = FireRichTextView(itemView.context).apply { + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) + setTextColor(itemView.context.getColor(R.color.fire_text_primary)) + setTextIsSelectable(false) + setContent("$contentId:text:$index", spannable) + } + bodyContainer.addView(textView) + } + } + is FireRichTextBlock.Image -> { + val imageView = ImageView(itemView.context).apply { + adjustViewBounds = true + maxHeight = dp(220) + scaleType = ImageView.ScaleType.CENTER_CROP + layoutParams = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ).apply { + if (index > 0) topMargin = dp(6) + } + } + FireImageLoader.load(block.image.url, imageView) + bodyContainer.addView(imageView) + } + } + } + if (bodyContainer.childCount > 0) return + } + val plain = presentation.plainText().trim() + if (plain.isNotEmpty()) { + bodyContainer.addView(plainTextView(plain)) + return + } + } + + val plain = when { + message.message.isNotBlank() -> message.message + message.uploads.isNotEmpty() -> itemView.context.getString(R.string.chat_image_attachment) + else -> message.previewText + } + bodyContainer.addView(plainTextView(plain)) + } + + private fun plainTextView(textValue: String): TextView { + return TextView(itemView.context).apply { + text = textValue + setTextColor(itemView.context.getColor(R.color.fire_text_primary)) + textSize = 15f + } + } + + private fun bindMeta(message: ChatMessageState) { + val parts = buildList { + if (message.edited) add(itemView.context.getString(R.string.chat_edited)) + if (message.pinned) add(itemView.context.getString(R.string.chat_pinned_message)) + if (message.reactions.isNotEmpty()) { + add(message.reactions.joinToString(" ") { ":${it.emoji}: ${it.count}" }) + } + } + if (parts.isEmpty()) { + meta.visibility = View.GONE + } else { + meta.visibility = View.VISIBLE + meta.text = parts.joinToString(" · ") + } + } + + private fun bindThread(message: ChatMessageState) { + val replyCount = message.thread?.replyCount ?: 0u + if (replyCount > 0u) { + thread.visibility = View.VISIBLE + thread.text = itemView.context.getString(R.string.chat_thread_replies, replyCount.toInt()) + thread.setOnClickListener { onThreadClick(message) } + } else { + thread.visibility = View.GONE + thread.setOnClickListener(null) + } + } + + private fun bindAvatar(username: String, avatarTemplate: String?, grouped: Boolean) { + if (grouped) { + header.visibility = View.GONE + avatarContainer.visibility = View.INVISIBLE + return + } + header.visibility = View.VISIBLE + avatarContainer.visibility = View.VISIBLE + monogram.text = username.take(1).uppercase() + monogram.visibility = View.VISIBLE + avatar.setImageDrawable(null) + FireAvatarUrls.build(avatarTemplate, baseUrl = baseUrl)?.let { url -> + FireImageLoader.load(url, avatar) + } + } + + private fun dp(value: Int): Int = + (value * itemView.resources.displayMetrics.density).toInt() + + private fun formatTime(value: String?): String { + if (value.isNullOrBlank()) return "" + return value + .removeSuffix("Z") + .substringAfter('T') + .take(5) + .ifBlank { value.takeLast(5) } + } + + private fun shouldGroup(previous: ChatMessageState?, current: ChatMessageState): Boolean { + if (previous == null) return false + if (previous.user?.id == null || previous.user?.id != current.user?.id) return false + val prev = previous.createdAt ?: return false + val curr = current.createdAt ?: return false + return prev.take(16) == curr.take(16) || prev.take(13) == curr.take(13) + } + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerAssist.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerAssist.kt deleted file mode 100644 index 02e67b16..00000000 --- a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerAssist.kt +++ /dev/null @@ -1,692 +0,0 @@ -package com.fire.app.ui.composer - -import android.content.Context -import android.net.Uri -import android.provider.OpenableColumns -import android.text.Editable -import android.text.TextWatcher -import android.view.View -import android.widget.EditText -import android.widget.LinearLayout -import android.widget.TextView -import com.fire.app.R -import com.fire.app.session.FireSessionStore -import com.google.android.material.chip.Chip -import com.google.android.material.chip.ChipGroup -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import uniffi.fire_uniffi_search.TagSearchQueryState -import uniffi.fire_uniffi_search.UserMentionQueryState -import uniffi.fire_uniffi_topics.UploadImageRequestState -import uniffi.fire_uniffi_topics.UploadResultState - -class ComposerMentionAssist( - private val input: EditText, - private val suggestions: LinearLayout, - private val sessionStore: FireSessionStore, - private val scope: CoroutineScope, - private val includeGroups: Boolean, - private val topicId: ULong? = null, - private val categoryIdProvider: () -> ULong? = { null }, -) { - private var searchJob: Job? = null - private var applyingSuggestion = false - - fun attach() { - input.addTextChangedListener(object : TextWatcher { - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = scheduleSearch() - override fun afterTextChanged(s: Editable?) = Unit - }) - } - - private fun scheduleSearch() { - if (applyingSuggestion) return - val context = mentionContext() ?: run { - hideSuggestions() - return - } - searchJob?.cancel() - searchJob = scope.launch { - delay(200) - val result = runCatching { - sessionStore.searchUsers( - UserMentionQueryState( - term = context.term, - includeGroups = includeGroups, - limit = 8u, - topicId = topicId, - categoryId = categoryIdProvider(), - ), - ) - }.getOrNull() - val items = buildList { - result?.users.orEmpty().forEach { user -> - val display = user.name?.takeIf { it.isNotBlank() } ?: user.username - add(Suggestion(label = "$display @${user.username}", value = user.username)) - } - result?.groups.orEmpty().forEach { group -> - val display = group.fullName?.takeIf { it.isNotBlank() } ?: group.name - add(Suggestion(label = "$display @${group.name}", value = group.name)) - } - }.take(8) - input.post { - val latest = mentionContext() - if (latest?.term == context.term) { - showSuggestions(items, latest) - } - } - } - } - - private fun showSuggestions(items: List, context: TextContext) { - suggestions.removeAllViews() - suggestions.visibility = if (items.isEmpty()) View.GONE else View.VISIBLE - items.forEach { item -> - suggestions.addView(suggestionView(input.context, item.label) { - applyingSuggestion = true - input.text.replace(context.start, context.end, "@${item.value} ") - input.setSelection((context.start + item.value.length + 2).coerceAtMost(input.text.length)) - applyingSuggestion = false - hideSuggestions() - }) - } - } - - private fun hideSuggestions() { - suggestions.removeAllViews() - suggestions.visibility = View.GONE - } - - private fun mentionContext(): TextContext? { - val cursor = input.selectionStart.coerceAtLeast(0) - val text = input.text.toString() - if (cursor > text.length) return null - val prefix = text.substring(0, cursor) - val atIndex = prefix.lastIndexOf('@') - if (atIndex < 0) return null - if (atIndex > 0 && !prefix[atIndex - 1].isWhitespace()) return null - val term = prefix.substring(atIndex + 1) - if (term.length !in 1..30 || term.any { it.isWhitespace() }) return null - return TextContext(start = atIndex, end = cursor, term = term) - } -} - -class ComposerTagAssist( - private val input: EditText, - private val suggestions: LinearLayout, - private val sessionStore: FireSessionStore, - private val scope: CoroutineScope, - private val categoryIdProvider: () -> ULong?, - private val selectedTagsProvider: () -> List, -) { - private var searchJob: Job? = null - private var applyingSuggestion = false - - fun attach() { - input.addTextChangedListener(object : TextWatcher { - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = scheduleSearch() - override fun afterTextChanged(s: Editable?) = Unit - }) - } - - private fun scheduleSearch() { - if (applyingSuggestion) return - val context = tagContext() ?: run { - hideSuggestions() - return - } - searchJob?.cancel() - searchJob = scope.launch { - delay(250) - val result = runCatching { - sessionStore.searchTags( - TagSearchQueryState( - q = context.term, - filterForInput = true, - limit = 8u, - categoryId = categoryIdProvider(), - selectedTags = selectedTagsProvider(), - ), - ) - }.getOrNull() - val items = result?.results.orEmpty() - .map { item -> - val label = item.text.takeIf { it.isNotBlank() } ?: item.name - Suggestion(label = "$label (${item.count})", value = item.name) - } - .take(8) - input.post { - val latest = tagContext() - if (latest?.term == context.term) { - showSuggestions(items, latest) - } - } - } - } - - private fun showSuggestions(items: List, context: TextContext) { - suggestions.removeAllViews() - suggestions.visibility = if (items.isEmpty()) View.GONE else View.VISIBLE - items.forEach { item -> - suggestions.addView(suggestionView(input.context, item.label) { - applyingSuggestion = true - input.text.replace(context.start, context.end, item.value) - input.text.insert((context.start + item.value.length).coerceAtMost(input.text.length), " ") - applyingSuggestion = false - hideSuggestions() - }) - } - } - - private fun hideSuggestions() { - suggestions.removeAllViews() - suggestions.visibility = View.GONE - } - - private fun tagContext(): TextContext? { - val cursor = input.selectionStart.coerceAtLeast(0) - val text = input.text.toString() - if (cursor > text.length) return null - val prefix = text.substring(0, cursor) - val separator = maxOf(prefix.lastIndexOf(' '), prefix.lastIndexOf(','), prefix.lastIndexOf('\n')) - val start = separator + 1 - val term = prefix.substring(start).trim() - if (term.length !in 1..30) return null - return TextContext(start = start, end = cursor, term = term) - } -} - -class ComposerRecipientAssist( - private val input: EditText, - private val suggestions: LinearLayout, - private val sessionStore: FireSessionStore, - private val scope: CoroutineScope, -) { - private var searchJob: Job? = null - private var applyingSuggestion = false - - fun attach() { - input.addTextChangedListener(object : TextWatcher { - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = scheduleSearch() - override fun afterTextChanged(s: Editable?) = Unit - }) - } - - private fun scheduleSearch() { - if (applyingSuggestion) return - val context = recipientContext() ?: run { - hideSuggestions() - return - } - searchJob?.cancel() - searchJob = scope.launch { - delay(200) - val result = runCatching { - sessionStore.searchUsers( - UserMentionQueryState( - term = context.term, - includeGroups = false, - limit = 8u, - topicId = null, - categoryId = null, - ), - ) - }.getOrNull() - val items = result?.users.orEmpty() - .map { user -> - val display = user.name?.takeIf { it.isNotBlank() } ?: user.username - Suggestion(label = "$display @${user.username}", value = user.username) - } - .take(8) - input.post { - val latest = recipientContext() - if (latest?.term == context.term) { - showSuggestions(items, latest) - } - } - } - } - - private fun showSuggestions(items: List, context: TextContext) { - suggestions.removeAllViews() - suggestions.visibility = if (items.isEmpty()) View.GONE else View.VISIBLE - items.forEach { item -> - suggestions.addView(suggestionView(input.context, item.label) { - applyingSuggestion = true - input.text.replace(context.start, context.end, item.value) - input.text.insert((context.start + item.value.length).coerceAtMost(input.text.length), " ") - input.setSelection(input.text.length) - applyingSuggestion = false - hideSuggestions() - }) - } - } - - private fun hideSuggestions() { - suggestions.removeAllViews() - suggestions.visibility = View.GONE - } - - private fun recipientContext(): TextContext? { - val cursor = input.selectionStart.coerceAtLeast(0) - val text = input.text.toString() - if (cursor > text.length) return null - val prefix = text.substring(0, cursor) - val separator = maxOf(prefix.lastIndexOf(' '), prefix.lastIndexOf(','), prefix.lastIndexOf('\n')) - val start = separator + 1 - val term = prefix.substring(start).trim().removePrefix("@") - if (term.length !in 1..30 || term.any { it.isWhitespace() }) return null - return TextContext(start = start, end = cursor, term = term) - } -} - -class ComposerRecipientTokenView( - private val input: EditText, - private val tokens: ChipGroup, -) { - private var applyingTokenChange = false - - fun attach() { - input.addTextChangedListener(object : TextWatcher { - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = render() - override fun afterTextChanged(s: Editable?) = Unit - }) - render() - } - - private fun render() { - if (applyingTokenChange) return - val recipients = recipientValues() - tokens.removeAllViews() - tokens.visibility = if (recipients.isEmpty()) View.GONE else View.VISIBLE - recipients.forEach { recipient -> - tokens.addView( - Chip(input.context).apply { - text = "@$recipient" - isCloseIconVisible = true - setOnCloseIconClickListener { - removeRecipient(recipient) - } - }, - ) - } - } - - private fun removeRecipient(username: String) { - applyingTokenChange = true - val remaining = recipientValues() - .filterNot { it.equals(username, ignoreCase = true) } - input.setText(remaining.joinToString(" ")) - input.setSelection(input.text.length) - applyingTokenChange = false - render() - } - - private fun recipientValues(): List = - input.text.toString() - .split("[,\\s]+".toRegex()) - .map { it.trim().removePrefix("@") } - .filter { it.isNotBlank() } - .distinctBy { it.lowercase() } -} - -class ComposerDraftAutosave( - private val scope: CoroutineScope, - private val saveDraft: suspend () -> Unit, - private val onSaveFailed: (Exception) -> Unit = {}, -) { - private var enabled = false - private var saveJob: Job? = null - - fun attach(vararg inputs: EditText) { - val watcher = object : TextWatcher { - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = schedule() - override fun afterTextChanged(s: Editable?) = Unit - } - inputs.forEach { input -> input.addTextChangedListener(watcher) } - } - - fun start() { - enabled = true - } - - fun schedule() { - if (!enabled) return - saveJob?.cancel() - saveJob = scope.launch { - delay(1_200) - saveDraftSafely() - } - } - - fun flush() { - if (!enabled) return - saveJob?.cancel() - saveJob = scope.launch { - saveDraftSafely() - } - } - - fun cancel() { - enabled = false - saveJob?.cancel() - saveJob = null - } - - private suspend fun saveDraftSafely() { - try { - saveDraft() - } catch (error: CancellationException) { - throw error - } catch (error: Exception) { - onSaveFailed(error) - } - } -} - -suspend fun uploadImageMarkdown( - context: Context, - sessionStore: FireSessionStore, - uri: Uri, -): String { - val resolver = context.contentResolver - val bytes = resolver.openInputStream(uri)?.use { it.readBytes() } - ?: error(context.getString(R.string.composer_upload_error)) - val mimeType = resolver.getType(uri) - val fileName = displayName(context, uri) ?: "image-${System.currentTimeMillis()}" - val result = sessionStore.uploadImage( - UploadImageRequestState( - fileName = fileName, - mimeType = mimeType, - bytes = bytes, - ), - ) - return markdownForUpload(result) -} - -fun insertMarkdownAtCursor(input: EditText, markdown: String) { - val start = input.selectionStart.coerceAtLeast(0) - val end = input.selectionEnd.coerceAtLeast(start) - val prefix = if (start == 0 || input.text.getOrNull(start - 1) == '\n') "" else "\n" - val suffix = if (end >= input.text.length || input.text.getOrNull(end) == '\n') "\n" else "\n\n" - input.text.replace(start, end, "$prefix$markdown$suffix") - input.setSelection((start + prefix.length + markdown.length + suffix.length).coerceAtMost(input.text.length)) -} - -fun applyMarkdownFormat(input: EditText, action: MarkdownFormatAction) { - val result = MarkdownInsertion.apply( - action = action, - text = input.text.toString(), - selectionStart = input.selectionStart, - selectionEnd = input.selectionEnd, - ) - input.text.replace(0, input.text.length, result.text) - input.setSelection( - result.selectionStart.coerceIn(0, input.text.length), - result.selectionEnd.coerceIn(0, input.text.length), - ) - input.requestFocus() -} - -enum class MarkdownFormatAction { - BOLD, - ITALIC, - STRIKETHROUGH, - INLINE_CODE, - CODE_BLOCK, - QUOTE, - UNORDERED_LIST, - ORDERED_LIST, - LINK, - IMAGE, -} - -data class MarkdownInsertionResult( - val text: String, - val selectionStart: Int, - val selectionEnd: Int = selectionStart, -) - -object QuoteMarkdown { - fun build( - username: String, - postNumber: UInt, - topicId: ULong, - plainText: String, - ): String? { - val trimmedText = plainText.trim() - if (trimmedText.isEmpty()) return null - - val author = username - .trim() - .replace(Regex("\\s+"), " ") - .replace('"', '\'') - .ifBlank { "unknown" } - return "[quote=\"$author, post:$postNumber, topic:$topicId\"]\n" + - trimmedText + - "\n[/quote]\n\n" - } -} - -object ComposerInitialBody { - fun merge( - initialBody: String, - currentBody: String, - preferredSelectionStart: Int = initialBody.length, - ): MarkdownInsertionResult { - if (initialBody.isBlank()) { - return MarkdownInsertionResult( - text = currentBody, - selectionStart = currentBody.length, - ) - } - - val trimmedInitial = initialBody.trim() - val exactExistingIndex = currentBody.indexOf(initialBody) - val trimmedExistingIndex = currentBody.indexOf(trimmedInitial) - if (exactExistingIndex >= 0 || trimmedExistingIndex >= 0) { - val index = if (exactExistingIndex >= 0) exactExistingIndex else trimmedExistingIndex - val selectionOffset = if (exactExistingIndex >= 0) { - preferredSelectionStart.coerceIn(0, initialBody.length) - } else { - preferredSelectionStart.coerceIn(0, trimmedInitial.length) - } - return MarkdownInsertionResult( - text = currentBody, - selectionStart = index + selectionOffset, - ) - } - - if (currentBody.isBlank()) { - return MarkdownInsertionResult( - text = initialBody, - selectionStart = preferredSelectionStart.coerceIn(0, initialBody.length), - ) - } - - val separator = if (initialBody.endsWith("\n\n") || currentBody.startsWith("\n")) { - "" - } else { - "\n\n" - } - val nextText = initialBody + separator + currentBody - return MarkdownInsertionResult( - text = nextText, - selectionStart = preferredSelectionStart.coerceIn(0, initialBody.length), - ) - } -} - -object MarkdownInsertion { - fun apply( - action: MarkdownFormatAction, - text: String, - selectionStart: Int, - selectionEnd: Int, - ): MarkdownInsertionResult { - return when (action) { - MarkdownFormatAction.BOLD -> wrap(text, selectionStart, selectionEnd, "**", "**") - MarkdownFormatAction.ITALIC -> wrap(text, selectionStart, selectionEnd, "*", "*") - MarkdownFormatAction.STRIKETHROUGH -> wrap(text, selectionStart, selectionEnd, "~~", "~~") - MarkdownFormatAction.INLINE_CODE -> wrap(text, selectionStart, selectionEnd, "`", "`") - MarkdownFormatAction.CODE_BLOCK -> codeBlock(text, selectionStart, selectionEnd) - MarkdownFormatAction.QUOTE -> prefixLines(text, selectionStart, selectionEnd) { "> " } - MarkdownFormatAction.UNORDERED_LIST -> prefixLines(text, selectionStart, selectionEnd) { "- " } - MarkdownFormatAction.ORDERED_LIST -> prefixLines(text, selectionStart, selectionEnd) { index -> - "${index + 1}. " - } - MarkdownFormatAction.LINK -> wrap(text, selectionStart, selectionEnd, "[", "](url)", "text") - MarkdownFormatAction.IMAGE -> wrap(text, selectionStart, selectionEnd, "![", "](url)", "alt") - } - } - - private fun wrap( - text: String, - selectionStart: Int, - selectionEnd: Int, - prefix: String, - suffix: String, - placeholder: String = "", - ): MarkdownInsertionResult { - val range = normalizedRange(text, selectionStart, selectionEnd) - val selected = if (range.start < range.end) { - text.substring(range.start, range.end) - } else { - placeholder - } - val replacement = "$prefix$selected$suffix" - val nextText = text.replaceRange(range.start, range.end, replacement) - val selectedLength = if (range.start < range.end) { - range.end - range.start - } else { - placeholder.length - } - val nextSelectionStart = range.start + prefix.length - return MarkdownInsertionResult( - text = nextText, - selectionStart = nextSelectionStart, - selectionEnd = nextSelectionStart + selectedLength, - ) - } - - private fun codeBlock( - text: String, - selectionStart: Int, - selectionEnd: Int, - ): MarkdownInsertionResult { - val range = normalizedRange(text, selectionStart, selectionEnd) - val selected = text.substring(range.start, range.end) - val startsLine = range.start == 0 || text.getOrNull(range.start - 1) == '\n' - val endsLine = range.end >= text.length || text.getOrNull(range.end) == '\n' - val leadingBreak = if (startsLine) "" else "\n" - val trailingBreak = if (endsLine) "" else "\n" - val replacement = "${leadingBreak}```\n$selected\n```$trailingBreak" - val nextText = text.replaceRange(range.start, range.end, replacement) - val nextSelectionStart = range.start + leadingBreak.length + "```\n".length - return MarkdownInsertionResult( - text = nextText, - selectionStart = nextSelectionStart, - selectionEnd = nextSelectionStart + selected.length, - ) - } - - private fun prefixLines( - text: String, - selectionStart: Int, - selectionEnd: Int, - prefix: (Int) -> String, - ): MarkdownInsertionResult { - val range = normalizedRange(text, selectionStart, selectionEnd) - if (range.start == range.end) { - val lineStart = lineStart(text, range.start) - val linePrefix = prefix(0) - val nextText = text.replaceRange(lineStart, lineStart, linePrefix) - val nextSelection = range.start + linePrefix.length - return MarkdownInsertionResult(nextText, nextSelection) - } - - val lineStart = lineStart(text, range.start) - val lineEnd = if (range.end >= text.length) { - text.length - } else { - text.indexOf('\n', range.end) - .let { if (it < 0) text.length else it } - } - val selectedLines = text.substring(lineStart, lineEnd) - val replacement = selectedLines - .split('\n') - .mapIndexed { index, line -> "${prefix(index)}$line" } - .joinToString("\n") - val nextText = text.replaceRange(lineStart, lineEnd, replacement) - return MarkdownInsertionResult( - text = nextText, - selectionStart = lineStart, - selectionEnd = lineStart + replacement.length, - ) - } - - private fun normalizedRange( - text: String, - selectionStart: Int, - selectionEnd: Int, - ): MarkdownTextRange { - val start = selectionStart.coerceIn(0, text.length) - val end = selectionEnd.coerceIn(0, text.length) - return MarkdownTextRange( - start = minOf(start, end), - end = maxOf(start, end), - ) - } - - private fun lineStart(text: String, offset: Int): Int { - if (offset <= 0) return 0 - val previousNewline = text.lastIndexOf('\n', offset - 1) - return if (previousNewline < 0) 0 else previousNewline + 1 - } - - private data class MarkdownTextRange( - val start: Int, - val end: Int, - ) -} - -private fun markdownForUpload(result: UploadResultState): String { - val alt = result.originalFilename?.takeIf { it.isNotBlank() } ?: "image" - val width = result.thumbnailWidth ?: result.width - val height = result.thumbnailHeight ?: result.height - return if (width != null && height != null) { - "![$alt|${width}x$height](${result.shortUrl})" - } else { - "![$alt](${result.shortUrl})" - } -} - -private fun displayName(context: Context, uri: Uri): String? { - return context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null) - ?.use { cursor -> - val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) - if (index >= 0 && cursor.moveToFirst()) cursor.getString(index) else null - } -} - -private fun suggestionView(context: Context, label: String, onClick: () -> Unit): TextView { - return TextView(context).apply { - text = label - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) - setTextColor(context.getColor(R.color.fire_accent)) - setPadding(0, 8, 0, 8) - setOnClickListener { onClick() } - } -} - -private data class Suggestion(val label: String, val value: String) - -private data class TextContext(val start: Int, val end: Int, val term: String) diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerAssistModels.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerAssistModels.kt new file mode 100644 index 00000000..97269b0e --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerAssistModels.kt @@ -0,0 +1,19 @@ +package com.fire.app.ui.composer + +import android.content.Context +import android.widget.TextView +import com.fire.app.R + +internal fun suggestionView(context: Context, label: String, onClick: () -> Unit): TextView { + return TextView(context).apply { + text = label + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) + setTextColor(context.getColor(R.color.fire_accent)) + setPadding(0, 8, 0, 8) + setOnClickListener { onClick() } + } +} + +internal data class Suggestion(val label: String, val value: String) + +internal data class TextContext(val start: Int, val end: Int, val term: String) diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerDraftAutosave.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerDraftAutosave.kt new file mode 100644 index 00000000..5549d1c7 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerDraftAutosave.kt @@ -0,0 +1,65 @@ +package com.fire.app.ui.composer + +import android.text.Editable +import android.text.TextWatcher +import android.widget.EditText +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +class ComposerDraftAutosave( + private val scope: CoroutineScope, + private val saveDraft: suspend () -> Unit, + private val onSaveFailed: (Exception) -> Unit = {}, +) { + private var enabled = false + private var saveJob: Job? = null + + fun attach(vararg inputs: EditText) { + val watcher = object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = schedule() + override fun afterTextChanged(s: Editable?) = Unit + } + inputs.forEach { input -> input.addTextChangedListener(watcher) } + } + + fun start() { + enabled = true + } + + fun schedule() { + if (!enabled) return + saveJob?.cancel() + saveJob = scope.launch { + delay(1_200) + saveDraftSafely() + } + } + + fun flush() { + if (!enabled) return + saveJob?.cancel() + saveJob = scope.launch { + saveDraftSafely() + } + } + + fun cancel() { + enabled = false + saveJob?.cancel() + saveJob = null + } + + private suspend fun saveDraftSafely() { + try { + saveDraft() + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + onSaveFailed(error) + } + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerMarkdown.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerMarkdown.kt new file mode 100644 index 00000000..624fc5e8 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerMarkdown.kt @@ -0,0 +1,249 @@ +package com.fire.app.ui.composer + +import android.widget.EditText + +fun insertMarkdownAtCursor(input: EditText, markdown: String) { + val start = input.selectionStart.coerceAtLeast(0) + val end = input.selectionEnd.coerceAtLeast(start) + val prefix = if (start == 0 || input.text.getOrNull(start - 1) == '\n') "" else "\n" + val suffix = if (end >= input.text.length || input.text.getOrNull(end) == '\n') "\n" else "\n\n" + input.text.replace(start, end, "$prefix$markdown$suffix") + input.setSelection((start + prefix.length + markdown.length + suffix.length).coerceAtMost(input.text.length)) +} + +fun applyMarkdownFormat(input: EditText, action: MarkdownFormatAction) { + val result = MarkdownInsertion.apply( + action = action, + text = input.text.toString(), + selectionStart = input.selectionStart, + selectionEnd = input.selectionEnd, + ) + input.text.replace(0, input.text.length, result.text) + input.setSelection( + result.selectionStart.coerceIn(0, input.text.length), + result.selectionEnd.coerceIn(0, input.text.length), + ) + input.requestFocus() +} + +enum class MarkdownFormatAction { + BOLD, + ITALIC, + STRIKETHROUGH, + INLINE_CODE, + CODE_BLOCK, + QUOTE, + UNORDERED_LIST, + ORDERED_LIST, + LINK, + IMAGE, +} + +data class MarkdownInsertionResult( + val text: String, + val selectionStart: Int, + val selectionEnd: Int = selectionStart, +) + +object QuoteMarkdown { + fun build( + username: String, + postNumber: UInt, + topicId: ULong, + plainText: String, + ): String? { + val trimmedText = plainText.trim() + if (trimmedText.isEmpty()) return null + + val author = username + .trim() + .replace(Regex("\\s+"), " ") + .replace('"', '\'') + .ifBlank { "unknown" } + return "[quote=\"$author, post:$postNumber, topic:$topicId\"]\n" + + trimmedText + + "\n[/quote]\n\n" + } +} + +object ComposerInitialBody { + fun merge( + initialBody: String, + currentBody: String, + preferredSelectionStart: Int = initialBody.length, + ): MarkdownInsertionResult { + if (initialBody.isBlank()) { + return MarkdownInsertionResult( + text = currentBody, + selectionStart = currentBody.length, + ) + } + + val trimmedInitial = initialBody.trim() + val exactExistingIndex = currentBody.indexOf(initialBody) + val trimmedExistingIndex = currentBody.indexOf(trimmedInitial) + if (exactExistingIndex >= 0 || trimmedExistingIndex >= 0) { + val index = if (exactExistingIndex >= 0) exactExistingIndex else trimmedExistingIndex + val selectionOffset = if (exactExistingIndex >= 0) { + preferredSelectionStart.coerceIn(0, initialBody.length) + } else { + preferredSelectionStart.coerceIn(0, trimmedInitial.length) + } + return MarkdownInsertionResult( + text = currentBody, + selectionStart = index + selectionOffset, + ) + } + + if (currentBody.isBlank()) { + return MarkdownInsertionResult( + text = initialBody, + selectionStart = preferredSelectionStart.coerceIn(0, initialBody.length), + ) + } + + val separator = if (initialBody.endsWith("\n\n") || currentBody.startsWith("\n")) { + "" + } else { + "\n\n" + } + val nextText = initialBody + separator + currentBody + return MarkdownInsertionResult( + text = nextText, + selectionStart = preferredSelectionStart.coerceIn(0, initialBody.length), + ) + } +} + +object MarkdownInsertion { + fun apply( + action: MarkdownFormatAction, + text: String, + selectionStart: Int, + selectionEnd: Int, + ): MarkdownInsertionResult { + return when (action) { + MarkdownFormatAction.BOLD -> wrap(text, selectionStart, selectionEnd, "**", "**") + MarkdownFormatAction.ITALIC -> wrap(text, selectionStart, selectionEnd, "*", "*") + MarkdownFormatAction.STRIKETHROUGH -> wrap(text, selectionStart, selectionEnd, "~~", "~~") + MarkdownFormatAction.INLINE_CODE -> wrap(text, selectionStart, selectionEnd, "`", "`") + MarkdownFormatAction.CODE_BLOCK -> codeBlock(text, selectionStart, selectionEnd) + MarkdownFormatAction.QUOTE -> prefixLines(text, selectionStart, selectionEnd) { "> " } + MarkdownFormatAction.UNORDERED_LIST -> prefixLines(text, selectionStart, selectionEnd) { "- " } + MarkdownFormatAction.ORDERED_LIST -> prefixLines(text, selectionStart, selectionEnd) { index -> + "${index + 1}. " + } + MarkdownFormatAction.LINK -> wrap(text, selectionStart, selectionEnd, "[", "](url)", "text") + MarkdownFormatAction.IMAGE -> wrap(text, selectionStart, selectionEnd, "![", "](url)", "alt") + } + } + + private fun wrap( + text: String, + selectionStart: Int, + selectionEnd: Int, + prefix: String, + suffix: String, + placeholder: String = "", + ): MarkdownInsertionResult { + val range = normalizedRange(text, selectionStart, selectionEnd) + val selected = if (range.start < range.end) { + text.substring(range.start, range.end) + } else { + placeholder + } + val replacement = "$prefix$selected$suffix" + val nextText = text.replaceRange(range.start, range.end, replacement) + val selectedLength = if (range.start < range.end) { + range.end - range.start + } else { + placeholder.length + } + val nextSelectionStart = range.start + prefix.length + return MarkdownInsertionResult( + text = nextText, + selectionStart = nextSelectionStart, + selectionEnd = nextSelectionStart + selectedLength, + ) + } + + private fun codeBlock( + text: String, + selectionStart: Int, + selectionEnd: Int, + ): MarkdownInsertionResult { + val range = normalizedRange(text, selectionStart, selectionEnd) + val selected = text.substring(range.start, range.end) + val startsLine = range.start == 0 || text.getOrNull(range.start - 1) == '\n' + val endsLine = range.end >= text.length || text.getOrNull(range.end) == '\n' + val leadingBreak = if (startsLine) "" else "\n" + val trailingBreak = if (endsLine) "" else "\n" + val replacement = "${leadingBreak}```\n$selected\n```$trailingBreak" + val nextText = text.replaceRange(range.start, range.end, replacement) + val nextSelectionStart = range.start + leadingBreak.length + "```\n".length + return MarkdownInsertionResult( + text = nextText, + selectionStart = nextSelectionStart, + selectionEnd = nextSelectionStart + selected.length, + ) + } + + private fun prefixLines( + text: String, + selectionStart: Int, + selectionEnd: Int, + prefix: (Int) -> String, + ): MarkdownInsertionResult { + val range = normalizedRange(text, selectionStart, selectionEnd) + if (range.start == range.end) { + val lineStart = lineStart(text, range.start) + val linePrefix = prefix(0) + val nextText = text.replaceRange(lineStart, lineStart, linePrefix) + val nextSelection = range.start + linePrefix.length + return MarkdownInsertionResult(nextText, nextSelection) + } + + val lineStart = lineStart(text, range.start) + val lineEnd = if (range.end >= text.length) { + text.length + } else { + text.indexOf('\n', range.end) + .let { if (it < 0) text.length else it } + } + val selectedLines = text.substring(lineStart, lineEnd) + val replacement = selectedLines + .split('\n') + .mapIndexed { index, line -> "${prefix(index)}$line" } + .joinToString("\n") + val nextText = text.replaceRange(lineStart, lineEnd, replacement) + return MarkdownInsertionResult( + text = nextText, + selectionStart = lineStart, + selectionEnd = lineStart + replacement.length, + ) + } + + private fun normalizedRange( + text: String, + selectionStart: Int, + selectionEnd: Int, + ): MarkdownTextRange { + val start = selectionStart.coerceIn(0, text.length) + val end = selectionEnd.coerceIn(0, text.length) + return MarkdownTextRange( + start = minOf(start, end), + end = maxOf(start, end), + ) + } + + private fun lineStart(text: String, offset: Int): Int { + if (offset <= 0) return 0 + val previousNewline = text.lastIndexOf('\n', offset - 1) + return if (previousNewline < 0) 0 else previousNewline + 1 + } + + private data class MarkdownTextRange( + val start: Int, + val end: Int, + ) +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerMentionAssist.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerMentionAssist.kt new file mode 100644 index 00000000..27311843 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerMentionAssist.kt @@ -0,0 +1,105 @@ +package com.fire.app.ui.composer + +import android.text.Editable +import android.text.TextWatcher +import android.view.View +import android.widget.EditText +import android.widget.LinearLayout +import com.fire.app.session.FireSessionStore +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_search.UserMentionQueryState + +class ComposerMentionAssist( + private val input: EditText, + private val suggestions: LinearLayout, + private val sessionStore: FireSessionStore, + private val scope: CoroutineScope, + private val includeGroups: Boolean, + private val topicId: ULong? = null, + private val categoryIdProvider: () -> ULong? = { null }, +) { + private var searchJob: Job? = null + private var applyingSuggestion = false + + fun attach() { + input.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = scheduleSearch() + override fun afterTextChanged(s: Editable?) = Unit + }) + } + + private fun scheduleSearch() { + if (applyingSuggestion) return + val context = mentionContext() ?: run { + hideSuggestions() + return + } + searchJob?.cancel() + searchJob = scope.launch { + delay(200) + val result = runCatching { + sessionStore.searchUsers( + UserMentionQueryState( + term = context.term, + includeGroups = includeGroups, + limit = 8u, + topicId = topicId, + categoryId = categoryIdProvider(), + ), + ) + }.getOrNull() + val items = buildList { + result?.users.orEmpty().forEach { user -> + val display = user.name?.takeIf { it.isNotBlank() } ?: user.username + add(Suggestion(label = "$display @${user.username}", value = user.username)) + } + result?.groups.orEmpty().forEach { group -> + val display = group.fullName?.takeIf { it.isNotBlank() } ?: group.name + add(Suggestion(label = "$display @${group.name}", value = group.name)) + } + }.take(8) + input.post { + val latest = mentionContext() + if (latest?.term == context.term) { + showSuggestions(items, latest) + } + } + } + } + + private fun showSuggestions(items: List, context: TextContext) { + suggestions.removeAllViews() + suggestions.visibility = if (items.isEmpty()) View.GONE else View.VISIBLE + items.forEach { item -> + suggestions.addView(suggestionView(input.context, item.label) { + applyingSuggestion = true + input.text.replace(context.start, context.end, "@${item.value} ") + input.setSelection((context.start + item.value.length + 2).coerceAtMost(input.text.length)) + applyingSuggestion = false + hideSuggestions() + }) + } + } + + private fun hideSuggestions() { + suggestions.removeAllViews() + suggestions.visibility = View.GONE + } + + private fun mentionContext(): TextContext? { + val cursor = input.selectionStart.coerceAtLeast(0) + val text = input.text.toString() + if (cursor > text.length) return null + val prefix = text.substring(0, cursor) + val atIndex = prefix.lastIndexOf('@') + if (atIndex < 0) return null + if (atIndex > 0 && !prefix[atIndex - 1].isWhitespace()) return null + val term = prefix.substring(atIndex + 1) + if (term.length !in 1..30 || term.any { it.isWhitespace() }) return null + return TextContext(start = atIndex, end = cursor, term = term) + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerRecipientAssist.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerRecipientAssist.kt new file mode 100644 index 00000000..246ce9f8 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerRecipientAssist.kt @@ -0,0 +1,151 @@ +package com.fire.app.ui.composer + +import android.text.Editable +import android.text.TextWatcher +import android.view.View +import android.widget.EditText +import android.widget.LinearLayout +import com.fire.app.session.FireSessionStore +import com.google.android.material.chip.Chip +import com.google.android.material.chip.ChipGroup +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_search.UserMentionQueryState + +class ComposerRecipientAssist( + private val input: EditText, + private val suggestions: LinearLayout, + private val sessionStore: FireSessionStore, + private val scope: CoroutineScope, +) { + private var searchJob: Job? = null + private var applyingSuggestion = false + + fun attach() { + input.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = scheduleSearch() + override fun afterTextChanged(s: Editable?) = Unit + }) + } + + private fun scheduleSearch() { + if (applyingSuggestion) return + val context = recipientContext() ?: run { + hideSuggestions() + return + } + searchJob?.cancel() + searchJob = scope.launch { + delay(200) + val result = runCatching { + sessionStore.searchUsers( + UserMentionQueryState( + term = context.term, + includeGroups = false, + limit = 8u, + topicId = null, + categoryId = null, + ), + ) + }.getOrNull() + val items = result?.users.orEmpty() + .map { user -> + val display = user.name?.takeIf { it.isNotBlank() } ?: user.username + Suggestion(label = "$display @${user.username}", value = user.username) + } + .take(8) + input.post { + val latest = recipientContext() + if (latest?.term == context.term) { + showSuggestions(items, latest) + } + } + } + } + + private fun showSuggestions(items: List, context: TextContext) { + suggestions.removeAllViews() + suggestions.visibility = if (items.isEmpty()) View.GONE else View.VISIBLE + items.forEach { item -> + suggestions.addView(suggestionView(input.context, item.label) { + applyingSuggestion = true + input.text.replace(context.start, context.end, item.value) + input.text.insert((context.start + item.value.length).coerceAtMost(input.text.length), " ") + input.setSelection(input.text.length) + applyingSuggestion = false + hideSuggestions() + }) + } + } + + private fun hideSuggestions() { + suggestions.removeAllViews() + suggestions.visibility = View.GONE + } + + private fun recipientContext(): TextContext? { + val cursor = input.selectionStart.coerceAtLeast(0) + val text = input.text.toString() + if (cursor > text.length) return null + val prefix = text.substring(0, cursor) + val separator = maxOf(prefix.lastIndexOf(' '), prefix.lastIndexOf(','), prefix.lastIndexOf('\n')) + val start = separator + 1 + val term = prefix.substring(start).trim().removePrefix("@") + if (term.length !in 1..30 || term.any { it.isWhitespace() }) return null + return TextContext(start = start, end = cursor, term = term) + } +} + +class ComposerRecipientTokenView( + private val input: EditText, + private val tokens: ChipGroup, +) { + private var applyingTokenChange = false + + fun attach() { + input.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = render() + override fun afterTextChanged(s: Editable?) = Unit + }) + render() + } + + private fun render() { + if (applyingTokenChange) return + val recipients = recipientValues() + tokens.removeAllViews() + tokens.visibility = if (recipients.isEmpty()) View.GONE else View.VISIBLE + recipients.forEach { recipient -> + tokens.addView( + Chip(input.context).apply { + text = "@$recipient" + isCloseIconVisible = true + setOnCloseIconClickListener { + removeRecipient(recipient) + } + }, + ) + } + } + + private fun removeRecipient(username: String) { + applyingTokenChange = true + val remaining = recipientValues() + .filterNot { it.equals(username, ignoreCase = true) } + input.setText(remaining.joinToString(" ")) + input.setSelection(input.text.length) + applyingTokenChange = false + render() + } + + private fun recipientValues(): List = + input.text.toString() + .split("[,\\s]+".toRegex()) + .map { it.trim().removePrefix("@") } + .filter { it.isNotBlank() } + .distinctBy { it.lowercase() } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerTagAssist.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerTagAssist.kt new file mode 100644 index 00000000..a8f5e664 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerTagAssist.kt @@ -0,0 +1,99 @@ +package com.fire.app.ui.composer + +import android.text.Editable +import android.text.TextWatcher +import android.view.View +import android.widget.EditText +import android.widget.LinearLayout +import com.fire.app.session.FireSessionStore +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_search.TagSearchQueryState + +class ComposerTagAssist( + private val input: EditText, + private val suggestions: LinearLayout, + private val sessionStore: FireSessionStore, + private val scope: CoroutineScope, + private val categoryIdProvider: () -> ULong?, + private val selectedTagsProvider: () -> List, +) { + private var searchJob: Job? = null + private var applyingSuggestion = false + + fun attach() { + input.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = scheduleSearch() + override fun afterTextChanged(s: Editable?) = Unit + }) + } + + private fun scheduleSearch() { + if (applyingSuggestion) return + val context = tagContext() ?: run { + hideSuggestions() + return + } + searchJob?.cancel() + searchJob = scope.launch { + delay(250) + val result = runCatching { + sessionStore.searchTags( + TagSearchQueryState( + q = context.term, + filterForInput = true, + limit = 8u, + categoryId = categoryIdProvider(), + selectedTags = selectedTagsProvider(), + ), + ) + }.getOrNull() + val items = result?.results.orEmpty() + .map { item -> + val label = item.text.takeIf { it.isNotBlank() } ?: item.name + Suggestion(label = "$label (${item.count})", value = item.name) + } + .take(8) + input.post { + val latest = tagContext() + if (latest?.term == context.term) { + showSuggestions(items, latest) + } + } + } + } + + private fun showSuggestions(items: List, context: TextContext) { + suggestions.removeAllViews() + suggestions.visibility = if (items.isEmpty()) View.GONE else View.VISIBLE + items.forEach { item -> + suggestions.addView(suggestionView(input.context, item.label) { + applyingSuggestion = true + input.text.replace(context.start, context.end, item.value) + input.text.insert((context.start + item.value.length).coerceAtMost(input.text.length), " ") + applyingSuggestion = false + hideSuggestions() + }) + } + } + + private fun hideSuggestions() { + suggestions.removeAllViews() + suggestions.visibility = View.GONE + } + + private fun tagContext(): TextContext? { + val cursor = input.selectionStart.coerceAtLeast(0) + val text = input.text.toString() + if (cursor > text.length) return null + val prefix = text.substring(0, cursor) + val separator = maxOf(prefix.lastIndexOf(' '), prefix.lastIndexOf(','), prefix.lastIndexOf('\n')) + val start = separator + 1 + val term = prefix.substring(start).trim() + if (term.length !in 1..30) return null + return TextContext(start = start, end = cursor, term = term) + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerUpload.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerUpload.kt new file mode 100644 index 00000000..23ca05ed --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerUpload.kt @@ -0,0 +1,48 @@ +package com.fire.app.ui.composer + +import android.content.Context +import android.net.Uri +import android.provider.OpenableColumns +import com.fire.app.R +import com.fire.app.session.FireSessionStore +import uniffi.fire_uniffi_topics.UploadImageRequestState +import uniffi.fire_uniffi_topics.UploadResultState + +suspend fun uploadImageMarkdown( + context: Context, + sessionStore: FireSessionStore, + uri: Uri, +): String { + val resolver = context.contentResolver + val bytes = resolver.openInputStream(uri)?.use { it.readBytes() } + ?: error(context.getString(R.string.composer_upload_error)) + val mimeType = resolver.getType(uri) + val fileName = displayName(context, uri) ?: "image-${System.currentTimeMillis()}" + val result = sessionStore.uploadImage( + UploadImageRequestState( + fileName = fileName, + mimeType = mimeType, + bytes = bytes, + ), + ) + return markdownForUpload(result) +} + +private fun markdownForUpload(result: UploadResultState): String { + val alt = result.originalFilename?.takeIf { it.isNotBlank() } ?: "image" + val width = result.thumbnailWidth ?: result.width + val height = result.thumbnailHeight ?: result.height + return if (width != null && height != null) { + "![$alt|${width}x$height](${result.shortUrl})" + } else { + "![$alt](${result.shortUrl})" + } +} + +private fun displayName(context: Context, uri: Uri): String? { + return context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null) + ?.use { cursor -> + val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (index >= 0 && cursor.moveToFirst()) cursor.getString(index) else null + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/HeaderAdapter.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/HeaderAdapter.kt new file mode 100644 index 00000000..cd679b23 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/HeaderAdapter.kt @@ -0,0 +1,400 @@ +package com.fire.app.ui.topicdetail + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import com.fire.app.R +import com.fire.app.TopicPresentation +import com.google.android.material.chip.Chip +import com.google.android.material.chip.ChipGroup +import uniffi.fire_uniffi_topics.TopicAiSummaryState +import uniffi.fire_uniffi_topics.TopicDetailState +import uniffi.fire_uniffi_topics.TopicPostState + +class HeaderAdapter( + private val callbacks: PostRowCallbacks, + private val onToggleTopicVote: () -> Unit, + private val onShowTopicVoters: (TopicDetailState) -> Unit, + private val onEditTopicClick: (TopicDetailState) -> Unit, +) : RecyclerView.Adapter() { + private val attachedHolders = mutableSetOf() + private var boostAnimationsEnabled = true + + var highlightedPostId: ULong? = null + set(value) { + if (field == value) return + field = value + notifyHeaderChanged() + } + + var detail: TopicDetailState? = null + set(value) { + val oldValue = field + if (oldValue != null && value != null && oldValue.hasSameHeaderContent(value)) { + field = value + return + } + field = value + when { + oldValue == null && value != null -> notifyItemInserted(0) + oldValue != null && value == null -> notifyItemRemoved(0) + oldValue != null && value != null -> notifyItemChanged(0) + } + } + + var aiSummary: TopicAiSummaryState? = null + set(value) { + if (field == value) return + field = value + if (value == null) { + isAiSummaryExpanded = false + } + notifyHeaderChanged() + } + + var isAiSummaryExpanded: Boolean = false + set(value) { + if (field == value) return + field = value + notifyHeaderChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HeaderViewHolder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.item_topic_header, parent, false) + return HeaderViewHolder( + itemView = view, + callbacks = callbacks, + onToggleTopicVote = onToggleTopicVote, + onShowTopicVoters = onShowTopicVoters, + onEditTopicClick = onEditTopicClick, + ) + } + + override fun onBindViewHolder(holder: HeaderViewHolder, position: Int) { + holder.setBoostAnimationsEnabled(boostAnimationsEnabled) + detail?.let { + holder.bind( + detail = it, + aiSummary = aiSummary, + isAiSummaryExpanded = isAiSummaryExpanded, + onToggleAiSummaryExpanded = { + isAiSummaryExpanded = !isAiSummaryExpanded + }, + highlightedPostId = highlightedPostId, + ) + } + } + + override fun onViewAttachedToWindow(holder: HeaderViewHolder) { + super.onViewAttachedToWindow(holder) + attachedHolders += holder + holder.onAttachedToWindow() + holder.setBoostAnimationsEnabled(boostAnimationsEnabled) + } + + override fun onViewDetachedFromWindow(holder: HeaderViewHolder) { + attachedHolders -= holder + holder.onDetachedFromWindow() + super.onViewDetachedFromWindow(holder) + } + + override fun getItemCount(): Int = if (detail != null) 1 else 0 + + private fun TopicDetailState.hasSameHeaderContent(other: TopicDetailState): Boolean { + return title == other.title && + tags == other.tags && + categoryId == other.categoryId && + postsCount == other.postsCount && + replyCount == other.replyCount && + highestPostNumber == other.highestPostNumber && + views == other.views && + likeCount == other.likeCount && + bookmarked == other.bookmarked && + bookmarkId == other.bookmarkId && + bookmarkName == other.bookmarkName && + bookmarkReminderAt == other.bookmarkReminderAt && + canVote == other.canVote && + voteCount == other.voteCount && + userVoted == other.userVoted && + summarizable == other.summarizable && + hasCachedSummary == other.hasCachedSummary && + hasSummary == other.hasSummary && + originalPost() == other.originalPost() + } + + private fun notifyHeaderChanged() { + if (detail != null) { + notifyItemChanged(0) + } + } + + fun refreshRows() { + notifyHeaderChanged() + } + + fun setBoostAnimationsEnabled(enabled: Boolean) { + if (boostAnimationsEnabled == enabled) return + boostAnimationsEnabled = enabled + attachedHolders.forEach { holder -> + holder.setBoostAnimationsEnabled(enabled) + } + } + + private fun TopicDetailState.originalPost(): TopicPostState? { + return postStream.posts.minByOrNull { it.postNumber } + } + + class HeaderViewHolder( + itemView: View, + private val callbacks: PostRowCallbacks, + private val onToggleTopicVote: () -> Unit, + private val onShowTopicVoters: (TopicDetailState) -> Unit, + private val onEditTopicClick: (TopicDetailState) -> Unit, + ) : RecyclerView.ViewHolder(itemView) { + private val titleText: TextView = itemView.findViewById(R.id.topic_title) + private val chips: ChipGroup = itemView.findViewById(R.id.topic_chips) + private val topicEditButton: TextView = itemView.findViewById(R.id.topic_edit_button) + private val topicBookmarkButton: TextView = itemView.findViewById(R.id.topic_bookmark_button) + private val aiSummaryContainer: View = itemView.findViewById(R.id.ai_summary_container) + private val aiSummaryHeader: View = itemView.findViewById(R.id.ai_summary_header) + private val aiSummaryStatus: TextView = itemView.findViewById(R.id.ai_summary_status) + private val aiSummaryExpandIcon: ImageView = itemView.findViewById(R.id.ai_summary_expand_icon) + private val aiSummaryContent: View = itemView.findViewById(R.id.ai_summary_content) + private val aiSummaryBody: TextView = itemView.findViewById(R.id.ai_summary_body) + private val aiSummaryMeta: TextView = itemView.findViewById(R.id.ai_summary_meta) + private val statReplies: TextView = itemView.findViewById(R.id.stat_replies) + private val statViews: TextView = itemView.findViewById(R.id.stat_views) + private val statLikes: TextView = itemView.findViewById(R.id.stat_likes) + private val topicVoteContainer: View = itemView.findViewById(R.id.topic_vote_container) + private val topicVoteCount: TextView = itemView.findViewById(R.id.topic_vote_count) + private val topicVoteStatus: TextView = itemView.findViewById(R.id.topic_vote_status) + private val topicVoteVotersButton: TextView = itemView.findViewById(R.id.topic_vote_voters_button) + private val topicVoteButton: TextView = itemView.findViewById(R.id.topic_vote_button) + private val originalPostContainer: View = itemView.findViewById(R.id.original_post_container) + private val originalPostHolder = PostViewHolder(originalPostContainer) + + fun onAttachedToWindow() { + originalPostHolder.onAttachedToWindow() + } + + fun onDetachedFromWindow() { + originalPostHolder.onDetachedFromWindow() + } + + fun setBoostAnimationsEnabled(enabled: Boolean) { + originalPostHolder.setBoostAnimationsEnabled(enabled) + } + + fun bind( + detail: TopicDetailState, + aiSummary: TopicAiSummaryState?, + isAiSummaryExpanded: Boolean, + onToggleAiSummaryExpanded: () -> Unit, + highlightedPostId: ULong?, + ) { + titleText.text = detail.title.trim() + val tagNames = TopicPresentation.tagNames(detail.tags) + if (tagNames.isNotEmpty() || detail.categoryId != null) { + chips.visibility = View.VISIBLE + chips.removeAllViews() + detail.categoryId?.let { cid -> + chips.addView(topicChip("分类 $cid", isCategory = true)) + } + for (tagName in tagNames) { + chips.addView(topicChip("#$tagName", isCategory = false)) + } + } else { + chips.visibility = View.GONE + } + bindTopicEdit(detail) + bindTopicBookmark() + bindAiSummary(aiSummary, isAiSummaryExpanded, onToggleAiSummaryExpanded) + statReplies.text = "${detail.replyCount}" + statViews.text = "${detail.views}" + statLikes.text = "${detail.likeCount}" + bindTopicVote(detail) + + val originalPost = detail.postStream.posts.minByOrNull { it.postNumber } + if (originalPost != null) { + originalPostContainer.visibility = View.VISIBLE + originalPostContainer.setPadding( + 0, + originalPostContainer.paddingTop, + 0, + originalPostContainer.paddingBottom, + ) + originalPostHolder.bind( + row = PostRow(post = originalPost, depth = 0, usesTitleWidthBody = true), + callbacks = callbacks, + isSearchHighlighted = originalPost.id == highlightedPostId, + ) + } else { + originalPostContainer.visibility = View.GONE + } + } + + private fun bindTopicEdit(detail: TopicDetailState) { + val isPrivateMessageThread = detail.archetype + ?.trim() + ?.equals("private_message", ignoreCase = true) == true + val visible = detail.details.canEdit && !isPrivateMessageThread + topicEditButton.visibility = if (visible) View.VISIBLE else View.GONE + if (visible) { + topicEditButton.setOnClickListener { onEditTopicClick(detail) } + } else { + topicEditButton.setOnClickListener(null) + } + } + + private fun bindTopicBookmark() { + topicBookmarkButton.visibility = View.GONE + topicBookmarkButton.setOnClickListener(null) + topicBookmarkButton.text = null + } + + private fun topicChip(label: String, isCategory: Boolean): Chip { + val context = itemView.context + return Chip(context).apply { + text = label + isClickable = false + isCheckable = false + isFocusable = false + minHeight = 0 + minimumHeight = 0 + chipMinHeight = dp(26).toFloat() + setEnsureMinTouchTargetSize(false) + includeFontPadding = false + textSize = 12f + setChipBackgroundColorResource( + if (isCategory) R.color.fire_chip_accent_background else R.color.fire_background_surface, + ) + setChipStrokeColorResource( + if (isCategory) R.color.fire_accent_soft else R.color.fire_divider, + ) + chipStrokeWidth = dp(1).toFloat() + setTextColor(context.getColor(if (isCategory) R.color.fire_accent else R.color.fire_text_secondary)) + chipStartPadding = dp(9).toFloat() + chipEndPadding = dp(9).toFloat() + textStartPadding = 0f + textEndPadding = 0f + closeIconStartPadding = 0f + closeIconEndPadding = 0f + layoutParams = ChipGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + dp(28), + ).apply { + marginEnd = dp(6) + bottomMargin = dp(6) + } + } + } + + private fun dp(value: Int): Int { + return (itemView.resources.displayMetrics.density * value).toInt() + } + + private fun bindTopicVote(detail: TopicDetailState) { + val visible = detail.canVote || detail.userVoted || detail.voteCount > 0 + topicVoteContainer.visibility = if (visible) View.VISIBLE else View.GONE + if (!visible) return + + val context = itemView.context + topicVoteCount.text = context.getString( + R.string.topic_detail_vote_count, + detail.voteCount.coerceAtLeast(0).toString(), + ) + topicVoteStatus.text = if (detail.userVoted) { + context.getString(R.string.topic_detail_vote_you_voted) + } else { + "" + } + topicVoteButton.text = context.getString( + if (detail.userVoted) { + R.string.topic_detail_unvote_topic + } else { + R.string.topic_detail_vote_topic + }, + ) + topicVoteButton.isEnabled = detail.canVote || detail.userVoted + topicVoteButton.setTextColor( + context.getColor( + if (detail.userVoted) R.color.fire_text_secondary else R.color.fire_accent, + ), + ) + topicVoteButton.setOnClickListener { + onToggleTopicVote() + } + topicVoteVotersButton.visibility = if (detail.voteCount > 0) View.VISIBLE else View.GONE + topicVoteVotersButton.setOnClickListener { + onShowTopicVoters(detail) + } + } + + private fun bindAiSummary( + summary: TopicAiSummaryState?, + isExpanded: Boolean, + onToggleExpanded: () -> Unit, + ) { + // Background-load only: keep the header free of loading/error chrome so the common + // no-summary path never inserts temporary layout that later disappears. + if (summary == null) { + aiSummaryContainer.visibility = View.GONE + aiSummaryHeader.setOnClickListener(null) + return + } + + aiSummaryContainer.visibility = View.VISIBLE + aiSummaryStatus.visibility = if (summary.outdated) View.VISIBLE else View.GONE + if (summary.outdated) { + aiSummaryStatus.text = itemView.context.getString(R.string.topic_detail_ai_summary_outdated) + } + aiSummaryExpandIcon.rotation = if (isExpanded) 180f else 0f + aiSummaryExpandIcon.contentDescription = itemView.context.getString( + if (isExpanded) { + R.string.topic_detail_ai_summary_collapse + } else { + R.string.topic_detail_ai_summary_expand + }, + ) + aiSummaryHeader.setOnClickListener { onToggleExpanded() } + + if (isExpanded) { + aiSummaryContent.visibility = View.VISIBLE + aiSummaryBody.text = summary.summarizedText.trim() + val metadata = topicAiSummaryMetadata(summary) + aiSummaryMeta.text = metadata.joinToString(" · ") + aiSummaryMeta.visibility = if (metadata.isNotEmpty()) View.VISIBLE else View.GONE + } else { + aiSummaryContent.visibility = View.GONE + } + } + + private fun topicAiSummaryMetadata(summary: TopicAiSummaryState): List { + val context = itemView.context + val metadata = mutableListOf() + TopicPresentation.formatTimestamp(summary.updatedAt)?.let { updatedAt -> + metadata.add(context.getString(R.string.topic_detail_ai_summary_updated, updatedAt)) + } + if (summary.outdated && summary.newPostsSinceSummary > 0u) { + metadata.add( + context.getString( + R.string.topic_detail_ai_summary_new_posts, + summary.newPostsSinceSummary.toString(), + ), + ) + } + val algorithm = summary.algorithm?.trim() + if (!algorithm.isNullOrEmpty()) { + metadata.add(algorithm) + } + if (summary.canRegenerate) { + metadata.add(context.getString(R.string.topic_detail_ai_summary_can_regenerate)) + } + return metadata + } + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/LoadingFooterAdapter.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/LoadingFooterAdapter.kt new file mode 100644 index 00000000..9f11985e --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/LoadingFooterAdapter.kt @@ -0,0 +1,34 @@ +package com.fire.app.ui.topicdetail + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import com.fire.app.R + +class LoadingFooterAdapter : RecyclerView.Adapter() { + + var isLoading: Boolean = false + set(value) { + val oldValue = field + if (oldValue == value) return + field = value + if (value) { + notifyItemInserted(0) + } else { + notifyItemRemoved(0) + } + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FooterViewHolder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.item_loading_footer, parent, false) + return FooterViewHolder(view) + } + + override fun onBindViewHolder(holder: FooterViewHolder, position: Int) {} + + override fun getItemCount(): Int = if (isLoading) 1 else 0 + + class FooterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListAdapter.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListAdapter.kt index 306adfff..013a0b9b 100644 --- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListAdapter.kt +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListAdapter.kt @@ -1,53 +1,8 @@ package com.fire.app.ui.topicdetail -import android.view.LayoutInflater -import android.view.View import android.view.ViewGroup -import android.widget.ImageView -import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter -import androidx.recyclerview.widget.RecyclerView -import com.fire.app.R -import com.fire.app.TopicPresentation -import com.fire.app.richtext.FireCookedImage -import com.google.android.material.chip.Chip -import com.google.android.material.chip.ChipGroup -import uniffi.fire_uniffi_topics.PollState -import uniffi.fire_uniffi_topics.TopicAiSummaryState -import uniffi.fire_uniffi_topics.TopicDetailState -import uniffi.fire_uniffi_topics.TopicPostState - -data class PostRow( - val post: TopicPostState, - val depth: Int = 0, - val parentPostNumber: UInt? = null, - val hasChildren: Boolean = false, - val usesTitleWidthBody: Boolean = false, - val hiddenReplyCount: UInt = 0u, -) - -data class PostRowCallbacks( - val reactionIds: () -> List = { emptyList() }, - val onPostClick: (TopicPostState) -> Unit = {}, - val onReplyClick: (TopicPostState) -> Unit = {}, - val onQuoteClick: (TopicPostState) -> Unit = {}, - val onHeartClick: (TopicPostState) -> Unit = {}, - val onReactClick: (TopicPostState) -> Unit = {}, - val onBookmarkClick: (TopicPostState) -> Unit = {}, - val onVotePoll: (TopicPostState, PollState, List) -> Unit = { _, _, _ -> }, - val onUnvotePoll: (TopicPostState, PollState) -> Unit = { _, _ -> }, - val onReactionsClick: (TopicPostState) -> Unit = {}, - val onReplyContextClick: (TopicPostState) -> Unit = {}, - val onMoreRepliesClick: (TopicPostState) -> Unit = {}, - val onDeletePostClick: (TopicPostState) -> Unit = {}, - val onRecoverPostClick: (TopicPostState) -> Unit = {}, - val onFlagPostClick: (TopicPostState) -> Unit = {}, - val onEditPostClick: (TopicPostState) -> Unit = {}, - val onImageClick: (FireCookedImage) -> Unit = {}, - val onAuthorClick: (String) -> Unit = {}, - val onLinkClick: (String) -> Unit = {}, -) class PostListAdapter( private val callbacks: PostRowCallbacks, @@ -109,415 +64,3 @@ class PostListAdapter( oldItem == newItem } } - -class HeaderAdapter( - private val callbacks: PostRowCallbacks, - private val onToggleTopicVote: () -> Unit, - private val onShowTopicVoters: (TopicDetailState) -> Unit, - private val onEditTopicClick: (TopicDetailState) -> Unit, -) : RecyclerView.Adapter() { - private val attachedHolders = mutableSetOf() - private var boostAnimationsEnabled = true - - var highlightedPostId: ULong? = null - set(value) { - if (field == value) return - field = value - notifyHeaderChanged() - } - - var detail: TopicDetailState? = null - set(value) { - val oldValue = field - if (oldValue != null && value != null && oldValue.hasSameHeaderContent(value)) { - field = value - return - } - field = value - when { - oldValue == null && value != null -> notifyItemInserted(0) - oldValue != null && value == null -> notifyItemRemoved(0) - oldValue != null && value != null -> notifyItemChanged(0) - } - } - - var aiSummary: TopicAiSummaryState? = null - set(value) { - if (field == value) return - field = value - if (value == null) { - isAiSummaryExpanded = false - } - notifyHeaderChanged() - } - - var isAiSummaryExpanded: Boolean = false - set(value) { - if (field == value) return - field = value - notifyHeaderChanged() - } - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HeaderViewHolder { - val view = LayoutInflater.from(parent.context) - .inflate(R.layout.item_topic_header, parent, false) - return HeaderViewHolder( - itemView = view, - callbacks = callbacks, - onToggleTopicVote = onToggleTopicVote, - onShowTopicVoters = onShowTopicVoters, - onEditTopicClick = onEditTopicClick, - ) - } - - override fun onBindViewHolder(holder: HeaderViewHolder, position: Int) { - holder.setBoostAnimationsEnabled(boostAnimationsEnabled) - detail?.let { - holder.bind( - detail = it, - aiSummary = aiSummary, - isAiSummaryExpanded = isAiSummaryExpanded, - onToggleAiSummaryExpanded = { - isAiSummaryExpanded = !isAiSummaryExpanded - }, - highlightedPostId = highlightedPostId, - ) - } - } - - override fun onViewAttachedToWindow(holder: HeaderViewHolder) { - super.onViewAttachedToWindow(holder) - attachedHolders += holder - holder.onAttachedToWindow() - holder.setBoostAnimationsEnabled(boostAnimationsEnabled) - } - - override fun onViewDetachedFromWindow(holder: HeaderViewHolder) { - attachedHolders -= holder - holder.onDetachedFromWindow() - super.onViewDetachedFromWindow(holder) - } - - override fun getItemCount(): Int = if (detail != null) 1 else 0 - - private fun TopicDetailState.hasSameHeaderContent(other: TopicDetailState): Boolean { - return title == other.title && - tags == other.tags && - categoryId == other.categoryId && - postsCount == other.postsCount && - replyCount == other.replyCount && - highestPostNumber == other.highestPostNumber && - views == other.views && - likeCount == other.likeCount && - bookmarked == other.bookmarked && - bookmarkId == other.bookmarkId && - bookmarkName == other.bookmarkName && - bookmarkReminderAt == other.bookmarkReminderAt && - canVote == other.canVote && - voteCount == other.voteCount && - userVoted == other.userVoted && - summarizable == other.summarizable && - hasCachedSummary == other.hasCachedSummary && - hasSummary == other.hasSummary && - originalPost() == other.originalPost() - } - - private fun notifyHeaderChanged() { - if (detail != null) { - notifyItemChanged(0) - } - } - - fun refreshRows() { - notifyHeaderChanged() - } - - fun setBoostAnimationsEnabled(enabled: Boolean) { - if (boostAnimationsEnabled == enabled) return - boostAnimationsEnabled = enabled - attachedHolders.forEach { holder -> - holder.setBoostAnimationsEnabled(enabled) - } - } - - private fun TopicDetailState.originalPost(): TopicPostState? { - return postStream.posts.minByOrNull { it.postNumber } - } - - class HeaderViewHolder( - itemView: View, - private val callbacks: PostRowCallbacks, - private val onToggleTopicVote: () -> Unit, - private val onShowTopicVoters: (TopicDetailState) -> Unit, - private val onEditTopicClick: (TopicDetailState) -> Unit, - ) : RecyclerView.ViewHolder(itemView) { - private val titleText: TextView = itemView.findViewById(R.id.topic_title) - private val chips: ChipGroup = itemView.findViewById(R.id.topic_chips) - private val topicEditButton: TextView = itemView.findViewById(R.id.topic_edit_button) - private val topicBookmarkButton: TextView = itemView.findViewById(R.id.topic_bookmark_button) - private val aiSummaryContainer: View = itemView.findViewById(R.id.ai_summary_container) - private val aiSummaryHeader: View = itemView.findViewById(R.id.ai_summary_header) - private val aiSummaryStatus: TextView = itemView.findViewById(R.id.ai_summary_status) - private val aiSummaryExpandIcon: ImageView = itemView.findViewById(R.id.ai_summary_expand_icon) - private val aiSummaryContent: View = itemView.findViewById(R.id.ai_summary_content) - private val aiSummaryBody: TextView = itemView.findViewById(R.id.ai_summary_body) - private val aiSummaryMeta: TextView = itemView.findViewById(R.id.ai_summary_meta) - private val statReplies: TextView = itemView.findViewById(R.id.stat_replies) - private val statViews: TextView = itemView.findViewById(R.id.stat_views) - private val statLikes: TextView = itemView.findViewById(R.id.stat_likes) - private val topicVoteContainer: View = itemView.findViewById(R.id.topic_vote_container) - private val topicVoteCount: TextView = itemView.findViewById(R.id.topic_vote_count) - private val topicVoteStatus: TextView = itemView.findViewById(R.id.topic_vote_status) - private val topicVoteVotersButton: TextView = itemView.findViewById(R.id.topic_vote_voters_button) - private val topicVoteButton: TextView = itemView.findViewById(R.id.topic_vote_button) - private val originalPostContainer: View = itemView.findViewById(R.id.original_post_container) - private val originalPostHolder = PostViewHolder(originalPostContainer) - - fun onAttachedToWindow() { - originalPostHolder.onAttachedToWindow() - } - - fun onDetachedFromWindow() { - originalPostHolder.onDetachedFromWindow() - } - - fun setBoostAnimationsEnabled(enabled: Boolean) { - originalPostHolder.setBoostAnimationsEnabled(enabled) - } - - fun bind( - detail: TopicDetailState, - aiSummary: TopicAiSummaryState?, - isAiSummaryExpanded: Boolean, - onToggleAiSummaryExpanded: () -> Unit, - highlightedPostId: ULong?, - ) { - titleText.text = detail.title.trim() - val tagNames = TopicPresentation.tagNames(detail.tags) - if (tagNames.isNotEmpty() || detail.categoryId != null) { - chips.visibility = View.VISIBLE - chips.removeAllViews() - detail.categoryId?.let { cid -> - chips.addView(topicChip("分类 $cid", isCategory = true)) - } - for (tagName in tagNames) { - chips.addView(topicChip("#$tagName", isCategory = false)) - } - } else { - chips.visibility = View.GONE - } - bindTopicEdit(detail) - bindTopicBookmark() - bindAiSummary(aiSummary, isAiSummaryExpanded, onToggleAiSummaryExpanded) - statReplies.text = "${detail.replyCount}" - statViews.text = "${detail.views}" - statLikes.text = "${detail.likeCount}" - bindTopicVote(detail) - - val originalPost = detail.postStream.posts.minByOrNull { it.postNumber } - if (originalPost != null) { - originalPostContainer.visibility = View.VISIBLE - originalPostContainer.setPadding( - 0, - originalPostContainer.paddingTop, - 0, - originalPostContainer.paddingBottom, - ) - originalPostHolder.bind( - row = PostRow(post = originalPost, depth = 0, usesTitleWidthBody = true), - callbacks = callbacks, - isSearchHighlighted = originalPost.id == highlightedPostId, - ) - } else { - originalPostContainer.visibility = View.GONE - } - } - - private fun bindTopicEdit(detail: TopicDetailState) { - val isPrivateMessageThread = detail.archetype - ?.trim() - ?.equals("private_message", ignoreCase = true) == true - val visible = detail.details.canEdit && !isPrivateMessageThread - topicEditButton.visibility = if (visible) View.VISIBLE else View.GONE - if (visible) { - topicEditButton.setOnClickListener { onEditTopicClick(detail) } - } else { - topicEditButton.setOnClickListener(null) - } - } - - private fun bindTopicBookmark() { - topicBookmarkButton.visibility = View.GONE - topicBookmarkButton.setOnClickListener(null) - topicBookmarkButton.text = null - } - - private fun topicChip(label: String, isCategory: Boolean): Chip { - val context = itemView.context - return Chip(context).apply { - text = label - isClickable = false - isCheckable = false - isFocusable = false - minHeight = 0 - minimumHeight = 0 - chipMinHeight = dp(26).toFloat() - setEnsureMinTouchTargetSize(false) - includeFontPadding = false - textSize = 12f - setChipBackgroundColorResource( - if (isCategory) R.color.fire_chip_accent_background else R.color.fire_background_surface, - ) - setChipStrokeColorResource( - if (isCategory) R.color.fire_accent_soft else R.color.fire_divider, - ) - chipStrokeWidth = dp(1).toFloat() - setTextColor(context.getColor(if (isCategory) R.color.fire_accent else R.color.fire_text_secondary)) - chipStartPadding = dp(9).toFloat() - chipEndPadding = dp(9).toFloat() - textStartPadding = 0f - textEndPadding = 0f - closeIconStartPadding = 0f - closeIconEndPadding = 0f - layoutParams = ChipGroup.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, - dp(28), - ).apply { - marginEnd = dp(6) - bottomMargin = dp(6) - } - } - } - - private fun dp(value: Int): Int { - return (itemView.resources.displayMetrics.density * value).toInt() - } - - private fun bindTopicVote(detail: TopicDetailState) { - val visible = detail.canVote || detail.userVoted || detail.voteCount > 0 - topicVoteContainer.visibility = if (visible) View.VISIBLE else View.GONE - if (!visible) return - - val context = itemView.context - topicVoteCount.text = context.getString( - R.string.topic_detail_vote_count, - detail.voteCount.coerceAtLeast(0).toString(), - ) - topicVoteStatus.text = if (detail.userVoted) { - context.getString(R.string.topic_detail_vote_you_voted) - } else { - "" - } - topicVoteButton.text = context.getString( - if (detail.userVoted) { - R.string.topic_detail_unvote_topic - } else { - R.string.topic_detail_vote_topic - }, - ) - topicVoteButton.isEnabled = detail.canVote || detail.userVoted - topicVoteButton.setTextColor( - context.getColor( - if (detail.userVoted) R.color.fire_text_secondary else R.color.fire_accent, - ), - ) - topicVoteButton.setOnClickListener { - onToggleTopicVote() - } - topicVoteVotersButton.visibility = if (detail.voteCount > 0) View.VISIBLE else View.GONE - topicVoteVotersButton.setOnClickListener { - onShowTopicVoters(detail) - } - } - - private fun bindAiSummary( - summary: TopicAiSummaryState?, - isExpanded: Boolean, - onToggleExpanded: () -> Unit, - ) { - // Background-load only: keep the header free of loading/error chrome so the common - // no-summary path never inserts temporary layout that later disappears. - if (summary == null) { - aiSummaryContainer.visibility = View.GONE - aiSummaryHeader.setOnClickListener(null) - return - } - - aiSummaryContainer.visibility = View.VISIBLE - aiSummaryStatus.visibility = if (summary.outdated) View.VISIBLE else View.GONE - if (summary.outdated) { - aiSummaryStatus.text = itemView.context.getString(R.string.topic_detail_ai_summary_outdated) - } - aiSummaryExpandIcon.rotation = if (isExpanded) 180f else 0f - aiSummaryExpandIcon.contentDescription = itemView.context.getString( - if (isExpanded) { - R.string.topic_detail_ai_summary_collapse - } else { - R.string.topic_detail_ai_summary_expand - }, - ) - aiSummaryHeader.setOnClickListener { onToggleExpanded() } - - if (isExpanded) { - aiSummaryContent.visibility = View.VISIBLE - aiSummaryBody.text = summary.summarizedText.trim() - val metadata = topicAiSummaryMetadata(summary) - aiSummaryMeta.text = metadata.joinToString(" · ") - aiSummaryMeta.visibility = if (metadata.isNotEmpty()) View.VISIBLE else View.GONE - } else { - aiSummaryContent.visibility = View.GONE - } - } - - private fun topicAiSummaryMetadata(summary: TopicAiSummaryState): List { - val context = itemView.context - val metadata = mutableListOf() - TopicPresentation.formatTimestamp(summary.updatedAt)?.let { updatedAt -> - metadata.add(context.getString(R.string.topic_detail_ai_summary_updated, updatedAt)) - } - if (summary.outdated && summary.newPostsSinceSummary > 0u) { - metadata.add( - context.getString( - R.string.topic_detail_ai_summary_new_posts, - summary.newPostsSinceSummary.toString(), - ), - ) - } - val algorithm = summary.algorithm?.trim() - if (!algorithm.isNullOrEmpty()) { - metadata.add(algorithm) - } - if (summary.canRegenerate) { - metadata.add(context.getString(R.string.topic_detail_ai_summary_can_regenerate)) - } - return metadata - } - } -} - -class LoadingFooterAdapter : RecyclerView.Adapter() { - - var isLoading: Boolean = false - set(value) { - val oldValue = field - if (oldValue == value) return - field = value - if (value) { - notifyItemInserted(0) - } else { - notifyItemRemoved(0) - } - } - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FooterViewHolder { - val view = LayoutInflater.from(parent.context) - .inflate(R.layout.item_loading_footer, parent, false) - return FooterViewHolder(view) - } - - override fun onBindViewHolder(holder: FooterViewHolder, position: Int) {} - - override fun getItemCount(): Int = if (isLoading) 1 else 0 - - class FooterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) -} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListModels.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListModels.kt new file mode 100644 index 00000000..a16864f2 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListModels.kt @@ -0,0 +1,36 @@ +package com.fire.app.ui.topicdetail + +import com.fire.app.richtext.FireCookedImage +import uniffi.fire_uniffi_topics.PollState +import uniffi.fire_uniffi_topics.TopicPostState + +data class PostRow( + val post: TopicPostState, + val depth: Int = 0, + val parentPostNumber: UInt? = null, + val hasChildren: Boolean = false, + val usesTitleWidthBody: Boolean = false, + val hiddenReplyCount: UInt = 0u, +) + +data class PostRowCallbacks( + val reactionIds: () -> List = { emptyList() }, + val onPostClick: (TopicPostState) -> Unit = {}, + val onReplyClick: (TopicPostState) -> Unit = {}, + val onQuoteClick: (TopicPostState) -> Unit = {}, + val onHeartClick: (TopicPostState) -> Unit = {}, + val onReactClick: (TopicPostState) -> Unit = {}, + val onBookmarkClick: (TopicPostState) -> Unit = {}, + val onVotePoll: (TopicPostState, PollState, List) -> Unit = { _, _, _ -> }, + val onUnvotePoll: (TopicPostState, PollState) -> Unit = { _, _ -> }, + val onReactionsClick: (TopicPostState) -> Unit = {}, + val onReplyContextClick: (TopicPostState) -> Unit = {}, + val onMoreRepliesClick: (TopicPostState) -> Unit = {}, + val onDeletePostClick: (TopicPostState) -> Unit = {}, + val onRecoverPostClick: (TopicPostState) -> Unit = {}, + val onFlagPostClick: (TopicPostState) -> Unit = {}, + val onEditPostClick: (TopicPostState) -> Unit = {}, + val onImageClick: (FireCookedImage) -> Unit = {}, + val onAuthorClick: (String) -> Unit = {}, + val onLinkClick: (String) -> Unit = {}, +) diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Actions.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Actions.kt new file mode 100644 index 00000000..76a98835 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Actions.kt @@ -0,0 +1,75 @@ +package com.fire.app.ui.topicdetail + +import android.content.res.ColorStateList +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import com.fire.app.R + +internal fun PostViewHolder.configureIconAction( + view: TextView, + iconRes: Int, + contentDescription: String, + active: Boolean = false, + enabled: Boolean = true, + onClick: () -> Unit, +) { + view.visibility = View.VISIBLE + view.text = null + view.contentDescription = contentDescription + view.isEnabled = enabled + view.alpha = if (enabled) 1f else 0.45f + view.gravity = android.view.Gravity.CENTER + view.includeFontPadding = false + view.setCompoundDrawablesRelativeWithIntrinsicBounds(iconRes, 0, 0, 0) + view.compoundDrawableTintList = ColorStateList.valueOf( + itemView.context.getColor(if (active) R.color.fire_accent else R.color.fire_text_secondary), + ) + view.setTextColor(itemView.context.getColor(if (active) R.color.fire_accent else R.color.fire_text_secondary)) + view.setOnClickListener(if (enabled) View.OnClickListener { onClick() } else null) +} + +internal fun PostViewHolder.configureHiddenAction(view: TextView) { + view.visibility = View.GONE + view.text = null + view.contentDescription = null + view.compoundDrawableTintList = null + view.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0) + view.setOnClickListener(null) + view.alpha = 1f + view.isEnabled = true +} + +internal fun PostViewHolder.bindMoreRepliesAction(row: PostRow, callbacks: PostRowCallbacks) { + val count = row.hiddenReplyCount + if (count == 0u) { + moreRepliesAction.visibility = View.GONE + moreRepliesAction.setOnClickListener(null) + applyActionStartMargin(likeAction, 0) + return + } + + moreRepliesAction.visibility = View.VISIBLE + moreRepliesAction.text = itemView.context.getString( + R.string.topic_detail_load_more_replies_count, + count.toString(), + ) + moreRepliesAction.setOnClickListener { callbacks.onMoreRepliesClick(row.post) } + applyActionStartMargin(likeAction, 16) +} + +internal fun PostViewHolder.applyActionsTopMargin(marginDp: Int) { + val params = actionsScroll.layoutParams as? ViewGroup.MarginLayoutParams ?: return + val marginPx = dp(marginDp) + if (params.topMargin == marginPx) return + params.topMargin = marginPx + actionsScroll.layoutParams = params +} + +internal fun PostViewHolder.applyActionStartMargin(view: View, marginDp: Int) { + val params = view.layoutParams as? ViewGroup.MarginLayoutParams ?: return + val marginPx = dp(marginDp) + if (params.marginStart == marginPx) return + params.marginStart = marginPx + view.layoutParams = params +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Author.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Author.kt new file mode 100644 index 00000000..97c531ac --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Author.kt @@ -0,0 +1,132 @@ +package com.fire.app.ui.topicdetail + +import android.graphics.drawable.GradientDrawable +import android.text.TextUtils +import android.view.View +import android.widget.LinearLayout +import android.widget.TextView +import com.fire.app.R +import uniffi.fire_uniffi_topics.TopicPostState + +internal data class AuthorMetadataChip( + val label: String, + val textColorRes: Int, + val backgroundColorRes: Int, +) + +internal fun PostViewHolder.bindAuthorChips(chips: List) { + authorChips.removeAllViews() + authorChips.visibility = if (chips.isEmpty()) View.GONE else View.VISIBLE + val context = itemView.context + chips.forEachIndexed { index, chip -> + val chipView = TextView(context).apply { + text = chip.label + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) + setTextColor(context.getColor(chip.textColorRes)) + maxLines = 1 + ellipsize = TextUtils.TruncateAt.END + includeFontPadding = false + setPadding(dp(6), dp(2), dp(6), dp(2)) + background = GradientDrawable().apply { + cornerRadius = dp(9).toFloat() + setColor(context.getColor(chip.backgroundColorRes)) + } + layoutParams = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ).apply { + if (index > 0) marginStart = dp(4) + } + } + authorChips.addView(chipView) + } +} + +internal fun displayName(post: TopicPostState): String { + return cleaned(post.name) + ?: cleaned(post.username) + ?: "Unknown" +} + +internal fun primaryMetadataParts(post: TopicPostState): List { + val metadata = post.authorMetadata + // Fluxdo-style: staff roles only on the primary line. + // Trust title sits on the secondary @username line; flair/group are not text chips. + return buildList { + if (metadata.admin) { + add(AuthorMetadataChip("管理员", R.color.fire_error, R.color.fire_chip_error_background)) + } + if (metadata.moderator) { + add(AuthorMetadataChip("版主", R.color.fire_link, R.color.fire_chip_link_background)) + } + if (metadata.groupModerator) { + add(AuthorMetadataChip("组版主", R.color.fire_warning, R.color.fire_chip_warning_background)) + } + }.take(MAX_PRIMARY_METADATA_CHIPS) +} + +internal fun secondaryMetadataParts(post: TopicPostState): List { + val metadata = post.authorMetadata + val username = cleaned(post.username) + val title = cleaned(metadata.userTitle)?.let(::humanizedUserTitle) + val statusDescription = cleaned(metadata.userStatusDescription) + val statusEmoji = cleaned(metadata.userStatusEmoji)?.let { ":$it:" } + + return buildList { + username?.let { add("@$it") } + title?.let { add(compactSecondaryLabel(it)) } + if (statusDescription != null) { + add(compactSecondaryLabel(statusDescription)) + } else { + statusEmoji?.let(::add) + } + } +} + +internal fun cleaned(value: String?): String? { + return value?.trim()?.takeIf { it.isNotEmpty() } +} + +private fun humanizedUserTitle(title: String): String { + val level = parsedTrustLevel(title) ?: return title + return trustLevelDisplayLabel(level) +} + +private fun parsedTrustLevel(value: String): Int? { + for (regex in TRUST_LEVEL_REGEXES) { + val match = regex.find(value) ?: continue + val level = match.groupValues.getOrNull(1)?.toIntOrNull() ?: continue + return level + } + return null +} + +private fun trustLevelDisplayLabel(level: Int): String { + return when (level) { + 0 -> "L0 新用户" + 1 -> "L1 基本用户" + 2 -> "L2 成员" + 3 -> "L3 活跃用户" + 4 -> "L4 领袖" + else -> "L$level" + } +} + +private fun compactSecondaryLabel(value: String): String { + return if (value.length <= MAX_SECONDARY_LABEL_LENGTH) { + value + } else { + value.take(MAX_SECONDARY_LABEL_LENGTH - 1) + "…" + } +} + +private const val MAX_PRIMARY_METADATA_CHIPS = 3 +private const val MAX_SECONDARY_LABEL_LENGTH = 16 +private val TRUST_LEVEL_REGEXES = listOf( + Regex("""(?i)trust[_\s-]*l(?:evel|v)[_\s-]*(\d+)"""), + Regex("""(?i)\btl[_\s-]*(\d+)\b"""), + Regex("""(?i)\blv\.?\s*(\d+)\b"""), + Regex("""(?i)\bl(\d+)\b"""), + Regex("""等级\s*(\d+)"""), + Regex("""(?i)level\s*(\d+)"""), +) diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Body.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Body.kt new file mode 100644 index 00000000..8341c051 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Body.kt @@ -0,0 +1,101 @@ +package com.fire.app.ui.topicdetail + +import android.view.View +import android.view.ViewGroup +import android.widget.LinearLayout +import com.fire.app.R +import com.fire.app.richtext.FireRichTextBlock +import com.fire.app.richtext.FireRenderPresentation +import com.fire.app.richtext.FireRichTextView +import com.fire.app.richtext.FireSpannableBuilder +import uniffi.fire_uniffi_types.RenderDocumentHandle + +internal fun PostViewHolder.bindPostBody( + contentId: String, + presentation: RenderDocumentHandle?, + callbacks: PostRowCallbacks, +) { + bodyContainer.removeAllViews() + bodyHasTextTarget = false + + if (presentation != null) { + val blocks = FireRenderPresentation.blocks(presentation) + blocks.forEachIndexed { index, block -> + when (block) { + is FireRichTextBlock.Text -> { + bodyHasTextTarget = addTextBlock(contentId, index, block, callbacks) || bodyHasTextTarget + } + is FireRichTextBlock.Image -> addImageBlock(index, block, callbacks) + } + } + } + + bodyContainer.visibility = if (bodyContainer.childCount == 0) View.GONE else View.VISIBLE +} + +internal fun PostViewHolder.addTextBlock( + contentId: String, + index: Int, + block: FireRichTextBlock.Text, + callbacks: PostRowCallbacks, +): Boolean { + val spannable = FireSpannableBuilder.build( + nodes = block.nodes, + context = itemView.context, + onLinkClicked = callbacks.onLinkClick, + ) + if (spannable.isBlank()) return false + val textView = FireRichTextView(itemView.context).apply { + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) + setTextColor(itemView.context.getColor(R.color.fire_text_primary)) + setTextIsSelectable(true) + setOnLongClickListener { + requestFocus() + false + } + setContent("$contentId:text:$index", spannable) + layoutParams = bodyBlockLayoutParams(index) + } + bodyContainer.addView(textView) + return true +} + +internal fun PostViewHolder.addImageBlock( + index: Int, + block: FireRichTextBlock.Image, + callbacks: PostRowCallbacks, +) { + val imageView = TopicPostImageView(itemView.context).apply { + layoutParams = bodyBlockLayoutParams(index) + bind(block.image, callbacks.onImageClick) + } + bodyContainer.addView(imageView) +} + +internal fun PostViewHolder.bodyBlockLayoutParams(index: Int): LinearLayout.LayoutParams { + return LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ).apply { + if (index > 0) topMargin = itemView.resources.displayMetrics.density.times(8).toInt() + } +} + +internal fun PostViewHolder.applyContentWidthMode(usesTitleWidthBody: Boolean) { + val leadingMargin = if (usesTitleWidthBody) 0 else POST_CONTENT_LEADING_MARGIN_DP + applyStartMargin(replyContextText, leadingMargin) + applyStartMargin(bodyFrame, leadingMargin) + applyStartMargin(pollContainer, leadingMargin) + applyStartMargin(boostContainer, leadingMargin) + applyStartMargin(actionsScroll, leadingMargin) +} + +internal fun PostViewHolder.applyStartMargin(view: View, marginDp: Int) { + val params = view.layoutParams as? ViewGroup.MarginLayoutParams ?: return + val marginPx = dp(marginDp) + if (params.marginStart == marginPx) return + params.marginStart = marginPx + view.layoutParams = params +} + +private const val POST_CONTENT_LEADING_MARGIN_DP = 46 diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Boosts.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Boosts.kt new file mode 100644 index 00000000..fc3940cc --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Boosts.kt @@ -0,0 +1,574 @@ +package com.fire.app.ui.topicdetail + +import android.animation.Animator +import android.animation.ValueAnimator +import android.content.Context +import android.graphics.drawable.GradientDrawable +import android.text.SpannableStringBuilder +import android.text.Spanned +import android.text.TextUtils +import android.text.style.ForegroundColorSpan +import android.util.AttributeSet +import android.view.View +import android.view.ViewGroup +import android.view.animation.LinearInterpolator +import android.widget.FrameLayout +import android.widget.HorizontalScrollView +import android.widget.LinearLayout +import android.widget.TextView +import com.fire.app.R +import com.fire.app.richtext.FireRenderPresentation +import com.fire.app.richtext.FireRichTextView +import com.fire.app.richtext.FireSpannableBuilder +import uniffi.fire_uniffi_topics.TopicPostBoostState +import uniffi.fire_uniffi_topics.TopicPostState + +internal fun PostViewHolder.bindBoosts(row: PostRow) { + val post = row.post + boostContainer.removeAllViews() + clearBoostBarrage() + if (post.boosts.isEmpty()) { + boostContainer.visibility = View.GONE + boostBarrageContainer.visibility = View.GONE + applyActionsTopMargin(ACTIONS_DEFAULT_TOP_MARGIN_DP) + return + } + + if (TopicDetailPostRows.usesBoostBarrage(row) && bodyHasTextTarget) { + boostContainer.visibility = View.GONE + bindBoostBarrage(post) + applyActionsTopMargin(ACTIONS_DEFAULT_TOP_MARGIN_DP) + return + } + + boostBarrageContainer.visibility = View.GONE + boostContainer.visibility = View.VISIBLE + bindManualBoostScroller(post.boosts) + applyActionsTopMargin(0) +} + +internal fun PostViewHolder.bindManualBoostScroller(boosts: List) { + val context = itemView.context + val scroller = HorizontalScrollView(context).apply { + isHorizontalScrollBarEnabled = false + isVerticalScrollBarEnabled = false + overScrollMode = View.OVER_SCROLL_IF_CONTENT_SCROLLS + clipToPadding = false + isFillViewport = true + layoutParams = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ) + } + val rowsContainer = FixedBoostManualChipLayout(context).apply { + rowCount = FIXED_BOOST_MANUAL_ROWS + rowHeightPx = dp(FIXED_BOOST_MANUAL_ROW_HEIGHT_DP) + rowSpacingPx = dp(FIXED_BOOST_MANUAL_ROW_SPACING_DP) + chipHeightPx = dp(FIXED_BOOST_MANUAL_CHIP_HEIGHT_DP) + chipSpacingPx = dp(FIXED_BOOST_MANUAL_CHIP_SPACING_DP) + minChipWidthPx = dp(FIXED_BOOST_MANUAL_MIN_CHIP_WIDTH_DP) + clipToPadding = false + layoutParams = FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.WRAP_CONTENT, + ) + } + boosts.forEach { boost -> + val boostView = boostChipView( + boost = boost, + textColor = context.getColor(R.color.fire_text_secondary), + backgroundColor = context.getColor(R.color.fire_boost_background), + heightDp = FIXED_BOOST_MANUAL_CHIP_HEIGHT_DP, + ).apply { + layoutParams = ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + dp(FIXED_BOOST_MANUAL_CHIP_HEIGHT_DP), + ) + } + rowsContainer.addView(boostView) + } + scroller.addView(rowsContainer) + boostContainer.addView(scroller) +} + +internal fun PostViewHolder.bindBoostBarrage(post: TopicPostState) { + val context = itemView.context + val visibleBoosts = post.boosts.take(TopicDetailBoostPresentation.BODY_BARRAGE_VISIBLE_LINE_LIMIT) + val signature = boostBarrageSignature(post, visibleBoosts) + boostBarrageSignature = signature + if (visibleBoosts.isEmpty() || hasPlayedBoostBarrage(signature)) { + boostBarrageContainer.visibility = View.GONE + return + } + + boostBarrageContainer.visibility = View.VISIBLE + visibleBoosts.forEach { boost -> + val boostView = boostChipView( + boost = boost, + textColor = context.getColor(R.color.fire_text_primary), + backgroundColor = context.getColor(R.color.fire_boost_barrage_background), + heightDp = BARRAGE_CHIP_HEIGHT_DP, + ).apply { + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO + layoutParams = FrameLayout.LayoutParams( + FrameLayout.LayoutParams.WRAP_CONTENT, + dp(24), + ) + } + boostBarrageContainer.addView(boostView) + } + val startRunnable = Runnable { startBoostBarrageAnimations() } + boostBarrageStartRunnable = startRunnable + boostBarrageContainer.post(startRunnable) +} + +internal fun PostViewHolder.boostBarrageSignature( + post: TopicPostState, + boosts: List, +): String { + return buildString { + append(post.id) + boosts.forEach { boost -> + append('|') + append(boost.id) + append(':') + append(boost.displayText.hashCode()) + append(':') + append(boost.presentation?.checksum()?.toInt() ?: 0) + } + } +} + +internal fun PostViewHolder.boostChipView( + boost: TopicPostBoostState, + textColor: Int, + backgroundColor: Int, + heightDp: Int, +): FireRichTextView { + return FireRichTextView(itemView.context).apply { + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) + setTextColor(textColor) + maxLines = 1 + ellipsize = TextUtils.TruncateAt.END + includeFontPadding = false + gravity = android.view.Gravity.CENTER_VERTICAL + setPadding(dp(10), 0, dp(10), 0) + background = GradientDrawable().apply { + cornerRadius = dp(heightDp / 2).toFloat() + setColor(backgroundColor) + } + val contentId = listOf( + boost.id, + boost.displayText.hashCode(), + boost.presentation?.checksum()?.toInt() ?: 0, + ).joinToString(separator = ":") + setContent( + "boost:$contentId", + buildBoostChipText(boost, textColor), + ) + } +} + +internal fun PostViewHolder.buildBoostChipText(boost: TopicPostBoostState, textColor: Int): Spanned { + val content = boost.presentation?.let(FireRenderPresentation::content) + val richText = content + ?.nodes + ?.takeIf { it.isNotEmpty() } + ?.let { nodes -> + trimSpannable( + FireSpannableBuilder.build( + nodes = nodes, + context = itemView.context, + onLinkClicked = null, + ), + ) + } + ?.takeIf { it.isNotBlank() } + val fallbackText = cleaned(boost.displayText) + val builder = when { + richText != null -> stripLeadingBoostAttribution(richText, boost) + fallbackText != null -> SpannableStringBuilder(stripLeadingBoostAttribution(fallbackText, boost)) + else -> SpannableStringBuilder() + } + builder.setSpan(ForegroundColorSpan(textColor), 0, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + return builder +} + +internal fun PostViewHolder.stripLeadingBoostAttribution( + value: SpannableStringBuilder, + boost: TopicPostBoostState, +): SpannableStringBuilder { + trimSpannable(value) + val plain = value.toString() + for (candidate in boostAttributionCandidates(boost)) { + val prefix = "$candidate:" + if (plain.startsWith(prefix, ignoreCase = true)) { + value.delete(0, prefix.length) + return trimSpannable(value) + } + } + val generic = BOOST_ATTRIBUTION_PREFIX_REGEX.find(plain)?.value + if (generic != null) { + value.delete(0, generic.length) + return trimSpannable(value) + } + return value +} + +internal fun PostViewHolder.stripLeadingBoostAttribution(value: String, boost: TopicPostBoostState): String { + val trimmed = value.trim() + for (candidate in boostAttributionCandidates(boost)) { + val prefix = "$candidate:" + if (trimmed.startsWith(prefix, ignoreCase = true)) { + return trimmed.drop(prefix.length).trim() + } + } + return BOOST_ATTRIBUTION_PREFIX_REGEX.replace(trimmed, "").trim() +} + +internal fun PostViewHolder.boostAttributionCandidates(boost: TopicPostBoostState): List { + return listOfNotNull( + cleaned(boost.user.username)?.let { "@$it" }, + cleaned(boost.user.username), + cleaned(boost.user.name), + ).distinctBy { it.lowercase() } +} + +internal fun PostViewHolder.trimSpannable(value: SpannableStringBuilder): SpannableStringBuilder { + while (value.isNotEmpty() && value.first().isWhitespace()) { + value.delete(0, 1) + } + while (value.isNotEmpty() && value.last().isWhitespace()) { + value.delete(value.length - 1, value.length) + } + return value +} + +internal fun PostViewHolder.clearBoostBarrage() { + boostBarrageStartRunnable?.let(boostBarrageContainer::removeCallbacks) + boostBarrageStartRunnable = null + boostBarrageAnimators.forEach { it.cancel() } + boostBarrageAnimators.clear() + boostBarrageExpectedCompletions = 0 + boostBarrageCompletedCount = 0 + for (index in 0 until boostBarrageContainer.childCount) { + boostBarrageContainer.getChildAt(index).animate().cancel() + } + boostBarrageContainer.removeAllViews() +} + +internal fun PostViewHolder.startBoostBarrageAnimations() { + boostBarrageStartRunnable = null + val width = boostBarrageContainer.width + val height = boostBarrageContainer.height + if (width <= 0 || height <= 0) { + scheduleBoostBarrageAfterLayout() + return + } + + val childCount = boostBarrageContainer.childCount + boostBarrageAnimators.clear() + boostBarrageExpectedCompletions = 0 + boostBarrageCompletedCount = 0 + val laneHeight = dp(BARRAGE_CHIP_HEIGHT_DP) + val laneGap = dp(BARRAGE_MIN_LANE_GAP_DP) + val availableLaneCount = ((height + laneGap) / (laneHeight + laneGap)) + .coerceAtLeast(1) + val laneCount = minOf( + childCount, + TopicDetailBoostPresentation.BODY_BARRAGE_MAX_LANES, + availableLaneCount, + ).coerceAtLeast(1) + val verticalStride = if (laneCount <= 1) { + 0 + } else { + ((height - laneHeight).coerceAtLeast(0) / (laneCount - 1)) + } + val maxChipWidth = (width * 0.72f).toInt().coerceAtLeast(1) + val animationsEnabled = ValueAnimator.areAnimatorsEnabled() + + for (index in 0 until childCount) { + val child = boostBarrageContainer.getChildAt(index) as? TextView ?: continue + child.animate().cancel() + child.measure( + View.MeasureSpec.makeMeasureSpec(maxChipWidth, View.MeasureSpec.AT_MOST), + View.MeasureSpec.makeMeasureSpec(dp(BARRAGE_CHIP_HEIGHT_DP), View.MeasureSpec.EXACTLY), + ) + val chipWidth = child.measuredWidth.coerceIn(dp(48), maxChipWidth) + val lane = index % laneCount + val y = (lane * verticalStride).coerceAtMost((height - laneHeight).coerceAtLeast(0)) + val params = child.layoutParams as FrameLayout.LayoutParams + params.width = chipWidth + params.height = laneHeight + child.layoutParams = params + child.translationY = y.toFloat() + child.alpha = BARRAGE_START_ALPHA + + if (!animationsEnabled || !shouldRunBoostAnimations()) { + val slotProgress = (index + 1).toFloat() / (childCount + 1).toFloat() + child.translationX = ((width - chipWidth).coerceAtLeast(0) * slotProgress) + continue + } + + val round = index / laneCount + val laneStagger = lane * BARRAGE_LANE_STAGGER_MS + val roundStagger = round * BARRAGE_ROUND_STAGGER_MS + val startX = width.toFloat() + lane * dp(18) + child.translationX = startX + val endX = -chipWidth.toFloat() - dp(16) + val animator = ValueAnimator.ofFloat(startX, endX).apply { + duration = BARRAGE_BASE_DURATION_MS + lane * BARRAGE_LANE_DURATION_STEP_MS + startDelay = laneStagger + roundStagger + interpolator = LinearInterpolator() + addUpdateListener { animation -> + child.translationX = animation.animatedValue as Float + child.alpha = BARRAGE_START_ALPHA - animation.animatedFraction * BARRAGE_ALPHA_DELTA + } + addListener(object : Animator.AnimatorListener { + private var canceled = false + + override fun onAnimationStart(animation: Animator) = Unit + + override fun onAnimationEnd(animation: Animator) { + if (!canceled) { + onBoostBarrageAnimatorFinished(animation) + } + } + + override fun onAnimationCancel(animation: Animator) { + canceled = true + } + + override fun onAnimationRepeat(animation: Animator) = Unit + }) + } + boostBarrageAnimators.add(animator) + boostBarrageExpectedCompletions += 1 + animator.start() + } +} + +internal fun PostViewHolder.onBoostBarrageAnimatorFinished(animation: Animator) { + (animation as? ValueAnimator)?.let { boostBarrageAnimators.remove(it) } + boostBarrageCompletedCount += 1 + if (boostBarrageExpectedCompletions <= 0 || + boostBarrageCompletedCount < boostBarrageExpectedCompletions + ) { + return + } + + val completedSignature = boostBarrageSignature ?: return + rememberPlayedBoostBarrage(completedSignature) + boostBarrageContainer.post { + if (boostBarrageSignature != completedSignature) return@post + boostBarrageStartRunnable?.let(boostBarrageContainer::removeCallbacks) + boostBarrageStartRunnable = null + boostBarrageAnimators.clear() + boostBarrageExpectedCompletions = 0 + boostBarrageCompletedCount = 0 + boostBarrageContainer.removeAllViews() + boostBarrageContainer.visibility = View.GONE + } +} + +internal fun PostViewHolder.scheduleBoostBarrageAfterLayout() { + if (boostBarrageStartRunnable != null || boostBarrageContainer.childCount == 0) return + val startRunnable = Runnable { startBoostBarrageAnimations() } + boostBarrageStartRunnable = startRunnable + boostBarrageContainer.postDelayed(startRunnable, BARRAGE_LAYOUT_RETRY_MS) +} + +internal fun PostViewHolder.updateBoostAnimationState() { + if (shouldRunBoostAnimations()) { + if (boostBarrageContainer.visibility == View.VISIBLE) { + if (!resumePausedAnimators(boostBarrageAnimators) && boostBarrageAnimators.isEmpty()) { + scheduleBoostBarrageAfterLayout() + } + } + } else { + pauseBoostAnimations() + } +} + +internal fun PostViewHolder.pauseBoostAnimations() { + boostBarrageStartRunnable?.let(boostBarrageContainer::removeCallbacks) + boostBarrageStartRunnable = null + pauseAnimators(boostBarrageAnimators) +} + +internal fun PostViewHolder.stopBoostAnimations() { + boostBarrageStartRunnable?.let(boostBarrageContainer::removeCallbacks) + boostBarrageStartRunnable = null + boostBarrageAnimators.forEach { it.cancel() } + boostBarrageAnimators.clear() +} + +internal fun PostViewHolder.pauseAnimators(animators: List) { + animators.forEach { animator -> + if (animator.isStarted && !animator.isPaused) { + animator.pause() + } + } +} + +internal fun PostViewHolder.resumePausedAnimators(animators: List): Boolean { + if (animators.isEmpty()) return false + var resumed = false + animators.forEach { animator -> + if (animator.isPaused) { + animator.resume() + resumed = true + } + } + return resumed || animators.any { it.isStarted } +} + +internal fun PostViewHolder.shouldRunBoostAnimations(): Boolean { + return isAttachedToWindow && boostAnimationsEnabled +} + +private fun hasPlayedBoostBarrage(signature: String): Boolean { + return playedBoostBarrageSignatures.contains(signature) +} + +private fun rememberPlayedBoostBarrage(signature: String) { + playedBoostBarrageSignatures.add(signature) + while (playedBoostBarrageSignatures.size > BARRAGE_PLAYED_CACHE_LIMIT) { + val iterator = playedBoostBarrageSignatures.iterator() + if (!iterator.hasNext()) return + iterator.next() + iterator.remove() + } +} + +private const val BARRAGE_CHIP_HEIGHT_DP = 24 +private const val BARRAGE_MIN_LANE_GAP_DP = 4 +private const val BARRAGE_BASE_DURATION_MS = 12_500L +private const val BARRAGE_LANE_DURATION_STEP_MS = 1_400L +private const val BARRAGE_LANE_STAGGER_MS = 1_500L +private const val BARRAGE_ROUND_STAGGER_MS = 4_600L +private const val BARRAGE_START_ALPHA = 0.82f +private const val BARRAGE_ALPHA_DELTA = 0.16f +private const val BARRAGE_LAYOUT_RETRY_MS = 48L +private const val BARRAGE_PLAYED_CACHE_LIMIT = 256 +private const val FIXED_BOOST_MANUAL_ROWS = 2 +private const val FIXED_BOOST_MANUAL_ROW_HEIGHT_DP = 30 +private const val FIXED_BOOST_MANUAL_ROW_SPACING_DP = 4 +private const val FIXED_BOOST_MANUAL_CHIP_HEIGHT_DP = 26 +private const val FIXED_BOOST_MANUAL_CHIP_SPACING_DP = 8 +private const val FIXED_BOOST_MANUAL_MIN_CHIP_WIDTH_DP = 48 +private const val ACTIONS_DEFAULT_TOP_MARGIN_DP = 8 +private val playedBoostBarrageSignatures = LinkedHashSet() +private val BOOST_ATTRIBUTION_PREFIX_REGEX = Regex("""^@?[^\s::]{1,40}[::]\s*""") + +private class FixedBoostManualChipLayout @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : ViewGroup(context, attrs) { + + var rowCount: Int = 2 + var rowHeightPx: Int = 0 + var rowSpacingPx: Int = 0 + var chipHeightPx: Int = 0 + var chipSpacingPx: Int = 0 + var minChipWidthPx: Int = 0 + + private var measuredChipWidths: IntArray = IntArray(0) + private var layoutResult = TopicDetailManualBoostLayoutResult( + placements = emptyList(), + contentWidth = 0, + usedRowCount = 0, + ) + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val viewportWidth = resolvedViewportWidth(widthMeasureSpec) + val maxChipWidth = (viewportWidth * MAX_CHIP_WIDTH_RATIO).toInt().coerceAtLeast(1) + val resolvedChipHeight = chipHeightPx.coerceAtLeast(1) + val childHeightSpec = MeasureSpec.makeMeasureSpec(resolvedChipHeight, MeasureSpec.EXACTLY) + val childWidthSpec = MeasureSpec.makeMeasureSpec(maxChipWidth, MeasureSpec.AT_MOST) + val widths = IntArray(childCount) + + for (index in 0 until childCount) { + val child = getChildAt(index) + if (child.visibility == GONE) { + widths[index] = 0 + continue + } + child.measure(childWidthSpec, childHeightSpec) + widths[index] = child.measuredWidth.coerceIn(minChipWidthPx.coerceAtLeast(1), maxChipWidth) + child.measure( + MeasureSpec.makeMeasureSpec(widths[index], MeasureSpec.EXACTLY), + childHeightSpec, + ) + } + + measuredChipWidths = widths + layoutResult = TopicDetailManualBoostLayout.placements( + chipWidths = widths.filter { it > 0 }, + pageWidth = viewportWidth, + rowCount = rowCount, + chipSpacing = chipSpacingPx, + ) + + val resolvedRowCount = layoutResult.usedRowCount.coerceIn(0, rowCount.coerceAtLeast(1)) + val resolvedRowHeight = rowHeightPx.coerceAtLeast(resolvedChipHeight) + val measuredHeight = if (resolvedRowCount == 0) { + 0 + } else { + resolvedRowCount * resolvedRowHeight + + (resolvedRowCount - 1) * rowSpacingPx + } + setMeasuredDimension( + layoutResult.contentWidth.coerceAtLeast(viewportWidth), + resolveSize(measuredHeight, heightMeasureSpec), + ) + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + val resolvedRowHeight = rowHeightPx.coerceAtLeast(chipHeightPx.coerceAtLeast(1)) + var placementIndex = 0 + for (index in 0 until childCount) { + val child = getChildAt(index) + if (child.visibility == GONE) continue + val placement = layoutResult.placements.getOrNull(placementIndex) ?: break + val width = measuredChipWidths.getOrNull(index)?.takeIf { it > 0 } ?: child.measuredWidth + val childTop = placement.rowIndex * (resolvedRowHeight + rowSpacingPx) + + ((resolvedRowHeight - child.measuredHeight).coerceAtLeast(0) / 2) + child.layout( + placement.x, + childTop, + placement.x + width, + childTop + child.measuredHeight, + ) + placementIndex += 1 + } + } + + override fun generateDefaultLayoutParams(): LayoutParams { + return LayoutParams(LayoutParams.WRAP_CONTENT, chipHeightPx.coerceAtLeast(1)) + } + + override fun generateLayoutParams(attrs: AttributeSet): LayoutParams { + return LayoutParams(context, attrs) + } + + override fun generateLayoutParams(params: LayoutParams): LayoutParams { + return LayoutParams(params) + } + + override fun checkLayoutParams(params: LayoutParams): Boolean { + return true + } + + private fun resolvedViewportWidth(widthMeasureSpec: Int): Int { + val specWidth = MeasureSpec.getSize(widthMeasureSpec) + if (specWidth > 0) return specWidth + val parentWidth = (parent as? View)?.width ?: 0 + if (parentWidth > 0) return parentWidth + return resources.displayMetrics.widthPixels.coerceAtLeast(1) + } + + private companion object { + private const val MAX_CHIP_WIDTH_RATIO = 0.72f + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Polls.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Polls.kt new file mode 100644 index 00000000..250f2f04 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder+Polls.kt @@ -0,0 +1,154 @@ +package com.fire.app.ui.topicdetail + +import android.view.View +import android.widget.CheckBox +import android.widget.LinearLayout +import android.widget.TextView +import android.widget.Toast +import com.fire.app.R +import uniffi.fire_uniffi_topics.PollState +import uniffi.fire_uniffi_topics.TopicPostState + +internal fun PostViewHolder.bindPolls(post: TopicPostState, callbacks: PostRowCallbacks) { + pollContainer.removeAllViews() + if (post.polls.isEmpty()) { + pollContainer.visibility = View.GONE + return + } + + pollContainer.visibility = View.VISIBLE + post.polls.forEachIndexed { index, poll -> + if (index > 0) { + pollContainer.addView(sectionDivider()) + } + pollContainer.addView(pollTitleView(poll)) + pollContainer.addView(pollOptionsView(post, poll, callbacks)) + } +} + +internal fun PostViewHolder.pollTitleView(poll: PollState): TextView { + val context = itemView.context + val labels = buildList { + add(context.getString(R.string.topic_detail_poll_title)) + if (poll.kind.equals("multiple", ignoreCase = true)) { + add(context.getString(R.string.topic_detail_poll_multiple)) + } + if (poll.status.equals("closed", ignoreCase = true)) { + add(context.getString(R.string.topic_detail_poll_closed)) + } + add(context.getString(R.string.topic_detail_poll_voters_count, poll.voters.toString())) + } + return TextView(context).apply { + text = labels.joinToString(" · ") + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) + setTextColor(context.getColor(R.color.fire_text_secondary)) + } +} + +internal fun PostViewHolder.pollOptionsView( + post: TopicPostState, + poll: PollState, + callbacks: PostRowCallbacks, +): LinearLayout { + val context = itemView.context + val selected = poll.userVotes.toMutableSet() + val isMultiple = poll.kind.equals("multiple", ignoreCase = true) + val isClosed = poll.status.equals("closed", ignoreCase = true) + val group = LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + layoutParams = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ) + } + val optionChecks = mutableListOf() + + for (option in poll.options) { + val checkBox = CheckBox(context).apply { + text = context.getString( + R.string.topic_detail_poll_option_with_votes, + option.plainText.trim().ifBlank { option.id }, + option.votes.toString(), + ) + isChecked = selected.contains(option.id) + isEnabled = !isClosed + setTextColor(context.getColor(R.color.fire_text_primary)) + setOnCheckedChangeListener { _, checked -> + if (checked) { + if (!isMultiple) { + selected.clear() + optionChecks.filter { it !== this }.forEach { it.isChecked = false } + } + selected.add(option.id) + } else { + selected.remove(option.id) + } + } + } + optionChecks.add(checkBox) + group.addView(checkBox) + } + + if (!isClosed) { + group.addView(pollActionsView(post, poll, selected, callbacks)) + } + return group +} + +internal fun PostViewHolder.pollActionsView( + post: TopicPostState, + poll: PollState, + selected: MutableSet, + callbacks: PostRowCallbacks, +): LinearLayout { + val context = itemView.context + return LinearLayout(context).apply { + orientation = LinearLayout.HORIZONTAL + gravity = android.view.Gravity.CENTER_VERTICAL + val submit = TextView(context).apply { + text = context.getString(R.string.topic_detail_poll_submit) + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) + setTextColor(context.getColor(R.color.fire_accent)) + setPadding(0, 8, 18, 8) + setOnClickListener { + val selectedOptions = selected.toList() + if (selectedOptions.isEmpty()) { + Toast.makeText( + context, + R.string.topic_detail_poll_select_required, + Toast.LENGTH_SHORT, + ).show() + } else { + callbacks.onVotePoll(post, poll, selectedOptions) + } + } + } + addView(submit) + + if (poll.userVotes.isNotEmpty()) { + val unvote = TextView(context).apply { + text = context.getString(R.string.topic_detail_poll_unvote) + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) + setTextColor(context.getColor(R.color.fire_text_secondary)) + setPadding(0, 8, 0, 8) + setOnClickListener { + callbacks.onUnvotePoll(post, poll) + } + } + addView(unvote) + } + } +} + +internal fun PostViewHolder.sectionDivider(): View { + return View(itemView.context).apply { + setBackgroundColor(itemView.context.getColor(R.color.fire_divider)) + layoutParams = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + 1, + ).apply { + topMargin = 10 + bottomMargin = 10 + } + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt index 2d8326bb..19d13910 100644 --- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt @@ -1,57 +1,38 @@ package com.fire.app.ui.topicdetail -import android.animation.Animator import android.animation.ValueAnimator -import android.content.Context -import android.content.res.ColorStateList import android.graphics.drawable.GradientDrawable -import android.text.SpannableStringBuilder -import android.text.Spanned -import android.text.TextUtils -import android.util.AttributeSet -import android.text.style.ForegroundColorSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.view.animation.LinearInterpolator -import android.widget.CheckBox import android.widget.FrameLayout import android.widget.HorizontalScrollView import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView -import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.fire.app.R import com.fire.app.TopicPresentation import com.fire.app.core.image.FireAvatarUrls import com.fire.app.core.image.FireImageLoader -import com.fire.app.richtext.FireRichTextBlock -import com.fire.app.richtext.FireRenderPresentation -import com.fire.app.richtext.FireRichTextView -import com.fire.app.richtext.FireSpannableBuilder -import uniffi.fire_uniffi_topics.PollState -import uniffi.fire_uniffi_topics.TopicPostBoostState -import uniffi.fire_uniffi_topics.TopicPostState -import uniffi.fire_uniffi_types.RenderDocumentHandle class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val avatar: ImageView = itemView.findViewById(R.id.post_avatar) private val usernameText: TextView = itemView.findViewById(R.id.post_username) - private val authorChips: LinearLayout = itemView.findViewById(R.id.post_author_chips) + internal val authorChips: LinearLayout = itemView.findViewById(R.id.post_author_chips) private val authorMetadataText: TextView = itemView.findViewById(R.id.post_author_metadata) private val metaText: TextView = itemView.findViewById(R.id.post_meta) private val floorText: TextView = itemView.findViewById(R.id.post_floor) - private val replyContextText: TextView = itemView.findViewById(R.id.post_reply_context) - private val bodyFrame: FrameLayout = itemView.findViewById(R.id.post_body_frame) - private val bodyContainer: LinearLayout = itemView.findViewById(R.id.post_body_container) - private val pollContainer: LinearLayout = itemView.findViewById(R.id.post_poll_container) - private val boostContainer: LinearLayout = itemView.findViewById(R.id.post_boost_container) - private val boostBarrageContainer: FrameLayout = itemView.findViewById(R.id.post_boost_barrage_container) - private val actionsScroll: HorizontalScrollView = itemView.findViewById(R.id.post_actions_scroll) - private val moreRepliesAction: TextView = itemView.findViewById(R.id.action_more_replies) - private val likeAction: TextView = itemView.findViewById(R.id.action_like) + internal val replyContextText: TextView = itemView.findViewById(R.id.post_reply_context) + internal val bodyFrame: FrameLayout = itemView.findViewById(R.id.post_body_frame) + internal val bodyContainer: LinearLayout = itemView.findViewById(R.id.post_body_container) + internal val pollContainer: LinearLayout = itemView.findViewById(R.id.post_poll_container) + internal val boostContainer: LinearLayout = itemView.findViewById(R.id.post_boost_container) + internal val boostBarrageContainer: FrameLayout = itemView.findViewById(R.id.post_boost_barrage_container) + internal val actionsScroll: HorizontalScrollView = itemView.findViewById(R.id.post_actions_scroll) + internal val moreRepliesAction: TextView = itemView.findViewById(R.id.action_more_replies) + internal val likeAction: TextView = itemView.findViewById(R.id.action_like) private val reactAction: TextView = itemView.findViewById(R.id.action_react) private val replyAction: TextView = itemView.findViewById(R.id.action_reply) private val quoteAction: TextView = itemView.findViewById(R.id.action_quote) @@ -60,14 +41,14 @@ class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val editAction: TextView = itemView.findViewById(R.id.action_edit) private val deleteRecoverAction: TextView = itemView.findViewById(R.id.action_delete_recover) private val flagAction: TextView = itemView.findViewById(R.id.action_flag) - private var boostBarrageStartRunnable: Runnable? = null - private val boostBarrageAnimators = mutableListOf() - private var boostBarrageSignature: String? = null - private var boostBarrageExpectedCompletions = 0 - private var boostBarrageCompletedCount = 0 - private var bodyHasTextTarget: Boolean = false - private var boostAnimationsEnabled = true - private var isAttachedToWindow = false + internal var boostBarrageStartRunnable: Runnable? = null + internal val boostBarrageAnimators = mutableListOf() + internal var boostBarrageSignature: String? = null + internal var boostBarrageExpectedCompletions = 0 + internal var boostBarrageCompletedCount = 0 + internal var bodyHasTextTarget: Boolean = false + internal var boostAnimationsEnabled = true + internal var isAttachedToWindow = false fun bind( row: PostRow, @@ -319,990 +300,17 @@ class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { } } - private fun configureIconAction( - view: TextView, - iconRes: Int, - contentDescription: String, - active: Boolean = false, - enabled: Boolean = true, - onClick: () -> Unit, - ) { - view.visibility = View.VISIBLE - view.text = null - view.contentDescription = contentDescription - view.isEnabled = enabled - view.alpha = if (enabled) 1f else 0.45f - view.gravity = android.view.Gravity.CENTER - view.includeFontPadding = false - view.setCompoundDrawablesRelativeWithIntrinsicBounds(iconRes, 0, 0, 0) - view.compoundDrawableTintList = ColorStateList.valueOf( - itemView.context.getColor(if (active) R.color.fire_accent else R.color.fire_text_secondary), - ) - view.setTextColor(itemView.context.getColor(if (active) R.color.fire_accent else R.color.fire_text_secondary)) - view.setOnClickListener(if (enabled) View.OnClickListener { onClick() } else null) - } - - private fun configureHiddenAction(view: TextView) { - view.visibility = View.GONE - view.text = null - view.contentDescription = null - view.compoundDrawableTintList = null - view.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0) - view.setOnClickListener(null) - view.alpha = 1f - view.isEnabled = true - } - - private fun bindPostBody( - contentId: String, - presentation: RenderDocumentHandle?, - callbacks: PostRowCallbacks, - ) { - bodyContainer.removeAllViews() - bodyHasTextTarget = false - - if (presentation != null) { - val blocks = FireRenderPresentation.blocks(presentation) - blocks.forEachIndexed { index, block -> - when (block) { - is FireRichTextBlock.Text -> { - bodyHasTextTarget = addTextBlock(contentId, index, block, callbacks) || bodyHasTextTarget - } - is FireRichTextBlock.Image -> addImageBlock(index, block, callbacks) - } - } - } - - bodyContainer.visibility = if (bodyContainer.childCount == 0) View.GONE else View.VISIBLE - } - - private fun addTextBlock( - contentId: String, - index: Int, - block: FireRichTextBlock.Text, - callbacks: PostRowCallbacks, - ): Boolean { - val spannable = FireSpannableBuilder.build( - nodes = block.nodes, - context = itemView.context, - onLinkClicked = callbacks.onLinkClick, - ) - if (spannable.isBlank()) return false - val textView = FireRichTextView(itemView.context).apply { - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) - setTextColor(itemView.context.getColor(R.color.fire_text_primary)) - setTextIsSelectable(true) - setOnLongClickListener { - requestFocus() - false - } - setContent("$contentId:text:$index", spannable) - layoutParams = bodyBlockLayoutParams(index) - } - bodyContainer.addView(textView) - return true - } - - private fun addImageBlock( - index: Int, - block: FireRichTextBlock.Image, - callbacks: PostRowCallbacks, - ) { - val imageView = TopicPostImageView(itemView.context).apply { - layoutParams = bodyBlockLayoutParams(index) - bind(block.image, callbacks.onImageClick) - } - bodyContainer.addView(imageView) - } - - private fun bodyBlockLayoutParams(index: Int): LinearLayout.LayoutParams { - return LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - LinearLayout.LayoutParams.WRAP_CONTENT, - ).apply { - if (index > 0) topMargin = itemView.resources.displayMetrics.density.times(8).toInt() - } - } - - private fun bindPolls(post: TopicPostState, callbacks: PostRowCallbacks) { - pollContainer.removeAllViews() - if (post.polls.isEmpty()) { - pollContainer.visibility = View.GONE - return - } - - pollContainer.visibility = View.VISIBLE - post.polls.forEachIndexed { index, poll -> - if (index > 0) { - pollContainer.addView(sectionDivider()) - } - pollContainer.addView(pollTitleView(poll)) - pollContainer.addView(pollOptionsView(post, poll, callbacks)) - } - } - - private fun bindBoosts(row: PostRow) { - val post = row.post - boostContainer.removeAllViews() - clearBoostBarrage() - if (post.boosts.isEmpty()) { - boostContainer.visibility = View.GONE - boostBarrageContainer.visibility = View.GONE - applyActionsTopMargin(ACTIONS_DEFAULT_TOP_MARGIN_DP) - return - } - - if (TopicDetailPostRows.usesBoostBarrage(row) && bodyHasTextTarget) { - boostContainer.visibility = View.GONE - bindBoostBarrage(post) - applyActionsTopMargin(ACTIONS_DEFAULT_TOP_MARGIN_DP) - return - } - - boostBarrageContainer.visibility = View.GONE - boostContainer.visibility = View.VISIBLE - bindManualBoostScroller(post.boosts) - applyActionsTopMargin(0) - } - - private fun bindManualBoostScroller(boosts: List) { - val context = itemView.context - val scroller = HorizontalScrollView(context).apply { - isHorizontalScrollBarEnabled = false - isVerticalScrollBarEnabled = false - overScrollMode = View.OVER_SCROLL_IF_CONTENT_SCROLLS - clipToPadding = false - isFillViewport = true - layoutParams = LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - LinearLayout.LayoutParams.WRAP_CONTENT, - ) - } - val rowsContainer = FixedBoostManualChipLayout(context).apply { - rowCount = FIXED_BOOST_MANUAL_ROWS - rowHeightPx = dp(FIXED_BOOST_MANUAL_ROW_HEIGHT_DP) - rowSpacingPx = dp(FIXED_BOOST_MANUAL_ROW_SPACING_DP) - chipHeightPx = dp(FIXED_BOOST_MANUAL_CHIP_HEIGHT_DP) - chipSpacingPx = dp(FIXED_BOOST_MANUAL_CHIP_SPACING_DP) - minChipWidthPx = dp(FIXED_BOOST_MANUAL_MIN_CHIP_WIDTH_DP) - clipToPadding = false - layoutParams = FrameLayout.LayoutParams( - FrameLayout.LayoutParams.MATCH_PARENT, - FrameLayout.LayoutParams.WRAP_CONTENT, - ) - } - boosts.forEach { boost -> - val boostView = boostChipView( - boost = boost, - textColor = context.getColor(R.color.fire_text_secondary), - backgroundColor = context.getColor(R.color.fire_boost_background), - heightDp = FIXED_BOOST_MANUAL_CHIP_HEIGHT_DP, - ).apply { - layoutParams = ViewGroup.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, - dp(FIXED_BOOST_MANUAL_CHIP_HEIGHT_DP), - ) - } - rowsContainer.addView(boostView) - } - scroller.addView(rowsContainer) - boostContainer.addView(scroller) - } - - private fun bindBoostBarrage(post: TopicPostState) { - val context = itemView.context - val visibleBoosts = post.boosts.take(TopicDetailBoostPresentation.BODY_BARRAGE_VISIBLE_LINE_LIMIT) - val signature = boostBarrageSignature(post, visibleBoosts) - boostBarrageSignature = signature - if (visibleBoosts.isEmpty() || hasPlayedBoostBarrage(signature)) { - boostBarrageContainer.visibility = View.GONE - return - } - - boostBarrageContainer.visibility = View.VISIBLE - visibleBoosts.forEach { boost -> - val boostView = boostChipView( - boost = boost, - textColor = context.getColor(R.color.fire_text_primary), - backgroundColor = context.getColor(R.color.fire_boost_barrage_background), - heightDp = BARRAGE_CHIP_HEIGHT_DP, - ).apply { - importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO - layoutParams = FrameLayout.LayoutParams( - FrameLayout.LayoutParams.WRAP_CONTENT, - dp(24), - ) - } - boostBarrageContainer.addView(boostView) - } - val startRunnable = Runnable { startBoostBarrageAnimations() } - boostBarrageStartRunnable = startRunnable - boostBarrageContainer.post(startRunnable) - } - - private fun boostBarrageSignature( - post: TopicPostState, - boosts: List, - ): String { - return buildString { - append(post.id) - boosts.forEach { boost -> - append('|') - append(boost.id) - append(':') - append(boost.displayText.hashCode()) - append(':') - append(boost.presentation?.checksum()?.toInt() ?: 0) - } - } - } - - private fun boostChipView( - boost: TopicPostBoostState, - textColor: Int, - backgroundColor: Int, - heightDp: Int, - ): FireRichTextView { - return FireRichTextView(itemView.context).apply { - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) - setTextColor(textColor) - maxLines = 1 - ellipsize = TextUtils.TruncateAt.END - includeFontPadding = false - gravity = android.view.Gravity.CENTER_VERTICAL - setPadding(dp(10), 0, dp(10), 0) - background = GradientDrawable().apply { - cornerRadius = dp(heightDp / 2).toFloat() - setColor(backgroundColor) - } - val contentId = listOf( - boost.id, - boost.displayText.hashCode(), - boost.presentation?.checksum()?.toInt() ?: 0, - ).joinToString(separator = ":") - setContent( - "boost:$contentId", - buildBoostChipText(boost, textColor), - ) - } - } - - private fun buildBoostChipText(boost: TopicPostBoostState, textColor: Int): Spanned { - val content = boost.presentation?.let(FireRenderPresentation::content) - val richText = content - ?.nodes - ?.takeIf { it.isNotEmpty() } - ?.let { nodes -> - trimSpannable( - FireSpannableBuilder.build( - nodes = nodes, - context = itemView.context, - onLinkClicked = null, - ), - ) - } - ?.takeIf { it.isNotBlank() } - val fallbackText = cleaned(boost.displayText) - val builder = when { - richText != null -> stripLeadingBoostAttribution(richText, boost) - fallbackText != null -> SpannableStringBuilder(stripLeadingBoostAttribution(fallbackText, boost)) - else -> SpannableStringBuilder() - } - builder.setSpan(ForegroundColorSpan(textColor), 0, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) - return builder - } - - private fun stripLeadingBoostAttribution( - value: SpannableStringBuilder, - boost: TopicPostBoostState, - ): SpannableStringBuilder { - trimSpannable(value) - val plain = value.toString() - for (candidate in boostAttributionCandidates(boost)) { - val prefix = "$candidate:" - if (plain.startsWith(prefix, ignoreCase = true)) { - value.delete(0, prefix.length) - return trimSpannable(value) - } - } - val generic = BOOST_ATTRIBUTION_PREFIX_REGEX.find(plain)?.value - if (generic != null) { - value.delete(0, generic.length) - return trimSpannable(value) - } - return value - } - - private fun stripLeadingBoostAttribution(value: String, boost: TopicPostBoostState): String { - val trimmed = value.trim() - for (candidate in boostAttributionCandidates(boost)) { - val prefix = "$candidate:" - if (trimmed.startsWith(prefix, ignoreCase = true)) { - return trimmed.drop(prefix.length).trim() - } - } - return BOOST_ATTRIBUTION_PREFIX_REGEX.replace(trimmed, "").trim() - } - - private fun boostAttributionCandidates(boost: TopicPostBoostState): List { - return listOfNotNull( - cleaned(boost.user.username)?.let { "@$it" }, - cleaned(boost.user.username), - cleaned(boost.user.name), - ).distinctBy { it.lowercase() } - } - - private fun trimSpannable(value: SpannableStringBuilder): SpannableStringBuilder { - while (value.isNotEmpty() && value.first().isWhitespace()) { - value.delete(0, 1) - } - while (value.isNotEmpty() && value.last().isWhitespace()) { - value.delete(value.length - 1, value.length) - } - return value - } - - private fun bindMoreRepliesAction(row: PostRow, callbacks: PostRowCallbacks) { - val count = row.hiddenReplyCount - if (count == 0u) { - moreRepliesAction.visibility = View.GONE - moreRepliesAction.setOnClickListener(null) - applyActionStartMargin(likeAction, 0) - return - } - - moreRepliesAction.visibility = View.VISIBLE - moreRepliesAction.text = itemView.context.getString( - R.string.topic_detail_load_more_replies_count, - count.toString(), - ) - moreRepliesAction.setOnClickListener { callbacks.onMoreRepliesClick(row.post) } - applyActionStartMargin(likeAction, 16) - } - - private fun clearBoostBarrage() { - boostBarrageStartRunnable?.let(boostBarrageContainer::removeCallbacks) - boostBarrageStartRunnable = null - boostBarrageAnimators.forEach { it.cancel() } - boostBarrageAnimators.clear() - boostBarrageExpectedCompletions = 0 - boostBarrageCompletedCount = 0 - for (index in 0 until boostBarrageContainer.childCount) { - boostBarrageContainer.getChildAt(index).animate().cancel() - } - boostBarrageContainer.removeAllViews() - } - - private fun startBoostBarrageAnimations() { - boostBarrageStartRunnable = null - val width = boostBarrageContainer.width - val height = boostBarrageContainer.height - if (width <= 0 || height <= 0) { - scheduleBoostBarrageAfterLayout() - return - } - - val childCount = boostBarrageContainer.childCount - boostBarrageAnimators.clear() - boostBarrageExpectedCompletions = 0 - boostBarrageCompletedCount = 0 - val laneHeight = dp(BARRAGE_CHIP_HEIGHT_DP) - val laneGap = dp(BARRAGE_MIN_LANE_GAP_DP) - val availableLaneCount = ((height + laneGap) / (laneHeight + laneGap)) - .coerceAtLeast(1) - val laneCount = minOf( - childCount, - TopicDetailBoostPresentation.BODY_BARRAGE_MAX_LANES, - availableLaneCount, - ).coerceAtLeast(1) - val verticalStride = if (laneCount <= 1) { - 0 - } else { - ((height - laneHeight).coerceAtLeast(0) / (laneCount - 1)) - } - val maxChipWidth = (width * 0.72f).toInt().coerceAtLeast(1) - val animationsEnabled = ValueAnimator.areAnimatorsEnabled() - - for (index in 0 until childCount) { - val child = boostBarrageContainer.getChildAt(index) as? TextView ?: continue - child.animate().cancel() - child.measure( - View.MeasureSpec.makeMeasureSpec(maxChipWidth, View.MeasureSpec.AT_MOST), - View.MeasureSpec.makeMeasureSpec(dp(BARRAGE_CHIP_HEIGHT_DP), View.MeasureSpec.EXACTLY), - ) - val chipWidth = child.measuredWidth.coerceIn(dp(48), maxChipWidth) - val lane = index % laneCount - val y = (lane * verticalStride).coerceAtMost((height - laneHeight).coerceAtLeast(0)) - val params = child.layoutParams as FrameLayout.LayoutParams - params.width = chipWidth - params.height = laneHeight - child.layoutParams = params - child.translationY = y.toFloat() - child.alpha = BARRAGE_START_ALPHA - - if (!animationsEnabled || !shouldRunBoostAnimations()) { - val slotProgress = (index + 1).toFloat() / (childCount + 1).toFloat() - child.translationX = ((width - chipWidth).coerceAtLeast(0) * slotProgress) - continue - } - - val round = index / laneCount - val laneStagger = lane * BARRAGE_LANE_STAGGER_MS - val roundStagger = round * BARRAGE_ROUND_STAGGER_MS - val startX = width.toFloat() + lane * dp(18) - child.translationX = startX - val endX = -chipWidth.toFloat() - dp(16) - val animator = ValueAnimator.ofFloat(startX, endX).apply { - duration = BARRAGE_BASE_DURATION_MS + lane * BARRAGE_LANE_DURATION_STEP_MS - startDelay = laneStagger + roundStagger - interpolator = LinearInterpolator() - addUpdateListener { animation -> - child.translationX = animation.animatedValue as Float - child.alpha = BARRAGE_START_ALPHA - animation.animatedFraction * BARRAGE_ALPHA_DELTA - } - addListener(object : Animator.AnimatorListener { - private var canceled = false - - override fun onAnimationStart(animation: Animator) = Unit - - override fun onAnimationEnd(animation: Animator) { - if (!canceled) { - onBoostBarrageAnimatorFinished(animation) - } - } - - override fun onAnimationCancel(animation: Animator) { - canceled = true - } - - override fun onAnimationRepeat(animation: Animator) = Unit - }) - } - boostBarrageAnimators.add(animator) - boostBarrageExpectedCompletions += 1 - animator.start() - } - } - - private fun onBoostBarrageAnimatorFinished(animation: Animator) { - (animation as? ValueAnimator)?.let { boostBarrageAnimators.remove(it) } - boostBarrageCompletedCount += 1 - if (boostBarrageExpectedCompletions <= 0 || - boostBarrageCompletedCount < boostBarrageExpectedCompletions - ) { - return - } - - val completedSignature = boostBarrageSignature ?: return - rememberPlayedBoostBarrage(completedSignature) - boostBarrageContainer.post { - if (boostBarrageSignature != completedSignature) return@post - boostBarrageStartRunnable?.let(boostBarrageContainer::removeCallbacks) - boostBarrageStartRunnable = null - boostBarrageAnimators.clear() - boostBarrageExpectedCompletions = 0 - boostBarrageCompletedCount = 0 - boostBarrageContainer.removeAllViews() - boostBarrageContainer.visibility = View.GONE - } - } - - private fun scheduleBoostBarrageAfterLayout() { - if (boostBarrageStartRunnable != null || boostBarrageContainer.childCount == 0) return - val startRunnable = Runnable { startBoostBarrageAnimations() } - boostBarrageStartRunnable = startRunnable - boostBarrageContainer.postDelayed(startRunnable, BARRAGE_LAYOUT_RETRY_MS) - } - - private fun updateBoostAnimationState() { - if (shouldRunBoostAnimations()) { - if (boostBarrageContainer.visibility == View.VISIBLE) { - if (!resumePausedAnimators(boostBarrageAnimators) && boostBarrageAnimators.isEmpty()) { - scheduleBoostBarrageAfterLayout() - } - } - } else { - pauseBoostAnimations() - } - } - - private fun pauseBoostAnimations() { - boostBarrageStartRunnable?.let(boostBarrageContainer::removeCallbacks) - boostBarrageStartRunnable = null - pauseAnimators(boostBarrageAnimators) - } - - private fun stopBoostAnimations() { - boostBarrageStartRunnable?.let(boostBarrageContainer::removeCallbacks) - boostBarrageStartRunnable = null - boostBarrageAnimators.forEach { it.cancel() } - boostBarrageAnimators.clear() - } - - private fun pauseAnimators(animators: List) { - animators.forEach { animator -> - if (animator.isStarted && !animator.isPaused) { - animator.pause() - } - } - } - - private fun resumePausedAnimators(animators: List): Boolean { - if (animators.isEmpty()) return false - var resumed = false - animators.forEach { animator -> - if (animator.isPaused) { - animator.resume() - resumed = true - } - } - return resumed || animators.any { it.isStarted } - } - - private fun shouldRunBoostAnimations(): Boolean { - return isAttachedToWindow && boostAnimationsEnabled - } - - private fun applyContentWidthMode(usesTitleWidthBody: Boolean) { - val leadingMargin = if (usesTitleWidthBody) 0 else POST_CONTENT_LEADING_MARGIN_DP - applyStartMargin(replyContextText, leadingMargin) - applyStartMargin(bodyFrame, leadingMargin) - applyStartMargin(pollContainer, leadingMargin) - applyStartMargin(boostContainer, leadingMargin) - applyStartMargin(actionsScroll, leadingMargin) - } - - private fun applyStartMargin(view: View, marginDp: Int) { - val params = view.layoutParams as? ViewGroup.MarginLayoutParams ?: return - val marginPx = dp(marginDp) - if (params.marginStart == marginPx) return - params.marginStart = marginPx - view.layoutParams = params - } - - private fun applyActionsTopMargin(marginDp: Int) { - val params = actionsScroll.layoutParams as? ViewGroup.MarginLayoutParams ?: return - val marginPx = dp(marginDp) - if (params.topMargin == marginPx) return - params.topMargin = marginPx - actionsScroll.layoutParams = params - } - - private fun applyActionStartMargin(view: View, marginDp: Int) { - val params = view.layoutParams as? ViewGroup.MarginLayoutParams ?: return - val marginPx = dp(marginDp) - if (params.marginStart == marginPx) return - params.marginStart = marginPx - view.layoutParams = params - } - - private fun bindAuthorChips(chips: List) { - authorChips.removeAllViews() - authorChips.visibility = if (chips.isEmpty()) View.GONE else View.VISIBLE - val context = itemView.context - chips.forEachIndexed { index, chip -> - val chipView = TextView(context).apply { - text = chip.label - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) - setTextColor(context.getColor(chip.textColorRes)) - maxLines = 1 - ellipsize = TextUtils.TruncateAt.END - includeFontPadding = false - setPadding(dp(6), dp(2), dp(6), dp(2)) - background = GradientDrawable().apply { - cornerRadius = dp(9).toFloat() - setColor(context.getColor(chip.backgroundColorRes)) - } - layoutParams = LinearLayout.LayoutParams( - LinearLayout.LayoutParams.WRAP_CONTENT, - LinearLayout.LayoutParams.WRAP_CONTENT, - ).apply { - if (index > 0) marginStart = dp(4) - } - } - authorChips.addView(chipView) - } - } - - private fun pollTitleView(poll: PollState): TextView { - val context = itemView.context - val labels = buildList { - add(context.getString(R.string.topic_detail_poll_title)) - if (poll.kind.equals("multiple", ignoreCase = true)) { - add(context.getString(R.string.topic_detail_poll_multiple)) - } - if (poll.status.equals("closed", ignoreCase = true)) { - add(context.getString(R.string.topic_detail_poll_closed)) - } - add(context.getString(R.string.topic_detail_poll_voters_count, poll.voters.toString())) - } - return TextView(context).apply { - text = labels.joinToString(" · ") - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) - setTextColor(context.getColor(R.color.fire_text_secondary)) - } - } - - private fun pollOptionsView( - post: TopicPostState, - poll: PollState, - callbacks: PostRowCallbacks, - ): LinearLayout { - val context = itemView.context - val selected = poll.userVotes.toMutableSet() - val isMultiple = poll.kind.equals("multiple", ignoreCase = true) - val isClosed = poll.status.equals("closed", ignoreCase = true) - val group = LinearLayout(context).apply { - orientation = LinearLayout.VERTICAL - layoutParams = LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - LinearLayout.LayoutParams.WRAP_CONTENT, - ) - } - val optionChecks = mutableListOf() - - for (option in poll.options) { - val checkBox = CheckBox(context).apply { - text = context.getString( - R.string.topic_detail_poll_option_with_votes, - option.plainText.trim().ifBlank { option.id }, - option.votes.toString(), - ) - isChecked = selected.contains(option.id) - isEnabled = !isClosed - setTextColor(context.getColor(R.color.fire_text_primary)) - setOnCheckedChangeListener { _, checked -> - if (checked) { - if (!isMultiple) { - selected.clear() - optionChecks.filter { it !== this }.forEach { it.isChecked = false } - } - selected.add(option.id) - } else { - selected.remove(option.id) - } - } - } - optionChecks.add(checkBox) - group.addView(checkBox) - } - - if (!isClosed) { - group.addView(pollActionsView(post, poll, selected, callbacks)) - } - return group - } - - private fun pollActionsView( - post: TopicPostState, - poll: PollState, - selected: MutableSet, - callbacks: PostRowCallbacks, - ): LinearLayout { - val context = itemView.context - return LinearLayout(context).apply { - orientation = LinearLayout.HORIZONTAL - gravity = android.view.Gravity.CENTER_VERTICAL - val submit = TextView(context).apply { - text = context.getString(R.string.topic_detail_poll_submit) - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) - setTextColor(context.getColor(R.color.fire_accent)) - setPadding(0, 8, 18, 8) - setOnClickListener { - val selectedOptions = selected.toList() - if (selectedOptions.isEmpty()) { - Toast.makeText( - context, - R.string.topic_detail_poll_select_required, - Toast.LENGTH_SHORT, - ).show() - } else { - callbacks.onVotePoll(post, poll, selectedOptions) - } - } - } - addView(submit) - - if (poll.userVotes.isNotEmpty()) { - val unvote = TextView(context).apply { - text = context.getString(R.string.topic_detail_poll_unvote) - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) - setTextColor(context.getColor(R.color.fire_text_secondary)) - setPadding(0, 8, 0, 8) - setOnClickListener { - callbacks.onUnvotePoll(post, poll) - } - } - addView(unvote) - } - } - } - - private fun sectionDivider(): View { - return View(itemView.context).apply { - setBackgroundColor(itemView.context.getColor(R.color.fire_divider)) - layoutParams = LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - 1, - ).apply { - topMargin = 10 - bottomMargin = 10 - } - } - } - - private fun dp(value: Int): Int { + internal fun dp(value: Int): Int { return itemView.resources.displayMetrics.density.times(value).toInt() } companion object { private const val HEART_REACTION_ID = "heart" - private const val BARRAGE_CHIP_HEIGHT_DP = 24 - private const val BARRAGE_MIN_LANE_GAP_DP = 4 - private const val BARRAGE_BASE_DURATION_MS = 12_500L - private const val BARRAGE_LANE_DURATION_STEP_MS = 1_400L - private const val BARRAGE_LANE_STAGGER_MS = 1_500L - private const val BARRAGE_ROUND_STAGGER_MS = 4_600L - private const val BARRAGE_START_ALPHA = 0.82f - private const val BARRAGE_ALPHA_DELTA = 0.16f - private const val BARRAGE_LAYOUT_RETRY_MS = 48L - private const val BARRAGE_PLAYED_CACHE_LIMIT = 256 - private const val FIXED_BOOST_MANUAL_ROWS = 2 - private const val FIXED_BOOST_MANUAL_ROW_HEIGHT_DP = 30 - private const val FIXED_BOOST_MANUAL_ROW_SPACING_DP = 4 - private const val FIXED_BOOST_MANUAL_CHIP_HEIGHT_DP = 26 - private const val FIXED_BOOST_MANUAL_CHIP_SPACING_DP = 8 - private const val FIXED_BOOST_MANUAL_MIN_CHIP_WIDTH_DP = 48 - private const val POST_CONTENT_LEADING_MARGIN_DP = 46 - private const val ACTIONS_DEFAULT_TOP_MARGIN_DP = 8 - private val playedBoostBarrageSignatures = LinkedHashSet() - - private fun hasPlayedBoostBarrage(signature: String): Boolean { - return playedBoostBarrageSignatures.contains(signature) - } - - private fun rememberPlayedBoostBarrage(signature: String) { - playedBoostBarrageSignatures.add(signature) - while (playedBoostBarrageSignatures.size > BARRAGE_PLAYED_CACHE_LIMIT) { - val iterator = playedBoostBarrageSignatures.iterator() - if (!iterator.hasNext()) return - iterator.next() - iterator.remove() - } - } fun create(parent: ViewGroup): PostViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_post, parent, false) return PostViewHolder(view) } - - private fun displayName(post: TopicPostState): String { - return cleaned(post.name) - ?: cleaned(post.username) - ?: "Unknown" - } - - private fun primaryMetadataParts(post: TopicPostState): List { - val metadata = post.authorMetadata - // Fluxdo-style: staff roles only on the primary line. - // Trust title sits on the secondary @username line; flair/group are not text chips. - return buildList { - if (metadata.admin) { - add(AuthorMetadataChip("管理员", R.color.fire_error, R.color.fire_chip_error_background)) - } - if (metadata.moderator) { - add(AuthorMetadataChip("版主", R.color.fire_link, R.color.fire_chip_link_background)) - } - if (metadata.groupModerator) { - add(AuthorMetadataChip("组版主", R.color.fire_warning, R.color.fire_chip_warning_background)) - } - }.take(MAX_PRIMARY_METADATA_CHIPS) - } - - private fun secondaryMetadataParts(post: TopicPostState): List { - val metadata = post.authorMetadata - val username = cleaned(post.username) - val title = cleaned(metadata.userTitle)?.let(::humanizedUserTitle) - val statusDescription = cleaned(metadata.userStatusDescription) - val statusEmoji = cleaned(metadata.userStatusEmoji)?.let { ":$it:" } - - return buildList { - username?.let { add("@$it") } - title?.let { add(compactSecondaryLabel(it)) } - if (statusDescription != null) { - add(compactSecondaryLabel(statusDescription)) - } else { - statusEmoji?.let(::add) - } - } - } - - private fun humanizedUserTitle(title: String): String { - val level = parsedTrustLevel(title) ?: return title - return trustLevelDisplayLabel(level) - } - - private fun parsedTrustLevel(value: String): Int? { - for (regex in TRUST_LEVEL_REGEXES) { - val match = regex.find(value) ?: continue - val level = match.groupValues.getOrNull(1)?.toIntOrNull() ?: continue - return level - } - return null - } - - private fun trustLevelDisplayLabel(level: Int): String { - return when (level) { - 0 -> "L0 新用户" - 1 -> "L1 基本用户" - 2 -> "L2 成员" - 3 -> "L3 活跃用户" - 4 -> "L4 领袖" - else -> "L$level" - } - } - - private fun cleaned(value: String?): String? { - return value?.trim()?.takeIf { it.isNotEmpty() } - } - - private fun compactSecondaryLabel(value: String): String { - return if (value.length <= MAX_SECONDARY_LABEL_LENGTH) { - value - } else { - value.take(MAX_SECONDARY_LABEL_LENGTH - 1) + "…" - } - } - - private const val MAX_PRIMARY_METADATA_CHIPS = 3 - private const val MAX_SECONDARY_LABEL_LENGTH = 16 - private val TRUST_LEVEL_REGEXES = listOf( - Regex("""(?i)trust[_\s-]*l(?:evel|v)[_\s-]*(\d+)"""), - Regex("""(?i)\btl[_\s-]*(\d+)\b"""), - Regex("""(?i)\blv\.?\s*(\d+)\b"""), - Regex("""(?i)\bl(\d+)\b"""), - Regex("""等级\s*(\d+)"""), - Regex("""(?i)level\s*(\d+)"""), - ) - private val BOOST_ATTRIBUTION_PREFIX_REGEX = Regex("""^@?[^\s::]{1,40}[::]\s*""") - } -} - -private data class AuthorMetadataChip( - val label: String, - val textColorRes: Int, - val backgroundColorRes: Int, -) - -private class FixedBoostManualChipLayout @JvmOverloads constructor( - context: Context, - attrs: AttributeSet? = null, -) : ViewGroup(context, attrs) { - - var rowCount: Int = 2 - var rowHeightPx: Int = 0 - var rowSpacingPx: Int = 0 - var chipHeightPx: Int = 0 - var chipSpacingPx: Int = 0 - var minChipWidthPx: Int = 0 - - private var measuredChipWidths: IntArray = IntArray(0) - private var layoutResult = TopicDetailManualBoostLayoutResult( - placements = emptyList(), - contentWidth = 0, - usedRowCount = 0, - ) - - override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { - val viewportWidth = resolvedViewportWidth(widthMeasureSpec) - val maxChipWidth = (viewportWidth * MAX_CHIP_WIDTH_RATIO).toInt().coerceAtLeast(1) - val resolvedChipHeight = chipHeightPx.coerceAtLeast(1) - val childHeightSpec = MeasureSpec.makeMeasureSpec(resolvedChipHeight, MeasureSpec.EXACTLY) - val childWidthSpec = MeasureSpec.makeMeasureSpec(maxChipWidth, MeasureSpec.AT_MOST) - val widths = IntArray(childCount) - - for (index in 0 until childCount) { - val child = getChildAt(index) - if (child.visibility == GONE) { - widths[index] = 0 - continue - } - child.measure(childWidthSpec, childHeightSpec) - widths[index] = child.measuredWidth.coerceIn(minChipWidthPx.coerceAtLeast(1), maxChipWidth) - child.measure( - MeasureSpec.makeMeasureSpec(widths[index], MeasureSpec.EXACTLY), - childHeightSpec, - ) - } - - measuredChipWidths = widths - layoutResult = TopicDetailManualBoostLayout.placements( - chipWidths = widths.filter { it > 0 }, - pageWidth = viewportWidth, - rowCount = rowCount, - chipSpacing = chipSpacingPx, - ) - - val resolvedRowCount = layoutResult.usedRowCount.coerceIn(0, rowCount.coerceAtLeast(1)) - val resolvedRowHeight = rowHeightPx.coerceAtLeast(resolvedChipHeight) - val measuredHeight = if (resolvedRowCount == 0) { - 0 - } else { - resolvedRowCount * resolvedRowHeight + - (resolvedRowCount - 1) * rowSpacingPx - } - setMeasuredDimension( - layoutResult.contentWidth.coerceAtLeast(viewportWidth), - resolveSize(measuredHeight, heightMeasureSpec), - ) - } - - override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { - val resolvedRowHeight = rowHeightPx.coerceAtLeast(chipHeightPx.coerceAtLeast(1)) - var placementIndex = 0 - for (index in 0 until childCount) { - val child = getChildAt(index) - if (child.visibility == GONE) continue - val placement = layoutResult.placements.getOrNull(placementIndex) ?: break - val width = measuredChipWidths.getOrNull(index)?.takeIf { it > 0 } ?: child.measuredWidth - val childTop = placement.rowIndex * (resolvedRowHeight + rowSpacingPx) + - ((resolvedRowHeight - child.measuredHeight).coerceAtLeast(0) / 2) - child.layout( - placement.x, - childTop, - placement.x + width, - childTop + child.measuredHeight, - ) - placementIndex += 1 - } - } - - override fun generateDefaultLayoutParams(): LayoutParams { - return LayoutParams(LayoutParams.WRAP_CONTENT, chipHeightPx.coerceAtLeast(1)) - } - - override fun generateLayoutParams(attrs: AttributeSet): LayoutParams { - return LayoutParams(context, attrs) - } - - override fun generateLayoutParams(params: LayoutParams): LayoutParams { - return LayoutParams(params) - } - - override fun checkLayoutParams(params: LayoutParams): Boolean { - return true - } - - private fun resolvedViewportWidth(widthMeasureSpec: Int): Int { - val specWidth = MeasureSpec.getSize(widthMeasureSpec) - if (specWidth > 0) return specWidth - val parentWidth = (parent as? View)?.width ?: 0 - if (parentWidth > 0) return parentWidth - return resources.displayMetrics.widthPixels.coerceAtLeast(1) - } - - private companion object { - private const val MAX_CHIP_WIDTH_RATIO = 0.72f } } diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Bookmarks.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Bookmarks.kt new file mode 100644 index 00000000..64592e3d --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Bookmarks.kt @@ -0,0 +1,237 @@ +package com.fire.app.ui.topicdetail + +import android.Manifest +import android.app.DatePickerDialog +import android.app.TimePickerDialog +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.view.View +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import androidx.core.content.ContextCompat +import com.fire.app.R +import com.fire.app.core.ext.dp +import uniffi.fire_uniffi_topics.TopicPostState +import java.time.Instant +import java.time.ZoneId +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle + +internal fun TopicDetailActivity.showPostBookmarkEditor(post: TopicPostState) { + showBookmarkEditor( + bookmarkableId = post.id, + bookmarkableType = "Post", + bookmarkId = post.bookmarkId, + bookmarkName = post.bookmarkName, + bookmarkReminderAt = post.bookmarkReminderAt, + targetPostNumber = post.postNumber, + ) +} + +internal fun TopicDetailActivity.showBookmarkEditor( + bookmarkableId: ULong, + bookmarkableType: String, + bookmarkId: ULong?, + bookmarkName: String?, + bookmarkReminderAt: String?, + targetPostNumber: UInt?, +) { + val nameInput = EditText(this).apply { + setText(bookmarkName.orEmpty()) + hint = getString(R.string.topic_detail_bookmark_name_hint) + setSingleLine(true) + } + val reminderSelection = BookmarkReminderSelection.from(bookmarkReminderAt) + val reminderToggle = androidx.appcompat.widget.SwitchCompat(this).apply { + text = getString(R.string.topic_detail_bookmark_reminder_label) + isChecked = reminderSelection.hasReminder + } + val reminderButton = TextView(this).apply { + setPadding(0, dp(12), 0, dp(4)) + text = reminderSelection.displayText(this@showBookmarkEditor) + setTextColor(getColor(R.color.fire_accent)) + setOnClickListener { + showBookmarkReminderDatePicker(reminderSelection, this) + } + } + reminderButton.visibility = if (reminderSelection.hasReminder) View.VISIBLE else View.GONE + reminderToggle.setOnCheckedChangeListener { _, isChecked -> + reminderSelection.hasReminder = isChecked + if (isChecked && reminderSelection.dateTime == null) { + reminderSelection.dateTime = ZonedDateTime.now().plusHours(1) + } + reminderButton.text = reminderSelection.displayText(this) + reminderButton.visibility = if (isChecked) View.VISIBLE else View.GONE + } + val content = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(dp(24), dp(8), dp(24), 0) + addView(nameInput) + addView(reminderToggle) + addView(reminderButton) + } + + val dialog = AlertDialog.Builder(this) + .setTitle( + if (bookmarkId == null) { + R.string.topic_detail_bookmark_add_title + } else { + R.string.topic_detail_bookmark_edit_title + }, + ) + .setView(content) + .setPositiveButton(R.string.topic_detail_bookmark_save, null) + .setNegativeButton(android.R.string.cancel, null) + .apply { + if (bookmarkId != null) { + setNeutralButton(R.string.topic_detail_bookmark_delete, null) + } + } + .create() + dialog.setOnShowListener { + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val reminderAt = reminderSelection.reminderAt() + val key = BookmarkReminderKey(bookmarkableId, bookmarkableType) + pendingBookmarkReminders[key] = BookmarkReminderRequest( + bookmarkableId = bookmarkableId, + bookmarkableType = bookmarkableType, + topicId = route?.topicId ?: -1L, + postNumber = targetPostNumber?.toInt() ?: -1, + title = bookmarkReminderTitle(bookmarkableType, targetPostNumber), + reminderAt = reminderAt, + ) + viewModel?.saveBookmark( + bookmarkableId = bookmarkableId, + bookmarkableType = bookmarkableType, + bookmarkId = bookmarkId, + name = nameInput.text.toString(), + reminderAt = reminderAt, + targetPostNumber = targetPostNumber, + ) + dialog.dismiss() + } + if (bookmarkId != null) { + dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener { + viewModel?.deleteBookmark( + bookmarkId = bookmarkId, + bookmarkableId = bookmarkableId, + bookmarkableType = bookmarkableType, + targetPostNumber = targetPostNumber, + ) + dialog.dismiss() + } + } + } + dialog.show() +} + +internal fun TopicDetailActivity.showBookmarkReminderDatePicker( + selection: BookmarkReminderSelection, + target: TextView, +) { + val current = selection.dateTime ?: ZonedDateTime.now().plusHours(1) + DatePickerDialog( + this, + { _, year, month, dayOfMonth -> + TimePickerDialog( + this, + { _, hourOfDay, minute -> + val selectedDateTime = current + .withYear(year) + .withMonth(month + 1) + .withDayOfMonth(dayOfMonth) + .withHour(hourOfDay) + .withMinute(minute) + .withSecond(0) + .withNano(0) + selection.dateTime = selectedDateTime.takeIf { it.isAfter(ZonedDateTime.now()) } + ?: ZonedDateTime.now().plusMinutes(1).withSecond(0).withNano(0) + target.text = selection.displayText(this) + }, + current.hour, + current.minute, + true, + ).show() + }, + current.year, + current.monthValue - 1, + current.dayOfMonth, + ).apply { + datePicker.minDate = System.currentTimeMillis() + }.show() +} + +internal fun TopicDetailActivity.scheduleBookmarkReminderAfterSave(request: BookmarkReminderRequest) { + if (request.reminderAt.isNullOrBlank()) { + BookmarkReminderScheduler.sync(this, request) + return + } + if ( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != + PackageManager.PERMISSION_GRANTED + ) { + pendingNotificationPermissionRequest = request + notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) + return + } + BookmarkReminderScheduler.sync(this, request) +} + +internal fun TopicDetailActivity.bookmarkReminderTitle(bookmarkableType: String, targetPostNumber: UInt?): String { + val detail = viewModel?.detail?.value + val title = detail?.title?.trim()?.takeIf { it.isNotEmpty() } + ?: route?.title?.trim()?.takeIf { it.isNotEmpty() } + ?: getString(R.string.topic_detail_title_fallback, route?.topicId?.toString().orEmpty()) + return if (bookmarkableType.equals("Post", ignoreCase = true) && targetPostNumber != null) { + "$title #$targetPostNumber" + } else { + title + } +} + +internal data class BookmarkReminderKey( + val bookmarkableId: ULong, + val bookmarkableType: String, +) + +internal class BookmarkReminderSelection( + var hasReminder: Boolean, + var dateTime: ZonedDateTime?, +) { + fun reminderAt(): String? { + if (!hasReminder) return null + val normalizedDateTime = dateTime + ?.takeIf { it.isAfter(ZonedDateTime.now()) } + ?: ZonedDateTime.now().plusMinutes(1) + return normalizedDateTime + ?.withSecond(0) + ?.withNano(0) + ?.toInstant() + ?.toString() + } + + fun displayText(context: Context): String { + val dateTime = dateTime ?: return context.getString(R.string.topic_detail_bookmark_reminder_pick) + return DateTimeFormatter + .ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT) + .format(dateTime.withZoneSameInstant(ZoneId.systemDefault())) + } + + companion object { + fun from(rawValue: String?): BookmarkReminderSelection { + val parsed = rawValue + ?.trim() + ?.takeIf { it.isNotEmpty() } + ?.let { runCatching { Instant.parse(it).atZone(ZoneId.systemDefault()) }.getOrNull() } + return BookmarkReminderSelection( + hasReminder = parsed != null, + dateTime = parsed, + ) + } + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Composer.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Composer.kt new file mode 100644 index 00000000..2a866857 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Composer.kt @@ -0,0 +1,209 @@ +package com.fire.app.ui.topicdetail + +import android.view.View +import android.widget.ArrayAdapter +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.Spinner +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.lifecycle.lifecycleScope +import com.fire.app.R +import com.fire.app.core.ui.FireToast +import com.fire.app.displayName +import com.fire.app.ui.composer.ComposerTagAssist +import com.fire.app.ui.composer.QuoteMarkdown +import com.fire.app.ui.composer.ReplyComposerSheet +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_session.TopicCategoryState +import uniffi.fire_uniffi_topics.TopicDetailState +import uniffi.fire_uniffi_topics.TopicPostState + +internal fun TopicDetailActivity.showReplyComposerForPost(post: TopicPostState) { + showReplyComposer(replyToPostNumber = post.postNumber.toInt()) +} + +internal fun TopicDetailActivity.showQuoteReplyComposerForPost(post: TopicPostState) { + val currentRoute = route ?: return + val quote = QuoteMarkdown.build( + username = post.username, + postNumber = post.postNumber, + topicId = currentRoute.topicId.toULong(), + plainText = post.presentation?.plainText().orEmpty(), + ) + if (quote == null) { + FireToast.show(binding.root, R.string.topic_detail_quote_empty, FireToast.Style.INFO) + return + } + showReplyComposer( + replyToPostNumber = post.postNumber.toInt(), + initialBody = quote, + ) +} + +internal fun TopicDetailActivity.showReplyComposer(replyToPostNumber: Int?, initialBody: String? = null) { + val currentRoute = route ?: return + val sheet = ReplyComposerSheet.newInstance( + topicId = currentRoute.topicId, + replyToPostNumber = replyToPostNumber, + initialBody = initialBody, + ) { + viewModel?.loadTopicDetail( + topicId = currentRoute.topicId.toULong(), + targetPostNumber = replyToPostNumber?.toUInt(), + ) + } + sheet.show(supportFragmentManager, "reply_composer") +} + +internal fun TopicDetailActivity.showTopicEditor(detail: TopicDetailState) { + lifecycleScope.launch { + try { + val session = sessionStore.snapshot() + val currentCategoryId = detail.categoryId + val categories = session.bootstrap.categories.filter { category -> + category.id == currentCategoryId || + category.permission?.toInt()?.let { it <= 1 } ?: true + } + if (categories.isEmpty()) { + Toast.makeText( + this@showTopicEditor, + R.string.topic_detail_edit_topic_no_categories, + Toast.LENGTH_SHORT, + ).show() + return@launch + } + showTopicEditorDialog( + detail = detail, + categories = categories, + minTitleLength = session.bootstrap.minTopicTitleLength.toInt().coerceAtLeast(1), + ) + } catch (e: Exception) { + Toast.makeText( + this@showTopicEditor, + e.localizedMessage ?: getString(R.string.topic_detail_edit_topic_error), + Toast.LENGTH_SHORT, + ).show() + } + } +} + +internal fun TopicDetailActivity.showTopicEditorDialog( + detail: TopicDetailState, + categories: List, + minTitleLength: Int, +) { + val titleInput = EditText(this).apply { + setText(detail.title.trim()) + hint = getString(R.string.topic_detail_edit_topic_title_hint) + setSingleLine(true) + } + val categorySpinner = Spinner(this).apply { + adapter = ArrayAdapter( + this@showTopicEditorDialog, + android.R.layout.simple_spinner_item, + categories.map { it.displayName() }, + ).apply { + setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + } + val selectedIndex = categories.indexOfFirst { it.id == detail.categoryId } + if (selectedIndex >= 0) { + setSelection(selectedIndex) + } + } + val tagsInput = EditText(this).apply { + setText(detail.tags.joinToString(" ") { it.name }) + hint = getString(R.string.topic_detail_edit_topic_tags_hint) + setSingleLine(true) + } + val tagSuggestions = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + visibility = View.GONE + } + val content = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(48, 8, 48, 0) + addView(titleInput) + addView(categorySpinner) + addView(tagsInput) + addView(tagSuggestions) + } + ComposerTagAssist( + input = tagsInput, + suggestions = tagSuggestions, + sessionStore = sessionStore, + scope = lifecycleScope, + categoryIdProvider = { categories.getOrNull(categorySpinner.selectedItemPosition)?.id }, + selectedTagsProvider = { + tagsInput.text.toString() + .split("[,\\s]+".toRegex()) + .filter { it.isNotBlank() } + }, + ).attach() + + val dialog = AlertDialog.Builder(this) + .setTitle(R.string.topic_detail_edit_topic_title) + .setView(content) + .setPositiveButton(R.string.topic_detail_edit_save, null) + .setNegativeButton(android.R.string.cancel, null) + .create() + dialog.setOnShowListener { + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val title = titleInput.text.toString().trim() + val category = categories.getOrNull(categorySpinner.selectedItemPosition) + val tags = tagsInput.text.toString() + .split("[,\\s]+".toRegex()) + .filter { it.isNotBlank() } + + if (title.length < minTitleLength) { + Toast.makeText( + this, + getString( + R.string.topic_detail_edit_topic_title_min_length, + minTitleLength.toString(), + ), + Toast.LENGTH_SHORT, + ).show() + return@setOnClickListener + } + if (category == null) { + Toast.makeText( + this, + R.string.topic_detail_edit_topic_category_required, + Toast.LENGTH_SHORT, + ).show() + return@setOnClickListener + } + if (tags.size < category.minimumRequiredTags.toInt()) { + Toast.makeText( + this, + getString( + R.string.topic_detail_edit_topic_tags_required, + category.minimumRequiredTags.toString(), + ), + Toast.LENGTH_SHORT, + ).show() + return@setOnClickListener + } + val disallowedTags = if (category.allowedTags.isEmpty()) { + emptyList() + } else { + tags.filterNot { tag -> category.allowedTags.contains(tag) } + } + if (disallowedTags.isNotEmpty()) { + Toast.makeText( + this, + getString( + R.string.topic_detail_edit_topic_tags_not_allowed, + disallowedTags.joinToString(", "), + ), + Toast.LENGTH_SHORT, + ).show() + return@setOnClickListener + } + viewModel?.updateTopic(title, category.id, tags) + dialog.dismiss() + } + } + dialog.show() +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Observe.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Observe.kt new file mode 100644 index 00000000..ace007bc --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Observe.kt @@ -0,0 +1,132 @@ +package com.fire.app.ui.topicdetail + +import android.view.View +import androidx.lifecycle.lifecycleScope +import com.fire.app.R +import com.fire.app.core.ui.FireToast +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch + +internal fun TopicDetailActivity.observeViewModel() { + val vm = viewModel ?: return + lifecycleScope.launch { + vm.isLoading.collectLatest { loading -> + loadingView.visibility = if (loading) View.VISIBLE else View.GONE + recyclerView.visibility = if (loading && vm.postRows.value.isEmpty()) View.GONE else View.VISIBLE + } + } + + lifecycleScope.launch { + vm.errorMessage.collectLatest { error -> + if (error != null) { + errorView.visibility = View.VISIBLE + errorText.text = error + if (vm.postRows.value.isEmpty() && vm.detail.value == null) { + recyclerView.visibility = View.GONE + } + } else { + errorView.visibility = View.GONE + recyclerView.visibility = if (vm.isLoading.value && vm.postRows.value.isEmpty()) { + View.GONE + } else { + View.VISIBLE + } + } + } + } + + lifecycleScope.launch { + vm.isCloudflareError.collectLatest { isCloudflare -> + (retryButton as? com.google.android.material.button.MaterialButton)?.text = + getString( + if (isCloudflare) R.string.action_cloudflare_verify else R.string.action_retry, + ) + } + } + + lifecycleScope.launch { + vm.detail.collectLatest { detail -> + headerAdapter.detail = detail + if (detail != null) { + pinnedTopicTitle = detail.title.trim() + if (toolbarTitlePinned) { + binding.topicDetailToolbar.title = pinnedTopicTitle + } + } + updateTopicNotificationToolbar(detail) + recomputeTopicSearch() + updateVisiblePostTimings() + } + } + + lifecycleScope.launch { + vm.topicAiSummary.collectLatest { summary -> + headerAdapter.aiSummary = summary + } + } + + lifecycleScope.launch { + vm.postRows.collectLatest { rows -> + postListAdapter.submitList(rows) { + updateVisiblePostTimings() + pendingScrollTargetPostNumber?.let { scrollToPostNumber(it) } + } + recomputeTopicSearch() + } + } + + lifecycleScope.launch { + vm.scrollTargetPostNumber.collectLatest { postNumber -> + scrollToPostNumber(postNumber) + } + } + + lifecycleScope.launch { + vm.actionError.collectLatest { error -> + FireToast.show(binding.root, error, FireToast.Style.ERROR) + } + } + + lifecycleScope.launch { + vm.bookmarkEvents.collectLatest { event -> + when (event) { + is BookmarkEvent.Saved -> { + FireToast.show( + binding.root, + R.string.topic_detail_bookmark_saved, + FireToast.Style.SUCCESS, + ) + val key = BookmarkReminderKey(event.bookmarkableId, event.bookmarkableType) + pendingBookmarkReminders.remove(key)?.let { request -> + scheduleBookmarkReminderAfterSave(request.copy(reminderAt = event.reminderAt)) + } + } + is BookmarkEvent.Deleted -> { + FireToast.show( + binding.root, + R.string.topic_detail_bookmark_deleted, + FireToast.Style.INFO, + ) + val key = BookmarkReminderKey(event.bookmarkableId, event.bookmarkableType) + pendingBookmarkReminders.remove(key) + BookmarkReminderScheduler.cancel( + this@observeViewModel, + event.bookmarkableId, + event.bookmarkableType, + ) + } + } + } + } + + lifecycleScope.launch { + vm.isLoadingMore.collectLatest { loadingMore -> + loadingFooterAdapter.isLoading = loadingMore + } + } +} + +internal fun TopicDetailActivity.loadRoute(route: TopicDetailActivity.TopicDetailRoute) { + val targetPostNumber = route.targetPostNumber.takeIf { it > 0 }?.toUInt() + viewModel?.loadTopicDetail(route.topicId.toULong(), targetPostNumber) +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+PostManagement.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+PostManagement.kt new file mode 100644 index 00000000..5d3eb362 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+PostManagement.kt @@ -0,0 +1,247 @@ +package com.fire.app.ui.topicdetail + +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.lifecycle.lifecycleScope +import com.fire.app.R +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_topics.PostActionTypeState +import uniffi.fire_uniffi_topics.PostFlagRequestState +import uniffi.fire_uniffi_topics.TopicPostState + +internal fun TopicDetailActivity.confirmDeletePost(post: TopicPostState) { + AlertDialog.Builder(this) + .setTitle( + getString( + R.string.topic_detail_delete_confirm_title, + post.postNumber.toString(), + ), + ) + .setMessage(R.string.topic_detail_delete_confirm_message) + .setPositiveButton(R.string.topic_detail_delete_post) { _, _ -> + viewModel?.deletePost(post) + } + .setNegativeButton(android.R.string.cancel, null) + .show() +} + +internal fun TopicDetailActivity.confirmRecoverPost(post: TopicPostState) { + AlertDialog.Builder(this) + .setTitle( + getString( + R.string.topic_detail_recover_confirm_title, + post.postNumber.toString(), + ), + ) + .setMessage(R.string.topic_detail_recover_confirm_message) + .setPositiveButton(R.string.topic_detail_recover_post) { _, _ -> + viewModel?.recoverPost(post) + } + .setNegativeButton(android.R.string.cancel, null) + .show() +} + +internal fun TopicDetailActivity.showPostEditor(post: TopicPostState) { + Toast.makeText(this, R.string.topic_detail_edit_post_loading, Toast.LENGTH_SHORT).show() + lifecycleScope.launch { + try { + val editablePost = sessionStore.fetchPost(post.id) + val raw = editablePost.raw + ?.takeIf { it.isNotBlank() } + ?: throw IllegalStateException(getString(R.string.topic_detail_edit_post_error)) + showPostEditorDialog(post, raw) + } catch (e: Exception) { + Toast.makeText( + this@showPostEditor, + e.localizedMessage ?: getString(R.string.topic_detail_edit_post_error), + Toast.LENGTH_SHORT, + ).show() + } + } +} + +internal fun TopicDetailActivity.showPostEditorDialog(post: TopicPostState, raw: String) { + val bodyInput = EditText(this).apply { + setText(raw) + hint = getString(R.string.topic_detail_edit_post_body_hint) + minLines = 8 + gravity = android.view.Gravity.TOP + } + val reasonInput = EditText(this).apply { + hint = getString(R.string.topic_detail_edit_post_reason_hint) + setSingleLine(true) + } + val content = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(48, 8, 48, 0) + addView(bodyInput) + addView(reasonInput) + } + + val dialog = AlertDialog.Builder(this) + .setTitle(getString(R.string.topic_detail_edit_post_title, post.postNumber.toString())) + .setView(content) + .setPositiveButton(R.string.topic_detail_edit_save, null) + .setNegativeButton(android.R.string.cancel, null) + .create() + dialog.setOnShowListener { + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val nextRaw = bodyInput.text.toString() + if (nextRaw.isBlank()) { + Toast.makeText( + this, + R.string.topic_detail_edit_post_error, + Toast.LENGTH_SHORT, + ).show() + return@setOnClickListener + } + viewModel?.updatePost( + post = post, + raw = nextRaw, + editReason = reasonInput.text.toString(), + ) + dialog.dismiss() + } + } + dialog.show() +} + +internal fun TopicDetailActivity.showFlagPostOptions(post: TopicPostState) { + lifecycleScope.launch { + try { + val options = sessionStore.fetchPostActionTypes() + .mapNotNull { postFlagOption(it) } + .ifEmpty { fallbackPostFlagOptions() } + val labels = options.map { option -> + if (option.detail.isBlank()) { + option.title + } else { + "${option.title}\n${option.detail}" + } + }.toTypedArray() + AlertDialog.Builder(this@showFlagPostOptions) + .setTitle( + getString( + R.string.topic_detail_flag_type_title, + post.postNumber.toString(), + ), + ) + .setItems(labels) { _, which -> + promptFlagPost(post, options[which]) + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } catch (e: Exception) { + Toast.makeText( + this@showFlagPostOptions, + e.localizedMessage ?: getString(R.string.topic_detail_flag_message_required), + Toast.LENGTH_SHORT, + ).show() + } + } +} + +internal fun TopicDetailActivity.postFlagOption(type: PostActionTypeState): PostFlagOption? { + if (!type.isFlag || !type.enabled) return null + if (type.appliesTo.isNotEmpty() && !type.appliesTo.contains("Post")) return null + + val detail = type.description.ifBlank { type.shortDescription.orEmpty() } + return PostFlagOption( + id = type.id, + title = type.name.ifBlank { fallbackFlagTitle(type.nameKey, type.id) }, + detail = plainText(detail), + requireMessage = type.requireMessage, + ) +} + +internal fun TopicDetailActivity.fallbackPostFlagOptions(): List { + return listOf( + PostFlagOption(3u, "Off topic", "This post is off topic.", false), + PostFlagOption(4u, "Inappropriate", "This post is inappropriate.", false), + PostFlagOption(8u, "Spam", "This post looks like spam.", false), + PostFlagOption(7u, "Notify moderators", "Add details for moderators.", true), + ) +} + +internal fun TopicDetailActivity.fallbackFlagTitle(nameKey: String, id: UInt): String { + return when (nameKey) { + "off_topic" -> "Off topic" + "inappropriate" -> "Inappropriate" + "spam" -> "Spam" + "notify_moderators" -> "Notify moderators" + else -> nameKey.ifBlank { "#$id" } + } +} + +internal fun TopicDetailActivity.promptFlagPost(post: TopicPostState, option: PostFlagOption) { + if (option.requireMessage) { + val input = EditText(this).apply { + hint = getString(R.string.topic_detail_flag_message_hint) + minLines = 3 + } + AlertDialog.Builder(this) + .setTitle(getString(R.string.topic_detail_flag_message_title, option.title)) + .setView(input) + .setPositiveButton(R.string.topic_detail_flag_submit) { _, _ -> + val message = input.text.toString().trim() + if (message.isBlank()) { + Toast.makeText( + this, + R.string.topic_detail_flag_message_required, + Toast.LENGTH_SHORT, + ).show() + } else { + submitFlagPost(post, option, message) + } + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } else { + AlertDialog.Builder(this) + .setTitle(getString(R.string.topic_detail_flag_confirm_title, option.title)) + .setMessage(option.detail.ifBlank { getString(R.string.topic_detail_flag_confirm_message) }) + .setPositiveButton(R.string.topic_detail_flag_submit) { _, _ -> + submitFlagPost(post, option, null) + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } +} + +internal fun TopicDetailActivity.submitFlagPost( + post: TopicPostState, + option: PostFlagOption, + message: String?, +) { + lifecycleScope.launch { + try { + sessionStore.flagPost( + PostFlagRequestState( + postId = post.id, + flagTypeId = option.id, + message = message, + ), + ) + Toast.makeText( + this@submitFlagPost, + R.string.topic_detail_flag_submitted, + Toast.LENGTH_SHORT, + ).show() + } catch (e: Exception) { + Toast.makeText( + this@submitFlagPost, + e.localizedMessage ?: getString(R.string.topic_detail_action_error), + Toast.LENGTH_SHORT, + ).show() + } + } +} + +internal data class PostFlagOption( + val id: UInt, + val title: String, + val detail: String, + val requireMessage: Boolean, +) diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Reactions.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Reactions.kt new file mode 100644 index 00000000..28a18332 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Reactions.kt @@ -0,0 +1,213 @@ +package com.fire.app.ui.topicdetail + +import android.widget.ArrayAdapter +import android.widget.LinearLayout +import android.widget.ListView +import androidx.appcompat.app.AlertDialog +import androidx.core.widget.doAfterTextChanged +import androidx.lifecycle.lifecycleScope +import com.fire.app.R +import com.fire.app.core.ext.dp +import com.fire.app.core.ui.FireToast +import com.google.android.material.textfield.TextInputEditText +import com.google.android.material.textfield.TextInputLayout +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_topics.ReactionUsersGroupState +import uniffi.fire_uniffi_topics.TopicPostState + +internal fun TopicDetailActivity.showReactionUsers(post: TopicPostState) { + showReactionUsers(post, reactionId = null) +} + +internal fun TopicDetailActivity.showReactionUsers(post: TopicPostState, reactionId: String?) { + lifecycleScope.launch { + try { + val groups = sessionStore.fetchReactionUsers(post.id) + .filterForReaction(reactionId) + val message = if (groups.isEmpty()) { + getString(R.string.topic_detail_reaction_users_empty) + } else { + groups.joinToString("\n\n") { formatReactionUsersGroup(it) } + } + AlertDialog.Builder(this@showReactionUsers) + .setTitle( + reactionId + ?.let { ReactionPresentation.optionFor(it) } + ?.let { getString(R.string.topic_detail_reaction_users_title_for_reaction, it.symbol, it.label) } + ?: getString(R.string.topic_detail_reaction_users_title), + ) + .setMessage(message) + .setPositiveButton(android.R.string.ok, null) + .show() + } catch (e: Exception) { + FireToast.show( + binding.root, + e.localizedMessage ?: getString(R.string.topic_detail_reaction_users_error), + FireToast.Style.ERROR, + ) + } + } +} + +private fun List.filterForReaction(reactionId: String?): List { + val trimmedReactionId = reactionId?.trim()?.takeIf { it.isNotEmpty() } ?: return this + return filter { group -> group.id.equals(trimmedReactionId, ignoreCase = true) } +} + +internal fun TopicDetailActivity.formatReactionUsersGroup(group: ReactionUsersGroupState): String { + val users = group.users + .joinToString(", ") { user -> + user.name?.takeIf { it.isNotBlank() } ?: "@${user.username}" + } + .ifBlank { getString(R.string.topic_detail_reaction_users_empty) } + return getString( + R.string.topic_detail_reaction_users_group, + group.id, + group.count.toString(), + ) + "\n" + users +} + +internal fun TopicDetailActivity.showReactionPicker(post: TopicPostState) { + val currentReaction = post.currentUserReaction + if (currentReaction?.canUndo == false) { + FireToast.show( + binding.root, + R.string.topic_detail_reaction_locked, + FireToast.Style.WARNING, + ) + return + } + + lifecycleScope.launch { + val options = fullReactionOptionsForPost(post) + if (options.isEmpty()) { + FireToast.show( + binding.root, + R.string.topic_detail_reaction_empty, + FireToast.Style.INFO, + ) + return@launch + } + + val content = LinearLayout(this@showReactionPicker).apply { + orientation = LinearLayout.VERTICAL + setPadding(dp(20), dp(8), dp(20), 0) + } + val searchLayout = TextInputLayout(this@showReactionPicker).apply { + hint = getString(R.string.topic_detail_reaction_search_hint) + } + val searchInput = TextInputEditText(searchLayout.context).apply { + isSingleLine = true + } + searchLayout.addView( + searchInput, + LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ), + ) + val listView = ListView(this@showReactionPicker).apply { + divider = null + choiceMode = ListView.CHOICE_MODE_NONE + } + content.addView( + searchLayout, + LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT, + ), + ) + content.addView( + listView, + LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + dp(360), + ), + ) + + var visibleOptions = options + val adapter = ArrayAdapter( + this@showReactionPicker, + android.R.layout.simple_list_item_1, + visibleOptions.map { option -> reactionChoiceLabel(post, option) }.toMutableList(), + ) + fun submitVisibleOptions(query: String) { + visibleOptions = ReactionPresentation.filteredOptions(options, query) + adapter.clear() + adapter.addAll(visibleOptions.map { option -> reactionChoiceLabel(post, option) }) + adapter.notifyDataSetChanged() + } + listView.adapter = adapter + listView.setOnItemLongClickListener { _, _, position, _ -> + visibleOptions.getOrNull(position)?.let { option -> + showReactionUsers(post, option.id) + } + true + } + searchInput.doAfterTextChanged { text -> + submitVisibleOptions(text?.toString().orEmpty()) + } + + val dialog = AlertDialog.Builder(this@showReactionPicker) + .setTitle( + getString( + R.string.topic_detail_reaction_title, + post.postNumber.toString(), + ), + ) + .setView(content) + .setNegativeButton(android.R.string.cancel, null) + .create() + listView.setOnItemClickListener { _, _, position, _ -> + visibleOptions.getOrNull(position)?.let { option -> + viewModel?.toggleReaction(post, option.id) + dialog.dismiss() + } + } + dialog.show() + } +} + +internal fun TopicDetailActivity.reactionChoiceLabel(post: TopicPostState, option: ReactionOption): String { + val count = post.reactions + .firstOrNull { it.id.equals(option.id, ignoreCase = true) } + ?.count + ?: 0u + val label = getString( + R.string.topic_detail_reaction_choice, + "${option.symbol} ${option.label}", + count.toString(), + ) + return if (post.currentUserReaction?.id?.equals(option.id, ignoreCase = true) == true) { + getString(R.string.topic_detail_reaction_choice_selected, label) + } else { + label + } +} + +internal suspend fun TopicDetailActivity.fullReactionOptionsForPost(post: TopicPostState): List { + if (enabledReactionIds.isEmpty()) { + enabledReactionIds = runCatching { + sessionStore.snapshot().bootstrap.enabledReactionIds + }.getOrDefault(emptyList()) + refreshReactionRows() + } + return ReactionPresentation.fullOptions( + reactionIds = enabledReactionIds, + currentReactionId = post.currentUserReaction?.id, + ) +} + +internal fun TopicDetailActivity.loadEnabledReactionIds() { + lifecycleScope.launch { + enabledReactionIds = runCatching { + sessionStore.snapshot().bootstrap.enabledReactionIds + }.getOrDefault(emptyList()) + refreshReactionRows() + } +} + +internal fun TopicDetailActivity.refreshReactionRows() { + headerAdapter.refreshRows() + postListAdapter.refreshRows() +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Routing.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Routing.kt new file mode 100644 index 00000000..77f7c4a2 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Routing.kt @@ -0,0 +1,180 @@ +package com.fire.app.ui.topicdetail + +import android.content.Intent +import android.net.Uri +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.core.text.HtmlCompat +import androidx.lifecycle.lifecycleScope +import com.fire.app.R +import com.fire.app.richtext.FireCookedImage +import com.fire.app.ui.webview.FireInAppWebViewActivity +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_topics.TopicPostState + +internal fun TopicDetailActivity.handleRichTextLink(rawUrl: String) { + val uri = runCatching { Uri.parse(rawUrl) }.getOrNull() ?: return + profileUsernameFromUri(uri)?.let { username -> + showUserInfoSheet(username) + return + } + topicRouteFromUri(uri)?.let { route -> + TopicDetailActivity.start( + context = this, + topicId = route.first, + targetPostNumber = route.second, + ) + return + } + val url = uri.toString() + if (url.startsWith("http://") || url.startsWith("https://")) { + FireInAppWebViewActivity.start(this, url) + return + } + runCatching { + startActivity(Intent(Intent.ACTION_VIEW, uri)) + } +} + +internal fun TopicDetailActivity.profileUsernameFromUri(uri: Uri): String? { + if (uri.scheme == "fire" && (uri.host == "profile" || uri.host == "user")) { + return uri.pathSegments.firstOrNull() + } + if ((uri.scheme == "http" || uri.scheme == "https") && + uri.host?.endsWith("linux.do") == true && + uri.pathSegments.firstOrNull() == "u" + ) { + return uri.pathSegments.getOrNull(1) + } + return null +} + +internal fun TopicDetailActivity.topicRouteFromUri(uri: Uri): Pair? { + if (uri.scheme == "fire" && uri.host == "topic") { + val topicId = uri.pathSegments.getOrNull(0)?.toLongOrNull()?.takeIf { it > 0 } ?: return null + val postNumber = uri.pathSegments.getOrNull(1)?.toIntOrNull() ?: -1 + return topicId to postNumber + } + if ((uri.scheme != "http" && uri.scheme != "https") || + uri.host?.endsWith("linux.do") != true || + uri.pathSegments.firstOrNull() != "t" + ) { + return null + } + val tail = uri.pathSegments.drop(1) + if (tail.size == 2) { + val topicId = tail[0].toLongOrNull()?.takeIf { it > 0 } + val postNumber = tail[1].toIntOrNull() + if (topicId != null && postNumber != null) { + return topicId to postNumber + } + } + if (tail.size >= 3) { + val postNumber = tail.last().toIntOrNull() + val topicId = tail.getOrNull(tail.size - 2)?.toLongOrNull()?.takeIf { it > 0 } + if (topicId != null && postNumber != null) { + return topicId to postNumber + } + } + val topicId = tail.lastOrNull()?.toLongOrNull()?.takeIf { it > 0 } ?: return null + return topicId to -1 +} + +internal fun TopicDetailActivity.showImageViewer(image: FireCookedImage) { + TopicImagePreviewDialogFragment + .newInstance(image) + .show(supportFragmentManager, "topic_image_preview") +} + +internal fun TopicDetailActivity.showReplyContext(post: TopicPostState) { + val currentRoute = route ?: return + Toast.makeText( + this, + R.string.topic_detail_reply_context_loading, + Toast.LENGTH_SHORT, + ).show() + lifecycleScope.launch { + try { + val history = if (post.replyToPostNumber != null) { + sessionStore.fetchPostReplyHistory(post.id) + } else { + emptyList() + } + val directReplies = fetchDirectReplies(currentRoute.topicId.toULong(), post) + val message = replyContextMessage(history, directReplies) + AlertDialog.Builder(this@showReplyContext) + .setTitle( + getString( + R.string.topic_detail_reply_context_title, + post.postNumber.toString(), + ), + ) + .setMessage(message) + .setPositiveButton(android.R.string.ok, null) + .show() + } catch (e: Exception) { + Toast.makeText( + this@showReplyContext, + e.localizedMessage ?: getString(R.string.topic_detail_reply_context_empty), + Toast.LENGTH_SHORT, + ).show() + } + } +} + +internal suspend fun TopicDetailActivity.fetchDirectReplies( + topicId: ULong, + post: TopicPostState, +): List { + if (post.replyCount == 0u) { + return emptyList() + } + val replyIds = sessionStore.fetchPostReplyIds(post.id) + .filter { it > 0u } + .distinct() + if (replyIds.isEmpty()) { + return emptyList() + } + + return replyIds.chunked(TopicDetailActivity.REPLY_CONTEXT_POST_BATCH_SIZE).flatMap { batch -> + sessionStore.fetchTopicPosts(topicId, batch) + } +} + +internal fun TopicDetailActivity.replyContextMessage( + history: List, + directReplies: List, +): String { + if (history.isEmpty() && directReplies.isEmpty()) { + return getString(R.string.topic_detail_reply_context_empty) + } + + return buildString { + if (history.isNotEmpty()) { + appendLine(getString(R.string.topic_detail_reply_context_history)) + appendLine(history.joinToString("\n\n") { replyContextPostLine(it) }) + } + if (directReplies.isNotEmpty()) { + if (isNotEmpty()) appendLine() + appendLine(getString(R.string.topic_detail_reply_context_direct)) + appendLine(directReplies.joinToString("\n\n") { replyContextPostLine(it) }) + } + }.trim() +} + +internal fun TopicDetailActivity.replyContextPostLine(post: TopicPostState): String { + val author = post.name?.takeIf { it.isNotBlank() } ?: "@${post.username}" + val body = post.presentation?.plainText().orEmpty() + .lineSequence() + .map { it.trim() } + .filter { it.isNotEmpty() } + .joinToString(" ") + .take(180) + return "#${post.postNumber} $author\n$body" +} + +internal fun TopicDetailActivity.plainText(html: String): String { + return HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY) + .toString() + .trim() +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Scrolling.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Scrolling.kt new file mode 100644 index 00000000..05f96357 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Scrolling.kt @@ -0,0 +1,98 @@ +package com.fire.app.ui.topicdetail + +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView + +internal fun TopicDetailActivity.scheduleLoadMorePosts(rv: RecyclerView) { + if (loadMorePostsPosted) return + loadMorePostsPosted = true + rv.post { + loadMorePostsPosted = false + viewModel?.loadMorePosts() + } +} + +internal fun TopicDetailActivity.updateVisiblePostTimings() { + val tracker = timingTracker ?: return + val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return + val firstVisible = layoutManager.findFirstVisibleItemPosition() + val lastVisible = layoutManager.findLastVisibleItemPosition() + if (firstVisible == RecyclerView.NO_POSITION || lastVisible == RecyclerView.NO_POSITION) { + tracker.updateVisiblePostNumbers(emptySet()) + return + } + + val visiblePostNumbers = buildSet { + for (adapterPosition in firstVisible..lastVisible) { + visiblePostNumberForAdapterPosition(adapterPosition)?.let(::add) + } + } + if (visiblePostNumbers.isNotEmpty()) { + tracker.recordInteraction() + } + tracker.updateVisiblePostNumbers(visiblePostNumbers) +} + +internal fun TopicDetailActivity.visiblePostNumberForAdapterPosition(adapterPosition: Int): UInt? { + if (adapterPosition < 0) return null + if (adapterPosition < headerAdapter.itemCount) { + return viewModel?.detail?.value?.postStream?.posts + ?.minByOrNull { it.postNumber } + ?.postNumber + } + + val rowIndex = adapterPosition - headerAdapter.itemCount + return postListAdapter.currentList.getOrNull(rowIndex)?.post?.postNumber +} + +internal fun TopicDetailActivity.scrollToPostNumber(postNumber: UInt) { + pendingScrollTargetPostNumber = postNumber + val adapterPosition = if (postNumber <= 1u) { + 0 + } else { + val rowIndex = postListAdapter.currentList.indexOfFirst { + it.post.postNumber == postNumber + } + if (rowIndex < 0) return + headerAdapter.itemCount + rowIndex + } + pendingScrollTargetPostNumber = null + + recyclerView.post { + val layoutManager = recyclerView.layoutManager as? LinearLayoutManager + if (layoutManager != null) { + layoutManager.scrollToPositionWithOffset(adapterPosition, 0) + } else { + recyclerView.scrollToPosition(adapterPosition) + } + } +} + +internal fun TopicDetailActivity.updatePinnedToolbarTitle(firstVisible: Int) { + val shouldPin = firstVisible > 0 + if (shouldPin == toolbarTitlePinned) return + toolbarTitlePinned = shouldPin + binding.topicDetailToolbar.title = if (shouldPin) pinnedTopicTitle.orEmpty() else "" +} + +internal fun TopicDetailActivity.applySystemBarInsets() { + val root = binding.root + val initialLeft = root.paddingLeft + val initialTop = root.paddingTop + val initialRight = root.paddingRight + val initialBottom = root.paddingBottom + ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets -> + val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) + view.updatePadding( + left = initialLeft + systemBars.left, + top = initialTop + systemBars.top, + right = initialRight + systemBars.right, + bottom = initialBottom + systemBars.bottom, + ) + insets + } + ViewCompat.requestApplyInsets(root) +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Search.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Search.kt new file mode 100644 index 00000000..7bf25141 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Search.kt @@ -0,0 +1,60 @@ +package com.fire.app.ui.topicdetail + +import android.view.View + +internal fun TopicDetailActivity.showTopicSearch() { + searchOverlay.visibility = View.VISIBLE + searchOverlay.focusSearch() + recomputeTopicSearch() +} + +internal fun TopicDetailActivity.hideTopicSearch() { + topicSearchQuery = "" + topicSearchMatches = emptyList() + topicSearchIndex = -1 + searchOverlay.reset() + searchOverlay.visibility = View.GONE + applyTopicSearchHighlight() +} + +internal fun TopicDetailActivity.updateTopicSearchQuery(query: String) { + topicSearchQuery = query + recomputeTopicSearch(scrollToActiveMatch = true) +} + +internal fun TopicDetailActivity.recomputeTopicSearch(scrollToActiveMatch: Boolean = false) { + if (searchOverlay.visibility != View.VISIBLE && topicSearchQuery.isBlank()) { + return + } + val posts = viewModel?.detail?.value?.postStream?.posts.orEmpty() + val previousPostId = topicSearchMatches.getOrNull(topicSearchIndex)?.postId + topicSearchMatches = TopicDetailPostRows.searchMatches(topicSearchQuery, posts) + topicSearchIndex = when { + topicSearchMatches.isEmpty() -> -1 + previousPostId != null -> topicSearchMatches + .indexOfFirst { it.postId == previousPostId } + .takeIf { it >= 0 } + ?: 0 + else -> 0 + } + searchOverlay.updateResult(topicSearchIndex, topicSearchMatches.size) + applyTopicSearchHighlight() + if (scrollToActiveMatch) { + topicSearchMatches.getOrNull(topicSearchIndex)?.postNumber?.let { scrollToPostNumber(it) } + } +} + +internal fun TopicDetailActivity.navigateTopicSearch(delta: Int) { + if (topicSearchMatches.isEmpty()) return + val size = topicSearchMatches.size + topicSearchIndex = Math.floorMod(topicSearchIndex + delta, size) + searchOverlay.updateResult(topicSearchIndex, size) + applyTopicSearchHighlight() + topicSearchMatches[topicSearchIndex].postNumber.let { scrollToPostNumber(it) } +} + +internal fun TopicDetailActivity.applyTopicSearchHighlight() { + val highlightedPostId = topicSearchMatches.getOrNull(topicSearchIndex)?.postId + headerAdapter.highlightedPostId = highlightedPostId + postListAdapter.highlightedPostId = highlightedPostId +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+TopicVoting.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+TopicVoting.kt new file mode 100644 index 00000000..3ed01ad0 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+TopicVoting.kt @@ -0,0 +1,127 @@ +package com.fire.app.ui.topicdetail + +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.lifecycle.lifecycleScope +import com.fire.app.R +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_topics.TopicDetailState +import uniffi.fire_uniffi_topics.VotedUserState + +internal fun TopicDetailActivity.updateTopicNotificationToolbar(detail: TopicDetailState?) { + val item = notificationMenuItem ?: return + val isPrivateMessageThread = detail?.archetype + ?.trim() + ?.equals("private_message", ignoreCase = true) == true + item.isVisible = detail != null && !isPrivateMessageThread + if (detail == null || isPrivateMessageThread) return + + val level = detail.details.notificationLevel ?: 1 + val title = topicNotificationTitle(level) + item.title = getString(R.string.topic_detail_notification_button, title) + item.setIcon(topicNotificationIcon(level)) + item.isEnabled = true +} + +internal fun TopicDetailActivity.topicNotificationTitle(level: Int): String { + return when (level) { + 0 -> getString(R.string.topic_detail_notification_muted) + 2 -> getString(R.string.topic_detail_notification_tracking) + 3 -> getString(R.string.topic_detail_notification_watching) + else -> getString(R.string.topic_detail_notification_regular) + } +} + +internal fun TopicDetailActivity.topicNotificationIcon(level: Int): Int { + return when (level) { + 0 -> R.drawable.ic_notifications_off + 2, 3 -> R.drawable.ic_notifications_active + else -> R.drawable.ic_notifications + } +} + +internal fun TopicDetailActivity.showTopicNotificationOptions(detail: TopicDetailState) { + val options = listOf( + TopicNotificationOption( + level = 0, + title = getString(R.string.topic_detail_notification_muted), + ), + TopicNotificationOption( + level = 1, + title = getString(R.string.topic_detail_notification_regular), + ), + TopicNotificationOption( + level = 2, + title = getString(R.string.topic_detail_notification_tracking), + ), + TopicNotificationOption( + level = 3, + title = getString(R.string.topic_detail_notification_watching), + ), + ) + val labels = options.map { option -> + option.title + }.toTypedArray() + val selectedIndex = options.indexOfFirst { + it.level == (detail.details.notificationLevel ?: 1) + }.coerceAtLeast(0) + + AlertDialog.Builder(this) + .setTitle(R.string.topic_detail_notification_title) + .setSingleChoiceItems(labels, selectedIndex) { dialog, which -> + viewModel?.setTopicNotificationLevel(options[which].level) + dialog.dismiss() + } + .setNegativeButton(android.R.string.cancel, null) + .show() +} + +internal fun TopicDetailActivity.showTopicVoters(detail: TopicDetailState) { + Toast.makeText( + this, + R.string.topic_detail_vote_voters_loading, + Toast.LENGTH_SHORT, + ).show() + lifecycleScope.launch { + try { + val voters = sessionStore.fetchTopicVoters(detail.id) + showTopicVotersDialog(voters) + } catch (e: Exception) { + Toast.makeText( + this@showTopicVoters, + e.localizedMessage ?: getString(R.string.topic_detail_vote_voters_empty), + Toast.LENGTH_SHORT, + ).show() + } + } +} + +internal fun TopicDetailActivity.showTopicVotersDialog(voters: List) { + if (voters.isEmpty()) { + AlertDialog.Builder(this) + .setTitle(R.string.topic_detail_vote_voters_title) + .setMessage(R.string.topic_detail_vote_voters_empty) + .setPositiveButton(android.R.string.ok, null) + .show() + return + } + + val labels = voters.map { topicVoterLabel(it) }.toTypedArray() + AlertDialog.Builder(this) + .setTitle(R.string.topic_detail_vote_voters_title) + .setItems(labels) { _, which -> + voters.getOrNull(which)?.username?.let { showUserInfoSheet(it) } + } + .setPositiveButton(android.R.string.ok, null) + .show() +} + +internal fun TopicDetailActivity.topicVoterLabel(voter: VotedUserState): String { + val displayName = voter.name?.takeIf { it.isNotBlank() } ?: voter.username + return "$displayName\n@${voter.username}" +} + +internal data class TopicNotificationOption( + val level: Int, + val title: String, +) diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+UserInfo.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+UserInfo.kt new file mode 100644 index 00000000..7da9f339 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+UserInfo.kt @@ -0,0 +1,161 @@ +package com.fire.app.ui.topicdetail + +import android.view.Gravity +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import androidx.lifecycle.lifecycleScope +import com.fire.app.R +import com.fire.app.core.ext.dp +import com.fire.app.core.image.FireAvatarUrls +import com.fire.app.core.image.FireImageLoader +import com.fire.app.session.FireSessionStoreRepository +import com.fire.app.ui.composer.PrivateMessageComposerSheet +import com.fire.app.ui.profile.FireUserCardSheet +import com.google.android.material.bottomsheet.BottomSheetDialog +import kotlinx.coroutines.launch +import uniffi.fire_uniffi_user.UserProfileState +import uniffi.fire_uniffi_user.UserSummaryState + +internal fun TopicDetailActivity.showUserInfoSheet(username: String) { + lifecycleScope.launch { + FireUserCardSheet.show( + this@showUserInfoSheet, + FireSessionStoreRepository.get(this@showUserInfoSheet), + username, + ) + } +} + +internal fun TopicDetailActivity.showUserInfoSheetLegacy(username: String) { + val normalized = username.trim().removePrefix("@").takeIf { it.isNotEmpty() } ?: return + val dialog = BottomSheetDialog(this) + val content = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(dp(20), dp(18), dp(20), dp(24)) + } + val loading = TextView(this).apply { + text = getString(R.string.profile_loading) + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) + setTextColor(getColor(R.color.fire_text_secondary)) + } + content.addView(loading) + dialog.setContentView(ScrollView(this).apply { addView(content) }) + dialog.show() + + lifecycleScope.launch { + try { + val profile = sessionStore.fetchUserProfile(normalized) + val summary = runCatching { sessionStore.fetchUserSummary(normalized) }.getOrNull() + val currentUsername = runCatching { + sessionStore.snapshot().bootstrap.currentUsername + }.getOrNull()?.trim() + if (!dialog.isShowing) return@launch + renderUserInfoSheet( + content = content, + dialog = dialog, + profile = profile, + summary = summary, + isOwnProfile = currentUsername.equals(profile.username.trim(), ignoreCase = true), + ) + } catch (e: Exception) { + if (!dialog.isShowing) return@launch + content.removeAllViews() + content.addView(TextView(this@showUserInfoSheetLegacy).apply { + text = e.localizedMessage ?: getString(R.string.profile_error) + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) + setTextColor(getColor(R.color.fire_text_secondary)) + }) + } + } +} + +internal fun TopicDetailActivity.renderUserInfoSheet( + content: LinearLayout, + dialog: BottomSheetDialog, + profile: UserProfileState, + summary: UserSummaryState?, + isOwnProfile: Boolean, +) { + content.removeAllViews() + val header = LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + } + val avatar = ImageView(this).apply { + layoutParams = LinearLayout.LayoutParams(dp(64), dp(64)) + scaleType = ImageView.ScaleType.CENTER_CROP + contentDescription = getString(R.string.content_desc_avatar) + } + profile.avatarTemplate?.takeIf { it.isNotBlank() }?.let { template -> + FireAvatarUrls.build(template)?.let { url -> + FireImageLoader.load(url, avatar) + } + } + val titleStack = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(dp(14), 0, 0, 0) + } + titleStack.addView(TextView(this).apply { + text = profile.name?.takeIf { it.isNotBlank() } ?: profile.username + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Title) + setTextColor(getColor(R.color.fire_text_primary)) + }) + titleStack.addView(TextView(this).apply { + text = "@${profile.username} · ${profile.trustLevelLabel}" + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) + setTextColor(getColor(R.color.fire_text_secondary)) + }) + header.addView(avatar) + header.addView(titleStack) + content.addView(header) + + val stats = summary?.stats + val statText = buildList { + add(getString(R.string.profile_topics_count, (stats?.topicCount ?: 0u).toString())) + add(getString(R.string.profile_posts_count, (stats?.postCount ?: 0u).toString())) + add(getString(R.string.profile_likes_received, (stats?.likesReceived ?: 0u).toString())) + add(getString(R.string.profile_followers_count, profile.totalFollowers.toString())) + }.joinToString("\n") + content.addView(TextView(this).apply { + text = statText + setPadding(0, dp(16), 0, 0) + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) + setTextColor(getColor(R.color.fire_text_primary)) + }) + + profile.bioPlainText?.trim()?.takeIf { it.isNotEmpty() }?.let { bio -> + content.addView(TextView(this).apply { + text = bio + setPadding(0, dp(14), 0, 0) + setTextIsSelectable(true) + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body2) + setTextColor(getColor(R.color.fire_text_secondary)) + }) + } + + if (!isOwnProfile && profile.canSendPrivateMessageToUser) { + content.addView(TextView(this).apply { + text = getString(R.string.profile_send_private_message) + gravity = Gravity.CENTER + setPadding(dp(12), dp(10), dp(12), dp(10)) + setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Button) + setTextColor(getColor(R.color.fire_accent)) + setOnClickListener { + dialog.dismiss() + PrivateMessageComposerSheet.newInstance( + targetUsername = profile.username, + displayName = profile.name?.takeIf { it.isNotBlank() } ?: profile.username, + onPrivateMessageCreated = { topicId, title -> + TopicDetailActivity.start( + context = this@renderUserInfoSheet, + topicId = topicId.toLong(), + topicTitle = title, + ) + }, + ).show(supportFragmentManager, "private_message_composer") + } + }) + } +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt index 7850265e..9de434b9 100644 --- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt @@ -1,111 +1,60 @@ package com.fire.app.ui.topicdetail -import android.Manifest -import android.app.DatePickerDialog -import android.app.TimePickerDialog import android.content.Context import android.content.Intent -import android.content.pm.PackageManager import android.net.Uri -import android.os.Build import android.os.Bundle -import android.view.Gravity import android.view.MenuItem import android.view.View -import android.widget.ArrayAdapter -import android.widget.EditText -import android.widget.ImageView -import android.widget.ListView -import android.widget.LinearLayout -import android.widget.ScrollView -import android.widget.Toast import android.widget.ProgressBar -import android.widget.Spinner import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels -import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity -import androidx.core.content.ContextCompat -import androidx.core.text.HtmlCompat -import androidx.core.view.ViewCompat -import androidx.core.view.WindowInsetsCompat -import androidx.core.view.updatePadding -import androidx.core.widget.doAfterTextChanged import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.fire.app.FireApplication import com.fire.app.R -import com.fire.app.displayName +import com.fire.app.core.ui.FireToast import com.fire.app.databinding.ActivityTopicDetailBinding -import com.fire.app.richtext.FireCookedImage import com.fire.app.session.FireSessionStore import com.fire.app.session.FireSessionStoreRepository -import com.fire.app.ui.profile.FireUserCardSheet -import com.fire.app.core.image.FireAvatarUrls -import com.fire.app.core.ui.FireToast -import com.fire.app.ui.composer.ComposerTagAssist -import com.fire.app.ui.composer.PrivateMessageComposerSheet -import com.fire.app.ui.composer.QuoteMarkdown -import com.fire.app.ui.composer.ReplyComposerSheet -import com.fire.app.ui.home.HomeTopicDetailPatchRepository -import com.fire.app.ui.webview.FireInAppWebViewActivity -import com.fire.app.core.ext.dp -import com.fire.app.core.image.FireImageLoader -import com.google.android.material.bottomsheet.BottomSheetDialog -import com.google.android.material.textfield.TextInputEditText -import com.google.android.material.textfield.TextInputLayout -import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch -import uniffi.fire_uniffi_session.TopicCategoryState -import uniffi.fire_uniffi_topics.PostActionTypeState -import uniffi.fire_uniffi_topics.PostFlagRequestState -import uniffi.fire_uniffi_topics.ReactionUsersGroupState -import uniffi.fire_uniffi_topics.TopicDetailState -import uniffi.fire_uniffi_topics.TopicPostState -import uniffi.fire_uniffi_topics.VotedUserState -import uniffi.fire_uniffi_user.UserProfileState -import uniffi.fire_uniffi_user.UserSummaryState -import java.time.Instant -import java.time.ZoneId -import java.time.ZonedDateTime -import java.time.format.DateTimeFormatter -import java.time.format.FormatStyle class TopicDetailActivity : AppCompatActivity() { - private lateinit var binding: ActivityTopicDetailBinding - private lateinit var recyclerView: RecyclerView - private lateinit var loadingView: ProgressBar - private lateinit var errorView: View - private lateinit var errorText: TextView - private lateinit var retryButton: View + internal lateinit var binding: ActivityTopicDetailBinding + internal lateinit var recyclerView: RecyclerView + internal lateinit var loadingView: ProgressBar + internal lateinit var errorView: View + internal lateinit var errorText: TextView + internal lateinit var retryButton: View private lateinit var quickReplyBar: View - private lateinit var searchOverlay: TopicSearchOverlay - private var pinnedTopicTitle: String? = null - private var toolbarTitlePinned = false - - private var viewModel: TopicDetailViewModel? = null - private var route: TopicDetailRoute? = null - private lateinit var sessionStore: FireSessionStore - - private lateinit var headerAdapter: HeaderAdapter - private lateinit var postListAdapter: PostListAdapter - private val loadingFooterAdapter = LoadingFooterAdapter() - private var loadMorePostsPosted = false - private var pendingScrollTargetPostNumber: UInt? = null - private var enabledReactionIds: List = emptyList() - private var timingTracker: TopicTimingTracker? = null + internal lateinit var searchOverlay: TopicSearchOverlay + internal var pinnedTopicTitle: String? = null + internal var toolbarTitlePinned = false + + internal var viewModel: TopicDetailViewModel? = null + internal var route: TopicDetailRoute? = null + internal lateinit var sessionStore: FireSessionStore + + internal lateinit var headerAdapter: HeaderAdapter + internal lateinit var postListAdapter: PostListAdapter + internal val loadingFooterAdapter = LoadingFooterAdapter() + internal var loadMorePostsPosted = false + internal var pendingScrollTargetPostNumber: UInt? = null + internal var enabledReactionIds: List = emptyList() + internal var timingTracker: TopicTimingTracker? = null private var searchMenuItem: MenuItem? = null - private var notificationMenuItem: MenuItem? = null - private var topicSearchQuery: String = "" - private var topicSearchMatches: List = emptyList() - private var topicSearchIndex: Int = -1 - private val pendingBookmarkReminders = mutableMapOf() - private var pendingNotificationPermissionRequest: BookmarkReminderRequest? = null - private val notificationPermissionLauncher = registerForActivityResult( + internal var notificationMenuItem: MenuItem? = null + internal var topicSearchQuery: String = "" + internal var topicSearchMatches: List = emptyList() + internal var topicSearchIndex: Int = -1 + internal val pendingBookmarkReminders = mutableMapOf() + internal var pendingNotificationPermissionRequest: BookmarkReminderRequest? = null + internal val notificationPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission(), ) { granted -> val request = pendingNotificationPermissionRequest @@ -161,7 +110,7 @@ class TopicDetailActivity : AppCompatActivity() { setIcon(R.drawable.ic_notifications) setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) setOnMenuItemClickListener { - viewModel?.detail?.value?.let(::showTopicNotificationOptions) + viewModel?.detail?.value?.let { showTopicNotificationOptions(it) } true } isVisible = false @@ -182,29 +131,29 @@ class TopicDetailActivity : AppCompatActivity() { val postCallbacks = PostRowCallbacks( reactionIds = { enabledReactionIds }, - onReplyClick = ::showReplyComposerForPost, - onQuoteClick = ::showQuoteReplyComposerForPost, + onReplyClick = { showReplyComposerForPost(it) }, + onQuoteClick = { showQuoteReplyComposerForPost(it) }, onHeartClick = { post -> viewModel?.toggleHeart(post) }, - onReactClick = ::showReactionPicker, - onBookmarkClick = ::showPostBookmarkEditor, + onReactClick = { showReactionPicker(it) }, + onBookmarkClick = { showPostBookmarkEditor(it) }, onVotePoll = { post, poll, options -> viewModel?.votePoll(post, poll, options) }, onUnvotePoll = { post, poll -> viewModel?.unvotePoll(post, poll) }, - onReactionsClick = ::showReactionUsers, - onReplyContextClick = ::showReplyContext, + onReactionsClick = { showReactionUsers(it) }, + onReplyContextClick = { showReplyContext(it) }, onMoreRepliesClick = { post -> viewModel?.expandReplyThread(post) }, - onDeletePostClick = ::confirmDeletePost, - onRecoverPostClick = ::confirmRecoverPost, - onFlagPostClick = ::showFlagPostOptions, - onEditPostClick = ::showPostEditor, - onImageClick = ::showImageViewer, - onAuthorClick = ::showUserInfoSheet, - onLinkClick = ::handleRichTextLink, + onDeletePostClick = { confirmDeletePost(it) }, + onRecoverPostClick = { confirmRecoverPost(it) }, + onFlagPostClick = { showFlagPostOptions(it) }, + onEditPostClick = { showPostEditor(it) }, + onImageClick = { showImageViewer(it) }, + onAuthorClick = { showUserInfoSheet(it) }, + onLinkClick = { handleRichTextLink(it) }, ) headerAdapter = HeaderAdapter( callbacks = postCallbacks, onToggleTopicVote = { viewModel?.toggleTopicVote() }, - onShowTopicVoters = ::showTopicVoters, - onEditTopicClick = ::showTopicEditor, + onShowTopicVoters = { showTopicVoters(it) }, + onEditTopicClick = { showTopicEditor(it) }, ) postListAdapter = PostListAdapter(postCallbacks) @@ -213,10 +162,10 @@ class TopicDetailActivity : AppCompatActivity() { recyclerView.adapter = concatAdapter loadEnabledReactionIds() searchOverlay.bind( - onQueryChanged = ::updateTopicSearchQuery, + onQueryChanged = { updateTopicSearchQuery(it) }, onPrevious = { navigateTopicSearch(-1) }, onNext = { navigateTopicSearch(1) }, - onClose = ::hideTopicSearch, + onClose = { hideTopicSearch() }, ) recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { @@ -304,1488 +253,7 @@ class TopicDetailActivity : AppCompatActivity() { super.onDestroy() } - private fun observeViewModel() { - val vm = viewModel ?: return - lifecycleScope.launch { - vm.isLoading.collectLatest { loading -> - loadingView.visibility = if (loading) View.VISIBLE else View.GONE - recyclerView.visibility = if (loading && vm.postRows.value.isEmpty()) View.GONE else View.VISIBLE - } - } - - lifecycleScope.launch { - vm.errorMessage.collectLatest { error -> - if (error != null) { - errorView.visibility = View.VISIBLE - errorText.text = error - if (vm.postRows.value.isEmpty() && vm.detail.value == null) { - recyclerView.visibility = View.GONE - } - } else { - errorView.visibility = View.GONE - recyclerView.visibility = if (vm.isLoading.value && vm.postRows.value.isEmpty()) { - View.GONE - } else { - View.VISIBLE - } - } - } - } - - lifecycleScope.launch { - vm.isCloudflareError.collectLatest { isCloudflare -> - (retryButton as? com.google.android.material.button.MaterialButton)?.text = - getString( - if (isCloudflare) R.string.action_cloudflare_verify else R.string.action_retry, - ) - } - } - - lifecycleScope.launch { - vm.detail.collectLatest { detail -> - headerAdapter.detail = detail - if (detail != null) { - pinnedTopicTitle = detail.title.trim() - if (toolbarTitlePinned) { - binding.topicDetailToolbar.title = pinnedTopicTitle - } - } - updateTopicNotificationToolbar(detail) - recomputeTopicSearch() - updateVisiblePostTimings() - } - } - - lifecycleScope.launch { - vm.topicAiSummary.collectLatest { summary -> - headerAdapter.aiSummary = summary - } - } - - lifecycleScope.launch { - vm.postRows.collectLatest { rows -> - postListAdapter.submitList(rows) { - updateVisiblePostTimings() - pendingScrollTargetPostNumber?.let { scrollToPostNumber(it) } - } - recomputeTopicSearch() - } - } - - lifecycleScope.launch { - vm.scrollTargetPostNumber.collectLatest { postNumber -> - scrollToPostNumber(postNumber) - } - } - - lifecycleScope.launch { - vm.actionError.collectLatest { error -> - FireToast.show(binding.root, error, FireToast.Style.ERROR) - } - } - - lifecycleScope.launch { - vm.bookmarkEvents.collectLatest { event -> - when (event) { - is BookmarkEvent.Saved -> { - FireToast.show( - binding.root, - R.string.topic_detail_bookmark_saved, - FireToast.Style.SUCCESS, - ) - val key = BookmarkReminderKey(event.bookmarkableId, event.bookmarkableType) - pendingBookmarkReminders.remove(key)?.let { request -> - scheduleBookmarkReminderAfterSave(request.copy(reminderAt = event.reminderAt)) - } - } - is BookmarkEvent.Deleted -> { - FireToast.show( - binding.root, - R.string.topic_detail_bookmark_deleted, - FireToast.Style.INFO, - ) - val key = BookmarkReminderKey(event.bookmarkableId, event.bookmarkableType) - pendingBookmarkReminders.remove(key) - BookmarkReminderScheduler.cancel( - this@TopicDetailActivity, - event.bookmarkableId, - event.bookmarkableType, - ) - } - } - } - } - - lifecycleScope.launch { - vm.isLoadingMore.collectLatest { loadingMore -> - loadingFooterAdapter.isLoading = loadingMore - } - } - } - - private fun showReplyComposerForPost(post: TopicPostState) { - showReplyComposer(replyToPostNumber = post.postNumber.toInt()) - } - - private fun showQuoteReplyComposerForPost(post: TopicPostState) { - val currentRoute = route ?: return - val quote = QuoteMarkdown.build( - username = post.username, - postNumber = post.postNumber, - topicId = currentRoute.topicId.toULong(), - plainText = post.presentation?.plainText().orEmpty(), - ) - if (quote == null) { - FireToast.show(binding.root, R.string.topic_detail_quote_empty, FireToast.Style.INFO) - return - } - showReplyComposer( - replyToPostNumber = post.postNumber.toInt(), - initialBody = quote, - ) - } - - private fun updateTopicNotificationToolbar(detail: TopicDetailState?) { - val item = notificationMenuItem ?: return - val isPrivateMessageThread = detail?.archetype - ?.trim() - ?.equals("private_message", ignoreCase = true) == true - item.isVisible = detail != null && !isPrivateMessageThread - if (detail == null || isPrivateMessageThread) return - - val level = detail.details.notificationLevel ?: 1 - val title = topicNotificationTitle(level) - item.title = getString(R.string.topic_detail_notification_button, title) - item.setIcon(topicNotificationIcon(level)) - item.isEnabled = true - } - - private fun topicNotificationTitle(level: Int): String { - return when (level) { - 0 -> getString(R.string.topic_detail_notification_muted) - 2 -> getString(R.string.topic_detail_notification_tracking) - 3 -> getString(R.string.topic_detail_notification_watching) - else -> getString(R.string.topic_detail_notification_regular) - } - } - - private fun topicNotificationIcon(level: Int): Int { - return when (level) { - 0 -> R.drawable.ic_notifications_off - 2, 3 -> R.drawable.ic_notifications_active - else -> R.drawable.ic_notifications - } - } - - private fun showTopicSearch() { - searchOverlay.visibility = View.VISIBLE - searchOverlay.focusSearch() - recomputeTopicSearch() - } - - private fun hideTopicSearch() { - topicSearchQuery = "" - topicSearchMatches = emptyList() - topicSearchIndex = -1 - searchOverlay.reset() - searchOverlay.visibility = View.GONE - applyTopicSearchHighlight() - } - - private fun updateTopicSearchQuery(query: String) { - topicSearchQuery = query - recomputeTopicSearch(scrollToActiveMatch = true) - } - - private fun recomputeTopicSearch(scrollToActiveMatch: Boolean = false) { - if (searchOverlay.visibility != View.VISIBLE && topicSearchQuery.isBlank()) { - return - } - val posts = viewModel?.detail?.value?.postStream?.posts.orEmpty() - val previousPostId = topicSearchMatches.getOrNull(topicSearchIndex)?.postId - topicSearchMatches = TopicDetailPostRows.searchMatches(topicSearchQuery, posts) - topicSearchIndex = when { - topicSearchMatches.isEmpty() -> -1 - previousPostId != null -> topicSearchMatches - .indexOfFirst { it.postId == previousPostId } - .takeIf { it >= 0 } - ?: 0 - else -> 0 - } - searchOverlay.updateResult(topicSearchIndex, topicSearchMatches.size) - applyTopicSearchHighlight() - if (scrollToActiveMatch) { - topicSearchMatches.getOrNull(topicSearchIndex)?.postNumber?.let(::scrollToPostNumber) - } - } - - private fun navigateTopicSearch(delta: Int) { - if (topicSearchMatches.isEmpty()) return - val size = topicSearchMatches.size - topicSearchIndex = Math.floorMod(topicSearchIndex + delta, size) - searchOverlay.updateResult(topicSearchIndex, size) - applyTopicSearchHighlight() - topicSearchMatches[topicSearchIndex].postNumber.let(::scrollToPostNumber) - } - - private fun applyTopicSearchHighlight() { - val highlightedPostId = topicSearchMatches.getOrNull(topicSearchIndex)?.postId - headerAdapter.highlightedPostId = highlightedPostId - postListAdapter.highlightedPostId = highlightedPostId - } - - private fun updatePinnedToolbarTitle(firstVisible: Int) { - val shouldPin = firstVisible > 0 - if (shouldPin == toolbarTitlePinned) return - toolbarTitlePinned = shouldPin - binding.topicDetailToolbar.title = if (shouldPin) pinnedTopicTitle.orEmpty() else "" - } - - private fun showReplyComposer(replyToPostNumber: Int?, initialBody: String? = null) { - val currentRoute = route ?: return - val sheet = ReplyComposerSheet.newInstance( - topicId = currentRoute.topicId, - replyToPostNumber = replyToPostNumber, - initialBody = initialBody, - ) { - viewModel?.loadTopicDetail( - topicId = currentRoute.topicId.toULong(), - targetPostNumber = replyToPostNumber?.toUInt(), - ) - } - sheet.show(supportFragmentManager, "reply_composer") - } - - private fun confirmDeletePost(post: TopicPostState) { - AlertDialog.Builder(this) - .setTitle( - getString( - R.string.topic_detail_delete_confirm_title, - post.postNumber.toString(), - ), - ) - .setMessage(R.string.topic_detail_delete_confirm_message) - .setPositiveButton(R.string.topic_detail_delete_post) { _, _ -> - viewModel?.deletePost(post) - } - .setNegativeButton(android.R.string.cancel, null) - .show() - } - - private fun confirmRecoverPost(post: TopicPostState) { - AlertDialog.Builder(this) - .setTitle( - getString( - R.string.topic_detail_recover_confirm_title, - post.postNumber.toString(), - ), - ) - .setMessage(R.string.topic_detail_recover_confirm_message) - .setPositiveButton(R.string.topic_detail_recover_post) { _, _ -> - viewModel?.recoverPost(post) - } - .setNegativeButton(android.R.string.cancel, null) - .show() - } - - private fun showPostEditor(post: TopicPostState) { - Toast.makeText(this, R.string.topic_detail_edit_post_loading, Toast.LENGTH_SHORT).show() - lifecycleScope.launch { - try { - val editablePost = sessionStore.fetchPost(post.id) - val raw = editablePost.raw - ?.takeIf { it.isNotBlank() } - ?: throw IllegalStateException(getString(R.string.topic_detail_edit_post_error)) - showPostEditorDialog(post, raw) - } catch (e: Exception) { - Toast.makeText( - this@TopicDetailActivity, - e.localizedMessage ?: getString(R.string.topic_detail_edit_post_error), - Toast.LENGTH_SHORT, - ).show() - } - } - } - - private fun showPostEditorDialog(post: TopicPostState, raw: String) { - val bodyInput = EditText(this).apply { - setText(raw) - hint = getString(R.string.topic_detail_edit_post_body_hint) - minLines = 8 - gravity = android.view.Gravity.TOP - } - val reasonInput = EditText(this).apply { - hint = getString(R.string.topic_detail_edit_post_reason_hint) - setSingleLine(true) - } - val content = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setPadding(48, 8, 48, 0) - addView(bodyInput) - addView(reasonInput) - } - - val dialog = AlertDialog.Builder(this) - .setTitle(getString(R.string.topic_detail_edit_post_title, post.postNumber.toString())) - .setView(content) - .setPositiveButton(R.string.topic_detail_edit_save, null) - .setNegativeButton(android.R.string.cancel, null) - .create() - dialog.setOnShowListener { - dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - val nextRaw = bodyInput.text.toString() - if (nextRaw.isBlank()) { - Toast.makeText( - this, - R.string.topic_detail_edit_post_error, - Toast.LENGTH_SHORT, - ).show() - return@setOnClickListener - } - viewModel?.updatePost( - post = post, - raw = nextRaw, - editReason = reasonInput.text.toString(), - ) - dialog.dismiss() - } - } - dialog.show() - } - - private fun showPostBookmarkEditor(post: TopicPostState) { - showBookmarkEditor( - bookmarkableId = post.id, - bookmarkableType = "Post", - bookmarkId = post.bookmarkId, - bookmarkName = post.bookmarkName, - bookmarkReminderAt = post.bookmarkReminderAt, - targetPostNumber = post.postNumber, - ) - } - - private fun showBookmarkEditor( - bookmarkableId: ULong, - bookmarkableType: String, - bookmarkId: ULong?, - bookmarkName: String?, - bookmarkReminderAt: String?, - targetPostNumber: UInt?, - ) { - val nameInput = EditText(this).apply { - setText(bookmarkName.orEmpty()) - hint = getString(R.string.topic_detail_bookmark_name_hint) - setSingleLine(true) - } - val reminderSelection = BookmarkReminderSelection.from(bookmarkReminderAt) - val reminderToggle = androidx.appcompat.widget.SwitchCompat(this).apply { - text = getString(R.string.topic_detail_bookmark_reminder_label) - isChecked = reminderSelection.hasReminder - } - val reminderButton = TextView(this).apply { - setPadding(0, dp(12), 0, dp(4)) - text = reminderSelection.displayText(this@TopicDetailActivity) - setTextColor(getColor(R.color.fire_accent)) - setOnClickListener { - showBookmarkReminderDatePicker(reminderSelection, this) - } - } - reminderButton.visibility = if (reminderSelection.hasReminder) View.VISIBLE else View.GONE - reminderToggle.setOnCheckedChangeListener { _, isChecked -> - reminderSelection.hasReminder = isChecked - if (isChecked && reminderSelection.dateTime == null) { - reminderSelection.dateTime = ZonedDateTime.now().plusHours(1) - } - reminderButton.text = reminderSelection.displayText(this) - reminderButton.visibility = if (isChecked) View.VISIBLE else View.GONE - } - val content = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setPadding(dp(24), dp(8), dp(24), 0) - addView(nameInput) - addView(reminderToggle) - addView(reminderButton) - } - - val dialog = AlertDialog.Builder(this) - .setTitle( - if (bookmarkId == null) { - R.string.topic_detail_bookmark_add_title - } else { - R.string.topic_detail_bookmark_edit_title - }, - ) - .setView(content) - .setPositiveButton(R.string.topic_detail_bookmark_save, null) - .setNegativeButton(android.R.string.cancel, null) - .apply { - if (bookmarkId != null) { - setNeutralButton(R.string.topic_detail_bookmark_delete, null) - } - } - .create() - dialog.setOnShowListener { - dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - val reminderAt = reminderSelection.reminderAt() - val key = BookmarkReminderKey(bookmarkableId, bookmarkableType) - pendingBookmarkReminders[key] = BookmarkReminderRequest( - bookmarkableId = bookmarkableId, - bookmarkableType = bookmarkableType, - topicId = route?.topicId ?: -1L, - postNumber = targetPostNumber?.toInt() ?: -1, - title = bookmarkReminderTitle(bookmarkableType, targetPostNumber), - reminderAt = reminderAt, - ) - viewModel?.saveBookmark( - bookmarkableId = bookmarkableId, - bookmarkableType = bookmarkableType, - bookmarkId = bookmarkId, - name = nameInput.text.toString(), - reminderAt = reminderAt, - targetPostNumber = targetPostNumber, - ) - dialog.dismiss() - } - if (bookmarkId != null) { - dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener { - viewModel?.deleteBookmark( - bookmarkId = bookmarkId, - bookmarkableId = bookmarkableId, - bookmarkableType = bookmarkableType, - targetPostNumber = targetPostNumber, - ) - dialog.dismiss() - } - } - } - dialog.show() - } - - private fun showBookmarkReminderDatePicker( - selection: BookmarkReminderSelection, - target: TextView, - ) { - val current = selection.dateTime ?: ZonedDateTime.now().plusHours(1) - DatePickerDialog( - this, - { _, year, month, dayOfMonth -> - TimePickerDialog( - this, - { _, hourOfDay, minute -> - val selectedDateTime = current - .withYear(year) - .withMonth(month + 1) - .withDayOfMonth(dayOfMonth) - .withHour(hourOfDay) - .withMinute(minute) - .withSecond(0) - .withNano(0) - selection.dateTime = selectedDateTime.takeIf { it.isAfter(ZonedDateTime.now()) } - ?: ZonedDateTime.now().plusMinutes(1).withSecond(0).withNano(0) - target.text = selection.displayText(this) - }, - current.hour, - current.minute, - true, - ).show() - }, - current.year, - current.monthValue - 1, - current.dayOfMonth, - ).apply { - datePicker.minDate = System.currentTimeMillis() - }.show() - } - - private fun scheduleBookmarkReminderAfterSave(request: BookmarkReminderRequest) { - if (request.reminderAt.isNullOrBlank()) { - BookmarkReminderScheduler.sync(this, request) - return - } - if ( - Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && - ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != - PackageManager.PERMISSION_GRANTED - ) { - pendingNotificationPermissionRequest = request - notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) - return - } - BookmarkReminderScheduler.sync(this, request) - } - - private fun bookmarkReminderTitle(bookmarkableType: String, targetPostNumber: UInt?): String { - val detail = viewModel?.detail?.value - val title = detail?.title?.trim()?.takeIf { it.isNotEmpty() } - ?: route?.title?.trim()?.takeIf { it.isNotEmpty() } - ?: getString(R.string.topic_detail_title_fallback, route?.topicId?.toString().orEmpty()) - return if (bookmarkableType.equals("Post", ignoreCase = true) && targetPostNumber != null) { - "$title #$targetPostNumber" - } else { - title - } - } - - private fun showFlagPostOptions(post: TopicPostState) { - lifecycleScope.launch { - try { - val options = sessionStore.fetchPostActionTypes() - .mapNotNull(::postFlagOption) - .ifEmpty { fallbackPostFlagOptions() } - val labels = options.map { option -> - if (option.detail.isBlank()) { - option.title - } else { - "${option.title}\n${option.detail}" - } - }.toTypedArray() - AlertDialog.Builder(this@TopicDetailActivity) - .setTitle( - getString( - R.string.topic_detail_flag_type_title, - post.postNumber.toString(), - ), - ) - .setItems(labels) { _, which -> - promptFlagPost(post, options[which]) - } - .setNegativeButton(android.R.string.cancel, null) - .show() - } catch (e: Exception) { - Toast.makeText( - this@TopicDetailActivity, - e.localizedMessage ?: getString(R.string.topic_detail_flag_message_required), - Toast.LENGTH_SHORT, - ).show() - } - } - } - - private fun postFlagOption(type: PostActionTypeState): PostFlagOption? { - if (!type.isFlag || !type.enabled) return null - if (type.appliesTo.isNotEmpty() && !type.appliesTo.contains("Post")) return null - - val detail = type.description.ifBlank { type.shortDescription.orEmpty() } - return PostFlagOption( - id = type.id, - title = type.name.ifBlank { fallbackFlagTitle(type.nameKey, type.id) }, - detail = plainText(detail), - requireMessage = type.requireMessage, - ) - } - - private fun fallbackPostFlagOptions(): List { - return listOf( - PostFlagOption(3u, "Off topic", "This post is off topic.", false), - PostFlagOption(4u, "Inappropriate", "This post is inappropriate.", false), - PostFlagOption(8u, "Spam", "This post looks like spam.", false), - PostFlagOption(7u, "Notify moderators", "Add details for moderators.", true), - ) - } - - private fun fallbackFlagTitle(nameKey: String, id: UInt): String { - return when (nameKey) { - "off_topic" -> "Off topic" - "inappropriate" -> "Inappropriate" - "spam" -> "Spam" - "notify_moderators" -> "Notify moderators" - else -> nameKey.ifBlank { "#$id" } - } - } - - private fun promptFlagPost(post: TopicPostState, option: PostFlagOption) { - if (option.requireMessage) { - val input = EditText(this).apply { - hint = getString(R.string.topic_detail_flag_message_hint) - minLines = 3 - } - AlertDialog.Builder(this) - .setTitle(getString(R.string.topic_detail_flag_message_title, option.title)) - .setView(input) - .setPositiveButton(R.string.topic_detail_flag_submit) { _, _ -> - val message = input.text.toString().trim() - if (message.isBlank()) { - Toast.makeText( - this, - R.string.topic_detail_flag_message_required, - Toast.LENGTH_SHORT, - ).show() - } else { - submitFlagPost(post, option, message) - } - } - .setNegativeButton(android.R.string.cancel, null) - .show() - } else { - AlertDialog.Builder(this) - .setTitle(getString(R.string.topic_detail_flag_confirm_title, option.title)) - .setMessage(option.detail.ifBlank { getString(R.string.topic_detail_flag_confirm_message) }) - .setPositiveButton(R.string.topic_detail_flag_submit) { _, _ -> - submitFlagPost(post, option, null) - } - .setNegativeButton(android.R.string.cancel, null) - .show() - } - } - - private fun submitFlagPost( - post: TopicPostState, - option: PostFlagOption, - message: String?, - ) { - lifecycleScope.launch { - try { - sessionStore.flagPost( - PostFlagRequestState( - postId = post.id, - flagTypeId = option.id, - message = message, - ), - ) - Toast.makeText( - this@TopicDetailActivity, - R.string.topic_detail_flag_submitted, - Toast.LENGTH_SHORT, - ).show() - } catch (e: Exception) { - Toast.makeText( - this@TopicDetailActivity, - e.localizedMessage ?: getString(R.string.topic_detail_action_error), - Toast.LENGTH_SHORT, - ).show() - } - } - } - - private fun plainText(html: String): String { - return HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY) - .toString() - .trim() - } - - private fun handleRichTextLink(rawUrl: String) { - val uri = runCatching { Uri.parse(rawUrl) }.getOrNull() ?: return - profileUsernameFromUri(uri)?.let { username -> - showUserInfoSheet(username) - return - } - topicRouteFromUri(uri)?.let { route -> - TopicDetailActivity.start( - context = this, - topicId = route.first, - targetPostNumber = route.second, - ) - return - } - val url = uri.toString() - if (url.startsWith("http://") || url.startsWith("https://")) { - FireInAppWebViewActivity.start(this, url) - return - } - runCatching { - startActivity(Intent(Intent.ACTION_VIEW, uri)) - } - } - - private fun showUserInfoSheet(username: String) { - lifecycleScope.launch { - FireUserCardSheet.show( - this@TopicDetailActivity, - FireSessionStoreRepository.get(this@TopicDetailActivity), - username, - ) - } - } - - private fun showUserInfoSheetLegacy(username: String) { - val normalized = username.trim().removePrefix("@").takeIf { it.isNotEmpty() } ?: return - val dialog = BottomSheetDialog(this) - val content = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setPadding(dp(20), dp(18), dp(20), dp(24)) - } - val loading = TextView(this).apply { - text = getString(R.string.profile_loading) - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) - setTextColor(getColor(R.color.fire_text_secondary)) - } - content.addView(loading) - dialog.setContentView(ScrollView(this).apply { addView(content) }) - dialog.show() - - lifecycleScope.launch { - try { - val profile = sessionStore.fetchUserProfile(normalized) - val summary = runCatching { sessionStore.fetchUserSummary(normalized) }.getOrNull() - val currentUsername = runCatching { - sessionStore.snapshot().bootstrap.currentUsername - }.getOrNull()?.trim() - if (!dialog.isShowing) return@launch - renderUserInfoSheet( - content = content, - dialog = dialog, - profile = profile, - summary = summary, - isOwnProfile = currentUsername.equals(profile.username.trim(), ignoreCase = true), - ) - } catch (e: Exception) { - if (!dialog.isShowing) return@launch - content.removeAllViews() - content.addView(TextView(this@TopicDetailActivity).apply { - text = e.localizedMessage ?: getString(R.string.profile_error) - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) - setTextColor(getColor(R.color.fire_text_secondary)) - }) - } - } - } - - private fun renderUserInfoSheet( - content: LinearLayout, - dialog: BottomSheetDialog, - profile: UserProfileState, - summary: UserSummaryState?, - isOwnProfile: Boolean, - ) { - content.removeAllViews() - val header = LinearLayout(this).apply { - orientation = LinearLayout.HORIZONTAL - gravity = Gravity.CENTER_VERTICAL - } - val avatar = ImageView(this).apply { - layoutParams = LinearLayout.LayoutParams(dp(64), dp(64)) - scaleType = ImageView.ScaleType.CENTER_CROP - contentDescription = getString(R.string.content_desc_avatar) - } - profile.avatarTemplate?.takeIf { it.isNotBlank() }?.let { template -> - FireAvatarUrls.build(template)?.let { url -> - FireImageLoader.load(url, avatar) - } - } - val titleStack = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setPadding(dp(14), 0, 0, 0) - } - titleStack.addView(TextView(this).apply { - text = profile.name?.takeIf { it.isNotBlank() } ?: profile.username - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Title) - setTextColor(getColor(R.color.fire_text_primary)) - }) - titleStack.addView(TextView(this).apply { - text = "@${profile.username} · ${profile.trustLevelLabel}" - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Caption) - setTextColor(getColor(R.color.fire_text_secondary)) - }) - header.addView(avatar) - header.addView(titleStack) - content.addView(header) - - val stats = summary?.stats - val statText = buildList { - add(getString(R.string.profile_topics_count, (stats?.topicCount ?: 0u).toString())) - add(getString(R.string.profile_posts_count, (stats?.postCount ?: 0u).toString())) - add(getString(R.string.profile_likes_received, (stats?.likesReceived ?: 0u).toString())) - add(getString(R.string.profile_followers_count, profile.totalFollowers.toString())) - }.joinToString("\n") - content.addView(TextView(this).apply { - text = statText - setPadding(0, dp(16), 0, 0) - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1) - setTextColor(getColor(R.color.fire_text_primary)) - }) - - profile.bioPlainText?.trim()?.takeIf { it.isNotEmpty() }?.let { bio -> - content.addView(TextView(this).apply { - text = bio - setPadding(0, dp(14), 0, 0) - setTextIsSelectable(true) - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body2) - setTextColor(getColor(R.color.fire_text_secondary)) - }) - } - - if (!isOwnProfile && profile.canSendPrivateMessageToUser) { - content.addView(TextView(this).apply { - text = getString(R.string.profile_send_private_message) - gravity = Gravity.CENTER - setPadding(dp(12), dp(10), dp(12), dp(10)) - setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Button) - setTextColor(getColor(R.color.fire_accent)) - setOnClickListener { - dialog.dismiss() - PrivateMessageComposerSheet.newInstance( - targetUsername = profile.username, - displayName = profile.name?.takeIf { it.isNotBlank() } ?: profile.username, - onPrivateMessageCreated = { topicId, title -> - TopicDetailActivity.start( - context = this@TopicDetailActivity, - topicId = topicId.toLong(), - topicTitle = title, - ) - }, - ).show(supportFragmentManager, "private_message_composer") - } - }) - } - } - - private fun profileUsernameFromUri(uri: Uri): String? { - if (uri.scheme == "fire" && (uri.host == "profile" || uri.host == "user")) { - return uri.pathSegments.firstOrNull() - } - if ((uri.scheme == "http" || uri.scheme == "https") && - uri.host?.endsWith("linux.do") == true && - uri.pathSegments.firstOrNull() == "u" - ) { - return uri.pathSegments.getOrNull(1) - } - return null - } - - private fun topicRouteFromUri(uri: Uri): Pair? { - if (uri.scheme == "fire" && uri.host == "topic") { - val topicId = uri.pathSegments.getOrNull(0)?.toLongOrNull()?.takeIf { it > 0 } ?: return null - val postNumber = uri.pathSegments.getOrNull(1)?.toIntOrNull() ?: -1 - return topicId to postNumber - } - if ((uri.scheme != "http" && uri.scheme != "https") || - uri.host?.endsWith("linux.do") != true || - uri.pathSegments.firstOrNull() != "t" - ) { - return null - } - val tail = uri.pathSegments.drop(1) - if (tail.size == 2) { - val topicId = tail[0].toLongOrNull()?.takeIf { it > 0 } - val postNumber = tail[1].toIntOrNull() - if (topicId != null && postNumber != null) { - return topicId to postNumber - } - } - if (tail.size >= 3) { - val postNumber = tail.last().toIntOrNull() - val topicId = tail.getOrNull(tail.size - 2)?.toLongOrNull()?.takeIf { it > 0 } - if (topicId != null && postNumber != null) { - return topicId to postNumber - } - } - val topicId = tail.lastOrNull()?.toLongOrNull()?.takeIf { it > 0 } ?: return null - return topicId to -1 - } - - private fun showImageViewer(image: FireCookedImage) { - TopicImagePreviewDialogFragment - .newInstance(image) - .show(supportFragmentManager, "topic_image_preview") - } - - private fun showReactionUsers(post: TopicPostState) { - showReactionUsers(post, reactionId = null) - } - - private fun showReactionUsers(post: TopicPostState, reactionId: String?) { - lifecycleScope.launch { - try { - val groups = sessionStore.fetchReactionUsers(post.id) - .filterForReaction(reactionId) - val message = if (groups.isEmpty()) { - getString(R.string.topic_detail_reaction_users_empty) - } else { - groups.joinToString("\n\n", transform = ::formatReactionUsersGroup) - } - AlertDialog.Builder(this@TopicDetailActivity) - .setTitle( - reactionId - ?.let { ReactionPresentation.optionFor(it) } - ?.let { getString(R.string.topic_detail_reaction_users_title_for_reaction, it.symbol, it.label) } - ?: getString(R.string.topic_detail_reaction_users_title), - ) - .setMessage(message) - .setPositiveButton(android.R.string.ok, null) - .show() - } catch (e: Exception) { - FireToast.show( - binding.root, - e.localizedMessage ?: getString(R.string.topic_detail_reaction_users_error), - FireToast.Style.ERROR, - ) - } - } - } - - private fun List.filterForReaction(reactionId: String?): List { - val trimmedReactionId = reactionId?.trim()?.takeIf { it.isNotEmpty() } ?: return this - return filter { group -> group.id.equals(trimmedReactionId, ignoreCase = true) } - } - - private fun formatReactionUsersGroup(group: ReactionUsersGroupState): String { - val users = group.users - .joinToString(", ") { user -> - user.name?.takeIf { it.isNotBlank() } ?: "@${user.username}" - } - .ifBlank { getString(R.string.topic_detail_reaction_users_empty) } - return getString( - R.string.topic_detail_reaction_users_group, - group.id, - group.count.toString(), - ) + "\n" + users - } - - private fun showReactionPicker(post: TopicPostState) { - val currentReaction = post.currentUserReaction - if (currentReaction?.canUndo == false) { - FireToast.show( - binding.root, - R.string.topic_detail_reaction_locked, - FireToast.Style.WARNING, - ) - return - } - - lifecycleScope.launch { - val options = fullReactionOptionsForPost(post) - if (options.isEmpty()) { - FireToast.show( - binding.root, - R.string.topic_detail_reaction_empty, - FireToast.Style.INFO, - ) - return@launch - } - - val content = LinearLayout(this@TopicDetailActivity).apply { - orientation = LinearLayout.VERTICAL - setPadding(dp(20), dp(8), dp(20), 0) - } - val searchLayout = TextInputLayout(this@TopicDetailActivity).apply { - hint = getString(R.string.topic_detail_reaction_search_hint) - } - val searchInput = TextInputEditText(searchLayout.context).apply { - isSingleLine = true - } - searchLayout.addView( - searchInput, - LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - LinearLayout.LayoutParams.WRAP_CONTENT, - ), - ) - val listView = ListView(this@TopicDetailActivity).apply { - divider = null - choiceMode = ListView.CHOICE_MODE_NONE - } - content.addView( - searchLayout, - LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - LinearLayout.LayoutParams.WRAP_CONTENT, - ), - ) - content.addView( - listView, - LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - dp(360), - ), - ) - - var visibleOptions = options - val adapter = ArrayAdapter( - this@TopicDetailActivity, - android.R.layout.simple_list_item_1, - visibleOptions.map { option -> reactionChoiceLabel(post, option) }.toMutableList(), - ) - fun submitVisibleOptions(query: String) { - visibleOptions = ReactionPresentation.filteredOptions(options, query) - adapter.clear() - adapter.addAll(visibleOptions.map { option -> reactionChoiceLabel(post, option) }) - adapter.notifyDataSetChanged() - } - listView.adapter = adapter - listView.setOnItemLongClickListener { _, _, position, _ -> - visibleOptions.getOrNull(position)?.let { option -> - showReactionUsers(post, option.id) - } - true - } - searchInput.doAfterTextChanged { text -> - submitVisibleOptions(text?.toString().orEmpty()) - } - - val dialog = AlertDialog.Builder(this@TopicDetailActivity) - .setTitle( - getString( - R.string.topic_detail_reaction_title, - post.postNumber.toString(), - ), - ) - .setView(content) - .setNegativeButton(android.R.string.cancel, null) - .create() - listView.setOnItemClickListener { _, _, position, _ -> - visibleOptions.getOrNull(position)?.let { option -> - viewModel?.toggleReaction(post, option.id) - dialog.dismiss() - } - } - dialog.show() - } - } - - private fun reactionChoiceLabel(post: TopicPostState, option: ReactionOption): String { - val count = post.reactions - .firstOrNull { it.id.equals(option.id, ignoreCase = true) } - ?.count - ?: 0u - val label = getString( - R.string.topic_detail_reaction_choice, - "${option.symbol} ${option.label}", - count.toString(), - ) - return if (post.currentUserReaction?.id?.equals(option.id, ignoreCase = true) == true) { - getString(R.string.topic_detail_reaction_choice_selected, label) - } else { - label - } - } - - private suspend fun fullReactionOptionsForPost(post: TopicPostState): List { - if (enabledReactionIds.isEmpty()) { - enabledReactionIds = runCatching { - sessionStore.snapshot().bootstrap.enabledReactionIds - }.getOrDefault(emptyList()) - refreshReactionRows() - } - return ReactionPresentation.fullOptions( - reactionIds = enabledReactionIds, - currentReactionId = post.currentUserReaction?.id, - ) - } - - private fun loadEnabledReactionIds() { - lifecycleScope.launch { - enabledReactionIds = runCatching { - sessionStore.snapshot().bootstrap.enabledReactionIds - }.getOrDefault(emptyList()) - refreshReactionRows() - } - } - - private fun refreshReactionRows() { - headerAdapter.refreshRows() - postListAdapter.refreshRows() - } - - private fun showTopicNotificationOptions(detail: TopicDetailState) { - val options = listOf( - TopicNotificationOption( - level = 0, - title = getString(R.string.topic_detail_notification_muted), - ), - TopicNotificationOption( - level = 1, - title = getString(R.string.topic_detail_notification_regular), - ), - TopicNotificationOption( - level = 2, - title = getString(R.string.topic_detail_notification_tracking), - ), - TopicNotificationOption( - level = 3, - title = getString(R.string.topic_detail_notification_watching), - ), - ) - val labels = options.map { option -> - option.title - }.toTypedArray() - val selectedIndex = options.indexOfFirst { - it.level == (detail.details.notificationLevel ?: 1) - }.coerceAtLeast(0) - - AlertDialog.Builder(this) - .setTitle(R.string.topic_detail_notification_title) - .setSingleChoiceItems(labels, selectedIndex) { dialog, which -> - viewModel?.setTopicNotificationLevel(options[which].level) - dialog.dismiss() - } - .setNegativeButton(android.R.string.cancel, null) - .show() - } - - private fun showTopicEditor(detail: TopicDetailState) { - lifecycleScope.launch { - try { - val session = sessionStore.snapshot() - val currentCategoryId = detail.categoryId - val categories = session.bootstrap.categories.filter { category -> - category.id == currentCategoryId || - category.permission?.toInt()?.let { it <= 1 } ?: true - } - if (categories.isEmpty()) { - Toast.makeText( - this@TopicDetailActivity, - R.string.topic_detail_edit_topic_no_categories, - Toast.LENGTH_SHORT, - ).show() - return@launch - } - showTopicEditorDialog( - detail = detail, - categories = categories, - minTitleLength = session.bootstrap.minTopicTitleLength.toInt().coerceAtLeast(1), - ) - } catch (e: Exception) { - Toast.makeText( - this@TopicDetailActivity, - e.localizedMessage ?: getString(R.string.topic_detail_edit_topic_error), - Toast.LENGTH_SHORT, - ).show() - } - } - } - - private fun showTopicEditorDialog( - detail: TopicDetailState, - categories: List, - minTitleLength: Int, - ) { - val titleInput = EditText(this).apply { - setText(detail.title.trim()) - hint = getString(R.string.topic_detail_edit_topic_title_hint) - setSingleLine(true) - } - val categorySpinner = Spinner(this).apply { - adapter = ArrayAdapter( - this@TopicDetailActivity, - android.R.layout.simple_spinner_item, - categories.map { it.displayName() }, - ).apply { - setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) - } - val selectedIndex = categories.indexOfFirst { it.id == detail.categoryId } - if (selectedIndex >= 0) { - setSelection(selectedIndex) - } - } - val tagsInput = EditText(this).apply { - setText(detail.tags.joinToString(" ") { it.name }) - hint = getString(R.string.topic_detail_edit_topic_tags_hint) - setSingleLine(true) - } - val tagSuggestions = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - visibility = View.GONE - } - val content = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setPadding(48, 8, 48, 0) - addView(titleInput) - addView(categorySpinner) - addView(tagsInput) - addView(tagSuggestions) - } - ComposerTagAssist( - input = tagsInput, - suggestions = tagSuggestions, - sessionStore = sessionStore, - scope = lifecycleScope, - categoryIdProvider = { categories.getOrNull(categorySpinner.selectedItemPosition)?.id }, - selectedTagsProvider = { - tagsInput.text.toString() - .split("[,\\s]+".toRegex()) - .filter { it.isNotBlank() } - }, - ).attach() - - val dialog = AlertDialog.Builder(this) - .setTitle(R.string.topic_detail_edit_topic_title) - .setView(content) - .setPositiveButton(R.string.topic_detail_edit_save, null) - .setNegativeButton(android.R.string.cancel, null) - .create() - dialog.setOnShowListener { - dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - val title = titleInput.text.toString().trim() - val category = categories.getOrNull(categorySpinner.selectedItemPosition) - val tags = tagsInput.text.toString() - .split("[,\\s]+".toRegex()) - .filter { it.isNotBlank() } - - if (title.length < minTitleLength) { - Toast.makeText( - this, - getString( - R.string.topic_detail_edit_topic_title_min_length, - minTitleLength.toString(), - ), - Toast.LENGTH_SHORT, - ).show() - return@setOnClickListener - } - if (category == null) { - Toast.makeText( - this, - R.string.topic_detail_edit_topic_category_required, - Toast.LENGTH_SHORT, - ).show() - return@setOnClickListener - } - if (tags.size < category.minimumRequiredTags.toInt()) { - Toast.makeText( - this, - getString( - R.string.topic_detail_edit_topic_tags_required, - category.minimumRequiredTags.toString(), - ), - Toast.LENGTH_SHORT, - ).show() - return@setOnClickListener - } - val disallowedTags = if (category.allowedTags.isEmpty()) { - emptyList() - } else { - tags.filterNot { tag -> category.allowedTags.contains(tag) } - } - if (disallowedTags.isNotEmpty()) { - Toast.makeText( - this, - getString( - R.string.topic_detail_edit_topic_tags_not_allowed, - disallowedTags.joinToString(", "), - ), - Toast.LENGTH_SHORT, - ).show() - return@setOnClickListener - } - viewModel?.updateTopic(title, category.id, tags) - dialog.dismiss() - } - } - dialog.show() - } - - private fun showTopicVoters(detail: TopicDetailState) { - Toast.makeText( - this, - R.string.topic_detail_vote_voters_loading, - Toast.LENGTH_SHORT, - ).show() - lifecycleScope.launch { - try { - val voters = sessionStore.fetchTopicVoters(detail.id) - showTopicVotersDialog(voters) - } catch (e: Exception) { - Toast.makeText( - this@TopicDetailActivity, - e.localizedMessage ?: getString(R.string.topic_detail_vote_voters_empty), - Toast.LENGTH_SHORT, - ).show() - } - } - } - - private fun showTopicVotersDialog(voters: List) { - if (voters.isEmpty()) { - AlertDialog.Builder(this) - .setTitle(R.string.topic_detail_vote_voters_title) - .setMessage(R.string.topic_detail_vote_voters_empty) - .setPositiveButton(android.R.string.ok, null) - .show() - return - } - - val labels = voters.map(::topicVoterLabel).toTypedArray() - AlertDialog.Builder(this) - .setTitle(R.string.topic_detail_vote_voters_title) - .setItems(labels) { _, which -> - voters.getOrNull(which)?.username?.let(::showUserInfoSheet) - } - .setPositiveButton(android.R.string.ok, null) - .show() - } - - private fun topicVoterLabel(voter: VotedUserState): String { - val displayName = voter.name?.takeIf { it.isNotBlank() } ?: voter.username - return "$displayName\n@${voter.username}" - } - - private fun showReplyContext(post: TopicPostState) { - val currentRoute = route ?: return - Toast.makeText( - this, - R.string.topic_detail_reply_context_loading, - Toast.LENGTH_SHORT, - ).show() - lifecycleScope.launch { - try { - val history = if (post.replyToPostNumber != null) { - sessionStore.fetchPostReplyHistory(post.id) - } else { - emptyList() - } - val directReplies = fetchDirectReplies(currentRoute.topicId.toULong(), post) - val message = replyContextMessage(history, directReplies) - AlertDialog.Builder(this@TopicDetailActivity) - .setTitle( - getString( - R.string.topic_detail_reply_context_title, - post.postNumber.toString(), - ), - ) - .setMessage(message) - .setPositiveButton(android.R.string.ok, null) - .show() - } catch (e: Exception) { - Toast.makeText( - this@TopicDetailActivity, - e.localizedMessage ?: getString(R.string.topic_detail_reply_context_empty), - Toast.LENGTH_SHORT, - ).show() - } - } - } - - private suspend fun fetchDirectReplies( - topicId: ULong, - post: TopicPostState, - ): List { - if (post.replyCount == 0u) { - return emptyList() - } - val replyIds = sessionStore.fetchPostReplyIds(post.id) - .filter { it > 0u } - .distinct() - if (replyIds.isEmpty()) { - return emptyList() - } - - return replyIds.chunked(REPLY_CONTEXT_POST_BATCH_SIZE).flatMap { batch -> - sessionStore.fetchTopicPosts(topicId, batch) - } - } - - private fun replyContextMessage( - history: List, - directReplies: List, - ): String { - if (history.isEmpty() && directReplies.isEmpty()) { - return getString(R.string.topic_detail_reply_context_empty) - } - - return buildString { - if (history.isNotEmpty()) { - appendLine(getString(R.string.topic_detail_reply_context_history)) - appendLine(history.joinToString("\n\n", transform = ::replyContextPostLine)) - } - if (directReplies.isNotEmpty()) { - if (isNotEmpty()) appendLine() - appendLine(getString(R.string.topic_detail_reply_context_direct)) - appendLine(directReplies.joinToString("\n\n", transform = ::replyContextPostLine)) - } - }.trim() - } - - private fun replyContextPostLine(post: TopicPostState): String { - val author = post.name?.takeIf { it.isNotBlank() } ?: "@${post.username}" - val body = post.presentation?.plainText().orEmpty() - .lineSequence() - .map { it.trim() } - .filter { it.isNotEmpty() } - .joinToString(" ") - .take(180) - return "#${post.postNumber} $author\n$body" - } - - private fun loadRoute(route: TopicDetailRoute) { - val targetPostNumber = route.targetPostNumber.takeIf { it > 0 }?.toUInt() - viewModel?.loadTopicDetail(route.topicId.toULong(), targetPostNumber) - } - - private fun scheduleLoadMorePosts(rv: RecyclerView) { - if (loadMorePostsPosted) return - loadMorePostsPosted = true - rv.post { - loadMorePostsPosted = false - viewModel?.loadMorePosts() - } - } - - private fun updateVisiblePostTimings() { - val tracker = timingTracker ?: return - val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return - val firstVisible = layoutManager.findFirstVisibleItemPosition() - val lastVisible = layoutManager.findLastVisibleItemPosition() - if (firstVisible == RecyclerView.NO_POSITION || lastVisible == RecyclerView.NO_POSITION) { - tracker.updateVisiblePostNumbers(emptySet()) - return - } - - val visiblePostNumbers = buildSet { - for (adapterPosition in firstVisible..lastVisible) { - visiblePostNumberForAdapterPosition(adapterPosition)?.let(::add) - } - } - if (visiblePostNumbers.isNotEmpty()) { - tracker.recordInteraction() - } - tracker.updateVisiblePostNumbers(visiblePostNumbers) - } - - private fun visiblePostNumberForAdapterPosition(adapterPosition: Int): UInt? { - if (adapterPosition < 0) return null - if (adapterPosition < headerAdapter.itemCount) { - return viewModel?.detail?.value?.postStream?.posts - ?.minByOrNull { it.postNumber } - ?.postNumber - } - - val rowIndex = adapterPosition - headerAdapter.itemCount - return postListAdapter.currentList.getOrNull(rowIndex)?.post?.postNumber - } - - private fun scrollToPostNumber(postNumber: UInt) { - pendingScrollTargetPostNumber = postNumber - val adapterPosition = if (postNumber <= 1u) { - 0 - } else { - val rowIndex = postListAdapter.currentList.indexOfFirst { - it.post.postNumber == postNumber - } - if (rowIndex < 0) return - headerAdapter.itemCount + rowIndex - } - pendingScrollTargetPostNumber = null - - recyclerView.post { - val layoutManager = recyclerView.layoutManager as? LinearLayoutManager - if (layoutManager != null) { - layoutManager.scrollToPositionWithOffset(adapterPosition, 0) - } else { - recyclerView.scrollToPosition(adapterPosition) - } - } - } - - private fun applySystemBarInsets() { - val root = binding.root - val initialLeft = root.paddingLeft - val initialTop = root.paddingTop - val initialRight = root.paddingRight - val initialBottom = root.paddingBottom - ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets -> - val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) - view.updatePadding( - left = initialLeft + systemBars.left, - top = initialTop + systemBars.top, - right = initialRight + systemBars.right, - bottom = initialBottom + systemBars.bottom, - ) - insets - } - ViewCompat.requestApplyInsets(root) - } - - private data class TopicDetailRoute( + internal data class TopicDetailRoute( val topicId: Long, val title: String?, val targetPostNumber: Int, @@ -1824,7 +292,7 @@ class TopicDetailActivity : AppCompatActivity() { private const val EXTRA_TOPIC_ID = "com.fire.app.extra.TOPIC_ID" private const val EXTRA_TOPIC_TITLE = "com.fire.app.extra.TOPIC_TITLE" private const val EXTRA_TARGET_POST_NUMBER = "com.fire.app.extra.TARGET_POST_NUMBER" - private const val REPLY_CONTEXT_POST_BATCH_SIZE = 20 + internal const val REPLY_CONTEXT_POST_BATCH_SIZE = 20 fun createIntent( context: Context, @@ -1856,57 +324,3 @@ class TopicDetailActivity : AppCompatActivity() { } } } - -private data class TopicNotificationOption( - val level: Int, - val title: String, -) - -private data class BookmarkReminderKey( - val bookmarkableId: ULong, - val bookmarkableType: String, -) - -private class BookmarkReminderSelection( - var hasReminder: Boolean, - var dateTime: ZonedDateTime?, -) { - fun reminderAt(): String? { - if (!hasReminder) return null - val normalizedDateTime = dateTime - ?.takeIf { it.isAfter(ZonedDateTime.now()) } - ?: ZonedDateTime.now().plusMinutes(1) - return normalizedDateTime - ?.withSecond(0) - ?.withNano(0) - ?.toInstant() - ?.toString() - } - - fun displayText(context: Context): String { - val dateTime = dateTime ?: return context.getString(R.string.topic_detail_bookmark_reminder_pick) - return DateTimeFormatter - .ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT) - .format(dateTime.withZoneSameInstant(ZoneId.systemDefault())) - } - - companion object { - fun from(rawValue: String?): BookmarkReminderSelection { - val parsed = rawValue - ?.trim() - ?.takeIf { it.isNotEmpty() } - ?.let { runCatching { Instant.parse(it).atZone(ZoneId.systemDefault()) }.getOrNull() } - return BookmarkReminderSelection( - hasReminder = parsed != null, - dateTime = parsed, - ) - } - } -} - -private data class PostFlagOption( - val id: UInt, - val title: String, - val detail: String, - val requireMessage: Boolean, -) diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailPostRows.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailPostRows.kt new file mode 100644 index 00000000..84af0ea5 --- /dev/null +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailPostRows.kt @@ -0,0 +1,209 @@ +package com.fire.app.ui.topicdetail + +import uniffi.fire_uniffi_topics.TopicPostState +import uniffi.fire_uniffi_topics.TopicTreeRowState + +object TopicDetailPostRows { + data class SearchMatch( + val postId: ULong, + val postNumber: UInt, + ) + + fun uniqueTreeRows( + rows: List, + bodyPostId: ULong? = null, + ): List { + val rowsByPostId = LinkedHashMap(rows.size) + for (row in rows) { + if (row.postId == bodyPostId) continue + rowsByPostId[row.postId] = row + } + return rowsByPostId.values.toList() + } + + fun initialScrollTargetPostNumber( + explicitTargetPostNumber: UInt?, + suggestedUnreadRootPostNumber: UInt?, + shouldUseSuggestedUnreadRootTarget: Boolean, + ): UInt? { + explicitTargetPostNumber?.takeIf { it > 0u }?.let { return it } + if (!shouldUseSuggestedUnreadRootTarget) return null + return suggestedUnreadRootPostNumber?.takeIf { it > 1u } + } + + fun usesBoostBarrage(row: PostRow): Boolean { + return row.depth == 0 && row.post.boosts.isNotEmpty() + } + + fun searchMatches(query: String, posts: List): List { + val needle = query.trim() + if (needle.isEmpty()) return emptyList() + + val seenPostIds = LinkedHashSet() + return posts + .asSequence() + .filter { post -> seenPostIds.add(post.id) } + .filter { post -> + post.presentation + ?.plainText() + ?.contains(needle, ignoreCase = true) == true + } + .sortedWith( + compareBy { it.postNumber } + .thenBy { it.id }, + ) + .map { post -> + SearchMatch( + postId = post.id, + postNumber = post.postNumber, + ) + } + .toList() + } + + fun projectRows( + rows: List, + postsById: Map, + expandedReplyRootPostIds: Set = emptySet(), + focusedPostNumber: UInt? = null, + ): List { + val availableRows = rows.mapNotNull { row -> + val post = postsById[row.postId] ?: return@mapNotNull null + ProjectableReplyRow(row = row, post = post) + } + if (availableRows.isEmpty()) return emptyList() + + val rowByPostNumber = availableRows + .mapIndexed { index, projected -> projected.row.postNumber to index } + .toMap() + val rootIndexByIndex = availableRows.indices.associateWith { index -> + rootIndexFor(index, availableRows, rowByPostNumber) + } + val secondaryIndicesByRoot = LinkedHashMap>() + for (index in availableRows.indices) { + val rootIndex = rootIndexByIndex[index] ?: index + if (rootIndex != index) { + secondaryIndicesByRoot.getOrPut(rootIndex) { mutableListOf() }.add(index) + } + } + + val focusedIndex = focusedPostNumber?.let(rowByPostNumber::get) + val focusedSecondaryIndices = focusedIndex + ?.let { selectedAncestryIndices(it, availableRows, rowByPostNumber, rootIndexByIndex) } + .orEmpty() + + return buildList { + availableRows.forEachIndexed { index, projected -> + val rootIndex = rootIndexByIndex[index] ?: index + if (rootIndex != index) return@forEachIndexed + + val secondaryIndices = secondaryIndicesByRoot[index].orEmpty() + val isExpanded = expandedReplyRootPostIds.contains(projected.post.id) + val selectedSecondaryIndices = if (isExpanded) { + secondaryIndices.toSet() + } else { + focusedSecondaryIndices.intersect(secondaryIndices.toSet()) + } + val hiddenReplyCount = (secondaryIndices.size - selectedSecondaryIndices.size).coerceAtLeast(0) + add( + postRow( + projected = projected, + hiddenReplyCount = hiddenReplyCount.toUInt().takeIf { it > 0u } ?: 0u, + ), + ) + secondaryIndices.forEach { secondaryIndex -> + if (!selectedSecondaryIndices.contains(secondaryIndex)) return@forEach + add(postRow(projected = availableRows[secondaryIndex])) + } + } + } + } + + private fun rootIndexFor( + startIndex: Int, + rows: List, + rowByPostNumber: Map, + ): Int { + var index = startIndex + val visited = mutableSetOf() + while (visited.add(index)) { + val row = rows[index].row + val parentNumber = row.parentPostNumber + if (row.depth.toInt() <= 1 || parentNumber == null || parentNumber <= 1u) { + return index + } + index = rowByPostNumber[parentNumber] ?: return index + } + return startIndex + } + + private fun selectedAncestryIndices( + focusedIndex: Int, + rows: List, + rowByPostNumber: Map, + rootIndexByIndex: Map, + ): Set { + val rootIndex = rootIndexByIndex[focusedIndex] ?: focusedIndex + if (rootIndex == focusedIndex) return emptySet() + + val selected = linkedSetOf() + var index = focusedIndex + val visited = mutableSetOf() + while (index != rootIndex && visited.add(index)) { + selected += index + val parentNumber = rows[index].row.parentPostNumber ?: break + index = rowByPostNumber[parentNumber] ?: break + } + return selected + } + + private fun postRow( + projected: ProjectableReplyRow, + hiddenReplyCount: UInt = 0u, + ): PostRow { + return projected.row.let { row -> + PostRow( + post = projected.post, + depth = row.depth.toInt(), + parentPostNumber = row.parentPostNumber, + hasChildren = row.hasChildren, + hiddenReplyCount = hiddenReplyCount, + ) + } + } + + fun postsForDetail( + bodyPost: TopicPostState, + loadedPosts: List, + replyRows: List, + ): List { + val postsById = postsById(listOf(bodyPost) + loadedPosts) + return uniquePosts( + listOf(bodyPost) + replyRows.mapNotNull { row -> + if (row.postId == bodyPost.id) null else postsById[row.postId] + }, + ) + } + + fun postsById(posts: List): Map { + return posts.associateBy { it.id } + } + + fun uniquePosts(posts: List): List { + val postsById = LinkedHashMap(posts.size) + for (post in posts) { + postsById[post.id] = post + } + return postsById.values.toList() + } + + private data class ProjectableReplyRow( + val row: TopicTreeRowState, + val post: TopicPostState, + ) +} + +object TopicDetailBoostPresentation { + const val BODY_BARRAGE_VISIBLE_LINE_LIMIT = 5 + const val BODY_BARRAGE_MAX_LANES = 5 +} diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt index 5eb65d11..da85dfab 100644 --- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt +++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt @@ -4,42 +4,26 @@ import android.util.LruCache import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope -import com.fire.app.TopicPresentation import com.fire.app.core.error.FireErrorReporter -import com.fire.app.data.repository.TopicRepository -import com.fire.app.messagebus.FireMessageBusCoordinator import com.fire.app.richtext.FireRichTextContent import com.fire.app.richtext.FireRenderPresentation -import com.fire.app.richtext.FireSpannableBuilder import com.fire.app.session.FireSessionStore import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import uniffi.fire_uniffi_topics.PollState -import uniffi.fire_uniffi_topics.PostUpdateRequestState -import uniffi.fire_uniffi_topics.PostReactionUpdateState import uniffi.fire_uniffi_topics.TopicAiSummaryState -import uniffi.fire_uniffi_topics.TopicBodyState -import uniffi.fire_uniffi_topics.TopicDetailPageState import uniffi.fire_uniffi_topics.TopicDetailState -import uniffi.fire_uniffi_topics.TopicDetailSourceSnapshotState import uniffi.fire_uniffi_topics.TopicPostState import uniffi.fire_uniffi_topics.TopicPostStreamState -import uniffi.fire_uniffi_topics.TopicSourceCursorState -import uniffi.fire_uniffi_topics.TopicTreePresentationState import uniffi.fire_uniffi_topics.TopicTreeRowState -import uniffi.fire_uniffi_topics.TopicUpdateRequestState class TopicDetailViewModel( - private val topicRepository: TopicRepository, private val sessionStore: FireSessionStore, - private val messageBusCoordinator: FireMessageBusCoordinator, ) : ViewModel() { private val _detail = MutableStateFlow(null) @@ -78,23 +62,10 @@ class TopicDetailViewModel( private val _bookmarkEvents = MutableSharedFlow(extraBufferCapacity = 1) val bookmarkEvents = _bookmarkEvents.asSharedFlow() - private var sourceCursor: TopicSourceCursorState? = null - private var sourceSnapshot: TopicDetailSourceSnapshotState? = null - private var treePresentation: TopicTreePresentationState? = null - private var messageBusJob: Job? = null - private var pendingMessageBusRefreshJob: Job? = null - private var isScrollInteractionActive = false - private var deferredMessageBusRefreshTopicId: ULong? = null - private var deferredMessageBusPayloadTopicId: ULong? = null - private var deferredMessageBusPayload: TopicDetailPageState? = null - private var topicAiSummaryJob: Job? = null - private var topicAiSummaryTopicId: ULong? = null - private var topicAiSummaryUnavailable: Boolean = false - private var subscribedTopicId: ULong? = null - private var subscribedOwnerToken: String? = null + private var openedTopicId: ULong? = null + private var snapshotReplyRows: List = emptyList() private val expandedReplyRootPostIds = mutableSetOf() private var sessionHandle: uniffi.fire_uniffi_topics.TopicDetailSessionHandle? = null - private var sessionOwnerToken: String? = null private val sessionObserver = object : uniffi.fire_uniffi_topics.TopicDetailObserver { override fun onSnapshot(snapshot: uniffi.fire_uniffi_topics.TopicDetailUiSnapshotState) { viewModelScope.launch(Dispatchers.Main) { @@ -118,7 +89,6 @@ class TopicDetailViewModel( try { val shouldUseSuggestedUnreadRootTarget = targetPostNumber == null && _detail.value == null val owner = "android.topic-detail.$topicId" - sessionOwnerToken = owner sessionHandle = sessionStore.openTopicDetail( uniffi.fire_uniffi_topics.TopicDetailOpenRequestState( topicId = topicId, @@ -132,6 +102,7 @@ class TopicDetailViewModel( ), sessionObserver, ) + openedTopicId = topicId } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -154,223 +125,26 @@ class TopicDetailViewModel( } private fun prepareForTopicLoad(topicId: ULong) { - val previousTopicId = sourceSnapshot?.header?.topicId ?: _detail.value?.id ?: subscribedTopicId + val previousTopicId = openedTopicId ?: _detail.value?.id if (previousTopicId != null && previousTopicId != topicId) { sessionHandle?.release() sessionHandle = null + openedTopicId = null + snapshotReplyRows = emptyList() + expandedReplyRootPostIds.clear() + renderCache.evictAll() + _detail.value = null + _postRows.value = emptyList() + _topicAiSummary.value = null + _topicAiSummaryError.value = null + _isLoadingTopicAiSummary.value = false } - if (previousTopicId == null || previousTopicId == topicId) { - return - } - - releaseTopicDetailMessageBus() - topicAiSummaryJob?.cancel() - topicAiSummaryJob = null - topicAiSummaryTopicId = null - topicAiSummaryUnavailable = false - sourceCursor = null - sourceSnapshot = null - treePresentation = null - expandedReplyRootPostIds.clear() - renderCache.evictAll() - _detail.value = null - _postRows.value = emptyList() - _topicAiSummary.value = null - _topicAiSummaryError.value = null - _isLoadingTopicAiSummary.value = false } fun setTopicDetailScrollInteractionActive(active: Boolean) { - isScrollInteractionActive = active sessionHandle?.noteScrollInteraction(active) } - private fun applyFetchedPayload( - payload: TopicDetailPageState, - focusedPostNumber: UInt? = null, - ): List { - val bodyPost = payload.sourceSnapshot.body.post - val normalizedReplyRows = TopicDetailPostRows.uniqueTreeRows( - rows = payload.treePresentation.replyRows, - bodyPostId = bodyPost.id, - ) - sourceSnapshot = payload.sourceSnapshot - treePresentation = payload.treePresentation.copy(replyRows = normalizedReplyRows) - sourceCursor = payload.sourceSnapshot.sourceCursor - - val header = payload.sourceSnapshot.header - val allPosts = TopicDetailPostRows.postsForDetail( - bodyPost = bodyPost, - loadedPosts = payload.sourceSnapshot.loadedPosts, - replyRows = normalizedReplyRows, - ) - val postsById = TopicDetailPostRows.postsById(allPosts) - val rows = TopicDetailPostRows.projectRows( - rows = normalizedReplyRows, - postsById = postsById, - expandedReplyRootPostIds = expandedReplyRootPostIds, - focusedPostNumber = focusedPostNumber, - ) - - val nextDetail = TopicDetailState( - id = header.topicId, - messageBusLastId = header.messageBusLastId, - title = header.title, - slug = header.slug, - postsCount = header.postsCount, - replyCount = header.replyCount, - categoryId = header.categoryId, - tags = header.tags, - views = header.views, - likeCount = header.likeCount, - createdAt = header.createdAt, - highestPostNumber = header.highestPostNumber, - lastReadPostNumber = header.lastReadPostNumber, - bookmarks = header.bookmarks, - bookmarked = header.bookmarked, - bookmarkId = header.bookmarkId, - bookmarkName = header.bookmarkName, - bookmarkReminderAt = header.bookmarkReminderAt, - acceptedAnswer = header.acceptedAnswer, - hasAcceptedAnswer = header.hasAcceptedAnswer, - canVote = header.canVote, - voteCount = header.voteCount, - userVoted = header.userVoted, - summarizable = header.summarizable, - hasCachedSummary = header.hasCachedSummary, - hasSummary = header.hasSummary, - archetype = header.archetype, - postStream = TopicPostStreamState( - posts = allPosts, - stream = allPosts.map { it.id }, - ), - details = header.details, - ) - if (_detail.value != nextDetail) { - _detail.value = nextDetail - } - if (_postRows.value != rows) { - _postRows.value = rows - } - _errorMessage.value = null - return allPosts - } - - private fun maintainTopicDetailMessageBus(topicId: ULong, lastMessageId: Long?) { - if (subscribedTopicId == topicId && messageBusJob != null) return - - releaseTopicDetailMessageBus() - val ownerToken = "android_topic_detail_$topicId" - subscribedTopicId = topicId - subscribedOwnerToken = ownerToken - - runCatching { - sessionStore.subscribeTopicDetailChannel(topicId, ownerToken, lastMessageId) - sessionStore.subscribeTopicReactionChannel(topicId, ownerToken) - sessionStore.subscribeTopicPollsChannel(topicId, ownerToken) - }.onFailure { - FireErrorReporter.report( - operation = "topic_detail.messagebus.subscribe", - error = it, - sessionStore = sessionStore, - ) - releaseTopicDetailMessageBus() - return - } - - viewModelScope.launch { - runCatching { sessionStore.bootstrapTopicReplyPresence(topicId, ownerToken) } - .onFailure { - FireErrorReporter.report( - operation = "topic_detail.presence.bootstrap", - error = it, - sessionStore = sessionStore, - ) - } - } - - messageBusJob = viewModelScope.launch { - try { - messageBusCoordinator.topicDetailEvents(topicId).collect { - scheduleTopicDetailRefresh(topicId) - } - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - messageBusJob = null - val reported = FireErrorReporter.report( - operation = "topic_detail.messagebus.collect", - error = e, - sessionStore = sessionStore, - ) - _actionError.tryEmit(reported.displayMessage) - } - } - } - - private fun scheduleTopicDetailRefresh(topicId: ULong) { - pendingMessageBusRefreshJob?.cancel() - pendingMessageBusRefreshJob = viewModelScope.launch { - delay(1_500L) - refreshTopicDetailFromMessageBus(topicId) - } - } - - private suspend fun refreshTopicDetailFromMessageBus(topicId: ULong) { - sessionHandle?.reload( - targetPostNumber = null, - forceLoad = false, - trackVisit = false, - allowSuggestedUnreadRoot = false, - ) - if (topicId == 0uL) return - } - - private fun drainDeferredMessageBusRefreshIfNeeded() { - val deferredPayload = deferredMessageBusPayload - val deferredPayloadTopicId = deferredMessageBusPayloadTopicId - if (deferredPayload != null && deferredPayloadTopicId != null) { - deferredMessageBusPayload = null - deferredMessageBusPayloadTopicId = null - deferredMessageBusRefreshTopicId = null - val allPosts = applyFetchedPayload(deferredPayload) - preloadRenderContent(allPosts) - loadTopicAiSummaryIfNeeded(deferredPayloadTopicId, _detail.value) - return - } - - val deferredTopicId = deferredMessageBusRefreshTopicId ?: return - deferredMessageBusRefreshTopicId = null - pendingMessageBusRefreshJob?.cancel() - pendingMessageBusRefreshJob = viewModelScope.launch { - refreshTopicDetailFromMessageBus(deferredTopicId) - } - } - - private fun releaseTopicDetailMessageBus() { - pendingMessageBusRefreshJob?.cancel() - pendingMessageBusRefreshJob = null - deferredMessageBusRefreshTopicId = null - deferredMessageBusPayloadTopicId = null - deferredMessageBusPayload = null - messageBusJob?.cancel() - messageBusJob = null - - val topicId = subscribedTopicId - val ownerToken = subscribedOwnerToken - subscribedTopicId = null - subscribedOwnerToken = null - - if (topicId != null && ownerToken != null) { - runCatching { - sessionStore.unsubscribeTopicDetailChannel(topicId, ownerToken) - sessionStore.unsubscribeTopicReactionChannel(topicId, ownerToken) - sessionStore.unsubscribeTopicPollsChannel(topicId, ownerToken) - sessionStore.unsubscribeTopicReplyPresenceChannel(topicId, ownerToken) - } - } - } - fun loadMorePosts() { if (_isLoadingMore.value) return sessionHandle?.loadMore() @@ -387,7 +161,11 @@ class TopicDetailViewModel( ?.posts ?.let(TopicDetailPostRows::postsById) ?: return - val rows = projectedPostRows(postsById) + val rows = TopicDetailPostRows.projectRows( + rows = snapshotReplyRows, + postsById = postsById, + expandedReplyRootPostIds = expandedReplyRootPostIds, + ) if (_postRows.value != rows) { _postRows.value = rows } @@ -398,16 +176,7 @@ class TopicDetailViewModel( if (!detail.canVote && !detail.userVoted) return viewModelScope.launch { try { - val response = if (detail.userVoted) { - sessionStore.unvoteTopic(detail.id) - } else { - sessionStore.voteTopic(detail.id) - } - _detail.value = detail.copy( - canVote = response.canVote, - voteCount = response.voteCount, - userVoted = !detail.userVoted, - ) + sessionHandle?.voteTopic(voted = !detail.userVoted) } catch (e: Exception) { handleActionError(e, "投票状态更新失败") } @@ -415,11 +184,10 @@ class TopicDetailViewModel( } fun setTopicNotificationLevel(notificationLevel: Int) { - val detail = _detail.value ?: return + if (_detail.value == null) return viewModelScope.launch { try { - sessionStore.setTopicNotificationLevel(detail.id, notificationLevel) - refreshCurrentTopic() + sessionHandle?.setNotificationLevel(notificationLevel) } catch (e: Exception) { handleActionError(e, "话题通知更新失败") } @@ -464,58 +232,6 @@ class TopicDetailViewModel( } } - private fun loadTopicAiSummaryIfNeeded( - topicId: ULong, - detail: TopicDetailState?, - force: Boolean = false, - ) { - if (topicAiSummaryTopicId != topicId) { - _topicAiSummary.value = null - _topicAiSummaryError.value = null - topicAiSummaryUnavailable = false - } - if (detail == null || !(detail.summarizable || detail.hasCachedSummary || detail.hasSummary)) { - return - } - if (!force && - topicAiSummaryTopicId == topicId && - (_topicAiSummary.value != null || _isLoadingTopicAiSummary.value || topicAiSummaryUnavailable) - ) { - return - } - - topicAiSummaryJob?.cancel() - topicAiSummaryTopicId = topicId - topicAiSummaryUnavailable = false - _topicAiSummaryError.value = null - _isLoadingTopicAiSummary.value = true - - topicAiSummaryJob = viewModelScope.launch { - try { - val summary = topicRepository.fetchTopicAiSummary(topicId, skipAgeCheck = false) - if (summary != null && summary.summarizedText.trim().isNotEmpty()) { - _topicAiSummary.value = summary - topicAiSummaryUnavailable = false - } else { - _topicAiSummary.value = null - topicAiSummaryUnavailable = true - } - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - val reported = FireErrorReporter.report( - operation = "topic_detail.ai_summary", - error = e, - sessionStore = sessionStore, - fallbackMessage = "AI 摘要加载失败", - ) - _topicAiSummaryError.value = reported.displayMessage - } finally { - _isLoadingTopicAiSummary.value = false - } - } - } - fun getRenderContent(post: TopicPostState): FireRichTextContent? { val cacheKey = renderCacheKey(post) val cached = renderCache.get(cacheKey) @@ -702,69 +418,6 @@ class TopicDetailViewModel( } } - private suspend fun scrollToPostWhenLoaded(postNumber: UInt) { - if (hasLoadedPostNumber(postNumber)) { - _scrollTargetPostNumber.emit(postNumber) - return - } - - var remainingPages = TARGET_HYDRATION_PAGE_LIMIT - while (remainingPages > 0 && sourceCursor != null && !hasLoadedPostNumber(postNumber)) { - remainingPages -= 1 - if (!loadMorePostsPage(focusedPostNumber = postNumber)) break - } - - if (hasLoadedPostNumber(postNumber)) { - _scrollTargetPostNumber.emit(postNumber) - } - } - - private fun hasLoadedPostNumber(postNumber: UInt): Boolean { - if (sourceSnapshot?.body?.post?.postNumber == postNumber) return true - return _postRows.value.any { row -> row.post.postNumber == postNumber } - } - - private suspend fun loadMorePostsPage(focusedPostNumber: UInt? = null): Boolean { - sessionHandle?.loadMore() - return focusedPostNumber == null || sourceCursor != null - } - - private fun projectedPostRows( - postsById: Map, - focusedPostNumber: UInt? = null, - ): List { - return TopicDetailPostRows.projectRows( - rows = treePresentation?.replyRows.orEmpty(), - postsById = postsById, - expandedReplyRootPostIds = expandedReplyRootPostIds, - focusedPostNumber = focusedPostNumber, - ) - } - - private fun mergeLoadMore(outcome: uniffi.fire_uniffi_topics.TopicLoadMoreOutcomeState): TopicDetailPageState? { - val current = sourceSnapshot ?: return null - val loaded = current.loadedPosts.toMutableList() - val indexById = loaded.withIndex().associate { it.value.id to it.index }.toMutableMap() - for (post in outcome.appendedPosts) { - val index = indexById[post.id] - if (index != null) { - loaded[index] = post - } else { - indexById[post.id] = loaded.size - loaded += post - } - } - return TopicDetailPageState( - sourceSnapshot = current.copy( - loadedPosts = loaded, - loadedRanges = outcome.loadedRanges, - sourceCursor = outcome.sourceCursor, - sourceExhausted = outcome.sourceExhausted, - ), - treePresentation = outcome.treePresentation, - ) - } - private fun renderCacheKey(post: TopicPostState): Pair { return post.id to (post.presentation?.checksum() ?: 0uL) } @@ -778,76 +431,6 @@ class TopicDetailViewModel( } } - private fun applyReactionUpdate(postId: ULong, update: PostReactionUpdateState) { - replacePost(postId) { post -> - val nextLikeCount = update.reactions - .firstOrNull { it.id == HEART_REACTION_ID } - ?.count - ?: 0u - post.copy( - likeCount = nextLikeCount, - reactions = update.reactions, - currentUserReaction = update.currentUserReaction, - ) - } - } - - private fun applyPollUpdate(postId: ULong, updatedPoll: PollState) { - replacePost(postId) { post -> - post.copy( - polls = post.polls.map { poll -> - if (poll.name == updatedPoll.name) updatedPoll else poll - }, - ) - } - } - - private suspend fun refreshCurrentTopic(targetPostNumber: UInt? = null) { - sessionHandle?.reload( - targetPostNumber = targetPostNumber, - forceLoad = false, - trackVisit = false, - allowSuggestedUnreadRoot = false, - ) - } - - private fun replacePost( - postId: ULong, - transform: (TopicPostState) -> TopicPostState, - ) { - sourceSnapshot = sourceSnapshot?.let { current -> - val nextBodyPost = current.body.post.let { post -> - if (post.id == postId) transform(post) else post - } - current.copy( - body = TopicBodyState(post = nextBodyPost), - loadedPosts = current.loadedPosts.map { post -> - if (post.id == postId) transform(post) else post - }, - ) - } - - val updatedDetail = _detail.value?.let { current -> - val updatedPosts = current.postStream.posts.map { post -> - if (post.id == postId) transform(post) else post - } - current.copy( - postStream = current.postStream.copy( - posts = updatedPosts, - stream = updatedPosts.map { it.id }, - ), - ) - } - _detail.value = updatedDetail - - val postsById = updatedDetail - ?.postStream - ?.posts - ?.let(TopicDetailPostRows::postsById) - ?: emptyMap() - _postRows.value = projectedPostRows(postsById) - } - private fun handleActionError(error: Exception, fallbackMessage: String) { val reported = FireErrorReporter.report( operation = "topic_detail.action", @@ -1013,10 +596,9 @@ class TopicDetailViewModel( val posts = snapshot.rows.map { rowToPost(it) } val detail = detailFromSnapshot(snapshot, posts) _detail.value = detail - sourceSnapshot = null - treePresentation = null + snapshotReplyRows = snapshot.rows.filter { !it.isOriginalPost }.map { rowToTreeRow(it) } _postRows.value = TopicDetailPostRows.projectRows( - rows = snapshot.rows.filter { !it.isOriginalPost }.map { rowToTreeRow(it) }, + rows = snapshotReplyRows, postsById = posts.associateBy { it.id }, expandedReplyRootPostIds = expandedReplyRootPostIds, focusedPostNumber = snapshot.scrollTargetPostNumber, @@ -1033,24 +615,20 @@ class TopicDetailViewModel( } _isLoadingTopicAiSummary.value = snapshot.sidecar.isLoading _topicAiSummaryError.value = snapshot.sidecar.error + preloadRenderContent(posts) } override fun onCleared() { - topicAiSummaryJob?.cancel() sessionHandle?.release() sessionHandle = null - releaseTopicDetailMessageBus() super.onCleared() } companion object { - private const val TARGET_HYDRATION_PAGE_LIMIT = 20 private const val HEART_REACTION_ID = "heart" fun create(sessionStore: FireSessionStore): TopicDetailViewModel { - val topicRepo = TopicRepository(sessionStore) - val messageBusCoordinator = FireMessageBusCoordinator(sessionStore) - return TopicDetailViewModel(topicRepo, sessionStore, messageBusCoordinator) + return TopicDetailViewModel(sessionStore) } } } @@ -1079,208 +657,3 @@ class TopicDetailViewModelFactory( throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}") } } - -object TopicDetailPostRows { - data class SearchMatch( - val postId: ULong, - val postNumber: UInt, - ) - - fun uniqueTreeRows( - rows: List, - bodyPostId: ULong? = null, - ): List { - val rowsByPostId = LinkedHashMap(rows.size) - for (row in rows) { - if (row.postId == bodyPostId) continue - rowsByPostId[row.postId] = row - } - return rowsByPostId.values.toList() - } - - fun initialScrollTargetPostNumber( - explicitTargetPostNumber: UInt?, - suggestedUnreadRootPostNumber: UInt?, - shouldUseSuggestedUnreadRootTarget: Boolean, - ): UInt? { - explicitTargetPostNumber?.takeIf { it > 0u }?.let { return it } - if (!shouldUseSuggestedUnreadRootTarget) return null - return suggestedUnreadRootPostNumber?.takeIf { it > 1u } - } - - fun usesBoostBarrage(row: PostRow): Boolean { - return row.depth == 0 && row.post.boosts.isNotEmpty() - } - - fun searchMatches(query: String, posts: List): List { - val needle = query.trim() - if (needle.isEmpty()) return emptyList() - - val seenPostIds = LinkedHashSet() - return posts - .asSequence() - .filter { post -> seenPostIds.add(post.id) } - .filter { post -> - post.presentation - ?.plainText() - ?.contains(needle, ignoreCase = true) == true - } - .sortedWith( - compareBy { it.postNumber } - .thenBy { it.id }, - ) - .map { post -> - SearchMatch( - postId = post.id, - postNumber = post.postNumber, - ) - } - .toList() - } - - fun projectRows( - rows: List, - postsById: Map, - expandedReplyRootPostIds: Set = emptySet(), - focusedPostNumber: UInt? = null, - ): List { - val availableRows = rows.mapNotNull { row -> - val post = postsById[row.postId] ?: return@mapNotNull null - ProjectableReplyRow(row = row, post = post) - } - if (availableRows.isEmpty()) return emptyList() - - val rowByPostNumber = availableRows - .mapIndexed { index, projected -> projected.row.postNumber to index } - .toMap() - val rootIndexByIndex = availableRows.indices.associateWith { index -> - rootIndexFor(index, availableRows, rowByPostNumber) - } - val secondaryIndicesByRoot = LinkedHashMap>() - for (index in availableRows.indices) { - val rootIndex = rootIndexByIndex[index] ?: index - if (rootIndex != index) { - secondaryIndicesByRoot.getOrPut(rootIndex) { mutableListOf() }.add(index) - } - } - - val focusedIndex = focusedPostNumber?.let(rowByPostNumber::get) - val focusedSecondaryIndices = focusedIndex - ?.let { selectedAncestryIndices(it, availableRows, rowByPostNumber, rootIndexByIndex) } - .orEmpty() - - return buildList { - availableRows.forEachIndexed { index, projected -> - val rootIndex = rootIndexByIndex[index] ?: index - if (rootIndex != index) return@forEachIndexed - - val secondaryIndices = secondaryIndicesByRoot[index].orEmpty() - val isExpanded = expandedReplyRootPostIds.contains(projected.post.id) - val selectedSecondaryIndices = if (isExpanded) { - secondaryIndices.toSet() - } else { - focusedSecondaryIndices.intersect(secondaryIndices.toSet()) - } - val hiddenReplyCount = (secondaryIndices.size - selectedSecondaryIndices.size).coerceAtLeast(0) - add( - postRow( - projected = projected, - hiddenReplyCount = hiddenReplyCount.toUInt().takeIf { it > 0u } ?: 0u, - ), - ) - secondaryIndices.forEach { secondaryIndex -> - if (!selectedSecondaryIndices.contains(secondaryIndex)) return@forEach - add(postRow(projected = availableRows[secondaryIndex])) - } - } - } - } - - private fun rootIndexFor( - startIndex: Int, - rows: List, - rowByPostNumber: Map, - ): Int { - var index = startIndex - val visited = mutableSetOf() - while (visited.add(index)) { - val row = rows[index].row - val parentNumber = row.parentPostNumber - if (row.depth.toInt() <= 1 || parentNumber == null || parentNumber <= 1u) { - return index - } - index = rowByPostNumber[parentNumber] ?: return index - } - return startIndex - } - - private fun selectedAncestryIndices( - focusedIndex: Int, - rows: List, - rowByPostNumber: Map, - rootIndexByIndex: Map, - ): Set { - val rootIndex = rootIndexByIndex[focusedIndex] ?: focusedIndex - if (rootIndex == focusedIndex) return emptySet() - - val selected = linkedSetOf() - var index = focusedIndex - val visited = mutableSetOf() - while (index != rootIndex && visited.add(index)) { - selected += index - val parentNumber = rows[index].row.parentPostNumber ?: break - index = rowByPostNumber[parentNumber] ?: break - } - return selected - } - - private fun postRow( - projected: ProjectableReplyRow, - hiddenReplyCount: UInt = 0u, - ): PostRow { - return projected.row.let { row -> - PostRow( - post = projected.post, - depth = row.depth.toInt(), - parentPostNumber = row.parentPostNumber, - hasChildren = row.hasChildren, - hiddenReplyCount = hiddenReplyCount, - ) - } - } - - fun postsForDetail( - bodyPost: TopicPostState, - loadedPosts: List, - replyRows: List, - ): List { - val postsById = postsById(listOf(bodyPost) + loadedPosts) - return uniquePosts( - listOf(bodyPost) + replyRows.mapNotNull { row -> - if (row.postId == bodyPost.id) null else postsById[row.postId] - }, - ) - } - - fun postsById(posts: List): Map { - return posts.associateBy { it.id } - } - - fun uniquePosts(posts: List): List { - val postsById = LinkedHashMap(posts.size) - for (post in posts) { - postsById[post.id] = post - } - return postsById.values.toList() - } - - private data class ProjectableReplyRow( - val row: TopicTreeRowState, - val post: TopicPostState, - ) -} - -object TopicDetailBoostPresentation { - const val BODY_BARRAGE_VISIBLE_LINE_LIMIT = 5 - const val BODY_BARRAGE_MAX_LANES = 5 -} diff --git a/apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicDetailPostRowsTest.kt b/apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicDetailPostRowsTest.kt index 06d74784..8e5c1814 100644 --- a/apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicDetailPostRowsTest.kt +++ b/apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicDetailPostRowsTest.kt @@ -248,6 +248,19 @@ class TopicDetailPostRowsTest { assertEquals(listOf(0u, 0u, 0u), projected.map { it.hiddenReplyCount }) } + @Test + fun projectRows_emptySnapshotRowsStayEmptyEvenWhenPostsExist() { + val root = post(id = 2uL, postNumber = 2u, username = "root") + + val projected = TopicDetailPostRows.projectRows( + rows = emptyList(), + postsById = TopicDetailPostRows.postsById(listOf(root)), + expandedReplyRootPostIds = setOf(root.id), + ) + + assertEquals(emptyList(), projected) + } + @Test fun searchMatches_withoutHandleDoesNotInventHostPlainText() { val later = post(id = 3uL, postNumber = 3u, username = "later") diff --git a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelSession.swift b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelSession.swift new file mode 100644 index 00000000..0d883501 --- /dev/null +++ b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelSession.swift @@ -0,0 +1,496 @@ +import Foundation + +struct FireChatPendingUpload { + let fileName: String + let mimeType: String + let bytes: Data +} + +@MainActor +final class FireChatChannelSession { + struct Snapshot { + let channel: ChatChannelState + let messages: [ChatMessageState] + let pins: [ChatMessageState] + let canLoadMorePast: Bool + } + + enum Change { + case cached + case initial + case older(anchorMessageID: UInt64) + case latest + case messageInserted + case messageUpdated(index: Int) + case messageDeleted(index: Int) + case pins + } + + enum Command { + case loadMorePast + case send(message: String, uploads: [FireChatPendingUpload]) + case toggleReaction(messageID: UInt64, emoji: String) + case setPinned(messageID: UInt64, pinned: Bool) + case deleteMessage(messageID: UInt64) + case resolveThread(messageID: UInt64) + } + + enum CommandResult { + case none + case threadID(UInt64) + } + + var onChange: ((Snapshot, Change) -> Void)? + var onRead: ((UInt64) -> Void)? + var onError: ((Error) -> Void)? + + private let viewModel: FireAppViewModel + private let threadID: UInt64? + private let ownerToken: String + private var channel: ChatChannelState + private var messages: [ChatMessageState] = [] + private var pins: [ChatMessageState] = [] + private var canLoadMorePast = false + private var isLoading = false + private var isSending = false + private var lifecycleGeneration: UInt64 = 0 + private var isOpen = false + private var busObserver: NSObjectProtocol? + + init( + channel: ChatChannelState, + viewModel: FireAppViewModel, + threadID: UInt64? + ) { + self.channel = channel + self.viewModel = viewModel + self.threadID = threadID + ownerToken = "chat-channel-\(channel.id)-\(threadID.map(String.init) ?? "main")" + } + + func open() async { + guard !isOpen else { return } + isOpen = true + lifecycleGeneration &+= 1 + let generation = lifecycleGeneration + observeMessageBus() + await applyCachedMessages(generation: generation) + await loadInitial(generation: generation) + } + + func close() { + guard isOpen || busObserver != nil else { return } + isOpen = false + lifecycleGeneration &+= 1 + if let busObserver { + NotificationCenter.default.removeObserver(busObserver) + self.busObserver = nil + } + let channelName = messageBusChannelName + Task { [viewModel, ownerToken] in + try? await viewModel.unsubscribeMessageBusChannel( + channel: channelName, + ownerToken: ownerToken + ) + } + } + + func command(_ command: Command) async throws -> CommandResult { + switch command { + case .loadMorePast: + try await loadMorePast() + return .none + case let .send(message, uploads): + try await send(message: message, uploads: uploads) + return .none + case let .toggleReaction(messageID, emoji): + try await toggleReaction(messageID: messageID, emoji: emoji) + return .none + case let .setPinned(messageID, pinned): + if pinned { + try await viewModel.pinChatMessage(channelID: channel.id, messageID: messageID) + } else { + try await viewModel.unpinChatMessage(channelID: channel.id, messageID: messageID) + } + return .none + case let .deleteMessage(messageID): + try await viewModel.deleteChatMessage(channelID: channel.id, messageID: messageID) + return .none + case let .resolveThread(messageID): + guard let message = messages.first(where: { $0.id == messageID }) else { + throw FireChatChannelSessionError.messageNotFound + } + if let existing = message.threadId ?? message.thread?.id { + return .threadID(existing) + } + let created = try await viewModel.createChatThread( + channelID: channel.id, + originalMessageID: message.id + ) + return .threadID(created) + } + } + + func searchMentions(term: String) async -> [FireBottomInputMention] { + do { + let result = try await viewModel.searchService.searchUsers( + term: term, + includeGroups: true, + limit: 8 + ) + let users = result.users.map { user in + FireBottomInputMention( + handle: user.username, + displayName: user.name?.trimmingCharacters(in: .whitespacesAndNewlines) + ?? user.username + ) + } + let groups = result.groups.map { group in + FireBottomInputMention( + handle: group.name, + displayName: group.fullName?.trimmingCharacters(in: .whitespacesAndNewlines) + ?? group.name + ) + } + return users + groups + } catch { + return [] + } + } + + private var messageBusChannelName: String { + threadID.map { "/chat/\(channel.id)/thread/\($0)" } ?? "/chat/\(channel.id)" + } + + private func observeMessageBus() { + guard busObserver == nil else { return } + busObserver = NotificationCenter.default.addObserver( + forName: .fireChatMessageBusEvent, + object: nil, + queue: .main + ) { [weak self] notification in + guard let event = notification.userInfo?["event"] as? MessageBusEventState else { return } + Task { @MainActor [weak self] in + self?.handleBusEvent(event) + } + } + } + + private func applyCachedMessages(generation: UInt64) async { + guard let cached = try? await viewModel.cachedChatMessages( + channelID: channel.id, + threadID: threadID + ), generation == lifecycleGeneration, isOpen, !cached.messages.isEmpty else { + return + } + messages = cached.messages.sorted { $0.id < $1.id } + canLoadMorePast = cached.canLoadMorePast + emit(.cached) + } + + private func loadInitial(generation: UInt64) async { + guard !isLoading else { return } + isLoading = true + defer { isLoading = false } + do { + if threadID == nil { + let fetchedChannel = try await viewModel.fetchChatChannel(channelID: channel.id) + guard generation == lifecycleGeneration, isOpen else { return } + channel = fetchedChannel + pins = try await viewModel.fetchChatChannelPins(channelID: channel.id) + guard generation == lifecycleGeneration, isOpen else { return } + if !pins.isEmpty { + try? await viewModel.markChatChannelPinsRead(channelID: channel.id) + } + } + + let page = try await fetchMessages(fetchFromLastRead: true) + guard generation == lifecycleGeneration, isOpen else { return } + messages = page.messages.sorted { $0.id < $1.id } + canLoadMorePast = page.canLoadMorePast + await markReadIfNeeded() + guard generation == lifecycleGeneration, isOpen else { return } + try? await viewModel.subscribeMessageBusChannel( + channel: messageBusChannelName, + ownerToken: ownerToken, + lastMessageId: threadID == nil ? channel.busLastIds.channelMessageBusLastId : nil + ) + guard generation == lifecycleGeneration, isOpen else { + try? await viewModel.unsubscribeMessageBusChannel( + channel: messageBusChannelName, + ownerToken: ownerToken + ) + return + } + emit(.initial) + } catch { + guard generation == lifecycleGeneration, isOpen else { return } + onError?(error) + } + } + + private func loadMorePast() async throws { + guard canLoadMorePast, !isLoading, let oldest = messages.first else { return } + isLoading = true + defer { isLoading = false } + let query = ChatMessagesQueryState( + channelId: channel.id, + direction: "past", + targetMessageId: oldest.id, + fetchFromLastRead: false, + pageSize: 50 + ) + let page = try await fetchMessages(query: query) + let older = page.messages.sorted { $0.id < $1.id } + messages = older + messages + canLoadMorePast = page.canLoadMorePast + emit(.older(anchorMessageID: oldest.id)) + } + + private func refreshLatest() async throws { + let page = try await fetchMessages(fetchFromLastRead: false) + messages = page.messages.sorted { $0.id < $1.id } + canLoadMorePast = page.canLoadMorePast + await markReadIfNeeded() + emit(.latest) + } + + private func fetchMessages(fetchFromLastRead: Bool) async throws -> ChatMessagesState { + let query = ChatMessagesQueryState( + channelId: channel.id, + direction: nil, + targetMessageId: nil, + fetchFromLastRead: fetchFromLastRead, + pageSize: 50 + ) + return try await fetchMessages(query: query) + } + + private func fetchMessages(query: ChatMessagesQueryState) async throws -> ChatMessagesState { + if let threadID { + return try await viewModel.fetchChatThreadMessages( + channelID: channel.id, + threadID: threadID, + query: query + ) + } + return try await viewModel.fetchChatMessages(query: query) + } + + private func markReadIfNeeded() async { + if let threadID { + try? await viewModel.markChatThreadRead(channelID: channel.id, threadID: threadID) + } else if let latest = messages.last?.id { + try? await viewModel.markChatChannelRead(channelID: channel.id, messageID: latest) + onRead?(channel.id) + } + } + + private func send(message: String, uploads: [FireChatPendingUpload]) async throws { + guard !isSending else { return } + isSending = true + defer { isSending = false } + + var content = message + var uploadIDs: [UInt64] = [] + for pending in uploads { + let upload = try await viewModel.uploadImage( + fileName: pending.fileName, + mimeType: pending.mimeType, + bytes: pending.bytes + ) + if let uploadID = upload.id, uploadID > 0 { + uploadIDs.append(uploadID) + } else { + let alt = upload.originalFilename?.isEmpty == false + ? upload.originalFilename! + : "image" + let markdown = "![\(alt)](\(upload.shortUrl))" + content = content.isEmpty ? markdown : content + "\n\n" + markdown + } + } + + _ = try await viewModel.sendChatMessage( + request: SendChatMessageRequestState( + channelId: channel.id, + message: content, + stagedId: UUID().uuidString, + inReplyToId: nil, + threadId: threadID, + uploadIds: uploadIDs + ) + ) + try await refreshLatest() + } + + private func toggleReaction(messageID: UInt64, emoji: String) async throws { + guard let message = messages.first(where: { $0.id == messageID }) else { + throw FireChatChannelSessionError.messageNotFound + } + let reacted = message.reactions.first(where: { $0.emoji == emoji })?.reacted == true + try await viewModel.reactChatMessage( + channelID: message.channelId, + messageID: message.id, + emoji: emoji, + reactAction: reacted ? "remove" : "add" + ) + } + + private func handleBusEvent(_ event: MessageBusEventState) { + guard isOpen, event.channel == messageBusChannelName else { return } + let type = event.detailEventType ?? event.messageType + let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" + switch type { + case "sent": + if let message = FireChatBusPayload.chatMessage( + from: event, + fallbackChannelID: channel.id, + baseURLString: baseURLString + ) { + upsertMessage(message, preferAppend: true) + } + case "edit", "processed", "refresh", "restore", "thread_created", + "update_thread_original_message": + if let message = FireChatBusPayload.chatMessage( + from: event, + fallbackChannelID: channel.id, + baseURLString: baseURLString + ) { + upsertMessage(message, preferAppend: false) + } + case "delete": + if case let .messageDeleted(deletedID) = FireChatBusPayload.event( + from: event, + fallbackChannelID: channel.id, + baseURLString: baseURLString + ), let index = messages.firstIndex(where: { $0.id == deletedID }) { + messages.remove(at: index) + emit(.messageDeleted(index: index)) + } + case "reaction": + applyReaction(event) + case "pin": + if let message = FireChatBusPayload.chatMessage( + from: event, + fallbackChannelID: channel.id, + baseURLString: baseURLString + ) { + pins = [message] + pins.filter { $0.id != message.id } + emit(.pins) + } + case "unpin": + if let message = FireChatBusPayload.chatMessage( + from: event, + fallbackChannelID: channel.id, + baseURLString: baseURLString + ) { + pins.removeAll { $0.id == message.id } + emit(.pins) + } + default: + break + } + } + + private func applyReaction(_ event: MessageBusEventState) { + let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" + guard case let .reaction(messageID, emoji, action, actorID) = FireChatBusPayload.event( + from: event, + fallbackChannelID: channel.id, + baseURLString: baseURLString + ), let index = messages.firstIndex(where: { $0.id == messageID }) else { + return + } + var message = messages[index] + var reactions = message.reactions + let isAdd = action == .add + if let existing = reactions.firstIndex(where: { $0.emoji == emoji }) { + let current = reactions[existing] + let nextCount = isAdd ? current.count &+ 1 : (current.count > 0 ? current.count - 1 : 0) + let reacted = isAdd && (current.reacted || actorID == viewModel.currentUserID) + if nextCount == 0 { + reactions.remove(at: existing) + } else { + reactions[existing] = ChatMessageReactionState( + emoji: emoji, + count: nextCount, + reacted: reacted, + users: current.users + ) + } + } else if isAdd { + reactions.append( + ChatMessageReactionState( + emoji: emoji, + count: 1, + reacted: true, + users: [] + ) + ) + } + messages[index] = withReactions(message, reactions) + emit(.messageUpdated(index: index)) + } + + private func upsertMessage(_ message: ChatMessageState, preferAppend: Bool) { + if let index = messages.firstIndex(where: { $0.id == message.id }) { + messages[index] = message + emit(.messageUpdated(index: index)) + return + } + guard preferAppend else { return } + messages.append(message) + emit(.messageInserted) + } + + private func emit(_ change: Change) { + onChange?( + Snapshot( + channel: channel, + messages: messages, + pins: pins, + canLoadMorePast: canLoadMorePast + ), + change + ) + } + + private func withReactions( + _ message: ChatMessageState, + _ reactions: [ChatMessageReactionState] + ) -> ChatMessageState { + ChatMessageState( + id: message.id, + channelId: message.channelId, + message: message.message, + presentation: message.presentation, + excerpt: message.excerpt, + previewText: message.previewText, + createdAt: message.createdAt, + deletedAt: message.deletedAt, + deletedById: message.deletedById, + edited: message.edited, + threadId: message.threadId, + thread: message.thread, + user: message.user, + mentionedUsers: message.mentionedUsers, + reactions: reactions, + uploads: message.uploads, + inReplyTo: message.inReplyTo, + streaming: message.streaming, + availableFlags: message.availableFlags, + userFlagStatus: message.userFlagStatus, + bookmark: message.bookmark, + pinned: message.pinned, + isDeleted: message.isDeleted + ) + } +} + +private enum FireChatChannelSessionError: LocalizedError { + case messageNotFound + + var errorDescription: String? { + "消息已不存在" + } +} diff --git a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Bus.swift b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Bus.swift index 2fabc102..9d835563 100644 --- a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Bus.swift +++ b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Bus.swift @@ -1,121 +1,46 @@ import UIKit extension FireChatChannelViewController { - func handleBusEvent(_ event: MessageBusEventState) { - let expected = threadID.map { "/chat/\(channel.id)/thread/\($0)" } ?? "/chat/\(channel.id)" - guard event.channel == expected else { return } - let type = event.detailEventType ?? event.messageType - let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" - switch type { - case "sent": - if let message = FireChatBusPayload.chatMessage( - from: event, - fallbackChannelID: channel.id, - baseURLString: baseURLString - ) { - upsertMessage(message, preferAppend: true) - } - case "edit", "processed", "refresh", "restore", "thread_created", "update_thread_original_message": - if let message = FireChatBusPayload.chatMessage( - from: event, - fallbackChannelID: channel.id, - baseURLString: baseURLString - ) { - upsertMessage(message, preferAppend: false) - } - case "delete": - if case let .messageDeleted(deletedID) = FireChatBusPayload.event( - from: event, - fallbackChannelID: channel.id, - baseURLString: baseURLString - ), - let index = messages.firstIndex(where: { $0.id == deletedID }) - { - messages.remove(at: index) - tableView.reloadData() - } - case "reaction": - applyReaction(event) - case "pin": - if let message = FireChatBusPayload.chatMessage( - from: event, - fallbackChannelID: channel.id, - baseURLString: baseURLString - ) { - pins = [message] + pins.filter { $0.id != message.id } - updatePinBanner() - } - case "unpin": - if let message = FireChatBusPayload.chatMessage( - from: event, - fallbackChannelID: channel.id, - baseURLString: baseURLString - ) { - pins.removeAll { $0.id == message.id } - updatePinBanner() - } - default: - break - } - } + func applySessionSnapshot( + _ snapshot: FireChatChannelSession.Snapshot, + change: FireChatChannelSession.Change + ) { + let wasNearBottom = isNearBottom() + channel = snapshot.channel + messages = snapshot.messages + pins = snapshot.pins + canLoadMorePast = snapshot.canLoadMorePast + title = isThread ? "消息串" : channel.displayTitle + updatePinBanner() - func applyReaction(_ event: MessageBusEventState) { - let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" - guard case let .reaction(messageID, emoji, action, actorID) = FireChatBusPayload.event( - from: event, - fallbackChannelID: channel.id, - baseURLString: baseURLString - ), - let index = messages.firstIndex(where: { $0.id == messageID }) - else { - return - } - var message = messages[index] - var reactions = message.reactions - let isAdd = action == .add - if let existing = reactions.firstIndex(where: { $0.emoji == emoji }) { - let current = reactions[existing] - let nextCount: UInt32 - let reacted: Bool - if isAdd { - nextCount = current.count &+ 1 - reacted = current.reacted || actorID == viewModel.currentUserID - } else { - nextCount = current.count > 0 ? current.count - 1 : 0 - reacted = false - } - if nextCount == 0 { - reactions.remove(at: existing) - } else { - reactions[existing] = ChatMessageReactionState( - emoji: emoji, - count: nextCount, - reacted: reacted, - users: current.users + switch change { + case .cached, .initial: + tableView.reloadData() + scrollToBottom(animated: false) + case let .older(anchorMessageID): + tableView.reloadData() + if let index = messages.firstIndex(where: { $0.id == anchorMessageID }) { + tableView.scrollToRow( + at: IndexPath(row: index, section: 0), + at: .top, + animated: false ) } - } else if isAdd { - reactions.append( - ChatMessageReactionState(emoji: emoji, count: 1, reacted: true, users: []) - ) - } - message = withReactions(message, reactions) - messages[index] = message - tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none) - } - - func upsertMessage(_ message: ChatMessageState, preferAppend: Bool) { - if let index = messages.firstIndex(where: { $0.id == message.id }) { - messages[index] = message - tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none) - return - } - guard preferAppend else { return } - let wasNearBottom = isNearBottom() - messages.append(message) - tableView.insertRows(at: [IndexPath(row: messages.count - 1, section: 0)], with: .fade) - if wasNearBottom { + case .latest: + tableView.reloadData() scrollToBottom(animated: true) + case .messageInserted: + let inserted = IndexPath(row: messages.count - 1, section: 0) + tableView.insertRows(at: [inserted], with: .fade) + if wasNearBottom { + scrollToBottom(animated: true) + } + case let .messageUpdated(index): + tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none) + case let .messageDeleted(index): + tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .fade) + case .pins: + break } } @@ -125,35 +50,4 @@ extension FireChatChannelViewController { guard let lastVisible = visible.map(\.row).max() else { return true } return lastVisible >= messages.count - 3 } - - func withReactions( - _ message: ChatMessageState, - _ reactions: [ChatMessageReactionState] - ) -> ChatMessageState { - ChatMessageState( - id: message.id, - channelId: message.channelId, - message: message.message, - presentation: message.presentation, - excerpt: message.excerpt, - previewText: message.previewText, - createdAt: message.createdAt, - deletedAt: message.deletedAt, - deletedById: message.deletedById, - edited: message.edited, - threadId: message.threadId, - thread: message.thread, - user: message.user, - mentionedUsers: message.mentionedUsers, - reactions: reactions, - uploads: message.uploads, - inReplyTo: message.inReplyTo, - streaming: message.streaming, - availableFlags: message.availableFlags, - userFlagStatus: message.userFlagStatus, - bookmark: message.bookmark, - pinned: message.pinned, - isDeleted: message.isDeleted - ) - } } diff --git a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Interactions.swift b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Interactions.swift index 6767cc19..911f3b8c 100644 --- a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Interactions.swift +++ b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Interactions.swift @@ -12,28 +12,7 @@ extension FireChatChannelViewController { } func searchChatMentions(term: String) async -> [FireBottomInputMention] { - do { - let result = try await viewModel.searchService.searchUsers( - term: term, - includeGroups: true, - limit: 8 - ) - let users = result.users.map { user in - FireBottomInputMention( - handle: user.username, - displayName: user.name?.trimmingCharacters(in: .whitespacesAndNewlines) ?? user.username - ) - } - let groups = result.groups.map { group in - FireBottomInputMention( - handle: group.name, - displayName: group.fullName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? group.name - ) - } - return users + groups - } catch { - return [] - } + await session.searchMentions(term: term) } func send(payload: FireBottomInputPayload) async { @@ -56,50 +35,21 @@ extension FireChatChannelViewController { ) } do { - var message = trimmed - var uploadIDs: [UInt64] = [] - for image in payload.images { - guard let data = image.fireJPEGDataForUpload() else { continue } - let upload = try await viewModel.uploadImage( + let uploads = payload.images.compactMap { image -> FireChatPendingUpload? in + guard let data = image.fireJPEGDataForUpload() else { return nil } + return FireChatPendingUpload( fileName: "chat-\(UUID().uuidString).jpg", mimeType: "image/jpeg", bytes: data ) - if let uploadID = upload.id, uploadID > 0 { - uploadIDs.append(uploadID) - } else { - let alt = upload.originalFilename?.isEmpty == false - ? upload.originalFilename! - : "image" - let markdown = "![\(alt)](\(upload.shortUrl))" - message = message.isEmpty ? markdown : message + "\n\n" + markdown - } } - await send(message: message, uploadIDs: uploadIDs) + _ = try await session.command(.send(message: trimmed, uploads: uploads)) inputBar.resetAfterSend() } catch { presentError(error) } } - func send(message: String, uploadIDs: [UInt64]) async { - do { - _ = try await viewModel.sendChatMessage( - request: SendChatMessageRequestState( - channelId: channel.id, - message: message, - stagedId: UUID().uuidString, - inReplyToId: nil, - threadId: threadID, - uploadIds: uploadIDs - ) - ) - await softRefreshLatest() - } catch { - presentError(error) - } - } - func presentMessageActions(for message: ChatMessageState) { let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) for emoji in ["heart", "tada", "laughing", "+1", "eyes"] { @@ -119,18 +69,16 @@ extension FireChatChannelViewController { if message.pinned { sheet.addAction(UIAlertAction(title: "取消置顶", style: .default) { [weak self] _ in Task { - try? await self?.viewModel.unpinChatMessage( - channelID: message.channelId, - messageID: message.id + _ = try? await self?.session.command( + .setPinned(messageID: message.id, pinned: false) ) } }) } else { sheet.addAction(UIAlertAction(title: "置顶", style: .default) { [weak self] _ in Task { - try? await self?.viewModel.pinChatMessage( - channelID: message.channelId, - messageID: message.id + _ = try? await self?.session.command( + .setPinned(messageID: message.id, pinned: true) ) } }) @@ -139,10 +87,7 @@ extension FireChatChannelViewController { if message.user?.id == viewModel.currentUserID || channel.canDeleteOthers || channel.canDeleteSelf { sheet.addAction(UIAlertAction(title: "删除", style: .destructive) { [weak self] _ in Task { - try? await self?.viewModel.deleteChatMessage( - channelID: message.channelId, - messageID: message.id - ) + _ = try? await self?.session.command(.deleteMessage(messageID: message.id)) } }) } @@ -155,13 +100,9 @@ extension FireChatChannelViewController { } func toggleReaction(message: ChatMessageState, emoji: String) async { - let reacted = message.reactions.first(where: { $0.emoji == emoji })?.reacted == true do { - try await viewModel.reactChatMessage( - channelID: message.channelId, - messageID: message.id, - emoji: emoji, - reactAction: reacted ? "remove" : "add" + _ = try await session.command( + .toggleReaction(messageID: message.id, emoji: emoji) ) } catch { presentError(error) @@ -170,15 +111,8 @@ extension FireChatChannelViewController { func openThread(for message: ChatMessageState) async { do { - let threadID: UInt64 - if let existing = message.threadId ?? message.thread?.id { - threadID = existing - } else { - threadID = try await viewModel.createChatThread( - channelID: channel.id, - originalMessageID: message.id - ) - } + let result = try await session.command(.resolveThread(messageID: message.id)) + guard case let .threadID(threadID) = result else { return } let controller = FireChatChannelViewController( channel: channel, viewModel: viewModel, diff --git a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Load.swift b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Load.swift index a585c473..cc81eb0b 100644 --- a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Load.swift +++ b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController+Load.swift @@ -1,144 +1,14 @@ import UIKit extension FireChatChannelViewController { - func applyCachedMessages() async { - guard let cached = try? await viewModel.cachedChatMessages( - channelID: channel.id, - threadID: threadID - ), !cached.messages.isEmpty else { - return - } - messages = cached.messages.sorted { $0.id < $1.id } - canLoadMorePast = cached.canLoadMorePast - tableView.reloadData() - scrollToBottom(animated: false) - } - - func loadInitial() async { - guard !isLoading else { return } - isLoading = true - defer { isLoading = false } - do { - if !isThread { - channel = try await viewModel.fetchChatChannel(channelID: channel.id) - title = channel.displayTitle - pins = try await viewModel.fetchChatChannelPins(channelID: channel.id) - updatePinBanner() - if !pins.isEmpty { - try? await viewModel.markChatChannelPinsRead(channelID: channel.id) - } - } - let query = ChatMessagesQueryState( - channelId: channel.id, - direction: nil, - targetMessageId: nil, - fetchFromLastRead: true, - pageSize: 50 - ) - let page: ChatMessagesState - if let threadID { - page = try await viewModel.fetchChatThreadMessages( - channelID: channel.id, - threadID: threadID, - query: query - ) - try? await viewModel.markChatThreadRead(channelID: channel.id, threadID: threadID) - } else { - page = try await viewModel.fetchChatMessages(query: query) - } - // Chronological ascending (Discord channel log). - messages = page.messages.sorted { $0.id < $1.id } - canLoadMorePast = page.canLoadMorePast - tableView.reloadData() - scrollToBottom(animated: false) - if let latest = messages.last?.id, !isThread { - try? await viewModel.markChatChannelRead(channelID: channel.id, messageID: latest) - onRead(channel.id) - } - let busName = threadID.map { "/chat/\(channel.id)/thread/\($0)" } ?? "/chat/\(channel.id)" - let lastID = isThread ? nil : channel.busLastIds.channelMessageBusLastId - try? await viewModel.subscribeMessageBusChannel( - channel: busName, - ownerToken: ownerToken, - lastMessageId: lastID - ) - } catch { - presentError(error) - } - } - func loadMorePast() async { - guard canLoadMorePast, !isLoading, let oldest = messages.first else { return } - isLoading = true - defer { isLoading = false } do { - let query = ChatMessagesQueryState( - channelId: channel.id, - direction: "past", - targetMessageId: oldest.id, - fetchFromLastRead: false, - pageSize: 50 - ) - let page: ChatMessagesState - if let threadID { - page = try await viewModel.fetchChatThreadMessages( - channelID: channel.id, - threadID: threadID, - query: query - ) - } else { - page = try await viewModel.fetchChatMessages(query: query) - } - let older = page.messages.sorted { $0.id < $1.id } - let anchorID = oldest.id - messages = older + messages - canLoadMorePast = page.canLoadMorePast - tableView.reloadData() - // Keep visual position after prepending history. - if let index = messages.firstIndex(where: { $0.id == anchorID }) { - tableView.scrollToRow( - at: IndexPath(row: index, section: 0), - at: .top, - animated: false - ) - } + _ = try await session.command(.loadMorePast) } catch { presentError(error) } } - func softRefreshLatest() async { - do { - let query = ChatMessagesQueryState( - channelId: channel.id, - direction: nil, - targetMessageId: nil, - fetchFromLastRead: false, - pageSize: 50 - ) - let page: ChatMessagesState - if let threadID { - page = try await viewModel.fetchChatThreadMessages( - channelID: channel.id, - threadID: threadID, - query: query - ) - } else { - page = try await viewModel.fetchChatMessages(query: query) - } - messages = page.messages.sorted { $0.id < $1.id } - canLoadMorePast = page.canLoadMorePast - tableView.reloadData() - scrollToBottom(animated: true) - if let latest = messages.last?.id, !isThread { - try? await viewModel.markChatChannelRead(channelID: channel.id, messageID: latest) - onRead(channel.id) - } - } catch { - // Keep bus path as primary; soft refresh failures are non-fatal. - } - } - func scrollToBottom(animated: Bool) { guard !messages.isEmpty else { return } let index = IndexPath(row: messages.count - 1, section: 0) diff --git a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController.swift b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController.swift index 104296ce..baa5b7bf 100644 --- a/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController.swift +++ b/apps/ios-app/App/Chat/Channel/Controller/FireChatChannelViewController.swift @@ -5,15 +5,13 @@ import UIKit final class FireChatChannelViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let viewModel: FireAppViewModel let onRead: (UInt64) -> Void - let ownerToken: String + let session: FireChatChannelSession var channel: ChatChannelState let threadID: UInt64? var messages: [ChatMessageState] = [] var pins: [ChatMessageState] = [] var canLoadMorePast = false - var isLoading = false var isSending = false - var busObserver: NSObjectProtocol? lazy var tableView: UITableView = { let table = UITableView(frame: .zero, style: .plain) @@ -84,9 +82,20 @@ final class FireChatChannelViewController: UIViewController, UITableViewDataSour self.threadID = threadID self.isThread = threadID != nil self.onRead = onRead - self.ownerToken = "chat-channel-\(channel.id)-\(threadID.map(String.init) ?? "main")" + session = FireChatChannelSession( + channel: channel, + viewModel: viewModel, + threadID: threadID + ) super.init(nibName: nil, bundle: nil) title = isThread ? "消息串" : channel.displayTitle + session.onChange = { [weak self] snapshot, change in + self?.applySessionSnapshot(snapshot, change: change) + } + session.onRead = onRead + session.onError = { [weak self] error in + self?.presentError(error) + } } @available(*, unavailable) @@ -104,19 +113,8 @@ final class FireChatChannelViewController: UIViewController, UITableViewDataSour name: UIResponder.keyboardWillChangeFrameNotification, object: nil ) - busObserver = NotificationCenter.default.addObserver( - forName: .fireChatMessageBusEvent, - object: nil, - queue: .main - ) { [weak self] notification in - guard let event = notification.userInfo?["event"] as? MessageBusEventState else { return } - Task { @MainActor in - self?.handleBusEvent(event) - } - } - Task { - await applyCachedMessages() - await loadInitial() + Task { [weak self] in + await self?.session.open() } } @@ -147,16 +145,9 @@ final class FireChatChannelViewController: UIViewController, UITableViewDataSour deinit { NotificationCenter.default.removeObserver(self) - if let busObserver { - NotificationCenter.default.removeObserver(busObserver) - } - let viewModel = viewModel - let ownerToken = ownerToken - let channelID = channel.id - let threadID = threadID - Task { - let channelName = threadID.map { "/chat/\(channelID)/thread/\($0)" } ?? "/chat/\(channelID)" - try? await viewModel.unsubscribeMessageBusChannel(channel: channelName, ownerToken: ownerToken) + let session = session + Task { @MainActor in + session.close() } } diff --git a/apps/ios-app/App/Composer/Controller/FireComposerViewController+Submit.swift b/apps/ios-app/App/Composer/Controller/FireComposerViewController+Submit.swift index 0529f2b5..afafe0ef 100644 --- a/apps/ios-app/App/Composer/Controller/FireComposerViewController+Submit.swift +++ b/apps/ios-app/App/Composer/Controller/FireComposerViewController+Submit.swift @@ -154,7 +154,7 @@ extension FireComposerViewController { func handleSubmissionError(_ error: Error, pendingReviewCompletion: (() -> Void)? = nil) { let message = error.localizedDescription - if message.localizedCaseInsensitiveContains("pending review") { + if FireComposerSession.isPendingReview(error) { Task { [weak self] in guard let self else { return } try? await viewModel.deleteDraft(draftKey: route.draftKey, sequence: draftSequence) diff --git a/apps/ios-app/App/Composer/State/FireComposerSession.swift b/apps/ios-app/App/Composer/State/FireComposerSession.swift new file mode 100644 index 00000000..746814bb --- /dev/null +++ b/apps/ios-app/App/Composer/State/FireComposerSession.swift @@ -0,0 +1,187 @@ +import Foundation + +@MainActor +final class FireComposerSession { + unowned let appViewModel: FireAppViewModel + + init(appViewModel: FireAppViewModel) { + self.appViewModel = appViewModel + } + + static func isPendingReview(_ error: Error) -> Bool { + error.localizedDescription.localizedCaseInsensitiveContains("pending review") + } + + static func normalizedTitle(_ title: String) throws -> String { + let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { + throw FireTopicInteractionError.emptyReply + } + return trimmed + } + + static func normalizedBody(_ raw: String) throws -> String { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { + throw FireTopicInteractionError.emptyReply + } + return trimmed + } + + static func normalizedRecipients(_ recipients: [String]) throws -> [String] { + let normalized = recipients + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + guard !normalized.isEmpty else { + throw FireTopicInteractionError.emptyReply + } + return normalized + } + + func createTopic( + title: String, + raw: String, + categoryID: UInt64, + tags: [String] + ) async throws -> UInt64 { + let trimmedTitle = try Self.normalizedTitle(title) + let trimmedRaw = try Self.normalizedBody(raw) + let sessionStore = try await appViewModel.sessionStoreValue() + guard appViewModel.canStartAuthenticatedMutation else { + throw FireTopicInteractionError.requiresAuthenticatedWrite + } + + do { + appViewModel.errorMessage = nil + let topicID = try await appViewModel.performWriteWithCloudflareRetry { + try await sessionStore.createTopic( + title: trimmedTitle, + raw: trimmedRaw, + categoryID: categoryID, + tags: tags + ) + } + await appViewModel.syncSessionSnapshotIfAvailable(from: sessionStore) + await appViewModel.refreshHomeFeedIfPossible(force: true) + return topicID + } catch { + _ = await appViewModel.handleInteractionError(error) + throw error + } + } + + func createPrivateMessage( + title: String, + raw: String, + targetRecipients: [String] + ) async throws -> UInt64 { + let trimmedTitle = try Self.normalizedTitle(title) + let trimmedRaw = try Self.normalizedBody(raw) + let recipients = try Self.normalizedRecipients(targetRecipients) + let sessionStore = try await appViewModel.sessionStoreValue() + guard appViewModel.canStartAuthenticatedMutation else { + throw FireTopicInteractionError.requiresAuthenticatedWrite + } + + do { + appViewModel.errorMessage = nil + let topicID = try await appViewModel.performWriteWithCloudflareRetry { + try await sessionStore.createPrivateMessage( + title: trimmedTitle, + raw: trimmedRaw, + targetRecipients: recipients + ) + } + await appViewModel.syncSessionSnapshotIfAvailable(from: sessionStore) + return topicID + } catch { + _ = await appViewModel.handleInteractionError(error) + throw error + } + } + + func updateTopic( + topicID: UInt64, + title: String, + categoryID: UInt64, + tags: [String] + ) async throws { + let trimmedTitle = try Self.normalizedTitle(title) + guard appViewModel.canStartAuthenticatedMutation else { + throw FireTopicInteractionError.requiresAuthenticatedWrite + } + + do { + appViewModel.errorMessage = nil + if appViewModel.topicDetailStore != nil { + try await appViewModel.performWriteWithCloudflareRetry { + try await self.appViewModel.topicDetailStore?.updateTopic( + topicId: topicID, + title: trimmedTitle, + categoryId: categoryID, + tags: tags + ) + } + } else { + let sessionStore = try await appViewModel.sessionStoreValue() + try await appViewModel.performWriteWithCloudflareRetry { + try await sessionStore.updateTopic( + topicID: topicID, + title: trimmedTitle, + categoryID: categoryID, + tags: tags + ) + } + await appViewModel.syncSessionSnapshotIfAvailable(from: sessionStore) + } + await appViewModel.refreshHomeFeedIfPossible(force: true) + } catch { + _ = await appViewModel.handleInteractionError(error) + throw error + } + } + + func saveDraft( + draftKey: String, + data: DraftDataState, + sequence: UInt32 + ) async throws -> UInt32 { + let sessionStore = try await appViewModel.sessionStoreValue() + return try await appViewModel.performWriteWithCloudflareRetry { + try await sessionStore.saveDraft( + draftKey: draftKey, + data: data, + sequence: sequence + ) + } + } + + func deleteDraft(draftKey: String, sequence: UInt32? = nil) async throws { + let sessionStore = try await appViewModel.sessionStoreValue() + try await appViewModel.performWriteWithCloudflareRetry { + try await sessionStore.deleteDraft(draftKey: draftKey, sequence: sequence) + } + } + + func uploadImage( + fileName: String, + mimeType: String?, + bytes: Data + ) async throws -> UploadResultState { + let sessionStore = try await appViewModel.sessionStoreValue() + return try await appViewModel.performWriteWithCloudflareRetry { + try await sessionStore.uploadImage( + fileName: fileName, + mimeType: mimeType, + bytes: bytes + ) + } + } + + func lookupUploadUrls(shortUrls: [String]) async throws -> [ResolvedUploadUrlState] { + let sessionStore = try await appViewModel.sessionStoreValue() + return try await appViewModel.performWriteWithCloudflareRetry { + try await sessionStore.lookupUploadUrls(shortUrls: shortUrls) + } + } +} diff --git a/apps/ios-app/App/Core/Components/FireAvatarView.swift b/apps/ios-app/App/Core/Components/FireAvatarView.swift new file mode 100644 index 00000000..7cc5ca9b --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireAvatarView.swift @@ -0,0 +1,83 @@ +import SwiftUI +import UIKit + +private let fireAvatarPlaceholderOpacity = 0.6 +private let fireAvatarCanonicalPixelSize = 384 + + +func fireAvatarURL( + avatarTemplate: String?, + size: CGFloat, + scale: CGFloat, + baseURLString: String = "https://linux.do" +) -> URL? { + guard let avatarTemplate, !avatarTemplate.isEmpty else { + return nil + } + + let displayPixelSize = max(1, Int((size * scale).rounded(.up))) + let pixelSize = max(displayPixelSize, fireAvatarCanonicalPixelSize) + let path = avatarTemplate.replacingOccurrences(of: "{size}", with: "\(pixelSize)") + if path.hasPrefix("http") { + return URL(string: path) + } + if path.hasPrefix("//") { + let scheme = URL(string: baseURLString)?.scheme ?? "https" + return URL(string: "\(scheme):\(path)") + } + return URL(string: path, relativeTo: URL(string: baseURLString))?.absoluteURL +} + +struct FireAvatarView: View { + let avatarTemplate: String? + let username: String + let size: CGFloat + var baseURLString: String = "https://linux.do" + + private var avatarRequest: FireAvatarImageRequest? { + guard let avatarURL = fireAvatarURL( + avatarTemplate: avatarTemplate, + size: size, + scale: UIScreen.main.scale, + baseURLString: baseURLString + ) else { + return nil + } + return FireAvatarImageRequest(url: avatarURL) + } + + private var monogram: String { + monogramForUsername(username: username.isEmpty ? "?" : username) + } + + var body: some View { + FireRemoteImage(request: avatarRequest) { resolvedImage in + Image(uiImage: resolvedImage) + .resizable() + .scaledToFill() + } placeholder: { state in + monogramView + .opacity(state == .loading && avatarRequest != nil ? fireAvatarPlaceholderOpacity : 1) + } + .frame(width: size, height: size) + .clipShape(Circle()) + } + + private var monogramView: some View { + ZStack { + Circle() + .fill( + LinearGradient( + colors: [FireTheme.accent, FireTheme.accentSoft], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + ) + + Text(monogram) + .font(.system(size: size * 0.36, weight: .bold)) + .foregroundStyle(.white) + } + .frame(width: size, height: size) + } +} diff --git a/apps/ios-app/App/Core/Components/FireButtonStyles.swift b/apps/ios-app/App/Core/Components/FireButtonStyles.swift new file mode 100644 index 00000000..173ca000 --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireButtonStyles.swift @@ -0,0 +1,80 @@ +import SwiftUI + +// MARK: - Toolbar Icon + +struct FireToolbarIcon: View { + let symbol: String + + var body: some View { + Image(systemName: symbol) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(FireTheme.subtleInk) + .frame(width: 36, height: 36) + .background( + Circle() + .fill(FireTheme.softSurface) + .overlay( + Circle() + .strokeBorder(FireTheme.divider, lineWidth: 1) + ) + ) + } +} + +// MARK: - Button Styles + +struct FirePrimaryButtonStyle: ButtonStyle { + @Environment(\.isEnabled) private var isEnabled + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.white) + .padding(.horizontal, 16) + .padding(.vertical, 12) + .background( + Capsule() + .fill( + LinearGradient( + colors: [FireTheme.accent, FireTheme.accentSoft], + startPoint: .leading, + endPoint: .trailing + ) + ) + ) + .opacity(isEnabled ? (configuration.isPressed ? 0.92 : 1) : 0.55) + .scaleEffect(configuration.isPressed && !reduceMotion ? 0.94 : 1) + .animation( + .spring(response: 0.28, dampingFraction: 0.55), + value: configuration.isPressed + ) + .animation(.easeOut(duration: 0.15), value: isEnabled) + } +} + +struct FireSecondaryButtonStyle: ButtonStyle { + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.subheadline.weight(.semibold)) + .foregroundStyle(FireTheme.ink) + .padding(.horizontal, 16) + .padding(.vertical, 12) + .background( + Capsule() + .fill(FireTheme.softSurface) + .overlay( + Capsule() + .strokeBorder(FireTheme.divider, lineWidth: 1) + ) + ) + .opacity(configuration.isPressed ? 0.92 : 1) + .scaleEffect(configuration.isPressed && !reduceMotion ? 0.94 : 1) + .animation( + .spring(response: 0.28, dampingFraction: 0.55), + value: configuration.isPressed + ) + } +} diff --git a/apps/ios-app/App/Core/Components/FireErrorStates.swift b/apps/ios-app/App/Core/Components/FireErrorStates.swift new file mode 100644 index 00000000..ab93e24f --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireErrorStates.swift @@ -0,0 +1,161 @@ +import SwiftUI + +// MARK: - Error Banner + +struct FireErrorBanner: View { + let message: String + let copied: Bool + let onCopy: () -> Void + let onDismiss: () -> Void + + var body: some View { + HStack(alignment: .top, spacing: 12) { + Image(systemName: "exclamationmark.triangle.fill") + .font(.headline) + .foregroundStyle(FireTheme.warning) + .padding(.top, 2) + + VStack(alignment: .leading, spacing: 4) { + Text("Error") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(FireTheme.ink) + + Text(message) + .font(.footnote.monospaced()) + .foregroundStyle(FireTheme.subtleInk) + .textSelection(.enabled) + .lineLimit(3) + } + + Spacer(minLength: 12) + + HStack(spacing: 8) { + Button { + onCopy() + } label: { + Image(systemName: copied ? "checkmark" : "doc.on.doc") + .font(.subheadline.weight(.semibold)) + } + .buttonStyle(.plain) + + Button { + onDismiss() + } label: { + Image(systemName: "xmark") + .font(.subheadline.weight(.semibold)) + } + .buttonStyle(.plain) + } + .foregroundStyle(FireTheme.subtleInk) + } + .padding(14) + .background( + RoundedRectangle(cornerRadius: FireTheme.mediumCornerRadius, style: .continuous) + .fill(FireTheme.softSurface) + .overlay( + RoundedRectangle(cornerRadius: FireTheme.mediumCornerRadius, style: .continuous) + .strokeBorder(FireTheme.warning.opacity(0.28), lineWidth: 1) + ) + ) + } +} + +// MARK: - Blocking Error State + +struct FireBlockingErrorState: View { + let title: String + let message: String + let retryTitle: String + let onRetry: () -> Void + + init( + title: String, + message: String, + retryTitle: String = "重试", + onRetry: @escaping () -> Void + ) { + self.title = title + self.message = message + self.retryTitle = retryTitle + self.onRetry = onRetry + } + + var body: some View { + VStack(spacing: 16) { + Image(systemName: "exclamationmark.triangle") + .font(.system(size: 32, weight: .light)) + .foregroundStyle(FireTheme.warning) + + VStack(spacing: 8) { + Text(title) + .font(.headline) + .foregroundStyle(FireTheme.ink) + + Text(message) + .font(.subheadline) + .foregroundStyle(FireTheme.subtleInk) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + } + + Button(retryTitle, action: onRetry) + .buttonStyle(FireSecondaryButtonStyle()) + } + .padding(.horizontal, 24) + .padding(.vertical, 32) + .frame(maxWidth: .infinity) + } +} + +// MARK: - Empty Feed State + +struct FireEmptyFeedState: View { + let systemImage: String + let title: String? + let message: String + let actionTitle: String? + let action: (() -> Void)? + + init( + systemImage: String = "text.bubble", + title: String? = nil, + message: String, + actionTitle: String? = nil, + action: (() -> Void)? = nil + ) { + self.systemImage = systemImage + self.title = title + self.message = message + self.actionTitle = actionTitle + self.action = action + } + + var body: some View { + VStack(spacing: 12) { + Image(systemName: systemImage) + .accessibilityHidden(true) + .font(.title2) + .foregroundStyle(FireTheme.accent) + + if let title { + Text(title) + .font(.headline) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + } + + Text(message) + .font(.subheadline) + .foregroundStyle(FireTheme.subtleInk) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + + if let actionTitle, let action { + Button(actionTitle, action: action) + .buttonStyle(FireSecondaryButtonStyle()) + } + } + .padding(.vertical, 24) + .frame(maxWidth: .infinity) + } +} diff --git a/apps/ios-app/App/Core/Components/FireFeedKindSelector.swift b/apps/ios-app/App/Core/Components/FireFeedKindSelector.swift new file mode 100644 index 00000000..e93bfe24 --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireFeedKindSelector.swift @@ -0,0 +1,45 @@ +import SwiftUI + +// MARK: - Feed Kind Selector + +struct FireFeedKindSelector: View { + let selectedKind: TopicListKindState + let namespace: Namespace.ID + let onSelect: (TopicListKindState) -> Void + + var body: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 4) { + ForEach(TopicListKindState.orderedCases, id: \.self) { kind in + Button { + onSelect(kind) + } label: { + ZStack { + if selectedKind == kind { + Capsule() + .fill(FireTheme.panel) + .matchedGeometryEffect(id: "feed-selection", in: namespace) + } else { + Capsule() + .fill(Color.clear) + } + + Text(kind.title) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(selectedKind == kind ? FireTheme.inverseInk : FireTheme.subtleInk) + .padding(.horizontal, 14) + .padding(.vertical, 8) + } + } + .buttonStyle(.plain) + } + } + .padding(4) + .background( + Capsule() + .fill(FireTheme.track) + ) + } + .scrollIndicators(.hidden) + } +} diff --git a/apps/ios-app/App/Core/Components/FireMetadataComponents.swift b/apps/ios-app/App/Core/Components/FireMetadataComponents.swift new file mode 100644 index 00000000..21160714 --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireMetadataComponents.swift @@ -0,0 +1,195 @@ +import SwiftUI + +// MARK: - Section Lead + +struct FireSectionLead: View { + let eyebrow: String + let title: String + let subtitle: String + var inverse = false + + private var eyebrowColor: Color { + inverse ? FireTheme.inverseSubtleInk : FireTheme.tertiaryInk + } + + private var titleColor: Color { + inverse ? FireTheme.inverseInk : FireTheme.ink + } + + private var subtitleColor: Color { + inverse ? FireTheme.inverseSubtleInk : FireTheme.subtleInk + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + Text(eyebrow) + .font(.caption.weight(.semibold)) + .tracking(1.6) + .foregroundStyle(eyebrowColor) + + Text(title) + .font(.title2.weight(.bold)) + .foregroundStyle(titleColor) + + Text(subtitle) + .font(.subheadline) + .foregroundStyle(subtitleColor) + .fixedSize(horizontal: false, vertical: true) + } + } +} + +// MARK: - Status Chip + +struct FireStatusChip: View { + let label: String + let tone: Tone + var inverse = false + + enum Tone { + case accent + case success + case warning + case muted + } + + private var background: Color { + switch tone { + case .accent: + return FireTheme.accent.opacity(inverse ? 0.2 : 0.12) + case .success: + return FireTheme.success.opacity(inverse ? 0.2 : 0.12) + case .warning: + return FireTheme.warning.opacity(inverse ? 0.18 : 0.12) + case .muted: + return inverse ? FireTheme.inverseDivider : FireTheme.softSurface + } + } + + private var foreground: Color { + switch tone { + case .accent: + return inverse ? FireTheme.accentGlow : FireTheme.accent + case .success: + return FireTheme.success + case .warning: + return FireTheme.warning + case .muted: + return inverse ? FireTheme.inverseSubtleInk : FireTheme.subtleInk + } + } + + var body: some View { + Text(label) + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(background) + .foregroundStyle(foreground) + .clipShape(Capsule()) + } +} + +// MARK: - Topic Pill + +struct FireTopicPill: View { + let label: String + let backgroundColor: Color + let foregroundColor: Color + + var body: some View { + Text(label) + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(backgroundColor) + .foregroundStyle(foregroundColor) + .clipShape(Capsule()) + } +} + +// MARK: - Inline Meta + +struct FireInlineMeta: View { + let label: String + let symbol: String + var color: Color = FireTheme.tertiaryInk + + var body: some View { + Label(label, systemImage: symbol) + .font(.caption2) + .foregroundStyle(color) + } +} + +// MARK: - Metric Tile + +struct FireMetricTile: View { + let label: String + let value: String + var inverse = false + + private var backgroundColor: Color { + inverse ? FireTheme.inverseDivider : FireTheme.softSurface + } + + private var valueColor: Color { + inverse ? FireTheme.inverseInk : FireTheme.ink + } + + private var labelColor: Color { + inverse ? FireTheme.inverseSubtleInk : FireTheme.tertiaryInk + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + Text(value) + .font(.title3.monospacedDigit().weight(.semibold)) + .foregroundStyle(valueColor) + .fireNumericChange(value: value) + + Text(label) + .font(.caption) + .foregroundStyle(labelColor) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14) + .padding(.vertical, 14) + .background( + RoundedRectangle(cornerRadius: FireTheme.mediumCornerRadius, style: .continuous) + .fill(backgroundColor) + ) + } +} + +// MARK: - Key Value Row + +struct FireKeyValueRow: View { + let label: String + let value: String + var inverse = false + + private var labelColor: Color { + inverse ? FireTheme.inverseSubtleInk : FireTheme.subtleInk + } + + private var valueColor: Color { + inverse ? FireTheme.inverseInk : FireTheme.ink + } + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 16) { + Text(label) + .font(.subheadline) + .foregroundStyle(labelColor) + + Spacer() + + Text(value) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(valueColor) + .multilineTextAlignment(.trailing) + } + .padding(.vertical, 12) + } +} diff --git a/apps/ios-app/App/Core/Components/FireOfflineBanner.swift b/apps/ios-app/App/Core/Components/FireOfflineBanner.swift new file mode 100644 index 00000000..6cb9281f --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireOfflineBanner.swift @@ -0,0 +1,40 @@ +import SwiftUI + +// MARK: - Offline Banner + +struct FireOfflineBanner: View { + let message: String + + init(_ message: String = "正在显示离线缓存") { + self.message = message + } + + var body: some View { + HStack(spacing: 10) { + Image(systemName: "wifi.slash") + .font(.footnote.weight(.semibold)) + .accessibilityHidden(true) + + Text(message) + .font(.footnote.weight(.medium)) + .lineLimit(2) + .fixedSize(horizontal: false, vertical: true) + + Spacer(minLength: 0) + } + .foregroundStyle(FireTheme.warning) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .frame(maxWidth: .infinity, alignment: .leading) + .background( + RoundedRectangle(cornerRadius: FireTheme.smallCornerRadius, style: .continuous) + .fill(FireTheme.warning.opacity(0.12)) + .overlay( + RoundedRectangle(cornerRadius: FireTheme.smallCornerRadius, style: .continuous) + .strokeBorder(FireTheme.warning.opacity(0.35), lineWidth: 1) + ) + ) + .accessibilityElement(children: .combine) + .accessibilityLabel(message) + } +} diff --git a/apps/ios-app/App/Core/Components/FirePanel.swift b/apps/ios-app/App/Core/Components/FirePanel.swift new file mode 100644 index 00000000..e5b8945d --- /dev/null +++ b/apps/ios-app/App/Core/Components/FirePanel.swift @@ -0,0 +1,83 @@ +import SwiftUI + +// MARK: - Panel + +enum FirePanelStyle { + case contrast + case chrome + case quiet +} + +struct FirePanel: View { + let style: FirePanelStyle + let padding: CGFloat + @ViewBuilder let content: Content + + init( + style: FirePanelStyle, + padding: CGFloat = 20, + @ViewBuilder content: () -> Content + ) { + self.style = style + self.padding = padding + self.content = content() + } + + private var fillStyle: AnyShapeStyle { + switch style { + case .contrast: + return AnyShapeStyle( + LinearGradient( + colors: [FireTheme.panel, FireTheme.panelElevated], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + ) + case .chrome: + return AnyShapeStyle( + LinearGradient( + colors: [FireTheme.chromeStrong, FireTheme.chrome], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + ) + case .quiet: + return AnyShapeStyle(FireTheme.softSurface) + } + } + + private var borderColor: Color { + switch style { + case .contrast: + return FireTheme.inverseDivider + case .chrome: + return FireTheme.chromeBorder + case .quiet: + return FireTheme.divider + } + } + + private var shadowColor: Color { + switch style { + case .contrast: + return FireTheme.contrastPanelShadow + case .chrome, .quiet: + return FireTheme.panelShadow + } + } + + var body: some View { + content + .padding(padding) + .frame(maxWidth: .infinity, alignment: .leading) + .background( + RoundedRectangle(cornerRadius: FireTheme.cornerRadius, style: .continuous) + .fill(fillStyle) + .overlay( + RoundedRectangle(cornerRadius: FireTheme.cornerRadius, style: .continuous) + .strokeBorder(borderColor, lineWidth: 1) + ) + ) + .shadow(color: shadowColor, radius: FireTheme.panelShadowRadius, y: FireTheme.panelShadowY) + } +} diff --git a/apps/ios-app/App/Core/Components/FireRemoteImage.swift b/apps/ios-app/App/Core/Components/FireRemoteImage.swift new file mode 100644 index 00000000..90ebe905 --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireRemoteImage.swift @@ -0,0 +1,197 @@ +import Nuke +import SwiftUI +import UIKit + +struct FireRemoteImageRequest: Hashable, Sendable { + let url: URL + + var cacheKey: String { + url.absoluteString + } +} + +typealias FireAvatarImageRequest = FireRemoteImageRequest + +enum FireRemoteImagePipelineError: Error { + case badServerResponse + case invalidImageData +} + +typealias FireAvatarImagePipelineError = FireRemoteImagePipelineError + +final class FireRemoteImageMemoryCache: @unchecked Sendable { + static let shared = FireRemoteImageMemoryCache() + + private let storage: NSCache + + init( + countLimit: Int = 256, + totalCostLimit: Int = 48 * 1024 * 1024, + storage: NSCache = NSCache() + ) { + self.storage = storage + self.storage.countLimit = countLimit + self.storage.totalCostLimit = totalCostLimit + } + + func image(for key: String) -> UIImage? { + storage.object(forKey: key as NSString) + } + + func insert(_ image: UIImage, for key: String) { + storage.setObject(image, forKey: key as NSString, cost: image.fireMemoryCost) + } + + func removeAllObjects() { + storage.removeAllObjects() + } +} + +typealias FireAvatarImageMemoryCache = FireRemoteImageMemoryCache + +final class FireRemoteImagePipeline: @unchecked Sendable { + static let shared = FireRemoteImagePipeline(pipeline: makeDefaultPipeline()) + + private let pipeline: ImagePipeline + private let prefetcher: ImagePrefetcher + + init(pipeline: ImagePipeline = makeDefaultPipeline()) { + self.pipeline = pipeline + self.prefetcher = ImagePrefetcher(pipeline: pipeline) + } + + func cachedImage(for request: FireRemoteImageRequest) -> UIImage? { + pipeline.cache.cachedImage(for: nukeRequest(for: request))?.image + } + + func loadImage(for request: FireRemoteImageRequest) async throws -> UIImage { + try await pipeline.image(for: nukeRequest(for: request)) + } + + func prefetch(_ requests: [FireRemoteImageRequest]) { + prefetcher.startPrefetching(with: requests.map(nukeRequest(for:))) + } + + func stopPrefetching(_ requests: [FireRemoteImageRequest]) { + prefetcher.stopPrefetching(with: requests.map(nukeRequest(for:))) + } + + private static func makeDefaultPipeline() -> ImagePipeline { + ImagePipeline( + configuration: .withDataCache( + name: "com.fire.remote-images", + sizeLimit: 128 * 1024 * 1024 + ) + ) + } + + private func nukeRequest(for request: FireRemoteImageRequest) -> ImageRequest { + ImageRequest(url: request.url) + } +} + +typealias FireAvatarImagePipeline = FireRemoteImagePipeline + +enum FireRemoteImagePlaceholderState: Equatable { + case loading + case failure + case missingRequest +} + +struct FireRemoteImage: View { + let request: FireRemoteImageRequest? + private let content: (UIImage) -> Content + private let placeholder: (FireRemoteImagePlaceholderState) -> Placeholder + + @State private var loadedImage: UIImage? + @State private var loadedImageKey: String? + @State private var loadFailed = false + + init( + request: FireRemoteImageRequest?, + @ViewBuilder content: @escaping (UIImage) -> Content, + @ViewBuilder placeholder: @escaping (FireRemoteImagePlaceholderState) -> Placeholder + ) { + self.request = request + self.content = content + self.placeholder = placeholder + } + + private var resolvedImage: UIImage? { + guard let request else { + return nil + } + if loadedImageKey == request.cacheKey, let loadedImage { + return loadedImage + } + return FireRemoteImagePipeline.shared.cachedImage(for: request) + } + + var body: some View { + Group { + if let resolvedImage { + content(resolvedImage) + } else if request != nil { + placeholder(loadFailed ? .failure : .loading) + } else { + placeholder(.missingRequest) + } + } + .task(id: request?.cacheKey) { + await loadImageIfNeeded() + } + } + + @MainActor + private func loadImageIfNeeded() async { + guard let request else { + loadedImage = nil + loadedImageKey = nil + loadFailed = false + return + } + + if loadedImageKey == request.cacheKey, loadedImage != nil { + loadFailed = false + return + } + + if let cachedImage = FireRemoteImagePipeline.shared.cachedImage(for: request) { + loadedImage = cachedImage + loadedImageKey = request.cacheKey + loadFailed = false + return + } + + if loadedImageKey != request.cacheKey { + loadedImage = nil + loadedImageKey = nil + } + loadFailed = false + + do { + let image = try await FireRemoteImagePipeline.shared.loadImage(for: request) + guard !Task.isCancelled else { + return + } + loadedImage = image + loadedImageKey = request.cacheKey + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { + return + } + loadFailed = true + } + } +} + +private extension UIImage { + var fireMemoryCost: Int { + guard let cgImage else { + return 0 + } + return cgImage.bytesPerRow * cgImage.height + } +} diff --git a/apps/ios-app/App/Core/Components/FireSceneBackground.swift b/apps/ios-app/App/Core/Components/FireSceneBackground.swift new file mode 100644 index 00000000..0c61a954 --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireSceneBackground.swift @@ -0,0 +1,28 @@ +import SwiftUI + +// MARK: - Scene Background + +struct FireSceneBackground: View { + var body: some View { + LinearGradient( + colors: [FireTheme.canvasTop, FireTheme.canvasMid, FireTheme.canvasBottom], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + .overlay(alignment: .topLeading) { + Circle() + .fill(FireTheme.accent.opacity(0.12)) + .frame(width: 260, height: 260) + .blur(radius: 54) + .offset(x: -80, y: -90) + } + .overlay(alignment: .bottomTrailing) { + Circle() + .fill(FireTheme.accentSoft.opacity(0.08)) + .frame(width: 280, height: 280) + .blur(radius: 70) + .offset(x: 90, y: 80) + } + .ignoresSafeArea() + } +} diff --git a/apps/ios-app/App/Core/Components/FireSkeleton.swift b/apps/ios-app/App/Core/Components/FireSkeleton.swift new file mode 100644 index 00000000..c303dc10 --- /dev/null +++ b/apps/ios-app/App/Core/Components/FireSkeleton.swift @@ -0,0 +1,111 @@ +import SwiftUI + +// MARK: - Skeleton List + +struct FireTopicSkeletonRow: View { + var avatarSize: CGFloat = 38 + var subtitleWidth: CGFloat = 120 + var showsTrailingMeta = true + var verticalPadding: CGFloat = 12 + + var body: some View { + HStack(spacing: 12) { + Circle() + .fill(FireTheme.track) + .frame(width: avatarSize, height: avatarSize) + + VStack(alignment: .leading, spacing: 6) { + RoundedRectangle(cornerRadius: 4, style: .continuous) + .fill(FireTheme.chromeStrong) + .frame(height: 14) + + RoundedRectangle(cornerRadius: 4, style: .continuous) + .fill(FireTheme.track) + .frame(width: subtitleWidth, height: 10) + } + + Spacer() + + if showsTrailingMeta { + RoundedRectangle(cornerRadius: 4, style: .continuous) + .fill(FireTheme.track) + .frame(width: 28, height: 20) + } + } + .padding(.vertical, verticalPadding) + .fireShimmer() + .accessibilityHidden(true) + } +} + +struct FireTopicSkeletonList: View { + var rowCount = 6 + var avatarSize: CGFloat = 38 + var subtitleWidth: CGFloat = 120 + var showsTrailingMeta = true + var verticalPadding: CGFloat = 12 + + var body: some View { + VStack(spacing: 0) { + ForEach(0..? + + func body(content: Content) -> some View { + content + .overlay(alignment: .top) { + if let toast { + FireToastView(toast: toast) + .padding(.top, topPadding) + .padding(.horizontal, 16) + .transition(.move(edge: .top).combined(with: .opacity)) + } + } + .animation(.easeOut(duration: 0.25), value: toast) + .onChange(of: toast) { newToast in + scheduleDismiss(for: newToast) + } + .onDisappear { + dismissTask?.cancel() + dismissTask = nil + } + } + + private func scheduleDismiss(for toast: FireToast?) { + dismissTask?.cancel() + guard let toast else { + dismissTask = nil + return + } + let toastID = toast.id + dismissTask = Task { @MainActor in + do { + try await Task.sleep(for: .seconds(2.5)) + } catch { + return + } + guard self.toast?.id == toastID else { + return + } + withAnimation(.easeOut(duration: 0.25)) { + self.toast = nil + } + } + } +} + +extension View { + func fireToast(_ toast: Binding, topPadding: CGFloat = 60) -> some View { + modifier(FireToastModifier(toast: toast, topPadding: topPadding)) + } +} diff --git a/apps/ios-app/App/Core/Components/FlowLayout.swift b/apps/ios-app/App/Core/Components/FlowLayout.swift new file mode 100644 index 00000000..a7c0ecc9 --- /dev/null +++ b/apps/ios-app/App/Core/Components/FlowLayout.swift @@ -0,0 +1,80 @@ +import SwiftUI +import UIKit + +// MARK: - Flow Layout + +struct FlowLayout: Layout { + var spacing: CGFloat = 6 + var fallbackWidth: CGFloat? = nil + + func sizeThatFits( + proposal: ProposedViewSize, + subviews: Subviews, + cache: inout () + ) -> CGSize { + let maxWidth = resolvedMaxWidth(for: proposal) + let hasExplicitWidth = proposal.width.map { $0.isFinite && $0 > 0 } ?? false + var lineWidth: CGFloat = 0 + var lineHeight: CGFloat = 0 + var totalHeight: CGFloat = 0 + var maxLineWidth: CGFloat = 0 + + for subview in subviews { + let size = subview.sizeThatFits(.unspecified) + if lineWidth > 0, lineWidth + spacing + size.width > maxWidth { + totalHeight += lineHeight + spacing + maxLineWidth = max(maxLineWidth, lineWidth) + lineWidth = size.width + lineHeight = size.height + } else { + lineWidth += (lineWidth > 0 ? spacing : 0) + size.width + lineHeight = max(lineHeight, size.height) + } + } + + totalHeight += lineHeight + maxLineWidth = max(maxLineWidth, lineWidth) + + let reportedWidth = hasExplicitWidth ? maxWidth : maxLineWidth + return CGSize(width: reportedWidth, height: totalHeight) + } + + func placeSubviews( + in bounds: CGRect, + proposal: ProposedViewSize, + subviews: Subviews, + cache: inout () + ) { + var cursor = CGPoint(x: bounds.minX, y: bounds.minY) + var lineHeight: CGFloat = 0 + + for subview in subviews { + let size = subview.sizeThatFits(.unspecified) + if cursor.x > bounds.minX, cursor.x + size.width > bounds.maxX { + cursor.x = bounds.minX + cursor.y += lineHeight + spacing + lineHeight = 0 + } + + subview.place( + at: cursor, + proposal: ProposedViewSize(width: size.width, height: size.height) + ) + + cursor.x += size.width + spacing + lineHeight = max(lineHeight, size.height) + } + } + + private func resolvedMaxWidth(for proposal: ProposedViewSize) -> CGFloat { + if let proposalWidth = proposal.width, proposalWidth.isFinite, proposalWidth > 0 { + return proposalWidth + } + + if let fallbackWidth, fallbackWidth.isFinite, fallbackWidth > 0 { + return fallbackWidth + } + + return max(UIScreen.main.bounds.width - 120, 180) + } +} diff --git a/apps/ios-app/App/Core/Components/String+FireIfEmpty.swift b/apps/ios-app/App/Core/Components/String+FireIfEmpty.swift new file mode 100644 index 00000000..b5941467 --- /dev/null +++ b/apps/ios-app/App/Core/Components/String+FireIfEmpty.swift @@ -0,0 +1,9 @@ +import Foundation + +// MARK: - String Extension + +extension String { + func ifEmpty(_ fallback: String) -> String { + isEmpty ? fallback : self + } +} diff --git a/apps/ios-app/App/Core/FireComponents.swift b/apps/ios-app/App/Core/FireComponents.swift deleted file mode 100644 index c98c6302..00000000 --- a/apps/ios-app/App/Core/FireComponents.swift +++ /dev/null @@ -1,1236 +0,0 @@ -import Nuke -import SwiftUI -import UIKit - -// MARK: - Toast - -enum FireToastStyle: Equatable { - case success - case error - case info - case warning - - var iconName: String { - switch self { - case .success: - return "checkmark.circle.fill" - case .error: - return "xmark.circle.fill" - case .info: - return "info.circle.fill" - case .warning: - return "exclamationmark.triangle.fill" - } - } - - var tintColor: Color { - switch self { - case .success: - return FireTheme.success - case .error: - return Color.red - case .info: - return FireTheme.accent - case .warning: - return FireTheme.warning - } - } -} - -struct FireToast: Equatable, Identifiable { - let id: UUID - let message: String - let style: FireToastStyle - - init(message: String, style: FireToastStyle = .info) { - self.id = UUID() - self.message = message - self.style = style - } -} - -struct FireToastView: View { - let toast: FireToast - - var body: some View { - HStack(alignment: .center, spacing: 10) { - Image(systemName: toast.style.iconName) - .font(.system(size: 18, weight: .semibold)) - .foregroundStyle(toast.style.tintColor) - .accessibilityHidden(true) - - Text(toast.message) - .font(.subheadline) - .foregroundStyle(FireTheme.ink) - .lineLimit(3) - .fixedSize(horizontal: false, vertical: true) - - Spacer(minLength: 0) - } - .padding(.horizontal, 16) - .padding(.vertical, 12) - .frame(maxWidth: .infinity, alignment: .leading) - .background( - RoundedRectangle(cornerRadius: FireTheme.smallCornerRadius, style: .continuous) - .fill(FireTheme.chromeStrong) - .overlay( - RoundedRectangle(cornerRadius: FireTheme.smallCornerRadius, style: .continuous) - .strokeBorder(FireTheme.chromeBorder, lineWidth: 1) - ) - ) - .shadow(color: FireTheme.panelShadow, radius: 12, y: 4) - .accessibilityElement(children: .ignore) - .accessibilityLabel(toast.message) - } -} - -private struct FireToastModifier: ViewModifier { - @Binding var toast: FireToast? - let topPadding: CGFloat - @State private var dismissTask: Task? - - func body(content: Content) -> some View { - content - .overlay(alignment: .top) { - if let toast { - FireToastView(toast: toast) - .padding(.top, topPadding) - .padding(.horizontal, 16) - .transition(.move(edge: .top).combined(with: .opacity)) - } - } - .animation(.easeOut(duration: 0.25), value: toast) - .onChange(of: toast) { newToast in - scheduleDismiss(for: newToast) - } - .onDisappear { - dismissTask?.cancel() - dismissTask = nil - } - } - - private func scheduleDismiss(for toast: FireToast?) { - dismissTask?.cancel() - guard let toast else { - dismissTask = nil - return - } - let toastID = toast.id - dismissTask = Task { @MainActor in - do { - try await Task.sleep(for: .seconds(2.5)) - } catch { - return - } - guard self.toast?.id == toastID else { - return - } - withAnimation(.easeOut(duration: 0.25)) { - self.toast = nil - } - } - } -} - -extension View { - func fireToast(_ toast: Binding, topPadding: CGFloat = 60) -> some View { - modifier(FireToastModifier(toast: toast, topPadding: topPadding)) - } -} - -// MARK: - Offline Banner - -struct FireOfflineBanner: View { - let message: String - - init(_ message: String = "正在显示离线缓存") { - self.message = message - } - - var body: some View { - HStack(spacing: 10) { - Image(systemName: "wifi.slash") - .font(.footnote.weight(.semibold)) - .accessibilityHidden(true) - - Text(message) - .font(.footnote.weight(.medium)) - .lineLimit(2) - .fixedSize(horizontal: false, vertical: true) - - Spacer(minLength: 0) - } - .foregroundStyle(FireTheme.warning) - .padding(.horizontal, 14) - .padding(.vertical, 10) - .frame(maxWidth: .infinity, alignment: .leading) - .background( - RoundedRectangle(cornerRadius: FireTheme.smallCornerRadius, style: .continuous) - .fill(FireTheme.warning.opacity(0.12)) - .overlay( - RoundedRectangle(cornerRadius: FireTheme.smallCornerRadius, style: .continuous) - .strokeBorder(FireTheme.warning.opacity(0.35), lineWidth: 1) - ) - ) - .accessibilityElement(children: .combine) - .accessibilityLabel(message) - } -} - -// MARK: - Scene Background - -struct FireSceneBackground: View { - var body: some View { - LinearGradient( - colors: [FireTheme.canvasTop, FireTheme.canvasMid, FireTheme.canvasBottom], - startPoint: .topLeading, - endPoint: .bottomTrailing - ) - .overlay(alignment: .topLeading) { - Circle() - .fill(FireTheme.accent.opacity(0.12)) - .frame(width: 260, height: 260) - .blur(radius: 54) - .offset(x: -80, y: -90) - } - .overlay(alignment: .bottomTrailing) { - Circle() - .fill(FireTheme.accentSoft.opacity(0.08)) - .frame(width: 280, height: 280) - .blur(radius: 70) - .offset(x: 90, y: 80) - } - .ignoresSafeArea() - } -} - -// MARK: - Panel - -enum FirePanelStyle { - case contrast - case chrome - case quiet -} - -struct FirePanel: View { - let style: FirePanelStyle - let padding: CGFloat - @ViewBuilder let content: Content - - init( - style: FirePanelStyle, - padding: CGFloat = 20, - @ViewBuilder content: () -> Content - ) { - self.style = style - self.padding = padding - self.content = content() - } - - private var fillStyle: AnyShapeStyle { - switch style { - case .contrast: - return AnyShapeStyle( - LinearGradient( - colors: [FireTheme.panel, FireTheme.panelElevated], - startPoint: .topLeading, - endPoint: .bottomTrailing - ) - ) - case .chrome: - return AnyShapeStyle( - LinearGradient( - colors: [FireTheme.chromeStrong, FireTheme.chrome], - startPoint: .topLeading, - endPoint: .bottomTrailing - ) - ) - case .quiet: - return AnyShapeStyle(FireTheme.softSurface) - } - } - - private var borderColor: Color { - switch style { - case .contrast: - return FireTheme.inverseDivider - case .chrome: - return FireTheme.chromeBorder - case .quiet: - return FireTheme.divider - } - } - - private var shadowColor: Color { - switch style { - case .contrast: - return FireTheme.contrastPanelShadow - case .chrome, .quiet: - return FireTheme.panelShadow - } - } - - var body: some View { - content - .padding(padding) - .frame(maxWidth: .infinity, alignment: .leading) - .background( - RoundedRectangle(cornerRadius: FireTheme.cornerRadius, style: .continuous) - .fill(fillStyle) - .overlay( - RoundedRectangle(cornerRadius: FireTheme.cornerRadius, style: .continuous) - .strokeBorder(borderColor, lineWidth: 1) - ) - ) - .shadow(color: shadowColor, radius: FireTheme.panelShadowRadius, y: FireTheme.panelShadowY) - } -} - -// MARK: - Section Lead - -struct FireSectionLead: View { - let eyebrow: String - let title: String - let subtitle: String - var inverse = false - - private var eyebrowColor: Color { - inverse ? FireTheme.inverseSubtleInk : FireTheme.tertiaryInk - } - - private var titleColor: Color { - inverse ? FireTheme.inverseInk : FireTheme.ink - } - - private var subtitleColor: Color { - inverse ? FireTheme.inverseSubtleInk : FireTheme.subtleInk - } - - var body: some View { - VStack(alignment: .leading, spacing: 6) { - Text(eyebrow) - .font(.caption.weight(.semibold)) - .tracking(1.6) - .foregroundStyle(eyebrowColor) - - Text(title) - .font(.title2.weight(.bold)) - .foregroundStyle(titleColor) - - Text(subtitle) - .font(.subheadline) - .foregroundStyle(subtitleColor) - .fixedSize(horizontal: false, vertical: true) - } - } -} - -// MARK: - Status Chip - -struct FireStatusChip: View { - let label: String - let tone: Tone - var inverse = false - - enum Tone { - case accent - case success - case warning - case muted - } - - private var background: Color { - switch tone { - case .accent: - return FireTheme.accent.opacity(inverse ? 0.2 : 0.12) - case .success: - return FireTheme.success.opacity(inverse ? 0.2 : 0.12) - case .warning: - return FireTheme.warning.opacity(inverse ? 0.18 : 0.12) - case .muted: - return inverse ? FireTheme.inverseDivider : FireTheme.softSurface - } - } - - private var foreground: Color { - switch tone { - case .accent: - return inverse ? FireTheme.accentGlow : FireTheme.accent - case .success: - return FireTheme.success - case .warning: - return FireTheme.warning - case .muted: - return inverse ? FireTheme.inverseSubtleInk : FireTheme.subtleInk - } - } - - var body: some View { - Text(label) - .font(.caption2.weight(.semibold)) - .padding(.horizontal, 8) - .padding(.vertical, 4) - .background(background) - .foregroundStyle(foreground) - .clipShape(Capsule()) - } -} - -// MARK: - Topic Pill - -struct FireTopicPill: View { - let label: String - let backgroundColor: Color - let foregroundColor: Color - - var body: some View { - Text(label) - .font(.caption2.weight(.semibold)) - .padding(.horizontal, 8) - .padding(.vertical, 4) - .background(backgroundColor) - .foregroundStyle(foregroundColor) - .clipShape(Capsule()) - } -} - -// MARK: - Inline Meta - -struct FireInlineMeta: View { - let label: String - let symbol: String - var color: Color = FireTheme.tertiaryInk - - var body: some View { - Label(label, systemImage: symbol) - .font(.caption2) - .foregroundStyle(color) - } -} - -// MARK: - Metric Tile - -struct FireMetricTile: View { - let label: String - let value: String - var inverse = false - - private var backgroundColor: Color { - inverse ? FireTheme.inverseDivider : FireTheme.softSurface - } - - private var valueColor: Color { - inverse ? FireTheme.inverseInk : FireTheme.ink - } - - private var labelColor: Color { - inverse ? FireTheme.inverseSubtleInk : FireTheme.tertiaryInk - } - - var body: some View { - VStack(alignment: .leading, spacing: 6) { - Text(value) - .font(.title3.monospacedDigit().weight(.semibold)) - .foregroundStyle(valueColor) - .fireNumericChange(value: value) - - Text(label) - .font(.caption) - .foregroundStyle(labelColor) - } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 14) - .padding(.vertical, 14) - .background( - RoundedRectangle(cornerRadius: FireTheme.mediumCornerRadius, style: .continuous) - .fill(backgroundColor) - ) - } -} - -// MARK: - Key Value Row - -struct FireKeyValueRow: View { - let label: String - let value: String - var inverse = false - - private var labelColor: Color { - inverse ? FireTheme.inverseSubtleInk : FireTheme.subtleInk - } - - private var valueColor: Color { - inverse ? FireTheme.inverseInk : FireTheme.ink - } - - var body: some View { - HStack(alignment: .firstTextBaseline, spacing: 16) { - Text(label) - .font(.subheadline) - .foregroundStyle(labelColor) - - Spacer() - - Text(value) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(valueColor) - .multilineTextAlignment(.trailing) - } - .padding(.vertical, 12) - } -} - -// MARK: - Error Banner - -struct FireErrorBanner: View { - let message: String - let copied: Bool - let onCopy: () -> Void - let onDismiss: () -> Void - - var body: some View { - HStack(alignment: .top, spacing: 12) { - Image(systemName: "exclamationmark.triangle.fill") - .font(.headline) - .foregroundStyle(FireTheme.warning) - .padding(.top, 2) - - VStack(alignment: .leading, spacing: 4) { - Text("Error") - .font(.subheadline.weight(.semibold)) - .foregroundStyle(FireTheme.ink) - - Text(message) - .font(.footnote.monospaced()) - .foregroundStyle(FireTheme.subtleInk) - .textSelection(.enabled) - .lineLimit(3) - } - - Spacer(minLength: 12) - - HStack(spacing: 8) { - Button { - onCopy() - } label: { - Image(systemName: copied ? "checkmark" : "doc.on.doc") - .font(.subheadline.weight(.semibold)) - } - .buttonStyle(.plain) - - Button { - onDismiss() - } label: { - Image(systemName: "xmark") - .font(.subheadline.weight(.semibold)) - } - .buttonStyle(.plain) - } - .foregroundStyle(FireTheme.subtleInk) - } - .padding(14) - .background( - RoundedRectangle(cornerRadius: FireTheme.mediumCornerRadius, style: .continuous) - .fill(FireTheme.softSurface) - .overlay( - RoundedRectangle(cornerRadius: FireTheme.mediumCornerRadius, style: .continuous) - .strokeBorder(FireTheme.warning.opacity(0.28), lineWidth: 1) - ) - ) - } -} - -// MARK: - Blocking Error State - -struct FireBlockingErrorState: View { - let title: String - let message: String - let retryTitle: String - let onRetry: () -> Void - - init( - title: String, - message: String, - retryTitle: String = "重试", - onRetry: @escaping () -> Void - ) { - self.title = title - self.message = message - self.retryTitle = retryTitle - self.onRetry = onRetry - } - - var body: some View { - VStack(spacing: 16) { - Image(systemName: "exclamationmark.triangle") - .font(.system(size: 32, weight: .light)) - .foregroundStyle(FireTheme.warning) - - VStack(spacing: 8) { - Text(title) - .font(.headline) - .foregroundStyle(FireTheme.ink) - - Text(message) - .font(.subheadline) - .foregroundStyle(FireTheme.subtleInk) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) - } - - Button(retryTitle, action: onRetry) - .buttonStyle(FireSecondaryButtonStyle()) - } - .padding(.horizontal, 24) - .padding(.vertical, 32) - .frame(maxWidth: .infinity) - } -} - -// MARK: - Empty Feed State - -struct FireEmptyFeedState: View { - let systemImage: String - let title: String? - let message: String - let actionTitle: String? - let action: (() -> Void)? - - init( - systemImage: String = "text.bubble", - title: String? = nil, - message: String, - actionTitle: String? = nil, - action: (() -> Void)? = nil - ) { - self.systemImage = systemImage - self.title = title - self.message = message - self.actionTitle = actionTitle - self.action = action - } - - var body: some View { - VStack(spacing: 12) { - Image(systemName: systemImage) - .accessibilityHidden(true) - .font(.title2) - .foregroundStyle(FireTheme.accent) - - if let title { - Text(title) - .font(.headline) - .foregroundStyle(.secondary) - .multilineTextAlignment(.center) - } - - Text(message) - .font(.subheadline) - .foregroundStyle(FireTheme.subtleInk) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) - - if let actionTitle, let action { - Button(actionTitle, action: action) - .buttonStyle(FireSecondaryButtonStyle()) - } - } - .padding(.vertical, 24) - .frame(maxWidth: .infinity) - } -} - -// MARK: - Skeleton List - -struct FireTopicSkeletonRow: View { - var avatarSize: CGFloat = 38 - var subtitleWidth: CGFloat = 120 - var showsTrailingMeta = true - var verticalPadding: CGFloat = 12 - - var body: some View { - HStack(spacing: 12) { - Circle() - .fill(FireTheme.track) - .frame(width: avatarSize, height: avatarSize) - - VStack(alignment: .leading, spacing: 6) { - RoundedRectangle(cornerRadius: 4, style: .continuous) - .fill(FireTheme.chromeStrong) - .frame(height: 14) - - RoundedRectangle(cornerRadius: 4, style: .continuous) - .fill(FireTheme.track) - .frame(width: subtitleWidth, height: 10) - } - - Spacer() - - if showsTrailingMeta { - RoundedRectangle(cornerRadius: 4, style: .continuous) - .fill(FireTheme.track) - .frame(width: 28, height: 20) - } - } - .padding(.vertical, verticalPadding) - .fireShimmer() - .accessibilityHidden(true) - } -} - -struct FireTopicSkeletonList: View { - var rowCount = 6 - var avatarSize: CGFloat = 38 - var subtitleWidth: CGFloat = 120 - var showsTrailingMeta = true - var verticalPadding: CGFloat = 12 - - var body: some View { - VStack(spacing: 0) { - ForEach(0.. Void - - var body: some View { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 4) { - ForEach(TopicListKindState.orderedCases, id: \.self) { kind in - Button { - onSelect(kind) - } label: { - ZStack { - if selectedKind == kind { - Capsule() - .fill(FireTheme.panel) - .matchedGeometryEffect(id: "feed-selection", in: namespace) - } else { - Capsule() - .fill(Color.clear) - } - - Text(kind.title) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(selectedKind == kind ? FireTheme.inverseInk : FireTheme.subtleInk) - .padding(.horizontal, 14) - .padding(.vertical, 8) - } - } - .buttonStyle(.plain) - } - } - .padding(4) - .background( - Capsule() - .fill(FireTheme.track) - ) - } - .scrollIndicators(.hidden) - } -} - -// MARK: - Toolbar Icon - -struct FireToolbarIcon: View { - let symbol: String - - var body: some View { - Image(systemName: symbol) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(FireTheme.subtleInk) - .frame(width: 36, height: 36) - .background( - Circle() - .fill(FireTheme.softSurface) - .overlay( - Circle() - .strokeBorder(FireTheme.divider, lineWidth: 1) - ) - ) - } -} - -// MARK: - Button Styles - -struct FirePrimaryButtonStyle: ButtonStyle { - @Environment(\.isEnabled) private var isEnabled - @Environment(\.accessibilityReduceMotion) private var reduceMotion - - func makeBody(configuration: Configuration) -> some View { - configuration.label - .font(.subheadline.weight(.semibold)) - .foregroundStyle(.white) - .padding(.horizontal, 16) - .padding(.vertical, 12) - .background( - Capsule() - .fill( - LinearGradient( - colors: [FireTheme.accent, FireTheme.accentSoft], - startPoint: .leading, - endPoint: .trailing - ) - ) - ) - .opacity(isEnabled ? (configuration.isPressed ? 0.92 : 1) : 0.55) - .scaleEffect(configuration.isPressed && !reduceMotion ? 0.94 : 1) - .animation( - .spring(response: 0.28, dampingFraction: 0.55), - value: configuration.isPressed - ) - .animation(.easeOut(duration: 0.15), value: isEnabled) - } -} - -struct FireSecondaryButtonStyle: ButtonStyle { - @Environment(\.accessibilityReduceMotion) private var reduceMotion - - func makeBody(configuration: Configuration) -> some View { - configuration.label - .font(.subheadline.weight(.semibold)) - .foregroundStyle(FireTheme.ink) - .padding(.horizontal, 16) - .padding(.vertical, 12) - .background( - Capsule() - .fill(FireTheme.softSurface) - .overlay( - Capsule() - .strokeBorder(FireTheme.divider, lineWidth: 1) - ) - ) - .opacity(configuration.isPressed ? 0.92 : 1) - .scaleEffect(configuration.isPressed && !reduceMotion ? 0.94 : 1) - .animation( - .spring(response: 0.28, dampingFraction: 0.55), - value: configuration.isPressed - ) - } -} - -// MARK: - Flow Layout - -struct FlowLayout: Layout { - var spacing: CGFloat = 6 - var fallbackWidth: CGFloat? = nil - - func sizeThatFits( - proposal: ProposedViewSize, - subviews: Subviews, - cache: inout () - ) -> CGSize { - let maxWidth = resolvedMaxWidth(for: proposal) - let hasExplicitWidth = proposal.width.map { $0.isFinite && $0 > 0 } ?? false - var lineWidth: CGFloat = 0 - var lineHeight: CGFloat = 0 - var totalHeight: CGFloat = 0 - var maxLineWidth: CGFloat = 0 - - for subview in subviews { - let size = subview.sizeThatFits(.unspecified) - if lineWidth > 0, lineWidth + spacing + size.width > maxWidth { - totalHeight += lineHeight + spacing - maxLineWidth = max(maxLineWidth, lineWidth) - lineWidth = size.width - lineHeight = size.height - } else { - lineWidth += (lineWidth > 0 ? spacing : 0) + size.width - lineHeight = max(lineHeight, size.height) - } - } - - totalHeight += lineHeight - maxLineWidth = max(maxLineWidth, lineWidth) - - let reportedWidth = hasExplicitWidth ? maxWidth : maxLineWidth - return CGSize(width: reportedWidth, height: totalHeight) - } - - func placeSubviews( - in bounds: CGRect, - proposal: ProposedViewSize, - subviews: Subviews, - cache: inout () - ) { - var cursor = CGPoint(x: bounds.minX, y: bounds.minY) - var lineHeight: CGFloat = 0 - - for subview in subviews { - let size = subview.sizeThatFits(.unspecified) - if cursor.x > bounds.minX, cursor.x + size.width > bounds.maxX { - cursor.x = bounds.minX - cursor.y += lineHeight + spacing - lineHeight = 0 - } - - subview.place( - at: cursor, - proposal: ProposedViewSize(width: size.width, height: size.height) - ) - - cursor.x += size.width + spacing - lineHeight = max(lineHeight, size.height) - } - } - - private func resolvedMaxWidth(for proposal: ProposedViewSize) -> CGFloat { - if let proposalWidth = proposal.width, proposalWidth.isFinite, proposalWidth > 0 { - return proposalWidth - } - - if let fallbackWidth, fallbackWidth.isFinite, fallbackWidth > 0 { - return fallbackWidth - } - - return max(UIScreen.main.bounds.width - 120, 180) - } -} - -// MARK: - Avatar View - -private let fireAvatarPlaceholderOpacity = 0.6 -private let fireAvatarCanonicalPixelSize = 384 - -struct FireRemoteImageRequest: Hashable, Sendable { - let url: URL - - var cacheKey: String { - url.absoluteString - } -} - -typealias FireAvatarImageRequest = FireRemoteImageRequest - -enum FireRemoteImagePipelineError: Error { - case badServerResponse - case invalidImageData -} - -typealias FireAvatarImagePipelineError = FireRemoteImagePipelineError - -final class FireRemoteImageMemoryCache: @unchecked Sendable { - static let shared = FireRemoteImageMemoryCache() - - private let storage: NSCache - - init( - countLimit: Int = 256, - totalCostLimit: Int = 48 * 1024 * 1024, - storage: NSCache = NSCache() - ) { - self.storage = storage - self.storage.countLimit = countLimit - self.storage.totalCostLimit = totalCostLimit - } - - func image(for key: String) -> UIImage? { - storage.object(forKey: key as NSString) - } - - func insert(_ image: UIImage, for key: String) { - storage.setObject(image, forKey: key as NSString, cost: image.fireMemoryCost) - } - - func removeAllObjects() { - storage.removeAllObjects() - } -} - -typealias FireAvatarImageMemoryCache = FireRemoteImageMemoryCache - -final class FireRemoteImagePipeline: @unchecked Sendable { - static let shared = FireRemoteImagePipeline(pipeline: makeDefaultPipeline()) - - private let pipeline: ImagePipeline - private let prefetcher: ImagePrefetcher - - init(pipeline: ImagePipeline = makeDefaultPipeline()) { - self.pipeline = pipeline - self.prefetcher = ImagePrefetcher(pipeline: pipeline) - } - - func cachedImage(for request: FireRemoteImageRequest) -> UIImage? { - pipeline.cache.cachedImage(for: nukeRequest(for: request))?.image - } - - func loadImage(for request: FireRemoteImageRequest) async throws -> UIImage { - try await pipeline.image(for: nukeRequest(for: request)) - } - - func prefetch(_ requests: [FireRemoteImageRequest]) { - prefetcher.startPrefetching(with: requests.map(nukeRequest(for:))) - } - - func stopPrefetching(_ requests: [FireRemoteImageRequest]) { - prefetcher.stopPrefetching(with: requests.map(nukeRequest(for:))) - } - - private static func makeDefaultPipeline() -> ImagePipeline { - ImagePipeline( - configuration: .withDataCache( - name: "com.fire.remote-images", - sizeLimit: 128 * 1024 * 1024 - ) - ) - } - - private func nukeRequest(for request: FireRemoteImageRequest) -> ImageRequest { - ImageRequest(url: request.url) - } -} - -typealias FireAvatarImagePipeline = FireRemoteImagePipeline - -enum FireRemoteImagePlaceholderState: Equatable { - case loading - case failure - case missingRequest -} - -struct FireRemoteImage: View { - let request: FireRemoteImageRequest? - private let content: (UIImage) -> Content - private let placeholder: (FireRemoteImagePlaceholderState) -> Placeholder - - @State private var loadedImage: UIImage? - @State private var loadedImageKey: String? - @State private var loadFailed = false - - init( - request: FireRemoteImageRequest?, - @ViewBuilder content: @escaping (UIImage) -> Content, - @ViewBuilder placeholder: @escaping (FireRemoteImagePlaceholderState) -> Placeholder - ) { - self.request = request - self.content = content - self.placeholder = placeholder - } - - private var resolvedImage: UIImage? { - guard let request else { - return nil - } - if loadedImageKey == request.cacheKey, let loadedImage { - return loadedImage - } - return FireRemoteImagePipeline.shared.cachedImage(for: request) - } - - var body: some View { - Group { - if let resolvedImage { - content(resolvedImage) - } else if request != nil { - placeholder(loadFailed ? .failure : .loading) - } else { - placeholder(.missingRequest) - } - } - .task(id: request?.cacheKey) { - await loadImageIfNeeded() - } - } - - @MainActor - private func loadImageIfNeeded() async { - guard let request else { - loadedImage = nil - loadedImageKey = nil - loadFailed = false - return - } - - if loadedImageKey == request.cacheKey, loadedImage != nil { - loadFailed = false - return - } - - if let cachedImage = FireRemoteImagePipeline.shared.cachedImage(for: request) { - loadedImage = cachedImage - loadedImageKey = request.cacheKey - loadFailed = false - return - } - - if loadedImageKey != request.cacheKey { - loadedImage = nil - loadedImageKey = nil - } - loadFailed = false - - do { - let image = try await FireRemoteImagePipeline.shared.loadImage(for: request) - guard !Task.isCancelled else { - return - } - loadedImage = image - loadedImageKey = request.cacheKey - } catch is CancellationError { - return - } catch { - guard !Task.isCancelled else { - return - } - loadFailed = true - } - } -} - -func fireAvatarURL( - avatarTemplate: String?, - size: CGFloat, - scale: CGFloat, - baseURLString: String = "https://linux.do" -) -> URL? { - guard let avatarTemplate, !avatarTemplate.isEmpty else { - return nil - } - - let displayPixelSize = max(1, Int((size * scale).rounded(.up))) - let pixelSize = max(displayPixelSize, fireAvatarCanonicalPixelSize) - let path = avatarTemplate.replacingOccurrences(of: "{size}", with: "\(pixelSize)") - if path.hasPrefix("http") { - return URL(string: path) - } - if path.hasPrefix("//") { - let scheme = URL(string: baseURLString)?.scheme ?? "https" - return URL(string: "\(scheme):\(path)") - } - return URL(string: path, relativeTo: URL(string: baseURLString))?.absoluteURL -} - -private extension UIImage { - var fireMemoryCost: Int { - guard let cgImage else { - return 0 - } - return cgImage.bytesPerRow * cgImage.height - } -} - -struct FireAvatarView: View { - let avatarTemplate: String? - let username: String - let size: CGFloat - var baseURLString: String = "https://linux.do" - - private var avatarRequest: FireAvatarImageRequest? { - guard let avatarURL = fireAvatarURL( - avatarTemplate: avatarTemplate, - size: size, - scale: UIScreen.main.scale, - baseURLString: baseURLString - ) else { - return nil - } - return FireAvatarImageRequest(url: avatarURL) - } - - private var monogram: String { - monogramForUsername(username: username.isEmpty ? "?" : username) - } - - var body: some View { - FireRemoteImage(request: avatarRequest) { resolvedImage in - Image(uiImage: resolvedImage) - .resizable() - .scaledToFill() - } placeholder: { state in - monogramView - .opacity(state == .loading && avatarRequest != nil ? fireAvatarPlaceholderOpacity : 1) - } - .frame(width: size, height: size) - .clipShape(Circle()) - } - - private var monogramView: some View { - ZStack { - Circle() - .fill( - LinearGradient( - colors: [FireTheme.accent, FireTheme.accentSoft], - startPoint: .topLeading, - endPoint: .bottomTrailing - ) - ) - - Text(monogram) - .font(.system(size: size * 0.36, weight: .bold)) - .foregroundStyle(.white) - } - .frame(width: size, height: size) - } -} - -// MARK: - String Extension - -extension String { - func ifEmpty(_ fallback: String) -> String { - isEmpty ? fallback : self - } -} diff --git a/apps/ios-app/App/Core/FireMainCardAnimator.swift b/apps/ios-app/App/Core/FireMainCardAnimator.swift new file mode 100644 index 00000000..adbbbc64 --- /dev/null +++ b/apps/ios-app/App/Core/FireMainCardAnimator.swift @@ -0,0 +1,131 @@ +import UIKit + +final class FireMainCardAnimator: NSObject, UIViewControllerAnimatedTransitioning { + enum Operation { + case push + case pop + } + + private let duration: TimeInterval = 0.28 + private let operation: Operation + private let parallaxDistanceRatio: CGFloat + var navigationBarSnapshot: UIView? + weak var navigationBarSnapshotHost: UIView? + + init(operation: Operation, parallaxDistanceRatio: CGFloat) { + self.operation = operation + self.parallaxDistanceRatio = parallaxDistanceRatio + } + + func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { + duration + } + + func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { + guard let fromView = transitionContext.view(forKey: .from), + let toView = transitionContext.view(forKey: .to) else { + transitionContext.completeTransition(!transitionContext.transitionWasCancelled) + return + } + + let containerView = transitionContext.containerView + let width = max(containerView.bounds.width, 1) + let toViewController = transitionContext.viewController(forKey: .to) + if let toViewController { + toView.frame = transitionContext.finalFrame(for: toViewController) + } else { + toView.frame = containerView.bounds + } + + switch operation { + case .push: + // Incoming secondary page slides from the right over the still tab shell. + toView.transform = CGAffineTransform(translationX: width, y: 0) + containerView.addSubview(toView) + applyOutgoingShadow(to: toView) + + UIView.animate( + withDuration: transitionDuration(using: transitionContext), + delay: 0, + options: [.curveEaseOut, .allowUserInteraction], + animations: { + toView.transform = .identity + fromView.transform = CGAffineTransform(translationX: -width * self.parallaxDistanceRatio, y: 0) + }, + completion: { _ in + let cancelled = transitionContext.transitionWasCancelled + fromView.transform = .identity + toView.transform = .identity + self.clearOutgoingShadow(from: toView) + if cancelled { + toView.removeFromSuperview() + } + transitionContext.completeTransition(!cancelled) + } + ) + + case .pop: + // Outgoing page slides right. Optional nav-bar snapshot rides with it so the real + // bar (already swapped to the destination) stays covered — WeChat whole-page card. + toView.transform = CGAffineTransform(translationX: -width * parallaxDistanceRatio, y: 0) + containerView.insertSubview(toView, belowSubview: fromView) + applyOutgoingShadow(to: fromView) + + let barSnapshot = navigationBarSnapshot + let barHost = navigationBarSnapshotHost + navigationBarSnapshot = nil + navigationBarSnapshotHost = nil + if let barSnapshot, let barHost { + let barFrame: CGRect + if let navigationBar = transitionContext.viewController(forKey: .from)?.navigationController?.navigationBar { + barFrame = navigationBar.convert(navigationBar.bounds, to: barHost) + } else { + barFrame = CGRect( + x: 0, + y: barHost.safeAreaInsets.top, + width: barHost.bounds.width, + height: max(barSnapshot.bounds.height, 44) + ) + } + barSnapshot.frame = barFrame + barHost.addSubview(barSnapshot) + } + + UIView.animate( + withDuration: transitionDuration(using: transitionContext), + delay: 0, + options: [.curveEaseOut, .allowUserInteraction], + animations: { + fromView.transform = CGAffineTransform(translationX: width, y: 0) + barSnapshot?.transform = CGAffineTransform(translationX: width, y: 0) + toView.transform = .identity + }, + completion: { _ in + let cancelled = transitionContext.transitionWasCancelled + fromView.transform = .identity + toView.transform = .identity + barSnapshot?.removeFromSuperview() + self.clearOutgoingShadow(from: fromView) + if cancelled { + toView.removeFromSuperview() + } + transitionContext.completeTransition(!cancelled) + } + ) + } + } + + private func applyOutgoingShadow(to view: UIView) { + view.layer.shadowColor = UIColor.black.cgColor + view.layer.shadowOpacity = 0.18 + view.layer.shadowRadius = 12 + view.layer.shadowOffset = CGSize(width: -3, height: 0) + } + + private func clearOutgoingShadow(from view: UIView) { + view.layer.shadowOpacity = 0 + view.layer.shadowRadius = 0 + view.layer.shadowOffset = .zero + view.layer.shadowColor = nil + } +} diff --git a/apps/ios-app/App/Core/FireMainNavigationController.swift b/apps/ios-app/App/Core/FireMainNavigationController.swift new file mode 100644 index 00000000..1f909c52 --- /dev/null +++ b/apps/ios-app/App/Core/FireMainNavigationController.swift @@ -0,0 +1,270 @@ +import UIKit + +/// Tab-owned and secondary-page navigation shell. +/// +/// Secondary topic routes are presented full-screen above the tab shell (Android multi-Activity +/// analogue). That presented host sets `allowsInteractiveDismissWhenAtRoot` so the root page can +/// swipe away and reveal the untouched tab bar underneath. In-stack pops also carry a navigation-bar +/// snapshot so chrome slides with the outgoing page. +final class FireMainNavigationController: UINavigationController, + UIGestureRecognizerDelegate, + UINavigationControllerDelegate, + UIViewControllerTransitioningDelegate +{ + private enum FullScreenPop { + static let parallaxDistanceRatio: CGFloat = 0.28 + static let finishProgress: CGFloat = 0.34 + static let finishVelocityX: CGFloat = 720 + static let horizontalBias: CGFloat = 1.08 + } + + /// When true, a rightward pan on the root controller interactively dismisses this + /// navigation controller (used by the app-root secondary page stack). + var allowsInteractiveDismissWhenAtRoot = false + + /// Called after this controller finishes dismissing as a presented secondary stack. + var onDidDismissCompletely: (() -> Void)? + + private let hidesNavigationBarAtRoot: Bool + private lazy var popAnimator = FireMainCardAnimator( + operation: .pop, + parallaxDistanceRatio: FullScreenPop.parallaxDistanceRatio + ) + private lazy var presentAnimator = FireMainCardAnimator( + operation: .push, + parallaxDistanceRatio: FullScreenPop.parallaxDistanceRatio + ) + private lazy var dismissAnimator = FireMainCardAnimator( + operation: .pop, + parallaxDistanceRatio: FullScreenPop.parallaxDistanceRatio + ) + private var interactionController: UIPercentDrivenInteractiveTransition? + private var isInteractiveDismiss = false + private var pendingNavigationBarSnapshot: UIView? + private lazy var fullScreenPopGestureRecognizer: UIPanGestureRecognizer = { + let gesture = UIPanGestureRecognizer( + target: self, + action: #selector(handleFullScreenPopPan(_:)) + ) + gesture.maximumNumberOfTouches = 1 + gesture.cancelsTouchesInView = false + gesture.delegate = self + return gesture + }() + + init(rootViewController: UIViewController, hidesNavigationBarAtRoot: Bool = false) { + self.hidesNavigationBarAtRoot = hidesNavigationBarAtRoot + super.init(rootViewController: rootViewController) + delegate = self + transitioningDelegate = self + setNavigationBarHidden(hidesNavigationBarAtRoot, animated: false) + } + + override func viewDidLoad() { + super.viewDidLoad() + interactivePopGestureRecognizer?.isEnabled = false + view.addGestureRecognizer(fullScreenPopGestureRecognizer) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) is not supported") + } + + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + // Secondary stack finished dismissing — release the root coordinator's host reference. + guard allowsInteractiveDismissWhenAtRoot, isBeingDismissed else { return } + let callback = onDidDismissCompletely + onDidDismissCompletely = nil + callback?() + } + + override func pushViewController(_ viewController: UIViewController, animated: Bool) { + if !viewControllers.isEmpty { + setNavigationBarHidden(false, animated: animated) + } + super.pushViewController(viewController, animated: animated) + } + + @discardableResult + override func popViewController(animated: Bool) -> UIViewController? { + if animated, viewControllers.count > 1 { + captureNavigationBarSnapshotIfNeeded() + } + return super.popViewController(animated: animated) + } + + @objc private func handleFullScreenPopPan(_ gestureRecognizer: UIPanGestureRecognizer) { + let translation = gestureRecognizer.translation(in: view) + let progress = min(max(translation.x / max(view.bounds.width, 1), 0), 1) + + switch gestureRecognizer.state { + case .began: + interactionController = UIPercentDrivenInteractiveTransition() + if viewControllers.count > 1 { + isInteractiveDismiss = false + if popViewController(animated: true) == nil { + clearInteractionState() + } + } else if canInteractivelyDismissRoot { + isInteractiveDismiss = true + pendingNavigationBarSnapshot = nil + dismiss(animated: true) + } else { + clearInteractionState() + } + case .changed: + interactionController?.update(progress) + case .ended: + let velocityX = gestureRecognizer.velocity(in: view).x + if shouldFinishFullScreenPop(progress: progress, velocityX: velocityX) { + interactionController?.finish() + } else { + interactionController?.cancel() + } + clearInteractionState() + case .cancelled, .failed: + interactionController?.cancel() + clearInteractionState() + default: + break + } + } + + func canBeginFullScreenPop(velocity: CGPoint) -> Bool { + guard transitionCoordinator == nil, + presentedViewController == nil, + velocity.x > 0 else { + return false + } + let canPop = viewControllers.count > 1 + let canDismiss = canInteractivelyDismissRoot + guard canPop || canDismiss else { + return false + } + return abs(velocity.x) > abs(velocity.y) * FullScreenPop.horizontalBias + } + + func shouldFinishFullScreenPop(progress: CGFloat, velocityX: CGFloat) -> Bool { + progress >= FullScreenPop.finishProgress || velocityX >= FullScreenPop.finishVelocityX + } + + func navigationController( + _ navigationController: UINavigationController, + willShow viewController: UIViewController, + animated: Bool + ) { + updateNavigationBarVisibility(for: viewController, animated: animated) + interactivePopGestureRecognizer?.isEnabled = false + updateSecondaryRootBackItemIfNeeded(for: viewController) + } + + /// Root page of the secondary stack has no system back target — provide an explicit dismiss control. + private func updateSecondaryRootBackItemIfNeeded(for viewController: UIViewController) { + guard allowsInteractiveDismissWhenAtRoot else { return } + let isRoot = viewControllers.first === viewController + guard isRoot else { return } + // Leave pages that already own their chrome (e.g. topic detail) untouched. + if viewController.navigationItem.leftBarButtonItem != nil + || !(viewController.navigationItem.leftBarButtonItems ?? []).isEmpty { + return + } + let dismissItem = UIBarButtonItem( + image: UIImage(systemName: "chevron.backward"), + style: .plain, + target: self, + action: #selector(dismissSecondaryRoot) + ) + dismissItem.accessibilityLabel = "返回" + viewController.navigationItem.leftBarButtonItem = dismissItem + } + + @objc private func dismissSecondaryRoot() { + dismiss(animated: true) + } + + func navigationController( + _ navigationController: UINavigationController, + animationControllerFor operation: UINavigationController.Operation, + from fromVC: UIViewController, + to toVC: UIViewController + ) -> UIViewControllerAnimatedTransitioning? { + guard operation == .pop else { return nil } + popAnimator.navigationBarSnapshot = pendingNavigationBarSnapshot + popAnimator.navigationBarSnapshotHost = view + pendingNavigationBarSnapshot = nil + return popAnimator + } + + func navigationController( + _ navigationController: UINavigationController, + interactionControllerFor animationController: UIViewControllerAnimatedTransitioning + ) -> UIViewControllerInteractiveTransitioning? { + isInteractiveDismiss ? nil : interactionController + } + + func animationController( + forPresented presented: UIViewController, + presenting: UIViewController, + source: UIViewController + ) -> UIViewControllerAnimatedTransitioning? { + guard presented === self else { return nil } + presentAnimator.navigationBarSnapshot = nil + presentAnimator.navigationBarSnapshotHost = nil + return presentAnimator + } + + func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { + guard dismissed === self else { return nil } + dismissAnimator.navigationBarSnapshot = nil + dismissAnimator.navigationBarSnapshotHost = nil + return dismissAnimator + } + + func interactionControllerForDismissal( + using animator: UIViewControllerAnimatedTransitioning + ) -> UIViewControllerInteractiveTransitioning? { + isInteractiveDismiss ? interactionController : nil + } + + func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + guard gestureRecognizer === fullScreenPopGestureRecognizer, + let panGesture = gestureRecognizer as? UIPanGestureRecognizer else { + return true + } + return canBeginFullScreenPop(velocity: panGesture.velocity(in: view)) + } + + func gestureRecognizer( + _ gestureRecognizer: UIGestureRecognizer, + shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer + ) -> Bool { + false + } + + func updateNavigationBarVisibility(for viewController: UIViewController, animated: Bool) { + let isRoot = viewControllers.first === viewController + setNavigationBarHidden(hidesNavigationBarAtRoot && isRoot, animated: animated) + } + + private var canInteractivelyDismissRoot: Bool { + allowsInteractiveDismissWhenAtRoot + && viewControllers.count <= 1 + && presentingViewController != nil + && presentedViewController == nil + } + + private func captureNavigationBarSnapshotIfNeeded() { + guard !isNavigationBarHidden else { + pendingNavigationBarSnapshot = nil + return + } + pendingNavigationBarSnapshot = navigationBar.snapshotView(afterScreenUpdates: false) + } + + private func clearInteractionState() { + interactionController = nil + isInteractiveDismiss = false + } +} diff --git a/apps/ios-app/App/Core/FireMainTabBarController.swift b/apps/ios-app/App/Core/FireMainTabBarController.swift index 95571715..62702175 100644 --- a/apps/ios-app/App/Core/FireMainTabBarController.swift +++ b/apps/ios-app/App/Core/FireMainTabBarController.swift @@ -151,404 +151,6 @@ final class FireMainTabBarController: UITabBarController, UITabBarControllerDele } } -/// Tab-owned and secondary-page navigation shell. -/// -/// Secondary topic routes are presented full-screen above the tab shell (Android multi-Activity -/// analogue). That presented host sets `allowsInteractiveDismissWhenAtRoot` so the root page can -/// swipe away and reveal the untouched tab bar underneath. In-stack pops also carry a navigation-bar -/// snapshot so chrome slides with the outgoing page. -final class FireMainNavigationController: UINavigationController, - UIGestureRecognizerDelegate, - UINavigationControllerDelegate, - UIViewControllerTransitioningDelegate -{ - private enum FullScreenPop { - static let parallaxDistanceRatio: CGFloat = 0.28 - static let finishProgress: CGFloat = 0.34 - static let finishVelocityX: CGFloat = 720 - static let horizontalBias: CGFloat = 1.08 - } - - /// When true, a rightward pan on the root controller interactively dismisses this - /// navigation controller (used by the app-root secondary page stack). - var allowsInteractiveDismissWhenAtRoot = false - - /// Called after this controller finishes dismissing as a presented secondary stack. - var onDidDismissCompletely: (() -> Void)? - - private let hidesNavigationBarAtRoot: Bool - private lazy var popAnimator = FireMainCardAnimator( - operation: .pop, - parallaxDistanceRatio: FullScreenPop.parallaxDistanceRatio - ) - private lazy var presentAnimator = FireMainCardAnimator( - operation: .push, - parallaxDistanceRatio: FullScreenPop.parallaxDistanceRatio - ) - private lazy var dismissAnimator = FireMainCardAnimator( - operation: .pop, - parallaxDistanceRatio: FullScreenPop.parallaxDistanceRatio - ) - private var interactionController: UIPercentDrivenInteractiveTransition? - private var isInteractiveDismiss = false - private var pendingNavigationBarSnapshot: UIView? - private lazy var fullScreenPopGestureRecognizer: UIPanGestureRecognizer = { - let gesture = UIPanGestureRecognizer( - target: self, - action: #selector(handleFullScreenPopPan(_:)) - ) - gesture.maximumNumberOfTouches = 1 - gesture.cancelsTouchesInView = false - gesture.delegate = self - return gesture - }() - - init(rootViewController: UIViewController, hidesNavigationBarAtRoot: Bool = false) { - self.hidesNavigationBarAtRoot = hidesNavigationBarAtRoot - super.init(rootViewController: rootViewController) - delegate = self - transitioningDelegate = self - setNavigationBarHidden(hidesNavigationBarAtRoot, animated: false) - } - - override func viewDidLoad() { - super.viewDidLoad() - interactivePopGestureRecognizer?.isEnabled = false - view.addGestureRecognizer(fullScreenPopGestureRecognizer) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) is not supported") - } - - override func viewDidDisappear(_ animated: Bool) { - super.viewDidDisappear(animated) - // Secondary stack finished dismissing — release the root coordinator's host reference. - guard allowsInteractiveDismissWhenAtRoot, isBeingDismissed else { return } - let callback = onDidDismissCompletely - onDidDismissCompletely = nil - callback?() - } - - override func pushViewController(_ viewController: UIViewController, animated: Bool) { - if !viewControllers.isEmpty { - setNavigationBarHidden(false, animated: animated) - } - super.pushViewController(viewController, animated: animated) - } - - @discardableResult - override func popViewController(animated: Bool) -> UIViewController? { - if animated, viewControllers.count > 1 { - captureNavigationBarSnapshotIfNeeded() - } - return super.popViewController(animated: animated) - } - - @objc private func handleFullScreenPopPan(_ gestureRecognizer: UIPanGestureRecognizer) { - let translation = gestureRecognizer.translation(in: view) - let progress = min(max(translation.x / max(view.bounds.width, 1), 0), 1) - - switch gestureRecognizer.state { - case .began: - interactionController = UIPercentDrivenInteractiveTransition() - if viewControllers.count > 1 { - isInteractiveDismiss = false - if popViewController(animated: true) == nil { - clearInteractionState() - } - } else if canInteractivelyDismissRoot { - isInteractiveDismiss = true - pendingNavigationBarSnapshot = nil - dismiss(animated: true) - } else { - clearInteractionState() - } - case .changed: - interactionController?.update(progress) - case .ended: - let velocityX = gestureRecognizer.velocity(in: view).x - if shouldFinishFullScreenPop(progress: progress, velocityX: velocityX) { - interactionController?.finish() - } else { - interactionController?.cancel() - } - clearInteractionState() - case .cancelled, .failed: - interactionController?.cancel() - clearInteractionState() - default: - break - } - } - - func canBeginFullScreenPop(velocity: CGPoint) -> Bool { - guard transitionCoordinator == nil, - presentedViewController == nil, - velocity.x > 0 else { - return false - } - let canPop = viewControllers.count > 1 - let canDismiss = canInteractivelyDismissRoot - guard canPop || canDismiss else { - return false - } - return abs(velocity.x) > abs(velocity.y) * FullScreenPop.horizontalBias - } - - func shouldFinishFullScreenPop(progress: CGFloat, velocityX: CGFloat) -> Bool { - progress >= FullScreenPop.finishProgress || velocityX >= FullScreenPop.finishVelocityX - } - - func navigationController( - _ navigationController: UINavigationController, - willShow viewController: UIViewController, - animated: Bool - ) { - updateNavigationBarVisibility(for: viewController, animated: animated) - interactivePopGestureRecognizer?.isEnabled = false - updateSecondaryRootBackItemIfNeeded(for: viewController) - } - - /// Root page of the secondary stack has no system back target — provide an explicit dismiss control. - private func updateSecondaryRootBackItemIfNeeded(for viewController: UIViewController) { - guard allowsInteractiveDismissWhenAtRoot else { return } - let isRoot = viewControllers.first === viewController - guard isRoot else { return } - // Leave pages that already own their chrome (e.g. topic detail) untouched. - if viewController.navigationItem.leftBarButtonItem != nil - || !(viewController.navigationItem.leftBarButtonItems ?? []).isEmpty { - return - } - let dismissItem = UIBarButtonItem( - image: UIImage(systemName: "chevron.backward"), - style: .plain, - target: self, - action: #selector(dismissSecondaryRoot) - ) - dismissItem.accessibilityLabel = "返回" - viewController.navigationItem.leftBarButtonItem = dismissItem - } - - @objc private func dismissSecondaryRoot() { - dismiss(animated: true) - } - - func navigationController( - _ navigationController: UINavigationController, - animationControllerFor operation: UINavigationController.Operation, - from fromVC: UIViewController, - to toVC: UIViewController - ) -> UIViewControllerAnimatedTransitioning? { - guard operation == .pop else { return nil } - popAnimator.navigationBarSnapshot = pendingNavigationBarSnapshot - popAnimator.navigationBarSnapshotHost = view - pendingNavigationBarSnapshot = nil - return popAnimator - } - - func navigationController( - _ navigationController: UINavigationController, - interactionControllerFor animationController: UIViewControllerAnimatedTransitioning - ) -> UIViewControllerInteractiveTransitioning? { - isInteractiveDismiss ? nil : interactionController - } - - func animationController( - forPresented presented: UIViewController, - presenting: UIViewController, - source: UIViewController - ) -> UIViewControllerAnimatedTransitioning? { - guard presented === self else { return nil } - presentAnimator.navigationBarSnapshot = nil - presentAnimator.navigationBarSnapshotHost = nil - return presentAnimator - } - - func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { - guard dismissed === self else { return nil } - dismissAnimator.navigationBarSnapshot = nil - dismissAnimator.navigationBarSnapshotHost = nil - return dismissAnimator - } - - func interactionControllerForDismissal( - using animator: UIViewControllerAnimatedTransitioning - ) -> UIViewControllerInteractiveTransitioning? { - isInteractiveDismiss ? interactionController : nil - } - - func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { - guard gestureRecognizer === fullScreenPopGestureRecognizer, - let panGesture = gestureRecognizer as? UIPanGestureRecognizer else { - return true - } - return canBeginFullScreenPop(velocity: panGesture.velocity(in: view)) - } - - func gestureRecognizer( - _ gestureRecognizer: UIGestureRecognizer, - shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer - ) -> Bool { - false - } - - func updateNavigationBarVisibility(for viewController: UIViewController, animated: Bool) { - let isRoot = viewControllers.first === viewController - setNavigationBarHidden(hidesNavigationBarAtRoot && isRoot, animated: animated) - } - - private var canInteractivelyDismissRoot: Bool { - allowsInteractiveDismissWhenAtRoot - && viewControllers.count <= 1 - && presentingViewController != nil - && presentedViewController == nil - } - - private func captureNavigationBarSnapshotIfNeeded() { - guard !isNavigationBarHidden else { - pendingNavigationBarSnapshot = nil - return - } - pendingNavigationBarSnapshot = navigationBar.snapshotView(afterScreenUpdates: false) - } - - private func clearInteractionState() { - interactionController = nil - isInteractiveDismiss = false - } -} - -private final class FireMainCardAnimator: NSObject, UIViewControllerAnimatedTransitioning { - enum Operation { - case push - case pop - } - - private let duration: TimeInterval = 0.28 - private let operation: Operation - private let parallaxDistanceRatio: CGFloat - var navigationBarSnapshot: UIView? - weak var navigationBarSnapshotHost: UIView? - - init(operation: Operation, parallaxDistanceRatio: CGFloat) { - self.operation = operation - self.parallaxDistanceRatio = parallaxDistanceRatio - } - - func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { - duration - } - - func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { - guard let fromView = transitionContext.view(forKey: .from), - let toView = transitionContext.view(forKey: .to) else { - transitionContext.completeTransition(!transitionContext.transitionWasCancelled) - return - } - - let containerView = transitionContext.containerView - let width = max(containerView.bounds.width, 1) - let toViewController = transitionContext.viewController(forKey: .to) - if let toViewController { - toView.frame = transitionContext.finalFrame(for: toViewController) - } else { - toView.frame = containerView.bounds - } - - switch operation { - case .push: - // Incoming secondary page slides from the right over the still tab shell. - toView.transform = CGAffineTransform(translationX: width, y: 0) - containerView.addSubview(toView) - applyOutgoingShadow(to: toView) - - UIView.animate( - withDuration: transitionDuration(using: transitionContext), - delay: 0, - options: [.curveEaseOut, .allowUserInteraction], - animations: { - toView.transform = .identity - fromView.transform = CGAffineTransform(translationX: -width * self.parallaxDistanceRatio, y: 0) - }, - completion: { _ in - let cancelled = transitionContext.transitionWasCancelled - fromView.transform = .identity - toView.transform = .identity - self.clearOutgoingShadow(from: toView) - if cancelled { - toView.removeFromSuperview() - } - transitionContext.completeTransition(!cancelled) - } - ) - - case .pop: - // Outgoing page slides right. Optional nav-bar snapshot rides with it so the real - // bar (already swapped to the destination) stays covered — WeChat whole-page card. - toView.transform = CGAffineTransform(translationX: -width * parallaxDistanceRatio, y: 0) - containerView.insertSubview(toView, belowSubview: fromView) - applyOutgoingShadow(to: fromView) - - let barSnapshot = navigationBarSnapshot - let barHost = navigationBarSnapshotHost - navigationBarSnapshot = nil - navigationBarSnapshotHost = nil - if let barSnapshot, let barHost { - let barFrame: CGRect - if let navigationBar = transitionContext.viewController(forKey: .from)?.navigationController?.navigationBar { - barFrame = navigationBar.convert(navigationBar.bounds, to: barHost) - } else { - barFrame = CGRect( - x: 0, - y: barHost.safeAreaInsets.top, - width: barHost.bounds.width, - height: max(barSnapshot.bounds.height, 44) - ) - } - barSnapshot.frame = barFrame - barHost.addSubview(barSnapshot) - } - - UIView.animate( - withDuration: transitionDuration(using: transitionContext), - delay: 0, - options: [.curveEaseOut, .allowUserInteraction], - animations: { - fromView.transform = CGAffineTransform(translationX: width, y: 0) - barSnapshot?.transform = CGAffineTransform(translationX: width, y: 0) - toView.transform = .identity - }, - completion: { _ in - let cancelled = transitionContext.transitionWasCancelled - fromView.transform = .identity - toView.transform = .identity - barSnapshot?.removeFromSuperview() - self.clearOutgoingShadow(from: fromView) - if cancelled { - toView.removeFromSuperview() - } - transitionContext.completeTransition(!cancelled) - } - ) - } - } - - private func applyOutgoingShadow(to view: UIView) { - view.layer.shadowColor = UIColor.black.cgColor - view.layer.shadowOpacity = 0.18 - view.layer.shadowRadius = 12 - view.layer.shadowOffset = CGSize(width: -3, height: 0) - } - - private func clearOutgoingShadow(from view: UIView) { - view.layer.shadowOpacity = 0 - view.layer.shadowRadius = 0 - view.layer.shadowOffset = .zero - view.layer.shadowColor = nil - } -} private extension Array { subscript(safe index: Index) -> Element? { diff --git a/apps/ios-app/App/Core/FireRootCoordinator+APM.swift b/apps/ios-app/App/Core/FireRootCoordinator+APM.swift new file mode 100644 index 00000000..0c0d6b68 --- /dev/null +++ b/apps/ios-app/App/Core/FireRootCoordinator+APM.swift @@ -0,0 +1,43 @@ +import UIKit + +extension FireRootCoordinator { + func handleScenePhaseChange(_ phase: ScenePhaseLabel) { + if phase == .active { + Self.activeCoordinator = self + } + + let isAuthenticated = currentAuthenticationState + homeFeedStore.setSceneActive(phase == .active) + FireAPMManager.shared.setScenePhase(phase.rawValue) + viewModel.handleDiagnosticsScenePhaseChange( + phase.rawValue, + isAuthenticated: isAuthenticated + ) + + switch phase { + case .active: + if isAuthenticated { + Task { + await FirePushRegistrationCoordinator.shared.refreshAuthorizationStatus() + await FirePushRegistrationCoordinator.shared.ensurePushRegistration() + } + } + handlePendingRouteIfReady(navigationState.pendingRoute) + case .background: + if isAuthenticated { + FireBackgroundNotificationAlertScheduler.scheduleRefresh() + } else { + FireBackgroundNotificationAlertScheduler.cancelRefresh() + } + case .inactive, .unknown: + break + } + } + + func updateTopLevelAPMRoute() { + viewModel.updateTopLevelAPMRoute( + selectedTab: navigationState.selectedTab, + isAuthenticated: currentAuthenticationState + ) + } +} diff --git a/apps/ios-app/App/Core/FireRootCoordinator+Authentication.swift b/apps/ios-app/App/Core/FireRootCoordinator+Authentication.swift new file mode 100644 index 00000000..d7c3b1e7 --- /dev/null +++ b/apps/ios-app/App/Core/FireRootCoordinator+Authentication.swift @@ -0,0 +1,187 @@ +import Combine +import UIKit + +extension FireRootCoordinator { + func bindState() { + viewModel.$session + .map { $0.readiness.canReadAuthenticatedApi } + .removeDuplicates() + .receive(on: RunLoop.main) + .sink { [weak self] isAuthenticated in + self?.handleAuthenticationChange(isAuthenticated) + } + .store(in: &cancellables) + + navigationState.$pendingRoute + .receive(on: RunLoop.main) + .sink { [weak self] route in + self?.handlePendingRouteIfReady(route) + } + .store(in: &cancellables) + + navigationState.$presentedTopicRoute + .receive(on: RunLoop.main) + .sink { [weak self] route in + self?.handleTopicRouteRequest(route) + } + .store(in: &cancellables) + + navigationState.$selectedTab + .removeDuplicates() + .receive(on: RunLoop.main) + .sink { [weak self] selectedTab in + guard let self else { return } + self.mainTabBarController?.setSelectedTab(selectedTab) + self.updateTopLevelAPMRoute() + } + .store(in: &cancellables) + + notificationStore.$unreadCount + .removeDuplicates() + .receive(on: RunLoop.main) + .sink { [weak self] unreadCount in + self?.mainTabBarController?.setUnreadCount(unreadCount) + } + .store(in: &cancellables) + + chatChannelsStore.$totalUnreadBadge + .removeDuplicates() + .receive(on: RunLoop.main) + .sink { [weak self] unreadCount in + self?.mainTabBarController?.setChatUnreadCount(unreadCount) + } + .store(in: &cancellables) + + // External writers (e.g. residual SwiftUI @AppStorage) still update + // UserDefaults; mirror into Environment so window + snapshot stay aligned. + NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification) + .receive(on: RunLoop.main) + .sink { [weak self] _ in + guard let self else { return } + _ = FireAppearanceEnvironment.syncFromStorage(window: self.window) + } + .store(in: &cancellables) + + viewModel.$midSessionReauthMessage + .receive(on: RunLoop.main) + .sink { [weak self] message in + self?.syncMidSessionReauthOverlay(message: message) + } + .store(in: &cancellables) + + viewModel.$isMidSessionReauthInFlight + .removeDuplicates() + .receive(on: RunLoop.main) + .sink { [weak self] inFlight in + self?.handleMidSessionReauthFlightChange(inFlight) + } + .store(in: &cancellables) + } + + func handleAuthenticationChange(_ isAuthenticated: Bool) { + let previous = lastAuthenticatedState + lastAuthenticatedState = isAuthenticated + + if previous == true, !isAuthenticated { + if viewModel.isMidSessionReauthInFlight { + // Passive logout raced with Google headless reauth. Keep the main + // shell + overlay so a successful reauth can retry the original request. + isHoldingMainShellForReauth = true + updateTopLevelAPMRoute() + return + } + + tearDownAuthenticatedShellForDeauth() + } + + if isAuthenticated { + isHoldingMainShellForReauth = false + } else if isHoldingMainShellForReauth, viewModel.isMidSessionReauthInFlight { + updateTopLevelAPMRoute() + return + } + + updateRoot(animated: previous != nil) + updateTopLevelAPMRoute() + + if isAuthenticated { + Task { + await FirePushRegistrationCoordinator.shared.ensurePushRegistration() + await chatChannelsStore.refresh() + } + handlePendingRouteIfReady(navigationState.pendingRoute) + } + } + + func tearDownAuthenticatedShellForDeauth() { + isHoldingMainShellForReauth = false + // Explicit logout → credential form only. + // Mid-session invalidation → sessionExpired so headless Google can auto-login. + pendingOnboardingEntry = viewModel.deauthOnboardingEntry() + homeFeedStore.reset() + searchStore.reset() + notificationStore.reset() + chatChannelsStore.reset() + topicDetailStore.reset() + FireMotionCelebrationGate.reset() + navigationState.dismissPresentedTopicRoute() + dismissSecondaryStack(animated: false) + FireBackgroundNotificationAlertScheduler.cancelRefresh() + dismissMidSessionReauthOverlay() + } + + func handleMidSessionReauthFlightChange(_ inFlight: Bool) { + guard !inFlight, isHoldingMainShellForReauth else { return } + guard !currentAuthenticationState else { + isHoldingMainShellForReauth = false + return + } + + // Reauth finished without restoring auth — fall through to onboarding. + tearDownAuthenticatedShellForDeauth() + updateRoot(animated: true) + updateTopLevelAPMRoute() + } + + func syncMidSessionReauthOverlay(message: String?) { + guard let message, !message.isEmpty else { + dismissMidSessionReauthOverlay() + return + } + + if let overlay = midSessionReauthOverlay { + overlay.updateMessage(message) + // Keep the overlay below any promoted OAuth surface. + overlay.view.superview?.bringSubviewToFront(overlay.view) + return + } + + guard let host = window?.rootViewController else { return } + let overlay = FireMidSessionReauthOverlayController() + overlay.updateMessage(message) + overlay.onCancel = { [weak self] in + self?.viewModel.cancelMidSessionReauth(reason: "overlay_cancel") + } + midSessionReauthOverlay = overlay + + // Child VC (not modal) so promoted full-screen OAuth can present cleanly above it. + host.addChild(overlay) + overlay.view.translatesAutoresizingMaskIntoConstraints = false + host.view.addSubview(overlay.view) + NSLayoutConstraint.activate([ + overlay.view.topAnchor.constraint(equalTo: host.view.topAnchor), + overlay.view.leadingAnchor.constraint(equalTo: host.view.leadingAnchor), + overlay.view.trailingAnchor.constraint(equalTo: host.view.trailingAnchor), + overlay.view.bottomAnchor.constraint(equalTo: host.view.bottomAnchor), + ]) + overlay.didMove(toParent: host) + } + + func dismissMidSessionReauthOverlay() { + guard let overlay = midSessionReauthOverlay else { return } + midSessionReauthOverlay = nil + overlay.willMove(toParent: nil) + overlay.view.removeFromSuperview() + overlay.removeFromParent() + } +} diff --git a/apps/ios-app/App/Core/FireRootCoordinator+RootPresentation.swift b/apps/ios-app/App/Core/FireRootCoordinator+RootPresentation.swift new file mode 100644 index 00000000..ad4c4e07 --- /dev/null +++ b/apps/ios-app/App/Core/FireRootCoordinator+RootPresentation.swift @@ -0,0 +1,118 @@ +import UIKit + +extension FireRootCoordinator { + func updateRoot(animated: Bool) { + let nextKind: RootKind = currentAuthenticationState ? .main : .launch + guard rootKind != nextKind else { return } + + rootKind = nextKind + let controller: UIViewController + switch nextKind { + case .launch: + controller = makeOnboardingController() + case .main: + controller = makeMainTabBarController() + } + + guard let window else { return } + guard animated, window.rootViewController != nil else { + window.rootViewController = controller + return + } + + UIView.transition( + with: window, + duration: 0.22, + options: [.transitionCrossDissolve, .allowAnimatedContent], + animations: { + window.rootViewController = controller + } + ) + } + + func makeOnboardingController() -> UIViewController { + dismissSecondaryStack(animated: false) + mainTabBarController = nil + let entry = pendingOnboardingEntry + // Cold start is the default for a fresh process; consume signedOut after one presentation. + pendingOnboardingEntry = .coldStart + let controller = FireOnboardingViewController(viewModel: viewModel, entry: entry) + // Hosting nav is only for optional drill-down (developer tools). Login itself hides the bar + // so the page is one continuous canvas, not a chrome strip + content stack. + let navigationController = UINavigationController(rootViewController: controller) + navigationController.setNavigationBarHidden(true, animated: false) + return navigationController + } + + func makeMainTabBarController() -> UIViewController { + let controller = FireMainTabBarController( + viewModel: viewModel, + navigationState: navigationState, + homeFeedStore: homeFeedStore, + searchStore: searchStore, + notificationStore: notificationStore, + chatChannelsStore: chatChannelsStore, + topicDetailStore: topicDetailStore, + profileViewModel: profileViewModel + ) + controller.onSelectedTabChanged = { [weak self] selectedTab in + guard let self else { return } + self.selectionFeedback.selectionChanged() + if self.navigationState.selectedTab != selectedTab { + self.navigationState.selectedTab = selectedTab + } + self.updateTopLevelAPMRoute() + self.handlePendingRouteIfReady(self.navigationState.pendingRoute) + } + controller.setSelectedTab(navigationState.selectedTab) + controller.setUnreadCount(notificationStore.unreadCount) + controller.setChatUnreadCount(chatChannelsStore.totalUnreadBadge) + mainTabBarController = controller + return controller + } + + func openSecondaryPage( + _ controller: UIViewController, + animated: Bool, + diagnostics: String? = nil + ) { + guard let tabBarController = mainTabBarController else { + viewModel.topicRouteLogger()?.warning( + "root coordinator could not resolve tab shell for secondary page \(diagnostics ?? controller.title ?? String(describing: type(of: controller)))" + ) + return + } + + // Prefer push onto the existing secondary stack when already covering the tab shell. + if let secondaryNavigationController, + secondaryNavigationController.presentingViewController != nil { + viewModel.topicRouteLogger()?.info( + "root coordinator pushing secondary page \(diagnostics ?? String(describing: type(of: controller))) stack_count=\(secondaryNavigationController.viewControllers.count)" + ) + secondaryNavigationController.pushViewController(controller, animated: animated) + return + } + + let secondary = FireMainNavigationController(rootViewController: controller) + secondary.modalPresentationStyle = .fullScreen + secondary.allowsInteractiveDismissWhenAtRoot = true + secondary.onDidDismissCompletely = { [weak self] in + self?.secondaryNavigationController = nil + } + secondaryNavigationController = secondary + + viewModel.topicRouteLogger()?.info( + "root coordinator presenting secondary stack \(diagnostics ?? String(describing: type(of: controller)))" + ) + tabBarController.present(secondary, animated: animated) + } + + func dismissSecondaryStack(animated: Bool) { + guard let secondaryNavigationController else { return } + secondaryNavigationController.onDidDismissCompletely = nil + if secondaryNavigationController.presentingViewController != nil { + secondaryNavigationController.dismiss(animated: animated) + } + self.secondaryNavigationController = nil + } +} diff --git a/apps/ios-app/App/Core/FireRootCoordinator+Routing.swift b/apps/ios-app/App/Core/FireRootCoordinator+Routing.swift new file mode 100644 index 00000000..74b8be91 --- /dev/null +++ b/apps/ios-app/App/Core/FireRootCoordinator+Routing.swift @@ -0,0 +1,60 @@ +import UIKit + +extension FireRootCoordinator { + func enqueue(_ route: FireAppRoute) { + viewModel.topicRouteLogger()?.info("root coordinator enqueued route \(route.diagnosticsSummary)") + navigationState.pendingRoute = route + handlePendingRouteIfReady(route) + } + + func handleTopicRouteRequest(_ route: FireAppRoute?) { + guard let route else { return } + openSecondaryRoute(route, animated: true) + navigationState.dismissPresentedTopicRoute() + } + + func openSecondaryRoute(_ route: FireAppRoute, animated: Bool) { + guard route.presentsAsSecondaryPage else { + viewModel.topicRouteLogger()?.debug( + "root coordinator ignored non-secondary route \(route.diagnosticsSummary)" + ) + return + } + + let topicRoutePresenter = FireAppRouteControllerFactory.makeTopicRoutePresenter( + viewModel: viewModel, + topicDetailStore: topicDetailStore, + navigationControllerProvider: { [weak self] in self?.secondaryNavigationController } + ) + let controller = FireAppRouteControllerFactory.makeViewController( + viewModel: viewModel, + topicDetailStore: topicDetailStore, + route: route, + topicRoutePresenter: topicRoutePresenter + ) + openSecondaryPage(controller, animated: animated, diagnostics: route.diagnosticsSummary) + } + + func handlePendingRouteIfReady(_ route: FireAppRoute?) { + guard let route, currentAuthenticationState else { return } + switch route { + case .topic: + navigationState.presentTopicRoute(route) + navigationState.pendingRoute = nil + case .notifications: + navigationState.selectedTab = 1 + navigationState.pendingRoute = nil + case .profileTab: + // Tabs: 0 home, 1 notifications, 2 chat, 3 profile + navigationState.selectedTab = 3 + navigationState.pendingRoute = nil + case .search(let query): + navigationState.pendingSearchQuery = query ?? "" + navigationState.selectedTab = 0 + navigationState.pendingRoute = nil + case .profile, .badge: + openSecondaryRoute(route, animated: true) + navigationState.pendingRoute = nil + } + } +} diff --git a/apps/ios-app/App/Core/FireRootCoordinator.swift b/apps/ios-app/App/Core/FireRootCoordinator.swift index ff4aacd2..2119c36e 100644 --- a/apps/ios-app/App/Core/FireRootCoordinator.swift +++ b/apps/ios-app/App/Core/FireRootCoordinator.swift @@ -10,19 +10,19 @@ final class FireRootCoordinator { case unknown } - private enum RootKind: Equatable { + enum RootKind: Equatable { case launch case main } /// How the next onboarding host should behave. Logout forces credential-only entry. - private var pendingOnboardingEntry: FireOnboardingEntry = .coldStart + var pendingOnboardingEntry: FireOnboardingEntry = .coldStart /// Keep the authenticated shell mounted while mid-session Google reauth runs, /// even if Rust has already cleared the local session snapshot. - private var isHoldingMainShellForReauth = false - private weak var midSessionReauthOverlay: FireMidSessionReauthOverlayController? + var isHoldingMainShellForReauth = false + weak var midSessionReauthOverlay: FireMidSessionReauthOverlayController? - private static weak var activeCoordinator: FireRootCoordinator? + static weak var activeCoordinator: FireRootCoordinator? static func dispatch(_ route: FireAppRoute) { if let activeCoordinator { @@ -46,7 +46,7 @@ final class FireRootCoordinator { activeCoordinator?.hasMainTabShell == true } - private var hasMainTabShell: Bool { + var hasMainTabShell: Bool { mainTabBarController != nil } @@ -69,24 +69,24 @@ final class FireRootCoordinator { activeCoordinator?.presentFeedback(source: source) } - private weak var window: UIWindow? - private let navigationState = FireNavigationState.shared - private let viewModel: FireAppViewModel - private let homeFeedStore: FireHomeFeedStore - private let searchStore: FireSearchStore - private let notificationStore: FireNotificationStore - private let chatChannelsStore: FireChatChannelsStore - private let topicDetailStore: FireTopicDetailStore - private let profileViewModel: FireProfileViewModel + weak var window: UIWindow? + let navigationState = FireNavigationState.shared + let viewModel: FireAppViewModel + let homeFeedStore: FireHomeFeedStore + let searchStore: FireSearchStore + let notificationStore: FireNotificationStore + let chatChannelsStore: FireChatChannelsStore + let topicDetailStore: FireTopicDetailStore + let profileViewModel: FireProfileViewModel - private var cancellables = Set() - private var rootKind: RootKind? - private var mainTabBarController: FireMainTabBarController? + var cancellables = Set() + var rootKind: RootKind? + var mainTabBarController: FireMainTabBarController? /// App-root secondary page stack (topics, nested drill-down). Covers the tab shell; /// does not mutate or hide the tab bar. - private weak var secondaryNavigationController: FireMainNavigationController? - private var lastAuthenticatedState: Bool? - private let selectionFeedback = UISelectionFeedbackGenerator() + weak var secondaryNavigationController: FireMainNavigationController? + var lastAuthenticatedState: Bool? + let selectionFeedback = UISelectionFeedbackGenerator() init(window: UIWindow) { let vm = FireAppViewModel() @@ -152,403 +152,8 @@ final class FireRootCoordinator { ) } - func handleScenePhaseChange(_ phase: ScenePhaseLabel) { - if phase == .active { - Self.activeCoordinator = self - } - - let isAuthenticated = currentAuthenticationState - homeFeedStore.setSceneActive(phase == .active) - FireAPMManager.shared.setScenePhase(phase.rawValue) - viewModel.handleDiagnosticsScenePhaseChange( - phase.rawValue, - isAuthenticated: isAuthenticated - ) - - switch phase { - case .active: - if isAuthenticated { - Task { - await FirePushRegistrationCoordinator.shared.refreshAuthorizationStatus() - await FirePushRegistrationCoordinator.shared.ensurePushRegistration() - } - } - handlePendingRouteIfReady(navigationState.pendingRoute) - case .background: - if isAuthenticated { - FireBackgroundNotificationAlertScheduler.scheduleRefresh() - } else { - FireBackgroundNotificationAlertScheduler.cancelRefresh() - } - case .inactive, .unknown: - break - } - } - - private var currentAuthenticationState: Bool { + var currentAuthenticationState: Bool { viewModel.session.readiness.canReadAuthenticatedApi } - private func bindState() { - viewModel.$session - .map { $0.readiness.canReadAuthenticatedApi } - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] isAuthenticated in - self?.handleAuthenticationChange(isAuthenticated) - } - .store(in: &cancellables) - - navigationState.$pendingRoute - .receive(on: RunLoop.main) - .sink { [weak self] route in - self?.handlePendingRouteIfReady(route) - } - .store(in: &cancellables) - - navigationState.$presentedTopicRoute - .receive(on: RunLoop.main) - .sink { [weak self] route in - self?.handleTopicRouteRequest(route) - } - .store(in: &cancellables) - - navigationState.$selectedTab - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] selectedTab in - guard let self else { return } - self.mainTabBarController?.setSelectedTab(selectedTab) - self.updateTopLevelAPMRoute() - } - .store(in: &cancellables) - - notificationStore.$unreadCount - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] unreadCount in - self?.mainTabBarController?.setUnreadCount(unreadCount) - } - .store(in: &cancellables) - - chatChannelsStore.$totalUnreadBadge - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] unreadCount in - self?.mainTabBarController?.setChatUnreadCount(unreadCount) - } - .store(in: &cancellables) - - // External writers (e.g. residual SwiftUI @AppStorage) still update - // UserDefaults; mirror into Environment so window + snapshot stay aligned. - NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification) - .receive(on: RunLoop.main) - .sink { [weak self] _ in - guard let self else { return } - _ = FireAppearanceEnvironment.syncFromStorage(window: self.window) - } - .store(in: &cancellables) - - viewModel.$midSessionReauthMessage - .receive(on: RunLoop.main) - .sink { [weak self] message in - self?.syncMidSessionReauthOverlay(message: message) - } - .store(in: &cancellables) - - viewModel.$isMidSessionReauthInFlight - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] inFlight in - self?.handleMidSessionReauthFlightChange(inFlight) - } - .store(in: &cancellables) - } - - private func enqueue(_ route: FireAppRoute) { - viewModel.topicRouteLogger()?.info("root coordinator enqueued route \(route.diagnosticsSummary)") - navigationState.pendingRoute = route - handlePendingRouteIfReady(route) - } - - private func handleAuthenticationChange(_ isAuthenticated: Bool) { - let previous = lastAuthenticatedState - lastAuthenticatedState = isAuthenticated - - if previous == true, !isAuthenticated { - if viewModel.isMidSessionReauthInFlight { - // Passive logout raced with Google headless reauth. Keep the main - // shell + overlay so a successful reauth can retry the original request. - isHoldingMainShellForReauth = true - updateTopLevelAPMRoute() - return - } - - tearDownAuthenticatedShellForDeauth() - } - - if isAuthenticated { - isHoldingMainShellForReauth = false - } else if isHoldingMainShellForReauth, viewModel.isMidSessionReauthInFlight { - updateTopLevelAPMRoute() - return - } - - updateRoot(animated: previous != nil) - updateTopLevelAPMRoute() - - if isAuthenticated { - Task { - await FirePushRegistrationCoordinator.shared.ensurePushRegistration() - await chatChannelsStore.refresh() - } - handlePendingRouteIfReady(navigationState.pendingRoute) - } - } - - private func tearDownAuthenticatedShellForDeauth() { - isHoldingMainShellForReauth = false - // Explicit logout → credential form only. - // Mid-session invalidation → sessionExpired so headless Google can auto-login. - pendingOnboardingEntry = viewModel.deauthOnboardingEntry() - homeFeedStore.reset() - searchStore.reset() - notificationStore.reset() - chatChannelsStore.reset() - topicDetailStore.reset() - FireMotionCelebrationGate.reset() - navigationState.dismissPresentedTopicRoute() - dismissSecondaryStack(animated: false) - FireBackgroundNotificationAlertScheduler.cancelRefresh() - dismissMidSessionReauthOverlay() - } - - private func handleMidSessionReauthFlightChange(_ inFlight: Bool) { - guard !inFlight, isHoldingMainShellForReauth else { return } - guard !currentAuthenticationState else { - isHoldingMainShellForReauth = false - return - } - - // Reauth finished without restoring auth — fall through to onboarding. - tearDownAuthenticatedShellForDeauth() - updateRoot(animated: true) - updateTopLevelAPMRoute() - } - - private func syncMidSessionReauthOverlay(message: String?) { - guard let message, !message.isEmpty else { - dismissMidSessionReauthOverlay() - return - } - - if let overlay = midSessionReauthOverlay { - overlay.updateMessage(message) - // Keep the overlay below any promoted OAuth surface. - overlay.view.superview?.bringSubviewToFront(overlay.view) - return - } - - guard let host = window?.rootViewController else { return } - let overlay = FireMidSessionReauthOverlayController() - overlay.updateMessage(message) - overlay.onCancel = { [weak self] in - self?.viewModel.cancelMidSessionReauth(reason: "overlay_cancel") - } - midSessionReauthOverlay = overlay - - // Child VC (not modal) so promoted full-screen OAuth can present cleanly above it. - host.addChild(overlay) - overlay.view.translatesAutoresizingMaskIntoConstraints = false - host.view.addSubview(overlay.view) - NSLayoutConstraint.activate([ - overlay.view.topAnchor.constraint(equalTo: host.view.topAnchor), - overlay.view.leadingAnchor.constraint(equalTo: host.view.leadingAnchor), - overlay.view.trailingAnchor.constraint(equalTo: host.view.trailingAnchor), - overlay.view.bottomAnchor.constraint(equalTo: host.view.bottomAnchor), - ]) - overlay.didMove(toParent: host) - } - - private func dismissMidSessionReauthOverlay() { - guard let overlay = midSessionReauthOverlay else { return } - midSessionReauthOverlay = nil - overlay.willMove(toParent: nil) - overlay.view.removeFromSuperview() - overlay.removeFromParent() - } - - private func updateRoot(animated: Bool) { - let nextKind: RootKind = currentAuthenticationState ? .main : .launch - guard rootKind != nextKind else { return } - - rootKind = nextKind - let controller: UIViewController - switch nextKind { - case .launch: - controller = makeOnboardingController() - case .main: - controller = makeMainTabBarController() - } - - guard let window else { return } - guard animated, window.rootViewController != nil else { - window.rootViewController = controller - return - } - - UIView.transition( - with: window, - duration: 0.22, - options: [.transitionCrossDissolve, .allowAnimatedContent], - animations: { - window.rootViewController = controller - } - ) - } - - private func makeOnboardingController() -> UIViewController { - dismissSecondaryStack(animated: false) - mainTabBarController = nil - let entry = pendingOnboardingEntry - // Cold start is the default for a fresh process; consume signedOut after one presentation. - pendingOnboardingEntry = .coldStart - let controller = FireOnboardingViewController(viewModel: viewModel, entry: entry) - // Hosting nav is only for optional drill-down (developer tools). Login itself hides the bar - // so the page is one continuous canvas, not a chrome strip + content stack. - let navigationController = UINavigationController(rootViewController: controller) - navigationController.setNavigationBarHidden(true, animated: false) - return navigationController - } - - private func makeMainTabBarController() -> UIViewController { - let controller = FireMainTabBarController( - viewModel: viewModel, - navigationState: navigationState, - homeFeedStore: homeFeedStore, - searchStore: searchStore, - notificationStore: notificationStore, - chatChannelsStore: chatChannelsStore, - topicDetailStore: topicDetailStore, - profileViewModel: profileViewModel - ) - controller.onSelectedTabChanged = { [weak self] selectedTab in - guard let self else { return } - self.selectionFeedback.selectionChanged() - if self.navigationState.selectedTab != selectedTab { - self.navigationState.selectedTab = selectedTab - } - self.updateTopLevelAPMRoute() - self.handlePendingRouteIfReady(self.navigationState.pendingRoute) - } - controller.setSelectedTab(navigationState.selectedTab) - controller.setUnreadCount(notificationStore.unreadCount) - controller.setChatUnreadCount(chatChannelsStore.totalUnreadBadge) - mainTabBarController = controller - return controller - } - - private func handleTopicRouteRequest(_ route: FireAppRoute?) { - guard let route else { return } - openSecondaryRoute(route, animated: true) - navigationState.dismissPresentedTopicRoute() - } - - private func openSecondaryRoute(_ route: FireAppRoute, animated: Bool) { - guard route.presentsAsSecondaryPage else { - viewModel.topicRouteLogger()?.debug( - "root coordinator ignored non-secondary route \(route.diagnosticsSummary)" - ) - return - } - - let topicRoutePresenter = FireAppRouteControllerFactory.makeTopicRoutePresenter( - viewModel: viewModel, - topicDetailStore: topicDetailStore, - navigationControllerProvider: { [weak self] in self?.secondaryNavigationController } - ) - let controller = FireAppRouteControllerFactory.makeViewController( - viewModel: viewModel, - topicDetailStore: topicDetailStore, - route: route, - topicRoutePresenter: topicRoutePresenter - ) - openSecondaryPage(controller, animated: animated, diagnostics: route.diagnosticsSummary) - } - - private func openSecondaryPage( - _ controller: UIViewController, - animated: Bool, - diagnostics: String? = nil - ) { - guard let tabBarController = mainTabBarController else { - viewModel.topicRouteLogger()?.warning( - "root coordinator could not resolve tab shell for secondary page \(diagnostics ?? controller.title ?? String(describing: type(of: controller)))" - ) - return - } - - // Prefer push onto the existing secondary stack when already covering the tab shell. - if let secondaryNavigationController, - secondaryNavigationController.presentingViewController != nil { - viewModel.topicRouteLogger()?.info( - "root coordinator pushing secondary page \(diagnostics ?? String(describing: type(of: controller))) stack_count=\(secondaryNavigationController.viewControllers.count)" - ) - secondaryNavigationController.pushViewController(controller, animated: animated) - return - } - - let secondary = FireMainNavigationController(rootViewController: controller) - secondary.modalPresentationStyle = .fullScreen - secondary.allowsInteractiveDismissWhenAtRoot = true - secondary.onDidDismissCompletely = { [weak self] in - self?.secondaryNavigationController = nil - } - secondaryNavigationController = secondary - - viewModel.topicRouteLogger()?.info( - "root coordinator presenting secondary stack \(diagnostics ?? String(describing: type(of: controller)))" - ) - tabBarController.present(secondary, animated: animated) - } - - private func dismissSecondaryStack(animated: Bool) { - guard let secondaryNavigationController else { return } - secondaryNavigationController.onDidDismissCompletely = nil - if secondaryNavigationController.presentingViewController != nil { - secondaryNavigationController.dismiss(animated: animated) - } - self.secondaryNavigationController = nil - } - - private func handlePendingRouteIfReady(_ route: FireAppRoute?) { - guard let route, currentAuthenticationState else { return } - switch route { - case .topic: - navigationState.presentTopicRoute(route) - navigationState.pendingRoute = nil - case .notifications: - navigationState.selectedTab = 1 - navigationState.pendingRoute = nil - case .profileTab: - // Tabs: 0 home, 1 notifications, 2 chat, 3 profile - navigationState.selectedTab = 3 - navigationState.pendingRoute = nil - case .search(let query): - navigationState.pendingSearchQuery = query ?? "" - navigationState.selectedTab = 0 - navigationState.pendingRoute = nil - case .profile, .badge: - openSecondaryRoute(route, animated: true) - navigationState.pendingRoute = nil - } - } - - private func updateTopLevelAPMRoute() { - viewModel.updateTopLevelAPMRoute( - selectedTab: navigationState.selectedTab, - isAuthenticated: currentAuthenticationState - ) - } - } diff --git a/apps/ios-app/App/Home/Controller/FireHomeViewController+Actions.swift b/apps/ios-app/App/Home/Controller/FireHomeViewController+Actions.swift index 860bf4a0..67b70f68 100644 --- a/apps/ios-app/App/Home/Controller/FireHomeViewController+Actions.swift +++ b/apps/ios-app/App/Home/Controller/FireHomeViewController+Actions.swift @@ -298,7 +298,6 @@ extension FireHomeViewController { FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) } - func syncOfflineBanner(animated: Bool) { let shouldShow = homeFeedStore.isOffline let changes = { diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Actions.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Actions.swift index 95ddcab9..72c679e5 100644 --- a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Actions.swift +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Actions.swift @@ -2,73 +2,6 @@ import AsyncDisplayKit import UIKit extension FirePostCellNode { - func configureReplyShortcut(payload: FirePostCellRenderPayload) { - guard let count = payload.replyShortcutCount else { - replyShortcutNode.isHidden = true - replyShortcutNode.setImage(nil, for: .normal) - replyShortcutNode.setAttributedTitle(nil, for: .normal) - return - } - replyShortcutNode.isHidden = false - // Always tappable so expand/collapse is never blocked by a loading flag. - replyShortcutNode.isEnabled = true - - let expanded = payload.isReplyThreadExpanded - let symbolName = expanded ? "bubble.left.fill" : "bubble.left" - // Collapsed = muted; expanded thread = accent orange for icon AND count. - let dynamicTint = expanded ? Self.accentTextColor : Self.tertiaryInkColor - let tint = FireTextureAttributedText.resolvedColor(dynamicTint, with: payload.colorTraits) - // Same glyph size as reply/react/boost action icons (14pt medium). - let symbolConfig = UIImage.SymbolConfiguration( - pointSize: 14, - weight: expanded ? .semibold : .medium - ) - // Template + tintColor keeps SF Symbol color in sync with the count label - // (alwaysOriginal dynamic UIColor can leave the glyph on the stale muted tint). - if let image = UIImage(systemName: symbolName, withConfiguration: symbolConfig) { - replyShortcutNode.tintColor = tint - replyShortcutNode.imageNode.tintColor = tint - replyShortcutNode.setImage(image.withRenderingMode(.alwaysTemplate), for: .normal) - replyShortcutNode.setImage(image.withRenderingMode(.alwaysTemplate), for: .disabled) - replyShortcutNode.setImage(image.withRenderingMode(.alwaysTemplate), for: .highlighted) - } - replyShortcutNode.imageNode.contentMode = .center - - let countText = payload.isLoadingReplyContext ? "…" : "\(count)" - let countFont = UIFontMetrics(forTextStyle: .caption1).scaledFont( - for: .systemFont(ofSize: 13, weight: expanded ? .semibold : .medium) - ) - let countAttributes: [NSAttributedString.Key: Any] = [ - .font: countFont, - .foregroundColor: tint, - ] - replyShortcutNode.setAttributedTitle(NSAttributedString( - string: countText, - attributes: countAttributes - ), for: .normal) - replyShortcutNode.setAttributedTitle(NSAttributedString( - string: countText, - attributes: countAttributes - ), for: .disabled) - replyShortcutNode.setAttributedTitle(NSAttributedString( - string: countText, - attributes: countAttributes - ), for: .highlighted) - replyShortcutNode.contentSpacing = 4 - replyShortcutNode.contentHorizontalAlignment = .middle - replyShortcutNode.contentVerticalAlignment = .center - // Match action-icon hit box height; width fits icon + count. - replyShortcutNode.style.minHeight = ASDimensionMake( - FirePostCellLayoutCalculator.replyShortcutHeight - ) - replyShortcutNode.style.minWidth = ASDimensionMake( - FirePostCellLayoutCalculator.replyShortcutMinWidth - ) - replyShortcutNode.hitTestSlop = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6) - replyShortcutNode.accessibilityLabel = expanded - ? "收起 \(count) 条回复" - : "展开 \(count) 条回复" - } func configureOverflowActions(payload: FirePostCellRenderPayload) { let canWrite = payload.canWriteInteractions && !payload.post.hidden @@ -241,30 +174,6 @@ extension FirePostCellNode { button.alpha = enabled ? 1 : 0.45 } - func menuAttributes( - for kind: FirePostCellActionKind, - isMutating: Bool, - destructive: Bool = false - ) -> UIMenuElement.Attributes { - var attributes: UIMenuElement.Attributes = [] - if destructive { - attributes.insert(.destructive) - } - if !FirePostCellActionAvailability.isEnabled(kind, canUse: true, isMutating: isMutating) { - attributes.insert(.disabled) - } - return attributes - } - - @objc func handleReplyContextTap() { - guard let payload = currentPayload, - let postNumber = payload.replyTargetPostNumber, - postNumber > 0, - let callbacks = currentCallbacks else { - return - } - callbacks.onOpenReplyTarget(postNumber) - } @objc func handleOverflowTap() { guard currentPayload?.showsInlineActions == true else { return } @@ -294,45 +203,6 @@ extension FirePostCellNode { callbacks.onBoostPost(payload.post) } - @objc func handleActionQuoteTap() { - guard let payload = currentPayload, let callbacks = currentCallbacks else { return } - noteOverflowInteraction() - FireMotionHaptics.impact(.light) - callbacks.onQuotePost(payload.post) - setOverflowActionsExpanded(false, animated: true) - } - - @objc func handleActionBookmarkTap() { - guard let payload = currentPayload, let callbacks = currentCallbacks else { return } - noteOverflowInteraction() - FireMotionHaptics.impact(.light) - callbacks.onBookmarkPost(payload.post) - setOverflowActionsExpanded(false, animated: true) - } - - @objc func handleActionEditTap() { - guard let payload = currentPayload, let callbacks = currentCallbacks else { return } - noteOverflowInteraction() - callbacks.onEditPost(payload.post) - setOverflowActionsExpanded(false, animated: true) - } - - @objc func handleActionFlagTap() { - guard let payload = currentPayload, let callbacks = currentCallbacks else { return } - noteOverflowInteraction() - callbacks.onFlagPost(payload.post) - setOverflowActionsExpanded(false, animated: true) - } - - @objc func handleReplyShortcutTap() { - guard let payload = currentPayload, - let callbacks = currentCallbacks else { - return - } - // Toggle must work even while nested replies are still loading. - FireMotionHaptics.impact(.light) - callbacks.onOpenReplies(payload.post) - } func setOverflowActionsExpanded(_ expanded: Bool, animated: Bool) { guard areOverflowActionsExpanded != expanded else { @@ -532,65 +402,6 @@ extension FirePostCellNode { } } - @objc func handleMenuTap() { - guard let payload = currentPayload, - let callbacks = currentCallbacks, - let presenter = nearestViewController() else { - return - } - let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) - let post = payload.post - let isMutating = payload.isMutating - if post.canEdit { - alert.addAction(UIAlertAction(title: "编辑", style: .default) { _ in - callbacks.onEditPost(post) - }) - } - if payload.canWriteInteractions && !post.hidden { - alert.addAction(UIAlertAction(title: "回复", style: .default) { _ in - callbacks.onReplyPost(post) - }) - let react = UIAlertAction(title: "回应", style: .default) { _ in - callbacks.onToggleReactionPicker(post) - } - react.isEnabled = FirePostCellActionAvailability.isEnabled( - .react, - canUse: true, - isMutating: isMutating - ) - alert.addAction(react) - if post.canBoost { - alert.addAction(UIAlertAction(title: "Boost", style: .default) { _ in - callbacks.onBoostPost(post) - }) - } - alert.addAction(UIAlertAction(title: "引用回复", style: .default) { _ in - callbacks.onQuotePost(post) - }) - alert.addAction(UIAlertAction(title: post.bookmarked ? "编辑书签" : "添加书签", style: .default) { _ in - FireMotionHaptics.impact(.light) - callbacks.onBookmarkPost(post) - }) - alert.addAction(UIAlertAction(title: "举报", style: .default) { _ in - callbacks.onFlagPost(post) - }) - } - if post.canRecover { - alert.addAction(UIAlertAction(title: "恢复", style: .default) { _ in - callbacks.onRecoverPost(post) - }) - } - if post.canDelete && !post.hidden { - alert.addAction(UIAlertAction(title: "删除", style: .destructive) { _ in - callbacks.onDeletePost(post) - }) - } - alert.addAction(UIAlertAction(title: "取消", style: .cancel)) - alert.popoverPresentationController?.sourceView = menuNode.view - alert.popoverPresentationController?.sourceRect = menuNode.view.bounds - FireMotionHaptics.impact(.medium) - presenter.present(alert, animated: true) - } // MARK: - Gesture Recognition @@ -638,83 +449,6 @@ extension FirePostCellNode { // MARK: - Menu - func buildMenu(for post: TopicPostState, callbacks: FirePostCellCallbacks, canWrite: Bool, isMutating: Bool) -> UIMenu { - var actions: [UIMenu] = [] - - if post.canEdit { - let edit = UIAction(title: "编辑", image: UIImage(systemName: "pencil")) { _ in - callbacks.onEditPost(post) - } - edit.attributes = menuAttributes(for: .edit, isMutating: isMutating) - actions.append(UIMenu(options: .displayInline, children: [edit])) - } - - var interactionActions: [UIAction] = [] - if canWrite && !post.hidden { - let reply = UIAction(title: "回复", image: UIImage(systemName: "arrowshape.turn.up.left")) { _ in - callbacks.onReplyPost(post) - } - reply.attributes = menuAttributes(for: .reply, isMutating: isMutating) - interactionActions.append(reply) - - let react = UIAction(title: "回应", image: UIImage(systemName: "face.smiling")) { _ in - callbacks.onToggleReactionPicker(post) - } - react.attributes = menuAttributes(for: .react, isMutating: isMutating) - interactionActions.append(react) - - if post.canBoost { - let boost = UIAction(title: "Boost", image: UIImage(systemName: "bolt")) { _ in - callbacks.onBoostPost(post) - } - boost.attributes = menuAttributes(for: .boost, isMutating: isMutating) - interactionActions.append(boost) - } - - let quote = UIAction(title: "引用回复", image: UIImage(systemName: "text.quote")) { _ in - callbacks.onQuotePost(post) - } - quote.attributes = menuAttributes(for: .quote, isMutating: isMutating) - interactionActions.append(quote) - - let bookmarkTitle = post.bookmarked ? "编辑书签" : "添加书签" - let bookmarkIcon = post.bookmarked ? "bookmark.fill" : "bookmark" - let bookmark = UIAction(title: bookmarkTitle, image: UIImage(systemName: bookmarkIcon)) { _ in - FireMotionHaptics.impact(.light) - callbacks.onBookmarkPost(post) - } - bookmark.attributes = menuAttributes(for: .bookmark, isMutating: isMutating) - interactionActions.append(bookmark) - - let flag = UIAction(title: "举报", image: UIImage(systemName: "flag")) { _ in - callbacks.onFlagPost(post) - } - flag.attributes = menuAttributes(for: .flag, isMutating: isMutating) - interactionActions.append(flag) - } - - if post.canRecover { - let recover = UIAction(title: "恢复", image: UIImage(systemName: "arrow.uturn.backward")) { _ in - callbacks.onRecoverPost(post) - } - recover.attributes = menuAttributes(for: .recover, isMutating: isMutating) - interactionActions.append(recover) - } - - if post.canDelete && !post.hidden { - let delete = UIAction(title: "删除", image: UIImage(systemName: "trash"), attributes: .destructive) { _ in - callbacks.onDeletePost(post) - } - delete.attributes = menuAttributes(for: .delete, isMutating: isMutating, destructive: true) - interactionActions.append(delete) - } - - if !interactionActions.isEmpty { - actions.append(UIMenu(options: .displayInline, children: interactionActions)) - } - - return UIMenu(children: actions) - } func replySwipeActivationRect() -> CGRect { if let layout = currentResolvedLayout { diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Appearance.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Appearance.swift new file mode 100644 index 00000000..356361f7 --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Appearance.swift @@ -0,0 +1,39 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func applyColorAppearance(_ appearance: FireAppearanceSnapshot) { + guard let payload = currentPayload else { + FireAppearanceTexture.applySnapshot(appearance, to: self) + setNeedsDisplay() + return + } + guard payload.appearance.token != appearance.token else { + // Already baked for this appearance; still refresh canvas in case highlight state moved. + configureSearchHighlight(payload.isSearchHighlighted) + return + } + let updated = payload.withAppearance(appearance) + currentPayload = updated + // Force text rebind when appearance flips, but keep `contentSegmentSignature` so + // FirePostImageNode instances are not destroyed mid-load (blank image placeholders). + renderedContentID = nil + configureMeta(payload: updated) + configureBodyContent(payload: updated) + configureReplyShortcut(payload: updated) + configureOverflowActions(payload: updated) + configureReactionPicker(payload: updated) + configureReactions(payload: updated) + configureSearchHighlight(updated.isSearchHighlighted) + setNeedsDisplay() + } + + func applyColorAppearance(_ colorTraits: UITraitCollection) { + applyColorAppearance(FireAppearanceEnvironment.snapshot(traits: colorTraits)) + } + + func refreshResolvedColorsFromLiveTraitsIfNeeded() { + guard isNodeLoaded, currentPayload != nil else { return } + applyColorAppearance(FireAppearanceEnvironment.snapshot(for: view)) + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Author.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Author.swift new file mode 100644 index 00000000..ce529469 --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Author.swift @@ -0,0 +1,233 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func configureAvatar(payload: FirePostCellRenderPayload, avatarSize: CGFloat) { + let username = payload.post.username.isEmpty ? "?" : payload.post.username + let avatarURL = fireAvatarURL( + avatarTemplate: payload.post.avatarTemplate, + size: avatarSize, + scale: cachedDisplayScale, + baseURLString: payload.baseURLString + ) + let nextAvatarSignature = [ + username, + payload.post.avatarTemplate ?? "", + payload.baseURLString, + avatarURL?.absoluteString ?? "monogram", + String(Int(avatarSize.rounded())), + ].joined(separator: "\u{1F}") + guard avatarSignature != nextAvatarSignature else { + return + } + avatarSignature = nextAvatarSignature + + let monogram = monogramForUsername(username: username) + avatarMonogramNode.attributedText = NSAttributedString( + string: monogram, + attributes: [ + .font: UIFont.systemFont(ofSize: avatarSize * 0.36, weight: .bold), + .foregroundColor: UIColor.white, + ] + ) + avatarMonogramNode.isHidden = false + avatarNode.isHidden = true + avatarNode.alpha = 0 + + if let avatarURL { + avatarNode.isHidden = false + avatarNode.alpha = 0 + loadAvatar(url: avatarURL) + } else { + cancelAvatarLoad() + avatarNode.isHidden = true + } + } + + func configureMeta(payload: FirePostCellRenderPayload) { + let subheadlineFont = UIFontMetrics(forTextStyle: .subheadline).scaledFont( + for: UIFont.systemFont( + ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, + weight: .semibold + ) + ) + let captionFont = UIFont.preferredFont(forTextStyle: .caption2) + let monoCaptionFont = UIFontMetrics(forTextStyle: .caption2).scaledFont( + for: UIFont.monospacedDigitSystemFont( + ofSize: captionFont.pointSize, + weight: .regular + ) + ) + + let appearance = payload.appearance + let primaryInk = appearance.ink + let secondaryInk = appearance.subtleInk + let tertiaryInk = appearance.tertiaryInk + + usernameNode.attributedText = NSAttributedString( + string: FirePostAuthorMetadataDisplay.displayName(for: payload.post), + attributes: [.font: subheadlineFont, .foregroundColor: primaryInk] + ) + let canOpenProfile = !payload.post.username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + avatarContainerNode.accessibilityLabel = canOpenProfile + ? "查看 \(FirePostAuthorMetadataDisplay.displayName(for: payload.post)) 的资料" + : "查看用户资料" + + let primaryBadges = FirePostAuthorMetadataDisplay.primaryBadgeParts(for: payload.post) + if primaryBadges.isEmpty { + authorBadgeNode.isHidden = true + authorBadgeNode.attributedText = nil + } else { + authorBadgeNode.isHidden = false + authorBadgeNode.attributedText = Self.badgeAttributedText(parts: primaryBadges) + } + + let secondaryParts = FirePostAuthorMetadataDisplay.secondaryLineParts(for: payload.post) + if secondaryParts.isEmpty { + authorMetadataNode.isHidden = true + authorMetadataNode.attributedText = nil + } else { + authorMetadataNode.isHidden = false + authorMetadataNode.attributedText = NSAttributedString( + string: secondaryParts.joined(separator: " · "), + attributes: [ + .font: captionFont, + .foregroundColor: secondaryInk, + ] + ) + } + + configureQuote(payload: payload) + + timestampNode.attributedText = NSAttributedString( + string: FireTopicPresentation.compactTimestamp(payload.post.createdAt) ?? "", + attributes: [.font: captionFont, .foregroundColor: tertiaryInk] + ) + + if payload.post.acceptedAnswer { + acceptedAnswerNode.isHidden = false + acceptedAnswerNode.attributedText = acceptedAnswerAttributedText() + } else { + acceptedAnswerNode.isHidden = true + } + + postNumberNode.attributedText = NSAttributedString( + string: "#\(payload.post.postNumber)楼", + attributes: [.font: monoCaptionFont, .foregroundColor: tertiaryInk] + ) + + // Header `...` is retired — overflow lives in the bottom action strip. + menuNode.isHidden = true + menuNode.isEnabled = false + } + + func acceptedAnswerAttributedText() -> NSAttributedString { + let font = UIFontMetrics(forTextStyle: .caption2).scaledFont( + for: UIFont.systemFont( + ofSize: UIFont.preferredFont(forTextStyle: .caption2).pointSize, + weight: .medium + ) + ) + let result = NSMutableAttributedString() + if let image = UIImage( + systemName: "checkmark.circle.fill", + withConfiguration: UIImage.SymbolConfiguration(font: font) + )?.withTintColor(.systemGreen, renderingMode: .alwaysOriginal) { + result.append(NSAttributedString(attachment: NSTextAttachment(image: image))) + result.append(NSAttributedString(string: " ")) + } + result.append(NSAttributedString( + string: "已采纳", + attributes: [.font: font, .foregroundColor: UIColor.systemGreen] + )) + return result + } + + static func badgeAttributedText(parts: [String]) -> NSAttributedString { + let captionFont = UIFont.preferredFont(forTextStyle: .caption2) + let result = NSMutableAttributedString() + let colors: [UIColor] = [ + UIColor.systemOrange, + UIColor.systemTeal, + UIColor.systemIndigo, + UIColor.systemPink, + ] + for (index, part) in parts.enumerated() { + if index > 0 { + result.append(NSAttributedString(string: " ")) + } + let color = colors[index % colors.count] + result.append(NSAttributedString( + string: part, + attributes: [ + .font: UIFontMetrics(forTextStyle: .caption2).scaledFont( + for: UIFont.systemFont(ofSize: captionFont.pointSize, weight: .semibold) + ), + .foregroundColor: color, + .backgroundColor: color.withAlphaComponent(0.13), + ] + )) + } + return result + } + + func showLoadedAvatar() { + avatarNode.alpha = 1 + } + + func showAvatarFallback() { + avatarNode.alpha = 0 + } + + func cancelAvatarLoad() { + avatarLoadTask?.cancel() + avatarLoadTask = nil + avatarLoadGeneration &+= 1 + avatarNode.image = nil + showAvatarFallback() + } + + func loadAvatar(url: URL) { + avatarLoadTask?.cancel() + avatarLoadGeneration &+= 1 + let generation = avatarLoadGeneration + let request = FireRemoteImageRequest(url: url) + + if let cachedImage = FireRemoteImagePipeline.shared.cachedImage(for: request) { + avatarNode.image = cachedImage + showLoadedAvatar() + return + } + + avatarNode.image = nil + showAvatarFallback() + avatarLoadTask = Task { [weak self] in + do { + let image = try await FireRemoteImagePipeline.shared.loadImage(for: request) + guard !Task.isCancelled else { return } + await MainActor.run { + self?.applyLoadedAvatar(image, generation: generation) + } + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { return } + await MainActor.run { + self?.applyFailedAvatarLoad(generation: generation) + } + } + } + } + + func applyLoadedAvatar(_ image: UIImage, generation: UInt64) { + guard generation == avatarLoadGeneration else { return } + avatarNode.image = image + showLoadedAvatar() + } + + func applyFailedAvatarLoad(generation: UInt64) { + guard generation == avatarLoadGeneration else { return } + avatarNode.image = nil + showAvatarFallback() + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Boosts.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Boosts.swift new file mode 100644 index 00000000..58438081 --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Boosts.swift @@ -0,0 +1,120 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func configureBoosts(payload: FirePostCellRenderPayload) { + guard !payload.post.boosts.isEmpty else { + boostContainerNode.isHidden = true + boostBarrageNode.isHidden = true + configureBoostBarrage(boosts: [], batchSignature: "") + configureFixedBoostManualScroller(boosts: []) + boostSignature = [] + return + } + + let usesBodyBarrage = FirePostBoostDisplay.usesBodyBarrage( + depth: currentDepth, + textExpansionState: payload.textExpansionState, + hasBodyTextTarget: payload.renderContent.hasBoostBarrageTextTarget + ) + let bodyBarrageBoosts = usesBodyBarrage + ? FirePostBoostDisplay.bodyBarrageBoosts(for: payload.post.boosts) + : [] + boostBarrageNode.isHidden = !usesBodyBarrage || bodyBarrageBoosts.isEmpty + configureBoostBarrage( + boosts: bodyBarrageBoosts, + batchSignature: usesBodyBarrage && !bodyBarrageBoosts.isEmpty + ? FirePostBoostDisplay.bodyBarrageBatchSignature( + postID: payload.post.id, + boosts: payload.post.boosts + ) + : "" + ) + boostContainerNode.isHidden = usesBodyBarrage + if usesBodyBarrage { + configureFixedBoostManualScroller(boosts: []) + boostSignature = [] + return + } + + let nextSignature = payload.post.boosts.map { boost in + [ + String(boost.id), + boost.user.username, + boost.user.name ?? "", + boost.displayText, + FirePostBoostDisplay.contentSignature(for: boost), + ].joined(separator: "\u{1E}") + } + if boostSignature != nextSignature { + boostSignature = nextSignature + } + configureFixedBoostManualScroller(boosts: payload.post.boosts) + boostContainerNode.setNeedsLayout() + } + + func configureFixedBoostManualScroller(boosts: [TopicPostBoostState]) { + boostManualBoosts = boosts + boostManualScrollerNode.isHidden = boosts.isEmpty + let baseURLString = currentPayload?.baseURLString ?? "https://linux.do" + performOnMain { [weak self] in + guard let self, + self.boostManualScrollerNode.isNodeLoaded, + let view = self.boostManualScrollerNode.view as? FirePostBoostManualScrollerView else { + return + } + view.configure(boosts: boosts, baseURLString: baseURLString) + } + } + + func fixedBoostManualScrollerHeight(availableWidth: CGFloat) -> CGFloat { + guard let payload = currentPayload else { + return FirePostCellLayoutCalculator.fixedBoostManualHeight(forUsedRowCount: 1) + } + let boostLines = FirePostBoostDisplay.fixedDisplayLines( + for: boostManualBoosts, + depth: currentDepth, + textExpansionState: payload.textExpansionState, + hasBodyTextTarget: payload.renderContent.hasBoostBarrageTextTarget + ) + return FirePostCellLayoutCalculator.fixedBoostManualHeight( + boostLines: boostLines, + containerWidth: availableWidth, + contentSizeCategory: currentContentSizeCategory + ) + } + + func configureBoostBarrage(boosts: [TopicPostBoostState], batchSignature: String) { + boostBarrageBoosts = boosts + boostBarrageLines = boosts.map(FirePostBoostDisplay.displayLine(for:)) + boostBarrageBatchSignature = batchSignature + let animationsEnabled = boostAnimationsEnabled + let baseURLString = currentPayload?.baseURLString ?? "https://linux.do" + performOnMain { [weak self] in + guard let self, + self.boostBarrageNode.isNodeLoaded, + let view = self.boostBarrageNode.view as? FirePostBoostBarrageView else { + return + } + view.configure( + boosts: boosts, + batchSignature: batchSignature, + animationsEnabled: animationsEnabled, + baseURLString: baseURLString + ) + } + } + + func setBoostAnimationsEnabled(_ enabled: Bool) { + guard boostAnimationsEnabled != enabled else { return } + boostAnimationsEnabled = enabled + performOnMain { [weak self] in + guard let self, + self.boostBarrageNode.isNodeLoaded, + let view = self.boostBarrageNode.view as? FirePostBoostBarrageView else { + return + } + view.setAnimationsEnabled(enabled) + } + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Configuration.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Configuration.swift new file mode 100644 index 00000000..29357d16 --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Configuration.swift @@ -0,0 +1,169 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func performOnMain(_ work: @escaping () -> Void) { + if Thread.isMainThread { + work() + } else { + DispatchQueue.main.async(execute: work) + } + } + + func configure( + payload: FirePostCellRenderPayload, + callbacks: FirePostCellCallbacks, + depth: Int, + showsThreadLine: Bool, + showsDivider: Bool + ) { + currentPayload = payload + currentCallbacks = callbacks + currentDepth = depth + currentShowsThreadLine = showsThreadLine + currentShowsDivider = showsDivider + currentLayoutWidth = payload.layoutWidth + currentResolvedLayout = payload.layout + // UIApplication is main-thread only; node-blocks may configure off-main. + if Thread.isMainThread { + Self.lastKnownContentSizeCategory = UIApplication.shared.preferredContentSizeCategory + cachedDisplayScale = UIScreen.main.scale + } + currentContentSizeCategory = Self.lastKnownContentSizeCategory + + let vd = FirePostCellLayoutCalculator.visualDepth(for: depth) + let avatarSz = vd > 0 ? FirePostCellLayoutCalculator.avatarSizeNested : FirePostCellLayoutCalculator.avatarSizeRoot + let avatarSp = vd > 0 ? FirePostCellLayoutCalculator.avatarSpacingNested : FirePostCellLayoutCalculator.avatarSpacingRoot + currentAvatarSize = avatarSz + currentAvatarSpacing = avatarSp + + avatarContainerNode.cornerRadius = avatarSz / 2 + avatarNode.cornerRadius = avatarSz / 2 + avatarContainerNode.style.preferredSize = CGSize(width: avatarSz, height: avatarSz) + avatarNode.style.preferredSize = CGSize(width: avatarSz, height: avatarSz) + + configureAvatar(payload: payload, avatarSize: avatarSz) + configureThreadLine(shows: showsThreadLine) + configureMeta(payload: payload) + configureBodyContent(payload: payload) + configurePolls(payload: payload) + boostAnimationsEnabled = payload.boostAnimationsEnabled + configureBoosts(payload: payload) + // Reset per-row overflow expansion on reuse / reconfigure. + // UIView transform / label work must stay on main — configure may run in a + // Texture background node-block. + cancelOverflowAutoCollapse() + areOverflowActionsExpanded = false + resetSwipeReplyReveal(animated: false) + + configureReplyShortcut(payload: payload) + configureOverflowActions(payload: payload) + configureReactionPicker(payload: payload) + configureReactions(payload: payload) + configureSearchHighlight(payload.isSearchHighlighted) + configureDivider(shows: showsDivider) + } + + func applyBands( + _ bands: Set, + payload: FirePostCellRenderPayload, + callbacks: FirePostCellCallbacks, + showsThreadLine: Bool, + relayout: Bool + ) { + guard !bands.isEmpty else { return } + currentPayload = payload + currentCallbacks = callbacks + currentShowsThreadLine = showsThreadLine + currentShowsDivider = payload.showsDivider + if relayout { + currentLayoutWidth = payload.layoutWidth + currentResolvedLayout = payload.layout + } + if bands.contains(.author) { + configureAvatar(payload: payload, avatarSize: currentAvatarSize) + configureMeta(payload: payload) + } + if bands.contains(.quote) { + configureQuote(payload: payload) + } + if bands.contains(.images) { + applyImageBand(payload: payload) + } + if bands.contains(.text) { + applyTextBand(payload: payload) + configurePolls(payload: payload) + boostAnimationsEnabled = payload.boostAnimationsEnabled + configureBoosts(payload: payload) + } + if bands.contains(.showMore) { + configureBodyContent(payload: payload) + configureReplyShortcut(payload: payload) + } + if bands.contains(.actions) { + applyInPlaceActionMutatingState(payload) + configureSearchHighlight(payload.isSearchHighlighted) + } + if bands.contains(.reactions) { + configureReactionPicker(payload: payload) + if relayout { + configureReactions(payload: payload) + } else { + applyInPlaceReactions(payload) + } + } + if bands.contains(.thread) { + configureThreadLine(shows: currentShowsThreadLine) + configureDivider(shows: payload.showsDivider) + } + if relayout { + setNeedsLayout() + } + } + + func applyInPlaceInteraction( + payload: FirePostCellRenderPayload, + callbacks: FirePostCellCallbacks + ) { + currentPayload = payload + currentCallbacks = callbacks + applyInPlaceActionMutatingState(payload) + applyInPlaceReactions(payload) + updatePollInteractionState(payload: payload) + configureSearchHighlight(payload.isSearchHighlighted) + } + + func applyVisibleRowRelayout( + payload: FirePostCellRenderPayload, + callbacks: FirePostCellCallbacks + ) { + currentPayload = payload + currentCallbacks = callbacks + currentLayoutWidth = payload.layoutWidth + currentResolvedLayout = payload.layout + configureBodyContent(payload: payload) + configureReactionPicker(payload: payload) + applyInPlaceActionMutatingState(payload) + applyInPlaceReactions(payload) + configureReplyShortcut(payload: payload) + configureSearchHighlight(payload.isSearchHighlighted) + } + + func configureSearchHighlight(_ isHighlighted: Bool) { + let appearance = currentPayload?.appearance + ?? FireAppearanceEnvironment.snapshot(traits: .current) + let accent = FireTextureAttributedText.resolvedColor( + Self.accentTextColor, + with: appearance.traits + ) + backgroundColor = isHighlighted + ? accent.withAlphaComponent(0.10) + : appearance.canvas + borderWidth = isHighlighted ? 1 : 0 + borderColor = isHighlighted + ? accent.withAlphaComponent(0.70).cgColor + : UIColor.clear.cgColor + cornerRadius = isHighlighted ? 8 : 0 + clipsToBounds = isHighlighted + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+ContextMenu.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+ContextMenu.swift new file mode 100644 index 00000000..b0a7adab --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+ContextMenu.swift @@ -0,0 +1,179 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func menuAttributes( + for kind: FirePostCellActionKind, + isMutating: Bool, + destructive: Bool = false + ) -> UIMenuElement.Attributes { + var attributes: UIMenuElement.Attributes = [] + if destructive { + attributes.insert(.destructive) + } + if !FirePostCellActionAvailability.isEnabled(kind, canUse: true, isMutating: isMutating) { + attributes.insert(.disabled) + } + return attributes + } + + @objc func handleActionBookmarkTap() { + guard let payload = currentPayload, let callbacks = currentCallbacks else { return } + noteOverflowInteraction() + FireMotionHaptics.impact(.light) + callbacks.onBookmarkPost(payload.post) + setOverflowActionsExpanded(false, animated: true) + } + + @objc func handleActionEditTap() { + guard let payload = currentPayload, let callbacks = currentCallbacks else { return } + noteOverflowInteraction() + callbacks.onEditPost(payload.post) + setOverflowActionsExpanded(false, animated: true) + } + + @objc func handleActionFlagTap() { + guard let payload = currentPayload, let callbacks = currentCallbacks else { return } + noteOverflowInteraction() + callbacks.onFlagPost(payload.post) + setOverflowActionsExpanded(false, animated: true) + } + + @objc func handleMenuTap() { + guard let payload = currentPayload, + let callbacks = currentCallbacks, + let presenter = nearestViewController() else { + return + } + let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) + let post = payload.post + let isMutating = payload.isMutating + if post.canEdit { + alert.addAction(UIAlertAction(title: "编辑", style: .default) { _ in + callbacks.onEditPost(post) + }) + } + if payload.canWriteInteractions && !post.hidden { + alert.addAction(UIAlertAction(title: "回复", style: .default) { _ in + callbacks.onReplyPost(post) + }) + let react = UIAlertAction(title: "回应", style: .default) { _ in + callbacks.onToggleReactionPicker(post) + } + react.isEnabled = FirePostCellActionAvailability.isEnabled( + .react, + canUse: true, + isMutating: isMutating + ) + alert.addAction(react) + if post.canBoost { + alert.addAction(UIAlertAction(title: "Boost", style: .default) { _ in + callbacks.onBoostPost(post) + }) + } + alert.addAction(UIAlertAction(title: "引用回复", style: .default) { _ in + callbacks.onQuotePost(post) + }) + alert.addAction(UIAlertAction(title: post.bookmarked ? "编辑书签" : "添加书签", style: .default) { _ in + FireMotionHaptics.impact(.light) + callbacks.onBookmarkPost(post) + }) + alert.addAction(UIAlertAction(title: "举报", style: .default) { _ in + callbacks.onFlagPost(post) + }) + } + if post.canRecover { + alert.addAction(UIAlertAction(title: "恢复", style: .default) { _ in + callbacks.onRecoverPost(post) + }) + } + if post.canDelete && !post.hidden { + alert.addAction(UIAlertAction(title: "删除", style: .destructive) { _ in + callbacks.onDeletePost(post) + }) + } + alert.addAction(UIAlertAction(title: "取消", style: .cancel)) + alert.popoverPresentationController?.sourceView = menuNode.view + alert.popoverPresentationController?.sourceRect = menuNode.view.bounds + FireMotionHaptics.impact(.medium) + presenter.present(alert, animated: true) + } + + func buildMenu(for post: TopicPostState, callbacks: FirePostCellCallbacks, canWrite: Bool, isMutating: Bool) -> UIMenu { + var actions: [UIMenu] = [] + + if post.canEdit { + let edit = UIAction(title: "编辑", image: UIImage(systemName: "pencil")) { _ in + callbacks.onEditPost(post) + } + edit.attributes = menuAttributes(for: .edit, isMutating: isMutating) + actions.append(UIMenu(options: .displayInline, children: [edit])) + } + + var interactionActions: [UIAction] = [] + if canWrite && !post.hidden { + let reply = UIAction(title: "回复", image: UIImage(systemName: "arrowshape.turn.up.left")) { _ in + callbacks.onReplyPost(post) + } + reply.attributes = menuAttributes(for: .reply, isMutating: isMutating) + interactionActions.append(reply) + + let react = UIAction(title: "回应", image: UIImage(systemName: "face.smiling")) { _ in + callbacks.onToggleReactionPicker(post) + } + react.attributes = menuAttributes(for: .react, isMutating: isMutating) + interactionActions.append(react) + + if post.canBoost { + let boost = UIAction(title: "Boost", image: UIImage(systemName: "bolt")) { _ in + callbacks.onBoostPost(post) + } + boost.attributes = menuAttributes(for: .boost, isMutating: isMutating) + interactionActions.append(boost) + } + + let quote = UIAction(title: "引用回复", image: UIImage(systemName: "text.quote")) { _ in + callbacks.onQuotePost(post) + } + quote.attributes = menuAttributes(for: .quote, isMutating: isMutating) + interactionActions.append(quote) + + let bookmarkTitle = post.bookmarked ? "编辑书签" : "添加书签" + let bookmarkIcon = post.bookmarked ? "bookmark.fill" : "bookmark" + let bookmark = UIAction(title: bookmarkTitle, image: UIImage(systemName: bookmarkIcon)) { _ in + FireMotionHaptics.impact(.light) + callbacks.onBookmarkPost(post) + } + bookmark.attributes = menuAttributes(for: .bookmark, isMutating: isMutating) + interactionActions.append(bookmark) + + let flag = UIAction(title: "举报", image: UIImage(systemName: "flag")) { _ in + callbacks.onFlagPost(post) + } + flag.attributes = menuAttributes(for: .flag, isMutating: isMutating) + interactionActions.append(flag) + } + + if post.canRecover { + let recover = UIAction(title: "恢复", image: UIImage(systemName: "arrow.uturn.backward")) { _ in + callbacks.onRecoverPost(post) + } + recover.attributes = menuAttributes(for: .recover, isMutating: isMutating) + interactionActions.append(recover) + } + + if post.canDelete && !post.hidden { + let delete = UIAction(title: "删除", image: UIImage(systemName: "trash"), attributes: .destructive) { _ in + callbacks.onDeletePost(post) + } + delete.attributes = menuAttributes(for: .delete, isMutating: isMutating, destructive: true) + interactionActions.append(delete) + } + + if !interactionActions.isEmpty { + actions.append(UIMenu(options: .displayInline, children: interactionActions)) + } + + return UIMenu(children: actions) + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+HitTesting.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+HitTesting.swift new file mode 100644 index 00000000..b1cabb67 --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+HitTesting.swift @@ -0,0 +1,75 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + @objc func handleImageTap(_ sender: FirePostImageNode) { + currentCallbacks?.onOpenImage(sender.image) + } + + @objc func handleProfileTapGesture(_ gesture: UITapGestureRecognizer) { + _ = handleProfileTap(at: gesture.location(in: view)) + } + + @discardableResult + func handleProfileTap(at point: CGPoint) -> Bool { + guard profileHitRects().contains(where: { $0.contains(point) }) else { + return false + } + guard let username = currentPayload?.post.username.trimmingCharacters(in: .whitespacesAndNewlines), + !username.isEmpty else { + return false + } + FireMotionHaptics.selection() + currentCallbacks?.onOpenProfile(username) + return true + } + + func profileHitRects() -> [CGRect] { + var rects: [CGRect] = [] + if isNodeLoaded { + let avatar = avatarContainerNode.view.convert(avatarContainerNode.view.bounds, to: view) + if !avatar.isNull, avatar.width > 1, avatar.height > 1 { + rects.append(avatar.insetBy(dx: -8, dy: -8)) + } + if !usernameNode.isHidden { + let name = usernameNode.view.convert(usernameNode.view.bounds, to: view) + if !name.isNull, name.width > 1, name.height > 1 { + rects.append(name.insetBy(dx: -4, dy: -6)) + } + } + } + if let layout = currentResolvedLayout { + rects.append(layout.avatarFrame.insetBy(dx: -8, dy: -8)) + let meta = layout.metaFrame + if !meta.isNull, !meta.isEmpty { + rects.append( + CGRect(x: meta.minX, y: meta.minY, width: min(meta.width, 168), height: meta.height) + .insetBy(dx: -4, dy: -6) + ) + } + } + if rects.isEmpty { + let indent = FirePostCellLayoutCalculator.indentWidth(for: currentDepth) + rects.append( + CGRect( + x: FirePostCellLayoutCalculator.outerHorizontalPadding + indent, + y: 0, + width: currentAvatarSize, + height: currentAvatarSize + ).insetBy(dx: -8, dy: -8) + ) + } + return rects + } + + func nearestViewController() -> UIViewController? { + var responder: UIResponder? = view + while let current = responder { + if let viewController = current as? UIViewController { + return viewController + } + responder = current.next + } + return nil + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+LayoutSpec.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+LayoutSpec.swift new file mode 100644 index 00000000..f0fcac7d --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+LayoutSpec.swift @@ -0,0 +1,360 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { + let vd = FirePostCellLayoutCalculator.visualDepth(for: currentDepth) + let indent = CGFloat(min(vd, FirePostCellLayoutCalculator.maxVisualDepth)) * FirePostCellLayoutCalculator.indentWidthPerDepth + let avatarSz = currentAvatarSize + let avatarSp = currentAvatarSpacing + let outerPadding = FirePostCellLayoutCalculator.outerHorizontalPadding + let totalWidth = constrainedSize.max.width.isFinite ? constrainedSize.max.width : currentLayoutWidth + let rowAvailableWidth = max(totalWidth - outerPadding * 2 - indent, 1) + let bodyAvailableWidth = Self.availableContentWidth( + totalWidth: totalWidth, + depth: currentDepth, + avatarSize: currentAvatarSize, + avatarSpacing: currentAvatarSpacing + ) + let headerAvailableWidth = max(rowAvailableWidth - avatarSz - avatarSp, 1) + let shouldSuppressAttachments: Bool + if let currentResolvedLayout { + shouldSuppressAttachments = currentResolvedLayout.textExpansionFrame != nil + } else { + let hasImageSegments = currentPayload?.renderContent.segments.contains(where: \.isImage) ?? false + shouldSuppressAttachments = (hasImageSegments || !pollContainerNode.isHidden) + && Self.shouldSuppressAttachmentsForCollapsedText( + plainText: currentPayload?.renderContent.plainText ?? "", + hasAttributedText: currentPayload?.renderContent.attributedText != nil, + textExpansionState: currentPayload?.textExpansionState ?? .disabled, + totalWidth: totalWidth, + depth: currentDepth, + avatarSize: currentAvatarSize, + avatarSpacing: currentAvatarSpacing, + contentSizeCategory: currentContentSizeCategory + ) + } + + // Avatar column + var avatarColumnChildren: [ASLayoutElement] = [avatarContainerNode] + if !threadLineNode.isHidden { + avatarColumnChildren.append(threadLineNode) + } + let avatarColumn = ASStackLayoutSpec( + direction: .vertical, + spacing: 0, + justifyContent: .start, + alignItems: .center, + children: avatarColumnChildren + ) + avatarColumn.style.minWidth = ASDimensionMake(avatarSz) + avatarColumn.style.maxWidth = ASDimensionMake(avatarSz) + avatarColumn.style.flexShrink = 0.0 + + // Meta row: display name + "回复 @user" share the first line; @handle/tags stay below. + var authorChildren: [ASLayoutElement] = [usernameNode] + if !replyContextNode.isHidden { + replyContextNode.style.flexShrink = 1.0 + authorChildren.append(replyContextNode) + } + if !authorBadgeNode.isHidden { + authorChildren.append(authorBadgeNode) + } + if !acceptedAnswerNode.isHidden { + authorChildren.append(acceptedAnswerNode) + } + if !menuNode.isHidden { + menuNode.style.preferredSize = CGSize(width: 20, height: 20) + authorChildren.append(menuNode) + } + let authorRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: 5, + justifyContent: .start, + alignItems: .center, + children: authorChildren + ) + authorRow.style.flexShrink = 1.0 + authorRow.style.flexGrow = 0.0 + + let firstLineSpacer = ASLayoutSpec() + firstLineSpacer.style.flexGrow = 1.0 + + let metaChildren: [ASLayoutElement] = [authorRow, firstLineSpacer, timestampNode] + let metaRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: 6, + justifyContent: .start, + alignItems: .center, + children: metaChildren + ) + metaRow.style.flexShrink = 1.0 + + // Header stays to the right of the avatar; body content uses the full row width below it. + var headerChildren: [ASLayoutElement] = [metaRow] + var didAttachBoostBarrage = false + var secondaryChildren: [ASLayoutElement] = [] + if !authorMetadataNode.isHidden { + secondaryChildren.append(authorMetadataNode) + } + if !secondaryChildren.isEmpty { + let secondarySpacer = ASLayoutSpec() + secondarySpacer.style.flexGrow = 1.0 + secondaryChildren.append(secondarySpacer) + secondaryChildren.append(postNumberNode) + let secondaryRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: 6, + justifyContent: .start, + alignItems: .center, + children: secondaryChildren + ) + secondaryRow.style.flexShrink = 1.0 + headerChildren.append(secondaryRow) + } else { + let secondarySpacer = ASLayoutSpec() + secondarySpacer.style.flexGrow = 1.0 + let postNumberRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: 0, + justifyContent: .start, + alignItems: .center, + children: [secondarySpacer, postNumberNode] + ) + headerChildren.append(postNumberRow) + } + + let headerContentStack = ASStackLayoutSpec( + direction: .vertical, + spacing: FirePostCellLayoutCalculator.headerStackSpacing, + justifyContent: .start, + alignItems: .stretch, + children: headerChildren + ) + headerContentStack.style.flexGrow = 1.0 + headerContentStack.style.flexShrink = 1.0 + headerContentStack.style.minWidth = ASDimensionMake(headerAvailableWidth) + headerContentStack.style.maxWidth = ASDimensionMake(headerAvailableWidth) + + var bodyChildren: [ASLayoutElement] = [] + + if !bodyTextNode.isHidden { + bodyChildren.append(bodyElement(bodyTextNode, didAttachBoostBarrage: &didAttachBoostBarrage)) + } + if !bodySelectableTextNode.isHidden { + bodyChildren.append(bodyElement(bodySelectableTextNode, didAttachBoostBarrage: &didAttachBoostBarrage)) + } + + if !shouldSuppressAttachments { + for segmentNode in contentSegmentNodes { + bodyChildren.append(bodyElement(segmentNode, didAttachBoostBarrage: &didAttachBoostBarrage)) + } + + // Poll container + if !pollContainerNode.isHidden { + bodyChildren.append(pollContainerNode) + } + } + + // Footer chrome: + // [bubble?] [reply react boost ...] + // [quick reaction strip when expanded] + // [existing reaction chips full width] + var actionRowChildren: [ASLayoutElement] = [] + if !replyShortcutNode.isHidden { + replyShortcutNode.style.flexGrow = 0 + replyShortcutNode.style.flexShrink = 0 + actionRowChildren.append(replyShortcutNode) + } + + let primaryCluster = [ + actionReplyNode, + actionReactNode, + actionBoostNode, + overflowNode, + ].filter { !$0.isHidden } + for node in primaryCluster { + node.style.flexGrow = 0 + node.style.flexShrink = 0 + actionRowChildren.append(node) + } + + let overflowCluster = [ + actionQuoteNode, + actionBookmarkNode, + actionFlagNode, + actionEditNode, + ].filter { !$0.isHidden } + actionRowChildren.append(contentsOf: overflowCluster) + + var footerChildren: [ASLayoutElement] = [] + if !actionRowChildren.isEmpty { + let actionRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: FirePostCellLayoutCalculator.actionIconSpacing, + justifyContent: .start, + alignItems: .center, + children: actionRowChildren + ) + actionRow.style.flexShrink = 1.0 + actionRow.style.minHeight = ASDimensionMake(FirePostCellLayoutCalculator.actionRowHeight) + footerChildren.append(actionRow) + } + + if !reactionPickerScrollNode.isHidden, !reactionPickerButtons.isEmpty { + reactionPickerScrollNode.style.flexGrow = 1 + reactionPickerScrollNode.style.flexShrink = 1 + reactionPickerScrollNode.style.minHeight = ASDimensionMake( + FirePostCellLayoutCalculator.reactionPickerStripHeight + ) + reactionPickerScrollNode.style.maxHeight = ASDimensionMake( + FirePostCellLayoutCalculator.reactionPickerStripHeight + ) + footerChildren.append(reactionPickerScrollNode) + } + + if !reactionContainerNode.isHidden, !reactionButtons.isEmpty { + let reactionRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: FirePostCellLayoutCalculator.reactionChipHorizontalSpacing, + justifyContent: .start, + alignItems: .center, + children: reactionButtons + ) + reactionRow.style.flexShrink = 1.0 + reactionRow.style.minHeight = ASDimensionMake( + FirePostCellLayoutCalculator.reactionChipHeight + ) + footerChildren.append(reactionRow) + } + + let actionElement: ASLayoutElement? + if footerChildren.isEmpty { + actionElement = nil + } else if footerChildren.count == 1 { + actionElement = footerChildren[0] + } else { + let stack = ASStackLayoutSpec( + direction: .vertical, + spacing: FirePostCellLayoutCalculator.reactionTopSpacing, + justifyContent: .start, + alignItems: .stretch, + children: footerChildren + ) + actionElement = stack + } + + let boostElement: ASLayoutElement? = !shouldSuppressAttachments && !boostContainerNode.isHidden + ? boostContainerNode + : nil + if let boostElement, let actionElement { + let footerStack = ASStackLayoutSpec( + direction: .vertical, + spacing: 0, + justifyContent: .start, + alignItems: .stretch, + children: [boostElement, actionElement] + ) + footerStack.style.flexShrink = 1.0 + bodyChildren.append(footerStack) + } else if let boostElement { + bodyChildren.append(boostElement) + } else if let actionElement { + bodyChildren.append(actionElement) + } + + // Divider + if !dividerNode.isHidden { + dividerNode.style.preferredSize = CGSize(width: max(bodyAvailableWidth, 1), height: 0.5) + bodyChildren.append(dividerNode) + } + + let rootStack: ASLayoutSpec + if FirePostCellLayoutCalculator.usesFullWidthBody(for: currentDepth) { + let headerRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: avatarSp, + justifyContent: .start, + alignItems: .start, + children: [avatarColumn, headerContentStack] + ) + headerRow.style.flexShrink = 1.0 + + let contentChildren: [ASLayoutElement] = [headerRow] + bodyChildren + let contentStack = ASStackLayoutSpec( + direction: .vertical, + spacing: FirePostCellLayoutCalculator.headerToBodySpacing, + justifyContent: .start, + alignItems: .stretch, + children: contentChildren + ) + contentStack.style.flexGrow = 1.0 + contentStack.style.flexShrink = 1.0 + contentStack.style.minWidth = ASDimensionMake(max(rowAvailableWidth, 1)) + contentStack.style.maxWidth = ASDimensionMake(max(rowAvailableWidth, 1)) + rootStack = contentStack + } else { + let contentColumnChildren: [ASLayoutElement] = [headerContentStack] + bodyChildren + let contentColumn = ASStackLayoutSpec( + direction: .vertical, + spacing: FirePostCellLayoutCalculator.headerToBodySpacing, + justifyContent: .start, + alignItems: .stretch, + children: contentColumnChildren + ) + contentColumn.style.flexGrow = 1.0 + contentColumn.style.flexShrink = 1.0 + contentColumn.style.minWidth = ASDimensionMake(max(bodyAvailableWidth, 1)) + contentColumn.style.maxWidth = ASDimensionMake(max(bodyAvailableWidth, 1)) + + let row = ASStackLayoutSpec( + direction: .horizontal, + spacing: avatarSp, + justifyContent: .start, + alignItems: .stretch, + children: [avatarColumn, contentColumn] + ) + row.style.flexShrink = 1.0 + row.style.minWidth = ASDimensionMake(max(rowAvailableWidth, 1)) + row.style.maxWidth = ASDimensionMake(max(rowAvailableWidth, 1)) + rootStack = row + } + + return ASInsetLayoutSpec( + insets: UIEdgeInsets( + top: 8, + left: outerPadding + indent, + bottom: 8, + right: outerPadding + ), + child: rootStack + ) + } + + override func layout() { + super.layout() + + // Size poll views inside the container. Prefer the container's laid-out width so + // hit targets match the Texture frame (do not overflow a narrow parent bounds). + let fallbackWidth = Self.availableContentWidth( + totalWidth: calculatedSize.width, + depth: currentDepth, + avatarSize: currentAvatarSize, + avatarSpacing: currentAvatarSpacing + ) + let containerWidth = pollContainerNode.bounds.width + let availableWidth = containerWidth > 1 ? containerWidth : fallbackWidth + + var pollY: CGFloat = 0 + for (index, pollView) in pollViews.enumerated() { + let height = index < pollHeights.count ? pollHeights[index] : 0 + pollView.frame = CGRect( + x: 0, + y: pollY, + width: availableWidth, + height: height + ) + pollY += height + 10 + } + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Polls.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Polls.swift new file mode 100644 index 00000000..6145bdfb --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Polls.swift @@ -0,0 +1,114 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func configurePolls(payload: FirePostCellRenderPayload) { + let pollModels = FirePostPollRenderModel.models(from: payload.post.polls) + guard !pollModels.isEmpty else { + pollContainerNode.isHidden = true + rebuildPollViews([], [], payload: payload) + return + } + + pollContainerNode.isHidden = false + let nextSignature = pollModels.map(\.signature) + let availableWidth = Self.availableContentWidth( + totalWidth: payload.layoutWidth, + depth: currentDepth, + avatarSize: currentAvatarSize, + avatarSpacing: currentAvatarSpacing + ) + if pollSignature != nextSignature || abs(pollWidth - availableWidth) > 0.5 { + rebuildPollViews(payload.post.polls, pollModels, payload: payload, availableWidth: availableWidth) + pollSignature = nextSignature + pollWidth = availableWidth + } else { + updatePollInteractionState(payload: payload) + } + } + + func updatePollInteractionState(payload: FirePostCellRenderPayload) { + let canWrite = payload.canWriteInteractions + let isMutating = payload.isMutating + performOnMain { [weak self] in + guard let self else { return } + for view in self.pollViews { + view.updateInteractionState(canInteract: canWrite, isMutating: isMutating) + } + } + } + + func rebuildPollViews( + _ polls: [PollState], + _ models: [FirePostPollRenderModel], + payload: FirePostCellRenderPayload, + availableWidth: CGFloat? = nil + ) { + // Do not touch UIView hierarchy here — this path can run off-main in Texture. + pollHeights.removeAll(keepingCapacity: true) + let width = availableWidth ?? Self.availableContentWidth( + totalWidth: payload.layoutWidth, + depth: currentDepth, + avatarSize: currentAvatarSize, + avatarSpacing: currentAvatarSpacing + ) + + // Heights are pure layout math and can stay on the Texture worker queue. + var nextHeights: [CGFloat] = [] + nextHeights.reserveCapacity(models.count) + for model in models { + nextHeights.append(FirePostPollView.preferredHeight( + for: model, + availableWidth: width, + contentSizeCategory: currentContentSizeCategory + )) + } + pollHeights = nextHeights + let totalPollHeight = pollHeights.reduce(0, +) + CGFloat(max(pollHeights.count - 1, 0)) * 10 + // Width must match the laid-out poll views. A 1pt container still draws subviews + // that overflow its bounds, but UIKit hit-testing never reaches those controls. + pollContainerNode.style.preferredSize = CGSize(width: max(width, 1), height: ceil(totalPollHeight)) + pollContainerNode.style.minWidth = ASDimensionMake(max(width, 1)) + pollContainerNode.style.maxWidth = ASDimensionMake(max(width, 1)) + + // UIView construction / hierarchy edits must happen on main. + let pollsSnapshot = polls + let modelsSnapshot = models + let canWrite = payload.canWriteInteractions + let isMutating = payload.isMutating + performOnMain { [weak self] in + guard let self else { return } + for view in self.pollViews { + view.removeFromSuperview() + } + self.pollViews.removeAll(keepingCapacity: true) + + for (index, model) in modelsSnapshot.enumerated() { + guard index < pollsSnapshot.count else { break } + let pollView = FirePostPollView() + let poll = pollsSnapshot[index] + pollView.isUserInteractionEnabled = true + pollView.configure( + model: model, + canInteract: canWrite, + isMutating: isMutating, + onSubmit: { [weak self] selectedOptions in + guard let self, + let p = self.currentPayload, + let callbacks = self.currentCallbacks else { return } + callbacks.onVotePoll(p.post, poll, selectedOptions) + }, + onRemoveVote: { [weak self] in + guard let self, + let p = self.currentPayload, + let callbacks = self.currentCallbacks else { return } + callbacks.onUnvotePoll(p.post, poll) + } + ) + self.pollContainerNode.view.addSubview(pollView) + self.pollViews.append(pollView) + } + self.setNeedsLayout() + } + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Quote.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Quote.swift new file mode 100644 index 00000000..ef06618d --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Quote.swift @@ -0,0 +1,19 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func configureQuote(payload: FirePostCellRenderPayload) { + if let replyContext = payload.replyContext, + let targetPN = payload.replyTargetPostNumber, targetPN > 0 { + replyContextNode.isHidden = false + let replyContextFont = UIFont.preferredFont(forTextStyle: .caption1) + replyContextNode.setAttributedTitle(NSAttributedString( + string: replyContext, + attributes: [.font: replyContextFont, .foregroundColor: Self.accentTextColor] + ), for: .normal) + } else { + replyContextNode.isHidden = true + replyContextNode.setAttributedTitle(nil, for: .normal) + } + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+QuoteAction.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+QuoteAction.swift new file mode 100644 index 00000000..510f7899 --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+QuoteAction.swift @@ -0,0 +1,100 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func configureReplyShortcut(payload: FirePostCellRenderPayload) { + guard let count = payload.replyShortcutCount else { + replyShortcutNode.isHidden = true + replyShortcutNode.setImage(nil, for: .normal) + replyShortcutNode.setAttributedTitle(nil, for: .normal) + return + } + replyShortcutNode.isHidden = false + // Always tappable so expand/collapse is never blocked by a loading flag. + replyShortcutNode.isEnabled = true + + let expanded = payload.isReplyThreadExpanded + let symbolName = expanded ? "bubble.left.fill" : "bubble.left" + // Collapsed = muted; expanded thread = accent orange for icon AND count. + let dynamicTint = expanded ? Self.accentTextColor : Self.tertiaryInkColor + let tint = FireTextureAttributedText.resolvedColor(dynamicTint, with: payload.colorTraits) + // Same glyph size as reply/react/boost action icons (14pt medium). + let symbolConfig = UIImage.SymbolConfiguration( + pointSize: 14, + weight: expanded ? .semibold : .medium + ) + // Template + tintColor keeps SF Symbol color in sync with the count label + // (alwaysOriginal dynamic UIColor can leave the glyph on the stale muted tint). + if let image = UIImage(systemName: symbolName, withConfiguration: symbolConfig) { + replyShortcutNode.tintColor = tint + replyShortcutNode.imageNode.tintColor = tint + replyShortcutNode.setImage(image.withRenderingMode(.alwaysTemplate), for: .normal) + replyShortcutNode.setImage(image.withRenderingMode(.alwaysTemplate), for: .disabled) + replyShortcutNode.setImage(image.withRenderingMode(.alwaysTemplate), for: .highlighted) + } + replyShortcutNode.imageNode.contentMode = .center + + let countText = payload.isLoadingReplyContext ? "…" : "\(count)" + let countFont = UIFontMetrics(forTextStyle: .caption1).scaledFont( + for: .systemFont(ofSize: 13, weight: expanded ? .semibold : .medium) + ) + let countAttributes: [NSAttributedString.Key: Any] = [ + .font: countFont, + .foregroundColor: tint, + ] + replyShortcutNode.setAttributedTitle(NSAttributedString( + string: countText, + attributes: countAttributes + ), for: .normal) + replyShortcutNode.setAttributedTitle(NSAttributedString( + string: countText, + attributes: countAttributes + ), for: .disabled) + replyShortcutNode.setAttributedTitle(NSAttributedString( + string: countText, + attributes: countAttributes + ), for: .highlighted) + replyShortcutNode.contentSpacing = 4 + replyShortcutNode.contentHorizontalAlignment = .middle + replyShortcutNode.contentVerticalAlignment = .center + // Match action-icon hit box height; width fits icon + count. + replyShortcutNode.style.minHeight = ASDimensionMake( + FirePostCellLayoutCalculator.replyShortcutHeight + ) + replyShortcutNode.style.minWidth = ASDimensionMake( + FirePostCellLayoutCalculator.replyShortcutMinWidth + ) + replyShortcutNode.hitTestSlop = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6) + replyShortcutNode.accessibilityLabel = expanded + ? "收起 \(count) 条回复" + : "展开 \(count) 条回复" + } + + @objc func handleReplyContextTap() { + guard let payload = currentPayload, + let postNumber = payload.replyTargetPostNumber, + postNumber > 0, + let callbacks = currentCallbacks else { + return + } + callbacks.onOpenReplyTarget(postNumber) + } + + @objc func handleActionQuoteTap() { + guard let payload = currentPayload, let callbacks = currentCallbacks else { return } + noteOverflowInteraction() + FireMotionHaptics.impact(.light) + callbacks.onQuotePost(payload.post) + setOverflowActionsExpanded(false, animated: true) + } + + @objc func handleReplyShortcutTap() { + guard let payload = currentPayload, + let callbacks = currentCallbacks else { + return + } + // Toggle must work even while nested replies are still loading. + FireMotionHaptics.impact(.light) + callbacks.onOpenReplies(payload.post) + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Reactions.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Reactions.swift index af7ab074..c552ceb7 100644 --- a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Reactions.swift +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Reactions.swift @@ -228,4 +228,19 @@ extension FirePostCellNode { callbacks.onSelectReaction(payload.post, reaction.id) } } + + static func reactionSignatureString( + reactions: [TopicReactionState], + currentUserReactionID: String?, + canWrite: Bool + ) -> String { + let reactionTokens = reactions.map { reaction in + [reaction.id, String(reaction.count), String(reaction.canUndo ?? true)].joined(separator: ":") + }.joined(separator: "|") + return [ + reactionTokens, + currentUserReactionID ?? "", + String(canWrite), + ].joined(separator: "\u{1F}") + } } diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Thread.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Thread.swift new file mode 100644 index 00000000..2cdc2733 --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Thread.swift @@ -0,0 +1,14 @@ +import AsyncDisplayKit +import UIKit + +extension FirePostCellNode { + func configureThreadLine(shows: Bool) { + threadLineNode.isHidden = !shows + threadLineNode.style.preferredSize = CGSize(width: 1, height: shows ? 1 : 0) + threadLineNode.style.flexGrow = shows ? 1.0 : 0.0 + } + + func configureDivider(shows: Bool) { + dividerNode.isHidden = !shows + } +} diff --git a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift index 75475396..c3c2ae6e 100644 --- a/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift +++ b/apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift @@ -207,44 +207,6 @@ final class FirePostCellNode: ASCellNode, UIGestureRecognizerDelegate { refreshResolvedColorsFromLiveTraitsIfNeeded() } - /// Re-bake Texture text colors after theme / trait changes (window override or system). - /// Soft rebind only — does not tear down image nodes or reset overflow/swipe state. - func applyColorAppearance(_ appearance: FireAppearanceSnapshot) { - guard let payload = currentPayload else { - FireAppearanceTexture.applySnapshot(appearance, to: self) - setNeedsDisplay() - return - } - guard payload.appearance.token != appearance.token else { - // Already baked for this appearance; still refresh canvas in case highlight state moved. - configureSearchHighlight(payload.isSearchHighlighted) - return - } - let updated = payload.withAppearance(appearance) - currentPayload = updated - // Force text rebind when appearance flips, but keep `contentSegmentSignature` so - // FirePostImageNode instances are not destroyed mid-load (blank image placeholders). - renderedContentID = nil - configureMeta(payload: updated) - configureBodyContent(payload: updated) - configureReplyShortcut(payload: updated) - configureOverflowActions(payload: updated) - configureReactionPicker(payload: updated) - configureReactions(payload: updated) - configureSearchHighlight(updated.isSearchHighlighted) - setNeedsDisplay() - } - - /// Compatibility entry for call sites that still hold traits only. - func applyColorAppearance(_ colorTraits: UITraitCollection) { - applyColorAppearance(FireAppearanceEnvironment.snapshot(traits: colorTraits)) - } - - func refreshResolvedColorsFromLiveTraitsIfNeeded() { - guard isNodeLoaded, currentPayload != nil else { return } - applyColorAppearance(FireAppearanceEnvironment.snapshot(for: view)) - } - func setupNodes() { backgroundColor = FireTheme.uiCanvas // Prefer stable body text display; meta is short and cheap to redraw sync. @@ -405,1136 +367,7 @@ final class FirePostCellNode: ASCellNode, UIGestureRecognizerDelegate { dividerNode.isHidden = true } - /// Texture may call configure/setup from a background node-block queue. - /// UIView/CALayer access must hop to main; node properties stay thread-safe. - func performOnMain(_ work: @escaping () -> Void) { - if Thread.isMainThread { - work() - } else { - DispatchQueue.main.async(execute: work) - } - } - - // MARK: - Configure - - func configure( - payload: FirePostCellRenderPayload, - callbacks: FirePostCellCallbacks, - depth: Int, - showsThreadLine: Bool, - showsDivider: Bool - ) { - currentPayload = payload - currentCallbacks = callbacks - currentDepth = depth - currentShowsThreadLine = showsThreadLine - currentShowsDivider = showsDivider - currentLayoutWidth = payload.layoutWidth - currentResolvedLayout = payload.layout - // UIApplication is main-thread only; node-blocks may configure off-main. - if Thread.isMainThread { - Self.lastKnownContentSizeCategory = UIApplication.shared.preferredContentSizeCategory - cachedDisplayScale = UIScreen.main.scale - } - currentContentSizeCategory = Self.lastKnownContentSizeCategory - - let vd = FirePostCellLayoutCalculator.visualDepth(for: depth) - let avatarSz = vd > 0 ? FirePostCellLayoutCalculator.avatarSizeNested : FirePostCellLayoutCalculator.avatarSizeRoot - let avatarSp = vd > 0 ? FirePostCellLayoutCalculator.avatarSpacingNested : FirePostCellLayoutCalculator.avatarSpacingRoot - currentAvatarSize = avatarSz - currentAvatarSpacing = avatarSp - - avatarContainerNode.cornerRadius = avatarSz / 2 - avatarNode.cornerRadius = avatarSz / 2 - avatarContainerNode.style.preferredSize = CGSize(width: avatarSz, height: avatarSz) - avatarNode.style.preferredSize = CGSize(width: avatarSz, height: avatarSz) - - configureAvatar(payload: payload, avatarSize: avatarSz) - configureThreadLine(shows: showsThreadLine) - configureMeta(payload: payload) - configureBodyContent(payload: payload) - configurePolls(payload: payload) - boostAnimationsEnabled = payload.boostAnimationsEnabled - configureBoosts(payload: payload) - // Reset per-row overflow expansion on reuse / reconfigure. - // UIView transform / label work must stay on main — configure may run in a - // Texture background node-block. - cancelOverflowAutoCollapse() - areOverflowActionsExpanded = false - resetSwipeReplyReveal(animated: false) - - configureReplyShortcut(payload: payload) - configureOverflowActions(payload: payload) - configureReactionPicker(payload: payload) - configureReactions(payload: payload) - configureSearchHighlight(payload.isSearchHighlighted) - configureDivider(shows: showsDivider) - } - - /// Updates only the bands that changed. `relayout` is for a height change - /// inside body, reactions, or the thread shortcut. - func applyBands( - _ bands: Set, - payload: FirePostCellRenderPayload, - callbacks: FirePostCellCallbacks, - showsThreadLine: Bool, - relayout: Bool - ) { - guard !bands.isEmpty else { return } - currentPayload = payload - currentCallbacks = callbacks - currentShowsThreadLine = showsThreadLine - currentShowsDivider = payload.showsDivider - if relayout { - currentLayoutWidth = payload.layoutWidth - currentResolvedLayout = payload.layout - } - if bands.contains(.author) { - configureAvatar(payload: payload, avatarSize: currentAvatarSize) - configureMeta(payload: payload) - } - if bands.contains(.quote) { - configureQuote(payload: payload) - } - if bands.contains(.images) { - applyImageBand(payload: payload) - } - if bands.contains(.text) { - applyTextBand(payload: payload) - configurePolls(payload: payload) - boostAnimationsEnabled = payload.boostAnimationsEnabled - configureBoosts(payload: payload) - } - if bands.contains(.showMore) { - configureBodyContent(payload: payload) - configureReplyShortcut(payload: payload) - } - if bands.contains(.actions) { - applyInPlaceActionMutatingState(payload) - configureSearchHighlight(payload.isSearchHighlighted) - } - if bands.contains(.reactions) { - configureReactionPicker(payload: payload) - if relayout { - configureReactions(payload: payload) - } else { - applyInPlaceReactions(payload) - } - } - if bands.contains(.thread) { - configureThreadLine(shows: currentShowsThreadLine) - configureDivider(shows: payload.showsDivider) - } - if relayout { - setNeedsLayout() - } - } - - /// Count / selection / mutating updates. Does not rebuild the row or reset overflow. - func applyInPlaceInteraction( - payload: FirePostCellRenderPayload, - callbacks: FirePostCellCallbacks - ) { - currentPayload = payload - currentCallbacks = callbacks - applyInPlaceActionMutatingState(payload) - applyInPlaceReactions(payload) - updatePollInteractionState(payload: payload) - configureSearchHighlight(payload.isSearchHighlighted) - } - - /// Height-changing local updates (body expand, picker, first reaction chip). - /// Relayouts this row only and leaves overflow expansion alone. - func applyVisibleRowRelayout( - payload: FirePostCellRenderPayload, - callbacks: FirePostCellCallbacks - ) { - currentPayload = payload - currentCallbacks = callbacks - currentLayoutWidth = payload.layoutWidth - currentResolvedLayout = payload.layout - configureBodyContent(payload: payload) - configureReactionPicker(payload: payload) - applyInPlaceActionMutatingState(payload) - applyInPlaceReactions(payload) - configureReplyShortcut(payload: payload) - configureSearchHighlight(payload.isSearchHighlighted) - } - - func configureSearchHighlight(_ isHighlighted: Bool) { - let appearance = currentPayload?.appearance - ?? FireAppearanceEnvironment.snapshot(traits: .current) - let accent = FireTextureAttributedText.resolvedColor( - Self.accentTextColor, - with: appearance.traits - ) - backgroundColor = isHighlighted - ? accent.withAlphaComponent(0.10) - : appearance.canvas - borderWidth = isHighlighted ? 1 : 0 - borderColor = isHighlighted - ? accent.withAlphaComponent(0.70).cgColor - : UIColor.clear.cgColor - cornerRadius = isHighlighted ? 8 : 0 - clipsToBounds = isHighlighted - } - - func configureAvatar(payload: FirePostCellRenderPayload, avatarSize: CGFloat) { - let username = payload.post.username.isEmpty ? "?" : payload.post.username - let avatarURL = fireAvatarURL( - avatarTemplate: payload.post.avatarTemplate, - size: avatarSize, - scale: cachedDisplayScale, - baseURLString: payload.baseURLString - ) - let nextAvatarSignature = [ - username, - payload.post.avatarTemplate ?? "", - payload.baseURLString, - avatarURL?.absoluteString ?? "monogram", - String(Int(avatarSize.rounded())), - ].joined(separator: "\u{1F}") - guard avatarSignature != nextAvatarSignature else { - return - } - avatarSignature = nextAvatarSignature - - let monogram = monogramForUsername(username: username) - avatarMonogramNode.attributedText = NSAttributedString( - string: monogram, - attributes: [ - .font: UIFont.systemFont(ofSize: avatarSize * 0.36, weight: .bold), - .foregroundColor: UIColor.white, - ] - ) - avatarMonogramNode.isHidden = false - avatarNode.isHidden = true - avatarNode.alpha = 0 - - if let avatarURL { - avatarNode.isHidden = false - avatarNode.alpha = 0 - loadAvatar(url: avatarURL) - } else { - cancelAvatarLoad() - avatarNode.isHidden = true - } - } - - func configureQuote(payload: FirePostCellRenderPayload) { - if let replyContext = payload.replyContext, - let targetPN = payload.replyTargetPostNumber, targetPN > 0 { - replyContextNode.isHidden = false - let replyContextFont = UIFont.preferredFont(forTextStyle: .caption1) - replyContextNode.setAttributedTitle(NSAttributedString( - string: replyContext, - attributes: [.font: replyContextFont, .foregroundColor: Self.accentTextColor] - ), for: .normal) - } else { - replyContextNode.isHidden = true - replyContextNode.setAttributedTitle(nil, for: .normal) - } - } - - func configureThreadLine(shows: Bool) { - threadLineNode.isHidden = !shows - threadLineNode.style.preferredSize = CGSize(width: 1, height: shows ? 1 : 0) - threadLineNode.style.flexGrow = shows ? 1.0 : 0.0 - } - - func configureMeta(payload: FirePostCellRenderPayload) { - let subheadlineFont = UIFontMetrics(forTextStyle: .subheadline).scaledFont( - for: UIFont.systemFont( - ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, - weight: .semibold - ) - ) - let captionFont = UIFont.preferredFont(forTextStyle: .caption2) - let monoCaptionFont = UIFontMetrics(forTextStyle: .caption2).scaledFont( - for: UIFont.monospacedDigitSystemFont( - ofSize: captionFont.pointSize, - weight: .regular - ) - ) - - let appearance = payload.appearance - let primaryInk = appearance.ink - let secondaryInk = appearance.subtleInk - let tertiaryInk = appearance.tertiaryInk - - usernameNode.attributedText = NSAttributedString( - string: FirePostAuthorMetadataDisplay.displayName(for: payload.post), - attributes: [.font: subheadlineFont, .foregroundColor: primaryInk] - ) - let canOpenProfile = !payload.post.username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - avatarContainerNode.accessibilityLabel = canOpenProfile - ? "查看 \(FirePostAuthorMetadataDisplay.displayName(for: payload.post)) 的资料" - : "查看用户资料" - - let primaryBadges = FirePostAuthorMetadataDisplay.primaryBadgeParts(for: payload.post) - if primaryBadges.isEmpty { - authorBadgeNode.isHidden = true - authorBadgeNode.attributedText = nil - } else { - authorBadgeNode.isHidden = false - authorBadgeNode.attributedText = Self.badgeAttributedText(parts: primaryBadges) - } - - let secondaryParts = FirePostAuthorMetadataDisplay.secondaryLineParts(for: payload.post) - if secondaryParts.isEmpty { - authorMetadataNode.isHidden = true - authorMetadataNode.attributedText = nil - } else { - authorMetadataNode.isHidden = false - authorMetadataNode.attributedText = NSAttributedString( - string: secondaryParts.joined(separator: " · "), - attributes: [ - .font: captionFont, - .foregroundColor: secondaryInk, - ] - ) - } - - configureQuote(payload: payload) - - timestampNode.attributedText = NSAttributedString( - string: FireTopicPresentation.compactTimestamp(payload.post.createdAt) ?? "", - attributes: [.font: captionFont, .foregroundColor: tertiaryInk] - ) - - if payload.post.acceptedAnswer { - acceptedAnswerNode.isHidden = false - acceptedAnswerNode.attributedText = acceptedAnswerAttributedText() - } else { - acceptedAnswerNode.isHidden = true - } - - postNumberNode.attributedText = NSAttributedString( - string: "#\(payload.post.postNumber)楼", - attributes: [.font: monoCaptionFont, .foregroundColor: tertiaryInk] - ) - - // Header `...` is retired — overflow lives in the bottom action strip. - menuNode.isHidden = true - menuNode.isEnabled = false - } - - - func configurePolls(payload: FirePostCellRenderPayload) { - let pollModels = FirePostPollRenderModel.models(from: payload.post.polls) - guard !pollModels.isEmpty else { - pollContainerNode.isHidden = true - rebuildPollViews([], [], payload: payload) - return - } - - pollContainerNode.isHidden = false - let nextSignature = pollModels.map(\.signature) - let availableWidth = Self.availableContentWidth( - totalWidth: payload.layoutWidth, - depth: currentDepth, - avatarSize: currentAvatarSize, - avatarSpacing: currentAvatarSpacing - ) - if pollSignature != nextSignature || abs(pollWidth - availableWidth) > 0.5 { - rebuildPollViews(payload.post.polls, pollModels, payload: payload, availableWidth: availableWidth) - pollSignature = nextSignature - pollWidth = availableWidth - } else { - updatePollInteractionState(payload: payload) - } - } - - func updatePollInteractionState(payload: FirePostCellRenderPayload) { - let canWrite = payload.canWriteInteractions - let isMutating = payload.isMutating - performOnMain { [weak self] in - guard let self else { return } - for view in self.pollViews { - view.updateInteractionState(canInteract: canWrite, isMutating: isMutating) - } - } - } - - func rebuildPollViews( - _ polls: [PollState], - _ models: [FirePostPollRenderModel], - payload: FirePostCellRenderPayload, - availableWidth: CGFloat? = nil - ) { - // Do not touch UIView hierarchy here — this path can run off-main in Texture. - pollHeights.removeAll(keepingCapacity: true) - let width = availableWidth ?? Self.availableContentWidth( - totalWidth: payload.layoutWidth, - depth: currentDepth, - avatarSize: currentAvatarSize, - avatarSpacing: currentAvatarSpacing - ) - - // Heights are pure layout math and can stay on the Texture worker queue. - var nextHeights: [CGFloat] = [] - nextHeights.reserveCapacity(models.count) - for model in models { - nextHeights.append(FirePostPollView.preferredHeight( - for: model, - availableWidth: width, - contentSizeCategory: currentContentSizeCategory - )) - } - pollHeights = nextHeights - let totalPollHeight = pollHeights.reduce(0, +) + CGFloat(max(pollHeights.count - 1, 0)) * 10 - // Width must match the laid-out poll views. A 1pt container still draws subviews - // that overflow its bounds, but UIKit hit-testing never reaches those controls. - pollContainerNode.style.preferredSize = CGSize(width: max(width, 1), height: ceil(totalPollHeight)) - pollContainerNode.style.minWidth = ASDimensionMake(max(width, 1)) - pollContainerNode.style.maxWidth = ASDimensionMake(max(width, 1)) - - // UIView construction / hierarchy edits must happen on main. - let pollsSnapshot = polls - let modelsSnapshot = models - let canWrite = payload.canWriteInteractions - let isMutating = payload.isMutating - performOnMain { [weak self] in - guard let self else { return } - for view in self.pollViews { - view.removeFromSuperview() - } - self.pollViews.removeAll(keepingCapacity: true) - - for (index, model) in modelsSnapshot.enumerated() { - guard index < pollsSnapshot.count else { break } - let pollView = FirePostPollView() - let poll = pollsSnapshot[index] - pollView.isUserInteractionEnabled = true - pollView.configure( - model: model, - canInteract: canWrite, - isMutating: isMutating, - onSubmit: { [weak self] selectedOptions in - guard let self, - let p = self.currentPayload, - let callbacks = self.currentCallbacks else { return } - callbacks.onVotePoll(p.post, poll, selectedOptions) - }, - onRemoveVote: { [weak self] in - guard let self, - let p = self.currentPayload, - let callbacks = self.currentCallbacks else { return } - callbacks.onUnvotePoll(p.post, poll) - } - ) - self.pollContainerNode.view.addSubview(pollView) - self.pollViews.append(pollView) - } - self.setNeedsLayout() - } - } - - func configureBoosts(payload: FirePostCellRenderPayload) { - guard !payload.post.boosts.isEmpty else { - boostContainerNode.isHidden = true - boostBarrageNode.isHidden = true - configureBoostBarrage(boosts: [], batchSignature: "") - configureFixedBoostManualScroller(boosts: []) - boostSignature = [] - return - } - - let usesBodyBarrage = FirePostBoostDisplay.usesBodyBarrage( - depth: currentDepth, - textExpansionState: payload.textExpansionState, - hasBodyTextTarget: payload.renderContent.hasBoostBarrageTextTarget - ) - let bodyBarrageBoosts = usesBodyBarrage - ? FirePostBoostDisplay.bodyBarrageBoosts(for: payload.post.boosts) - : [] - boostBarrageNode.isHidden = !usesBodyBarrage || bodyBarrageBoosts.isEmpty - configureBoostBarrage( - boosts: bodyBarrageBoosts, - batchSignature: usesBodyBarrage && !bodyBarrageBoosts.isEmpty - ? FirePostBoostDisplay.bodyBarrageBatchSignature( - postID: payload.post.id, - boosts: payload.post.boosts - ) - : "" - ) - boostContainerNode.isHidden = usesBodyBarrage - if usesBodyBarrage { - configureFixedBoostManualScroller(boosts: []) - boostSignature = [] - return - } - - let nextSignature = payload.post.boosts.map { boost in - [ - String(boost.id), - boost.user.username, - boost.user.name ?? "", - boost.displayText, - FirePostBoostDisplay.contentSignature(for: boost), - ].joined(separator: "\u{1E}") - } - if boostSignature != nextSignature { - boostSignature = nextSignature - } - configureFixedBoostManualScroller(boosts: payload.post.boosts) - boostContainerNode.setNeedsLayout() - } - - func configureFixedBoostManualScroller(boosts: [TopicPostBoostState]) { - boostManualBoosts = boosts - boostManualScrollerNode.isHidden = boosts.isEmpty - let baseURLString = currentPayload?.baseURLString ?? "https://linux.do" - performOnMain { [weak self] in - guard let self, - self.boostManualScrollerNode.isNodeLoaded, - let view = self.boostManualScrollerNode.view as? FirePostBoostManualScrollerView else { - return - } - view.configure(boosts: boosts, baseURLString: baseURLString) - } - } - - func fixedBoostManualScrollerHeight(availableWidth: CGFloat) -> CGFloat { - guard let payload = currentPayload else { - return FirePostCellLayoutCalculator.fixedBoostManualHeight(forUsedRowCount: 1) - } - let boostLines = FirePostBoostDisplay.fixedDisplayLines( - for: boostManualBoosts, - depth: currentDepth, - textExpansionState: payload.textExpansionState, - hasBodyTextTarget: payload.renderContent.hasBoostBarrageTextTarget - ) - return FirePostCellLayoutCalculator.fixedBoostManualHeight( - boostLines: boostLines, - containerWidth: availableWidth, - contentSizeCategory: currentContentSizeCategory - ) - } - - func configureBoostBarrage(boosts: [TopicPostBoostState], batchSignature: String) { - boostBarrageBoosts = boosts - boostBarrageLines = boosts.map(FirePostBoostDisplay.displayLine(for:)) - boostBarrageBatchSignature = batchSignature - let animationsEnabled = boostAnimationsEnabled - let baseURLString = currentPayload?.baseURLString ?? "https://linux.do" - performOnMain { [weak self] in - guard let self, - self.boostBarrageNode.isNodeLoaded, - let view = self.boostBarrageNode.view as? FirePostBoostBarrageView else { - return - } - view.configure( - boosts: boosts, - batchSignature: batchSignature, - animationsEnabled: animationsEnabled, - baseURLString: baseURLString - ) - } - } - - - func setBoostAnimationsEnabled(_ enabled: Bool) { - guard boostAnimationsEnabled != enabled else { return } - boostAnimationsEnabled = enabled - performOnMain { [weak self] in - guard let self, - self.boostBarrageNode.isNodeLoaded, - let view = self.boostBarrageNode.view as? FirePostBoostBarrageView else { - return - } - view.setAnimationsEnabled(enabled) - } - } - - - func configureDivider(shows: Bool) { - dividerNode.isHidden = !shows - } - - // MARK: - Layout - - override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { - let vd = FirePostCellLayoutCalculator.visualDepth(for: currentDepth) - let indent = CGFloat(min(vd, FirePostCellLayoutCalculator.maxVisualDepth)) * FirePostCellLayoutCalculator.indentWidthPerDepth - let avatarSz = currentAvatarSize - let avatarSp = currentAvatarSpacing - let outerPadding = FirePostCellLayoutCalculator.outerHorizontalPadding - let totalWidth = constrainedSize.max.width.isFinite ? constrainedSize.max.width : currentLayoutWidth - let rowAvailableWidth = max(totalWidth - outerPadding * 2 - indent, 1) - let bodyAvailableWidth = Self.availableContentWidth( - totalWidth: totalWidth, - depth: currentDepth, - avatarSize: currentAvatarSize, - avatarSpacing: currentAvatarSpacing - ) - let headerAvailableWidth = max(rowAvailableWidth - avatarSz - avatarSp, 1) - let shouldSuppressAttachments: Bool - if let currentResolvedLayout { - shouldSuppressAttachments = currentResolvedLayout.textExpansionFrame != nil - } else { - let hasImageSegments = currentPayload?.renderContent.segments.contains(where: \.isImage) ?? false - shouldSuppressAttachments = (hasImageSegments || !pollContainerNode.isHidden) - && Self.shouldSuppressAttachmentsForCollapsedText( - plainText: currentPayload?.renderContent.plainText ?? "", - hasAttributedText: currentPayload?.renderContent.attributedText != nil, - textExpansionState: currentPayload?.textExpansionState ?? .disabled, - totalWidth: totalWidth, - depth: currentDepth, - avatarSize: currentAvatarSize, - avatarSpacing: currentAvatarSpacing, - contentSizeCategory: currentContentSizeCategory - ) - } - - // Avatar column - var avatarColumnChildren: [ASLayoutElement] = [avatarContainerNode] - if !threadLineNode.isHidden { - avatarColumnChildren.append(threadLineNode) - } - let avatarColumn = ASStackLayoutSpec( - direction: .vertical, - spacing: 0, - justifyContent: .start, - alignItems: .center, - children: avatarColumnChildren - ) - avatarColumn.style.minWidth = ASDimensionMake(avatarSz) - avatarColumn.style.maxWidth = ASDimensionMake(avatarSz) - avatarColumn.style.flexShrink = 0.0 - - // Meta row: display name + "回复 @user" share the first line; @handle/tags stay below. - var authorChildren: [ASLayoutElement] = [usernameNode] - if !replyContextNode.isHidden { - replyContextNode.style.flexShrink = 1.0 - authorChildren.append(replyContextNode) - } - if !authorBadgeNode.isHidden { - authorChildren.append(authorBadgeNode) - } - if !acceptedAnswerNode.isHidden { - authorChildren.append(acceptedAnswerNode) - } - if !menuNode.isHidden { - menuNode.style.preferredSize = CGSize(width: 20, height: 20) - authorChildren.append(menuNode) - } - let authorRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: 5, - justifyContent: .start, - alignItems: .center, - children: authorChildren - ) - authorRow.style.flexShrink = 1.0 - authorRow.style.flexGrow = 0.0 - - let firstLineSpacer = ASLayoutSpec() - firstLineSpacer.style.flexGrow = 1.0 - - let metaChildren: [ASLayoutElement] = [authorRow, firstLineSpacer, timestampNode] - let metaRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: 6, - justifyContent: .start, - alignItems: .center, - children: metaChildren - ) - metaRow.style.flexShrink = 1.0 - - // Header stays to the right of the avatar; body content uses the full row width below it. - var headerChildren: [ASLayoutElement] = [metaRow] - var didAttachBoostBarrage = false - var secondaryChildren: [ASLayoutElement] = [] - if !authorMetadataNode.isHidden { - secondaryChildren.append(authorMetadataNode) - } - if !secondaryChildren.isEmpty { - let secondarySpacer = ASLayoutSpec() - secondarySpacer.style.flexGrow = 1.0 - secondaryChildren.append(secondarySpacer) - secondaryChildren.append(postNumberNode) - let secondaryRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: 6, - justifyContent: .start, - alignItems: .center, - children: secondaryChildren - ) - secondaryRow.style.flexShrink = 1.0 - headerChildren.append(secondaryRow) - } else { - let secondarySpacer = ASLayoutSpec() - secondarySpacer.style.flexGrow = 1.0 - let postNumberRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: 0, - justifyContent: .start, - alignItems: .center, - children: [secondarySpacer, postNumberNode] - ) - headerChildren.append(postNumberRow) - } - - let headerContentStack = ASStackLayoutSpec( - direction: .vertical, - spacing: FirePostCellLayoutCalculator.headerStackSpacing, - justifyContent: .start, - alignItems: .stretch, - children: headerChildren - ) - headerContentStack.style.flexGrow = 1.0 - headerContentStack.style.flexShrink = 1.0 - headerContentStack.style.minWidth = ASDimensionMake(headerAvailableWidth) - headerContentStack.style.maxWidth = ASDimensionMake(headerAvailableWidth) - - var bodyChildren: [ASLayoutElement] = [] - - if !bodyTextNode.isHidden { - bodyChildren.append(bodyElement(bodyTextNode, didAttachBoostBarrage: &didAttachBoostBarrage)) - } - if !bodySelectableTextNode.isHidden { - bodyChildren.append(bodyElement(bodySelectableTextNode, didAttachBoostBarrage: &didAttachBoostBarrage)) - } - - if !shouldSuppressAttachments { - for segmentNode in contentSegmentNodes { - bodyChildren.append(bodyElement(segmentNode, didAttachBoostBarrage: &didAttachBoostBarrage)) - } - - // Poll container - if !pollContainerNode.isHidden { - bodyChildren.append(pollContainerNode) - } - } - - // Footer chrome: - // [bubble?] [reply react boost ...] - // [quick reaction strip when expanded] - // [existing reaction chips full width] - var actionRowChildren: [ASLayoutElement] = [] - if !replyShortcutNode.isHidden { - replyShortcutNode.style.flexGrow = 0 - replyShortcutNode.style.flexShrink = 0 - actionRowChildren.append(replyShortcutNode) - } - - let primaryCluster = [ - actionReplyNode, - actionReactNode, - actionBoostNode, - overflowNode, - ].filter { !$0.isHidden } - for node in primaryCluster { - node.style.flexGrow = 0 - node.style.flexShrink = 0 - actionRowChildren.append(node) - } - - let overflowCluster = [ - actionQuoteNode, - actionBookmarkNode, - actionFlagNode, - actionEditNode, - ].filter { !$0.isHidden } - actionRowChildren.append(contentsOf: overflowCluster) - - var footerChildren: [ASLayoutElement] = [] - if !actionRowChildren.isEmpty { - let actionRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: FirePostCellLayoutCalculator.actionIconSpacing, - justifyContent: .start, - alignItems: .center, - children: actionRowChildren - ) - actionRow.style.flexShrink = 1.0 - actionRow.style.minHeight = ASDimensionMake(FirePostCellLayoutCalculator.actionRowHeight) - footerChildren.append(actionRow) - } - - if !reactionPickerScrollNode.isHidden, !reactionPickerButtons.isEmpty { - reactionPickerScrollNode.style.flexGrow = 1 - reactionPickerScrollNode.style.flexShrink = 1 - reactionPickerScrollNode.style.minHeight = ASDimensionMake( - FirePostCellLayoutCalculator.reactionPickerStripHeight - ) - reactionPickerScrollNode.style.maxHeight = ASDimensionMake( - FirePostCellLayoutCalculator.reactionPickerStripHeight - ) - footerChildren.append(reactionPickerScrollNode) - } - - if !reactionContainerNode.isHidden, !reactionButtons.isEmpty { - let reactionRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: FirePostCellLayoutCalculator.reactionChipHorizontalSpacing, - justifyContent: .start, - alignItems: .center, - children: reactionButtons - ) - reactionRow.style.flexShrink = 1.0 - reactionRow.style.minHeight = ASDimensionMake( - FirePostCellLayoutCalculator.reactionChipHeight - ) - footerChildren.append(reactionRow) - } - - let actionElement: ASLayoutElement? - if footerChildren.isEmpty { - actionElement = nil - } else if footerChildren.count == 1 { - actionElement = footerChildren[0] - } else { - let stack = ASStackLayoutSpec( - direction: .vertical, - spacing: FirePostCellLayoutCalculator.reactionTopSpacing, - justifyContent: .start, - alignItems: .stretch, - children: footerChildren - ) - actionElement = stack - } - - let boostElement: ASLayoutElement? = !shouldSuppressAttachments && !boostContainerNode.isHidden - ? boostContainerNode - : nil - if let boostElement, let actionElement { - let footerStack = ASStackLayoutSpec( - direction: .vertical, - spacing: 0, - justifyContent: .start, - alignItems: .stretch, - children: [boostElement, actionElement] - ) - footerStack.style.flexShrink = 1.0 - bodyChildren.append(footerStack) - } else if let boostElement { - bodyChildren.append(boostElement) - } else if let actionElement { - bodyChildren.append(actionElement) - } - - // Divider - if !dividerNode.isHidden { - dividerNode.style.preferredSize = CGSize(width: max(bodyAvailableWidth, 1), height: 0.5) - bodyChildren.append(dividerNode) - } - - let rootStack: ASLayoutSpec - if FirePostCellLayoutCalculator.usesFullWidthBody(for: currentDepth) { - let headerRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: avatarSp, - justifyContent: .start, - alignItems: .start, - children: [avatarColumn, headerContentStack] - ) - headerRow.style.flexShrink = 1.0 - - let contentChildren: [ASLayoutElement] = [headerRow] + bodyChildren - let contentStack = ASStackLayoutSpec( - direction: .vertical, - spacing: FirePostCellLayoutCalculator.headerToBodySpacing, - justifyContent: .start, - alignItems: .stretch, - children: contentChildren - ) - contentStack.style.flexGrow = 1.0 - contentStack.style.flexShrink = 1.0 - contentStack.style.minWidth = ASDimensionMake(max(rowAvailableWidth, 1)) - contentStack.style.maxWidth = ASDimensionMake(max(rowAvailableWidth, 1)) - rootStack = contentStack - } else { - let contentColumnChildren: [ASLayoutElement] = [headerContentStack] + bodyChildren - let contentColumn = ASStackLayoutSpec( - direction: .vertical, - spacing: FirePostCellLayoutCalculator.headerToBodySpacing, - justifyContent: .start, - alignItems: .stretch, - children: contentColumnChildren - ) - contentColumn.style.flexGrow = 1.0 - contentColumn.style.flexShrink = 1.0 - contentColumn.style.minWidth = ASDimensionMake(max(bodyAvailableWidth, 1)) - contentColumn.style.maxWidth = ASDimensionMake(max(bodyAvailableWidth, 1)) - - let row = ASStackLayoutSpec( - direction: .horizontal, - spacing: avatarSp, - justifyContent: .start, - alignItems: .stretch, - children: [avatarColumn, contentColumn] - ) - row.style.flexShrink = 1.0 - row.style.minWidth = ASDimensionMake(max(rowAvailableWidth, 1)) - row.style.maxWidth = ASDimensionMake(max(rowAvailableWidth, 1)) - rootStack = row - } - - return ASInsetLayoutSpec( - insets: UIEdgeInsets( - top: 8, - left: outerPadding + indent, - bottom: 8, - right: outerPadding - ), - child: rootStack - ) - } - - override func layout() { - super.layout() - - // Size poll views inside the container. Prefer the container's laid-out width so - // hit targets match the Texture frame (do not overflow a narrow parent bounds). - let fallbackWidth = Self.availableContentWidth( - totalWidth: calculatedSize.width, - depth: currentDepth, - avatarSize: currentAvatarSize, - avatarSpacing: currentAvatarSpacing - ) - let containerWidth = pollContainerNode.bounds.width - let availableWidth = containerWidth > 1 ? containerWidth : fallbackWidth - - var pollY: CGFloat = 0 - for (index, pollView) in pollViews.enumerated() { - let height = index < pollHeights.count ? pollHeights[index] : 0 - pollView.frame = CGRect( - x: 0, - y: pollY, - width: availableWidth, - height: height - ) - pollY += height + 10 - } - } - - // MARK: - Actions - - - - - @objc func handleImageTap(_ sender: FirePostImageNode) { - currentCallbacks?.onOpenImage(sender.image) - } - - @objc func handleProfileTapGesture(_ gesture: UITapGestureRecognizer) { - _ = handleProfileTap(at: gesture.location(in: view)) - } - - /// Shared by the cell tap recognizer and tests. Uses live node frames when - /// loaded, otherwise the precomputed `avatarFrame` / `metaFrame`. - @discardableResult - func handleProfileTap(at point: CGPoint) -> Bool { - guard profileHitRects().contains(where: { $0.contains(point) }) else { - return false - } - guard let username = currentPayload?.post.username.trimmingCharacters(in: .whitespacesAndNewlines), - !username.isEmpty else { - return false - } - FireMotionHaptics.selection() - currentCallbacks?.onOpenProfile(username) - return true - } - - func profileHitRects() -> [CGRect] { - var rects: [CGRect] = [] - if isNodeLoaded { - let avatar = avatarContainerNode.view.convert(avatarContainerNode.view.bounds, to: view) - if !avatar.isNull, avatar.width > 1, avatar.height > 1 { - rects.append(avatar.insetBy(dx: -8, dy: -8)) - } - if !usernameNode.isHidden { - let name = usernameNode.view.convert(usernameNode.view.bounds, to: view) - if !name.isNull, name.width > 1, name.height > 1 { - rects.append(name.insetBy(dx: -4, dy: -6)) - } - } - } - if let layout = currentResolvedLayout { - rects.append(layout.avatarFrame.insetBy(dx: -8, dy: -8)) - let meta = layout.metaFrame - if !meta.isNull, !meta.isEmpty { - rects.append( - CGRect(x: meta.minX, y: meta.minY, width: min(meta.width, 168), height: meta.height) - .insetBy(dx: -4, dy: -6) - ) - } - } - if rects.isEmpty { - let indent = FirePostCellLayoutCalculator.indentWidth(for: currentDepth) - rects.append( - CGRect( - x: FirePostCellLayoutCalculator.outerHorizontalPadding + indent, - y: 0, - width: currentAvatarSize, - height: currentAvatarSize - ).insetBy(dx: -8, dy: -8) - ) - } - return rects - } - - - - - // MARK: - Helpers - - func acceptedAnswerAttributedText() -> NSAttributedString { - let font = UIFontMetrics(forTextStyle: .caption2).scaledFont( - for: UIFont.systemFont( - ofSize: UIFont.preferredFont(forTextStyle: .caption2).pointSize, - weight: .medium - ) - ) - let result = NSMutableAttributedString() - if let image = UIImage( - systemName: "checkmark.circle.fill", - withConfiguration: UIImage.SymbolConfiguration(font: font) - )?.withTintColor(.systemGreen, renderingMode: .alwaysOriginal) { - result.append(NSAttributedString(attachment: NSTextAttachment(image: image))) - result.append(NSAttributedString(string: " ")) - } - result.append(NSAttributedString( - string: "已采纳", - attributes: [.font: font, .foregroundColor: UIColor.systemGreen] - )) - return result - } - - static func badgeAttributedText(parts: [String]) -> NSAttributedString { - let captionFont = UIFont.preferredFont(forTextStyle: .caption2) - let result = NSMutableAttributedString() - let colors: [UIColor] = [ - UIColor.systemOrange, - UIColor.systemTeal, - UIColor.systemIndigo, - UIColor.systemPink, - ] - for (index, part) in parts.enumerated() { - if index > 0 { - result.append(NSAttributedString(string: " ")) - } - let color = colors[index % colors.count] - result.append(NSAttributedString( - string: part, - attributes: [ - .font: UIFontMetrics(forTextStyle: .caption2).scaledFont( - for: UIFont.systemFont(ofSize: captionFont.pointSize, weight: .semibold) - ), - .foregroundColor: color, - .backgroundColor: color.withAlphaComponent(0.13), - ] - )) - } - return result - } - - static func reactionSignatureString( - reactions: [TopicReactionState], - currentUserReactionID: String?, - canWrite: Bool - ) -> String { - let reactionTokens = reactions.map { reaction in - [reaction.id, String(reaction.count), String(reaction.canUndo ?? true)].joined(separator: ":") - }.joined(separator: "|") - return [ - reactionTokens, - currentUserReactionID ?? "", - String(canWrite), - ].joined(separator: "\u{1F}") - } - - - - - func showLoadedAvatar() { - avatarNode.alpha = 1 - } - - func showAvatarFallback() { - avatarNode.alpha = 0 - } - - func cancelAvatarLoad() { - avatarLoadTask?.cancel() - avatarLoadTask = nil - avatarLoadGeneration &+= 1 - avatarNode.image = nil - showAvatarFallback() - } - - func loadAvatar(url: URL) { - avatarLoadTask?.cancel() - avatarLoadGeneration &+= 1 - let generation = avatarLoadGeneration - let request = FireRemoteImageRequest(url: url) - - if let cachedImage = FireRemoteImagePipeline.shared.cachedImage(for: request) { - avatarNode.image = cachedImage - showLoadedAvatar() - return - } - - avatarNode.image = nil - showAvatarFallback() - avatarLoadTask = Task { [weak self] in - do { - let image = try await FireRemoteImagePipeline.shared.loadImage(for: request) - guard !Task.isCancelled else { return } - await MainActor.run { - self?.applyLoadedAvatar(image, generation: generation) - } - } catch is CancellationError { - return - } catch { - guard !Task.isCancelled else { return } - await MainActor.run { - self?.applyFailedAvatarLoad(generation: generation) - } - } - } - } - - func applyLoadedAvatar(_ image: UIImage, generation: UInt64) { - guard generation == avatarLoadGeneration else { return } - avatarNode.image = image - showLoadedAvatar() - } - - func applyFailedAvatarLoad(generation: UInt64) { - guard generation == avatarLoadGeneration else { return } - avatarNode.image = nil - showAvatarFallback() - } - deinit { avatarLoadTask?.cancel() } - - func nearestViewController() -> UIViewController? { - var responder: UIResponder? = view - while let current = responder { - if let viewController = current as? UIViewController { - return viewController - } - responder = current.next - } - return nil - } -} - -extension UIView { - func isDescendant(ofType type: T.Type) -> Bool { - var current: UIView? = self - while let view = current { - if view is T { - return true - } - current = view.superview - } - return false - } } diff --git a/apps/ios-app/App/ListKit/TopicDetail/UIView+FireHierarchy.swift b/apps/ios-app/App/ListKit/TopicDetail/UIView+FireHierarchy.swift new file mode 100644 index 00000000..24ec2803 --- /dev/null +++ b/apps/ios-app/App/ListKit/TopicDetail/UIView+FireHierarchy.swift @@ -0,0 +1,14 @@ +import UIKit + +extension UIView { + func isDescendant(ofType type: T.Type) -> Bool { + var current: UIView? = self + while let view = current { + if view is T { + return true + } + current = view.superview + } + return false + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Actions.swift b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Actions.swift new file mode 100644 index 00000000..1c2ef4a6 --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Actions.swift @@ -0,0 +1,85 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationHistoryViewController { + func updateToolbar() { + guard notificationStore.unreadCount > 0 else { + navigationItem.rightBarButtonItem = nil + return + } + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "全部已读", + style: .plain, + target: self, + action: #selector(markAllRead) + ) + } + + @objc func markAllRead() { + notificationStore.markAllRead() + } + + func contextMenuConfiguration( + for item: FireNotificationHistoryCollectionItem + ) -> UIContextMenuConfiguration? { + guard case let .notification(id) = item, + let notification = notification(id: id) + else { + return nil + } + let shareURL = notification.fireShareURL(baseURL: baseURLString) + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in + UIMenu(children: self?.notificationMenuActions(item: notification, shareURL: shareURL) ?? []) + } + } + + func notificationMenuActions( + item: NotificationItemState, + shareURL: URL? + ) -> [UIAction] { + var actions: [UIAction] = [ + UIAction(title: "跳转到通知", image: UIImage(systemName: "arrow.up.right")) { [weak self] _ in + self?.open(item) + }, + ] + + if !item.read { + actions.append( + UIAction(title: "标记为已读", image: UIImage(systemName: "envelope.open")) { [weak self] _ in + self?.notificationStore.markRead(id: item.id) + } + ) + } + + actions.append( + UIAction(title: "复制通知内容", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in + UIPasteboard.general.string = item.displayDescription + self?.showToast("已复制通知内容", style: .success) + } + ) + + if let shareURL { + actions.append( + UIAction(title: "分享链接", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in + self?.presentShareSheet(url: shareURL) + } + ) + actions.append( + UIAction(title: "复制链接", image: UIImage(systemName: "link")) { [weak self] _ in + UIPasteboard.general.string = shareURL.absoluteString + self?.showToast("已复制链接", style: .success) + } + ) + } + + return actions + } + + func showToast(_ message: String, style: FireTopicListToastView.Style) { + toastDismissTask?.cancel() + toastView?.removeFromSuperview() + toastView = nil + FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Feed.swift b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Feed.swift new file mode 100644 index 00000000..ac800326 --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Feed.swift @@ -0,0 +1,145 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationHistoryViewController { + var baseURLString: String { + let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? "https://linux.do" : trimmed + } + + var contentVersion: ContentVersion { + ContentVersion( + unreadCount: notificationStore.unreadCount, + notifications: notificationStore.fullNotifications.map(FireNotificationItemContentToken.init), + nextOffset: notificationStore.fullNextOffset, + isLoading: notificationStore.isLoadingFullPage, + hasLoadedOnce: notificationStore.hasLoadedFullOnce, + hasMore: notificationStore.hasMoreFull, + shouldShowRetry: notificationStore.shouldShowFullPaginationRetry, + errorMessage: notificationStore.fullErrorMessage, + isOffline: notificationStore.isFullOffline + ) + } + + func render() { + let sections = makeSections() + var tokens: [FireNotificationHistoryCollectionItem: AnyHashable] = [:] + tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) + for section in sections { + for item in section.items { + tokens[item] = itemContentToken(for: item) + } + } + listController.setSections( + sections, + contentVersion: contentVersion, + itemContentTokens: tokens, + animatingDifferences: true + ) + } + + func makeSections() + -> [FireListSectionModel] + { + var items: [FireNotificationHistoryCollectionItem] = [] + + if let errorMessage = notificationStore.blockingFullErrorMessage { + items.append(.blockingError(errorMessage)) + return [.init(id: .content, items: items)] + } + + if !notificationStore.hasLoadedFullOnce, + notificationStore.fullNotifications.isEmpty { + items.append(.loading) + return [.init(id: .content, items: items)] + } + + if notificationStore.isFullOffline { + items.append(.offlineBanner) + } + + if let errorMessage = notificationStore.fullNonBlockingErrorMessage { + items.append(.inlineErrorBanner(errorMessage)) + } + + if notificationStore.fullNotifications.isEmpty { + items.append(.empty) + } else { + items.append(contentsOf: notificationStore.fullNotifications.map { .notification($0.id) }) + + if notificationStore.shouldShowFullPaginationRetry { + items.append(.retryFooter) + } else if notificationStore.hasMoreFull { + items.append(.loadingMore) + } + } + + return [.init(id: .content, items: items)] + } + + func cell( + collectionView: UICollectionView, + indexPath: IndexPath, + item: FireNotificationHistoryCollectionItem + ) -> UICollectionViewCell { + switch item { + case .blockingError, .loading, .empty, .loadingMore: + return collectionView.dequeueConfiguredReusableCell( + using: stateCellRegistration, + for: indexPath, + item: item + ) + case .offlineBanner: + return collectionView.dequeueConfiguredReusableCell( + using: offlineCellRegistration, + for: indexPath, + item: item + ) + case .inlineErrorBanner: + return collectionView.dequeueConfiguredReusableCell( + using: bannerCellRegistration, + for: indexPath, + item: item + ) + case .notification: + return collectionView.dequeueConfiguredReusableCell( + using: notificationCellRegistration, + for: indexPath, + item: item + ) + case .retryFooter: + return collectionView.dequeueConfiguredReusableCell( + using: retryCellRegistration, + for: indexPath, + item: item + ) + } + } + + func notification(id: UInt64) -> NotificationItemState? { + notificationStore.fullNotifications.first { $0.id == id } + } + + func itemContentToken(for item: FireNotificationHistoryCollectionItem) -> AnyHashable { + switch item { + case let .blockingError(message), let .inlineErrorBanner(message): + return AnyHashable(message) + case .loading: + return AnyHashable(notificationStore.isLoadingFullPage) + case .empty: + return AnyHashable(notificationStore.hasLoadedFullOnce) + case .offlineBanner: + return AnyHashable(notificationStore.isFullOffline) + case let .notification(id): + guard let notification = notification(id: id) else { + return AnyHashable("missing|\(id)") + } + return AnyHashable(FireNotificationItemContentToken(notification)) + case .retryFooter: + return AnyHashable(notificationStore.shouldShowFullPaginationRetry) + case .loadingMore: + return AnyHashable(notificationStore.fullNextOffset) + } + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Pagination.swift b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Pagination.swift new file mode 100644 index 00000000..530a4472 --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Pagination.swift @@ -0,0 +1,21 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationHistoryViewController { + func loadMoreIfNeeded(from items: [FireNotificationHistoryCollectionItem]) { + guard notificationStore.hasMoreFull, + !notificationStore.isLoadingFullPage, + !notificationStore.shouldShowFullPaginationRetry else { return } + let lastNotificationID = notificationStore.fullNotifications.last?.id + guard items.contains(.loadingMore) + || lastNotificationID.map({ items.contains(.notification($0)) }) == true + else { + return + } + loadTask = Task { [weak self] in + guard let self else { return } + await self.notificationStore.loadFullPage(offset: self.notificationStore.fullNextOffset) + } + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Routing.swift b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Routing.swift new file mode 100644 index 00000000..e921aa8b --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Routing.swift @@ -0,0 +1,66 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationHistoryViewController { + func canSelect(_ item: FireNotificationHistoryCollectionItem) -> Bool { + switch item { + case .notification, .retryFooter: + return true + case .blockingError, .loading, .empty, .offlineBanner, .inlineErrorBanner, .loadingMore: + return false + } + } + + func handleSelection(_ item: FireNotificationHistoryCollectionItem) { + switch item { + case let .notification(id): + guard let notification = notification(id: id) else { return } + open(notification) + case .retryFooter: + loadTask = Task { [weak self] in + await self?.notificationStore.retryFullLoad() + } + case .blockingError, .loading, .empty, .offlineBanner, .inlineErrorBanner, .loadingMore: + break + } + } + + func open(_ item: NotificationItemState) { + if !item.read { + notificationStore.markRead(id: item.id) + } + guard let route = item.appRoute else { return } + presentRoute(route) + } + + func presentRoute(_ route: FireAppRoute) { + if route.isTopicRoute { + appViewModel.topicRouteLogger()?.info("notification history presenting topic route \(route.diagnosticsSummary)") + navigationState.presentTopicRoute(route) + return + } + if route.presentsAsSecondaryPage { + FireAppRouteControllerFactory.presentSecondaryRoute( + route, + viewModel: appViewModel, + topicDetailStore: topicDetailStore + ) + return + } + } + + func presentShareSheet(url: URL) { + let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) + if let popover = controller.popoverPresentationController { + popover.sourceView = view + popover.sourceRect = CGRect( + x: view.bounds.midX, + y: view.safeAreaInsets.top + 24, + width: 1, + height: 1 + ) + } + present(controller, animated: true) + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Setup.swift b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Setup.swift new file mode 100644 index 00000000..d0b0ffee --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController+Setup.swift @@ -0,0 +1,50 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationHistoryViewController { + func configureListController() { + listController.updateCellProvider { [weak self] collectionView, indexPath, item in + guard let self else { + return UICollectionViewCell() + } + return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) + } + listController.updateContextMenuConfigurationProvider { [weak self] item in + self?.contextMenuConfiguration(for: item) + } + } + + func prepareCellRegistrations() { + _ = stateCellRegistration + _ = offlineCellRegistration + _ = bannerCellRegistration + _ = notificationCellRegistration + _ = retryCellRegistration + } + + func installListController() { + addChild(listController) + view.addSubview(listController.view) + listController.view.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + listController.view.topAnchor.constraint(equalTo: view.topAnchor), + listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + listController.didMove(toParent: self) + } + + func bindStore() { + notificationStore.objectWillChange + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + DispatchQueue.main.async { + self?.render() + self?.updateToolbar() + } + } + .store(in: &cancellables) + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationHistoryViewController.swift b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController.swift index b9aeace1..75ef2a6e 100644 --- a/apps/ios-app/App/Notifications/FireNotificationHistoryViewController.swift +++ b/apps/ios-app/App/Notifications/FireNotificationHistoryViewController.swift @@ -171,348 +171,6 @@ final class FireNotificationHistoryViewController: UIViewController { updateToolbar() } - func configureListController() { - listController.updateCellProvider { [weak self] collectionView, indexPath, item in - guard let self else { - return UICollectionViewCell() - } - return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) - } - listController.updateContextMenuConfigurationProvider { [weak self] item in - self?.contextMenuConfiguration(for: item) - } - } - - func prepareCellRegistrations() { - _ = stateCellRegistration - _ = offlineCellRegistration - _ = bannerCellRegistration - _ = notificationCellRegistration - _ = retryCellRegistration - } - - func installListController() { - addChild(listController) - view.addSubview(listController.view) - listController.view.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), - listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), - listController.view.topAnchor.constraint(equalTo: view.topAnchor), - listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) - listController.didMove(toParent: self) - } - - func bindStore() { - notificationStore.objectWillChange - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - DispatchQueue.main.async { - self?.render() - self?.updateToolbar() - } - } - .store(in: &cancellables) - } - - var baseURLString: String { - let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? "https://linux.do" : trimmed - } - - var contentVersion: ContentVersion { - ContentVersion( - unreadCount: notificationStore.unreadCount, - notifications: notificationStore.fullNotifications.map(FireNotificationItemContentToken.init), - nextOffset: notificationStore.fullNextOffset, - isLoading: notificationStore.isLoadingFullPage, - hasLoadedOnce: notificationStore.hasLoadedFullOnce, - hasMore: notificationStore.hasMoreFull, - shouldShowRetry: notificationStore.shouldShowFullPaginationRetry, - errorMessage: notificationStore.fullErrorMessage, - isOffline: notificationStore.isFullOffline - ) - } - - func updateToolbar() { - guard notificationStore.unreadCount > 0 else { - navigationItem.rightBarButtonItem = nil - return - } - navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "全部已读", - style: .plain, - target: self, - action: #selector(markAllRead) - ) - } - - @objc func markAllRead() { - notificationStore.markAllRead() - } - - func render() { - let sections = makeSections() - var tokens: [FireNotificationHistoryCollectionItem: AnyHashable] = [:] - tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) - for section in sections { - for item in section.items { - tokens[item] = itemContentToken(for: item) - } - } - listController.setSections( - sections, - contentVersion: contentVersion, - itemContentTokens: tokens, - animatingDifferences: true - ) - } - - func makeSections() - -> [FireListSectionModel] - { - var items: [FireNotificationHistoryCollectionItem] = [] - - if let errorMessage = notificationStore.blockingFullErrorMessage { - items.append(.blockingError(errorMessage)) - return [.init(id: .content, items: items)] - } - - if !notificationStore.hasLoadedFullOnce, - notificationStore.fullNotifications.isEmpty { - items.append(.loading) - return [.init(id: .content, items: items)] - } - - if notificationStore.isFullOffline { - items.append(.offlineBanner) - } - - if let errorMessage = notificationStore.fullNonBlockingErrorMessage { - items.append(.inlineErrorBanner(errorMessage)) - } - - if notificationStore.fullNotifications.isEmpty { - items.append(.empty) - } else { - items.append(contentsOf: notificationStore.fullNotifications.map { .notification($0.id) }) - - if notificationStore.shouldShowFullPaginationRetry { - items.append(.retryFooter) - } else if notificationStore.hasMoreFull { - items.append(.loadingMore) - } - } - - return [.init(id: .content, items: items)] - } - - func cell( - collectionView: UICollectionView, - indexPath: IndexPath, - item: FireNotificationHistoryCollectionItem - ) -> UICollectionViewCell { - switch item { - case .blockingError, .loading, .empty, .loadingMore: - return collectionView.dequeueConfiguredReusableCell( - using: stateCellRegistration, - for: indexPath, - item: item - ) - case .offlineBanner: - return collectionView.dequeueConfiguredReusableCell( - using: offlineCellRegistration, - for: indexPath, - item: item - ) - case .inlineErrorBanner: - return collectionView.dequeueConfiguredReusableCell( - using: bannerCellRegistration, - for: indexPath, - item: item - ) - case .notification: - return collectionView.dequeueConfiguredReusableCell( - using: notificationCellRegistration, - for: indexPath, - item: item - ) - case .retryFooter: - return collectionView.dequeueConfiguredReusableCell( - using: retryCellRegistration, - for: indexPath, - item: item - ) - } - } - - func canSelect(_ item: FireNotificationHistoryCollectionItem) -> Bool { - switch item { - case .notification, .retryFooter: - return true - case .blockingError, .loading, .empty, .offlineBanner, .inlineErrorBanner, .loadingMore: - return false - } - } - - func handleSelection(_ item: FireNotificationHistoryCollectionItem) { - switch item { - case let .notification(id): - guard let notification = notification(id: id) else { return } - open(notification) - case .retryFooter: - loadTask = Task { [weak self] in - await self?.notificationStore.retryFullLoad() - } - case .blockingError, .loading, .empty, .offlineBanner, .inlineErrorBanner, .loadingMore: - break - } - } - - func notification(id: UInt64) -> NotificationItemState? { - notificationStore.fullNotifications.first { $0.id == id } - } - - func loadMoreIfNeeded(from items: [FireNotificationHistoryCollectionItem]) { - guard notificationStore.hasMoreFull, - !notificationStore.isLoadingFullPage, - !notificationStore.shouldShowFullPaginationRetry else { return } - let lastNotificationID = notificationStore.fullNotifications.last?.id - guard items.contains(.loadingMore) - || lastNotificationID.map({ items.contains(.notification($0)) }) == true - else { - return - } - loadTask = Task { [weak self] in - guard let self else { return } - await self.notificationStore.loadFullPage(offset: self.notificationStore.fullNextOffset) - } - } - - func itemContentToken(for item: FireNotificationHistoryCollectionItem) -> AnyHashable { - switch item { - case let .blockingError(message), let .inlineErrorBanner(message): - return AnyHashable(message) - case .loading: - return AnyHashable(notificationStore.isLoadingFullPage) - case .empty: - return AnyHashable(notificationStore.hasLoadedFullOnce) - case .offlineBanner: - return AnyHashable(notificationStore.isFullOffline) - case let .notification(id): - guard let notification = notification(id: id) else { - return AnyHashable("missing|\(id)") - } - return AnyHashable(FireNotificationItemContentToken(notification)) - case .retryFooter: - return AnyHashable(notificationStore.shouldShowFullPaginationRetry) - case .loadingMore: - return AnyHashable(notificationStore.fullNextOffset) - } - } - - func contextMenuConfiguration( - for item: FireNotificationHistoryCollectionItem - ) -> UIContextMenuConfiguration? { - guard case let .notification(id) = item, - let notification = notification(id: id) - else { - return nil - } - let shareURL = notification.fireShareURL(baseURL: baseURLString) - return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in - UIMenu(children: self?.notificationMenuActions(item: notification, shareURL: shareURL) ?? []) - } - } - - func notificationMenuActions( - item: NotificationItemState, - shareURL: URL? - ) -> [UIAction] { - var actions: [UIAction] = [ - UIAction(title: "跳转到通知", image: UIImage(systemName: "arrow.up.right")) { [weak self] _ in - self?.open(item) - }, - ] - - if !item.read { - actions.append( - UIAction(title: "标记为已读", image: UIImage(systemName: "envelope.open")) { [weak self] _ in - self?.notificationStore.markRead(id: item.id) - } - ) - } - - actions.append( - UIAction(title: "复制通知内容", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in - UIPasteboard.general.string = item.displayDescription - self?.showToast("已复制通知内容", style: .success) - } - ) - - if let shareURL { - actions.append( - UIAction(title: "分享链接", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in - self?.presentShareSheet(url: shareURL) - } - ) - actions.append( - UIAction(title: "复制链接", image: UIImage(systemName: "link")) { [weak self] _ in - UIPasteboard.general.string = shareURL.absoluteString - self?.showToast("已复制链接", style: .success) - } - ) - } - - return actions - } - - func open(_ item: NotificationItemState) { - if !item.read { - notificationStore.markRead(id: item.id) - } - guard let route = item.appRoute else { return } - presentRoute(route) - } - - func presentRoute(_ route: FireAppRoute) { - if route.isTopicRoute { - appViewModel.topicRouteLogger()?.info("notification history presenting topic route \(route.diagnosticsSummary)") - navigationState.presentTopicRoute(route) - return - } - if route.presentsAsSecondaryPage { - FireAppRouteControllerFactory.presentSecondaryRoute( - route, - viewModel: appViewModel, - topicDetailStore: topicDetailStore - ) - return - } - } - - func presentShareSheet(url: URL) { - let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) - if let popover = controller.popoverPresentationController { - popover.sourceView = view - popover.sourceRect = CGRect( - x: view.bounds.midX, - y: view.safeAreaInsets.top + 24, - width: 1, - height: 1 - ) - } - present(controller, animated: true) - } - - func showToast(_ message: String, style: FireTopicListToastView.Style) { - toastDismissTask?.cancel() - toastView?.removeFromSuperview() - toastView = nil - FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) - } - } final class FireNotificationHistoryControllerReference { diff --git a/apps/ios-app/App/Notifications/FireNotificationsViewController+Actions.swift b/apps/ios-app/App/Notifications/FireNotificationsViewController+Actions.swift new file mode 100644 index 00000000..6e31c164 --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationsViewController+Actions.swift @@ -0,0 +1,85 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationsViewController { + func updateToolbar() { + guard notificationStore.unreadCount > 0 else { + navigationItem.rightBarButtonItem = nil + return + } + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "全部已读", + style: .plain, + target: self, + action: #selector(markAllRead) + ) + } + + @objc func markAllRead() { + notificationStore.markAllRead() + } + + func contextMenuConfiguration( + for item: FireNotificationsCollectionItem + ) -> UIContextMenuConfiguration? { + guard case let .notification(id) = item, + let notification = notification(id: id) + else { + return nil + } + let shareURL = notification.fireShareURL(baseURL: baseURLString) + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in + UIMenu(children: self?.notificationMenuActions(item: notification, shareURL: shareURL) ?? []) + } + } + + func notificationMenuActions( + item: NotificationItemState, + shareURL: URL? + ) -> [UIAction] { + var actions: [UIAction] = [ + UIAction(title: "跳转到通知", image: UIImage(systemName: "arrow.up.right")) { [weak self] _ in + self?.open(item) + }, + ] + + if !item.read { + actions.append( + UIAction(title: "标记为已读", image: UIImage(systemName: "envelope.open")) { [weak self] _ in + self?.notificationStore.markRead(id: item.id) + } + ) + } + + actions.append( + UIAction(title: "复制通知内容", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in + UIPasteboard.general.string = item.displayDescription + self?.showToast("已复制通知内容", style: .success) + } + ) + + if let shareURL { + actions.append( + UIAction(title: "分享链接", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in + self?.presentShareSheet(url: shareURL) + } + ) + actions.append( + UIAction(title: "复制链接", image: UIImage(systemName: "link")) { [weak self] _ in + UIPasteboard.general.string = shareURL.absoluteString + self?.showToast("已复制链接", style: .success) + } + ) + } + + return actions + } + + func showToast(_ message: String, style: FireTopicListToastView.Style) { + toastDismissTask?.cancel() + toastView?.removeFromSuperview() + toastView = nil + FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationsViewController+Feed.swift b/apps/ios-app/App/Notifications/FireNotificationsViewController+Feed.swift new file mode 100644 index 00000000..5d9b76cf --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationsViewController+Feed.swift @@ -0,0 +1,133 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationsViewController { + var baseURLString: String { + let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? "https://linux.do" : trimmed + } + + var contentVersion: ContentVersion { + ContentVersion( + unreadCount: notificationStore.unreadCount, + notifications: notificationStore.recentNotifications.map(FireNotificationItemContentToken.init), + isLoading: notificationStore.isLoadingRecent, + hasLoadedOnce: notificationStore.hasLoadedRecentOnce, + errorMessage: notificationStore.recentErrorMessage, + isOffline: notificationStore.isRecentOffline + ) + } + + func render() { + let sections = makeSections() + var tokens: [FireNotificationsCollectionItem: AnyHashable] = [:] + tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) + for section in sections { + for item in section.items { + tokens[item] = itemContentToken(for: item) + } + } + listController.setSections( + sections, + contentVersion: contentVersion, + itemContentTokens: tokens, + animatingDifferences: true + ) + } + + func makeSections() + -> [FireListSectionModel] + { + var items: [FireNotificationsCollectionItem] = [] + + if !notificationStore.hasLoadedRecentOnce { + if let errorMessage = notificationStore.blockingRecentErrorMessage { + items.append(.blockingError(errorMessage)) + } else { + items.append(.loading) + } + return [.init(id: .content, items: items)] + } + + if notificationStore.isRecentOffline { + items.append(.offlineBanner) + } + + if let errorMessage = notificationStore.recentNonBlockingErrorMessage { + items.append(.inlineErrorBanner(errorMessage)) + } + + if notificationStore.recentNotifications.isEmpty { + items.append(.empty) + } else { + items.append(contentsOf: notificationStore.recentNotifications.map { .notification($0.id) }) + items.append(.historyLink) + } + + return [.init(id: .content, items: items)] + } + + func cell( + collectionView: UICollectionView, + indexPath: IndexPath, + item: FireNotificationsCollectionItem + ) -> UICollectionViewCell { + switch item { + case .blockingError, .loading, .empty: + return collectionView.dequeueConfiguredReusableCell( + using: stateCellRegistration, + for: indexPath, + item: item + ) + case .offlineBanner: + return collectionView.dequeueConfiguredReusableCell( + using: offlineCellRegistration, + for: indexPath, + item: item + ) + case .inlineErrorBanner: + return collectionView.dequeueConfiguredReusableCell( + using: bannerCellRegistration, + for: indexPath, + item: item + ) + case .notification: + return collectionView.dequeueConfiguredReusableCell( + using: notificationCellRegistration, + for: indexPath, + item: item + ) + case .historyLink: + return collectionView.dequeueConfiguredReusableCell( + using: historyLinkCellRegistration, + for: indexPath, + item: item + ) + } + } + + func notification(id: UInt64) -> NotificationItemState? { + notificationStore.recentNotifications.first { $0.id == id } + } + + func itemContentToken(for item: FireNotificationsCollectionItem) -> AnyHashable { + switch item { + case let .blockingError(message), let .inlineErrorBanner(message): + return AnyHashable(message) + case .loading: + return AnyHashable(notificationStore.isLoadingRecent) + case .empty: + return AnyHashable(notificationStore.hasLoadedRecentOnce) + case .offlineBanner: + return AnyHashable(notificationStore.isRecentOffline) + case let .notification(id): + guard let notification = notification(id: id) else { + return AnyHashable("missing|\(id)") + } + return AnyHashable(FireNotificationItemContentToken(notification)) + case .historyLink: + return AnyHashable(notificationStore.recentNotifications.count) + } + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationsViewController+Pagination.swift b/apps/ios-app/App/Notifications/FireNotificationsViewController+Pagination.swift new file mode 100644 index 00000000..8455419e --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationsViewController+Pagination.swift @@ -0,0 +1,13 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationsViewController { + func loadRecentIfNeeded() { + guard !notificationStore.hasLoadedRecentOnce, + !notificationStore.isLoadingRecent else { return } + loadTask = Task { [weak self] in + await self?.notificationStore.loadRecent(force: false) + } + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationsViewController+Routing.swift b/apps/ios-app/App/Notifications/FireNotificationsViewController+Routing.swift new file mode 100644 index 00000000..184e59d5 --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationsViewController+Routing.swift @@ -0,0 +1,70 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationsViewController { + func canSelect(_ item: FireNotificationsCollectionItem) -> Bool { + switch item { + case .notification, .historyLink: + return true + case .blockingError, .loading, .empty, .offlineBanner, .inlineErrorBanner: + return false + } + } + + func handleSelection(_ item: FireNotificationsCollectionItem) { + switch item { + case let .notification(id): + guard let notification = notification(id: id) else { return } + open(notification) + case .historyLink: + let controller = FireNotificationHistoryViewController( + viewModel: appViewModel, + navigationState: navigationState, + notificationStore: notificationStore, + topicDetailStore: topicDetailStore + ) + FireRootCoordinator.presentSecondary(controller) + case .blockingError, .loading, .empty, .offlineBanner, .inlineErrorBanner: + break + } + } + + func open(_ item: NotificationItemState) { + if !item.read { + notificationStore.markRead(id: item.id) + } + guard let route = item.appRoute else { return } + presentRoute(route) + } + + func presentRoute(_ route: FireAppRoute) { + if route.isTopicRoute { + appViewModel.topicRouteLogger()?.info("notifications tab presenting topic route \(route.diagnosticsSummary)") + navigationState.presentTopicRoute(route) + return + } + if route.presentsAsSecondaryPage { + FireAppRouteControllerFactory.presentSecondaryRoute( + route, + viewModel: appViewModel, + topicDetailStore: topicDetailStore + ) + return + } + } + + func presentShareSheet(url: URL) { + let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) + if let popover = controller.popoverPresentationController { + popover.sourceView = view + popover.sourceRect = CGRect( + x: view.bounds.midX, + y: view.safeAreaInsets.top + 24, + width: 1, + height: 1 + ) + } + present(controller, animated: true) + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationsViewController+Setup.swift b/apps/ios-app/App/Notifications/FireNotificationsViewController+Setup.swift new file mode 100644 index 00000000..eac9f38e --- /dev/null +++ b/apps/ios-app/App/Notifications/FireNotificationsViewController+Setup.swift @@ -0,0 +1,50 @@ +import Combine +import UIKit + +@MainActor +extension FireNotificationsViewController { + func configureListController() { + listController.updateCellProvider { [weak self] collectionView, indexPath, item in + guard let self else { + return UICollectionViewCell() + } + return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) + } + listController.updateContextMenuConfigurationProvider { [weak self] item in + self?.contextMenuConfiguration(for: item) + } + } + + func prepareCellRegistrations() { + _ = stateCellRegistration + _ = offlineCellRegistration + _ = bannerCellRegistration + _ = notificationCellRegistration + _ = historyLinkCellRegistration + } + + func installListController() { + addChild(listController) + view.addSubview(listController.view) + listController.view.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + listController.view.topAnchor.constraint(equalTo: view.topAnchor), + listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + listController.didMove(toParent: self) + } + + func bindStore() { + notificationStore.objectWillChange + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + DispatchQueue.main.async { + self?.render() + self?.updateToolbar() + } + } + .store(in: &cancellables) + } +} diff --git a/apps/ios-app/App/Notifications/FireNotificationsViewController.swift b/apps/ios-app/App/Notifications/FireNotificationsViewController.swift index 57d94106..a0047a0b 100644 --- a/apps/ios-app/App/Notifications/FireNotificationsViewController.swift +++ b/apps/ios-app/App/Notifications/FireNotificationsViewController.swift @@ -159,332 +159,6 @@ final class FireNotificationsViewController: UIViewController { loadRecentIfNeeded() } - func configureListController() { - listController.updateCellProvider { [weak self] collectionView, indexPath, item in - guard let self else { - return UICollectionViewCell() - } - return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) - } - listController.updateContextMenuConfigurationProvider { [weak self] item in - self?.contextMenuConfiguration(for: item) - } - } - - func prepareCellRegistrations() { - _ = stateCellRegistration - _ = offlineCellRegistration - _ = bannerCellRegistration - _ = notificationCellRegistration - _ = historyLinkCellRegistration - } - - func installListController() { - addChild(listController) - view.addSubview(listController.view) - listController.view.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), - listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), - listController.view.topAnchor.constraint(equalTo: view.topAnchor), - listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) - listController.didMove(toParent: self) - } - - func bindStore() { - notificationStore.objectWillChange - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - DispatchQueue.main.async { - self?.render() - self?.updateToolbar() - } - } - .store(in: &cancellables) - } - - var baseURLString: String { - let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? "https://linux.do" : trimmed - } - - var contentVersion: ContentVersion { - ContentVersion( - unreadCount: notificationStore.unreadCount, - notifications: notificationStore.recentNotifications.map(FireNotificationItemContentToken.init), - isLoading: notificationStore.isLoadingRecent, - hasLoadedOnce: notificationStore.hasLoadedRecentOnce, - errorMessage: notificationStore.recentErrorMessage, - isOffline: notificationStore.isRecentOffline - ) - } - - func loadRecentIfNeeded() { - guard !notificationStore.hasLoadedRecentOnce, - !notificationStore.isLoadingRecent else { return } - loadTask = Task { [weak self] in - await self?.notificationStore.loadRecent(force: false) - } - } - - func updateToolbar() { - guard notificationStore.unreadCount > 0 else { - navigationItem.rightBarButtonItem = nil - return - } - navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "全部已读", - style: .plain, - target: self, - action: #selector(markAllRead) - ) - } - - @objc func markAllRead() { - notificationStore.markAllRead() - } - - func render() { - let sections = makeSections() - var tokens: [FireNotificationsCollectionItem: AnyHashable] = [:] - tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) - for section in sections { - for item in section.items { - tokens[item] = itemContentToken(for: item) - } - } - listController.setSections( - sections, - contentVersion: contentVersion, - itemContentTokens: tokens, - animatingDifferences: true - ) - } - - func makeSections() - -> [FireListSectionModel] - { - var items: [FireNotificationsCollectionItem] = [] - - if !notificationStore.hasLoadedRecentOnce { - if let errorMessage = notificationStore.blockingRecentErrorMessage { - items.append(.blockingError(errorMessage)) - } else { - items.append(.loading) - } - return [.init(id: .content, items: items)] - } - - if notificationStore.isRecentOffline { - items.append(.offlineBanner) - } - - if let errorMessage = notificationStore.recentNonBlockingErrorMessage { - items.append(.inlineErrorBanner(errorMessage)) - } - - if notificationStore.recentNotifications.isEmpty { - items.append(.empty) - } else { - items.append(contentsOf: notificationStore.recentNotifications.map { .notification($0.id) }) - items.append(.historyLink) - } - - return [.init(id: .content, items: items)] - } - - func cell( - collectionView: UICollectionView, - indexPath: IndexPath, - item: FireNotificationsCollectionItem - ) -> UICollectionViewCell { - switch item { - case .blockingError, .loading, .empty: - return collectionView.dequeueConfiguredReusableCell( - using: stateCellRegistration, - for: indexPath, - item: item - ) - case .offlineBanner: - return collectionView.dequeueConfiguredReusableCell( - using: offlineCellRegistration, - for: indexPath, - item: item - ) - case .inlineErrorBanner: - return collectionView.dequeueConfiguredReusableCell( - using: bannerCellRegistration, - for: indexPath, - item: item - ) - case .notification: - return collectionView.dequeueConfiguredReusableCell( - using: notificationCellRegistration, - for: indexPath, - item: item - ) - case .historyLink: - return collectionView.dequeueConfiguredReusableCell( - using: historyLinkCellRegistration, - for: indexPath, - item: item - ) - } - } - - func canSelect(_ item: FireNotificationsCollectionItem) -> Bool { - switch item { - case .notification, .historyLink: - return true - case .blockingError, .loading, .empty, .offlineBanner, .inlineErrorBanner: - return false - } - } - - func handleSelection(_ item: FireNotificationsCollectionItem) { - switch item { - case let .notification(id): - guard let notification = notification(id: id) else { return } - open(notification) - case .historyLink: - let controller = FireNotificationHistoryViewController( - viewModel: appViewModel, - navigationState: navigationState, - notificationStore: notificationStore, - topicDetailStore: topicDetailStore - ) - FireRootCoordinator.presentSecondary(controller) - case .blockingError, .loading, .empty, .offlineBanner, .inlineErrorBanner: - break - } - } - - func notification(id: UInt64) -> NotificationItemState? { - notificationStore.recentNotifications.first { $0.id == id } - } - - func itemContentToken(for item: FireNotificationsCollectionItem) -> AnyHashable { - switch item { - case let .blockingError(message), let .inlineErrorBanner(message): - return AnyHashable(message) - case .loading: - return AnyHashable(notificationStore.isLoadingRecent) - case .empty: - return AnyHashable(notificationStore.hasLoadedRecentOnce) - case .offlineBanner: - return AnyHashable(notificationStore.isRecentOffline) - case let .notification(id): - guard let notification = notification(id: id) else { - return AnyHashable("missing|\(id)") - } - return AnyHashable(FireNotificationItemContentToken(notification)) - case .historyLink: - return AnyHashable(notificationStore.recentNotifications.count) - } - } - - func contextMenuConfiguration( - for item: FireNotificationsCollectionItem - ) -> UIContextMenuConfiguration? { - guard case let .notification(id) = item, - let notification = notification(id: id) - else { - return nil - } - let shareURL = notification.fireShareURL(baseURL: baseURLString) - return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in - UIMenu(children: self?.notificationMenuActions(item: notification, shareURL: shareURL) ?? []) - } - } - - func notificationMenuActions( - item: NotificationItemState, - shareURL: URL? - ) -> [UIAction] { - var actions: [UIAction] = [ - UIAction(title: "跳转到通知", image: UIImage(systemName: "arrow.up.right")) { [weak self] _ in - self?.open(item) - }, - ] - - if !item.read { - actions.append( - UIAction(title: "标记为已读", image: UIImage(systemName: "envelope.open")) { [weak self] _ in - self?.notificationStore.markRead(id: item.id) - } - ) - } - - actions.append( - UIAction(title: "复制通知内容", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in - UIPasteboard.general.string = item.displayDescription - self?.showToast("已复制通知内容", style: .success) - } - ) - - if let shareURL { - actions.append( - UIAction(title: "分享链接", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in - self?.presentShareSheet(url: shareURL) - } - ) - actions.append( - UIAction(title: "复制链接", image: UIImage(systemName: "link")) { [weak self] _ in - UIPasteboard.general.string = shareURL.absoluteString - self?.showToast("已复制链接", style: .success) - } - ) - } - - return actions - } - - func open(_ item: NotificationItemState) { - if !item.read { - notificationStore.markRead(id: item.id) - } - guard let route = item.appRoute else { return } - presentRoute(route) - } - - func presentRoute(_ route: FireAppRoute) { - if route.isTopicRoute { - appViewModel.topicRouteLogger()?.info("notifications tab presenting topic route \(route.diagnosticsSummary)") - navigationState.presentTopicRoute(route) - return - } - if route.presentsAsSecondaryPage { - FireAppRouteControllerFactory.presentSecondaryRoute( - route, - viewModel: appViewModel, - topicDetailStore: topicDetailStore - ) - return - } - } - - func presentShareSheet(url: URL) { - let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) - if let popover = controller.popoverPresentationController { - popover.sourceView = view - popover.sourceRect = CGRect( - x: view.bounds.midX, - y: view.safeAreaInsets.top + 24, - width: 1, - height: 1 - ) - } - present(controller, animated: true) - } - - func showToast(_ message: String, style: FireTopicListToastView.Style) { - toastDismissTask?.cancel() - toastView?.removeFromSuperview() - toastView = nil - FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) - } - } final class FireNotificationsControllerReference { diff --git a/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+ExternalMethods.swift b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+ExternalMethods.swift new file mode 100644 index 00000000..dce3a1db --- /dev/null +++ b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+ExternalMethods.swift @@ -0,0 +1,72 @@ +import UIKit + +extension FireOnboardingCredentialFormView { + func setupExternalLoginMethods() { + dividerLabel.translatesAutoresizingMaskIntoConstraints = false + dividerLabel.text = "- 其他方式 -" + dividerLabel.font = .systemFont(ofSize: 13) + dividerLabel.textColor = .tertiaryLabel + dividerLabel.textAlignment = .center + + externalLoginStack.translatesAutoresizingMaskIntoConstraints = false + externalLoginStack.axis = .horizontal + externalLoginStack.alignment = .fill + externalLoginStack.distribution = .fillEqually + externalLoginStack.spacing = 8 + + for method in FireExternalLoginMethod.allCases { + let button = makeExternalLoginButton(for: method) + externalLoginButtons.append(button) + externalLoginStack.addArrangedSubview(button) + } + + contentView.addSubview(dividerLabel) + contentView.addSubview(externalLoginStack) + + NSLayoutConstraint.activate([ + dividerLabel.topAnchor.constraint(equalTo: lastLoginHintLabel.bottomAnchor, constant: 18), + dividerLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + + externalLoginStack.topAnchor.constraint(equalTo: dividerLabel.bottomAnchor, constant: 14), + externalLoginStack.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), + externalLoginStack.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), + externalLoginStack.heightAnchor.constraint(equalToConstant: 52), + externalLoginStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -32), + ]) + } + func makeExternalLoginButton(for method: FireExternalLoginMethod) -> UIButton { + let button = UIButton(type: .system) + button.translatesAutoresizingMaskIntoConstraints = false + button.accessibilityLabel = method.accessibilityLabel + button.tag = FireExternalLoginMethod.allCases.firstIndex(of: method) ?? 0 + button.configuration = externalLoginConfiguration(for: method, highlighted: false) + button.addTarget(self, action: #selector(externalLoginTapped(_:)), for: .touchUpInside) + button.fireBindPressBounce(.compact) + return button + } + func externalLoginConfiguration( + for method: FireExternalLoginMethod, + highlighted: Bool + ) -> UIButton.Configuration { + var configuration = UIButton.Configuration.plain() + configuration.image = method.iconImage + // Elevated chip that stays readable on both light canvas and pure black dark canvas. + configuration.background.backgroundColor = UIColor { traits in + traits.userInterfaceStyle == .dark + ? UIColor.secondarySystemFill + : UIColor.secondarySystemGroupedBackground + } + configuration.background.cornerRadius = 14 + configuration.background.strokeColor = highlighted + ? FireTheme.uiAccent + : UIColor.separator.withAlphaComponent(0.55) + configuration.background.strokeWidth = highlighted ? 1.5 : 1 + configuration.contentInsets = NSDirectionalEdgeInsets(top: 12, leading: 10, bottom: 12, trailing: 10) + return configuration + } + @objc func externalLoginTapped(_ sender: UIButton) { + let methods = FireExternalLoginMethod.allCases + guard methods.indices.contains(sender.tag) else { return } + onExternalLogin?(methods[sender.tag]) + } +} diff --git a/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Fields.swift b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Fields.swift new file mode 100644 index 00000000..f183730d --- /dev/null +++ b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Fields.swift @@ -0,0 +1,131 @@ +import UIKit + +extension FireOnboardingCredentialFormView { + func setupCredentialFields() { + configureTextField(identifierField, placeholder: "用户名或邮箱", secure: false) + identifierField.returnKeyType = .next + identifierField.delegate = self + identifierField.addTarget(self, action: #selector(textFieldsChanged), for: .editingChanged) + + configureTextField(passwordField, placeholder: "密码", secure: true) + passwordField.returnKeyType = .go + passwordField.delegate = self + passwordField.addTarget(self, action: #selector(textFieldsChanged), for: .editingChanged) + // Eye toggle replaces clear button on the password field. + passwordField.clearButtonMode = .never + passwordField.rightView = makePasswordVisibilityAccessory() + passwordField.rightViewMode = .always + + contentView.addSubview(identifierField) + contentView.addSubview(passwordField) + + NSLayoutConstraint.activate([ + identifierField.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), + identifierField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), + identifierField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), + identifierField.heightAnchor.constraint(equalToConstant: 48), + + passwordField.topAnchor.constraint(equalTo: identifierField.bottomAnchor, constant: 12), + passwordField.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), + passwordField.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), + passwordField.heightAnchor.constraint(equalToConstant: 48), + ]) + } + func configureTextField(_ field: UITextField, placeholder: String, secure: Bool) { + field.translatesAutoresizingMaskIntoConstraints = false + field.placeholder = placeholder + // Custom chrome instead of .roundedRect: system roundedRect sits too dark on + // pure-black onboarding canvas and loses edge definition in dark mode. + field.borderStyle = .none + field.autocapitalizationType = .none + field.autocorrectionType = .no + field.clearButtonMode = .whileEditing + field.isSecureTextEntry = secure + field.textContentType = secure ? .password : .username + field.inputAccessoryView = keyboardToolbar + field.layer.cornerRadius = 10 + field.layer.masksToBounds = true + field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 1)) + field.leftViewMode = .always + applyCredentialFieldChrome(to: field) + } + func applyCredentialFieldChrome(to field: UITextField) { + let isDark = traitCollection.userInterfaceStyle == .dark + field.backgroundColor = isDark + ? UIColor.secondarySystemFill + : UIColor.secondarySystemGroupedBackground + field.textColor = .label + field.tintColor = FireTheme.uiAccent + field.layer.borderWidth = 1 + field.layer.borderColor = UIColor.separator.withAlphaComponent(isDark ? 0.7 : 0.45).cgColor + field.attributedPlaceholder = NSAttributedString( + string: field.placeholder ?? "", + attributes: [ + .foregroundColor: UIColor.secondaryLabel.withAlphaComponent(0.85), + .font: UIFont.systemFont(ofSize: 17), + ] + ) + } + func restyleCredentialFieldsForCurrentAppearance() { + applyCredentialFieldChrome(to: identifierField) + applyCredentialFieldChrome(to: passwordField) + updatePasswordVisibilityAppearance() + } + func makePasswordVisibilityAccessory() -> UIView { + var configuration = UIButton.Configuration.plain() + configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 10) + configuration.preferredSymbolConfigurationForImage = Self.passwordVisibilitySymbolConfiguration + passwordVisibilityButton.configuration = configuration + passwordVisibilityButton.translatesAutoresizingMaskIntoConstraints = false + passwordVisibilityButton.addTarget(self, action: #selector(passwordVisibilityTapped), for: .touchUpInside) + passwordVisibilityButton.accessibilityLabel = "显示密码" + passwordVisibilityButton.fireBindPressBounce(.compact) + + // Slightly wider trailing chrome so the glyph doesn't hug the field edge. + let host = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 40)) + host.addSubview(passwordVisibilityButton) + NSLayoutConstraint.activate([ + passwordVisibilityButton.leadingAnchor.constraint(equalTo: host.leadingAnchor), + passwordVisibilityButton.trailingAnchor.constraint(equalTo: host.trailingAnchor), + passwordVisibilityButton.topAnchor.constraint(equalTo: host.topAnchor), + passwordVisibilityButton.bottomAnchor.constraint(equalTo: host.bottomAnchor), + host.widthAnchor.constraint(equalToConstant: 44), + host.heightAnchor.constraint(equalToConstant: 40), + ]) + return host + } + func updatePasswordVisibilityAppearance() { + // Prefer the filled pair — reads cleaner at small sizes than the outline glyphs. + let symbol = isPasswordVisible ? "eye.slash.fill" : "eye.fill" + let image = UIImage(systemName: symbol, withConfiguration: Self.passwordVisibilitySymbolConfiguration)? + .withRenderingMode(.alwaysTemplate) + + var configuration = passwordVisibilityButton.configuration ?? .plain() + configuration.image = image + configuration.baseForegroundColor = UIColor { traits in + traits.userInterfaceStyle == .dark + ? UIColor.tertiaryLabel + : UIColor.secondaryLabel.withAlphaComponent(0.85) + } + configuration.preferredSymbolConfigurationForImage = Self.passwordVisibilitySymbolConfiguration + configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 10) + passwordVisibilityButton.configuration = configuration + passwordVisibilityButton.accessibilityLabel = isPasswordVisible ? "隐藏密码" : "显示密码" + } + @objc func textFieldsChanged() { + updateLoginButtonState() + } + @objc func passwordVisibilityTapped() { + isPasswordVisible.toggle() + // Preserve caret / text when flipping secure entry (UIKit quirk). + let wasFirstResponder = passwordField.isFirstResponder + let existing = passwordField.text + passwordField.isSecureTextEntry = !isPasswordVisible + passwordField.text = nil + passwordField.text = existing + if wasFirstResponder { + passwordField.becomeFirstResponder() + } + updatePasswordVisibilityAppearance() + } +} diff --git a/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Keyboard.swift b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Keyboard.swift new file mode 100644 index 00000000..3e1faf64 --- /dev/null +++ b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Keyboard.swift @@ -0,0 +1,63 @@ +import UIKit + +extension FireOnboardingCredentialFormView { + func setupScrollView() { + scrollView.translatesAutoresizingMaskIntoConstraints = false + scrollView.keyboardDismissMode = .interactive + scrollView.alwaysBounceVertical = true + addSubview(scrollView) + + contentView.translatesAutoresizingMaskIntoConstraints = false + scrollView.addSubview(contentView) + + let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped)) + tapGesture.cancelsTouchesInView = false + scrollView.addGestureRecognizer(tapGesture) + + NSLayoutConstraint.activate([ + scrollView.topAnchor.constraint(equalTo: topAnchor), + scrollView.leadingAnchor.constraint(equalTo: leadingAnchor), + scrollView.trailingAnchor.constraint(equalTo: trailingAnchor), + scrollView.bottomAnchor.constraint(equalTo: bottomAnchor), + + contentView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor), + contentView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor), + contentView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor), + contentView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor), + contentView.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor), + ]) + } + func observeKeyboardNotifications() { + NotificationCenter.default.addObserver( + self, + selector: #selector(keyboardWillChangeFrame(_:)), + name: UIResponder.keyboardWillChangeFrameNotification, + object: nil + ) + NotificationCenter.default.addObserver( + self, + selector: #selector(keyboardWillHide(_:)), + name: UIResponder.keyboardWillHideNotification, + object: nil + ) + } + @objc func keyboardWillChangeFrame(_ notification: Notification) { + guard let frameEnd = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { + return + } + let convertedFrame = convert(frameEnd, from: nil) + let overlap = max(0, bounds.maxY - convertedFrame.minY) + scrollView.contentInset.bottom = overlap + scrollView.verticalScrollIndicatorInsets.bottom = overlap + } + @objc func keyboardWillHide(_ notification: Notification) { + scrollView.contentInset.bottom = 0 + scrollView.verticalScrollIndicatorInsets.bottom = 0 + } + @objc func backgroundTapped() { + endEditing(true) + } + @objc func doneEditingTapped() { + endEditing(true) + } +} diff --git a/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+LastLoginHint.swift b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+LastLoginHint.swift new file mode 100644 index 00000000..d5e7d29f --- /dev/null +++ b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+LastLoginHint.swift @@ -0,0 +1,55 @@ +import UIKit + +extension FireOnboardingCredentialFormView { + func setupLastLoginHint() { + lastLoginHintLabel.translatesAutoresizingMaskIntoConstraints = false + lastLoginHintLabel.font = .systemFont(ofSize: 12, weight: .regular) + lastLoginHintLabel.textColor = .secondaryLabel + lastLoginHintLabel.textAlignment = .center + lastLoginHintLabel.numberOfLines = 1 + lastLoginHintLabel.isHidden = true + + contentView.addSubview(lastLoginHintLabel) + + NSLayoutConstraint.activate([ + lastLoginHintLabel.topAnchor.constraint(equalTo: loginButton.bottomAnchor, constant: 10), + lastLoginHintLabel.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), + lastLoginHintLabel.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), + ]) + } + func updateLastLoginAppearance() { + let highlightedExternal = lastLoginMethod.flatMap(FireExternalLoginMethod.externalIcon(for:)) + + if let method = lastLoginMethod { + lastLoginHintLabel.isHidden = false + lastLoginHintLabel.text = "上次使用:\(method.displayName)" + } else { + lastLoginHintLabel.isHidden = true + lastLoginHintLabel.text = nil + } + + // Password is a first-class last-login method; emphasize the primary login button. + let passwordWasLast = lastLoginMethod == .password + var loginConfiguration = loginButton.configuration ?? .filled() + loginConfiguration.baseBackgroundColor = .systemOrange + loginConfiguration.baseForegroundColor = .white + if passwordWasLast { + loginConfiguration.background.strokeColor = FireTheme.uiAccent + loginConfiguration.background.strokeWidth = 1.5 + loginButton.accessibilityValue = "上次使用" + } else { + loginConfiguration.background.strokeColor = nil + loginConfiguration.background.strokeWidth = 0 + loginButton.accessibilityValue = nil + } + loginButton.configuration = loginConfiguration + + for (index, button) in externalLoginButtons.enumerated() { + guard FireExternalLoginMethod.allCases.indices.contains(index) else { continue } + let method = FireExternalLoginMethod.allCases[index] + let isLastUsed = method == highlightedExternal + button.configuration = externalLoginConfiguration(for: method, highlighted: isLastUsed) + button.accessibilityValue = isLastUsed ? "上次使用" : nil + } + } +} diff --git a/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+LoginButton.swift b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+LoginButton.swift new file mode 100644 index 00000000..b2f6a8c8 --- /dev/null +++ b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+LoginButton.swift @@ -0,0 +1,37 @@ +import UIKit + +extension FireOnboardingCredentialFormView { + func setupLoginButton() { + loginButton.translatesAutoresizingMaskIntoConstraints = false + var configuration = UIButton.Configuration.filled() + configuration.title = "登录" + configuration.baseBackgroundColor = .systemOrange + configuration.baseForegroundColor = .white + configuration.cornerStyle = .medium + loginButton.configuration = configuration + loginButton.addTarget(self, action: #selector(loginTapped), for: .touchUpInside) + loginButton.fireBindPressBounce(.button) + loginButton.isEnabled = false + + contentView.addSubview(loginButton) + + NSLayoutConstraint.activate([ + loginButton.topAnchor.constraint(equalTo: optionsRow.bottomAnchor, constant: 16), + loginButton.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), + loginButton.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), + loginButton.heightAnchor.constraint(equalToConstant: 50), + ]) + } + @objc func loginTapped() { + guard let identifier = identifierField.text? + .trimmingCharacters(in: .whitespacesAndNewlines), + let password = passwordField.text, + !identifier.isEmpty, + !password.isEmpty + else { + return + } + endEditing(true) + onLoginTapped?(identifier, password, isRememberChecked) + } +} diff --git a/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Options.swift b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Options.swift new file mode 100644 index 00000000..1700bd31 --- /dev/null +++ b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView+Options.swift @@ -0,0 +1,83 @@ +import UIKit + +extension FireOnboardingCredentialFormView { + func setupOptionsRow() { + optionsRow.translatesAutoresizingMaskIntoConstraints = false + + rememberRow.translatesAutoresizingMaskIntoConstraints = false + rememberRow.addTarget(self, action: #selector(rememberTapped), for: .touchUpInside) + rememberRow.accessibilityTraits = .button + + rememberCheckboxButton.translatesAutoresizingMaskIntoConstraints = false + rememberCheckboxButton.isUserInteractionEnabled = false + rememberCheckboxButton.tintColor = FireTheme.uiAccent + rememberCheckboxButton.setContentHuggingPriority(.required, for: .horizontal) + + rememberLabel.translatesAutoresizingMaskIntoConstraints = false + rememberLabel.text = "记住密码" + rememberLabel.font = .systemFont(ofSize: 13, weight: .regular) + rememberLabel.textColor = .secondaryLabel + rememberLabel.isUserInteractionEnabled = false + + forgotPasswordButton.translatesAutoresizingMaskIntoConstraints = false + forgotPasswordButton.setTitle("忘记密码?", for: .normal) + forgotPasswordButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) + forgotPasswordButton.setTitleColor(.systemBlue, for: .normal) + forgotPasswordButton.setTitleColor(.systemBlue.withAlphaComponent(0.55), for: .highlighted) + forgotPasswordButton.contentHorizontalAlignment = .trailing + forgotPasswordButton.addTarget(self, action: #selector(forgotPasswordTapped), for: .touchUpInside) + forgotPasswordButton.fireBindPressBounce(.compact) + forgotPasswordButton.setContentHuggingPriority(.required, for: .horizontal) + forgotPasswordButton.setContentCompressionResistancePriority(.required, for: .horizontal) + + rememberRow.addSubview(rememberCheckboxButton) + rememberRow.addSubview(rememberLabel) + optionsRow.addSubview(rememberRow) + optionsRow.addSubview(forgotPasswordButton) + contentView.addSubview(optionsRow) + + NSLayoutConstraint.activate([ + optionsRow.topAnchor.constraint(equalTo: passwordField.bottomAnchor, constant: 12), + optionsRow.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), + optionsRow.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), + optionsRow.heightAnchor.constraint(equalToConstant: 24), + + rememberRow.leadingAnchor.constraint(equalTo: optionsRow.leadingAnchor), + rememberRow.centerYAnchor.constraint(equalTo: optionsRow.centerYAnchor), + rememberRow.trailingAnchor.constraint(lessThanOrEqualTo: forgotPasswordButton.leadingAnchor, constant: -8), + rememberRow.heightAnchor.constraint(equalTo: optionsRow.heightAnchor), + + rememberCheckboxButton.leadingAnchor.constraint(equalTo: rememberRow.leadingAnchor), + rememberCheckboxButton.centerYAnchor.constraint(equalTo: rememberLabel.centerYAnchor), + rememberCheckboxButton.widthAnchor.constraint(equalToConstant: 16), + rememberCheckboxButton.heightAnchor.constraint(equalToConstant: 16), + + rememberLabel.leadingAnchor.constraint(equalTo: rememberCheckboxButton.trailingAnchor, constant: 5), + rememberLabel.centerYAnchor.constraint(equalTo: rememberRow.centerYAnchor), + rememberLabel.trailingAnchor.constraint(equalTo: rememberRow.trailingAnchor), + + forgotPasswordButton.trailingAnchor.constraint(equalTo: optionsRow.trailingAnchor), + forgotPasswordButton.centerYAnchor.constraint(equalTo: optionsRow.centerYAnchor), + forgotPasswordButton.heightAnchor.constraint(equalTo: optionsRow.heightAnchor), + ]) + } + func updateRememberCheckboxAppearance() { + let symbol = isRememberChecked ? "checkmark.circle.fill" : "circle" + // Match the 13pt label optically; previous 18pt mark dominated the row. + let config = UIImage.SymbolConfiguration(pointSize: 14, weight: .regular) + rememberCheckboxButton.setImage(UIImage(systemName: symbol, withConfiguration: config), for: .normal) + rememberCheckboxButton.tintColor = isRememberChecked ? FireTheme.uiAccent : .tertiaryLabel + rememberCheckboxButton.contentVerticalAlignment = .center + rememberCheckboxButton.contentHorizontalAlignment = .center + rememberRow.accessibilityLabel = isRememberChecked ? "已勾选记住密码" : "记住密码" + rememberRow.accessibilityValue = isRememberChecked ? "已选中" : "未选中" + } + @objc func rememberTapped() { + isRememberChecked.toggle() + updateRememberCheckboxAppearance() + FireMotionHaptics.selection() + } + @objc func forgotPasswordTapped() { + onForgotPassword?() + } +} diff --git a/apps/ios-app/App/Startup/FireOnboardingCredentialFormView.swift b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView.swift index f6d33f3e..23a4b774 100644 --- a/apps/ios-app/App/Startup/FireOnboardingCredentialFormView.swift +++ b/apps/ios-app/App/Startup/FireOnboardingCredentialFormView.swift @@ -6,26 +6,26 @@ final class FireOnboardingCredentialFormView: UIView, UITextFieldDelegate { var onForgotPassword: (() -> Void)? var onExternalLogin: ((FireExternalLoginMethod) -> Void)? - private let scrollView = UIScrollView() - private let contentView = UIView() - private let identifierField = UITextField() - private let passwordField = UITextField() - private let passwordVisibilityButton = UIButton(type: .system) - private let rememberCheckboxButton = UIButton(type: .system) - private let rememberLabel = UILabel() - private let rememberRow = UIControl() - private let optionsRow = UIView() - private let loginButton = UIButton(type: .system) - private let lastLoginHintLabel = UILabel() - private let forgotPasswordButton = UIButton(type: .system) - private let dividerLabel = UILabel() - private let externalLoginStack = UIStackView() - private var externalLoginButtons: [UIButton] = [] - private var isLoggingIn = false - private var isPasswordVisible = false - private var isRememberChecked = false - private var lastLoginMethod: FireLastLoginMethod? - private lazy var keyboardToolbar: UIToolbar = { + let scrollView = UIScrollView() + let contentView = UIView() + let identifierField = UITextField() + let passwordField = UITextField() + let passwordVisibilityButton = UIButton(type: .system) + let rememberCheckboxButton = UIButton(type: .system) + let rememberLabel = UILabel() + let rememberRow = UIControl() + let optionsRow = UIView() + let loginButton = UIButton(type: .system) + let lastLoginHintLabel = UILabel() + let forgotPasswordButton = UIButton(type: .system) + let dividerLabel = UILabel() + let externalLoginStack = UIStackView() + var externalLoginButtons: [UIButton] = [] + var isLoggingIn = false + var isPasswordVisible = false + var isRememberChecked = false + var lastLoginMethod: FireLastLoginMethod? + lazy var keyboardToolbar: UIToolbar = { let toolbar = UIToolbar() toolbar.items = [ UIBarButtonItem(systemItem: .flexibleSpace), @@ -142,319 +142,13 @@ final class FireOnboardingCredentialFormView: UIView, UITextFieldDelegate { } } - private func setupScrollView() { - scrollView.translatesAutoresizingMaskIntoConstraints = false - scrollView.keyboardDismissMode = .interactive - scrollView.alwaysBounceVertical = true - addSubview(scrollView) - - contentView.translatesAutoresizingMaskIntoConstraints = false - scrollView.addSubview(contentView) - - let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped)) - tapGesture.cancelsTouchesInView = false - scrollView.addGestureRecognizer(tapGesture) - - NSLayoutConstraint.activate([ - scrollView.topAnchor.constraint(equalTo: topAnchor), - scrollView.leadingAnchor.constraint(equalTo: leadingAnchor), - scrollView.trailingAnchor.constraint(equalTo: trailingAnchor), - scrollView.bottomAnchor.constraint(equalTo: bottomAnchor), - - contentView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor), - contentView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor), - contentView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor), - contentView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor), - contentView.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor), - ]) - } - - private func setupCredentialFields() { - configureTextField(identifierField, placeholder: "用户名或邮箱", secure: false) - identifierField.returnKeyType = .next - identifierField.delegate = self - identifierField.addTarget(self, action: #selector(textFieldsChanged), for: .editingChanged) - - configureTextField(passwordField, placeholder: "密码", secure: true) - passwordField.returnKeyType = .go - passwordField.delegate = self - passwordField.addTarget(self, action: #selector(textFieldsChanged), for: .editingChanged) - // Eye toggle replaces clear button on the password field. - passwordField.clearButtonMode = .never - passwordField.rightView = makePasswordVisibilityAccessory() - passwordField.rightViewMode = .always - - contentView.addSubview(identifierField) - contentView.addSubview(passwordField) - - NSLayoutConstraint.activate([ - identifierField.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), - identifierField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), - identifierField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), - identifierField.heightAnchor.constraint(equalToConstant: 48), - - passwordField.topAnchor.constraint(equalTo: identifierField.bottomAnchor, constant: 12), - passwordField.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - passwordField.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - passwordField.heightAnchor.constraint(equalToConstant: 48), - ]) - } - - private func configureTextField(_ field: UITextField, placeholder: String, secure: Bool) { - field.translatesAutoresizingMaskIntoConstraints = false - field.placeholder = placeholder - // Custom chrome instead of .roundedRect: system roundedRect sits too dark on - // pure-black onboarding canvas and loses edge definition in dark mode. - field.borderStyle = .none - field.autocapitalizationType = .none - field.autocorrectionType = .no - field.clearButtonMode = .whileEditing - field.isSecureTextEntry = secure - field.textContentType = secure ? .password : .username - field.inputAccessoryView = keyboardToolbar - field.layer.cornerRadius = 10 - field.layer.masksToBounds = true - field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 1)) - field.leftViewMode = .always - applyCredentialFieldChrome(to: field) - } - - private func applyCredentialFieldChrome(to field: UITextField) { - let isDark = traitCollection.userInterfaceStyle == .dark - field.backgroundColor = isDark - ? UIColor.secondarySystemFill - : UIColor.secondarySystemGroupedBackground - field.textColor = .label - field.tintColor = FireTheme.uiAccent - field.layer.borderWidth = 1 - field.layer.borderColor = UIColor.separator.withAlphaComponent(isDark ? 0.7 : 0.45).cgColor - field.attributedPlaceholder = NSAttributedString( - string: field.placeholder ?? "", - attributes: [ - .foregroundColor: UIColor.secondaryLabel.withAlphaComponent(0.85), - .font: UIFont.systemFont(ofSize: 17), - ] - ) - } - - private func restyleCredentialFieldsForCurrentAppearance() { - applyCredentialFieldChrome(to: identifierField) - applyCredentialFieldChrome(to: passwordField) - updatePasswordVisibilityAppearance() - } - - private func makePasswordVisibilityAccessory() -> UIView { - var configuration = UIButton.Configuration.plain() - configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 10) - configuration.preferredSymbolConfigurationForImage = Self.passwordVisibilitySymbolConfiguration - passwordVisibilityButton.configuration = configuration - passwordVisibilityButton.translatesAutoresizingMaskIntoConstraints = false - passwordVisibilityButton.addTarget(self, action: #selector(passwordVisibilityTapped), for: .touchUpInside) - passwordVisibilityButton.accessibilityLabel = "显示密码" - passwordVisibilityButton.fireBindPressBounce(.compact) - - // Slightly wider trailing chrome so the glyph doesn't hug the field edge. - let host = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 40)) - host.addSubview(passwordVisibilityButton) - NSLayoutConstraint.activate([ - passwordVisibilityButton.leadingAnchor.constraint(equalTo: host.leadingAnchor), - passwordVisibilityButton.trailingAnchor.constraint(equalTo: host.trailingAnchor), - passwordVisibilityButton.topAnchor.constraint(equalTo: host.topAnchor), - passwordVisibilityButton.bottomAnchor.constraint(equalTo: host.bottomAnchor), - host.widthAnchor.constraint(equalToConstant: 44), - host.heightAnchor.constraint(equalToConstant: 40), - ]) - return host - } - - private static var passwordVisibilitySymbolConfiguration: UIImage.SymbolConfiguration { + static var passwordVisibilitySymbolConfiguration: UIImage.SymbolConfiguration { let pointSize = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium, scale: .medium) // Hierarchical rendering gives the eyelid/pupil softer depth than flat template monochrome. return pointSize.applying(UIImage.SymbolConfiguration(hierarchicalColor: .tertiaryLabel)) } - private func setupOptionsRow() { - optionsRow.translatesAutoresizingMaskIntoConstraints = false - - rememberRow.translatesAutoresizingMaskIntoConstraints = false - rememberRow.addTarget(self, action: #selector(rememberTapped), for: .touchUpInside) - rememberRow.accessibilityTraits = .button - - rememberCheckboxButton.translatesAutoresizingMaskIntoConstraints = false - rememberCheckboxButton.isUserInteractionEnabled = false - rememberCheckboxButton.tintColor = FireTheme.uiAccent - rememberCheckboxButton.setContentHuggingPriority(.required, for: .horizontal) - - rememberLabel.translatesAutoresizingMaskIntoConstraints = false - rememberLabel.text = "记住密码" - rememberLabel.font = .systemFont(ofSize: 13, weight: .regular) - rememberLabel.textColor = .secondaryLabel - rememberLabel.isUserInteractionEnabled = false - - forgotPasswordButton.translatesAutoresizingMaskIntoConstraints = false - forgotPasswordButton.setTitle("忘记密码?", for: .normal) - forgotPasswordButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) - forgotPasswordButton.setTitleColor(.systemBlue, for: .normal) - forgotPasswordButton.setTitleColor(.systemBlue.withAlphaComponent(0.55), for: .highlighted) - forgotPasswordButton.contentHorizontalAlignment = .trailing - forgotPasswordButton.addTarget(self, action: #selector(forgotPasswordTapped), for: .touchUpInside) - forgotPasswordButton.fireBindPressBounce(.compact) - forgotPasswordButton.setContentHuggingPriority(.required, for: .horizontal) - forgotPasswordButton.setContentCompressionResistancePriority(.required, for: .horizontal) - - rememberRow.addSubview(rememberCheckboxButton) - rememberRow.addSubview(rememberLabel) - optionsRow.addSubview(rememberRow) - optionsRow.addSubview(forgotPasswordButton) - contentView.addSubview(optionsRow) - - NSLayoutConstraint.activate([ - optionsRow.topAnchor.constraint(equalTo: passwordField.bottomAnchor, constant: 12), - optionsRow.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - optionsRow.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - optionsRow.heightAnchor.constraint(equalToConstant: 24), - - rememberRow.leadingAnchor.constraint(equalTo: optionsRow.leadingAnchor), - rememberRow.centerYAnchor.constraint(equalTo: optionsRow.centerYAnchor), - rememberRow.trailingAnchor.constraint(lessThanOrEqualTo: forgotPasswordButton.leadingAnchor, constant: -8), - rememberRow.heightAnchor.constraint(equalTo: optionsRow.heightAnchor), - - rememberCheckboxButton.leadingAnchor.constraint(equalTo: rememberRow.leadingAnchor), - rememberCheckboxButton.centerYAnchor.constraint(equalTo: rememberLabel.centerYAnchor), - rememberCheckboxButton.widthAnchor.constraint(equalToConstant: 16), - rememberCheckboxButton.heightAnchor.constraint(equalToConstant: 16), - - rememberLabel.leadingAnchor.constraint(equalTo: rememberCheckboxButton.trailingAnchor, constant: 5), - rememberLabel.centerYAnchor.constraint(equalTo: rememberRow.centerYAnchor), - rememberLabel.trailingAnchor.constraint(equalTo: rememberRow.trailingAnchor), - - forgotPasswordButton.trailingAnchor.constraint(equalTo: optionsRow.trailingAnchor), - forgotPasswordButton.centerYAnchor.constraint(equalTo: optionsRow.centerYAnchor), - forgotPasswordButton.heightAnchor.constraint(equalTo: optionsRow.heightAnchor), - ]) - } - - private func setupLoginButton() { - loginButton.translatesAutoresizingMaskIntoConstraints = false - var configuration = UIButton.Configuration.filled() - configuration.title = "登录" - configuration.baseBackgroundColor = .systemOrange - configuration.baseForegroundColor = .white - configuration.cornerStyle = .medium - loginButton.configuration = configuration - loginButton.addTarget(self, action: #selector(loginTapped), for: .touchUpInside) - loginButton.fireBindPressBounce(.button) - loginButton.isEnabled = false - - contentView.addSubview(loginButton) - - NSLayoutConstraint.activate([ - loginButton.topAnchor.constraint(equalTo: optionsRow.bottomAnchor, constant: 16), - loginButton.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - loginButton.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - loginButton.heightAnchor.constraint(equalToConstant: 50), - ]) - } - - private func setupLastLoginHint() { - lastLoginHintLabel.translatesAutoresizingMaskIntoConstraints = false - lastLoginHintLabel.font = .systemFont(ofSize: 12, weight: .regular) - lastLoginHintLabel.textColor = .secondaryLabel - lastLoginHintLabel.textAlignment = .center - lastLoginHintLabel.numberOfLines = 1 - lastLoginHintLabel.isHidden = true - - contentView.addSubview(lastLoginHintLabel) - - NSLayoutConstraint.activate([ - lastLoginHintLabel.topAnchor.constraint(equalTo: loginButton.bottomAnchor, constant: 10), - lastLoginHintLabel.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - lastLoginHintLabel.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - ]) - } - - private func setupExternalLoginMethods() { - dividerLabel.translatesAutoresizingMaskIntoConstraints = false - dividerLabel.text = "- 其他方式 -" - dividerLabel.font = .systemFont(ofSize: 13) - dividerLabel.textColor = .tertiaryLabel - dividerLabel.textAlignment = .center - - externalLoginStack.translatesAutoresizingMaskIntoConstraints = false - externalLoginStack.axis = .horizontal - externalLoginStack.alignment = .fill - externalLoginStack.distribution = .fillEqually - externalLoginStack.spacing = 8 - - for method in FireExternalLoginMethod.allCases { - let button = makeExternalLoginButton(for: method) - externalLoginButtons.append(button) - externalLoginStack.addArrangedSubview(button) - } - - contentView.addSubview(dividerLabel) - contentView.addSubview(externalLoginStack) - - NSLayoutConstraint.activate([ - dividerLabel.topAnchor.constraint(equalTo: lastLoginHintLabel.bottomAnchor, constant: 18), - dividerLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - - externalLoginStack.topAnchor.constraint(equalTo: dividerLabel.bottomAnchor, constant: 14), - externalLoginStack.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - externalLoginStack.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - externalLoginStack.heightAnchor.constraint(equalToConstant: 52), - externalLoginStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -32), - ]) - } - - private func makeExternalLoginButton(for method: FireExternalLoginMethod) -> UIButton { - let button = UIButton(type: .system) - button.translatesAutoresizingMaskIntoConstraints = false - button.accessibilityLabel = method.accessibilityLabel - button.tag = FireExternalLoginMethod.allCases.firstIndex(of: method) ?? 0 - button.configuration = externalLoginConfiguration(for: method, highlighted: false) - button.addTarget(self, action: #selector(externalLoginTapped(_:)), for: .touchUpInside) - button.fireBindPressBounce(.compact) - return button - } - - private func externalLoginConfiguration( - for method: FireExternalLoginMethod, - highlighted: Bool - ) -> UIButton.Configuration { - var configuration = UIButton.Configuration.plain() - configuration.image = method.iconImage - // Elevated chip that stays readable on both light canvas and pure black dark canvas. - configuration.background.backgroundColor = UIColor { traits in - traits.userInterfaceStyle == .dark - ? UIColor.secondarySystemFill - : UIColor.secondarySystemGroupedBackground - } - configuration.background.cornerRadius = 14 - configuration.background.strokeColor = highlighted - ? FireTheme.uiAccent - : UIColor.separator.withAlphaComponent(0.55) - configuration.background.strokeWidth = highlighted ? 1.5 : 1 - configuration.contentInsets = NSDirectionalEdgeInsets(top: 12, leading: 10, bottom: 12, trailing: 10) - return configuration - } - - private func observeKeyboardNotifications() { - NotificationCenter.default.addObserver( - self, - selector: #selector(keyboardWillChangeFrame(_:)), - name: UIResponder.keyboardWillChangeFrameNotification, - object: nil - ) - NotificationCenter.default.addObserver( - self, - selector: #selector(keyboardWillHide(_:)), - name: UIResponder.keyboardWillHideNotification, - object: nil - ) - } - - private func updateLoginButtonState() { + func updateLoginButtonState() { guard !isLoggingIn else { return } let hasIdentifier = !(identifierField.text? .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true) @@ -462,73 +156,6 @@ final class FireOnboardingCredentialFormView: UIView, UITextFieldDelegate { loginButton.isEnabled = hasIdentifier && hasPassword } - private func updateRememberCheckboxAppearance() { - let symbol = isRememberChecked ? "checkmark.circle.fill" : "circle" - // Match the 13pt label optically; previous 18pt mark dominated the row. - let config = UIImage.SymbolConfiguration(pointSize: 14, weight: .regular) - rememberCheckboxButton.setImage(UIImage(systemName: symbol, withConfiguration: config), for: .normal) - rememberCheckboxButton.tintColor = isRememberChecked ? FireTheme.uiAccent : .tertiaryLabel - rememberCheckboxButton.contentVerticalAlignment = .center - rememberCheckboxButton.contentHorizontalAlignment = .center - rememberRow.accessibilityLabel = isRememberChecked ? "已勾选记住密码" : "记住密码" - rememberRow.accessibilityValue = isRememberChecked ? "已选中" : "未选中" - } - - private func updatePasswordVisibilityAppearance() { - // Prefer the filled pair — reads cleaner at small sizes than the outline glyphs. - let symbol = isPasswordVisible ? "eye.slash.fill" : "eye.fill" - let image = UIImage(systemName: symbol, withConfiguration: Self.passwordVisibilitySymbolConfiguration)? - .withRenderingMode(.alwaysTemplate) - - var configuration = passwordVisibilityButton.configuration ?? .plain() - configuration.image = image - configuration.baseForegroundColor = UIColor { traits in - traits.userInterfaceStyle == .dark - ? UIColor.tertiaryLabel - : UIColor.secondaryLabel.withAlphaComponent(0.85) - } - configuration.preferredSymbolConfigurationForImage = Self.passwordVisibilitySymbolConfiguration - configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 10) - passwordVisibilityButton.configuration = configuration - passwordVisibilityButton.accessibilityLabel = isPasswordVisible ? "隐藏密码" : "显示密码" - } - - private func updateLastLoginAppearance() { - let highlightedExternal = lastLoginMethod.flatMap(FireExternalLoginMethod.externalIcon(for:)) - - if let method = lastLoginMethod { - lastLoginHintLabel.isHidden = false - lastLoginHintLabel.text = "上次使用:\(method.displayName)" - } else { - lastLoginHintLabel.isHidden = true - lastLoginHintLabel.text = nil - } - - // Password is a first-class last-login method; emphasize the primary login button. - let passwordWasLast = lastLoginMethod == .password - var loginConfiguration = loginButton.configuration ?? .filled() - loginConfiguration.baseBackgroundColor = .systemOrange - loginConfiguration.baseForegroundColor = .white - if passwordWasLast { - loginConfiguration.background.strokeColor = FireTheme.uiAccent - loginConfiguration.background.strokeWidth = 1.5 - loginButton.accessibilityValue = "上次使用" - } else { - loginConfiguration.background.strokeColor = nil - loginConfiguration.background.strokeWidth = 0 - loginButton.accessibilityValue = nil - } - loginButton.configuration = loginConfiguration - - for (index, button) in externalLoginButtons.enumerated() { - guard FireExternalLoginMethod.allCases.indices.contains(index) else { continue } - let method = FireExternalLoginMethod.allCases[index] - let isLastUsed = method == highlightedExternal - button.configuration = externalLoginConfiguration(for: method, highlighted: isLastUsed) - button.accessibilityValue = isLastUsed ? "上次使用" : nil - } - } - override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else { @@ -540,76 +167,6 @@ final class FireOnboardingCredentialFormView: UIView, UITextFieldDelegate { restyleCredentialFieldsForCurrentAppearance() } - @objc private func keyboardWillChangeFrame(_ notification: Notification) { - guard let frameEnd = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { - return - } - let convertedFrame = convert(frameEnd, from: nil) - let overlap = max(0, bounds.maxY - convertedFrame.minY) - scrollView.contentInset.bottom = overlap - scrollView.verticalScrollIndicatorInsets.bottom = overlap - } - - @objc private func keyboardWillHide(_ notification: Notification) { - scrollView.contentInset.bottom = 0 - scrollView.verticalScrollIndicatorInsets.bottom = 0 - } - - @objc private func textFieldsChanged() { - updateLoginButtonState() - } - - @objc private func backgroundTapped() { - endEditing(true) - } - - @objc private func doneEditingTapped() { - endEditing(true) - } - - @objc private func rememberTapped() { - isRememberChecked.toggle() - updateRememberCheckboxAppearance() - FireMotionHaptics.selection() - } - - @objc private func passwordVisibilityTapped() { - isPasswordVisible.toggle() - // Preserve caret / text when flipping secure entry (UIKit quirk). - let wasFirstResponder = passwordField.isFirstResponder - let existing = passwordField.text - passwordField.isSecureTextEntry = !isPasswordVisible - passwordField.text = nil - passwordField.text = existing - if wasFirstResponder { - passwordField.becomeFirstResponder() - } - updatePasswordVisibilityAppearance() - } - - @objc private func loginTapped() { - guard let identifier = identifierField.text? - .trimmingCharacters(in: .whitespacesAndNewlines), - let password = passwordField.text, - !identifier.isEmpty, - !password.isEmpty - else { - return - } - endEditing(true) - onLoginTapped?(identifier, password, isRememberChecked) - } - - @objc private func forgotPasswordTapped() { - onForgotPassword?() - } - - @objc private func externalLoginTapped(_ sender: UIButton) { - let methods = FireExternalLoginMethod.allCases - guard methods.indices.contains(sender.tag) else { return } - onExternalLogin?(methods[sender.tag]) - } - func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField === identifierField { passwordField.becomeFirstResponder() diff --git a/apps/ios-app/App/Stores/FireHomeFeedSession.swift b/apps/ios-app/App/Stores/FireHomeFeedSession.swift new file mode 100644 index 00000000..1ea9b16f --- /dev/null +++ b/apps/ios-app/App/Stores/FireHomeFeedSession.swift @@ -0,0 +1,788 @@ +import Foundation + +@MainActor +final class FireHomeFeedSession { + private static let topicListRefreshLoadingPollInterval: Duration = .milliseconds(250) + + private struct TopicRowsMergeResult: Sendable { + let rows: [FireTopicRowPresentation] + let entities: FireEntityIndex + let order: FireOrderedIDList + let contentTokens: [UInt64: String] + } + + private weak var store: FireHomeFeedStore? + private let appViewModel: FireAppViewModel + private let topicListRefreshClock = ContinuousClock() + private var pendingTopicListRefreshTask: Task? + private var filterChangeRefreshTask: Task? + private var topicListMessageBusRefreshController = FireTopicListMessageBusRefreshController() + private var topicEntities = FireEntityIndex() + private var topicOrder = FireOrderedIDList() + private var topicRowContentTokensByID: [UInt64: String] = [:] + private var renderedTopicListScope: FireTopicListRefreshScope? + private var isTopicListVisible = false + private var isSceneActive = false + + init(appViewModel: FireAppViewModel) { + self.appViewModel = appViewModel + } + + func attach(store: FireHomeFeedStore) { + self.store = store + } + + var hasResolvedCurrentScope: Bool { + guard store != nil else { return false } + return renderedTopicListScope == currentTopicListRefreshScope + } + + func categoryPresentation(for categoryID: UInt64?) -> FireTopicCategoryPresentation? { + guard let categoryID else { return nil } + return store?.topicCategories[categoryID] + } + + func topicRow(for topicID: UInt64) -> FireTopicRowPresentation? { + topicEntities.entity(for: topicID) + } + + func topicRowContentToken(for topicID: UInt64) -> String? { + topicRowContentTokensByID[topicID] + } + + func updateVisibleTopicIDs(_ topicIDs: Set) { + guard let store else { return } + store.visibleTopicIDs = Self.sanitizedVisibleTopicIDs( + currentTopicIDs: store.topicRows.map(\.topic.id), + candidateVisibleTopicIDs: topicIDs + ) + } + + func setTopicListVisible(_ isVisible: Bool) { + guard isTopicListVisible != isVisible else { return } + isTopicListVisible = isVisible + if !isVisible { + cancelPendingTopicListRefresh() + } + } + + func setSceneActive(_ isActive: Bool) { + guard isSceneActive != isActive else { return } + isSceneActive = isActive + if !isActive { + cancelPendingTopicListRefresh() + } + } + + func applySession(_ session: SessionState) { + guard let store else { return } + store.allCategories = session.bootstrap.categories + store.topicCategories = Dictionary( + uniqueKeysWithValues: session.bootstrap.categories.map { ($0.id, $0) } + ) + store.topTags = session.bootstrap.topTags + store.canTagTopics = session.bootstrap.canTagTopics + + guard session.readiness.canReadAuthenticatedApi else { + reset(resetTopicKind: true) + return + } + } + + @discardableResult + func applyHomeRowCountPatch(_ patch: TopicHomeRowCountPatchState) -> Bool { + guard let store, + let row = topicEntities.entity(for: patch.topicId), + let patched = Self.applyHomeRowCountPatch(row, patch: patch) else { + return false + } + + topicEntities.upsert([patched], id: \.topic.id) + let rows = topicEntities.orderedValues(for: topicOrder) + store.topicRows = rows + topicRowContentTokensByID[patch.topicId] = Self.makeTopicRowContentToken( + patched, + category: categoryPresentation(for: patched.topic.categoryId) + ) + store.visibleTopicIDs = Self.sanitizedVisibleTopicIDs( + currentTopicIDs: rows.map(\.topic.id), + candidateVisibleTopicIDs: store.visibleTopicIDs + ) + return true + } + + func selectTopicKind(_ kind: TopicListKindState) { + guard let store, store.selectedTopicKind != kind else { return } + store.selectedTopicKind = kind + clearLoadFailure() + syncCurrentHomeTopicListScope() + scheduleDebouncedRefresh() + } + + func selectHomeCategory(_ categoryID: UInt64?) { + guard let store, store.selectedHomeCategoryId != categoryID else { return } + store.selectedHomeCategoryId = categoryID + store.selectedHomeTags = [] + clearLoadFailure() + syncCurrentHomeTopicListScope() + scheduleDebouncedRefresh() + } + + func addHomeTag(_ tag: String) { + guard let store, !store.selectedHomeTags.contains(tag) else { return } + store.selectedHomeTags.append(tag) + clearLoadFailure() + syncCurrentHomeTopicListScope() + scheduleDebouncedRefresh() + } + + func removeHomeTag(_ tag: String) { + guard let store, store.selectedHomeTags.contains(tag) else { return } + store.selectedHomeTags.removeAll { $0 == tag } + clearLoadFailure() + syncCurrentHomeTopicListScope() + scheduleDebouncedRefresh() + } + + func clearHomeTags() { + guard let store, !store.selectedHomeTags.isEmpty else { return } + store.selectedHomeTags = [] + clearLoadFailure() + syncCurrentHomeTopicListScope() + scheduleDebouncedRefresh() + } + + func refreshTopics() { + Task { + await refreshTopicsAsync() + } + } + + func refreshTopicsAsync() async { + await refreshTopicsIfPossible(force: true) + } + + func applyTopicList(_ state: TopicListState) { + Task { @MainActor [weak self] in + guard let self, let store = self.store else { return } + let mergeResult = await self.prepareTopicRowsMerge( + incoming: state.rows, + reset: true, + usesIncrementalRefresh: false + ) + self.applyTopicRows(mergeResult) + self.renderedTopicListScope = self.currentTopicListRefreshScope + store.topicLoadErrorMessage = nil + store.topicLoadErrorIsCloudflare = false + store.isOffline = state.isCached + store.moreTopicsUrl = state.moreTopicsUrl + store.nextTopicsPage = state.nextPage + store.isLoadingTopics = false + store.isAppendingTopics = false + self.appViewModel.updateWidgetData() + } + } + + @discardableResult + func refreshTopicsIfPossible(force: Bool) async -> Bool { + cancelPendingTopicListRefresh() + return await loadTopics(page: nil, reset: true, force: force, refreshMode: .full) + } + + func loadMoreTopics() { + guard let store, let nextTopicsPage = store.currentScopeNextTopicsPage else { return } + Task { + await loadTopics(page: nextTopicsPage, reset: false, force: true) + } + } + + func handleTopicListMessageBusEvent(_ event: MessageBusEventState) { + guard let store, let busKind = event.topicListKind else { return } + let scope = currentTopicListRefreshScope + guard busKind == scope.kind else { return } + + let allowIncremental = Self.canScheduleIncrementalMessageBusRefresh( + scope: scope, + renderedScope: renderedTopicListScope, + isTopicListVisible: isTopicListVisible, + isSceneActive: isSceneActive, + hasRows: !store.topicRows.isEmpty + ) + guard let delay = topicListMessageBusRefreshController.register( + event: event, + for: scope, + now: topicListRefreshClock.now, + allowIncremental: allowIncremental + ) else { + return + } + + pendingTopicListRefreshTask?.cancel() + pendingTopicListRefreshTask = Task { [weak self] in + do { + try await Task.sleep(for: delay) + } catch { + return + } + + guard let self else { return } + while self.store?.isLoadingTopics == true { + do { + try await Task.sleep(for: Self.topicListRefreshLoadingPollInterval) + } catch { + return + } + } + + let scope = self.currentTopicListRefreshScope + let refreshMode = self.topicListMessageBusRefreshController.takePendingRefresh(for: scope) + self.pendingTopicListRefreshTask = nil + guard let refreshMode else { return } + await self.refreshTopicsFromMessageBus(refreshMode) + } + } + + func handleMessageBusStopped() { + cancelPendingTopicListRefresh() + } + + func reset(resetTopicKind: Bool = true) { + guard let store else { return } + cancelPendingTopicListRefresh() + filterChangeRefreshTask?.cancel() + filterChangeRefreshTask = nil + topicEntities.removeAll() + topicOrder.removeAll() + topicRowContentTokensByID = [:] + store.topicRows = [] + store.moreTopicsUrl = nil + store.nextTopicsPage = nil + store.isLoadingTopics = false + store.isAppendingTopics = false + store.topicLoadErrorMessage = nil + store.topicLoadErrorIsCloudflare = false + store.isOffline = false + renderedTopicListScope = nil + store.selectedHomeCategoryId = nil + store.selectedHomeTags = [] + if resetTopicKind { + store.selectedTopicKind = .latest + } + } + + func clearTopicLoadError() { + store?.topicLoadErrorMessage = nil + store?.topicLoadErrorIsCloudflare = false + } + + private var currentTopicListRefreshScope: FireTopicListRefreshScope { + guard let store else { + return FireTopicListRefreshScope(kind: .latest, categoryId: nil, tags: []) + } + return FireTopicListRefreshScope( + kind: store.selectedTopicKind, + categoryId: store.selectedHomeCategoryId, + tags: store.selectedHomeTags + ) + } + + private func applyCurrentTopicListRefreshScope(_ scope: FireTopicListRefreshScope) { + store?.selectedTopicKind = scope.kind + store?.selectedHomeCategoryId = scope.categoryId + store?.selectedHomeTags = scope.tags + } + + private func clearLoadFailure() { + store?.topicLoadErrorMessage = nil + store?.topicLoadErrorIsCloudflare = false + store?.isOffline = false + } + + private func syncCurrentHomeTopicListScope() { + let scope = currentTopicListRefreshScope + Task { [weak self] in + guard let self else { return } + do { + let sessionStore = try await appViewModel.sessionStoreValue() + let updated = try await sessionStore.setCurrentHomeTopicListScope(scope.state) + await MainActor.run { + self.applyCurrentTopicListRefreshScope(FireTopicListRefreshScope(updated)) + } + } catch { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: "home.feed", + message: "failed to sync home topic list scope: \(error.localizedDescription)" + ) + } + } + } + + private func scheduleDebouncedRefresh() { + cancelPendingTopicListRefresh() + filterChangeRefreshTask?.cancel() + filterChangeRefreshTask = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(300)) + guard !Task.isCancelled, let self else { return } + await self.refreshTopicsIfPossible(force: true) + } + } + + private func refreshTopicsFromMessageBus(_ refreshMode: FireTopicListMessageBusRefreshMode) async { + guard let store, + case .incremental = refreshMode, + Self.canScheduleIncrementalMessageBusRefresh( + scope: currentTopicListRefreshScope, + renderedScope: renderedTopicListScope, + isTopicListVisible: isTopicListVisible, + isSceneActive: isSceneActive, + hasRows: !store.topicRows.isEmpty + ) else { + return + } + await loadTopics(page: nil, reset: true, force: true, refreshMode: refreshMode) + } + + nonisolated static func canScheduleIncrementalMessageBusRefresh( + scope: FireTopicListRefreshScope, + renderedScope: FireTopicListRefreshScope?, + isTopicListVisible: Bool, + isSceneActive: Bool, + hasRows: Bool + ) -> Bool { + isSceneActive + && isTopicListVisible + && hasRows + && scope.supportsIncrementalMessageBusRefresh + && renderedScope == scope + } + + @discardableResult + private func loadTopics( + page: UInt32?, + reset: Bool, + force: Bool, + refreshMode: FireTopicListMessageBusRefreshMode = .full + ) async -> Bool { + guard let store else { return false } + if !appViewModel.session.readiness.canReadAuthenticatedApi { + self.reset(resetTopicKind: true) + return false + } + if store.isLoadingTopics { + return false + } + if reset && !force && !store.topicRows.isEmpty { + return false + } + + store.isLoadingTopics = true + store.isAppendingTopics = !reset + store.topicLoadErrorMessage = nil + store.topicLoadErrorIsCloudflare = false + if reset { + store.isOffline = false + } + defer { + store.isLoadingTopics = false + store.isAppendingTopics = false + } + + do { + let sessionStore = try await appViewModel.sessionStoreValue() + let requestedScopeState = try await sessionStore.setCurrentHomeTopicListScope( + currentTopicListRefreshScope.state + ) + let requestedScope = FireTopicListRefreshScope(requestedScopeState) + applyCurrentTopicListRefreshScope(requestedScope) + let requestedKind = requestedScope.kind + let categoryID = requestedScope.categoryId + let requestedTags = requestedScope.tags + let categorySlug = categoryID.flatMap { categoryPresentation(for: $0)?.slug } + let parentSlug: String? = categoryID.flatMap { id in + guard let category = categoryPresentation(for: id), + let parentID = category.parentCategoryId else { + return nil + } + return categoryPresentation(for: parentID)?.slug + } + let primaryTag = requestedTags.first + let additionalTags = requestedTags.count > 1 ? Array(requestedTags.dropFirst()) : [] + let incrementalTopicIDs: [UInt64] + switch refreshMode { + case .full: + incrementalTopicIDs = [] + case .incremental(let topicIDs): + incrementalTopicIDs = topicIDs + } + let usesIncrementalRefresh = page == nil + && reset + && !incrementalTopicIDs.isEmpty + && requestedScope.supportsIncrementalMessageBusRefresh + && renderedTopicListScope == requestedScope + && !store.topicRows.isEmpty + let topicListQuery = TopicListQueryState( + kind: requestedKind, + page: page, + topicIds: usesIncrementalRefresh ? incrementalTopicIDs : [], + order: nil, + ascending: nil, + categorySlug: categorySlug, + categoryId: categoryID, + parentCategorySlug: parentSlug, + tag: primaryTag, + additionalTags: additionalTags, + matchAllTags: !additionalTags.isEmpty + ) + let recoveryURL = appViewModel.cloudflareRecoveryTopicListURL(query: topicListQuery) + let fetch: () async throws -> TopicListState = { + try await sessionStore.fetchTopicList(query: topicListQuery) + } + let operationDescription = (page == nil && reset) + ? "刷新首页话题列表" + : "加载更多首页话题" + let fetchWithRecovery: () async throws -> TopicListState = { + try await self.appViewModel.performWithCloudflareRecovery( + operation: operationDescription, + originURL: recoveryURL, + work: fetch + ) + } + + let response: TopicListState + if reset && page == nil && requestedKind == .latest { + response = try await FireAPMManager.shared.withSpan( + .feedLatestInitialLoad, + metadata: [ + "category_id": categoryID.map(String.init) ?? "none", + "tag": primaryTag ?? "none", + "incremental": usesIncrementalRefresh ? "true" : "false", + ], + operation: fetchWithRecovery + ) + } else { + response = try await fetchWithRecovery() + } + + guard requestedScope == currentTopicListRefreshScope else { + return false + } + + let mergeResult = await prepareTopicRowsMerge( + incoming: response.rows, + reset: reset, + usesIncrementalRefresh: usesIncrementalRefresh + ) + applyTopicRows(mergeResult) + renderedTopicListScope = requestedScope + store.topicLoadErrorMessage = nil + store.topicLoadErrorIsCloudflare = false + store.isOffline = response.isCached + if reset && page == nil { + appViewModel.updateWidgetData() + } + if !usesIncrementalRefresh { + store.moreTopicsUrl = response.moreTopicsUrl + store.nextTopicsPage = response.nextPage + } + + appViewModel.pruneTopicDetailState(retainingVisibleTopicIDs: store.visibleTopicIDs) + + if reset && page == nil { + topicListMessageBusRefreshController.markRefreshCompleted( + for: requestedScope, + at: topicListRefreshClock.now + ) + Task { [appViewModel] in + await appViewModel.ensureMessageBusActiveIfPossible() + } + } + return true + } catch { + let recoveryOperationDescription = (page == nil && reset) + ? "刷新首页话题列表" + : "加载更多首页话题" + if await appViewModel.attemptReadPathLoginRecovery( + operation: recoveryOperationDescription, + error: error + ) { + store.isLoadingTopics = false + store.isAppendingTopics = false + return await loadTopics( + page: page, + reset: reset, + force: true, + refreshMode: refreshMode + ) + } + if !force, case FireUniFfiError.StaleSessionResponse = error { + store.isLoadingTopics = false + store.isAppendingTopics = false + return await loadTopics( + page: page, + reset: reset, + force: true, + refreshMode: refreshMode + ) + } + if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { + return false + } + if FireAppViewModel.isCloudflareChallengeError(error) { + let reason = FireAppViewModel.cloudflareChallengeReason(from: error) + store.topicLoadErrorIsCloudflare = true + store.topicLoadErrorMessage = Self.cloudflareErrorMessage(reason: reason) + } else { + store.topicLoadErrorIsCloudflare = false + store.topicLoadErrorMessage = error.localizedDescription + } + return false + } + } + + private static func cloudflareErrorMessage(reason: String) -> String { + switch reason { + case "in_progress": + return "正在完成 Cloudflare 验证,请稍候" + case "cooldown": + return "Cloudflare 验证暂时冷却中,可点横幅重试验证" + case "cancelled": + return "已取消 Cloudflare 验证,可点横幅重新验证" + case "background_suppressed": + return "后台请求遇到 Cloudflare 验证,可点横幅手动验证" + case "failed": + return "Cloudflare 验证未完成,可点横幅重试" + default: + return "需要完成 Cloudflare 验证,可点横幅立即验证" + } + } + + private func cancelPendingTopicListRefresh() { + pendingTopicListRefreshTask?.cancel() + pendingTopicListRefreshTask = nil + topicListMessageBusRefreshController.clearPending(for: currentTopicListRefreshScope) + } + + private func applyTopicRows(_ result: TopicRowsMergeResult) { + guard let store else { return } + topicEntities = result.entities + topicOrder = result.order + store.topicRows = result.rows + topicRowContentTokensByID = result.contentTokens + store.visibleTopicIDs = Self.sanitizedVisibleTopicIDs( + currentTopicIDs: result.rows.map(\.topic.id), + candidateVisibleTopicIDs: store.visibleTopicIDs + ) + } + + private func prepareTopicRowsMerge( + incoming: [FireTopicRowPresentation], + reset: Bool, + usesIncrementalRefresh: Bool + ) async -> TopicRowsMergeResult { + guard let store else { + return TopicRowsMergeResult( + rows: [], + entities: FireEntityIndex(), + order: FireOrderedIDList(), + contentTokens: [:] + ) + } + let existingRows = store.topicRows + let existingEntities = topicEntities + let existingOrder = topicOrder + let previousTokens = topicRowContentTokensByID + let categories = store.topicCategories + + return await Task.detached(priority: .userInitiated) { + Self.mergeTopicRows( + incoming: incoming, + existingRows: existingRows, + existingEntities: existingEntities, + existingOrder: existingOrder, + previousTokens: previousTokens, + categories: categories, + reset: reset, + usesIncrementalRefresh: usesIncrementalRefresh + ) + }.value + } + + nonisolated private static func mergeTopicRows( + incoming: [FireTopicRowPresentation], + existingRows: [FireTopicRowPresentation], + existingEntities: FireEntityIndex, + existingOrder: FireOrderedIDList, + previousTokens: [UInt64: String], + categories: [UInt64: FireTopicCategoryPresentation], + reset: Bool, + usesIncrementalRefresh: Bool + ) -> TopicRowsMergeResult { + let dirtyTopicIDs = Set(incoming.map(\.topic.id)) + let rebuildAllTokens: Bool + let rows: [FireTopicRowPresentation] + let entities: FireEntityIndex + let order: FireOrderedIDList + + if reset { + if usesIncrementalRefresh { + let mergedRows = FireTopicListMessageBusRefreshMerger.merge( + existing: existingRows, + incoming: incoming + ) + var nextEntities = FireEntityIndex() + nextEntities.replaceAll(mergedRows, id: \.topic.id) + rows = mergedRows + entities = nextEntities + order = FireOrderedIDList(ids: mergedRows.map(\.topic.id)) + rebuildAllTokens = false + } else { + var nextEntities = FireEntityIndex() + nextEntities.replaceAll(incoming, id: \.topic.id) + rows = incoming + entities = nextEntities + order = FireOrderedIDList(ids: incoming.map(\.topic.id)) + rebuildAllTokens = true + } + } else { + var nextEntities = existingEntities + nextEntities.upsert(incoming, id: \.topic.id) + var nextOrder = existingOrder + nextOrder.append(incoming.map(\.topic.id)) + rows = nextEntities.orderedValues(for: nextOrder) + entities = nextEntities + order = nextOrder + rebuildAllTokens = false + } + + let contentTokens = buildTopicRowContentTokens( + rows: rows, + dirtyTopicIDs: dirtyTopicIDs, + rebuildAll: rebuildAllTokens, + previousTokens: previousTokens, + categories: categories + ) + return TopicRowsMergeResult( + rows: rows, + entities: entities, + order: order, + contentTokens: contentTokens + ) + } + + nonisolated private static func buildTopicRowContentTokens( + rows: [FireTopicRowPresentation], + dirtyTopicIDs: Set, + rebuildAll: Bool, + previousTokens: [UInt64: String], + categories: [UInt64: FireTopicCategoryPresentation] + ) -> [UInt64: String] { + let currentTopicIDs = Set(rows.map(\.topic.id)) + var nextTokens: [UInt64: String] + if rebuildAll { + nextTokens = [:] + nextTokens.reserveCapacity(rows.count) + } else { + nextTokens = previousTokens.filter { currentTopicIDs.contains($0.key) } + } + + for row in rows where rebuildAll || dirtyTopicIDs.contains(row.topic.id) { + let category = row.topic.categoryId.flatMap { categories[$0] } + nextTokens[row.topic.id] = makeTopicRowContentToken(row, category: category) + } + return nextTokens + } + + nonisolated static func sanitizedVisibleTopicIDs( + currentTopicIDs: [UInt64], + candidateVisibleTopicIDs: Set + ) -> Set { + candidateVisibleTopicIDs.intersection(currentTopicIDs) + } + + nonisolated static func applyHomeRowCountPatch( + _ row: FireTopicRowPresentation, + patch: TopicHomeRowCountPatchState + ) -> FireTopicRowPresentation? { + guard row.topic.id == patch.topicId else { return nil } + let (unreadPosts, newPosts, hasUnreadPosts) = unreadCounts( + hasUnreadPosts: row.hasUnreadPosts, + decision: patch.unread, + unreadPosts: row.topic.unreadPosts, + newPosts: row.topic.newPosts + ) + guard row.topic.postsCount != patch.postsCount + || row.topic.replyCount != patch.replyCount + || row.topic.views != patch.views + || row.topic.lastReadPostNumber != patch.lastReadPostNumber + || row.topic.highestPostNumber != patch.highestPostNumber + || row.topic.unreadPosts != unreadPosts + || row.topic.newPosts != newPosts + || row.hasUnreadPosts != hasUnreadPosts else { + return nil + } + var patched = row + patched.topic.postsCount = patch.postsCount + patched.topic.replyCount = patch.replyCount + patched.topic.views = patch.views + patched.topic.lastReadPostNumber = patch.lastReadPostNumber + patched.topic.highestPostNumber = patch.highestPostNumber + patched.topic.unreadPosts = unreadPosts + patched.topic.newPosts = newPosts + patched.hasUnreadPosts = hasUnreadPosts + return patched + } + + nonisolated private static func unreadCounts( + hasUnreadPosts: Bool, + decision: TopicHomeUnreadDecisionState, + unreadPosts: UInt32, + newPosts: UInt32 + ) -> (UInt32, UInt32, Bool) { + switch decision { + case .whenLastReadMissing: + return hasUnreadPosts ? (unreadPosts, newPosts, hasUnreadPosts) : (0, 0, hasUnreadPosts) + case .caughtUp: + return (0, 0, false) + case .stillUnread: + return (unreadPosts, newPosts, true) + } + } + + nonisolated static func makeTopicRowContentToken( + _ row: FireTopicRowPresentation, + category: FireTopicCategoryPresentation? + ) -> String { + let topic = row.topic + var parts: [String] = [] + parts.reserveCapacity(26) + parts.append(String(topic.id)) + parts.append(topic.title) + parts.append(topic.slug) + parts.append(String(topic.postsCount)) + parts.append(String(topic.replyCount)) + parts.append(String(topic.views)) + parts.append(String(topic.likeCount)) + parts.append(topic.excerpt ?? "") + parts.append(topic.createdAt ?? "") + parts.append(topic.lastPostedAt ?? "") + parts.append(topic.lastPosterUsername ?? "") + parts.append(topic.categoryId.map(String.init) ?? "") + parts.append(String(topic.pinned)) + parts.append(String(topic.closed)) + parts.append(String(topic.archived)) + parts.append(String(topic.unseen)) + parts.append(String(row.hasUnreadPosts)) + parts.append(String(topic.unreadPosts)) + parts.append(String(topic.newPosts)) + parts.append(topic.lastReadPostNumber.map(String.init) ?? "") + parts.append(String(topic.highestPostNumber)) + parts.append(row.excerptText ?? "") + parts.append(row.originalPosterUsername ?? "") + parts.append(row.originalPosterAvatarTemplate ?? "") + parts.append(row.tagNames.joined(separator: ",")) + parts.append(row.statusLabels.joined(separator: ",")) + parts.append(category.map { "\($0.id)|\($0.displayName)|\($0.colorHex ?? "")" } ?? "") + return parts.joined(separator: "\u{1F}") + } +} diff --git a/apps/ios-app/App/Stores/FireHomeFeedStore.swift b/apps/ios-app/App/Stores/FireHomeFeedStore.swift index 109cffd5..b8ff7337 100644 --- a/apps/ios-app/App/Stores/FireHomeFeedStore.swift +++ b/apps/ios-app/App/Stores/FireHomeFeedStore.swift @@ -21,68 +21,49 @@ public enum FireHomeTopicListDisplayState: Hashable { if hasRows { return .content(nonBlockingErrorMessage: errorMessage) } - return .empty(nonBlockingErrorMessage: errorMessage) } } @MainActor final class FireHomeFeedStore: ObservableObject { - private static let topicListRefreshLoadingPollInterval: Duration = .milliseconds(250) - - private struct FireHomeTopicRowsMergeResult: Sendable { - let rows: [FireTopicRowPresentation] - let entities: FireEntityIndex - let order: FireOrderedIDList - let contentTokens: [UInt64: String] - } - - @Published private(set) var selectedTopicKind: TopicListKindState = .latest - @Published private(set) var selectedHomeCategoryId: UInt64? - @Published private(set) var selectedHomeTags: [String] = [] - @Published private(set) var topicRows: [FireTopicRowPresentation] = [] - @Published private(set) var moreTopicsUrl: String? - @Published private(set) var nextTopicsPage: UInt32? - @Published private(set) var allCategories: [FireTopicCategoryPresentation] = [] - @Published private(set) var topicCategories: [UInt64: FireTopicCategoryPresentation] = [:] - @Published private(set) var topTags: [String] = [] - @Published private(set) var canTagTopics = false - @Published private(set) var isLoadingTopics = false - @Published private(set) var isAppendingTopics = false - @Published private(set) var topicLoadErrorMessage: String? - @Published private(set) var topicLoadErrorIsCloudflare = false - @Published private(set) var isOffline = false - - private(set) var visibleTopicIDs: Set = [] - private(set) var isTopicListVisible = false - private(set) var isSceneActive = false - private(set) var renderedTopicListScope: FireTopicListRefreshScope? - private let appViewModel: FireAppViewModel - private let topicListRefreshClock = ContinuousClock() - private var pendingTopicListRefreshTask: Task? - private var filterChangeRefreshTask: Task? - private var topicListMessageBusRefreshController = FireTopicListMessageBusRefreshController() - private var topicEntities = FireEntityIndex() - private var topicOrder = FireOrderedIDList() - private var topicRowContentTokensByID: [UInt64: String] = [:] + @Published var selectedTopicKind: TopicListKindState = .latest + @Published var selectedHomeCategoryId: UInt64? + @Published var selectedHomeTags: [String] = [] + @Published var topicRows: [FireTopicRowPresentation] = [] + @Published var moreTopicsUrl: String? + @Published var nextTopicsPage: UInt32? + @Published var allCategories: [FireTopicCategoryPresentation] = [] + @Published var topicCategories: [UInt64: FireTopicCategoryPresentation] = [:] + @Published var topTags: [String] = [] + @Published var canTagTopics = false + @Published var isLoadingTopics = false + @Published var isAppendingTopics = false + @Published var topicLoadErrorMessage: String? + @Published var topicLoadErrorIsCloudflare = false + @Published var isOffline = false + + var visibleTopicIDs: Set = [] + + private let feedSession: FireHomeFeedSession init(appViewModel: FireAppViewModel) { - self.appViewModel = appViewModel - applySession(appViewModel.session) + feedSession = FireHomeFeedSession(appViewModel: appViewModel) + feedSession.attach(store: self) + feedSession.applySession(appViewModel.session) } var selectedHomeCategoryPresentation: FireTopicCategoryPresentation? { - guard let id = selectedHomeCategoryId else { return nil } - return categoryPresentation(for: id) + categoryPresentation(for: selectedHomeCategoryId) } var currentScopeNextTopicsPage: UInt32? { - hasResolvedCurrentScope ? nextTopicsPage : nil + feedSession.hasResolvedCurrentScope ? nextTopicsPage : nil } var topicListDisplayState: FireHomeTopicListDisplayState { FireHomeTopicListDisplayState.resolve( - hasResolvedCurrentScope: hasResolvedCurrentScope, + hasResolvedCurrentScope: feedSession.hasResolvedCurrentScope, hasRows: !topicRows.isEmpty, errorMessage: topicLoadErrorMessage ) @@ -92,779 +73,122 @@ final class FireHomeFeedStore: ObservableObject { currentTopicIDs: [UInt64], candidateVisibleTopicIDs: Set ) -> Set { - candidateVisibleTopicIDs.intersection(currentTopicIDs) + FireHomeFeedSession.sanitizedVisibleTopicIDs( + currentTopicIDs: currentTopicIDs, + candidateVisibleTopicIDs: candidateVisibleTopicIDs + ) } static func applyHomeRowCountPatch( _ row: FireTopicRowPresentation, patch: TopicHomeRowCountPatchState ) -> FireTopicRowPresentation? { - guard row.topic.id == patch.topicId else { - return nil - } - let (unreadPosts, newPosts, hasUnreadPosts) = unreadCounts( - hasUnreadPosts: row.hasUnreadPosts, - decision: patch.unread, - unreadPosts: row.topic.unreadPosts, - newPosts: row.topic.newPosts - ) - guard row.topic.postsCount != patch.postsCount - || row.topic.replyCount != patch.replyCount - || row.topic.views != patch.views - || row.topic.lastReadPostNumber != patch.lastReadPostNumber - || row.topic.highestPostNumber != patch.highestPostNumber - || row.topic.unreadPosts != unreadPosts - || row.topic.newPosts != newPosts - || row.hasUnreadPosts != hasUnreadPosts else { - return nil - } - var patched = row - patched.topic.postsCount = patch.postsCount - patched.topic.replyCount = patch.replyCount - patched.topic.views = patch.views - patched.topic.lastReadPostNumber = patch.lastReadPostNumber - patched.topic.highestPostNumber = patch.highestPostNumber - patched.topic.unreadPosts = unreadPosts - patched.topic.newPosts = newPosts - patched.hasUnreadPosts = hasUnreadPosts - return patched + FireHomeFeedSession.applyHomeRowCountPatch(row, patch: patch) } - private static func unreadCounts( - hasUnreadPosts: Bool, - decision: TopicHomeUnreadDecisionState, - unreadPosts: UInt32, - newPosts: UInt32 - ) -> (UInt32, UInt32, Bool) { - switch decision { - case .whenLastReadMissing: - return hasUnreadPosts ? (unreadPosts, newPosts, hasUnreadPosts) : (0, 0, hasUnreadPosts) - case .caughtUp: - return (0, 0, false) - case .stillUnread: - return (unreadPosts, newPosts, true) - } + nonisolated static func canScheduleIncrementalMessageBusRefresh( + scope: FireTopicListRefreshScope, + renderedScope: FireTopicListRefreshScope?, + isTopicListVisible: Bool, + isSceneActive: Bool, + hasRows: Bool + ) -> Bool { + FireHomeFeedSession.canScheduleIncrementalMessageBusRefresh( + scope: scope, + renderedScope: renderedScope, + isTopicListVisible: isTopicListVisible, + isSceneActive: isSceneActive, + hasRows: hasRows + ) } func updateVisibleTopicIDs(_ topicIDs: Set) { - visibleTopicIDs = Self.sanitizedVisibleTopicIDs( - currentTopicIDs: topicRows.map(\.topic.id), - candidateVisibleTopicIDs: topicIDs - ) + feedSession.updateVisibleTopicIDs(topicIDs) } func setTopicListVisible(_ isVisible: Bool) { - guard isTopicListVisible != isVisible else { - return - } - isTopicListVisible = isVisible - if !isVisible { - cancelPendingTopicListRefresh() - } + feedSession.setTopicListVisible(isVisible) } func setSceneActive(_ isActive: Bool) { - guard isSceneActive != isActive else { - return - } - isSceneActive = isActive - if !isActive { - cancelPendingTopicListRefresh() - } + feedSession.setSceneActive(isActive) } func applySession(_ session: SessionState) { - allCategories = session.bootstrap.categories - topicCategories = Dictionary( - uniqueKeysWithValues: session.bootstrap.categories.map { ($0.id, $0) } - ) - topTags = session.bootstrap.topTags - canTagTopics = session.bootstrap.canTagTopics - - guard session.readiness.canReadAuthenticatedApi else { - reset(resetTopicKind: true) - return - } + feedSession.applySession(session) } func categoryPresentation(for categoryID: UInt64?) -> FireTopicCategoryPresentation? { - guard let categoryID else { - return nil - } - return topicCategories[categoryID] + feedSession.categoryPresentation(for: categoryID) } func topicRow(for topicID: UInt64) -> FireTopicRowPresentation? { - topicEntities.entity(for: topicID) + feedSession.topicRow(for: topicID) } func topicRowContentToken(for topicID: UInt64) -> String? { - topicRowContentTokensByID[topicID] + feedSession.topicRowContentToken(for: topicID) } @discardableResult func applyHomeRowCountPatch(_ patch: TopicHomeRowCountPatchState) -> Bool { - guard let row = topicEntities.entity(for: patch.topicId), - let patched = Self.applyHomeRowCountPatch(row, patch: patch) else { - return false - } - - topicEntities.upsert([patched], id: \.topic.id) - let rows = topicEntities.orderedValues(for: topicOrder) - topicRows = rows - topicRowContentTokensByID[patch.topicId] = Self.makeTopicRowContentToken( - patched, - category: categoryPresentation(for: patched.topic.categoryId) - ) - visibleTopicIDs = Self.sanitizedVisibleTopicIDs( - currentTopicIDs: rows.map(\.topic.id), - candidateVisibleTopicIDs: visibleTopicIDs - ) - return true + feedSession.applyHomeRowCountPatch(patch) } func selectTopicKind(_ kind: TopicListKindState) { - guard selectedTopicKind != kind else { - return - } - selectedTopicKind = kind - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - isOffline = false - syncCurrentHomeTopicListScope() - scheduleDebouncedRefresh() + feedSession.selectTopicKind(kind) } - func selectHomeCategory(_ categoryId: UInt64?) { - guard selectedHomeCategoryId != categoryId else { return } - selectedHomeCategoryId = categoryId - selectedHomeTags = [] - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - isOffline = false - syncCurrentHomeTopicListScope() - scheduleDebouncedRefresh() + func selectHomeCategory(_ categoryID: UInt64?) { + feedSession.selectHomeCategory(categoryID) } func addHomeTag(_ tag: String) { - guard !selectedHomeTags.contains(tag) else { return } - selectedHomeTags.append(tag) - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - isOffline = false - syncCurrentHomeTopicListScope() - scheduleDebouncedRefresh() + feedSession.addHomeTag(tag) } func removeHomeTag(_ tag: String) { - guard selectedHomeTags.contains(tag) else { return } - selectedHomeTags.removeAll { $0 == tag } - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - isOffline = false - syncCurrentHomeTopicListScope() - scheduleDebouncedRefresh() + feedSession.removeHomeTag(tag) } func clearHomeTags() { - guard !selectedHomeTags.isEmpty else { return } - selectedHomeTags = [] - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - isOffline = false - syncCurrentHomeTopicListScope() - scheduleDebouncedRefresh() + feedSession.clearHomeTags() } func refreshTopics() { - Task { - await refreshTopicsAsync() - } + feedSession.refreshTopics() } func refreshTopicsAsync() async { - await refreshTopicsIfPossible(force: true) + await feedSession.refreshTopicsAsync() } func applyTopicList(_ state: TopicListState) { - Task { @MainActor [weak self] in - guard let self else { return } - let mergeResult = await self.prepareTopicRowsMerge( - incoming: state.rows, - reset: true, - usesIncrementalRefresh: false - ) - self.applyTopicRows(mergeResult) - self.renderedTopicListScope = self.currentTopicListRefreshScope - self.topicLoadErrorMessage = nil - self.topicLoadErrorIsCloudflare = false - self.isOffline = state.isCached - self.moreTopicsUrl = state.moreTopicsUrl - self.nextTopicsPage = state.nextPage - self.isLoadingTopics = false - self.isAppendingTopics = false - self.appViewModel.updateWidgetData() - } + feedSession.applyTopicList(state) } @discardableResult func refreshTopicsIfPossible(force: Bool) async -> Bool { - cancelPendingTopicListRefresh() - return await loadTopics(page: nil, reset: true, force: force, refreshMode: .full) + await feedSession.refreshTopicsIfPossible(force: force) } func loadMoreTopics() { - guard let nextTopicsPage = currentScopeNextTopicsPage else { - return - } - - Task { - await loadTopics(page: nextTopicsPage, reset: false, force: true) - } + feedSession.loadMoreTopics() } func handleTopicListMessageBusEvent(_ event: MessageBusEventState) { - guard let busKind = event.topicListKind else { return } - let scope = currentTopicListRefreshScope - guard busKind == scope.kind else { return } - - let allowIncremental = Self.canScheduleIncrementalMessageBusRefresh( - scope: scope, - renderedScope: renderedTopicListScope, - isTopicListVisible: isTopicListVisible, - isSceneActive: isSceneActive, - hasRows: !topicRows.isEmpty - ) - guard let delay = topicListMessageBusRefreshController.register( - event: event, - for: scope, - now: topicListRefreshClock.now, - allowIncremental: allowIncremental - ) else { - return - } - - pendingTopicListRefreshTask?.cancel() - pendingTopicListRefreshTask = Task { [weak self] in - do { - try await Task.sleep(for: delay) - } catch { - return - } - - guard let self else { return } - - while self.isLoadingTopics { - do { - try await Task.sleep(for: Self.topicListRefreshLoadingPollInterval) - } catch { - return - } - } - - let scope = self.currentTopicListRefreshScope - let refreshMode = self.topicListMessageBusRefreshController.takePendingRefresh(for: scope) - self.pendingTopicListRefreshTask = nil - - guard let refreshMode else { return } - await self.refreshTopicsFromMessageBus(refreshMode) - } + feedSession.handleTopicListMessageBusEvent(event) } func handleMessageBusStopped() { - cancelPendingTopicListRefresh() + feedSession.handleMessageBusStopped() } func reset(resetTopicKind: Bool = true) { - cancelPendingTopicListRefresh() - filterChangeRefreshTask?.cancel() - filterChangeRefreshTask = nil - topicEntities.removeAll() - topicOrder.removeAll() - topicRowContentTokensByID = [:] - topicRows = [] - moreTopicsUrl = nil - nextTopicsPage = nil - isLoadingTopics = false - isAppendingTopics = false - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - isOffline = false - renderedTopicListScope = nil - selectedHomeCategoryId = nil - selectedHomeTags = [] - if resetTopicKind { - selectedTopicKind = .latest - } + feedSession.reset(resetTopicKind: resetTopicKind) } func clearTopicLoadError() { - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - } - - private var currentTopicListRefreshScope: FireTopicListRefreshScope { - FireTopicListRefreshScope( - kind: selectedTopicKind, - categoryId: selectedHomeCategoryId, - tags: selectedHomeTags - ) - } - - private func applyCurrentTopicListRefreshScope(_ scope: FireTopicListRefreshScope) { - selectedTopicKind = scope.kind - selectedHomeCategoryId = scope.categoryId - selectedHomeTags = scope.tags - } - - private var hasResolvedCurrentScope: Bool { - renderedTopicListScope == currentTopicListRefreshScope - } - - private func syncCurrentHomeTopicListScope() { - let scope = currentTopicListRefreshScope - Task { [weak self] in - guard let self else { return } - do { - let sessionStore = try await appViewModel.sessionStoreValue() - let updated = try await sessionStore.setCurrentHomeTopicListScope(scope.state) - await MainActor.run { - self.applyCurrentTopicListRefreshScope(FireTopicListRefreshScope(updated)) - } - } catch { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: "home.feed", - message: "failed to sync home topic list scope: \(error.localizedDescription)" - ) - } - } - } - - private func scheduleDebouncedRefresh() { - cancelPendingTopicListRefresh() - filterChangeRefreshTask?.cancel() - filterChangeRefreshTask = Task { [weak self] in - try? await Task.sleep(for: .milliseconds(300)) - guard !Task.isCancelled else { return } - guard let self else { return } - await self.refreshTopicsIfPossible(force: true) - } - } - - private func refreshTopicsFromMessageBus(_ refreshMode: FireTopicListMessageBusRefreshMode) async { - guard case .incremental = refreshMode, - Self.canScheduleIncrementalMessageBusRefresh( - scope: currentTopicListRefreshScope, - renderedScope: renderedTopicListScope, - isTopicListVisible: isTopicListVisible, - isSceneActive: isSceneActive, - hasRows: !topicRows.isEmpty - ) else { - return - } - await loadTopics(page: nil, reset: true, force: true, refreshMode: refreshMode) - } - - nonisolated static func canScheduleIncrementalMessageBusRefresh( - scope: FireTopicListRefreshScope, - renderedScope: FireTopicListRefreshScope?, - isTopicListVisible: Bool, - isSceneActive: Bool, - hasRows: Bool - ) -> Bool { - isSceneActive - && isTopicListVisible - && hasRows - && scope.supportsIncrementalMessageBusRefresh - && renderedScope == scope - } - - @discardableResult - private func loadTopics( - page: UInt32?, - reset: Bool, - force: Bool, - refreshMode: FireTopicListMessageBusRefreshMode = .full - ) async -> Bool { - if !appViewModel.session.readiness.canReadAuthenticatedApi { - self.reset(resetTopicKind: true) - return false - } - if isLoadingTopics { - return false - } - if reset && !force && !topicRows.isEmpty { - return false - } - - isLoadingTopics = true - isAppendingTopics = !reset - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - if reset { - isOffline = false - } - defer { - isLoadingTopics = false - isAppendingTopics = false - } - - do { - let sessionStore = try await appViewModel.sessionStoreValue() - let requestedScopeState = try await sessionStore.setCurrentHomeTopicListScope( - currentTopicListRefreshScope.state - ) - let requestedScope = FireTopicListRefreshScope(requestedScopeState) - applyCurrentTopicListRefreshScope(requestedScope) - let requestedKind = requestedScope.kind - let categoryId = requestedScope.categoryId - let requestedTags = requestedScope.tags - let categorySlug = categoryId.flatMap { categoryPresentation(for: $0)?.slug } - let parentSlug: String? = categoryId.flatMap { id in - guard let category = categoryPresentation(for: id), - let parentId = category.parentCategoryId else { - return nil - } - return categoryPresentation(for: parentId)?.slug - } - let primaryTag = requestedTags.first - let additionalTags = requestedTags.count > 1 - ? Array(requestedTags.dropFirst()) - : [] - let incrementalTopicIDs: [UInt64] - switch refreshMode { - case .full: - incrementalTopicIDs = [] - case .incremental(let topicIDs): - incrementalTopicIDs = topicIDs - } - let usesIncrementalRefresh = page == nil - && reset - && !incrementalTopicIDs.isEmpty - && requestedScope.supportsIncrementalMessageBusRefresh - && renderedTopicListScope == requestedScope - && !topicRows.isEmpty - let topicListQuery = TopicListQueryState( - kind: requestedKind, - page: page, - topicIds: usesIncrementalRefresh ? incrementalTopicIDs : [], - order: nil, - ascending: nil, - categorySlug: categorySlug, - categoryId: categoryId, - parentCategorySlug: parentSlug, - tag: primaryTag, - additionalTags: additionalTags, - matchAllTags: !additionalTags.isEmpty - ) - let recoveryURL = appViewModel.cloudflareRecoveryTopicListURL(query: topicListQuery) - let fetch: () async throws -> TopicListState = { - try await sessionStore.fetchTopicList( - query: topicListQuery - ) - } - let operationDescription = (page == nil && reset) - ? "刷新首页话题列表" - : "加载更多首页话题" - let fetchWithRecovery: () async throws -> TopicListState = { - try await self.appViewModel.performWithCloudflareRecovery( - operation: operationDescription, - originURL: recoveryURL, - work: fetch - ) - } - - let response: TopicListState - if reset && page == nil && requestedKind == .latest { - response = try await FireAPMManager.shared.withSpan( - .feedLatestInitialLoad, - metadata: [ - "category_id": categoryId.map(String.init) ?? "none", - "tag": primaryTag ?? "none", - "incremental": usesIncrementalRefresh ? "true" : "false" - ], - operation: fetchWithRecovery - ) - } else { - response = try await fetchWithRecovery() - } - - guard requestedScope == currentTopicListRefreshScope else { - return false - } - - let mergeResult = await prepareTopicRowsMerge( - incoming: response.rows, - reset: reset, - usesIncrementalRefresh: usesIncrementalRefresh - ) - applyTopicRows(mergeResult) - renderedTopicListScope = requestedScope - topicLoadErrorMessage = nil - topicLoadErrorIsCloudflare = false - isOffline = response.isCached - if reset && page == nil { - appViewModel.updateWidgetData() - } - - if !usesIncrementalRefresh { - moreTopicsUrl = response.moreTopicsUrl - nextTopicsPage = response.nextPage - } - - appViewModel.pruneTopicDetailState(retainingVisibleTopicIDs: visibleTopicIDs) - - if reset && page == nil { - topicListMessageBusRefreshController.markRefreshCompleted( - for: requestedScope, - at: topicListRefreshClock.now - ) - Task { [appViewModel] in - await appViewModel.ensureMessageBusActiveIfPossible() - } - } - return true - } catch { - let recoveryOperationDescription = (page == nil && reset) - ? "刷新首页话题列表" - : "加载更多首页话题" - if await appViewModel.attemptReadPathLoginRecovery( - operation: recoveryOperationDescription, - error: error - ) { - // Tear down the in-flight gate before recursing; without this - // the inner `loadTopics` returns immediately on the - // `isLoadingTopics` guard, and the `reset && !force && !rows.isEmpty` - // guard would also short-circuit incremental refreshes. - isLoadingTopics = false - isAppendingTopics = false - return await loadTopics( - page: page, - reset: reset, - force: true, - refreshMode: refreshMode - ) - } - if !force, - case FireUniFfiError.StaleSessionResponse = error { - isLoadingTopics = false - isAppendingTopics = false - return await loadTopics( - page: page, - reset: reset, - force: true, - refreshMode: refreshMode - ) - } - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - return false - } - if FireAppViewModel.isCloudflareChallengeError(error) { - let reason = FireAppViewModel.cloudflareChallengeReason(from: error) - topicLoadErrorIsCloudflare = true - topicLoadErrorMessage = Self.cloudflareErrorMessage(reason: reason) - } else { - topicLoadErrorIsCloudflare = false - topicLoadErrorMessage = error.localizedDescription - } - return false - } - } - - private static func cloudflareErrorMessage(reason: String) -> String { - switch reason { - case "in_progress": - return "正在完成 Cloudflare 验证,请稍候" - case "cooldown": - return "Cloudflare 验证暂时冷却中,可点横幅重试验证" - case "cancelled": - return "已取消 Cloudflare 验证,可点横幅重新验证" - case "background_suppressed": - return "后台请求遇到 Cloudflare 验证,可点横幅手动验证" - case "failed": - return "Cloudflare 验证未完成,可点横幅重试" - default: - return "需要完成 Cloudflare 验证,可点横幅立即验证" - } - } - - private func cancelPendingTopicListRefresh() { - pendingTopicListRefreshTask?.cancel() - pendingTopicListRefreshTask = nil - - let scope = currentTopicListRefreshScope - topicListMessageBusRefreshController.clearPending(for: scope) - } - - private func applyTopicRows(_ result: FireHomeTopicRowsMergeResult) { - topicEntities = result.entities - topicOrder = result.order - topicRows = result.rows - topicRowContentTokensByID = result.contentTokens - visibleTopicIDs = Self.sanitizedVisibleTopicIDs( - currentTopicIDs: result.rows.map(\.topic.id), - candidateVisibleTopicIDs: visibleTopicIDs - ) - } - - private func clearTopicRows() { - topicEntities.removeAll() - topicOrder.removeAll() - topicRowContentTokensByID = [:] - topicRows = [] - visibleTopicIDs = [] - moreTopicsUrl = nil - nextTopicsPage = nil - renderedTopicListScope = nil - } - - /// Snapshot current indexes, then merge + rebuild content tokens off the main actor. - private func prepareTopicRowsMerge( - incoming: [FireTopicRowPresentation], - reset: Bool, - usesIncrementalRefresh: Bool - ) async -> FireHomeTopicRowsMergeResult { - let existingRows = topicRows - let existingEntities = topicEntities - let existingOrder = topicOrder - let previousTokens = topicRowContentTokensByID - let categories = topicCategories - - return await Task.detached(priority: .userInitiated) { - Self.mergeTopicRows( - incoming: incoming, - existingRows: existingRows, - existingEntities: existingEntities, - existingOrder: existingOrder, - previousTokens: previousTokens, - categories: categories, - reset: reset, - usesIncrementalRefresh: usesIncrementalRefresh - ) - }.value - } - - nonisolated private static func mergeTopicRows( - incoming: [FireTopicRowPresentation], - existingRows: [FireTopicRowPresentation], - existingEntities: FireEntityIndex, - existingOrder: FireOrderedIDList, - previousTokens: [UInt64: String], - categories: [UInt64: FireTopicCategoryPresentation], - reset: Bool, - usesIncrementalRefresh: Bool - ) -> FireHomeTopicRowsMergeResult { - let dirtyTopicIDs = Set(incoming.map(\.topic.id)) - let rebuildAllTokens: Bool - let rows: [FireTopicRowPresentation] - let entities: FireEntityIndex - let order: FireOrderedIDList - - if reset { - if usesIncrementalRefresh { - let mergedRows = FireTopicListMessageBusRefreshMerger.merge( - existing: existingRows, - incoming: incoming - ) - var nextEntities = FireEntityIndex() - nextEntities.replaceAll(mergedRows, id: \.topic.id) - rows = mergedRows - entities = nextEntities - order = FireOrderedIDList(ids: mergedRows.map(\.topic.id)) - rebuildAllTokens = false - } else { - var nextEntities = FireEntityIndex() - nextEntities.replaceAll(incoming, id: \.topic.id) - rows = incoming - entities = nextEntities - order = FireOrderedIDList(ids: incoming.map(\.topic.id)) - rebuildAllTokens = true - } - } else { - var nextEntities = existingEntities - nextEntities.upsert(incoming, id: \.topic.id) - var nextOrder = existingOrder - nextOrder.append(incoming.map(\.topic.id)) - rows = nextEntities.orderedValues(for: nextOrder) - entities = nextEntities - order = nextOrder - rebuildAllTokens = false - } - - let contentTokens = buildTopicRowContentTokens( - rows: rows, - dirtyTopicIDs: dirtyTopicIDs, - rebuildAll: rebuildAllTokens, - previousTokens: previousTokens, - categories: categories - ) - - return FireHomeTopicRowsMergeResult( - rows: rows, - entities: entities, - order: order, - contentTokens: contentTokens - ) - } - - nonisolated private static func buildTopicRowContentTokens( - rows: [FireTopicRowPresentation], - dirtyTopicIDs: Set, - rebuildAll: Bool, - previousTokens: [UInt64: String], - categories: [UInt64: FireTopicCategoryPresentation] - ) -> [UInt64: String] { - let currentTopicIDs = Set(rows.map(\.topic.id)) - var nextTokens: [UInt64: String] - if rebuildAll { - nextTokens = [:] - nextTokens.reserveCapacity(rows.count) - } else { - nextTokens = previousTokens.filter { currentTopicIDs.contains($0.key) } - } - - for row in rows where rebuildAll || dirtyTopicIDs.contains(row.topic.id) { - let category = row.topic.categoryId.flatMap { categories[$0] } - nextTokens[row.topic.id] = makeTopicRowContentToken(row, category: category) - } - return nextTokens - } - - nonisolated static func makeTopicRowContentToken( - _ row: FireTopicRowPresentation, - category: FireTopicCategoryPresentation? - ) -> String { - let topic = row.topic - var parts: [String] = [] - parts.reserveCapacity(26) - parts.append(String(topic.id)) - parts.append(topic.title) - parts.append(topic.slug) - parts.append(String(topic.postsCount)) - parts.append(String(topic.replyCount)) - parts.append(String(topic.views)) - parts.append(String(topic.likeCount)) - parts.append(topic.excerpt ?? "") - parts.append(topic.createdAt ?? "") - parts.append(topic.lastPostedAt ?? "") - parts.append(topic.lastPosterUsername ?? "") - parts.append(topic.categoryId.map(String.init) ?? "") - parts.append(String(topic.pinned)) - parts.append(String(topic.closed)) - parts.append(String(topic.archived)) - parts.append(String(topic.unseen)) - parts.append(String(row.hasUnreadPosts)) - parts.append(String(topic.unreadPosts)) - parts.append(String(topic.newPosts)) - parts.append(topic.lastReadPostNumber.map(String.init) ?? "") - parts.append(String(topic.highestPostNumber)) - parts.append(row.excerptText ?? "") - parts.append(row.originalPosterUsername ?? "") - parts.append(row.originalPosterAvatarTemplate ?? "") - parts.append(row.tagNames.joined(separator: ",")) - parts.append(row.statusLabels.joined(separator: ",")) - parts.append(category.map { "\($0.id)|\($0.displayName)|\($0.colorHex ?? "")" } ?? "") - return parts.joined(separator: "\u{1F}") + feedSession.clearTopicLoadError() } } diff --git a/apps/ios-app/App/Stores/FireNotificationStore.swift b/apps/ios-app/App/Stores/FireNotificationStore.swift index 1d18087a..74743360 100644 --- a/apps/ios-app/App/Stores/FireNotificationStore.swift +++ b/apps/ios-app/App/Stores/FireNotificationStore.swift @@ -1,5 +1,4 @@ import Foundation -import Combine @MainActor final class FireNotificationStore: ObservableObject { @@ -10,54 +9,32 @@ final class FireNotificationStore: ObservableObject { @Published private(set) var recentErrorMessage: String? @Published private(set) var isRecentOffline = false + @Published private(set) var fullNotifications: [NotificationItemState] = [] + @Published private(set) var fullNextOffset: UInt32? + @Published private(set) var isLoadingFull = false + @Published private(set) var isLoadingMoreFull = false + @Published private(set) var hasLoadedFullOnce = false + @Published private(set) var isFullOffline = false + @Published private(set) var blockingFullErrorMessage: String? + @Published private(set) var fullNonBlockingErrorMessage: String? + private let appViewModel: FireAppViewModel - private let fullPagination = FireNotificationFullPaginationStore() - private var pendingStateRefreshTask: Task? private var lastFailedFullOffset: UInt32? - private var cancellables: Set = [] init(appViewModel: FireAppViewModel) { self.appViewModel = appViewModel - fullPagination.configure(appViewModel: appViewModel) - fullPagination.onPageLoaded = { [weak self] in - self?.lastFailedFullOffset = nil - } - fullPagination.onPageFailed = { [weak self] offset in - self?.lastFailedFullOffset = offset - } - fullPagination.objectWillChange - .sink { [weak self] _ in - self?.objectWillChange.send() - } - .store(in: &cancellables) - } - - var fullNotifications: [NotificationItemState] { - fullPagination.items - } - - var fullNextOffset: UInt32? { - fullPagination.currentNextOffset } var isLoadingFullPage: Bool { - fullPagination.isLoading || fullPagination.isLoadingMore - } - - var isFullOffline: Bool { - fullPagination.isOffline - } - - var hasLoadedFullOnce: Bool { - fullPagination.hasLoadedOnce + isLoadingFull || isLoadingMoreFull } var hasMoreFull: Bool { - fullPagination.hasMore + fullNextOffset != nil } var fullErrorMessage: String? { - fullPagination.blockingErrorMessage ?? fullPagination.nonBlockingErrorMessage + blockingFullErrorMessage ?? fullNonBlockingErrorMessage } var blockingRecentErrorMessage: String? { @@ -68,42 +45,37 @@ final class FireNotificationStore: ObservableObject { hasLoadedRecentOnce ? recentErrorMessage : nil } - var blockingFullErrorMessage: String? { - fullPagination.blockingErrorMessage - } - - var fullNonBlockingErrorMessage: String? { - fullPagination.nonBlockingErrorMessage - } - var shouldShowFullPaginationRetry: Bool { lastFailedFullOffset != nil } func reset() { - pendingStateRefreshTask?.cancel() - pendingStateRefreshTask = nil unreadCount = 0 recentNotifications = [] isLoadingRecent = false hasLoadedRecentOnce = false recentErrorMessage = nil isRecentOffline = false - fullPagination.reset() + fullNotifications = [] + fullNextOffset = nil + isLoadingFull = false + isLoadingMoreFull = false + hasLoadedFullOnce = false + isFullOffline = false + blockingFullErrorMessage = nil + fullNonBlockingErrorMessage = nil lastFailedFullOffset = nil } - func cancelScheduledRefresh() { - pendingStateRefreshTask?.cancel() - pendingStateRefreshTask = nil - } + func cancelScheduledRefresh() {} func clearRecentError() { recentErrorMessage = nil } func clearFullError() { - fullPagination.clearErrors() + blockingFullErrorMessage = nil + fullNonBlockingErrorMessage = nil lastFailedFullOffset = nil } @@ -112,12 +84,16 @@ final class FireNotificationStore: ObservableObject { } func recordFullLoadFailure(_ message: String, offset: UInt32? = nil) { - fullPagination.recordFailure(message, isBlocking: !fullPagination.hasLoadedOnce) + if hasLoadedFullOnce { + fullNonBlockingErrorMessage = message + } else { + blockingFullErrorMessage = message + } lastFailedFullOffset = offset } func retryFullLoad() async { - await loadFullPage(offset: lastFailedFullOffset ?? fullPagination.currentNextOffset) + await loadFullPage(offset: lastFailedFullOffset ?? fullNextOffset) } func syncStateFromRuntimeIfAvailable() async { @@ -144,14 +120,9 @@ final class FireNotificationStore: ObservableObject { do { try await FireAPMManager.shared.withSpan(.notificationsRefresh) { - let list = try await appViewModel.notificationService.fetchRecentNotifications() - recentNotifications = list.notifications - isRecentOffline = list.isCached - hasLoadedRecentOnce = true - recentErrorMessage = nil - if let state = try? await appViewModel.notificationService.notificationCenterState() { - apply(centerState: state, updateRecent: true, updateFull: state.hasLoadedFull) - } + _ = try await appViewModel.notificationService.fetchRecentNotifications() + let state = try await appViewModel.notificationService.notificationCenterState() + apply(centerState: state, updateRecent: true, updateFull: state.hasLoadedFull) } } catch { if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { @@ -186,20 +157,34 @@ final class FireNotificationStore: ObservableObject { func loadFullPage(offset: UInt32?) async { guard appViewModel.session.readiness.canReadAuthenticatedApi else { return } lastFailedFullOffset = nil - if let offset { - await fullPagination.loadPage(offset: offset) + let isMore = offset != nil && hasLoadedFullOnce + if isMore { + isLoadingMoreFull = true } else { - await fullPagination.loadAsync(forceRefresh: true) + isLoadingFull = true + } + blockingFullErrorMessage = nil + fullNonBlockingErrorMessage = nil + defer { + isLoadingFull = false + isLoadingMoreFull = false + } + + do { + _ = try await appViewModel.notificationService.fetchNotifications(offset: offset) + let state = try await appViewModel.notificationService.notificationCenterState() + apply(centerState: state, updateRecent: state.hasLoadedRecent, updateFull: true) + } catch { + if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { + return + } + recordFullLoadFailure(error.localizedDescription, offset: offset) } } func scheduleStateRefresh() { - pendingStateRefreshTask?.cancel() - pendingStateRefreshTask = Task { [weak self] in - try? await Task.sleep(for: .milliseconds(150)) - guard !Task.isCancelled else { return } + Task { [weak self] in guard let self else { return } - do { let state = try await self.appViewModel.notificationService.notificationCenterState() self.apply( @@ -210,8 +195,6 @@ final class FireNotificationStore: ObservableObject { } catch { _ = await self.appViewModel.handleRecoverableSessionErrorIfNeeded(error) } - - self.pendingStateRefreshTask = nil } } @@ -228,99 +211,14 @@ final class FireNotificationStore: ObservableObject { recentErrorMessage = nil } if updateFull { - fullPagination.applyPage( - FirePaginatedStore.PageResult( - items: centerState.full, - nextOffset: centerState.fullNextOffset, - isCached: centerState.fullIsCached - ), - reset: true - ) + fullNotifications = centerState.full + fullNextOffset = centerState.fullNextOffset + hasLoadedFullOnce = true + isFullOffline = centerState.fullIsCached + blockingFullErrorMessage = nil + fullNonBlockingErrorMessage = nil lastFailedFullOffset = nil } appViewModel.updateWidgetData() } } - -@MainActor -private final class FireNotificationFullPaginationStore: FirePaginatedStore { - private weak var appViewModel: FireAppViewModel? - private var requestedOffset: UInt32? - private(set) var isOffline = false - var onPageLoaded: (() -> Void)? - var onPageFailed: ((UInt32?) -> Void)? - - func configure(appViewModel: FireAppViewModel) { - self.appViewModel = appViewModel - } - - func loadPage(offset: UInt32) async { - requestedOffset = offset - await loadMoreAsync() - } - - override func fetchPage(offset: UInt32?) async throws -> PageResult { - guard let appViewModel else { - throw FireNotificationPaginationError.missingAppViewModel - } - - let pageOffset = offset ?? requestedOffset - let list = try await appViewModel.notificationService.fetchNotifications(offset: pageOffset) - requestedOffset = nil - return PageResult( - items: list.notifications, - nextOffset: list.nextOffset, - loadedOffset: pageOffset, - isCached: list.isCached - ) - } - - override func applyPage(_ result: PageResult, reset: Bool) { - super.applyPage(result, reset: reset) - isOffline = result.isCached - onPageLoaded?() - } - - override func reset() { - super.reset() - isOffline = false - } - - override func mergeItems( - existing: [NotificationItemState], - incoming: [NotificationItemState] - ) -> [NotificationItemState] { - var merged = Dictionary(uniqueKeysWithValues: existing.map { ($0.id, $0) }) - var orderedIDs = existing.map(\.id) - - for item in incoming { - if merged[item.id] == nil { - orderedIDs.append(item.id) - } - merged[item.id] = item - } - - return orderedIDs.compactMap { merged[$0] } - } - - override func handlePageLoadError(_ error: Error, offset: UInt32?) async -> Bool { - guard let appViewModel else { return false } - requestedOffset = offset ?? requestedOffset - let handled = await appViewModel.handleRecoverableSessionErrorIfNeeded(error) - if !handled { - onPageFailed?(requestedOffset) - } - return handled - } -} - -private enum FireNotificationPaginationError: LocalizedError { - case missingAppViewModel - - var errorDescription: String? { - switch self { - case .missingAppViewModel: - return "Notification pagination store is not configured." - } - } -} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailFlagSheetHost.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailFlagSheetHost.swift new file mode 100644 index 00000000..39f6e6c1 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailFlagSheetHost.swift @@ -0,0 +1,37 @@ +import SwiftUI + +struct FireTopicDetailFlagSheetHost: View { + @ObservedObject var store: FireTopicDetailStore + + let topicID: UInt64 + let context: FirePostManagementContext + let onSubmitted: @MainActor (String) -> Void + + @State private var isLoadingOptions = false + + var body: some View { + FirePostFlagSheet( + context: context, + options: FirePostFlagOption.options(from: store.snapshot(for: topicID)?.flagTypes ?? []), + isLoadingOptions: isLoadingOptions + ) { option, message in + try await store.flagPost( + topicId: topicID, + postId: context.postID, + flagTypeId: option.id, + message: message + ) + await MainActor.run { + onSubmitted("举报已提交。") + } + } + .task { + guard (store.snapshot(for: topicID)?.flagTypes ?? []).isEmpty else { + return + } + isLoadingOptions = true + defer { isLoadingOptions = false } + try? await store.ensureFlagTypes(topicId: topicID) + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Alerts.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Alerts.swift new file mode 100644 index 00000000..7fc79f9a --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Alerts.swift @@ -0,0 +1,26 @@ +import UIKit + +@MainActor +extension FireTopicDetailModalRouter { + func presentDeleteConfirmation( + postNumber: UInt32, + onConfirm: @escaping () -> Void + ) { + let alert = UIAlertController( + title: "删除回复", + message: "确认删除 #\(postNumber) 吗?", + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "取消", style: .cancel)) + alert.addAction(UIAlertAction(title: "删除", style: .destructive) { _ in + onConfirm() + }) + viewController?.present(alert, animated: true) + } + + func presentNotice(title: String = "提示", message: String) { + let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "知道了", style: .cancel)) + viewController?.present(alert, animated: true) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Composer.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Composer.swift new file mode 100644 index 00000000..07bb00cd --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Composer.swift @@ -0,0 +1,139 @@ +import SwiftUI +import UIKit + +@MainActor +extension FireTopicDetailModalRouter { + private func presentPrivateMessageComposer(username: String, displayName: String) { + let composer = FireComposerViewController( + viewModel: viewModel, + route: FireComposerRoute(kind: .privateMessage(recipients: [username], title: nil)), + onPrivateMessageCreated: { [weak self] topicID, title in + self?.push(route: .topic( + topicId: topicID, + postNumber: nil, + preview: FireTopicRoutePreview.fromMetadata(title: title, slug: nil) + )) + } + ) + let navigationController = UINavigationController(rootViewController: composer) + navigationController.modalPresentationStyle = .fullScreen + viewController?.present(navigationController, animated: true) + } + + func presentBookmarkEditor( + context: FireBookmarkEditorContext, + recoveryOriginURL: URL, + onReload: @escaping @MainActor () async -> Void + ) { + let rootView = FireBookmarkEditorSheet( + context: context, + onSave: { [viewModel] name, reminderAt in + if let bookmarkID = context.bookmarkID { + try await viewModel.topicInteraction.updateBookmark( + bookmarkID: bookmarkID, + name: name, + reminderAt: reminderAt, + recoveryOriginURL: recoveryOriginURL + ) + } else { + _ = try await viewModel.topicInteraction.createBookmark( + bookmarkableID: context.bookmarkableID, + bookmarkableType: context.bookmarkableType, + name: name, + reminderAt: reminderAt, + recoveryOriginURL: recoveryOriginURL + ) + } + await onReload() + }, + onDelete: context.bookmarkID.map { [viewModel] bookmarkID in + { + try await viewModel.topicInteraction.deleteBookmark( + bookmarkID: bookmarkID, + recoveryOriginURL: recoveryOriginURL + ) + await onReload() + } + } + ) + presentSheetController(UIHostingController(rootView: rootView)) + } + + func presentPostEditor( + topicID: UInt64, + context: FirePostEditorContext, + onSaved: @escaping @MainActor () async -> Void + ) { + let rootView = NavigationStack { + FirePostEditorView( + viewModel: viewModel, + topicID: topicID, + postID: context.postID, + postNumber: context.postNumber, + onSaved: { + Task { await onSaved() } + } + ) + } + presentSheetController(UIHostingController(rootView: rootView)) + } + + func presentTopicEditor( + topicID: UInt64, + initialTitle: String, + initialCategoryID: UInt64?, + initialTags: [String], + onSaved: @escaping @MainActor () async -> Void + ) { + let rootView = NavigationStack { + FireTopicEditorView( + viewModel: viewModel, + topicID: topicID, + initialTitle: initialTitle, + initialCategoryID: initialCategoryID, + initialTags: initialTags, + onSaved: { + Task { await onSaved() } + } + ) + } + presentSheetController(UIHostingController(rootView: rootView)) + } + + func presentAdvancedComposer( + route: FireComposerRoute, + initialBody: String, + initialBodySelectionLocation: Int? = nil, + onReplySubmitted: @escaping @MainActor () -> Void, + onSubmissionNotice: @escaping @MainActor (String) -> Void, + scrollToCreatedReply: Bool = false + ) { + let composer = FireComposerViewController( + viewModel: viewModel, + route: route, + initialBody: initialBody, + initialBodySelectionLocation: initialBodySelectionLocation, + onReplySubmitted: onReplySubmitted, + onSubmissionNotice: onSubmissionNotice, + scrollToCreatedReply: scrollToCreatedReply + ) + let navigationController = UINavigationController(rootViewController: composer) + navigationController.modalPresentationStyle = .fullScreen + viewController?.present(navigationController, animated: true) + } + + func presentBoostComposer(onSubmit: @escaping (String) -> Void) { + let controller = FireBoostInputViewController() + controller.onSubmit = onSubmit + controller.modalPresentationStyle = .pageSheet + if let sheet = controller.sheetPresentationController { + // Keep a single medium detent. Custom short detents + keyboard overlap + // previously produced unsatisfiable top/bottom constraints. + sheet.detents = [.medium()] + sheet.prefersGrabberVisible = true + sheet.prefersScrollingExpandsWhenScrolledToEdge = false + sheet.preferredCornerRadius = 18 + } + viewController?.present(controller, animated: true) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Navigation.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Navigation.swift new file mode 100644 index 00000000..44992705 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+Navigation.swift @@ -0,0 +1,57 @@ +import SafariServices +import UIKit + +@MainActor +extension FireTopicDetailModalRouter { + func push(route: FireAppRoute) { + guard let navigationController = viewController?.navigationController else { return } + let topicRoutePresenter = FireAppRouteControllerFactory.makeTopicRoutePresenter( + viewModel: viewModel, + topicDetailStore: topicDetailStore, + navigationControllerProvider: { [weak navigationController] in navigationController } + ) + let controller = FireAppRouteControllerFactory.makeViewController( + viewModel: viewModel, + topicDetailStore: topicDetailStore, + route: route, + topicRoutePresenter: topicRoutePresenter + ) + navigationController.pushViewController(controller, animated: true) + } + + func push(filterRoute: FireTopicFilterRoute) { + guard let navigationController = viewController?.navigationController else { return } + let topicRoutePresenter = FireAppRouteControllerFactory.makeTopicRoutePresenter( + viewModel: viewModel, + topicDetailStore: topicDetailStore, + navigationControllerProvider: { [weak navigationController] in navigationController } + ) + let controller = FireFilteredTopicListViewController( + viewModel: viewModel, + topicDetailStore: topicDetailStore, + title: filterRoute.title, + categorySlug: filterRoute.categorySlug, + categoryId: filterRoute.categoryId, + parentCategorySlug: filterRoute.parentCategorySlug, + tag: filterRoute.tag, + topicRoutePresenter: topicRoutePresenter + ) + navigationController.pushViewController(controller, animated: true) + } + + func presentProfile(username: String) { + guard let viewController else { return } + FireUserCard.present(from: viewController, viewModel: viewModel, username: username) + } + + func presentWebLink(_ url: URL) { + let controller = SFSafariViewController(url: url) + viewController?.present(controller, animated: true) + } + + func presentImageViewer(image: FireCookedImage) { + guard let viewController else { return } + let controller = FireTopicPhotoBrowserController(image: image) + controller.present(from: viewController) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+PostModals.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+PostModals.swift new file mode 100644 index 00000000..078420be --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter+PostModals.swift @@ -0,0 +1,98 @@ +import SwiftUI +import UIKit + +@MainActor +extension FireTopicDetailModalRouter { + func presentFlagSheet( + topicID: UInt64, + context: FirePostManagementContext, + onSubmitted: @escaping @MainActor (String) -> Void + ) { + let rootView = FireTopicDetailFlagSheetHost( + store: topicDetailStore, + topicID: topicID, + context: context, + onSubmitted: onSubmitted + ) + presentSheetController(UIHostingController(rootView: rootView)) + } + + func presentTopicVoters(_ voters: [VotedUserState], isLoading: Bool) { + let rootView = NavigationStack { + FireTopicVotersSheet(voters: voters, isLoading: isLoading) + } + presentSheetController(UIHostingController(rootView: rootView)) + } + + func presentReactionPicker( + post: TopicPostState, + options: [FireReactionOption], + onSelectReaction: @escaping @MainActor (String) -> Void, + onShowUsers: @escaping @MainActor (String) -> Void + ) { + let rootView = NavigationStack { + FirePostReactionPickerSheet( + post: post, + options: options, + onSelectReaction: { [weak self] reactionID in + self?.viewController?.dismiss(animated: true) { + Task { @MainActor in + onSelectReaction(reactionID) + } + } + }, + onShowUsers: { [weak self] reactionID in + self?.viewController?.dismiss(animated: true) { + Task { @MainActor in + onShowUsers(reactionID) + } + } + } + ) + } + presentSheetController(UIHostingController(rootView: rootView)) + } + + func presentReactionUsers( + groups: [ReactionUsersGroupState], + reactionID: String? + ) { + let rootView = NavigationStack { + FireReactionUsersSheet(groups: groups, reactionID: reactionID) + } + presentSheetController(UIHostingController(rootView: rootView)) + } + + func presentPostReplies( + topicID: UInt64, + context: FirePostReplyContext, + baseURLString: String, + onJumpToPost: @escaping (UInt32) -> Void + ) { + let rootView = NavigationStack { + FireTopicDetailPostRepliesHost( + store: topicDetailStore, + topicID: topicID, + context: context, + baseURLString: baseURLString, + onJumpToPost: { [weak self] postNumber in + self?.viewController?.dismiss(animated: true) { + onJumpToPost(postNumber) + } + } + ) + } + presentSheetController(UIHostingController(rootView: rootView)) + } + + func presentSheetController(_ controller: UIViewController) { + if controller.view.backgroundColor == nil || controller.view.backgroundColor == .systemBackground { + controller.view.backgroundColor = FireTheme.uiCanvas + } + if let sheet = controller.sheetPresentationController { + sheet.detents = [.medium(), .large()] + sheet.prefersGrabberVisible = true + } + viewController?.present(controller, animated: true) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift index 9e18f4d0..bc8efa1d 100644 --- a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift @@ -4,9 +4,9 @@ import UIKit @MainActor final class FireTopicDetailModalRouter { - private weak var viewController: UIViewController? - private let viewModel: FireAppViewModel - private let topicDetailStore: FireTopicDetailStore + weak var viewController: UIViewController? + let viewModel: FireAppViewModel + let topicDetailStore: FireTopicDetailStore init( viewController: UIViewController, @@ -17,496 +17,4 @@ final class FireTopicDetailModalRouter { self.viewModel = viewModel self.topicDetailStore = topicDetailStore } - - func push(route: FireAppRoute) { - guard let navigationController = viewController?.navigationController else { return } - let topicRoutePresenter = FireAppRouteControllerFactory.makeTopicRoutePresenter( - viewModel: viewModel, - topicDetailStore: topicDetailStore, - navigationControllerProvider: { [weak navigationController] in navigationController } - ) - let controller = FireAppRouteControllerFactory.makeViewController( - viewModel: viewModel, - topicDetailStore: topicDetailStore, - route: route, - topicRoutePresenter: topicRoutePresenter - ) - navigationController.pushViewController(controller, animated: true) - } - - func push(filterRoute: FireTopicFilterRoute) { - guard let navigationController = viewController?.navigationController else { return } - let topicRoutePresenter = FireAppRouteControllerFactory.makeTopicRoutePresenter( - viewModel: viewModel, - topicDetailStore: topicDetailStore, - navigationControllerProvider: { [weak navigationController] in navigationController } - ) - let controller = FireFilteredTopicListViewController( - viewModel: viewModel, - topicDetailStore: topicDetailStore, - title: filterRoute.title, - categorySlug: filterRoute.categorySlug, - categoryId: filterRoute.categoryId, - parentCategorySlug: filterRoute.parentCategorySlug, - tag: filterRoute.tag, - topicRoutePresenter: topicRoutePresenter - ) - navigationController.pushViewController(controller, animated: true) - } - - func presentProfile(username: String) { - guard let viewController else { return } - FireUserCard.present(from: viewController, viewModel: viewModel, username: username) - } - - func presentWebLink(_ url: URL) { - let controller = SFSafariViewController(url: url) - viewController?.present(controller, animated: true) - } - - private func presentPrivateMessageComposer(username: String, displayName: String) { - let composer = FireComposerViewController( - viewModel: viewModel, - route: FireComposerRoute(kind: .privateMessage(recipients: [username], title: nil)), - onPrivateMessageCreated: { [weak self] topicID, title in - self?.push(route: .topic( - topicId: topicID, - postNumber: nil, - preview: FireTopicRoutePreview.fromMetadata(title: title, slug: nil) - )) - } - ) - let navigationController = UINavigationController(rootViewController: composer) - navigationController.modalPresentationStyle = .fullScreen - viewController?.present(navigationController, animated: true) - } - - func presentBookmarkEditor( - context: FireBookmarkEditorContext, - recoveryOriginURL: URL, - onReload: @escaping @MainActor () async -> Void - ) { - let rootView = FireBookmarkEditorSheet( - context: context, - onSave: { [viewModel] name, reminderAt in - if let bookmarkID = context.bookmarkID { - try await viewModel.topicInteraction.updateBookmark( - bookmarkID: bookmarkID, - name: name, - reminderAt: reminderAt, - recoveryOriginURL: recoveryOriginURL - ) - } else { - _ = try await viewModel.topicInteraction.createBookmark( - bookmarkableID: context.bookmarkableID, - bookmarkableType: context.bookmarkableType, - name: name, - reminderAt: reminderAt, - recoveryOriginURL: recoveryOriginURL - ) - } - await onReload() - }, - onDelete: context.bookmarkID.map { [viewModel] bookmarkID in - { - try await viewModel.topicInteraction.deleteBookmark( - bookmarkID: bookmarkID, - recoveryOriginURL: recoveryOriginURL - ) - await onReload() - } - } - ) - presentSheetController(UIHostingController(rootView: rootView)) - } - - func presentPostEditor( - topicID: UInt64, - context: FirePostEditorContext, - onSaved: @escaping @MainActor () async -> Void - ) { - let rootView = NavigationStack { - FirePostEditorView( - viewModel: viewModel, - topicID: topicID, - postID: context.postID, - postNumber: context.postNumber, - onSaved: { - Task { await onSaved() } - } - ) - } - presentSheetController(UIHostingController(rootView: rootView)) - } - - func presentTopicEditor( - topicID: UInt64, - initialTitle: String, - initialCategoryID: UInt64?, - initialTags: [String], - onSaved: @escaping @MainActor () async -> Void - ) { - let rootView = NavigationStack { - FireTopicEditorView( - viewModel: viewModel, - topicID: topicID, - initialTitle: initialTitle, - initialCategoryID: initialCategoryID, - initialTags: initialTags, - onSaved: { - Task { await onSaved() } - } - ) - } - presentSheetController(UIHostingController(rootView: rootView)) - } - - func presentFlagSheet( - topicID: UInt64, - context: FirePostManagementContext, - onSubmitted: @escaping @MainActor (String) -> Void - ) { - let rootView = FireTopicDetailFlagSheetHost( - store: topicDetailStore, - topicID: topicID, - context: context, - onSubmitted: onSubmitted - ) - presentSheetController(UIHostingController(rootView: rootView)) - } - - func presentTopicVoters(_ voters: [VotedUserState], isLoading: Bool) { - let rootView = NavigationStack { - FireTopicVotersSheet(voters: voters, isLoading: isLoading) - } - presentSheetController(UIHostingController(rootView: rootView)) - } - - func presentReactionPicker( - post: TopicPostState, - options: [FireReactionOption], - onSelectReaction: @escaping @MainActor (String) -> Void, - onShowUsers: @escaping @MainActor (String) -> Void - ) { - let rootView = NavigationStack { - FirePostReactionPickerSheet( - post: post, - options: options, - onSelectReaction: { [weak self] reactionID in - self?.viewController?.dismiss(animated: true) { - Task { @MainActor in - onSelectReaction(reactionID) - } - } - }, - onShowUsers: { [weak self] reactionID in - self?.viewController?.dismiss(animated: true) { - Task { @MainActor in - onShowUsers(reactionID) - } - } - } - ) - } - presentSheetController(UIHostingController(rootView: rootView)) - } - - func presentReactionUsers( - groups: [ReactionUsersGroupState], - reactionID: String? - ) { - let rootView = NavigationStack { - FireReactionUsersSheet(groups: groups, reactionID: reactionID) - } - presentSheetController(UIHostingController(rootView: rootView)) - } - - func presentPostReplies( - topicID: UInt64, - context: FirePostReplyContext, - baseURLString: String, - onJumpToPost: @escaping (UInt32) -> Void - ) { - let rootView = NavigationStack { - FireTopicDetailPostRepliesHost( - store: topicDetailStore, - topicID: topicID, - context: context, - baseURLString: baseURLString, - onJumpToPost: { [weak self] postNumber in - self?.viewController?.dismiss(animated: true) { - onJumpToPost(postNumber) - } - } - ) - } - presentSheetController(UIHostingController(rootView: rootView)) - } - - func presentAdvancedComposer( - route: FireComposerRoute, - initialBody: String, - initialBodySelectionLocation: Int? = nil, - onReplySubmitted: @escaping @MainActor () -> Void, - onSubmissionNotice: @escaping @MainActor (String) -> Void, - scrollToCreatedReply: Bool = false - ) { - let composer = FireComposerViewController( - viewModel: viewModel, - route: route, - initialBody: initialBody, - initialBodySelectionLocation: initialBodySelectionLocation, - onReplySubmitted: onReplySubmitted, - onSubmissionNotice: onSubmissionNotice, - scrollToCreatedReply: scrollToCreatedReply - ) - let navigationController = UINavigationController(rootViewController: composer) - navigationController.modalPresentationStyle = .fullScreen - viewController?.present(navigationController, animated: true) - } - - func presentImageViewer(image: FireCookedImage) { - guard let viewController else { return } - let controller = FireTopicPhotoBrowserController(image: image) - controller.present(from: viewController) - } - - func presentDeleteConfirmation( - postNumber: UInt32, - onConfirm: @escaping () -> Void - ) { - let alert = UIAlertController( - title: "删除回复", - message: "确认删除 #\(postNumber) 吗?", - preferredStyle: .alert - ) - alert.addAction(UIAlertAction(title: "取消", style: .cancel)) - alert.addAction(UIAlertAction(title: "删除", style: .destructive) { _ in - onConfirm() - }) - viewController?.present(alert, animated: true) - } - - func presentNotice(title: String = "提示", message: String) { - let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "知道了", style: .cancel)) - viewController?.present(alert, animated: true) - } - - func presentBoostComposer(onSubmit: @escaping (String) -> Void) { - let controller = FireBoostInputViewController() - controller.onSubmit = onSubmit - controller.modalPresentationStyle = .pageSheet - if let sheet = controller.sheetPresentationController { - // Keep a single medium detent. Custom short detents + keyboard overlap - // previously produced unsatisfiable top/bottom constraints. - sheet.detents = [.medium()] - sheet.prefersGrabberVisible = true - sheet.prefersScrollingExpandsWhenScrolledToEdge = false - sheet.preferredCornerRadius = 18 - } - viewController?.present(controller, animated: true) - } - - private func presentSheetController(_ controller: UIViewController) { - if controller.view.backgroundColor == nil || controller.view.backgroundColor == .systemBackground { - controller.view.backgroundColor = FireTheme.uiCanvas - } - if let sheet = controller.sheetPresentationController { - sheet.detents = [.medium(), .large()] - sheet.prefersGrabberVisible = true - } - viewController?.present(controller, animated: true) - } -} - -private struct FireTopicDetailFlagSheetHost: View { - @ObservedObject var store: FireTopicDetailStore - - let topicID: UInt64 - let context: FirePostManagementContext - let onSubmitted: @MainActor (String) -> Void - - @State private var isLoadingOptions = false - - var body: some View { - FirePostFlagSheet( - context: context, - options: FirePostFlagOption.options(from: store.snapshot(for: topicID)?.flagTypes ?? []), - isLoadingOptions: isLoadingOptions - ) { option, message in - try await store.flagPost( - topicId: topicID, - postId: context.postID, - flagTypeId: option.id, - message: message - ) - await MainActor.run { - onSubmitted("举报已提交。") - } - } - .task { - guard (store.snapshot(for: topicID)?.flagTypes ?? []).isEmpty else { - return - } - isLoadingOptions = true - defer { isLoadingOptions = false } - try? await store.ensureFlagTypes(topicId: topicID) - } - } -} - -private struct FireTopicUserInfoSheet: View { - @ObservedObject var viewModel: FireAppViewModel - let username: String - let onMessage: (UserProfileState) -> Void - - @State private var profile: UserProfileState? - @State private var summary: UserSummaryState? - @State private var isLoading = false - @State private var errorMessage: String? - - var body: some View { - VStack(alignment: .leading, spacing: 18) { - if let profile { - header(profile) - FireProfileStatsRow(items: [ - (formatNumber(summary?.stats.topicCount ?? 0), "话题"), - (formatNumber(summary?.stats.postCount ?? 0), "回复"), - (formatNumber(summary?.stats.likesReceived ?? 0), "获赞"), - (formatNumber(profile.totalFollowers), "粉丝"), - ]) - metaRows(profile) - if let bio = profile.bioPlainText?.trimmingCharacters(in: .whitespacesAndNewlines), - !bio.isEmpty { - Text(bio) - .font(.footnote) - .foregroundStyle(FireTheme.subtleInk) - .textSelection(.enabled) - .fixedSize(horizontal: false, vertical: true) - } - if canSendPrivateMessage(profile) { - Button { - onMessage(profile) - } label: { - Label("发私信", systemImage: "envelope") - .frame(maxWidth: .infinity) - } - .buttonStyle(.borderedProminent) - .tint(FireTheme.accent) - } - } else if isLoading { - ProgressView("正在加载用户信息...") - .frame(maxWidth: .infinity, alignment: .center) - } else { - Text(errorMessage ?? "无法加载用户信息。") - .font(.footnote) - .foregroundStyle(FireTheme.subtleInk) - } - } - .padding(20) - .frame(maxWidth: .infinity, alignment: .leading) - .task(id: username) { - await load() - } - } - - private func header(_ profile: UserProfileState) -> some View { - HStack(alignment: .center, spacing: 14) { - FireAvatarView( - avatarTemplate: profile.avatarTemplate, - username: profile.username, - size: 64, - baseURLString: viewModel.session.bootstrap.baseUrl.ifEmpty("https://linux.do") - ) - - VStack(alignment: .leading, spacing: 5) { - Text((profile.name ?? "").ifEmpty(profile.username)) - .font(.headline) - .foregroundStyle(FireTheme.ink) - Text("@\(profile.username) · \(profile.trustLevelLabel)") - .font(.caption) - .foregroundStyle(FireTheme.tertiaryInk) - } - } - } - - @ViewBuilder - private func metaRows(_ profile: UserProfileState) -> some View { - VStack(alignment: .leading, spacing: 10) { - if let createdAt = profile.createdAt, !createdAt.isEmpty { - FireProfileMetaEntryView(symbol: "calendar", label: "加入时间", value: createdAt) - } - if let lastSeenAt = profile.lastSeenAt, !lastSeenAt.isEmpty { - FireProfileMetaEntryView(symbol: "clock", label: "最近活跃", value: lastSeenAt) - } - if let score = profile.gamificationScore { - FireProfileMetaEntryView(symbol: "sparkles", label: "积分", value: formatNumber(score)) - } - } - } - - private func load() async { - let normalized = username.trimmingCharacters(in: .whitespacesAndNewlines) - guard !normalized.isEmpty else { return } - isLoading = true - errorMessage = nil - do { - async let fetchedProfile = viewModel.fetchUserProfile(username: normalized) - async let fetchedSummary = viewModel.fetchUserSummary(username: normalized) - let (profile, summary) = try await (fetchedProfile, fetchedSummary) - self.profile = profile - self.summary = summary - isLoading = false - } catch { - isLoading = false - errorMessage = error.localizedDescription - } - } - - private func canSendPrivateMessage(_ profile: UserProfileState) -> Bool { - let current = viewModel.session.bootstrap.currentUsername? - .trimmingCharacters(in: .whitespacesAndNewlines) - return current?.localizedCaseInsensitiveCompare(profile.username) != ComparisonResult.orderedSame - && profile.canSendPrivateMessageToUser - } - - private func formatNumber(_ value: UInt32) -> String { - if value >= 10_000 { - return String(format: "%.1f万", Double(value) / 10_000.0) - } - return "\(value)" - } -} - -private struct FireTopicDetailPostRepliesHost: View { - @ObservedObject var store: FireTopicDetailStore - - let topicID: UInt64 - let context: FirePostReplyContext - let baseURLString: String - let onJumpToPost: (UInt32) -> Void - - var body: some View { - let snapshot = store.snapshot(for: topicID) - let appendedIDs = Set(snapshot?.focusedReplyContext?.appendedPostIds ?? []) - let replies = (snapshot?.rows ?? []) - .filter { appendedIDs.contains($0.postId) } - .map(FireTopicDetailUiProjection.post(from:)) - FirePostRepliesSheet( - post: context.post, - replies: replies, - replyHistory: snapshot?.focusedReplyContext?.historyRows.map(FireTopicDetailUiProjection.post(from:)) ?? [], - isLoading: snapshot?.rows.contains { $0.postId == context.post.id && $0.isLoadingReplyContext } ?? false, - errorMessage: nil, - baseURLString: baseURLString, - onJumpToPost: onJumpToPost, - onRetry: { - store.loadReplyContext(topicId: topicID, postId: context.post.id) - } - ) - .task(id: context.post.id) { - store.loadReplyContext(topicId: topicID, postId: context.post.id) - } - } } diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailPostRepliesHost.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailPostRepliesHost.swift new file mode 100644 index 00000000..f8925119 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailPostRepliesHost.swift @@ -0,0 +1,33 @@ +import SwiftUI + +struct FireTopicDetailPostRepliesHost: View { + @ObservedObject var store: FireTopicDetailStore + + let topicID: UInt64 + let context: FirePostReplyContext + let baseURLString: String + let onJumpToPost: (UInt32) -> Void + + var body: some View { + let snapshot = store.snapshot(for: topicID) + let appendedIDs = Set(snapshot?.focusedReplyContext?.appendedPostIds ?? []) + let replies = (snapshot?.rows ?? []) + .filter { appendedIDs.contains($0.postId) } + .map(FireTopicDetailUiProjection.post(from:)) + FirePostRepliesSheet( + post: context.post, + replies: replies, + replyHistory: snapshot?.focusedReplyContext?.historyRows.map(FireTopicDetailUiProjection.post(from:)) ?? [], + isLoading: snapshot?.rows.contains { $0.postId == context.post.id && $0.isLoadingReplyContext } ?? false, + errorMessage: nil, + baseURLString: baseURLString, + onJumpToPost: onJumpToPost, + onRetry: { + store.loadReplyContext(topicId: topicID, postId: context.post.id) + } + ) + .task(id: context.post.id) { + store.loadReplyContext(topicId: topicID, postId: context.post.id) + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarActionsView.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarActionsView.swift new file mode 100644 index 00000000..a347640e --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarActionsView.swift @@ -0,0 +1,311 @@ +import UIKit + +final class FireTopicDetailToolbarActionsView: UIView { + struct Configuration: Equatable { + var shareURLAvailable: Bool + var showsNotification: Bool + var isBookmarked: Bool + var canWriteInteractions: Bool + var canEditTopic: Bool + var currentNotificationLevel: FireTopicNotificationLevelOption + var isExpanded: Bool + /// When false, the cluster stays fully expanded (header still visible). + var collapsesToOverflow: Bool + } + + private static let barHeight: CGFloat = 36 + private static let buttonSide: CGFloat = 32 + private static let horizontalInset: CGFloat = 6 + private static let interItemSpacing: CGFloat = 2 + + var onSearch: (() -> Void)? + var onShare: ((UIView) -> Void)? + var onExpand: (() -> Void)? + var onNotificationMenuAction: (() -> Void)? + var onSelectNotificationLevel: ((FireTopicNotificationLevelOption) -> Void)? + var onPresentTopicEditor: (() -> Void)? + var onPresentBookmarkEditor: (() -> Void)? + + private let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .systemChromeMaterial)) + private let stackView = UIStackView() + private let searchButton = UIButton(type: .system) + private let shareButton = UIButton(type: .system) + private let notificationButton = UIButton(type: .system) + private let editButton = UIButton(type: .system) + private let bookmarkButton = UIButton(type: .system) + /// Collapsed-only control that expands the action cluster. + private let overflowButton = UIButton(type: .system) + + private var configuration = Configuration( + shareURLAvailable: false, + showsNotification: true, + isBookmarked: false, + canWriteInteractions: false, + canEditTopic: false, + currentNotificationLevel: .regular, + isExpanded: true, + collapsesToOverflow: false + ) + + override init(frame: CGRect) { + super.init(frame: frame) + // Keep the root view frame-driven for UIBarButtonItem; only subviews use AL. + translatesAutoresizingMaskIntoConstraints = true + autoresizingMask = [.flexibleLeftMargin, .flexibleHeight] + // Actions own a fixed capsule width. Never let the titleView compress us. + setContentHuggingPriority(.required, for: .horizontal) + setContentCompressionResistancePriority(.required, for: .horizontal) + configureHierarchy() + apply(configuration: configuration, animated: false) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func apply(configuration: Configuration, animated: Bool) { + self.configuration = configuration + rebuildNotificationControl() + + // Expanded: flat action icons (search/share/bell/edit/bookmark), no overflow. + // Collapsed: only `...`, which expands the cluster inline. + let showCluster = configuration.isExpanded || !configuration.collapsesToOverflow + let showShare = showCluster && configuration.shareURLAvailable + let showNotification = showCluster && configuration.showsNotification + let showEdit = showCluster && configuration.canEditTopic + let showBookmark = showCluster + let showOverflow = !showCluster + let visibleCount = visibleButtonCount( + showCluster: showCluster, + showShare: showShare, + showNotification: showNotification, + showEdit: showEdit, + showBookmark: showBookmark + ) + let targetWidth = contentWidth(visibleButtonCount: visibleCount) + + let updates = { + self.setArranged(self.searchButton, visible: showCluster) + self.setArranged(self.shareButton, visible: showShare) + self.setArranged(self.notificationButton, visible: showNotification) + self.setArranged(self.editButton, visible: showEdit) + self.updateBookmarkButton(visible: showBookmark) + self.setArranged(self.overflowButton, visible: showOverflow) + self.setContentWidth(targetWidth) + self.layoutIfNeeded() + } + + if animated { + UIView.animate( + withDuration: FireTopicDetailToolbarCoordinator.animationDuration, + delay: 0, + usingSpringWithDamping: 0.88, + initialSpringVelocity: 0.25, + options: [.allowUserInteraction, .beginFromCurrentState], + animations: updates + ) + } else { + updates() + } + } + + override var intrinsicContentSize: CGSize { + CGSize(width: bounds.width > 0 ? bounds.width : contentWidth(visibleButtonCount: 1), height: Self.barHeight) + } + + override func sizeThatFits(_ size: CGSize) -> CGSize { + intrinsicContentSize + } + + private func configureHierarchy() { + backgroundView.translatesAutoresizingMaskIntoConstraints = false + backgroundView.clipsToBounds = true + backgroundView.layer.cornerRadius = Self.barHeight / 2 + backgroundView.layer.cornerCurve = .continuous + // Keep a portable material fill. `UIGlassEffect` is only in newer SDKs and + // breaks CI builds that compile against older Xcode toolchains. + backgroundView.effect = UIBlurEffect(style: .systemChromeMaterial) + + stackView.axis = .horizontal + stackView.alignment = .center + stackView.spacing = Self.interItemSpacing + stackView.translatesAutoresizingMaskIntoConstraints = false + // Hug content; width is owned by `setContentWidth`, not by stretching the stack. + stackView.setContentHuggingPriority(.required, for: .horizontal) + stackView.setContentCompressionResistancePriority(.required, for: .horizontal) + + addSubview(backgroundView) + addSubview(stackView) + + NSLayoutConstraint.activate([ + backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor), + backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor), + backgroundView.topAnchor.constraint(equalTo: topAnchor), + backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor), + + // Leading + intrinsic stack width only. Do not pin trailing to the + // bar-button wrapper — UINavigationBar may temporarily keep an old + // autoresizing width while we animate bounds, and a trailing pin would + // fight the fixed button widths. + stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Self.horizontalInset), + stackView.centerYAnchor.constraint(equalTo: centerYAnchor), + ]) + + configureIconButton(searchButton, systemName: "magnifyingglass", accessibilityLabel: "搜索已加载帖子") + searchButton.addAction(UIAction { [weak self] _ in + self?.onSearch?() + }, for: .touchUpInside) + + configureIconButton(shareButton, systemName: "square.and.arrow.up", accessibilityLabel: "分享话题") + shareButton.addAction(UIAction { [weak self] _ in + guard let self else { return } + self.onShare?(self.shareButton) + }, for: .touchUpInside) + + configureIconButton( + notificationButton, + systemName: configuration.currentNotificationLevel.systemImageName, + accessibilityLabel: notificationAccessibilityLabel( + for: configuration.currentNotificationLevel + ) + ) + // One-tap cycle through levels — no menu popup. + notificationButton.addAction(UIAction { [weak self] _ in + self?.cycleNotificationLevel() + }, for: .touchUpInside) + + configureIconButton(editButton, systemName: "pencil", accessibilityLabel: "编辑话题") + editButton.addAction(UIAction { [weak self] _ in + self?.onPresentTopicEditor?() + }, for: .touchUpInside) + + configureIconButton(bookmarkButton, systemName: "bookmark", accessibilityLabel: "添加书签") + bookmarkButton.addAction(UIAction { [weak self] _ in + self?.onPresentBookmarkEditor?() + }, for: .touchUpInside) + + configureIconButton(overflowButton, systemName: "ellipsis.circle", accessibilityLabel: "展开话题操作") + overflowButton.addAction(UIAction { [weak self] _ in + self?.onExpand?() + }, for: .touchUpInside) + + [searchButton, shareButton, notificationButton, editButton, bookmarkButton, overflowButton].forEach { button in + stackView.addArrangedSubview(button) + button.translatesAutoresizingMaskIntoConstraints = false + // Fixed icon slots; required is safe because outer width always matches + // the number of currently visible slots. + let width = button.widthAnchor.constraint(equalToConstant: Self.buttonSide) + let height = button.heightAnchor.constraint(equalToConstant: Self.buttonSide) + width.isActive = true + height.isActive = true + } + } + + private func configureIconButton( + _ button: UIButton, + systemName: String, + accessibilityLabel: String + ) { + var configuration = UIButton.Configuration.plain() + configuration.image = UIImage(systemName: systemName) + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration( + pointSize: 15, + weight: .semibold + ) + configuration.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 6) + configuration.baseForegroundColor = FireTheme.uiInk + button.configuration = configuration + button.accessibilityLabel = accessibilityLabel + } + + private func setArranged(_ button: UIButton, visible: Bool) { + button.isHidden = !visible + button.alpha = visible ? 1 : 0 + button.isAccessibilityElement = visible + } + + private func updateBookmarkButton(visible: Bool) { + let symbolName = configuration.isBookmarked ? "bookmark.fill" : "bookmark" + applySymbol(bookmarkButton, systemName: symbolName) + bookmarkButton.accessibilityLabel = configuration.isBookmarked ? "编辑书签" : "添加书签" + bookmarkButton.isEnabled = configuration.canWriteInteractions + setArranged(bookmarkButton, visible: visible) + } + + private func applySymbol(_ button: UIButton, systemName: String) { + var configuration = button.configuration ?? .plain() + configuration.image = UIImage(systemName: systemName) + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration( + pointSize: 15, + weight: .semibold + ) + configuration.baseForegroundColor = FireTheme.uiInk + button.configuration = configuration + } + + private func visibleButtonCount( + showCluster: Bool, + showShare: Bool, + showNotification: Bool, + showEdit: Bool, + showBookmark: Bool + ) -> Int { + if !showCluster { + return 1 // overflow only + } + var count = 1 // search + if showShare { count += 1 } + if showNotification { count += 1 } + if showEdit { count += 1 } + if showBookmark { count += 1 } + return count + } + + private func contentWidth(visibleButtonCount: Int) -> CGFloat { + let count = CGFloat(max(visibleButtonCount, 1)) + return Self.horizontalInset * 2 + + count * Self.buttonSide + + max(0, count - 1) * Self.interItemSpacing + } + + private func setContentWidth(_ width: CGFloat) { + let size = CGSize(width: width, height: Self.barHeight) + // UINavigationBar reads the custom view's bounds through an autoresizing + // wrapper. Updating bounds/frame keeps that wrapper aligned with content. + bounds = CGRect(origin: .zero, size: size) + frame = CGRect(origin: frame.origin, size: size) + invalidateIntrinsicContentSize() + } + + private func rebuildNotificationControl() { + guard configuration.showsNotification else { return } + notificationButton.showsMenuAsPrimaryAction = false + notificationButton.menu = nil + notificationButton.isEnabled = configuration.canWriteInteractions + notificationButton.accessibilityLabel = notificationAccessibilityLabel( + for: configuration.currentNotificationLevel + ) + applySymbol(notificationButton, systemName: configuration.currentNotificationLevel.systemImageName) + } + + private func cycleNotificationLevel() { + guard configuration.canWriteInteractions else { return } + let next = configuration.currentNotificationLevel.nextCycledLevel + // Optimistic glyph update so the tap feels immediate; chrome refresh will + // reconcile from server state after the write completes. + configuration.currentNotificationLevel = next + applySymbol(notificationButton, systemName: next.systemImageName) + notificationButton.accessibilityLabel = notificationAccessibilityLabel(for: next) + onNotificationMenuAction?() + onSelectNotificationLevel?(next) + } + + private func notificationAccessibilityLabel( + for level: FireTopicNotificationLevelOption + ) -> String { + "通知设置:\(level.title),点击切换" + } +} + +// MARK: - Scroll metrics diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift index f40760ac..663114c2 100644 --- a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift @@ -15,8 +15,8 @@ final class FireTopicDetailToolbarCoordinator { let onUpdateNotificationLevel: (FireTopicNotificationLevelOption) -> Void } - fileprivate static let autoCollapseDelay: TimeInterval = 3.0 - fileprivate static let animationDuration: TimeInterval = 0.24 + static let autoCollapseDelay: TimeInterval = 3.0 + static let animationDuration: TimeInterval = 0.24 private weak var viewController: UIViewController? private let actions: Actions @@ -249,433 +249,3 @@ final class FireTopicDetailToolbarCoordinator { viewController.present(activityVC, animated: true) } } - -// MARK: - Title label - -private final class FireTopicDetailToolbarTitleLabel: UIView { - private let label = UILabel() - private var isTitleVisible = false - - override init(frame: CGRect) { - super.init(frame: frame) - isUserInteractionEnabled = false - isAccessibilityElement = false - // Title must yield horizontal space to trailing actions. Publishing a - // content-sized width lets long titles compete with (and shove) icons. - setContentHuggingPriority(.defaultLow, for: .horizontal) - setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - - label.translatesAutoresizingMaskIntoConstraints = false - label.font = .preferredFont(forTextStyle: .headline) - label.adjustsFontForContentSizeCategory = true - label.textColor = FireTheme.uiInk - label.textAlignment = .center - label.lineBreakMode = .byTruncatingTail - label.numberOfLines = 1 - label.alpha = 0 - label.setContentHuggingPriority(.defaultLow, for: .horizontal) - label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - - addSubview(label) - NSLayoutConstraint.activate([ - label.leadingAnchor.constraint(equalTo: leadingAnchor), - label.trailingAnchor.constraint(equalTo: trailingAnchor), - label.topAnchor.constraint(equalTo: topAnchor), - label.bottomAnchor.constraint(equalTo: bottomAnchor), - heightAnchor.constraint(greaterThanOrEqualToConstant: FireTopicDetailToolbarTitleMetrics.minimumHeight), - ]) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - func setTitle(_ text: String, visible: Bool, animated: Bool) { - isTitleVisible = visible - let updates = { - self.label.text = text - self.label.alpha = visible ? 1 : 0 - self.isAccessibilityElement = visible - self.accessibilityLabel = visible ? "话题标题:\(text)" : nil - self.invalidateIntrinsicContentSize() - } - if animated { - UIView.animate( - withDuration: FireTopicDetailToolbarCoordinator.animationDuration, - delay: 0, - options: [.curveEaseInOut, .beginFromCurrentState, .allowUserInteraction], - animations: updates - ) - } else { - updates() - } - } - - override var intrinsicContentSize: CGSize { - FireTopicDetailToolbarTitleMetrics.preferredIntrinsicSize( - isVisible: isTitleVisible, - labelHeight: label.intrinsicContentSize.height - ) - } - - override func sizeThatFits(_ size: CGSize) -> CGSize { - // Accept whatever width the navigation bar assigns after reserving - // left/right items; height stays compact for the single-line title. - let intrinsic = intrinsicContentSize - let width = size.width > 0 ? size.width : intrinsic.width - return CGSize(width: width, height: intrinsic.height) - } -} - -// MARK: - Actions cluster - -private final class FireTopicDetailToolbarActionsView: UIView { - struct Configuration: Equatable { - var shareURLAvailable: Bool - var showsNotification: Bool - var isBookmarked: Bool - var canWriteInteractions: Bool - var canEditTopic: Bool - var currentNotificationLevel: FireTopicNotificationLevelOption - var isExpanded: Bool - /// When false, the cluster stays fully expanded (header still visible). - var collapsesToOverflow: Bool - } - - private static let barHeight: CGFloat = 36 - private static let buttonSide: CGFloat = 32 - private static let horizontalInset: CGFloat = 6 - private static let interItemSpacing: CGFloat = 2 - - var onSearch: (() -> Void)? - var onShare: ((UIView) -> Void)? - var onExpand: (() -> Void)? - var onNotificationMenuAction: (() -> Void)? - var onSelectNotificationLevel: ((FireTopicNotificationLevelOption) -> Void)? - var onPresentTopicEditor: (() -> Void)? - var onPresentBookmarkEditor: (() -> Void)? - - private let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .systemChromeMaterial)) - private let stackView = UIStackView() - private let searchButton = UIButton(type: .system) - private let shareButton = UIButton(type: .system) - private let notificationButton = UIButton(type: .system) - private let editButton = UIButton(type: .system) - private let bookmarkButton = UIButton(type: .system) - /// Collapsed-only control that expands the action cluster. - private let overflowButton = UIButton(type: .system) - - private var configuration = Configuration( - shareURLAvailable: false, - showsNotification: true, - isBookmarked: false, - canWriteInteractions: false, - canEditTopic: false, - currentNotificationLevel: .regular, - isExpanded: true, - collapsesToOverflow: false - ) - - override init(frame: CGRect) { - super.init(frame: frame) - // Keep the root view frame-driven for UIBarButtonItem; only subviews use AL. - translatesAutoresizingMaskIntoConstraints = true - autoresizingMask = [.flexibleLeftMargin, .flexibleHeight] - // Actions own a fixed capsule width. Never let the titleView compress us. - setContentHuggingPriority(.required, for: .horizontal) - setContentCompressionResistancePriority(.required, for: .horizontal) - configureHierarchy() - apply(configuration: configuration, animated: false) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - func apply(configuration: Configuration, animated: Bool) { - self.configuration = configuration - rebuildNotificationControl() - - // Expanded: flat action icons (search/share/bell/edit/bookmark), no overflow. - // Collapsed: only `...`, which expands the cluster inline. - let showCluster = configuration.isExpanded || !configuration.collapsesToOverflow - let showShare = showCluster && configuration.shareURLAvailable - let showNotification = showCluster && configuration.showsNotification - let showEdit = showCluster && configuration.canEditTopic - let showBookmark = showCluster - let showOverflow = !showCluster - let visibleCount = visibleButtonCount( - showCluster: showCluster, - showShare: showShare, - showNotification: showNotification, - showEdit: showEdit, - showBookmark: showBookmark - ) - let targetWidth = contentWidth(visibleButtonCount: visibleCount) - - let updates = { - self.setArranged(self.searchButton, visible: showCluster) - self.setArranged(self.shareButton, visible: showShare) - self.setArranged(self.notificationButton, visible: showNotification) - self.setArranged(self.editButton, visible: showEdit) - self.updateBookmarkButton(visible: showBookmark) - self.setArranged(self.overflowButton, visible: showOverflow) - self.setContentWidth(targetWidth) - self.layoutIfNeeded() - } - - if animated { - UIView.animate( - withDuration: FireTopicDetailToolbarCoordinator.animationDuration, - delay: 0, - usingSpringWithDamping: 0.88, - initialSpringVelocity: 0.25, - options: [.allowUserInteraction, .beginFromCurrentState], - animations: updates - ) - } else { - updates() - } - } - - override var intrinsicContentSize: CGSize { - CGSize(width: bounds.width > 0 ? bounds.width : contentWidth(visibleButtonCount: 1), height: Self.barHeight) - } - - override func sizeThatFits(_ size: CGSize) -> CGSize { - intrinsicContentSize - } - - private func configureHierarchy() { - backgroundView.translatesAutoresizingMaskIntoConstraints = false - backgroundView.clipsToBounds = true - backgroundView.layer.cornerRadius = Self.barHeight / 2 - backgroundView.layer.cornerCurve = .continuous - // Keep a portable material fill. `UIGlassEffect` is only in newer SDKs and - // breaks CI builds that compile against older Xcode toolchains. - backgroundView.effect = UIBlurEffect(style: .systemChromeMaterial) - - stackView.axis = .horizontal - stackView.alignment = .center - stackView.spacing = Self.interItemSpacing - stackView.translatesAutoresizingMaskIntoConstraints = false - // Hug content; width is owned by `setContentWidth`, not by stretching the stack. - stackView.setContentHuggingPriority(.required, for: .horizontal) - stackView.setContentCompressionResistancePriority(.required, for: .horizontal) - - addSubview(backgroundView) - addSubview(stackView) - - NSLayoutConstraint.activate([ - backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor), - backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor), - backgroundView.topAnchor.constraint(equalTo: topAnchor), - backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor), - - // Leading + intrinsic stack width only. Do not pin trailing to the - // bar-button wrapper — UINavigationBar may temporarily keep an old - // autoresizing width while we animate bounds, and a trailing pin would - // fight the fixed button widths. - stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Self.horizontalInset), - stackView.centerYAnchor.constraint(equalTo: centerYAnchor), - ]) - - configureIconButton(searchButton, systemName: "magnifyingglass", accessibilityLabel: "搜索已加载帖子") - searchButton.addAction(UIAction { [weak self] _ in - self?.onSearch?() - }, for: .touchUpInside) - - configureIconButton(shareButton, systemName: "square.and.arrow.up", accessibilityLabel: "分享话题") - shareButton.addAction(UIAction { [weak self] _ in - guard let self else { return } - self.onShare?(self.shareButton) - }, for: .touchUpInside) - - configureIconButton( - notificationButton, - systemName: configuration.currentNotificationLevel.systemImageName, - accessibilityLabel: notificationAccessibilityLabel( - for: configuration.currentNotificationLevel - ) - ) - // One-tap cycle through levels — no menu popup. - notificationButton.addAction(UIAction { [weak self] _ in - self?.cycleNotificationLevel() - }, for: .touchUpInside) - - configureIconButton(editButton, systemName: "pencil", accessibilityLabel: "编辑话题") - editButton.addAction(UIAction { [weak self] _ in - self?.onPresentTopicEditor?() - }, for: .touchUpInside) - - configureIconButton(bookmarkButton, systemName: "bookmark", accessibilityLabel: "添加书签") - bookmarkButton.addAction(UIAction { [weak self] _ in - self?.onPresentBookmarkEditor?() - }, for: .touchUpInside) - - configureIconButton(overflowButton, systemName: "ellipsis.circle", accessibilityLabel: "展开话题操作") - overflowButton.addAction(UIAction { [weak self] _ in - self?.onExpand?() - }, for: .touchUpInside) - - [searchButton, shareButton, notificationButton, editButton, bookmarkButton, overflowButton].forEach { button in - stackView.addArrangedSubview(button) - button.translatesAutoresizingMaskIntoConstraints = false - // Fixed icon slots; required is safe because outer width always matches - // the number of currently visible slots. - let width = button.widthAnchor.constraint(equalToConstant: Self.buttonSide) - let height = button.heightAnchor.constraint(equalToConstant: Self.buttonSide) - width.isActive = true - height.isActive = true - } - } - - private func configureIconButton( - _ button: UIButton, - systemName: String, - accessibilityLabel: String - ) { - var configuration = UIButton.Configuration.plain() - configuration.image = UIImage(systemName: systemName) - configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration( - pointSize: 15, - weight: .semibold - ) - configuration.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 6) - configuration.baseForegroundColor = FireTheme.uiInk - button.configuration = configuration - button.accessibilityLabel = accessibilityLabel - } - - private func setArranged(_ button: UIButton, visible: Bool) { - button.isHidden = !visible - button.alpha = visible ? 1 : 0 - button.isAccessibilityElement = visible - } - - private func updateBookmarkButton(visible: Bool) { - let symbolName = configuration.isBookmarked ? "bookmark.fill" : "bookmark" - applySymbol(bookmarkButton, systemName: symbolName) - bookmarkButton.accessibilityLabel = configuration.isBookmarked ? "编辑书签" : "添加书签" - bookmarkButton.isEnabled = configuration.canWriteInteractions - setArranged(bookmarkButton, visible: visible) - } - - private func applySymbol(_ button: UIButton, systemName: String) { - var configuration = button.configuration ?? .plain() - configuration.image = UIImage(systemName: systemName) - configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration( - pointSize: 15, - weight: .semibold - ) - configuration.baseForegroundColor = FireTheme.uiInk - button.configuration = configuration - } - - private func visibleButtonCount( - showCluster: Bool, - showShare: Bool, - showNotification: Bool, - showEdit: Bool, - showBookmark: Bool - ) -> Int { - if !showCluster { - return 1 // overflow only - } - var count = 1 // search - if showShare { count += 1 } - if showNotification { count += 1 } - if showEdit { count += 1 } - if showBookmark { count += 1 } - return count - } - - private func contentWidth(visibleButtonCount: Int) -> CGFloat { - let count = CGFloat(max(visibleButtonCount, 1)) - return Self.horizontalInset * 2 - + count * Self.buttonSide - + max(0, count - 1) * Self.interItemSpacing - } - - private func setContentWidth(_ width: CGFloat) { - let size = CGSize(width: width, height: Self.barHeight) - // UINavigationBar reads the custom view's bounds through an autoresizing - // wrapper. Updating bounds/frame keeps that wrapper aligned with content. - bounds = CGRect(origin: .zero, size: size) - frame = CGRect(origin: frame.origin, size: size) - invalidateIntrinsicContentSize() - } - - private func rebuildNotificationControl() { - guard configuration.showsNotification else { return } - notificationButton.showsMenuAsPrimaryAction = false - notificationButton.menu = nil - notificationButton.isEnabled = configuration.canWriteInteractions - notificationButton.accessibilityLabel = notificationAccessibilityLabel( - for: configuration.currentNotificationLevel - ) - applySymbol(notificationButton, systemName: configuration.currentNotificationLevel.systemImageName) - } - - private func cycleNotificationLevel() { - guard configuration.canWriteInteractions else { return } - let next = configuration.currentNotificationLevel.nextCycledLevel - // Optimistic glyph update so the tap feels immediate; chrome refresh will - // reconcile from server state after the write completes. - configuration.currentNotificationLevel = next - applySymbol(notificationButton, systemName: next.systemImageName) - notificationButton.accessibilityLabel = notificationAccessibilityLabel(for: next) - onNotificationMenuAction?() - onSelectNotificationLevel?(next) - } - - private func notificationAccessibilityLabel( - for level: FireTopicNotificationLevelOption - ) -> String { - "通知设置:\(level.title),点击切换" - } -} - -// MARK: - Scroll metrics - -enum FireTopicDetailToolbarChromeMetrics { - /// Approximate distance from the header cell top to below its title band. - static let headerTitleBandHeight: CGFloat = 52 - - static func isTitlePinned( - headerFrame: CGRect?, - visibleTop: CGFloat - ) -> Bool { - if let headerFrame { - return headerFrame.minY + headerTitleBandHeight <= visibleTop + 0.5 - } - return visibleTop > 24 - } -} - -enum FireTopicDetailToolbarTitleMetrics { - static let minimumHeight: CGFloat = 24 - - /// Title views must not publish a content-sized width. - /// - /// Publishing the text width (even capped) makes `UINavigationBar` treat the - /// title as a fixed peer of the trailing actions, so long titles shove icons - /// toward — or past — the screen edge. Request expanded width instead; the - /// bar assigns leftover space between back and actions, and the label - /// truncates inside those bounds. - static func preferredIntrinsicSize( - isVisible: Bool, - labelHeight: CGFloat - ) -> CGSize { - let height = max(labelHeight, minimumHeight) - guard isVisible else { - return CGSize(width: UIView.noIntrinsicMetric, height: height) - } - return CGSize( - width: UIView.layoutFittingExpandedSize.width, - height: height - ) - } -} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarMetrics.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarMetrics.swift new file mode 100644 index 00000000..84c9bac7 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarMetrics.swift @@ -0,0 +1,41 @@ +import UIKit + +enum FireTopicDetailToolbarChromeMetrics { + /// Approximate distance from the header cell top to below its title band. + static let headerTitleBandHeight: CGFloat = 52 + + static func isTitlePinned( + headerFrame: CGRect?, + visibleTop: CGFloat + ) -> Bool { + if let headerFrame { + return headerFrame.minY + headerTitleBandHeight <= visibleTop + 0.5 + } + return visibleTop > 24 + } +} + +enum FireTopicDetailToolbarTitleMetrics { + static let minimumHeight: CGFloat = 24 + + /// Title views must not publish a content-sized width. + /// + /// Publishing the text width (even capped) makes `UINavigationBar` treat the + /// title as a fixed peer of the trailing actions, so long titles shove icons + /// toward — or past — the screen edge. Request expanded width instead; the + /// bar assigns leftover space between back and actions, and the label + /// truncates inside those bounds. + static func preferredIntrinsicSize( + isVisible: Bool, + labelHeight: CGFloat + ) -> CGSize { + let height = max(labelHeight, minimumHeight) + guard isVisible else { + return CGSize(width: UIView.noIntrinsicMetric, height: height) + } + return CGSize( + width: UIView.layoutFittingExpandedSize.width, + height: height + ) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarTitleView.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarTitleView.swift new file mode 100644 index 00000000..0c61652c --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarTitleView.swift @@ -0,0 +1,77 @@ +import UIKit + +final class FireTopicDetailToolbarTitleLabel: UIView { + private let label = UILabel() + private var isTitleVisible = false + + override init(frame: CGRect) { + super.init(frame: frame) + isUserInteractionEnabled = false + isAccessibilityElement = false + // Title must yield horizontal space to trailing actions. Publishing a + // content-sized width lets long titles compete with (and shove) icons. + setContentHuggingPriority(.defaultLow, for: .horizontal) + setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + + label.translatesAutoresizingMaskIntoConstraints = false + label.font = .preferredFont(forTextStyle: .headline) + label.adjustsFontForContentSizeCategory = true + label.textColor = FireTheme.uiInk + label.textAlignment = .center + label.lineBreakMode = .byTruncatingTail + label.numberOfLines = 1 + label.alpha = 0 + label.setContentHuggingPriority(.defaultLow, for: .horizontal) + label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + + addSubview(label) + NSLayoutConstraint.activate([ + label.leadingAnchor.constraint(equalTo: leadingAnchor), + label.trailingAnchor.constraint(equalTo: trailingAnchor), + label.topAnchor.constraint(equalTo: topAnchor), + label.bottomAnchor.constraint(equalTo: bottomAnchor), + heightAnchor.constraint(greaterThanOrEqualToConstant: FireTopicDetailToolbarTitleMetrics.minimumHeight), + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func setTitle(_ text: String, visible: Bool, animated: Bool) { + isTitleVisible = visible + let updates = { + self.label.text = text + self.label.alpha = visible ? 1 : 0 + self.isAccessibilityElement = visible + self.accessibilityLabel = visible ? "话题标题:\(text)" : nil + self.invalidateIntrinsicContentSize() + } + if animated { + UIView.animate( + withDuration: FireTopicDetailToolbarCoordinator.animationDuration, + delay: 0, + options: [.curveEaseInOut, .beginFromCurrentState, .allowUserInteraction], + animations: updates + ) + } else { + updates() + } + } + + override var intrinsicContentSize: CGSize { + FireTopicDetailToolbarTitleMetrics.preferredIntrinsicSize( + isVisible: isTitleVisible, + labelHeight: label.intrinsicContentSize.height + ) + } + + override func sizeThatFits(_ size: CGSize) -> CGSize { + // Accept whatever width the navigation bar assigns after reserving + // left/right items; height stays compact for the single-line title. + let intrinsic = intrinsicContentSize + let width = size.width > 0 ? size.width : intrinsic.width + return CGSize(width: width, height: intrinsic.height) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Appearance.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Appearance.swift new file mode 100644 index 00000000..ab98ae67 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Appearance.swift @@ -0,0 +1,47 @@ +import Combine +import UIKit + +@MainActor +extension FireTopicDetailViewController { + func bindColorAppearanceObservers() { + // Single bus from Environment (preference write / storage sync). Avoid also + // listening to the NotificationCenter name here — same event would re-apply twice. + FireAppearanceEnvironment.snapshotPublisher + .receive(on: RunLoop.main) + .sink { [weak self] snapshot in + self?.applyAppearance(snapshot) + } + .store(in: &appearanceCancellables) + } + + func handleColorAppearanceChange(reason: String) { + let snapshot = FireAppearanceEnvironment.snapshot(for: view, window: view.window) + applyAppearance(snapshot) + viewModel.topicDetailLogger()?.debug( + "topic detail appearance reason=\(reason) token=\(snapshot.token)" + ) + } + + /// Shell layers that sit outside factory cell rebuilds (VC view + Texture root). + func applyAppearanceShell(_ snapshot: FireAppearanceSnapshot? = nil) { + let resolved = snapshot ?? FireAppearanceEnvironment.snapshot(for: view, window: view.window) + FireAppearanceTexture.applySnapshot(resolved, to: view) + rootNode.applyAppearance(resolved) + feedController.assertFeedShellAppearance(resolved) + configureNavigationAppearance() + } +} + +extension FireTopicDetailViewController: FireAppearanceApplying { + func applyAppearance(_ snapshot: FireAppearanceSnapshot) { + let style = snapshot.userInterfaceStyle + let styleChanged = lastColorAppearanceStyle != style + lastColorAppearanceStyle = style + viewModel.topicDetailLogger()?.info( + "topic detail applyAppearance topic_id=\(row.topic.id) style=\(style.rawValue) token=\(snapshot.token) style_changed=\(styleChanged)" + ) + applyAppearanceShell(snapshot) + quickReplyBar.applyThemeColorsIfNeeded() + feedController.refreshColorAppearance(snapshot) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Keyboard.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Keyboard.swift new file mode 100644 index 00000000..6eaec4d7 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Keyboard.swift @@ -0,0 +1,97 @@ +import Combine +import UIKit + +@MainActor +extension FireTopicDetailViewController { + func subscribeToKeyboardNotifications() { + // Deliver synchronously on the posting thread (main). Do not hop through + // RunLoop.main / DispatchQueue.main — that defers handling by a turn and + // makes the quick-reply bar lag behind the keyboard after swipe-to-reply. + NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification) + .merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) + .sink { [weak self] notification in + self?.handleKeyboardNotification(notification) + } + .store(in: &cancellables) + } + + func handleKeyboardNotification(_ notification: Notification) { + if notification.name == UIResponder.keyboardWillHideNotification { + keyboardFrameInScreen = .null + } else { + keyboardFrameInScreen = + (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect) ?? .null + } + updateBottomChromeInset(animatedWith: notification) + } + + func updateBottomChromeInset(animatedWith notification: Notification? = nil) { + // WeChat-style bottom input — pure UIKit, no Texture overlay: + // + // 1) Bar internal bottom padding + // - keyboard hidden → home-indicator safe area + // - keyboard up → small pad (keyboard covers home indicator) + // 2) Keyboard overlap → bar bottom constraint constant + // 3) Feed contentInset.bottom = barHeight + keyboardOverlap + let keyboardOverlap = keyboardOverlapHeight + let keyboardVisible = keyboardOverlap > 0.5 + let homeIndicator = view.safeAreaInsets.bottom + let barBottomPadding: CGFloat = keyboardVisible ? 8 : homeIndicator + + quickReplyBar.updateBottomInset(barBottomPadding) + + let previousBottom = quickReplyBottomConstraint?.constant ?? 0 + let previousHeight = quickReplyHeightConstraint?.constant ?? 0 + let measuredBarHeight = quickReplyBar.preferredHeight(forWidth: max(view.bounds.width, 1)) + quickReplyBottomConstraint?.constant = -keyboardOverlap + quickReplyHeightConstraint?.constant = measuredBarHeight + + let barVisible = !quickReplyBar.isHidden + let feedBottom = fireTopicDetailFeedBottomInset( + quickReplyBarHeight: measuredBarHeight, + safeAreaBottom: homeIndicator, + keyboardOverlap: keyboardOverlap, + isQuickReplyVisible: barVisible + ) + rootNode.updateFeedBottomInset(feedBottom) + updateFeedTopInset() + view.bringSubviewToFront(quickReplyBar) + + let geometryChanged = + abs(previousBottom + keyboardOverlap) > 0.5 + || abs(previousHeight - measuredBarHeight) > 0.5 + + guard geometryChanged || notification != nil else { return } + + if let notification { + let duration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)? + .doubleValue ?? 0.25 + let curveRawValue = (notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)? + .uintValue ?? UInt(UIView.AnimationCurve.easeInOut.rawValue) + // Keyboard uses a private curve (rawValue 7). Shift into + // UIView.AnimationOptions so the bar tracks the system animation. + let options = UIView.AnimationOptions(rawValue: curveRawValue << 16) + UIView.animate( + withDuration: duration, + delay: 0, + options: [options, .beginFromCurrentState, .allowUserInteraction] + ) { + self.view.layoutIfNeeded() + } + } + // Non-keyboard geometry commits on the next layout pass, or via an + // explicit layoutIfNeeded() in presentQuickReplyInput() before focus. + } + + var currentSearchBarHeight: CGFloat { + topicSearchBar.isHidden ? 0 : topicSearchBar.bounds.height + } + + var keyboardOverlapHeight: CGFloat { + guard !keyboardFrameInScreen.isNull else { + return 0 + } + let frameInView = view.convert(keyboardFrameInScreen, from: nil) + return max(view.bounds.intersection(frameInView).height, 0) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Lifecycle.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Lifecycle.swift new file mode 100644 index 00000000..e289bccf --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Lifecycle.swift @@ -0,0 +1,177 @@ +import Combine +import UIKit + +@MainActor +extension FireTopicDetailViewController { + func beginPageLifecycle() { + viewModel.topicDetailLogger()?.info( + "topic detail lifecycle begin topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" + ) + let hasReadySnapshot = topicDetailStore.snapshot(for: row.topic.id)?.phase == .ready + topicDetailStore.open( + topicId: row.topic.id, + ownerToken: detailOwnerToken, + slug: displayedTopicSlug.isEmpty ? nil : displayedTopicSlug, + targetPostNumber: scrollToPostNumber, + bypassCache: false, + forceLoad: false, + trackVisit: true, + allowSuggestedUnreadRoot: scrollToPostNumber == nil && !hasReadySnapshot + ) + + timingTracker.start { [weak viewModel] topicId, topicTimeMs, timings in + guard let viewModel else { return false } + return await viewModel.topicInteraction.reportTopicTimings( + topicId: topicId, + topicTimeMs: topicTimeMs, + timings: timings + ) + } + + subscribeToKeyboardNotifications() + subscribeToStoreRevisions() + kickOffInitialLoad() + // The Rust topic session subscribes to detail, reactions, polls, and presence. + viewModel.topicDetailLogger()?.debug( + "topic detail lifecycle begin scheduled tasks topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" + ) + } + + func endPageLifecycle() { + viewModel.topicDetailLogger()?.info( + "topic detail lifecycle end topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" + ) + initialLoadTask?.cancel() + initialLoadTask = nil + subscriptionTask?.cancel() + subscriptionTask = nil + snapshotBuildTask?.cancel() + snapshotBuildTask = nil + cancellables.removeAll() + topicDetailStore.noteScrollInteraction(topicId: row.topic.id, active: false) + + topicDetailStore.close(topicId: row.topic.id, ownerToken: detailOwnerToken) + } + + func kickOffInitialLoad() { + initialLoadTask?.cancel() + viewModel.topicDetailLogger()?.info( + "topic detail initial load task scheduled topic_id=\(row.topic.id) target_post=\(scrollToPostNumber.map(String.init) ?? "nil")" + ) + initialLoadTask = Task { [weak self] in + guard let self else { return } + let startedAt = Date() + self.viewModel.topicDetailLogger()?.info( + "topic detail initial load task start topic_id=\(self.row.topic.id) target_post=\(self.scrollToPostNumber.map(String.init) ?? "nil")" + ) + _ = self.topicDetailStore.snapshot(for: self.row.topic.id) + self.viewModel.topicDetailLogger()?.info( + "topic detail initial load task complete topic_id=\(self.row.topic.id) elapsed_ms=\(Self.elapsedMilliseconds(since: startedAt)) cancelled=\(Task.isCancelled)" + ) + } + } + + func kickOffMessageBusSubscription() { + subscriptionTask?.cancel() + viewModel.topicDetailLogger()?.debug( + "topic detail messagebus subscription task scheduled topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" + ) + subscriptionTask = Task { [weak self] in + guard let self else { return } + self.viewModel.topicDetailLogger()?.debug( + "topic detail messagebus subscription task start topic_id=\(self.row.topic.id) owner_token=\(self.detailOwnerToken)" + ) + await self.viewModel.maintainTopicDetailSubscription( + topicId: self.row.topic.id, + ownerToken: self.detailOwnerToken + ) + self.viewModel.topicDetailLogger()?.debug( + "topic detail messagebus subscription task complete topic_id=\(self.row.topic.id) cancelled=\(Task.isCancelled)" + ) + } + } + + func loadTopicDetail( + targetPostNumber: UInt32? = nil, + force: Bool = false + ) async { + let topicSlug = displayedTopicSlug + let startedAt = Date() + viewModel.topicDetailLogger()?.info( + "topic detail controller load request start topic_id=\(row.topic.id) force=\(force) target_post=\(targetPostNumber.map(String.init) ?? "nil") slug_present=\(!topicSlug.isEmpty)" + ) + let hasReadySnapshot = topicDetailStore.snapshot(for: row.topic.id)?.phase == .ready + topicDetailStore.open( + topicId: row.topic.id, + ownerToken: detailOwnerToken, + slug: topicSlug.isEmpty ? nil : topicSlug, + targetPostNumber: targetPostNumber, + bypassCache: force, + forceLoad: force, + trackVisit: true, + allowSuggestedUnreadRoot: targetPostNumber == nil && !hasReadySnapshot + ) + let loaded = topicDetailStore.snapshot(for: row.topic.id) + viewModel.topicDetailLogger()?.info( + "topic detail controller load request complete topic_id=\(row.topic.id) elapsed_ms=\(Self.elapsedMilliseconds(since: startedAt)) phase=\(String(describing: loaded?.phase)) rows=\(loaded?.rows.count ?? 0)" + ) + } + + func subscribeToStoreRevisions() { + let topicId = row.topic.id + topicDetailStore.$snapshots + .map { snapshots -> FireTopicDetailRevisionFingerprint in + let snapshot = snapshots[topicId] + return FireTopicDetailRevisionFingerprint( + collection: snapshot?.collectionRevision ?? 0, + chrome: snapshot?.chromeRevision ?? 0, + sidecar: snapshot?.sidecarRevision ?? 0, + interaction: snapshot?.interactionRevision ?? 0 + ) + } + .removeDuplicates() + .receive(on: RunLoop.main) + .sink { [weak self] revisions in + guard let self else { return } + let collectionChanged = revisions.collection != self.lastAppliedCollectionRevision + let chromeChanged = revisions.chrome != self.lastAppliedChromeRevision + let sidecarChanged = revisions.sidecar != self.lastAppliedSidecarRevision + let interactionChanged = revisions.interaction != self.lastAppliedInteractionRevision + self.lastAppliedCollectionRevision = revisions.collection + self.lastAppliedChromeRevision = revisions.chrome + self.lastAppliedSidecarRevision = revisions.sidecar + self.lastAppliedInteractionRevision = revisions.interaction + + if chromeChanged { + self.buildAndApplyChromeState() + } + guard collectionChanged || chromeChanged || sidecarChanged || interactionChanged else { + return + } + let reuseComments = !collectionChanged && !interactionChanged + self.buildAndApplySnapshot(reuseComments: reuseComments) + } + .store(in: &cancellables) + } + + func performRefresh() async { + timingTracker.recordInteraction() + topicDetailStore.clearScrollTarget(topicId: topic.id) + await loadTopicDetail(force: true) + // Force-load rebuilds Texture nodes; re-assert shell so dark→light survives PTR. + applyAppearanceShell() + } + + func handleVisiblePostNumbersChanged(_ visiblePostNumbers: Set) { + if !visiblePostNumbers.isEmpty { + timingTracker.recordInteraction() + } + timingTracker.updateVisiblePostNumbers(visiblePostNumbers) + + topicDetailStore.noteVisiblePosts( + topicId: topic.id, + postNumbers: visiblePostNumbers + ) + maybePresentReactionPickerCoachmark(visiblePostNumbers: visiblePostNumbers) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Modals.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Modals.swift new file mode 100644 index 00000000..14020b37 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Modals.swift @@ -0,0 +1,105 @@ +import UIKit + +@MainActor +extension FireTopicDetailViewController { + var topicBookmarkContext: FireBookmarkEditorContext { + FireBookmarkEditorContext( + bookmarkID: detailSnapshot?.chrome.bookmarkId, + bookmarkableID: topic.id, + bookmarkableType: "Topic", + topicID: topic.id, + postNumber: nil, + title: displayedTopicTitle, + initialName: detailSnapshot?.chrome.bookmarkName, + initialReminderAt: detailSnapshot?.chrome.bookmarkReminderAt, + allowsDelete: detailSnapshot?.chrome.bookmarkId != nil + ) + } + + func postBookmarkContext(for post: TopicPostState) -> FireBookmarkEditorContext { + let username = post.username.trimmingCharacters(in: .whitespacesAndNewlines) + return FireBookmarkEditorContext( + bookmarkID: post.bookmarkId, + bookmarkableID: post.id, + bookmarkableType: "Post", + topicID: topic.id, + postNumber: post.postNumber, + title: username.isEmpty ? "#\(post.postNumber)" : "#\(post.postNumber) · \(username)", + initialName: post.bookmarkName, + initialReminderAt: post.bookmarkReminderAt, + allowsDelete: post.bookmarkId != nil + ) + } + + func presentTopicBookmarkEditor() { + modalRouter.presentBookmarkEditor( + context: topicBookmarkContext, + recoveryOriginURL: topicCloudflareRecoveryURL, + onReload: { } + ) + } + + func presentPostBookmarkEditor(_ post: TopicPostState) { + modalRouter.presentBookmarkEditor( + context: postBookmarkContext(for: post), + recoveryOriginURL: topicCloudflareRecoveryURL, + onReload: { } + ) + } + + func presentPostEditor(_ post: TopicPostState) { + modalRouter.presentPostEditor( + topicID: topic.id, + context: FirePostEditorContext(postID: post.id, postNumber: post.postNumber), + onSaved: { [weak self] in + guard let self else { return } + _ = try? await self.topicDetailStore.prepareEdit(topicId: self.topic.id, postId: post.id) + } + ) + } + + func presentTopicEditor() { + modalRouter.presentTopicEditor( + topicID: topic.id, + initialTitle: detailSnapshot?.chrome.title ?? topic.title, + initialCategoryID: detailSnapshot?.chrome.categoryId ?? topic.categoryId, + initialTags: detailSnapshot?.chrome.tags ?? row.tagNames, + onSaved: { } + ) + } + + func presentFlagSheet(_ post: TopicPostState) { + modalRouter.presentFlagSheet( + topicID: topic.id, + context: FirePostManagementContext( + postID: post.id, + postNumber: post.postNumber, + username: post.username + ), + onSubmitted: { [weak self] message in + self?.modalRouter.presentNotice(message: message) + } + ) + } + + func updateTopicNotificationLevel(_ option: FireTopicNotificationLevelOption) { + Task { @MainActor in + do { + try await viewModel.topicInteraction.setTopicNotificationLevel( + topicID: topic.id, + notificationLevel: option.rawValue, + recoveryOriginURL: topicCloudflareRecoveryURL + ) + try await topicDetailStore.setNotificationLevel( + topicId: topic.id, + level: Int32(option.rawValue) + ) + FireUIKitToast.show(option.cycleToastMessage, style: .success, in: view) + } catch { + // Reconcile toolbar glyph if the optimistic cycle preview diverged. + buildAndApplyChromeState() + modalRouter.presentNotice(message: error.localizedDescription) + } + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Navigation.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Navigation.swift new file mode 100644 index 00000000..b6eaf37d --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Navigation.swift @@ -0,0 +1,113 @@ +import UIKit + +@MainActor +extension FireTopicDetailViewController { + func updateDismissButtonIfNeeded() { + let isRootPresentedTopic = + navigationController?.presentingViewController != nil + && navigationController?.viewControllers.count == 1 + if isRootPresentedTopic { + let dismissAction = UIAction { [weak self] _ in + self?.dismissPresentedTopicDetail() + } + let dismissItem = UIBarButtonItem( + title: "返回", + image: UIImage(systemName: "chevron.backward"), + primaryAction: dismissAction + ) + dismissItem.accessibilityLabel = "返回" + navigationItem.leftBarButtonItem = dismissItem + } else { + navigationItem.leftBarButtonItem = nil + } + } + + func dismissPresentedTopicDetail() { + navigationController?.dismiss(animated: true) + } + + var needsPresentedRootEdgeDismissGesture: Bool { + (navigationController?.viewControllers.count ?? 0) <= 1 + && (navigationController?.presentingViewController != nil || presentingViewController != nil) + } + + var canNavigateBackFromTopicDetail: Bool { + if let navigationController { + return navigationController.viewControllers.count > 1 + || navigationController.presentingViewController != nil + } + return presentingViewController != nil + } + + func updateBackGestureAvailability() { + let usesMainNavigationController = navigationController is FireMainNavigationController + navigationController?.interactivePopGestureRecognizer?.isEnabled = + !usesMainNavigationController && (navigationController?.viewControllers.count ?? 0) > 1 + pageBackEdgePanGestureRecognizer.isEnabled = + !usesMainNavigationController && canNavigateBackFromTopicDetail + } + + @objc func handlePageBackEdgePan(_ gestureRecognizer: UIScreenEdgePanGestureRecognizer) { + guard gestureRecognizer.state == .ended, + canNavigateBackFromTopicDetail, + navigationController?.transitionCoordinator == nil else { + return + } + let translation = gestureRecognizer.translation(in: view) + let velocity = gestureRecognizer.velocity(in: view) + let horizontalDistance = max(translation.x, 0) + let horizontalVelocity = max(velocity.x, 0) + guard horizontalDistance > 72 || horizontalVelocity > 420, + max(abs(translation.x), abs(velocity.x)) > max(abs(translation.y), abs(velocity.y)) else { + return + } + navigateBackFromTopicDetail() + } + + func navigateBackFromTopicDetail() { + if let navigationController, navigationController.viewControllers.count > 1 { + navigationController.popViewController(animated: true) + } else if let navigationController { + navigationController.dismiss(animated: true) + } else { + dismiss(animated: true) + } + } + + func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + guard gestureRecognizer === pageBackEdgePanGestureRecognizer, + let panGesture = gestureRecognizer as? UIScreenEdgePanGestureRecognizer else { + return true + } + guard canNavigateBackFromTopicDetail, + navigationController?.transitionCoordinator == nil else { + return false + } + let velocity = panGesture.velocity(in: view) + return velocity.x >= 0 && abs(velocity.x) >= abs(velocity.y) + } + + func configureNavigationAppearance() { + // Opaque chrome so dark images scrolling underneath cannot tint the bar black + // in light mode (translucent material samples feed content). + let appearance = UINavigationBarAppearance() + appearance.configureWithOpaqueBackground() + appearance.backgroundColor = FireTheme.uiCanvas + appearance.shadowColor = FireTheme.uiDivider + appearance.titleTextAttributes = [ + .foregroundColor: FireTheme.uiInk, + ] + appearance.largeTitleTextAttributes = [ + .foregroundColor: FireTheme.uiInk, + ] + + navigationItem.standardAppearance = appearance + navigationItem.scrollEdgeAppearance = appearance + navigationItem.compactAppearance = appearance + navigationController?.navigationBar.isTranslucent = false + navigationController?.navigationBar.tintColor = FireTheme.uiAccent + navigationController?.navigationBar.barTintColor = FireTheme.uiCanvas + view.backgroundColor = FireTheme.uiCanvas + view.tintColor = FireTheme.uiAccent + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+PollVoting.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+PollVoting.swift new file mode 100644 index 00000000..41828faf --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+PollVoting.swift @@ -0,0 +1,39 @@ +import UIKit + +@MainActor +extension FireTopicDetailViewController { + func submitPollVote( + for post: TopicPostState, + poll: PollState, + options: [String] + ) { + Task { @MainActor in + do { + _ = try await viewModel.topicInteraction.votePoll( + topicID: topic.id, + postID: post.id, + pollName: poll.name, + options: options, + recoveryOriginURL: topicCloudflareRecoveryURL + ) + } catch { + modalRouter.presentNotice(message: error.localizedDescription) + } + } + } + + func removePollVote(for post: TopicPostState, poll: PollState) { + Task { @MainActor in + do { + _ = try await viewModel.topicInteraction.unvotePoll( + topicID: topic.id, + postID: post.id, + pollName: poll.name, + recoveryOriginURL: topicCloudflareRecoveryURL + ) + } catch { + modalRouter.presentNotice(message: error.localizedDescription) + } + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+PostManagement.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+PostManagement.swift new file mode 100644 index 00000000..2d4a75bb --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+PostManagement.swift @@ -0,0 +1,41 @@ +import UIKit + +@MainActor +extension FireTopicDetailViewController { + func confirmDelete(_ post: TopicPostState) { + modalRouter.presentDeleteConfirmation(postNumber: post.postNumber) { [weak self] in + self?.deletePost( + FirePostManagementContext(postID: post.id, postNumber: post.postNumber) + ) + } + } + + func deletePost(_ context: FirePostManagementContext) { + Task { @MainActor in + do { + try await topicDetailStore.deletePost( + topicId: topic.id, + postId: context.postID + ) + modalRouter.presentNotice(message: "已删除 #\(context.postNumber)。") + } catch { + modalRouter.presentNotice(message: error.localizedDescription) + } + } + } + + func recoverPost(_ post: TopicPostState) { + let context = FirePostManagementContext(postID: post.id, postNumber: post.postNumber) + Task { @MainActor in + do { + try await topicDetailStore.recoverPost( + topicId: topic.id, + postId: context.postID + ) + modalRouter.presentNotice(message: "已恢复 #\(context.postNumber)。") + } catch { + modalRouter.presentNotice(message: error.localizedDescription) + } + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+QuickReply.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+QuickReply.swift new file mode 100644 index 00000000..71c90952 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+QuickReply.swift @@ -0,0 +1,340 @@ +import PhotosUI +import UIKit + +@MainActor +extension FireTopicDetailViewController { + func configureQuickReplyBar() { + // Layer above Texture feed so cells never show through the bar. + quickReplyBar.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(quickReplyBar) + + let bottom = quickReplyBar.bottomAnchor.constraint(equalTo: view.bottomAnchor) + let height = quickReplyBar.heightAnchor.constraint(equalToConstant: 0) + quickReplyBottomConstraint = bottom + quickReplyHeightConstraint = height + + NSLayoutConstraint.activate([ + quickReplyBar.leadingAnchor.constraint(equalTo: view.leadingAnchor), + quickReplyBar.trailingAnchor.constraint(equalTo: view.trailingAnchor), + bottom, + height, + ]) + view.bringSubviewToFront(quickReplyBar) + } + + func handleQuickReplyFocusChanged(_ focused: Bool) { + if focused { + topicDetailStore.beginReplyTyping(topicId: topic.id) + } else { + Task { + topicDetailStore.endReplyTyping(topicId: topic.id) + } + } + } + + func openComposer(replyToPost: TopicPostState?) { + composerContext = FireReplyComposerContext( + topicId: topic.id, + postId: replyToPost?.id, + replyToPostNumber: replyToPost?.postNumber, + replyToUsername: replyToPost?.username, + kind: .reply + ) + presentQuickReplyInput() + } + + func openBoostComposer(for post: TopicPostState) { + guard post.canBoost else { + modalRouter.presentNotice(message: "当前帖子暂时不能 Boost。") + return + } + guard canWriteInteractions else { + modalRouter.presentNotice(message: "登录后才能 Boost。") + return + } + // Share the bottom quick-reply chrome with comments instead of a separate sheet. + composerContext = FireReplyComposerContext( + topicId: topic.id, + postId: post.id, + replyToPostNumber: post.postNumber, + replyToUsername: post.username, + kind: .boost + ) + if !replyDraft.isEmpty, composerContext?.isBoost == true { + // Keep draft if user was already drafting a boost; otherwise clear reply draft noise. + } + presentQuickReplyInput() + } + + /// Apply chrome first, commit bar geometry, then focus so the keyboard and + /// input strip rise together (especially for swipe-to-reply). + func presentQuickReplyInput() { + buildAndApplyChromeState() + // Target row / height must be in the hierarchy before first-responder + // kicks off the keyboard animation; otherwise the bar catches up late. + view.layoutIfNeeded() + quickReplyBar.focusInput() + } + + func clearComposerTarget() { + // Cancel target is a full dismiss of the current compose session: drop the + // reply/Boost target, wipe draft text, and leave the keyboard down. + composerContext = nil + replyDraft = "" + quickReplyError = nil + buildAndApplyChromeState() + view.layoutIfNeeded() + quickReplyBar.resignInputFocus() + } + + func openAdvancedComposer() { + let context = composerContext + ?? FireReplyComposerContext( + topicId: topic.id, + postId: nil, + replyToPostNumber: nil, + replyToUsername: nil + ) + quickReplyBar.resignInputFocus() + modalRouter.presentAdvancedComposer( + route: FireComposerRoute( + kind: .advancedReply( + topicID: topic.id, + topicTitle: displayedTopicTitle, + categoryID: displayedCategoryId, + replyToPostNumber: context.replyToPostNumber, + replyToUsername: context.replyToUsername, + isPrivateMessage: isPrivateMessageThread + ) + ), + initialBody: replyDraft, + onReplySubmitted: { [weak self] in + guard let self else { return } + self.replyDraft = "" + self.composerContext = nil + self.quickReplyError = nil + self.buildAndApplyChromeState() + }, + onSubmissionNotice: { [weak self] message in + self?.modalRouter.presentNotice(message: message) + } + ) + } + + func openQuoteComposer(for post: TopicPostState) { + guard let quote = FireQuoteMarkdown.build( + username: post.username, + postNumber: post.postNumber, + topicID: topic.id, + plainText: post.presentation?.plainText() ?? "" + ) else { + modalRouter.presentNotice(message: "该帖子暂无可引用内容。") + return + } + + let quickReplyDraft = replyDraft + let initialBody = FireComposerInitialBody.merge( + initialBody: quote, + currentBody: quickReplyDraft + ).text + let quoteSelectionLocation = (quote as NSString).length + composerContext = FireReplyComposerContext( + topicId: topic.id, + postId: post.id, + replyToPostNumber: post.postNumber, + replyToUsername: post.username + ) + quickReplyBar.resignInputFocus() + buildAndApplyChromeState() + modalRouter.presentAdvancedComposer( + route: FireComposerRoute( + kind: .advancedReply( + topicID: topic.id, + topicTitle: displayedTopicTitle, + categoryID: displayedCategoryId, + replyToPostNumber: post.postNumber, + replyToUsername: post.username, + isPrivateMessage: isPrivateMessageThread + ) + ), + initialBody: initialBody, + initialBodySelectionLocation: quoteSelectionLocation, + onReplySubmitted: { [weak self] in + guard let self else { return } + self.replyDraft = "" + self.composerContext = nil + self.quickReplyError = nil + self.buildAndApplyChromeState() + }, + onSubmissionNotice: { [weak self] message in + self?.modalRouter.presentNotice(message: message) + }, + scrollToCreatedReply: true + ) + } + + func submitQuickReply(_ payload: FireBottomInputPayload) { + Task { @MainActor in + let raw: String + do { + raw = try await composeQuickReplyRaw(from: payload) + } catch { + quickReplyError = error.localizedDescription + buildAndApplyChromeState() + return + } + + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { + quickReplyError = composerContext?.isBoost == true + ? "Boost 内容不能为空。" + : "回复内容不能为空。" + buildAndApplyChromeState() + return + } + + if composerContext?.isBoost == true { + submitBoostFromQuickReply(raw: trimmed) + return + } + + guard trimmed.count >= minimumReplyLength else { + quickReplyError = "回复至少需要 \(minimumReplyLength) 个字。" + buildAndApplyChromeState() + return + } + + let topicId = composerContext?.topicId ?? topic.id + let replyToPostNumber = composerContext?.replyToPostNumber + quickReplyError = nil + buildAndApplyChromeState() + + do { + try await topicDetailStore.submitReply( + topicId: topicId, + raw: trimmed, + replyToPostNumber: replyToPostNumber, + scrollToCreated: false + ) + finishQuickReplySuccess() + } catch { + let message = error.localizedDescription + if message.localizedCaseInsensitiveContains("pending review") { + finishQuickReplySuccess() + modalRouter.presentNotice(message: "回复已提交,等待审核。") + return + } + quickReplyError = message + buildAndApplyChromeState() + } + } + } + + func composeQuickReplyRaw(from payload: FireBottomInputPayload) async throws -> String { + var parts: [String] = [] + let trimmed = payload.text.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + parts.append(trimmed) + } + for image in payload.images { + guard let data = image.fireJPEGDataForUpload() else { continue } + let upload = try await viewModel.uploadImage( + fileName: "reply-\(UUID().uuidString).jpg", + mimeType: "image/jpeg", + bytes: data + ) + let alt = upload.originalFilename?.isEmpty == false + ? upload.originalFilename! + : "image" + parts.append("![\(alt)](\(upload.shortUrl))") + } + return parts.joined(separator: "\n\n") + } + + func finishQuickReplySuccess() { + replyDraft = "" + composerContext = nil + quickReplyBar.resetAfterSend() + quickReplyBar.resignInputFocus() + buildAndApplyChromeState() + } + + func searchQuickReplyMentions(term: String) async -> [FireBottomInputMention] { + do { + let result = try await viewModel.searchService.searchUsers( + term: term, + includeGroups: true, + limit: 8, + topicID: topic.id, + categoryID: displayedCategoryId + ) + let users = result.users.map { user in + FireBottomInputMention( + handle: user.username, + displayName: user.name?.trimmingCharacters(in: .whitespacesAndNewlines) ?? user.username + ) + } + let groups = result.groups.map { group in + FireBottomInputMention( + handle: group.name, + displayName: group.fullName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? group.name + ) + } + return users + groups + } catch { + return [] + } + } + + func presentQuickReplyImagePicker() { + var configuration = PHPickerConfiguration(photoLibrary: .shared()) + configuration.filter = .images + configuration.selectionLimit = 4 + let picker = PHPickerViewController(configuration: configuration) + picker.delegate = self + present(picker, animated: true) + } + + func submitBoostFromQuickReply(raw: String) { + guard let postId = composerContext?.postId else { + quickReplyError = "找不到要 Boost 的帖子。" + buildAndApplyChromeState() + return + } + quickReplyError = nil + buildAndApplyChromeState() + Task { @MainActor in + do { + try await topicDetailStore.createBoost( + topicId: topic.id, + postId: postId, + raw: raw + ) + finishQuickReplySuccess() + FireMotionHaptics.success() + } catch is CancellationError { + // ignore + } catch { + FireMotionHaptics.error() + quickReplyError = error.localizedDescription + buildAndApplyChromeState() + } + } + } +} + +extension FireTopicDetailViewController: PHPickerViewControllerDelegate { + func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { + picker.dismiss(animated: true) + for result in results { + let provider = result.itemProvider + guard provider.canLoadObject(ofClass: UIImage.self) else { continue } + provider.loadObject(ofClass: UIImage.self) { [weak self] object, _ in + guard let image = object as? UIImage else { return } + Task { @MainActor in + self?.quickReplyBar.insertImage(image) + } + } + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Reactions.swift similarity index 68% rename from apps/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift rename to apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Reactions.swift index 638c72e9..da77f73b 100644 --- a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Reactions.swift @@ -184,98 +184,4 @@ extension FireTopicDetailViewController { ) } } - - func confirmDelete(_ post: TopicPostState) { - modalRouter.presentDeleteConfirmation(postNumber: post.postNumber) { [weak self] in - self?.deletePost( - FirePostManagementContext(postID: post.id, postNumber: post.postNumber) - ) - } - } - - func deletePost(_ context: FirePostManagementContext) { - Task { @MainActor in - do { - try await topicDetailStore.deletePost( - topicId: topic.id, - postId: context.postID - ) - modalRouter.presentNotice(message: "已删除 #\(context.postNumber)。") - } catch { - modalRouter.presentNotice(message: error.localizedDescription) - } - } - } - - func recoverPost(_ post: TopicPostState) { - let context = FirePostManagementContext(postID: post.id, postNumber: post.postNumber) - Task { @MainActor in - do { - try await topicDetailStore.recoverPost( - topicId: topic.id, - postId: context.postID - ) - modalRouter.presentNotice(message: "已恢复 #\(context.postNumber)。") - } catch { - modalRouter.presentNotice(message: error.localizedDescription) - } - } - } - - func toggleTopicVote() async { - let userVoted = detailSnapshot?.chrome.userVoted ?? false - do { - _ = try await viewModel.topicInteraction.voteTopic( - topicID: topic.id, - voted: !userVoted, - recoveryOriginURL: topicCloudflareRecoveryURL - ) - } catch { - modalRouter.presentNotice(message: error.localizedDescription) - } - } - - func presentTopicVoters() async { - do { - let voters = try await viewModel.topicInteraction.fetchTopicVoters(topicID: topic.id) - modalRouter.presentTopicVoters(voters, isLoading: false) - } catch { - modalRouter.presentNotice(message: error.localizedDescription) - } - } - - func submitPollVote( - for post: TopicPostState, - poll: PollState, - options: [String] - ) { - Task { @MainActor in - do { - _ = try await viewModel.topicInteraction.votePoll( - topicID: topic.id, - postID: post.id, - pollName: poll.name, - options: options, - recoveryOriginURL: topicCloudflareRecoveryURL - ) - } catch { - modalRouter.presentNotice(message: error.localizedDescription) - } - } - } - - func removePollVote(for post: TopicPostState, poll: PollState) { - Task { @MainActor in - do { - _ = try await viewModel.topicInteraction.unvotePoll( - topicID: topic.id, - postID: post.id, - pollName: poll.name, - recoveryOriginURL: topicCloudflareRecoveryURL - ) - } catch { - modalRouter.presentNotice(message: error.localizedDescription) - } - } - } } diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Routing.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Routing.swift new file mode 100644 index 00000000..199ed9d6 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+Routing.swift @@ -0,0 +1,40 @@ +import Foundation + +@MainActor +extension FireTopicDetailViewController { + func handleRichTextLink(_ url: URL) { + timingTracker.recordInteraction() + + guard let route = FireRouteParser.parse(url: url) else { + modalRouter.presentWebLink(url) + return + } + + switch route { + case .profile(let username): + modalRouter.presentProfile(username: username) + case .topic(let payload): + handleTopicLink(payload) + case .badge: + modalRouter.push(route: route) + case .notifications, .profileTab, .search: + break + } + } + + func handleTopicLink(_ payload: FireTopicRoutePayload) { + if payload.topicId == topic.id { + guard let postNumber = payload.postNumber else { return } + openPostNumber(postNumber) + return + } + modalRouter.push(route: .topic(payload: payload)) + } + + func openPostNumber(_ postNumber: UInt32) { + guard postNumber > 0 else { return } + Task { + await loadTopicDetail(targetPostNumber: postNumber) + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+SnapshotApplication.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+SnapshotApplication.swift new file mode 100644 index 00000000..8eb74a7a --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+SnapshotApplication.swift @@ -0,0 +1,211 @@ +import UIKit + +let fireTopicDetailSnapshotBuildDiagnosticThresholdMs: Int64 = 50 +let fireTopicDetailSnapshotApplyDiagnosticThresholdMs: Int64 = 16 + +struct FireTopicDetailRevisionFingerprint: Equatable { + let collection: UInt64 + let chrome: UInt64 + let sidecar: UInt64 + let interaction: UInt64 +} + +@MainActor +extension FireTopicDetailViewController { + func buildRuntimeConfiguration(from state: FireTopicDetailPageState) -> FireTopicDetailRuntimeConfiguration { + FireTopicDetailRuntimeConfiguration( + viewModel: viewModel, + displayedCategory: state.route.displayedCategory, + currentUsername: state.route.currentUsername, + row: state.route.row, + baseURLString: state.route.baseURLString, + snapshot: topicDetailStore.snapshot(for: state.topic.id), + detail: state.feed.detail, + renderState: state.feed.renderState, + pendingScrollTarget: state.feed.pendingScrollTarget, + detailError: state.feed.detailError, + detailNotice: state.feed.detailNotice, + hasMoreTopicPosts: state.feed.hasMoreTopicPosts, + isLoadingTopic: state.feed.isLoadingTopic, + isLoadingMoreTopicPosts: state.feed.isLoadingMoreTopicPosts, + loadMoreTopicPostsError: state.feed.loadMoreTopicPostsError, + topicAiSummary: state.sidecar.topicAiSummary, + isLoadingTopicAiSummary: state.sidecar.isLoadingTopicAiSummary, + topicAiSummaryError: state.sidecar.topicAiSummaryError, + isTopicAiSummaryExpanded: isTopicAiSummaryExpanded, + topicCollectionRevision: state.feed.topicCollectionRevision, + canWriteInteractions: state.route.canWriteInteractions, + postLookup: state.feed.postLookup, + interactionState: state.interaction, + activeSearchPostID: activeTopicSearchMatch?.postID, + snapshotInvalidationToken: AnyHashable(FireTopicDetailFeedInvalidationToken( + topicID: state.topic.id, + topicCollectionRevision: state.feed.topicCollectionRevision, + pendingScrollTarget: state.feed.pendingScrollTarget, + detailError: state.feed.detailError ?? "", + detailNotice: state.feed.detailNotice, + hasDetail: state.feed.detail != nil, + isLoadingTopic: state.feed.isLoadingTopic, + isLoadingMoreTopicPosts: state.feed.isLoadingMoreTopicPosts, + loadMoreTopicPostsError: state.feed.loadMoreTopicPostsError ?? "", + hasMoreTopicPosts: state.feed.hasMoreTopicPosts, + canWriteInteractions: state.route.canWriteInteractions, + currentUsername: state.route.currentUsername ?? "", + baseURLString: state.route.baseURLString, + activeSearchPostID: activeTopicSearchMatch?.postID, + expandedReplyRootPostIDs: state.interaction.expandedReplyRootPostIDs, + expandedReactionPickerPostIDs: state.interaction.expandedReactionPickerPostIDs + )), + interactions: runtimeInteractions + ) + } + + func buildAndApplySnapshot(reuseComments: Bool = false) { + snapshotBuildGeneration &+= 1 + let generation = snapshotBuildGeneration + let pageState = buildCurrentPageState() + let configuration = buildRuntimeConfiguration(from: pageState) + let input = FireTopicDetailSnapshotInput( + configuration: configuration, + toolbarState: snapshotAssembler.makeToolbarState(from: pageState.chrome), + quickReplyState: snapshotAssembler.makeQuickReplyState(from: pageState.composer), + pendingScrollTarget: pageState.feed.pendingScrollTarget, + invalidationToken: configuration.snapshotInvalidationToken + ) + + applyChromeState(chrome: pageState.chrome, composer: pageState.composer) + + snapshotBuildTask?.cancel() + let logger = viewModel.topicDetailLogger() + let cachedComments = reuseComments ? lastFeedSnapshot : nil + snapshotBuildTask = Task.detached(priority: .userInitiated) { [weak self, snapshotAssembler, input, configuration, generation, logger, cachedComments] in + let buildStartedAt = Date() + let snapshot = snapshotAssembler.buildSnapshot(from: input, reusingComments: cachedComments) + let buildDurationMs = Self.elapsedMilliseconds(since: buildStartedAt) + if buildDurationMs >= fireTopicDetailSnapshotBuildDiagnosticThresholdMs { + logger?.debug( + "topic detail snapshot build slow topic_id=\(configuration.row.topic.id) generation=\(generation) build_ms=\(buildDurationMs) item_count=\(snapshot.items.count)" + ) + } + + await MainActor.run { [weak self] in + guard let self, + self.snapshotBuildGeneration == generation, + !Task.isCancelled else { + return + } + self.applyBuiltSnapshot( + snapshot, + configuration: configuration, + buildDurationMs: buildDurationMs + ) + } + } + } + + /// Local expand / picker / reply-tree toggles stay on the main thread so a + /// single row can relayout without a detached full-page snapshot rebuild. + func applyLocalInteractionSnapshot() { + snapshotBuildGeneration &+= 1 + snapshotBuildTask?.cancel() + snapshotBuildTask = nil + let pageState = buildCurrentPageState() + let configuration = buildRuntimeConfiguration(from: pageState) + let input = FireTopicDetailSnapshotInput( + configuration: configuration, + toolbarState: snapshotAssembler.makeToolbarState(from: pageState.chrome), + quickReplyState: snapshotAssembler.makeQuickReplyState(from: pageState.composer), + pendingScrollTarget: pageState.feed.pendingScrollTarget, + invalidationToken: configuration.snapshotInvalidationToken + ) + applyChromeState(chrome: pageState.chrome, composer: pageState.composer) + let snapshot = snapshotAssembler.buildSnapshot(from: input) + applyBuiltSnapshot( + snapshot, + configuration: configuration, + buildDurationMs: 0 + ) + } + + func buildAndApplyChromeState() { + let topicId = row.topic.id + applyChromeState( + chrome: buildCurrentChromeState(topicId: topicId), + composer: buildCurrentComposerState(topicId: topicId) + ) + } + + func applyChromeState( + chrome: FireTopicDetailChromeState, + composer: FireTopicDetailComposerState + ) { + toolbarCoordinator.apply(state: snapshotAssembler.makeToolbarState(from: chrome)) + quickReplyBar.apply(state: snapshotAssembler.makeQuickReplyState(from: composer)) + updateBottomChromeInset() + } + + func applyBuiltSnapshot( + _ snapshot: FireTopicDetailPageSnapshot, + configuration: FireTopicDetailRuntimeConfiguration, + buildDurationMs: Int64 + ) { + let applyStartedAt = Date() + lastFeedSnapshot = FireTopicDetailRuntimeSnapshot( + items: snapshot.items, + replyIndexByPostID: snapshot.replyIndexByPostID + ) + feedUpdatePipeline.apply(snapshot: snapshot, configuration: configuration) + // Collection updates can recreate Texture shells; keep canvas in sync with + // the current appearance so dark→light survives data reload paths. + applyAppearanceShell() + let applyDurationMs = Self.elapsedMilliseconds(since: applyStartedAt) + logSnapshotApply( + snapshot: snapshot, + configuration: configuration, + buildDurationMs: buildDurationMs, + applyDurationMs: applyDurationMs + ) + } + + func logSnapshotApply( + snapshot: FireTopicDetailPageSnapshot, + configuration: FireTopicDetailRuntimeConfiguration, + buildDurationMs: Int64, + applyDurationMs: Int64 + ) { + guard buildDurationMs >= fireTopicDetailSnapshotBuildDiagnosticThresholdMs + || applyDurationMs >= fireTopicDetailSnapshotApplyDiagnosticThresholdMs + || !feedController.isViewAttached else { + return + } + viewModel.topicDetailLogger()?.debug( + "topic detail snapshot apply diagnostic topic_id=\(topic.id) snapshot_build_ms=\(buildDurationMs) feed_apply_ms=\(applyDurationMs) snapshot_item_count=\(snapshot.items.count) topic_collection_revision=\(configuration.topicCollectionRevision) has_detail=\(configuration.detail != nil) feed_attached=\(feedController.isViewAttached)" + ) + } + + func layoutDiagnosticsSignature() -> String { + "bounds=\(Self.formatSize(view.bounds.size)) safe_bottom=\(Int(view.safeAreaInsets.bottom.rounded())) feed_attached=\(feedController.isViewAttached)" + } + + func shouldLogLayoutDiagnostics(signature: String) -> Bool { + guard lastLayoutDiagnosticsSignature == signature else { + lastLayoutDiagnosticsSignature = signature + repeatedLayoutDiagnosticsCount = 0 + return true + } + repeatedLayoutDiagnosticsCount += 1 + return repeatedLayoutDiagnosticsCount.isMultiple(of: 500) + } + + func handleLayoutRevisionChanged() { + guard let snapshot = feedUpdatePipeline.currentSnapshot, + let configuration = feedUpdatePipeline.currentConfiguration else { + return + } + feedController.applyPublishedLayoutRevision( + publishedKeys: layoutManager.currentPublishedKeys, + items: snapshot.items, + configuration: configuration + ) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+StateProjection.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+StateProjection.swift new file mode 100644 index 00000000..397af080 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+StateProjection.swift @@ -0,0 +1,117 @@ +import Foundation + +@MainActor +extension FireTopicDetailViewController { + func buildCurrentRouteState(topicId: UInt64) -> FireTopicDetailRouteState { + let chrome = topicDetailStore.snapshot(for: topicId)?.chrome + return FireTopicDetailRouteState( + currentUsername: viewModel.session.bootstrap.currentUsername, + baseURLString: baseURLString, + canWriteInteractions: canWriteInteractions, + row: row, + displayedCategory: viewModel.categoryPresentation(for: chrome?.categoryId ?? row.topic.categoryId) + ) + } + + func buildCurrentFeedState(topicId: UInt64) -> FireTopicDetailFeedState { + let snapshot = topicDetailStore.snapshot(for: topicId) + let posts = snapshot.map(FireTopicDetailUiProjection.posts(from:)) ?? [] + return FireTopicDetailFeedState( + detail: nil, + renderState: nil, + postLookup: Dictionary(uniqueKeysWithValues: posts.map { ($0.id, $0) }), + isLoadingTopic: snapshot?.phase == .loading, + isLoadingMoreTopicPosts: snapshot?.isLoadingMore ?? false, + loadMoreTopicPostsError: snapshot?.loadMoreError, + hasMoreTopicPosts: snapshot?.hasMore ?? false, + detailError: Self.loadErrorMessage(snapshot?.loadError), + detailNotice: snapshot?.notice.map { + FireTopicDetailStatusMessage( + title: $0.title, + message: $0.message, + retryable: $0.retryable, + emphasizesError: $0.emphasizesError + ) + }, + topicCollectionRevision: snapshot?.collectionRevision ?? 0, + pendingScrollTarget: snapshot?.scrollTargetPostNumber + ) + } + + func buildCurrentChromeState(topicId: UInt64) -> FireTopicDetailChromeState { + FireTopicDetailChromeState( + detail: nil, + row: row, + baseURLString: baseURLString, + canWriteInteractions: canWriteInteractions + ) + } + + func buildCurrentComposerState(topicId: UInt64) -> FireTopicDetailComposerState { + let snapshot = topicDetailStore.snapshot(for: topicId) + return FireTopicDetailComposerState( + typingUsers: snapshot?.composer.typingUsers ?? [], + composerContext: composerContext, + replyDraft: replyDraft, + quickReplyError: quickReplyError, + isSubmittingReply: snapshot?.composer.isSubmitting ?? false, + minimumReplyLength: minimumReplyLength, + canWriteInteractions: canWriteInteractions + ) + } + + func buildCurrentSidecarState(topicId: UInt64) -> FireTopicDetailSidecarState { + let sidecar = topicDetailStore.snapshot(for: topicId)?.sidecar + let summary = sidecar?.summarizedText.map { text in + TopicAiSummaryState( + summarizedText: text, + algorithm: sidecar?.algorithm, + outdated: sidecar?.outdated ?? false, + canRegenerate: sidecar?.canRegenerate ?? false, + newPostsSinceSummary: sidecar?.newPostsSinceSummary ?? 0, + updatedAt: sidecar?.updatedAt + ) + } + return FireTopicDetailSidecarState( + topicAiSummary: summary, + isLoadingTopicAiSummary: sidecar?.isLoading ?? false, + topicAiSummaryError: sidecar?.error + ) + } + + func buildCurrentInteractionState() -> FireTopicDetailInteractionState { + let rows = topicDetailStore.snapshot(for: row.topic.id)?.rows ?? [] + return FireTopicDetailInteractionState( + mutatingPostIDs: Set(rows.filter(\.isMutating).map(\.postId)), + loadingPostReplyContextIDs: Set(rows.filter(\.isLoadingReplyContext).map(\.postId)), + expandedPostTextIDs: expandedPostTextIDs, + expandedReplyRootPostIDs: expandedReplyRootPostIDs, + expandedReactionPickerPostIDs: expandedReactionPickerPostIDs + ) + } + + private static func loadErrorMessage(_ error: TopicDetailLoadErrorState?) -> String? { + switch error { + case .network: + return "网络错误" + case .loginRequired: + return "需要登录" + case .unrecoverable(let message): + return message + case nil: + return nil + } + } + + func buildCurrentPageState() -> FireTopicDetailPageState { + let topicId = row.topic.id + return FireTopicDetailPageState( + feed: buildCurrentFeedState(topicId: topicId), + chrome: buildCurrentChromeState(topicId: topicId), + composer: buildCurrentComposerState(topicId: topicId), + sidecar: buildCurrentSidecarState(topicId: topicId), + interaction: buildCurrentInteractionState(), + route: buildCurrentRouteState(topicId: topicId) + ) + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+TopicVoting.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+TopicVoting.swift new file mode 100644 index 00000000..8a9474c1 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController+TopicVoting.swift @@ -0,0 +1,26 @@ +import UIKit + +@MainActor +extension FireTopicDetailViewController { + func toggleTopicVote() async { + let userVoted = detailSnapshot?.chrome.userVoted ?? false + do { + _ = try await viewModel.topicInteraction.voteTopic( + topicID: topic.id, + voted: !userVoted, + recoveryOriginURL: topicCloudflareRecoveryURL + ) + } catch { + modalRouter.presentNotice(message: error.localizedDescription) + } + } + + func presentTopicVoters() async { + do { + let voters = try await viewModel.topicInteraction.fetchTopicVoters(topicID: topic.id) + modalRouter.presentTopicVoters(voters, isLoading: false) + } catch { + modalRouter.presentNotice(message: error.localizedDescription) + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift index f00c3d18..baac491b 100644 --- a/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift @@ -1,17 +1,5 @@ import Combine -import PhotosUI import UIKit -import UniformTypeIdentifiers - -private let fireTopicDetailSnapshotBuildDiagnosticThresholdMs: Int64 = 50 -private let fireTopicDetailSnapshotApplyDiagnosticThresholdMs: Int64 = 16 - -private struct FireTopicDetailRevisionFingerprint: Equatable { - let collection: UInt64 - let chrome: UInt64 - let sidecar: UInt64 - let interaction: UInt64 -} @MainActor final class FireTopicDetailViewController: UIViewController, UIGestureRecognizerDelegate { @@ -207,11 +195,11 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer var snapshotBuildTask: Task? var snapshotBuildGeneration: UInt64 = 0 var cancellables = Set() - private var lastAppliedCollectionRevision: UInt64 = 0 - private var lastAppliedChromeRevision: UInt64 = 0 - private var lastAppliedSidecarRevision: UInt64 = 0 - private var lastAppliedInteractionRevision: UInt64 = 0 - private var lastFeedSnapshot: FireTopicDetailRuntimeSnapshot? + var lastAppliedCollectionRevision: UInt64 = 0 + var lastAppliedChromeRevision: UInt64 = 0 + var lastAppliedSidecarRevision: UInt64 = 0 + var lastAppliedInteractionRevision: UInt64 = 0 + var lastFeedSnapshot: FireTopicDetailRuntimeSnapshot? var expandedPostTextIDs: Set = [] var expandedReplyRootPostIDs: Set = [] @@ -436,34 +424,6 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer ) } - var topicBookmarkContext: FireBookmarkEditorContext { - FireBookmarkEditorContext( - bookmarkID: detailSnapshot?.chrome.bookmarkId, - bookmarkableID: topic.id, - bookmarkableType: "Topic", - topicID: topic.id, - postNumber: nil, - title: displayedTopicTitle, - initialName: detailSnapshot?.chrome.bookmarkName, - initialReminderAt: detailSnapshot?.chrome.bookmarkReminderAt, - allowsDelete: detailSnapshot?.chrome.bookmarkId != nil - ) - } - - func postBookmarkContext(for post: TopicPostState) -> FireBookmarkEditorContext { - let username = post.username.trimmingCharacters(in: .whitespacesAndNewlines) - return FireBookmarkEditorContext( - bookmarkID: post.bookmarkId, - bookmarkableID: post.id, - bookmarkableType: "Post", - topicID: topic.id, - postNumber: post.postNumber, - title: username.isEmpty ? "#\(post.postNumber)" : "#\(post.postNumber) · \(username)", - initialName: post.bookmarkName, - initialReminderAt: post.bookmarkReminderAt, - allowsDelete: post.bookmarkId != nil - ) - } func configureRuntime() { let startedAt = Date() @@ -569,1198 +529,15 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer ) } - func configureQuickReplyBar() { - // Layer above Texture feed so cells never show through the bar. - quickReplyBar.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(quickReplyBar) - - let bottom = quickReplyBar.bottomAnchor.constraint(equalTo: view.bottomAnchor) - let height = quickReplyBar.heightAnchor.constraint(equalToConstant: 0) - quickReplyBottomConstraint = bottom - quickReplyHeightConstraint = height - - NSLayoutConstraint.activate([ - quickReplyBar.leadingAnchor.constraint(equalTo: view.leadingAnchor), - quickReplyBar.trailingAnchor.constraint(equalTo: view.trailingAnchor), - bottom, - height, - ]) - view.bringSubviewToFront(quickReplyBar) - } - - - func beginPageLifecycle() { - viewModel.topicDetailLogger()?.info( - "topic detail lifecycle begin topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" - ) - let hasReadySnapshot = topicDetailStore.snapshot(for: row.topic.id)?.phase == .ready - topicDetailStore.open( - topicId: row.topic.id, - ownerToken: detailOwnerToken, - slug: displayedTopicSlug.isEmpty ? nil : displayedTopicSlug, - targetPostNumber: scrollToPostNumber, - bypassCache: false, - forceLoad: false, - trackVisit: true, - allowSuggestedUnreadRoot: scrollToPostNumber == nil && !hasReadySnapshot - ) - - timingTracker.start { [weak viewModel] topicId, topicTimeMs, timings in - guard let viewModel else { return false } - return await viewModel.topicInteraction.reportTopicTimings( - topicId: topicId, - topicTimeMs: topicTimeMs, - timings: timings - ) - } - - subscribeToKeyboardNotifications() - subscribeToStoreRevisions() - kickOffInitialLoad() - // The Rust topic session subscribes to detail, reactions, polls, and presence. - viewModel.topicDetailLogger()?.debug( - "topic detail lifecycle begin scheduled tasks topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" - ) - } - - func endPageLifecycle() { - viewModel.topicDetailLogger()?.info( - "topic detail lifecycle end topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" - ) - initialLoadTask?.cancel() - initialLoadTask = nil - subscriptionTask?.cancel() - subscriptionTask = nil - snapshotBuildTask?.cancel() - snapshotBuildTask = nil - cancellables.removeAll() - topicDetailStore.noteScrollInteraction(topicId: row.topic.id, active: false) - - topicDetailStore.close(topicId: row.topic.id, ownerToken: detailOwnerToken) - } - - func kickOffInitialLoad() { - initialLoadTask?.cancel() - viewModel.topicDetailLogger()?.info( - "topic detail initial load task scheduled topic_id=\(row.topic.id) target_post=\(scrollToPostNumber.map(String.init) ?? "nil")" - ) - initialLoadTask = Task { [weak self] in - guard let self else { return } - let startedAt = Date() - self.viewModel.topicDetailLogger()?.info( - "topic detail initial load task start topic_id=\(self.row.topic.id) target_post=\(self.scrollToPostNumber.map(String.init) ?? "nil")" - ) - _ = self.topicDetailStore.snapshot(for: self.row.topic.id) - self.viewModel.topicDetailLogger()?.info( - "topic detail initial load task complete topic_id=\(self.row.topic.id) elapsed_ms=\(Self.elapsedMilliseconds(since: startedAt)) cancelled=\(Task.isCancelled)" - ) - } - } - - func updateDismissButtonIfNeeded() { - let isRootPresentedTopic = - navigationController?.presentingViewController != nil - && navigationController?.viewControllers.count == 1 - if isRootPresentedTopic { - let dismissAction = UIAction { [weak self] _ in - self?.dismissPresentedTopicDetail() - } - let dismissItem = UIBarButtonItem( - title: "返回", - image: UIImage(systemName: "chevron.backward"), - primaryAction: dismissAction - ) - dismissItem.accessibilityLabel = "返回" - navigationItem.leftBarButtonItem = dismissItem - } else { - navigationItem.leftBarButtonItem = nil - } - } - - func dismissPresentedTopicDetail() { - navigationController?.dismiss(animated: true) - } - - var needsPresentedRootEdgeDismissGesture: Bool { - (navigationController?.viewControllers.count ?? 0) <= 1 - && (navigationController?.presentingViewController != nil || presentingViewController != nil) - } - - var canNavigateBackFromTopicDetail: Bool { - if let navigationController { - return navigationController.viewControllers.count > 1 - || navigationController.presentingViewController != nil - } - return presentingViewController != nil - } - - func updateBackGestureAvailability() { - let usesMainNavigationController = navigationController is FireMainNavigationController - navigationController?.interactivePopGestureRecognizer?.isEnabled = - !usesMainNavigationController && (navigationController?.viewControllers.count ?? 0) > 1 - pageBackEdgePanGestureRecognizer.isEnabled = - !usesMainNavigationController && canNavigateBackFromTopicDetail - } - - @objc private func handlePageBackEdgePan(_ gestureRecognizer: UIScreenEdgePanGestureRecognizer) { - guard gestureRecognizer.state == .ended, - canNavigateBackFromTopicDetail, - navigationController?.transitionCoordinator == nil else { - return - } - let translation = gestureRecognizer.translation(in: view) - let velocity = gestureRecognizer.velocity(in: view) - let horizontalDistance = max(translation.x, 0) - let horizontalVelocity = max(velocity.x, 0) - guard horizontalDistance > 72 || horizontalVelocity > 420, - max(abs(translation.x), abs(velocity.x)) > max(abs(translation.y), abs(velocity.y)) else { - return - } - navigateBackFromTopicDetail() - } - - func navigateBackFromTopicDetail() { - if let navigationController, navigationController.viewControllers.count > 1 { - navigationController.popViewController(animated: true) - } else if let navigationController { - navigationController.dismiss(animated: true) - } else { - dismiss(animated: true) - } - } - - func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { - guard gestureRecognizer === pageBackEdgePanGestureRecognizer, - let panGesture = gestureRecognizer as? UIScreenEdgePanGestureRecognizer else { - return true - } - guard canNavigateBackFromTopicDetail, - navigationController?.transitionCoordinator == nil else { - return false - } - let velocity = panGesture.velocity(in: view) - return velocity.x >= 0 && abs(velocity.x) >= abs(velocity.y) - } - - func configureNavigationAppearance() { - // Opaque chrome so dark images scrolling underneath cannot tint the bar black - // in light mode (translucent material samples feed content). - let appearance = UINavigationBarAppearance() - appearance.configureWithOpaqueBackground() - appearance.backgroundColor = FireTheme.uiCanvas - appearance.shadowColor = FireTheme.uiDivider - appearance.titleTextAttributes = [ - .foregroundColor: FireTheme.uiInk, - ] - appearance.largeTitleTextAttributes = [ - .foregroundColor: FireTheme.uiInk, - ] - - navigationItem.standardAppearance = appearance - navigationItem.scrollEdgeAppearance = appearance - navigationItem.compactAppearance = appearance - navigationController?.navigationBar.isTranslucent = false - navigationController?.navigationBar.tintColor = FireTheme.uiAccent - navigationController?.navigationBar.barTintColor = FireTheme.uiCanvas - view.backgroundColor = FireTheme.uiCanvas - view.tintColor = FireTheme.uiAccent - } - - func bindColorAppearanceObservers() { - // Single bus from Environment (preference write / storage sync). Avoid also - // listening to the NotificationCenter name here — same event would re-apply twice. - FireAppearanceEnvironment.snapshotPublisher - .receive(on: RunLoop.main) - .sink { [weak self] snapshot in - self?.applyAppearance(snapshot) - } - .store(in: &appearanceCancellables) - } - - func handleColorAppearanceChange(reason: String) { - let snapshot = FireAppearanceEnvironment.snapshot(for: view, window: view.window) - applyAppearance(snapshot) - viewModel.topicDetailLogger()?.debug( - "topic detail appearance reason=\(reason) token=\(snapshot.token)" - ) - } - - /// Shell layers that sit outside factory cell rebuilds (VC view + Texture root). - func applyAppearanceShell(_ snapshot: FireAppearanceSnapshot? = nil) { - let resolved = snapshot ?? FireAppearanceEnvironment.snapshot(for: view, window: view.window) - FireAppearanceTexture.applySnapshot(resolved, to: view) - rootNode.applyAppearance(resolved) - feedController.assertFeedShellAppearance(resolved) - configureNavigationAppearance() - } - - func kickOffMessageBusSubscription() { - subscriptionTask?.cancel() - viewModel.topicDetailLogger()?.debug( - "topic detail messagebus subscription task scheduled topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" - ) - subscriptionTask = Task { [weak self] in - guard let self else { return } - self.viewModel.topicDetailLogger()?.debug( - "topic detail messagebus subscription task start topic_id=\(self.row.topic.id) owner_token=\(self.detailOwnerToken)" - ) - await self.viewModel.maintainTopicDetailSubscription( - topicId: self.row.topic.id, - ownerToken: self.detailOwnerToken - ) - self.viewModel.topicDetailLogger()?.debug( - "topic detail messagebus subscription task complete topic_id=\(self.row.topic.id) cancelled=\(Task.isCancelled)" - ) - } - } - - func loadTopicDetail( - targetPostNumber: UInt32? = nil, - force: Bool = false - ) async { - let topicSlug = displayedTopicSlug - let startedAt = Date() - viewModel.topicDetailLogger()?.info( - "topic detail controller load request start topic_id=\(row.topic.id) force=\(force) target_post=\(targetPostNumber.map(String.init) ?? "nil") slug_present=\(!topicSlug.isEmpty)" - ) - let hasReadySnapshot = topicDetailStore.snapshot(for: row.topic.id)?.phase == .ready - topicDetailStore.open( - topicId: row.topic.id, - ownerToken: detailOwnerToken, - slug: topicSlug.isEmpty ? nil : topicSlug, - targetPostNumber: targetPostNumber, - bypassCache: force, - forceLoad: force, - trackVisit: true, - allowSuggestedUnreadRoot: targetPostNumber == nil && !hasReadySnapshot - ) - let loaded = topicDetailStore.snapshot(for: row.topic.id) - viewModel.topicDetailLogger()?.info( - "topic detail controller load request complete topic_id=\(row.topic.id) elapsed_ms=\(Self.elapsedMilliseconds(since: startedAt)) phase=\(String(describing: loaded?.phase)) rows=\(loaded?.rows.count ?? 0)" - ) - } - - func subscribeToStoreRevisions() { - let topicId = row.topic.id - topicDetailStore.$snapshots - .map { snapshots -> FireTopicDetailRevisionFingerprint in - let snapshot = snapshots[topicId] - return FireTopicDetailRevisionFingerprint( - collection: snapshot?.collectionRevision ?? 0, - chrome: snapshot?.chromeRevision ?? 0, - sidecar: snapshot?.sidecarRevision ?? 0, - interaction: snapshot?.interactionRevision ?? 0 - ) - } - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] revisions in - guard let self else { return } - let collectionChanged = revisions.collection != self.lastAppliedCollectionRevision - let chromeChanged = revisions.chrome != self.lastAppliedChromeRevision - let sidecarChanged = revisions.sidecar != self.lastAppliedSidecarRevision - let interactionChanged = revisions.interaction != self.lastAppliedInteractionRevision - self.lastAppliedCollectionRevision = revisions.collection - self.lastAppliedChromeRevision = revisions.chrome - self.lastAppliedSidecarRevision = revisions.sidecar - self.lastAppliedInteractionRevision = revisions.interaction - if chromeChanged { - self.buildAndApplyChromeState() - } - guard collectionChanged || chromeChanged || sidecarChanged || interactionChanged else { - return - } - let reuseComments = !collectionChanged && !interactionChanged - self.buildAndApplySnapshot(reuseComments: reuseComments) - } - .store(in: &cancellables) - } - - func subscribeToKeyboardNotifications() { - // Deliver synchronously on the posting thread (main). Do not hop through - // RunLoop.main / DispatchQueue.main — that defers handling by a turn and - // makes the quick-reply bar lag behind the keyboard after swipe-to-reply. - NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification) - .merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) - .sink { [weak self] notification in - self?.handleKeyboardNotification(notification) - } - .store(in: &cancellables) - } - - func buildCurrentRouteState(topicId: UInt64) -> FireTopicDetailRouteState { - let chrome = topicDetailStore.snapshot(for: topicId)?.chrome - return FireTopicDetailRouteState( - currentUsername: viewModel.session.bootstrap.currentUsername, - baseURLString: baseURLString, - canWriteInteractions: canWriteInteractions, - row: row, - displayedCategory: viewModel.categoryPresentation(for: chrome?.categoryId ?? row.topic.categoryId) - ) - } - - func buildCurrentFeedState(topicId: UInt64) -> FireTopicDetailFeedState { - let snapshot = topicDetailStore.snapshot(for: topicId) - let posts = snapshot.map(FireTopicDetailUiProjection.posts(from:)) ?? [] - return FireTopicDetailFeedState( - detail: nil, - renderState: nil, - postLookup: Dictionary(uniqueKeysWithValues: posts.map { ($0.id, $0) }), - isLoadingTopic: snapshot?.phase == .loading, - isLoadingMoreTopicPosts: snapshot?.isLoadingMore ?? false, - loadMoreTopicPostsError: snapshot?.loadMoreError, - hasMoreTopicPosts: snapshot?.hasMore ?? false, - detailError: Self.loadErrorMessage(snapshot?.loadError), - detailNotice: snapshot?.notice.map { - FireTopicDetailStatusMessage( - title: $0.title, - message: $0.message, - retryable: $0.retryable, - emphasizesError: $0.emphasizesError - ) - }, - topicCollectionRevision: snapshot?.collectionRevision ?? 0, - pendingScrollTarget: snapshot?.scrollTargetPostNumber - ) - } - - func buildCurrentChromeState(topicId: UInt64) -> FireTopicDetailChromeState { - FireTopicDetailChromeState( - detail: nil, - row: row, - baseURLString: baseURLString, - canWriteInteractions: canWriteInteractions - ) - } - - func buildCurrentComposerState(topicId: UInt64) -> FireTopicDetailComposerState { - let snapshot = topicDetailStore.snapshot(for: topicId) - return FireTopicDetailComposerState( - typingUsers: snapshot?.composer.typingUsers ?? [], - composerContext: composerContext, - replyDraft: replyDraft, - quickReplyError: quickReplyError, - isSubmittingReply: snapshot?.composer.isSubmitting ?? false, - minimumReplyLength: minimumReplyLength, - canWriteInteractions: canWriteInteractions - ) - } - - func buildCurrentSidecarState(topicId: UInt64) -> FireTopicDetailSidecarState { - let sidecar = topicDetailStore.snapshot(for: topicId)?.sidecar - let summary = sidecar?.summarizedText.map { text in - TopicAiSummaryState( - summarizedText: text, - algorithm: sidecar?.algorithm, - outdated: sidecar?.outdated ?? false, - canRegenerate: sidecar?.canRegenerate ?? false, - newPostsSinceSummary: sidecar?.newPostsSinceSummary ?? 0, - updatedAt: sidecar?.updatedAt - ) - } - return FireTopicDetailSidecarState( - topicAiSummary: summary, - isLoadingTopicAiSummary: sidecar?.isLoading ?? false, - topicAiSummaryError: sidecar?.error - ) - } - - func buildCurrentInteractionState() -> FireTopicDetailInteractionState { - let rows = topicDetailStore.snapshot(for: row.topic.id)?.rows ?? [] - return FireTopicDetailInteractionState( - mutatingPostIDs: Set(rows.filter(\.isMutating).map(\.postId)), - loadingPostReplyContextIDs: Set(rows.filter(\.isLoadingReplyContext).map(\.postId)), - expandedPostTextIDs: expandedPostTextIDs, - expandedReplyRootPostIDs: expandedReplyRootPostIDs, - expandedReactionPickerPostIDs: expandedReactionPickerPostIDs - ) - } - - private static func loadErrorMessage(_ error: TopicDetailLoadErrorState?) -> String? { - switch error { - case .network: - return "网络错误" - case .loginRequired: - return "需要登录" - case .unrecoverable(let message): - return message - case nil: - return nil - } - } - - func buildCurrentPageState() -> FireTopicDetailPageState { - let topicId = row.topic.id - return FireTopicDetailPageState( - feed: buildCurrentFeedState(topicId: topicId), - chrome: buildCurrentChromeState(topicId: topicId), - composer: buildCurrentComposerState(topicId: topicId), - sidecar: buildCurrentSidecarState(topicId: topicId), - interaction: buildCurrentInteractionState(), - route: buildCurrentRouteState(topicId: topicId) - ) - } - - func buildRuntimeConfiguration(from state: FireTopicDetailPageState) -> FireTopicDetailRuntimeConfiguration { - FireTopicDetailRuntimeConfiguration( - viewModel: viewModel, - displayedCategory: state.route.displayedCategory, - currentUsername: state.route.currentUsername, - row: state.route.row, - baseURLString: state.route.baseURLString, - snapshot: topicDetailStore.snapshot(for: state.topic.id), - detail: state.feed.detail, - renderState: state.feed.renderState, - pendingScrollTarget: state.feed.pendingScrollTarget, - detailError: state.feed.detailError, - detailNotice: state.feed.detailNotice, - hasMoreTopicPosts: state.feed.hasMoreTopicPosts, - isLoadingTopic: state.feed.isLoadingTopic, - isLoadingMoreTopicPosts: state.feed.isLoadingMoreTopicPosts, - loadMoreTopicPostsError: state.feed.loadMoreTopicPostsError, - topicAiSummary: state.sidecar.topicAiSummary, - isLoadingTopicAiSummary: state.sidecar.isLoadingTopicAiSummary, - topicAiSummaryError: state.sidecar.topicAiSummaryError, - isTopicAiSummaryExpanded: isTopicAiSummaryExpanded, - topicCollectionRevision: state.feed.topicCollectionRevision, - canWriteInteractions: state.route.canWriteInteractions, - postLookup: state.feed.postLookup, - interactionState: state.interaction, - activeSearchPostID: activeTopicSearchMatch?.postID, - snapshotInvalidationToken: AnyHashable(FireTopicDetailFeedInvalidationToken( - topicID: state.topic.id, - topicCollectionRevision: state.feed.topicCollectionRevision, - pendingScrollTarget: state.feed.pendingScrollTarget, - detailError: state.feed.detailError ?? "", - detailNotice: state.feed.detailNotice, - hasDetail: state.feed.detail != nil, - isLoadingTopic: state.feed.isLoadingTopic, - isLoadingMoreTopicPosts: state.feed.isLoadingMoreTopicPosts, - loadMoreTopicPostsError: state.feed.loadMoreTopicPostsError ?? "", - hasMoreTopicPosts: state.feed.hasMoreTopicPosts, - canWriteInteractions: state.route.canWriteInteractions, - currentUsername: state.route.currentUsername ?? "", - baseURLString: state.route.baseURLString, - activeSearchPostID: activeTopicSearchMatch?.postID, - expandedReplyRootPostIDs: state.interaction.expandedReplyRootPostIDs, - expandedReactionPickerPostIDs: state.interaction.expandedReactionPickerPostIDs - )), - interactions: runtimeInteractions - ) - } - - func buildAndApplySnapshot(reuseComments: Bool = false) { - snapshotBuildGeneration &+= 1 - let generation = snapshotBuildGeneration - let pageState = buildCurrentPageState() - let configuration = buildRuntimeConfiguration(from: pageState) - let input = FireTopicDetailSnapshotInput( - configuration: configuration, - toolbarState: snapshotAssembler.makeToolbarState(from: pageState.chrome), - quickReplyState: snapshotAssembler.makeQuickReplyState(from: pageState.composer), - pendingScrollTarget: pageState.feed.pendingScrollTarget, - invalidationToken: configuration.snapshotInvalidationToken - ) - - applyChromeState(chrome: pageState.chrome, composer: pageState.composer) - - snapshotBuildTask?.cancel() - let logger = viewModel.topicDetailLogger() - let cachedComments = reuseComments ? lastFeedSnapshot : nil - snapshotBuildTask = Task.detached(priority: .userInitiated) { [weak self, snapshotAssembler, input, configuration, generation, logger, cachedComments] in - let buildStartedAt = Date() - let snapshot = snapshotAssembler.buildSnapshot(from: input, reusingComments: cachedComments) - let buildDurationMs = Self.elapsedMilliseconds(since: buildStartedAt) - if buildDurationMs >= fireTopicDetailSnapshotBuildDiagnosticThresholdMs { - logger?.debug( - "topic detail snapshot build slow topic_id=\(configuration.row.topic.id) generation=\(generation) build_ms=\(buildDurationMs) item_count=\(snapshot.items.count)" - ) - } - - await MainActor.run { [weak self] in - guard let self, - self.snapshotBuildGeneration == generation, - !Task.isCancelled else { - return - } - self.applyBuiltSnapshot( - snapshot, - configuration: configuration, - buildDurationMs: buildDurationMs - ) - } - } - } - - /// Local expand / picker / reply-tree toggles stay on the main thread so a - /// single row can relayout without a detached full-page snapshot rebuild. - func applyLocalInteractionSnapshot() { - snapshotBuildGeneration &+= 1 - snapshotBuildTask?.cancel() - snapshotBuildTask = nil - let pageState = buildCurrentPageState() - let configuration = buildRuntimeConfiguration(from: pageState) - let input = FireTopicDetailSnapshotInput( - configuration: configuration, - toolbarState: snapshotAssembler.makeToolbarState(from: pageState.chrome), - quickReplyState: snapshotAssembler.makeQuickReplyState(from: pageState.composer), - pendingScrollTarget: pageState.feed.pendingScrollTarget, - invalidationToken: configuration.snapshotInvalidationToken - ) - applyChromeState(chrome: pageState.chrome, composer: pageState.composer) - let snapshot = snapshotAssembler.buildSnapshot(from: input) - applyBuiltSnapshot( - snapshot, - configuration: configuration, - buildDurationMs: 0 - ) - } - - func buildAndApplyChromeState() { - let topicId = row.topic.id - applyChromeState( - chrome: buildCurrentChromeState(topicId: topicId), - composer: buildCurrentComposerState(topicId: topicId) - ) - } - - func applyChromeState( - chrome: FireTopicDetailChromeState, - composer: FireTopicDetailComposerState - ) { - toolbarCoordinator.apply(state: snapshotAssembler.makeToolbarState(from: chrome)) - quickReplyBar.apply(state: snapshotAssembler.makeQuickReplyState(from: composer)) - updateBottomChromeInset() - } - - func applyBuiltSnapshot( - _ snapshot: FireTopicDetailPageSnapshot, - configuration: FireTopicDetailRuntimeConfiguration, - buildDurationMs: Int64 - ) { - let applyStartedAt = Date() - lastFeedSnapshot = FireTopicDetailRuntimeSnapshot( - items: snapshot.items, - replyIndexByPostID: snapshot.replyIndexByPostID - ) - feedUpdatePipeline.apply(snapshot: snapshot, configuration: configuration) - // Collection updates can recreate Texture shells; keep canvas in sync with - // the current appearance so dark→light survives data reload paths. - applyAppearanceShell() - let applyDurationMs = Self.elapsedMilliseconds(since: applyStartedAt) - logSnapshotApply( - snapshot: snapshot, - configuration: configuration, - buildDurationMs: buildDurationMs, - applyDurationMs: applyDurationMs - ) - } - - func logSnapshotApply( - snapshot: FireTopicDetailPageSnapshot, - configuration: FireTopicDetailRuntimeConfiguration, - buildDurationMs: Int64, - applyDurationMs: Int64 - ) { - guard buildDurationMs >= fireTopicDetailSnapshotBuildDiagnosticThresholdMs - || applyDurationMs >= fireTopicDetailSnapshotApplyDiagnosticThresholdMs - || !feedController.isViewAttached else { - return - } - viewModel.topicDetailLogger()?.debug( - "topic detail snapshot apply diagnostic topic_id=\(topic.id) snapshot_build_ms=\(buildDurationMs) feed_apply_ms=\(applyDurationMs) snapshot_item_count=\(snapshot.items.count) topic_collection_revision=\(configuration.topicCollectionRevision) has_detail=\(configuration.detail != nil) feed_attached=\(feedController.isViewAttached)" - ) - } - - nonisolated private static func elapsedMilliseconds(since startedAt: Date) -> Int64 { + nonisolated static func elapsedMilliseconds(since startedAt: Date) -> Int64 { Int64((Date().timeIntervalSince(startedAt) * 1_000).rounded()) } - nonisolated private static func formatSize(_ size: CGSize) -> String { + nonisolated static func formatSize(_ size: CGSize) -> String { "\(Int(size.width.rounded()))x\(Int(size.height.rounded()))" } - func layoutDiagnosticsSignature() -> String { - "bounds=\(Self.formatSize(view.bounds.size)) safe_bottom=\(Int(view.safeAreaInsets.bottom.rounded())) feed_attached=\(feedController.isViewAttached)" - } - - func shouldLogLayoutDiagnostics(signature: String) -> Bool { - guard lastLayoutDiagnosticsSignature == signature else { - lastLayoutDiagnosticsSignature = signature - repeatedLayoutDiagnosticsCount = 0 - return true - } - repeatedLayoutDiagnosticsCount += 1 - return repeatedLayoutDiagnosticsCount.isMultiple(of: 500) - } - - func handleLayoutRevisionChanged() { - guard let snapshot = feedUpdatePipeline.currentSnapshot, - let configuration = feedUpdatePipeline.currentConfiguration else { - return - } - feedController.applyPublishedLayoutRevision( - publishedKeys: layoutManager.currentPublishedKeys, - items: snapshot.items, - configuration: configuration - ) - } - - func performRefresh() async { - timingTracker.recordInteraction() - topicDetailStore.clearScrollTarget(topicId: topic.id) - await loadTopicDetail(force: true) - // Force-load rebuilds Texture nodes; re-assert shell so dark→light survives PTR. - applyAppearanceShell() - } - - func handleKeyboardNotification(_ notification: Notification) { - if notification.name == UIResponder.keyboardWillHideNotification { - keyboardFrameInScreen = .null - } else { - keyboardFrameInScreen = - (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect) ?? .null - } - updateBottomChromeInset(animatedWith: notification) - } - - func updateBottomChromeInset(animatedWith notification: Notification? = nil) { - // WeChat-style bottom input — pure UIKit, no Texture overlay: - // - // 1) Bar internal bottom padding - // - keyboard hidden → home-indicator safe area - // - keyboard up → small pad (keyboard covers home indicator) - // 2) Keyboard overlap → bar bottom constraint constant - // 3) Feed contentInset.bottom = barHeight + keyboardOverlap - let keyboardOverlap = keyboardOverlapHeight - let keyboardVisible = keyboardOverlap > 0.5 - let homeIndicator = view.safeAreaInsets.bottom - let barBottomPadding: CGFloat = keyboardVisible ? 8 : homeIndicator - - quickReplyBar.updateBottomInset(barBottomPadding) - - let previousBottom = quickReplyBottomConstraint?.constant ?? 0 - let previousHeight = quickReplyHeightConstraint?.constant ?? 0 - let measuredBarHeight = quickReplyBar.preferredHeight(forWidth: max(view.bounds.width, 1)) - quickReplyBottomConstraint?.constant = -keyboardOverlap - quickReplyHeightConstraint?.constant = measuredBarHeight - - let barVisible = !quickReplyBar.isHidden - let feedBottom = fireTopicDetailFeedBottomInset( - quickReplyBarHeight: measuredBarHeight, - safeAreaBottom: homeIndicator, - keyboardOverlap: keyboardOverlap, - isQuickReplyVisible: barVisible - ) - rootNode.updateFeedBottomInset(feedBottom) - updateFeedTopInset() - view.bringSubviewToFront(quickReplyBar) - - let geometryChanged = - abs(previousBottom + keyboardOverlap) > 0.5 - || abs(previousHeight - measuredBarHeight) > 0.5 - - guard geometryChanged || notification != nil else { return } - - if let notification { - let duration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)? - .doubleValue ?? 0.25 - let curveRawValue = (notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)? - .uintValue ?? UInt(UIView.AnimationCurve.easeInOut.rawValue) - // Keyboard uses a private curve (rawValue 7). Shift into - // UIView.AnimationOptions so the bar tracks the system animation. - let options = UIView.AnimationOptions(rawValue: curveRawValue << 16) - UIView.animate( - withDuration: duration, - delay: 0, - options: [options, .beginFromCurrentState, .allowUserInteraction] - ) { - self.view.layoutIfNeeded() - } - } - // Non-keyboard geometry commits on the next layout pass, or via an - // explicit layoutIfNeeded() in presentQuickReplyInput() before focus. - } - - var currentSearchBarHeight: CGFloat { - topicSearchBar.isHidden ? 0 : topicSearchBar.bounds.height - } - - var keyboardOverlapHeight: CGFloat { - guard !keyboardFrameInScreen.isNull else { - return 0 - } - let frameInView = view.convert(keyboardFrameInScreen, from: nil) - return max(view.bounds.intersection(frameInView).height, 0) - } - - func handleVisiblePostNumbersChanged(_ visiblePostNumbers: Set) { - if !visiblePostNumbers.isEmpty { - timingTracker.recordInteraction() - } - timingTracker.updateVisiblePostNumbers(visiblePostNumbers) - - topicDetailStore.noteVisiblePosts( - topicId: topic.id, - postNumbers: visiblePostNumbers - ) - maybePresentReactionPickerCoachmark(visiblePostNumbers: visiblePostNumbers) - } - - func handleRichTextLink(_ url: URL) { - timingTracker.recordInteraction() - - guard let route = FireRouteParser.parse(url: url) else { - modalRouter.presentWebLink(url) - return - } - - switch route { - case .profile(let username): - modalRouter.presentProfile(username: username) - case .topic(let payload): - handleTopicLink(payload) - case .badge: - modalRouter.push(route: route) - case .notifications, .profileTab, .search: - break - } - } - - func handleTopicLink(_ payload: FireTopicRoutePayload) { - if payload.topicId == topic.id { - guard let postNumber = payload.postNumber else { return } - openPostNumber(postNumber) - return - } - modalRouter.push(route: .topic(payload: payload)) - } - - func handleQuickReplyFocusChanged(_ focused: Bool) { - if focused { - topicDetailStore.beginReplyTyping(topicId: topic.id) - } else { - Task { - topicDetailStore.endReplyTyping(topicId: topic.id) - } - } - } - - func openComposer(replyToPost: TopicPostState?) { - composerContext = FireReplyComposerContext( - topicId: topic.id, - postId: replyToPost?.id, - replyToPostNumber: replyToPost?.postNumber, - replyToUsername: replyToPost?.username, - kind: .reply - ) - presentQuickReplyInput() - } - - func openBoostComposer(for post: TopicPostState) { - guard post.canBoost else { - modalRouter.presentNotice(message: "当前帖子暂时不能 Boost。") - return - } - guard canWriteInteractions else { - modalRouter.presentNotice(message: "登录后才能 Boost。") - return - } - // Share the bottom quick-reply chrome with comments instead of a separate sheet. - composerContext = FireReplyComposerContext( - topicId: topic.id, - postId: post.id, - replyToPostNumber: post.postNumber, - replyToUsername: post.username, - kind: .boost - ) - if !replyDraft.isEmpty, composerContext?.isBoost == true { - // Keep draft if user was already drafting a boost; otherwise clear reply draft noise. - } - presentQuickReplyInput() - } - - /// Apply chrome first, commit bar geometry, then focus so the keyboard and - /// input strip rise together (especially for swipe-to-reply). - func presentQuickReplyInput() { - buildAndApplyChromeState() - // Target row / height must be in the hierarchy before first-responder - // kicks off the keyboard animation; otherwise the bar catches up late. - view.layoutIfNeeded() - quickReplyBar.focusInput() - } - - - - - - static let reactionPickerAutoCollapseSeconds: TimeInterval = 3.5 - - func openPostNumber(_ postNumber: UInt32) { - guard postNumber > 0 else { return } - Task { - await loadTopicDetail(targetPostNumber: postNumber) - } - } - - - - - - - - - - - func clearComposerTarget() { - // Cancel target is a full dismiss of the current compose session: drop the - // reply/Boost target, wipe draft text, and leave the keyboard down. - composerContext = nil - replyDraft = "" - quickReplyError = nil - buildAndApplyChromeState() - view.layoutIfNeeded() - quickReplyBar.resignInputFocus() - } - - func openAdvancedComposer() { - let context = composerContext - ?? FireReplyComposerContext( - topicId: topic.id, - postId: nil, - replyToPostNumber: nil, - replyToUsername: nil - ) - quickReplyBar.resignInputFocus() - modalRouter.presentAdvancedComposer( - route: FireComposerRoute( - kind: .advancedReply( - topicID: topic.id, - topicTitle: displayedTopicTitle, - categoryID: displayedCategoryId, - replyToPostNumber: context.replyToPostNumber, - replyToUsername: context.replyToUsername, - isPrivateMessage: isPrivateMessageThread - ) - ), - initialBody: replyDraft, - onReplySubmitted: { [weak self] in - guard let self else { return } - self.replyDraft = "" - self.composerContext = nil - self.quickReplyError = nil - self.buildAndApplyChromeState() - }, - onSubmissionNotice: { [weak self] message in - self?.modalRouter.presentNotice(message: message) - } - ) - } - - func openQuoteComposer(for post: TopicPostState) { - guard let quote = FireQuoteMarkdown.build( - username: post.username, - postNumber: post.postNumber, - topicID: topic.id, - plainText: post.presentation?.plainText() ?? "" - ) else { - modalRouter.presentNotice(message: "该帖子暂无可引用内容。") - return - } - - let quickReplyDraft = replyDraft - let initialBody = FireComposerInitialBody.merge( - initialBody: quote, - currentBody: quickReplyDraft - ).text - let quoteSelectionLocation = (quote as NSString).length - composerContext = FireReplyComposerContext( - topicId: topic.id, - postId: post.id, - replyToPostNumber: post.postNumber, - replyToUsername: post.username - ) - quickReplyBar.resignInputFocus() - buildAndApplyChromeState() - modalRouter.presentAdvancedComposer( - route: FireComposerRoute( - kind: .advancedReply( - topicID: topic.id, - topicTitle: displayedTopicTitle, - categoryID: displayedCategoryId, - replyToPostNumber: post.postNumber, - replyToUsername: post.username, - isPrivateMessage: isPrivateMessageThread - ) - ), - initialBody: initialBody, - initialBodySelectionLocation: quoteSelectionLocation, - onReplySubmitted: { [weak self] in - guard let self else { return } - self.replyDraft = "" - self.composerContext = nil - self.quickReplyError = nil - self.buildAndApplyChromeState() - }, - onSubmissionNotice: { [weak self] message in - self?.modalRouter.presentNotice(message: message) - }, - scrollToCreatedReply: true - ) - } - - func submitQuickReply(_ payload: FireBottomInputPayload) { - Task { @MainActor in - let raw: String - do { - raw = try await composeQuickReplyRaw(from: payload) - } catch { - quickReplyError = error.localizedDescription - buildAndApplyChromeState() - return - } - - let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { - quickReplyError = composerContext?.isBoost == true - ? "Boost 内容不能为空。" - : "回复内容不能为空。" - buildAndApplyChromeState() - return - } - - if composerContext?.isBoost == true { - submitBoostFromQuickReply(raw: trimmed) - return - } - - guard trimmed.count >= minimumReplyLength else { - quickReplyError = "回复至少需要 \(minimumReplyLength) 个字。" - buildAndApplyChromeState() - return - } - - let topicId = composerContext?.topicId ?? topic.id - let replyToPostNumber = composerContext?.replyToPostNumber - quickReplyError = nil - buildAndApplyChromeState() - - do { - try await topicDetailStore.submitReply( - topicId: topicId, - raw: trimmed, - replyToPostNumber: replyToPostNumber, - scrollToCreated: false - ) - finishQuickReplySuccess() - } catch { - let message = error.localizedDescription - if message.localizedCaseInsensitiveContains("pending review") { - finishQuickReplySuccess() - modalRouter.presentNotice(message: "回复已提交,等待审核。") - return - } - quickReplyError = message - buildAndApplyChromeState() - } - } - } - - func composeQuickReplyRaw(from payload: FireBottomInputPayload) async throws -> String { - var parts: [String] = [] - let trimmed = payload.text.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmed.isEmpty { - parts.append(trimmed) - } - for image in payload.images { - guard let data = image.fireJPEGDataForUpload() else { continue } - let upload = try await viewModel.uploadImage( - fileName: "reply-\(UUID().uuidString).jpg", - mimeType: "image/jpeg", - bytes: data - ) - let alt = upload.originalFilename?.isEmpty == false - ? upload.originalFilename! - : "image" - parts.append("![\(alt)](\(upload.shortUrl))") - } - return parts.joined(separator: "\n\n") - } - - func finishQuickReplySuccess() { - replyDraft = "" - composerContext = nil - quickReplyBar.resetAfterSend() - quickReplyBar.resignInputFocus() - buildAndApplyChromeState() - } - - func searchQuickReplyMentions(term: String) async -> [FireBottomInputMention] { - do { - let result = try await viewModel.searchService.searchUsers( - term: term, - includeGroups: true, - limit: 8, - topicID: topic.id, - categoryID: displayedCategoryId - ) - let users = result.users.map { user in - FireBottomInputMention( - handle: user.username, - displayName: user.name?.trimmingCharacters(in: .whitespacesAndNewlines) ?? user.username - ) - } - let groups = result.groups.map { group in - FireBottomInputMention( - handle: group.name, - displayName: group.fullName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? group.name - ) - } - return users + groups - } catch { - return [] - } - } - - func presentQuickReplyImagePicker() { - var configuration = PHPickerConfiguration(photoLibrary: .shared()) - configuration.filter = .images - configuration.selectionLimit = 4 - let picker = PHPickerViewController(configuration: configuration) - picker.delegate = self - present(picker, animated: true) - } - - func submitBoostFromQuickReply(raw: String) { - guard let postId = composerContext?.postId else { - quickReplyError = "找不到要 Boost 的帖子。" - buildAndApplyChromeState() - return - } - quickReplyError = nil - buildAndApplyChromeState() - Task { @MainActor in - do { - try await topicDetailStore.createBoost( - topicId: topic.id, - postId: postId, - raw: raw - ) - finishQuickReplySuccess() - FireMotionHaptics.success() - } catch is CancellationError { - // ignore - } catch { - FireMotionHaptics.error() - quickReplyError = error.localizedDescription - buildAndApplyChromeState() - } - } - } - - func presentTopicBookmarkEditor() { - modalRouter.presentBookmarkEditor( - context: topicBookmarkContext, - recoveryOriginURL: topicCloudflareRecoveryURL, - onReload: { } - ) - } - - func presentPostBookmarkEditor(_ post: TopicPostState) { - modalRouter.presentBookmarkEditor( - context: postBookmarkContext(for: post), - recoveryOriginURL: topicCloudflareRecoveryURL, - onReload: { } - ) - } - - func presentPostEditor(_ post: TopicPostState) { - modalRouter.presentPostEditor( - topicID: topic.id, - context: FirePostEditorContext(postID: post.id, postNumber: post.postNumber), - onSaved: { [weak self] in - guard let self else { return } - _ = try? await self.topicDetailStore.prepareEdit(topicId: self.topic.id, postId: post.id) - } - ) - } - - func presentTopicEditor() { - modalRouter.presentTopicEditor( - topicID: topic.id, - initialTitle: detailSnapshot?.chrome.title ?? topic.title, - initialCategoryID: detailSnapshot?.chrome.categoryId ?? topic.categoryId, - initialTags: detailSnapshot?.chrome.tags ?? row.tagNames, - onSaved: { } - ) - } - - func presentFlagSheet(_ post: TopicPostState) { - modalRouter.presentFlagSheet( - topicID: topic.id, - context: FirePostManagementContext( - postID: post.id, - postNumber: post.postNumber, - username: post.username - ), - onSubmitted: { [weak self] message in - self?.modalRouter.presentNotice(message: message) - } - ) - } - - func updateTopicNotificationLevel(_ option: FireTopicNotificationLevelOption) { - Task { @MainActor in - do { - try await viewModel.topicInteraction.setTopicNotificationLevel( - topicID: topic.id, - notificationLevel: option.rawValue, - recoveryOriginURL: topicCloudflareRecoveryURL - ) - try await topicDetailStore.setNotificationLevel( - topicId: topic.id, - level: Int32(option.rawValue) - ) - FireUIKitToast.show(option.cycleToastMessage, style: .success, in: view) - } catch { - // Reconcile toolbar glyph if the optimistic cycle preview diverged. - buildAndApplyChromeState() - modalRouter.presentNotice(message: error.localizedDescription) - } - } - } - -} - -extension FireTopicDetailViewController: PHPickerViewControllerDelegate { - func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { - picker.dismiss(animated: true) - for result in results { - let provider = result.itemProvider - guard provider.canLoadObject(ofClass: UIImage.self) else { continue } - provider.loadObject(ofClass: UIImage.self) { [weak self] object, _ in - guard let image = object as? UIImage else { return } - Task { @MainActor in - self?.quickReplyBar.insertImage(image) - } - } - } - } -} - -extension FireTopicDetailViewController: FireAppearanceApplying { - func applyAppearance(_ snapshot: FireAppearanceSnapshot) { - let style = snapshot.userInterfaceStyle - let styleChanged = lastColorAppearanceStyle != style - lastColorAppearanceStyle = style - viewModel.topicDetailLogger()?.info( - "topic detail applyAppearance topic_id=\(row.topic.id) style=\(style.rawValue) token=\(snapshot.token) style_changed=\(styleChanged)" - ) - applyAppearanceShell(snapshot) - quickReplyBar.applyThemeColorsIfNeeded() - feedController.refreshColorAppearance(snapshot) - } } diff --git a/apps/ios-app/App/TopicDetail/Controller/FireTopicUserInfoSheet.swift b/apps/ios-app/App/TopicDetail/Controller/FireTopicUserInfoSheet.swift new file mode 100644 index 00000000..054ec598 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Controller/FireTopicUserInfoSheet.swift @@ -0,0 +1,124 @@ +import SwiftUI + +struct FireTopicUserInfoSheet: View { + @ObservedObject var viewModel: FireAppViewModel + let username: String + let onMessage: (UserProfileState) -> Void + + @State private var profile: UserProfileState? + @State private var summary: UserSummaryState? + @State private var isLoading = false + @State private var errorMessage: String? + + var body: some View { + VStack(alignment: .leading, spacing: 18) { + if let profile { + header(profile) + FireProfileStatsRow(items: [ + (formatNumber(summary?.stats.topicCount ?? 0), "话题"), + (formatNumber(summary?.stats.postCount ?? 0), "回复"), + (formatNumber(summary?.stats.likesReceived ?? 0), "获赞"), + (formatNumber(profile.totalFollowers), "粉丝"), + ]) + metaRows(profile) + if let bio = profile.bioPlainText?.trimmingCharacters(in: .whitespacesAndNewlines), + !bio.isEmpty { + Text(bio) + .font(.footnote) + .foregroundStyle(FireTheme.subtleInk) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + } + if canSendPrivateMessage(profile) { + Button { + onMessage(profile) + } label: { + Label("发私信", systemImage: "envelope") + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .tint(FireTheme.accent) + } + } else if isLoading { + ProgressView("正在加载用户信息...") + .frame(maxWidth: .infinity, alignment: .center) + } else { + Text(errorMessage ?? "无法加载用户信息。") + .font(.footnote) + .foregroundStyle(FireTheme.subtleInk) + } + } + .padding(20) + .frame(maxWidth: .infinity, alignment: .leading) + .task(id: username) { + await load() + } + } + + private func header(_ profile: UserProfileState) -> some View { + HStack(alignment: .center, spacing: 14) { + FireAvatarView( + avatarTemplate: profile.avatarTemplate, + username: profile.username, + size: 64, + baseURLString: viewModel.session.bootstrap.baseUrl.ifEmpty("https://linux.do") + ) + + VStack(alignment: .leading, spacing: 5) { + Text((profile.name ?? "").ifEmpty(profile.username)) + .font(.headline) + .foregroundStyle(FireTheme.ink) + Text("@\(profile.username) · \(profile.trustLevelLabel)") + .font(.caption) + .foregroundStyle(FireTheme.tertiaryInk) + } + } + } + + @ViewBuilder + private func metaRows(_ profile: UserProfileState) -> some View { + VStack(alignment: .leading, spacing: 10) { + if let createdAt = profile.createdAt, !createdAt.isEmpty { + FireProfileMetaEntryView(symbol: "calendar", label: "加入时间", value: createdAt) + } + if let lastSeenAt = profile.lastSeenAt, !lastSeenAt.isEmpty { + FireProfileMetaEntryView(symbol: "clock", label: "最近活跃", value: lastSeenAt) + } + if let score = profile.gamificationScore { + FireProfileMetaEntryView(symbol: "sparkles", label: "积分", value: formatNumber(score)) + } + } + } + + private func load() async { + let normalized = username.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalized.isEmpty else { return } + isLoading = true + errorMessage = nil + do { + async let fetchedProfile = viewModel.fetchUserProfile(username: normalized) + async let fetchedSummary = viewModel.fetchUserSummary(username: normalized) + let (profile, summary) = try await (fetchedProfile, fetchedSummary) + self.profile = profile + self.summary = summary + isLoading = false + } catch { + isLoading = false + errorMessage = error.localizedDescription + } + } + + private func canSendPrivateMessage(_ profile: UserProfileState) -> Bool { + let current = viewModel.session.bootstrap.currentUsername? + .trimmingCharacters(in: .whitespacesAndNewlines) + return current?.localizedCaseInsensitiveCompare(profile.username) != ComparisonResult.orderedSame + && profile.canSendPrivateMessageToUser + } + + private func formatNumber(_ value: UInt32) -> String { + if value >= 10_000 { + return String(format: "%.1f万", Double(value) / 10_000.0) + } + return "\(value)" + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailAISummaryCellNode.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailAISummaryCellNode.swift new file mode 100644 index 00000000..13a48de7 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailAISummaryCellNode.swift @@ -0,0 +1,186 @@ +import AsyncDisplayKit +import UIKit + +final class FireTopicDetailAISummaryCellNode: ASCellNode { + private let backgroundNode = ASDisplayNode() + private let headerButtonNode: FireTopicDetailChipButtonNode + private let iconNode = ASImageNode() + private let titleNode = ASTextNode() + private let statusNode = ASTextNode() + private let chevronNode = ASImageNode() + private let bodyNode = ASTextNode() + private let metadataNode = ASTextNode() + private let isExpanded: Bool + + init( + configuration: FireTopicDetailRuntimeConfiguration, + appearance: FireAppearanceSnapshot = FireAppearanceEnvironment.snapshot(traits: .current) + ) { + let summary = configuration.topicAiSummary + isExpanded = configuration.isTopicAiSummaryExpanded && summary != nil + let primaryInk = appearance.ink + let secondaryInk = appearance.subtleInk + let tertiaryInk = appearance.tertiaryInk + + backgroundNode.backgroundColor = .secondarySystemBackground + backgroundNode.cornerRadius = 8 + backgroundNode.clipsToBounds = true + + iconNode.image = UIImage(systemName: "sparkles")?.withTintColor( + FireTopicDetailCellColors.accent, + renderingMode: .alwaysOriginal + ) + iconNode.style.preferredSize = CGSize(width: 17, height: 17) + + titleNode.attributedText = NSAttributedString( + string: "AI 摘要", + attributes: [ + .font: FireTopicDetailRuntimeTypography.scaledFont(textStyle: .subheadline, weight: .semibold), + .foregroundColor: primaryInk, + ] + ) + + if summary?.outdated == true { + statusNode.attributedText = NSAttributedString( + string: "有新回复", + attributes: [ + .font: FireTopicDetailRuntimeTypography.scaledFont(textStyle: .caption2, weight: .semibold), + .foregroundColor: FireTopicDetailCellColors.warning, + ] + ) + statusNode.backgroundColor = FireTopicDetailCellColors.warning.withAlphaComponent(0.12) + statusNode.cornerRadius = 10 + statusNode.textContainerInset = UIEdgeInsets(top: 3, left: 8, bottom: 3, right: 8) + } else { + statusNode.isHidden = true + } + + let chevronName = isExpanded ? "chevron.up" : "chevron.down" + chevronNode.image = UIImage(systemName: chevronName)?.withTintColor( + tertiaryInk, + renderingMode: .alwaysOriginal + ) + chevronNode.style.preferredSize = CGSize(width: 14, height: 14) + + if let summary, isExpanded { + bodyNode.attributedText = NSAttributedString( + string: summary.summarizedText, + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: primaryInk, + ] + ) + bodyNode.maximumNumberOfLines = 0 + bodyNode.style.flexShrink = 1.0 + + let metadata = Self.metadata(for: summary) + if !metadata.isEmpty { + metadataNode.attributedText = NSAttributedString( + string: metadata.joined(separator: " · "), + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .caption2), + .foregroundColor: secondaryInk, + ] + ) + metadataNode.maximumNumberOfLines = 0 + } else { + metadataNode.isHidden = true + } + } else { + bodyNode.isHidden = true + metadataNode.isHidden = true + } + + headerButtonNode = FireTopicDetailChipButtonNode(action: configuration.onToggleTopicAiSummaryExpanded) + headerButtonNode.accessibilityLabel = isExpanded ? "收起 AI 摘要" : "展开 AI 摘要" + + super.init() + automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: self) + FireAppearanceTexture.configureChromeTextNode(titleNode) + FireAppearanceTexture.configureChromeTextNode(statusNode) + FireAppearanceTexture.configureChromeTextNode(bodyNode) + FireAppearanceTexture.configureChromeTextNode(metadataNode) + isAccessibilityElement = false + accessibilityElements = [headerButtonNode, bodyNode, metadataNode].filter { !$0.isHidden } + headerButtonNode.accessibilityValue = [ + statusNode.isHidden ? nil : "有新回复", + isExpanded ? bodyNode.attributedText?.string : "已折叠", + isExpanded ? metadataNode.attributedText?.string : nil, + ] + .compactMap { $0 } + .filter { !$0.isEmpty } + .joined(separator: ",") + } + + override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { + let headerSpacer = ASLayoutSpec() + headerSpacer.style.flexGrow = 1.0 + let headerChildren: [ASLayoutElement] = [ + iconNode, + titleNode, + headerSpacer, + statusNode, + chevronNode, + ].filter { element in + guard let node = element as? ASDisplayNode else { return true } + return !node.isHidden + } + let headerContent = ASStackLayoutSpec( + direction: .horizontal, + spacing: 8, + justifyContent: .start, + alignItems: .center, + children: headerChildren + ) + let headerButtonSpec = ASBackgroundLayoutSpec( + child: headerContent, + background: headerButtonNode + ) + headerButtonNode.style.flexGrow = 1.0 + headerButtonNode.style.alignSelf = .stretch + + var contentChildren: [ASLayoutElement] = [headerButtonSpec] + if !bodyNode.isHidden { + contentChildren.append(bodyNode) + } + if !metadataNode.isHidden { + contentChildren.append(metadataNode) + } + + let contentStack = ASStackLayoutSpec( + direction: .vertical, + spacing: isExpanded ? 10 : 0, + justifyContent: .start, + alignItems: .stretch, + children: contentChildren + ) + let paddedContent = ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 12, left: 14, bottom: 12, right: 14), + child: contentStack + ) + let card = ASBackgroundLayoutSpec(child: paddedContent, background: backgroundNode) + return ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 4, left: 16, bottom: 10, right: 16), + child: card + ) + } + + private static func metadata(for summary: TopicAiSummaryState) -> [String] { + var metadata: [String] = [] + if let updatedAt = FireTopicPresentation.formatTimestamp(summary.updatedAt) { + metadata.append("更新 \(updatedAt)") + } + if summary.outdated, summary.newPostsSinceSummary > 0 { + metadata.append("\(summary.newPostsSinceSummary) 条新回复") + } + if let algorithm = summary.algorithm?.trimmingCharacters(in: .whitespacesAndNewlines), + !algorithm.isEmpty { + metadata.append(algorithm) + } + if summary.canRegenerate { + metadata.append("可重新生成") + } + return metadata + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailBodyStateCell.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailBodyStateCell.swift new file mode 100644 index 00000000..4a45647a --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailBodyStateCell.swift @@ -0,0 +1,81 @@ +import UIKit + +final class FireTopicDetailBodyStateCell: UICollectionViewCell { + static let reuseID = "FireTopicDetailBodyStateCell" + + private let activityIndicator = UIActivityIndicatorView(style: .medium) + private let messageLabel = UILabel() + private let button = UIButton(type: .system) + private let stackView = UIStackView() + private var action: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + setup() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setup() { + contentView.backgroundColor = FireTheme.uiCanvas + + messageLabel.font = .preferredFont(forTextStyle: .caption1) + messageLabel.adjustsFontForContentSizeCategory = true + messageLabel.textColor = .secondaryLabel + messageLabel.numberOfLines = 0 + messageLabel.textAlignment = .center + + button.setTitleColor(FireTopicDetailCellColors.accent, for: .normal) + button.titleLabel?.font = .preferredFont(forTextStyle: .subheadline) + button.titleLabel?.adjustsFontForContentSizeCategory = true + button.addAction(UIAction { [weak self] _ in + self?.action?() + }, for: .touchUpInside) + + stackView.axis = .vertical + stackView.alignment = .center + stackView.spacing = 8 + stackView.translatesAutoresizingMaskIntoConstraints = false + stackView.addArrangedSubview(activityIndicator) + stackView.addArrangedSubview(messageLabel) + stackView.addArrangedSubview(button) + contentView.addSubview(stackView) + + NSLayoutConstraint.activate([ + stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), + stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), + stackView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + ]) + + configure(isLoading: false, errorMessage: nil, action: nil) + } + + func configure(isLoading: Bool, errorMessage: String?, action: (() -> Void)?) { + self.action = action + if isLoading { + activityIndicator.isHidden = false + activityIndicator.startAnimating() + messageLabel.text = "加载中..." + button.isHidden = true + button.setTitle(nil, for: .normal) + } else { + activityIndicator.stopAnimating() + activityIndicator.isHidden = true + messageLabel.text = errorMessage ?? "加载帖子" + button.setTitle(errorMessage == nil ? "加载" : "重试", for: .normal) + button.isHidden = action == nil + } + accessibilityLabel = [messageLabel.text, button.title(for: .normal)] + .compactMap { $0 } + .joined(separator: ",") + } + + override func prepareForReuse() { + super.prepareForReuse() + configure(isLoading: false, errorMessage: nil, action: nil) + } +} + diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailCellTheme.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailCellTheme.swift new file mode 100644 index 00000000..2a1f3824 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailCellTheme.swift @@ -0,0 +1,38 @@ +import AsyncDisplayKit +import UIKit + +enum FireTopicDetailCellColors { + static var accent: UIColor { FireTheme.uiAccent } + static var warning: UIColor { FireTheme.uiWarning } + static var tagChipBackground: UIColor { FireTheme.uiTagChipBackground } + static var tagChipForeground: UIColor { FireTheme.uiTagChipForeground } + static let privateMessageForeground = UIColor.systemIndigo + + static func categoryChipBackground(accent: UIColor) -> UIColor { + FireTheme.uiCategoryChipBackground(accent: accent) + } +} + + +final class FireTopicDetailChipButtonNode: ASButtonNode { + private let action: (() -> Void)? + + init(action: (() -> Void)?) { + self.action = action + super.init() + addTarget(self, action: #selector(handleTap), forControlEvents: .touchUpInside) + } + + @objc private func handleTap() { + action?() + } +} + +enum FireTopicDetailRuntimeTypography { + static func scaledFont(textStyle: UIFont.TextStyle, weight: UIFont.Weight) -> UIFont { + let preferred = UIFont.preferredFont(forTextStyle: textStyle) + return UIFontMetrics(forTextStyle: textStyle).scaledFont( + for: UIFont.systemFont(ofSize: preferred.pointSize, weight: weight) + ) + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+BodyState.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+BodyState.swift new file mode 100644 index 00000000..49c45a7c --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+BodyState.swift @@ -0,0 +1,220 @@ +import AsyncDisplayKit +import UIKit + +extension FireTopicDetailFeedCellFactory { + @objc + private func handleLoadTopicDetail() { + guard let configuration else { return } + Task { await configuration.onLoadTopicDetail() } + } + + func makeBodyStateCellNode( + configuration: FireTopicDetailRuntimeConfiguration, + appearance: FireAppearanceSnapshot + ) -> ASCellNode { + let node = ASCellNode() + node.automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: node) + + let stackChildren: [ASLayoutElement] + if configuration.isLoadingTopic || configuration.isWaitingForPostRender { + let label = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(label) + label.attributedText = NSAttributedString( + string: "加载中...", + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .caption1), + .foregroundColor: appearance.subtleInk, + ] + ) + stackChildren = [label] + } else { + let messageNode = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(messageNode) + messageNode.attributedText = NSAttributedString( + string: configuration.detailError ?? "加载帖子", + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .caption1), + .foregroundColor: appearance.subtleInk, + ] + ) + messageNode.maximumNumberOfLines = 0 + + let buttonNode = ASButtonNode() + buttonNode.setTitle( + configuration.detailError == nil ? "加载" : "重试", + with: UIFont.preferredFont(forTextStyle: .subheadline), + with: FireTopicDetailCellColors.accent, + for: .normal + ) + buttonNode.addTarget(self, action: #selector(handleLoadTopicDetail), forControlEvents: .touchUpInside) + buttonNode.fireBindPressBounce(.button) + + stackChildren = [messageNode, buttonNode] + } + + node.layoutSpecBlock = { _, constrainedSize in + let height = max(constrainedSize.min.height, 96) + let stack = ASStackLayoutSpec( + direction: .vertical, + spacing: 8, + justifyContent: .center, + alignItems: .center, + children: stackChildren + ) + let sized = ASStackLayoutSpec( + direction: .vertical, + spacing: 8, + justifyContent: .center, + alignItems: .center, + children: [stack] + ) + sized.style.preferredSize = CGSize(width: constrainedSize.max.width, height: height) + return ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16), + child: sized + ) + } + return node + } + + func makeTextCellNode( + for item: FireTopicDetailRuntimeItem, + configuration: FireTopicDetailRuntimeConfiguration, + appearance: FireAppearanceSnapshot + ) -> ASCellNode { + let node = ASCellNode() + node.automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: node) + + let titleNode = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(titleNode) + titleNode.maximumNumberOfLines = 0 + let bodyNode = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(bodyNode) + bodyNode.maximumNumberOfLines = 0 + + switch item.kind { + case .header: + let status = configuration.row.statusLabels.joined(separator: " · ") + titleNode.attributedText = NSAttributedString( + string: configuration.displayedTopicTitle, + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .headline), + .foregroundColor: appearance.ink, + ] + ) + bodyNode.attributedText = status.isEmpty ? nil : NSAttributedString( + string: status, + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: appearance.subtleInk, + ] + ) + case .aiSummary: + let title = "AI 摘要" + let body: String + if let summary = configuration.topicAiSummary { + body = configuration.isTopicAiSummaryExpanded + ? summary.summarizedText + : "点击展开" + } else { + body = "" + } + titleNode.attributedText = NSAttributedString( + string: title, + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .headline), + .foregroundColor: appearance.ink, + ] + ) + bodyNode.attributedText = NSAttributedString( + string: body, + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: appearance.subtleInk, + ] + ) + case .notice: + let statusMessage = item.statusMessage + let title = statusMessage?.title?.trimmingCharacters(in: .whitespacesAndNewlines) + let trimmedTitle = (title?.isEmpty == false) ? title : nil + let messageColor = statusMessage?.emphasizesError == true ? UIColor.systemRed : appearance.subtleInk + bodyNode.attributedText = NSAttributedString( + string: statusMessage?.message ?? "正在显示缓存内容", + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: messageColor, + ] + ) + if let trimmedTitle { + titleNode.attributedText = NSAttributedString( + string: trimmedTitle, + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .headline), + .foregroundColor: statusMessage?.emphasizesError == true ? UIColor.systemRed : appearance.ink, + ] + ) + } + default: + break + } + + var children: [ASLayoutElement] = [ + titleNode.attributedText != nil ? titleNode : nil, + bodyNode.attributedText != nil ? bodyNode : nil, + ].compactMap { $0 } + + if item.kind == .notice, item.statusMessage?.retryable == true { + let buttonNode = ASButtonNode() + buttonNode.setTitle( + "重试", + with: UIFont.preferredFont(forTextStyle: .subheadline), + with: FireTopicDetailCellColors.accent, + for: .normal + ) + buttonNode.addTarget(self, action: #selector(handleLoadTopicDetail), forControlEvents: .touchUpInside) + buttonNode.fireBindPressBounce(.button) + children.append(buttonNode) + } + + node.layoutSpecBlock = { _, _ in + let stack = ASStackLayoutSpec( + direction: .vertical, + spacing: 8, + justifyContent: .start, + alignItems: .stretch, + children: children + ) + return ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), + child: stack + ) + } + return node + } + + func makeMissingPostCellNode(appearance: FireAppearanceSnapshot) -> ASCellNode { + let node = ASCellNode() + node.automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: node) + + let textNode = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(textNode) + textNode.attributedText = NSAttributedString( + string: "帖子内容加载中...", + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: appearance.subtleInk, + ] + ) + + node.layoutSpecBlock = { _, _ in + ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), + child: textNode + ) + } + return node + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Replies.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Replies.swift new file mode 100644 index 00000000..0deec71b --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Replies.swift @@ -0,0 +1,178 @@ +import AsyncDisplayKit +import UIKit + +extension FireTopicDetailFeedCellFactory { + @objc + private func handleLoadMoreReplies() { + onRequestLoadMore?() + } + + func makeRepliesHeaderCellNode( + configuration: FireTopicDetailRuntimeConfiguration, + appearance: FireAppearanceSnapshot + ) -> ASCellNode { + let node = ASCellNode() + node.automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: node) + + let titleNode = ASTextNode() + configureChromeTextNode(titleNode) + titleNode.attributedText = NSAttributedString( + string: "回复", + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .headline), + .foregroundColor: appearance.ink, + ] + ) + + let countNode = ASTextNode() + configureChromeTextNode(countNode) + let countText: String + if configuration.detail != nil { + if configuration.loadedReplyCount < configuration.totalReplyCount { + countText = "已加载 \(configuration.loadedReplyCount) / \(configuration.totalReplyCount) 条" + } else { + countText = "\(configuration.totalReplyCount) 条 · \(configuration.displayedFloorCount) 楼" + } + } else { + countText = "" + } + countNode.attributedText = NSAttributedString( + string: countText, + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: appearance.subtleInk, + ] + ) + countNode.style.flexShrink = 1.0 + + node.layoutSpecBlock = { _, _ in + let spacer = ASLayoutSpec() + spacer.style.flexGrow = 1.0 + let stack = ASStackLayoutSpec( + direction: .horizontal, + spacing: 12, + justifyContent: .start, + alignItems: .center, + children: [titleNode, spacer, countNode] + ) + return ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 18, left: 16, bottom: 14, right: 16), + child: stack + ) + } + return node + } + + func makeReplyFooterCellNode( + for item: FireTopicDetailRuntimeItem, + configuration _: FireTopicDetailRuntimeConfiguration, + appearance: FireAppearanceSnapshot + ) -> ASCellNode { + let node = ASCellNode() + node.automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: node) + + let state = (item.contentToken.base as? String) + .flatMap(FireTopicDetailRuntimeReplyFooterState.fromContentToken(_:)) + ?? .none + + let childElement: ASLayoutElement? + switch state { + case .none: + childElement = nil + case .loadMoreAvailable: + let buttonNode = ASButtonNode() + buttonNode.setImage(UIImage(systemName: "arrow.down.circle"), for: .normal) + buttonNode.setTitle( + "加载更多回复", + with: UIFont.preferredFont(forTextStyle: .subheadline), + with: FireTopicDetailCellColors.accent, + for: .normal + ) + buttonNode.contentSpacing = 6 + buttonNode.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) + buttonNode.isEnabled = true + buttonNode.addTarget(self, action: #selector(handleLoadMoreReplies), forControlEvents: .touchUpInside) + buttonNode.fireBindPressBounce(.button) + childElement = buttonNode + case .emptyPrompt: + let label = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(label) + label.attributedText = NSAttributedString( + string: "还没有回复,发表你的看法吧", + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: appearance.subtleInk, + ] + ) + childElement = label + case .endReached: + let label = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(label) + label.attributedText = NSAttributedString( + string: "---- 到底了 ----", + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: appearance.tertiaryInk, + ] + ) + childElement = label + case .loadFailed(_): + let buttonNode = ASButtonNode() + buttonNode.setImage(UIImage(systemName: "arrow.clockwise.circle"), for: .normal) + buttonNode.setTitle( + "加载更多回复失败,点击重试", + with: UIFont.preferredFont(forTextStyle: .subheadline), + with: FireTopicDetailCellColors.accent, + for: .normal + ) + buttonNode.contentSpacing = 6 + buttonNode.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) + buttonNode.isEnabled = true + buttonNode.addTarget(self, action: #selector(handleLoadMoreReplies), forControlEvents: .touchUpInside) + buttonNode.fireBindPressBounce(.button) + childElement = buttonNode + case .loadingFooter: + let label = ASTextNode() + label.attributedText = NSAttributedString( + string: "正在加载更多回复...", + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: appearance.subtleInk, + ] + ) + let indicator = ASDisplayNode(viewBlock: { + let view = UIActivityIndicatorView(style: .medium) + view.startAnimating() + return view + }) + indicator.style.preferredSize = CGSize(width: 20, height: 20) + childElement = ASStackLayoutSpec( + direction: .horizontal, + spacing: 8, + justifyContent: .center, + alignItems: .center, + children: [indicator, label] + ) + } + + node.layoutSpecBlock = { _, constrainedSize in + let height = max(constrainedSize.min.height, 44) + let child = childElement ?? ASLayoutSpec() + let sized = ASStackLayoutSpec( + direction: .vertical, + spacing: 0, + justifyContent: .center, + alignItems: .center, + children: [child] + ) + sized.style.preferredSize = CGSize(width: constrainedSize.max.width, height: height) + return ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16), + child: sized + ) + } + return node + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Stats.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Stats.swift new file mode 100644 index 00000000..8ddc49d4 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Stats.swift @@ -0,0 +1,102 @@ +import AsyncDisplayKit +import UIKit + +extension FireTopicDetailFeedCellFactory { + func makeStatsCellNode( + configuration: FireTopicDetailRuntimeConfiguration, + layoutWidth: CGFloat, + appearance: FireAppearanceSnapshot + ) -> ASCellNode { + let node = ASCellNode() + node.automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: node) + + let dividerNode = ASDisplayNode() + dividerNode.backgroundColor = appearance.divider + dividerNode.style.preferredSize = CGSize(width: max(layoutWidth, 1), height: 0.5) + + let replyNode = makeStatNode(value: "\(configuration.displayedReplyCount)", label: "回复", appearance: appearance) + let viewNode = makeStatNode(value: "\(configuration.displayedViewsCount)", label: "浏览", appearance: appearance) + let interactionNode = makeStatNode( + value: configuration.displayedInteractionCount.map(String.init) ?? "...", + label: "互动", + appearance: appearance + ) + [replyNode, viewNode, interactionNode].forEach { + $0.style.flexGrow = 1.0 + $0.style.flexShrink = 1.0 + } + + node.layoutSpecBlock = { _, _ in + let stack = ASStackLayoutSpec( + direction: .horizontal, + spacing: 0, + justifyContent: .start, + alignItems: .stretch, + children: [replyNode, viewNode, interactionNode] + ) + stack.style.flexGrow = 1.0 + let rootStack = ASStackLayoutSpec( + direction: .vertical, + spacing: 0, + justifyContent: .start, + alignItems: .stretch, + children: [dividerNode, stack] + ) + return ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 12, left: 16, bottom: 8, right: 16), + child: rootStack + ) + } + return node + } + + private func makeStatNode(value: String, label: String, appearance: FireAppearanceSnapshot) -> ASDisplayNode { + let valueNode = ASTextNode() + // Texture ASTextNode defaults to opaque; without a clear background the + // display fill is pure black, which survives light-theme switches as a + // black bar under 回复/浏览/互动. + configureChromeTextNode(valueNode) + let captionFont = UIFont.preferredFont(forTextStyle: .subheadline) + valueNode.attributedText = NSAttributedString( + string: value, + attributes: [ + .font: UIFontMetrics(forTextStyle: .subheadline).scaledFont( + for: UIFont.monospacedDigitSystemFont(ofSize: captionFont.pointSize, weight: .semibold) + ), + .foregroundColor: appearance.ink, + ] + ) + + let labelNode = ASTextNode() + configureChromeTextNode(labelNode) + labelNode.attributedText = NSAttributedString( + string: label, + attributes: [ + .font: UIFont.preferredFont(forTextStyle: .caption2), + .foregroundColor: appearance.subtleInk, + ] + ) + + let wrapper = ASDisplayNode() + wrapper.automaticallyManagesSubnodes = true + wrapper.backgroundColor = .clear + wrapper.isOpaque = false + wrapper.layoutSpecBlock = { _, _ in + let stack = ASStackLayoutSpec( + direction: .vertical, + spacing: 2, + justifyContent: .start, + alignItems: .center, + children: [valueNode, labelNode] + ) + stack.style.flexGrow = 1.0 + return stack + } + return wrapper + } + + func configureChromeTextNode(_ node: ASTextNode) { + FireAppearanceTexture.configureChromeTextNode(node) + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Voting.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Voting.swift new file mode 100644 index 00000000..3a442a3a --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory+Voting.swift @@ -0,0 +1,135 @@ +import AsyncDisplayKit +import UIKit + +extension FireTopicDetailFeedCellFactory { + @objc + private func handleToggleTopicVote() { + guard let configuration else { return } + Task { await configuration.onToggleTopicVote() } + } + + @objc + private func handleShowTopicVoters() { + guard let configuration else { return } + Task { await configuration.onShowTopicVoters() } + } + + func makeTopicVoteCellNode( + configuration: FireTopicDetailRuntimeConfiguration, + appearance: FireAppearanceSnapshot + ) -> ASCellNode { + guard let detail = configuration.detail else { return ASCellNode() } + + let wrapperNode = ASCellNode() + wrapperNode.automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: wrapperNode) + + let containerNode = ASDisplayNode() + containerNode.backgroundColor = .secondarySystemBackground + containerNode.cornerRadius = 8 + containerNode.automaticallyManagesSubnodes = true + + let titleNode = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(titleNode) + titleNode.attributedText = NSAttributedString( + string: "\(detail.voteCount) 票", + attributes: [ + .font: UIFontMetrics(forTextStyle: .subheadline).scaledFont( + for: UIFont.systemFont( + ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, + weight: .semibold + ) + ), + .foregroundColor: FireTopicDetailCellColors.accent, + ] + ) + + let statusNode = ASTextNode() + FireAppearanceTexture.configureChromeTextNode(statusNode) + if detail.userVoted { + statusNode.attributedText = NSAttributedString( + string: "你已投票", + attributes: [ + .font: UIFontMetrics(forTextStyle: .caption1).scaledFont( + for: UIFont.systemFont( + ofSize: UIFont.preferredFont(forTextStyle: .caption1).pointSize, + weight: .semibold + ) + ), + .foregroundColor: UIColor.systemGreen, + ] + ) + } + statusNode.isHidden = !detail.userVoted + statusNode.style.flexShrink = 1.0 + + let toggleNode = ASButtonNode() + toggleNode.setTitle( + detail.userVoted ? "取消投票" : "投一票", + with: UIFont.preferredFont(forTextStyle: .caption1), + with: detail.userVoted ? appearance.ink : .white, + for: .normal + ) + toggleNode.contentEdgeInsets = UIEdgeInsets(top: 8, left: 14, bottom: 8, right: 14) + toggleNode.backgroundColor = detail.userVoted ? .tertiarySystemFill : FireTopicDetailCellColors.accent + toggleNode.cornerRadius = 16 + toggleNode.clipsToBounds = true + toggleNode.isEnabled = configuration.canWriteInteractions + toggleNode.addTarget(self, action: #selector(handleToggleTopicVote), forControlEvents: .touchUpInside) + toggleNode.fireBindPressBounce(.button) + + let votersNode = ASButtonNode() + votersNode.setImage(UIImage(systemName: "person.3"), for: .normal) + votersNode.setTitle( + "查看投票用户", + with: UIFont.preferredFont(forTextStyle: .caption1), + with: FireTopicDetailCellColors.accent, + for: .normal + ) + votersNode.contentSpacing = 6 + votersNode.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) + votersNode.addTarget(self, action: #selector(handleShowTopicVoters), forControlEvents: .touchUpInside) + votersNode.fireBindPressBounce(.compact) + + containerNode.layoutSpecBlock = { _, _ in + let spacer = ASLayoutSpec() + spacer.style.flexGrow = 1.0 + let headerChildren: [ASLayoutElement] = detail.userVoted + ? [titleNode, spacer, statusNode] + : [titleNode, spacer] + let headerRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: 10, + justifyContent: .start, + alignItems: .center, + children: headerChildren + ) + let buttonRow = ASStackLayoutSpec( + direction: .horizontal, + spacing: 10, + justifyContent: .start, + alignItems: .center, + children: [toggleNode, votersNode] + ) + let innerStack = ASStackLayoutSpec( + direction: .vertical, + spacing: 10, + justifyContent: .start, + alignItems: .stretch, + children: [headerRow, buttonRow] + ) + return ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 14, left: 14, bottom: 14, right: 14), + child: innerStack + ) + } + + wrapperNode.layoutSpecBlock = { _, _ in + ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 8, left: 16, bottom: 4, right: 16), + child: containerNode + ) + } + return wrapperNode + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory.swift index a949edbf..42368bc6 100644 --- a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory.swift +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCellFactory.swift @@ -44,623 +44,4 @@ final class FireTopicDetailFeedCellFactory: NSObject { return makeMissingPostCellNode(appearance: appearance) } } - - @objc - private func handleToggleTopicVote() { - guard let configuration else { return } - Task { await configuration.onToggleTopicVote() } - } - - @objc - private func handleShowTopicVoters() { - guard let configuration else { return } - Task { await configuration.onShowTopicVoters() } - } - - @objc - private func handleLoadMoreReplies() { - onRequestLoadMore?() - } - - @objc - private func handleLoadTopicDetail() { - guard let configuration else { return } - Task { await configuration.onLoadTopicDetail() } - } - - private func makeStatsCellNode( - configuration: FireTopicDetailRuntimeConfiguration, - layoutWidth: CGFloat, - appearance: FireAppearanceSnapshot - ) -> ASCellNode { - let node = ASCellNode() - node.automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: node) - - let dividerNode = ASDisplayNode() - dividerNode.backgroundColor = appearance.divider - dividerNode.style.preferredSize = CGSize(width: max(layoutWidth, 1), height: 0.5) - - let replyNode = makeStatNode(value: "\(configuration.displayedReplyCount)", label: "回复", appearance: appearance) - let viewNode = makeStatNode(value: "\(configuration.displayedViewsCount)", label: "浏览", appearance: appearance) - let interactionNode = makeStatNode( - value: configuration.displayedInteractionCount.map(String.init) ?? "...", - label: "互动", - appearance: appearance - ) - [replyNode, viewNode, interactionNode].forEach { - $0.style.flexGrow = 1.0 - $0.style.flexShrink = 1.0 - } - - node.layoutSpecBlock = { _, _ in - let stack = ASStackLayoutSpec( - direction: .horizontal, - spacing: 0, - justifyContent: .start, - alignItems: .stretch, - children: [replyNode, viewNode, interactionNode] - ) - stack.style.flexGrow = 1.0 - let rootStack = ASStackLayoutSpec( - direction: .vertical, - spacing: 0, - justifyContent: .start, - alignItems: .stretch, - children: [dividerNode, stack] - ) - return ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 12, left: 16, bottom: 8, right: 16), - child: rootStack - ) - } - return node - } - - private func makeStatNode(value: String, label: String, appearance: FireAppearanceSnapshot) -> ASDisplayNode { - let valueNode = ASTextNode() - // Texture ASTextNode defaults to opaque; without a clear background the - // display fill is pure black, which survives light-theme switches as a - // black bar under 回复/浏览/互动. - configureChromeTextNode(valueNode) - let captionFont = UIFont.preferredFont(forTextStyle: .subheadline) - valueNode.attributedText = NSAttributedString( - string: value, - attributes: [ - .font: UIFontMetrics(forTextStyle: .subheadline).scaledFont( - for: UIFont.monospacedDigitSystemFont(ofSize: captionFont.pointSize, weight: .semibold) - ), - .foregroundColor: appearance.ink, - ] - ) - - let labelNode = ASTextNode() - configureChromeTextNode(labelNode) - labelNode.attributedText = NSAttributedString( - string: label, - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .caption2), - .foregroundColor: appearance.subtleInk, - ] - ) - - let wrapper = ASDisplayNode() - wrapper.automaticallyManagesSubnodes = true - wrapper.backgroundColor = .clear - wrapper.isOpaque = false - wrapper.layoutSpecBlock = { _, _ in - let stack = ASStackLayoutSpec( - direction: .vertical, - spacing: 2, - justifyContent: .start, - alignItems: .center, - children: [valueNode, labelNode] - ) - stack.style.flexGrow = 1.0 - return stack - } - return wrapper - } - - private func configureChromeTextNode(_ node: ASTextNode) { - FireAppearanceTexture.configureChromeTextNode(node) - } - - private func makeTopicVoteCellNode( - configuration: FireTopicDetailRuntimeConfiguration, - appearance: FireAppearanceSnapshot - ) -> ASCellNode { - guard let detail = configuration.detail else { return ASCellNode() } - - let wrapperNode = ASCellNode() - wrapperNode.automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: wrapperNode) - - let containerNode = ASDisplayNode() - containerNode.backgroundColor = .secondarySystemBackground - containerNode.cornerRadius = 8 - containerNode.automaticallyManagesSubnodes = true - - let titleNode = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(titleNode) - titleNode.attributedText = NSAttributedString( - string: "\(detail.voteCount) 票", - attributes: [ - .font: UIFontMetrics(forTextStyle: .subheadline).scaledFont( - for: UIFont.systemFont( - ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, - weight: .semibold - ) - ), - .foregroundColor: FireTopicDetailCellColors.accent, - ] - ) - - let statusNode = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(statusNode) - if detail.userVoted { - statusNode.attributedText = NSAttributedString( - string: "你已投票", - attributes: [ - .font: UIFontMetrics(forTextStyle: .caption1).scaledFont( - for: UIFont.systemFont( - ofSize: UIFont.preferredFont(forTextStyle: .caption1).pointSize, - weight: .semibold - ) - ), - .foregroundColor: UIColor.systemGreen, - ] - ) - } - statusNode.isHidden = !detail.userVoted - statusNode.style.flexShrink = 1.0 - - let toggleNode = ASButtonNode() - toggleNode.setTitle( - detail.userVoted ? "取消投票" : "投一票", - with: UIFont.preferredFont(forTextStyle: .caption1), - with: detail.userVoted ? appearance.ink : .white, - for: .normal - ) - toggleNode.contentEdgeInsets = UIEdgeInsets(top: 8, left: 14, bottom: 8, right: 14) - toggleNode.backgroundColor = detail.userVoted ? .tertiarySystemFill : FireTopicDetailCellColors.accent - toggleNode.cornerRadius = 16 - toggleNode.clipsToBounds = true - toggleNode.isEnabled = configuration.canWriteInteractions - toggleNode.addTarget(self, action: #selector(handleToggleTopicVote), forControlEvents: .touchUpInside) - toggleNode.fireBindPressBounce(.button) - - let votersNode = ASButtonNode() - votersNode.setImage(UIImage(systemName: "person.3"), for: .normal) - votersNode.setTitle( - "查看投票用户", - with: UIFont.preferredFont(forTextStyle: .caption1), - with: FireTopicDetailCellColors.accent, - for: .normal - ) - votersNode.contentSpacing = 6 - votersNode.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) - votersNode.addTarget(self, action: #selector(handleShowTopicVoters), forControlEvents: .touchUpInside) - votersNode.fireBindPressBounce(.compact) - - containerNode.layoutSpecBlock = { _, _ in - let spacer = ASLayoutSpec() - spacer.style.flexGrow = 1.0 - let headerChildren: [ASLayoutElement] = detail.userVoted - ? [titleNode, spacer, statusNode] - : [titleNode, spacer] - let headerRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: 10, - justifyContent: .start, - alignItems: .center, - children: headerChildren - ) - let buttonRow = ASStackLayoutSpec( - direction: .horizontal, - spacing: 10, - justifyContent: .start, - alignItems: .center, - children: [toggleNode, votersNode] - ) - let innerStack = ASStackLayoutSpec( - direction: .vertical, - spacing: 10, - justifyContent: .start, - alignItems: .stretch, - children: [headerRow, buttonRow] - ) - return ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 14, left: 14, bottom: 14, right: 14), - child: innerStack - ) - } - - wrapperNode.layoutSpecBlock = { _, _ in - ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 8, left: 16, bottom: 4, right: 16), - child: containerNode - ) - } - return wrapperNode - } - - private func makeRepliesHeaderCellNode( - configuration: FireTopicDetailRuntimeConfiguration, - appearance: FireAppearanceSnapshot - ) -> ASCellNode { - let node = ASCellNode() - node.automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: node) - - let titleNode = ASTextNode() - configureChromeTextNode(titleNode) - titleNode.attributedText = NSAttributedString( - string: "回复", - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .headline), - .foregroundColor: appearance.ink, - ] - ) - - let countNode = ASTextNode() - configureChromeTextNode(countNode) - let countText: String - if configuration.detail != nil { - if configuration.loadedReplyCount < configuration.totalReplyCount { - countText = "已加载 \(configuration.loadedReplyCount) / \(configuration.totalReplyCount) 条" - } else { - countText = "\(configuration.totalReplyCount) 条 · \(configuration.displayedFloorCount) 楼" - } - } else { - countText = "" - } - countNode.attributedText = NSAttributedString( - string: countText, - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: appearance.subtleInk, - ] - ) - countNode.style.flexShrink = 1.0 - - node.layoutSpecBlock = { _, _ in - let spacer = ASLayoutSpec() - spacer.style.flexGrow = 1.0 - let stack = ASStackLayoutSpec( - direction: .horizontal, - spacing: 12, - justifyContent: .start, - alignItems: .center, - children: [titleNode, spacer, countNode] - ) - return ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 18, left: 16, bottom: 14, right: 16), - child: stack - ) - } - return node - } - - private func makeReplyFooterCellNode( - for item: FireTopicDetailRuntimeItem, - configuration _: FireTopicDetailRuntimeConfiguration, - appearance: FireAppearanceSnapshot - ) -> ASCellNode { - let node = ASCellNode() - node.automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: node) - - let state = (item.contentToken.base as? String) - .flatMap(FireTopicDetailRuntimeReplyFooterState.fromContentToken(_:)) - ?? .none - - let childElement: ASLayoutElement? - switch state { - case .none: - childElement = nil - case .loadMoreAvailable: - let buttonNode = ASButtonNode() - buttonNode.setImage(UIImage(systemName: "arrow.down.circle"), for: .normal) - buttonNode.setTitle( - "加载更多回复", - with: UIFont.preferredFont(forTextStyle: .subheadline), - with: FireTopicDetailCellColors.accent, - for: .normal - ) - buttonNode.contentSpacing = 6 - buttonNode.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) - buttonNode.isEnabled = true - buttonNode.addTarget(self, action: #selector(handleLoadMoreReplies), forControlEvents: .touchUpInside) - buttonNode.fireBindPressBounce(.button) - childElement = buttonNode - case .emptyPrompt: - let label = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(label) - label.attributedText = NSAttributedString( - string: "还没有回复,发表你的看法吧", - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: appearance.subtleInk, - ] - ) - childElement = label - case .endReached: - let label = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(label) - label.attributedText = NSAttributedString( - string: "---- 到底了 ----", - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: appearance.tertiaryInk, - ] - ) - childElement = label - case .loadFailed(_): - let buttonNode = ASButtonNode() - buttonNode.setImage(UIImage(systemName: "arrow.clockwise.circle"), for: .normal) - buttonNode.setTitle( - "加载更多回复失败,点击重试", - with: UIFont.preferredFont(forTextStyle: .subheadline), - with: FireTopicDetailCellColors.accent, - for: .normal - ) - buttonNode.contentSpacing = 6 - buttonNode.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) - buttonNode.isEnabled = true - buttonNode.addTarget(self, action: #selector(handleLoadMoreReplies), forControlEvents: .touchUpInside) - buttonNode.fireBindPressBounce(.button) - childElement = buttonNode - case .loadingFooter: - let label = ASTextNode() - label.attributedText = NSAttributedString( - string: "正在加载更多回复...", - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: appearance.subtleInk, - ] - ) - let indicator = ASDisplayNode(viewBlock: { - let view = UIActivityIndicatorView(style: .medium) - view.startAnimating() - return view - }) - indicator.style.preferredSize = CGSize(width: 20, height: 20) - childElement = ASStackLayoutSpec( - direction: .horizontal, - spacing: 8, - justifyContent: .center, - alignItems: .center, - children: [indicator, label] - ) - } - - node.layoutSpecBlock = { _, constrainedSize in - let height = max(constrainedSize.min.height, 44) - let child = childElement ?? ASLayoutSpec() - let sized = ASStackLayoutSpec( - direction: .vertical, - spacing: 0, - justifyContent: .center, - alignItems: .center, - children: [child] - ) - sized.style.preferredSize = CGSize(width: constrainedSize.max.width, height: height) - return ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16), - child: sized - ) - } - return node - } - - private func makeBodyStateCellNode( - configuration: FireTopicDetailRuntimeConfiguration, - appearance: FireAppearanceSnapshot - ) -> ASCellNode { - let node = ASCellNode() - node.automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: node) - - let stackChildren: [ASLayoutElement] - if configuration.isLoadingTopic || configuration.isWaitingForPostRender { - let label = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(label) - label.attributedText = NSAttributedString( - string: "加载中...", - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .caption1), - .foregroundColor: appearance.subtleInk, - ] - ) - stackChildren = [label] - } else { - let messageNode = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(messageNode) - messageNode.attributedText = NSAttributedString( - string: configuration.detailError ?? "加载帖子", - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .caption1), - .foregroundColor: appearance.subtleInk, - ] - ) - messageNode.maximumNumberOfLines = 0 - - let buttonNode = ASButtonNode() - buttonNode.setTitle( - configuration.detailError == nil ? "加载" : "重试", - with: UIFont.preferredFont(forTextStyle: .subheadline), - with: FireTopicDetailCellColors.accent, - for: .normal - ) - buttonNode.addTarget(self, action: #selector(handleLoadTopicDetail), forControlEvents: .touchUpInside) - buttonNode.fireBindPressBounce(.button) - - stackChildren = [messageNode, buttonNode] - } - - node.layoutSpecBlock = { _, constrainedSize in - let height = max(constrainedSize.min.height, 96) - let stack = ASStackLayoutSpec( - direction: .vertical, - spacing: 8, - justifyContent: .center, - alignItems: .center, - children: stackChildren - ) - let sized = ASStackLayoutSpec( - direction: .vertical, - spacing: 8, - justifyContent: .center, - alignItems: .center, - children: [stack] - ) - sized.style.preferredSize = CGSize(width: constrainedSize.max.width, height: height) - return ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16), - child: sized - ) - } - return node - } - - private func makeTextCellNode( - for item: FireTopicDetailRuntimeItem, - configuration: FireTopicDetailRuntimeConfiguration, - appearance: FireAppearanceSnapshot - ) -> ASCellNode { - let node = ASCellNode() - node.automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: node) - - let titleNode = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(titleNode) - titleNode.maximumNumberOfLines = 0 - let bodyNode = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(bodyNode) - bodyNode.maximumNumberOfLines = 0 - - switch item.kind { - case .header: - let status = configuration.row.statusLabels.joined(separator: " · ") - titleNode.attributedText = NSAttributedString( - string: configuration.displayedTopicTitle, - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .headline), - .foregroundColor: appearance.ink, - ] - ) - bodyNode.attributedText = status.isEmpty ? nil : NSAttributedString( - string: status, - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: appearance.subtleInk, - ] - ) - case .aiSummary: - let title = "AI 摘要" - let body: String - if let summary = configuration.topicAiSummary { - body = configuration.isTopicAiSummaryExpanded - ? summary.summarizedText - : "点击展开" - } else { - body = "" - } - titleNode.attributedText = NSAttributedString( - string: title, - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .headline), - .foregroundColor: appearance.ink, - ] - ) - bodyNode.attributedText = NSAttributedString( - string: body, - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: appearance.subtleInk, - ] - ) - case .notice: - let statusMessage = item.statusMessage - let title = statusMessage?.title?.trimmingCharacters(in: .whitespacesAndNewlines) - let trimmedTitle = (title?.isEmpty == false) ? title : nil - let messageColor = statusMessage?.emphasizesError == true ? UIColor.systemRed : appearance.subtleInk - bodyNode.attributedText = NSAttributedString( - string: statusMessage?.message ?? "正在显示缓存内容", - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: messageColor, - ] - ) - if let trimmedTitle { - titleNode.attributedText = NSAttributedString( - string: trimmedTitle, - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .headline), - .foregroundColor: statusMessage?.emphasizesError == true ? UIColor.systemRed : appearance.ink, - ] - ) - } - default: - break - } - - var children: [ASLayoutElement] = [ - titleNode.attributedText != nil ? titleNode : nil, - bodyNode.attributedText != nil ? bodyNode : nil, - ].compactMap { $0 } - - if item.kind == .notice, item.statusMessage?.retryable == true { - let buttonNode = ASButtonNode() - buttonNode.setTitle( - "重试", - with: UIFont.preferredFont(forTextStyle: .subheadline), - with: FireTopicDetailCellColors.accent, - for: .normal - ) - buttonNode.addTarget(self, action: #selector(handleLoadTopicDetail), forControlEvents: .touchUpInside) - buttonNode.fireBindPressBounce(.button) - children.append(buttonNode) - } - - node.layoutSpecBlock = { _, _ in - let stack = ASStackLayoutSpec( - direction: .vertical, - spacing: 8, - justifyContent: .start, - alignItems: .stretch, - children: children - ) - return ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), - child: stack - ) - } - return node - } - - private func makeMissingPostCellNode(appearance: FireAppearanceSnapshot) -> ASCellNode { - let node = ASCellNode() - node.automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: node) - - let textNode = ASTextNode() - FireAppearanceTexture.configureChromeTextNode(textNode) - textNode.attributedText = NSAttributedString( - string: "帖子内容加载中...", - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: appearance.subtleInk, - ] - ) - - node.layoutSpecBlock = { _, _ in - ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), - child: textNode - ) - } - return node - } } diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCells.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCells.swift deleted file mode 100644 index 6cec1bd7..00000000 --- a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedCells.swift +++ /dev/null @@ -1,976 +0,0 @@ -import AsyncDisplayKit -import UIKit - -enum FireTopicDetailCellColors { - static var accent: UIColor { FireTheme.uiAccent } - static var warning: UIColor { FireTheme.uiWarning } - static var tagChipBackground: UIColor { FireTheme.uiTagChipBackground } - static var tagChipForeground: UIColor { FireTheme.uiTagChipForeground } - static let privateMessageForeground = UIColor.systemIndigo - - static func categoryChipBackground(accent: UIColor) -> UIColor { - FireTheme.uiCategoryChipBackground(accent: accent) - } -} - -final class FireTopicDetailTextCell: UICollectionViewCell { - static let reuseID = "FireTopicDetailTextCell" - - private let titleLabel = UILabel() - private let bodyLabel = UILabel() - private let stackView = UIStackView() - - override init(frame: CGRect) { - super.init(frame: frame) - setup() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setup() { - contentView.backgroundColor = FireTheme.uiCanvas - stackView.axis = .vertical - stackView.alignment = .fill - stackView.spacing = 6 - stackView.translatesAutoresizingMaskIntoConstraints = false - - titleLabel.font = .preferredFont(forTextStyle: .headline) - titleLabel.adjustsFontForContentSizeCategory = true - titleLabel.numberOfLines = 0 - titleLabel.textColor = .label - - bodyLabel.font = .preferredFont(forTextStyle: .subheadline) - bodyLabel.adjustsFontForContentSizeCategory = true - bodyLabel.numberOfLines = 0 - bodyLabel.textColor = .secondaryLabel - - stackView.addArrangedSubview(titleLabel) - stackView.addArrangedSubview(bodyLabel) - contentView.addSubview(stackView) - - NSLayoutConstraint.activate([ - stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), - stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), - stackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10), - stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10), - ]) - } - - func configure(title: String?, body: String?) { - titleLabel.text = title - titleLabel.isHidden = (title ?? "").isEmpty - bodyLabel.text = body - bodyLabel.isHidden = (body ?? "").isEmpty - accessibilityLabel = [title, body] - .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - .joined(separator: "\n") - } - - override func prepareForReuse() { - super.prepareForReuse() - configure(title: nil, body: nil) - } -} - -final class FireTopicDetailStatsCell: UICollectionViewCell { - static let reuseID = "FireTopicDetailStatsCell" - - private let dividerView = UIView() - private let stackView = UIStackView() - private let replyStat = FireTopicDetailStatView() - private let viewStat = FireTopicDetailStatView() - private let interactionStat = FireTopicDetailStatView() - - override init(frame: CGRect) { - super.init(frame: frame) - setup() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setup() { - contentView.backgroundColor = FireTheme.uiCanvas - dividerView.backgroundColor = .separator - dividerView.translatesAutoresizingMaskIntoConstraints = false - - stackView.axis = .horizontal - stackView.alignment = .center - stackView.distribution = .fillEqually - stackView.spacing = 20 - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.addArrangedSubview(replyStat) - stackView.addArrangedSubview(viewStat) - stackView.addArrangedSubview(interactionStat) - - contentView.addSubview(dividerView) - contentView.addSubview(stackView) - - NSLayoutConstraint.activate([ - dividerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), - dividerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), - dividerView.topAnchor.constraint(equalTo: contentView.topAnchor), - dividerView.heightAnchor.constraint(equalToConstant: 0.5), - - stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), - stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), - stackView.topAnchor.constraint(equalTo: dividerView.bottomAnchor, constant: 12), - stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8), - ]) - } - - func configure(replyCount: UInt32, viewCount: UInt32, interactionCount: UInt32?) { - replyStat.configure(value: "\(replyCount)", label: "回复") - viewStat.configure(value: "\(viewCount)", label: "浏览") - interactionStat.configure(value: interactionCount.map(String.init) ?? "...", label: "互动") - accessibilityLabel = "\(replyCount) 回复,\(viewCount) 浏览" - } -} - -private final class FireTopicDetailStatView: UIView { - private let valueLabel = UILabel() - private let titleLabel = UILabel() - private let stackView = UIStackView() - - override init(frame: CGRect) { - super.init(frame: frame) - setup() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setup() { - valueLabel.font = UIFontMetrics(forTextStyle: .subheadline).scaledFont( - for: UIFont.monospacedDigitSystemFont( - ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, - weight: .semibold - ) - ) - valueLabel.adjustsFontForContentSizeCategory = true - valueLabel.textColor = .label - valueLabel.textAlignment = .center - - titleLabel.font = .preferredFont(forTextStyle: .caption2) - titleLabel.adjustsFontForContentSizeCategory = true - titleLabel.textColor = .secondaryLabel - titleLabel.textAlignment = .center - - stackView.axis = .vertical - stackView.alignment = .fill - stackView.spacing = 2 - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.addArrangedSubview(valueLabel) - stackView.addArrangedSubview(titleLabel) - addSubview(stackView) - - NSLayoutConstraint.activate([ - stackView.leadingAnchor.constraint(equalTo: leadingAnchor), - stackView.trailingAnchor.constraint(equalTo: trailingAnchor), - stackView.topAnchor.constraint(equalTo: topAnchor), - stackView.bottomAnchor.constraint(equalTo: bottomAnchor), - ]) - } - - func configure(value: String, label: String) { - valueLabel.text = value - titleLabel.text = label - } -} - -final class FireTopicDetailRepliesHeaderCell: UICollectionViewCell { - static let reuseID = "FireTopicDetailRepliesHeaderCell" - - private let titleLabel = UILabel() - private let countLabel = UILabel() - private let stackView = UIStackView() - - override init(frame: CGRect) { - super.init(frame: frame) - setup() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setup() { - contentView.backgroundColor = FireTheme.uiCanvas - - titleLabel.text = "回复" - titleLabel.font = .preferredFont(forTextStyle: .headline) - titleLabel.adjustsFontForContentSizeCategory = true - titleLabel.textColor = .label - - countLabel.font = .preferredFont(forTextStyle: .subheadline) - countLabel.adjustsFontForContentSizeCategory = true - countLabel.textColor = .secondaryLabel - countLabel.textAlignment = .right - countLabel.setContentCompressionResistancePriority(.required, for: .horizontal) - - stackView.axis = .horizontal - stackView.alignment = .center - stackView.spacing = 12 - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.addArrangedSubview(titleLabel) - stackView.addArrangedSubview(countLabel) - contentView.addSubview(stackView) - - NSLayoutConstraint.activate([ - stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), - stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), - stackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 18), - stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -14), - ]) - } - - func configure(loadedReplyCount: Int, totalReplyCount: Int, displayedFloorCount: Int, hasDetail: Bool) { - if hasDetail { - if loadedReplyCount < totalReplyCount { - countLabel.text = "已加载 \(loadedReplyCount) / \(totalReplyCount) 条" - } else { - countLabel.text = "\(totalReplyCount) 条 · \(displayedFloorCount) 楼" - } - } else { - countLabel.text = nil - } - accessibilityLabel = [titleLabel.text, countLabel.text] - .compactMap { $0 } - .joined(separator: ",") - } - - override func prepareForReuse() { - super.prepareForReuse() - configure(loadedReplyCount: 0, totalReplyCount: 0, displayedFloorCount: 0, hasDetail: false) - } -} - -final class FireTopicDetailReplyFooterCell: UICollectionViewCell { - static let reuseID = "FireTopicDetailReplyFooterCell" - - private let label = UILabel() - private let button = UIButton(type: .system) - private let loadingStack = UIStackView() - private let activityIndicator = UIActivityIndicatorView(style: .medium) - private let loadingLabel = UILabel() - private var action: (() -> Void)? - - override init(frame: CGRect) { - super.init(frame: frame) - setup() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setup() { - contentView.backgroundColor = FireTheme.uiCanvas - - label.font = .preferredFont(forTextStyle: .subheadline) - label.adjustsFontForContentSizeCategory = true - label.textColor = .secondaryLabel - label.textAlignment = .center - label.translatesAutoresizingMaskIntoConstraints = false - - var buttonConfiguration = UIButton.Configuration.plain() - buttonConfiguration.image = UIImage(systemName: "arrow.down.circle") - buttonConfiguration.imagePadding = 6 - buttonConfiguration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16) - button.configuration = buttonConfiguration - button.tintColor = FireTopicDetailCellColors.accent - button.titleLabel?.font = UIFontMetrics(forTextStyle: .subheadline).scaledFont( - for: UIFont.systemFont( - ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, - weight: .semibold - ) - ) - button.titleLabel?.adjustsFontForContentSizeCategory = true - button.translatesAutoresizingMaskIntoConstraints = false - button.addAction(UIAction { [weak self] _ in - self?.action?() - }, for: .touchUpInside) - - loadingLabel.text = "正在加载更多回复..." - loadingLabel.font = .preferredFont(forTextStyle: .subheadline) - loadingLabel.adjustsFontForContentSizeCategory = true - loadingLabel.textColor = .secondaryLabel - loadingStack.axis = .horizontal - loadingStack.alignment = .center - loadingStack.spacing = 8 - loadingStack.translatesAutoresizingMaskIntoConstraints = false - loadingStack.addArrangedSubview(activityIndicator) - loadingStack.addArrangedSubview(loadingLabel) - - contentView.addSubview(label) - contentView.addSubview(button) - contentView.addSubview(loadingStack) - - NSLayoutConstraint.activate([ - label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), - label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), - label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), - - button.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor, constant: 16), - button.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor, constant: -16), - button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), - button.heightAnchor.constraint(greaterThanOrEqualToConstant: 36), - - loadingStack.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor, constant: 16), - loadingStack.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor, constant: -16), - loadingStack.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - loadingStack.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), - ]) - - configure(state: .none, action: nil) - } - - func configure(state: FireTopicDetailRuntimeReplyFooterState, action: (() -> Void)?) { - self.action = action - label.isHidden = true - button.isHidden = true - loadingStack.isHidden = true - activityIndicator.stopAnimating() - accessibilityTraits = [] - - switch state { - case .none: - accessibilityLabel = nil - case .loadMoreAvailable: - var configuration = button.configuration - configuration?.image = UIImage(systemName: "arrow.down.circle") - configuration?.title = "加载更多回复" - button.configuration = configuration - button.isHidden = false - button.isEnabled = action != nil - accessibilityLabel = "加载更多回复" - accessibilityTraits = [.button] - case .emptyPrompt: - label.text = "还没有回复,发表你的看法吧" - label.isHidden = false - accessibilityLabel = label.text - case .endReached: - label.text = "---- 到底了 ----" - label.isHidden = false - accessibilityLabel = label.text - case .loadFailed(_): - var configuration = button.configuration - configuration?.image = UIImage(systemName: "arrow.clockwise.circle") - configuration?.title = "加载更多回复失败,点击重试" - button.configuration = configuration - button.isHidden = false - button.isEnabled = action != nil - accessibilityLabel = "加载更多回复失败,点击重试" - accessibilityTraits = [.button] - case .loadingFooter: - loadingStack.isHidden = false - activityIndicator.startAnimating() - accessibilityLabel = loadingLabel.text - } - } - - override func prepareForReuse() { - super.prepareForReuse() - configure(state: .none, action: nil) - } -} - -final class FireTopicDetailBodyStateCell: UICollectionViewCell { - static let reuseID = "FireTopicDetailBodyStateCell" - - private let activityIndicator = UIActivityIndicatorView(style: .medium) - private let messageLabel = UILabel() - private let button = UIButton(type: .system) - private let stackView = UIStackView() - private var action: (() -> Void)? - - override init(frame: CGRect) { - super.init(frame: frame) - setup() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setup() { - contentView.backgroundColor = FireTheme.uiCanvas - - messageLabel.font = .preferredFont(forTextStyle: .caption1) - messageLabel.adjustsFontForContentSizeCategory = true - messageLabel.textColor = .secondaryLabel - messageLabel.numberOfLines = 0 - messageLabel.textAlignment = .center - - button.setTitleColor(FireTopicDetailCellColors.accent, for: .normal) - button.titleLabel?.font = .preferredFont(forTextStyle: .subheadline) - button.titleLabel?.adjustsFontForContentSizeCategory = true - button.addAction(UIAction { [weak self] _ in - self?.action?() - }, for: .touchUpInside) - - stackView.axis = .vertical - stackView.alignment = .center - stackView.spacing = 8 - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.addArrangedSubview(activityIndicator) - stackView.addArrangedSubview(messageLabel) - stackView.addArrangedSubview(button) - contentView.addSubview(stackView) - - NSLayoutConstraint.activate([ - stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), - stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), - stackView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), - ]) - - configure(isLoading: false, errorMessage: nil, action: nil) - } - - func configure(isLoading: Bool, errorMessage: String?, action: (() -> Void)?) { - self.action = action - if isLoading { - activityIndicator.isHidden = false - activityIndicator.startAnimating() - messageLabel.text = "加载中..." - button.isHidden = true - button.setTitle(nil, for: .normal) - } else { - activityIndicator.stopAnimating() - activityIndicator.isHidden = true - messageLabel.text = errorMessage ?? "加载帖子" - button.setTitle(errorMessage == nil ? "加载" : "重试", for: .normal) - button.isHidden = action == nil - } - accessibilityLabel = [messageLabel.text, button.title(for: .normal)] - .compactMap { $0 } - .joined(separator: ",") - } - - override func prepareForReuse() { - super.prepareForReuse() - configure(isLoading: false, errorMessage: nil, action: nil) - } -} - -final class FireTopicDetailTopicVoteCell: UICollectionViewCell { - static let reuseID = "FireTopicDetailTopicVoteCell" - - private let containerView = UIView() - private let titleLabel = UILabel() - private let statusLabel = UILabel() - private let toggleButton = UIButton(type: .system) - private let votersButton = UIButton(type: .system) - private let headerStack = UIStackView() - private let buttonStack = UIStackView() - private let rootStack = UIStackView() - private var toggleAction: (() -> Void)? - private var votersAction: (() -> Void)? - - override init(frame: CGRect) { - super.init(frame: frame) - setup() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setup() { - contentView.backgroundColor = FireTheme.uiCanvas - - containerView.backgroundColor = .secondarySystemBackground - containerView.layer.cornerRadius = 8 - containerView.translatesAutoresizingMaskIntoConstraints = false - - titleLabel.font = UIFontMetrics(forTextStyle: .subheadline).scaledFont( - for: UIFont.systemFont( - ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, - weight: .semibold - ) - ) - titleLabel.adjustsFontForContentSizeCategory = true - titleLabel.textColor = FireTopicDetailCellColors.accent - - statusLabel.font = UIFontMetrics(forTextStyle: .caption1).scaledFont( - for: UIFont.systemFont( - ofSize: UIFont.preferredFont(forTextStyle: .caption1).pointSize, - weight: .semibold - ) - ) - statusLabel.adjustsFontForContentSizeCategory = true - statusLabel.textColor = .systemGreen - statusLabel.setContentHuggingPriority(.required, for: .horizontal) - - headerStack.axis = .horizontal - headerStack.alignment = .center - headerStack.spacing = 10 - headerStack.addArrangedSubview(titleLabel) - headerStack.addArrangedSubview(UIView()) - headerStack.addArrangedSubview(statusLabel) - - configureToggleButtonStyle() - configureVotersButtonStyle() - - toggleButton.addAction(UIAction { [weak self] _ in - self?.toggleAction?() - }, for: .touchUpInside) - votersButton.addAction(UIAction { [weak self] _ in - self?.votersAction?() - }, for: .touchUpInside) - - buttonStack.axis = .horizontal - buttonStack.alignment = .center - buttonStack.spacing = 10 - buttonStack.addArrangedSubview(toggleButton) - buttonStack.addArrangedSubview(votersButton) - buttonStack.addArrangedSubview(UIView()) - - rootStack.axis = .vertical - rootStack.alignment = .fill - rootStack.spacing = 10 - rootStack.translatesAutoresizingMaskIntoConstraints = false - rootStack.addArrangedSubview(headerStack) - rootStack.addArrangedSubview(buttonStack) - - contentView.addSubview(containerView) - containerView.addSubview(rootStack) - - NSLayoutConstraint.activate([ - containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), - containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), - containerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), - containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4), - - rootStack.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 14), - rootStack.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -14), - rootStack.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 14), - rootStack.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -14), - ]) - } - - private func configureToggleButtonStyle() { - var configuration = UIButton.Configuration.filled() - configuration.cornerStyle = .capsule - configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14) - toggleButton.configuration = configuration - toggleButton.titleLabel?.adjustsFontForContentSizeCategory = true - } - - private func configureVotersButtonStyle() { - var configuration = UIButton.Configuration.plain() - configuration.image = UIImage(systemName: "person.3") - configuration.imagePadding = 6 - configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8) - votersButton.configuration = configuration - votersButton.tintColor = FireTopicDetailCellColors.accent - votersButton.titleLabel?.adjustsFontForContentSizeCategory = true - } - - func configure( - detail: TopicDetailState, - canWriteInteractions: Bool, - onToggle: (() -> Void)?, - onShowVoters: (() -> Void)? - ) { - titleLabel.text = "\(detail.voteCount) 票" - statusLabel.text = detail.userVoted ? "你已投票" : nil - statusLabel.isHidden = !detail.userVoted - - var toggleConfiguration = toggleButton.configuration - toggleConfiguration?.title = detail.userVoted ? "取消投票" : "投一票" - toggleConfiguration?.baseBackgroundColor = detail.userVoted - ? .tertiarySystemFill - : FireTopicDetailCellColors.accent - toggleConfiguration?.baseForegroundColor = detail.userVoted ? .label : .white - toggleButton.configuration = toggleConfiguration - toggleButton.isEnabled = canWriteInteractions - - var votersConfiguration = votersButton.configuration - votersConfiguration?.title = "查看投票用户" - votersButton.configuration = votersConfiguration - - toggleAction = onToggle - votersAction = onShowVoters - accessibilityLabel = "\(detail.voteCount) 票" + (detail.userVoted ? ",你已投票" : "") - } - - override func prepareForReuse() { - super.prepareForReuse() - toggleAction = nil - votersAction = nil - statusLabel.text = nil - statusLabel.isHidden = true - } -} - -final class FireTopicDetailHeaderCellNode: ASCellNode { - private let titleNode = ASTextNode() - private let chipNodes: [ASButtonNode] - - init( - configuration: FireTopicDetailRuntimeConfiguration, - appearance: FireAppearanceSnapshot = FireAppearanceEnvironment.snapshot(traits: .current) - ) { - var chips: [ASButtonNode] = [] - let titleInk = appearance.ink - - titleNode.attributedText = NSAttributedString( - string: configuration.displayedTopicTitle, - attributes: [ - .font: FireTopicDetailRuntimeTypography.scaledFont(textStyle: .title3, weight: .bold), - .foregroundColor: titleInk, - ] - ) - titleNode.maximumNumberOfLines = 0 - titleNode.style.flexShrink = 1.0 - // Avoid Texture opaque default fill painting a black title strip on light canvas. - titleNode.isOpaque = false - titleNode.backgroundColor = .clear - titleNode.displaysAsynchronously = false - - if configuration.isPrivateMessageThread { - chips.append(Self.makeChip( - title: "私信", - foregroundColor: FireTopicDetailCellColors.accent, - backgroundColor: FireTopicDetailCellColors.accent.withAlphaComponent(0.12) - )) - - for participant in configuration.displayedParticipants { - let label = (participant.name ?? "").ifEmpty(participant.username ?? "用户 \(participant.userId)") - chips.append(Self.makeChip( - title: "@\(label)", - foregroundColor: FireTopicDetailCellColors.privateMessageForeground, - backgroundColor: FireTopicDetailCellColors.privateMessageForeground.withAlphaComponent(0.12) - )) - } - } else { - if let category = configuration.displayedCategory { - let accent = UIColor(fireHex: category.colorHex) ?? FireTopicDetailCellColors.accent - chips.append(Self.makeChip( - title: category.displayName, - foregroundColor: accent, - backgroundColor: FireTopicDetailCellColors.categoryChipBackground(accent: accent), - action: configuration.viewModel == nil ? nil : { - configuration.onOpenCategory(category) - } - )) - } - - for tagName in configuration.displayedTagNames { - chips.append(Self.makeChip( - title: "#\(tagName)", - foregroundColor: FireTopicDetailCellColors.tagChipForeground, - backgroundColor: FireTopicDetailCellColors.tagChipBackground, - horizontalInset: 6, - verticalInset: 3, - action: configuration.viewModel == nil ? nil : { - configuration.onOpenTag(tagName) - } - )) - } - - for label in configuration.row.statusLabels { - chips.append(Self.makeChip( - title: label, - foregroundColor: FireTopicDetailCellColors.accent, - backgroundColor: FireTopicDetailCellColors.accent.withAlphaComponent(0.12) - )) - } - } - - chipNodes = chips - super.init() - automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: self) - isAccessibilityElement = true - accessibilityLabel = [configuration.displayedTopicTitle, chips.compactMap(\.accessibilityLabel).joined(separator: ", ")] - .filter { !$0.isEmpty } - .joined(separator: "\n") - } - - override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { - var children: [ASLayoutElement] = [titleNode] - if !chipNodes.isEmpty { - let chipStack = ASStackLayoutSpec( - direction: .horizontal, - spacing: 6, - justifyContent: .start, - alignItems: .start, - children: chipNodes - ) - chipStack.flexWrap = .wrap - chipStack.alignContent = .start - chipStack.lineSpacing = 6 - children.append(chipStack) - } - - let stack = ASStackLayoutSpec( - direction: .vertical, - spacing: 8, - justifyContent: .start, - alignItems: .stretch, - children: children - ) - return ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 16, left: 16, bottom: 0, right: 16), - child: stack - ) - } - - private static func makeChip( - title: String, - foregroundColor: UIColor, - backgroundColor: UIColor, - horizontalInset: CGFloat = 8, - verticalInset: CGFloat = 4, - action: (() -> Void)? = nil - ) -> ASButtonNode { - let node = FireTopicDetailChipButtonNode(action: action) - node.setAttributedTitle( - NSAttributedString( - string: title, - attributes: [ - .font: FireTopicDetailRuntimeTypography.scaledFont(textStyle: .caption2, weight: .medium), - .foregroundColor: foregroundColor, - ] - ), - for: .normal - ) - node.contentEdgeInsets = UIEdgeInsets( - top: verticalInset, - left: horizontalInset, - bottom: verticalInset, - right: horizontalInset - ) - node.backgroundColor = backgroundColor - node.cornerRadius = 12 - node.clipsToBounds = true - node.isEnabled = action != nil - node.accessibilityLabel = title - if action != nil { - node.accessibilityTraits.insert(.button) - } - return node - } -} - -final class FireTopicDetailAISummaryCellNode: ASCellNode { - private let backgroundNode = ASDisplayNode() - private let headerButtonNode: FireTopicDetailChipButtonNode - private let iconNode = ASImageNode() - private let titleNode = ASTextNode() - private let statusNode = ASTextNode() - private let chevronNode = ASImageNode() - private let bodyNode = ASTextNode() - private let metadataNode = ASTextNode() - private let isExpanded: Bool - - init( - configuration: FireTopicDetailRuntimeConfiguration, - appearance: FireAppearanceSnapshot = FireAppearanceEnvironment.snapshot(traits: .current) - ) { - let summary = configuration.topicAiSummary - isExpanded = configuration.isTopicAiSummaryExpanded && summary != nil - let primaryInk = appearance.ink - let secondaryInk = appearance.subtleInk - let tertiaryInk = appearance.tertiaryInk - - backgroundNode.backgroundColor = .secondarySystemBackground - backgroundNode.cornerRadius = 8 - backgroundNode.clipsToBounds = true - - iconNode.image = UIImage(systemName: "sparkles")?.withTintColor( - FireTopicDetailCellColors.accent, - renderingMode: .alwaysOriginal - ) - iconNode.style.preferredSize = CGSize(width: 17, height: 17) - - titleNode.attributedText = NSAttributedString( - string: "AI 摘要", - attributes: [ - .font: FireTopicDetailRuntimeTypography.scaledFont(textStyle: .subheadline, weight: .semibold), - .foregroundColor: primaryInk, - ] - ) - - if summary?.outdated == true { - statusNode.attributedText = NSAttributedString( - string: "有新回复", - attributes: [ - .font: FireTopicDetailRuntimeTypography.scaledFont(textStyle: .caption2, weight: .semibold), - .foregroundColor: FireTopicDetailCellColors.warning, - ] - ) - statusNode.backgroundColor = FireTopicDetailCellColors.warning.withAlphaComponent(0.12) - statusNode.cornerRadius = 10 - statusNode.textContainerInset = UIEdgeInsets(top: 3, left: 8, bottom: 3, right: 8) - } else { - statusNode.isHidden = true - } - - let chevronName = isExpanded ? "chevron.up" : "chevron.down" - chevronNode.image = UIImage(systemName: chevronName)?.withTintColor( - tertiaryInk, - renderingMode: .alwaysOriginal - ) - chevronNode.style.preferredSize = CGSize(width: 14, height: 14) - - if let summary, isExpanded { - bodyNode.attributedText = NSAttributedString( - string: summary.summarizedText, - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: primaryInk, - ] - ) - bodyNode.maximumNumberOfLines = 0 - bodyNode.style.flexShrink = 1.0 - - let metadata = Self.metadata(for: summary) - if !metadata.isEmpty { - metadataNode.attributedText = NSAttributedString( - string: metadata.joined(separator: " · "), - attributes: [ - .font: UIFont.preferredFont(forTextStyle: .caption2), - .foregroundColor: secondaryInk, - ] - ) - metadataNode.maximumNumberOfLines = 0 - } else { - metadataNode.isHidden = true - } - } else { - bodyNode.isHidden = true - metadataNode.isHidden = true - } - - headerButtonNode = FireTopicDetailChipButtonNode(action: configuration.onToggleTopicAiSummaryExpanded) - headerButtonNode.accessibilityLabel = isExpanded ? "收起 AI 摘要" : "展开 AI 摘要" - - super.init() - automaticallyManagesSubnodes = true - FireAppearanceTexture.applySnapshot(appearance, to: self) - FireAppearanceTexture.configureChromeTextNode(titleNode) - FireAppearanceTexture.configureChromeTextNode(statusNode) - FireAppearanceTexture.configureChromeTextNode(bodyNode) - FireAppearanceTexture.configureChromeTextNode(metadataNode) - isAccessibilityElement = false - accessibilityElements = [headerButtonNode, bodyNode, metadataNode].filter { !$0.isHidden } - headerButtonNode.accessibilityValue = [ - statusNode.isHidden ? nil : "有新回复", - isExpanded ? bodyNode.attributedText?.string : "已折叠", - isExpanded ? metadataNode.attributedText?.string : nil, - ] - .compactMap { $0 } - .filter { !$0.isEmpty } - .joined(separator: ",") - } - - override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { - let headerSpacer = ASLayoutSpec() - headerSpacer.style.flexGrow = 1.0 - let headerChildren: [ASLayoutElement] = [ - iconNode, - titleNode, - headerSpacer, - statusNode, - chevronNode, - ].filter { element in - guard let node = element as? ASDisplayNode else { return true } - return !node.isHidden - } - let headerContent = ASStackLayoutSpec( - direction: .horizontal, - spacing: 8, - justifyContent: .start, - alignItems: .center, - children: headerChildren - ) - let headerButtonSpec = ASBackgroundLayoutSpec( - child: headerContent, - background: headerButtonNode - ) - headerButtonNode.style.flexGrow = 1.0 - headerButtonNode.style.alignSelf = .stretch - - var contentChildren: [ASLayoutElement] = [headerButtonSpec] - if !bodyNode.isHidden { - contentChildren.append(bodyNode) - } - if !metadataNode.isHidden { - contentChildren.append(metadataNode) - } - - let contentStack = ASStackLayoutSpec( - direction: .vertical, - spacing: isExpanded ? 10 : 0, - justifyContent: .start, - alignItems: .stretch, - children: contentChildren - ) - let paddedContent = ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 12, left: 14, bottom: 12, right: 14), - child: contentStack - ) - let card = ASBackgroundLayoutSpec(child: paddedContent, background: backgroundNode) - return ASInsetLayoutSpec( - insets: UIEdgeInsets(top: 4, left: 16, bottom: 10, right: 16), - child: card - ) - } - - private static func metadata(for summary: TopicAiSummaryState) -> [String] { - var metadata: [String] = [] - if let updatedAt = FireTopicPresentation.formatTimestamp(summary.updatedAt) { - metadata.append("更新 \(updatedAt)") - } - if summary.outdated, summary.newPostsSinceSummary > 0 { - metadata.append("\(summary.newPostsSinceSummary) 条新回复") - } - if let algorithm = summary.algorithm?.trimmingCharacters(in: .whitespacesAndNewlines), - !algorithm.isEmpty { - metadata.append(algorithm) - } - if summary.canRegenerate { - metadata.append("可重新生成") - } - return metadata - } -} - -private final class FireTopicDetailChipButtonNode: ASButtonNode { - private let action: (() -> Void)? - - init(action: (() -> Void)?) { - self.action = action - super.init() - addTarget(self, action: #selector(handleTap), forControlEvents: .touchUpInside) - } - - @objc private func handleTap() { - action?() - } -} - -private enum FireTopicDetailRuntimeTypography { - static func scaledFont(textStyle: UIFont.TextStyle, weight: UIFont.Weight) -> UIFont { - let preferred = UIFont.preferredFont(forTextStyle: textStyle) - return UIFontMetrics(forTextStyle: textStyle).scaledFont( - for: UIFont.systemFont(ofSize: preferred.pointSize, weight: weight) - ) - } -} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Appearance.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Appearance.swift new file mode 100644 index 00000000..41042c80 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Appearance.swift @@ -0,0 +1,91 @@ +import AsyncDisplayKit +import UIKit + +@MainActor +extension FireTopicDetailFeedController { + func layoutContentWidth(proposedWidth: CGFloat? = nil) -> CGFloat { + let adjustedBoundsWidth = collectionNode.view.bounds.width + - collectionNode.view.adjustedContentInset.left + - collectionNode.view.adjustedContentInset.right + if adjustedBoundsWidth > 0 { + return adjustedBoundsWidth + } + return max(proposedWidth ?? collectionNode.view.bounds.width, 1) + } + + /// Trait collection used to bake Texture text colors. Prefer the loaded + /// collection view so window `overrideUserInterfaceStyle` is respected. + func currentColorTraits() -> UITraitCollection { + if collectionNode.isNodeLoaded { + return FireAppearanceEnvironment.traits(for: collectionNode.view) + } + return FireAppearanceEnvironment.traits() + } + + func currentAppearanceSnapshot() -> FireAppearanceSnapshot { + if collectionNode.isNodeLoaded { + return FireAppearanceEnvironment.snapshot(for: collectionNode.view) + } + return FireAppearanceEnvironment.snapshot() + } + + /// Re-assert collection + scroll-view canvas from the current snapshot. + /// Must run after theme flips **and** after data reloads (PTR) so pure-black + /// Texture shells cannot survive a light switch. + func assertFeedShellAppearance(_ snapshot: FireAppearanceSnapshot? = nil) { + let resolved = snapshot ?? currentAppearanceSnapshot() + FireAppearanceTexture.applyCanvas(resolved.canvas, to: collectionNode) + if collectionNode.isNodeLoaded { + FireAppearanceTexture.applyCanvas(resolved.canvas, to: collectionNode.view) + collectionNode.view.refreshControl?.tintColor = resolved.subtleInk + } + } + + /// Full color-appearance refresh after light/dark (or OLED) changes. + /// Rebuilds chrome + re-bakes visible post cells; reloads so factory ASTextNodes + /// also pick up resolved ink tokens. + func refreshColorAppearance(_ snapshot: FireAppearanceSnapshot? = nil) { + let resolved = snapshot ?? currentAppearanceSnapshot() + assertFeedShellAppearance(resolved) + + for indexPath in visibleIndexPaths { + guard let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { + continue + } + node.applyColorAppearance(resolved) + node.invalidateCalculatedLayout() + node.setNeedsLayout() + } + + // Header / stats / footer Texture nodes are one-shot factories — reload so they + // rebuild with the new resolved palette (and clear any black opaque fills). + if !currentItems.isEmpty { + collectionNode.reloadData() + } + // reloadData may recreate the scroll view hierarchy; re-assert shell after. + assertFeedShellAppearance(resolved) + } + + func invalidateLayoutIfWidthChanged() { + let width = layoutContentWidth() + guard width > 1 else { return } + if let lastLayoutContentWidth, + abs(lastLayoutContentWidth - width) < 0.5 { + return + } + let hadMeasuredWidth = lastLayoutContentWidth != nil + lastLayoutContentWidth = width + collectionNode.view.collectionViewLayout.invalidateLayout() + if let layoutManager { + layoutManager.updateTraitSignature( + FirePostLayoutTraitSignature( + contentWidthPixels: Int(width.rounded(.toNearestOrEven)), + contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue + ) + ) + } + if hadMeasuredWidth, !currentItems.isEmpty { + collectionNode.reloadData() + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+CellApplication.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+CellApplication.swift new file mode 100644 index 00000000..dc2936b2 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+CellApplication.swift @@ -0,0 +1,249 @@ +import AsyncDisplayKit +import UIKit + +@MainActor +extension FireTopicDetailFeedController { + func applyVisibleNodeUpdates( + at indices: [Int], + previousItems: [FireTopicDetailRuntimeItem], + nextItems: [FireTopicDetailRuntimeItem], + configuration: FireTopicDetailRuntimeConfiguration + ) { + for index in indices { + guard index < nextItems.count, + let postContext = configuration.postContext(for: nextItems[index]), + let node = collectionNode.nodeForItem(at: IndexPath(item: index, section: 0)) as? FirePostCellNode else { + continue + } + let previous = index < previousItems.count ? previousItems[index] : nil + let bands = previous.map { nextItems[index].changedMessageBands(from: $0) } + ?? Set(FireTopicDetailMessageBand.allCases) + applyPostCellNode( + node, + with: postContext, + configuration: configuration, + mode: .bands(bands, relayout: false) + ) + } + } + + func applyVisiblePostRelayouts( + at indexPaths: [IndexPath], + previousItems: [FireTopicDetailRuntimeItem], + items: [FireTopicDetailRuntimeItem], + configuration: FireTopicDetailRuntimeConfiguration + ) { + for indexPath in indexPaths { + guard indexPath.item >= 0, + indexPath.item < items.count, + let postContext = configuration.postContext(for: items[indexPath.item]), + let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { + continue + } + let previous = indexPath.item < previousItems.count ? previousItems[indexPath.item] : nil + let bands = previous.map { items[indexPath.item].changedMessageBands(from: $0) } + ?? Set(FireTopicDetailMessageBand.allCases) + applyPostCellNode( + node, + with: postContext, + configuration: configuration, + mode: .bands(bands, relayout: true) + ) + } + } + + func reloadReplyFooterIfNeeded(items: [FireTopicDetailRuntimeItem], completion: (() -> Void)? = nil) { + reloadReplyFooterIfNeeded(items: items, attempt: 0, completion: completion) + } + + func reloadItemsIfNeeded(at indexPaths: [IndexPath], completion: (() -> Void)? = nil) { + reloadItemsIfNeeded(at: indexPaths, attempt: 0, completion: completion) + } + + private func reloadReplyFooterIfNeeded( + items: [FireTopicDetailRuntimeItem], + attempt: Int, + completion: (() -> Void)? + ) { + guard let indexPath = replyFooterIndexPath(in: items) else { + completion?() + return + } + if collectionNode.isProcessingUpdates { + guard attempt < Self.maxReplyFooterReloadAttempts else { + collectionNode.reloadData(completion: completion) + return + } + DispatchQueue.main.asyncAfter(deadline: .now() + Self.collectionUpdateRetryDelay) { [weak self] in + self?.reloadReplyFooterIfNeeded( + items: items, + attempt: attempt + 1, + completion: completion + ) + } + return + } + collectionNode.reloadItems(at: [indexPath]) + completion?() + } + + private func reloadItemsIfNeeded( + at indexPaths: [IndexPath], + attempt: Int, + completion: (() -> Void)? + ) { + let validIndexPaths = Array(Set(indexPaths.filter { indexPath in + indexPath.section == 0 + && indexPath.item >= 0 + && indexPath.item < currentItems.count + })).sorted() + + guard !validIndexPaths.isEmpty, + collectionNode.view.window != nil else { + completion?() + return + } + + if collectionNode.isProcessingUpdates { + guard attempt < Self.maxReplyFooterReloadAttempts else { + collectionNode.reloadData(completion: completion) + return + } + DispatchQueue.main.asyncAfter(deadline: .now() + Self.collectionUpdateRetryDelay) { [weak self] in + self?.reloadItemsIfNeeded( + at: validIndexPaths, + attempt: attempt + 1, + completion: completion + ) + } + return + } + + collectionNode.reloadItems(at: validIndexPaths) + completion?() + } + + func applyItems( + _ items: [FireTopicDetailRuntimeItem], + configuration: FireTopicDetailRuntimeConfiguration + ) { + currentItems = items + currentConfiguration = configuration + cellFactory.configuration = configuration + // Header geometry may change with the new snapshot; re-evaluate pin state + // after the collection settles on the next run loop turn. + DispatchQueue.main.async { [weak self] in + self?.publishTitlePinStateIfNeeded() + } + } + + func postCallbacks(configuration: FireTopicDetailRuntimeConfiguration) -> FirePostCellCallbacks { + FirePostCellCallbacks( + onLinkTapped: configuration.onLinkTapped, + onOpenProfile: configuration.onOpenProfile, + onOpenImage: configuration.onOpenImage, + onToggleLike: configuration.onToggleLike, + onSelectReaction: configuration.onSelectReaction, + onToggleReactionPicker: configuration.onToggleReactionPicker, + onReplyPost: { post in + configuration.onOpenComposer(post) + }, + onBoostPost: configuration.onBoostPost, + onQuotePost: configuration.onQuotePost, + onEditPost: configuration.onEditPost, + onBookmarkPost: configuration.onBookmarkPost, + onDeletePost: configuration.onDeletePost, + onRecoverPost: configuration.onRecoverPost, + onFlagPost: configuration.onFlagPost, + onOpenReplyTarget: configuration.onOpenPostNumber, + onOpenReplies: configuration.onOpenPostReplies, + onExpandText: configuration.onExpandPostText, + onVotePoll: configuration.onVotePoll, + onUnvotePoll: configuration.onUnvotePoll, + onSwipeReply: { post in + configuration.onOpenComposer(post) + } + ) + } + + private enum FirePostCellApplyMode { + case configure + case bands(Set, relayout: Bool) + } + + func configurePostCellNode( + _ node: FirePostCellNode, + with context: FireTopicDetailRuntimePostContext, + configuration: FireTopicDetailRuntimeConfiguration + ) { + applyPostCellNode(node, with: context, configuration: configuration, mode: .configure) + } + + private func applyPostCellNode( + _ node: FirePostCellNode, + with context: FireTopicDetailRuntimePostContext, + configuration: FireTopicDetailRuntimeConfiguration, + mode: FirePostCellApplyMode + ) { + let width = layoutContentWidth() + let trait = FirePostLayoutTraitSignature( + contentWidthPixels: Int(width.rounded(.toNearestOrEven)), + contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue + ) + let layoutKey = makeLayoutKey( + for: context, + canWriteInteractions: configuration.canWriteInteractions, + isReactionPickerExpanded: configuration.isReactionPickerExpanded(context.post.id), + trait: trait + ) + let payload = FirePostCellRenderPayload( + post: context.post, + renderContent: context.renderContent, + baseURLString: configuration.baseURLString, + canWriteInteractions: configuration.canWriteInteractions, + isMutating: configuration.isMutatingPost(context.post.id), + replyContext: context.replyContext, + replyTargetPostNumber: context.replyTargetPostNumber, + replyShortcutCount: context.replyShortcutCount, + isReplyThreadExpanded: context.isReplyThreadExpanded, + isLoadingReplyContext: context.isLoadingReplyContext, + textExpansionState: context.textExpansionState, + isSearchHighlighted: configuration.isSearchHighlighted(postID: context.post.id), + showsDivider: context.showsDivider, + layoutWidth: width, + boostAnimationsEnabled: !isScrollInteractionActive, + isReactionPickerExpanded: configuration.isReactionPickerExpanded(context.post.id), + quickReactionOptions: configuration.quickReactionOptions, + layout: layoutManager?.cachedLayout(forKey: layoutKey), + layoutKey: layoutKey, + appearance: currentAppearanceSnapshot() + ) + let callbacks = postCallbacks(configuration: configuration) + switch mode { + case .configure: + node.configure( + payload: payload, + callbacks: callbacks, + depth: context.depth, + showsThreadLine: context.showsThreadLine, + showsDivider: context.showsDivider + ) + case .bands(let bands, let relayout): + node.applyBands( + bands, + payload: payload, + callbacks: callbacks, + showsThreadLine: context.showsThreadLine, + relayout: relayout + ) + if relayout { + node.invalidateCalculatedLayout() + } + } + } + + private func replyFooterIndexPath(in items: [FireTopicDetailRuntimeItem]) -> IndexPath? { + guard let index = items.firstIndex(where: { $0.kind == .replyFooter }) else { return nil } + return IndexPath(item: index, section: 0) + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+CollectionUpdates.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+CollectionUpdates.swift new file mode 100644 index 00000000..a3d9b982 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+CollectionUpdates.swift @@ -0,0 +1,170 @@ +import AsyncDisplayKit +import UIKit + +@MainActor +extension FireTopicDetailFeedController { + func applyCollectionUpdate( + updatePlan: FireTopicDetailCollectionUpdatePlan, + previousItems: [FireTopicDetailRuntimeItem], + nextItems: [FireTopicDetailRuntimeItem], + animated: Bool, + completion: @escaping () -> Void + ) { + let topicId = diagnosticTopicId + let itemDelta = nextItems.count - previousItems.count + let changeCount = + updatePlan.deletions.count + + updatePlan.insertions.count + + updatePlan.reloads.count + + updatePlan.postUpdateReloads.count + let shouldLogDiagnostics = + previousItems.isEmpty + || !isViewAttached + || collectionNode.isProcessingUpdates + || changeCount >= fireTopicDetailCollectionUpdateDiagnosticChangeThreshold + || abs(itemDelta) >= fireTopicDetailCollectionUpdateDiagnosticChangeThreshold + if shouldLogDiagnostics { + diagnosticsLogger?.debug( + "topic detail feed controller apply collection update start topic_id=\(topicId) deletions=\(updatePlan.deletions.count) insertions=\(updatePlan.insertions.count) reloads=\(updatePlan.reloads.count) previous_item_count=\(previousItems.count) next_item_count=\(nextItems.count) animated=\(animated) is_processing_updates=\(collectionNode.isProcessingUpdates) is_view_attached=\(isViewAttached)" + ) + } + guard updatePlan.hasBatchUpdates else { + if shouldLogDiagnostics { + diagnosticsLogger?.debug("topic detail feed controller apply collection update no_batch topic_id=\(topicId)") + } + completion() + return + } + + if fireTopicDetailShouldBypassTextureReloadCompletion( + previousItemsIsEmpty: previousItems.isEmpty, + isViewAttached: collectionNode.view.window != nil + ) { + if shouldLogDiagnostics { + diagnosticsLogger?.debug( + "topic detail feed controller reloadData bypass start topic_id=\(topicId) previous_items_empty=\(previousItems.isEmpty) is_view_attached=\(isViewAttached)" + ) + } + reloadDataCompletingOnNextRunLoop { [weak self] in + if shouldLogDiagnostics { + self?.diagnosticsLogger?.debug( + "topic detail feed controller reloadData bypass completion topic_id=\(topicId)" + ) + } + self?.drainPendingCollectionUpdateIfPossible() + completion() + } + return + } + + guard collectionNode.isProcessingUpdates == false else { + diagnosticsLogger?.debug("topic detail feed controller enqueue pending update topic_id=\(topicId)") + enqueuePendingCollectionUpdate( + updatePlan: updatePlan, + previousItems: previousItems, + nextItems: nextItems, + animated: animated, + completion: completion + ) + return + } + + if shouldLogDiagnostics { + diagnosticsLogger?.debug("topic detail feed controller performBatch dispatch topic_id=\(topicId)") + } + collectionNode.performBatch(animated: animated, updates: { [self] in + if shouldLogDiagnostics { + diagnosticsLogger?.debug("topic detail feed controller performBatch updates start topic_id=\(topicId)") + } + if !updatePlan.deletions.isEmpty { + collectionNode.deleteItems(at: updatePlan.deletions) + } + if !updatePlan.insertions.isEmpty { + collectionNode.insertItems(at: updatePlan.insertions) + } + if !updatePlan.reloads.isEmpty { + collectionNode.reloadItems(at: updatePlan.reloads) + } + if shouldLogDiagnostics { + diagnosticsLogger?.debug("topic detail feed controller performBatch updates complete topic_id=\(topicId)") + } + }, completion: { [weak self] _ in + if shouldLogDiagnostics { + self?.diagnosticsLogger?.debug("topic detail feed controller performBatch completion topic_id=\(topicId)") + } + self?.drainPendingCollectionUpdateIfPossible() + completion() + }) + } + + private func enqueuePendingCollectionUpdate( + updatePlan: FireTopicDetailCollectionUpdatePlan, + previousItems: [FireTopicDetailRuntimeItem], + nextItems: [FireTopicDetailRuntimeItem], + animated: Bool, + completion: @escaping () -> Void + ) { + pendingCollectionUpdate = PendingCollectionUpdate( + updatePlan: updatePlan, + previousItems: previousItems, + nextItems: nextItems, + animated: animated, + completion: completion + ) + pendingCollectionUpdateAttempts = 0 + schedulePendingCollectionUpdateDrain() + } + + private func schedulePendingCollectionUpdateDrain() { + guard !isPendingCollectionUpdateDrainScheduled else { return } + isPendingCollectionUpdateDrainScheduled = true + DispatchQueue.main.asyncAfter(deadline: .now() + Self.collectionUpdateRetryDelay) { [weak self] in + guard let self else { return } + self.isPendingCollectionUpdateDrainScheduled = false + self.drainPendingCollectionUpdateIfPossible() + } + } + + private func drainPendingCollectionUpdateIfPossible() { + guard let pendingCollectionUpdate else { + pendingCollectionUpdateAttempts = 0 + return + } + + guard collectionNode.isProcessingUpdates == false else { + pendingCollectionUpdateAttempts += 1 + guard pendingCollectionUpdateAttempts < Self.maxPendingCollectionUpdateAttempts else { + self.pendingCollectionUpdate = nil + self.pendingCollectionUpdateAttempts = 0 + reloadDataCompletingOnNextRunLoop(completion: pendingCollectionUpdate.completion) + return + } + schedulePendingCollectionUpdateDrain() + return + } + + self.pendingCollectionUpdate = nil + self.pendingCollectionUpdateAttempts = 0 + applyCollectionUpdate( + updatePlan: pendingCollectionUpdate.updatePlan, + previousItems: pendingCollectionUpdate.previousItems, + nextItems: pendingCollectionUpdate.nextItems, + animated: pendingCollectionUpdate.animated, + completion: pendingCollectionUpdate.completion + ) + } + + private func reloadDataCompletingOnNextRunLoop(completion: @escaping () -> Void) { + let topicId = diagnosticTopicId + diagnosticsLogger?.debug("topic detail feed controller reloadData call start topic_id=\(topicId)") + collectionNode.reloadData() + diagnosticsLogger?.debug("topic detail feed controller reloadData call returned topic_id=\(topicId)") + DispatchQueue.main.async { + completion() + } + } + + private var diagnosticTopicId: UInt64 { + currentConfiguration?.row.topic.id ?? 0 + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+DataSource.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+DataSource.swift new file mode 100644 index 00000000..365a59ae --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+DataSource.swift @@ -0,0 +1,115 @@ +import AsyncDisplayKit +import UIKit + +@MainActor +extension FireTopicDetailFeedController { + func numberOfSections(in collectionNode: ASCollectionNode) -> Int { 1 } + + func collectionNode( + _ collectionNode: ASCollectionNode, + numberOfItemsInSection section: Int + ) -> Int { + currentItems.count + } + + func collectionNode( + _ collectionNode: ASCollectionNode, + nodeBlockForItemAt indexPath: IndexPath + ) -> ASCellNodeBlock { + guard indexPath.item < currentItems.count else { + return { ASCellNode() } + } + + let item = currentItems[indexPath.item] + guard let configuration = currentConfiguration else { + return { ASCellNode() } + } + + let capturedLayoutWidth = layoutContentWidth() + let capturedTrait = FirePostLayoutTraitSignature( + contentWidthPixels: Int(capturedLayoutWidth.rounded(.toNearestOrEven)), + contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue + ) + // Capture appearance snapshot on the main thread before Texture may run this block off-main. + let capturedAppearance = currentAppearanceSnapshot() + let capturedPostContext = configuration.postContext(for: item) + let capturedLayoutKey = capturedPostContext.map { + makeLayoutKey( + for: $0, + canWriteInteractions: configuration.canWriteInteractions, + isReactionPickerExpanded: configuration.isReactionPickerExpanded($0.post.id), + trait: capturedTrait + ) + } + let capturedCallbacks = postCallbacks(configuration: configuration) + let capturedConfiguration = configuration + let capturedLayoutManager = layoutManager + let capturedCellFactory = cellFactory + let capturedBoostAnimationsEnabled = !isScrollInteractionActive + + return { + if let postContext = capturedPostContext { + let node = FirePostCellNode() + node.configure( + payload: FirePostCellRenderPayload( + post: postContext.post, + renderContent: postContext.renderContent, + baseURLString: capturedConfiguration.baseURLString, + canWriteInteractions: capturedConfiguration.canWriteInteractions, + isMutating: capturedConfiguration.isMutatingPost(postContext.post.id), + replyContext: postContext.replyContext, + replyTargetPostNumber: postContext.replyTargetPostNumber, + replyShortcutCount: postContext.replyShortcutCount, + isReplyThreadExpanded: postContext.isReplyThreadExpanded, + isLoadingReplyContext: postContext.isLoadingReplyContext, + textExpansionState: postContext.textExpansionState, + isSearchHighlighted: capturedConfiguration.isSearchHighlighted(postID: postContext.post.id), + showsDivider: postContext.showsDivider, + layoutWidth: capturedLayoutWidth, + boostAnimationsEnabled: capturedBoostAnimationsEnabled, + isReactionPickerExpanded: capturedConfiguration.isReactionPickerExpanded(postContext.post.id), + quickReactionOptions: capturedConfiguration.quickReactionOptions, + layout: capturedLayoutKey.flatMap { capturedLayoutManager?.cachedLayout(forKey: $0) }, + layoutKey: capturedLayoutKey, + appearance: capturedAppearance + ), + callbacks: capturedCallbacks, + depth: postContext.depth, + showsThreadLine: postContext.showsThreadLine, + showsDivider: postContext.showsDivider + ) + return node + } + // Capture layout width on the main thread above. Texture may execute this + // node block off-main, so cell factories must not touch UIKit here. + return capturedCellFactory.makeCellNode( + for: item, + configuration: capturedConfiguration, + layoutWidth: capturedLayoutWidth, + appearance: capturedAppearance + ) + } + } + + func collectionNode( + _ collectionNode: ASCollectionNode, + constrainedSizeForItemAt indexPath: IndexPath + ) -> ASSizeRange { + let width = layoutContentWidth() + return ASSizeRange( + min: CGSize(width: width, height: 0), + max: CGSize(width: width, height: .greatestFiniteMagnitude) + ) + } + + func collectionNode( + _ collectionNode: ASCollectionNode, + willBeginBatchFetchWith context: ASBatchContext + ) { + context.completeBatchFetching(true) + } + + func shouldBatchFetch(for collectionNode: ASCollectionNode) -> Bool { + return false + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Layout.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Layout.swift new file mode 100644 index 00000000..57895a6c --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Layout.swift @@ -0,0 +1,202 @@ +import AsyncDisplayKit +import UIKit + +@MainActor +extension FireTopicDetailFeedController { + func prepareLayoutsIfNeeded( + items: [FireTopicDetailRuntimeItem], + configuration: FireTopicDetailRuntimeConfiguration, + pendingScrollTarget: UInt32? + ) { + guard let layoutManager else { return } + + let width = layoutContentWidth() + let trait = FirePostLayoutTraitSignature( + contentWidthPixels: Int(width.rounded(.toNearestOrEven)), + contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue + ) + layoutManager.updateTraitSignature(trait) + + let visibleIndices = collectionNode.indexPathsForVisibleItems.map(\.item) + var candidateIndices = Set() + for visibleIndex in visibleIndices { + let lowerBound = max(visibleIndex - 6, 0) + let upperBound = min(visibleIndex + 6, items.count - 1) + for index in lowerBound...upperBound { + candidateIndices.insert(index) + } + } + if candidateIndices.isEmpty { + for index in items.indices.prefix(12) { + candidateIndices.insert(index) + } + } + if let pendingScrollTarget, + let targetIndex = items.firstIndex(where: { $0.postNumber == pendingScrollTarget }) { + candidateIndices.insert(targetIndex) + } + + for index in candidateIndices.sorted() { + guard index >= 0, + index < items.count, + let postContext = configuration.postContext(for: items[index]) else { + continue + } + let key = makeLayoutKey( + for: postContext, + canWriteInteractions: configuration.canWriteInteractions, + isReactionPickerExpanded: configuration.isReactionPickerExpanded(postContext.post.id), + trait: trait + ) + layoutManager.enqueueCalculation( + key: key, + attributedText: postContext.renderContent.attributedText, + plainText: postContext.renderContent.plainText, + images: postContext.renderContent.imageAttachments, + polls: FirePostPollRenderModel.models(from: postContext.post.polls), + boostLines: FirePostBoostDisplay.fixedDisplayLines( + for: postContext.post.boosts, + depth: postContext.depth, + textExpansionState: postContext.textExpansionState, + hasBodyTextTarget: postContext.renderContent.hasBoostBarrageTextTarget + ), + trait: trait + ) + } + } + + func applyPublishedLayoutRevision( + publishedKeys: Set, + items: [FireTopicDetailRuntimeItem], + configuration: FireTopicDetailRuntimeConfiguration + ) { + guard let layoutManager, !publishedKeys.isEmpty else { return } + + let width = layoutContentWidth() + let trait = FirePostLayoutTraitSignature( + contentWidthPixels: Int(width.rounded(.toNearestOrEven)), + contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue + ) + + for indexPath in visibleIndexPaths { + guard indexPath.item >= 0, + indexPath.item < items.count, + let postContext = configuration.postContext(for: items[indexPath.item]) else { + continue + } + + let key = makeLayoutKey( + for: postContext, + canWriteInteractions: configuration.canWriteInteractions, + isReactionPickerExpanded: configuration.isReactionPickerExpanded(postContext.post.id), + trait: trait + ) + guard publishedKeys.contains(key), + layoutManager.cachedLayout(forKey: key) != nil, + let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { + continue + } + + configurePostCellNode(node, with: postContext, configuration: configuration) + node.invalidateCalculatedLayout() + node.setNeedsLayout() + } + } + + func makeLayoutKey( + for context: FireTopicDetailRuntimePostContext, + canWriteInteractions: Bool, + isReactionPickerExpanded: Bool, + trait: FirePostLayoutTraitSignature + ) -> FirePostCellLayoutKey { + let textContentID = [ + String(context.post.id), + context.renderContent.signature.token, + String(context.textExpansionState.isExpanded), + String(context.textExpansionState.isCollapsible), + ].joined(separator: "\u{1F}") + + let pollSignature = FirePostPollRenderModel.models(from: context.post.polls) + .map(\.signature) + let boostSignature = context.post.boosts.map { boost in + [ + String(boost.id), + boost.user.username, + boost.user.name ?? "", + boost.displayText, + ].joined(separator: "\u{1E}") + } + + return FirePostCellLayoutKey( + postID: context.post.id, + depth: context.depth, + showsThreadLine: context.showsThreadLine, + showsDivider: context.showsDivider, + replyTargetPostNumber: context.replyTargetPostNumber, + replyContext: context.replyContext, + textContentID: textContentID, + imageSignature: context.renderContent.segments.map(\.signatureToken), + pollSignature: pollSignature, + boostSignature: boostSignature, + hasReactions: !context.post.reactions.isEmpty, + replyShortcutCount: context.replyShortcutCount, + isReplyThreadExpanded: context.isReplyThreadExpanded, + showsInlineActions: { + guard context.allowsInlineOverflowActions else { return false } + let post = context.post + return canWriteInteractions && !post.hidden + || post.canEdit + || post.canRecover + || (post.canDelete && !post.hidden) + }(), + primaryActionSlotCount: { + guard context.allowsInlineOverflowActions else { return 0 } + let post = context.post + let canWrite = canWriteInteractions && !post.hidden + var slots = 0 + if canWrite { + slots += 2 // reply + react + if post.canBoost { + slots += 1 + } + } + let hasSecondary = canWrite + || post.canEdit + || post.canRecover + || (post.canDelete && !post.hidden) + if hasSecondary { + slots += 1 // overflow + } + return slots + }(), + isReactionPickerExpanded: isReactionPickerExpanded, + textExpansionState: context.textExpansionState, + acceptedAnswer: context.post.acceptedAnswer, + hasAuthorMetadata: FirePostAuthorMetadataDisplay.hasVisibleMetadata(context.post), + trait: trait + ) + } + + + static func makeCollectionLayout() -> UICollectionViewFlowLayout { + let flowLayout = UICollectionViewFlowLayout() + flowLayout.minimumLineSpacing = 0 + flowLayout.minimumInteritemSpacing = 0 + flowLayout.estimatedItemSize = .zero + return flowLayout + } + + func configureTextureRanges() { + collectionNode.leadingScreensForBatching = 1.5 + + var displayTuning = ASRangeTuningParameters() + displayTuning.leadingBufferScreenfuls = 1.0 + displayTuning.trailingBufferScreenfuls = 0.5 + collectionNode.setTuningParameters(displayTuning, for: .display) + + var preloadTuning = ASRangeTuningParameters() + preloadTuning.leadingBufferScreenfuls = 1.5 + preloadTuning.trailingBufferScreenfuls = 1.0 + collectionNode.setTuningParameters(preloadTuning, for: .preload) + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Scrolling.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Scrolling.swift new file mode 100644 index 00000000..4f1251c6 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController+Scrolling.swift @@ -0,0 +1,189 @@ +import AsyncDisplayKit +import UIKit + +@MainActor +extension FireTopicDetailFeedController { + func handlePendingScrollTarget( + _ target: UInt32?, + handledTarget: inout UInt32?, + onScrollTargetHandled: (UInt32) -> Void + ) { + guard let target, + handledTarget != target, + let index = currentItems.firstIndex(where: { $0.postNumber == target }) else { + return + } + handledTarget = target + collectionNode.scrollToItem( + at: IndexPath(item: index, section: 0), + at: .centeredVertically, + animated: true + ) + onScrollTargetHandled(target) + } + + var visibleMaxItem: Int? { + collectionNode.indexPathsForVisibleItems.map(\.item).max() + } + + var visibleIndexPaths: Set { + Set(collectionNode.indexPathsForVisibleItems) + } + + var isScrollInteractionActive: Bool { + collectionNode.view.isDragging + || collectionNode.view.isDecelerating + || collectionNode.view.isTracking + } + + var isViewAttached: Bool { + collectionNode.view.window != nil + } + + var contentFitsWithoutScrolling: Bool { + let visibleHeight = collectionNode.view.bounds.height + - collectionNode.view.adjustedContentInset.top + - collectionNode.view.adjustedContentInset.bottom + guard visibleHeight > 0 else { return false } + return collectionNode.view.contentSize.height <= visibleHeight + 1 + } + + func replyFooterState(in items: [FireTopicDetailRuntimeItem]) -> FireTopicDetailRuntimeReplyFooterState? { + guard let item = items.first(where: { $0.kind == .replyFooter }), + let token = item.contentToken.base as? String else { + return nil + } + return FireTopicDetailRuntimeReplyFooterState.fromContentToken(token) + } + + func currentVisiblePostNumbers(items: [FireTopicDetailRuntimeItem]) -> Set { + Set(collectionNode.indexPathsForVisibleItems.compactMap { indexPath -> UInt32? in + guard indexPath.item < items.count else { return nil } + return items[indexPath.item].postNumber + }) + } + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + publishScrollInteractionStateIfNeeded() + publishTitlePinStateIfNeeded() + reevaluateVisibleState(forceLoadMoreEvaluation: false) + } + + func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { + publishScrollInteractionStateIfNeeded() + publishTitlePinStateIfNeeded() + if !decelerate { + scheduleDeferredScrollIdleCheck() + reevaluateVisibleState(forceLoadMoreEvaluation: true) + } + } + + func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { + publishScrollInteractionStateIfNeeded() + publishTitlePinStateIfNeeded() + scheduleDeferredScrollIdleCheck() + reevaluateVisibleState(forceLoadMoreEvaluation: true) + } + + func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + deferredIdleCheckGeneration &+= 1 + publishScrollInteractionStateIfNeeded() + publishTitlePinStateIfNeeded() + } + + func performPullToRefresh() { + Task { [weak self] in + await self?.onRefresh?() + await MainActor.run { [weak self] in + guard let self else { return } + // Data reload rebuilds Texture nodes; re-assert shell so dark→light + // never leaves a pure-black collection/root after PTR. + self.assertFeedShellAppearance() + self.collectionNode.view.refreshControl?.endRefreshing() + } + } + } + + private func reevaluateVisibleState(forceLoadMoreEvaluation: Bool) { + visibilityCoordinator?.publishIfChanged(items: currentItems) + if fireTopicDetailShouldEvaluatePagination( + forceLoadMoreEvaluation: forceLoadMoreEvaluation, + isScrollInteractionActive: isScrollInteractionActive + ) { + paginationCoordinator?.loadMoreIfNeeded( + itemCount: currentItems.count, + visibleMaxItem: visibleMaxItem, + forceEvaluation: forceLoadMoreEvaluation + ) + } + if let configuration = currentConfiguration { + prepareLayoutsIfNeeded( + items: currentItems, + configuration: configuration, + pendingScrollTarget: configuration.pendingScrollTarget + ) + } + updateVisibleBoostAnimationState() + } + + private func publishScrollInteractionStateIfNeeded() { + let isActive = isScrollInteractionActive + guard lastPublishedScrollInteractionActive != isActive else { return } + lastPublishedScrollInteractionActive = isActive + onScrollInteractionChanged?(isActive) + updateVisibleBoostAnimationState() + } + + func publishTitlePinStateIfNeeded() { + let pinned = resolveIsTitlePinned() + guard lastPublishedTitlePinned != pinned else { return } + lastPublishedTitlePinned = pinned + onTitlePinStateChanged?(pinned) + } + + func resolveIsTitlePinned() -> Bool { + let scrollView = collectionNode.view + let visibleTop = scrollView.contentOffset.y + scrollView.adjustedContentInset.top + let headerFrame: CGRect? + if let headerIndex = currentItems.firstIndex(where: { $0.kind == .header }) { + headerFrame = collectionNode.collectionViewLayout + .layoutAttributesForItem(at: IndexPath(item: headerIndex, section: 0))? + .frame + } else { + headerFrame = nil + } + return FireTopicDetailToolbarChromeMetrics.isTitlePinned( + headerFrame: headerFrame, + visibleTop: visibleTop + ) + } + + private func scheduleDeferredScrollIdleCheck() { + deferredIdleCheckGeneration &+= 1 + let generation = deferredIdleCheckGeneration + DispatchQueue.main.async { [weak self] in + guard let self, + self.deferredIdleCheckGeneration == generation else { + return + } + self.publishScrollInteractionStateIfNeeded() + self.publishTitlePinStateIfNeeded() + self.updateVisibleBoostAnimationState() + } + } + + private func updateVisibleBoostAnimationState() { + let enabled = !isScrollInteractionActive + for indexPath in visibleIndexPaths { + guard let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { + continue + } + node.setBoostAnimationsEnabled(enabled) + } + } + + @objc + func handleBackgroundTap() { + onBackgroundTap?() + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift index b6547e10..7d73fdb8 100644 --- a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift @@ -7,7 +7,7 @@ final class FireTopicDetailFeedController: NSObject, @preconcurrency ASCollectionDelegate, UIScrollViewDelegate { - private struct PendingCollectionUpdate { + struct PendingCollectionUpdate { let updatePlan: FireTopicDetailCollectionUpdatePlan let previousItems: [FireTopicDetailRuntimeItem] let nextItems: [FireTopicDetailRuntimeItem] @@ -15,22 +15,22 @@ final class FireTopicDetailFeedController: NSObject, let completion: () -> Void } - private static let collectionUpdateRetryDelay: TimeInterval = 0.05 - private static let maxPendingCollectionUpdateAttempts = 8 - private static let maxReplyFooterReloadAttempts = 8 + static let collectionUpdateRetryDelay: TimeInterval = 0.05 + static let maxPendingCollectionUpdateAttempts = 8 + static let maxReplyFooterReloadAttempts = 8 let collectionNode = ASCollectionNode( collectionViewLayout: FireTopicDetailFeedController.makeCollectionLayout() ) - private(set) var currentItems: [FireTopicDetailRuntimeItem] = [] - private var currentConfiguration: FireTopicDetailRuntimeConfiguration? - private var lastLayoutContentWidth: CGFloat? - private var pendingCollectionUpdate: PendingCollectionUpdate? - private var pendingCollectionUpdateAttempts = 0 - private var isPendingCollectionUpdateDrainScheduled = false - private let cellFactory = FireTopicDetailFeedCellFactory() - private lazy var dismissKeyboardTapGestureRecognizer = UITapGestureRecognizer( + var currentItems: [FireTopicDetailRuntimeItem] = [] + var currentConfiguration: FireTopicDetailRuntimeConfiguration? + var lastLayoutContentWidth: CGFloat? + var pendingCollectionUpdate: PendingCollectionUpdate? + var pendingCollectionUpdateAttempts = 0 + var isPendingCollectionUpdateDrainScheduled = false + let cellFactory = FireTopicDetailFeedCellFactory() + lazy var dismissKeyboardTapGestureRecognizer = UITapGestureRecognizer( target: self, action: #selector(handleBackgroundTap) ) @@ -45,9 +45,9 @@ final class FireTopicDetailFeedController: NSObject, var onScrollInteractionChanged: ((Bool) -> Void)? /// Reports whether the in-feed topic title has scrolled under the nav bar. var onTitlePinStateChanged: ((Bool) -> Void)? - private var lastPublishedScrollInteractionActive = false - private var lastPublishedTitlePinned = false - private var deferredIdleCheckGeneration: UInt64 = 0 + var lastPublishedScrollInteractionActive = false + var lastPublishedTitlePinned = false + var deferredIdleCheckGeneration: UInt64 = 0 var isTitleCurrentlyPinned: Bool { resolveIsTitlePinned() @@ -81,989 +81,4 @@ final class FireTopicDetailFeedController: NSObject, ) } } - - func layoutContentWidth(proposedWidth: CGFloat? = nil) -> CGFloat { - let adjustedBoundsWidth = collectionNode.view.bounds.width - - collectionNode.view.adjustedContentInset.left - - collectionNode.view.adjustedContentInset.right - if adjustedBoundsWidth > 0 { - return adjustedBoundsWidth - } - return max(proposedWidth ?? collectionNode.view.bounds.width, 1) - } - - /// Trait collection used to bake Texture text colors. Prefer the loaded - /// collection view so window `overrideUserInterfaceStyle` is respected. - func currentColorTraits() -> UITraitCollection { - if collectionNode.isNodeLoaded { - return FireAppearanceEnvironment.traits(for: collectionNode.view) - } - return FireAppearanceEnvironment.traits() - } - - func currentAppearanceSnapshot() -> FireAppearanceSnapshot { - if collectionNode.isNodeLoaded { - return FireAppearanceEnvironment.snapshot(for: collectionNode.view) - } - return FireAppearanceEnvironment.snapshot() - } - - /// Re-assert collection + scroll-view canvas from the current snapshot. - /// Must run after theme flips **and** after data reloads (PTR) so pure-black - /// Texture shells cannot survive a light switch. - func assertFeedShellAppearance(_ snapshot: FireAppearanceSnapshot? = nil) { - let resolved = snapshot ?? currentAppearanceSnapshot() - FireAppearanceTexture.applyCanvas(resolved.canvas, to: collectionNode) - if collectionNode.isNodeLoaded { - FireAppearanceTexture.applyCanvas(resolved.canvas, to: collectionNode.view) - collectionNode.view.refreshControl?.tintColor = resolved.subtleInk - } - } - - /// Full color-appearance refresh after light/dark (or OLED) changes. - /// Rebuilds chrome + re-bakes visible post cells; reloads so factory ASTextNodes - /// also pick up resolved ink tokens. - func refreshColorAppearance(_ snapshot: FireAppearanceSnapshot? = nil) { - let resolved = snapshot ?? currentAppearanceSnapshot() - assertFeedShellAppearance(resolved) - - for indexPath in visibleIndexPaths { - guard let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { - continue - } - node.applyColorAppearance(resolved) - node.invalidateCalculatedLayout() - node.setNeedsLayout() - } - - // Header / stats / footer Texture nodes are one-shot factories — reload so they - // rebuild with the new resolved palette (and clear any black opaque fills). - if !currentItems.isEmpty { - collectionNode.reloadData() - } - // reloadData may recreate the scroll view hierarchy; re-assert shell after. - assertFeedShellAppearance(resolved) - } - - func invalidateLayoutIfWidthChanged() { - let width = layoutContentWidth() - guard width > 1 else { return } - if let lastLayoutContentWidth, - abs(lastLayoutContentWidth - width) < 0.5 { - return - } - let hadMeasuredWidth = lastLayoutContentWidth != nil - lastLayoutContentWidth = width - collectionNode.view.collectionViewLayout.invalidateLayout() - if let layoutManager { - layoutManager.updateTraitSignature( - FirePostLayoutTraitSignature( - contentWidthPixels: Int(width.rounded(.toNearestOrEven)), - contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue - ) - ) - } - if hadMeasuredWidth, !currentItems.isEmpty { - collectionNode.reloadData() - } - } - - func handlePendingScrollTarget( - _ target: UInt32?, - handledTarget: inout UInt32?, - onScrollTargetHandled: (UInt32) -> Void - ) { - guard let target, - handledTarget != target, - let index = currentItems.firstIndex(where: { $0.postNumber == target }) else { - return - } - handledTarget = target - collectionNode.scrollToItem( - at: IndexPath(item: index, section: 0), - at: .centeredVertically, - animated: true - ) - onScrollTargetHandled(target) - } - - func applyVisibleNodeUpdates( - at indices: [Int], - previousItems: [FireTopicDetailRuntimeItem], - nextItems: [FireTopicDetailRuntimeItem], - configuration: FireTopicDetailRuntimeConfiguration - ) { - for index in indices { - guard index < nextItems.count, - let postContext = configuration.postContext(for: nextItems[index]), - let node = collectionNode.nodeForItem(at: IndexPath(item: index, section: 0)) as? FirePostCellNode else { - continue - } - let previous = index < previousItems.count ? previousItems[index] : nil - let bands = previous.map { nextItems[index].changedMessageBands(from: $0) } - ?? Set(FireTopicDetailMessageBand.allCases) - applyPostCellNode( - node, - with: postContext, - configuration: configuration, - mode: .bands(bands, relayout: false) - ) - } - } - - func applyVisiblePostRelayouts( - at indexPaths: [IndexPath], - previousItems: [FireTopicDetailRuntimeItem], - items: [FireTopicDetailRuntimeItem], - configuration: FireTopicDetailRuntimeConfiguration - ) { - for indexPath in indexPaths { - guard indexPath.item >= 0, - indexPath.item < items.count, - let postContext = configuration.postContext(for: items[indexPath.item]), - let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { - continue - } - let previous = indexPath.item < previousItems.count ? previousItems[indexPath.item] : nil - let bands = previous.map { items[indexPath.item].changedMessageBands(from: $0) } - ?? Set(FireTopicDetailMessageBand.allCases) - applyPostCellNode( - node, - with: postContext, - configuration: configuration, - mode: .bands(bands, relayout: true) - ) - } - } - - func applyCollectionUpdate( - updatePlan: FireTopicDetailCollectionUpdatePlan, - previousItems: [FireTopicDetailRuntimeItem], - nextItems: [FireTopicDetailRuntimeItem], - animated: Bool, - completion: @escaping () -> Void - ) { - let topicId = diagnosticTopicId - let itemDelta = nextItems.count - previousItems.count - let changeCount = - updatePlan.deletions.count - + updatePlan.insertions.count - + updatePlan.reloads.count - + updatePlan.postUpdateReloads.count - let shouldLogDiagnostics = - previousItems.isEmpty - || !isViewAttached - || collectionNode.isProcessingUpdates - || changeCount >= fireTopicDetailCollectionUpdateDiagnosticChangeThreshold - || abs(itemDelta) >= fireTopicDetailCollectionUpdateDiagnosticChangeThreshold - if shouldLogDiagnostics { - diagnosticsLogger?.debug( - "topic detail feed controller apply collection update start topic_id=\(topicId) deletions=\(updatePlan.deletions.count) insertions=\(updatePlan.insertions.count) reloads=\(updatePlan.reloads.count) previous_item_count=\(previousItems.count) next_item_count=\(nextItems.count) animated=\(animated) is_processing_updates=\(collectionNode.isProcessingUpdates) is_view_attached=\(isViewAttached)" - ) - } - guard updatePlan.hasBatchUpdates else { - if shouldLogDiagnostics { - diagnosticsLogger?.debug("topic detail feed controller apply collection update no_batch topic_id=\(topicId)") - } - completion() - return - } - - if fireTopicDetailShouldBypassTextureReloadCompletion( - previousItemsIsEmpty: previousItems.isEmpty, - isViewAttached: collectionNode.view.window != nil - ) { - if shouldLogDiagnostics { - diagnosticsLogger?.debug( - "topic detail feed controller reloadData bypass start topic_id=\(topicId) previous_items_empty=\(previousItems.isEmpty) is_view_attached=\(isViewAttached)" - ) - } - reloadDataCompletingOnNextRunLoop { [weak self] in - if shouldLogDiagnostics { - self?.diagnosticsLogger?.debug( - "topic detail feed controller reloadData bypass completion topic_id=\(topicId)" - ) - } - self?.drainPendingCollectionUpdateIfPossible() - completion() - } - return - } - - guard collectionNode.isProcessingUpdates == false else { - diagnosticsLogger?.debug("topic detail feed controller enqueue pending update topic_id=\(topicId)") - enqueuePendingCollectionUpdate( - updatePlan: updatePlan, - previousItems: previousItems, - nextItems: nextItems, - animated: animated, - completion: completion - ) - return - } - - if shouldLogDiagnostics { - diagnosticsLogger?.debug("topic detail feed controller performBatch dispatch topic_id=\(topicId)") - } - collectionNode.performBatch(animated: animated, updates: { [self] in - if shouldLogDiagnostics { - diagnosticsLogger?.debug("topic detail feed controller performBatch updates start topic_id=\(topicId)") - } - if !updatePlan.deletions.isEmpty { - collectionNode.deleteItems(at: updatePlan.deletions) - } - if !updatePlan.insertions.isEmpty { - collectionNode.insertItems(at: updatePlan.insertions) - } - if !updatePlan.reloads.isEmpty { - collectionNode.reloadItems(at: updatePlan.reloads) - } - if shouldLogDiagnostics { - diagnosticsLogger?.debug("topic detail feed controller performBatch updates complete topic_id=\(topicId)") - } - }, completion: { [weak self] _ in - if shouldLogDiagnostics { - self?.diagnosticsLogger?.debug("topic detail feed controller performBatch completion topic_id=\(topicId)") - } - self?.drainPendingCollectionUpdateIfPossible() - completion() - }) - } - - func reloadReplyFooterIfNeeded(items: [FireTopicDetailRuntimeItem], completion: (() -> Void)? = nil) { - reloadReplyFooterIfNeeded(items: items, attempt: 0, completion: completion) - } - - func reloadItemsIfNeeded(at indexPaths: [IndexPath], completion: (() -> Void)? = nil) { - reloadItemsIfNeeded(at: indexPaths, attempt: 0, completion: completion) - } - - private func reloadReplyFooterIfNeeded( - items: [FireTopicDetailRuntimeItem], - attempt: Int, - completion: (() -> Void)? - ) { - guard let indexPath = replyFooterIndexPath(in: items) else { - completion?() - return - } - if collectionNode.isProcessingUpdates { - guard attempt < Self.maxReplyFooterReloadAttempts else { - collectionNode.reloadData(completion: completion) - return - } - DispatchQueue.main.asyncAfter(deadline: .now() + Self.collectionUpdateRetryDelay) { [weak self] in - self?.reloadReplyFooterIfNeeded( - items: items, - attempt: attempt + 1, - completion: completion - ) - } - return - } - collectionNode.reloadItems(at: [indexPath]) - completion?() - } - - private func reloadItemsIfNeeded( - at indexPaths: [IndexPath], - attempt: Int, - completion: (() -> Void)? - ) { - let validIndexPaths = Array(Set(indexPaths.filter { indexPath in - indexPath.section == 0 - && indexPath.item >= 0 - && indexPath.item < currentItems.count - })).sorted() - - guard !validIndexPaths.isEmpty, - collectionNode.view.window != nil else { - completion?() - return - } - - if collectionNode.isProcessingUpdates { - guard attempt < Self.maxReplyFooterReloadAttempts else { - collectionNode.reloadData(completion: completion) - return - } - DispatchQueue.main.asyncAfter(deadline: .now() + Self.collectionUpdateRetryDelay) { [weak self] in - self?.reloadItemsIfNeeded( - at: validIndexPaths, - attempt: attempt + 1, - completion: completion - ) - } - return - } - - collectionNode.reloadItems(at: validIndexPaths) - completion?() - } - - var visibleMaxItem: Int? { - collectionNode.indexPathsForVisibleItems.map(\.item).max() - } - - var visibleIndexPaths: Set { - Set(collectionNode.indexPathsForVisibleItems) - } - - var isScrollInteractionActive: Bool { - collectionNode.view.isDragging - || collectionNode.view.isDecelerating - || collectionNode.view.isTracking - } - - var isViewAttached: Bool { - collectionNode.view.window != nil - } - - var contentFitsWithoutScrolling: Bool { - let visibleHeight = collectionNode.view.bounds.height - - collectionNode.view.adjustedContentInset.top - - collectionNode.view.adjustedContentInset.bottom - guard visibleHeight > 0 else { return false } - return collectionNode.view.contentSize.height <= visibleHeight + 1 - } - - func replyFooterState(in items: [FireTopicDetailRuntimeItem]) -> FireTopicDetailRuntimeReplyFooterState? { - guard let item = items.first(where: { $0.kind == .replyFooter }), - let token = item.contentToken.base as? String else { - return nil - } - return FireTopicDetailRuntimeReplyFooterState.fromContentToken(token) - } - - func currentVisiblePostNumbers(items: [FireTopicDetailRuntimeItem]) -> Set { - Set(collectionNode.indexPathsForVisibleItems.compactMap { indexPath -> UInt32? in - guard indexPath.item < items.count else { return nil } - return items[indexPath.item].postNumber - }) - } - - func prepareLayoutsIfNeeded( - items: [FireTopicDetailRuntimeItem], - configuration: FireTopicDetailRuntimeConfiguration, - pendingScrollTarget: UInt32? - ) { - guard let layoutManager else { return } - - let width = layoutContentWidth() - let trait = FirePostLayoutTraitSignature( - contentWidthPixels: Int(width.rounded(.toNearestOrEven)), - contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue - ) - layoutManager.updateTraitSignature(trait) - - let visibleIndices = collectionNode.indexPathsForVisibleItems.map(\.item) - var candidateIndices = Set() - for visibleIndex in visibleIndices { - let lowerBound = max(visibleIndex - 6, 0) - let upperBound = min(visibleIndex + 6, items.count - 1) - for index in lowerBound...upperBound { - candidateIndices.insert(index) - } - } - if candidateIndices.isEmpty { - for index in items.indices.prefix(12) { - candidateIndices.insert(index) - } - } - if let pendingScrollTarget, - let targetIndex = items.firstIndex(where: { $0.postNumber == pendingScrollTarget }) { - candidateIndices.insert(targetIndex) - } - - for index in candidateIndices.sorted() { - guard index >= 0, - index < items.count, - let postContext = configuration.postContext(for: items[index]) else { - continue - } - let key = makeLayoutKey( - for: postContext, - canWriteInteractions: configuration.canWriteInteractions, - isReactionPickerExpanded: configuration.isReactionPickerExpanded(postContext.post.id), - trait: trait - ) - layoutManager.enqueueCalculation( - key: key, - attributedText: postContext.renderContent.attributedText, - plainText: postContext.renderContent.plainText, - images: postContext.renderContent.imageAttachments, - polls: FirePostPollRenderModel.models(from: postContext.post.polls), - boostLines: FirePostBoostDisplay.fixedDisplayLines( - for: postContext.post.boosts, - depth: postContext.depth, - textExpansionState: postContext.textExpansionState, - hasBodyTextTarget: postContext.renderContent.hasBoostBarrageTextTarget - ), - trait: trait - ) - } - } - - func applyPublishedLayoutRevision( - publishedKeys: Set, - items: [FireTopicDetailRuntimeItem], - configuration: FireTopicDetailRuntimeConfiguration - ) { - guard let layoutManager, !publishedKeys.isEmpty else { return } - - let width = layoutContentWidth() - let trait = FirePostLayoutTraitSignature( - contentWidthPixels: Int(width.rounded(.toNearestOrEven)), - contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue - ) - - for indexPath in visibleIndexPaths { - guard indexPath.item >= 0, - indexPath.item < items.count, - let postContext = configuration.postContext(for: items[indexPath.item]) else { - continue - } - - let key = makeLayoutKey( - for: postContext, - canWriteInteractions: configuration.canWriteInteractions, - isReactionPickerExpanded: configuration.isReactionPickerExpanded(postContext.post.id), - trait: trait - ) - guard publishedKeys.contains(key), - layoutManager.cachedLayout(forKey: key) != nil, - let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { - continue - } - - configurePostCellNode(node, with: postContext, configuration: configuration) - node.invalidateCalculatedLayout() - node.setNeedsLayout() - } - } - - func numberOfSections(in collectionNode: ASCollectionNode) -> Int { 1 } - - func collectionNode( - _ collectionNode: ASCollectionNode, - numberOfItemsInSection section: Int - ) -> Int { - currentItems.count - } - - func collectionNode( - _ collectionNode: ASCollectionNode, - nodeBlockForItemAt indexPath: IndexPath - ) -> ASCellNodeBlock { - guard indexPath.item < currentItems.count else { - return { ASCellNode() } - } - - let item = currentItems[indexPath.item] - guard let configuration = currentConfiguration else { - return { ASCellNode() } - } - - let capturedLayoutWidth = layoutContentWidth() - let capturedTrait = FirePostLayoutTraitSignature( - contentWidthPixels: Int(capturedLayoutWidth.rounded(.toNearestOrEven)), - contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue - ) - // Capture appearance snapshot on the main thread before Texture may run this block off-main. - let capturedAppearance = currentAppearanceSnapshot() - let capturedPostContext = configuration.postContext(for: item) - let capturedLayoutKey = capturedPostContext.map { - makeLayoutKey( - for: $0, - canWriteInteractions: configuration.canWriteInteractions, - isReactionPickerExpanded: configuration.isReactionPickerExpanded($0.post.id), - trait: capturedTrait - ) - } - let capturedCallbacks = postCallbacks(configuration: configuration) - let capturedConfiguration = configuration - let capturedLayoutManager = layoutManager - let capturedCellFactory = cellFactory - let capturedBoostAnimationsEnabled = !isScrollInteractionActive - - return { - if let postContext = capturedPostContext { - let node = FirePostCellNode() - node.configure( - payload: FirePostCellRenderPayload( - post: postContext.post, - renderContent: postContext.renderContent, - baseURLString: capturedConfiguration.baseURLString, - canWriteInteractions: capturedConfiguration.canWriteInteractions, - isMutating: capturedConfiguration.isMutatingPost(postContext.post.id), - replyContext: postContext.replyContext, - replyTargetPostNumber: postContext.replyTargetPostNumber, - replyShortcutCount: postContext.replyShortcutCount, - isReplyThreadExpanded: postContext.isReplyThreadExpanded, - isLoadingReplyContext: postContext.isLoadingReplyContext, - textExpansionState: postContext.textExpansionState, - isSearchHighlighted: capturedConfiguration.isSearchHighlighted(postID: postContext.post.id), - showsDivider: postContext.showsDivider, - layoutWidth: capturedLayoutWidth, - boostAnimationsEnabled: capturedBoostAnimationsEnabled, - isReactionPickerExpanded: capturedConfiguration.isReactionPickerExpanded(postContext.post.id), - quickReactionOptions: capturedConfiguration.quickReactionOptions, - layout: capturedLayoutKey.flatMap { capturedLayoutManager?.cachedLayout(forKey: $0) }, - layoutKey: capturedLayoutKey, - appearance: capturedAppearance - ), - callbacks: capturedCallbacks, - depth: postContext.depth, - showsThreadLine: postContext.showsThreadLine, - showsDivider: postContext.showsDivider - ) - return node - } - // Capture layout width on the main thread above. Texture may execute this - // node block off-main, so cell factories must not touch UIKit here. - return capturedCellFactory.makeCellNode( - for: item, - configuration: capturedConfiguration, - layoutWidth: capturedLayoutWidth, - appearance: capturedAppearance - ) - } - } - - func collectionNode( - _ collectionNode: ASCollectionNode, - constrainedSizeForItemAt indexPath: IndexPath - ) -> ASSizeRange { - let width = layoutContentWidth() - return ASSizeRange( - min: CGSize(width: width, height: 0), - max: CGSize(width: width, height: .greatestFiniteMagnitude) - ) - } - - func collectionNode( - _ collectionNode: ASCollectionNode, - willBeginBatchFetchWith context: ASBatchContext - ) { - context.completeBatchFetching(true) - } - - func shouldBatchFetch(for collectionNode: ASCollectionNode) -> Bool { - return false - } - - func scrollViewDidScroll(_ scrollView: UIScrollView) { - publishScrollInteractionStateIfNeeded() - publishTitlePinStateIfNeeded() - reevaluateVisibleState(forceLoadMoreEvaluation: false) - } - - func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { - publishScrollInteractionStateIfNeeded() - publishTitlePinStateIfNeeded() - if !decelerate { - scheduleDeferredScrollIdleCheck() - reevaluateVisibleState(forceLoadMoreEvaluation: true) - } - } - - func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { - publishScrollInteractionStateIfNeeded() - publishTitlePinStateIfNeeded() - scheduleDeferredScrollIdleCheck() - reevaluateVisibleState(forceLoadMoreEvaluation: true) - } - - func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { - deferredIdleCheckGeneration &+= 1 - publishScrollInteractionStateIfNeeded() - publishTitlePinStateIfNeeded() - } - - func applyItems( - _ items: [FireTopicDetailRuntimeItem], - configuration: FireTopicDetailRuntimeConfiguration - ) { - currentItems = items - currentConfiguration = configuration - cellFactory.configuration = configuration - // Header geometry may change with the new snapshot; re-evaluate pin state - // after the collection settles on the next run loop turn. - DispatchQueue.main.async { [weak self] in - self?.publishTitlePinStateIfNeeded() - } - } - - private func postCallbacks(configuration: FireTopicDetailRuntimeConfiguration) -> FirePostCellCallbacks { - FirePostCellCallbacks( - onLinkTapped: configuration.onLinkTapped, - onOpenProfile: configuration.onOpenProfile, - onOpenImage: configuration.onOpenImage, - onToggleLike: configuration.onToggleLike, - onSelectReaction: configuration.onSelectReaction, - onToggleReactionPicker: configuration.onToggleReactionPicker, - onReplyPost: { post in - configuration.onOpenComposer(post) - }, - onBoostPost: configuration.onBoostPost, - onQuotePost: configuration.onQuotePost, - onEditPost: configuration.onEditPost, - onBookmarkPost: configuration.onBookmarkPost, - onDeletePost: configuration.onDeletePost, - onRecoverPost: configuration.onRecoverPost, - onFlagPost: configuration.onFlagPost, - onOpenReplyTarget: configuration.onOpenPostNumber, - onOpenReplies: configuration.onOpenPostReplies, - onExpandText: configuration.onExpandPostText, - onVotePoll: configuration.onVotePoll, - onUnvotePoll: configuration.onUnvotePoll, - onSwipeReply: { post in - configuration.onOpenComposer(post) - } - ) - } - - private enum FirePostCellApplyMode { - case configure - case bands(Set, relayout: Bool) - } - - private func configurePostCellNode( - _ node: FirePostCellNode, - with context: FireTopicDetailRuntimePostContext, - configuration: FireTopicDetailRuntimeConfiguration - ) { - applyPostCellNode(node, with: context, configuration: configuration, mode: .configure) - } - - private func applyPostCellNode( - _ node: FirePostCellNode, - with context: FireTopicDetailRuntimePostContext, - configuration: FireTopicDetailRuntimeConfiguration, - mode: FirePostCellApplyMode - ) { - let width = layoutContentWidth() - let trait = FirePostLayoutTraitSignature( - contentWidthPixels: Int(width.rounded(.toNearestOrEven)), - contentSizeCategory: UIApplication.shared.preferredContentSizeCategory.rawValue - ) - let layoutKey = makeLayoutKey( - for: context, - canWriteInteractions: configuration.canWriteInteractions, - isReactionPickerExpanded: configuration.isReactionPickerExpanded(context.post.id), - trait: trait - ) - let payload = FirePostCellRenderPayload( - post: context.post, - renderContent: context.renderContent, - baseURLString: configuration.baseURLString, - canWriteInteractions: configuration.canWriteInteractions, - isMutating: configuration.isMutatingPost(context.post.id), - replyContext: context.replyContext, - replyTargetPostNumber: context.replyTargetPostNumber, - replyShortcutCount: context.replyShortcutCount, - isReplyThreadExpanded: context.isReplyThreadExpanded, - isLoadingReplyContext: context.isLoadingReplyContext, - textExpansionState: context.textExpansionState, - isSearchHighlighted: configuration.isSearchHighlighted(postID: context.post.id), - showsDivider: context.showsDivider, - layoutWidth: width, - boostAnimationsEnabled: !isScrollInteractionActive, - isReactionPickerExpanded: configuration.isReactionPickerExpanded(context.post.id), - quickReactionOptions: configuration.quickReactionOptions, - layout: layoutManager?.cachedLayout(forKey: layoutKey), - layoutKey: layoutKey, - appearance: currentAppearanceSnapshot() - ) - let callbacks = postCallbacks(configuration: configuration) - switch mode { - case .configure: - node.configure( - payload: payload, - callbacks: callbacks, - depth: context.depth, - showsThreadLine: context.showsThreadLine, - showsDivider: context.showsDivider - ) - case .bands(let bands, let relayout): - node.applyBands( - bands, - payload: payload, - callbacks: callbacks, - showsThreadLine: context.showsThreadLine, - relayout: relayout - ) - if relayout { - node.invalidateCalculatedLayout() - } - } - } - - private func makeLayoutKey( - for context: FireTopicDetailRuntimePostContext, - canWriteInteractions: Bool, - isReactionPickerExpanded: Bool, - trait: FirePostLayoutTraitSignature - ) -> FirePostCellLayoutKey { - let textContentID = [ - String(context.post.id), - context.renderContent.signature.token, - String(context.textExpansionState.isExpanded), - String(context.textExpansionState.isCollapsible), - ].joined(separator: "\u{1F}") - - let pollSignature = FirePostPollRenderModel.models(from: context.post.polls) - .map(\.signature) - let boostSignature = context.post.boosts.map { boost in - [ - String(boost.id), - boost.user.username, - boost.user.name ?? "", - boost.displayText, - ].joined(separator: "\u{1E}") - } - - return FirePostCellLayoutKey( - postID: context.post.id, - depth: context.depth, - showsThreadLine: context.showsThreadLine, - showsDivider: context.showsDivider, - replyTargetPostNumber: context.replyTargetPostNumber, - replyContext: context.replyContext, - textContentID: textContentID, - imageSignature: context.renderContent.segments.map(\.signatureToken), - pollSignature: pollSignature, - boostSignature: boostSignature, - hasReactions: !context.post.reactions.isEmpty, - replyShortcutCount: context.replyShortcutCount, - isReplyThreadExpanded: context.isReplyThreadExpanded, - showsInlineActions: { - guard context.allowsInlineOverflowActions else { return false } - let post = context.post - return canWriteInteractions && !post.hidden - || post.canEdit - || post.canRecover - || (post.canDelete && !post.hidden) - }(), - primaryActionSlotCount: { - guard context.allowsInlineOverflowActions else { return 0 } - let post = context.post - let canWrite = canWriteInteractions && !post.hidden - var slots = 0 - if canWrite { - slots += 2 // reply + react - if post.canBoost { - slots += 1 - } - } - let hasSecondary = canWrite - || post.canEdit - || post.canRecover - || (post.canDelete && !post.hidden) - if hasSecondary { - slots += 1 // overflow - } - return slots - }(), - isReactionPickerExpanded: isReactionPickerExpanded, - textExpansionState: context.textExpansionState, - acceptedAnswer: context.post.acceptedAnswer, - hasAuthorMetadata: FirePostAuthorMetadataDisplay.hasVisibleMetadata(context.post), - trait: trait - ) - } - - private func replyFooterIndexPath(in items: [FireTopicDetailRuntimeItem]) -> IndexPath? { - guard let index = items.firstIndex(where: { $0.kind == .replyFooter }) else { return nil } - return IndexPath(item: index, section: 0) - } - - private func performPullToRefresh() { - Task { [weak self] in - await self?.onRefresh?() - await MainActor.run { [weak self] in - guard let self else { return } - // Data reload rebuilds Texture nodes; re-assert shell so dark→light - // never leaves a pure-black collection/root after PTR. - self.assertFeedShellAppearance() - self.collectionNode.view.refreshControl?.endRefreshing() - } - } - } - - private static func makeCollectionLayout() -> UICollectionViewFlowLayout { - let flowLayout = UICollectionViewFlowLayout() - flowLayout.minimumLineSpacing = 0 - flowLayout.minimumInteritemSpacing = 0 - flowLayout.estimatedItemSize = .zero - return flowLayout - } - - private func configureTextureRanges() { - collectionNode.leadingScreensForBatching = 1.5 - - var displayTuning = ASRangeTuningParameters() - displayTuning.leadingBufferScreenfuls = 1.0 - displayTuning.trailingBufferScreenfuls = 0.5 - collectionNode.setTuningParameters(displayTuning, for: .display) - - var preloadTuning = ASRangeTuningParameters() - preloadTuning.leadingBufferScreenfuls = 1.5 - preloadTuning.trailingBufferScreenfuls = 1.0 - collectionNode.setTuningParameters(preloadTuning, for: .preload) - } - - private func enqueuePendingCollectionUpdate( - updatePlan: FireTopicDetailCollectionUpdatePlan, - previousItems: [FireTopicDetailRuntimeItem], - nextItems: [FireTopicDetailRuntimeItem], - animated: Bool, - completion: @escaping () -> Void - ) { - pendingCollectionUpdate = PendingCollectionUpdate( - updatePlan: updatePlan, - previousItems: previousItems, - nextItems: nextItems, - animated: animated, - completion: completion - ) - pendingCollectionUpdateAttempts = 0 - schedulePendingCollectionUpdateDrain() - } - - private func schedulePendingCollectionUpdateDrain() { - guard !isPendingCollectionUpdateDrainScheduled else { return } - isPendingCollectionUpdateDrainScheduled = true - DispatchQueue.main.asyncAfter(deadline: .now() + Self.collectionUpdateRetryDelay) { [weak self] in - guard let self else { return } - self.isPendingCollectionUpdateDrainScheduled = false - self.drainPendingCollectionUpdateIfPossible() - } - } - - private func drainPendingCollectionUpdateIfPossible() { - guard let pendingCollectionUpdate else { - pendingCollectionUpdateAttempts = 0 - return - } - - guard collectionNode.isProcessingUpdates == false else { - pendingCollectionUpdateAttempts += 1 - guard pendingCollectionUpdateAttempts < Self.maxPendingCollectionUpdateAttempts else { - self.pendingCollectionUpdate = nil - self.pendingCollectionUpdateAttempts = 0 - reloadDataCompletingOnNextRunLoop(completion: pendingCollectionUpdate.completion) - return - } - schedulePendingCollectionUpdateDrain() - return - } - - self.pendingCollectionUpdate = nil - self.pendingCollectionUpdateAttempts = 0 - applyCollectionUpdate( - updatePlan: pendingCollectionUpdate.updatePlan, - previousItems: pendingCollectionUpdate.previousItems, - nextItems: pendingCollectionUpdate.nextItems, - animated: pendingCollectionUpdate.animated, - completion: pendingCollectionUpdate.completion - ) - } - - private func reevaluateVisibleState(forceLoadMoreEvaluation: Bool) { - visibilityCoordinator?.publishIfChanged(items: currentItems) - if fireTopicDetailShouldEvaluatePagination( - forceLoadMoreEvaluation: forceLoadMoreEvaluation, - isScrollInteractionActive: isScrollInteractionActive - ) { - paginationCoordinator?.loadMoreIfNeeded( - itemCount: currentItems.count, - visibleMaxItem: visibleMaxItem, - forceEvaluation: forceLoadMoreEvaluation - ) - } - if let configuration = currentConfiguration { - prepareLayoutsIfNeeded( - items: currentItems, - configuration: configuration, - pendingScrollTarget: configuration.pendingScrollTarget - ) - } - updateVisibleBoostAnimationState() - } - - private func reloadDataCompletingOnNextRunLoop(completion: @escaping () -> Void) { - let topicId = diagnosticTopicId - diagnosticsLogger?.debug("topic detail feed controller reloadData call start topic_id=\(topicId)") - collectionNode.reloadData() - diagnosticsLogger?.debug("topic detail feed controller reloadData call returned topic_id=\(topicId)") - DispatchQueue.main.async { - completion() - } - } - - private var diagnosticTopicId: UInt64 { - currentConfiguration?.row.topic.id ?? 0 - } - - private func publishScrollInteractionStateIfNeeded() { - let isActive = isScrollInteractionActive - guard lastPublishedScrollInteractionActive != isActive else { return } - lastPublishedScrollInteractionActive = isActive - onScrollInteractionChanged?(isActive) - updateVisibleBoostAnimationState() - } - - private func publishTitlePinStateIfNeeded() { - let pinned = resolveIsTitlePinned() - guard lastPublishedTitlePinned != pinned else { return } - lastPublishedTitlePinned = pinned - onTitlePinStateChanged?(pinned) - } - - private func resolveIsTitlePinned() -> Bool { - let scrollView = collectionNode.view - let visibleTop = scrollView.contentOffset.y + scrollView.adjustedContentInset.top - let headerFrame: CGRect? - if let headerIndex = currentItems.firstIndex(where: { $0.kind == .header }) { - headerFrame = collectionNode.collectionViewLayout - .layoutAttributesForItem(at: IndexPath(item: headerIndex, section: 0))? - .frame - } else { - headerFrame = nil - } - return FireTopicDetailToolbarChromeMetrics.isTitlePinned( - headerFrame: headerFrame, - visibleTop: visibleTop - ) - } - - private func scheduleDeferredScrollIdleCheck() { - deferredIdleCheckGeneration &+= 1 - let generation = deferredIdleCheckGeneration - DispatchQueue.main.async { [weak self] in - guard let self, - self.deferredIdleCheckGeneration == generation else { - return - } - self.publishScrollInteractionStateIfNeeded() - self.publishTitlePinStateIfNeeded() - self.updateVisibleBoostAnimationState() - } - } - - private func updateVisibleBoostAnimationState() { - let enabled = !isScrollInteractionActive - for indexPath in visibleIndexPaths { - guard let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { - continue - } - node.setBoostAnimationsEnabled(enabled) - } - } - - @objc - private func handleBackgroundTap() { - onBackgroundTap?() - } } diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailHeaderCellNode.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailHeaderCellNode.swift new file mode 100644 index 00000000..3976981d --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailHeaderCellNode.swift @@ -0,0 +1,154 @@ +import AsyncDisplayKit +import UIKit + +final class FireTopicDetailHeaderCellNode: ASCellNode { + private let titleNode = ASTextNode() + private let chipNodes: [ASButtonNode] + + init( + configuration: FireTopicDetailRuntimeConfiguration, + appearance: FireAppearanceSnapshot = FireAppearanceEnvironment.snapshot(traits: .current) + ) { + var chips: [ASButtonNode] = [] + let titleInk = appearance.ink + + titleNode.attributedText = NSAttributedString( + string: configuration.displayedTopicTitle, + attributes: [ + .font: FireTopicDetailRuntimeTypography.scaledFont(textStyle: .title3, weight: .bold), + .foregroundColor: titleInk, + ] + ) + titleNode.maximumNumberOfLines = 0 + titleNode.style.flexShrink = 1.0 + // Avoid Texture opaque default fill painting a black title strip on light canvas. + titleNode.isOpaque = false + titleNode.backgroundColor = .clear + titleNode.displaysAsynchronously = false + + if configuration.isPrivateMessageThread { + chips.append(Self.makeChip( + title: "私信", + foregroundColor: FireTopicDetailCellColors.accent, + backgroundColor: FireTopicDetailCellColors.accent.withAlphaComponent(0.12) + )) + + for participant in configuration.displayedParticipants { + let label = (participant.name ?? "").ifEmpty(participant.username ?? "用户 \(participant.userId)") + chips.append(Self.makeChip( + title: "@\(label)", + foregroundColor: FireTopicDetailCellColors.privateMessageForeground, + backgroundColor: FireTopicDetailCellColors.privateMessageForeground.withAlphaComponent(0.12) + )) + } + } else { + if let category = configuration.displayedCategory { + let accent = UIColor(fireHex: category.colorHex) ?? FireTopicDetailCellColors.accent + chips.append(Self.makeChip( + title: category.displayName, + foregroundColor: accent, + backgroundColor: FireTopicDetailCellColors.categoryChipBackground(accent: accent), + action: configuration.viewModel == nil ? nil : { + configuration.onOpenCategory(category) + } + )) + } + + for tagName in configuration.displayedTagNames { + chips.append(Self.makeChip( + title: "#\(tagName)", + foregroundColor: FireTopicDetailCellColors.tagChipForeground, + backgroundColor: FireTopicDetailCellColors.tagChipBackground, + horizontalInset: 6, + verticalInset: 3, + action: configuration.viewModel == nil ? nil : { + configuration.onOpenTag(tagName) + } + )) + } + + for label in configuration.row.statusLabels { + chips.append(Self.makeChip( + title: label, + foregroundColor: FireTopicDetailCellColors.accent, + backgroundColor: FireTopicDetailCellColors.accent.withAlphaComponent(0.12) + )) + } + } + + chipNodes = chips + super.init() + automaticallyManagesSubnodes = true + FireAppearanceTexture.applySnapshot(appearance, to: self) + isAccessibilityElement = true + accessibilityLabel = [configuration.displayedTopicTitle, chips.compactMap(\.accessibilityLabel).joined(separator: ", ")] + .filter { !$0.isEmpty } + .joined(separator: "\n") + } + + override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { + var children: [ASLayoutElement] = [titleNode] + if !chipNodes.isEmpty { + let chipStack = ASStackLayoutSpec( + direction: .horizontal, + spacing: 6, + justifyContent: .start, + alignItems: .start, + children: chipNodes + ) + chipStack.flexWrap = .wrap + chipStack.alignContent = .start + chipStack.lineSpacing = 6 + children.append(chipStack) + } + + let stack = ASStackLayoutSpec( + direction: .vertical, + spacing: 8, + justifyContent: .start, + alignItems: .stretch, + children: children + ) + return ASInsetLayoutSpec( + insets: UIEdgeInsets(top: 16, left: 16, bottom: 0, right: 16), + child: stack + ) + } + + private static func makeChip( + title: String, + foregroundColor: UIColor, + backgroundColor: UIColor, + horizontalInset: CGFloat = 8, + verticalInset: CGFloat = 4, + action: (() -> Void)? = nil + ) -> ASButtonNode { + let node = FireTopicDetailChipButtonNode(action: action) + node.setAttributedTitle( + NSAttributedString( + string: title, + attributes: [ + .font: FireTopicDetailRuntimeTypography.scaledFont(textStyle: .caption2, weight: .medium), + .foregroundColor: foregroundColor, + ] + ), + for: .normal + ) + node.contentEdgeInsets = UIEdgeInsets( + top: verticalInset, + left: horizontalInset, + bottom: verticalInset, + right: horizontalInset + ) + node.backgroundColor = backgroundColor + node.cornerRadius = 12 + node.clipsToBounds = true + node.isEnabled = action != nil + node.accessibilityLabel = title + if action != nil { + node.accessibilityTraits.insert(.button) + } + return node + } +} + diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRepliesHeaderCell.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRepliesHeaderCell.swift new file mode 100644 index 00000000..c9cee930 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRepliesHeaderCell.swift @@ -0,0 +1,70 @@ +import UIKit + +final class FireTopicDetailRepliesHeaderCell: UICollectionViewCell { + static let reuseID = "FireTopicDetailRepliesHeaderCell" + + private let titleLabel = UILabel() + private let countLabel = UILabel() + private let stackView = UIStackView() + + override init(frame: CGRect) { + super.init(frame: frame) + setup() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setup() { + contentView.backgroundColor = FireTheme.uiCanvas + + titleLabel.text = "回复" + titleLabel.font = .preferredFont(forTextStyle: .headline) + titleLabel.adjustsFontForContentSizeCategory = true + titleLabel.textColor = .label + + countLabel.font = .preferredFont(forTextStyle: .subheadline) + countLabel.adjustsFontForContentSizeCategory = true + countLabel.textColor = .secondaryLabel + countLabel.textAlignment = .right + countLabel.setContentCompressionResistancePriority(.required, for: .horizontal) + + stackView.axis = .horizontal + stackView.alignment = .center + stackView.spacing = 12 + stackView.translatesAutoresizingMaskIntoConstraints = false + stackView.addArrangedSubview(titleLabel) + stackView.addArrangedSubview(countLabel) + contentView.addSubview(stackView) + + NSLayoutConstraint.activate([ + stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), + stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), + stackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 18), + stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -14), + ]) + } + + func configure(loadedReplyCount: Int, totalReplyCount: Int, displayedFloorCount: Int, hasDetail: Bool) { + if hasDetail { + if loadedReplyCount < totalReplyCount { + countLabel.text = "已加载 \(loadedReplyCount) / \(totalReplyCount) 条" + } else { + countLabel.text = "\(totalReplyCount) 条 · \(displayedFloorCount) 楼" + } + } else { + countLabel.text = nil + } + accessibilityLabel = [titleLabel.text, countLabel.text] + .compactMap { $0 } + .joined(separator: ",") + } + + override func prepareForReuse() { + super.prepareForReuse() + configure(loadedReplyCount: 0, totalReplyCount: 0, displayedFloorCount: 0, hasDetail: false) + } +} + diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailReplyFooterCell.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailReplyFooterCell.swift new file mode 100644 index 00000000..ab7b905f --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailReplyFooterCell.swift @@ -0,0 +1,134 @@ +import UIKit + +final class FireTopicDetailReplyFooterCell: UICollectionViewCell { + static let reuseID = "FireTopicDetailReplyFooterCell" + + private let label = UILabel() + private let button = UIButton(type: .system) + private let loadingStack = UIStackView() + private let activityIndicator = UIActivityIndicatorView(style: .medium) + private let loadingLabel = UILabel() + private var action: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + setup() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setup() { + contentView.backgroundColor = FireTheme.uiCanvas + + label.font = .preferredFont(forTextStyle: .subheadline) + label.adjustsFontForContentSizeCategory = true + label.textColor = .secondaryLabel + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + + var buttonConfiguration = UIButton.Configuration.plain() + buttonConfiguration.image = UIImage(systemName: "arrow.down.circle") + buttonConfiguration.imagePadding = 6 + buttonConfiguration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16) + button.configuration = buttonConfiguration + button.tintColor = FireTopicDetailCellColors.accent + button.titleLabel?.font = UIFontMetrics(forTextStyle: .subheadline).scaledFont( + for: UIFont.systemFont( + ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, + weight: .semibold + ) + ) + button.titleLabel?.adjustsFontForContentSizeCategory = true + button.translatesAutoresizingMaskIntoConstraints = false + button.addAction(UIAction { [weak self] _ in + self?.action?() + }, for: .touchUpInside) + + loadingLabel.text = "正在加载更多回复..." + loadingLabel.font = .preferredFont(forTextStyle: .subheadline) + loadingLabel.adjustsFontForContentSizeCategory = true + loadingLabel.textColor = .secondaryLabel + loadingStack.axis = .horizontal + loadingStack.alignment = .center + loadingStack.spacing = 8 + loadingStack.translatesAutoresizingMaskIntoConstraints = false + loadingStack.addArrangedSubview(activityIndicator) + loadingStack.addArrangedSubview(loadingLabel) + + contentView.addSubview(label) + contentView.addSubview(button) + contentView.addSubview(loadingStack) + + NSLayoutConstraint.activate([ + label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), + label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), + label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + + button.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor, constant: 16), + button.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor, constant: -16), + button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + button.heightAnchor.constraint(greaterThanOrEqualToConstant: 36), + + loadingStack.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor, constant: 16), + loadingStack.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor, constant: -16), + loadingStack.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + loadingStack.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + ]) + + configure(state: .none, action: nil) + } + + func configure(state: FireTopicDetailRuntimeReplyFooterState, action: (() -> Void)?) { + self.action = action + label.isHidden = true + button.isHidden = true + loadingStack.isHidden = true + activityIndicator.stopAnimating() + accessibilityTraits = [] + + switch state { + case .none: + accessibilityLabel = nil + case .loadMoreAvailable: + var configuration = button.configuration + configuration?.image = UIImage(systemName: "arrow.down.circle") + configuration?.title = "加载更多回复" + button.configuration = configuration + button.isHidden = false + button.isEnabled = action != nil + accessibilityLabel = "加载更多回复" + accessibilityTraits = [.button] + case .emptyPrompt: + label.text = "还没有回复,发表你的看法吧" + label.isHidden = false + accessibilityLabel = label.text + case .endReached: + label.text = "---- 到底了 ----" + label.isHidden = false + accessibilityLabel = label.text + case .loadFailed(_): + var configuration = button.configuration + configuration?.image = UIImage(systemName: "arrow.clockwise.circle") + configuration?.title = "加载更多回复失败,点击重试" + button.configuration = configuration + button.isHidden = false + button.isEnabled = action != nil + accessibilityLabel = "加载更多回复失败,点击重试" + accessibilityTraits = [.button] + case .loadingFooter: + loadingStack.isHidden = false + activityIndicator.startAnimating() + accessibilityLabel = loadingLabel.text + } + } + + override func prepareForReuse() { + super.prepareForReuse() + configure(state: .none, action: nil) + } +} + diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeConfiguration.swift similarity index 52% rename from apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift rename to apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeConfiguration.swift index 545c31a7..f81809b0 100644 --- a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeConfiguration.swift @@ -1,267 +1,6 @@ import Foundation import UIKit -enum FireTopicDetailRuntimeSection: Sendable { - case main -} - -struct FireTopicDetailStatusMessage: Hashable, Sendable { - let title: String? - let message: String - let retryable: Bool - let emphasizesError: Bool -} - -enum FireTopicDetailRuntimeItemKind: Hashable, Sendable { - case header - case aiSummary - case originalPost - case stats - case topicVote - case repliesHeader - case bodyState - case reply - case replyFooter - case notice -} - -struct FireTopicDetailRuntimeItem: Hashable, @unchecked Sendable { - let id: String - let kind: FireTopicDetailRuntimeItemKind - let postID: UInt64? - let postNumber: UInt32? - let replyIndex: Int? - let replyShowsThreadLine: Bool - let replyShowsDivider: Bool - let replyShortcutCount: UInt32? - let isReplyThreadExpanded: Bool - let contentToken: AnyHashable - let inPlaceUpdateToken: AnyHashable? - let messageBands: FireTopicDetailMessageBands? - let statusMessage: FireTopicDetailStatusMessage? - - init( - id: String, - kind: FireTopicDetailRuntimeItemKind, - postID: UInt64?, - postNumber: UInt32?, - replyIndex: Int?, - replyShowsThreadLine: Bool = false, - replyShowsDivider: Bool = false, - replyShortcutCount: UInt32? = nil, - isReplyThreadExpanded: Bool = false, - contentToken: AnyHashable, - inPlaceUpdateToken: AnyHashable? = nil, - messageBands: FireTopicDetailMessageBands? = nil, - statusMessage: FireTopicDetailStatusMessage? = nil - ) { - self.id = id - self.kind = kind - self.postID = postID - self.postNumber = postNumber - self.replyIndex = replyIndex - self.replyShowsThreadLine = replyShowsThreadLine - self.replyShowsDivider = replyShowsDivider - self.replyShortcutCount = replyShortcutCount - self.isReplyThreadExpanded = isReplyThreadExpanded - self.contentToken = contentToken - self.inPlaceUpdateToken = inPlaceUpdateToken - self.messageBands = messageBands - self.statusMessage = statusMessage - } - - /// Identity-only equality for diff planning. Use `hasSameRenderedContent` - /// when comparing what the reader should actually see on screen. - static func == (lhs: Self, rhs: Self) -> Bool { - lhs.id == rhs.id - } - - func hash(into hasher: inout Hasher) { - hasher.combine(id) - } - - func hasSameRenderedContent(as other: Self) -> Bool { - id == other.id - && kind == other.kind - && postID == other.postID - && postNumber == other.postNumber - && replyIndex == other.replyIndex - && replyShowsThreadLine == other.replyShowsThreadLine - && replyShowsDivider == other.replyShowsDivider - && replyShortcutCount == other.replyShortcutCount - && isReplyThreadExpanded == other.isReplyThreadExpanded - && contentToken == other.contentToken - && statusMessage == other.statusMessage - } - - func needsVisibleNodeUpdate(comparedTo other: Self) -> Bool { - hasSameRenderedContent(as: other) - && inPlaceUpdateToken != other.inPlaceUpdateToken - } - - func changedMessageBands(from previous: FireTopicDetailRuntimeItem) -> Set { - guard let messageBands, let previousBands = previous.messageBands else { - return Set(FireTopicDetailMessageBand.allCases) - } - return messageBands.changed(from: previousBands) - } -} - -struct FireTopicDetailRuntimeSnapshot: Sendable { - let items: [FireTopicDetailRuntimeItem] - let replyIndexByPostID: [UInt64: Int] -} - -struct FireTopicDetailRuntimePostContext { - let post: TopicPostState - let renderContent: FireTopicPostRenderContent - let depth: Int - let replyContext: String? - let replyTargetPostNumber: UInt32? - let showsThreadLine: Bool - let showsDivider: Bool - let replyShortcutCount: UInt32? - let isReplyThreadExpanded: Bool - let isLoadingReplyContext: Bool - let textExpansionState: FirePostTextExpansionState - /// Original/main post keeps actions in the nav toolbar; only replies show cell `...`. - let allowsInlineOverflowActions: Bool -} - -struct FireTopicDetailReplyDisplayPlan { - struct DisplayedRow { - let row: FirePreparedTopicTimelineRow - let sourceIndex: Int - let showsThreadLine: Bool - let showsDivider: Bool - let replyShortcutCount: UInt32? - let isReplyThreadExpanded: Bool - } - - let rows: [DisplayedRow] - let sourceIndexByPostID: [UInt64: Int] -} - -struct FireTopicDetailReplyThreadIndex { - let rootIndexBySourceIndex: [Int: Int] - let secondaryIndicesByRoot: [Int: [Int]] -} - -final class FireTopicDetailRuntimeInteractions { - let isMutatingPost: (UInt64) -> Bool - let isPostTextExpanded: (UInt64) -> Bool - let isReplyThreadExpanded: (UInt64) -> Bool - let isLoadingPostReplyContext: (UInt64) -> Bool - let onVisiblePostNumbersChanged: (Set) -> Void - let onRefresh: () async -> Void - let onLoadTopicDetail: () async -> Void - let onScrollTargetHandled: (UInt32) -> Void - let onLoadMoreTopicPosts: () -> Bool - let onReloadTopicAiSummary: () -> Void - let onToggleTopicAiSummaryExpanded: () -> Void - let onOpenComposer: (TopicPostState?) -> Void - let onOpenPostNumber: (UInt32) -> Void - let onOpenPostReplies: (TopicPostState) -> Void - let onLinkTapped: (URL) -> Void - let onOpenProfile: (String) -> Void - let onOpenImage: (FireCookedImage) -> Void - let onToggleLike: (TopicPostState) -> Void - let onSelectReaction: (TopicPostState, String) -> Void - let onToggleReactionPicker: (TopicPostState) -> Void - let onBoostPost: (TopicPostState) -> Void - let quickReactionOptionsProvider: () -> [FireReactionOption] - let isReactionPickerExpanded: (UInt64) -> Bool - let onQuotePost: (TopicPostState) -> Void - let onEditPost: (TopicPostState) -> Void - let onBookmarkPost: (TopicPostState) -> Void - let onDeletePost: (TopicPostState) -> Void - let onRecoverPost: (TopicPostState) -> Void - let onFlagPost: (TopicPostState) -> Void - let onExpandPostText: (TopicPostState) -> Void - let onVotePoll: (TopicPostState, PollState, [String]) -> Void - let onUnvotePoll: (TopicPostState, PollState) -> Void - let onToggleTopicVote: () async -> Void - let onShowTopicVoters: () async -> Void - let onOpenCategory: (FireTopicCategoryPresentation) -> Void - let onOpenTag: (String) -> Void - - init( - isMutatingPost: @escaping (UInt64) -> Bool, - isPostTextExpanded: @escaping (UInt64) -> Bool, - isReplyThreadExpanded: @escaping (UInt64) -> Bool, - isLoadingPostReplyContext: @escaping (UInt64) -> Bool, - onVisiblePostNumbersChanged: @escaping (Set) -> Void, - onRefresh: @escaping () async -> Void, - onLoadTopicDetail: @escaping () async -> Void, - onScrollTargetHandled: @escaping (UInt32) -> Void, - onLoadMoreTopicPosts: @escaping () -> Bool, - onReloadTopicAiSummary: @escaping () -> Void, - onToggleTopicAiSummaryExpanded: @escaping () -> Void, - onOpenComposer: @escaping (TopicPostState?) -> Void, - onOpenPostNumber: @escaping (UInt32) -> Void, - onOpenPostReplies: @escaping (TopicPostState) -> Void, - onLinkTapped: @escaping (URL) -> Void, - onOpenProfile: @escaping (String) -> Void, - onOpenImage: @escaping (FireCookedImage) -> Void, - onToggleLike: @escaping (TopicPostState) -> Void, - onSelectReaction: @escaping (TopicPostState, String) -> Void, - onToggleReactionPicker: @escaping (TopicPostState) -> Void, - onBoostPost: @escaping (TopicPostState) -> Void, - quickReactionOptionsProvider: @escaping () -> [FireReactionOption], - isReactionPickerExpanded: @escaping (UInt64) -> Bool, - onQuotePost: @escaping (TopicPostState) -> Void, - onEditPost: @escaping (TopicPostState) -> Void, - onBookmarkPost: @escaping (TopicPostState) -> Void, - onDeletePost: @escaping (TopicPostState) -> Void, - onRecoverPost: @escaping (TopicPostState) -> Void, - onFlagPost: @escaping (TopicPostState) -> Void, - onExpandPostText: @escaping (TopicPostState) -> Void, - onVotePoll: @escaping (TopicPostState, PollState, [String]) -> Void, - onUnvotePoll: @escaping (TopicPostState, PollState) -> Void, - onToggleTopicVote: @escaping () async -> Void, - onShowTopicVoters: @escaping () async -> Void, - onOpenCategory: @escaping (FireTopicCategoryPresentation) -> Void, - onOpenTag: @escaping (String) -> Void - ) { - self.isMutatingPost = isMutatingPost - self.isPostTextExpanded = isPostTextExpanded - self.isReplyThreadExpanded = isReplyThreadExpanded - self.isLoadingPostReplyContext = isLoadingPostReplyContext - self.onVisiblePostNumbersChanged = onVisiblePostNumbersChanged - self.onRefresh = onRefresh - self.onLoadTopicDetail = onLoadTopicDetail - self.onScrollTargetHandled = onScrollTargetHandled - self.onLoadMoreTopicPosts = onLoadMoreTopicPosts - self.onReloadTopicAiSummary = onReloadTopicAiSummary - self.onToggleTopicAiSummaryExpanded = onToggleTopicAiSummaryExpanded - self.onOpenComposer = onOpenComposer - self.onOpenPostNumber = onOpenPostNumber - self.onOpenPostReplies = onOpenPostReplies - self.onLinkTapped = onLinkTapped - self.onOpenProfile = onOpenProfile - self.onOpenImage = onOpenImage - self.onToggleLike = onToggleLike - self.onSelectReaction = onSelectReaction - self.onToggleReactionPicker = onToggleReactionPicker - self.onBoostPost = onBoostPost - self.quickReactionOptionsProvider = quickReactionOptionsProvider - self.isReactionPickerExpanded = isReactionPickerExpanded - self.onQuotePost = onQuotePost - self.onEditPost = onEditPost - self.onBookmarkPost = onBookmarkPost - self.onDeletePost = onDeletePost - self.onRecoverPost = onRecoverPost - self.onFlagPost = onFlagPost - self.onExpandPostText = onExpandPostText - self.onVotePoll = onVotePoll - self.onUnvotePoll = onUnvotePoll - self.onToggleTopicVote = onToggleTopicVote - self.onShowTopicVoters = onShowTopicVoters - self.onOpenCategory = onOpenCategory - self.onOpenTag = onOpenTag - } -} - struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { let viewModel: FireAppViewModel? let displayedCategory: FireTopicCategoryPresentation? @@ -590,68 +329,3 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { makeSnapshot().items.first { $0.postNumber == postNumber } } } - -enum FireTopicDetailRuntimeReplyFooterState: Equatable { - case none - case loadMoreAvailable - case loadingFooter - case loadFailed(String) - case endReached - case emptyPrompt - - private static let loadFailedPrefix = "loadFailed\u{1F}" - - var contentToken: String { - switch self { - case .none: - return "none" - case .loadMoreAvailable: - return "loadMoreAvailable" - case .loadingFooter: - return "loadingFooter" - case let .loadFailed(message): - return Self.loadFailedPrefix + message - case .endReached: - return "endReached" - case .emptyPrompt: - return "emptyPrompt" - } - } - - var identityToken: String { - switch self { - case .none: - return "none" - case .loadMoreAvailable: - return "loadMoreAvailable" - case .loadingFooter: - return "loadingFooter" - case .loadFailed: - return "loadFailed" - case .endReached: - return "endReached" - case .emptyPrompt: - return "emptyPrompt" - } - } - - static func fromContentToken(_ token: String) -> Self? { - switch token { - case Self.none.contentToken: - return FireTopicDetailRuntimeReplyFooterState.none - case Self.loadMoreAvailable.contentToken: - return .loadMoreAvailable - case Self.loadingFooter.contentToken: - return .loadingFooter - case Self.endReached.contentToken: - return .endReached - case Self.emptyPrompt.contentToken: - return .emptyPrompt - default: - guard token.hasPrefix(Self.loadFailedPrefix) else { - return nil - } - return .loadFailed(String(token.dropFirst(Self.loadFailedPrefix.count))) - } - } -} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeInteractions.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeInteractions.swift new file mode 100644 index 00000000..48f8a034 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeInteractions.swift @@ -0,0 +1,116 @@ +import Foundation + +final class FireTopicDetailRuntimeInteractions { + let isMutatingPost: (UInt64) -> Bool + let isPostTextExpanded: (UInt64) -> Bool + let isReplyThreadExpanded: (UInt64) -> Bool + let isLoadingPostReplyContext: (UInt64) -> Bool + let onVisiblePostNumbersChanged: (Set) -> Void + let onRefresh: () async -> Void + let onLoadTopicDetail: () async -> Void + let onScrollTargetHandled: (UInt32) -> Void + let onLoadMoreTopicPosts: () -> Bool + let onReloadTopicAiSummary: () -> Void + let onToggleTopicAiSummaryExpanded: () -> Void + let onOpenComposer: (TopicPostState?) -> Void + let onOpenPostNumber: (UInt32) -> Void + let onOpenPostReplies: (TopicPostState) -> Void + let onLinkTapped: (URL) -> Void + let onOpenProfile: (String) -> Void + let onOpenImage: (FireCookedImage) -> Void + let onToggleLike: (TopicPostState) -> Void + let onSelectReaction: (TopicPostState, String) -> Void + let onToggleReactionPicker: (TopicPostState) -> Void + let onBoostPost: (TopicPostState) -> Void + let quickReactionOptionsProvider: () -> [FireReactionOption] + let isReactionPickerExpanded: (UInt64) -> Bool + let onQuotePost: (TopicPostState) -> Void + let onEditPost: (TopicPostState) -> Void + let onBookmarkPost: (TopicPostState) -> Void + let onDeletePost: (TopicPostState) -> Void + let onRecoverPost: (TopicPostState) -> Void + let onFlagPost: (TopicPostState) -> Void + let onExpandPostText: (TopicPostState) -> Void + let onVotePoll: (TopicPostState, PollState, [String]) -> Void + let onUnvotePoll: (TopicPostState, PollState) -> Void + let onToggleTopicVote: () async -> Void + let onShowTopicVoters: () async -> Void + let onOpenCategory: (FireTopicCategoryPresentation) -> Void + let onOpenTag: (String) -> Void + + init( + isMutatingPost: @escaping (UInt64) -> Bool, + isPostTextExpanded: @escaping (UInt64) -> Bool, + isReplyThreadExpanded: @escaping (UInt64) -> Bool, + isLoadingPostReplyContext: @escaping (UInt64) -> Bool, + onVisiblePostNumbersChanged: @escaping (Set) -> Void, + onRefresh: @escaping () async -> Void, + onLoadTopicDetail: @escaping () async -> Void, + onScrollTargetHandled: @escaping (UInt32) -> Void, + onLoadMoreTopicPosts: @escaping () -> Bool, + onReloadTopicAiSummary: @escaping () -> Void, + onToggleTopicAiSummaryExpanded: @escaping () -> Void, + onOpenComposer: @escaping (TopicPostState?) -> Void, + onOpenPostNumber: @escaping (UInt32) -> Void, + onOpenPostReplies: @escaping (TopicPostState) -> Void, + onLinkTapped: @escaping (URL) -> Void, + onOpenProfile: @escaping (String) -> Void, + onOpenImage: @escaping (FireCookedImage) -> Void, + onToggleLike: @escaping (TopicPostState) -> Void, + onSelectReaction: @escaping (TopicPostState, String) -> Void, + onToggleReactionPicker: @escaping (TopicPostState) -> Void, + onBoostPost: @escaping (TopicPostState) -> Void, + quickReactionOptionsProvider: @escaping () -> [FireReactionOption], + isReactionPickerExpanded: @escaping (UInt64) -> Bool, + onQuotePost: @escaping (TopicPostState) -> Void, + onEditPost: @escaping (TopicPostState) -> Void, + onBookmarkPost: @escaping (TopicPostState) -> Void, + onDeletePost: @escaping (TopicPostState) -> Void, + onRecoverPost: @escaping (TopicPostState) -> Void, + onFlagPost: @escaping (TopicPostState) -> Void, + onExpandPostText: @escaping (TopicPostState) -> Void, + onVotePoll: @escaping (TopicPostState, PollState, [String]) -> Void, + onUnvotePoll: @escaping (TopicPostState, PollState) -> Void, + onToggleTopicVote: @escaping () async -> Void, + onShowTopicVoters: @escaping () async -> Void, + onOpenCategory: @escaping (FireTopicCategoryPresentation) -> Void, + onOpenTag: @escaping (String) -> Void + ) { + self.isMutatingPost = isMutatingPost + self.isPostTextExpanded = isPostTextExpanded + self.isReplyThreadExpanded = isReplyThreadExpanded + self.isLoadingPostReplyContext = isLoadingPostReplyContext + self.onVisiblePostNumbersChanged = onVisiblePostNumbersChanged + self.onRefresh = onRefresh + self.onLoadTopicDetail = onLoadTopicDetail + self.onScrollTargetHandled = onScrollTargetHandled + self.onLoadMoreTopicPosts = onLoadMoreTopicPosts + self.onReloadTopicAiSummary = onReloadTopicAiSummary + self.onToggleTopicAiSummaryExpanded = onToggleTopicAiSummaryExpanded + self.onOpenComposer = onOpenComposer + self.onOpenPostNumber = onOpenPostNumber + self.onOpenPostReplies = onOpenPostReplies + self.onLinkTapped = onLinkTapped + self.onOpenProfile = onOpenProfile + self.onOpenImage = onOpenImage + self.onToggleLike = onToggleLike + self.onSelectReaction = onSelectReaction + self.onToggleReactionPicker = onToggleReactionPicker + self.onBoostPost = onBoostPost + self.quickReactionOptionsProvider = quickReactionOptionsProvider + self.isReactionPickerExpanded = isReactionPickerExpanded + self.onQuotePost = onQuotePost + self.onEditPost = onEditPost + self.onBookmarkPost = onBookmarkPost + self.onDeletePost = onDeletePost + self.onRecoverPost = onRecoverPost + self.onFlagPost = onFlagPost + self.onExpandPostText = onExpandPostText + self.onVotePoll = onVotePoll + self.onUnvotePoll = onUnvotePoll + self.onToggleTopicVote = onToggleTopicVote + self.onShowTopicVoters = onShowTopicVoters + self.onOpenCategory = onOpenCategory + self.onOpenTag = onOpenTag + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeItem.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeItem.swift new file mode 100644 index 00000000..a9d84bf2 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeItem.swift @@ -0,0 +1,107 @@ +import Foundation + +enum FireTopicDetailRuntimeSection: Sendable { + case main +} + +struct FireTopicDetailStatusMessage: Hashable, Sendable { + let title: String? + let message: String + let retryable: Bool + let emphasizesError: Bool +} + +enum FireTopicDetailRuntimeItemKind: Hashable, Sendable { + case header + case aiSummary + case originalPost + case stats + case topicVote + case repliesHeader + case bodyState + case reply + case replyFooter + case notice +} + +struct FireTopicDetailRuntimeItem: Hashable, @unchecked Sendable { + let id: String + let kind: FireTopicDetailRuntimeItemKind + let postID: UInt64? + let postNumber: UInt32? + let replyIndex: Int? + let replyShowsThreadLine: Bool + let replyShowsDivider: Bool + let replyShortcutCount: UInt32? + let isReplyThreadExpanded: Bool + let contentToken: AnyHashable + let inPlaceUpdateToken: AnyHashable? + let messageBands: FireTopicDetailMessageBands? + let statusMessage: FireTopicDetailStatusMessage? + + init( + id: String, + kind: FireTopicDetailRuntimeItemKind, + postID: UInt64?, + postNumber: UInt32?, + replyIndex: Int?, + replyShowsThreadLine: Bool = false, + replyShowsDivider: Bool = false, + replyShortcutCount: UInt32? = nil, + isReplyThreadExpanded: Bool = false, + contentToken: AnyHashable, + inPlaceUpdateToken: AnyHashable? = nil, + messageBands: FireTopicDetailMessageBands? = nil, + statusMessage: FireTopicDetailStatusMessage? = nil + ) { + self.id = id + self.kind = kind + self.postID = postID + self.postNumber = postNumber + self.replyIndex = replyIndex + self.replyShowsThreadLine = replyShowsThreadLine + self.replyShowsDivider = replyShowsDivider + self.replyShortcutCount = replyShortcutCount + self.isReplyThreadExpanded = isReplyThreadExpanded + self.contentToken = contentToken + self.inPlaceUpdateToken = inPlaceUpdateToken + self.messageBands = messageBands + self.statusMessage = statusMessage + } + + /// Identity-only equality for diff planning. Use `hasSameRenderedContent` + /// when comparing what the reader should actually see on screen. + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.id == rhs.id + } + + func hash(into hasher: inout Hasher) { + hasher.combine(id) + } + + func hasSameRenderedContent(as other: Self) -> Bool { + id == other.id + && kind == other.kind + && postID == other.postID + && postNumber == other.postNumber + && replyIndex == other.replyIndex + && replyShowsThreadLine == other.replyShowsThreadLine + && replyShowsDivider == other.replyShowsDivider + && replyShortcutCount == other.replyShortcutCount + && isReplyThreadExpanded == other.isReplyThreadExpanded + && contentToken == other.contentToken + && statusMessage == other.statusMessage + } + + func needsVisibleNodeUpdate(comparedTo other: Self) -> Bool { + hasSameRenderedContent(as: other) + && inPlaceUpdateToken != other.inPlaceUpdateToken + } + + func changedMessageBands(from previous: FireTopicDetailRuntimeItem) -> Set { + guard let messageBands, let previousBands = previous.messageBands else { + return Set(FireTopicDetailMessageBand.allCases) + } + return messageBands.changed(from: previousBands) + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeReplyFooterState.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeReplyFooterState.swift new file mode 100644 index 00000000..7a416b27 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeReplyFooterState.swift @@ -0,0 +1,66 @@ +import Foundation + +enum FireTopicDetailRuntimeReplyFooterState: Equatable { + case none + case loadMoreAvailable + case loadingFooter + case loadFailed(String) + case endReached + case emptyPrompt + + private static let loadFailedPrefix = "loadFailed\u{1F}" + + var contentToken: String { + switch self { + case .none: + return "none" + case .loadMoreAvailable: + return "loadMoreAvailable" + case .loadingFooter: + return "loadingFooter" + case let .loadFailed(message): + return Self.loadFailedPrefix + message + case .endReached: + return "endReached" + case .emptyPrompt: + return "emptyPrompt" + } + } + + var identityToken: String { + switch self { + case .none: + return "none" + case .loadMoreAvailable: + return "loadMoreAvailable" + case .loadingFooter: + return "loadingFooter" + case .loadFailed: + return "loadFailed" + case .endReached: + return "endReached" + case .emptyPrompt: + return "emptyPrompt" + } + } + + static func fromContentToken(_ token: String) -> Self? { + switch token { + case Self.none.contentToken: + return FireTopicDetailRuntimeReplyFooterState.none + case Self.loadMoreAvailable.contentToken: + return .loadMoreAvailable + case Self.loadingFooter.contentToken: + return .loadingFooter + case Self.endReached.contentToken: + return .endReached + case Self.emptyPrompt.contentToken: + return .emptyPrompt + default: + guard token.hasPrefix(Self.loadFailedPrefix) else { + return nil + } + return .loadFailed(String(token.dropFirst(Self.loadFailedPrefix.count))) + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshot.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshot.swift new file mode 100644 index 00000000..b2c75a62 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshot.swift @@ -0,0 +1,41 @@ +import Foundation + +struct FireTopicDetailRuntimeSnapshot: Sendable { + let items: [FireTopicDetailRuntimeItem] + let replyIndexByPostID: [UInt64: Int] +} + +struct FireTopicDetailRuntimePostContext { + let post: TopicPostState + let renderContent: FireTopicPostRenderContent + let depth: Int + let replyContext: String? + let replyTargetPostNumber: UInt32? + let showsThreadLine: Bool + let showsDivider: Bool + let replyShortcutCount: UInt32? + let isReplyThreadExpanded: Bool + let isLoadingReplyContext: Bool + let textExpansionState: FirePostTextExpansionState + /// Original/main post keeps actions in the nav toolbar; only replies show cell `...`. + let allowsInlineOverflowActions: Bool +} + +struct FireTopicDetailReplyDisplayPlan { + struct DisplayedRow { + let row: FirePreparedTopicTimelineRow + let sourceIndex: Int + let showsThreadLine: Bool + let showsDivider: Bool + let replyShortcutCount: UInt32? + let isReplyThreadExpanded: Bool + } + + let rows: [DisplayedRow] + let sourceIndexByPostID: [UInt64: Int] +} + +struct FireTopicDetailReplyThreadIndex { + let rootIndexBySourceIndex: [Int: Int] + let secondaryIndicesByRoot: [Int: [Int]] +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailStatsCell.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailStatsCell.swift new file mode 100644 index 00000000..cb16a870 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailStatsCell.swift @@ -0,0 +1,111 @@ +import UIKit + +final class FireTopicDetailStatsCell: UICollectionViewCell { + static let reuseID = "FireTopicDetailStatsCell" + + private let dividerView = UIView() + private let stackView = UIStackView() + private let replyStat = FireTopicDetailStatView() + private let viewStat = FireTopicDetailStatView() + private let interactionStat = FireTopicDetailStatView() + + override init(frame: CGRect) { + super.init(frame: frame) + setup() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setup() { + contentView.backgroundColor = FireTheme.uiCanvas + dividerView.backgroundColor = .separator + dividerView.translatesAutoresizingMaskIntoConstraints = false + + stackView.axis = .horizontal + stackView.alignment = .center + stackView.distribution = .fillEqually + stackView.spacing = 20 + stackView.translatesAutoresizingMaskIntoConstraints = false + stackView.addArrangedSubview(replyStat) + stackView.addArrangedSubview(viewStat) + stackView.addArrangedSubview(interactionStat) + + contentView.addSubview(dividerView) + contentView.addSubview(stackView) + + NSLayoutConstraint.activate([ + dividerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), + dividerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), + dividerView.topAnchor.constraint(equalTo: contentView.topAnchor), + dividerView.heightAnchor.constraint(equalToConstant: 0.5), + + stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), + stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), + stackView.topAnchor.constraint(equalTo: dividerView.bottomAnchor, constant: 12), + stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8), + ]) + } + + func configure(replyCount: UInt32, viewCount: UInt32, interactionCount: UInt32?) { + replyStat.configure(value: "\(replyCount)", label: "回复") + viewStat.configure(value: "\(viewCount)", label: "浏览") + interactionStat.configure(value: interactionCount.map(String.init) ?? "...", label: "互动") + accessibilityLabel = "\(replyCount) 回复,\(viewCount) 浏览" + } +} + +final class FireTopicDetailStatView: UIView { + private let valueLabel = UILabel() + private let titleLabel = UILabel() + private let stackView = UIStackView() + + override init(frame: CGRect) { + super.init(frame: frame) + setup() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setup() { + valueLabel.font = UIFontMetrics(forTextStyle: .subheadline).scaledFont( + for: UIFont.monospacedDigitSystemFont( + ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, + weight: .semibold + ) + ) + valueLabel.adjustsFontForContentSizeCategory = true + valueLabel.textColor = .label + valueLabel.textAlignment = .center + + titleLabel.font = .preferredFont(forTextStyle: .caption2) + titleLabel.adjustsFontForContentSizeCategory = true + titleLabel.textColor = .secondaryLabel + titleLabel.textAlignment = .center + + stackView.axis = .vertical + stackView.alignment = .fill + stackView.spacing = 2 + stackView.translatesAutoresizingMaskIntoConstraints = false + stackView.addArrangedSubview(valueLabel) + stackView.addArrangedSubview(titleLabel) + addSubview(stackView) + + NSLayoutConstraint.activate([ + stackView.leadingAnchor.constraint(equalTo: leadingAnchor), + stackView.trailingAnchor.constraint(equalTo: trailingAnchor), + stackView.topAnchor.constraint(equalTo: topAnchor), + stackView.bottomAnchor.constraint(equalTo: bottomAnchor), + ]) + } + + func configure(value: String, label: String) { + valueLabel.text = value + titleLabel.text = label + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailTextCell.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailTextCell.swift new file mode 100644 index 00000000..bd301007 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailTextCell.swift @@ -0,0 +1,64 @@ +import UIKit + +final class FireTopicDetailTextCell: UICollectionViewCell { + static let reuseID = "FireTopicDetailTextCell" + + private let titleLabel = UILabel() + private let bodyLabel = UILabel() + private let stackView = UIStackView() + + override init(frame: CGRect) { + super.init(frame: frame) + setup() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setup() { + contentView.backgroundColor = FireTheme.uiCanvas + stackView.axis = .vertical + stackView.alignment = .fill + stackView.spacing = 6 + stackView.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = .preferredFont(forTextStyle: .headline) + titleLabel.adjustsFontForContentSizeCategory = true + titleLabel.numberOfLines = 0 + titleLabel.textColor = .label + + bodyLabel.font = .preferredFont(forTextStyle: .subheadline) + bodyLabel.adjustsFontForContentSizeCategory = true + bodyLabel.numberOfLines = 0 + bodyLabel.textColor = .secondaryLabel + + stackView.addArrangedSubview(titleLabel) + stackView.addArrangedSubview(bodyLabel) + contentView.addSubview(stackView) + + NSLayoutConstraint.activate([ + stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), + stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), + stackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10), + stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10), + ]) + } + + func configure(title: String?, body: String?) { + titleLabel.text = title + titleLabel.isHidden = (title ?? "").isEmpty + bodyLabel.text = body + bodyLabel.isHidden = (body ?? "").isEmpty + accessibilityLabel = [title, body] + .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + .joined(separator: "\n") + } + + override func prepareForReuse() { + super.prepareForReuse() + configure(title: nil, body: nil) + } +} diff --git a/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailTopicVoteCell.swift b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailTopicVoteCell.swift new file mode 100644 index 00000000..4f0478c8 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Feed/FireTopicDetailTopicVoteCell.swift @@ -0,0 +1,154 @@ +import UIKit + +final class FireTopicDetailTopicVoteCell: UICollectionViewCell { + static let reuseID = "FireTopicDetailTopicVoteCell" + + private let containerView = UIView() + private let titleLabel = UILabel() + private let statusLabel = UILabel() + private let toggleButton = UIButton(type: .system) + private let votersButton = UIButton(type: .system) + private let headerStack = UIStackView() + private let buttonStack = UIStackView() + private let rootStack = UIStackView() + private var toggleAction: (() -> Void)? + private var votersAction: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + setup() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setup() { + contentView.backgroundColor = FireTheme.uiCanvas + + containerView.backgroundColor = .secondarySystemBackground + containerView.layer.cornerRadius = 8 + containerView.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = UIFontMetrics(forTextStyle: .subheadline).scaledFont( + for: UIFont.systemFont( + ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize, + weight: .semibold + ) + ) + titleLabel.adjustsFontForContentSizeCategory = true + titleLabel.textColor = FireTopicDetailCellColors.accent + + statusLabel.font = UIFontMetrics(forTextStyle: .caption1).scaledFont( + for: UIFont.systemFont( + ofSize: UIFont.preferredFont(forTextStyle: .caption1).pointSize, + weight: .semibold + ) + ) + statusLabel.adjustsFontForContentSizeCategory = true + statusLabel.textColor = .systemGreen + statusLabel.setContentHuggingPriority(.required, for: .horizontal) + + headerStack.axis = .horizontal + headerStack.alignment = .center + headerStack.spacing = 10 + headerStack.addArrangedSubview(titleLabel) + headerStack.addArrangedSubview(UIView()) + headerStack.addArrangedSubview(statusLabel) + + configureToggleButtonStyle() + configureVotersButtonStyle() + + toggleButton.addAction(UIAction { [weak self] _ in + self?.toggleAction?() + }, for: .touchUpInside) + votersButton.addAction(UIAction { [weak self] _ in + self?.votersAction?() + }, for: .touchUpInside) + + buttonStack.axis = .horizontal + buttonStack.alignment = .center + buttonStack.spacing = 10 + buttonStack.addArrangedSubview(toggleButton) + buttonStack.addArrangedSubview(votersButton) + buttonStack.addArrangedSubview(UIView()) + + rootStack.axis = .vertical + rootStack.alignment = .fill + rootStack.spacing = 10 + rootStack.translatesAutoresizingMaskIntoConstraints = false + rootStack.addArrangedSubview(headerStack) + rootStack.addArrangedSubview(buttonStack) + + contentView.addSubview(containerView) + containerView.addSubview(rootStack) + + NSLayoutConstraint.activate([ + containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), + containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), + containerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), + containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4), + + rootStack.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 14), + rootStack.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -14), + rootStack.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 14), + rootStack.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -14), + ]) + } + + private func configureToggleButtonStyle() { + var configuration = UIButton.Configuration.filled() + configuration.cornerStyle = .capsule + configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14) + toggleButton.configuration = configuration + toggleButton.titleLabel?.adjustsFontForContentSizeCategory = true + } + + private func configureVotersButtonStyle() { + var configuration = UIButton.Configuration.plain() + configuration.image = UIImage(systemName: "person.3") + configuration.imagePadding = 6 + configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8) + votersButton.configuration = configuration + votersButton.tintColor = FireTopicDetailCellColors.accent + votersButton.titleLabel?.adjustsFontForContentSizeCategory = true + } + + func configure( + detail: TopicDetailState, + canWriteInteractions: Bool, + onToggle: (() -> Void)?, + onShowVoters: (() -> Void)? + ) { + titleLabel.text = "\(detail.voteCount) 票" + statusLabel.text = detail.userVoted ? "你已投票" : nil + statusLabel.isHidden = !detail.userVoted + + var toggleConfiguration = toggleButton.configuration + toggleConfiguration?.title = detail.userVoted ? "取消投票" : "投一票" + toggleConfiguration?.baseBackgroundColor = detail.userVoted + ? .tertiarySystemFill + : FireTopicDetailCellColors.accent + toggleConfiguration?.baseForegroundColor = detail.userVoted ? .label : .white + toggleButton.configuration = toggleConfiguration + toggleButton.isEnabled = canWriteInteractions + + var votersConfiguration = votersButton.configuration + votersConfiguration?.title = "查看投票用户" + votersButton.configuration = votersConfiguration + + toggleAction = onToggle + votersAction = onShowVoters + accessibilityLabel = "\(detail.voteCount) 票" + (detail.userVoted ? ",你已投票" : "") + } + + override func prepareForReuse() { + super.prepareForReuse() + toggleAction = nil + votersAction = nil + statusLabel.text = nil + statusLabel.isHidden = true + } +} + diff --git a/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarNode.swift b/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarNode.swift index b731d022..c2724a82 100644 --- a/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarNode.swift +++ b/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarNode.swift @@ -43,41 +43,22 @@ final class FireTopicQuickReplyBarView: UIView { } /// Preferred height for Auto Layout height constraint (includes bottom padding). - func preferredHeight(forWidth width: CGFloat) -> CGFloat { - guard !isHidden else { return 0 } - if bounds.width > 1 { - layoutIfNeeded() - let measured = backgroundFill.systemLayoutSizeFitting( - CGSize(width: max(width, 1), height: UIView.layoutFittingCompressedSize.height), - withHorizontalFittingPriority: .required, - verticalFittingPriority: .fittingSizeLevel - ).height - if measured > 1 { - return ceil(measured) - } - } - return Self.estimatedHeight( - state: currentState, - width: max(width, 1), - bottomInset: bottomInset - ) - } - - private let backgroundFill = UIView() - private let topBorderView = UIView() - private let contentStack = UIStackView() - private let topStack = UIStackView() - private let typingLabel = UILabel() - private let targetRow = UIStackView() - private let targetLabel = UILabel() - private let clearTargetButton = UIButton(type: .system) - private let inputBar = FireBottomInputBar(kind: .topicQuickReply) - private let messageLabel = UILabel() - private var applyingState = false - private var contentStackBottomConstraint: NSLayoutConstraint? - private var bottomInset: CGFloat = 0 - private var currentState = FireTopicDetailQuickReplyState( + let backgroundFill = UIView() + let topBorderView = UIView() + let contentStack = UIStackView() + let topStack = UIStackView() + let typingLabel = UILabel() + let targetRow = UIStackView() + let targetLabel = UILabel() + let clearTargetButton = UIButton(type: .system) + let inputBar = FireBottomInputBar(kind: .topicQuickReply) + let messageLabel = UILabel() + + var applyingState = false + var contentStackBottomConstraint: NSLayoutConstraint? + var bottomInset: CGFloat = 0 + var currentState = FireTopicDetailQuickReplyState( isVisible: false, typingSummary: nil, targetSummary: nil, @@ -173,214 +154,9 @@ final class FireTopicQuickReplyBarView: UIView { func insertImage(_ image: UIImage) { inputBar.insertImage(image) } - - /// Home-indicator / keyboard-adjacent padding under the input row. - func updateBottomInset(_ inset: CGFloat) { - let target = max(inset, 0) - guard abs(bottomInset - target) > 0.5 else { return } - bottomInset = target - contentStackBottomConstraint?.constant = -(10 + bottomInset) - invalidateIntrinsicContentSize() - setNeedsLayout() - } - - /// Deterministic height used by tests and intrinsic content size fallback. - static func estimatedHeight( - state: FireTopicDetailQuickReplyState, - width: CGFloat, - bottomInset: CGFloat - ) -> CGFloat { - guard state.isVisible else { return 0 } - let contentWidth = max(width - 24, 1) - var height: CGFloat = 10 + 10 + max(bottomInset, 0) - height += FireBottomInputBar.estimatedWrappedHeight(text: state.draft, width: contentWidth) - - let caption1LineHeight = ceil(UIFont.preferredFont(forTextStyle: .caption1).lineHeight) - var topStackHeight: CGFloat = 0 - if !(state.typingSummary?.isEmpty ?? true) { - topStackHeight += caption1LineHeight - } - if !(state.targetSummary?.isEmpty ?? true) { - if topStackHeight > 0 { - topStackHeight += 8 - } - topStackHeight += max(caption1LineHeight, 18) - } - if topStackHeight > 0 { - height += topStackHeight + 8 - } - - if let message = state.validationMessage, !message.isEmpty { - let font = UIFont.preferredFont(forTextStyle: .caption2) - let messageBounds = (message as NSString).boundingRect( - with: CGSize(width: contentWidth, height: .greatestFiniteMagnitude), - options: [.usesLineFragmentOrigin, .usesFontLeading], - attributes: [.font: font], - context: nil - ) - height += 8 + ceil(messageBounds.height) - } - - return ceil(height) - } - - // MARK: - Actions - - @objc private func handleClearTarget() { - callbacks?.onClearTarget() - inputBar.resignInputFocus() - callbacks?.onFocusChanged(false) - } - - // MARK: - Private - - private func bindInputBarCallbacks() { - inputBar.callbacks = .init( - onTextChanged: { [weak self] text in - guard let self, !self.applyingState else { return } - self.callbacks?.onDraftChanged(text) - }, - onSend: { [weak self] payload in - self?.callbacks?.onSubmit(payload) - }, - onLeadingAction: { [weak self] in - self?.callbacks?.onOpenAdvancedComposer() - }, - onFocusChanged: { [weak self] focused in - self?.callbacks?.onFocusChanged(focused) - }, - onHeightChanged: { [weak self] _ in - guard let self else { return } - self.invalidateIntrinsicContentSize() - self.callbacks?.onHeightChanged() - }, - onSearchMentions: { [weak self] term in - await self?.callbacks?.onSearchMentions(term) ?? [] - }, - onPickImage: { [weak self] in - self?.callbacks?.onPickImage() - } - ) - } - - private func setupView() { - // Fully opaque canvas — never translucent chrome over scrolling feed text. - let canvas = FireTheme.uiCanvas.resolvedColor(with: traitCollection) - isOpaque = true - backgroundColor = canvas - clipsToBounds = true - tintColor = FireTheme.uiAccent - - backgroundFill.translatesAutoresizingMaskIntoConstraints = false - backgroundFill.isOpaque = true - backgroundFill.backgroundColor = canvas - addSubview(backgroundFill) - - topBorderView.translatesAutoresizingMaskIntoConstraints = false - topBorderView.backgroundColor = FireTheme.uiDivider - backgroundFill.addSubview(topBorderView) - - contentStack.axis = .vertical - contentStack.spacing = 8 - contentStack.translatesAutoresizingMaskIntoConstraints = false - backgroundFill.addSubview(contentStack) - - topStack.axis = .vertical - topStack.spacing = 8 - - typingLabel.font = UIFont.preferredFont(forTextStyle: .caption1) - typingLabel.textColor = FireTheme.uiSubtleInk - typingLabel.numberOfLines = 1 - - targetRow.axis = .horizontal - targetRow.spacing = 8 - targetRow.alignment = .center - - targetLabel.font = UIFont.preferredFont(forTextStyle: .caption1) - targetLabel.textColor = FireTheme.uiAccent - targetLabel.numberOfLines = 1 - - var clearConfig = UIButton.Configuration.plain() - clearConfig.image = UIImage(systemName: "xmark.circle.fill") - clearConfig.contentInsets = .zero - clearConfig.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration( - pointSize: 18, - weight: .regular - ) - clearTargetButton.configuration = clearConfig - clearTargetButton.tintColor = FireTheme.uiTertiaryInk - clearTargetButton.accessibilityLabel = "取消目标" - clearTargetButton.addTarget(self, action: #selector(handleClearTarget), for: .touchUpInside) - clearTargetButton.setContentHuggingPriority(.required, for: .horizontal) - clearTargetButton.setContentCompressionResistancePriority(.required, for: .horizontal) - clearTargetButton.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - clearTargetButton.widthAnchor.constraint(equalToConstant: 28), - clearTargetButton.heightAnchor.constraint(equalToConstant: 28), - ]) - - let targetSpacer = UIView() - targetSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) - targetSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - targetRow.addArrangedSubview(targetLabel) - targetRow.addArrangedSubview(targetSpacer) - targetRow.addArrangedSubview(clearTargetButton) - - topStack.addArrangedSubview(typingLabel) - topStack.addArrangedSubview(targetRow) - contentStack.addArrangedSubview(topStack) - contentStack.addArrangedSubview(inputBar) - - messageLabel.font = UIFont.preferredFont(forTextStyle: .caption2) - messageLabel.numberOfLines = 0 - messageLabel.isHidden = true - contentStack.addArrangedSubview(messageLabel) - - let bottomConstraint = contentStack.bottomAnchor.constraint( - equalTo: backgroundFill.bottomAnchor, - constant: -10 - ) - contentStackBottomConstraint = bottomConstraint - - NSLayoutConstraint.activate([ - backgroundFill.leadingAnchor.constraint(equalTo: leadingAnchor), - backgroundFill.trailingAnchor.constraint(equalTo: trailingAnchor), - backgroundFill.topAnchor.constraint(equalTo: topAnchor), - backgroundFill.bottomAnchor.constraint(equalTo: bottomAnchor), - - topBorderView.leadingAnchor.constraint(equalTo: backgroundFill.leadingAnchor), - topBorderView.trailingAnchor.constraint(equalTo: backgroundFill.trailingAnchor), - topBorderView.topAnchor.constraint(equalTo: backgroundFill.topAnchor), - topBorderView.heightAnchor.constraint(equalToConstant: 1.0 / UIScreen.main.scale), - - contentStack.leadingAnchor.constraint(equalTo: backgroundFill.leadingAnchor, constant: 12), - contentStack.trailingAnchor.constraint(equalTo: backgroundFill.trailingAnchor, constant: -12), - contentStack.topAnchor.constraint(equalTo: backgroundFill.topAnchor, constant: 10), - bottomConstraint, - ]) - - isHidden = true - } - - override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { - super.traitCollectionDidChange(previousTraitCollection) - guard traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else { - return - } - applyThemeColorsIfNeeded() - } - - /// Re-resolve opaque canvas colors after appearance preference changes. - func applyThemeColorsIfNeeded() { - let canvas = FireTheme.uiCanvas.resolvedColor(with: traitCollection) - backgroundColor = canvas - backgroundFill.backgroundColor = canvas - topBorderView.backgroundColor = FireTheme.uiDivider - tintColor = FireTheme.uiAccent - inputBar.applyThemeColorsIfNeeded() - } } + // MARK: - Compatibility alias for older call sites / docs typealias FireTopicQuickReplyBarNode = FireTopicQuickReplyBarView diff --git a/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Appearance.swift b/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Appearance.swift new file mode 100644 index 00000000..63c761fa --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Appearance.swift @@ -0,0 +1,23 @@ +import UIKit + +@MainActor +extension FireTopicQuickReplyBarView { + + override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { + super.traitCollectionDidChange(previousTraitCollection) + guard traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else { + return + } + applyThemeColorsIfNeeded() + } + + /// Re-resolve opaque canvas colors after appearance preference changes. + func applyThemeColorsIfNeeded() { + let canvas = FireTheme.uiCanvas.resolvedColor(with: traitCollection) + backgroundColor = canvas + backgroundFill.backgroundColor = canvas + topBorderView.backgroundColor = FireTheme.uiDivider + tintColor = FireTheme.uiAccent + inputBar.applyThemeColorsIfNeeded() + } +} diff --git a/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Callbacks.swift b/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Callbacks.swift new file mode 100644 index 00000000..9ee975bf --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Callbacks.swift @@ -0,0 +1,43 @@ +import UIKit + +@MainActor +extension FireTopicQuickReplyBarView { + // MARK: - Actions + + @objc func handleClearTarget() { + callbacks?.onClearTarget() + inputBar.resignInputFocus() + callbacks?.onFocusChanged(false) + } + + // MARK: - Private + + func bindInputBarCallbacks() { + inputBar.callbacks = .init( + onTextChanged: { [weak self] text in + guard let self, !self.applyingState else { return } + self.callbacks?.onDraftChanged(text) + }, + onSend: { [weak self] payload in + self?.callbacks?.onSubmit(payload) + }, + onLeadingAction: { [weak self] in + self?.callbacks?.onOpenAdvancedComposer() + }, + onFocusChanged: { [weak self] focused in + self?.callbacks?.onFocusChanged(focused) + }, + onHeightChanged: { [weak self] _ in + guard let self else { return } + self.invalidateIntrinsicContentSize() + self.callbacks?.onHeightChanged() + }, + onSearchMentions: { [weak self] term in + await self?.callbacks?.onSearchMentions(term) ?? [] + }, + onPickImage: { [weak self] in + self?.callbacks?.onPickImage() + } + ) + } +} diff --git a/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Layout.swift b/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Layout.swift new file mode 100644 index 00000000..6c8b4a32 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarView+Layout.swift @@ -0,0 +1,174 @@ +import UIKit + +@MainActor +extension FireTopicQuickReplyBarView { + func preferredHeight(forWidth width: CGFloat) -> CGFloat { + guard !isHidden else { return 0 } + if bounds.width > 1 { + layoutIfNeeded() + let measured = backgroundFill.systemLayoutSizeFitting( + CGSize(width: max(width, 1), height: UIView.layoutFittingCompressedSize.height), + withHorizontalFittingPriority: .required, + verticalFittingPriority: .fittingSizeLevel + ).height + if measured > 1 { + return ceil(measured) + } + } + return Self.estimatedHeight( + state: currentState, + width: max(width, 1), + bottomInset: bottomInset + ) + } + + /// Home-indicator / keyboard-adjacent padding under the input row. + func updateBottomInset(_ inset: CGFloat) { + let target = max(inset, 0) + guard abs(bottomInset - target) > 0.5 else { return } + bottomInset = target + contentStackBottomConstraint?.constant = -(10 + bottomInset) + invalidateIntrinsicContentSize() + setNeedsLayout() + } + + /// Deterministic height used by tests and intrinsic content size fallback. + static func estimatedHeight( + state: FireTopicDetailQuickReplyState, + width: CGFloat, + bottomInset: CGFloat + ) -> CGFloat { + guard state.isVisible else { return 0 } + let contentWidth = max(width - 24, 1) + var height: CGFloat = 10 + 10 + max(bottomInset, 0) + height += FireBottomInputBar.estimatedWrappedHeight(text: state.draft, width: contentWidth) + + let caption1LineHeight = ceil(UIFont.preferredFont(forTextStyle: .caption1).lineHeight) + var topStackHeight: CGFloat = 0 + if !(state.typingSummary?.isEmpty ?? true) { + topStackHeight += caption1LineHeight + } + if !(state.targetSummary?.isEmpty ?? true) { + if topStackHeight > 0 { + topStackHeight += 8 + } + topStackHeight += max(caption1LineHeight, 18) + } + if topStackHeight > 0 { + height += topStackHeight + 8 + } + + if let message = state.validationMessage, !message.isEmpty { + let font = UIFont.preferredFont(forTextStyle: .caption2) + let messageBounds = (message as NSString).boundingRect( + with: CGSize(width: contentWidth, height: .greatestFiniteMagnitude), + options: [.usesLineFragmentOrigin, .usesFontLeading], + attributes: [.font: font], + context: nil + ) + height += 8 + ceil(messageBounds.height) + } + + return ceil(height) + } + + + func setupView() { + // Fully opaque canvas — never translucent chrome over scrolling feed text. + let canvas = FireTheme.uiCanvas.resolvedColor(with: traitCollection) + isOpaque = true + backgroundColor = canvas + clipsToBounds = true + tintColor = FireTheme.uiAccent + + backgroundFill.translatesAutoresizingMaskIntoConstraints = false + backgroundFill.isOpaque = true + backgroundFill.backgroundColor = canvas + addSubview(backgroundFill) + + topBorderView.translatesAutoresizingMaskIntoConstraints = false + topBorderView.backgroundColor = FireTheme.uiDivider + backgroundFill.addSubview(topBorderView) + + contentStack.axis = .vertical + contentStack.spacing = 8 + contentStack.translatesAutoresizingMaskIntoConstraints = false + backgroundFill.addSubview(contentStack) + + topStack.axis = .vertical + topStack.spacing = 8 + + typingLabel.font = UIFont.preferredFont(forTextStyle: .caption1) + typingLabel.textColor = FireTheme.uiSubtleInk + typingLabel.numberOfLines = 1 + + targetRow.axis = .horizontal + targetRow.spacing = 8 + targetRow.alignment = .center + + targetLabel.font = UIFont.preferredFont(forTextStyle: .caption1) + targetLabel.textColor = FireTheme.uiAccent + targetLabel.numberOfLines = 1 + + var clearConfig = UIButton.Configuration.plain() + clearConfig.image = UIImage(systemName: "xmark.circle.fill") + clearConfig.contentInsets = .zero + clearConfig.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration( + pointSize: 18, + weight: .regular + ) + clearTargetButton.configuration = clearConfig + clearTargetButton.tintColor = FireTheme.uiTertiaryInk + clearTargetButton.accessibilityLabel = "取消目标" + clearTargetButton.addTarget(self, action: #selector(handleClearTarget), for: .touchUpInside) + clearTargetButton.setContentHuggingPriority(.required, for: .horizontal) + clearTargetButton.setContentCompressionResistancePriority(.required, for: .horizontal) + clearTargetButton.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + clearTargetButton.widthAnchor.constraint(equalToConstant: 28), + clearTargetButton.heightAnchor.constraint(equalToConstant: 28), + ]) + + let targetSpacer = UIView() + targetSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) + targetSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + targetRow.addArrangedSubview(targetLabel) + targetRow.addArrangedSubview(targetSpacer) + targetRow.addArrangedSubview(clearTargetButton) + + topStack.addArrangedSubview(typingLabel) + topStack.addArrangedSubview(targetRow) + contentStack.addArrangedSubview(topStack) + contentStack.addArrangedSubview(inputBar) + + messageLabel.font = UIFont.preferredFont(forTextStyle: .caption2) + messageLabel.numberOfLines = 0 + messageLabel.isHidden = true + contentStack.addArrangedSubview(messageLabel) + + let bottomConstraint = contentStack.bottomAnchor.constraint( + equalTo: backgroundFill.bottomAnchor, + constant: -10 + ) + contentStackBottomConstraint = bottomConstraint + + NSLayoutConstraint.activate([ + backgroundFill.leadingAnchor.constraint(equalTo: leadingAnchor), + backgroundFill.trailingAnchor.constraint(equalTo: trailingAnchor), + backgroundFill.topAnchor.constraint(equalTo: topAnchor), + backgroundFill.bottomAnchor.constraint(equalTo: bottomAnchor), + + topBorderView.leadingAnchor.constraint(equalTo: backgroundFill.leadingAnchor), + topBorderView.trailingAnchor.constraint(equalTo: backgroundFill.trailingAnchor), + topBorderView.topAnchor.constraint(equalTo: backgroundFill.topAnchor), + topBorderView.heightAnchor.constraint(equalToConstant: 1.0 / UIScreen.main.scale), + + contentStack.leadingAnchor.constraint(equalTo: backgroundFill.leadingAnchor, constant: 12), + contentStack.trailingAnchor.constraint(equalTo: backgroundFill.trailingAnchor, constant: -12), + contentStack.topAnchor.constraint(equalTo: backgroundFill.topAnchor, constant: 10), + bottomConstraint, + ]) + + isHidden = true + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FirePostReactionPickerSheet.swift b/apps/ios-app/App/TopicDetail/Support/FirePostReactionPickerSheet.swift new file mode 100644 index 00000000..8103ac91 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FirePostReactionPickerSheet.swift @@ -0,0 +1,76 @@ +import SwiftUI + +struct FirePostReactionPickerSheet: View { + let post: TopicPostState + let options: [FireReactionOption] + let onSelectReaction: @MainActor (String) -> Void + let onShowUsers: @MainActor (String) -> Void + + @State private var query = "" + + private var filteredOptions: [FireReactionOption] { + FireTopicPresentation.filterReactionOptions(options, query: query) + } + + var body: some View { + List { + ForEach(filteredOptions) { option in + reactionRow(option) + } + } + .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "搜索表情") + .navigationTitle("回应 #\(post.postNumber)") + .navigationBarTitleDisplayMode(.inline) + } + + private func reactionRow(_ option: FireReactionOption) -> some View { + let count = post.reactions + .first { $0.id.caseInsensitiveCompare(option.id) == .orderedSame } + .map(\.count) ?? 0 + let isSelected = post.currentUserReaction?.id.caseInsensitiveCompare(option.id) == .orderedSame + + return HStack(spacing: 12) { + Text(option.symbol) + .font(.title3) + .frame(width: 32, alignment: .center) + + VStack(alignment: .leading, spacing: 3) { + Text(option.label) + .font(.subheadline.weight(.medium)) + .foregroundStyle(FireTheme.ink) + Text("\(option.id) · \(count)") + .font(.caption) + .foregroundStyle(FireTheme.subtleInk) + } + + Spacer() + + Button { + onShowUsers(option.id) + } label: { + Image(systemName: "person.2") + .font(.subheadline.weight(.semibold)) + } + .buttonStyle(.borderless) + .accessibilityLabel("查看\(option.label)用户") + + if isSelected { + Image(systemName: "checkmark") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(FireTheme.accent) + } + } + .padding(.vertical, 4) + .contentShape(Rectangle()) + .onTapGesture { + onSelectReaction(option.id) + } + .contextMenu { + Button { + onShowUsers(option.id) + } label: { + Label("查看回应用户", systemImage: "person.2") + } + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FirePostRepliesSheet.swift b/apps/ios-app/App/TopicDetail/Support/FirePostRepliesSheet.swift new file mode 100644 index 00000000..ab9ddeee --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FirePostRepliesSheet.swift @@ -0,0 +1,162 @@ +import SwiftUI + +struct FirePostRepliesSheet: View { + @Environment(\.dismiss) private var dismiss + + let post: TopicPostState + let replies: [TopicPostState] + let replyHistory: [TopicPostState] + let isLoading: Bool + let errorMessage: String? + let baseURLString: String + let onJumpToPost: (UInt32) -> Void + let onRetry: () async -> Void + + private var hasContent: Bool { + !replies.isEmpty || !replyHistory.isEmpty + } + + var body: some View { + List { + if isLoading && !hasContent { + loadingRow + } + + if let errorMessage { + errorRow(message: errorMessage) + } + + if !replyHistory.isEmpty { + Section("回复来源") { + ForEach(replyHistory, id: \.id) { reply in + FirePostReplyContextRow( + post: reply, + baseURLString: baseURLString, + onJump: onJumpToPost + ) + } + } + } + + if !replies.isEmpty { + Section("直接回复") { + ForEach(replies, id: \.id) { reply in + FirePostReplyContextRow( + post: reply, + baseURLString: baseURLString, + onJump: onJumpToPost + ) + } + } + } + + if !isLoading && errorMessage == nil && !hasContent { + emptyRow + } + } + .navigationTitle("#\(post.postNumber) 的回复") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("收起") { + dismiss() + } + } + } + } + + private var loadingRow: some View { + HStack { + Spacer() + ProgressView() + .padding(.vertical, 20) + Spacer() + } + } + + private func errorRow(message: String) -> some View { + VStack(alignment: .leading, spacing: 10) { + Text(message) + .font(.footnote) + .foregroundStyle(.red) + + Button { + Task { await onRetry() } + } label: { + Label("重试", systemImage: "arrow.clockwise") + } + .buttonStyle(.bordered) + } + .padding(.vertical, 6) + } + + private var emptyRow: some View { + VStack(spacing: 10) { + Image(systemName: "bubble.left.and.bubble.right") + .font(.title2) + .foregroundStyle(FireTheme.subtleInk) + Text("暂时没有可显示的回复上下文") + .font(.subheadline.weight(.medium)) + .foregroundStyle(FireTheme.ink) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 28) + } +} + +private struct FirePostReplyContextRow: View { + let post: TopicPostState + let baseURLString: String + let onJump: (UInt32) -> Void + + private var displayName: String { + (post.name ?? "").ifEmpty(post.username.ifEmpty("Unknown")) + } + + private var excerpt: String { + (post.presentation?.plainText() ?? "") + .trimmingCharacters(in: .whitespacesAndNewlines) + .ifEmpty("无正文预览") + } + + var body: some View { + Button { + onJump(post.postNumber) + } label: { + HStack(alignment: .top, spacing: 12) { + FireAvatarView( + avatarTemplate: post.avatarTemplate, + username: post.username.ifEmpty("?"), + size: 34, + baseURLString: baseURLString + ) + + VStack(alignment: .leading, spacing: 5) { + HStack(spacing: 6) { + Text(displayName) + .font(.subheadline.weight(.medium)) + .foregroundStyle(FireTheme.ink) + .lineLimit(1) + + Text("#\(post.postNumber)") + .font(.caption.monospacedDigit()) + .foregroundStyle(FireTheme.tertiaryInk) + + Spacer(minLength: 0) + + Image(systemName: "arrow.up.forward") + .font(.caption.weight(.semibold)) + .foregroundStyle(FireTheme.tertiaryInk) + } + + Text(excerpt) + .font(.footnote) + .foregroundStyle(FireTheme.subtleInk) + .lineLimit(3) + } + } + .padding(.vertical, 4) + } + .buttonStyle(.plain) + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireReactionUsersSheet.swift b/apps/ios-app/App/TopicDetail/Support/FireReactionUsersSheet.swift new file mode 100644 index 00000000..7d61477c --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireReactionUsersSheet.swift @@ -0,0 +1,73 @@ +import SwiftUI + +struct FireReactionUsersSheet: View { + let groups: [ReactionUsersGroupState] + let reactionID: String? + + var body: some View { + List { + if groups.isEmpty { + VStack(spacing: 10) { + Image(systemName: "person.2") + .font(.title2) + .foregroundStyle(FireTheme.subtleInk) + Text("暂时没有回应用户") + .font(.subheadline.weight(.medium)) + .foregroundStyle(FireTheme.ink) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 28) + } else { + ForEach(groups, id: \.id) { group in + Section { + ForEach(group.users, id: \.id) { user in + HStack(spacing: 12) { + FireAvatarView( + avatarTemplate: user.avatarTemplate, + username: user.username, + size: 36 + ) + + VStack(alignment: .leading, spacing: 4) { + Text((user.name ?? "").ifEmpty(user.username)) + .font(.subheadline.weight(.medium)) + .foregroundStyle(FireTheme.ink) + Text("@\(user.username)") + .font(.caption) + .foregroundStyle(FireTheme.subtleInk) + } + } + .padding(.vertical, 3) + } + } header: { + let option = FireTopicPresentation.reactionOption(for: group.id) + Text("\(option.symbol) \(option.label) · \(group.count)") + } + } + } + } + .navigationTitle(title) + .navigationBarTitleDisplayMode(.inline) + } + + private var title: String { + guard let reactionID, + !reactionID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return "回应用户" + } + let option = FireTopicPresentation.reactionOption(for: reactionID) + return "\(option.symbol) \(option.label)" + } +} + +extension Array where Element == ReactionUsersGroupState { + func filter(for reactionID: String?) -> [ReactionUsersGroupState] { + guard let reactionID = reactionID?.trimmingCharacters(in: .whitespacesAndNewlines), + !reactionID.isEmpty else { + return self + } + return filter { group in + group.id.caseInsensitiveCompare(reactionID) == .orderedSame + } + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicDetailModalViews.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicDetailModalViews.swift deleted file mode 100644 index 030e6219..00000000 --- a/apps/ios-app/App/TopicDetail/Support/FireTopicDetailModalViews.swift +++ /dev/null @@ -1,1086 +0,0 @@ -import JXPhotoBrowser -import Photos -import SwiftUI -import UIKit - -struct FireTopicVotersSheet: View { - let voters: [VotedUserState] - let isLoading: Bool - - var body: some View { - List { - if isLoading { - HStack { - Spacer() - ProgressView() - .padding(.vertical, 20) - Spacer() - } - } else if voters.isEmpty { - VStack(spacing: 10) { - Image(systemName: "person.3") - .font(.title2) - .foregroundStyle(FireTheme.subtleInk) - Text("暂时还没有投票用户") - .font(.subheadline.weight(.medium)) - .foregroundStyle(FireTheme.ink) - } - .frame(maxWidth: .infinity) - .padding(.vertical, 28) - } else { - ForEach(voters, id: \.id) { voter in - HStack(spacing: 12) { - FireAvatarView( - avatarTemplate: voter.avatarTemplate, - username: voter.username, - size: 40 - ) - - VStack(alignment: .leading, spacing: 4) { - Text((voter.name ?? "").ifEmpty(voter.username)) - .font(.subheadline.weight(.medium)) - .foregroundStyle(FireTheme.ink) - Text("@\(voter.username)") - .font(.caption) - .foregroundStyle(FireTheme.subtleInk) - } - } - .padding(.vertical, 4) - } - } - } - .navigationTitle("投票用户") - .navigationBarTitleDisplayMode(.inline) - } -} - -struct FirePostReactionPickerSheet: View { - let post: TopicPostState - let options: [FireReactionOption] - let onSelectReaction: @MainActor (String) -> Void - let onShowUsers: @MainActor (String) -> Void - - @State private var query = "" - - private var filteredOptions: [FireReactionOption] { - FireTopicPresentation.filterReactionOptions(options, query: query) - } - - var body: some View { - List { - ForEach(filteredOptions) { option in - reactionRow(option) - } - } - .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "搜索表情") - .navigationTitle("回应 #\(post.postNumber)") - .navigationBarTitleDisplayMode(.inline) - } - - private func reactionRow(_ option: FireReactionOption) -> some View { - let count = post.reactions - .first { $0.id.caseInsensitiveCompare(option.id) == .orderedSame } - .map(\.count) ?? 0 - let isSelected = post.currentUserReaction?.id.caseInsensitiveCompare(option.id) == .orderedSame - - return HStack(spacing: 12) { - Text(option.symbol) - .font(.title3) - .frame(width: 32, alignment: .center) - - VStack(alignment: .leading, spacing: 3) { - Text(option.label) - .font(.subheadline.weight(.medium)) - .foregroundStyle(FireTheme.ink) - Text("\(option.id) · \(count)") - .font(.caption) - .foregroundStyle(FireTheme.subtleInk) - } - - Spacer() - - Button { - onShowUsers(option.id) - } label: { - Image(systemName: "person.2") - .font(.subheadline.weight(.semibold)) - } - .buttonStyle(.borderless) - .accessibilityLabel("查看\(option.label)用户") - - if isSelected { - Image(systemName: "checkmark") - .font(.subheadline.weight(.semibold)) - .foregroundStyle(FireTheme.accent) - } - } - .padding(.vertical, 4) - .contentShape(Rectangle()) - .onTapGesture { - onSelectReaction(option.id) - } - .contextMenu { - Button { - onShowUsers(option.id) - } label: { - Label("查看回应用户", systemImage: "person.2") - } - } - } -} - -struct FireReactionUsersSheet: View { - let groups: [ReactionUsersGroupState] - let reactionID: String? - - var body: some View { - List { - if groups.isEmpty { - VStack(spacing: 10) { - Image(systemName: "person.2") - .font(.title2) - .foregroundStyle(FireTheme.subtleInk) - Text("暂时没有回应用户") - .font(.subheadline.weight(.medium)) - .foregroundStyle(FireTheme.ink) - } - .frame(maxWidth: .infinity) - .padding(.vertical, 28) - } else { - ForEach(groups, id: \.id) { group in - Section { - ForEach(group.users, id: \.id) { user in - HStack(spacing: 12) { - FireAvatarView( - avatarTemplate: user.avatarTemplate, - username: user.username, - size: 36 - ) - - VStack(alignment: .leading, spacing: 4) { - Text((user.name ?? "").ifEmpty(user.username)) - .font(.subheadline.weight(.medium)) - .foregroundStyle(FireTheme.ink) - Text("@\(user.username)") - .font(.caption) - .foregroundStyle(FireTheme.subtleInk) - } - } - .padding(.vertical, 3) - } - } header: { - let option = FireTopicPresentation.reactionOption(for: group.id) - Text("\(option.symbol) \(option.label) · \(group.count)") - } - } - } - } - .navigationTitle(title) - .navigationBarTitleDisplayMode(.inline) - } - - private var title: String { - guard let reactionID, - !reactionID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { - return "回应用户" - } - let option = FireTopicPresentation.reactionOption(for: reactionID) - return "\(option.symbol) \(option.label)" - } -} - -extension Array where Element == ReactionUsersGroupState { - func filter(for reactionID: String?) -> [ReactionUsersGroupState] { - guard let reactionID = reactionID?.trimmingCharacters(in: .whitespacesAndNewlines), - !reactionID.isEmpty else { - return self - } - return filter { group in - group.id.caseInsensitiveCompare(reactionID) == .orderedSame - } - } -} - -final class FireTopicPhotoBrowserController: JXPhotoBrowserViewController, JXPhotoBrowserDelegate { - private enum PhotoSaveError: Error { - case unknownFailure - } - - private let image: FireCookedImage - private let imageRequest: FireRemoteImageRequest - private let toolbar = UIStackView() - private let statusStack = UIStackView() - private let statusLabel = UILabel() - private let activityIndicator = UIActivityIndicatorView(style: .large) - private let retryButton = UIButton(type: .system) - private weak var activeCell: JXZoomImageCell? - private var loadedImage: UIImage? - private var loadTask: Task? - - init(image: FireCookedImage) { - self.image = image - self.imageRequest = FireTopicImageRequestBuilder.cookedImageRequest(image) - super.init(nibName: nil, bundle: nil) - delegate = self - initialIndex = 0 - isLoopingEnabled = false - transitionType = .fade - itemSpacing = 0 - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - deinit { - loadTask?.cancel() - } - - override func viewDidLoad() { - super.viewDidLoad() - configureOverlayControls() - showLoading() - } - - func numberOfItems(in browser: JXPhotoBrowserViewController) -> Int { - 1 - } - - func photoBrowser( - _ browser: JXPhotoBrowserViewController, - cellForItemAt index: Int, - at indexPath: IndexPath - ) -> JXPhotoBrowserAnyCell { - browser.dequeueReusableCell( - withReuseIdentifier: JXZoomImageCell.reuseIdentifier, - for: indexPath - ) - } - - func photoBrowser( - _ browser: JXPhotoBrowserViewController, - willDisplay cell: JXPhotoBrowserAnyCell, - at index: Int - ) { - guard let photoCell = cell as? JXZoomImageCell else { return } - photoCell.imageView.contentMode = .scaleAspectFit - photoCell.imageView.accessibilityLabel = image.altText?.trimmingCharacters(in: .whitespacesAndNewlines).ifEmpty("帖子图片") - activeCell = photoCell - if let loadedImage { - photoCell.imageView.image = loadedImage - photoCell.adjustImageViewFrame() - hideStatus() - } else { - photoCell.imageView.image = nil - loadImage() - } - } - - func photoBrowser( - _ browser: JXPhotoBrowserViewController, - didEndDisplaying cell: JXPhotoBrowserAnyCell, - at index: Int - ) { - if activeCell === cell { - activeCell = nil - } - } - - private func configureOverlayControls() { - toolbar.axis = .horizontal - toolbar.alignment = .center - toolbar.distribution = .equalSpacing - toolbar.spacing = 12 - toolbar.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(toolbar) - - toolbar.addArrangedSubview(controlButton(systemName: "xmark", action: #selector(closeTapped))) - toolbar.addArrangedSubview(UIView()) - toolbar.addArrangedSubview(controlButton(systemName: "square.and.arrow.up", action: #selector(shareTapped))) - toolbar.addArrangedSubview(controlButton(systemName: "arrow.down.to.line", action: #selector(saveTapped))) - - statusStack.axis = .vertical - statusStack.alignment = .center - statusStack.spacing = 12 - statusStack.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(statusStack) - - statusLabel.font = .preferredFont(forTextStyle: .subheadline) - statusLabel.textColor = .white - statusLabel.textAlignment = .center - statusLabel.numberOfLines = 0 - retryButton.setTitle("重试", for: .normal) - retryButton.addTarget(self, action: #selector(retryTapped), for: .touchUpInside) - retryButton.tintColor = .white - statusStack.addArrangedSubview(activityIndicator) - statusStack.addArrangedSubview(statusLabel) - statusStack.addArrangedSubview(retryButton) - - NSLayoutConstraint.activate([ - toolbar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16), - toolbar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16), - toolbar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 12), - toolbar.heightAnchor.constraint(equalToConstant: 44), - - statusStack.centerXAnchor.constraint(equalTo: view.centerXAnchor), - statusStack.centerYAnchor.constraint(equalTo: view.centerYAnchor), - statusStack.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 32), - statusStack.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -32), - ]) - } - - private func controlButton(systemName: String, action: Selector) -> UIButton { - var configuration = UIButton.Configuration.filled() - configuration.image = UIImage(systemName: systemName) - configuration.baseForegroundColor = .white - configuration.baseBackgroundColor = UIColor.black.withAlphaComponent(0.42) - configuration.cornerStyle = .capsule - let button = UIButton(configuration: configuration) - button.addTarget(self, action: action, for: .touchUpInside) - button.widthAnchor.constraint(equalToConstant: 42).isActive = true - button.heightAnchor.constraint(equalToConstant: 42).isActive = true - return button - } - - private func loadImage() { - loadTask?.cancel() - showLoading() - if let cachedImage = FireRemoteImagePipeline.shared.cachedImage(for: imageRequest) { - applyLoadedImage(cachedImage) - return - } - - loadTask = Task { [weak self] in - guard let self else { return } - do { - let resolvedImage = try await FireRemoteImagePipeline.shared.loadImage(for: imageRequest) - guard !Task.isCancelled else { return } - await MainActor.run { - self.applyLoadedImage(resolvedImage) - } - } catch is CancellationError { - return - } catch { - guard !Task.isCancelled else { return } - await MainActor.run { - self.showFailure() - } - } - } - } - - private func showLoading() { - statusStack.isHidden = false - retryButton.isHidden = true - statusLabel.text = "图片加载中..." - activityIndicator.startAnimating() - } - - private func showFailure() { - loadedImage = nil - activeCell?.imageView.image = nil - statusStack.isHidden = false - retryButton.isHidden = false - statusLabel.text = "图片加载失败" - activityIndicator.stopAnimating() - } - - private func hideStatus() { - statusStack.isHidden = true - activityIndicator.stopAnimating() - } - - private func applyLoadedImage(_ image: UIImage) { - loadedImage = image - activeCell?.imageView.image = image - activeCell?.adjustImageViewFrame() - hideStatus() - } - - @objc private func retryTapped() { - loadImage() - } - - @objc private func closeTapped() { - dismiss(animated: true) - } - - @objc private func shareTapped() { - Task { @MainActor in - guard let image = await resolvedToolbarImage() else { return } - let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil) - present(controller, animated: true) - } - } - - @objc private func saveTapped() { - Task { @MainActor in - guard let image = await resolvedToolbarImage() else { return } - let status = await photoLibraryAuthorizationStatus() - guard status == .authorized || status == .limited else { - presentAlert(title: "无法保存到相册", message: "Fire 需要照片权限才能保存当前图片。") - return - } - do { - try await saveImageToPhotoLibrary(image) - presentAlert(title: "已保存到相册", message: "当前帖子图片已经保存。") - } catch { - presentAlert(title: "保存失败", message: "系统暂时无法写入相册,请稍后再试。") - } - } - } - - @MainActor - private func resolvedToolbarImage() async -> UIImage? { - if let loadedImage { - return loadedImage - } - do { - let image = try await FireRemoteImagePipeline.shared.loadImage(for: imageRequest) - applyLoadedImage(image) - return image - } catch { - showFailure() - return nil - } - } - - private func photoLibraryAuthorizationStatus() async -> PHAuthorizationStatus { - let currentStatus = PHPhotoLibrary.authorizationStatus(for: .addOnly) - guard currentStatus == .notDetermined else { - return currentStatus - } - return await withCheckedContinuation { continuation in - PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in - continuation.resume(returning: status) - } - } - } - - private func saveImageToPhotoLibrary(_ image: UIImage) async throws { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - PHPhotoLibrary.shared().performChanges { - PHAssetCreationRequest.creationRequestForAsset(from: image) - } completionHandler: { success, error in - if let error { - continuation.resume(throwing: error) - } else if success { - continuation.resume(returning: ()) - } else { - continuation.resume(throwing: PhotoSaveError.unknownFailure) - } - } - } - } - - private func presentAlert(title: String, message: String) { - let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "知道了", style: .cancel)) - present(alert, animated: true) - } -} - -struct FirePostRepliesSheet: View { - @Environment(\.dismiss) private var dismiss - - let post: TopicPostState - let replies: [TopicPostState] - let replyHistory: [TopicPostState] - let isLoading: Bool - let errorMessage: String? - let baseURLString: String - let onJumpToPost: (UInt32) -> Void - let onRetry: () async -> Void - - private var hasContent: Bool { - !replies.isEmpty || !replyHistory.isEmpty - } - - var body: some View { - List { - if isLoading && !hasContent { - loadingRow - } - - if let errorMessage { - errorRow(message: errorMessage) - } - - if !replyHistory.isEmpty { - Section("回复来源") { - ForEach(replyHistory, id: \.id) { reply in - FirePostReplyContextRow( - post: reply, - baseURLString: baseURLString, - onJump: onJumpToPost - ) - } - } - } - - if !replies.isEmpty { - Section("直接回复") { - ForEach(replies, id: \.id) { reply in - FirePostReplyContextRow( - post: reply, - baseURLString: baseURLString, - onJump: onJumpToPost - ) - } - } - } - - if !isLoading && errorMessage == nil && !hasContent { - emptyRow - } - } - .navigationTitle("#\(post.postNumber) 的回复") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("收起") { - dismiss() - } - } - } - } - - private var loadingRow: some View { - HStack { - Spacer() - ProgressView() - .padding(.vertical, 20) - Spacer() - } - } - - private func errorRow(message: String) -> some View { - VStack(alignment: .leading, spacing: 10) { - Text(message) - .font(.footnote) - .foregroundStyle(.red) - - Button { - Task { await onRetry() } - } label: { - Label("重试", systemImage: "arrow.clockwise") - } - .buttonStyle(.bordered) - } - .padding(.vertical, 6) - } - - private var emptyRow: some View { - VStack(spacing: 10) { - Image(systemName: "bubble.left.and.bubble.right") - .font(.title2) - .foregroundStyle(FireTheme.subtleInk) - Text("暂时没有可显示的回复上下文") - .font(.subheadline.weight(.medium)) - .foregroundStyle(FireTheme.ink) - } - .frame(maxWidth: .infinity) - .padding(.vertical, 28) - } -} - -private struct FirePostReplyContextRow: View { - let post: TopicPostState - let baseURLString: String - let onJump: (UInt32) -> Void - - private var displayName: String { - (post.name ?? "").ifEmpty(post.username.ifEmpty("Unknown")) - } - - private var excerpt: String { - (post.presentation?.plainText() ?? "") - .trimmingCharacters(in: .whitespacesAndNewlines) - .ifEmpty("无正文预览") - } - - var body: some View { - Button { - onJump(post.postNumber) - } label: { - HStack(alignment: .top, spacing: 12) { - FireAvatarView( - avatarTemplate: post.avatarTemplate, - username: post.username.ifEmpty("?"), - size: 34, - baseURLString: baseURLString - ) - - VStack(alignment: .leading, spacing: 5) { - HStack(spacing: 6) { - Text(displayName) - .font(.subheadline.weight(.medium)) - .foregroundStyle(FireTheme.ink) - .lineLimit(1) - - Text("#\(post.postNumber)") - .font(.caption.monospacedDigit()) - .foregroundStyle(FireTheme.tertiaryInk) - - Spacer(minLength: 0) - - Image(systemName: "arrow.up.forward") - .font(.caption.weight(.semibold)) - .foregroundStyle(FireTheme.tertiaryInk) - } - - Text(excerpt) - .font(.footnote) - .foregroundStyle(FireTheme.subtleInk) - .lineLimit(3) - } - } - .padding(.vertical, 4) - } - .buttonStyle(.plain) - } -} - -struct FireTopicImageViewer: View { - let image: FireCookedImage - - private enum InteractionMode { - case idle - case zooming - case panning - case dismissing - } - - private enum DragMode { - case pan - case dismiss - case ignore - } - - private enum ToolbarAction { - case share - case save - } - - private enum PhotoSaveError: Error { - case unknownFailure - } - - @Environment(\.dismiss) private var dismiss - @State private var interactionMode: InteractionMode = .idle - @State private var activeDragMode: DragMode? - @State private var activeToolbarAction: ToolbarAction? - @State private var sharedImage: UIImage? - @State private var isShowingShareSheet = false - @State private var isShowingAlert = false - @State private var alertTitle = "" - @State private var alertMessage = "" - @State private var steadyZoomScale: CGFloat = 1 - @State private var gestureZoomScale: CGFloat = 1 - @State private var panOffset: CGSize = .zero - @State private var dragStartOffset: CGSize = .zero - @State private var dismissOffset: CGSize = .zero - - private let minimumZoomScale: CGFloat = 1 - private let maximumZoomScale: CGFloat = 4 - private let dismissThreshold: CGFloat = 140 - private let dismissProgressDistance: CGFloat = 220 - private let imagePadding: CGFloat = 16 - - private var imageRequest: FireRemoteImageRequest { - FireRemoteImageRequest(url: image.url) - } - - private var shareSubject: String { - let fileName = image.url.lastPathComponent.trimmingCharacters(in: .whitespacesAndNewlines) - return fileName.isEmpty ? "Fire 帖子图片" : fileName - } - - private var effectiveZoomScale: CGFloat { - clampedScale(steadyZoomScale * gestureZoomScale) - } - - private var dismissProgress: CGFloat { - min(max(dismissOffset.height / dismissProgressDistance, 0), 1) - } - - private var backgroundOpacity: Double { - Double(max(0.22, 1 - dismissProgress * 0.78)) - } - - private var contentScale: CGFloat { - let dismissScale = max(0.88, 1 - dismissProgress * 0.12) - return effectiveZoomScale * dismissScale - } - - private var isToolbarBusy: Bool { - activeToolbarAction != nil - } - - var body: some View { - GeometryReader { proxy in - let containerSize = proxy.size - - ZStack { - Color.black - .opacity(backgroundOpacity) - .ignoresSafeArea() - - FireRemoteImage(request: imageRequest) { loadedImage in - Image(uiImage: loadedImage) - .resizable() - .scaledToFit() - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(imagePadding) - } placeholder: { state in - switch state { - case .loading, .missingRequest: - ProgressView() - .tint(.white) - case .failure: - VStack(spacing: 12) { - Image(systemName: "photo") - .font(.largeTitle) - Text("图片加载失败") - .font(.subheadline) - } - .foregroundStyle(.white) - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .scaleEffect(contentScale) - .offset(displayOffset(in: containerSize)) - .simultaneousGesture(magnificationGesture(in: containerSize)) - - VStack { - HStack(spacing: 12) { - Spacer() - - viewerControlButton( - systemName: "square.and.arrow.up", - isBusy: activeToolbarAction == .share, - action: { Task { await handleShareAction() } } - ) - .disabled(isToolbarBusy) - - viewerControlButton( - systemName: "arrow.down.to.line", - isBusy: activeToolbarAction == .save, - action: { Task { await handleSaveAction() } } - ) - .disabled(isToolbarBusy) - - viewerControlButton(systemName: "xmark", action: { - dismiss() - }) - } - .padding(.top, proxy.safeAreaInsets.top + 12) - .padding(.horizontal, 16) - - Spacer() - } - .opacity(max(0.4, backgroundOpacity)) - } - .contentShape(Rectangle()) - .simultaneousGesture(dragGesture(in: containerSize)) - } - .sheet(isPresented: $isShowingShareSheet, onDismiss: { - sharedImage = nil - }) { - Group { - if let sharedImage { - FireActivityShareSheet( - activityItems: [sharedImage], - subject: shareSubject - ) - } - } - .fireSheet(presented: $isShowingShareSheet) - } - .alert(alertTitle, isPresented: $isShowingAlert) { - Button("知道了", role: .cancel) {} - } message: { - Text(alertMessage) - } - } - - private func viewerControlButton( - systemName: String, - isBusy: Bool = false, - action: @escaping () -> Void - ) -> some View { - Button(action: action) { - Group { - if isBusy { - ProgressView() - .controlSize(.small) - .tint(.white) - } else { - Image(systemName: systemName) - .font(.system(size: 18, weight: .semibold)) - .foregroundStyle(.white.opacity(0.92)) - } - } - .frame(width: 42, height: 42) - .background( - Circle() - .fill(Color.black.opacity(0.34)) - ) - .overlay( - Circle() - .stroke(Color.white.opacity(0.14), lineWidth: 1) - ) - } - .buttonStyle(.plain) - } - - @MainActor - private func handleShareAction() async { - guard activeToolbarAction == nil else { return } - - activeToolbarAction = .share - defer { activeToolbarAction = nil } - - do { - let resolvedImage = try await FireRemoteImagePipeline.shared.loadImage(for: imageRequest) - sharedImage = resolvedImage - isShowingShareSheet = true - } catch { - presentAlert( - title: "无法分享图片", - message: "图片还没加载完成或下载失败,请稍后再试。" - ) - } - } - - @MainActor - private func handleSaveAction() async { - guard activeToolbarAction == nil else { return } - - activeToolbarAction = .save - defer { activeToolbarAction = nil } - - let resolvedImage: UIImage - do { - resolvedImage = try await FireRemoteImagePipeline.shared.loadImage(for: imageRequest) - } catch { - presentAlert( - title: "无法保存图片", - message: "图片还没加载完成或下载失败,请稍后再试。" - ) - return - } - - let authorizationStatus = await photoLibraryAuthorizationStatus() - guard authorizationStatus == .authorized || authorizationStatus == .limited else { - presentAlert( - title: "无法保存到相册", - message: "Fire 需要照片权限才能把当前图片保存到相册,请在系统设置里允许添加照片。" - ) - return - } - - do { - try await saveImageToPhotoLibrary(resolvedImage) - presentAlert( - title: "已保存到相册", - message: "当前帖子图片已经保存到系统相册。" - ) - } catch { - presentAlert( - title: "保存失败", - message: "系统暂时无法写入相册,请稍后再试。" - ) - } - } - - @MainActor - private func presentAlert(title: String, message: String) { - alertTitle = title - alertMessage = message - isShowingAlert = true - } - - private func photoLibraryAuthorizationStatus() async -> PHAuthorizationStatus { - let currentStatus = PHPhotoLibrary.authorizationStatus(for: .addOnly) - guard currentStatus == .notDetermined else { - return currentStatus - } - - return await withCheckedContinuation { continuation in - PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in - continuation.resume(returning: status) - } - } - } - - private func saveImageToPhotoLibrary(_ image: UIImage) async throws { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - PHPhotoLibrary.shared().performChanges { - PHAssetCreationRequest.creationRequestForAsset(from: image) - } completionHandler: { success, error in - if let error { - continuation.resume(throwing: error) - } else if success { - continuation.resume(returning: ()) - } else { - continuation.resume(throwing: PhotoSaveError.unknownFailure) - } - } - } - } - - private func magnificationGesture(in containerSize: CGSize) -> some Gesture { - MagnificationGesture() - .onChanged { value in - activeDragMode = nil - dismissOffset = .zero - interactionMode = .zooming - gestureZoomScale = value - } - .onEnded { value in - let resolvedScale = clampedScale(steadyZoomScale * value) - withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { - steadyZoomScale = resolvedScale - gestureZoomScale = 1 - if resolvedScale <= minimumZoomScale + 0.01 { - resetTransformState() - } else { - panOffset = clampedPanOffset(panOffset, in: containerSize, scale: resolvedScale) - interactionMode = .panning - } - } - } - } - - private func dragGesture(in containerSize: CGSize) -> some Gesture { - DragGesture(minimumDistance: 10) - .onChanged { value in - handleDragChanged(value, in: containerSize) - } - .onEnded { value in - handleDragEnded(value, in: containerSize) - } - } - - private func handleDragChanged(_ value: DragGesture.Value, in containerSize: CGSize) { - guard interactionMode != .zooming else { return } - - if activeDragMode == nil { - if effectiveZoomScale > minimumZoomScale + 0.01 { - activeDragMode = .pan - dragStartOffset = panOffset - } else if value.translation.height > 0, - abs(value.translation.height) > abs(value.translation.width) { - activeDragMode = .dismiss - } else { - activeDragMode = .ignore - } - } - - switch activeDragMode { - case .pan: - interactionMode = .panning - dismissOffset = .zero - let proposedOffset = CGSize( - width: dragStartOffset.width + value.translation.width, - height: dragStartOffset.height + value.translation.height - ) - panOffset = clampedPanOffset(proposedOffset, in: containerSize, scale: effectiveZoomScale) - case .dismiss: - interactionMode = .dismissing - let horizontalDrift = value.translation.width * 0.18 - let verticalOffset = value.translation.height > dismissThreshold - ? dismissThreshold + (value.translation.height - dismissThreshold) * 0.72 - : value.translation.height - dismissOffset = CGSize(width: horizontalDrift, height: verticalOffset) - case .ignore, .none: - break - } - } - - private func handleDragEnded(_ value: DragGesture.Value, in containerSize: CGSize) { - defer { activeDragMode = nil } - - switch activeDragMode { - case .pan: - withAnimation(.spring(response: 0.25, dampingFraction: 0.82)) { - panOffset = clampedPanOffset(panOffset, in: containerSize, scale: effectiveZoomScale) - } - interactionMode = effectiveZoomScale > minimumZoomScale + 0.01 ? .panning : .idle - case .dismiss: - let projectedDismissDistance = max(value.translation.height, value.predictedEndTranslation.height) - if projectedDismissDistance > dismissThreshold { - dismiss() - } else { - withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { - dismissOffset = .zero - interactionMode = effectiveZoomScale > minimumZoomScale + 0.01 ? .panning : .idle - } - } - case .ignore, .none: - withAnimation(.spring(response: 0.25, dampingFraction: 0.82)) { - dismissOffset = .zero - } - interactionMode = effectiveZoomScale > minimumZoomScale + 0.01 ? .panning : .idle - } - } - - private func displayOffset(in containerSize: CGSize) -> CGSize { - let clampedPan = clampedPanOffset(panOffset, in: containerSize, scale: effectiveZoomScale) - return CGSize( - width: clampedPan.width + dismissOffset.width, - height: clampedPan.height + dismissOffset.height - ) - } - - private func resetTransformState() { - steadyZoomScale = minimumZoomScale - gestureZoomScale = 1 - panOffset = .zero - dragStartOffset = .zero - dismissOffset = .zero - interactionMode = .idle - } - - private func clampedScale(_ scale: CGFloat) -> CGFloat { - min(max(scale, minimumZoomScale), maximumZoomScale) - } - - private func clampedPanOffset(_ proposedOffset: CGSize, in containerSize: CGSize, scale: CGFloat) -> CGSize { - let maxOffset = maximumPanOffset(in: containerSize, scale: scale) - return CGSize( - width: min(max(proposedOffset.width, -maxOffset.width), maxOffset.width), - height: min(max(proposedOffset.height, -maxOffset.height), maxOffset.height) - ) - } - - private func maximumPanOffset(in containerSize: CGSize, scale: CGFloat) -> CGSize { - guard scale > minimumZoomScale else { - return .zero - } - - let fittedSize = fittedImageSize(in: containerSize) - let scaledSize = CGSize(width: fittedSize.width * scale, height: fittedSize.height * scale) - return CGSize( - width: max((scaledSize.width - fittedSize.width) / 2, 0), - height: max((scaledSize.height - fittedSize.height) / 2, 0) - ) - } - - private func fittedImageSize(in containerSize: CGSize) -> CGSize { - let availableWidth = max(containerSize.width - imagePadding * 2, 1) - let availableHeight = max(containerSize.height - imagePadding * 2, 1) - - guard let aspectRatio = image.aspectRatio, aspectRatio > 0 else { - return CGSize(width: availableWidth, height: availableHeight) - } - - let containerAspectRatio = availableWidth / availableHeight - if aspectRatio > containerAspectRatio { - return CGSize(width: availableWidth, height: availableWidth / aspectRatio) - } - return CGSize(width: availableHeight * aspectRatio, height: availableHeight) - } -} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicDetailUiProjection.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicDetailUiProjection.swift new file mode 100644 index 00000000..7f01e1f6 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicDetailUiProjection.swift @@ -0,0 +1,96 @@ +import Foundation + +enum FireTopicDetailUiProjection { + static func posts(from snapshot: TopicDetailUiSnapshotState) -> [TopicPostState] { + snapshot.rows.map(post(from:)) + } + + static func timelineEntry(from row: TopicDetailUiRowState) -> FireTopicTimelineEntry { + FireTopicTimelineEntry( + postId: row.postId, + postNumber: row.postNumber, + parentPostNumber: row.parentPostNumber, + depth: UInt32(row.depth), + isOriginalPost: row.isOriginalPost + ) + } + + static func post(from row: TopicDetailUiRowState) -> TopicPostState { + let author = row.author + return TopicPostState( + id: row.postId, + username: author.username, + name: author.name, + avatarTemplate: author.avatarTemplate, + authorMetadata: TopicPostAuthorMetadataState( + userId: author.userId, + userTitle: author.userTitle, + primaryGroupName: author.primaryGroupName, + flairUrl: author.flairUrl, + flairName: author.flairName, + flairBgColor: author.flairBgColor, + flairColor: author.flairColor, + flairGroupId: author.flairGroupId, + moderator: author.moderator, + admin: author.admin, + groupModerator: author.groupModerator, + userStatusEmoji: author.userStatusEmoji, + userStatusDescription: author.userStatusDescription + ), + presentation: row.presentation, + raw: nil, + postNumber: row.postNumber, + postType: row.postType, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + likeCount: row.likeCount, + replyCount: row.replyCount, + replyToPostNumber: row.parentPostNumber, + replyToUser: row.replyToUser.map { + TopicReplyToUserState( + username: $0.username, + name: $0.name, + avatarTemplate: $0.avatarTemplate + ) + }, + bookmarked: row.bookmarked, + bookmarkId: row.bookmarkId, + bookmarkName: row.bookmarkName, + bookmarkReminderAt: row.bookmarkReminderAt, + reactions: row.reactions.map { + TopicReactionState(id: $0.id, kind: $0.kind, count: $0.count, canUndo: $0.canUndo) + }, + currentUserReaction: row.currentReactionId.flatMap { id in + row.reactions.first { $0.id == id }.map { + TopicReactionState(id: $0.id, kind: $0.kind, count: $0.count, canUndo: $0.canUndo) + } + }, + boosts: row.boosts.map { boost in + TopicPostBoostState( + id: boost.id, + presentation: boost.presentation, + displayText: boost.displayText, + user: TopicPostBoostUserState( + id: boost.user.id, + username: boost.user.username, + name: boost.user.name, + avatarTemplate: boost.user.avatarTemplate + ), + canDelete: boost.canDelete, + canFlag: boost.canFlag, + userFlagStatus: boost.userFlagStatus, + availableFlags: boost.availableFlags + ) + }, + canBoost: row.canBoost, + polls: row.polls, + acceptedAnswer: row.acceptedAnswer, + canAcceptAnswer: row.canAcceptAnswer, + canUnacceptAnswer: row.canUnacceptAnswer, + canEdit: row.canEdit, + canDelete: row.canDelete, + canRecover: row.canRecover, + hidden: row.hidden + ) + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicFormatting.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicFormatting.swift new file mode 100644 index 00000000..a8ca41f3 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicFormatting.swift @@ -0,0 +1,155 @@ +import Foundation +import SwiftUI + +typealias FireTopicCategoryPresentation = TopicCategoryState +extension TopicCategoryState { + var displayName: String { + name.isEmpty ? "Category #\(id)" : name + } +} +extension FireTopicPresentation { + static func formatTimestamp(_ rawValue: String?) -> String? { + guard let rawValue, !rawValue.isEmpty else { + return nil + } + + let date = fractionalISO8601.date(from: rawValue) ?? basicISO8601.date(from: rawValue) + guard let date else { + return rawValue + } + return displayFormatter.string(from: date) + } + static func compactTimestamp(_ rawValue: String?) -> String? { + TimestampFormatter(style: .compact).format(rawValue) + } + static func compactTimestamp(unixMs: UInt64?) -> String? { + guard let unixMs else { + return nil + } + return TimestampFormatter(style: .compact).format( + date: Date(timeIntervalSince1970: Double(unixMs) / 1000.0) + ) + } + static func compactCount(_ value: UInt32) -> String { + compactCount(UInt64(value)) + } + private static func compactCount(_ value: UInt64) -> String { + switch value { + case 0..<1_000: + return "\(value)" + case 1_000..<10_000: + return compactCountSegment(Double(value), divisor: 1_000, suffix: "k") + case 10_000..<100_000_000: + return compactCountSegment(Double(value), divisor: 10_000, suffix: "万") + default: + return compactCountSegment(Double(value), divisor: 100_000_000, suffix: "亿") + } + } + private static func compactCountSegment(_ value: Double, divisor: Double, suffix: String) -> String { + let compact = value / divisor + let formatted: String + + if compact >= 10 { + formatted = String(format: "%.0f", compact.rounded()) + } else { + formatted = String(format: "%.1f", compact) + } + + return formatted.replacingOccurrences(of: ".0", with: "") + suffix + } + private static let fractionalISO8601: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter + }() + private static let basicISO8601: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime] + return formatter + }() + private static let displayFormatter: DateFormatter = { + let formatter = DateFormatter() + formatter.dateStyle = .medium + formatter.timeStyle = .short + return formatter + }() +} +private struct TimestampFormatter { + private let fractionalISO8601: ISO8601DateFormatter + private let basicISO8601: ISO8601DateFormatter + private let style: Style + + enum Style { + case full + case compact + } + + init(style: Style = .full) { + self.style = style + + let fractionalISO8601 = ISO8601DateFormatter() + fractionalISO8601.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + self.fractionalISO8601 = fractionalISO8601 + + let basicISO8601 = ISO8601DateFormatter() + basicISO8601.formatOptions = [.withInternetDateTime] + self.basicISO8601 = basicISO8601 + } + + func format(_ rawValue: String?) -> String? { + guard let rawValue, !rawValue.isEmpty else { + return nil + } + + let date = fractionalISO8601.date(from: rawValue) ?? basicISO8601.date(from: rawValue) + guard let date else { + return rawValue + } + + return format(date: date) + } + + func format(date: Date) -> String { + switch style { + case .full: + return Self.fullFormatter.string(from: date) + case .compact: + return Self.compactFormatter.localizedString(for: date, relativeTo: Date()) + } + } + + private static let fullFormatter: DateFormatter = { + let formatter = DateFormatter() + formatter.dateStyle = .medium + formatter.timeStyle = .short + return formatter + }() + + private static let compactFormatter: RelativeDateTimeFormatter = { + let formatter = RelativeDateTimeFormatter() + formatter.unitsStyle = .short + return formatter + }() +} +extension Color { + init?(fireHex hex: String?) { + guard let hex else { + return nil + } + + let cleaned = hex + .trimmingCharacters(in: CharacterSet.alphanumerics.inverted) + .uppercased() + guard cleaned.count == 6, let value = Int(cleaned, radix: 16) else { + return nil + } + + self.init( + .sRGB, + red: Double((value >> 16) & 0xFF) / 255.0, + green: Double((value >> 8) & 0xFF) / 255.0, + blue: Double(value & 0xFF) / 255.0, + opacity: 1.0 + ) + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicImageViewer.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicImageViewer.swift new file mode 100644 index 00000000..7376ef48 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicImageViewer.swift @@ -0,0 +1,446 @@ +import Photos +import SwiftUI +import UIKit + +struct FireTopicImageViewer: View { + let image: FireCookedImage + + private enum InteractionMode { + case idle + case zooming + case panning + case dismissing + } + + private enum DragMode { + case pan + case dismiss + case ignore + } + + private enum ToolbarAction { + case share + case save + } + + private enum PhotoSaveError: Error { + case unknownFailure + } + + @Environment(\.dismiss) private var dismiss + @State private var interactionMode: InteractionMode = .idle + @State private var activeDragMode: DragMode? + @State private var activeToolbarAction: ToolbarAction? + @State private var sharedImage: UIImage? + @State private var isShowingShareSheet = false + @State private var isShowingAlert = false + @State private var alertTitle = "" + @State private var alertMessage = "" + @State private var steadyZoomScale: CGFloat = 1 + @State private var gestureZoomScale: CGFloat = 1 + @State private var panOffset: CGSize = .zero + @State private var dragStartOffset: CGSize = .zero + @State private var dismissOffset: CGSize = .zero + + private let minimumZoomScale: CGFloat = 1 + private let maximumZoomScale: CGFloat = 4 + private let dismissThreshold: CGFloat = 140 + private let dismissProgressDistance: CGFloat = 220 + private let imagePadding: CGFloat = 16 + + private var imageRequest: FireRemoteImageRequest { + FireRemoteImageRequest(url: image.url) + } + + private var shareSubject: String { + let fileName = image.url.lastPathComponent.trimmingCharacters(in: .whitespacesAndNewlines) + return fileName.isEmpty ? "Fire 帖子图片" : fileName + } + + private var effectiveZoomScale: CGFloat { + clampedScale(steadyZoomScale * gestureZoomScale) + } + + private var dismissProgress: CGFloat { + min(max(dismissOffset.height / dismissProgressDistance, 0), 1) + } + + private var backgroundOpacity: Double { + Double(max(0.22, 1 - dismissProgress * 0.78)) + } + + private var contentScale: CGFloat { + let dismissScale = max(0.88, 1 - dismissProgress * 0.12) + return effectiveZoomScale * dismissScale + } + + private var isToolbarBusy: Bool { + activeToolbarAction != nil + } + + var body: some View { + GeometryReader { proxy in + let containerSize = proxy.size + + ZStack { + Color.black + .opacity(backgroundOpacity) + .ignoresSafeArea() + + FireRemoteImage(request: imageRequest) { loadedImage in + Image(uiImage: loadedImage) + .resizable() + .scaledToFit() + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(imagePadding) + } placeholder: { state in + switch state { + case .loading, .missingRequest: + ProgressView() + .tint(.white) + case .failure: + VStack(spacing: 12) { + Image(systemName: "photo") + .font(.largeTitle) + Text("图片加载失败") + .font(.subheadline) + } + .foregroundStyle(.white) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .scaleEffect(contentScale) + .offset(displayOffset(in: containerSize)) + .simultaneousGesture(magnificationGesture(in: containerSize)) + + VStack { + HStack(spacing: 12) { + Spacer() + + viewerControlButton( + systemName: "square.and.arrow.up", + isBusy: activeToolbarAction == .share, + action: { Task { await handleShareAction() } } + ) + .disabled(isToolbarBusy) + + viewerControlButton( + systemName: "arrow.down.to.line", + isBusy: activeToolbarAction == .save, + action: { Task { await handleSaveAction() } } + ) + .disabled(isToolbarBusy) + + viewerControlButton(systemName: "xmark", action: { + dismiss() + }) + } + .padding(.top, proxy.safeAreaInsets.top + 12) + .padding(.horizontal, 16) + + Spacer() + } + .opacity(max(0.4, backgroundOpacity)) + } + .contentShape(Rectangle()) + .simultaneousGesture(dragGesture(in: containerSize)) + } + .sheet(isPresented: $isShowingShareSheet, onDismiss: { + sharedImage = nil + }) { + Group { + if let sharedImage { + FireActivityShareSheet( + activityItems: [sharedImage], + subject: shareSubject + ) + } + } + .fireSheet(presented: $isShowingShareSheet) + } + .alert(alertTitle, isPresented: $isShowingAlert) { + Button("知道了", role: .cancel) {} + } message: { + Text(alertMessage) + } + } + + private func viewerControlButton( + systemName: String, + isBusy: Bool = false, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + Group { + if isBusy { + ProgressView() + .controlSize(.small) + .tint(.white) + } else { + Image(systemName: systemName) + .font(.system(size: 18, weight: .semibold)) + .foregroundStyle(.white.opacity(0.92)) + } + } + .frame(width: 42, height: 42) + .background( + Circle() + .fill(Color.black.opacity(0.34)) + ) + .overlay( + Circle() + .stroke(Color.white.opacity(0.14), lineWidth: 1) + ) + } + .buttonStyle(.plain) + } + + @MainActor + private func handleShareAction() async { + guard activeToolbarAction == nil else { return } + + activeToolbarAction = .share + defer { activeToolbarAction = nil } + + do { + let resolvedImage = try await FireRemoteImagePipeline.shared.loadImage(for: imageRequest) + sharedImage = resolvedImage + isShowingShareSheet = true + } catch { + presentAlert( + title: "无法分享图片", + message: "图片还没加载完成或下载失败,请稍后再试。" + ) + } + } + + @MainActor + private func handleSaveAction() async { + guard activeToolbarAction == nil else { return } + + activeToolbarAction = .save + defer { activeToolbarAction = nil } + + let resolvedImage: UIImage + do { + resolvedImage = try await FireRemoteImagePipeline.shared.loadImage(for: imageRequest) + } catch { + presentAlert( + title: "无法保存图片", + message: "图片还没加载完成或下载失败,请稍后再试。" + ) + return + } + + let authorizationStatus = await photoLibraryAuthorizationStatus() + guard authorizationStatus == .authorized || authorizationStatus == .limited else { + presentAlert( + title: "无法保存到相册", + message: "Fire 需要照片权限才能把当前图片保存到相册,请在系统设置里允许添加照片。" + ) + return + } + + do { + try await saveImageToPhotoLibrary(resolvedImage) + presentAlert( + title: "已保存到相册", + message: "当前帖子图片已经保存到系统相册。" + ) + } catch { + presentAlert( + title: "保存失败", + message: "系统暂时无法写入相册,请稍后再试。" + ) + } + } + + @MainActor + private func presentAlert(title: String, message: String) { + alertTitle = title + alertMessage = message + isShowingAlert = true + } + + private func photoLibraryAuthorizationStatus() async -> PHAuthorizationStatus { + let currentStatus = PHPhotoLibrary.authorizationStatus(for: .addOnly) + guard currentStatus == .notDetermined else { + return currentStatus + } + + return await withCheckedContinuation { continuation in + PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in + continuation.resume(returning: status) + } + } + } + + private func saveImageToPhotoLibrary(_ image: UIImage) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + PHPhotoLibrary.shared().performChanges { + PHAssetCreationRequest.creationRequestForAsset(from: image) + } completionHandler: { success, error in + if let error { + continuation.resume(throwing: error) + } else if success { + continuation.resume(returning: ()) + } else { + continuation.resume(throwing: PhotoSaveError.unknownFailure) + } + } + } + } + + private func magnificationGesture(in containerSize: CGSize) -> some Gesture { + MagnificationGesture() + .onChanged { value in + activeDragMode = nil + dismissOffset = .zero + interactionMode = .zooming + gestureZoomScale = value + } + .onEnded { value in + let resolvedScale = clampedScale(steadyZoomScale * value) + withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { + steadyZoomScale = resolvedScale + gestureZoomScale = 1 + if resolvedScale <= minimumZoomScale + 0.01 { + resetTransformState() + } else { + panOffset = clampedPanOffset(panOffset, in: containerSize, scale: resolvedScale) + interactionMode = .panning + } + } + } + } + + private func dragGesture(in containerSize: CGSize) -> some Gesture { + DragGesture(minimumDistance: 10) + .onChanged { value in + handleDragChanged(value, in: containerSize) + } + .onEnded { value in + handleDragEnded(value, in: containerSize) + } + } + + private func handleDragChanged(_ value: DragGesture.Value, in containerSize: CGSize) { + guard interactionMode != .zooming else { return } + + if activeDragMode == nil { + if effectiveZoomScale > minimumZoomScale + 0.01 { + activeDragMode = .pan + dragStartOffset = panOffset + } else if value.translation.height > 0, + abs(value.translation.height) > abs(value.translation.width) { + activeDragMode = .dismiss + } else { + activeDragMode = .ignore + } + } + + switch activeDragMode { + case .pan: + interactionMode = .panning + dismissOffset = .zero + let proposedOffset = CGSize( + width: dragStartOffset.width + value.translation.width, + height: dragStartOffset.height + value.translation.height + ) + panOffset = clampedPanOffset(proposedOffset, in: containerSize, scale: effectiveZoomScale) + case .dismiss: + interactionMode = .dismissing + let horizontalDrift = value.translation.width * 0.18 + let verticalOffset = value.translation.height > dismissThreshold + ? dismissThreshold + (value.translation.height - dismissThreshold) * 0.72 + : value.translation.height + dismissOffset = CGSize(width: horizontalDrift, height: verticalOffset) + case .ignore, .none: + break + } + } + + private func handleDragEnded(_ value: DragGesture.Value, in containerSize: CGSize) { + defer { activeDragMode = nil } + + switch activeDragMode { + case .pan: + withAnimation(.spring(response: 0.25, dampingFraction: 0.82)) { + panOffset = clampedPanOffset(panOffset, in: containerSize, scale: effectiveZoomScale) + } + interactionMode = effectiveZoomScale > minimumZoomScale + 0.01 ? .panning : .idle + case .dismiss: + let projectedDismissDistance = max(value.translation.height, value.predictedEndTranslation.height) + if projectedDismissDistance > dismissThreshold { + dismiss() + } else { + withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { + dismissOffset = .zero + interactionMode = effectiveZoomScale > minimumZoomScale + 0.01 ? .panning : .idle + } + } + case .ignore, .none: + withAnimation(.spring(response: 0.25, dampingFraction: 0.82)) { + dismissOffset = .zero + } + interactionMode = effectiveZoomScale > minimumZoomScale + 0.01 ? .panning : .idle + } + } + + private func displayOffset(in containerSize: CGSize) -> CGSize { + let clampedPan = clampedPanOffset(panOffset, in: containerSize, scale: effectiveZoomScale) + return CGSize( + width: clampedPan.width + dismissOffset.width, + height: clampedPan.height + dismissOffset.height + ) + } + + private func resetTransformState() { + steadyZoomScale = minimumZoomScale + gestureZoomScale = 1 + panOffset = .zero + dragStartOffset = .zero + dismissOffset = .zero + interactionMode = .idle + } + + private func clampedScale(_ scale: CGFloat) -> CGFloat { + min(max(scale, minimumZoomScale), maximumZoomScale) + } + + private func clampedPanOffset(_ proposedOffset: CGSize, in containerSize: CGSize, scale: CGFloat) -> CGSize { + let maxOffset = maximumPanOffset(in: containerSize, scale: scale) + return CGSize( + width: min(max(proposedOffset.width, -maxOffset.width), maxOffset.width), + height: min(max(proposedOffset.height, -maxOffset.height), maxOffset.height) + ) + } + + private func maximumPanOffset(in containerSize: CGSize, scale: CGFloat) -> CGSize { + guard scale > minimumZoomScale else { + return .zero + } + + let fittedSize = fittedImageSize(in: containerSize) + let scaledSize = CGSize(width: fittedSize.width * scale, height: fittedSize.height * scale) + return CGSize( + width: max((scaledSize.width - fittedSize.width) / 2, 0), + height: max((scaledSize.height - fittedSize.height) / 2, 0) + ) + } + + private func fittedImageSize(in containerSize: CGSize) -> CGSize { + let availableWidth = max(containerSize.width - imagePadding * 2, 1) + let availableHeight = max(containerSize.height - imagePadding * 2, 1) + + guard let aspectRatio = image.aspectRatio, aspectRatio > 0 else { + return CGSize(width: availableWidth, height: availableHeight) + } + + let containerAspectRatio = availableWidth / availableHeight + if aspectRatio > containerAspectRatio { + return CGSize(width: availableWidth, height: availableWidth / aspectRatio) + } + return CGSize(width: availableHeight * aspectRatio, height: availableHeight) + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicPhotoBrowserController.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicPhotoBrowserController.swift new file mode 100644 index 00000000..15a0b9a7 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicPhotoBrowserController.swift @@ -0,0 +1,283 @@ +import JXPhotoBrowser +import Photos +import UIKit + +final class FireTopicPhotoBrowserController: JXPhotoBrowserViewController, JXPhotoBrowserDelegate { + private enum PhotoSaveError: Error { + case unknownFailure + } + + private let image: FireCookedImage + private let imageRequest: FireRemoteImageRequest + private let toolbar = UIStackView() + private let statusStack = UIStackView() + private let statusLabel = UILabel() + private let activityIndicator = UIActivityIndicatorView(style: .large) + private let retryButton = UIButton(type: .system) + private weak var activeCell: JXZoomImageCell? + private var loadedImage: UIImage? + private var loadTask: Task? + + init(image: FireCookedImage) { + self.image = image + self.imageRequest = FireTopicImageRequestBuilder.cookedImageRequest(image) + super.init(nibName: nil, bundle: nil) + delegate = self + initialIndex = 0 + isLoopingEnabled = false + transitionType = .fade + itemSpacing = 0 + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + deinit { + loadTask?.cancel() + } + + override func viewDidLoad() { + super.viewDidLoad() + configureOverlayControls() + showLoading() + } + + func numberOfItems(in browser: JXPhotoBrowserViewController) -> Int { + 1 + } + + func photoBrowser( + _ browser: JXPhotoBrowserViewController, + cellForItemAt index: Int, + at indexPath: IndexPath + ) -> JXPhotoBrowserAnyCell { + browser.dequeueReusableCell( + withReuseIdentifier: JXZoomImageCell.reuseIdentifier, + for: indexPath + ) + } + + func photoBrowser( + _ browser: JXPhotoBrowserViewController, + willDisplay cell: JXPhotoBrowserAnyCell, + at index: Int + ) { + guard let photoCell = cell as? JXZoomImageCell else { return } + photoCell.imageView.contentMode = .scaleAspectFit + photoCell.imageView.accessibilityLabel = image.altText?.trimmingCharacters(in: .whitespacesAndNewlines).ifEmpty("帖子图片") + activeCell = photoCell + if let loadedImage { + photoCell.imageView.image = loadedImage + photoCell.adjustImageViewFrame() + hideStatus() + } else { + photoCell.imageView.image = nil + loadImage() + } + } + + func photoBrowser( + _ browser: JXPhotoBrowserViewController, + didEndDisplaying cell: JXPhotoBrowserAnyCell, + at index: Int + ) { + if activeCell === cell { + activeCell = nil + } + } + + private func configureOverlayControls() { + toolbar.axis = .horizontal + toolbar.alignment = .center + toolbar.distribution = .equalSpacing + toolbar.spacing = 12 + toolbar.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(toolbar) + + toolbar.addArrangedSubview(controlButton(systemName: "xmark", action: #selector(closeTapped))) + toolbar.addArrangedSubview(UIView()) + toolbar.addArrangedSubview(controlButton(systemName: "square.and.arrow.up", action: #selector(shareTapped))) + toolbar.addArrangedSubview(controlButton(systemName: "arrow.down.to.line", action: #selector(saveTapped))) + + statusStack.axis = .vertical + statusStack.alignment = .center + statusStack.spacing = 12 + statusStack.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(statusStack) + + statusLabel.font = .preferredFont(forTextStyle: .subheadline) + statusLabel.textColor = .white + statusLabel.textAlignment = .center + statusLabel.numberOfLines = 0 + retryButton.setTitle("重试", for: .normal) + retryButton.addTarget(self, action: #selector(retryTapped), for: .touchUpInside) + retryButton.tintColor = .white + statusStack.addArrangedSubview(activityIndicator) + statusStack.addArrangedSubview(statusLabel) + statusStack.addArrangedSubview(retryButton) + + NSLayoutConstraint.activate([ + toolbar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16), + toolbar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16), + toolbar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 12), + toolbar.heightAnchor.constraint(equalToConstant: 44), + + statusStack.centerXAnchor.constraint(equalTo: view.centerXAnchor), + statusStack.centerYAnchor.constraint(equalTo: view.centerYAnchor), + statusStack.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 32), + statusStack.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -32), + ]) + } + + private func controlButton(systemName: String, action: Selector) -> UIButton { + var configuration = UIButton.Configuration.filled() + configuration.image = UIImage(systemName: systemName) + configuration.baseForegroundColor = .white + configuration.baseBackgroundColor = UIColor.black.withAlphaComponent(0.42) + configuration.cornerStyle = .capsule + let button = UIButton(configuration: configuration) + button.addTarget(self, action: action, for: .touchUpInside) + button.widthAnchor.constraint(equalToConstant: 42).isActive = true + button.heightAnchor.constraint(equalToConstant: 42).isActive = true + return button + } + + private func loadImage() { + loadTask?.cancel() + showLoading() + if let cachedImage = FireRemoteImagePipeline.shared.cachedImage(for: imageRequest) { + applyLoadedImage(cachedImage) + return + } + + loadTask = Task { [weak self] in + guard let self else { return } + do { + let resolvedImage = try await FireRemoteImagePipeline.shared.loadImage(for: imageRequest) + guard !Task.isCancelled else { return } + await MainActor.run { + self.applyLoadedImage(resolvedImage) + } + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { return } + await MainActor.run { + self.showFailure() + } + } + } + } + + private func showLoading() { + statusStack.isHidden = false + retryButton.isHidden = true + statusLabel.text = "图片加载中..." + activityIndicator.startAnimating() + } + + private func showFailure() { + loadedImage = nil + activeCell?.imageView.image = nil + statusStack.isHidden = false + retryButton.isHidden = false + statusLabel.text = "图片加载失败" + activityIndicator.stopAnimating() + } + + private func hideStatus() { + statusStack.isHidden = true + activityIndicator.stopAnimating() + } + + private func applyLoadedImage(_ image: UIImage) { + loadedImage = image + activeCell?.imageView.image = image + activeCell?.adjustImageViewFrame() + hideStatus() + } + + @objc private func retryTapped() { + loadImage() + } + + @objc private func closeTapped() { + dismiss(animated: true) + } + + @objc private func shareTapped() { + Task { @MainActor in + guard let image = await resolvedToolbarImage() else { return } + let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil) + present(controller, animated: true) + } + } + + @objc private func saveTapped() { + Task { @MainActor in + guard let image = await resolvedToolbarImage() else { return } + let status = await photoLibraryAuthorizationStatus() + guard status == .authorized || status == .limited else { + presentAlert(title: "无法保存到相册", message: "Fire 需要照片权限才能保存当前图片。") + return + } + do { + try await saveImageToPhotoLibrary(image) + presentAlert(title: "已保存到相册", message: "当前帖子图片已经保存。") + } catch { + presentAlert(title: "保存失败", message: "系统暂时无法写入相册,请稍后再试。") + } + } + } + + @MainActor + private func resolvedToolbarImage() async -> UIImage? { + if let loadedImage { + return loadedImage + } + do { + let image = try await FireRemoteImagePipeline.shared.loadImage(for: imageRequest) + applyLoadedImage(image) + return image + } catch { + showFailure() + return nil + } + } + + private func photoLibraryAuthorizationStatus() async -> PHAuthorizationStatus { + let currentStatus = PHPhotoLibrary.authorizationStatus(for: .addOnly) + guard currentStatus == .notDetermined else { + return currentStatus + } + return await withCheckedContinuation { continuation in + PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in + continuation.resume(returning: status) + } + } + } + + private func saveImageToPhotoLibrary(_ image: UIImage) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + PHPhotoLibrary.shared().performChanges { + PHAssetCreationRequest.creationRequestForAsset(from: image) + } completionHandler: { success, error in + if let error { + continuation.resume(throwing: error) + } else if success { + continuation.resume(returning: ()) + } else { + continuation.resume(throwing: PhotoSaveError.unknownFailure) + } + } + } + } + + private func presentAlert(title: String, message: String) { + let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "知道了", style: .cancel)) + present(alert, animated: true) + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicPostMerge.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicPostMerge.swift new file mode 100644 index 00000000..b76c369b --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicPostMerge.swift @@ -0,0 +1,94 @@ +import Foundation + +extension FireTopicPresentation { + static func mergeTopicPosts( + existing: [TopicPostState], + incoming: [TopicPostState], + orderedPostIDs: [UInt64] + ) -> [TopicPostState] { + let orderedPostIDs = uniqueTopicPostIDsPreservingOrder(orderedPostIDs) + if incoming.isEmpty, + existing.count == orderedPostIDs.count, + zip(existing, orderedPostIDs).allSatisfy({ post, postID in + post.id == postID + }) { + return existing + } + + var postsByID: [UInt64: TopicPostState] = [:] + for post in existing { + postsByID[post.id] = post + } + for post in incoming { + postsByID[post.id] = post + } + + var mergedPosts: [TopicPostState] = [] + mergedPosts.reserveCapacity(postsByID.count) + for postID in orderedPostIDs { + if let post = postsByID.removeValue(forKey: postID) { + mergedPosts.append(post) + } + } + + let trailingPosts = postsByID.values.sorted(by: comparePosts(_:_:)) + mergedPosts.append(contentsOf: trailingPosts) + return mergedPosts + } + static func uniqueTopicPostsPreservingOrder(_ posts: [TopicPostState]) -> [TopicPostState] { + var orderedPostIDs: [UInt64] = [] + orderedPostIDs.reserveCapacity(posts.count) + var postsByID: [UInt64: TopicPostState] = [:] + postsByID.reserveCapacity(posts.count) + + for post in posts { + if postsByID[post.id] == nil { + orderedPostIDs.append(post.id) + } + postsByID[post.id] = post + } + + return orderedPostIDs.compactMap { postsByID[$0] } + } + static func uniqueTreeRowsPreservingOrder( + _ rows: [TopicTreeRowState] + ) -> [TopicTreeRowState] { + var orderedPostIDs: [UInt64] = [] + orderedPostIDs.reserveCapacity(rows.count) + var rowsByPostID: [UInt64: TopicTreeRowState] = [:] + rowsByPostID.reserveCapacity(rows.count) + + for row in rows { + if rowsByPostID[row.postId] == nil { + orderedPostIDs.append(row.postId) + } + rowsByPostID[row.postId] = row + } + + return orderedPostIDs.compactMap { rowsByPostID[$0] } + } + static func uniqueTopicPostIDsPreservingOrder(_ postIDs: [UInt64]) -> [UInt64] { + var seenPostIDs = Set() + seenPostIDs.reserveCapacity(postIDs.count) + var orderedPostIDs: [UInt64] = [] + orderedPostIDs.reserveCapacity(postIDs.count) + + for postID in postIDs where seenPostIDs.insert(postID).inserted { + orderedPostIDs.append(postID) + } + + return orderedPostIDs + } + static func topicPostsByID(_ posts: [TopicPostState]) -> [UInt64: TopicPostState] { + Dictionary( + posts.map { ($0.id, $0) }, + uniquingKeysWith: { _, newest in newest } + ) + } + static func comparePosts(_ lhs: TopicPostState, _ rhs: TopicPostState) -> Bool { + if lhs.postNumber != rhs.postNumber { + return lhs.postNumber < rhs.postNumber + } + return lhs.id < rhs.id + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift index 091fcea2..b18e3d65 100644 --- a/apps/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift @@ -1,223 +1,4 @@ import Foundation -import SwiftUI -import UIKit - -typealias FireTopicCategoryPresentation = TopicCategoryState -typealias FireTopicRowPresentation = TopicRowState - -struct FireTopicTimelineEntry: Hashable, Sendable { - let postId: UInt64 - let postNumber: UInt32 - let parentPostNumber: UInt32? - let depth: UInt32 - let isOriginalPost: Bool -} - -struct FireTopicTimelineRow: Identifiable { - let entry: FireTopicTimelineEntry - let post: TopicPostState? - var id: UInt64 { entry.postId } - var isLoaded: Bool { post != nil } -} - -extension TopicCategoryState { - var displayName: String { - name.isEmpty ? "Category #\(id)" : name - } -} - -struct FireCookedImage: Identifiable, Hashable, Sendable { - let url: URL - let altText: String? - let width: CGFloat? - let height: CGFloat? - - var id: String { url.absoluteString } - - var aspectRatio: CGFloat? { - guard let width, let height, width > 0, height > 0 else { - return nil - } - return width / height - } -} - -struct FireTopicOneboxCard: Hashable, Sendable { - let url: String? - let title: String? - let description: String? - let sourceName: String? - let iconURL: URL? - let thumbnailURL: URL? - let thumbnailWidth: CGFloat? - let thumbnailHeight: CGFloat? -} - -struct FireTopicPostRenderSignature: Hashable, Sendable { - let sourceLength: Int - let sourceChecksum: UInt64 - let segmentIDs: [String] - - var token: String { - var parts: [String] = [] - parts.reserveCapacity(segmentIDs.count + 2) - parts.append(String(sourceLength)) - parts.append(String(sourceChecksum, radix: 16)) - parts.append(contentsOf: segmentIDs) - return parts.joined(separator: ":") - } - - static func make( - source: String, - imageAttachments: [FireCookedImage], - segments: [FireTopicPostRenderSegment] = [] - ) -> Self { - FireTopicPostRenderSignature( - sourceLength: source.utf8.count, - sourceChecksum: stableChecksum(source), - segmentIDs: segments.isEmpty - ? imageAttachments.map { "image:\($0.id)" } - : segments.map(\.signatureToken) - ) - } - - fileprivate static func stableChecksum(_ value: String) -> UInt64 { - var hash: UInt64 = 0xcbf29ce484222325 - for byte in value.utf8 { - hash ^= UInt64(byte) - hash &*= 0x100000001b3 - } - hash ^= hash >> 33 - hash &*= 0xff51afd7ed558ccd - hash ^= hash >> 33 - hash &*= 0xc4ceb9fe1a85ec53 - hash ^= hash >> 33 - return hash - } -} - -// NSAttributedString is not Sendable; render content is built during cache preparation and then shared immutably. -struct FireTopicPostRenderContent: @unchecked Sendable { - let plainText: String - let attributedText: NSAttributedString? - let imageAttachments: [FireCookedImage] - let segments: [FireTopicPostRenderSegment] - let signature: FireTopicPostRenderSignature -} - -// NSAttributedString is immutable after construction and segment values are only read by the UI layer. -enum FireTopicPostRenderSegment: @unchecked Sendable { - case text(NSAttributedString) - case image(FireCookedImage) - case onebox(FireTopicOneboxCard) - - var signatureToken: String { - switch self { - case .text(let attributedText): - return "text:\(attributedText.string.utf8.count):\(FireTopicPostRenderSignature.stableChecksum(attributedText.string))" - case .image(let image): - return "image:\(image.id)" - case .onebox(let card): - return "onebox:\(card.url ?? ""):\(card.thumbnailURL?.absoluteString ?? ""):\(card.title ?? "")" - } - } - - var isImage: Bool { - if case .image = self { return true } - return false - } - - var isOnebox: Bool { - if case .onebox = self { return true } - return false - } - - enum Kind: Hashable { - case text - case image - case onebox - } - - var kind: Kind { - switch self { - case .text: return .text - case .image: return .image - case .onebox: return .onebox - } - } -} - -struct FirePreparedTopicTimelineRow: Identifiable, Sendable { - let entry: FireTopicTimelineEntry - - var id: UInt64 { entry.postId } -} - -struct FireTopicTimelineRowInput: Equatable, Sendable { - let postID: UInt64 - let postNumber: UInt32 - let replyToPostNumber: UInt32? - let responseParentPostNumber: UInt32? - let responseDepth: UInt16? - let responsePreorderIndex: UInt32? - let responseHasChildren: Bool? - let responseDescendantCount: UInt32? - let responseSiblingIndex: UInt16? - let responseIsLastSibling: Bool? - - init( - postID: UInt64, - postNumber: UInt32, - replyToPostNumber: UInt32?, - responseParentPostNumber: UInt32? = nil, - responseDepth: UInt16? = nil, - responsePreorderIndex: UInt32? = nil, - responseHasChildren: Bool? = nil, - responseDescendantCount: UInt32? = nil, - responseSiblingIndex: UInt16? = nil, - responseIsLastSibling: Bool? = nil - ) { - self.postID = postID - self.postNumber = postNumber - self.replyToPostNumber = replyToPostNumber - self.responseParentPostNumber = responseParentPostNumber - self.responseDepth = responseDepth - self.responsePreorderIndex = responsePreorderIndex - self.responseHasChildren = responseHasChildren - self.responseDescendantCount = responseDescendantCount - self.responseSiblingIndex = responseSiblingIndex - self.responseIsLastSibling = responseIsLastSibling - } -} - -struct FireTopicPostRenderInput: Equatable, Sendable { - let presentationChecksum: UInt64? -} - -struct FireTopicDetailRenderState: Sendable { - let originalRow: FirePreparedTopicTimelineRow? - let replyRows: [FirePreparedTopicTimelineRow] - let contentByPostID: [UInt64: FireTopicPostRenderContent] -} - -struct FireTopicDetailRenderCache: Sendable { - let baseURLString: String - let rowInputs: [FireTopicTimelineRowInput] - let contentInputsByPostID: [UInt64: FireTopicPostRenderInput] - let renderState: FireTopicDetailRenderState -} - -struct FireReactionOption: Identifiable, Hashable, Sendable { - let id: String - let symbol: String - let label: String -} - -struct FireTopicSearchMatch: Equatable, Sendable { - let postID: UInt64 - let postNumber: UInt32 -} - enum FireTopicPresentation { static func isPrivateMessageArchetype(_ archetype: String?) -> Bool { let trimmed = archetype?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" @@ -226,1074 +7,4 @@ enum FireTopicPresentation { } return trimmed.caseInsensitiveCompare("private_message") == .orderedSame } - - static func formatTimestamp(_ rawValue: String?) -> String? { - guard let rawValue, !rawValue.isEmpty else { - return nil - } - - let date = fractionalISO8601.date(from: rawValue) ?? basicISO8601.date(from: rawValue) - guard let date else { - return rawValue - } - return displayFormatter.string(from: date) - } - - static func compactTimestamp(_ rawValue: String?) -> String? { - TimestampFormatter(style: .compact).format(rawValue) - } - - static func compactTimestamp(unixMs: UInt64?) -> String? { - guard let unixMs else { - return nil - } - return TimestampFormatter(style: .compact).format( - date: Date(timeIntervalSince1970: Double(unixMs) / 1000.0) - ) - } - - static func compactCount(_ value: UInt32) -> String { - compactCount(UInt64(value)) - } - - static func topicSearchMatches( - query: String, - posts: [TopicPostState] - ) -> [FireTopicSearchMatch] { - let needle = query.trimmingCharacters(in: .whitespacesAndNewlines) - guard !needle.isEmpty else { - return [] - } - - var seenPostIDs = Set() - return posts - .filter { seenPostIDs.insert($0.id).inserted } - .filter { post in - let plainText = post.presentation?.plainText() ?? "" - return plainText.range(of: needle, options: [.caseInsensitive, .diacriticInsensitive]) != nil - } - .sorted { lhs, rhs in - if lhs.postNumber == rhs.postNumber { - return lhs.id < rhs.id - } - return lhs.postNumber < rhs.postNumber - } - .map { FireTopicSearchMatch(postID: $0.id, postNumber: $0.postNumber) } - } - - static func imageAttachments(from presentation: RenderDocumentHandle) -> [FireCookedImage] { - FireRenderPresentation.images(from: presentation) - } - - static func renderContent( - from presentation: RenderDocumentHandle, - sourceToken: String - ) -> FireTopicPostRenderContent { - renderContentFromPresentation(presentation, source: sourceToken) - } - - static func renderContent(from post: TopicPostState) -> FireTopicPostRenderContent? { - guard let presentation = post.presentation else { - return nil - } - return renderContentFromPresentation( - presentation, - source: Self.renderInput(for: post).presentationChecksum.map(String.init) ?? "missing" - ) - } - - private static func renderInput(for post: TopicPostState) -> FireTopicPostRenderInput { - FireTopicPostRenderInput( - presentationChecksum: post.presentation.map { $0.checksum() } - ) - } - - private static func renderContentFromPresentation( - _ presentation: RenderDocumentHandle, - source: String - ) -> FireTopicPostRenderContent { - let imageAttachments = FireRenderPresentation.images(from: presentation) - let richNodes = FireRenderPresentation.richNodes(from: presentation) - let segments = FireRenderPresentation.segments(from: presentation).compactMap { segment -> FireTopicPostRenderSegment? in - switch segment { - case let .rich(nodes): - let attributedText = FireRichTextAttributedStringBuilder.build( - from: nodes, - textColor: FireTheme.uiInk, - accentColor: FireTopicDetailCellColors.accent - ) - return attributedText.length > 0 ? .text(attributedText) : nil - case let .image(image): - return .image(image) - case let .onebox(card): - return .onebox(card) - } - } - - let attributedText = richNodes.isEmpty ? nil : - FireRichTextAttributedStringBuilder.build( - from: richNodes, - textColor: FireTheme.uiInk, - accentColor: FireTopicDetailCellColors.accent - ) - - return FireTopicPostRenderContent( - plainText: presentation.plainText(), - attributedText: attributedText, - imageAttachments: imageAttachments, - segments: segments, - signature: FireTopicPostRenderSignature.make( - source: source, - imageAttachments: imageAttachments, - segments: segments - ) - ) - } - - static func detailRenderState( - from detail: TopicDetailState, - baseURLString: String - ) -> FireTopicDetailRenderState { - detailRenderCache( - from: detail, - baseURLString: baseURLString - ).renderState - } - - private static func timelineRowInput(for post: TopicPostState) -> FireTopicTimelineRowInput { - FireTopicTimelineRowInput( - postID: post.id, - postNumber: post.postNumber, - replyToPostNumber: post.replyToPostNumber, - responseParentPostNumber: nil, - responseDepth: nil, - responsePreorderIndex: nil, - responseHasChildren: nil, - responseDescendantCount: nil, - responseSiblingIndex: nil, - responseIsLastSibling: nil - ) - } - - private static func timelineRowInput(for treeRow: TopicTreeRowState) -> FireTopicTimelineRowInput { - FireTopicTimelineRowInput( - postID: treeRow.postId, - postNumber: treeRow.postNumber, - replyToPostNumber: treeRow.parentPostNumber, - responseParentPostNumber: treeRow.parentPostNumber, - responseDepth: treeRow.depth, - responsePreorderIndex: treeRow.preorderIndex, - responseHasChildren: treeRow.hasChildren, - responseDescendantCount: treeRow.descendantCount, - responseSiblingIndex: treeRow.siblingIndex, - responseIsLastSibling: treeRow.isLastSibling - ) - } - - private static func originalTimelineRow(for post: TopicPostState) -> FirePreparedTopicTimelineRow { - FirePreparedTopicTimelineRow( - entry: FireTopicTimelineEntry( - postId: post.id, - postNumber: post.postNumber, - parentPostNumber: nil, - depth: 0, - isOriginalPost: true - ) - ) - } - - static func replyTargetPostNumber( - for post: TopicPostState, - preferredPostNumber: UInt32? - ) -> UInt32? { - preferredPostNumber ?? post.replyToPostNumber - } - - static func replyContextLabel( - for post: TopicPostState, - preferredPostNumber: UInt32? - ) -> String? { - let targetPostNumber = replyTargetPostNumber( - for: post, - preferredPostNumber: preferredPostNumber - ) - guard let targetPostNumber, targetPostNumber > 0 else { - return nil - } - - let canUseReplyUser = preferredPostNumber == nil - || preferredPostNumber == post.replyToPostNumber - if canUseReplyUser { - let username = post.replyToUser?.username - .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - if !username.isEmpty { - return "回复 @\(username)" - } - } - - return "回复 #\(targetPostNumber)" - } - - private static func replyTimelineRow(from treeRow: TopicTreeRowState) -> FirePreparedTopicTimelineRow { - FirePreparedTopicTimelineRow( - entry: FireTopicTimelineEntry( - postId: treeRow.postId, - postNumber: treeRow.postNumber, - parentPostNumber: treeRow.parentPostNumber, - depth: UInt32(treeRow.depth), - isOriginalPost: false - ) - ) - } - - static func detailRenderCache( - from detail: TopicDetailState, - baseURLString: String, - previous: FireTopicDetailRenderCache? = nil - ) -> FireTopicDetailRenderCache { - let orderedPosts = uniqueTopicPostsPreservingOrder( - mergeTopicPosts( - existing: detail.postStream.posts, - incoming: [], - orderedPostIDs: detail.postStream.stream - ) - ) - let rowInputs = orderedPosts.map(timelineRowInput(for:)) - let contentInputsByPostID = Dictionary( - orderedPosts.map { post in - (post.id, renderInput(for: post)) - }, - uniquingKeysWith: { _, newest in newest } - ) - - let originalRow: FirePreparedTopicTimelineRow? - let replyRows: [FirePreparedTopicTimelineRow] - if previous?.rowInputs == rowInputs { - originalRow = previous?.renderState.originalRow - replyRows = previous?.renderState.replyRows ?? [] - } else { - let rows = rebuildTimelineEntries(from: orderedPosts).map(FirePreparedTopicTimelineRow.init) - let resolvedOriginalRow = rows.first(where: { $0.entry.isOriginalPost }) - originalRow = resolvedOriginalRow - replyRows = rows.filter { row in - row.entry.postId != resolvedOriginalRow?.entry.postId - } - } - - var contentByPostID: [UInt64: FireTopicPostRenderContent] = [:] - contentByPostID.reserveCapacity(orderedPosts.count) - let canReuseContent = previous?.baseURLString == baseURLString - for post in orderedPosts { - if canReuseContent, - previous?.contentInputsByPostID[post.id] == contentInputsByPostID[post.id], - let cachedContent = previous?.renderState.contentByPostID[post.id] { - contentByPostID[post.id] = cachedContent - } else { - contentByPostID[post.id] = renderContent(from: post) - } - } - - return FireTopicDetailRenderCache( - baseURLString: baseURLString, - rowInputs: rowInputs, - contentInputsByPostID: contentInputsByPostID, - renderState: FireTopicDetailRenderState( - originalRow: originalRow, - replyRows: replyRows, - contentByPostID: contentByPostID - ) - ) - } - - static func detailRenderCache( - sourceSnapshot: TopicDetailSourceSnapshotState, - treePresentation: TopicTreePresentationState, - baseURLString: String, - previous: FireTopicDetailRenderCache? = nil - ) -> FireTopicDetailRenderCache { - let normalizedReplyRows = uniqueTreeRowsPreservingOrder(treePresentation.replyRows).filter { row in - row.postId != sourceSnapshot.body.post.id - } - let postsByID = topicPostsByID([sourceSnapshot.body.post] + sourceSnapshot.loadedPosts) - let orderedPosts = uniqueTopicPostsPreservingOrder( - [sourceSnapshot.body.post] + normalizedReplyRows.compactMap { postsByID[$0.postId] } - ) - let rowInputs = [timelineRowInput(for: sourceSnapshot.body.post)] - + normalizedReplyRows.map(timelineRowInput(for:)) - let contentInputsByPostID = Dictionary( - orderedPosts.map { post in - (post.id, renderInput(for: post)) - }, - uniquingKeysWith: { _, newest in newest } - ) - - let originalRow = originalTimelineRow(for: sourceSnapshot.body.post) - let preparedReplyRows: [FirePreparedTopicTimelineRow] - if let previous, - previous.rowInputs.count <= rowInputs.count, - Array(rowInputs.prefix(previous.rowInputs.count)) == previous.rowInputs { - let suffixRows = normalizedReplyRows - .dropFirst(previous.renderState.replyRows.count) - .map(replyTimelineRow(from:)) - preparedReplyRows = previous.renderState.replyRows + suffixRows - } else { - preparedReplyRows = normalizedReplyRows.map(replyTimelineRow(from:)) - } - - var contentByPostID: [UInt64: FireTopicPostRenderContent] = [:] - contentByPostID.reserveCapacity(orderedPosts.count) - let canReuseContent = previous?.baseURLString == baseURLString - for post in orderedPosts { - if canReuseContent, - previous?.contentInputsByPostID[post.id] == contentInputsByPostID[post.id], - let cachedContent = previous?.renderState.contentByPostID[post.id] { - contentByPostID[post.id] = cachedContent - } else { - contentByPostID[post.id] = renderContent(from: post) - } - } - - return FireTopicDetailRenderCache( - baseURLString: baseURLString, - rowInputs: rowInputs, - contentInputsByPostID: contentInputsByPostID, - renderState: FireTopicDetailRenderState( - originalRow: originalRow, - replyRows: preparedReplyRows, - contentByPostID: contentByPostID - ) - ) - } - - static func detailRenderCache( - sourceSnapshot: TopicDetailSourceSnapshotState, - appending replyRows: [TopicTreeRowState], - baseURLString: String, - previous: FireTopicDetailRenderCache - ) -> FireTopicDetailRenderCache? { - let originalInput = renderInput(for: sourceSnapshot.body.post) - guard !replyRows.isEmpty, - previous.baseURLString == baseURLString, - previous.rowInputs.first == timelineRowInput(for: sourceSnapshot.body.post), - previous.contentInputsByPostID[sourceSnapshot.body.post.id] == originalInput, - previous.renderState.originalRow?.entry.postId == sourceSnapshot.body.post.id, - previous.renderState.contentByPostID[sourceSnapshot.body.post.id] != nil, - previous.rowInputs.count == previous.renderState.replyRows.count + 1 else { - return nil - } - - var rowInputs = previous.rowInputs - rowInputs.reserveCapacity(rowInputs.count + replyRows.count) - - var contentInputsByPostID = previous.contentInputsByPostID - contentInputsByPostID.reserveCapacity(contentInputsByPostID.count + replyRows.count) - - var preparedReplyRows = previous.renderState.replyRows - preparedReplyRows.reserveCapacity(preparedReplyRows.count + replyRows.count) - - var contentByPostID = previous.renderState.contentByPostID - contentByPostID.reserveCapacity(contentByPostID.count + replyRows.count) - - let postsByID = topicPostsByID([sourceSnapshot.body.post] + sourceSnapshot.loadedPosts) - for treeRow in replyRows { - guard let post = postsByID[treeRow.postId] else { - return nil - } - guard contentInputsByPostID[post.id] == nil else { - return nil - } - - rowInputs.append(timelineRowInput(for: treeRow)) - contentInputsByPostID[post.id] = renderInput(for: post) - preparedReplyRows.append(replyTimelineRow(from: treeRow)) - contentByPostID[post.id] = renderContent(from: post) - } - - return FireTopicDetailRenderCache( - baseURLString: baseURLString, - rowInputs: rowInputs, - contentInputsByPostID: contentInputsByPostID, - renderState: FireTopicDetailRenderState( - originalRow: previous.renderState.originalRow ?? originalTimelineRow(for: sourceSnapshot.body.post), - replyRows: preparedReplyRows, - contentByPostID: contentByPostID - ) - ) - } - - static func minimumReplyLength(from minPostLength: UInt32) -> Int { - max(Int(minPostLength), 1) - } - - static func enabledReactionOptions(from reactionIDs: [String]) -> [FireReactionOption] { - reactionOptions(from: reactionIDs, currentReactionID: nil) - } - - /// Compact strip under the action row — always show a friendly common set. - /// (Site `enabledReactionIds` is often just `heart`; filtering to that made the strip look empty.) - static let quickReactionPreferenceIDs = [ - "heart", "+1", "laughing", "open_mouth", "cry", "clap", "tada", "confused", - ] - - static func quickReactionOptions(from reactionIDs: [String]) -> [FireReactionOption] { - let enabled = reactionIDs - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - // Prefer site-enabled reactions first (preserve server order), then fill with commons. - var ordered: [String] = [] - for id in enabled { - if !ordered.contains(where: { $0.caseInsensitiveCompare(id) == .orderedSame }) { - ordered.append(id) - } - } - for id in quickReactionPreferenceIDs { - if !ordered.contains(where: { $0.caseInsensitiveCompare(id) == .orderedSame }) { - ordered.append(id) - } - } - if ordered.isEmpty { - ordered = quickReactionPreferenceIDs - } - return Array(ordered.prefix(8)).map(reactionOption(for:)) - } - - static func reactionOptions( - from reactionIDs: [String], - currentReactionID: String? - ) -> [FireReactionOption] { - var ids = reactionIDs.isEmpty ? ["heart"] : reactionIDs - if let currentReactionID = currentReactionID?.trimmingCharacters(in: .whitespacesAndNewlines), - !currentReactionID.isEmpty { - ids.append(currentReactionID) - } - return ids.reduce(into: [FireReactionOption]()) { result, reactionID in - let trimmedReactionID = reactionID.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmedReactionID.isEmpty, - !result.contains(where: { $0.id.caseInsensitiveCompare(trimmedReactionID) == .orderedSame }) else { - return - } - result.append(reactionOption(for: trimmedReactionID)) - } - } - - static func filterReactionOptions( - _ options: [FireReactionOption], - query: String - ) -> [FireReactionOption] { - let needle = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - guard !needle.isEmpty else { return options } - return options.filter { option in - option.id.lowercased().contains(needle) - || option.label.lowercased().contains(needle) - || option.symbol.contains(needle) - } - } - - static func reactionOption(for reactionID: String) -> FireReactionOption { - let normalized = reactionID.lowercased() - let mapping: [String: (String, String)] = [ - "heart": ("❤️", "点赞"), - "+1": ("👍", "赞同"), - "-1": ("👎", "反对"), - "thumbsup": ("👍", "赞同"), - "laughing": ("😆", "笑哭"), - "open_mouth": ("😮", "惊讶"), - "cry": ("😢", "难过"), - "angry": ("😡", "生气"), - "confused": ("😕", "困惑"), - "clap": ("👏", "鼓掌"), - "tada": ("🎉", "庆祝"), - ] - let fallbackLabel = normalized.replacingOccurrences(of: "_", with: " ") - let (symbol, label) = mapping[normalized] ?? ("🙂", fallbackLabel) - return FireReactionOption(id: reactionID, symbol: symbol, label: label) - } - - static func mergeTopicPosts( - existing: [TopicPostState], - incoming: [TopicPostState], - orderedPostIDs: [UInt64] - ) -> [TopicPostState] { - let orderedPostIDs = uniqueTopicPostIDsPreservingOrder(orderedPostIDs) - if incoming.isEmpty, - existing.count == orderedPostIDs.count, - zip(existing, orderedPostIDs).allSatisfy({ post, postID in - post.id == postID - }) { - return existing - } - - var postsByID: [UInt64: TopicPostState] = [:] - for post in existing { - postsByID[post.id] = post - } - for post in incoming { - postsByID[post.id] = post - } - - var mergedPosts: [TopicPostState] = [] - mergedPosts.reserveCapacity(postsByID.count) - for postID in orderedPostIDs { - if let post = postsByID.removeValue(forKey: postID) { - mergedPosts.append(post) - } - } - - let trailingPosts = postsByID.values.sorted(by: comparePosts(_:_:)) - mergedPosts.append(contentsOf: trailingPosts) - return mergedPosts - } - - static func uniqueTopicPostsPreservingOrder(_ posts: [TopicPostState]) -> [TopicPostState] { - var orderedPostIDs: [UInt64] = [] - orderedPostIDs.reserveCapacity(posts.count) - var postsByID: [UInt64: TopicPostState] = [:] - postsByID.reserveCapacity(posts.count) - - for post in posts { - if postsByID[post.id] == nil { - orderedPostIDs.append(post.id) - } - postsByID[post.id] = post - } - - return orderedPostIDs.compactMap { postsByID[$0] } - } - - static func uniqueTreeRowsPreservingOrder( - _ rows: [TopicTreeRowState] - ) -> [TopicTreeRowState] { - var orderedPostIDs: [UInt64] = [] - orderedPostIDs.reserveCapacity(rows.count) - var rowsByPostID: [UInt64: TopicTreeRowState] = [:] - rowsByPostID.reserveCapacity(rows.count) - - for row in rows { - if rowsByPostID[row.postId] == nil { - orderedPostIDs.append(row.postId) - } - rowsByPostID[row.postId] = row - } - - return orderedPostIDs.compactMap { rowsByPostID[$0] } - } - - static func uniqueTopicPostIDsPreservingOrder(_ postIDs: [UInt64]) -> [UInt64] { - var seenPostIDs = Set() - seenPostIDs.reserveCapacity(postIDs.count) - var orderedPostIDs: [UInt64] = [] - orderedPostIDs.reserveCapacity(postIDs.count) - - for postID in postIDs where seenPostIDs.insert(postID).inserted { - orderedPostIDs.append(postID) - } - - return orderedPostIDs - } - - static func topicPostsByID(_ posts: [TopicPostState]) -> [UInt64: TopicPostState] { - Dictionary( - posts.map { ($0.id, $0) }, - uniquingKeysWith: { _, newest in newest } - ) - } - - // MARK: - Timeline Entries - - /// Builds timeline entries using DFS ordering: children are grouped immediately - /// after their parent so that the visual thread structure is correct. - /// When the original post is not in the loaded set (partial/anchored load), falls - /// back to postNumber ordering with depth computed by walking the reply chain. - static func rebuildTimelineEntries(from posts: [TopicPostState]) -> [FireTopicTimelineEntry] { - guard !posts.isEmpty else { return [] } - - let postNumbers = Set(posts.map(\.postNumber)) - let minPN = posts.map(\.postNumber).min() ?? 0 - - // Detect the original post: the earliest post with no parent reference. - // If no such post exists, this is a partial/anchored load — use flat ordering. - let opPost = posts - .filter { normalizedReplyTarget($0.replyToPostNumber) == nil } - .min(by: comparePosts(_:_:)) - - guard let opPost, opPost.postNumber == minPN else { - // Partial load — fall back to flat postNumber ordering with depth walk - return flatTimelineEntries(from: posts, postNumbers: postNumbers, minPN: minPN) - } - - // Full/near-full load: use DFS ordering - return dfsTimelineEntries(from: posts, opPost: opPost, postNumbers: postNumbers) - } - - /// Flat postNumber ordering with depth computed by walking the parent chain. - /// Used for partial/anchored loads where the OP may not be present. - private static func flatTimelineEntries( - from posts: [TopicPostState], - postNumbers: Set, - minPN: UInt32 - ) -> [FireTopicTimelineEntry] { - let sorted = posts.sorted(by: comparePosts(_:_:)) - return sorted.map { post in - let parent = normalizedReplyTarget(post.replyToPostNumber) - let depth: UInt32 - if let pn = parent, pn != post.postNumber { - depth = computeDepthWalk( - parentPN: pn, posts: posts, loaded: postNumbers, currentDepth: 1 - ) - } else { - depth = 0 - } - return FireTopicTimelineEntry( - postId: post.id, - postNumber: post.postNumber, - parentPostNumber: parent, - depth: depth, - isOriginalPost: post.postNumber == minPN && parent == nil - ) - } - } - - /// DFS ordering: groups children immediately after their parent. - private static func dfsTimelineEntries( - from posts: [TopicPostState], - opPost: TopicPostState, - postNumbers: Set - ) -> [FireTopicTimelineEntry] { - let opPN = opPost.postNumber - - // Build children-by-parent map - var childrenByParent: [UInt32: [TopicPostState]] = [:] - var topLevelPosts: [TopicPostState] = [] - - for post in posts { - if post.postNumber == opPN { - continue - } - - let parent = normalizedReplyTarget(post.replyToPostNumber) - // A post is top-level if: no parent, self-ref, replies to OP, - // or its parent is not loaded. - let isTopLevel = parent == nil - || parent == post.postNumber - || parent == opPN - || parent.map({ !postNumbers.contains($0) }) ?? false - - if isTopLevel { - topLevelPosts.append(post) - } else if let parentPN = parent { - childrenByParent[parentPN, default: []].append(post) - } - } - - // Sort children within each group by postNumber - for key in childrenByParent.keys { - childrenByParent[key]?.sort(by: comparePosts(_:_:)) - } - topLevelPosts.sort(by: comparePosts(_:_:)) - - // DFS traversal - var result: [FireTopicTimelineEntry] = [] - var visited: Set = [opPN] - - // Add OP first - result.append(FireTopicTimelineEntry( - postId: opPost.id, - postNumber: opPost.postNumber, - parentPostNumber: nil, - depth: 0, - isOriginalPost: true - )) - - func dfs(post: TopicPostState, depth: UInt32) { - guard !visited.contains(post.postNumber) else { return } - visited.insert(post.postNumber) - - let parent = normalizedReplyTarget(post.replyToPostNumber) - result.append(FireTopicTimelineEntry( - postId: post.id, - postNumber: post.postNumber, - parentPostNumber: parent, - depth: depth, - isOriginalPost: false - )) - - if let children = childrenByParent[post.postNumber] { - for child in children { - dfs(post: child, depth: depth + 1) - } - } - } - - // Process top-level posts (depth 1 = direct replies to OP) - for post in topLevelPosts { - dfs(post: post, depth: 1) - } - - // Handle remaining orphans - let remaining = posts - .filter { !visited.contains($0.postNumber) } - .sorted(by: comparePosts(_:_:)) - for post in remaining { - dfs(post: post, depth: 1) - } - - return result - } - - private static func computeDepthWalk( - parentPN: UInt32, - posts: [TopicPostState], - loaded: Set, - currentDepth: UInt32 - ) -> UInt32 { - guard loaded.contains(parentPN) else { return currentDepth } - guard let parentPost = posts.first(where: { $0.postNumber == parentPN }) else { - return currentDepth - } - if let gp = normalizedReplyTarget(parentPost.replyToPostNumber), gp != parentPN { - return computeDepthWalk( - parentPN: gp, posts: posts, loaded: loaded, currentDepth: currentDepth + 1 - ) - } - return currentDepth - } - - static func timelineRows( - entries: [FireTopicTimelineEntry], - posts: [TopicPostState] - ) -> [FireTopicTimelineRow] { - let postsByID = topicPostsByID(posts) - return entries.map { entry in - FireTopicTimelineRow(entry: entry, post: postsByID[entry.postId]) - } - } - - static func missingPostIDs( - orderedPostIDs: [UInt64], - in requestedRange: Range, - loadedPostIDs: Set, - excluding exhaustedPostIDs: Set - ) -> [UInt64] { - let clampedRange = requestedRange.clamped(to: 0.. UInt32 { - interactionCount( - likeCount: detail.likeCount, - posts: detail.postStream.posts - ) - } - - static func interactionCount( - likeCount: UInt32, - posts: [TopicPostState] - ) -> UInt32 { - let extraReactionCount = posts - .flatMap(\.reactions) - .filter { $0.id.caseInsensitiveCompare("heart") != .orderedSame } - .reduce(0 as UInt32) { partialResult, reaction in - partialResult > UInt32.max - reaction.count - ? UInt32.max - : partialResult + reaction.count - } - return likeCount > UInt32.max - extraReactionCount - ? UInt32.max - : likeCount + extraReactionCount - } - - static func loadedWindowCount(detail: TopicDetailState) -> Int { - loadedWindowCount( - orderedPostIDs: detail.postStream.stream, - loadedPosts: detail.postStream.posts - ) - } - - static func loadedWindowCount( - orderedPostIDs: [UInt64], - loadedPosts: [TopicPostState] - ) -> Int { - guard !orderedPostIDs.isEmpty else { - return loadedPosts.count - } - - let loadedPostIDs = Set(loadedPosts.map(\.id)) - var loadedWindowCount = 0 - for postID in orderedPostIDs { - guard loadedPostIDs.contains(postID) else { - break - } - loadedWindowCount += 1 - } - return loadedWindowCount - } - - static func missingPostIDs( - orderedPostIDs: [UInt64], - loadedPostIDs: Set, - upTo targetLoadedCount: Int, - excluding exhaustedPostIDs: Set = [] - ) -> [UInt64] { - let targetCount = max(0, min(targetLoadedCount, orderedPostIDs.count)) - guard targetCount > 0 else { - return [] - } - - return orderedPostIDs.prefix(targetCount).filter { postID in - !loadedPostIDs.contains(postID) && !exhaustedPostIDs.contains(postID) - } - } - - static func missingPostIDs( - in detail: TopicDetailState, - upTo targetLoadedCount: Int, - excluding exhaustedPostIDs: Set = [] - ) -> [UInt64] { - missingPostIDs( - orderedPostIDs: detail.postStream.stream, - loadedPostIDs: Set(detail.postStream.posts.map(\.id)), - upTo: targetLoadedCount, - excluding: exhaustedPostIDs - ) - } - - private static func compactCount(_ value: UInt64) -> String { - switch value { - case 0..<1_000: - return "\(value)" - case 1_000..<10_000: - return compactCountSegment(Double(value), divisor: 1_000, suffix: "k") - case 10_000..<100_000_000: - return compactCountSegment(Double(value), divisor: 10_000, suffix: "万") - default: - return compactCountSegment(Double(value), divisor: 100_000_000, suffix: "亿") - } - } - - private static func compactCountSegment(_ value: Double, divisor: Double, suffix: String) -> String { - let compact = value / divisor - let formatted: String - - if compact >= 10 { - formatted = String(format: "%.0f", compact.rounded()) - } else { - formatted = String(format: "%.1f", compact) - } - - return formatted.replacingOccurrences(of: ".0", with: "") + suffix - } - - private static func normalizedReplyTarget(_ replyToPostNumber: UInt32?) -> UInt32? { - guard let replyToPostNumber, replyToPostNumber > 0 else { - return nil - } - return replyToPostNumber - } - - private static func comparePosts(_ lhs: TopicPostState, _ rhs: TopicPostState) -> Bool { - if lhs.postNumber != rhs.postNumber { - return lhs.postNumber < rhs.postNumber - } - return lhs.id < rhs.id - } - - private static let fractionalISO8601: ISO8601DateFormatter = { - let formatter = ISO8601DateFormatter() - formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] - return formatter - }() - - private static let basicISO8601: ISO8601DateFormatter = { - let formatter = ISO8601DateFormatter() - formatter.formatOptions = [.withInternetDateTime] - return formatter - }() - - private static let displayFormatter: DateFormatter = { - let formatter = DateFormatter() - formatter.dateStyle = .medium - formatter.timeStyle = .short - return formatter - }() - -} - -private struct TimestampFormatter { - private let fractionalISO8601: ISO8601DateFormatter - private let basicISO8601: ISO8601DateFormatter - private let style: Style - - enum Style { - case full - case compact - } - - init(style: Style = .full) { - self.style = style - - let fractionalISO8601 = ISO8601DateFormatter() - fractionalISO8601.formatOptions = [.withInternetDateTime, .withFractionalSeconds] - self.fractionalISO8601 = fractionalISO8601 - - let basicISO8601 = ISO8601DateFormatter() - basicISO8601.formatOptions = [.withInternetDateTime] - self.basicISO8601 = basicISO8601 - } - - func format(_ rawValue: String?) -> String? { - guard let rawValue, !rawValue.isEmpty else { - return nil - } - - let date = fractionalISO8601.date(from: rawValue) ?? basicISO8601.date(from: rawValue) - guard let date else { - return rawValue - } - - return format(date: date) - } - - func format(date: Date) -> String { - switch style { - case .full: - return Self.fullFormatter.string(from: date) - case .compact: - return Self.compactFormatter.localizedString(for: date, relativeTo: Date()) - } - } - - private static let fullFormatter: DateFormatter = { - let formatter = DateFormatter() - formatter.dateStyle = .medium - formatter.timeStyle = .short - return formatter - }() - - private static let compactFormatter: RelativeDateTimeFormatter = { - let formatter = RelativeDateTimeFormatter() - formatter.unitsStyle = .short - return formatter - }() -} - -extension Color { - init?(fireHex hex: String?) { - guard let hex else { - return nil - } - - let cleaned = hex - .trimmingCharacters(in: CharacterSet.alphanumerics.inverted) - .uppercased() - guard cleaned.count == 6, let value = Int(cleaned, radix: 16) else { - return nil - } - - self.init( - .sRGB, - red: Double((value >> 16) & 0xFF) / 255.0, - green: Double((value >> 8) & 0xFF) / 255.0, - blue: Double(value & 0xFF) / 255.0, - opacity: 1.0 - ) - } -} - -enum FireTopicDetailUiProjection { - static func posts(from snapshot: TopicDetailUiSnapshotState) -> [TopicPostState] { - snapshot.rows.map(post(from:)) - } - - static func timelineEntry(from row: TopicDetailUiRowState) -> FireTopicTimelineEntry { - FireTopicTimelineEntry( - postId: row.postId, - postNumber: row.postNumber, - parentPostNumber: row.parentPostNumber, - depth: UInt32(row.depth), - isOriginalPost: row.isOriginalPost - ) - } - - static func post(from row: TopicDetailUiRowState) -> TopicPostState { - let author = row.author - return TopicPostState( - id: row.postId, - username: author.username, - name: author.name, - avatarTemplate: author.avatarTemplate, - authorMetadata: TopicPostAuthorMetadataState( - userId: author.userId, - userTitle: author.userTitle, - primaryGroupName: author.primaryGroupName, - flairUrl: author.flairUrl, - flairName: author.flairName, - flairBgColor: author.flairBgColor, - flairColor: author.flairColor, - flairGroupId: author.flairGroupId, - moderator: author.moderator, - admin: author.admin, - groupModerator: author.groupModerator, - userStatusEmoji: author.userStatusEmoji, - userStatusDescription: author.userStatusDescription - ), - presentation: row.presentation, - raw: nil, - postNumber: row.postNumber, - postType: row.postType, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - likeCount: row.likeCount, - replyCount: row.replyCount, - replyToPostNumber: row.parentPostNumber, - replyToUser: row.replyToUser.map { - TopicReplyToUserState( - username: $0.username, - name: $0.name, - avatarTemplate: $0.avatarTemplate - ) - }, - bookmarked: row.bookmarked, - bookmarkId: row.bookmarkId, - bookmarkName: row.bookmarkName, - bookmarkReminderAt: row.bookmarkReminderAt, - reactions: row.reactions.map { - TopicReactionState(id: $0.id, kind: $0.kind, count: $0.count, canUndo: $0.canUndo) - }, - currentUserReaction: row.currentReactionId.flatMap { id in - row.reactions.first { $0.id == id }.map { - TopicReactionState(id: $0.id, kind: $0.kind, count: $0.count, canUndo: $0.canUndo) - } - }, - boosts: row.boosts.map { boost in - TopicPostBoostState( - id: boost.id, - presentation: boost.presentation, - displayText: boost.displayText, - user: TopicPostBoostUserState( - id: boost.user.id, - username: boost.user.username, - name: boost.user.name, - avatarTemplate: boost.user.avatarTemplate - ), - canDelete: boost.canDelete, - canFlag: boost.canFlag, - userFlagStatus: boost.userFlagStatus, - availableFlags: boost.availableFlags - ) - }, - canBoost: row.canBoost, - polls: row.polls, - acceptedAnswer: row.acceptedAnswer, - canAcceptAnswer: row.canAcceptAnswer, - canUnacceptAnswer: row.canUnacceptAnswer, - canEdit: row.canEdit, - canDelete: row.canDelete, - canRecover: row.canRecover, - hidden: row.hidden - ) - } } diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicReactionPresentation.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicReactionPresentation.swift new file mode 100644 index 00000000..180a277f --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicReactionPresentation.swift @@ -0,0 +1,85 @@ +import Foundation + +struct FireReactionOption: Identifiable, Hashable, Sendable { + let id: String + let symbol: String + let label: String +} +extension FireTopicPresentation { + static func enabledReactionOptions(from reactionIDs: [String]) -> [FireReactionOption] { + reactionOptions(from: reactionIDs, currentReactionID: nil) + } + static let quickReactionPreferenceIDs = [ + "heart", "+1", "laughing", "open_mouth", "cry", "clap", "tada", "confused", + ] + static func quickReactionOptions(from reactionIDs: [String]) -> [FireReactionOption] { + let enabled = reactionIDs + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + // Prefer site-enabled reactions first (preserve server order), then fill with commons. + var ordered: [String] = [] + for id in enabled { + if !ordered.contains(where: { $0.caseInsensitiveCompare(id) == .orderedSame }) { + ordered.append(id) + } + } + for id in quickReactionPreferenceIDs { + if !ordered.contains(where: { $0.caseInsensitiveCompare(id) == .orderedSame }) { + ordered.append(id) + } + } + if ordered.isEmpty { + ordered = quickReactionPreferenceIDs + } + return Array(ordered.prefix(8)).map(reactionOption(for:)) + } + static func reactionOptions( + from reactionIDs: [String], + currentReactionID: String? + ) -> [FireReactionOption] { + var ids = reactionIDs.isEmpty ? ["heart"] : reactionIDs + if let currentReactionID = currentReactionID?.trimmingCharacters(in: .whitespacesAndNewlines), + !currentReactionID.isEmpty { + ids.append(currentReactionID) + } + return ids.reduce(into: [FireReactionOption]()) { result, reactionID in + let trimmedReactionID = reactionID.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedReactionID.isEmpty, + !result.contains(where: { $0.id.caseInsensitiveCompare(trimmedReactionID) == .orderedSame }) else { + return + } + result.append(reactionOption(for: trimmedReactionID)) + } + } + static func filterReactionOptions( + _ options: [FireReactionOption], + query: String + ) -> [FireReactionOption] { + let needle = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !needle.isEmpty else { return options } + return options.filter { option in + option.id.lowercased().contains(needle) + || option.label.lowercased().contains(needle) + || option.symbol.contains(needle) + } + } + static func reactionOption(for reactionID: String) -> FireReactionOption { + let normalized = reactionID.lowercased() + let mapping: [String: (String, String)] = [ + "heart": ("❤️", "点赞"), + "+1": ("👍", "赞同"), + "-1": ("👎", "反对"), + "thumbsup": ("👍", "赞同"), + "laughing": ("😆", "笑哭"), + "open_mouth": ("😮", "惊讶"), + "cry": ("😢", "难过"), + "angry": ("😡", "生气"), + "confused": ("😕", "困惑"), + "clap": ("👏", "鼓掌"), + "tada": ("🎉", "庆祝"), + ] + let fallbackLabel = normalized.replacingOccurrences(of: "_", with: " ") + let (symbol, label) = mapping[normalized] ?? ("🙂", fallbackLabel) + return FireReactionOption(id: reactionID, symbol: symbol, label: label) + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicRenderModels.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicRenderModels.swift new file mode 100644 index 00000000..1678bc13 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicRenderModels.swift @@ -0,0 +1,133 @@ +import Foundation +import UIKit + +struct FireCookedImage: Identifiable, Hashable, Sendable { + let url: URL + let altText: String? + let width: CGFloat? + let height: CGFloat? + + var id: String { url.absoluteString } + + var aspectRatio: CGFloat? { + guard let width, let height, width > 0, height > 0 else { + return nil + } + return width / height + } +} +struct FireTopicOneboxCard: Hashable, Sendable { + let url: String? + let title: String? + let description: String? + let sourceName: String? + let iconURL: URL? + let thumbnailURL: URL? + let thumbnailWidth: CGFloat? + let thumbnailHeight: CGFloat? +} +struct FireTopicPostRenderSignature: Hashable, Sendable { + let sourceLength: Int + let sourceChecksum: UInt64 + let segmentIDs: [String] + + var token: String { + var parts: [String] = [] + parts.reserveCapacity(segmentIDs.count + 2) + parts.append(String(sourceLength)) + parts.append(String(sourceChecksum, radix: 16)) + parts.append(contentsOf: segmentIDs) + return parts.joined(separator: ":") + } + + static func make( + source: String, + imageAttachments: [FireCookedImage], + segments: [FireTopicPostRenderSegment] = [] + ) -> Self { + FireTopicPostRenderSignature( + sourceLength: source.utf8.count, + sourceChecksum: stableChecksum(source), + segmentIDs: segments.isEmpty + ? imageAttachments.map { "image:\($0.id)" } + : segments.map(\.signatureToken) + ) + } + + fileprivate static func stableChecksum(_ value: String) -> UInt64 { + var hash: UInt64 = 0xcbf29ce484222325 + for byte in value.utf8 { + hash ^= UInt64(byte) + hash &*= 0x100000001b3 + } + hash ^= hash >> 33 + hash &*= 0xff51afd7ed558ccd + hash ^= hash >> 33 + hash &*= 0xc4ceb9fe1a85ec53 + hash ^= hash >> 33 + return hash + } +} +// NSAttributedString is not Sendable; render content is built during cache preparation and then shared immutably. +struct FireTopicPostRenderContent: @unchecked Sendable { + let plainText: String + let attributedText: NSAttributedString? + let imageAttachments: [FireCookedImage] + let segments: [FireTopicPostRenderSegment] + let signature: FireTopicPostRenderSignature +} +// NSAttributedString is immutable after construction and segment values are only read by the UI layer. +enum FireTopicPostRenderSegment: @unchecked Sendable { + case text(NSAttributedString) + case image(FireCookedImage) + case onebox(FireTopicOneboxCard) + + var signatureToken: String { + switch self { + case .text(let attributedText): + return "text:\(attributedText.string.utf8.count):\(FireTopicPostRenderSignature.stableChecksum(attributedText.string))" + case .image(let image): + return "image:\(image.id)" + case .onebox(let card): + return "onebox:\(card.url ?? ""):\(card.thumbnailURL?.absoluteString ?? ""):\(card.title ?? "")" + } + } + + var isImage: Bool { + if case .image = self { return true } + return false + } + + var isOnebox: Bool { + if case .onebox = self { return true } + return false + } + + enum Kind: Hashable { + case text + case image + case onebox + } + + var kind: Kind { + switch self { + case .text: return .text + case .image: return .image + case .onebox: return .onebox + } + } +} +struct FireTopicPostRenderInput: Equatable, Sendable { + let presentationChecksum: UInt64? +} +struct FireTopicDetailRenderState: Sendable { + let originalRow: FirePreparedTopicTimelineRow? + let replyRows: [FirePreparedTopicTimelineRow] + let contentByPostID: [UInt64: FireTopicPostRenderContent] +} +struct FireTopicDetailRenderCache: Sendable { + let baseURLString: String + let rowInputs: [FireTopicTimelineRowInput] + let contentInputsByPostID: [UInt64: FireTopicPostRenderInput] + let renderState: FireTopicDetailRenderState +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicRenderProjection.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicRenderProjection.swift new file mode 100644 index 00000000..92f008bb --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicRenderProjection.swift @@ -0,0 +1,300 @@ +import Foundation +import UIKit + +extension FireTopicPresentation { + static func imageAttachments(from presentation: RenderDocumentHandle) -> [FireCookedImage] { + FireRenderPresentation.images(from: presentation) + } + static func renderContent( + from presentation: RenderDocumentHandle, + sourceToken: String + ) -> FireTopicPostRenderContent { + renderContentFromPresentation(presentation, source: sourceToken) + } + static func renderContent(from post: TopicPostState) -> FireTopicPostRenderContent? { + guard let presentation = post.presentation else { + return nil + } + return renderContentFromPresentation( + presentation, + source: Self.renderInput(for: post).presentationChecksum.map(String.init) ?? "missing" + ) + } + private static func renderInput(for post: TopicPostState) -> FireTopicPostRenderInput { + FireTopicPostRenderInput( + presentationChecksum: post.presentation.map { $0.checksum() } + ) + } + private static func renderContentFromPresentation( + _ presentation: RenderDocumentHandle, + source: String + ) -> FireTopicPostRenderContent { + let imageAttachments = FireRenderPresentation.images(from: presentation) + let richNodes = FireRenderPresentation.richNodes(from: presentation) + let segments = FireRenderPresentation.segments(from: presentation).compactMap { segment -> FireTopicPostRenderSegment? in + switch segment { + case let .rich(nodes): + let attributedText = FireRichTextAttributedStringBuilder.build( + from: nodes, + textColor: FireTheme.uiInk, + accentColor: FireTopicDetailCellColors.accent + ) + return attributedText.length > 0 ? .text(attributedText) : nil + case let .image(image): + return .image(image) + case let .onebox(card): + return .onebox(card) + } + } + + let attributedText = richNodes.isEmpty ? nil : + FireRichTextAttributedStringBuilder.build( + from: richNodes, + textColor: FireTheme.uiInk, + accentColor: FireTopicDetailCellColors.accent + ) + + return FireTopicPostRenderContent( + plainText: presentation.plainText(), + attributedText: attributedText, + imageAttachments: imageAttachments, + segments: segments, + signature: FireTopicPostRenderSignature.make( + source: source, + imageAttachments: imageAttachments, + segments: segments + ) + ) + } + static func detailRenderState( + from detail: TopicDetailState, + baseURLString: String + ) -> FireTopicDetailRenderState { + detailRenderCache( + from: detail, + baseURLString: baseURLString + ).renderState + } + private static func timelineRowInput(for post: TopicPostState) -> FireTopicTimelineRowInput { + FireTopicTimelineRowInput( + postID: post.id, + postNumber: post.postNumber, + replyToPostNumber: post.replyToPostNumber, + responseParentPostNumber: nil, + responseDepth: nil, + responsePreorderIndex: nil, + responseHasChildren: nil, + responseDescendantCount: nil, + responseSiblingIndex: nil, + responseIsLastSibling: nil + ) + } + private static func timelineRowInput(for treeRow: TopicTreeRowState) -> FireTopicTimelineRowInput { + FireTopicTimelineRowInput( + postID: treeRow.postId, + postNumber: treeRow.postNumber, + replyToPostNumber: treeRow.parentPostNumber, + responseParentPostNumber: treeRow.parentPostNumber, + responseDepth: treeRow.depth, + responsePreorderIndex: treeRow.preorderIndex, + responseHasChildren: treeRow.hasChildren, + responseDescendantCount: treeRow.descendantCount, + responseSiblingIndex: treeRow.siblingIndex, + responseIsLastSibling: treeRow.isLastSibling + ) + } + private static func originalTimelineRow(for post: TopicPostState) -> FirePreparedTopicTimelineRow { + FirePreparedTopicTimelineRow( + entry: FireTopicTimelineEntry( + postId: post.id, + postNumber: post.postNumber, + parentPostNumber: nil, + depth: 0, + isOriginalPost: true + ) + ) + } + private static func replyTimelineRow(from treeRow: TopicTreeRowState) -> FirePreparedTopicTimelineRow { + FirePreparedTopicTimelineRow( + entry: FireTopicTimelineEntry( + postId: treeRow.postId, + postNumber: treeRow.postNumber, + parentPostNumber: treeRow.parentPostNumber, + depth: UInt32(treeRow.depth), + isOriginalPost: false + ) + ) + } + static func detailRenderCache( + from detail: TopicDetailState, + baseURLString: String, + previous: FireTopicDetailRenderCache? = nil + ) -> FireTopicDetailRenderCache { + let orderedPosts = uniqueTopicPostsPreservingOrder( + mergeTopicPosts( + existing: detail.postStream.posts, + incoming: [], + orderedPostIDs: detail.postStream.stream + ) + ) + let rowInputs = orderedPosts.map(timelineRowInput(for:)) + let contentInputsByPostID = Dictionary( + orderedPosts.map { post in + (post.id, renderInput(for: post)) + }, + uniquingKeysWith: { _, newest in newest } + ) + + let originalRow: FirePreparedTopicTimelineRow? + let replyRows: [FirePreparedTopicTimelineRow] + if previous?.rowInputs == rowInputs { + originalRow = previous?.renderState.originalRow + replyRows = previous?.renderState.replyRows ?? [] + } else { + let rows = rebuildTimelineEntries(from: orderedPosts).map(FirePreparedTopicTimelineRow.init) + let resolvedOriginalRow = rows.first(where: { $0.entry.isOriginalPost }) + originalRow = resolvedOriginalRow + replyRows = rows.filter { row in + row.entry.postId != resolvedOriginalRow?.entry.postId + } + } + + var contentByPostID: [UInt64: FireTopicPostRenderContent] = [:] + contentByPostID.reserveCapacity(orderedPosts.count) + let canReuseContent = previous?.baseURLString == baseURLString + for post in orderedPosts { + if canReuseContent, + previous?.contentInputsByPostID[post.id] == contentInputsByPostID[post.id], + let cachedContent = previous?.renderState.contentByPostID[post.id] { + contentByPostID[post.id] = cachedContent + } else { + contentByPostID[post.id] = renderContent(from: post) + } + } + + return FireTopicDetailRenderCache( + baseURLString: baseURLString, + rowInputs: rowInputs, + contentInputsByPostID: contentInputsByPostID, + renderState: FireTopicDetailRenderState( + originalRow: originalRow, + replyRows: replyRows, + contentByPostID: contentByPostID + ) + ) + } + static func detailRenderCache( + sourceSnapshot: TopicDetailSourceSnapshotState, + treePresentation: TopicTreePresentationState, + baseURLString: String, + previous: FireTopicDetailRenderCache? = nil + ) -> FireTopicDetailRenderCache { + let normalizedReplyRows = uniqueTreeRowsPreservingOrder(treePresentation.replyRows).filter { row in + row.postId != sourceSnapshot.body.post.id + } + let postsByID = topicPostsByID([sourceSnapshot.body.post] + sourceSnapshot.loadedPosts) + let orderedPosts = uniqueTopicPostsPreservingOrder( + [sourceSnapshot.body.post] + normalizedReplyRows.compactMap { postsByID[$0.postId] } + ) + let rowInputs = [timelineRowInput(for: sourceSnapshot.body.post)] + + normalizedReplyRows.map(timelineRowInput(for:)) + let contentInputsByPostID = Dictionary( + orderedPosts.map { post in + (post.id, renderInput(for: post)) + }, + uniquingKeysWith: { _, newest in newest } + ) + + let originalRow = originalTimelineRow(for: sourceSnapshot.body.post) + let preparedReplyRows: [FirePreparedTopicTimelineRow] + if let previous, + previous.rowInputs.count <= rowInputs.count, + Array(rowInputs.prefix(previous.rowInputs.count)) == previous.rowInputs { + let suffixRows = normalizedReplyRows + .dropFirst(previous.renderState.replyRows.count) + .map(replyTimelineRow(from:)) + preparedReplyRows = previous.renderState.replyRows + suffixRows + } else { + preparedReplyRows = normalizedReplyRows.map(replyTimelineRow(from:)) + } + + var contentByPostID: [UInt64: FireTopicPostRenderContent] = [:] + contentByPostID.reserveCapacity(orderedPosts.count) + let canReuseContent = previous?.baseURLString == baseURLString + for post in orderedPosts { + if canReuseContent, + previous?.contentInputsByPostID[post.id] == contentInputsByPostID[post.id], + let cachedContent = previous?.renderState.contentByPostID[post.id] { + contentByPostID[post.id] = cachedContent + } else { + contentByPostID[post.id] = renderContent(from: post) + } + } + + return FireTopicDetailRenderCache( + baseURLString: baseURLString, + rowInputs: rowInputs, + contentInputsByPostID: contentInputsByPostID, + renderState: FireTopicDetailRenderState( + originalRow: originalRow, + replyRows: preparedReplyRows, + contentByPostID: contentByPostID + ) + ) + } + static func detailRenderCache( + sourceSnapshot: TopicDetailSourceSnapshotState, + appending replyRows: [TopicTreeRowState], + baseURLString: String, + previous: FireTopicDetailRenderCache + ) -> FireTopicDetailRenderCache? { + let originalInput = renderInput(for: sourceSnapshot.body.post) + guard !replyRows.isEmpty, + previous.baseURLString == baseURLString, + previous.rowInputs.first == timelineRowInput(for: sourceSnapshot.body.post), + previous.contentInputsByPostID[sourceSnapshot.body.post.id] == originalInput, + previous.renderState.originalRow?.entry.postId == sourceSnapshot.body.post.id, + previous.renderState.contentByPostID[sourceSnapshot.body.post.id] != nil, + previous.rowInputs.count == previous.renderState.replyRows.count + 1 else { + return nil + } + + var rowInputs = previous.rowInputs + rowInputs.reserveCapacity(rowInputs.count + replyRows.count) + + var contentInputsByPostID = previous.contentInputsByPostID + contentInputsByPostID.reserveCapacity(contentInputsByPostID.count + replyRows.count) + + var preparedReplyRows = previous.renderState.replyRows + preparedReplyRows.reserveCapacity(preparedReplyRows.count + replyRows.count) + + var contentByPostID = previous.renderState.contentByPostID + contentByPostID.reserveCapacity(contentByPostID.count + replyRows.count) + + let postsByID = topicPostsByID([sourceSnapshot.body.post] + sourceSnapshot.loadedPosts) + for treeRow in replyRows { + guard let post = postsByID[treeRow.postId] else { + return nil + } + guard contentInputsByPostID[post.id] == nil else { + return nil + } + + rowInputs.append(timelineRowInput(for: treeRow)) + contentInputsByPostID[post.id] = renderInput(for: post) + preparedReplyRows.append(replyTimelineRow(from: treeRow)) + contentByPostID[post.id] = renderContent(from: post) + } + + return FireTopicDetailRenderCache( + baseURLString: baseURLString, + rowInputs: rowInputs, + contentInputsByPostID: contentInputsByPostID, + renderState: FireTopicDetailRenderState( + originalRow: previous.renderState.originalRow ?? originalTimelineRow(for: sourceSnapshot.body.post), + replyRows: preparedReplyRows, + contentByPostID: contentByPostID + ) + ) + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicReplyPresentation.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicReplyPresentation.swift new file mode 100644 index 00000000..2a2fc8b1 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicReplyPresentation.swift @@ -0,0 +1,37 @@ +import Foundation + +extension FireTopicPresentation { + static func replyTargetPostNumber( + for post: TopicPostState, + preferredPostNumber: UInt32? + ) -> UInt32? { + preferredPostNumber ?? post.replyToPostNumber + } + static func replyContextLabel( + for post: TopicPostState, + preferredPostNumber: UInt32? + ) -> String? { + let targetPostNumber = replyTargetPostNumber( + for: post, + preferredPostNumber: preferredPostNumber + ) + guard let targetPostNumber, targetPostNumber > 0 else { + return nil + } + + let canUseReplyUser = preferredPostNumber == nil + || preferredPostNumber == post.replyToPostNumber + if canUseReplyUser { + let username = post.replyToUser?.username + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !username.isEmpty { + return "回复 @\(username)" + } + } + + return "回复 #\(targetPostNumber)" + } + static func minimumReplyLength(from minPostLength: UInt32) -> Int { + max(Int(minPostLength), 1) + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicSearchPresentation.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicSearchPresentation.swift new file mode 100644 index 00000000..03c1c65c --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicSearchPresentation.swift @@ -0,0 +1,32 @@ +import Foundation + +struct FireTopicSearchMatch: Equatable, Sendable { + let postID: UInt64 + let postNumber: UInt32 +} +extension FireTopicPresentation { + static func topicSearchMatches( + query: String, + posts: [TopicPostState] + ) -> [FireTopicSearchMatch] { + let needle = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !needle.isEmpty else { + return [] + } + + var seenPostIDs = Set() + return posts + .filter { seenPostIDs.insert($0.id).inserted } + .filter { post in + let plainText = post.presentation?.plainText() ?? "" + return plainText.range(of: needle, options: [.caseInsensitive, .diacriticInsensitive]) != nil + } + .sorted { lhs, rhs in + if lhs.postNumber == rhs.postNumber { + return lhs.id < rhs.id + } + return lhs.postNumber < rhs.postNumber + } + .map { FireTopicSearchMatch(postID: $0.id, postNumber: $0.postNumber) } + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicTimelineBuilder.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicTimelineBuilder.swift new file mode 100644 index 00000000..1e62113f --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicTimelineBuilder.swift @@ -0,0 +1,259 @@ +import Foundation + +extension FireTopicPresentation { + /// Builds timeline entries using DFS ordering: children are grouped immediately + /// after their parent so that the visual thread structure is correct. + /// When the original post is not in the loaded set (partial/anchored load), falls + /// back to postNumber ordering with depth computed by walking the reply chain. + static func rebuildTimelineEntries(from posts: [TopicPostState]) -> [FireTopicTimelineEntry] { + guard !posts.isEmpty else { return [] } + + let postNumbers = Set(posts.map(\.postNumber)) + let minPN = posts.map(\.postNumber).min() ?? 0 + + // Detect the original post: the earliest post with no parent reference. + // If no such post exists, this is a partial/anchored load — use flat ordering. + let opPost = posts + .filter { normalizedReplyTarget($0.replyToPostNumber) == nil } + .min(by: comparePosts(_:_:)) + + guard let opPost, opPost.postNumber == minPN else { + // Partial load — fall back to flat postNumber ordering with depth walk + return flatTimelineEntries(from: posts, postNumbers: postNumbers, minPN: minPN) + } + + // Full/near-full load: use DFS ordering + return dfsTimelineEntries(from: posts, opPost: opPost, postNumbers: postNumbers) + } + /// Flat postNumber ordering with depth computed by walking the parent chain. + /// Used for partial/anchored loads where the OP may not be present. + private static func flatTimelineEntries( + from posts: [TopicPostState], + postNumbers: Set, + minPN: UInt32 + ) -> [FireTopicTimelineEntry] { + let sorted = posts.sorted(by: comparePosts(_:_:)) + return sorted.map { post in + let parent = normalizedReplyTarget(post.replyToPostNumber) + let depth: UInt32 + if let pn = parent, pn != post.postNumber { + depth = computeDepthWalk( + parentPN: pn, posts: posts, loaded: postNumbers, currentDepth: 1 + ) + } else { + depth = 0 + } + return FireTopicTimelineEntry( + postId: post.id, + postNumber: post.postNumber, + parentPostNumber: parent, + depth: depth, + isOriginalPost: post.postNumber == minPN && parent == nil + ) + } + } + /// DFS ordering: groups children immediately after their parent. + private static func dfsTimelineEntries( + from posts: [TopicPostState], + opPost: TopicPostState, + postNumbers: Set + ) -> [FireTopicTimelineEntry] { + let opPN = opPost.postNumber + + // Build children-by-parent map + var childrenByParent: [UInt32: [TopicPostState]] = [:] + var topLevelPosts: [TopicPostState] = [] + + for post in posts { + if post.postNumber == opPN { + continue + } + + let parent = normalizedReplyTarget(post.replyToPostNumber) + // A post is top-level if: no parent, self-ref, replies to OP, + // or its parent is not loaded. + let isTopLevel = parent == nil + || parent == post.postNumber + || parent == opPN + || parent.map({ !postNumbers.contains($0) }) ?? false + + if isTopLevel { + topLevelPosts.append(post) + } else if let parentPN = parent { + childrenByParent[parentPN, default: []].append(post) + } + } + + // Sort children within each group by postNumber + for key in childrenByParent.keys { + childrenByParent[key]?.sort(by: comparePosts(_:_:)) + } + topLevelPosts.sort(by: comparePosts(_:_:)) + + // DFS traversal + var result: [FireTopicTimelineEntry] = [] + var visited: Set = [opPN] + + // Add OP first + result.append(FireTopicTimelineEntry( + postId: opPost.id, + postNumber: opPost.postNumber, + parentPostNumber: nil, + depth: 0, + isOriginalPost: true + )) + + func dfs(post: TopicPostState, depth: UInt32) { + guard !visited.contains(post.postNumber) else { return } + visited.insert(post.postNumber) + + let parent = normalizedReplyTarget(post.replyToPostNumber) + result.append(FireTopicTimelineEntry( + postId: post.id, + postNumber: post.postNumber, + parentPostNumber: parent, + depth: depth, + isOriginalPost: false + )) + + if let children = childrenByParent[post.postNumber] { + for child in children { + dfs(post: child, depth: depth + 1) + } + } + } + + // Process top-level posts (depth 1 = direct replies to OP) + for post in topLevelPosts { + dfs(post: post, depth: 1) + } + + // Handle remaining orphans + let remaining = posts + .filter { !visited.contains($0.postNumber) } + .sorted(by: comparePosts(_:_:)) + for post in remaining { + dfs(post: post, depth: 1) + } + + return result + } + private static func computeDepthWalk( + parentPN: UInt32, + posts: [TopicPostState], + loaded: Set, + currentDepth: UInt32 + ) -> UInt32 { + guard loaded.contains(parentPN) else { return currentDepth } + guard let parentPost = posts.first(where: { $0.postNumber == parentPN }) else { + return currentDepth + } + if let gp = normalizedReplyTarget(parentPost.replyToPostNumber), gp != parentPN { + return computeDepthWalk( + parentPN: gp, posts: posts, loaded: loaded, currentDepth: currentDepth + 1 + ) + } + return currentDepth + } + static func timelineRows( + entries: [FireTopicTimelineEntry], + posts: [TopicPostState] + ) -> [FireTopicTimelineRow] { + let postsByID = topicPostsByID(posts) + return entries.map { entry in + FireTopicTimelineRow(entry: entry, post: postsByID[entry.postId]) + } + } + static func missingPostIDs( + orderedPostIDs: [UInt64], + in requestedRange: Range, + loadedPostIDs: Set, + excluding exhaustedPostIDs: Set + ) -> [UInt64] { + let clampedRange = requestedRange.clamped(to: 0.. UInt32 { + interactionCount( + likeCount: detail.likeCount, + posts: detail.postStream.posts + ) + } + static func interactionCount( + likeCount: UInt32, + posts: [TopicPostState] + ) -> UInt32 { + let extraReactionCount = posts + .flatMap(\.reactions) + .filter { $0.id.caseInsensitiveCompare("heart") != .orderedSame } + .reduce(0 as UInt32) { partialResult, reaction in + partialResult > UInt32.max - reaction.count + ? UInt32.max + : partialResult + reaction.count + } + return likeCount > UInt32.max - extraReactionCount + ? UInt32.max + : likeCount + extraReactionCount + } + static func loadedWindowCount(detail: TopicDetailState) -> Int { + loadedWindowCount( + orderedPostIDs: detail.postStream.stream, + loadedPosts: detail.postStream.posts + ) + } + static func loadedWindowCount( + orderedPostIDs: [UInt64], + loadedPosts: [TopicPostState] + ) -> Int { + guard !orderedPostIDs.isEmpty else { + return loadedPosts.count + } + + let loadedPostIDs = Set(loadedPosts.map(\.id)) + var loadedWindowCount = 0 + for postID in orderedPostIDs { + guard loadedPostIDs.contains(postID) else { + break + } + loadedWindowCount += 1 + } + return loadedWindowCount + } + static func missingPostIDs( + orderedPostIDs: [UInt64], + loadedPostIDs: Set, + upTo targetLoadedCount: Int, + excluding exhaustedPostIDs: Set = [] + ) -> [UInt64] { + let targetCount = max(0, min(targetLoadedCount, orderedPostIDs.count)) + guard targetCount > 0 else { + return [] + } + + return orderedPostIDs.prefix(targetCount).filter { postID in + !loadedPostIDs.contains(postID) && !exhaustedPostIDs.contains(postID) + } + } + static func missingPostIDs( + in detail: TopicDetailState, + upTo targetLoadedCount: Int, + excluding exhaustedPostIDs: Set = [] + ) -> [UInt64] { + missingPostIDs( + orderedPostIDs: detail.postStream.stream, + loadedPostIDs: Set(detail.postStream.posts.map(\.id)), + upTo: targetLoadedCount, + excluding: exhaustedPostIDs + ) + } + private static func normalizedReplyTarget(_ replyToPostNumber: UInt32?) -> UInt32? { + guard let replyToPostNumber, replyToPostNumber > 0 else { + return nil + } + return replyToPostNumber + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicTimelineModels.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicTimelineModels.swift new file mode 100644 index 00000000..0568453b --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicTimelineModels.swift @@ -0,0 +1,57 @@ +import Foundation + +typealias FireTopicRowPresentation = TopicRowState +struct FireTopicTimelineEntry: Hashable, Sendable { + let postId: UInt64 + let postNumber: UInt32 + let parentPostNumber: UInt32? + let depth: UInt32 + let isOriginalPost: Bool +} +struct FireTopicTimelineRow: Identifiable { + let entry: FireTopicTimelineEntry + let post: TopicPostState? + var id: UInt64 { entry.postId } + var isLoaded: Bool { post != nil } +} +struct FirePreparedTopicTimelineRow: Identifiable, Sendable { + let entry: FireTopicTimelineEntry + + var id: UInt64 { entry.postId } +} +struct FireTopicTimelineRowInput: Equatable, Sendable { + let postID: UInt64 + let postNumber: UInt32 + let replyToPostNumber: UInt32? + let responseParentPostNumber: UInt32? + let responseDepth: UInt16? + let responsePreorderIndex: UInt32? + let responseHasChildren: Bool? + let responseDescendantCount: UInt32? + let responseSiblingIndex: UInt16? + let responseIsLastSibling: Bool? + + init( + postID: UInt64, + postNumber: UInt32, + replyToPostNumber: UInt32?, + responseParentPostNumber: UInt32? = nil, + responseDepth: UInt16? = nil, + responsePreorderIndex: UInt32? = nil, + responseHasChildren: Bool? = nil, + responseDescendantCount: UInt32? = nil, + responseSiblingIndex: UInt16? = nil, + responseIsLastSibling: Bool? = nil + ) { + self.postID = postID + self.postNumber = postNumber + self.replyToPostNumber = replyToPostNumber + self.responseParentPostNumber = responseParentPostNumber + self.responseDepth = responseDepth + self.responsePreorderIndex = responsePreorderIndex + self.responseHasChildren = responseHasChildren + self.responseDescendantCount = responseDescendantCount + self.responseSiblingIndex = responseSiblingIndex + self.responseIsLastSibling = responseIsLastSibling + } +} diff --git a/apps/ios-app/App/TopicDetail/Support/FireTopicVotersSheet.swift b/apps/ios-app/App/TopicDetail/Support/FireTopicVotersSheet.swift new file mode 100644 index 00000000..3573bd02 --- /dev/null +++ b/apps/ios-app/App/TopicDetail/Support/FireTopicVotersSheet.swift @@ -0,0 +1,52 @@ +import SwiftUI + +struct FireTopicVotersSheet: View { + let voters: [VotedUserState] + let isLoading: Bool + + var body: some View { + List { + if isLoading { + HStack { + Spacer() + ProgressView() + .padding(.vertical, 20) + Spacer() + } + } else if voters.isEmpty { + VStack(spacing: 10) { + Image(systemName: "person.3") + .font(.title2) + .foregroundStyle(FireTheme.subtleInk) + Text("暂时还没有投票用户") + .font(.subheadline.weight(.medium)) + .foregroundStyle(FireTheme.ink) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 28) + } else { + ForEach(voters, id: \.id) { voter in + HStack(spacing: 12) { + FireAvatarView( + avatarTemplate: voter.avatarTemplate, + username: voter.username, + size: 40 + ) + + VStack(alignment: .leading, spacing: 4) { + Text((voter.name ?? "").ifEmpty(voter.username)) + .font(.subheadline.weight(.medium)) + .foregroundStyle(FireTheme.ink) + Text("@\(voter.username)") + .font(.caption) + .foregroundStyle(FireTheme.subtleInk) + } + } + .padding(.vertical, 4) + } + } + } + .navigationTitle("投票用户") + .navigationBarTitleDisplayMode(.inline) + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+APM.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+APM.swift new file mode 100644 index 00000000..c4aca533 --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+APM.swift @@ -0,0 +1,41 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func dismissError() { + errorMessage = nil + } + + func updateTopLevelAPMRoute(selectedTab: Int, isAuthenticated: Bool) { + let route: String + if !isAuthenticated { + route = "session.onboarding" + } else { + switch selectedTab { + case 0: + route = "tab.home" + case 1: + route = "tab.notifications" + case 2: + route = "tab.chat" + case 3: + route = "tab.profile" + default: + route = "tab.unknown" + } + } + topLevelAPMRoute = route + FireAPMManager.shared.setCurrentRoute(route) + } + + func restoreTopLevelAPMRoute() { + FireAPMManager.shared.setCurrentRoute(topLevelAPMRoute) + } + + func setAPMRoute(_ route: String) { + FireAPMManager.shared.setCurrentRoute(route) + } + + // MARK: - MessageBus lifecycle +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+Authentication.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+Authentication.swift new file mode 100644 index 00000000..87320080 --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+Authentication.swift @@ -0,0 +1,411 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + var isPresentingLogin: Bool { + authPresentationState != nil + } + + func openLogin() { + guard authPresentationState == nil else { return } + errorMessage = nil + canSyncLoginSession = false + cachedLoginSyncReadiness = nil + setAuthPresentationState(.login) + + Task { await prepareLoginForm() } + } + + func completeLogin( + from webView: WKWebView, + method: FireLastLoginMethod? = nil + ) { + Task { + _ = await completeLoginAwaitingResult(from: webView, method: method) + } + } + + /// Finalize WebView/OAuth login and return whether session is ready for home. + @discardableResult + func completeLoginAwaitingResult( + from webView: WKWebView, + method: FireLastLoginMethod? = nil + ) async -> Bool { + guard !isSyncingLoginSession else { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: "auth.login", + message: "completeLogin ignored; already syncing" + ) + return session.readiness.canReadAuthenticatedApi + } + + isSyncingLoginSession = true + defer { isSyncingLoginSession = false } + + do { + return try await FireAPMManager.shared.withSpan(.authLoginSync) { + let loginCoordinator = try await loginCoordinatorValue() + let sessionStore = try await sessionStoreValue() + errorMessage = nil + let readiness = try await loginCoordinator.probeLoginSyncReadiness(from: webView) + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.login", + message: "completeLogin probe ready=\(readiness.isReady) username=\(readiness.username ?? "nil") authCookies=\(readiness.hasAuthCookies) bootstrap=\(readiness.hasBootstrapHTML) score=\(readiness.preferredBootstrapScore)" + ) + let session = try await loginCoordinator.completeLogin(from: webView) + // Prefer starting MessageBus when bootstrap already made it possible. + await applySession(session, activateMessageBus: true) + if let method { + try await persistLastLoginMethod(method, sessionStore: sessionStore) + } + FireCfClearanceRefreshService.shared.setLoginStateConfirmed(true) + FireCfClearanceRefreshService.shared.updateSession( + session, + loginCoordinator: loginCoordinator + ) + // fluxdo finally: cookies trusted → enter home immediately. + // App-state refresh must not block login-ready UI forever. + setAuthPresentationState(nil) + canSyncLoginSession = false + cachedLoginSyncReadiness = nil + Task { [weak self] in + guard let self else { return } + try? await sessionStore.triggerAppStateRefresh( + .loginCompleted, + handler: self.appStateRefreshCoordinator + ) + await self.ensureMessageBusActiveIfPossible() + } + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.login", + message: "completeLogin finished canReadAuth=\(session.readiness.canReadAuthenticatedApi)" + ) + return session.readiness.canReadAuthenticatedApi + } + } catch { + FireAPMManager.shared.recordBreadcrumb( + level: "error", + target: "auth.login", + message: "completeLogin failed: \(error.localizedDescription)" + ) + if await handleRecoverableSessionErrorIfNeeded(error) { + return session.readiness.canReadAuthenticatedApi + } + errorMessage = error.localizedDescription + return false + } + } + + func completeMinimalLogin( + from webView: WKWebView, + identifier: String, + password: String, + rememberCredential: Bool + ) { + guard !isSyncingLoginSession else { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: "auth.login", + message: "completeMinimalLogin ignored; already syncing" + ) + return + } + + isSyncingLoginSession = true + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.login", + message: "completeMinimalLogin capture-from-webView start remember=\(rememberCredential)" + ) + Task { + do { + let loginCoordinator = try await loginCoordinatorValue() + let captured = try await loginCoordinator.captureJsLoginState( + from: webView, + identifier: identifier + ) + await completeMinimalLogin( + captured: captured, + password: password, + rememberCredential: rememberCredential, + alreadyMarkedSyncing: true + ) + } catch { + isSyncingLoginSession = false + FireAPMManager.shared.recordBreadcrumb( + level: "error", + target: "auth.login", + message: "completeMinimalLogin capture failed: \(error.localizedDescription)" + ) + if await handleRecoverableSessionErrorIfNeeded(error) { + return + } + errorMessage = error.localizedDescription + } + } + } + + /// Finalize password login from an already-captured WebView cookie snapshot. + /// Callers should dismiss captcha UI first and show host-owned sync loading. + func completeMinimalLogin( + captured: FireCapturedLoginState, + password: String, + rememberCredential: Bool, + alreadyMarkedSyncing: Bool = false + ) async { + if !alreadyMarkedSyncing { + guard !isSyncingLoginSession else { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: "auth.login", + message: "completeMinimalLogin(captured) ignored; already syncing" + ) + return + } + isSyncingLoginSession = true + } + + let identifier = (captured.username ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.login", + message: "completeMinimalLogin start remember=\(rememberCredential) identifier_present=\(!identifier.isEmpty)" + ) + + defer { isSyncingLoginSession = false } + + do { + try await FireAPMManager.shared.withSpan(.authLoginSync) { + let loginCoordinator = try await loginCoordinatorValue() + let sessionStore = try await sessionStoreValue() + errorMessage = nil + let session = try await loginCoordinator.completeJsLogin(captured) + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.login", + message: "completeJsLogin ok canReadAuth=\(session.readiness.canReadAuthenticatedApi) loginPhase=\(String(describing: session.loginPhase))" + ) + await applySession(session, activateMessageBus: true) + try await persistLastLoginMethod(.password, sessionStore: sessionStore) + if rememberCredential, !identifier.isEmpty { + try await sessionStore.saveLoginCredential( + username: identifier, + password: password + ) + savedLoginCredential = try await sessionStore.loadSavedCredential() + } else if !rememberCredential { + try await sessionStore.clearSavedCredential() + savedLoginCredential = nil + } + FireCfClearanceRefreshService.shared.setLoginStateConfirmed(true) + // fluxdo finally: trusted cookies are enough to leave the login UI. + setAuthPresentationState(nil) + canSyncLoginSession = false + cachedLoginSyncReadiness = nil + Task { [weak self] in + guard let self else { return } + try? await sessionStore.triggerAppStateRefresh( + .loginCompleted, + handler: self.appStateRefreshCoordinator + ) + await self.ensureMessageBusActiveIfPossible() + } + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.login", + message: "completeMinimalLogin finished successfully" + ) + } + } catch { + FireAPMManager.shared.recordBreadcrumb( + level: "error", + target: "auth.login", + message: "completeMinimalLogin failed: \(error.localizedDescription)" + ) + if await handleRecoverableSessionErrorIfNeeded(error) { + return + } + errorMessage = error.localizedDescription + } + } + + func classifyWebViewLoginResult( + _ result: WebViewLoginJsResultState + ) async throws -> WebViewLoginDecisionState { + let sessionStore = try await sessionStoreValue() + return try await sessionStore.classifyWebViewLoginResult(result) + } + + func classifyLoginResult( + phase: WebViewLoginPhaseState, + status: UInt16, + body: String + ) async throws -> WebViewLoginDecisionState { + let result = WebViewLoginJsResultState( + phase: phase, + status: status, + body: body + ) + return try await classifyWebViewLoginResult(result) + } + + func dismissAuthPresentation() { + canSyncLoginSession = false + cachedLoginSyncReadiness = nil + setAuthPresentationState(nil) + } + + func prepareAuthWebView(_ webView: WKWebView) { + guard webView.url == nil else { + return + } + + let targetURL = authPresentationURL + Task { [weak self, weak webView] in + guard let self, let webView else { return } + do { + let sessionStore = try await sessionStoreValue() + let replayEntries = try await sessionStore.cookieReplayQueue() + if !replayEntries.isEmpty { + let cookieStore = webView.configuration.websiteDataStore.httpCookieStore + for entry in replayEntries { + guard let cookieURL = URL(string: entry.url) else { + continue + } + let cookies = HTTPCookie.cookies( + withResponseHeaderFields: ["Set-Cookie": entry.rawSetCookie], + for: cookieURL + ) + for cookie in cookies { + await setWebKitCookie(cookie, in: cookieStore) + } + } + try await sessionStore.clearCookieReplayQueue() + } + } catch { + errorMessage = error.localizedDescription + } + + guard webView.url == nil else { + return + } + webView.load(URLRequest(url: targetURL)) + } + } + + func saveLoginCredential(username: String, password: String) { + Task { [weak self] in + guard let self else { return } + do { + let sessionStore = try await sessionStoreValue() + try await sessionStore.saveLoginCredential(username: username, password: password) + savedLoginCredential = try await sessionStore.loadSavedCredential() + } catch { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: Self.authDiagnosticsLogTarget, + message: "failed to persist login credential: \(error.localizedDescription)" + ) + } + } + } + + private func persistLastLoginMethod( + _ method: FireLastLoginMethod, + sessionStore: FireSessionStore + ) async throws { + try await sessionStore.saveLastLoginMethod(method) + lastLoginMethod = method + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: Self.authDiagnosticsLogTarget, + message: "recorded last login method=\(method.rawValue)" + ) + } + + func recordLoginFingerprintDone() { + Task { [weak self] in + guard let self else { return } + do { + let sessionStore = try await sessionStoreValue() + await sessionStore.recordFingerprintDone() + } catch { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: Self.authDiagnosticsLogTarget, + message: "failed to record fingerprint completion: \(error.localizedDescription)" + ) + } + } + } + + func logout() { + guard !isLoggingOut else { + return + } + + isLoggingOut = true + // Explicit logout must never trigger mid-session / session-expired auto-login. + didRequestExplicitLogout = true + cancelMidSessionReauth(reason: "explicit_logout") + + Task { + defer { isLoggingOut = false } + + do { + let loginCoordinator = try await loginCoordinatorValue() + stopMessageBus() + errorMessage = nil + FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) + await applySession(try await loginCoordinator.logout()) + let sessionStore = try await sessionStoreValue() + try await sessionStore.triggerAppStateRefresh(.logoutCompleted) + canSyncLoginSession = false + cachedLoginSyncReadiness = nil + clearTopicState() + notificationStore?.reset() + updateWidgetData() + } catch { + do { + let loginCoordinator = try await loginCoordinatorValue() + FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) + await applySession( + try await loginCoordinator.logoutLocalAndClearPlatformCookies( + preserveCfClearance: true + ) + ) + canSyncLoginSession = false + cachedLoginSyncReadiness = nil + clearTopicState() + notificationStore?.reset() + updateWidgetData() + } catch { + errorMessage = error.localizedDescription + } + } + } + } + + // MARK: - Topic list + + var authPresentationURL: URL { + loginURL + } + + func deauthOnboardingEntry() -> FireOnboardingEntry { + if didRequestExplicitLogout { + didRequestExplicitLogout = false + return .signedOut + } + return .sessionExpired + } + + /// Cancel an in-flight mid-session reauth (overlay cancel / explicit logout). + private func setAuthPresentationState(_ state: FireAuthPresentationState?) { + authPresentationState = state + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+Binding.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+Binding.swift new file mode 100644 index 00000000..8e9c8c6e --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+Binding.swift @@ -0,0 +1,23 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func updateWidgetData() { + guard session.readiness.canReadAuthenticatedApi else { + FireWidgetSnapshotWriter.clear() + return + } + FireWidgetSnapshotWriter.update( + session: session, + topicRows: homeFeedStore?.topicRows ?? [], + unreadNotificationCount: notificationStore?.unreadCount ?? 0 + ) + } + + // MARK: - Lifecycle + + var boundTopicDetailStore: FireTopicDetailStore? { + topicDetailStore + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+Composer.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+Composer.swift new file mode 100644 index 00000000..5d0d8fd4 --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+Composer.swift @@ -0,0 +1,168 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + var canStartAuthenticatedMutation: Bool { + session.readiness.canReadAuthenticatedApi + } + + func fetchPrivateMessages( + kind: TopicListKindState, + page: UInt32? = nil + ) async throws -> TopicListState { + let sessionStore = try await sessionStoreValue() + return try await sessionStore.fetchTopicList( + query: TopicListQueryState( + kind: kind, + page: page, + topicIds: [], + order: nil, + ascending: nil, + categorySlug: nil, + categoryId: nil, + parentCategorySlug: nil, + tag: nil, + additionalTags: [], + matchAllTags: false + ) + ) + } + + func enabledReactionOptions() -> [FireReactionOption] { + FireTopicPresentation.enabledReactionOptions(from: session.bootstrap.enabledReactionIds) + } + + func submitReply( + topicId: UInt64, + raw: String, + replyToPostNumber: UInt32?, + scrollToCreated: Bool = false + ) async throws { + guard let topicDetailStore else { + throw FireTopicInteractionError.unavailable + } + try await topicDetailStore.submitReply( + topicId: topicId, + raw: raw, + replyToPostNumber: replyToPostNumber, + scrollToCreated: scrollToCreated + ) + } + + func createTopic( + title: String, + raw: String, + categoryID: UInt64, + tags: [String] + ) async throws -> UInt64 { + try await composerSession.createTopic( + title: title, + raw: raw, + categoryID: categoryID, + tags: tags + ) + } + + func createPrivateMessage( + title: String, + raw: String, + targetRecipients: [String] + ) async throws -> UInt64 { + try await composerSession.createPrivateMessage( + title: title, + raw: raw, + targetRecipients: targetRecipients + ) + } + + func updateTopic( + topicID: UInt64, + title: String, + categoryID: UInt64, + tags: [String] + ) async throws { + try await composerSession.updateTopic( + topicID: topicID, + title: title, + categoryID: categoryID, + tags: tags + ) + } + + func fetchPost(postID: UInt64) async throws -> TopicPostState { + let sessionStore = try await sessionStoreValue() + return try await sessionStore.fetchPost(postID: postID) + } + + func updatePost( + topicID: UInt64, + postID: UInt64, + raw: String, + editReason: String? = nil + ) async throws { + guard let topicDetailStore else { + throw FireTopicInteractionError.unavailable + } + try await topicDetailStore.updatePost( + topicId: topicID, + postId: postID, + raw: raw, + editReason: editReason + ) + await refreshHomeFeedIfPossible(force: false) + } + + func fetchDrafts( + offset: UInt32? = nil, + limit: UInt32? = nil + ) async throws -> DraftListResponseState { + let sessionStore = try await sessionStoreValue() + return try await sessionStore.fetchDrafts(offset: offset, limit: limit) + } + + func fetchReadHistory(page: UInt32? = nil) async throws -> TopicListState { + let sessionStore = try await sessionStoreValue() + return try await sessionStore.fetchReadHistory(page: page) + } + + func fetchDraft(draftKey: String) async throws -> DraftState? { + let sessionStore = try await sessionStoreValue() + return try await sessionStore.fetchDraft(draftKey: draftKey) + } + + func saveDraft( + draftKey: String, + data: DraftDataState, + sequence: UInt32 + ) async throws -> UInt32 { + try await composerSession.saveDraft( + draftKey: draftKey, + data: data, + sequence: sequence + ) + } + + func deleteDraft( + draftKey: String, + sequence: UInt32? = nil + ) async throws { + try await composerSession.deleteDraft(draftKey: draftKey, sequence: sequence) + } + + func uploadImage( + fileName: String, + mimeType: String?, + bytes: Data + ) async throws -> UploadResultState { + try await composerSession.uploadImage( + fileName: fileName, + mimeType: mimeType, + bytes: bytes + ) + } + + func lookupUploadUrls(shortUrls: [String]) async throws -> [ResolvedUploadUrlState] { + try await composerSession.lookupUploadUrls(shortUrls: shortUrls) + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+HomeFeed.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+HomeFeed.swift new file mode 100644 index 00000000..6fbff73c --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+HomeFeed.swift @@ -0,0 +1,79 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func selectTopicKind(_ kind: TopicListKindState) { + homeFeedStore?.selectTopicKind(kind) + } + + func selectHomeCategory(_ categoryId: UInt64?) { + homeFeedStore?.selectHomeCategory(categoryId) + } + + func addHomeTag(_ tag: String) { + homeFeedStore?.addHomeTag(tag) + } + + func removeHomeTag(_ tag: String) { + homeFeedStore?.removeHomeTag(tag) + } + + func clearHomeTags() { + homeFeedStore?.clearHomeTags() + } + + var selectedHomeCategoryPresentation: FireTopicCategoryPresentation? { + homeFeedStore?.selectedHomeCategoryPresentation + } + + func refreshTopics() { + homeFeedStore?.refreshTopics() + } + + func refreshTopicsAsync() async { + await homeFeedStore?.refreshTopicsAsync() + } + + func loadMoreTopics() { + homeFeedStore?.loadMoreTopics() + } + + func applyHomeRowCountPatch(_ patch: TopicHomeRowCountPatchState) { + homeFeedStore?.applyHomeRowCountPatch(patch) + } + + func categoryPresentation(for categoryID: UInt64?) -> FireTopicCategoryPresentation? { + if let category = homeFeedStore?.categoryPresentation(for: categoryID) { + return category + } + guard let categoryID else { return nil } + return session.bootstrap.categories.first(where: { $0.id == categoryID }) + } + + func allCategories() -> [FireTopicCategoryPresentation] { + homeFeedStore?.allCategories ?? session.bootstrap.categories + } + + func topTags() -> [String] { + homeFeedStore?.topTags ?? session.bootstrap.topTags + } + + var canTagTopics: Bool { + homeFeedStore?.canTagTopics ?? session.bootstrap.canTagTopics + } + + func fetchFilteredTopicList(query: TopicListQueryState) async throws -> TopicListState { + let sessionStore = try await sessionStoreValue() + return try await sessionStore.fetchTopicList(query: query) + } + + private func refreshTopicsIfPossible(force: Bool) async { + await refreshHomeFeedIfPossible(force: force) + } + + @discardableResult + func refreshHomeFeedIfPossible(force: Bool) async -> Bool { + await homeFeedStore?.refreshTopicsIfPossible(force: force) ?? false + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+Logging.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+Logging.swift new file mode 100644 index 00000000..d6c48d45 --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+Logging.swift @@ -0,0 +1,28 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func currentSessionEpoch() async throws -> UInt64 { + let sessionStore = try await sessionStoreValue() + return try await sessionStore.currentSessionEpoch() + } + + func authDiagnosticsLogger() async -> FireHostLogger? { + if let sessionStore { + return sessionStore.makeLogger(target: Self.authDiagnosticsLogTarget) + } + guard let sessionStore = try? await sessionStoreValue() else { + return nil + } + return sessionStore.makeLogger(target: Self.authDiagnosticsLogTarget) + } + + func topicDetailLogger() -> FireHostLogger? { + sessionStore?.makeLogger(target: Self.topicDetailLogTarget) + } + + func topicRouteLogger() -> FireHostLogger? { + sessionStore?.makeLogger(target: Self.topicRouteLogTarget) + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+LoginSupport.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+LoginSupport.swift new file mode 100644 index 00000000..0ab94db7 --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+LoginSupport.swift @@ -0,0 +1,152 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func recoverLoginCloudflareChallenge(in webView: WKWebView) async throws { + let sessionStore = try await sessionStoreValue() + try await completeLoginCloudflareChallenge(sessionStore: sessionStore) + try await Task.sleep(for: .milliseconds(1_500)) + let loginCoordinator = try await loginCoordinatorValue() + try await loginCoordinator.primeCookies( + into: webView, + targetURL: URL(string: "https://linux.do/") + ) + } + + func ensureCloudflareClearance() async -> Bool { + do { + let sessionStore = try await sessionStoreValue() + // Do not trust jar clearance that CF recently rejected (cold start / IP drift). + if try await sessionStore.cloudflareClearanceIsTrusted() { + return true + } + + try await completeLoginCloudflareChallenge(sessionStore: sessionStore) + try await Task.sleep(for: .milliseconds(1_500)) + return try await sessionStore.cloudflareClearanceIsTrusted() + } catch { + errorMessage = error.localizedDescription + return false + } + } + + func loginCoordinatorForDialog() async throws -> FireWebViewLoginCoordinator { + try await loginCoordinatorValue() + } + + func probeLoginSyncReadiness(from webView: WKWebView) async throws -> FireLoginSyncReadiness { + let loginCoordinator = try await loginCoordinatorValue() + return try await loginCoordinator.probeLoginSyncReadiness(from: webView) + } + + private func completeLoginCloudflareChallenge( + sessionStore: FireSessionStore + ) async throws { + let challengeCoordinator = FireCloudflareChallengeCoordinator(sessionStore: sessionStore) + let result = await challengeCoordinator.completeManualVerification(originURL: "https://linux.do/") + guard result.completed else { + throw FireLoginPreparationError.cloudflareVerificationIncomplete + } + + _ = try await sessionStore.completeCloudflareChallenge( + cookies: result.cookies, + freshCfClearance: result.freshCfClearance, + browserUserAgent: result.browserUserAgent + ) + } + + private func prepareLoginNetworkAccess() async throws { + let configuration = URLSessionConfiguration.ephemeral + configuration.waitsForConnectivity = true + + let session = URLSession(configuration: configuration) + var request = URLRequest(url: loginURL) + request.timeoutInterval = 20 + request.cachePolicy = .reloadIgnoringLocalCacheData + + let (_, response) = try await session.data(for: request) + guard response is HTTPURLResponse else { + throw FireLoginPreparationError.invalidResponse + } + } + + private func preloadLoginCoordinator() async throws { + if let loginCoordinatorPreloader { + try await loginCoordinatorPreloader() + return + } + + _ = try await loginCoordinatorValue() + } + + private func warmLoginNetworkAccess() async { + if let loginNetworkWarmup { + await loginNetworkWarmup() + return + } + + do { + try await prepareLoginNetworkAccess() + } catch { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: "auth.login", + message: "login network warmup failed: \(error.localizedDescription)" + ) + } + } + + func refreshLoginSyncReadiness(from webView: WKWebView) { + loginSyncReadinessTask?.cancel() + loginSyncReadinessTask = Task { [weak self] in + guard let self else { return } + do { + let coordinator = try await loginCoordinatorValue() + let readiness = try await coordinator.probeLoginSyncReadiness(from: webView) + guard !Task.isCancelled else { return } + let previous = canSyncLoginSession + cachedLoginSyncReadiness = readiness.isReady + ? CachedLoginSyncReadiness( + currentURL: webView.url?.absoluteString, + readiness: readiness + ) + : nil + canSyncLoginSession = readiness.isReady + if previous != readiness.isReady { + FireAPMManager.shared.recordBreadcrumb( + target: "auth.login", + message: readiness.isReady + ? "login sync readiness satisfied" + : "login sync readiness cleared" + ) + } + } catch { + guard !Task.isCancelled else { return } + canSyncLoginSession = false + cachedLoginSyncReadiness = nil + } + } + } + + func setWebKitCookie(_ cookie: HTTPCookie, in store: WKHTTPCookieStore) async { + await withCheckedContinuation { continuation in + store.setCookie(cookie) { + continuation.resume() + } + } + } + + func loginCoordinatorValue() async throws -> FireWebViewLoginCoordinator { + if let loginCoordinator { + return loginCoordinator + } + + let sessionStore = try await sessionStoreValue() + await configureAuthenticatedWriteHostResyncProvider(with: sessionStore) + guard let loginCoordinator else { + throw CancellationError() + } + return loginCoordinator + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+MessageBus.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+MessageBus.swift new file mode 100644 index 00000000..1891546b --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+MessageBus.swift @@ -0,0 +1,133 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func startMessageBus() async { + guard let sessionStore else { return } + guard session.readiness.canOpenMessageBus else { return } + guard !isMessageBusActive else { return } + + messageBusRetryTask?.cancel() + messageBusRetryTask = nil + + let coordinator = FireMessageBusCoordinator { [weak self] event in + self?.handleMessageBusEvent(event) + } + messageBusCoordinator = coordinator + + do { + _ = try await FireAPMManager.shared.withSpan(.messageBusStart) { + try await sessionStore.startMessageBus(handler: coordinator) + } + isMessageBusActive = true + messageBusStartRetryCount = 0 + clearMessageBusError() + } catch { + messageBusCoordinator = nil + if await handleRecoverableSessionErrorIfNeeded(error) { + return + } + errorMessage = Self.messageBusErrorPrefix + error.localizedDescription + scheduleMessageBusRetry() + } + } + + func stopMessageBus() { + messageBusRetryTask?.cancel() + messageBusRetryTask = nil + messageBusStartRetryCount = 0 + notificationStore?.cancelScheduledRefresh() + homeFeedStore?.handleMessageBusStopped() + clearMessageBusError() + guard isMessageBusActive else { return } + messageBusCoordinator = nil + isMessageBusActive = false + guard let sessionStore else { return } + Task { try? await sessionStore.stopMessageBus(clearSubscriptions: true) } + } + + private func handleMessageBusEvent(_ event: MessageBusEventState) { + switch event.kind { + case .topicList: + homeFeedStore?.handleTopicListMessageBusEvent(event) + + case .topicDetail, .topicReaction, .presence: + break + + case .notification: + notificationStore?.scheduleStateRefresh() + + case .notificationAlert: + break + + case .chat: + chatChannelsStore?.handleMessageBusEvent(event) + NotificationCenter.default.post( + name: .fireChatMessageBusEvent, + object: nil, + userInfo: ["event": event] + ) + + case .sessionLogout: + serverForcedLogout = true + cancelMidSessionReauth(reason: "server_forced_logout") + + case .unknown: + break + } + } + + func beginTopicReplyPresence(topicId: UInt64) { + topicDetailStore?.beginReplyTyping(topicId: topicId) + } + + func endTopicReplyPresence(topicId: UInt64) async { + topicDetailStore?.endReplyTyping(topicId: topicId) + } + + // MARK: - Private helpers + + private func scheduleMessageBusRetry() { + guard session.readiness.canOpenMessageBus else { return } + guard !isMessageBusActive else { return } + guard messageBusStartRetryCount < 3 else { return } + + messageBusStartRetryCount += 1 + let retryDelay = Duration.seconds(Double(messageBusStartRetryCount * 2)) + messageBusRetryTask = Task { [weak self] in + do { + try await Task.sleep(for: retryDelay) + } catch { + return + } + guard let self else { return } + self.messageBusRetryTask = nil + await self.startMessageBus() + } + } + + private func clearMessageBusError() { + if errorMessage?.hasPrefix(Self.messageBusErrorPrefix) == true { + errorMessage = nil + } + } + + /// Write-path CF wrapper. **Passthrough** — does not wait or present. + /// + /// Rust already fails writes quickly with `CloudflareChallengeInProgress` + /// while a challenge is active. Host-side wait/retry would hang composer + /// actions for up to minutes with no UI feedback; callers should surface + /// the error and let the user retry after verification. + func ensureMessageBusActiveIfPossible() async { + guard !isMessageBusActive else { return } + await startMessageBus() + } + + func restartMessageBusAfterClearanceIfPossible() async { + if isMessageBusActive { + stopMessageBus() + } + await startMessageBus() + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+Recovery.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+Recovery.swift new file mode 100644 index 00000000..235340b6 --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+Recovery.swift @@ -0,0 +1,556 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func performWriteWithCloudflareRetry( + operationDescription: String = "执行当前操作", + originURL: URL? = nil, + operation: @escaping () async throws -> T + ) async throws -> T { + _ = operationDescription + _ = originURL + return try await operation() + } + + /// Read-path join/retry helper for Cloudflare errors. **Does not present** UI. + /// + /// - `in_progress`: wait for the host presentation gate (Rust handler already + /// owns the WebView), settle jar merge, then retry `work` once. + /// - other CF reasons: rethrow for banners / explicit manual verify. + /// + /// `originURL` is retained for call-site compatibility and diagnostics only. + func performWithCloudflareRecovery( + operation: String, + originURL: URL? = nil, + work: @escaping () async throws -> T + ) async throws -> T { + do { + return try await work() + } catch { + guard Self.isCloudflareChallengeError(error) else { + throw error + } + let reason = Self.cloudflareChallengeReason(from: error) + switch Self.cloudflareRecoveryAction(forReason: reason) { + case .waitThenRetry: + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.cf", + message: "recovery wait-then-retry operation=\(operation) reason=\(reason) origin=\(originURL?.absoluteString ?? "nil")" + ) + await Self.awaitCloudflareChallengeQuietPeriod() + return try await work() + case .rethrow: + throw error + } + } + } + + /// Host recovery policy for a normalized CF reason token (read path). + /// Automatic paths never present UI (`waitThenRetry` / `rethrow` only). + enum CloudflareRecoveryAction: Equatable { + case waitThenRetry + case rethrow + } + + nonisolated static func cloudflareRecoveryAction( + forReason reason: String + ) -> CloudflareRecoveryAction { + switch reason { + case "in_progress": + return .waitThenRetry + default: + // required / failed / cancelled / cooldown / background_suppressed: + // surface to UI. Present only via Rust handler or explicit manual APIs. + return .rethrow + } + } + + /// Wait for an in-flight host challenge presentation, then briefly settle. + /// Used on read paths when Rust blocks concurrent traffic with `in_progress`. + static func awaitCloudflareChallengeQuietPeriod( + appearTimeout: Duration = .seconds(2), + presentationTimeout: Duration = .seconds(120), + settle: Duration = .milliseconds(500) + ) async { + await FireCloudflareChallengePresentationGate.awaitPresentationAppearance( + timeout: appearTimeout + ) + if FireCloudflareChallengePresentationGate.isPresentationInFlight { + await FireCloudflareChallengePresentationGate.awaitActivePresentationIfAny( + timeout: presentationTimeout + ) + } + try? await Task.sleep(for: settle) + } + + nonisolated static func isCloudflareChallengeError(_ error: Error) -> Bool { + if let fireError = error as? FireUniFfiError { + if case .CloudflareChallenge = fireError { + return true + } + } + let message = String(describing: error).lowercased() + return message.contains("cloudflare challenge") + } + + nonisolated static func cloudflareChallengeReason(from error: Error) -> String { + if let fireError = error as? FireUniFfiError, + case let .CloudflareChallenge(reason) = fireError { + let trimmed = reason.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + return trimmed + } + } + let message = String(describing: error) + for token in ["in_progress", "cooldown", "cancelled", "failed", "background_suppressed", "required"] { + if message.contains("(\(token))") || message.contains(token) { + return token + } + } + return "required" + } + + /// Onboarding entry used when the authenticated shell loses auth. + /// Explicit logout always returns `.signedOut` (no auto-login). + /// Passive / mid-session invalidation returns `.sessionExpired` so headless + /// Google can auto-login on the onboarding host as a fallback path. + func cancelMidSessionReauth(reason: String = "user_cancel") { + guard isMidSessionReauthInFlight || midSessionReauthEngine != nil else { return } + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: Self.authDiagnosticsLogTarget, + message: "mid-session reauth cancelled reason=\(reason)" + ) + if let engine = midSessionReauthEngine { + engine.cancel() + return + } + finishMidSessionReauth(success: false) + } + + /// Read-side recovery for transient `LoginRequired` errors observed during + /// passive reads (home feed, topic detail) and other in-app requests. + /// + /// Recovery order: + /// 1. Single-flight host cookie resync per session epoch (WebKit may be ahead + /// of the shared Rust jar after `_t` / `_forum_session` rotation). + /// 2. If the last login method is headless-capable (currently Google), run + /// mid-session headless reauth under a loading overlay and keep the main + /// shell mounted so the caller can retry the original request in place. + /// + /// - Returns: `true` when recovery succeeded and the caller should retry once. + @discardableResult + func attemptReadPathLoginRecovery( + operation: String, + error: Error + ) async -> Bool { + guard case FireUniFfiError.LoginRequired = error else { + return false + } + + if await attemptHostCookieResyncRecovery(operation: operation) { + return true + } + + return await attemptMidSessionHeadlessReauth(operation: operation) + } + + func attemptHostCookieResyncRecovery(operation: String) async -> Bool { + let logger = await authDiagnosticsLogger() + + let beforeEpoch: UInt64 + do { + beforeEpoch = try await currentSessionEpoch() + } catch { + logger?.warning( + "read-path resync skipped operation=\(operation) reason=epoch_unavailable error=\(error.localizedDescription)" + ) + return false + } + + if readPathLoginRecoveryAttemptedEpochs.contains(beforeEpoch) { + logger?.notice( + "read-path resync skipped operation=\(operation) reason=already_attempted epoch=\(beforeEpoch)" + ) + return false + } + + if let existingTask = readPathLoginRecoveryTask, + readPathLoginRecoveryEpoch == beforeEpoch { + return await existingTask.value + } + + let task = Task { [weak self] in + guard let self else { return false } + return await self.runReadPathLoginRecovery( + operation: operation, + beforeEpoch: beforeEpoch + ) + } + readPathLoginRecoveryTask = task + readPathLoginRecoveryEpoch = beforeEpoch + defer { + if readPathLoginRecoveryEpoch == beforeEpoch { + readPathLoginRecoveryTask = nil + readPathLoginRecoveryEpoch = nil + } + } + return await task.value + } + + private func runReadPathLoginRecovery( + operation: String, + beforeEpoch: UInt64 + ) async -> Bool { + readPathLoginRecoveryAttemptedEpochs.insert(beforeEpoch) + let logger = await authDiagnosticsLogger() + + let coordinator: FireWebViewLoginCoordinator + do { + coordinator = try await loginCoordinatorValue() + } catch { + logger?.warning( + "read-path resync skipped operation=\(operation) epoch=\(beforeEpoch) reason=no_coordinator error=\(error.localizedDescription)" + ) + return false + } + + let cookies: [PlatformCookieState] + do { + cookies = try await coordinator.platformCookiesForSessionResync() + } catch { + logger?.warning( + "read-path resync failed operation=\(operation) epoch=\(beforeEpoch) reason=cookie_fetch_failed error=\(error.localizedDescription)" + ) + return false + } + + guard FireWebViewLoginCoordinator.containsActiveAuthCookies(in: cookies) else { + logger?.notice( + "read-path resync skipped operation=\(operation) epoch=\(beforeEpoch) reason=no_authoritative_webview_auth_cookies cookie_count=\(cookies.count)" + ) + return false + } + + let sessionStore: FireSessionStore + do { + sessionStore = try await sessionStoreValue() + } catch { + logger?.warning( + "read-path resync skipped operation=\(operation) epoch=\(beforeEpoch) reason=no_session_store error=\(error.localizedDescription)" + ) + return false + } + + do { + _ = try await sessionStore.applyPlatformCookies(cookies) + } catch { + logger?.warning( + "read-path resync failed operation=\(operation) epoch=\(beforeEpoch) reason=apply_failed error=\(error.localizedDescription)" + ) + return false + } + + let afterEpoch: UInt64 + do { + afterEpoch = try await sessionStore.currentSessionEpoch() + } catch { + logger?.warning( + "read-path resync inconclusive operation=\(operation) epoch=\(beforeEpoch) reason=post_epoch_unavailable error=\(error.localizedDescription)" + ) + return false + } + + let didRotate = afterEpoch != beforeEpoch + if didRotate { + // Once the resync actually rotated us into a new auth epoch, the + // older `attempted` markers no longer protect us from anything; + // keep the set small so a long-lived session doesn't accumulate + // stale markers. + readPathLoginRecoveryAttemptedEpochs = readPathLoginRecoveryAttemptedEpochs + .filter { $0 == afterEpoch } + FireAPMManager.shared.recordBreadcrumb( + target: Self.authDiagnosticsLogTarget, + message: "read-path resync rotated auth operation=\(operation) before_epoch=\(beforeEpoch) after_epoch=\(afterEpoch) cookie_count=\(cookies.count)" + ) + logger?.notice( + "read-path resync rotated auth operation=\(operation) before_epoch=\(beforeEpoch) after_epoch=\(afterEpoch) cookie_count=\(cookies.count)" + ) + } else { + logger?.notice( + "read-path resync no_change operation=\(operation) epoch=\(beforeEpoch) cookie_count=\(cookies.count)" + ) + } + return didRotate + } + + /// Called from `applySession` when auth drops without an explicit logout. + /// Starts Google headless recovery early enough for RootCoordinator to hold the shell. + func scheduleMidSessionReauthAfterPassiveDeauth() { + if midSessionReauthTask != nil || isMidSessionReauthInFlight { + return + } + + let knownMethod = FireAutoLoginPlanner.midSessionHeadlessKind( + lastLoginMethod: lastLoginMethod + ) + // lastLoginMethod may not be loaded yet on a long-lived session; optimistically + // hold and resolve eligibility inside the single-flight reauth task. + guard knownMethod != nil || lastLoginMethod == nil else { + return + } + + isMidSessionReauthInFlight = true + if midSessionReauthMessage == nil { + if let knownMethod { + midSessionReauthMessage = FireAutoLoginPlanner.loadingMessage( + for: .external(knownMethod) + ) + } else { + midSessionReauthMessage = "正在恢复登录…" + } + } + + Task { @MainActor [weak self] in + guard let self else { return } + _ = await self.attemptMidSessionHeadlessReauth(operation: "session_deauth") + } + } + + /// Mid-session headless reauth for LoginRequired when cookie resync cannot help. + /// Currently limited to providers in `FireAutoLoginPlanner.headlessExternalPool` + /// (Google). Single-flight across the app so concurrent failing requests share + /// one overlay + one OAuth attempt, then all retry. + func attemptMidSessionHeadlessReauth(operation: String) async -> Bool { + if let existing = midSessionReauthTask { + return await existing.value + } + + let task = Task { [weak self] in + guard let self else { return false } + return await self.runMidSessionHeadlessReauth(operation: operation) + } + midSessionReauthTask = task + let result = await task.value + if midSessionReauthTask != nil { + midSessionReauthTask = nil + } + return result + } + + private func runMidSessionHeadlessReauth(operation: String) async -> Bool { + // Explicit logout wins over any in-flight recovery. + guard !didRequestExplicitLogout, !isLoggingOut else { + finishMidSessionReauth(success: false) + return false + } + + if lastLoginMethod == nil { + await prepareLoginForm() + } + + guard let method = FireAutoLoginPlanner.midSessionHeadlessKind( + lastLoginMethod: lastLoginMethod + ) else { + let logger = await authDiagnosticsLogger() + logger?.notice( + "mid-session reauth skipped operation=\(operation) reason=method_ineligible last=\(String(describing: lastLoginMethod))" + ) + finishMidSessionReauth(success: false) + return false + } + + guard let hostViewController = Self.topPresenterForMidSessionReauth() else { + let logger = await authDiagnosticsLogger() + logger?.warning( + "mid-session reauth skipped operation=\(operation) reason=no_presenter" + ) + finishMidSessionReauth(success: false) + return false + } + + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: Self.authDiagnosticsLogTarget, + message: "mid-session reauth begin operation=\(operation) method=\(method.rawValue)" + ) + + isMidSessionReauthInFlight = true + midSessionReauthMessage = FireAutoLoginPlanner.loadingMessage(for: .external(method)) + + let succeeded = await withCheckedContinuation { (continuation: CheckedContinuation) in + // A proactive deauth hold may already have flipped inFlight without a waiter. + if let previous = self.midSessionReauthContinuation { + self.midSessionReauthContinuation = nil + previous.resume(returning: false) + } + self.midSessionReauthContinuation = continuation + + let engine = FireHeadlessExternalLoginEngine(method: method, viewModel: self) + self.midSessionReauthEngine = engine + engine.onOutcome = { [weak self] outcome in + guard let self else { return } + self.handleMidSessionReauthOutcome( + outcome, + method: method, + presenter: hostViewController + ) + } + engine.start(in: hostViewController.view) + } + + if succeeded { + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: Self.authDiagnosticsLogTarget, + message: "mid-session reauth succeeded operation=\(operation) method=\(method.rawValue)" + ) + } else { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: Self.authDiagnosticsLogTarget, + message: "mid-session reauth failed operation=\(operation) method=\(method.rawValue)" + ) + } + return succeeded + } + + private func handleMidSessionReauthOutcome( + _ outcome: FireHeadlessExternalLoginEngine.Outcome, + method: FireExternalLoginMethod, + presenter: UIViewController + ) { + switch outcome { + case .authenticated: + guard let webView = midSessionReauthEngine?.currentWebView else { + finishMidSessionReauth(success: false) + return + } + midSessionReauthMessage = "正在同步登录态…" + Task { @MainActor in + let ok = await self.completeLoginAwaitingResult( + from: webView, + method: method.lastLoginMethod + ) + self.finishMidSessionReauth(success: ok && self.session.readiness.canReadAuthenticatedApi) + } + + case .needsUserInteraction: + midSessionReauthMessage = FireAutoLoginPlanner.loadingMessage(for: .external(method)) + .replacingOccurrences(of: "正在通过", with: "请完成") + .replacingOccurrences(of: "…", with: "") + midSessionReauthEngine?.promote(from: presenter) + + case .failed: + finishMidSessionReauth(success: false) + + case .cancelled: + finishMidSessionReauth(success: false) + } + } + + private func finishMidSessionReauth(success: Bool) { + midSessionReauthEngine?.teardown() + midSessionReauthEngine = nil + midSessionReauthMessage = nil + isMidSessionReauthInFlight = false + + if let continuation = midSessionReauthContinuation { + midSessionReauthContinuation = nil + continuation.resume(returning: success) + } + } + + private static func topPresenterForMidSessionReauth() -> UIViewController? { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let window = scenes + .flatMap(\.windows) + .first(where: \.isKeyWindow) + ?? scenes.flatMap(\.windows).first + guard var top = window?.rootViewController else { return nil } + while let presented = top.presentedViewController { + top = presented + } + return top + } + + @discardableResult + func handleRecoverableSessionErrorIfNeeded(_ error: Error) async -> Bool { + await handleStaleSessionResponseIfNeeded(error) + } + + @discardableResult + func handleStaleSessionResponseIfNeeded(_ error: Error) async -> Bool { + guard case let FireUniFfiError.StaleSessionResponse(operation) = error else { + return false + } + + FireAPMManager.shared.recordBreadcrumb( + target: Self.authDiagnosticsLogTarget, + message: "discarded stale session response operation=\(operation)" + ) + return true + } + + @discardableResult + func handleInteractionError(_ error: Error) async -> Bool { + if await handleRecoverableSessionErrorIfNeeded(error) { + return true + } + errorMessage = error.localizedDescription + return false + } + + func configureAuthenticatedWriteHostResyncProvider( + with sessionStore: FireSessionStore + ) async { + let loginCoordinator: FireWebViewLoginCoordinator + if let existingLoginCoordinator = self.loginCoordinator { + loginCoordinator = existingLoginCoordinator + } else { + let newLoginCoordinator = FireWebViewLoginCoordinator(sessionStore: sessionStore) + self.loginCoordinator = newLoginCoordinator + loginCoordinator = newLoginCoordinator + } + + await sessionStore.setAuthenticatedWriteHostResyncProvider { [weak loginCoordinator] in + guard let loginCoordinator else { + return nil + } + return try await loginCoordinator.platformCookiesForSessionResync() + } + + if cloudflareChallengeHandler == nil { + cloudflareChallengeHandler = FireCloudflareChallengeRuntimeHandler( + sessionStore: sessionStore + ) + } + if let cloudflareChallengeHandler { + try? await sessionStore.registerCloudflareChallengeHandler( + cloudflareChallengeHandler + ) + } + if clearanceResolvedHandler == nil { + clearanceResolvedHandler = FireClearanceResolvedRuntimeHandler { [weak self] event in + await self?.handleClearanceResolved(event) + } + } + if let clearanceResolvedHandler { + try? await sessionStore.registerCloudflareClearanceResolvedHandler( + clearanceResolvedHandler + ) + } + if cookieSelfHealingHandler == nil { + cookieSelfHealingHandler = FireCookieSelfHealingRuntimeHandler( + loginCoordinator: loginCoordinator + ) + } + if let cookieSelfHealingHandler { + try? await sessionStore.registerCookieSelfHealingHandler( + cookieSelfHealingHandler + ) + } + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+SessionApply.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+SessionApply.swift new file mode 100644 index 00000000..e7901292 --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+SessionApply.swift @@ -0,0 +1,194 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func refreshBootstrap() { + Task { + do { + try await FireAPMManager.shared.withSpan(.bootstrapRefresh) { + let sessionStore = try await sessionStoreValue() + errorMessage = nil + await applySession(try await sessionStore.refreshBootstrap()) + await refreshHomeFeedIfPossible(force: false) + } + } catch { + if await handleRecoverableSessionErrorIfNeeded(error) { + return + } + errorMessage = error.localizedDescription + } + } + } + + func clearTopicState() { + homeFeedStore?.reset(resetTopicKind: true) + topicDetailStore?.reset() + } + + func applySession(_ session: SessionState, activateMessageBus: Bool = true) async { + let wasAuthenticated = self.session.readiness.canReadAuthenticatedApi + let shouldSyncNativeCookies = session.cookies != self.session.cookies + || session.bootstrap.baseUrl != self.session.bootstrap.baseUrl + self.session = session + if shouldSyncNativeCookies { + session.syncCookiesToNativeStorage() + } + homeFeedStore?.applySession(session) + topicDetailStore?.applySession(session) + if let request = session.readPathLoginRequest, + request.generation != lastReadPathLoginGeneration { + lastReadPathLoginGeneration = request.generation + let operation = request.operation + let recovered = await attemptHostCookieResyncRecovery(operation: operation) + let succeeded: Bool + if recovered { + succeeded = true + } else { + succeeded = await attemptMidSessionHeadlessReauth(operation: operation) + } + if let sessionStore = currentSessionStore() { + try? await sessionStore.completeReadPathLogin( + generation: request.generation, + succeeded: succeeded + ) + } + } + + let isAuthenticated = session.readiness.canReadAuthenticatedApi + if wasAuthenticated && !isAuthenticated { + if let coordinator = try? await loginCoordinatorValue() { + try? await coordinator.clearSameSiteIdentityCookies(preservingCfClearance: true) + } + if serverForcedLogout { + serverForcedLogout = false + } else if !didRequestExplicitLogout { + // Raise the reauth hold synchronously so RootCoordinator's next main-runloop + // auth sink keeps the main shell mounted for Google headless recovery. + scheduleMidSessionReauthAfterPassiveDeauth() + } + } + + if isAuthenticated { + await notificationStore?.syncStateFromRuntimeIfAvailable() + if needsBootstrapIdentityHydration(session) { + Task { await self.hydrateBootstrapIfNeeded() } + } + } else { + notificationStore?.reset() + updateWidgetData() + } + + // Reconcile MessageBus lifecycle + if session.readiness.canOpenMessageBus && activateMessageBus && !isMessageBusActive { + await startMessageBus() + } else if !session.readiness.canOpenMessageBus && isMessageBusActive { + stopMessageBus() + } else if !session.readiness.canOpenMessageBus { + stopMessageBus() + } + + if let coordinator = try? await loginCoordinatorValue() { + FireCfClearanceRefreshService.shared.updateSession( + session, + loginCoordinator: coordinator, + onSessionRefreshed: { [weak self] updatedSession in + guard let self else { return } + await self.cfClearanceDidRefresh(updatedSession) + } + ) + } + } + + func cfClearanceDidRefresh(_ updatedSession: SessionState) async { + await applySession(updatedSession) + } + + func handleAppStateRefreshEvent(_ event: AppStateRefreshEventState) { + if event.trigger == .cloudflareResolved { + Task { @MainActor in + self.homeFeedStore?.clearTopicLoadError() + if self.session.readiness.canOpenMessageBus { + await self.restartMessageBusAfterClearanceIfPossible() + } + } + } + } + + func handleClearanceResolved(_ event: CloudflareClearanceResolvedEventState) async { + homeFeedStore?.clearTopicLoadError() + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.cf", + message: "clearance resolved gen=\(event.generation) login=\(event.hasLoginSession) bus=\(event.canOpenMessageBus)" + ) + if event.canOpenMessageBus || session.readiness.canOpenMessageBus { + await restartMessageBusAfterClearanceIfPossible() + } + // Home topic list may still show a CF failure banner; force one refresh. + _ = await refreshHomeFeedIfPossible(force: true) + await hydrateBootstrapIfNeeded(force: true) + } + + /// Pull home bootstrap when cookies exist but `current_username` / preloaded + /// data never landed. Profile, logout, and MessageBus all need that identity. + func hydrateBootstrapIfNeeded(force: Bool = false) async { + let current = session + guard current.hasLoginSession || current.readiness.canReadAuthenticatedApi else { + lastBootstrapHydrationAttemptKey = nil + return + } + guard needsBootstrapIdentityHydration(current) else { + lastBootstrapHydrationAttemptKey = nil + return + } + let attemptKey = bootstrapHydrationAttemptKey(current) + guard force || lastBootstrapHydrationAttemptKey != attemptKey else { + return + } + guard !isHydratingBootstrap else { + return + } + isHydratingBootstrap = true + lastBootstrapHydrationAttemptKey = attemptKey + defer { isHydratingBootstrap = false } + do { + let sessionStore = try await sessionStoreValue() + var snapshot = try await sessionStore.refreshBootstrapIfNeeded() + await applySession(snapshot, activateMessageBus: false) + if needsBootstrapIdentityHydration(snapshot) { + snapshot = try await sessionStore.refreshBootstrap() + await applySession(snapshot, activateMessageBus: false) + } + } catch { + FireAPMManager.shared.recordBreadcrumb( + level: "warn", + target: "auth.bootstrap", + message: "bootstrap hydration failed: \(error.localizedDescription)" + ) + } + } + + private func needsBootstrapIdentityHydration(_ session: SessionState) -> Bool { + !session.readiness.hasCurrentUser || !session.readiness.hasPreloadedData + } + + private func bootstrapHydrationAttemptKey(_ session: SessionState) -> String { + [ + session.hasLoginSession ? "1" : "0", + session.readiness.canReadAuthenticatedApi ? "1" : "0", + session.cookies.tToken ?? "", + session.cookies.forumSession ?? "", + ].joined(separator: "|") + } + + func syncSessionSnapshotIfAvailable(from sessionStore: FireSessionStore) async { + if let snapshot = try? await sessionStore.snapshot() { + await applySession(snapshot) + } + } + + func registerStateObserver(with sessionStore: FireSessionStore) async { + await sessionStore.registerStateObserver(stateObserverCoordinator) + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+Startup.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+Startup.swift new file mode 100644 index 00000000..af0b0f2e --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+Startup.swift @@ -0,0 +1,166 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func loadInitialState() { + initialStateLoadGeneration &+= 1 + let generation = initialStateLoadGeneration + + initialStateTask?.cancel() + initialStateLoadingDelayTask?.cancel() + FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) + isBootstrappingSession = true + isStartupLoadingVisible = false + + initialStateLoadingDelayTask = Task { [weak self] in + do { + try await Task.sleep(for: .milliseconds(500)) + } catch { + return + } + + guard let self else { return } + guard self.initialStateLoadGeneration == generation else { return } + guard self.isBootstrappingSession else { return } + self.isStartupLoadingVisible = true + } + + initialStateTask = Task { [weak self] in + guard let self else { return } + defer { + self.finishInitialStateLoading(generation: generation) + } + + do { + try await FireAPMManager.shared.withSpan(.appLaunchRestoreSession) { + let sessionStore = try await self.sessionStoreValue() + guard self.initialStateLoadGeneration == generation else { return } + self.errorMessage = nil + _ = try await sessionStore.prepareStartupSession() + guard self.initialStateLoadGeneration == generation else { return } + Task { + try? await sessionStore.ensurePreloadedDataLoaded() + } + } + } catch { + guard self.initialStateLoadGeneration == generation else { return } + if await self.handleRecoverableSessionErrorIfNeeded(error) { + return + } + self.errorMessage = error.localizedDescription + } + } + } + + func completeStartupAfterPreheat() async { + let generation = initialStateLoadGeneration + do { + let sessionStore = try await sessionStoreValue() + guard self.initialStateLoadGeneration == generation else { return } + self.errorMessage = nil + let loginState = try await sessionStore.determineLoginStateWithProbe() + guard self.initialStateLoadGeneration == generation else { return } + switch loginState { + case .loggedIn: + FireCfClearanceRefreshService.shared.setLoginStateConfirmed(true) + try await sessionStore.triggerAppStateRefresh( + .sessionRestored, + handler: appStateRefreshCoordinator + ) + let snapshot = try await sessionStore.snapshot() + guard self.initialStateLoadGeneration == generation else { return } + await self.ensureLastLoginMethodLoaded(using: sessionStore) + await self.applySession(snapshot, activateMessageBus: false) + case .networkErrorPreserveState, .sessionExpired, .notLoggedIn: + FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) + let snapshot = try await sessionStore.snapshot() + guard self.initialStateLoadGeneration == generation else { return } + await self.applySession(snapshot, activateMessageBus: false) + @unknown default: + break + } + } catch { + guard self.initialStateLoadGeneration == generation else { return } + if await self.handleRecoverableSessionErrorIfNeeded(error) { + return + } + if let sessionStore = self.sessionStore, + let snapshot = try? await sessionStore.snapshot() { + await self.applySession(snapshot, activateMessageBus: false) + } + self.errorMessage = error.localizedDescription + } + } + + func completeStartupAfterPreheatFailure(message: String?) { + initialStateLoadGeneration &+= 1 + initialStateTask?.cancel() + initialStateTask = nil + initialStateLoadingDelayTask?.cancel() + initialStateLoadingDelayTask = nil + isBootstrappingSession = false + isStartupLoadingVisible = false + FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) + if let message, !message.isEmpty { + errorMessage = message + } + } + + func performStartupValidation() async { + guard !isStartupValidationComplete else { return } + guard !isStartupValidationInFlight else { return } + isStartupValidationInFlight = true + defer { + isStartupValidationInFlight = false + isStartupValidationComplete = true + } + + do { + let sessionStore = try await sessionStoreValue() + _ = try await sessionStore.prepareStartupSession() + do { + _ = try await sessionStore.awaitPreloadedData() + } catch { + let snapshot = try? await sessionStore.snapshot() + let readiness = snapshot?.readiness + guard readiness?.canReadAuthenticatedApi == true + || readiness?.hasLoginCookie == true + else { + throw error + } + } + await completeStartupAfterPreheat() + } catch { + completeStartupAfterPreheatFailure(message: "网络异常,请重新登录") + } + } + + func prepareLoginForm() async { + do { + let sessionStore = try await sessionStoreValue() + savedLoginCredential = try await sessionStore.loadSavedCredential() + lastLoginMethod = try await sessionStore.loadLastLoginMethod() + _ = try await loginCoordinatorValue() + } catch { + errorMessage = error.localizedDescription + } + } + + private func ensureLastLoginMethodLoaded(using sessionStore: FireSessionStore) async { + guard lastLoginMethod == nil else { return } + lastLoginMethod = try? await sessionStore.loadLastLoginMethod() + } + + private func finishInitialStateLoading(generation: UInt64) { + guard initialStateLoadGeneration == generation else { + return + } + + initialStateLoadingDelayTask?.cancel() + initialStateLoadingDelayTask = nil + isBootstrappingSession = false + isStartupLoadingVisible = false + initialStateTask = nil + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel+TopicDetail.swift b/apps/ios-app/App/ViewModels/FireAppViewModel+TopicDetail.swift new file mode 100644 index 00000000..d9068bf3 --- /dev/null +++ b/apps/ios-app/App/ViewModels/FireAppViewModel+TopicDetail.swift @@ -0,0 +1,98 @@ +import Foundation +import UIKit +import WebKit + +extension FireAppViewModel { + func openTopicDetail( + topicId: UInt64, + ownerToken: String, + topicSlug: String? = nil, + targetPostNumber: UInt32? = nil, + bypassCache: Bool, + forceLoad: Bool, + trackVisit: Bool, + allowSuggestedUnreadRoot: Bool + ) { + topicDetailStore?.open( + topicId: topicId, + ownerToken: ownerToken, + slug: topicSlug, + targetPostNumber: targetPostNumber, + bypassCache: bypassCache, + forceLoad: forceLoad, + trackVisit: trackVisit, + allowSuggestedUnreadRoot: allowSuggestedUnreadRoot + ) + } + + func clearTopicDetailAnchor(topicId: UInt64) { + topicDetailStore?.clearScrollTarget(topicId: topicId) + } + + func topicDetail(for topicId: UInt64) -> TopicDetailUiSnapshotState? { + topicDetailStore?.snapshot(for: topicId) + } + + func topicPresenceUsers(for topicId: UInt64) -> [TopicDetailTypingUserState] { + topicDetailStore?.snapshot(for: topicId)?.composer.typingUsers ?? [] + } + + func isLoadingTopic(topicId: UInt64) -> Bool { + topicDetailStore?.snapshot(for: topicId)?.phase == .loading + } + + func isLoadingMoreTopicPosts(topicId: UInt64) -> Bool { + topicDetailStore?.snapshot(for: topicId)?.isLoadingMore ?? false + } + + func hasMoreTopicPosts(topicId: UInt64) -> Bool { + topicDetailStore?.snapshot(for: topicId)?.hasMore ?? false + } + + func beginTopicDetailLifecycle(topicId: UInt64, ownerToken: String) { + topicDetailStore?.open( + topicId: topicId, + ownerToken: ownerToken, + slug: nil, + targetPostNumber: nil, + bypassCache: false, + forceLoad: false, + trackVisit: true, + allowSuggestedUnreadRoot: topicDetailStore?.snapshot(for: topicId)?.phase != .ready + ) + } + + func endTopicDetailLifecycle(topicId: UInt64, ownerToken: String) { + topicDetailStore?.close(topicId: topicId, ownerToken: ownerToken) + } + + func retainedTopicDetailIDs(visibleTopicIDs: Set) -> Set { + // Owner refcount is the retention source of truth; keep any still-visible + // list rows so hosts can avoid premature eviction while scrolling. + (topicDetailStore?.ownedTopicIDs() ?? []).union(visibleTopicIDs) + } + + // MARK: - Topic detail MessageBus subscription + + func maintainTopicDetailSubscription(topicId: UInt64, ownerToken: String) async { + _ = (topicId, ownerToken) + } + + // MARK: - Write interactions + + func isSubmittingReply(topicId: UInt64) -> Bool { + topicDetailStore?.snapshot(for: topicId)?.composer.isSubmitting ?? false + } + + func isMutatingPost(postId: UInt64) -> Bool { + topicDetailStore?.isMutatingPost(postId: postId) ?? false + } + + func pruneTopicDetailState(retainingVisibleTopicIDs visibleTopicIDs: Set) { + _ = visibleTopicIDs + } + + func currentVisibleTopicIDs() -> Set { + homeFeedStore?.visibleTopicIDs ?? [] + } +} diff --git a/apps/ios-app/App/ViewModels/FireAppViewModel.swift b/apps/ios-app/App/ViewModels/FireAppViewModel.swift index b159e03e..0246e584 100644 --- a/apps/ios-app/App/ViewModels/FireAppViewModel.swift +++ b/apps/ios-app/App/ViewModels/FireAppViewModel.swift @@ -7,87 +7,88 @@ final class FireAppViewModel: ObservableObject { typealias LoginCoordinatorPreloader = @Sendable () async throws -> Void typealias LoginNetworkWarmup = @Sendable () async -> Void - private static let messageBusErrorPrefix = "实时同步连接失败:" - private static let loginRequiredMessage = "登录状态已失效,请重新登录。" - private static let authDiagnosticsLogTarget = "ios.auth" - private static let topicRouteLogTarget = "ios.topic-route" - private static let topicDetailLogTarget = "ios.topic-detail" + static let messageBusErrorPrefix = "实时同步连接失败:" + static let loginRequiredMessage = "登录状态已失效,请重新登录。" + static let authDiagnosticsLogTarget = "ios.auth" + static let topicRouteLogTarget = "ios.topic-route" + static let topicDetailLogTarget = "ios.topic-detail" static let diagnosticsLifecycleLogTarget = "ios.lifecycle" // MARK: - Session - @Published private(set) var session: SessionState = .placeholder() + @Published var session: SessionState = .placeholder() // MARK: - General UI state @Published var errorMessage: String? - @Published private(set) var isBootstrappingSession = false - @Published private(set) var isStartupLoadingVisible = false + @Published var isBootstrappingSession = false + @Published var isStartupLoadingVisible = false @Published var authPresentationState: FireAuthPresentationState? @Published var isPreparingLogin = false @Published var isSyncingLoginSession = false - @Published private(set) var canSyncLoginSession = false - @Published private(set) var savedLoginCredential: FireSavedCredential? - @Published private(set) var lastLoginMethod: FireLastLoginMethod? + @Published var canSyncLoginSession = false + @Published var savedLoginCredential: FireSavedCredential? + @Published var lastLoginMethod: FireLastLoginMethod? @Published var isLoggingOut = false - @Published private(set) var isStartupValidationComplete = false + @Published var isStartupValidationComplete = false /// Non-nil while mid-session Google/headless reauth is running on the main shell. - @Published private(set) var midSessionReauthMessage: String? - @Published private(set) var isMidSessionReauthInFlight = false - private var isStartupValidationInFlight = false + @Published var midSessionReauthMessage: String? + @Published var isMidSessionReauthInFlight = false + var isStartupValidationInFlight = false /// Set when the user taps logout so deauth routes to the credential form only. - private var didRequestExplicitLogout = false + var didRequestExplicitLogout = false /// Set when MessageBus `/logout/{user_id}` revokes the session. - private var serverForcedLogout = false + var serverForcedLogout = false /// Cookies can restore a login shell before home HTML hydrates `current_username`. - private var isHydratingBootstrap = false - private var lastBootstrapHydrationAttemptKey: String? + var isHydratingBootstrap = false + var lastBootstrapHydrationAttemptKey: String? // MARK: - Private - private var sessionStore: FireSessionStore? - private var loginCoordinator: FireWebViewLoginCoordinator? - private var cloudflareChallengeHandler: FireCloudflareChallengeRuntimeHandler? - private var clearanceResolvedHandler: FireClearanceResolvedRuntimeHandler? - private var cookieSelfHealingHandler: FireCookieSelfHealingRuntimeHandler? - private var sessionStoreInitializationTask: Task? - private var initialStateTask: Task? - private var initialStateLoadingDelayTask: Task? - private var initialStateLoadGeneration: UInt64 = 0 - private var loginSyncReadinessTask: Task? - private var cachedLoginSyncReadiness: CachedLoginSyncReadiness? + var sessionStore: FireSessionStore? + var loginCoordinator: FireWebViewLoginCoordinator? + var cloudflareChallengeHandler: FireCloudflareChallengeRuntimeHandler? + var clearanceResolvedHandler: FireClearanceResolvedRuntimeHandler? + var cookieSelfHealingHandler: FireCookieSelfHealingRuntimeHandler? + var sessionStoreInitializationTask: Task? + var initialStateTask: Task? + var initialStateLoadingDelayTask: Task? + var initialStateLoadGeneration: UInt64 = 0 + var loginSyncReadinessTask: Task? + var cachedLoginSyncReadiness: CachedLoginSyncReadiness? /// Single-flight read-path login recovery: at most one resync runs per session /// epoch, and once an epoch's resync has failed we stop retrying it on read /// errors so the caller falls back to reporting the original error. - private var readPathLoginRecoveryTask: Task? - private var lastReadPathLoginGeneration: UInt64 = 0 - private var readPathLoginRecoveryEpoch: UInt64? - private var readPathLoginRecoveryAttemptedEpochs: Set = [] + var readPathLoginRecoveryTask: Task? + var lastReadPathLoginGeneration: UInt64 = 0 + var readPathLoginRecoveryEpoch: UInt64? + var readPathLoginRecoveryAttemptedEpochs: Set = [] /// Single-flight mid-session headless reauth (Google first). - private var midSessionReauthTask: Task? - private var midSessionReauthEngine: FireHeadlessExternalLoginEngine? - private var midSessionReauthContinuation: CheckedContinuation? - private let loginURL = URL(string: "https://linux.do/")! - private let loginCoordinatorPreloader: LoginCoordinatorPreloader? - private let loginNetworkWarmup: LoginNetworkWarmup? + var midSessionReauthTask: Task? + var midSessionReauthEngine: FireHeadlessExternalLoginEngine? + var midSessionReauthContinuation: CheckedContinuation? + let loginURL = URL(string: "https://linux.do/")! + let loginCoordinatorPreloader: LoginCoordinatorPreloader? + let loginNetworkWarmup: LoginNetworkWarmup? private lazy var appServiceHost = FireAppServiceHost(owner: self) lazy var topicInteraction = FireTopicInteractionService(host: appServiceHost) lazy var notificationService = FireNotificationService(host: appServiceHost) lazy var searchService = FireSearchService(host: appServiceHost) + lazy var composerSession = FireComposerSession(appViewModel: self) // MessageBus - private var messageBusCoordinator: FireMessageBusCoordinator? - private var isMessageBusActive = false - private var messageBusStartRetryCount = 0 - private var messageBusRetryTask: Task? - private var topLevelAPMRoute = "session.onboarding" - private weak var homeFeedStore: FireHomeFeedStore? - private weak var notificationStore: FireNotificationStore? - private weak var topicDetailStore: FireTopicDetailStore? - private weak var chatChannelsStore: FireChatChannelsStore? - private lazy var appStateRefreshCoordinator = FireAppStateRefreshCoordinator { [weak self] event in + var messageBusCoordinator: FireMessageBusCoordinator? + var isMessageBusActive = false + var messageBusStartRetryCount = 0 + var messageBusRetryTask: Task? + var topLevelAPMRoute = "session.onboarding" + weak var homeFeedStore: FireHomeFeedStore? + weak var notificationStore: FireNotificationStore? + weak var topicDetailStore: FireTopicDetailStore? + weak var chatChannelsStore: FireChatChannelsStore? + lazy var appStateRefreshCoordinator = FireAppStateRefreshCoordinator { [weak self] event in self?.handleAppStateRefreshEvent(event) } - private lazy var stateObserverCoordinator = FireStateObserverCoordinator( + lazy var stateObserverCoordinator = FireStateObserverCoordinator( onSession: { [weak self] snapshot in guard let self else { return } await self.applySession(snapshot, activateMessageBus: false) @@ -114,2041 +115,26 @@ final class FireAppViewModel: ObservableObject { self.loginNetworkWarmup = loginNetworkWarmup } - var isPresentingLogin: Bool { - authPresentationState != nil - } - - func bindHomeFeedStore(_ store: FireHomeFeedStore) { - homeFeedStore = store - } - - func bindChatChannelsStore(_ store: FireChatChannelsStore) { - chatChannelsStore = store - } - - func bindNotificationStore(_ store: FireNotificationStore) { - notificationStore = store - } - - func bindTopicDetailStore(_ store: FireTopicDetailStore) { - topicDetailStore = store - } - - func updateWidgetData() { - guard session.readiness.canReadAuthenticatedApi else { - FireWidgetSnapshotWriter.clear() - return - } - FireWidgetSnapshotWriter.update( - session: session, - topicRows: homeFeedStore?.topicRows ?? [], - unreadNotificationCount: notificationStore?.unreadCount ?? 0 - ) - } - - // MARK: - Lifecycle - - func loadInitialState() { - initialStateLoadGeneration &+= 1 - let generation = initialStateLoadGeneration - - initialStateTask?.cancel() - initialStateLoadingDelayTask?.cancel() - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) - isBootstrappingSession = true - isStartupLoadingVisible = false - - initialStateLoadingDelayTask = Task { [weak self] in - do { - try await Task.sleep(for: .milliseconds(500)) - } catch { - return - } - - guard let self else { return } - guard self.initialStateLoadGeneration == generation else { return } - guard self.isBootstrappingSession else { return } - self.isStartupLoadingVisible = true - } - - initialStateTask = Task { [weak self] in - guard let self else { return } - defer { - self.finishInitialStateLoading(generation: generation) - } - - do { - try await FireAPMManager.shared.withSpan(.appLaunchRestoreSession) { - let sessionStore = try await self.sessionStoreValue() - guard self.initialStateLoadGeneration == generation else { return } - self.errorMessage = nil - _ = try await sessionStore.prepareStartupSession() - guard self.initialStateLoadGeneration == generation else { return } - Task { - try? await sessionStore.ensurePreloadedDataLoaded() - } - } - } catch { - guard self.initialStateLoadGeneration == generation else { return } - if await self.handleRecoverableSessionErrorIfNeeded(error) { - return - } - self.errorMessage = error.localizedDescription - } - } - } - - func completeStartupAfterPreheat() async { - let generation = initialStateLoadGeneration - do { - let sessionStore = try await sessionStoreValue() - guard self.initialStateLoadGeneration == generation else { return } - self.errorMessage = nil - let loginState = try await sessionStore.determineLoginStateWithProbe() - guard self.initialStateLoadGeneration == generation else { return } - switch loginState { - case .loggedIn: - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(true) - try await sessionStore.triggerAppStateRefresh( - .sessionRestored, - handler: appStateRefreshCoordinator - ) - let snapshot = try await sessionStore.snapshot() - guard self.initialStateLoadGeneration == generation else { return } - await self.ensureLastLoginMethodLoaded(using: sessionStore) - await self.applySession(snapshot, activateMessageBus: false) - case .networkErrorPreserveState, .sessionExpired, .notLoggedIn: - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) - let snapshot = try await sessionStore.snapshot() - guard self.initialStateLoadGeneration == generation else { return } - await self.applySession(snapshot, activateMessageBus: false) - @unknown default: - break - } - } catch { - guard self.initialStateLoadGeneration == generation else { return } - if await self.handleRecoverableSessionErrorIfNeeded(error) { - return - } - if let sessionStore = self.sessionStore, - let snapshot = try? await sessionStore.snapshot() { - await self.applySession(snapshot, activateMessageBus: false) - } - self.errorMessage = error.localizedDescription - } - } - - func completeStartupAfterPreheatFailure(message: String?) { - initialStateLoadGeneration &+= 1 - initialStateTask?.cancel() - initialStateTask = nil - initialStateLoadingDelayTask?.cancel() - initialStateLoadingDelayTask = nil - isBootstrappingSession = false - isStartupLoadingVisible = false - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) - if let message, !message.isEmpty { - errorMessage = message - } - } - - func performStartupValidation() async { - guard !isStartupValidationComplete else { return } - guard !isStartupValidationInFlight else { return } - isStartupValidationInFlight = true - defer { - isStartupValidationInFlight = false - isStartupValidationComplete = true - } - - do { - let sessionStore = try await sessionStoreValue() - _ = try await sessionStore.prepareStartupSession() - do { - _ = try await sessionStore.awaitPreloadedData() - } catch { - let snapshot = try? await sessionStore.snapshot() - let readiness = snapshot?.readiness - guard readiness?.canReadAuthenticatedApi == true - || readiness?.hasLoginCookie == true - else { - throw error - } - } - await completeStartupAfterPreheat() - } catch { - completeStartupAfterPreheatFailure(message: "网络异常,请重新登录") - } - } - - func prepareLoginForm() async { - do { - let sessionStore = try await sessionStoreValue() - savedLoginCredential = try await sessionStore.loadSavedCredential() - lastLoginMethod = try await sessionStore.loadLastLoginMethod() - _ = try await loginCoordinatorValue() - } catch { - errorMessage = error.localizedDescription - } - } - - private func ensureLastLoginMethodLoaded(using sessionStore: FireSessionStore) async { - guard lastLoginMethod == nil else { return } - lastLoginMethod = try? await sessionStore.loadLastLoginMethod() - } - - func openLogin() { - guard authPresentationState == nil else { return } - errorMessage = nil - canSyncLoginSession = false - cachedLoginSyncReadiness = nil - setAuthPresentationState(.login) - - Task { await prepareLoginForm() } - } - - func completeLogin( - from webView: WKWebView, - method: FireLastLoginMethod? = nil - ) { - Task { - _ = await completeLoginAwaitingResult(from: webView, method: method) - } - } - - /// Finalize WebView/OAuth login and return whether session is ready for home. - @discardableResult - func completeLoginAwaitingResult( - from webView: WKWebView, - method: FireLastLoginMethod? = nil - ) async -> Bool { - guard !isSyncingLoginSession else { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: "auth.login", - message: "completeLogin ignored; already syncing" - ) - return session.readiness.canReadAuthenticatedApi - } - - isSyncingLoginSession = true - defer { isSyncingLoginSession = false } - - do { - return try await FireAPMManager.shared.withSpan(.authLoginSync) { - let loginCoordinator = try await loginCoordinatorValue() - let sessionStore = try await sessionStoreValue() - errorMessage = nil - let readiness = try await loginCoordinator.probeLoginSyncReadiness(from: webView) - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.login", - message: "completeLogin probe ready=\(readiness.isReady) username=\(readiness.username ?? "nil") authCookies=\(readiness.hasAuthCookies) bootstrap=\(readiness.hasBootstrapHTML) score=\(readiness.preferredBootstrapScore)" - ) - let session = try await loginCoordinator.completeLogin(from: webView) - // Prefer starting MessageBus when bootstrap already made it possible. - await applySession(session, activateMessageBus: true) - if let method { - try await persistLastLoginMethod(method, sessionStore: sessionStore) - } - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(true) - FireCfClearanceRefreshService.shared.updateSession( - session, - loginCoordinator: loginCoordinator - ) - // fluxdo finally: cookies trusted → enter home immediately. - // App-state refresh must not block login-ready UI forever. - setAuthPresentationState(nil) - canSyncLoginSession = false - cachedLoginSyncReadiness = nil - Task { [weak self] in - guard let self else { return } - try? await sessionStore.triggerAppStateRefresh( - .loginCompleted, - handler: self.appStateRefreshCoordinator - ) - await self.ensureMessageBusActiveIfPossible() - } - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.login", - message: "completeLogin finished canReadAuth=\(session.readiness.canReadAuthenticatedApi)" - ) - return session.readiness.canReadAuthenticatedApi - } - } catch { - FireAPMManager.shared.recordBreadcrumb( - level: "error", - target: "auth.login", - message: "completeLogin failed: \(error.localizedDescription)" - ) - if await handleRecoverableSessionErrorIfNeeded(error) { - return session.readiness.canReadAuthenticatedApi - } - errorMessage = error.localizedDescription - return false - } - } - - func completeMinimalLogin( - from webView: WKWebView, - identifier: String, - password: String, - rememberCredential: Bool - ) { - guard !isSyncingLoginSession else { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: "auth.login", - message: "completeMinimalLogin ignored; already syncing" - ) - return - } - - isSyncingLoginSession = true - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.login", - message: "completeMinimalLogin capture-from-webView start remember=\(rememberCredential)" - ) - Task { - do { - let loginCoordinator = try await loginCoordinatorValue() - let captured = try await loginCoordinator.captureJsLoginState( - from: webView, - identifier: identifier - ) - await completeMinimalLogin( - captured: captured, - password: password, - rememberCredential: rememberCredential, - alreadyMarkedSyncing: true - ) - } catch { - isSyncingLoginSession = false - FireAPMManager.shared.recordBreadcrumb( - level: "error", - target: "auth.login", - message: "completeMinimalLogin capture failed: \(error.localizedDescription)" - ) - if await handleRecoverableSessionErrorIfNeeded(error) { - return - } - errorMessage = error.localizedDescription - } - } - } - - /// Finalize password login from an already-captured WebView cookie snapshot. - /// Callers should dismiss captcha UI first and show host-owned sync loading. - func completeMinimalLogin( - captured: FireCapturedLoginState, - password: String, - rememberCredential: Bool, - alreadyMarkedSyncing: Bool = false - ) async { - if !alreadyMarkedSyncing { - guard !isSyncingLoginSession else { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: "auth.login", - message: "completeMinimalLogin(captured) ignored; already syncing" - ) - return - } - isSyncingLoginSession = true - } - - let identifier = (captured.username ?? "").trimmingCharacters(in: .whitespacesAndNewlines) - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.login", - message: "completeMinimalLogin start remember=\(rememberCredential) identifier_present=\(!identifier.isEmpty)" - ) - - defer { isSyncingLoginSession = false } - - do { - try await FireAPMManager.shared.withSpan(.authLoginSync) { - let loginCoordinator = try await loginCoordinatorValue() - let sessionStore = try await sessionStoreValue() - errorMessage = nil - let session = try await loginCoordinator.completeJsLogin(captured) - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.login", - message: "completeJsLogin ok canReadAuth=\(session.readiness.canReadAuthenticatedApi) loginPhase=\(String(describing: session.loginPhase))" - ) - await applySession(session, activateMessageBus: true) - try await persistLastLoginMethod(.password, sessionStore: sessionStore) - if rememberCredential, !identifier.isEmpty { - try await sessionStore.saveLoginCredential( - username: identifier, - password: password - ) - savedLoginCredential = try await sessionStore.loadSavedCredential() - } else if !rememberCredential { - try await sessionStore.clearSavedCredential() - savedLoginCredential = nil - } - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(true) - // fluxdo finally: trusted cookies are enough to leave the login UI. - setAuthPresentationState(nil) - canSyncLoginSession = false - cachedLoginSyncReadiness = nil - Task { [weak self] in - guard let self else { return } - try? await sessionStore.triggerAppStateRefresh( - .loginCompleted, - handler: self.appStateRefreshCoordinator - ) - await self.ensureMessageBusActiveIfPossible() - } - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.login", - message: "completeMinimalLogin finished successfully" - ) - } - } catch { - FireAPMManager.shared.recordBreadcrumb( - level: "error", - target: "auth.login", - message: "completeMinimalLogin failed: \(error.localizedDescription)" - ) - if await handleRecoverableSessionErrorIfNeeded(error) { - return - } - errorMessage = error.localizedDescription - } - } - - func classifyWebViewLoginResult( - _ result: WebViewLoginJsResultState - ) async throws -> WebViewLoginDecisionState { - let sessionStore = try await sessionStoreValue() - return try await sessionStore.classifyWebViewLoginResult(result) - } - - func classifyLoginResult( - phase: WebViewLoginPhaseState, - status: UInt16, - body: String - ) async throws -> WebViewLoginDecisionState { - let result = WebViewLoginJsResultState( - phase: phase, - status: status, - body: body - ) - return try await classifyWebViewLoginResult(result) - } - - func recoverLoginCloudflareChallenge(in webView: WKWebView) async throws { - let sessionStore = try await sessionStoreValue() - try await completeLoginCloudflareChallenge(sessionStore: sessionStore) - try await Task.sleep(for: .milliseconds(1_500)) - let loginCoordinator = try await loginCoordinatorValue() - try await loginCoordinator.primeCookies( - into: webView, - targetURL: URL(string: "https://linux.do/") - ) - } - - func ensureCloudflareClearance() async -> Bool { - do { - let sessionStore = try await sessionStoreValue() - // Do not trust jar clearance that CF recently rejected (cold start / IP drift). - if try await sessionStore.cloudflareClearanceIsTrusted() { - return true - } - - try await completeLoginCloudflareChallenge(sessionStore: sessionStore) - try await Task.sleep(for: .milliseconds(1_500)) - return try await sessionStore.cloudflareClearanceIsTrusted() - } catch { - errorMessage = error.localizedDescription - return false - } - } - - func loginCoordinatorForDialog() async throws -> FireWebViewLoginCoordinator { - try await loginCoordinatorValue() - } - - func probeLoginSyncReadiness(from webView: WKWebView) async throws -> FireLoginSyncReadiness { - let loginCoordinator = try await loginCoordinatorValue() - return try await loginCoordinator.probeLoginSyncReadiness(from: webView) - } - - private func completeLoginCloudflareChallenge( - sessionStore: FireSessionStore - ) async throws { - let challengeCoordinator = FireCloudflareChallengeCoordinator(sessionStore: sessionStore) - let result = await challengeCoordinator.completeManualVerification(originURL: "https://linux.do/") - guard result.completed else { - throw FireLoginPreparationError.cloudflareVerificationIncomplete - } - - _ = try await sessionStore.completeCloudflareChallenge( - cookies: result.cookies, - freshCfClearance: result.freshCfClearance, - browserUserAgent: result.browserUserAgent - ) - } - - func dismissAuthPresentation() { - canSyncLoginSession = false - cachedLoginSyncReadiness = nil - setAuthPresentationState(nil) - } - - func prepareAuthWebView(_ webView: WKWebView) { - guard webView.url == nil else { - return - } - - let targetURL = authPresentationURL - Task { [weak self, weak webView] in - guard let self, let webView else { return } - do { - let sessionStore = try await sessionStoreValue() - let replayEntries = try await sessionStore.cookieReplayQueue() - if !replayEntries.isEmpty { - let cookieStore = webView.configuration.websiteDataStore.httpCookieStore - for entry in replayEntries { - guard let cookieURL = URL(string: entry.url) else { - continue - } - let cookies = HTTPCookie.cookies( - withResponseHeaderFields: ["Set-Cookie": entry.rawSetCookie], - for: cookieURL - ) - for cookie in cookies { - await setWebKitCookie(cookie, in: cookieStore) - } - } - try await sessionStore.clearCookieReplayQueue() - } - } catch { - errorMessage = error.localizedDescription - } - - guard webView.url == nil else { - return - } - webView.load(URLRequest(url: targetURL)) - } - } - - func saveLoginCredential(username: String, password: String) { - Task { [weak self] in - guard let self else { return } - do { - let sessionStore = try await sessionStoreValue() - try await sessionStore.saveLoginCredential(username: username, password: password) - savedLoginCredential = try await sessionStore.loadSavedCredential() - } catch { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: Self.authDiagnosticsLogTarget, - message: "failed to persist login credential: \(error.localizedDescription)" - ) - } - } - } - - private func persistLastLoginMethod( - _ method: FireLastLoginMethod, - sessionStore: FireSessionStore - ) async throws { - try await sessionStore.saveLastLoginMethod(method) - lastLoginMethod = method - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: Self.authDiagnosticsLogTarget, - message: "recorded last login method=\(method.rawValue)" - ) - } - - func recordLoginFingerprintDone() { - Task { [weak self] in - guard let self else { return } - do { - let sessionStore = try await sessionStoreValue() - await sessionStore.recordFingerprintDone() - } catch { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: Self.authDiagnosticsLogTarget, - message: "failed to record fingerprint completion: \(error.localizedDescription)" - ) - } - } - } - - func refreshBootstrap() { - Task { - do { - try await FireAPMManager.shared.withSpan(.bootstrapRefresh) { - let sessionStore = try await sessionStoreValue() - errorMessage = nil - await applySession(try await sessionStore.refreshBootstrap()) - await refreshHomeFeedIfPossible(force: false) - } - } catch { - if await handleRecoverableSessionErrorIfNeeded(error) { - return - } - errorMessage = error.localizedDescription - } - } - } - - func logout() { - guard !isLoggingOut else { - return - } - - isLoggingOut = true - // Explicit logout must never trigger mid-session / session-expired auto-login. - didRequestExplicitLogout = true - cancelMidSessionReauth(reason: "explicit_logout") - - Task { - defer { isLoggingOut = false } - - do { - let loginCoordinator = try await loginCoordinatorValue() - stopMessageBus() - errorMessage = nil - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) - await applySession(try await loginCoordinator.logout()) - let sessionStore = try await sessionStoreValue() - try await sessionStore.triggerAppStateRefresh(.logoutCompleted) - canSyncLoginSession = false - cachedLoginSyncReadiness = nil - clearTopicState() - notificationStore?.reset() - updateWidgetData() - } catch { - do { - let loginCoordinator = try await loginCoordinatorValue() - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(false) - await applySession( - try await loginCoordinator.logoutLocalAndClearPlatformCookies( - preserveCfClearance: true - ) - ) - canSyncLoginSession = false - cachedLoginSyncReadiness = nil - clearTopicState() - notificationStore?.reset() - updateWidgetData() - } catch { - errorMessage = error.localizedDescription - } - } - } - } - - // MARK: - Topic list - - func selectTopicKind(_ kind: TopicListKindState) { - homeFeedStore?.selectTopicKind(kind) - } - - func selectHomeCategory(_ categoryId: UInt64?) { - homeFeedStore?.selectHomeCategory(categoryId) - } - - func addHomeTag(_ tag: String) { - homeFeedStore?.addHomeTag(tag) - } - - func removeHomeTag(_ tag: String) { - homeFeedStore?.removeHomeTag(tag) - } - - func clearHomeTags() { - homeFeedStore?.clearHomeTags() - } - - var selectedHomeCategoryPresentation: FireTopicCategoryPresentation? { - homeFeedStore?.selectedHomeCategoryPresentation - } - - func refreshTopics() { - homeFeedStore?.refreshTopics() - } - - func refreshTopicsAsync() async { - await homeFeedStore?.refreshTopicsAsync() - } - - func loadMoreTopics() { - homeFeedStore?.loadMoreTopics() - } - - func applyHomeRowCountPatch(_ patch: TopicHomeRowCountPatchState) { - homeFeedStore?.applyHomeRowCountPatch(patch) - } - - func openTopicDetail( - topicId: UInt64, - ownerToken: String, - topicSlug: String? = nil, - targetPostNumber: UInt32? = nil, - bypassCache: Bool, - forceLoad: Bool, - trackVisit: Bool, - allowSuggestedUnreadRoot: Bool - ) { - topicDetailStore?.open( - topicId: topicId, - ownerToken: ownerToken, - slug: topicSlug, - targetPostNumber: targetPostNumber, - bypassCache: bypassCache, - forceLoad: forceLoad, - trackVisit: trackVisit, - allowSuggestedUnreadRoot: allowSuggestedUnreadRoot - ) - } - - func clearTopicDetailAnchor(topicId: UInt64) { - topicDetailStore?.clearScrollTarget(topicId: topicId) - } - - func topicDetail(for topicId: UInt64) -> TopicDetailUiSnapshotState? { - topicDetailStore?.snapshot(for: topicId) - } - - func topicPresenceUsers(for topicId: UInt64) -> [TopicDetailTypingUserState] { - topicDetailStore?.snapshot(for: topicId)?.composer.typingUsers ?? [] - } - - func isLoadingTopic(topicId: UInt64) -> Bool { - topicDetailStore?.snapshot(for: topicId)?.phase == .loading - } - - func isLoadingMoreTopicPosts(topicId: UInt64) -> Bool { - topicDetailStore?.snapshot(for: topicId)?.isLoadingMore ?? false - } - - func hasMoreTopicPosts(topicId: UInt64) -> Bool { - topicDetailStore?.snapshot(for: topicId)?.hasMore ?? false - } - - func beginTopicDetailLifecycle(topicId: UInt64, ownerToken: String) { - topicDetailStore?.open( - topicId: topicId, - ownerToken: ownerToken, - slug: nil, - targetPostNumber: nil, - bypassCache: false, - forceLoad: false, - trackVisit: true, - allowSuggestedUnreadRoot: topicDetailStore?.snapshot(for: topicId)?.phase != .ready - ) - } - - func endTopicDetailLifecycle(topicId: UInt64, ownerToken: String) { - topicDetailStore?.close(topicId: topicId, ownerToken: ownerToken) - } - - func retainedTopicDetailIDs(visibleTopicIDs: Set) -> Set { - // Owner refcount is the retention source of truth; keep any still-visible - // list rows so hosts can avoid premature eviction while scrolling. - (topicDetailStore?.ownedTopicIDs() ?? []).union(visibleTopicIDs) - } - - // MARK: - Topic detail MessageBus subscription - - func maintainTopicDetailSubscription(topicId: UInt64, ownerToken: String) async { - _ = (topicId, ownerToken) - } - - // MARK: - Write interactions - - func isSubmittingReply(topicId: UInt64) -> Bool { - topicDetailStore?.snapshot(for: topicId)?.composer.isSubmitting ?? false - } - - func isMutatingPost(postId: UInt64) -> Bool { - topicDetailStore?.isMutatingPost(postId: postId) ?? false - } - - func categoryPresentation(for categoryID: UInt64?) -> FireTopicCategoryPresentation? { - if let category = homeFeedStore?.categoryPresentation(for: categoryID) { - return category - } - guard let categoryID else { return nil } - return session.bootstrap.categories.first(where: { $0.id == categoryID }) - } - - func allCategories() -> [FireTopicCategoryPresentation] { - homeFeedStore?.allCategories ?? session.bootstrap.categories - } - - func topTags() -> [String] { - homeFeedStore?.topTags ?? session.bootstrap.topTags - } - - var canTagTopics: Bool { - homeFeedStore?.canTagTopics ?? session.bootstrap.canTagTopics - } - - var canStartAuthenticatedMutation: Bool { - session.readiness.canReadAuthenticatedApi - } - - var boundTopicDetailStore: FireTopicDetailStore? { - topicDetailStore - } - - func fetchFilteredTopicList(query: TopicListQueryState) async throws -> TopicListState { - let sessionStore = try await sessionStoreValue() - return try await sessionStore.fetchTopicList(query: query) - } - - func fetchPrivateMessages( - kind: TopicListKindState, - page: UInt32? = nil - ) async throws -> TopicListState { - let sessionStore = try await sessionStoreValue() - return try await sessionStore.fetchTopicList( - query: TopicListQueryState( - kind: kind, - page: page, - topicIds: [], - order: nil, - ascending: nil, - categorySlug: nil, - categoryId: nil, - parentCategorySlug: nil, - tag: nil, - additionalTags: [], - matchAllTags: false - ) - ) - } - - func enabledReactionOptions() -> [FireReactionOption] { - FireTopicPresentation.enabledReactionOptions(from: session.bootstrap.enabledReactionIds) - } - - func submitReply( - topicId: UInt64, - raw: String, - replyToPostNumber: UInt32?, - scrollToCreated: Bool = false - ) async throws { - guard let topicDetailStore else { - throw FireTopicInteractionError.unavailable - } - try await topicDetailStore.submitReply( - topicId: topicId, - raw: raw, - replyToPostNumber: replyToPostNumber, - scrollToCreated: scrollToCreated - ) - } - - func createTopic( - title: String, - raw: String, - categoryID: UInt64, - tags: [String] - ) async throws -> UInt64 { - let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines) - let trimmedRaw = raw.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmedTitle.isEmpty else { - throw FireTopicInteractionError.emptyReply - } - guard !trimmedRaw.isEmpty else { - throw FireTopicInteractionError.emptyReply - } - - let sessionStore = try await sessionStoreValue() - guard canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - - do { - errorMessage = nil - let topicID = try await performWriteWithCloudflareRetry { - try await sessionStore.createTopic( - title: trimmedTitle, - raw: trimmedRaw, - categoryID: categoryID, - tags: tags - ) - } - await syncSessionSnapshotIfAvailable(from: sessionStore) - await refreshHomeFeedIfPossible(force: true) - return topicID - } catch { - _ = await handleInteractionError(error) - throw error - } - } - - func createPrivateMessage( - title: String, - raw: String, - targetRecipients: [String] - ) async throws -> UInt64 { - let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines) - let trimmedRaw = raw.trimmingCharacters(in: .whitespacesAndNewlines) - let recipients = targetRecipients - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - - guard !trimmedTitle.isEmpty else { - throw FireTopicInteractionError.emptyReply - } - guard !trimmedRaw.isEmpty else { - throw FireTopicInteractionError.emptyReply - } - guard !recipients.isEmpty else { - throw FireTopicInteractionError.emptyReply - } - - let sessionStore = try await sessionStoreValue() - guard canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - - do { - errorMessage = nil - let topicID = try await performWriteWithCloudflareRetry { - try await sessionStore.createPrivateMessage( - title: trimmedTitle, - raw: trimmedRaw, - targetRecipients: recipients - ) - } - await syncSessionSnapshotIfAvailable(from: sessionStore) - return topicID - } catch { - _ = await handleInteractionError(error) - throw error - } - } - - func updateTopic( - topicID: UInt64, - title: String, - categoryID: UInt64, - tags: [String] - ) async throws { - let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmedTitle.isEmpty else { - throw FireTopicInteractionError.emptyReply - } - - let sessionStore = try await sessionStoreValue() - guard canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - - do { - errorMessage = nil - try await performWriteWithCloudflareRetry { - try await sessionStore.updateTopic( - topicID: topicID, - title: trimmedTitle, - categoryID: categoryID, - tags: tags - ) - } - await syncSessionSnapshotIfAvailable(from: sessionStore) - try await topicDetailStore?.updateTopic( - topicId: topicID, - title: trimmedTitle, - categoryId: categoryID, - tags: tags - ) - await refreshHomeFeedIfPossible(force: true) - } catch { - _ = await handleInteractionError(error) - throw error - } - } - - func fetchPost(postID: UInt64) async throws -> TopicPostState { - let sessionStore = try await sessionStoreValue() - return try await sessionStore.fetchPost(postID: postID) - } - - func updatePost( - topicID: UInt64, - postID: UInt64, - raw: String, - editReason: String? = nil - ) async throws { - guard let topicDetailStore else { - throw FireTopicInteractionError.unavailable - } - try await topicDetailStore.updatePost( - topicId: topicID, - postId: postID, - raw: raw, - editReason: editReason - ) - await refreshHomeFeedIfPossible(force: false) - } - - func fetchDrafts( - offset: UInt32? = nil, - limit: UInt32? = nil - ) async throws -> DraftListResponseState { - let sessionStore = try await sessionStoreValue() - return try await sessionStore.fetchDrafts(offset: offset, limit: limit) - } - - func fetchReadHistory(page: UInt32? = nil) async throws -> TopicListState { - let sessionStore = try await sessionStoreValue() - return try await sessionStore.fetchReadHistory(page: page) - } - - func fetchDraft(draftKey: String) async throws -> DraftState? { - let sessionStore = try await sessionStoreValue() - return try await sessionStore.fetchDraft(draftKey: draftKey) - } - - func saveDraft( - draftKey: String, - data: DraftDataState, - sequence: UInt32 - ) async throws -> UInt32 { - let sessionStore = try await sessionStoreValue() - return try await performWriteWithCloudflareRetry { - try await sessionStore.saveDraft( - draftKey: draftKey, - data: data, - sequence: sequence - ) - } - } - - func deleteDraft( - draftKey: String, - sequence: UInt32? = nil - ) async throws { - let sessionStore = try await sessionStoreValue() - try await performWriteWithCloudflareRetry { - try await sessionStore.deleteDraft(draftKey: draftKey, sequence: sequence) - } - } - - func uploadImage( - fileName: String, - mimeType: String?, - bytes: Data - ) async throws -> UploadResultState { - let sessionStore = try await sessionStoreValue() - return try await performWriteWithCloudflareRetry { - try await sessionStore.uploadImage( - fileName: fileName, - mimeType: mimeType, - bytes: bytes - ) - } - } - - func lookupUploadUrls(shortUrls: [String]) async throws -> [ResolvedUploadUrlState] { - let sessionStore = try await sessionStoreValue() - return try await performWriteWithCloudflareRetry { - try await sessionStore.lookupUploadUrls(shortUrls: shortUrls) - } - } - - func dismissError() { - errorMessage = nil - } - - func updateTopLevelAPMRoute(selectedTab: Int, isAuthenticated: Bool) { - let route: String - if !isAuthenticated { - route = "session.onboarding" - } else { - switch selectedTab { - case 0: - route = "tab.home" - case 1: - route = "tab.notifications" - case 2: - route = "tab.chat" - case 3: - route = "tab.profile" - default: - route = "tab.unknown" - } - } - topLevelAPMRoute = route - FireAPMManager.shared.setCurrentRoute(route) - } - - func restoreTopLevelAPMRoute() { - FireAPMManager.shared.setCurrentRoute(topLevelAPMRoute) - } - - func setAPMRoute(_ route: String) { - FireAPMManager.shared.setCurrentRoute(route) - } - - // MARK: - MessageBus lifecycle - - private func startMessageBus() async { - guard let sessionStore else { return } - guard session.readiness.canOpenMessageBus else { return } - guard !isMessageBusActive else { return } - - messageBusRetryTask?.cancel() - messageBusRetryTask = nil - - let coordinator = FireMessageBusCoordinator { [weak self] event in - self?.handleMessageBusEvent(event) - } - messageBusCoordinator = coordinator - - do { - _ = try await FireAPMManager.shared.withSpan(.messageBusStart) { - try await sessionStore.startMessageBus(handler: coordinator) - } - isMessageBusActive = true - messageBusStartRetryCount = 0 - clearMessageBusError() - } catch { - messageBusCoordinator = nil - if await handleRecoverableSessionErrorIfNeeded(error) { - return - } - errorMessage = Self.messageBusErrorPrefix + error.localizedDescription - scheduleMessageBusRetry() - } - } - - private func stopMessageBus() { - messageBusRetryTask?.cancel() - messageBusRetryTask = nil - messageBusStartRetryCount = 0 - notificationStore?.cancelScheduledRefresh() - homeFeedStore?.handleMessageBusStopped() - clearMessageBusError() - guard isMessageBusActive else { return } - messageBusCoordinator = nil - isMessageBusActive = false - guard let sessionStore else { return } - Task { try? await sessionStore.stopMessageBus(clearSubscriptions: true) } - } - - private func handleMessageBusEvent(_ event: MessageBusEventState) { - switch event.kind { - case .topicList: - homeFeedStore?.handleTopicListMessageBusEvent(event) - - case .topicDetail, .topicReaction, .presence: - break - - case .notification: - notificationStore?.scheduleStateRefresh() - - case .notificationAlert: - break - - case .chat: - chatChannelsStore?.handleMessageBusEvent(event) - NotificationCenter.default.post( - name: .fireChatMessageBusEvent, - object: nil, - userInfo: ["event": event] - ) - - case .sessionLogout: - serverForcedLogout = true - cancelMidSessionReauth(reason: "server_forced_logout") - - case .unknown: - break - } - } - - func beginTopicReplyPresence(topicId: UInt64) { - topicDetailStore?.beginReplyTyping(topicId: topicId) - } - - func endTopicReplyPresence(topicId: UInt64) async { - topicDetailStore?.endReplyTyping(topicId: topicId) - } - - // MARK: - Private helpers - - private func prepareLoginNetworkAccess() async throws { - let configuration = URLSessionConfiguration.ephemeral - configuration.waitsForConnectivity = true - - let session = URLSession(configuration: configuration) - var request = URLRequest(url: loginURL) - request.timeoutInterval = 20 - request.cachePolicy = .reloadIgnoringLocalCacheData - - let (_, response) = try await session.data(for: request) - guard response is HTTPURLResponse else { - throw FireLoginPreparationError.invalidResponse - } - } - - private func preloadLoginCoordinator() async throws { - if let loginCoordinatorPreloader { - try await loginCoordinatorPreloader() - return - } - - _ = try await loginCoordinatorValue() - } - - private func warmLoginNetworkAccess() async { - if let loginNetworkWarmup { - await loginNetworkWarmup() - return - } - - do { - try await prepareLoginNetworkAccess() - } catch { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: "auth.login", - message: "login network warmup failed: \(error.localizedDescription)" - ) - } - } - - private func refreshTopicsIfPossible(force: Bool) async { - await refreshHomeFeedIfPossible(force: force) - } - - var authPresentationURL: URL { - loginURL - } - - private func clearTopicState() { - homeFeedStore?.reset(resetTopicKind: true) - topicDetailStore?.reset() - } - - private func finishInitialStateLoading(generation: UInt64) { - guard initialStateLoadGeneration == generation else { - return - } - - initialStateLoadingDelayTask?.cancel() - initialStateLoadingDelayTask = nil - isBootstrappingSession = false - isStartupLoadingVisible = false - initialStateTask = nil - } - - private func applySession(_ session: SessionState, activateMessageBus: Bool = true) async { - let wasAuthenticated = self.session.readiness.canReadAuthenticatedApi - let shouldSyncNativeCookies = session.cookies != self.session.cookies - || session.bootstrap.baseUrl != self.session.bootstrap.baseUrl - self.session = session - if shouldSyncNativeCookies { - session.syncCookiesToNativeStorage() - } - homeFeedStore?.applySession(session) - topicDetailStore?.applySession(session) - if let request = session.readPathLoginRequest, - request.generation != lastReadPathLoginGeneration { - lastReadPathLoginGeneration = request.generation - let operation = request.operation - let recovered = await attemptHostCookieResyncRecovery(operation: operation) - let succeeded: Bool - if recovered { - succeeded = true - } else { - succeeded = await attemptMidSessionHeadlessReauth(operation: operation) - } - if let sessionStore = currentSessionStore() { - try? await sessionStore.completeReadPathLogin( - generation: request.generation, - succeeded: succeeded - ) - } - } - - let isAuthenticated = session.readiness.canReadAuthenticatedApi - if wasAuthenticated && !isAuthenticated { - if let coordinator = try? await loginCoordinatorValue() { - try? await coordinator.clearSameSiteIdentityCookies(preservingCfClearance: true) - } - if serverForcedLogout { - serverForcedLogout = false - } else if !didRequestExplicitLogout { - // Raise the reauth hold synchronously so RootCoordinator's next main-runloop - // auth sink keeps the main shell mounted for Google headless recovery. - scheduleMidSessionReauthAfterPassiveDeauth() - } - } - - if isAuthenticated { - await notificationStore?.syncStateFromRuntimeIfAvailable() - if needsBootstrapIdentityHydration(session) { - Task { await self.hydrateBootstrapIfNeeded() } - } - } else { - notificationStore?.reset() - updateWidgetData() - } - - // Reconcile MessageBus lifecycle - if session.readiness.canOpenMessageBus && activateMessageBus && !isMessageBusActive { - await startMessageBus() - } else if !session.readiness.canOpenMessageBus && isMessageBusActive { - stopMessageBus() - } else if !session.readiness.canOpenMessageBus { - stopMessageBus() - } - - if let coordinator = try? await loginCoordinatorValue() { - FireCfClearanceRefreshService.shared.updateSession( - session, - loginCoordinator: coordinator, - onSessionRefreshed: { [weak self] updatedSession in - guard let self else { return } - await self.cfClearanceDidRefresh(updatedSession) - } - ) - } - } - - func cfClearanceDidRefresh(_ updatedSession: SessionState) async { - await applySession(updatedSession) - } - - func refreshLoginSyncReadiness(from webView: WKWebView) { - loginSyncReadinessTask?.cancel() - loginSyncReadinessTask = Task { [weak self] in - guard let self else { return } - do { - let coordinator = try await loginCoordinatorValue() - let readiness = try await coordinator.probeLoginSyncReadiness(from: webView) - guard !Task.isCancelled else { return } - let previous = canSyncLoginSession - cachedLoginSyncReadiness = readiness.isReady - ? CachedLoginSyncReadiness( - currentURL: webView.url?.absoluteString, - readiness: readiness - ) - : nil - canSyncLoginSession = readiness.isReady - if previous != readiness.isReady { - FireAPMManager.shared.recordBreadcrumb( - target: "auth.login", - message: readiness.isReady - ? "login sync readiness satisfied" - : "login sync readiness cleared" - ) - } - } catch { - guard !Task.isCancelled else { return } - canSyncLoginSession = false - cachedLoginSyncReadiness = nil - } - } - } - - private func scheduleMessageBusRetry() { - guard session.readiness.canOpenMessageBus else { return } - guard !isMessageBusActive else { return } - guard messageBusStartRetryCount < 3 else { return } - - messageBusStartRetryCount += 1 - let retryDelay = Duration.seconds(Double(messageBusStartRetryCount * 2)) - messageBusRetryTask = Task { [weak self] in - do { - try await Task.sleep(for: retryDelay) - } catch { - return - } - guard let self else { return } - self.messageBusRetryTask = nil - await self.startMessageBus() - } - } - - private func clearMessageBusError() { - if errorMessage?.hasPrefix(Self.messageBusErrorPrefix) == true { - errorMessage = nil - } - } - - /// Write-path CF wrapper. **Passthrough** — does not wait or present. - /// - /// Rust already fails writes quickly with `CloudflareChallengeInProgress` - /// while a challenge is active. Host-side wait/retry would hang composer - /// actions for up to minutes with no UI feedback; callers should surface - /// the error and let the user retry after verification. - func performWriteWithCloudflareRetry( - operationDescription: String = "执行当前操作", - originURL: URL? = nil, - operation: @escaping () async throws -> T - ) async throws -> T { - _ = operationDescription - _ = originURL - return try await operation() - } - - /// Read-path join/retry helper for Cloudflare errors. **Does not present** UI. - /// - /// - `in_progress`: wait for the host presentation gate (Rust handler already - /// owns the WebView), settle jar merge, then retry `work` once. - /// - other CF reasons: rethrow for banners / explicit manual verify. - /// - /// `originURL` is retained for call-site compatibility and diagnostics only. - func performWithCloudflareRecovery( - operation: String, - originURL: URL? = nil, - work: @escaping () async throws -> T - ) async throws -> T { - do { - return try await work() - } catch { - guard Self.isCloudflareChallengeError(error) else { - throw error - } - let reason = Self.cloudflareChallengeReason(from: error) - switch Self.cloudflareRecoveryAction(forReason: reason) { - case .waitThenRetry: - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.cf", - message: "recovery wait-then-retry operation=\(operation) reason=\(reason) origin=\(originURL?.absoluteString ?? "nil")" - ) - await Self.awaitCloudflareChallengeQuietPeriod() - return try await work() - case .rethrow: - throw error - } - } - } - - /// Host recovery policy for a normalized CF reason token (read path). - /// Automatic paths never present UI (`waitThenRetry` / `rethrow` only). - enum CloudflareRecoveryAction: Equatable { - case waitThenRetry - case rethrow - } - - nonisolated static func cloudflareRecoveryAction( - forReason reason: String - ) -> CloudflareRecoveryAction { - switch reason { - case "in_progress": - return .waitThenRetry - default: - // required / failed / cancelled / cooldown / background_suppressed: - // surface to UI. Present only via Rust handler or explicit manual APIs. - return .rethrow - } - } - - /// Wait for an in-flight host challenge presentation, then briefly settle. - /// Used on read paths when Rust blocks concurrent traffic with `in_progress`. - static func awaitCloudflareChallengeQuietPeriod( - appearTimeout: Duration = .seconds(2), - presentationTimeout: Duration = .seconds(120), - settle: Duration = .milliseconds(500) - ) async { - await FireCloudflareChallengePresentationGate.awaitPresentationAppearance( - timeout: appearTimeout - ) - if FireCloudflareChallengePresentationGate.isPresentationInFlight { - await FireCloudflareChallengePresentationGate.awaitActivePresentationIfAny( - timeout: presentationTimeout - ) - } - try? await Task.sleep(for: settle) - } - - nonisolated static func isCloudflareChallengeError(_ error: Error) -> Bool { - if let fireError = error as? FireUniFfiError { - if case .CloudflareChallenge = fireError { - return true - } - } - let message = String(describing: error).lowercased() - return message.contains("cloudflare challenge") - } - - nonisolated static func cloudflareChallengeReason(from error: Error) -> String { - if let fireError = error as? FireUniFfiError, - case let .CloudflareChallenge(reason) = fireError { - let trimmed = reason.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmed.isEmpty { - return trimmed - } - } - let message = String(describing: error) - for token in ["in_progress", "cooldown", "cancelled", "failed", "background_suppressed", "required"] { - if message.contains("(\(token))") || message.contains(token) { - return token - } - } - return "required" - } - - /// Onboarding entry used when the authenticated shell loses auth. - /// Explicit logout always returns `.signedOut` (no auto-login). - /// Passive / mid-session invalidation returns `.sessionExpired` so headless - /// Google can auto-login on the onboarding host as a fallback path. - func deauthOnboardingEntry() -> FireOnboardingEntry { - if didRequestExplicitLogout { - didRequestExplicitLogout = false - return .signedOut - } - return .sessionExpired - } - - /// Cancel an in-flight mid-session reauth (overlay cancel / explicit logout). - func cancelMidSessionReauth(reason: String = "user_cancel") { - guard isMidSessionReauthInFlight || midSessionReauthEngine != nil else { return } - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: Self.authDiagnosticsLogTarget, - message: "mid-session reauth cancelled reason=\(reason)" - ) - if let engine = midSessionReauthEngine { - engine.cancel() - return - } - finishMidSessionReauth(success: false) - } - - /// Read-side recovery for transient `LoginRequired` errors observed during - /// passive reads (home feed, topic detail) and other in-app requests. - /// - /// Recovery order: - /// 1. Single-flight host cookie resync per session epoch (WebKit may be ahead - /// of the shared Rust jar after `_t` / `_forum_session` rotation). - /// 2. If the last login method is headless-capable (currently Google), run - /// mid-session headless reauth under a loading overlay and keep the main - /// shell mounted so the caller can retry the original request in place. - /// - /// - Returns: `true` when recovery succeeded and the caller should retry once. - @discardableResult - func attemptReadPathLoginRecovery( - operation: String, - error: Error - ) async -> Bool { - guard case FireUniFfiError.LoginRequired = error else { - return false - } - - if await attemptHostCookieResyncRecovery(operation: operation) { - return true - } - - return await attemptMidSessionHeadlessReauth(operation: operation) - } - - private func attemptHostCookieResyncRecovery(operation: String) async -> Bool { - let logger = await authDiagnosticsLogger() - - let beforeEpoch: UInt64 - do { - beforeEpoch = try await currentSessionEpoch() - } catch { - logger?.warning( - "read-path resync skipped operation=\(operation) reason=epoch_unavailable error=\(error.localizedDescription)" - ) - return false - } - - if readPathLoginRecoveryAttemptedEpochs.contains(beforeEpoch) { - logger?.notice( - "read-path resync skipped operation=\(operation) reason=already_attempted epoch=\(beforeEpoch)" - ) - return false - } - - if let existingTask = readPathLoginRecoveryTask, - readPathLoginRecoveryEpoch == beforeEpoch { - return await existingTask.value - } - - let task = Task { [weak self] in - guard let self else { return false } - return await self.runReadPathLoginRecovery( - operation: operation, - beforeEpoch: beforeEpoch - ) - } - readPathLoginRecoveryTask = task - readPathLoginRecoveryEpoch = beforeEpoch - defer { - if readPathLoginRecoveryEpoch == beforeEpoch { - readPathLoginRecoveryTask = nil - readPathLoginRecoveryEpoch = nil - } - } - return await task.value - } - - private func runReadPathLoginRecovery( - operation: String, - beforeEpoch: UInt64 - ) async -> Bool { - readPathLoginRecoveryAttemptedEpochs.insert(beforeEpoch) - let logger = await authDiagnosticsLogger() - - let coordinator: FireWebViewLoginCoordinator - do { - coordinator = try await loginCoordinatorValue() - } catch { - logger?.warning( - "read-path resync skipped operation=\(operation) epoch=\(beforeEpoch) reason=no_coordinator error=\(error.localizedDescription)" - ) - return false - } - - let cookies: [PlatformCookieState] - do { - cookies = try await coordinator.platformCookiesForSessionResync() - } catch { - logger?.warning( - "read-path resync failed operation=\(operation) epoch=\(beforeEpoch) reason=cookie_fetch_failed error=\(error.localizedDescription)" - ) - return false - } - - guard FireWebViewLoginCoordinator.containsActiveAuthCookies(in: cookies) else { - logger?.notice( - "read-path resync skipped operation=\(operation) epoch=\(beforeEpoch) reason=no_authoritative_webview_auth_cookies cookie_count=\(cookies.count)" - ) - return false - } - - let sessionStore: FireSessionStore - do { - sessionStore = try await sessionStoreValue() - } catch { - logger?.warning( - "read-path resync skipped operation=\(operation) epoch=\(beforeEpoch) reason=no_session_store error=\(error.localizedDescription)" - ) - return false - } - - do { - _ = try await sessionStore.applyPlatformCookies(cookies) - } catch { - logger?.warning( - "read-path resync failed operation=\(operation) epoch=\(beforeEpoch) reason=apply_failed error=\(error.localizedDescription)" - ) - return false - } - - let afterEpoch: UInt64 - do { - afterEpoch = try await sessionStore.currentSessionEpoch() - } catch { - logger?.warning( - "read-path resync inconclusive operation=\(operation) epoch=\(beforeEpoch) reason=post_epoch_unavailable error=\(error.localizedDescription)" - ) - return false - } - - let didRotate = afterEpoch != beforeEpoch - if didRotate { - // Once the resync actually rotated us into a new auth epoch, the - // older `attempted` markers no longer protect us from anything; - // keep the set small so a long-lived session doesn't accumulate - // stale markers. - readPathLoginRecoveryAttemptedEpochs = readPathLoginRecoveryAttemptedEpochs - .filter { $0 == afterEpoch } - FireAPMManager.shared.recordBreadcrumb( - target: Self.authDiagnosticsLogTarget, - message: "read-path resync rotated auth operation=\(operation) before_epoch=\(beforeEpoch) after_epoch=\(afterEpoch) cookie_count=\(cookies.count)" - ) - logger?.notice( - "read-path resync rotated auth operation=\(operation) before_epoch=\(beforeEpoch) after_epoch=\(afterEpoch) cookie_count=\(cookies.count)" - ) - } else { - logger?.notice( - "read-path resync no_change operation=\(operation) epoch=\(beforeEpoch) cookie_count=\(cookies.count)" - ) - } - return didRotate - } - - /// Called from `applySession` when auth drops without an explicit logout. - /// Starts Google headless recovery early enough for RootCoordinator to hold the shell. - private func scheduleMidSessionReauthAfterPassiveDeauth() { - if midSessionReauthTask != nil || isMidSessionReauthInFlight { - return - } - - let knownMethod = FireAutoLoginPlanner.midSessionHeadlessKind( - lastLoginMethod: lastLoginMethod - ) - // lastLoginMethod may not be loaded yet on a long-lived session; optimistically - // hold and resolve eligibility inside the single-flight reauth task. - guard knownMethod != nil || lastLoginMethod == nil else { - return - } - - isMidSessionReauthInFlight = true - if midSessionReauthMessage == nil { - if let knownMethod { - midSessionReauthMessage = FireAutoLoginPlanner.loadingMessage( - for: .external(knownMethod) - ) - } else { - midSessionReauthMessage = "正在恢复登录…" - } - } - - Task { @MainActor [weak self] in - guard let self else { return } - _ = await self.attemptMidSessionHeadlessReauth(operation: "session_deauth") - } - } - - /// Mid-session headless reauth for LoginRequired when cookie resync cannot help. - /// Currently limited to providers in `FireAutoLoginPlanner.headlessExternalPool` - /// (Google). Single-flight across the app so concurrent failing requests share - /// one overlay + one OAuth attempt, then all retry. - private func attemptMidSessionHeadlessReauth(operation: String) async -> Bool { - if let existing = midSessionReauthTask { - return await existing.value - } - - let task = Task { [weak self] in - guard let self else { return false } - return await self.runMidSessionHeadlessReauth(operation: operation) - } - midSessionReauthTask = task - let result = await task.value - if midSessionReauthTask != nil { - midSessionReauthTask = nil - } - return result - } - - private func runMidSessionHeadlessReauth(operation: String) async -> Bool { - // Explicit logout wins over any in-flight recovery. - guard !didRequestExplicitLogout, !isLoggingOut else { - finishMidSessionReauth(success: false) - return false - } - - if lastLoginMethod == nil { - await prepareLoginForm() - } - - guard let method = FireAutoLoginPlanner.midSessionHeadlessKind( - lastLoginMethod: lastLoginMethod - ) else { - let logger = await authDiagnosticsLogger() - logger?.notice( - "mid-session reauth skipped operation=\(operation) reason=method_ineligible last=\(String(describing: lastLoginMethod))" - ) - finishMidSessionReauth(success: false) - return false - } - - guard let hostViewController = Self.topPresenterForMidSessionReauth() else { - let logger = await authDiagnosticsLogger() - logger?.warning( - "mid-session reauth skipped operation=\(operation) reason=no_presenter" - ) - finishMidSessionReauth(success: false) - return false - } - - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: Self.authDiagnosticsLogTarget, - message: "mid-session reauth begin operation=\(operation) method=\(method.rawValue)" - ) - - isMidSessionReauthInFlight = true - midSessionReauthMessage = FireAutoLoginPlanner.loadingMessage(for: .external(method)) - - let succeeded = await withCheckedContinuation { (continuation: CheckedContinuation) in - // A proactive deauth hold may already have flipped inFlight without a waiter. - if let previous = self.midSessionReauthContinuation { - self.midSessionReauthContinuation = nil - previous.resume(returning: false) - } - self.midSessionReauthContinuation = continuation - - let engine = FireHeadlessExternalLoginEngine(method: method, viewModel: self) - self.midSessionReauthEngine = engine - engine.onOutcome = { [weak self] outcome in - guard let self else { return } - self.handleMidSessionReauthOutcome( - outcome, - method: method, - presenter: hostViewController - ) - } - engine.start(in: hostViewController.view) - } - - if succeeded { - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: Self.authDiagnosticsLogTarget, - message: "mid-session reauth succeeded operation=\(operation) method=\(method.rawValue)" - ) - } else { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: Self.authDiagnosticsLogTarget, - message: "mid-session reauth failed operation=\(operation) method=\(method.rawValue)" - ) - } - return succeeded - } - - private func handleMidSessionReauthOutcome( - _ outcome: FireHeadlessExternalLoginEngine.Outcome, - method: FireExternalLoginMethod, - presenter: UIViewController - ) { - switch outcome { - case .authenticated: - guard let webView = midSessionReauthEngine?.currentWebView else { - finishMidSessionReauth(success: false) - return - } - midSessionReauthMessage = "正在同步登录态…" - Task { @MainActor in - let ok = await self.completeLoginAwaitingResult( - from: webView, - method: method.lastLoginMethod - ) - self.finishMidSessionReauth(success: ok && self.session.readiness.canReadAuthenticatedApi) - } - - case .needsUserInteraction: - midSessionReauthMessage = FireAutoLoginPlanner.loadingMessage(for: .external(method)) - .replacingOccurrences(of: "正在通过", with: "请完成") - .replacingOccurrences(of: "…", with: "") - midSessionReauthEngine?.promote(from: presenter) - - case .failed: - finishMidSessionReauth(success: false) - - case .cancelled: - finishMidSessionReauth(success: false) - } - } - - private func finishMidSessionReauth(success: Bool) { - midSessionReauthEngine?.teardown() - midSessionReauthEngine = nil - midSessionReauthMessage = nil - isMidSessionReauthInFlight = false - - if let continuation = midSessionReauthContinuation { - midSessionReauthContinuation = nil - continuation.resume(returning: success) - } - } - - private static func topPresenterForMidSessionReauth() -> UIViewController? { - let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } - let window = scenes - .flatMap(\.windows) - .first(where: \.isKeyWindow) - ?? scenes.flatMap(\.windows).first - guard var top = window?.rootViewController else { return nil } - while let presented = top.presentedViewController { - top = presented - } - return top - } - - private func currentSessionEpoch() async throws -> UInt64 { - let sessionStore = try await sessionStoreValue() - return try await sessionStore.currentSessionEpoch() - } - - @discardableResult - func handleRecoverableSessionErrorIfNeeded(_ error: Error) async -> Bool { - await handleStaleSessionResponseIfNeeded(error) - } - - @discardableResult - func handleStaleSessionResponseIfNeeded(_ error: Error) async -> Bool { - guard case let FireUniFfiError.StaleSessionResponse(operation) = error else { - return false - } - - FireAPMManager.shared.recordBreadcrumb( - target: Self.authDiagnosticsLogTarget, - message: "discarded stale session response operation=\(operation)" - ) - return true - } - - @discardableResult - func handleInteractionError(_ error: Error) async -> Bool { - if await handleRecoverableSessionErrorIfNeeded(error) { - return true - } - errorMessage = error.localizedDescription - return false - } - - private func authDiagnosticsLogger() async -> FireHostLogger? { - if let sessionStore { - return sessionStore.makeLogger(target: Self.authDiagnosticsLogTarget) - } - guard let sessionStore = try? await sessionStoreValue() else { - return nil - } - return sessionStore.makeLogger(target: Self.authDiagnosticsLogTarget) - } - - private func setWebKitCookie(_ cookie: HTTPCookie, in store: WKHTTPCookieStore) async { - await withCheckedContinuation { continuation in - store.setCookie(cookie) { - continuation.resume() - } - } + func bindHomeFeedStore(_ store: FireHomeFeedStore) { + homeFeedStore = store } - private func setAuthPresentationState(_ state: FireAuthPresentationState?) { - authPresentationState = state + func bindChatChannelsStore(_ store: FireChatChannelsStore) { + chatChannelsStore = store } - func topicDetailLogger() -> FireHostLogger? { - sessionStore?.makeLogger(target: Self.topicDetailLogTarget) + func bindNotificationStore(_ store: FireNotificationStore) { + notificationStore = store } - func topicRouteLogger() -> FireHostLogger? { - sessionStore?.makeLogger(target: Self.topicRouteLogTarget) + func bindTopicDetailStore(_ store: FireTopicDetailStore) { + topicDetailStore = store } func currentSessionStore() -> FireSessionStore? { sessionStore } - func ensureMessageBusActiveIfPossible() async { - guard !isMessageBusActive else { return } - await startMessageBus() - } - - func restartMessageBusAfterClearanceIfPossible() async { - if isMessageBusActive { - stopMessageBus() - } - await startMessageBus() - } - - private func handleAppStateRefreshEvent(_ event: AppStateRefreshEventState) { - if event.trigger == .cloudflareResolved { - Task { @MainActor in - self.homeFeedStore?.clearTopicLoadError() - if self.session.readiness.canOpenMessageBus { - await self.restartMessageBusAfterClearanceIfPossible() - } - } - } - } - - private func handleClearanceResolved(_ event: CloudflareClearanceResolvedEventState) async { - homeFeedStore?.clearTopicLoadError() - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.cf", - message: "clearance resolved gen=\(event.generation) login=\(event.hasLoginSession) bus=\(event.canOpenMessageBus)" - ) - if event.canOpenMessageBus || session.readiness.canOpenMessageBus { - await restartMessageBusAfterClearanceIfPossible() - } - // Home topic list may still show a CF failure banner; force one refresh. - _ = await refreshHomeFeedIfPossible(force: true) - await hydrateBootstrapIfNeeded(force: true) - } - - /// Pull home bootstrap when cookies exist but `current_username` / preloaded - /// data never landed. Profile, logout, and MessageBus all need that identity. - func hydrateBootstrapIfNeeded(force: Bool = false) async { - let current = session - guard current.hasLoginSession || current.readiness.canReadAuthenticatedApi else { - lastBootstrapHydrationAttemptKey = nil - return - } - guard needsBootstrapIdentityHydration(current) else { - lastBootstrapHydrationAttemptKey = nil - return - } - let attemptKey = bootstrapHydrationAttemptKey(current) - guard force || lastBootstrapHydrationAttemptKey != attemptKey else { - return - } - guard !isHydratingBootstrap else { - return - } - isHydratingBootstrap = true - lastBootstrapHydrationAttemptKey = attemptKey - defer { isHydratingBootstrap = false } - do { - let sessionStore = try await sessionStoreValue() - var snapshot = try await sessionStore.refreshBootstrapIfNeeded() - await applySession(snapshot, activateMessageBus: false) - if needsBootstrapIdentityHydration(snapshot) { - snapshot = try await sessionStore.refreshBootstrap() - await applySession(snapshot, activateMessageBus: false) - } - } catch { - FireAPMManager.shared.recordBreadcrumb( - level: "warn", - target: "auth.bootstrap", - message: "bootstrap hydration failed: \(error.localizedDescription)" - ) - } - } - - private func needsBootstrapIdentityHydration(_ session: SessionState) -> Bool { - !session.readiness.hasCurrentUser || !session.readiness.hasPreloadedData - } - - private func bootstrapHydrationAttemptKey(_ session: SessionState) -> String { - [ - session.hasLoginSession ? "1" : "0", - session.readiness.canReadAuthenticatedApi ? "1" : "0", - session.cookies.tToken ?? "", - session.cookies.forumSession ?? "", - ].joined(separator: "|") - } - - @discardableResult - func refreshHomeFeedIfPossible(force: Bool) async -> Bool { - await homeFeedStore?.refreshTopicsIfPossible(force: force) ?? false - } - - func pruneTopicDetailState(retainingVisibleTopicIDs visibleTopicIDs: Set) { - _ = visibleTopicIDs - } - - func currentVisibleTopicIDs() -> Set { - homeFeedStore?.visibleTopicIDs ?? [] - } - - func syncSessionSnapshotIfAvailable(from sessionStore: FireSessionStore) async { - if let snapshot = try? await sessionStore.snapshot() { - await applySession(snapshot) - } - } - func sessionStoreValue() async throws -> FireSessionStore { if let sessionStore { await registerStateObserver(with: sessionStore) @@ -2183,73 +169,4 @@ final class FireAppViewModel: ObservableObject { throw error } } - - private func registerStateObserver(with sessionStore: FireSessionStore) async { - await sessionStore.registerStateObserver(stateObserverCoordinator) - } - - private func loginCoordinatorValue() async throws -> FireWebViewLoginCoordinator { - if let loginCoordinator { - return loginCoordinator - } - - let sessionStore = try await sessionStoreValue() - await configureAuthenticatedWriteHostResyncProvider(with: sessionStore) - guard let loginCoordinator else { - throw CancellationError() - } - return loginCoordinator - } - - private func configureAuthenticatedWriteHostResyncProvider( - with sessionStore: FireSessionStore - ) async { - let loginCoordinator: FireWebViewLoginCoordinator - if let existingLoginCoordinator = self.loginCoordinator { - loginCoordinator = existingLoginCoordinator - } else { - let newLoginCoordinator = FireWebViewLoginCoordinator(sessionStore: sessionStore) - self.loginCoordinator = newLoginCoordinator - loginCoordinator = newLoginCoordinator - } - - await sessionStore.setAuthenticatedWriteHostResyncProvider { [weak loginCoordinator] in - guard let loginCoordinator else { - return nil - } - return try await loginCoordinator.platformCookiesForSessionResync() - } - - if cloudflareChallengeHandler == nil { - cloudflareChallengeHandler = FireCloudflareChallengeRuntimeHandler( - sessionStore: sessionStore - ) - } - if let cloudflareChallengeHandler { - try? await sessionStore.registerCloudflareChallengeHandler( - cloudflareChallengeHandler - ) - } - if clearanceResolvedHandler == nil { - clearanceResolvedHandler = FireClearanceResolvedRuntimeHandler { [weak self] event in - await self?.handleClearanceResolved(event) - } - } - if let clearanceResolvedHandler { - try? await sessionStore.registerCloudflareClearanceResolvedHandler( - clearanceResolvedHandler - ) - } - if cookieSelfHealingHandler == nil { - cookieSelfHealingHandler = FireCookieSelfHealingRuntimeHandler( - loginCoordinator: loginCoordinator - ) - } - if let cookieSelfHealingHandler { - try? await sessionStore.registerCookieSelfHealingHandler( - cookieSelfHealingHandler - ) - } - } - } diff --git a/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Actions.swift b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Actions.swift new file mode 100644 index 00000000..6f5dbb35 --- /dev/null +++ b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Actions.swift @@ -0,0 +1,160 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireBookmarksViewController { + func contextMenuConfiguration( + for item: FireBookmarksCollectionItem + ) -> UIContextMenuConfiguration? { + guard case let .bookmark(rowID) = item, + let row = bookmarksViewModel.row(for: rowID) + else { + return nil + } + let shareURL = row.fireTopicURL(baseURL: baseURLString) + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in + UIMenu(children: self?.topicMenuActions(row: row, shareURL: shareURL) ?? []) + } + } + + func topicMenuActions( + row: FireTopicRowPresentation, + shareURL: URL + ) -> [UIAction] { + [ + UIAction(title: "打开话题", image: UIImage(systemName: "arrow.up.right")) { [weak self] _ in + self?.presentRoute(.topic( + row: row, + postNumber: row.topic.bookmarkedPostNumber ?? row.topic.lastReadPostNumber + )) + }, + UIAction( + title: row.topic.bookmarkId == nil ? "添加书签" : "编辑书签", + image: UIImage(systemName: row.topic.bookmarkId == nil ? "bookmark" : "bookmark.fill") + ) { [weak self] _ in + self?.presentBookmarkEditor(for: row) + }, + UIAction(title: "分享话题", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in + self?.presentShareSheet(url: shareURL) + }, + UIAction(title: "复制链接", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in + UIPasteboard.general.string = shareURL.absoluteString + self?.showToast("已复制链接", style: .success) + }, + UIAction(title: "静音话题", image: UIImage(systemName: "bell.slash")) { [weak self] _ in + self?.muteTopicFromAction(row) + }, + ] + } + + func presentBookmarkEditor(for row: FireTopicRowPresentation) { + let context = row.fireBookmarkEditorContext() + let recoveryOriginURL = row.fireTopicURL(baseURL: baseURLString) + let rootView = FireBookmarkEditorSheet( + context: context, + onSave: { [weak self] name, reminderAt in + try await self?.saveBookmark( + context: context, + name: name, + reminderAt: reminderAt, + recoveryOriginURL: recoveryOriginURL + ) + }, + onDelete: context.bookmarkID.map { bookmarkID in + { [weak self] in + try await self?.deleteBookmark( + bookmarkID: bookmarkID, + recoveryOriginURL: recoveryOriginURL, + showSuccessToast: false + ) + } + } + ) + let controller = UIHostingController(rootView: rootView) + if let sheet = controller.sheetPresentationController { + sheet.detents = [.medium(), .large()] + sheet.prefersGrabberVisible = true + } + present(controller, animated: true) + } + + func saveBookmark( + context: FireBookmarkEditorContext, + name: String?, + reminderAt: String?, + recoveryOriginURL: URL + ) async throws { + if let bookmarkID = context.bookmarkID { + try await appViewModel.topicInteraction.updateBookmark( + bookmarkID: bookmarkID, + name: name, + reminderAt: reminderAt, + recoveryOriginURL: recoveryOriginURL + ) + } else { + _ = try await appViewModel.topicInteraction.createBookmark( + bookmarkableID: context.bookmarkableID, + bookmarkableType: context.bookmarkableType, + name: name, + reminderAt: reminderAt, + recoveryOriginURL: recoveryOriginURL + ) + } + await bookmarksViewModel.refresh() + } + + func deleteBookmarkFromAction(for row: FireTopicRowPresentation) { + guard let bookmarkID = row.topic.bookmarkId else { return } + let recoveryOriginURL = row.fireTopicURL(baseURL: baseURLString) + loadTask = Task { [weak self] in + do { + try await self?.deleteBookmark( + bookmarkID: bookmarkID, + recoveryOriginURL: recoveryOriginURL, + showSuccessToast: true + ) + } catch { + self?.bookmarksViewModel.reportError(error.localizedDescription) + self?.showToast(error.localizedDescription, style: .error) + } + } + } + + func deleteBookmark( + bookmarkID: UInt64, + recoveryOriginURL: URL, + showSuccessToast: Bool + ) async throws { + try await appViewModel.topicInteraction.deleteBookmark( + bookmarkID: bookmarkID, + recoveryOriginURL: recoveryOriginURL + ) + await bookmarksViewModel.refresh() + if showSuccessToast { + showToast("已删除书签", style: .success) + } + } + + func muteTopicFromAction(_ row: FireTopicRowPresentation) { + loadTask = Task { [weak self] in + do { + try await self?.appViewModel.topicInteraction.setTopicNotificationLevel( + topicID: row.topic.id, + notificationLevel: FireTopicNotificationLevelOption.muted.rawValue, + recoveryOriginURL: row.fireTopicURL(baseURL: self?.baseURLString ?? "https://linux.do") + ) + self?.showToast("已静音话题", style: .success) + } catch { + self?.showToast(error.localizedDescription, style: .error) + } + } + } + + func showToast(_ message: String, style: FireTopicListToastView.Style) { + toastDismissTask?.cancel() + toastView?.removeFromSuperview() + toastView = nil + FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) + } +} diff --git a/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Feed.swift b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Feed.swift new file mode 100644 index 00000000..f12c5afd --- /dev/null +++ b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Feed.swift @@ -0,0 +1,154 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireBookmarksViewController { + var baseURLString: String { + let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? "https://linux.do" : trimmed + } + + var contentVersion: ContentVersion { + ContentVersion( + rows: bookmarksViewModel.rows, + nextPage: bookmarksViewModel.nextPage, + isLoading: bookmarksViewModel.isLoading, + isLoadingMore: bookmarksViewModel.isLoadingMore, + hasLoadedOnce: bookmarksViewModel.hasLoadedOnce, + errorMessage: bookmarksViewModel.errorMessage + ) + } + + func render() { + let sections = makeSections() + var tokens: [FireBookmarksCollectionItem: AnyHashable] = [:] + tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) + for section in sections { + for item in section.items { + tokens[item] = itemContentToken(for: item) + } + } + listController.setSections( + sections, + contentVersion: contentVersion, + itemContentTokens: tokens, + animatingDifferences: true + ) + } + + func makeSections() + -> [FireListSectionModel] + { + var items: [FireBookmarksCollectionItem] = [] + + if let errorMessage = bookmarksViewModel.errorMessage, + bookmarksViewModel.hasLoadedOnce { + items.append(.inlineErrorBanner(errorMessage)) + } + + if !bookmarksViewModel.hasLoadedOnce { + if let errorMessage = bookmarksViewModel.errorMessage { + items.append(.blockingError(errorMessage)) + } else { + items.append(.loading) + } + } else if bookmarksViewModel.rows.isEmpty { + items.append(.empty) + } else { + items.append(contentsOf: bookmarksViewModel.rows.map { + .bookmark(FireBookmarksViewModel.rowID(for: $0)) + }) + + if bookmarksViewModel.isLoadingMore { + items.append(.loadingMore) + } + } + + return [.init(id: .content, items: items)] + } + + func cell( + collectionView: UICollectionView, + indexPath: IndexPath, + item: FireBookmarksCollectionItem + ) -> UICollectionViewCell { + switch item { + case .blockingError, .loading, .empty, .loadingMore: + return collectionView.dequeueConfiguredReusableCell( + using: stateCellRegistration, + for: indexPath, + item: item + ) + case .inlineErrorBanner: + return collectionView.dequeueConfiguredReusableCell( + using: bannerCellRegistration, + for: indexPath, + item: item + ) + case .bookmark: + return collectionView.dequeueConfiguredReusableCell( + using: topicCellRegistration, + for: indexPath, + item: item + ) + } + } + + func itemContentToken(for item: FireBookmarksCollectionItem) -> AnyHashable { + switch item { + case let .blockingError(message), let .inlineErrorBanner(message): + return AnyHashable(message) + case .loading: + return AnyHashable(bookmarksViewModel.isLoading) + case .empty: + return AnyHashable(bookmarksViewModel.hasLoadedOnce) + case let .bookmark(id): + guard let row = bookmarksViewModel.row(for: id) else { + return AnyHashable("missing|\(id.value)") + } + return AnyHashable(bookmarkRowContentToken(row)) + case .loadingMore: + return AnyHashable(bookmarksViewModel.isLoadingMore) + } + } + + func bookmarkRowContentToken(_ row: FireTopicRowPresentation) -> String { + let topic = row.topic + let category = appViewModel.categoryPresentation(for: topic.categoryId) + var parts: [String] = [] + parts.reserveCapacity(31) + parts.append(String(topic.id)) + parts.append(topic.title) + parts.append(topic.slug) + parts.append(String(topic.postsCount)) + parts.append(String(topic.replyCount)) + parts.append(String(topic.views)) + parts.append(String(topic.likeCount)) + parts.append(topic.excerpt ?? "") + parts.append(topic.createdAt ?? "") + parts.append(topic.lastPostedAt ?? "") + parts.append(topic.lastPosterUsername ?? "") + parts.append(topic.categoryId.map(String.init) ?? "") + parts.append(String(topic.pinned)) + parts.append(String(topic.closed)) + parts.append(String(topic.archived)) + parts.append(String(topic.unseen)) + parts.append(String(topic.unreadPosts)) + parts.append(String(topic.newPosts)) + parts.append(topic.lastReadPostNumber.map(String.init) ?? "") + parts.append(String(topic.highestPostNumber)) + parts.append(topic.bookmarkedPostNumber.map(String.init) ?? "") + parts.append(topic.bookmarkId.map(String.init) ?? "") + parts.append(topic.bookmarkName ?? "") + parts.append(topic.bookmarkReminderAt ?? "") + parts.append(topic.bookmarkableType ?? "") + parts.append(row.excerptText ?? "") + parts.append(row.originalPosterUsername ?? "") + parts.append(row.originalPosterAvatarTemplate ?? "") + parts.append(row.tagNames.joined(separator: ",")) + parts.append(row.statusLabels.joined(separator: ",")) + parts.append(category.map { "\($0.id)|\($0.displayName)|\($0.colorHex ?? "")" } ?? "") + return parts.joined(separator: "\u{1F}") + } +} diff --git a/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Pagination.swift b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Pagination.swift new file mode 100644 index 00000000..7f019dd6 --- /dev/null +++ b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Pagination.swift @@ -0,0 +1,18 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireBookmarksViewController { + func handleVisibleItemsChanged(_ items: [FireBookmarksCollectionItem]) { + loadMoreIfNeeded(from: items) + } + + func loadMoreIfNeeded(from items: [FireBookmarksCollectionItem]) { + guard let lastRowID = bookmarksViewModel.lastRowID else { return } + guard items.contains(.bookmark(lastRowID)) || items.contains(.loadingMore) else { return } + loadTask = Task { [weak self] in + await self?.bookmarksViewModel.loadMoreIfNeeded(currentRowID: lastRowID) + } + } +} diff --git a/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Routing.swift b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Routing.swift new file mode 100644 index 00000000..b212ecb4 --- /dev/null +++ b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Routing.swift @@ -0,0 +1,53 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireBookmarksViewController { + func updateTopicRoutePresenter(_ presenter: FireTopicRoutePresenter) { + topicRoutePresenter = presenter + } + + func canSelect(_ item: FireBookmarksCollectionItem) -> Bool { + if case .bookmark = item { + return true + } + return false + } + + func handleSelection(_ item: FireBookmarksCollectionItem) { + guard case let .bookmark(id) = item, + let row = bookmarksViewModel.row(for: id) else { return } + presentRoute(.topic( + row: row, + postNumber: row.topic.bookmarkedPostNumber ?? row.topic.lastReadPostNumber + )) + } + + func presentRoute(_ route: FireAppRoute) { + if topicRoutePresenter.present(route) { + return + } + if route.presentsAsSecondaryPage { + FireAppRouteControllerFactory.presentSecondaryRoute( + route, + viewModel: appViewModel, + topicDetailStore: topicDetailStore + ) + } + } + + func presentShareSheet(url: URL) { + let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) + if let popover = controller.popoverPresentationController { + popover.sourceView = view + popover.sourceRect = CGRect( + x: view.bounds.midX, + y: view.safeAreaInsets.top + 24, + width: 1, + height: 1 + ) + } + present(controller, animated: true) + } +} diff --git a/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Setup.swift b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Setup.swift new file mode 100644 index 00000000..07a53ed0 --- /dev/null +++ b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController+Setup.swift @@ -0,0 +1,48 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireBookmarksViewController { + func configureListController() { + listController.updateCellProvider { [weak self] collectionView, indexPath, item in + guard let self else { + return UICollectionViewCell() + } + return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) + } + listController.updateContextMenuConfigurationProvider { [weak self] item in + self?.contextMenuConfiguration(for: item) + } + } + + func prepareCellRegistrations() { + _ = stateCellRegistration + _ = bannerCellRegistration + _ = topicCellRegistration + } + + func installListController() { + addChild(listController) + view.addSubview(listController.view) + listController.view.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + listController.view.topAnchor.constraint(equalTo: view.topAnchor), + listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + listController.didMove(toParent: self) + } + + func bindViewModel() { + bookmarksViewModel.objectWillChange + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + DispatchQueue.main.async { + self?.render() + } + } + .store(in: &cancellables) + } +} diff --git a/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController.swift b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController.swift index 284603c3..a13c3fcb 100644 --- a/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController.swift +++ b/apps/ios-app/App/Views/Bookmarks/FireBookmarksViewController.swift @@ -3,8 +3,8 @@ import SwiftUI import UIKit struct FireBookmarksControllerHost: UIViewControllerRepresentable { - @Environment(\.fireTopicRoutePresenter) private var topicRoutePresenter - @EnvironmentObject private var topicDetailStore: FireTopicDetailStore + @Environment(\.fireTopicRoutePresenter) var topicRoutePresenter + @EnvironmentObject var topicDetailStore: FireTopicDetailStore let viewModel: FireAppViewModel let username: String @@ -28,7 +28,7 @@ struct FireBookmarksControllerHost: UIViewControllerRepresentable { @MainActor final class FireBookmarksViewController: UIViewController { - private struct ContentVersion: Hashable { + struct ContentVersion: Hashable { let rows: [FireTopicRowPresentation] let nextPage: UInt32? let isLoading: Bool @@ -37,18 +37,18 @@ final class FireBookmarksViewController: UIViewController { let errorMessage: String? } - private let appViewModel: FireAppViewModel - private let topicDetailStore: FireTopicDetailStore - private let bookmarksViewModel: FireBookmarksViewModel - private let controllerReference: FireBookmarksControllerReference - private let listController: FireListViewController - private var topicRoutePresenter: FireTopicRoutePresenter - private var cancellables: Set = [] - private var loadTask: Task? - private var toastDismissTask: Task? - private weak var toastView: UIView? + let appViewModel: FireAppViewModel + let topicDetailStore: FireTopicDetailStore + let bookmarksViewModel: FireBookmarksViewModel + let controllerReference: FireBookmarksControllerReference + let listController: FireListViewController + var topicRoutePresenter: FireTopicRoutePresenter + var cancellables: Set = [] + var loadTask: Task? + var toastDismissTask: Task? + weak var toastView: UIView? - private lazy var stateCellRegistration = UICollectionView.CellRegistration< + lazy var stateCellRegistration = UICollectionView.CellRegistration< FireTopicListStateCell, FireBookmarksCollectionItem > { [weak self] cell, _, item in @@ -71,7 +71,7 @@ final class FireBookmarksViewController: UIViewController { } } - private lazy var bannerCellRegistration = UICollectionView.CellRegistration< + lazy var bannerCellRegistration = UICollectionView.CellRegistration< FireTopicListErrorBannerCell, FireBookmarksCollectionItem > { [weak self] cell, _, item in @@ -87,7 +87,7 @@ final class FireBookmarksViewController: UIViewController { ) } - private lazy var topicCellRegistration = UICollectionView.CellRegistration< + lazy var topicCellRegistration = UICollectionView.CellRegistration< FireTopicListTopicCell, FireBookmarksCollectionItem > { [weak self] cell, _, item in @@ -177,410 +177,8 @@ final class FireBookmarksViewController: UIViewController { } } - func updateTopicRoutePresenter(_ presenter: FireTopicRoutePresenter) { - topicRoutePresenter = presenter - } - - private func configureListController() { - listController.updateCellProvider { [weak self] collectionView, indexPath, item in - guard let self else { - return UICollectionViewCell() - } - return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) - } - listController.updateContextMenuConfigurationProvider { [weak self] item in - self?.contextMenuConfiguration(for: item) - } - } - - private func prepareCellRegistrations() { - _ = stateCellRegistration - _ = bannerCellRegistration - _ = topicCellRegistration - } - - private func installListController() { - addChild(listController) - view.addSubview(listController.view) - listController.view.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), - listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), - listController.view.topAnchor.constraint(equalTo: view.topAnchor), - listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) - listController.didMove(toParent: self) - } - - private func bindViewModel() { - bookmarksViewModel.objectWillChange - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - DispatchQueue.main.async { - self?.render() - } - } - .store(in: &cancellables) - } - - private var baseURLString: String { - let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? "https://linux.do" : trimmed - } - - private var contentVersion: ContentVersion { - ContentVersion( - rows: bookmarksViewModel.rows, - nextPage: bookmarksViewModel.nextPage, - isLoading: bookmarksViewModel.isLoading, - isLoadingMore: bookmarksViewModel.isLoadingMore, - hasLoadedOnce: bookmarksViewModel.hasLoadedOnce, - errorMessage: bookmarksViewModel.errorMessage - ) - } - - private func render() { - let sections = makeSections() - var tokens: [FireBookmarksCollectionItem: AnyHashable] = [:] - tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) - for section in sections { - for item in section.items { - tokens[item] = itemContentToken(for: item) - } - } - listController.setSections( - sections, - contentVersion: contentVersion, - itemContentTokens: tokens, - animatingDifferences: true - ) - } - - private func makeSections() - -> [FireListSectionModel] - { - var items: [FireBookmarksCollectionItem] = [] - - if let errorMessage = bookmarksViewModel.errorMessage, - bookmarksViewModel.hasLoadedOnce { - items.append(.inlineErrorBanner(errorMessage)) - } - - if !bookmarksViewModel.hasLoadedOnce { - if let errorMessage = bookmarksViewModel.errorMessage { - items.append(.blockingError(errorMessage)) - } else { - items.append(.loading) - } - } else if bookmarksViewModel.rows.isEmpty { - items.append(.empty) - } else { - items.append(contentsOf: bookmarksViewModel.rows.map { - .bookmark(FireBookmarksViewModel.rowID(for: $0)) - }) - - if bookmarksViewModel.isLoadingMore { - items.append(.loadingMore) - } - } - - return [.init(id: .content, items: items)] - } - - private func cell( - collectionView: UICollectionView, - indexPath: IndexPath, - item: FireBookmarksCollectionItem - ) -> UICollectionViewCell { - switch item { - case .blockingError, .loading, .empty, .loadingMore: - return collectionView.dequeueConfiguredReusableCell( - using: stateCellRegistration, - for: indexPath, - item: item - ) - case .inlineErrorBanner: - return collectionView.dequeueConfiguredReusableCell( - using: bannerCellRegistration, - for: indexPath, - item: item - ) - case .bookmark: - return collectionView.dequeueConfiguredReusableCell( - using: topicCellRegistration, - for: indexPath, - item: item - ) - } - } - - private func canSelect(_ item: FireBookmarksCollectionItem) -> Bool { - if case .bookmark = item { - return true - } - return false - } - - private func handleSelection(_ item: FireBookmarksCollectionItem) { - guard case let .bookmark(id) = item, - let row = bookmarksViewModel.row(for: id) else { return } - presentRoute(.topic( - row: row, - postNumber: row.topic.bookmarkedPostNumber ?? row.topic.lastReadPostNumber - )) - } - - private func handleVisibleItemsChanged(_ items: [FireBookmarksCollectionItem]) { - loadMoreIfNeeded(from: items) - } - - private func loadMoreIfNeeded(from items: [FireBookmarksCollectionItem]) { - guard let lastRowID = bookmarksViewModel.lastRowID else { return } - guard items.contains(.bookmark(lastRowID)) || items.contains(.loadingMore) else { return } - loadTask = Task { [weak self] in - await self?.bookmarksViewModel.loadMoreIfNeeded(currentRowID: lastRowID) - } - } - - private func contextMenuConfiguration( - for item: FireBookmarksCollectionItem - ) -> UIContextMenuConfiguration? { - guard case let .bookmark(rowID) = item, - let row = bookmarksViewModel.row(for: rowID) - else { - return nil - } - let shareURL = row.fireTopicURL(baseURL: baseURLString) - return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in - UIMenu(children: self?.topicMenuActions(row: row, shareURL: shareURL) ?? []) - } - } - - private func topicMenuActions( - row: FireTopicRowPresentation, - shareURL: URL - ) -> [UIAction] { - [ - UIAction(title: "打开话题", image: UIImage(systemName: "arrow.up.right")) { [weak self] _ in - self?.presentRoute(.topic( - row: row, - postNumber: row.topic.bookmarkedPostNumber ?? row.topic.lastReadPostNumber - )) - }, - UIAction( - title: row.topic.bookmarkId == nil ? "添加书签" : "编辑书签", - image: UIImage(systemName: row.topic.bookmarkId == nil ? "bookmark" : "bookmark.fill") - ) { [weak self] _ in - self?.presentBookmarkEditor(for: row) - }, - UIAction(title: "分享话题", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in - self?.presentShareSheet(url: shareURL) - }, - UIAction(title: "复制链接", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in - UIPasteboard.general.string = shareURL.absoluteString - self?.showToast("已复制链接", style: .success) - }, - UIAction(title: "静音话题", image: UIImage(systemName: "bell.slash")) { [weak self] _ in - self?.muteTopicFromAction(row) - }, - ] - } - - private func itemContentToken(for item: FireBookmarksCollectionItem) -> AnyHashable { - switch item { - case let .blockingError(message), let .inlineErrorBanner(message): - return AnyHashable(message) - case .loading: - return AnyHashable(bookmarksViewModel.isLoading) - case .empty: - return AnyHashable(bookmarksViewModel.hasLoadedOnce) - case let .bookmark(id): - guard let row = bookmarksViewModel.row(for: id) else { - return AnyHashable("missing|\(id.value)") - } - return AnyHashable(bookmarkRowContentToken(row)) - case .loadingMore: - return AnyHashable(bookmarksViewModel.isLoadingMore) - } - } - - private func bookmarkRowContentToken(_ row: FireTopicRowPresentation) -> String { - let topic = row.topic - let category = appViewModel.categoryPresentation(for: topic.categoryId) - var parts: [String] = [] - parts.reserveCapacity(31) - parts.append(String(topic.id)) - parts.append(topic.title) - parts.append(topic.slug) - parts.append(String(topic.postsCount)) - parts.append(String(topic.replyCount)) - parts.append(String(topic.views)) - parts.append(String(topic.likeCount)) - parts.append(topic.excerpt ?? "") - parts.append(topic.createdAt ?? "") - parts.append(topic.lastPostedAt ?? "") - parts.append(topic.lastPosterUsername ?? "") - parts.append(topic.categoryId.map(String.init) ?? "") - parts.append(String(topic.pinned)) - parts.append(String(topic.closed)) - parts.append(String(topic.archived)) - parts.append(String(topic.unseen)) - parts.append(String(topic.unreadPosts)) - parts.append(String(topic.newPosts)) - parts.append(topic.lastReadPostNumber.map(String.init) ?? "") - parts.append(String(topic.highestPostNumber)) - parts.append(topic.bookmarkedPostNumber.map(String.init) ?? "") - parts.append(topic.bookmarkId.map(String.init) ?? "") - parts.append(topic.bookmarkName ?? "") - parts.append(topic.bookmarkReminderAt ?? "") - parts.append(topic.bookmarkableType ?? "") - parts.append(row.excerptText ?? "") - parts.append(row.originalPosterUsername ?? "") - parts.append(row.originalPosterAvatarTemplate ?? "") - parts.append(row.tagNames.joined(separator: ",")) - parts.append(row.statusLabels.joined(separator: ",")) - parts.append(category.map { "\($0.id)|\($0.displayName)|\($0.colorHex ?? "")" } ?? "") - return parts.joined(separator: "\u{1F}") - } - - private func presentRoute(_ route: FireAppRoute) { - if topicRoutePresenter.present(route) { - return - } - if route.presentsAsSecondaryPage { - FireAppRouteControllerFactory.presentSecondaryRoute( - route, - viewModel: appViewModel, - topicDetailStore: topicDetailStore - ) - } - } - - private func presentBookmarkEditor(for row: FireTopicRowPresentation) { - let context = row.fireBookmarkEditorContext() - let recoveryOriginURL = row.fireTopicURL(baseURL: baseURLString) - let rootView = FireBookmarkEditorSheet( - context: context, - onSave: { [weak self] name, reminderAt in - try await self?.saveBookmark( - context: context, - name: name, - reminderAt: reminderAt, - recoveryOriginURL: recoveryOriginURL - ) - }, - onDelete: context.bookmarkID.map { bookmarkID in - { [weak self] in - try await self?.deleteBookmark( - bookmarkID: bookmarkID, - recoveryOriginURL: recoveryOriginURL, - showSuccessToast: false - ) - } - } - ) - let controller = UIHostingController(rootView: rootView) - if let sheet = controller.sheetPresentationController { - sheet.detents = [.medium(), .large()] - sheet.prefersGrabberVisible = true - } - present(controller, animated: true) - } - - private func saveBookmark( - context: FireBookmarkEditorContext, - name: String?, - reminderAt: String?, - recoveryOriginURL: URL - ) async throws { - if let bookmarkID = context.bookmarkID { - try await appViewModel.topicInteraction.updateBookmark( - bookmarkID: bookmarkID, - name: name, - reminderAt: reminderAt, - recoveryOriginURL: recoveryOriginURL - ) - } else { - _ = try await appViewModel.topicInteraction.createBookmark( - bookmarkableID: context.bookmarkableID, - bookmarkableType: context.bookmarkableType, - name: name, - reminderAt: reminderAt, - recoveryOriginURL: recoveryOriginURL - ) - } - await bookmarksViewModel.refresh() - } - - private func deleteBookmarkFromAction(for row: FireTopicRowPresentation) { - guard let bookmarkID = row.topic.bookmarkId else { return } - let recoveryOriginURL = row.fireTopicURL(baseURL: baseURLString) - loadTask = Task { [weak self] in - do { - try await self?.deleteBookmark( - bookmarkID: bookmarkID, - recoveryOriginURL: recoveryOriginURL, - showSuccessToast: true - ) - } catch { - self?.bookmarksViewModel.reportError(error.localizedDescription) - self?.showToast(error.localizedDescription, style: .error) - } - } - } - - private func deleteBookmark( - bookmarkID: UInt64, - recoveryOriginURL: URL, - showSuccessToast: Bool - ) async throws { - try await appViewModel.topicInteraction.deleteBookmark( - bookmarkID: bookmarkID, - recoveryOriginURL: recoveryOriginURL - ) - await bookmarksViewModel.refresh() - if showSuccessToast { - showToast("已删除书签", style: .success) - } - } - - private func muteTopicFromAction(_ row: FireTopicRowPresentation) { - loadTask = Task { [weak self] in - do { - try await self?.appViewModel.topicInteraction.setTopicNotificationLevel( - topicID: row.topic.id, - notificationLevel: FireTopicNotificationLevelOption.muted.rawValue, - recoveryOriginURL: row.fireTopicURL(baseURL: self?.baseURLString ?? "https://linux.do") - ) - self?.showToast("已静音话题", style: .success) - } catch { - self?.showToast(error.localizedDescription, style: .error) - } - } - } - - private func presentShareSheet(url: URL) { - let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) - if let popover = controller.popoverPresentationController { - popover.sourceView = view - popover.sourceRect = CGRect( - x: view.bounds.midX, - y: view.safeAreaInsets.top + 24, - width: 1, - height: 1 - ) - } - present(controller, animated: true) - } - - private func showToast(_ message: String, style: FireTopicListToastView.Style) { - toastDismissTask?.cancel() - toastView?.removeFromSuperview() - toastView = nil - FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) - } } -private final class FireBookmarksControllerReference { +final class FireBookmarksControllerReference { weak var controller: FireBookmarksViewController? } diff --git a/apps/ios-app/App/Views/Chat/FireChatChannelsStore.swift b/apps/ios-app/App/Views/Chat/FireChatChannelsStore.swift index 21b3f300..9e631354 100644 --- a/apps/ios-app/App/Views/Chat/FireChatChannelsStore.swift +++ b/apps/ios-app/App/Views/Chat/FireChatChannelsStore.swift @@ -10,302 +10,60 @@ final class FireChatChannelsStore: ObservableObject { @Published private(set) var isLoading = false @Published private(set) var hasLoadedOnce = false @Published var errorMessage: String? - private var didRefreshFromNetwork = false - private let viewModel: FireAppViewModel - private let ownerToken = "chat-channels-list" - private var loadGeneration: UInt64 = 0 - private var subscribedNewMessageChannels = Set() - private var globalBusLastIDs: [String: Int64] = [:] + private let session: FireChatListSession + private var orderedChannels: [ChatChannelState] = [] + private var badgeByChannelID: [UInt64: UInt32] = [:] init(viewModel: FireAppViewModel) { - self.viewModel = viewModel + let session = FireChatListSession(viewModel: viewModel) + self.session = session + session.onSnapshot = { [weak self] snapshot in + self?.apply(snapshot) + } } var displayedChannels: [ChatChannelState] { - sorted(directMessageChannels + publicChannels) + orderedChannels } func badge(for channel: ChatChannelState) -> UInt32 { - if channel.currentUserMembership?.muted == true { - return 0 - } - let tracking = trackingByChannelID[channel.id] - if channel.isDirectMessage { - return (tracking?.unread ?? 0) &+ (tracking?.mention ?? 0) - } - return tracking?.mention ?? 0 + badgeByChannelID[channel.id] ?? 0 } func loadIfNeeded() async { - if !hasLoadedOnce { - await loadCachedIfAvailable() - } - guard !didRefreshFromNetwork, !isLoading else { return } - await refresh() - } - - func loadCachedIfAvailable() async { - guard let cached = try? await viewModel.cachedMyChatChannels() else { return } - apply(cached) - hasLoadedOnce = true + await session.open() } func refresh() async { - loadGeneration &+= 1 - let generation = loadGeneration - isLoading = true - defer { - if generation == loadGeneration { - isLoading = false - } - } - - didRefreshFromNetwork = true - do { - let response = try await viewModel.fetchMyChatChannels() - guard generation == loadGeneration else { return } - apply(response) - await resubscribeMessageBus(with: response) - errorMessage = nil - hasLoadedOnce = true - } catch { - guard generation == loadGeneration else { return } - if publicChannels.isEmpty && directMessageChannels.isEmpty { - errorMessage = error.localizedDescription - } - hasLoadedOnce = true - } + await session.refresh() } func upsert(_ channel: ChatChannelState) { - if channel.isDirectMessage { - directMessageChannels = upsert(channel, into: directMessageChannels) - } else { - publicChannels = upsert(channel, into: publicChannels) - } - Task { await subscribeNewMessagesIfNeeded(for: channel) } + session.upsert(channel) } func clearTracking(for channelID: UInt64) { - trackingByChannelID[channelID] = (0, 0) - recomputeBadge() - } - - func applyIncomingLastMessage(_ message: ChatMessageState, isSelf: Bool) { - let channelID = message.channelId - if !isSelf { - let old = trackingByChannelID[channelID] ?? (0, 0) - trackingByChannelID[channelID] = (old.unread &+ 1, old.mention) - recomputeBadge() - } - if let index = directMessageChannels.firstIndex(where: { $0.id == channelID }) { - directMessageChannels[index] = withLastMessage(directMessageChannels[index], message) - directMessageChannels = sorted(directMessageChannels) - return - } - if let index = publicChannels.firstIndex(where: { $0.id == channelID }) { - publicChannels[index] = withLastMessage(publicChannels[index], message) - publicChannels = sorted(publicChannels) - } + session.clearTracking(for: channelID) } func handleMessageBusEvent(_ event: MessageBusEventState) { - let channel = event.channel - if channel == "/chat/new-channel" { - handleNewChannel(event) - return - } - if channel.hasPrefix("/chat/user-tracking-state/") { - handleTracking(event) - return - } - if channel.hasSuffix("/new-messages") { - handleNewMessages(event) - } + session.handleMessageBusEvent(event) } func reset() { - loadGeneration &+= 1 - Task { await teardownSubscriptions() } - publicChannels = [] - directMessageChannels = [] - trackingByChannelID = [:] - totalUnreadBadge = 0 - isLoading = false - hasLoadedOnce = false - didRefreshFromNetwork = false - errorMessage = nil - subscribedNewMessageChannels.removeAll() - globalBusLastIDs = [:] - } - - private func handleNewChannel(_ event: MessageBusEventState) { - let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" - guard let channel = FireChatBusPayload.channel(from: event, baseURLString: baseURLString), - channel.isDirectMessage - else { - return - } - upsert(channel) - } - - private func handleTracking(_ event: MessageBusEventState) { - let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" - guard case let .tracking(channelID, unread, mention, threadID) = FireChatBusPayload.event( - from: event, - fallbackChannelID: event.topicId, - baseURLString: baseURLString - ), threadID == nil, channelID > 0 else { - return - } - trackingByChannelID[channelID] = (unread, mention) - recomputeBadge() - } - - private func handleNewMessages(_ event: MessageBusEventState) { - let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" - switch FireChatBusPayload.event( - from: event, - fallbackChannelID: event.topicId, - baseURLString: baseURLString - ) { - case let .newMessages(channelID, isChannelLevel, message, _): - guard isChannelLevel, channelID > 0, let message else { return } - let isSelf = message.user?.id == viewModel.currentUserID - applyIncomingLastMessage(message, isSelf: isSelf) - case let .messageUpsert(message): - let isSelf = message.user?.id == viewModel.currentUserID - applyIncomingLastMessage(message, isSelf: isSelf) - default: - break - } - } - - private func apply(_ response: MyChatChannelsState) { - publicChannels = response.publicChannels - directMessageChannels = response.directMessageChannels - trackingByChannelID = Dictionary( - uniqueKeysWithValues: response.channelTracking.map { - ($0.channelId, (unread: $0.unreadCount, mention: $0.mentionCount)) - } - ) - totalUnreadBadge = Int(response.totalUnreadBadge) - globalBusLastIDs = Dictionary( - uniqueKeysWithValues: response.globalBusLastIds.map { ($0.channel, $0.lastId) } - ) - } - - private func resubscribeMessageBus(with response: MyChatChannelsState) async { - await teardownSubscriptions() - let userID = viewModel.currentUserID - let trackingChannel = userID.map { "/chat/user-tracking-state/\($0)" } - let globalChannels: [(String, Int64?)] = [ - ("/chat/new-channel", globalBusLastIDs["new_channel"]), - ("/chat/channel-edits", globalBusLastIDs["channel_edits"]), - ] + (trackingChannel.map { [($0, globalBusLastIDs["user_tracking_state"])] } ?? []) - - for (channel, lastID) in globalChannels { - try? await viewModel.subscribeMessageBusChannel( - channel: channel, - ownerToken: ownerToken, - lastMessageId: lastID - ) - } - for channel in response.directMessageChannels + response.publicChannels { - await subscribeNewMessagesIfNeeded(for: channel) - } - } - - private func subscribeNewMessagesIfNeeded(for channel: ChatChannelState) async { - guard !subscribedNewMessageChannels.contains(channel.id) else { return } - subscribedNewMessageChannels.insert(channel.id) - try? await viewModel.subscribeMessageBusChannel( - channel: "/chat/\(channel.id)/new-messages", - ownerToken: ownerToken, - lastMessageId: channel.busLastIds.newMessages - ) - } - - private func teardownSubscriptions() async { - let channels = subscribedNewMessageChannels.map { "/chat/\($0)/new-messages" } - + [ - "/chat/new-channel", - "/chat/channel-edits", - ] - + (viewModel.currentUserID.map { ["/chat/user-tracking-state/\($0)"] } ?? []) - for channel in channels { - try? await viewModel.unsubscribeMessageBusChannel(channel: channel, ownerToken: ownerToken) - } - subscribedNewMessageChannels.removeAll() - } - - private func recomputeBadge() { - var sum: UInt32 = 0 - for channel in directMessageChannels where !(channel.currentUserMembership?.muted ?? false) { - let tracking = trackingByChannelID[channel.id] - sum = sum &+ (tracking?.unread ?? 0) &+ (tracking?.mention ?? 0) - } - for channel in publicChannels where !(channel.currentUserMembership?.muted ?? false) { - sum = sum &+ (trackingByChannelID[channel.id]?.mention ?? 0) - } - totalUnreadBadge = Int(sum) - } - - private func sorted(_ channels: [ChatChannelState]) -> [ChatChannelState] { - channels.sorted { lhs, rhs in - let leftStarred = lhs.currentUserMembership?.starred ?? false - let rightStarred = rhs.currentUserMembership?.starred ?? false - if leftStarred != rightStarred { - return leftStarred && !rightStarred - } - let leftTime = lhs.lastMessage?.createdAt ?? "" - let rightTime = rhs.lastMessage?.createdAt ?? "" - if leftTime != rightTime { - return leftTime > rightTime - } - return lhs.id > rhs.id - } - } - - private func upsert( - _ channel: ChatChannelState, - into channels: [ChatChannelState] - ) -> [ChatChannelState] { - var next = channels.filter { $0.id != channel.id } - next.insert(channel, at: 0) - return next - } - - private func withLastMessage(_ channel: ChatChannelState, _ message: ChatMessageState) -> ChatChannelState { - ChatChannelState( - id: channel.id, - title: channel.title, - unicodeTitle: channel.unicodeTitle, - displayTitle: channel.displayTitle, - slug: channel.slug, - description: channel.description, - chatableType: channel.chatableType, - status: channel.status, - threadingEnabled: channel.threadingEnabled, - membershipsCount: channel.membershipsCount, - isGroupDm: channel.isGroupDm, - isDirectMessage: channel.isDirectMessage, - isPublicChannel: channel.isPublicChannel, - dmUsers: channel.dmUsers, - categoryColor: channel.categoryColor, - categoryName: channel.categoryName, - emoji: channel.emoji, - formattedEmoji: channel.formattedEmoji, - currentUserMembership: channel.currentUserMembership, - lastMessage: message, - busLastIds: channel.busLastIds, - canModerate: channel.canModerate, - canManagePins: channel.canManagePins, - canDeleteSelf: channel.canDeleteSelf, - canDeleteOthers: channel.canDeleteOthers, - canRemoveMembers: channel.canRemoveMembers, - canFlag: channel.canFlag - ) + session.close(reset: true) + } + + private func apply(_ snapshot: FireChatListSession.Snapshot) { + publicChannels = snapshot.publicChannels + directMessageChannels = snapshot.directMessageChannels + orderedChannels = snapshot.displayedChannels + badgeByChannelID = snapshot.badgeByChannelID + trackingByChannelID = snapshot.trackingByChannelID + totalUnreadBadge = snapshot.totalUnreadBadge + isLoading = snapshot.isLoading + hasLoadedOnce = snapshot.hasLoadedOnce + errorMessage = snapshot.errorMessage } } diff --git a/apps/ios-app/App/Views/Chat/FireChatListSession.swift b/apps/ios-app/App/Views/Chat/FireChatListSession.swift new file mode 100644 index 00000000..faf55627 --- /dev/null +++ b/apps/ios-app/App/Views/Chat/FireChatListSession.swift @@ -0,0 +1,393 @@ +import Foundation + +@MainActor +final class FireChatListSession { + struct Snapshot { + let publicChannels: [ChatChannelState] + let directMessageChannels: [ChatChannelState] + let displayedChannels: [ChatChannelState] + let badgeByChannelID: [UInt64: UInt32] + let trackingByChannelID: [UInt64: (unread: UInt32, mention: UInt32)] + let totalUnreadBadge: Int + let isLoading: Bool + let hasLoadedOnce: Bool + let errorMessage: String? + } + + var onSnapshot: ((Snapshot) -> Void)? + + private let viewModel: FireAppViewModel + private let ownerToken = "chat-channels-list" + private var publicChannels: [ChatChannelState] = [] + private var directMessageChannels: [ChatChannelState] = [] + private var trackingByChannelID: [UInt64: (unread: UInt32, mention: UInt32)] = [:] + private var totalUnreadBadge = 0 + private var isLoading = false + private var hasLoadedOnce = false + private var errorMessage: String? + private var didRefreshFromNetwork = false + private var loadGeneration: UInt64 = 0 + private var subscribedNewMessageChannels = Set() + private var globalBusLastIDs: [String: Int64] = [:] + + init(viewModel: FireAppViewModel) { + self.viewModel = viewModel + } + + func open() async { + if !hasLoadedOnce { + await loadCachedIfAvailable() + } + guard !didRefreshFromNetwork, !isLoading else { return } + await refresh() + } + + func refresh() async { + loadGeneration &+= 1 + let generation = loadGeneration + isLoading = true + didRefreshFromNetwork = true + emitSnapshot() + defer { + if generation == loadGeneration { + isLoading = false + emitSnapshot() + } + } + + do { + let response = try await viewModel.fetchMyChatChannels() + guard generation == loadGeneration else { return } + apply(response) + await resubscribeMessageBus(with: response, generation: generation) + guard generation == loadGeneration else { return } + errorMessage = nil + hasLoadedOnce = true + emitSnapshot() + } catch { + guard generation == loadGeneration else { return } + if publicChannels.isEmpty && directMessageChannels.isEmpty { + errorMessage = error.localizedDescription + } + hasLoadedOnce = true + emitSnapshot() + } + } + + func upsert(_ channel: ChatChannelState) { + if channel.isDirectMessage { + directMessageChannels = upsert(channel, into: directMessageChannels) + } else { + publicChannels = upsert(channel, into: publicChannels) + } + emitSnapshot() + let generation = loadGeneration + Task { await subscribeNewMessagesIfNeeded(for: channel, generation: generation) } + } + + func clearTracking(for channelID: UInt64) { + trackingByChannelID[channelID] = (0, 0) + recomputeBadge() + emitSnapshot() + } + + func handleMessageBusEvent(_ event: MessageBusEventState) { + let channel = event.channel + if channel == "/chat/new-channel" { + handleNewChannel(event) + } else if channel.hasPrefix("/chat/user-tracking-state/") { + handleTracking(event) + } else if channel.hasSuffix("/new-messages") { + handleNewMessages(event) + } + } + + func close(reset: Bool) { + loadGeneration &+= 1 + let channels = subscriptionChannelNames() + subscribedNewMessageChannels.removeAll() + Task { [viewModel, ownerToken] in + for channel in channels { + try? await viewModel.unsubscribeMessageBusChannel( + channel: channel, + ownerToken: ownerToken + ) + } + } + + guard reset else { return } + publicChannels = [] + directMessageChannels = [] + trackingByChannelID = [:] + totalUnreadBadge = 0 + isLoading = false + hasLoadedOnce = false + didRefreshFromNetwork = false + errorMessage = nil + globalBusLastIDs = [:] + emitSnapshot() + } + + private func loadCachedIfAvailable() async { + guard let cached = try? await viewModel.cachedMyChatChannels() else { return } + apply(cached) + hasLoadedOnce = true + emitSnapshot() + } + + private func handleNewChannel(_ event: MessageBusEventState) { + let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" + guard let channel = FireChatBusPayload.channel(from: event, baseURLString: baseURLString), + channel.isDirectMessage + else { + return + } + upsert(channel) + } + + private func handleTracking(_ event: MessageBusEventState) { + let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" + guard case let .tracking(channelID, unread, mention, threadID) = FireChatBusPayload.event( + from: event, + fallbackChannelID: event.topicId, + baseURLString: baseURLString + ), threadID == nil, channelID > 0 else { + return + } + trackingByChannelID[channelID] = (unread, mention) + recomputeBadge() + emitSnapshot() + } + + private func handleNewMessages(_ event: MessageBusEventState) { + let baseURLString = viewModel.bootstrapBaseURLString() ?? "https://linux.do" + switch FireChatBusPayload.event( + from: event, + fallbackChannelID: event.topicId, + baseURLString: baseURLString + ) { + case let .newMessages(channelID, isChannelLevel, message, _): + guard isChannelLevel, channelID > 0, let message else { return } + applyIncomingLastMessage( + message, + isSelf: message.user?.id == viewModel.currentUserID + ) + case let .messageUpsert(message): + applyIncomingLastMessage( + message, + isSelf: message.user?.id == viewModel.currentUserID + ) + default: + break + } + } + + private func applyIncomingLastMessage(_ message: ChatMessageState, isSelf: Bool) { + let channelID = message.channelId + if !isSelf { + let old = trackingByChannelID[channelID] ?? (0, 0) + trackingByChannelID[channelID] = (old.unread &+ 1, old.mention) + recomputeBadge() + } + if let index = directMessageChannels.firstIndex(where: { $0.id == channelID }) { + directMessageChannels[index] = withLastMessage(directMessageChannels[index], message) + directMessageChannels = sorted(directMessageChannels) + emitSnapshot() + return + } + if let index = publicChannels.firstIndex(where: { $0.id == channelID }) { + publicChannels[index] = withLastMessage(publicChannels[index], message) + publicChannels = sorted(publicChannels) + emitSnapshot() + } + } + + private func apply(_ response: MyChatChannelsState) { + publicChannels = response.publicChannels + directMessageChannels = response.directMessageChannels + trackingByChannelID = Dictionary( + uniqueKeysWithValues: response.channelTracking.map { + ($0.channelId, (unread: $0.unreadCount, mention: $0.mentionCount)) + } + ) + totalUnreadBadge = Int(response.totalUnreadBadge) + globalBusLastIDs = Dictionary( + uniqueKeysWithValues: response.globalBusLastIds.map { ($0.channel, $0.lastId) } + ) + } + + private func resubscribeMessageBus( + with response: MyChatChannelsState, + generation: UInt64 + ) async { + await teardownSubscriptions() + guard generation == loadGeneration else { return } + let trackingChannel = viewModel.currentUserID.map { "/chat/user-tracking-state/\($0)" } + let globalChannels: [(String, Int64?)] = [ + ("/chat/new-channel", globalBusLastIDs["new_channel"]), + ("/chat/channel-edits", globalBusLastIDs["channel_edits"]), + ] + (trackingChannel.map { [($0, globalBusLastIDs["user_tracking_state"])] } ?? []) + + for (channel, lastID) in globalChannels { + try? await viewModel.subscribeMessageBusChannel( + channel: channel, + ownerToken: ownerToken, + lastMessageId: lastID + ) + guard generation == loadGeneration else { + try? await viewModel.unsubscribeMessageBusChannel( + channel: channel, + ownerToken: ownerToken + ) + return + } + } + for channel in response.directMessageChannels + response.publicChannels { + await subscribeNewMessagesIfNeeded(for: channel, generation: generation) + guard generation == loadGeneration else { return } + } + } + + private func subscribeNewMessagesIfNeeded( + for channel: ChatChannelState, + generation: UInt64 + ) async { + guard generation == loadGeneration else { return } + guard !subscribedNewMessageChannels.contains(channel.id) else { return } + subscribedNewMessageChannels.insert(channel.id) + let channelName = "/chat/\(channel.id)/new-messages" + try? await viewModel.subscribeMessageBusChannel( + channel: channelName, + ownerToken: ownerToken, + lastMessageId: channel.busLastIds.newMessages + ) + guard generation == loadGeneration else { + subscribedNewMessageChannels.remove(channel.id) + try? await viewModel.unsubscribeMessageBusChannel( + channel: channelName, + ownerToken: ownerToken + ) + return + } + } + + private func teardownSubscriptions() async { + let channels = subscriptionChannelNames() + for channel in channels { + try? await viewModel.unsubscribeMessageBusChannel(channel: channel, ownerToken: ownerToken) + } + subscribedNewMessageChannels.removeAll() + } + + private func subscriptionChannelNames() -> [String] { + subscribedNewMessageChannels.map { "/chat/\($0)/new-messages" } + + [ + "/chat/new-channel", + "/chat/channel-edits", + ] + + (viewModel.currentUserID.map { ["/chat/user-tracking-state/\($0)"] } ?? []) + } + + private func recomputeBadge() { + var sum: UInt32 = 0 + for channel in directMessageChannels where !(channel.currentUserMembership?.muted ?? false) { + let tracking = trackingByChannelID[channel.id] + sum = sum &+ (tracking?.unread ?? 0) &+ (tracking?.mention ?? 0) + } + for channel in publicChannels where !(channel.currentUserMembership?.muted ?? false) { + sum = sum &+ (trackingByChannelID[channel.id]?.mention ?? 0) + } + totalUnreadBadge = Int(sum) + } + + private func emitSnapshot() { + onSnapshot?( + Snapshot( + publicChannels: publicChannels, + directMessageChannels: directMessageChannels, + displayedChannels: sorted(directMessageChannels + publicChannels), + badgeByChannelID: Dictionary( + uniqueKeysWithValues: (directMessageChannels + publicChannels).map { + ($0.id, badge(for: $0)) + } + ), + trackingByChannelID: trackingByChannelID, + totalUnreadBadge: totalUnreadBadge, + isLoading: isLoading, + hasLoadedOnce: hasLoadedOnce, + errorMessage: errorMessage + ) + ) + } + + private func sorted(_ channels: [ChatChannelState]) -> [ChatChannelState] { + channels.sorted { lhs, rhs in + let leftStarred = lhs.currentUserMembership?.starred ?? false + let rightStarred = rhs.currentUserMembership?.starred ?? false + if leftStarred != rightStarred { + return leftStarred && !rightStarred + } + let leftTime = lhs.lastMessage?.createdAt ?? "" + let rightTime = rhs.lastMessage?.createdAt ?? "" + if leftTime != rightTime { + return leftTime > rightTime + } + return lhs.id > rhs.id + } + } + + private func badge(for channel: ChatChannelState) -> UInt32 { + if channel.currentUserMembership?.muted == true { + return 0 + } + let tracking = trackingByChannelID[channel.id] + if channel.isDirectMessage { + return (tracking?.unread ?? 0) &+ (tracking?.mention ?? 0) + } + return tracking?.mention ?? 0 + } + + private func upsert( + _ channel: ChatChannelState, + into channels: [ChatChannelState] + ) -> [ChatChannelState] { + var next = channels.filter { $0.id != channel.id } + next.insert(channel, at: 0) + return next + } + + private func withLastMessage( + _ channel: ChatChannelState, + _ message: ChatMessageState + ) -> ChatChannelState { + ChatChannelState( + id: channel.id, + title: channel.title, + unicodeTitle: channel.unicodeTitle, + displayTitle: channel.displayTitle, + slug: channel.slug, + description: channel.description, + chatableType: channel.chatableType, + status: channel.status, + threadingEnabled: channel.threadingEnabled, + membershipsCount: channel.membershipsCount, + isGroupDm: channel.isGroupDm, + isDirectMessage: channel.isDirectMessage, + isPublicChannel: channel.isPublicChannel, + dmUsers: channel.dmUsers, + categoryColor: channel.categoryColor, + categoryName: channel.categoryName, + emoji: channel.emoji, + formattedEmoji: channel.formattedEmoji, + currentUserMembership: channel.currentUserMembership, + lastMessage: message, + busLastIds: channel.busLastIds, + canModerate: channel.canModerate, + canManagePins: channel.canManagePins, + canDeleteSelf: channel.canDeleteSelf, + canDeleteOthers: channel.canDeleteOthers, + canRemoveMembers: channel.canRemoveMembers, + canFlag: channel.canFlag + ) + } +} diff --git a/apps/ios-app/App/Views/Drafts/FireDraftState+Presentation.swift b/apps/ios-app/App/Views/Drafts/FireDraftState+Presentation.swift new file mode 100644 index 00000000..cd069440 --- /dev/null +++ b/apps/ios-app/App/Views/Drafts/FireDraftState+Presentation.swift @@ -0,0 +1,104 @@ +import Foundation + +struct FireDraftContentToken: Hashable { + let key: String + let title: String + let excerpt: String? + let kind: String + let updatedAt: String? + let routeID: String? + + init(_ draft: DraftState) { + key = draft.draftKey + title = draft.fireDraftTitle + excerpt = draft.fireDraftExcerpt + kind = draft.fireDraftKindLabel + updatedAt = FireTopicPresentation.compactTimestamp(draft.updatedAt) + routeID = draft.fireComposerRoute()?.id + } +} + +extension DraftState { + func fireComposerRoute() -> FireComposerRoute? { + let key = draftKey + if key == "new_topic" { + return FireComposerRoute(kind: .createTopic) + } + if key == "new_private_message" { + return FireComposerRoute( + kind: .privateMessage( + recipients: data.recipients, + title: data.title + ) + ) + } + guard let topicID = self.topicId else { + return nil + } + let title = title?.ifEmpty("话题 #\(topicID)") ?? "话题 #\(topicID)" + return FireComposerRoute( + kind: .advancedReply( + topicID: topicID, + topicTitle: title, + categoryID: data.categoryId, + replyToPostNumber: data.replyToPostNumber, + replyToUsername: nil, + isPrivateMessage: data.archetypeId == "private_message" + ) + ) + } + + var fireDraftTitle: String { + if draftKey == "new_topic" { + return title?.ifEmpty("未命名新话题") ?? "未命名新话题" + } + if draftKey == "new_private_message" { + return title?.ifEmpty("未命名私信") ?? "未命名私信" + } + return title?.ifEmpty("回复草稿") ?? "回复草稿" + } + + var fireDraftExcerpt: String? { + let excerpt = excerpt?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !excerpt.isEmpty { + return excerpt + } + let reply = data.reply?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return reply.isEmpty ? nil : reply + } + + var fireDraftKindLabel: String { + if draftKey == "new_topic" { + return "新话题" + } + if draftKey == "new_private_message" || data.archetypeId == "private_message" { + return "私信" + } + return "完整回复" + } + + var fireDraftIcon: String { + switch fireDraftKindLabel { + case "新话题": + return "square.and.pencil" + case "私信": + return "paperplane" + default: + return "arrowshape.turn.up.left" + } + } + + func fireDraftAccessibilityLabel(supported: Bool) -> String { + var parts = [fireDraftTitle, fireDraftKindLabel] + if let excerpt = fireDraftExcerpt { + parts.append(excerpt) + } + if let updatedAt = FireTopicPresentation.compactTimestamp(updatedAt) { + parts.append(updatedAt) + } + if !supported { + parts.append("暂不支持") + } + return parts.joined(separator: ",") + } +} diff --git a/apps/ios-app/App/Views/Drafts/FireDraftsViewController+ComposerRouting.swift b/apps/ios-app/App/Views/Drafts/FireDraftsViewController+ComposerRouting.swift new file mode 100644 index 00000000..e79ac6dc --- /dev/null +++ b/apps/ios-app/App/Views/Drafts/FireDraftsViewController+ComposerRouting.swift @@ -0,0 +1,102 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireDraftsViewController { + func canSelect(_ item: FireDraftsCollectionItem) -> Bool { + guard case let .draft(key) = item, + let draft = draft(key: key) + else { + return false + } + return draft.fireComposerRoute() != nil + } + + func handleSelection(_ item: FireDraftsCollectionItem) { + guard case let .draft(key) = item, + let draft = draft(key: key) + else { + return + } + open(draft) + } + + func contextMenuConfiguration(for item: FireDraftsCollectionItem) -> UIContextMenuConfiguration? { + guard case let .draft(key) = item, + let draft = draft(key: key) + else { + return nil + } + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in + UIMenu(children: self?.draftMenuActions(draft) ?? []) + } + } + + func draftMenuActions(_ draft: DraftState) -> [UIAction] { + var actions: [UIAction] = [] + if draft.fireComposerRoute() != nil { + actions.append( + UIAction(title: "继续编辑", image: UIImage(systemName: "square.and.pencil")) { [weak self] _ in + self?.open(draft) + } + ) + } + actions.append( + UIAction( + title: "删除", + image: UIImage(systemName: "trash"), + attributes: .destructive + ) { [weak self] _ in + self?.delete(draft) + } + ) + return actions + } + + func open(_ draft: DraftState) { + guard let route = draft.fireComposerRoute() else { + showToast("当前草稿类型暂不支持继续编辑", style: .error) + return + } + + let composer = FireComposerViewController( + viewModel: appViewModel, + route: route, + onTopicCreated: { [weak self] _ in + self?.refreshAfterComposerMutation() + }, + onReplySubmitted: { [weak self] in + self?.refreshAfterComposerMutation() + }, + onPrivateMessageCreated: { [weak self] _, _ in + self?.refreshAfterComposerMutation() + }, + onSubmissionNotice: { [weak self] message in + self?.showToast(message, style: .success) + } + ) + let navigationController = UINavigationController(rootViewController: composer) + navigationController.modalPresentationStyle = .fullScreen + present(navigationController, animated: true) + } + + func refreshAfterComposerMutation() { + loadTask = Task { [weak self] in + await self?.draftsViewModel.refresh() + } + } + + func delete(_ draft: DraftState) { + loadTask = Task { [weak self] in + await self?.draftsViewModel.deleteDraft(draft) + } + } + + func showToast(_ message: String, style: FireTopicListToastView.Style) { + toastDismissTask?.cancel() + toastView?.removeFromSuperview() + toastView = nil + FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) + } +} diff --git a/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Feed.swift b/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Feed.swift new file mode 100644 index 00000000..296ef3ae --- /dev/null +++ b/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Feed.swift @@ -0,0 +1,111 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireDraftsViewController { + var contentVersion: ContentVersion { + ContentVersion( + drafts: draftsViewModel.drafts.map(FireDraftContentToken.init), + hasMore: draftsViewModel.hasMore, + isLoading: draftsViewModel.isLoading, + isLoadingMore: draftsViewModel.isLoadingMore, + hasLoadedOnce: draftsViewModel.hasLoadedOnce, + errorMessage: draftsViewModel.errorMessage + ) + } + + func render() { + let sections = makeSections() + var tokens: [FireDraftsCollectionItem: AnyHashable] = [:] + tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) + for section in sections { + for item in section.items { + tokens[item] = itemContentToken(for: item) + } + } + listController.setSections( + sections, + contentVersion: contentVersion, + itemContentTokens: tokens, + animatingDifferences: true + ) + } + + func makeSections() -> [FireListSectionModel] { + var items: [FireDraftsCollectionItem] = [] + + if !draftsViewModel.hasLoadedOnce { + if let errorMessage = draftsViewModel.errorMessage { + items.append(.blockingError(errorMessage)) + } else { + items.append(.loading) + } + return [.init(id: .content, items: items)] + } + + if let errorMessage = draftsViewModel.errorMessage { + items.append(.inlineErrorBanner(errorMessage)) + } + + if draftsViewModel.drafts.isEmpty { + items.append(.empty) + } else { + items.append(contentsOf: draftsViewModel.drafts.map { .draft($0.draftKey) }) + if draftsViewModel.isLoadingMore { + items.append(.loadingMore) + } + } + + return [.init(id: .content, items: items)] + } + + func cell( + collectionView: UICollectionView, + indexPath: IndexPath, + item: FireDraftsCollectionItem + ) -> UICollectionViewCell { + switch item { + case .blockingError, .loading, .empty, .loadingMore: + return collectionView.dequeueConfiguredReusableCell( + using: stateCellRegistration, + for: indexPath, + item: item + ) + case .inlineErrorBanner: + return collectionView.dequeueConfiguredReusableCell( + using: bannerCellRegistration, + for: indexPath, + item: item + ) + case .draft: + return collectionView.dequeueConfiguredReusableCell( + using: draftCellRegistration, + for: indexPath, + item: item + ) + } + } + + func draft(key: String) -> DraftState? { + draftsViewModel.drafts.first { $0.draftKey == key } + } + + func itemContentToken(for item: FireDraftsCollectionItem) -> AnyHashable { + switch item { + case let .blockingError(message), let .inlineErrorBanner(message): + return AnyHashable(message) + case .loading: + return AnyHashable(draftsViewModel.isLoading) + case .empty: + return AnyHashable(draftsViewModel.hasLoadedOnce) + case let .draft(key): + guard let draft = draft(key: key) else { + return AnyHashable("missing|\(key)") + } + return AnyHashable(FireDraftContentToken(draft)) + case .loadingMore: + return AnyHashable(draftsViewModel.isLoadingMore) + } + } +} diff --git a/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Pagination.swift b/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Pagination.swift new file mode 100644 index 00000000..2d8aafd2 --- /dev/null +++ b/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Pagination.swift @@ -0,0 +1,14 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireDraftsViewController { + func loadMoreIfNeeded(from items: [FireDraftsCollectionItem]) { + guard let lastDraftKey = draftsViewModel.drafts.last?.draftKey else { return } + guard items.contains(.draft(lastDraftKey)) || items.contains(.loadingMore) else { return } + loadTask = Task { [weak self] in + await self?.draftsViewModel.loadMoreIfNeeded(currentDraftKey: lastDraftKey) + } + } +} diff --git a/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Setup.swift b/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Setup.swift new file mode 100644 index 00000000..5c0fb7e8 --- /dev/null +++ b/apps/ios-app/App/Views/Drafts/FireDraftsViewController+Setup.swift @@ -0,0 +1,48 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireDraftsViewController { + func configureListController() { + listController.updateCellProvider { [weak self] collectionView, indexPath, item in + guard let self else { + return UICollectionViewCell() + } + return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) + } + listController.updateContextMenuConfigurationProvider { [weak self] item in + self?.contextMenuConfiguration(for: item) + } + } + + func prepareCellRegistrations() { + _ = stateCellRegistration + _ = bannerCellRegistration + _ = draftCellRegistration + } + + func installListController() { + addChild(listController) + view.addSubview(listController.view) + listController.view.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + listController.view.topAnchor.constraint(equalTo: view.topAnchor), + listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + listController.didMove(toParent: self) + } + + func bindViewModel() { + draftsViewModel.objectWillChange + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + DispatchQueue.main.async { + self?.render() + } + } + .store(in: &cancellables) + } +} diff --git a/apps/ios-app/App/Views/Drafts/FireDraftsViewController.swift b/apps/ios-app/App/Views/Drafts/FireDraftsViewController.swift index a9fc7850..e567c544 100644 --- a/apps/ios-app/App/Views/Drafts/FireDraftsViewController.swift +++ b/apps/ios-app/App/Views/Drafts/FireDraftsViewController.swift @@ -17,7 +17,7 @@ enum FireDraftsCollectionItem: Hashable { @MainActor final class FireDraftsViewController: UIViewController { - private struct ContentVersion: Hashable { + struct ContentVersion: Hashable { let drafts: [FireDraftContentToken] let hasMore: Bool let isLoading: Bool @@ -26,16 +26,16 @@ final class FireDraftsViewController: UIViewController { let errorMessage: String? } - private let appViewModel: FireAppViewModel - private let draftsViewModel: FireDraftsViewModel - private let controllerReference: FireDraftsControllerReference - private let listController: FireListViewController - private var cancellables: Set = [] - private var loadTask: Task? - private var toastDismissTask: Task? - private weak var toastView: UIView? + let appViewModel: FireAppViewModel + let draftsViewModel: FireDraftsViewModel + let controllerReference: FireDraftsControllerReference + let listController: FireListViewController + var cancellables: Set = [] + var loadTask: Task? + var toastDismissTask: Task? + weak var toastView: UIView? - private lazy var stateCellRegistration = UICollectionView.CellRegistration< + lazy var stateCellRegistration = UICollectionView.CellRegistration< FireTopicListStateCell, FireDraftsCollectionItem > { [weak self] cell, _, item in @@ -61,7 +61,7 @@ final class FireDraftsViewController: UIViewController { } } - private lazy var bannerCellRegistration = UICollectionView.CellRegistration< + lazy var bannerCellRegistration = UICollectionView.CellRegistration< FireTopicListErrorBannerCell, FireDraftsCollectionItem > { [weak self] cell, _, item in @@ -77,7 +77,7 @@ final class FireDraftsViewController: UIViewController { ) } - private lazy var draftCellRegistration = UICollectionView.CellRegistration< + lazy var draftCellRegistration = UICollectionView.CellRegistration< FireDraftListCell, FireDraftsCollectionItem > { [weak self] cell, _, item in @@ -159,362 +159,8 @@ final class FireDraftsViewController: UIViewController { } } - private func configureListController() { - listController.updateCellProvider { [weak self] collectionView, indexPath, item in - guard let self else { - return UICollectionViewCell() - } - return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) - } - listController.updateContextMenuConfigurationProvider { [weak self] item in - self?.contextMenuConfiguration(for: item) - } - } - - private func prepareCellRegistrations() { - _ = stateCellRegistration - _ = bannerCellRegistration - _ = draftCellRegistration - } - - private func installListController() { - addChild(listController) - view.addSubview(listController.view) - listController.view.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), - listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), - listController.view.topAnchor.constraint(equalTo: view.topAnchor), - listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) - listController.didMove(toParent: self) - } - - private func bindViewModel() { - draftsViewModel.objectWillChange - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - DispatchQueue.main.async { - self?.render() - } - } - .store(in: &cancellables) - } - - private var contentVersion: ContentVersion { - ContentVersion( - drafts: draftsViewModel.drafts.map(FireDraftContentToken.init), - hasMore: draftsViewModel.hasMore, - isLoading: draftsViewModel.isLoading, - isLoadingMore: draftsViewModel.isLoadingMore, - hasLoadedOnce: draftsViewModel.hasLoadedOnce, - errorMessage: draftsViewModel.errorMessage - ) - } - - private func render() { - let sections = makeSections() - var tokens: [FireDraftsCollectionItem: AnyHashable] = [:] - tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) - for section in sections { - for item in section.items { - tokens[item] = itemContentToken(for: item) - } - } - listController.setSections( - sections, - contentVersion: contentVersion, - itemContentTokens: tokens, - animatingDifferences: true - ) - } - - private func makeSections() -> [FireListSectionModel] { - var items: [FireDraftsCollectionItem] = [] - - if !draftsViewModel.hasLoadedOnce { - if let errorMessage = draftsViewModel.errorMessage { - items.append(.blockingError(errorMessage)) - } else { - items.append(.loading) - } - return [.init(id: .content, items: items)] - } - - if let errorMessage = draftsViewModel.errorMessage { - items.append(.inlineErrorBanner(errorMessage)) - } - - if draftsViewModel.drafts.isEmpty { - items.append(.empty) - } else { - items.append(contentsOf: draftsViewModel.drafts.map { .draft($0.draftKey) }) - if draftsViewModel.isLoadingMore { - items.append(.loadingMore) - } - } - - return [.init(id: .content, items: items)] - } - - private func cell( - collectionView: UICollectionView, - indexPath: IndexPath, - item: FireDraftsCollectionItem - ) -> UICollectionViewCell { - switch item { - case .blockingError, .loading, .empty, .loadingMore: - return collectionView.dequeueConfiguredReusableCell( - using: stateCellRegistration, - for: indexPath, - item: item - ) - case .inlineErrorBanner: - return collectionView.dequeueConfiguredReusableCell( - using: bannerCellRegistration, - for: indexPath, - item: item - ) - case .draft: - return collectionView.dequeueConfiguredReusableCell( - using: draftCellRegistration, - for: indexPath, - item: item - ) - } - } - - private func canSelect(_ item: FireDraftsCollectionItem) -> Bool { - guard case let .draft(key) = item, - let draft = draft(key: key) - else { - return false - } - return draft.fireComposerRoute() != nil - } - - private func handleSelection(_ item: FireDraftsCollectionItem) { - guard case let .draft(key) = item, - let draft = draft(key: key) - else { - return - } - open(draft) - } - - private func loadMoreIfNeeded(from items: [FireDraftsCollectionItem]) { - guard let lastDraftKey = draftsViewModel.drafts.last?.draftKey else { return } - guard items.contains(.draft(lastDraftKey)) || items.contains(.loadingMore) else { return } - loadTask = Task { [weak self] in - await self?.draftsViewModel.loadMoreIfNeeded(currentDraftKey: lastDraftKey) - } - } - - private func draft(key: String) -> DraftState? { - draftsViewModel.drafts.first { $0.draftKey == key } - } - - private func itemContentToken(for item: FireDraftsCollectionItem) -> AnyHashable { - switch item { - case let .blockingError(message), let .inlineErrorBanner(message): - return AnyHashable(message) - case .loading: - return AnyHashable(draftsViewModel.isLoading) - case .empty: - return AnyHashable(draftsViewModel.hasLoadedOnce) - case let .draft(key): - guard let draft = draft(key: key) else { - return AnyHashable("missing|\(key)") - } - return AnyHashable(FireDraftContentToken(draft)) - case .loadingMore: - return AnyHashable(draftsViewModel.isLoadingMore) - } - } - - private func contextMenuConfiguration(for item: FireDraftsCollectionItem) -> UIContextMenuConfiguration? { - guard case let .draft(key) = item, - let draft = draft(key: key) - else { - return nil - } - return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in - UIMenu(children: self?.draftMenuActions(draft) ?? []) - } - } - - private func draftMenuActions(_ draft: DraftState) -> [UIAction] { - var actions: [UIAction] = [] - if draft.fireComposerRoute() != nil { - actions.append( - UIAction(title: "继续编辑", image: UIImage(systemName: "square.and.pencil")) { [weak self] _ in - self?.open(draft) - } - ) - } - actions.append( - UIAction( - title: "删除", - image: UIImage(systemName: "trash"), - attributes: .destructive - ) { [weak self] _ in - self?.delete(draft) - } - ) - return actions - } - - private func open(_ draft: DraftState) { - guard let route = draft.fireComposerRoute() else { - showToast("当前草稿类型暂不支持继续编辑", style: .error) - return - } - - let composer = FireComposerViewController( - viewModel: appViewModel, - route: route, - onTopicCreated: { [weak self] _ in - self?.refreshAfterComposerMutation() - }, - onReplySubmitted: { [weak self] in - self?.refreshAfterComposerMutation() - }, - onPrivateMessageCreated: { [weak self] _, _ in - self?.refreshAfterComposerMutation() - }, - onSubmissionNotice: { [weak self] message in - self?.showToast(message, style: .success) - } - ) - let navigationController = UINavigationController(rootViewController: composer) - navigationController.modalPresentationStyle = .fullScreen - present(navigationController, animated: true) - } - - private func refreshAfterComposerMutation() { - loadTask = Task { [weak self] in - await self?.draftsViewModel.refresh() - } - } - - private func delete(_ draft: DraftState) { - loadTask = Task { [weak self] in - await self?.draftsViewModel.deleteDraft(draft) - } - } - - private func showToast(_ message: String, style: FireTopicListToastView.Style) { - toastDismissTask?.cancel() - toastView?.removeFromSuperview() - toastView = nil - FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) - } - -} - -struct FireDraftContentToken: Hashable { - let key: String - let title: String - let excerpt: String? - let kind: String - let updatedAt: String? - let routeID: String? - - init(_ draft: DraftState) { - key = draft.draftKey - title = draft.fireDraftTitle - excerpt = draft.fireDraftExcerpt - kind = draft.fireDraftKindLabel - updatedAt = FireTopicPresentation.compactTimestamp(draft.updatedAt) - routeID = draft.fireComposerRoute()?.id - } } final class FireDraftsControllerReference { weak var controller: FireDraftsViewController? } - -extension DraftState { - func fireComposerRoute() -> FireComposerRoute? { - let key = draftKey - if key == "new_topic" { - return FireComposerRoute(kind: .createTopic) - } - if key == "new_private_message" { - return FireComposerRoute( - kind: .privateMessage( - recipients: data.recipients, - title: data.title - ) - ) - } - guard let topicID = self.topicId else { - return nil - } - let title = title?.ifEmpty("话题 #\(topicID)") ?? "话题 #\(topicID)" - return FireComposerRoute( - kind: .advancedReply( - topicID: topicID, - topicTitle: title, - categoryID: data.categoryId, - replyToPostNumber: data.replyToPostNumber, - replyToUsername: nil, - isPrivateMessage: data.archetypeId == "private_message" - ) - ) - } - - var fireDraftTitle: String { - if draftKey == "new_topic" { - return title?.ifEmpty("未命名新话题") ?? "未命名新话题" - } - if draftKey == "new_private_message" { - return title?.ifEmpty("未命名私信") ?? "未命名私信" - } - return title?.ifEmpty("回复草稿") ?? "回复草稿" - } - - var fireDraftExcerpt: String? { - let excerpt = excerpt?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - if !excerpt.isEmpty { - return excerpt - } - let reply = data.reply?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - return reply.isEmpty ? nil : reply - } - - var fireDraftKindLabel: String { - if draftKey == "new_topic" { - return "新话题" - } - if draftKey == "new_private_message" || data.archetypeId == "private_message" { - return "私信" - } - return "完整回复" - } - - var fireDraftIcon: String { - switch fireDraftKindLabel { - case "新话题": - return "square.and.pencil" - case "私信": - return "paperplane" - default: - return "arrowshape.turn.up.left" - } - } - - func fireDraftAccessibilityLabel(supported: Bool) -> String { - var parts = [fireDraftTitle, fireDraftKindLabel] - if let excerpt = fireDraftExcerpt { - parts.append(excerpt) - } - if let updatedAt = FireTopicPresentation.compactTimestamp(updatedAt) { - parts.append(updatedAt) - } - if !supported { - parts.append("暂不支持") - } - return parts.joined(separator: ",") - } -} diff --git a/apps/ios-app/App/Views/Home/FireFilteredFeedSelectorCell.swift b/apps/ios-app/App/Views/Home/FireFilteredFeedSelectorCell.swift new file mode 100644 index 00000000..0c4c95ea --- /dev/null +++ b/apps/ios-app/App/Views/Home/FireFilteredFeedSelectorCell.swift @@ -0,0 +1,70 @@ +import UIKit + +final class FireFilteredFeedSelectorCell: UICollectionViewCell { + private let scrollView = UIScrollView() + private let stackView = UIStackView() + + override init(frame: CGRect) { + super.init(frame: frame) + configureSubviews() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func prepareForReuse() { + super.prepareForReuse() + stackView.arrangedSubviews.forEach { + stackView.removeArrangedSubview($0) + $0.removeFromSuperview() + } + } + + func configure( + selectedKind: TopicListKindState, + onSelectKind: @escaping (TopicListKindState) -> Void + ) { + prepareForReuse() + for kind in TopicListKindState.orderedCases { + var configuration = UIButton.Configuration.filled() + configuration.title = kind.title + configuration.cornerStyle = .capsule + configuration.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 12, bottom: 6, trailing: 12) + let selected = selectedKind == kind + configuration.baseBackgroundColor = selected ? FireTheme.uiAccent : .tertiarySystemFill + configuration.baseForegroundColor = selected ? .white : .label + let button = UIButton(configuration: configuration) + button.addAction(UIAction { _ in + FireMotionHaptics.selection() + onSelectKind(kind) + }, for: .touchUpInside) + button.fireBindPressBounce(.compact) + stackView.addArrangedSubview(button) + } + } + + private func configureSubviews() { + backgroundConfiguration = .clear() + contentView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 16) + scrollView.showsHorizontalScrollIndicator = false + scrollView.translatesAutoresizingMaskIntoConstraints = false + stackView.axis = .horizontal + stackView.spacing = 6 + stackView.translatesAutoresizingMaskIntoConstraints = false + contentView.addSubview(scrollView) + scrollView.addSubview(stackView) + NSLayoutConstraint.activate([ + scrollView.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), + scrollView.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor), + scrollView.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor), + scrollView.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor), + stackView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor), + stackView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor), + stackView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor), + stackView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor), + stackView.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor), + ]) + } +} diff --git a/apps/ios-app/App/Views/Home/FireFilteredTopicListControllerHost.swift b/apps/ios-app/App/Views/Home/FireFilteredTopicListControllerHost.swift new file mode 100644 index 00000000..7f066c8b --- /dev/null +++ b/apps/ios-app/App/Views/Home/FireFilteredTopicListControllerHost.swift @@ -0,0 +1,35 @@ +import Combine +import SwiftUI +import UIKit + +struct FireFilteredTopicListControllerHost: UIViewControllerRepresentable { + @Environment(\.fireTopicRoutePresenter) private var topicRoutePresenter + @EnvironmentObject private var topicDetailStore: FireTopicDetailStore + + let viewModel: FireAppViewModel + let title: String + let categorySlug: String? + let categoryId: UInt64? + let parentCategorySlug: String? + let tag: String? + + func makeUIViewController(context: Context) -> FireFilteredTopicListViewController { + FireFilteredTopicListViewController( + viewModel: viewModel, + topicDetailStore: topicDetailStore, + title: title, + categorySlug: categorySlug, + categoryId: categoryId, + parentCategorySlug: parentCategorySlug, + tag: tag, + topicRoutePresenter: topicRoutePresenter + ) + } + + func updateUIViewController( + _ uiViewController: FireFilteredTopicListViewController, + context: Context + ) { + uiViewController.updateTopicRoutePresenter(topicRoutePresenter) + } +} diff --git a/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Actions.swift b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Actions.swift new file mode 100644 index 00000000..731f56e4 --- /dev/null +++ b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Actions.swift @@ -0,0 +1,108 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireFilteredTopicListViewController { + func contextMenuConfiguration( + for item: FireFilteredTopicItem + ) -> UIContextMenuConfiguration? { + guard case let .topic(id) = item, + let row = listViewModel.displayedRows.first(where: { $0.topic.id == id }) + else { return nil } + let shareURL = row.fireTopicURL(baseURL: baseURLString) + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in + UIMenu(children: [ + UIAction(title: "打开话题", image: UIImage(systemName: "arrow.up.right")) { _ in + self?.presentRoute(.topic(row: row)) + }, + UIAction( + title: row.topic.bookmarkId == nil ? "添加书签" : "编辑书签", + image: UIImage(systemName: row.topic.bookmarkId == nil ? "bookmark" : "bookmark.fill") + ) { _ in + self?.presentBookmarkEditor(for: row) + }, + UIAction(title: "分享话题", image: UIImage(systemName: "square.and.arrow.up")) { _ in + self?.presentShareSheet(url: shareURL) + }, + UIAction(title: "复制链接", image: UIImage(systemName: "doc.on.doc")) { _ in + UIPasteboard.general.string = shareURL.absoluteString + self?.showToast("已复制链接", style: .success) + }, + UIAction(title: "静音话题", image: UIImage(systemName: "bell.slash")) { _ in + self?.muteTopic(row) + }, + ]) + } + } + + func presentBookmarkEditor(for row: FireTopicRowPresentation) { + let context = row.fireBookmarkEditorContext() + let sheet = FireBookmarkEditorSheet( + context: context, + onSave: { [weak self] name, reminderAt in + guard let self else { return } + if let bookmarkID = context.bookmarkID { + try await self.appViewModel.topicInteraction.updateBookmark( + bookmarkID: bookmarkID, + name: name, + reminderAt: reminderAt + ) + } else { + _ = try await self.appViewModel.topicInteraction.createBookmark( + bookmarkableID: context.bookmarkableID, + bookmarkableType: context.bookmarkableType, + name: name, + reminderAt: reminderAt + ) + } + await self.listViewModel.refresh() + }, + onDelete: context.bookmarkID.map { bookmarkID in + { [weak self] in + try await self?.appViewModel.topicInteraction.deleteBookmark(bookmarkID: bookmarkID) + await self?.listViewModel.refresh() + } + } + ) + let host = UIHostingController(rootView: sheet) + if let sheetController = host.sheetPresentationController { + sheetController.detents = [.medium(), .large()] + sheetController.prefersGrabberVisible = true + } + present(host, animated: true) + } + + func deleteBookmark(for row: FireTopicRowPresentation) { + guard let bookmarkID = row.topic.bookmarkId else { return } + loadTask = Task { [weak self] in + guard let self else { return } + do { + try await appViewModel.topicInteraction.deleteBookmark(bookmarkID: bookmarkID) + await listViewModel.refresh() + showToast("已删除书签", style: .success) + } catch { + showToast(error.localizedDescription, style: .error) + } + } + } + + func muteTopic(_ row: FireTopicRowPresentation) { + loadTask = Task { [weak self] in + guard let self else { return } + do { + try await appViewModel.topicInteraction.setTopicNotificationLevel( + topicID: row.topic.id, + notificationLevel: FireTopicNotificationLevelOption.muted.rawValue + ) + showToast("已静音话题", style: .success) + } catch { + showToast(error.localizedDescription, style: .error) + } + } + } + + func showToast(_ message: String, style: FireUIKitToast.Style) { + FireUIKitToast.show(message, style: style, in: view) + } +} diff --git a/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Feed.swift b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Feed.swift new file mode 100644 index 00000000..574ab665 --- /dev/null +++ b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Feed.swift @@ -0,0 +1,130 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireFilteredTopicListViewController { + var baseURLString: String { + let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? "https://linux.do" : trimmed + } + + var contentVersion: ContentVersion { + ContentVersion( + selectedKind: listViewModel.selectedKind, + rows: listViewModel.displayedRows.map(\.topic.id), + nextPage: listViewModel.currentKindNextPage, + isLoading: listViewModel.isLoading, + isLoadingMore: listViewModel.isLoadingMore, + hasResolved: listViewModel.hasResolvedCurrentKind, + errorMessage: listViewModel.errorMessage, + displayState: listViewModel.currentKindDisplayState + ) + } + + func render() { + let sections = makeSections() + var tokens: [FireFilteredTopicItem: AnyHashable] = [:] + for section in sections { + for item in section.items { + tokens[item] = itemContentToken(for: item) + } + } + listController.setSections( + sections, + contentVersion: contentVersion, + itemContentTokens: tokens, + animatingDifferences: true + ) + } + + func makeSections() + -> [FireListSectionModel] + { + var sections: [FireListSectionModel] = [ + .init(id: .feedSelector, items: [.feedSelector]), + ] + + var items: [FireFilteredTopicItem] = [] + switch listViewModel.currentKindDisplayState { + case .loading: + items.append(contentsOf: (0..<6).map { .loadingSkeleton($0) }) + case let .blockingError(message): + items.append(.blockingError(message)) + case let .empty(nonBlocking): + if let nonBlocking { + items.append(.inlineErrorBanner(nonBlocking)) + } + items.append(.empty) + case let .content(nonBlocking): + if let nonBlocking { + items.append(.inlineErrorBanner(nonBlocking)) + } + items.append(contentsOf: listViewModel.displayedRows.map { .topic($0.topic.id) }) + if listViewModel.currentKindNextPage != nil { + items.append(.loadingMore) + } + } + sections.append(.init(id: .content, items: items)) + return sections + } + + func itemContentToken(for item: FireFilteredTopicItem) -> AnyHashable { + switch item { + case .feedSelector: + return listViewModel.selectedKind + case let .blockingError(message), let .inlineErrorBanner(message): + return message + case let .loadingSkeleton(index): + return index + case .empty: + return "empty" + case let .topic(id): + if let row = listViewModel.displayedRows.first(where: { $0.topic.id == id }) { + return "\(id)-\(row.topic.likeCount)-\(row.topic.replyCount)-\(row.topic.bookmarkId ?? 0)" + } + return id + case .loadingMore: + return listViewModel.isLoadingMore + } + } + + func cell( + collectionView: UICollectionView, + indexPath: IndexPath, + item: FireFilteredTopicItem + ) -> UICollectionViewCell { + switch item { + case .feedSelector: + return collectionView.dequeueConfiguredReusableCell( + using: feedSelectorCellRegistration, + for: indexPath, + item: item + ) + case .blockingError, .empty, .loadingMore: + return collectionView.dequeueConfiguredReusableCell( + using: stateCellRegistration, + for: indexPath, + item: item + ) + case .loadingSkeleton: + return collectionView.dequeueConfiguredReusableCell( + using: skeletonCellRegistration, + for: indexPath, + item: item + ) + case .inlineErrorBanner: + return collectionView.dequeueConfiguredReusableCell( + using: bannerCellRegistration, + for: indexPath, + item: item + ) + case .topic: + return collectionView.dequeueConfiguredReusableCell( + using: topicCellRegistration, + for: indexPath, + item: item + ) + } + } +} diff --git a/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Pagination.swift b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Pagination.swift new file mode 100644 index 00000000..5e2c1584 --- /dev/null +++ b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Pagination.swift @@ -0,0 +1,20 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireFilteredTopicListViewController { + func handleVisibleItemsChanged(_ items: [FireFilteredTopicItem]) { + let nearEnd = items.contains { + if case .loadingMore = $0 { return true } + if case let .topic(id) = $0 { + return id == listViewModel.displayedRows.last?.topic.id + } + return false + } + guard nearEnd else { return } + loadTask = Task { [weak self] in + await self?.listViewModel.loadMore() + } + } +} diff --git a/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Routing.swift b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Routing.swift new file mode 100644 index 00000000..98f4592e --- /dev/null +++ b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Routing.swift @@ -0,0 +1,40 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireFilteredTopicListViewController { + func updateTopicRoutePresenter(_ presenter: FireTopicRoutePresenter) { + topicRoutePresenter = presenter + } + + func canSelect(_ item: FireFilteredTopicItem) -> Bool { + if case .topic = item { return true } + return false + } + + func handleSelection(_ item: FireFilteredTopicItem) { + guard case let .topic(id) = item, + let row = listViewModel.displayedRows.first(where: { $0.topic.id == id }) + else { return } + presentRoute(.topic(row: row)) + } + + func presentRoute(_ route: FireAppRoute) { + if topicRoutePresenter.present(route) { + return + } + if route.presentsAsSecondaryPage { + FireAppRouteControllerFactory.presentSecondaryRoute( + route, + viewModel: appViewModel, + topicDetailStore: topicDetailStore + ) + } + } + + func presentShareSheet(url: URL) { + let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) + present(controller, animated: true) + } +} diff --git a/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Setup.swift b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Setup.swift new file mode 100644 index 00000000..92d39747 --- /dev/null +++ b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController+Setup.swift @@ -0,0 +1,48 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireFilteredTopicListViewController { + func configureListController() { + listController.updateCellProvider { [weak self] collectionView, indexPath, item in + guard let self else { return UICollectionViewCell() } + return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) + } + listController.updateContextMenuConfigurationProvider { [weak self] item in + self?.contextMenuConfiguration(for: item) + } + } + + func prepareCellRegistrations() { + _ = feedSelectorCellRegistration + _ = stateCellRegistration + _ = skeletonCellRegistration + _ = bannerCellRegistration + _ = topicCellRegistration + } + + func installListController() { + addChild(listController) + view.addSubview(listController.view) + listController.view.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + listController.view.topAnchor.constraint(equalTo: view.topAnchor), + listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + listController.didMove(toParent: self) + } + + func bindViewModel() { + listViewModel.objectWillChange + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + DispatchQueue.main.async { + self?.render() + } + } + .store(in: &cancellables) + } +} diff --git a/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController.swift b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController.swift index 12f4b49b..668b0794 100644 --- a/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController.swift +++ b/apps/ios-app/App/Views/Home/FireFilteredTopicListViewController.swift @@ -4,46 +4,14 @@ import UIKit // MARK: - SwiftUI host (category browser NavigationLink) -struct FireFilteredTopicListControllerHost: UIViewControllerRepresentable { - @Environment(\.fireTopicRoutePresenter) private var topicRoutePresenter - @EnvironmentObject private var topicDetailStore: FireTopicDetailStore - - let viewModel: FireAppViewModel - let title: String - let categorySlug: String? - let categoryId: UInt64? - let parentCategorySlug: String? - let tag: String? - - func makeUIViewController(context: Context) -> FireFilteredTopicListViewController { - FireFilteredTopicListViewController( - viewModel: viewModel, - topicDetailStore: topicDetailStore, - title: title, - categorySlug: categorySlug, - categoryId: categoryId, - parentCategorySlug: parentCategorySlug, - tag: tag, - topicRoutePresenter: topicRoutePresenter - ) - } - - func updateUIViewController( - _ uiViewController: FireFilteredTopicListViewController, - context: Context - ) { - uiViewController.updateTopicRoutePresenter(topicRoutePresenter) - } -} - // MARK: - Collection model -private enum FireFilteredTopicSection: Int, Hashable { +enum FireFilteredTopicSection: Int, Hashable { case feedSelector case content } -private enum FireFilteredTopicItem: Hashable { +enum FireFilteredTopicItem: Hashable { case feedSelector case blockingError(String) case inlineErrorBanner(String) @@ -57,7 +25,7 @@ private enum FireFilteredTopicItem: Hashable { @MainActor final class FireFilteredTopicListViewController: UIViewController { - private struct ContentVersion: Hashable { + struct ContentVersion: Hashable { let selectedKind: TopicListKindState let rows: [UInt64] let nextPage: UInt32? @@ -68,17 +36,17 @@ final class FireFilteredTopicListViewController: UIViewController { let displayState: FireScopedTopicListDisplayState } - private let appViewModel: FireAppViewModel - private let topicDetailStore: FireTopicDetailStore - private let listViewModel: FireFilteredTopicListViewModel - private let listTitle: String - private let controllerReference = FireFilteredTopicListControllerReference() - private let listController: FireListViewController - private var topicRoutePresenter: FireTopicRoutePresenter - private var cancellables: Set = [] - private var loadTask: Task? + let appViewModel: FireAppViewModel + let topicDetailStore: FireTopicDetailStore + let listViewModel: FireFilteredTopicListViewModel + let listTitle: String + let controllerReference = FireFilteredTopicListControllerReference() + let listController: FireListViewController + var topicRoutePresenter: FireTopicRoutePresenter + var cancellables: Set = [] + var loadTask: Task? - private lazy var feedSelectorCellRegistration = UICollectionView.CellRegistration< + lazy var feedSelectorCellRegistration = UICollectionView.CellRegistration< FireFilteredFeedSelectorCell, FireFilteredTopicItem > { [weak self] cell, _, item in @@ -93,7 +61,7 @@ final class FireFilteredTopicListViewController: UIViewController { ) } - private lazy var stateCellRegistration = UICollectionView.CellRegistration< + lazy var stateCellRegistration = UICollectionView.CellRegistration< FireTopicListStateCell, FireFilteredTopicItem > { [weak self] cell, _, item in @@ -121,14 +89,14 @@ final class FireFilteredTopicListViewController: UIViewController { } } - private lazy var skeletonCellRegistration = UICollectionView.CellRegistration< + lazy var skeletonCellRegistration = UICollectionView.CellRegistration< FireHomeStyleSkeletonCell, FireFilteredTopicItem > { cell, _, _ in cell.configure() } - private lazy var bannerCellRegistration = UICollectionView.CellRegistration< + lazy var bannerCellRegistration = UICollectionView.CellRegistration< FireTopicListErrorBannerCell, FireFilteredTopicItem > { [weak self] cell, _, item in @@ -142,7 +110,7 @@ final class FireFilteredTopicListViewController: UIViewController { ) } - private lazy var topicCellRegistration = UICollectionView.CellRegistration< + lazy var topicCellRegistration = UICollectionView.CellRegistration< FireTopicListTopicCell, FireFilteredTopicItem > { [weak self] cell, _, item in @@ -242,452 +210,11 @@ final class FireFilteredTopicListViewController: UIViewController { } } - func updateTopicRoutePresenter(_ presenter: FireTopicRoutePresenter) { - topicRoutePresenter = presenter - } - - private func configureListController() { - listController.updateCellProvider { [weak self] collectionView, indexPath, item in - guard let self else { return UICollectionViewCell() } - return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) - } - listController.updateContextMenuConfigurationProvider { [weak self] item in - self?.contextMenuConfiguration(for: item) - } - } - - private func prepareCellRegistrations() { - _ = feedSelectorCellRegistration - _ = stateCellRegistration - _ = skeletonCellRegistration - _ = bannerCellRegistration - _ = topicCellRegistration - } - - private func installListController() { - addChild(listController) - view.addSubview(listController.view) - listController.view.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), - listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), - listController.view.topAnchor.constraint(equalTo: view.topAnchor), - listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) - listController.didMove(toParent: self) - } - - private func bindViewModel() { - listViewModel.objectWillChange - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - DispatchQueue.main.async { - self?.render() - } - } - .store(in: &cancellables) - } - - private var baseURLString: String { - let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? "https://linux.do" : trimmed - } - - private var contentVersion: ContentVersion { - ContentVersion( - selectedKind: listViewModel.selectedKind, - rows: listViewModel.displayedRows.map(\.topic.id), - nextPage: listViewModel.currentKindNextPage, - isLoading: listViewModel.isLoading, - isLoadingMore: listViewModel.isLoadingMore, - hasResolved: listViewModel.hasResolvedCurrentKind, - errorMessage: listViewModel.errorMessage, - displayState: listViewModel.currentKindDisplayState - ) - } - - private func render() { - let sections = makeSections() - var tokens: [FireFilteredTopicItem: AnyHashable] = [:] - for section in sections { - for item in section.items { - tokens[item] = itemContentToken(for: item) - } - } - listController.setSections( - sections, - contentVersion: contentVersion, - itemContentTokens: tokens, - animatingDifferences: true - ) - } - - private func makeSections() - -> [FireListSectionModel] - { - var sections: [FireListSectionModel] = [ - .init(id: .feedSelector, items: [.feedSelector]), - ] - - var items: [FireFilteredTopicItem] = [] - switch listViewModel.currentKindDisplayState { - case .loading: - items.append(contentsOf: (0..<6).map { .loadingSkeleton($0) }) - case let .blockingError(message): - items.append(.blockingError(message)) - case let .empty(nonBlocking): - if let nonBlocking { - items.append(.inlineErrorBanner(nonBlocking)) - } - items.append(.empty) - case let .content(nonBlocking): - if let nonBlocking { - items.append(.inlineErrorBanner(nonBlocking)) - } - items.append(contentsOf: listViewModel.displayedRows.map { .topic($0.topic.id) }) - if listViewModel.currentKindNextPage != nil { - items.append(.loadingMore) - } - } - sections.append(.init(id: .content, items: items)) - return sections - } - - private func itemContentToken(for item: FireFilteredTopicItem) -> AnyHashable { - switch item { - case .feedSelector: - return listViewModel.selectedKind - case let .blockingError(message), let .inlineErrorBanner(message): - return message - case let .loadingSkeleton(index): - return index - case .empty: - return "empty" - case let .topic(id): - if let row = listViewModel.displayedRows.first(where: { $0.topic.id == id }) { - return "\(id)-\(row.topic.likeCount)-\(row.topic.replyCount)-\(row.topic.bookmarkId ?? 0)" - } - return id - case .loadingMore: - return listViewModel.isLoadingMore - } - } - - private func cell( - collectionView: UICollectionView, - indexPath: IndexPath, - item: FireFilteredTopicItem - ) -> UICollectionViewCell { - switch item { - case .feedSelector: - return collectionView.dequeueConfiguredReusableCell( - using: feedSelectorCellRegistration, - for: indexPath, - item: item - ) - case .blockingError, .empty, .loadingMore: - return collectionView.dequeueConfiguredReusableCell( - using: stateCellRegistration, - for: indexPath, - item: item - ) - case .loadingSkeleton: - return collectionView.dequeueConfiguredReusableCell( - using: skeletonCellRegistration, - for: indexPath, - item: item - ) - case .inlineErrorBanner: - return collectionView.dequeueConfiguredReusableCell( - using: bannerCellRegistration, - for: indexPath, - item: item - ) - case .topic: - return collectionView.dequeueConfiguredReusableCell( - using: topicCellRegistration, - for: indexPath, - item: item - ) - } - } - - private func canSelect(_ item: FireFilteredTopicItem) -> Bool { - if case .topic = item { return true } - return false - } - - private func handleSelection(_ item: FireFilteredTopicItem) { - guard case let .topic(id) = item, - let row = listViewModel.displayedRows.first(where: { $0.topic.id == id }) - else { return } - presentRoute(.topic(row: row)) - } - - private func handleVisibleItemsChanged(_ items: [FireFilteredTopicItem]) { - let nearEnd = items.contains { - if case .loadingMore = $0 { return true } - if case let .topic(id) = $0 { - return id == listViewModel.displayedRows.last?.topic.id - } - return false - } - guard nearEnd else { return } - loadTask = Task { [weak self] in - await self?.listViewModel.loadMore() - } - } - - private func contextMenuConfiguration( - for item: FireFilteredTopicItem - ) -> UIContextMenuConfiguration? { - guard case let .topic(id) = item, - let row = listViewModel.displayedRows.first(where: { $0.topic.id == id }) - else { return nil } - let shareURL = row.fireTopicURL(baseURL: baseURLString) - return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in - UIMenu(children: [ - UIAction(title: "打开话题", image: UIImage(systemName: "arrow.up.right")) { _ in - self?.presentRoute(.topic(row: row)) - }, - UIAction( - title: row.topic.bookmarkId == nil ? "添加书签" : "编辑书签", - image: UIImage(systemName: row.topic.bookmarkId == nil ? "bookmark" : "bookmark.fill") - ) { _ in - self?.presentBookmarkEditor(for: row) - }, - UIAction(title: "分享话题", image: UIImage(systemName: "square.and.arrow.up")) { _ in - self?.presentShareSheet(url: shareURL) - }, - UIAction(title: "复制链接", image: UIImage(systemName: "doc.on.doc")) { _ in - UIPasteboard.general.string = shareURL.absoluteString - self?.showToast("已复制链接", style: .success) - }, - UIAction(title: "静音话题", image: UIImage(systemName: "bell.slash")) { _ in - self?.muteTopic(row) - }, - ]) - } - } - - private func presentRoute(_ route: FireAppRoute) { - if topicRoutePresenter.present(route) { - return - } - if route.presentsAsSecondaryPage { - FireAppRouteControllerFactory.presentSecondaryRoute( - route, - viewModel: appViewModel, - topicDetailStore: topicDetailStore - ) - } - } - - private func presentShareSheet(url: URL) { - let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) - present(controller, animated: true) - } - - private func presentBookmarkEditor(for row: FireTopicRowPresentation) { - let context = row.fireBookmarkEditorContext() - let sheet = FireBookmarkEditorSheet( - context: context, - onSave: { [weak self] name, reminderAt in - guard let self else { return } - if let bookmarkID = context.bookmarkID { - try await self.appViewModel.topicInteraction.updateBookmark( - bookmarkID: bookmarkID, - name: name, - reminderAt: reminderAt - ) - } else { - _ = try await self.appViewModel.topicInteraction.createBookmark( - bookmarkableID: context.bookmarkableID, - bookmarkableType: context.bookmarkableType, - name: name, - reminderAt: reminderAt - ) - } - await self.listViewModel.refresh() - }, - onDelete: context.bookmarkID.map { bookmarkID in - { [weak self] in - try await self?.appViewModel.topicInteraction.deleteBookmark(bookmarkID: bookmarkID) - await self?.listViewModel.refresh() - } - } - ) - let host = UIHostingController(rootView: sheet) - if let sheetController = host.sheetPresentationController { - sheetController.detents = [.medium(), .large()] - sheetController.prefersGrabberVisible = true - } - present(host, animated: true) - } - - private func deleteBookmark(for row: FireTopicRowPresentation) { - guard let bookmarkID = row.topic.bookmarkId else { return } - loadTask = Task { [weak self] in - guard let self else { return } - do { - try await appViewModel.topicInteraction.deleteBookmark(bookmarkID: bookmarkID) - await listViewModel.refresh() - showToast("已删除书签", style: .success) - } catch { - showToast(error.localizedDescription, style: .error) - } - } - } - - private func muteTopic(_ row: FireTopicRowPresentation) { - loadTask = Task { [weak self] in - guard let self else { return } - do { - try await appViewModel.topicInteraction.setTopicNotificationLevel( - topicID: row.topic.id, - notificationLevel: FireTopicNotificationLevelOption.muted.rawValue - ) - showToast("已静音话题", style: .success) - } catch { - showToast(error.localizedDescription, style: .error) - } - } - } - - private func showToast(_ message: String, style: FireUIKitToast.Style) { - FireUIKitToast.show(message, style: style, in: view) - } } // MARK: - Supporting cells -private final class FireFilteredFeedSelectorCell: UICollectionViewCell { - private let scrollView = UIScrollView() - private let stackView = UIStackView() - - override init(frame: CGRect) { - super.init(frame: frame) - configureSubviews() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override func prepareForReuse() { - super.prepareForReuse() - stackView.arrangedSubviews.forEach { - stackView.removeArrangedSubview($0) - $0.removeFromSuperview() - } - } - - func configure( - selectedKind: TopicListKindState, - onSelectKind: @escaping (TopicListKindState) -> Void - ) { - prepareForReuse() - for kind in TopicListKindState.orderedCases { - var configuration = UIButton.Configuration.filled() - configuration.title = kind.title - configuration.cornerStyle = .capsule - configuration.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 12, bottom: 6, trailing: 12) - let selected = selectedKind == kind - configuration.baseBackgroundColor = selected ? FireTheme.uiAccent : .tertiarySystemFill - configuration.baseForegroundColor = selected ? .white : .label - let button = UIButton(configuration: configuration) - button.addAction(UIAction { _ in - FireMotionHaptics.selection() - onSelectKind(kind) - }, for: .touchUpInside) - button.fireBindPressBounce(.compact) - stackView.addArrangedSubview(button) - } - } - - private func configureSubviews() { - backgroundConfiguration = .clear() - contentView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 16) - scrollView.showsHorizontalScrollIndicator = false - scrollView.translatesAutoresizingMaskIntoConstraints = false - stackView.axis = .horizontal - stackView.spacing = 6 - stackView.translatesAutoresizingMaskIntoConstraints = false - contentView.addSubview(scrollView) - scrollView.addSubview(stackView) - NSLayoutConstraint.activate([ - scrollView.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), - scrollView.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor), - scrollView.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor), - scrollView.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor), - stackView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor), - stackView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor), - stackView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor), - stackView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor), - stackView.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor), - ]) - } -} - /// Shared-style skeleton matching home feed placeholder geometry. -final class FireHomeStyleSkeletonCell: UICollectionViewCell { - private let avatarView = UIView() - private let titleBar = UIView() - private let subtitleBar = UIView() - - override init(frame: CGRect) { - super.init(frame: frame) - configureSubviews() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override func prepareForReuse() { - super.prepareForReuse() - FireUIKitSkeleton.hide(contentView) - } - - func configure() { - isAccessibilityElement = false - FireUIKitSkeleton.show(contentView) - } - - private func configureSubviews() { - backgroundConfiguration = .clear() - contentView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 16) - avatarView.layer.cornerRadius = 19 - avatarView.layer.cornerCurve = .continuous - titleBar.layer.cornerRadius = 4 - subtitleBar.layer.cornerRadius = 4 - let body = UIStackView(arrangedSubviews: [titleBar, subtitleBar]) - body.axis = .vertical - body.spacing = 6 - let row = UIStackView(arrangedSubviews: [avatarView, body]) - row.axis = .horizontal - row.spacing = 12 - row.alignment = .center - row.translatesAutoresizingMaskIntoConstraints = false - contentView.addSubview(row) - NSLayoutConstraint.activate([ - avatarView.widthAnchor.constraint(equalToConstant: 38), - avatarView.heightAnchor.constraint(equalToConstant: 38), - titleBar.heightAnchor.constraint(equalToConstant: 14), - titleBar.widthAnchor.constraint(equalTo: body.widthAnchor), - subtitleBar.widthAnchor.constraint(equalToConstant: 100), - subtitleBar.heightAnchor.constraint(equalToConstant: 10), - row.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), - row.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor), - row.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor), - row.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor), - ]) - FireUIKitSkeleton.prepareHierarchy(in: contentView) - } -} - -private final class FireFilteredTopicListControllerReference { +final class FireFilteredTopicListControllerReference { weak var controller: FireFilteredTopicListViewController? } diff --git a/apps/ios-app/App/Views/Home/FireHomeStyleSkeletonCell.swift b/apps/ios-app/App/Views/Home/FireHomeStyleSkeletonCell.swift new file mode 100644 index 00000000..72361f85 --- /dev/null +++ b/apps/ios-app/App/Views/Home/FireHomeStyleSkeletonCell.swift @@ -0,0 +1,58 @@ +import UIKit + +final class FireHomeStyleSkeletonCell: UICollectionViewCell { + private let avatarView = UIView() + private let titleBar = UIView() + private let subtitleBar = UIView() + + override init(frame: CGRect) { + super.init(frame: frame) + configureSubviews() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func prepareForReuse() { + super.prepareForReuse() + FireUIKitSkeleton.hide(contentView) + } + + func configure() { + isAccessibilityElement = false + FireUIKitSkeleton.show(contentView) + } + + private func configureSubviews() { + backgroundConfiguration = .clear() + contentView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 16) + avatarView.layer.cornerRadius = 19 + avatarView.layer.cornerCurve = .continuous + titleBar.layer.cornerRadius = 4 + subtitleBar.layer.cornerRadius = 4 + let body = UIStackView(arrangedSubviews: [titleBar, subtitleBar]) + body.axis = .vertical + body.spacing = 6 + let row = UIStackView(arrangedSubviews: [avatarView, body]) + row.axis = .horizontal + row.spacing = 12 + row.alignment = .center + row.translatesAutoresizingMaskIntoConstraints = false + contentView.addSubview(row) + NSLayoutConstraint.activate([ + avatarView.widthAnchor.constraint(equalToConstant: 38), + avatarView.heightAnchor.constraint(equalToConstant: 38), + titleBar.heightAnchor.constraint(equalToConstant: 14), + titleBar.widthAnchor.constraint(equalTo: body.widthAnchor), + subtitleBar.widthAnchor.constraint(equalToConstant: 100), + subtitleBar.heightAnchor.constraint(equalToConstant: 10), + row.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), + row.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor), + row.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor), + row.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor), + ]) + FireUIKitSkeleton.prepareHierarchy(in: contentView) + } +} diff --git a/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Composer.swift b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Composer.swift new file mode 100644 index 00000000..cb7adb2e --- /dev/null +++ b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Composer.swift @@ -0,0 +1,39 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FirePrivateMessagesViewController { + @objc func openComposer() { + let composer = FireComposerViewController( + viewModel: appViewModel, + route: FireComposerRoute(kind: .privateMessage(recipients: [], title: nil)), + onPrivateMessageCreated: { [weak self] topicID, title in + guard let self else { return } + let route = FireAppRoute.topic( + topicId: topicID, + postNumber: nil, + preview: FireTopicRoutePreview.fromMetadata(title: title, slug: nil) + ) + self.presentRoute(route) + self.loadTask = Task { [weak self] in + await self?.mailboxViewModel.refresh() + } + }, + onSubmissionNotice: { [weak self] message in + guard message.contains("等待审核") else { return } + self?.showToast(message, style: .info) + } + ) + let navigationController = UINavigationController(rootViewController: composer) + navigationController.modalPresentationStyle = .fullScreen + present(navigationController, animated: true) + } + + func showToast(_ message: String, style: FireTopicListToastView.Style) { + toastDismissTask?.cancel() + toastView?.removeFromSuperview() + toastView = nil + FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) + } +} diff --git a/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Feed.swift b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Feed.swift new file mode 100644 index 00000000..8b859730 --- /dev/null +++ b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Feed.swift @@ -0,0 +1,155 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FirePrivateMessagesViewController { + var baseURLString: String { + let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? "https://linux.do" : trimmed + } + + var contentVersion: ContentVersion { + ContentVersion( + selectedKind: Self.kindIdentifier(mailboxViewModel.selectedKind), + renderedKind: mailboxViewModel.renderedKind.map(Self.kindIdentifier(_:)), + rowIDs: mailboxViewModel.displayedRows.map(\.topic.id), + userIDs: mailboxViewModel.displayedUsers.map(\.id), + isLoading: mailboxViewModel.isLoading, + isLoadingMore: mailboxViewModel.isLoadingMore, + hasLoadedOnce: mailboxViewModel.hasLoadedOnce, + errorMessage: mailboxViewModel.errorMessage + ) + } + + var nonBlockingErrorMessage: String? { + switch mailboxViewModel.currentKindDisplayState { + case .empty(let message), .content(let message): + return message + case .loading, .blockingError: + return nil + } + } + + func render() { + let sections = makeSections() + var tokens: [FirePrivateMessagesCollectionItem: AnyHashable] = [:] + tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) + for section in sections { + for item in section.items { + tokens[item] = itemContentToken(for: item) + } + } + listController.setSections( + sections, + contentVersion: contentVersion, + itemContentTokens: tokens, + animatingDifferences: true + ) + } + + func makeSections() + -> [FireListSectionModel] + { + var sections: [FireListSectionModel] = [ + .init(id: .controls, items: [.mailboxPicker]), + ] + + var contentItems: [FirePrivateMessagesCollectionItem] = [] + if let errorMessage = nonBlockingErrorMessage { + contentItems.append(.inlineErrorBanner(errorMessage)) + } + + switch mailboxViewModel.currentKindDisplayState { + case .loading: + contentItems.append(.loading) + case let .blockingError(message): + contentItems.append(.blockingError(message)) + case .empty: + contentItems.append(.empty) + case .content: + contentItems.append(contentsOf: mailboxViewModel.displayedRows.map { .message($0.topic.id) }) + if mailboxViewModel.isLoadingMore { + contentItems.append(.loadingMore) + } + } + + sections.append(.init(id: .content, items: contentItems)) + return sections + } + + func cell( + collectionView: UICollectionView, + indexPath: IndexPath, + item: FirePrivateMessagesCollectionItem + ) -> UICollectionViewCell { + switch item { + case .mailboxPicker: + return collectionView.dequeueConfiguredReusableCell( + using: pickerCellRegistration, + for: indexPath, + item: item + ) + case .inlineErrorBanner: + return collectionView.dequeueConfiguredReusableCell( + using: bannerCellRegistration, + for: indexPath, + item: item + ) + case .loading, .blockingError, .empty, .loadingMore: + return collectionView.dequeueConfiguredReusableCell( + using: stateCellRegistration, + for: indexPath, + item: item + ) + case .message: + return collectionView.dequeueConfiguredReusableCell( + using: messageCellRegistration, + for: indexPath, + item: item + ) + } + } + + func itemContentToken(for item: FirePrivateMessagesCollectionItem) -> AnyHashable { + switch item { + case .mailboxPicker: + return AnyHashable(mailboxViewModel.selectedKind) + case let .inlineErrorBanner(message), let .blockingError(message): + return AnyHashable(message) + case .loading: + return AnyHashable(mailboxViewModel.isLoading) + case .empty: + return AnyHashable("\(Self.kindIdentifier(mailboxViewModel.selectedKind))|\(mailboxViewModel.hasLoadedOnce)") + case let .message(topicID): + guard let row = row(topicID: topicID) else { + return AnyHashable("missing|\(topicID)") + } + return AnyHashable(MessageContentToken( + topicID: topicID, + title: row.topic.title, + replyCount: row.topic.replyCount, + excerptText: row.excerptText, + activityTimestampUnixMs: row.activityTimestampUnixMs, + participants: resolvedParticipants(for: row.topic).map { + ParticipantToken( + userID: $0.userId, + username: $0.username, + name: $0.name, + avatarTemplate: $0.avatarTemplate + ) + } + )) + case .loadingMore: + return AnyHashable(mailboxViewModel.isLoadingMore) + } + } + + static func kindIdentifier(_ kind: TopicListKindState) -> String { + String(describing: kind) + } + + func row(topicID: UInt64) -> TopicRowState? { + mailboxViewModel.displayedRows.first { $0.topic.id == topicID } + } +} diff --git a/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Pagination.swift b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Pagination.swift new file mode 100644 index 00000000..ca360d2d --- /dev/null +++ b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Pagination.swift @@ -0,0 +1,14 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FirePrivateMessagesViewController { + func loadMoreIfNeeded(from items: [FirePrivateMessagesCollectionItem]) { + guard let lastTopicID = mailboxViewModel.displayedRows.last?.topic.id else { return } + guard items.contains(.message(lastTopicID)) || items.contains(.loadingMore) else { return } + loadTask = Task { [weak self] in + await self?.mailboxViewModel.loadMoreIfNeeded(currentTopicID: lastTopicID) + } + } +} diff --git a/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Participants.swift b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Participants.swift new file mode 100644 index 00000000..a7290fba --- /dev/null +++ b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Participants.swift @@ -0,0 +1,40 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FirePrivateMessagesViewController { + var currentUsername: String? { + appViewModel.session.bootstrap.currentUsername?.trimmingCharacters(in: .whitespacesAndNewlines) + } + + var usersByID: [UInt64: TopicUserState] { + mailboxViewModel.displayedUsers.reduce(into: [:]) { partialResult, user in + partialResult[user.id] = user + } + } + + func resolvedParticipants(for topic: TopicSummaryState) -> [TopicParticipantState] { + var merged: [TopicParticipantState] = [] + for participant in topic.participants { + let resolvedUser = usersByID[participant.userId] + let resolved = TopicParticipantState( + userId: participant.userId, + username: participant.username ?? resolvedUser?.username, + name: participant.name, + avatarTemplate: participant.avatarTemplate ?? resolvedUser?.avatarTemplate + ) + let stableName = resolved.username?.lowercased() ?? "id:\(resolved.userId)" + if merged.contains(where: { + ($0.username?.lowercased() ?? "id:\($0.userId)") == stableName + }) { + continue + } + if let currentUsername, resolved.username?.caseInsensitiveCompare(currentUsername) == .orderedSame { + continue + } + merged.append(resolved) + } + return merged + } +} diff --git a/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Routing.swift b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Routing.swift new file mode 100644 index 00000000..7da58723 --- /dev/null +++ b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Routing.swift @@ -0,0 +1,50 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FirePrivateMessagesViewController { + func updateTopicRoutePresenter(_ presenter: FireTopicRoutePresenter) { + topicRoutePresenter = presenter + } + + func canSelect(_ item: FirePrivateMessagesCollectionItem) -> Bool { + if case .message = item { + return true + } + return false + } + + func handleSelection(_ item: FirePrivateMessagesCollectionItem) { + guard case let .message(topicID) = item, + let row = row(topicID: topicID) + else { + return + } + presentRoute(.topic(row: row)) + } + + func presentRoute(_ route: FireAppRoute) { + if topicRoutePresenter.present(route) { + return + } + if route.presentsAsSecondaryPage { + FireAppRouteControllerFactory.presentSecondaryRoute( + route, + viewModel: appViewModel, + topicDetailStore: topicDetailStore + ) + return + } + // Already inside secondary stack: push local drill-down. + if let navigationController { + let controller = FireAppRouteControllerFactory.makeViewController( + viewModel: appViewModel, + topicDetailStore: topicDetailStore, + route: route, + topicRoutePresenter: topicRoutePresenter + ) + navigationController.pushViewController(controller, animated: true) + } + } +} diff --git a/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Setup.swift b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Setup.swift new file mode 100644 index 00000000..30cfba85 --- /dev/null +++ b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController+Setup.swift @@ -0,0 +1,46 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FirePrivateMessagesViewController { + func configureListController() { + listController.updateCellProvider { [weak self] collectionView, indexPath, item in + guard let self else { + return UICollectionViewCell() + } + return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) + } + } + + func prepareCellRegistrations() { + _ = pickerCellRegistration + _ = stateCellRegistration + _ = bannerCellRegistration + _ = messageCellRegistration + } + + func installListController() { + addChild(listController) + view.addSubview(listController.view) + listController.view.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + listController.view.topAnchor.constraint(equalTo: view.topAnchor), + listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + listController.didMove(toParent: self) + } + + func bindViewModel() { + mailboxViewModel.objectWillChange + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + DispatchQueue.main.async { + self?.render() + } + } + .store(in: &cancellables) + } +} diff --git a/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController.swift b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController.swift index 8b0d5b46..e1ad6f27 100644 --- a/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController.swift +++ b/apps/ios-app/App/Views/Messages/FirePrivateMessagesViewController.swift @@ -19,7 +19,7 @@ enum FirePrivateMessagesCollectionItem: Hashable { @MainActor final class FirePrivateMessagesViewController: UIViewController { - private struct ContentVersion: Hashable { + struct ContentVersion: Hashable { let selectedKind: String let renderedKind: String? let rowIDs: [UInt64] @@ -30,14 +30,14 @@ final class FirePrivateMessagesViewController: UIViewController { let errorMessage: String? } - private struct ParticipantToken: Hashable { + struct ParticipantToken: Hashable { let userID: UInt64 let username: String? let name: String? let avatarTemplate: String? } - private struct MessageContentToken: Hashable { + struct MessageContentToken: Hashable { let topicID: UInt64 let title: String let replyCount: UInt32 @@ -46,21 +46,21 @@ final class FirePrivateMessagesViewController: UIViewController { let participants: [ParticipantToken] } - private let appViewModel: FireAppViewModel - private let topicDetailStore: FireTopicDetailStore - private let mailboxViewModel: FirePrivateMessagesViewModel - private let controllerReference: FirePrivateMessagesControllerReference - private let listController: FireListViewController< + let appViewModel: FireAppViewModel + let topicDetailStore: FireTopicDetailStore + let mailboxViewModel: FirePrivateMessagesViewModel + let controllerReference: FirePrivateMessagesControllerReference + let listController: FireListViewController< FirePrivateMessagesCollectionSection, FirePrivateMessagesCollectionItem > - private var topicRoutePresenter: FireTopicRoutePresenter - private var cancellables: Set = [] - private var loadTask: Task? - private var toastDismissTask: Task? - private weak var toastView: UIView? + var topicRoutePresenter: FireTopicRoutePresenter + var cancellables: Set = [] + var loadTask: Task? + var toastDismissTask: Task? + weak var toastView: UIView? - private lazy var pickerCellRegistration = UICollectionView.CellRegistration< + lazy var pickerCellRegistration = UICollectionView.CellRegistration< FirePrivateMessagesPickerCell, FirePrivateMessagesCollectionItem > { [weak self] cell, _, _ in @@ -72,7 +72,7 @@ final class FirePrivateMessagesViewController: UIViewController { } } - private lazy var stateCellRegistration = UICollectionView.CellRegistration< + lazy var stateCellRegistration = UICollectionView.CellRegistration< FireTopicListStateCell, FirePrivateMessagesCollectionItem > { [weak self] cell, _, item in @@ -101,7 +101,7 @@ final class FirePrivateMessagesViewController: UIViewController { } } - private lazy var bannerCellRegistration = UICollectionView.CellRegistration< + lazy var bannerCellRegistration = UICollectionView.CellRegistration< FireTopicListErrorBannerCell, FirePrivateMessagesCollectionItem > { [weak self] cell, _, item in @@ -118,7 +118,7 @@ final class FirePrivateMessagesViewController: UIViewController { ) } - private lazy var messageCellRegistration = UICollectionView.CellRegistration< + lazy var messageCellRegistration = UICollectionView.CellRegistration< FirePrivateMessageListCell, FirePrivateMessagesCollectionItem > { [weak self] cell, _, item in @@ -205,313 +205,6 @@ final class FirePrivateMessagesViewController: UIViewController { } } - func updateTopicRoutePresenter(_ presenter: FireTopicRoutePresenter) { - topicRoutePresenter = presenter - } - - private func configureListController() { - listController.updateCellProvider { [weak self] collectionView, indexPath, item in - guard let self else { - return UICollectionViewCell() - } - return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) - } - } - - private func prepareCellRegistrations() { - _ = pickerCellRegistration - _ = stateCellRegistration - _ = bannerCellRegistration - _ = messageCellRegistration - } - - private func installListController() { - addChild(listController) - view.addSubview(listController.view) - listController.view.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), - listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), - listController.view.topAnchor.constraint(equalTo: view.topAnchor), - listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) - listController.didMove(toParent: self) - } - - private func bindViewModel() { - mailboxViewModel.objectWillChange - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - DispatchQueue.main.async { - self?.render() - } - } - .store(in: &cancellables) - } - - private var currentUsername: String? { - appViewModel.session.bootstrap.currentUsername?.trimmingCharacters(in: .whitespacesAndNewlines) - } - - private var baseURLString: String { - let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? "https://linux.do" : trimmed - } - - private var usersByID: [UInt64: TopicUserState] { - mailboxViewModel.displayedUsers.reduce(into: [:]) { partialResult, user in - partialResult[user.id] = user - } - } - - private var contentVersion: ContentVersion { - ContentVersion( - selectedKind: Self.kindIdentifier(mailboxViewModel.selectedKind), - renderedKind: mailboxViewModel.renderedKind.map(Self.kindIdentifier(_:)), - rowIDs: mailboxViewModel.displayedRows.map(\.topic.id), - userIDs: mailboxViewModel.displayedUsers.map(\.id), - isLoading: mailboxViewModel.isLoading, - isLoadingMore: mailboxViewModel.isLoadingMore, - hasLoadedOnce: mailboxViewModel.hasLoadedOnce, - errorMessage: mailboxViewModel.errorMessage - ) - } - - private var nonBlockingErrorMessage: String? { - switch mailboxViewModel.currentKindDisplayState { - case .empty(let message), .content(let message): - return message - case .loading, .blockingError: - return nil - } - } - - private func render() { - let sections = makeSections() - var tokens: [FirePrivateMessagesCollectionItem: AnyHashable] = [:] - tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) - for section in sections { - for item in section.items { - tokens[item] = itemContentToken(for: item) - } - } - listController.setSections( - sections, - contentVersion: contentVersion, - itemContentTokens: tokens, - animatingDifferences: true - ) - } - - private func makeSections() - -> [FireListSectionModel] - { - var sections: [FireListSectionModel] = [ - .init(id: .controls, items: [.mailboxPicker]), - ] - - var contentItems: [FirePrivateMessagesCollectionItem] = [] - if let errorMessage = nonBlockingErrorMessage { - contentItems.append(.inlineErrorBanner(errorMessage)) - } - - switch mailboxViewModel.currentKindDisplayState { - case .loading: - contentItems.append(.loading) - case let .blockingError(message): - contentItems.append(.blockingError(message)) - case .empty: - contentItems.append(.empty) - case .content: - contentItems.append(contentsOf: mailboxViewModel.displayedRows.map { .message($0.topic.id) }) - if mailboxViewModel.isLoadingMore { - contentItems.append(.loadingMore) - } - } - - sections.append(.init(id: .content, items: contentItems)) - return sections - } - - private func cell( - collectionView: UICollectionView, - indexPath: IndexPath, - item: FirePrivateMessagesCollectionItem - ) -> UICollectionViewCell { - switch item { - case .mailboxPicker: - return collectionView.dequeueConfiguredReusableCell( - using: pickerCellRegistration, - for: indexPath, - item: item - ) - case .inlineErrorBanner: - return collectionView.dequeueConfiguredReusableCell( - using: bannerCellRegistration, - for: indexPath, - item: item - ) - case .loading, .blockingError, .empty, .loadingMore: - return collectionView.dequeueConfiguredReusableCell( - using: stateCellRegistration, - for: indexPath, - item: item - ) - case .message: - return collectionView.dequeueConfiguredReusableCell( - using: messageCellRegistration, - for: indexPath, - item: item - ) - } - } - - private func itemContentToken(for item: FirePrivateMessagesCollectionItem) -> AnyHashable { - switch item { - case .mailboxPicker: - return AnyHashable(mailboxViewModel.selectedKind) - case let .inlineErrorBanner(message), let .blockingError(message): - return AnyHashable(message) - case .loading: - return AnyHashable(mailboxViewModel.isLoading) - case .empty: - return AnyHashable("\(Self.kindIdentifier(mailboxViewModel.selectedKind))|\(mailboxViewModel.hasLoadedOnce)") - case let .message(topicID): - guard let row = row(topicID: topicID) else { - return AnyHashable("missing|\(topicID)") - } - return AnyHashable(MessageContentToken( - topicID: topicID, - title: row.topic.title, - replyCount: row.topic.replyCount, - excerptText: row.excerptText, - activityTimestampUnixMs: row.activityTimestampUnixMs, - participants: resolvedParticipants(for: row.topic).map { - ParticipantToken( - userID: $0.userId, - username: $0.username, - name: $0.name, - avatarTemplate: $0.avatarTemplate - ) - } - )) - case .loadingMore: - return AnyHashable(mailboxViewModel.isLoadingMore) - } - } - - private static func kindIdentifier(_ kind: TopicListKindState) -> String { - String(describing: kind) - } - - private func row(topicID: UInt64) -> TopicRowState? { - mailboxViewModel.displayedRows.first { $0.topic.id == topicID } - } - - private func canSelect(_ item: FirePrivateMessagesCollectionItem) -> Bool { - if case .message = item { - return true - } - return false - } - - private func handleSelection(_ item: FirePrivateMessagesCollectionItem) { - guard case let .message(topicID) = item, - let row = row(topicID: topicID) - else { - return - } - presentRoute(.topic(row: row)) - } - - private func loadMoreIfNeeded(from items: [FirePrivateMessagesCollectionItem]) { - guard let lastTopicID = mailboxViewModel.displayedRows.last?.topic.id else { return } - guard items.contains(.message(lastTopicID)) || items.contains(.loadingMore) else { return } - loadTask = Task { [weak self] in - await self?.mailboxViewModel.loadMoreIfNeeded(currentTopicID: lastTopicID) - } - } - - private func resolvedParticipants(for topic: TopicSummaryState) -> [TopicParticipantState] { - var merged: [TopicParticipantState] = [] - for participant in topic.participants { - let resolvedUser = usersByID[participant.userId] - let resolved = TopicParticipantState( - userId: participant.userId, - username: participant.username ?? resolvedUser?.username, - name: participant.name, - avatarTemplate: participant.avatarTemplate ?? resolvedUser?.avatarTemplate - ) - let stableName = resolved.username?.lowercased() ?? "id:\(resolved.userId)" - if merged.contains(where: { - ($0.username?.lowercased() ?? "id:\($0.userId)") == stableName - }) { - continue - } - if let currentUsername, resolved.username?.caseInsensitiveCompare(currentUsername) == .orderedSame { - continue - } - merged.append(resolved) - } - return merged - } - - private func presentRoute(_ route: FireAppRoute) { - if topicRoutePresenter.present(route) { - return - } - if route.presentsAsSecondaryPage { - FireAppRouteControllerFactory.presentSecondaryRoute( - route, - viewModel: appViewModel, - topicDetailStore: topicDetailStore - ) - return - } - // Already inside secondary stack: push local drill-down. - if let navigationController { - let controller = FireAppRouteControllerFactory.makeViewController( - viewModel: appViewModel, - topicDetailStore: topicDetailStore, - route: route, - topicRoutePresenter: topicRoutePresenter - ) - navigationController.pushViewController(controller, animated: true) - } - } - - @objc private func openComposer() { - let composer = FireComposerViewController( - viewModel: appViewModel, - route: FireComposerRoute(kind: .privateMessage(recipients: [], title: nil)), - onPrivateMessageCreated: { [weak self] topicID, title in - guard let self else { return } - let route = FireAppRoute.topic( - topicId: topicID, - postNumber: nil, - preview: FireTopicRoutePreview.fromMetadata(title: title, slug: nil) - ) - self.presentRoute(route) - self.loadTask = Task { [weak self] in - await self?.mailboxViewModel.refresh() - } - }, - onSubmissionNotice: { [weak self] message in - guard message.contains("等待审核") else { return } - self?.showToast(message, style: .info) - } - ) - let navigationController = UINavigationController(rootViewController: composer) - navigationController.modalPresentationStyle = .fullScreen - present(navigationController, animated: true) - } - - private func showToast(_ message: String, style: FireTopicListToastView.Style) { - toastDismissTask?.cancel() - toastView?.removeFromSuperview() - toastView = nil - FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) - } } final class FirePrivateMessagesControllerReference { diff --git a/apps/ios-app/App/Views/Other/FireOnboardingErrorBannerView.swift b/apps/ios-app/App/Views/Other/FireOnboardingErrorBannerView.swift new file mode 100644 index 00000000..c4ba0dfc --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingErrorBannerView.swift @@ -0,0 +1,87 @@ +import UIKit + +extension FireOnboardingViewController { + func showErrorBanner(_ message: String) { + errorDismissWorkItem?.cancel() + errorBanner.configure(message: message) + errorBanner.isHidden = false + + let workItem = DispatchWorkItem { [weak self] in + self?.hideErrorBanner() + } + errorDismissWorkItem = workItem + DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: workItem) + } + func hideErrorBanner() { + errorDismissWorkItem?.cancel() + errorDismissWorkItem = nil + errorBanner.isHidden = true + } +} + +final class FireOnboardingErrorBannerView: UIView { + private let messageLabel = UILabel() + var onDismiss: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + configureSubviews() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func configure(message: String) { + messageLabel.text = message + } + + private func configureSubviews() { + backgroundColor = .tertiarySystemFill + layer.cornerRadius = FireTheme.smallCornerRadius + layer.cornerCurve = .continuous + directionalLayoutMargins = NSDirectionalEdgeInsets( + top: 12, + leading: 12, + bottom: 12, + trailing: 12 + ) + + let imageView = UIImageView(image: UIImage(systemName: "exclamationmark.triangle.fill")) + imageView.tintColor = .systemOrange + imageView.contentMode = .scaleAspectFit + imageView.setContentHuggingPriority(.required, for: .horizontal) + + messageLabel.font = UIFont.preferredFont(forTextStyle: .caption1) + messageLabel.adjustsFontForContentSizeCategory = true + messageLabel.textColor = .secondaryLabel + messageLabel.numberOfLines = 2 + + let closeButton = UIButton(type: .system) + closeButton.setImage(UIImage(systemName: "xmark"), for: .normal) + closeButton.tintColor = .secondaryLabel + closeButton.accessibilityLabel = "关闭错误提示" + closeButton.addAction(UIAction { [weak self] _ in + self?.onDismiss?() + }, for: .touchUpInside) + + let stackView = UIStackView(arrangedSubviews: [imageView, messageLabel, closeButton]) + stackView.axis = .horizontal + stackView.alignment = .center + stackView.spacing = 8 + stackView.translatesAutoresizingMaskIntoConstraints = false + + addSubview(stackView) + NSLayoutConstraint.activate([ + imageView.widthAnchor.constraint(equalToConstant: 18), + imageView.heightAnchor.constraint(equalToConstant: 18), + closeButton.widthAnchor.constraint(equalToConstant: 30), + closeButton.heightAnchor.constraint(equalToConstant: 30), + stackView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor), + stackView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor), + stackView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), + stackView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor), + ]) + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingView.swift b/apps/ios-app/App/Views/Other/FireOnboardingView.swift index 8d856c74..18df30f8 100644 --- a/apps/ios-app/App/Views/Other/FireOnboardingView.swift +++ b/apps/ios-app/App/Views/Other/FireOnboardingView.swift @@ -4,48 +4,48 @@ import UIKit @MainActor final class FireOnboardingViewController: UIViewController { - private enum FireOnboardingPhase: Equatable { + enum FireOnboardingPhase: Equatable { case validating case credential case loggingIn } - private let viewModel: FireAppViewModel - private let entry: FireOnboardingEntry - private let contentColumn = UIStackView() - private let brandStack = UIStackView() - private let bottomStack = UIStackView() - private let errorBanner = FireOnboardingErrorBannerView() - private let phaseContainerView = UIView() - private let developerToolsButton = UIButton(type: .system) - private let feedbackButton = UIButton(type: .system) - private var contentCenterYConstraint: NSLayoutConstraint? - private var contentTopConstraint: NSLayoutConstraint? - private var contentBottomConstraint: NSLayoutConstraint? - private lazy var validatingView = FireOnboardingValidatingView() - private lazy var credentialFormView = FireOnboardingCredentialFormView() - private var phase: FireOnboardingPhase = .validating - private var errorDismissWorkItem: DispatchWorkItem? - private var cancellables: Set = [] - - private var captchaDialog: FireCaptchaLoginDialogController? - private var cfRetryUsed = false - private var pendingIdentifier = "" - private var pendingPassword = "" - private var pendingRememberCredential = false - private var hasShownSecondFactor = false - private var loggingInMessage = "正在登录…" + let viewModel: FireAppViewModel + let entry: FireOnboardingEntry + let contentColumn = UIStackView() + let brandStack = UIStackView() + let bottomStack = UIStackView() + let errorBanner = FireOnboardingErrorBannerView() + let phaseContainerView = UIView() + let developerToolsButton = UIButton(type: .system) + let feedbackButton = UIButton(type: .system) + var contentCenterYConstraint: NSLayoutConstraint? + var contentTopConstraint: NSLayoutConstraint? + var contentBottomConstraint: NSLayoutConstraint? + lazy var validatingView = FireOnboardingValidatingView() + lazy var credentialFormView = FireOnboardingCredentialFormView() + var phase: FireOnboardingPhase = .validating + var errorDismissWorkItem: DispatchWorkItem? + var cancellables: Set = [] + + var captchaDialog: FireCaptchaLoginDialogController? + var cfRetryUsed = false + var pendingIdentifier = "" + var pendingPassword = "" + var pendingRememberCredential = false + var hasShownSecondFactor = false + var loggingInMessage = "正在登录…" /// Cold-start post-validation routing: pending → routing → finished. - private enum StartupRouteState { + enum StartupRouteState { case pending case routing case finished } - private var startupRouteState: StartupRouteState = .pending - private var isAutoLoginInFlight = false - private var activeAutoLoginKind: FireAutoLoginKind? - private var headlessExternalEngine: FireHeadlessExternalLoginEngine? + var startupRouteState: StartupRouteState = .pending + var isAutoLoginInFlight = false + var activeAutoLoginKind: FireAutoLoginKind? + var headlessExternalEngine: FireHeadlessExternalLoginEngine? init(viewModel: FireAppViewModel, entry: FireOnboardingEntry = .coldStart) { self.viewModel = viewModel @@ -107,97 +107,6 @@ final class FireOnboardingViewController: UIViewController { NotificationCenter.default.removeObserver(self) } - private func configureBrand() { - let imageView = UIImageView(image: UIImage(systemName: "flame.fill")) - imageView.tintColor = .systemOrange - imageView.contentMode = .scaleAspectFit - - let titleLabel = UILabel() - titleLabel.text = "Fire" - titleLabel.font = UIFont.preferredFont(forTextStyle: .title1).withOnboardingWeight(.bold) - titleLabel.adjustsFontForContentSizeCategory = true - titleLabel.textColor = .label - titleLabel.textAlignment = .center - - let subtitleLabel = UILabel() - subtitleLabel.text = "LinuxDo 原生客户端" - subtitleLabel.font = UIFont.preferredFont(forTextStyle: .subheadline) - subtitleLabel.adjustsFontForContentSizeCategory = true - subtitleLabel.textColor = .secondaryLabel - subtitleLabel.textAlignment = .center - - let textStack = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel]) - textStack.axis = .vertical - textStack.alignment = .center - textStack.spacing = 4 - - brandStack.axis = .vertical - brandStack.alignment = .center - brandStack.spacing = 10 - brandStack.translatesAutoresizingMaskIntoConstraints = false - brandStack.addArrangedSubview(imageView) - brandStack.addArrangedSubview(textStack) - - NSLayoutConstraint.activate([ - imageView.widthAnchor.constraint(equalToConstant: 44), - imageView.heightAnchor.constraint(equalToConstant: 44), - ]) - } - - private func configureDeveloperToolsButton() { - var configuration = UIButton.Configuration.plain() - configuration.image = UIImage(systemName: "ant") - configuration.baseForegroundColor = FireTheme.uiTertiaryInk - configuration.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) - developerToolsButton.configuration = configuration - developerToolsButton.accessibilityLabel = "开发者工具" - developerToolsButton.translatesAutoresizingMaskIntoConstraints = false - developerToolsButton.addTarget(self, action: #selector(developerToolsButtonTapped), for: .touchUpInside) - developerToolsButton.fireBindPressBounce(.compact) - view.addSubview(developerToolsButton) - NSLayoutConstraint.activate([ - developerToolsButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 4), - developerToolsButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8), - ]) - } - - private func configureFeedbackButton() { - var configuration = UIButton.Configuration.plain() - configuration.image = UIImage(systemName: "bubble.left.and.exclamationmark.bubble.right") - configuration.baseForegroundColor = FireTheme.uiTertiaryInk - configuration.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) - feedbackButton.configuration = configuration - feedbackButton.accessibilityLabel = "反馈与建议" - feedbackButton.translatesAutoresizingMaskIntoConstraints = false - feedbackButton.addTarget(self, action: #selector(feedbackButtonTapped), for: .touchUpInside) - feedbackButton.fireBindPressBounce(.compact) - view.addSubview(feedbackButton) - NSLayoutConstraint.activate([ - feedbackButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 4), - feedbackButton.trailingAnchor.constraint(equalTo: developerToolsButton.leadingAnchor, constant: -2), - ]) - } - - private func configureBottomControls() { - errorBanner.onDismiss = { [weak self] in - self?.viewModel.dismissError() - } - - phaseContainerView.translatesAutoresizingMaskIntoConstraints = false - // Hug the active phase content instead of expanding into a tall empty well. - phaseContainerView.setContentHuggingPriority(.required, for: .vertical) - phaseContainerView.setContentCompressionResistancePriority(.required, for: .vertical) - - bottomStack.axis = .vertical - bottomStack.alignment = .fill - bottomStack.spacing = 12 - bottomStack.translatesAutoresizingMaskIntoConstraints = false - bottomStack.addArrangedSubview(errorBanner) - bottomStack.addArrangedSubview(phaseContainerView) - bottomStack.setContentHuggingPriority(.required, for: .vertical) - bottomStack.setContentCompressionResistancePriority(.required, for: .vertical) - } - /// Center brand + form as one content block. Tall phones get balanced /// top/bottom breathing room without sinking the form into the lower half. private func configureRootLayout() { @@ -243,21 +152,6 @@ final class FireOnboardingViewController: UIViewController { view.bringSubviewToFront(feedbackButton) } - private func installKeyboardDismissGesture() { - let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped)) - tapGesture.cancelsTouchesInView = false - view.addGestureRecognizer(tapGesture) - } - - private func observeKeyboardNotifications() { - NotificationCenter.default.addObserver( - self, - selector: #selector(keyboardWillChangeFrame(_:)), - name: UIResponder.keyboardWillChangeFrameNotification, - object: nil - ) - } - private func bindState() { viewModel.$errorMessage .receive(on: RunLoop.main) @@ -398,809 +292,4 @@ final class FireOnboardingViewController: UIViewController { wireCredentialFormCallbacks() } - private func wireCredentialFormCallbacks() { - credentialFormView.onLoginTapped = { [weak self] identifier, password, remember in - guard let self else { return } - self.pendingIdentifier = identifier - self.pendingPassword = password - self.pendingRememberCredential = remember - self.cfRetryUsed = false - self.hasShownSecondFactor = false - self.hideErrorBanner() - self.logAuth("login tapped identifier_len=\(identifier.count) remember=\(remember)") - self.loggingInMessage = "正在准备验证…" - self.applyPhase(.loggingIn) - Task { await self.performLogin() } - } - credentialFormView.onForgotPassword = { [weak self] in - self?.presentWebViewBrowser(url: URL(string: "https://linux.do/password-reset")!) - } - credentialFormView.onExternalLogin = { [weak self] method in - self?.presentWebViewBrowser( - url: URL(string: "https://linux.do/login")!, - autoStartExternalLogin: method - ) - } - } - - private func applyPhase(_ next: FireOnboardingPhase) { - guard phase != next else { return } - - if next == .credential, phase != .credential { - Task { await viewModel.prepareLoginForm() } - } - - let previous = phase - phase = next - - if next == .loggingIn { - setLoginLoading(true) - } else if previous == .loggingIn { - setLoginLoading(false) - } - - UIView.transition( - with: phaseContainerView, - duration: 0.22, - options: [.transitionCrossDissolve] - ) { - self.installPhaseSubviews(for: next, replacing: previous) - } - } - - private func installValidatingPhaseInitial() { - phaseContainerView.addSubview(validatingView) - validatingView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - validatingView.topAnchor.constraint(equalTo: phaseContainerView.topAnchor), - validatingView.leadingAnchor.constraint(equalTo: phaseContainerView.leadingAnchor), - validatingView.trailingAnchor.constraint(equalTo: phaseContainerView.trailingAnchor), - validatingView.bottomAnchor.constraint(equalTo: phaseContainerView.bottomAnchor), - ]) - validatingView.configure( - isAnimating: true, - message: "正在校验登录态…", - showsCancel: false - ) - } - - private func installPhaseSubviews(for next: FireOnboardingPhase, replacing previous: FireOnboardingPhase) { - if previous == .loggingIn { - credentialFormView.setLoggingIn(false) - } - - validatingView.removeFromSuperview() - credentialFormView.removeFromSuperview() - - switch next { - case .validating: - phaseContainerView.addSubview(validatingView) - validatingView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - validatingView.topAnchor.constraint(equalTo: phaseContainerView.topAnchor), - validatingView.leadingAnchor.constraint(equalTo: phaseContainerView.leadingAnchor), - validatingView.trailingAnchor.constraint(equalTo: phaseContainerView.trailingAnchor), - validatingView.bottomAnchor.constraint(equalTo: phaseContainerView.bottomAnchor), - ]) - validatingView.configure( - isAnimating: true, - message: "正在校验登录态…", - showsCancel: false - ) - - case .credential: - phaseContainerView.addSubview(credentialFormView) - credentialFormView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - credentialFormView.topAnchor.constraint(equalTo: phaseContainerView.topAnchor), - credentialFormView.leadingAnchor.constraint(equalTo: phaseContainerView.leadingAnchor), - credentialFormView.trailingAnchor.constraint(equalTo: phaseContainerView.trailingAnchor), - credentialFormView.bottomAnchor.constraint(equalTo: phaseContainerView.bottomAnchor), - ]) - - case .loggingIn: - // Host-owned loading for: auto-login prep, captcha underlying wait, and post-login sync. - phaseContainerView.addSubview(validatingView) - validatingView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - validatingView.topAnchor.constraint(equalTo: phaseContainerView.topAnchor), - validatingView.leadingAnchor.constraint(equalTo: phaseContainerView.leadingAnchor), - validatingView.trailingAnchor.constraint(equalTo: phaseContainerView.trailingAnchor), - validatingView.bottomAnchor.constraint(equalTo: phaseContainerView.bottomAnchor), - ]) - refreshLoggingInChrome() - } - } - - private func refreshLoggingInChrome() { - let detail: String? - if isAutoLoginInFlight { - switch activeAutoLoginKind { - case .password: - detail = "将使用已保存的账号密码" - case let .external(method): - detail = method == .google - ? "正在安全连接 Google,通常只需几秒" - : "正在安全连接,通常只需几秒" - case .none: - detail = nil - } - } else { - detail = nil - } - validatingView.configure( - isAnimating: true, - message: loggingInMessage, - detail: detail, - // Cancel only while auto-login is waiting (prep). Captcha has its own dismiss; - // once cookie sync starts the session is already past the cancellable boundary. - showsCancel: isAutoLoginInFlight - && captchaDialog == nil - && !viewModel.isSyncingLoginSession - ) - } - - private func updateLoggingInMessage(_ message: String) { - loggingInMessage = message - guard phase == .loggingIn else { return } - refreshLoggingInChrome() - } - - private func scheduleRouteAfterStartupValidationIfNeeded() { - guard startupRouteState == .pending else { return } - startupRouteState = .routing - Task { @MainActor in - await self.routeAfterStartupValidation() - } - } - - /// Session-expired onboarding: try headless Google auto-login once, else credential form. - private func routeAfterSessionExpired() async { - guard entry == .sessionExpired else { return } - guard startupRouteState == .pending else { return } - startupRouteState = .routing - defer { - if startupRouteState == .routing { - startupRouteState = .finished - } - } - - guard !viewModel.session.readiness.canReadAuthenticatedApi else { - logAuth("routeAfterSessionExpired skipped; already authenticated") - return - } - - await viewModel.prepareLoginForm() - credentialFormView.applySavedCredential(viewModel.savedLoginCredential) - credentialFormView.applyLastLoginMethod(viewModel.lastLoginMethod) - - let kind = FireAutoLoginPlanner.autoLoginKind( - entry: .sessionExpired, - lastLoginMethod: viewModel.lastLoginMethod, - savedCredential: viewModel.savedLoginCredential - ) - - guard let kind else { - logAuth( - "session-expired auto-login ineligible method=\(String(describing: viewModel.lastLoginMethod))" - ) - startupRouteState = .finished - applyPhase(.credential) - return - } - - switch kind { - case .password: - // Mid-session recovery only auto-runs headless external methods. - startupRouteState = .finished - applyPhase(.credential) - case let .external(method): - startupRouteState = .finished - startExternalAutoLogin(method: method) - } - } - - /// After cold-start auth probe fails, optionally attempt password auto-login once - /// before falling through to the manual credential form. - private func routeAfterStartupValidation() async { - defer { - if startupRouteState == .routing { - startupRouteState = .finished - } - } - - guard !viewModel.session.readiness.canReadAuthenticatedApi else { - logAuth("routeAfterStartupValidation skipped; already authenticated") - return - } - - await viewModel.prepareLoginForm() - credentialFormView.applySavedCredential(viewModel.savedLoginCredential) - credentialFormView.applyLastLoginMethod(viewModel.lastLoginMethod) - - let kind = FireAutoLoginPlanner.coldStartKind( - entry: entry, - lastLoginMethod: viewModel.lastLoginMethod, - savedCredential: viewModel.savedLoginCredential - ) - - guard let kind else { - logAuth( - "auto-login ineligible method=\(String(describing: viewModel.lastLoginMethod)) has_credential=\(viewModel.savedLoginCredential != nil)" - ) - applyPhase(.credential) - return - } - - switch kind { - case let .password(credential): - // Mark finished before awaiting login so bindState can keep loggingIn via isAutoLoginInFlight. - startupRouteState = .finished - await startPasswordAutoLogin(credential: credential) - case let .external(method): - startupRouteState = .finished - startExternalAutoLogin(method: method) - } - } - - private func startPasswordAutoLogin(credential: FireSavedCredential) async { - guard !viewModel.session.readiness.canReadAuthenticatedApi else { return } - guard !isAutoLoginInFlight else { return } - - isAutoLoginInFlight = true - activeAutoLoginKind = .password(credential) - pendingIdentifier = credential.username - pendingPassword = credential.password - pendingRememberCredential = true - cfRetryUsed = false - hasShownSecondFactor = false - hideErrorBanner() - updateLoggingInMessage(FireAutoLoginPlanner.loadingMessage(for: .password(credential))) - applyPhase(.loggingIn) - logAuth("password auto-login begin user_len=\(credential.username.count)") - await performLogin() - } - - private func startExternalAutoLogin(method: FireExternalLoginMethod) { - guard !viewModel.session.readiness.canReadAuthenticatedApi else { return } - guard !isAutoLoginInFlight else { return } - - isAutoLoginInFlight = true - activeAutoLoginKind = .external(method) - hideErrorBanner() - updateLoggingInMessage(FireAutoLoginPlanner.loadingMessage(for: .external(method))) - applyPhase(.loggingIn) - logAuth("external auto-login begin method=\(method.rawValue)") - - let engine = FireHeadlessExternalLoginEngine(method: method, viewModel: viewModel) - headlessExternalEngine = engine - engine.onOutcome = { [weak self] outcome in - self?.handleHeadlessExternalOutcome(outcome) - } - engine.start(in: view) - } - - private func handleHeadlessExternalOutcome( - _ outcome: FireHeadlessExternalLoginEngine.Outcome - ) { - switch outcome { - case .authenticated: - guard let webView = headlessExternalEngine?.currentWebView, - case let .external(method) = activeAutoLoginKind else { - abortLoginAttempt( - message: "自动登录状态丢失,请手动登录", - source: "headless.authenticated.missing_webview" - ) - return - } - logAuth("headless external authenticated method=\(method.rawValue); syncing") - updateLoggingInMessage("正在同步登录态…") - applyPhase(.loggingIn) - Task { @MainActor in - let ok = await self.viewModel.completeLoginAwaitingResult( - from: webView, - method: method.lastLoginMethod - ) - if ok { - self.logAuth("headless external login finalized") - self.isAutoLoginInFlight = false - self.activeAutoLoginKind = nil - self.teardownHeadlessExternalEngine() - // Root coordinator swaps to home when canReadAuthenticatedApi flips. - } else { - self.abortLoginAttempt( - message: self.viewModel.errorMessage ?? "登录态同步失败,请重试", - source: "headless.authenticated.sync_failed" - ) - } - } - - case .needsUserInteraction: - logAuth("headless external needs user interaction") - updateLoggingInMessage("请完成登录") - headlessExternalEngine?.promote(from: self) - - case let .failed(message): - abortLoginAttempt(message: message, source: "headless.failed") - - case .cancelled: - abortLoginAttempt(message: "已取消自动登录", source: "headless.cancelled") - } - } - - private func teardownHeadlessExternalEngine() { - headlessExternalEngine?.teardown() - headlessExternalEngine = nil - } - - private func cancelAutoLogin(source: String) { - guard isAutoLoginInFlight else { return } - logAuth("auto-login cancelled source=\(source)") - if headlessExternalEngine != nil { - headlessExternalEngine?.cancel() - return - } - abortLoginAttempt(message: "已取消自动登录", source: source) - } - - private func showErrorBanner(_ message: String) { - errorDismissWorkItem?.cancel() - errorBanner.configure(message: message) - errorBanner.isHidden = false - - let workItem = DispatchWorkItem { [weak self] in - self?.hideErrorBanner() - } - errorDismissWorkItem = workItem - DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: workItem) - } - - private func hideErrorBanner() { - errorDismissWorkItem?.cancel() - errorDismissWorkItem = nil - errorBanner.isHidden = true - } - - private func performLogin() async { - logAuth("performLogin begin; ensuring cloudflare clearance") - let hasCloudflareClearance = await viewModel.ensureCloudflareClearance() - guard hasCloudflareClearance else { - let reason = viewModel.errorMessage.map { message in - // Reuse token scan against the last CF error string. - for token in ["cooldown", "cancelled", "in_progress", "background_suppressed", "failed", "required"] { - if message.localizedCaseInsensitiveContains(token) { - return token - } - } - return "failed" - } - abortLoginAttempt( - message: Self.loginCloudflareFailureMessage(reason: reason), - source: "ensureCloudflareClearance" - ) - return - } - - let loginCoordinator: FireWebViewLoginCoordinator - do { - loginCoordinator = try await viewModel.loginCoordinatorForDialog() - } catch { - abortLoginAttempt( - message: "网络准备失败,请重试", - source: "loginCoordinatorForDialog: \(error.localizedDescription)" - ) - return - } - - logAuth("presenting captcha dialog") - presentCaptchaDialog(loginCoordinator: loginCoordinator) - } - - private func presentCaptchaDialog(loginCoordinator: FireWebViewLoginCoordinator) { - let dialog = FireCaptchaLoginDialogController( - identifier: pendingIdentifier, - password: pendingPassword, - loginCoordinator: loginCoordinator, - onResult: { [weak self] result in - self?.handleDialogResult(result) - }, - onCancel: { [weak self] in - self?.abortLoginAttempt( - message: self?.isAutoLoginInFlight == true ? "已取消自动登录" : nil, - source: "captchaDialog.cancel" - ) - } - ) - - dialog.classifyResult = { [weak self, weak dialog] phase, status, body in - guard let self, let dialog else { return } - self.logAuth( - "login_result bridge phase=\(String(describing: phase)) status=\(status) body_len=\(body.count)" - ) - Task { - do { - let decision = try await self.viewModel.classifyLoginResult( - phase: phase, - status: status, - body: body - ) - self.logAuth("classifyLoginResult decision=\(String(describing: decision))") - dialog.dispatchResult(self.dialogResult(from: decision)) - } catch { - self.logAuth("classifyLoginResult failed: \(error.localizedDescription)") - dialog.dispatchResult( - .failure( - LoginFailureState( - kind: .unknown, - message: error.localizedDescription, - sentToEmail: nil, - currentEmail: nil - ) - ) - ) - } - } - } - - if isAutoLoginInFlight { - // Keep host loading under the sheet so auto-login feels continuous. - if let kind = activeAutoLoginKind { - updateLoggingInMessage(FireAutoLoginPlanner.captchaUnderlyingMessage(for: kind)) - } - applyPhase(.loggingIn) - } else if phase == .loggingIn { - // Manual login: captcha sheet is the wait UI over the credential form. - applyPhase(.credential) - } - - captchaDialog = dialog - refreshLoggingInChrome() - present(dialog, animated: true) - } - - private func dialogResult(from decision: WebViewLoginDecisionState) -> FireCaptchaDialogResult { - switch decision { - case .success: - return .success - case let .needSecondFactor(requirement): - return .needSecondFactor(requirement) - case .retryCloudflare: - return .retryCloudflare - case let .failure(failure): - return .failure(failure) - } - } - - private func handleDialogResult(_ result: FireCaptchaDialogResult) { - logAuth("captcha dialog result=\(String(describing: result))") - switch result { - case .success: - completeLoginFromDialog() - case let .needSecondFactor(requirement): - showSecondFactorPrompt(requirement: requirement) - case .retryCloudflare: - recoverCloudflare() - case let .failure(failure): - // Keep the typed account/password so the user can fix a typo and retry. - abortLoginAttempt( - message: failure.message ?? "登录失败", - source: "captchaDialog.failure kind=\(String(describing: failure.kind))" - ) - } - } - - private func completeLoginFromDialog() { - guard let dialog = captchaDialog else { - abortLoginAttempt(message: "登录状态丢失,请重试", source: "completeLoginFromDialog missing dialog") - return - } - let webView = dialog.webView! - logAuth("login API succeeded; capturing cookies then dismissing captcha for sync loading") - - // Switch to host loading immediately so the sheet is not the wait UI. - // Auto-login remains in-flight until sync finishes or aborts. - updateLoggingInMessage("正在同步登录态…") - applyPhase(.loggingIn) - - Task { @MainActor in - do { - let loginCoordinator = try await viewModel.loginCoordinatorForDialog() - let captured = try await loginCoordinator.captureJsLoginState( - from: webView, - identifier: pendingIdentifier - ) - self.dismissCaptchaDialog() - self.logAuth("captcha dismissed; completeMinimalLogin begin") - await self.viewModel.completeMinimalLogin( - captured: captured, - password: self.pendingPassword, - rememberCredential: self.pendingRememberCredential - ) - } catch { - self.abortLoginAttempt( - message: error.localizedDescription, - source: "completeLoginFromDialog capture/sync: \(error.localizedDescription)" - ) - } - } - } - - /// Tear down captcha + logging-in overlay and return to the credential form. - private func abortLoginAttempt(message: String?, source: String) { - logAuth("abortLoginAttempt source=\(source) message=\(message ?? "nil") auto=\(isAutoLoginInFlight)") - let wasAutoLogin = isAutoLoginInFlight - isAutoLoginInFlight = false - activeAutoLoginKind = nil - teardownHeadlessExternalEngine() - dismissCaptchaDialog() - if viewModel.session.readiness.canReadAuthenticatedApi { - setLoginLoading(false) - return - } - // Prefill remembered credentials after a failed/cancelled auto-login. - if wasAutoLogin { - credentialFormView.applySavedCredential(viewModel.savedLoginCredential) - credentialFormView.applyLastLoginMethod(viewModel.lastLoginMethod) - } - applyPhase(.credential) - if let message, !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - showErrorBanner(message) - } else if wasAutoLogin { - showErrorBanner("自动登录未完成,请手动登录") - } - } - - private func logAuth(_ message: String) { - FireAPMManager.shared.recordBreadcrumb( - level: "info", - target: "auth.login", - message: message - ) - } - - private func showSecondFactorPrompt(requirement: SecondFactorRequirementState) { - let isFirstAttempt = !hasShownSecondFactor - hasShownSecondFactor = true - - let fallbackHint: String? - if !requirement.totpEnabled && (requirement.backupEnabled || requirement.securityKeyEnabled) { - fallbackHint = "备用码或安全密钥请通过其他方式登录。" - } else { - fallbackHint = nil - } - let baseMessage = requirement.message ?? "请输入验证器中的 6 位代码" - let message = [baseMessage, fallbackHint].compactMap { $0 }.joined(separator: "\n") - - let alert = UIAlertController( - title: isFirstAttempt ? "两步验证" : "验证码错误", - message: message, - preferredStyle: .alert - ) - alert.addTextField { field in - field.placeholder = "6 位验证码" - field.keyboardType = .numberPad - field.textContentType = .oneTimeCode - } - alert.addAction(UIAlertAction(title: "确定", style: .default) { [weak self, weak alert] _ in - guard let self else { return } - guard let code = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespacesAndNewlines), - !code.isEmpty - else { - return - } - self.captchaDialog?.retryWithSecondFactor(code) - }) - alert.addAction(UIAlertAction(title: "取消", style: .cancel) { [weak self] _ in - self?.abortLoginAttempt(message: nil, source: "secondFactor.cancel") - }) - (captchaDialog ?? self).present(alert, animated: true) - } - - private func recoverCloudflare() { - guard !cfRetryUsed else { - abortLoginAttempt( - message: Self.loginCloudflareFailureMessage(reason: "failed"), - source: "recoverCloudflare already used" - ) - return - } - cfRetryUsed = true - logAuth("recoverCloudflare begin") - - Task { - guard let dialog = captchaDialog else { - abortLoginAttempt( - message: Self.loginCloudflareFailureMessage(reason: "failed"), - source: "recoverCloudflare missing dialog" - ) - return - } - do { - try await viewModel.recoverLoginCloudflareChallenge(in: dialog.webView) - } catch { - abortLoginAttempt( - message: Self.loginCloudflareFailureMessage( - reason: FireAppViewModel.cloudflareChallengeReason(from: error) - ), - source: "recoverCloudflare: \(error.localizedDescription)" - ) - return - } - logAuth("recoverCloudflare done; retrying login in dialog") - dialog.retryAfterCloudflareRecovery() - } - } - - private static func loginCloudflareFailureMessage(reason: String?) -> String { - switch reason?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { - case "cooldown": - return "网络验证暂时冷却中,可稍后重试或手动完成验证" - case "cancelled": - return "已取消网络验证,账号密码仍保留,可继续登录" - case "in_progress": - return "网络验证进行中,请稍候" - case "background_suppressed": - return "需要前台完成网络验证,请重试" - default: - return "网络验证未完成,请重试或手动验证后继续" - } - } - - private func presentWebViewBrowser( - url: URL, - autoStartExternalLogin: FireExternalLoginMethod? = nil - ) { - let browser = FireWebViewBrowserViewController( - url: url, - viewModel: viewModel, - autoStartExternalLogin: autoStartExternalLogin - ) - browser.modalPresentationStyle = .fullScreen - present(browser, animated: true) - } - - private func setLoginLoading(_ loading: Bool) { - if loading { - view.endEditing(true) - } - credentialFormView.setLoggingIn(loading) - view.isUserInteractionEnabled = !loading - } - - private func dismissCaptchaDialog() { - captchaDialog?.dismiss(animated: true) { [weak self] in - self?.captchaDialog = nil - } - } - - @objc private func developerToolsButtonTapped() { - let controller = FireHosting.controller( - rootView: FireDeveloperToolsView(viewModel: viewModel), - title: "开发者工具" - ) - // Show nav chrome only for the pushed diagnostics page; login itself stays bar-less. - navigationController?.setNavigationBarHidden(false, animated: true) - navigationController?.pushViewController(controller, animated: true) - } - - @objc private func feedbackButtonTapped() { - FireFeedbackPresenter.present( - from: self, - appViewModel: viewModel, - source: "onboarding" - ) - } - - @objc private func backgroundTapped() { - view.endEditing(true) - } - - @objc private func keyboardWillChangeFrame(_ notification: Notification) { - guard let frameEnd = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { - return - } - - let convertedFrame = view.convert(frameEnd, from: nil) - let overlap = max(0, view.bounds.maxY - convertedFrame.minY - view.safeAreaInsets.bottom) - let keyboardVisible = overlap > 0 - - if keyboardVisible { - // Pin content above the keyboard; drop vertical centering while editing. - contentCenterYConstraint?.isActive = false - contentTopConstraint?.constant = 12 - contentBottomConstraint?.constant = -(overlap + 12) - } else { - contentCenterYConstraint?.isActive = true - contentTopConstraint?.constant = 16 - contentBottomConstraint?.constant = -20 - } - - let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval - ?? 0.25 - let curve = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt - ?? UIView.AnimationOptions.curveEaseInOut.rawValue - UIView.animate( - withDuration: duration, - delay: 0, - options: UIView.AnimationOptions(rawValue: curve << 16) - ) { - self.view.layoutIfNeeded() - } - } -} - -private final class FireOnboardingErrorBannerView: UIView { - private let messageLabel = UILabel() - var onDismiss: (() -> Void)? - - override init(frame: CGRect) { - super.init(frame: frame) - configureSubviews() - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - func configure(message: String) { - messageLabel.text = message - } - - private func configureSubviews() { - backgroundColor = .tertiarySystemFill - layer.cornerRadius = FireTheme.smallCornerRadius - layer.cornerCurve = .continuous - directionalLayoutMargins = NSDirectionalEdgeInsets( - top: 12, - leading: 12, - bottom: 12, - trailing: 12 - ) - - let imageView = UIImageView(image: UIImage(systemName: "exclamationmark.triangle.fill")) - imageView.tintColor = .systemOrange - imageView.contentMode = .scaleAspectFit - imageView.setContentHuggingPriority(.required, for: .horizontal) - - messageLabel.font = UIFont.preferredFont(forTextStyle: .caption1) - messageLabel.adjustsFontForContentSizeCategory = true - messageLabel.textColor = .secondaryLabel - messageLabel.numberOfLines = 2 - - let closeButton = UIButton(type: .system) - closeButton.setImage(UIImage(systemName: "xmark"), for: .normal) - closeButton.tintColor = .secondaryLabel - closeButton.accessibilityLabel = "关闭错误提示" - closeButton.addAction(UIAction { [weak self] _ in - self?.onDismiss?() - }, for: .touchUpInside) - - let stackView = UIStackView(arrangedSubviews: [imageView, messageLabel, closeButton]) - stackView.axis = .horizontal - stackView.alignment = .center - stackView.spacing = 8 - stackView.translatesAutoresizingMaskIntoConstraints = false - - addSubview(stackView) - NSLayoutConstraint.activate([ - imageView.widthAnchor.constraint(equalToConstant: 18), - imageView.heightAnchor.constraint(equalToConstant: 18), - closeButton.widthAnchor.constraint(equalToConstant: 30), - closeButton.heightAnchor.constraint(equalToConstant: 30), - stackView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor), - stackView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor), - stackView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), - stackView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor), - ]) - } -} - -private extension UIFont { - func withOnboardingWeight(_ weight: Weight) -> UIFont { - let descriptor = fontDescriptor.addingAttributes([ - .traits: [UIFontDescriptor.TraitKey.weight: weight], - ]) - return UIFont(descriptor: descriptor, size: pointSize) - } } diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+AuthLog.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+AuthLog.swift new file mode 100644 index 00000000..4e883d9f --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+AuthLog.swift @@ -0,0 +1,11 @@ +import Foundation + +extension FireOnboardingViewController { + func logAuth(_ message: String) { + FireAPMManager.shared.recordBreadcrumb( + level: "info", + target: "auth.login", + message: message + ) + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+BottomControls.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+BottomControls.swift new file mode 100644 index 00000000..5cf8be97 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+BottomControls.swift @@ -0,0 +1,72 @@ +import SwiftUI +import UIKit + +extension FireOnboardingViewController { + func configureDeveloperToolsButton() { + var configuration = UIButton.Configuration.plain() + configuration.image = UIImage(systemName: "ant") + configuration.baseForegroundColor = FireTheme.uiTertiaryInk + configuration.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) + developerToolsButton.configuration = configuration + developerToolsButton.accessibilityLabel = "开发者工具" + developerToolsButton.translatesAutoresizingMaskIntoConstraints = false + developerToolsButton.addTarget(self, action: #selector(developerToolsButtonTapped), for: .touchUpInside) + developerToolsButton.fireBindPressBounce(.compact) + view.addSubview(developerToolsButton) + NSLayoutConstraint.activate([ + developerToolsButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 4), + developerToolsButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8), + ]) + } + func configureFeedbackButton() { + var configuration = UIButton.Configuration.plain() + configuration.image = UIImage(systemName: "bubble.left.and.exclamationmark.bubble.right") + configuration.baseForegroundColor = FireTheme.uiTertiaryInk + configuration.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) + feedbackButton.configuration = configuration + feedbackButton.accessibilityLabel = "反馈与建议" + feedbackButton.translatesAutoresizingMaskIntoConstraints = false + feedbackButton.addTarget(self, action: #selector(feedbackButtonTapped), for: .touchUpInside) + feedbackButton.fireBindPressBounce(.compact) + view.addSubview(feedbackButton) + NSLayoutConstraint.activate([ + feedbackButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 4), + feedbackButton.trailingAnchor.constraint(equalTo: developerToolsButton.leadingAnchor, constant: -2), + ]) + } + func configureBottomControls() { + errorBanner.onDismiss = { [weak self] in + self?.viewModel.dismissError() + } + + phaseContainerView.translatesAutoresizingMaskIntoConstraints = false + // Hug the active phase content instead of expanding into a tall empty well. + phaseContainerView.setContentHuggingPriority(.required, for: .vertical) + phaseContainerView.setContentCompressionResistancePriority(.required, for: .vertical) + + bottomStack.axis = .vertical + bottomStack.alignment = .fill + bottomStack.spacing = 12 + bottomStack.translatesAutoresizingMaskIntoConstraints = false + bottomStack.addArrangedSubview(errorBanner) + bottomStack.addArrangedSubview(phaseContainerView) + bottomStack.setContentHuggingPriority(.required, for: .vertical) + bottomStack.setContentCompressionResistancePriority(.required, for: .vertical) + } + @objc func developerToolsButtonTapped() { + let controller = FireHosting.controller( + rootView: FireDeveloperToolsView(viewModel: viewModel), + title: "开发者工具" + ) + // Show nav chrome only for the pushed diagnostics page; login itself stays bar-less. + navigationController?.setNavigationBarHidden(false, animated: true) + navigationController?.pushViewController(controller, animated: true) + } + @objc func feedbackButtonTapped() { + FireFeedbackPresenter.present( + from: self, + appViewModel: viewModel, + source: "onboarding" + ) + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+Brand.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+Brand.swift new file mode 100644 index 00000000..85b02de4 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+Brand.swift @@ -0,0 +1,49 @@ +import UIKit + +extension FireOnboardingViewController { + func configureBrand() { + let imageView = UIImageView(image: UIImage(systemName: "flame.fill")) + imageView.tintColor = .systemOrange + imageView.contentMode = .scaleAspectFit + + let titleLabel = UILabel() + titleLabel.text = "Fire" + titleLabel.font = UIFont.preferredFont(forTextStyle: .title1).withOnboardingWeight(.bold) + titleLabel.adjustsFontForContentSizeCategory = true + titleLabel.textColor = .label + titleLabel.textAlignment = .center + + let subtitleLabel = UILabel() + subtitleLabel.text = "LinuxDo 原生客户端" + subtitleLabel.font = UIFont.preferredFont(forTextStyle: .subheadline) + subtitleLabel.adjustsFontForContentSizeCategory = true + subtitleLabel.textColor = .secondaryLabel + subtitleLabel.textAlignment = .center + + let textStack = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel]) + textStack.axis = .vertical + textStack.alignment = .center + textStack.spacing = 4 + + brandStack.axis = .vertical + brandStack.alignment = .center + brandStack.spacing = 10 + brandStack.translatesAutoresizingMaskIntoConstraints = false + brandStack.addArrangedSubview(imageView) + brandStack.addArrangedSubview(textStack) + + NSLayoutConstraint.activate([ + imageView.widthAnchor.constraint(equalToConstant: 44), + imageView.heightAnchor.constraint(equalToConstant: 44), + ]) + } +} + +private extension UIFont { + func withOnboardingWeight(_ weight: Weight) -> UIFont { + let descriptor = fontDescriptor.addingAttributes([ + .traits: [UIFontDescriptor.TraitKey.weight: weight], + ]) + return UIFont(descriptor: descriptor, size: pointSize) + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+Captcha.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+Captcha.swift new file mode 100644 index 00000000..12717d66 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+Captcha.swift @@ -0,0 +1,134 @@ +import UIKit + +extension FireOnboardingViewController { + func presentCaptchaDialog(loginCoordinator: FireWebViewLoginCoordinator) { + let dialog = FireCaptchaLoginDialogController( + identifier: pendingIdentifier, + password: pendingPassword, + loginCoordinator: loginCoordinator, + onResult: { [weak self] result in + self?.handleDialogResult(result) + }, + onCancel: { [weak self] in + self?.abortLoginAttempt( + message: self?.isAutoLoginInFlight == true ? "已取消自动登录" : nil, + source: "captchaDialog.cancel" + ) + } + ) + + dialog.classifyResult = { [weak self, weak dialog] phase, status, body in + guard let self, let dialog else { return } + self.logAuth( + "login_result bridge phase=\(String(describing: phase)) status=\(status) body_len=\(body.count)" + ) + Task { + do { + let decision = try await self.viewModel.classifyLoginResult( + phase: phase, + status: status, + body: body + ) + self.logAuth("classifyLoginResult decision=\(String(describing: decision))") + dialog.dispatchResult(self.dialogResult(from: decision)) + } catch { + self.logAuth("classifyLoginResult failed: \(error.localizedDescription)") + dialog.dispatchResult( + .failure( + LoginFailureState( + kind: .unknown, + message: error.localizedDescription, + sentToEmail: nil, + currentEmail: nil + ) + ) + ) + } + } + } + + if isAutoLoginInFlight { + // Keep host loading under the sheet so auto-login feels continuous. + if let kind = activeAutoLoginKind { + updateLoggingInMessage(FireAutoLoginPlanner.captchaUnderlyingMessage(for: kind)) + } + applyPhase(.loggingIn) + } else if phase == .loggingIn { + // Manual login: captcha sheet is the wait UI over the credential form. + applyPhase(.credential) + } + + captchaDialog = dialog + refreshLoggingInChrome() + present(dialog, animated: true) + } + func dialogResult(from decision: WebViewLoginDecisionState) -> FireCaptchaDialogResult { + switch decision { + case .success: + return .success + case let .needSecondFactor(requirement): + return .needSecondFactor(requirement) + case .retryCloudflare: + return .retryCloudflare + case let .failure(failure): + return .failure(failure) + } + } + func handleDialogResult(_ result: FireCaptchaDialogResult) { + logAuth("captcha dialog result=\(String(describing: result))") + switch result { + case .success: + completeLoginFromDialog() + case let .needSecondFactor(requirement): + showSecondFactorPrompt(requirement: requirement) + case .retryCloudflare: + recoverCloudflare() + case let .failure(failure): + // Keep the typed account/password so the user can fix a typo and retry. + abortLoginAttempt( + message: failure.message ?? "登录失败", + source: "captchaDialog.failure kind=\(String(describing: failure.kind))" + ) + } + } + func completeLoginFromDialog() { + guard let dialog = captchaDialog else { + abortLoginAttempt(message: "登录状态丢失,请重试", source: "completeLoginFromDialog missing dialog") + return + } + let webView = dialog.webView! + logAuth("login API succeeded; capturing cookies then dismissing captcha for sync loading") + + // Switch to host loading immediately so the sheet is not the wait UI. + // Auto-login remains in-flight until sync finishes or aborts. + updateLoggingInMessage("正在同步登录态…") + applyPhase(.loggingIn) + + Task { @MainActor in + do { + let loginCoordinator = try await viewModel.loginCoordinatorForDialog() + let captured = try await loginCoordinator.captureJsLoginState( + from: webView, + identifier: pendingIdentifier + ) + self.dismissCaptchaDialog() + self.logAuth("captcha dismissed; completeMinimalLogin begin") + await self.viewModel.completeMinimalLogin( + captured: captured, + password: self.pendingPassword, + rememberCredential: self.pendingRememberCredential + ) + } catch { + self.abortLoginAttempt( + message: error.localizedDescription, + source: "completeLoginFromDialog capture/sync: \(error.localizedDescription)" + ) + } + } + } + func dismissCaptchaDialog() { + captchaDialog?.dismiss(animated: true) { [weak self] in + self?.captchaDialog = nil + } + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+CloudflareRecovery.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+CloudflareRecovery.swift new file mode 100644 index 00000000..6760e31c --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+CloudflareRecovery.swift @@ -0,0 +1,64 @@ +import UIKit + +extension FireOnboardingViewController { + func recoverCloudflare() { + guard !cfRetryUsed else { + abortLoginAttempt( + message: Self.loginCloudflareFailureMessage(reason: "failed"), + source: "recoverCloudflare already used" + ) + return + } + cfRetryUsed = true + logAuth("recoverCloudflare begin") + + Task { + guard let dialog = captchaDialog else { + abortLoginAttempt( + message: Self.loginCloudflareFailureMessage(reason: "failed"), + source: "recoverCloudflare missing dialog" + ) + return + } + do { + try await viewModel.recoverLoginCloudflareChallenge(in: dialog.webView) + } catch { + abortLoginAttempt( + message: Self.loginCloudflareFailureMessage( + reason: FireAppViewModel.cloudflareChallengeReason(from: error) + ), + source: "recoverCloudflare: \(error.localizedDescription)" + ) + return + } + logAuth("recoverCloudflare done; retrying login in dialog") + dialog.retryAfterCloudflareRecovery() + } + } + static func loginCloudflareFailureMessage(reason: String?) -> String { + switch reason?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { + case "cooldown": + return "网络验证暂时冷却中,可稍后重试或手动完成验证" + case "cancelled": + return "已取消网络验证,账号密码仍保留,可继续登录" + case "in_progress": + return "网络验证进行中,请稍候" + case "background_suppressed": + return "需要前台完成网络验证,请重试" + default: + return "网络验证未完成,请重试或手动验证后继续" + } + } + func presentWebViewBrowser( + url: URL, + autoStartExternalLogin: FireExternalLoginMethod? = nil + ) { + let browser = FireWebViewBrowserViewController( + url: url, + viewModel: viewModel, + autoStartExternalLogin: autoStartExternalLogin + ) + browser.modalPresentationStyle = .fullScreen + present(browser, animated: true) + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+ExternalAutoLogin.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+ExternalAutoLogin.swift new file mode 100644 index 00000000..025ed5b5 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+ExternalAutoLogin.swift @@ -0,0 +1,82 @@ +import UIKit + +extension FireOnboardingViewController { + func startExternalAutoLogin(method: FireExternalLoginMethod) { + guard !viewModel.session.readiness.canReadAuthenticatedApi else { return } + guard !isAutoLoginInFlight else { return } + + isAutoLoginInFlight = true + activeAutoLoginKind = .external(method) + hideErrorBanner() + updateLoggingInMessage(FireAutoLoginPlanner.loadingMessage(for: .external(method))) + applyPhase(.loggingIn) + logAuth("external auto-login begin method=\(method.rawValue)") + + let engine = FireHeadlessExternalLoginEngine(method: method, viewModel: viewModel) + headlessExternalEngine = engine + engine.onOutcome = { [weak self] outcome in + self?.handleHeadlessExternalOutcome(outcome) + } + engine.start(in: view) + } + func handleHeadlessExternalOutcome( + _ outcome: FireHeadlessExternalLoginEngine.Outcome + ) { + switch outcome { + case .authenticated: + guard let webView = headlessExternalEngine?.currentWebView, + case let .external(method) = activeAutoLoginKind else { + abortLoginAttempt( + message: "自动登录状态丢失,请手动登录", + source: "headless.authenticated.missing_webview" + ) + return + } + logAuth("headless external authenticated method=\(method.rawValue); syncing") + updateLoggingInMessage("正在同步登录态…") + applyPhase(.loggingIn) + Task { @MainActor in + let ok = await self.viewModel.completeLoginAwaitingResult( + from: webView, + method: method.lastLoginMethod + ) + if ok { + self.logAuth("headless external login finalized") + self.isAutoLoginInFlight = false + self.activeAutoLoginKind = nil + self.teardownHeadlessExternalEngine() + // Root coordinator swaps to home when canReadAuthenticatedApi flips. + } else { + self.abortLoginAttempt( + message: self.viewModel.errorMessage ?? "登录态同步失败,请重试", + source: "headless.authenticated.sync_failed" + ) + } + } + + case .needsUserInteraction: + logAuth("headless external needs user interaction") + updateLoggingInMessage("请完成登录") + headlessExternalEngine?.promote(from: self) + + case let .failed(message): + abortLoginAttempt(message: message, source: "headless.failed") + + case .cancelled: + abortLoginAttempt(message: "已取消自动登录", source: "headless.cancelled") + } + } + func teardownHeadlessExternalEngine() { + headlessExternalEngine?.teardown() + headlessExternalEngine = nil + } + func cancelAutoLogin(source: String) { + guard isAutoLoginInFlight else { return } + logAuth("auto-login cancelled source=\(source)") + if headlessExternalEngine != nil { + headlessExternalEngine?.cancel() + return + } + abortLoginAttempt(message: "已取消自动登录", source: source) + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+Keyboard.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+Keyboard.swift new file mode 100644 index 00000000..ea4417c7 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+Keyboard.swift @@ -0,0 +1,52 @@ +import UIKit + +extension FireOnboardingViewController { + func installKeyboardDismissGesture() { + let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped)) + tapGesture.cancelsTouchesInView = false + view.addGestureRecognizer(tapGesture) + } + func observeKeyboardNotifications() { + NotificationCenter.default.addObserver( + self, + selector: #selector(keyboardWillChangeFrame(_:)), + name: UIResponder.keyboardWillChangeFrameNotification, + object: nil + ) + } + @objc func backgroundTapped() { + view.endEditing(true) + } + @objc func keyboardWillChangeFrame(_ notification: Notification) { + guard let frameEnd = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { + return + } + + let convertedFrame = view.convert(frameEnd, from: nil) + let overlap = max(0, view.bounds.maxY - convertedFrame.minY - view.safeAreaInsets.bottom) + let keyboardVisible = overlap > 0 + + if keyboardVisible { + // Pin content above the keyboard; drop vertical centering while editing. + contentCenterYConstraint?.isActive = false + contentTopConstraint?.constant = 12 + contentBottomConstraint?.constant = -(overlap + 12) + } else { + contentCenterYConstraint?.isActive = true + contentTopConstraint?.constant = 16 + contentBottomConstraint?.constant = -20 + } + + let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval + ?? 0.25 + let curve = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt + ?? UIView.AnimationOptions.curveEaseInOut.rawValue + UIView.animate( + withDuration: duration, + delay: 0, + options: UIView.AnimationOptions(rawValue: curve << 16) + ) { + self.view.layoutIfNeeded() + } + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+LoginActions.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+LoginActions.swift new file mode 100644 index 00000000..ba222148 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+LoginActions.swift @@ -0,0 +1,93 @@ +import UIKit + +extension FireOnboardingViewController { + func wireCredentialFormCallbacks() { + credentialFormView.onLoginTapped = { [weak self] identifier, password, remember in + guard let self else { return } + self.pendingIdentifier = identifier + self.pendingPassword = password + self.pendingRememberCredential = remember + self.cfRetryUsed = false + self.hasShownSecondFactor = false + self.hideErrorBanner() + self.logAuth("login tapped identifier_len=\(identifier.count) remember=\(remember)") + self.loggingInMessage = "正在准备验证…" + self.applyPhase(.loggingIn) + Task { await self.performLogin() } + } + credentialFormView.onForgotPassword = { [weak self] in + self?.presentWebViewBrowser(url: URL(string: "https://linux.do/password-reset")!) + } + credentialFormView.onExternalLogin = { [weak self] method in + self?.presentWebViewBrowser( + url: URL(string: "https://linux.do/login")!, + autoStartExternalLogin: method + ) + } + } + func performLogin() async { + logAuth("performLogin begin; ensuring cloudflare clearance") + let hasCloudflareClearance = await viewModel.ensureCloudflareClearance() + guard hasCloudflareClearance else { + let reason = viewModel.errorMessage.map { message in + // Reuse token scan against the last CF error string. + for token in ["cooldown", "cancelled", "in_progress", "background_suppressed", "failed", "required"] { + if message.localizedCaseInsensitiveContains(token) { + return token + } + } + return "failed" + } + abortLoginAttempt( + message: Self.loginCloudflareFailureMessage(reason: reason), + source: "ensureCloudflareClearance" + ) + return + } + + let loginCoordinator: FireWebViewLoginCoordinator + do { + loginCoordinator = try await viewModel.loginCoordinatorForDialog() + } catch { + abortLoginAttempt( + message: "网络准备失败,请重试", + source: "loginCoordinatorForDialog: \(error.localizedDescription)" + ) + return + } + + logAuth("presenting captcha dialog") + presentCaptchaDialog(loginCoordinator: loginCoordinator) + } + /// Tear down captcha + logging-in overlay and return to the credential form. + func abortLoginAttempt(message: String?, source: String) { + logAuth("abortLoginAttempt source=\(source) message=\(message ?? "nil") auto=\(isAutoLoginInFlight)") + let wasAutoLogin = isAutoLoginInFlight + isAutoLoginInFlight = false + activeAutoLoginKind = nil + teardownHeadlessExternalEngine() + dismissCaptchaDialog() + if viewModel.session.readiness.canReadAuthenticatedApi { + setLoginLoading(false) + return + } + // Prefill remembered credentials after a failed/cancelled auto-login. + if wasAutoLogin { + credentialFormView.applySavedCredential(viewModel.savedLoginCredential) + credentialFormView.applyLastLoginMethod(viewModel.lastLoginMethod) + } + applyPhase(.credential) + if let message, !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + showErrorBanner(message) + } else if wasAutoLogin { + showErrorBanner("自动登录未完成,请手动登录") + } + } + func setLoginLoading(_ loading: Bool) { + if loading { + view.endEditing(true) + } + credentialFormView.setLoggingIn(loading) + view.isUserInteractionEnabled = !loading + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+PasswordAutoLogin.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+PasswordAutoLogin.swift new file mode 100644 index 00000000..7fe8dfa3 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+PasswordAutoLogin.swift @@ -0,0 +1,21 @@ +import UIKit + +extension FireOnboardingViewController { + func startPasswordAutoLogin(credential: FireSavedCredential) async { + guard !viewModel.session.readiness.canReadAuthenticatedApi else { return } + guard !isAutoLoginInFlight else { return } + + isAutoLoginInFlight = true + activeAutoLoginKind = .password(credential) + pendingIdentifier = credential.username + pendingPassword = credential.password + pendingRememberCredential = true + cfRetryUsed = false + hasShownSecondFactor = false + hideErrorBanner() + updateLoggingInMessage(FireAutoLoginPlanner.loadingMessage(for: .password(credential))) + applyPhase(.loggingIn) + logAuth("password auto-login begin user_len=\(credential.username.count)") + await performLogin() + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+PhaseRendering.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+PhaseRendering.swift new file mode 100644 index 00000000..b91df261 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+PhaseRendering.swift @@ -0,0 +1,122 @@ +import UIKit + +extension FireOnboardingViewController { + func applyPhase(_ next: FireOnboardingPhase) { + guard phase != next else { return } + + if next == .credential, phase != .credential { + Task { await viewModel.prepareLoginForm() } + } + + let previous = phase + phase = next + + if next == .loggingIn { + setLoginLoading(true) + } else if previous == .loggingIn { + setLoginLoading(false) + } + + UIView.transition( + with: phaseContainerView, + duration: 0.22, + options: [.transitionCrossDissolve] + ) { + self.installPhaseSubviews(for: next, replacing: previous) + } + } + func installValidatingPhaseInitial() { + phaseContainerView.addSubview(validatingView) + validatingView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + validatingView.topAnchor.constraint(equalTo: phaseContainerView.topAnchor), + validatingView.leadingAnchor.constraint(equalTo: phaseContainerView.leadingAnchor), + validatingView.trailingAnchor.constraint(equalTo: phaseContainerView.trailingAnchor), + validatingView.bottomAnchor.constraint(equalTo: phaseContainerView.bottomAnchor), + ]) + validatingView.configure( + isAnimating: true, + message: "正在校验登录态…", + showsCancel: false + ) + } + func installPhaseSubviews(for next: FireOnboardingPhase, replacing previous: FireOnboardingPhase) { + if previous == .loggingIn { + credentialFormView.setLoggingIn(false) + } + + validatingView.removeFromSuperview() + credentialFormView.removeFromSuperview() + + switch next { + case .validating: + phaseContainerView.addSubview(validatingView) + validatingView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + validatingView.topAnchor.constraint(equalTo: phaseContainerView.topAnchor), + validatingView.leadingAnchor.constraint(equalTo: phaseContainerView.leadingAnchor), + validatingView.trailingAnchor.constraint(equalTo: phaseContainerView.trailingAnchor), + validatingView.bottomAnchor.constraint(equalTo: phaseContainerView.bottomAnchor), + ]) + validatingView.configure( + isAnimating: true, + message: "正在校验登录态…", + showsCancel: false + ) + + case .credential: + phaseContainerView.addSubview(credentialFormView) + credentialFormView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + credentialFormView.topAnchor.constraint(equalTo: phaseContainerView.topAnchor), + credentialFormView.leadingAnchor.constraint(equalTo: phaseContainerView.leadingAnchor), + credentialFormView.trailingAnchor.constraint(equalTo: phaseContainerView.trailingAnchor), + credentialFormView.bottomAnchor.constraint(equalTo: phaseContainerView.bottomAnchor), + ]) + + case .loggingIn: + // Host-owned loading for: auto-login prep, captcha underlying wait, and post-login sync. + phaseContainerView.addSubview(validatingView) + validatingView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + validatingView.topAnchor.constraint(equalTo: phaseContainerView.topAnchor), + validatingView.leadingAnchor.constraint(equalTo: phaseContainerView.leadingAnchor), + validatingView.trailingAnchor.constraint(equalTo: phaseContainerView.trailingAnchor), + validatingView.bottomAnchor.constraint(equalTo: phaseContainerView.bottomAnchor), + ]) + refreshLoggingInChrome() + } + } + func refreshLoggingInChrome() { + let detail: String? + if isAutoLoginInFlight { + switch activeAutoLoginKind { + case .password: + detail = "将使用已保存的账号密码" + case let .external(method): + detail = method == .google + ? "正在安全连接 Google,通常只需几秒" + : "正在安全连接,通常只需几秒" + case .none: + detail = nil + } + } else { + detail = nil + } + validatingView.configure( + isAnimating: true, + message: loggingInMessage, + detail: detail, + // Cancel only while auto-login is waiting (prep). Captcha has its own dismiss; + // once cookie sync starts the session is already past the cancellable boundary. + showsCancel: isAutoLoginInFlight + && captchaDialog == nil + && !viewModel.isSyncingLoginSession + ) + } + func updateLoggingInMessage(_ message: String) { + loggingInMessage = message + guard phase == .loggingIn else { return } + refreshLoggingInChrome() + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+SecondFactor.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+SecondFactor.swift new file mode 100644 index 00000000..6d7b4df4 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+SecondFactor.swift @@ -0,0 +1,41 @@ +import UIKit + +extension FireOnboardingViewController { + func showSecondFactorPrompt(requirement: SecondFactorRequirementState) { + let isFirstAttempt = !hasShownSecondFactor + hasShownSecondFactor = true + + let fallbackHint: String? + if !requirement.totpEnabled && (requirement.backupEnabled || requirement.securityKeyEnabled) { + fallbackHint = "备用码或安全密钥请通过其他方式登录。" + } else { + fallbackHint = nil + } + let baseMessage = requirement.message ?? "请输入验证器中的 6 位代码" + let message = [baseMessage, fallbackHint].compactMap { $0 }.joined(separator: "\n") + + let alert = UIAlertController( + title: isFirstAttempt ? "两步验证" : "验证码错误", + message: message, + preferredStyle: .alert + ) + alert.addTextField { field in + field.placeholder = "6 位验证码" + field.keyboardType = .numberPad + field.textContentType = .oneTimeCode + } + alert.addAction(UIAlertAction(title: "确定", style: .default) { [weak self, weak alert] _ in + guard let self else { return } + guard let code = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespacesAndNewlines), + !code.isEmpty + else { + return + } + self.captchaDialog?.retryWithSecondFactor(code) + }) + alert.addAction(UIAlertAction(title: "取消", style: .cancel) { [weak self] _ in + self?.abortLoginAttempt(message: nil, source: "secondFactor.cancel") + }) + (captchaDialog ?? self).present(alert, animated: true) + } +} diff --git a/apps/ios-app/App/Views/Other/FireOnboardingViewController+StartupRouting.swift b/apps/ios-app/App/Views/Other/FireOnboardingViewController+StartupRouting.swift new file mode 100644 index 00000000..108f55cc --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireOnboardingViewController+StartupRouting.swift @@ -0,0 +1,98 @@ +import UIKit + +extension FireOnboardingViewController { + func scheduleRouteAfterStartupValidationIfNeeded() { + guard startupRouteState == .pending else { return } + startupRouteState = .routing + Task { @MainActor in + await self.routeAfterStartupValidation() + } + } + /// Session-expired onboarding: try headless Google auto-login once, else credential form. + func routeAfterSessionExpired() async { + guard entry == .sessionExpired else { return } + guard startupRouteState == .pending else { return } + startupRouteState = .routing + defer { + if startupRouteState == .routing { + startupRouteState = .finished + } + } + + guard !viewModel.session.readiness.canReadAuthenticatedApi else { + logAuth("routeAfterSessionExpired skipped; already authenticated") + return + } + + await viewModel.prepareLoginForm() + credentialFormView.applySavedCredential(viewModel.savedLoginCredential) + credentialFormView.applyLastLoginMethod(viewModel.lastLoginMethod) + + let kind = FireAutoLoginPlanner.autoLoginKind( + entry: .sessionExpired, + lastLoginMethod: viewModel.lastLoginMethod, + savedCredential: viewModel.savedLoginCredential + ) + + guard let kind else { + logAuth( + "session-expired auto-login ineligible method=\(String(describing: viewModel.lastLoginMethod))" + ) + startupRouteState = .finished + applyPhase(.credential) + return + } + + switch kind { + case .password: + // Mid-session recovery only auto-runs headless external methods. + startupRouteState = .finished + applyPhase(.credential) + case let .external(method): + startupRouteState = .finished + startExternalAutoLogin(method: method) + } + } + /// After cold-start auth probe fails, optionally attempt password auto-login once + /// before falling through to the manual credential form. + func routeAfterStartupValidation() async { + defer { + if startupRouteState == .routing { + startupRouteState = .finished + } + } + + guard !viewModel.session.readiness.canReadAuthenticatedApi else { + logAuth("routeAfterStartupValidation skipped; already authenticated") + return + } + + await viewModel.prepareLoginForm() + credentialFormView.applySavedCredential(viewModel.savedLoginCredential) + credentialFormView.applyLastLoginMethod(viewModel.lastLoginMethod) + + let kind = FireAutoLoginPlanner.coldStartKind( + entry: entry, + lastLoginMethod: viewModel.lastLoginMethod, + savedCredential: viewModel.savedLoginCredential + ) + + guard let kind else { + logAuth( + "auto-login ineligible method=\(String(describing: viewModel.lastLoginMethod)) has_credential=\(viewModel.savedLoginCredential != nil)" + ) + applyPhase(.credential) + return + } + + switch kind { + case let .password(credential): + // Mark finished before awaiting login so bindState can keep loggingIn via isAutoLoginInFlight. + startupRouteState = .finished + await startPasswordAutoLogin(credential: credential) + case let .external(method): + startupRouteState = .finished + startExternalAutoLogin(method: method) + } + } +} diff --git a/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Actions.swift b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Actions.swift new file mode 100644 index 00000000..a83bb9f6 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Actions.swift @@ -0,0 +1,157 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireReadHistoryViewController { + func contextMenuConfiguration( + for item: FireReadHistoryCollectionItem + ) -> UIContextMenuConfiguration? { + guard case let .topic(topicID) = item, + let row = historyViewModel.row(for: topicID) + else { + return nil + } + let shareURL = row.fireTopicURL(baseURL: baseURLString) + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in + UIMenu(children: self?.topicMenuActions(row: row, shareURL: shareURL) ?? []) + } + } + + func topicMenuActions( + row: FireTopicRowPresentation, + shareURL: URL + ) -> [UIAction] { + [ + UIAction(title: "打开话题", image: UIImage(systemName: "arrow.up.right")) { [weak self] _ in + self?.presentRoute(.topic(row: row, postNumber: row.topic.lastReadPostNumber)) + }, + UIAction( + title: row.topic.bookmarkId == nil ? "添加书签" : "编辑书签", + image: UIImage(systemName: row.topic.bookmarkId == nil ? "bookmark" : "bookmark.fill") + ) { [weak self] _ in + self?.presentBookmarkEditor(for: row) + }, + UIAction(title: "分享话题", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in + self?.presentShareSheet(url: shareURL) + }, + UIAction(title: "复制链接", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in + UIPasteboard.general.string = shareURL.absoluteString + self?.showToast("已复制链接", style: .success) + }, + UIAction(title: "静音话题", image: UIImage(systemName: "bell.slash")) { [weak self] _ in + self?.muteTopicFromAction(row) + }, + ] + } + + func presentBookmarkEditor(for row: FireTopicRowPresentation) { + let context = row.fireBookmarkEditorContext() + let recoveryOriginURL = row.fireTopicURL(baseURL: baseURLString) + let rootView = FireBookmarkEditorSheet( + context: context, + onSave: { [weak self] name, reminderAt in + try await self?.saveBookmark( + context: context, + name: name, + reminderAt: reminderAt, + recoveryOriginURL: recoveryOriginURL + ) + }, + onDelete: context.bookmarkID.map { bookmarkID in + { [weak self] in + try await self?.deleteBookmark( + bookmarkID: bookmarkID, + recoveryOriginURL: recoveryOriginURL, + showSuccessToast: false + ) + } + } + ) + let controller = UIHostingController(rootView: rootView) + if let sheet = controller.sheetPresentationController { + sheet.detents = [.medium(), .large()] + sheet.prefersGrabberVisible = true + } + present(controller, animated: true) + } + + func saveBookmark( + context: FireBookmarkEditorContext, + name: String?, + reminderAt: String?, + recoveryOriginURL: URL + ) async throws { + if let bookmarkID = context.bookmarkID { + try await appViewModel.topicInteraction.updateBookmark( + bookmarkID: bookmarkID, + name: name, + reminderAt: reminderAt, + recoveryOriginURL: recoveryOriginURL + ) + } else { + _ = try await appViewModel.topicInteraction.createBookmark( + bookmarkableID: context.bookmarkableID, + bookmarkableType: context.bookmarkableType, + name: name, + reminderAt: reminderAt, + recoveryOriginURL: recoveryOriginURL + ) + } + await historyViewModel.refresh() + } + + func deleteBookmarkFromAction(for row: FireTopicRowPresentation) { + guard let bookmarkID = row.topic.bookmarkId else { return } + let recoveryOriginURL = row.fireTopicURL(baseURL: baseURLString) + loadTask = Task { [weak self] in + do { + try await self?.deleteBookmark( + bookmarkID: bookmarkID, + recoveryOriginURL: recoveryOriginURL, + showSuccessToast: true + ) + } catch { + self?.historyViewModel.reportError(error.localizedDescription) + self?.showToast(error.localizedDescription, style: .error) + } + } + } + + func deleteBookmark( + bookmarkID: UInt64, + recoveryOriginURL: URL, + showSuccessToast: Bool + ) async throws { + try await appViewModel.topicInteraction.deleteBookmark( + bookmarkID: bookmarkID, + recoveryOriginURL: recoveryOriginURL + ) + await historyViewModel.refresh() + if showSuccessToast { + showToast("已删除书签", style: .success) + } + } + + func muteTopicFromAction(_ row: FireTopicRowPresentation) { + loadTask = Task { [weak self] in + do { + try await self?.appViewModel.topicInteraction.setTopicNotificationLevel( + topicID: row.topic.id, + notificationLevel: FireTopicNotificationLevelOption.muted.rawValue, + recoveryOriginURL: row.fireTopicURL(baseURL: self?.baseURLString ?? "https://linux.do") + ) + self?.showToast("已静音话题", style: .success) + } catch { + self?.showToast(error.localizedDescription, style: .error) + } + } + } + + func showToast(_ message: String, style: FireTopicListToastView.Style) { + toastDismissTask?.cancel() + toastView?.removeFromSuperview() + toastView = nil + FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) + } +} diff --git a/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Feed.swift b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Feed.swift new file mode 100644 index 00000000..5413ce51 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Feed.swift @@ -0,0 +1,154 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireReadHistoryViewController { + var baseURLString: String { + let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? "https://linux.do" : trimmed + } + + var contentVersion: ContentVersion { + ContentVersion( + rows: historyViewModel.rows, + nextPage: historyViewModel.nextPage, + isLoading: historyViewModel.isLoading, + isLoadingMore: historyViewModel.isLoadingMore, + hasLoadedOnce: historyViewModel.hasLoadedOnce, + errorMessage: historyViewModel.errorMessage + ) + } + + func render() { + let sections = makeSections() + var tokens: [FireReadHistoryCollectionItem: AnyHashable] = [:] + tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) + for section in sections { + for item in section.items { + tokens[item] = itemContentToken(for: item) + } + } + listController.setSections( + sections, + contentVersion: contentVersion, + itemContentTokens: tokens, + animatingDifferences: true + ) + } + + func makeSections() + -> [FireListSectionModel] + { + var items: [FireReadHistoryCollectionItem] = [] + + if let errorMessage = historyViewModel.errorMessage, + historyViewModel.hasLoadedOnce { + items.append(.inlineErrorBanner(errorMessage)) + } + + if !historyViewModel.hasLoadedOnce { + if let errorMessage = historyViewModel.errorMessage { + items.append(.blockingError(errorMessage)) + } else { + items.append(.loading) + } + } else if historyViewModel.rows.isEmpty { + items.append(.empty) + } else { + items.append(contentsOf: historyViewModel.rows.map { + .topic($0.topic.id) + }) + + if historyViewModel.isLoadingMore { + items.append(.loadingMore) + } + } + + return [.init(id: .content, items: items)] + } + + func cell( + collectionView: UICollectionView, + indexPath: IndexPath, + item: FireReadHistoryCollectionItem + ) -> UICollectionViewCell { + switch item { + case .blockingError, .loading, .empty, .loadingMore: + return collectionView.dequeueConfiguredReusableCell( + using: stateCellRegistration, + for: indexPath, + item: item + ) + case .inlineErrorBanner: + return collectionView.dequeueConfiguredReusableCell( + using: bannerCellRegistration, + for: indexPath, + item: item + ) + case .topic: + return collectionView.dequeueConfiguredReusableCell( + using: topicCellRegistration, + for: indexPath, + item: item + ) + } + } + + func itemContentToken(for item: FireReadHistoryCollectionItem) -> AnyHashable { + switch item { + case let .blockingError(message), let .inlineErrorBanner(message): + return AnyHashable(message) + case .loading: + return AnyHashable(historyViewModel.isLoading) + case .empty: + return AnyHashable(historyViewModel.hasLoadedOnce) + case let .topic(topicID): + guard let row = historyViewModel.row(for: topicID) else { + return AnyHashable("missing|\(topicID)") + } + return AnyHashable(topicRowContentToken(row)) + case .loadingMore: + return AnyHashable(historyViewModel.isLoadingMore) + } + } + + func topicRowContentToken(_ row: FireTopicRowPresentation) -> String { + let topic = row.topic + let category = appViewModel.categoryPresentation(for: topic.categoryId) + var parts: [String] = [] + parts.reserveCapacity(31) + parts.append(String(topic.id)) + parts.append(topic.title) + parts.append(topic.slug) + parts.append(String(topic.postsCount)) + parts.append(String(topic.replyCount)) + parts.append(String(topic.views)) + parts.append(String(topic.likeCount)) + parts.append(topic.excerpt ?? "") + parts.append(topic.createdAt ?? "") + parts.append(topic.lastPostedAt ?? "") + parts.append(topic.lastPosterUsername ?? "") + parts.append(topic.categoryId.map(String.init) ?? "") + parts.append(String(topic.pinned)) + parts.append(String(topic.closed)) + parts.append(String(topic.archived)) + parts.append(String(topic.unseen)) + parts.append(String(topic.unreadPosts)) + parts.append(String(topic.newPosts)) + parts.append(topic.lastReadPostNumber.map(String.init) ?? "") + parts.append(String(topic.highestPostNumber)) + parts.append(topic.bookmarkedPostNumber.map(String.init) ?? "") + parts.append(topic.bookmarkId.map(String.init) ?? "") + parts.append(topic.bookmarkName ?? "") + parts.append(topic.bookmarkReminderAt ?? "") + parts.append(topic.bookmarkableType ?? "") + parts.append(row.excerptText ?? "") + parts.append(row.originalPosterUsername ?? "") + parts.append(row.originalPosterAvatarTemplate ?? "") + parts.append(row.tagNames.joined(separator: ",")) + parts.append(row.statusLabels.joined(separator: ",")) + parts.append(category.map { "\($0.id)|\($0.displayName)|\($0.colorHex ?? "")" } ?? "") + return parts.joined(separator: "\u{1F}") + } +} diff --git a/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Pagination.swift b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Pagination.swift new file mode 100644 index 00000000..81f2fc83 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Pagination.swift @@ -0,0 +1,18 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireReadHistoryViewController { + func handleVisibleItemsChanged(_ items: [FireReadHistoryCollectionItem]) { + loadMoreIfNeeded(from: items) + } + + func loadMoreIfNeeded(from items: [FireReadHistoryCollectionItem]) { + guard let lastTopicID = historyViewModel.lastTopicID else { return } + guard items.contains(.topic(lastTopicID)) || items.contains(.loadingMore) else { return } + loadTask = Task { [weak self] in + await self?.historyViewModel.loadMoreIfNeeded(currentTopicID: lastTopicID) + } + } +} diff --git a/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Routing.swift b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Routing.swift new file mode 100644 index 00000000..ca89f288 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Routing.swift @@ -0,0 +1,50 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireReadHistoryViewController { + func updateTopicRoutePresenter(_ presenter: FireTopicRoutePresenter) { + topicRoutePresenter = presenter + } + + func canSelect(_ item: FireReadHistoryCollectionItem) -> Bool { + if case .topic = item { + return true + } + return false + } + + func handleSelection(_ item: FireReadHistoryCollectionItem) { + guard case let .topic(topicID) = item, + let row = historyViewModel.row(for: topicID) else { return } + presentRoute(.topic(row: row, postNumber: row.topic.lastReadPostNumber)) + } + + func presentRoute(_ route: FireAppRoute) { + if topicRoutePresenter.present(route) { + return + } + if route.presentsAsSecondaryPage { + FireAppRouteControllerFactory.presentSecondaryRoute( + route, + viewModel: appViewModel, + topicDetailStore: topicDetailStore + ) + } + } + + func presentShareSheet(url: URL) { + let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) + if let popover = controller.popoverPresentationController { + popover.sourceView = view + popover.sourceRect = CGRect( + x: view.bounds.midX, + y: view.safeAreaInsets.top + 24, + width: 1, + height: 1 + ) + } + present(controller, animated: true) + } +} diff --git a/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Setup.swift b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Setup.swift new file mode 100644 index 00000000..956fd212 --- /dev/null +++ b/apps/ios-app/App/Views/Other/FireReadHistoryViewController+Setup.swift @@ -0,0 +1,48 @@ +import Combine +import SwiftUI +import UIKit + +@MainActor +extension FireReadHistoryViewController { + func configureListController() { + listController.updateCellProvider { [weak self] collectionView, indexPath, item in + guard let self else { + return UICollectionViewCell() + } + return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) + } + listController.updateContextMenuConfigurationProvider { [weak self] item in + self?.contextMenuConfiguration(for: item) + } + } + + func prepareCellRegistrations() { + _ = stateCellRegistration + _ = bannerCellRegistration + _ = topicCellRegistration + } + + func installListController() { + addChild(listController) + view.addSubview(listController.view) + listController.view.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + listController.view.topAnchor.constraint(equalTo: view.topAnchor), + listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + listController.didMove(toParent: self) + } + + func bindViewModel() { + historyViewModel.objectWillChange + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + DispatchQueue.main.async { + self?.render() + } + } + .store(in: &cancellables) + } +} diff --git a/apps/ios-app/App/Views/Other/FireReadHistoryViewController.swift b/apps/ios-app/App/Views/Other/FireReadHistoryViewController.swift index 29f83264..634f147f 100644 --- a/apps/ios-app/App/Views/Other/FireReadHistoryViewController.swift +++ b/apps/ios-app/App/Views/Other/FireReadHistoryViewController.swift @@ -3,8 +3,8 @@ import SwiftUI import UIKit struct FireReadHistoryControllerHost: UIViewControllerRepresentable { - @Environment(\.fireTopicRoutePresenter) private var topicRoutePresenter - @EnvironmentObject private var topicDetailStore: FireTopicDetailStore + @Environment(\.fireTopicRoutePresenter) var topicRoutePresenter + @EnvironmentObject var topicDetailStore: FireTopicDetailStore let viewModel: FireAppViewModel @@ -26,7 +26,7 @@ struct FireReadHistoryControllerHost: UIViewControllerRepresentable { @MainActor final class FireReadHistoryViewController: UIViewController { - private struct ContentVersion: Hashable { + struct ContentVersion: Hashable { let rows: [FireTopicRowPresentation] let nextPage: UInt32? let isLoading: Bool @@ -35,18 +35,18 @@ final class FireReadHistoryViewController: UIViewController { let errorMessage: String? } - private let appViewModel: FireAppViewModel - private let topicDetailStore: FireTopicDetailStore - private let historyViewModel: FireReadHistoryViewModel - private let controllerReference: FireReadHistoryControllerReference - private let listController: FireListViewController - private var topicRoutePresenter: FireTopicRoutePresenter - private var cancellables: Set = [] - private var loadTask: Task? - private var toastDismissTask: Task? - private weak var toastView: UIView? + let appViewModel: FireAppViewModel + let topicDetailStore: FireTopicDetailStore + let historyViewModel: FireReadHistoryViewModel + let controllerReference: FireReadHistoryControllerReference + let listController: FireListViewController + var topicRoutePresenter: FireTopicRoutePresenter + var cancellables: Set = [] + var loadTask: Task? + var toastDismissTask: Task? + weak var toastView: UIView? - private lazy var stateCellRegistration = UICollectionView.CellRegistration< + lazy var stateCellRegistration = UICollectionView.CellRegistration< FireTopicListStateCell, FireReadHistoryCollectionItem > { [weak self] cell, _, item in @@ -73,7 +73,7 @@ final class FireReadHistoryViewController: UIViewController { } } - private lazy var bannerCellRegistration = UICollectionView.CellRegistration< + lazy var bannerCellRegistration = UICollectionView.CellRegistration< FireTopicListErrorBannerCell, FireReadHistoryCollectionItem > { [weak self] cell, _, item in @@ -89,7 +89,7 @@ final class FireReadHistoryViewController: UIViewController { ) } - private lazy var topicCellRegistration = UICollectionView.CellRegistration< + lazy var topicCellRegistration = UICollectionView.CellRegistration< FireTopicListTopicCell, FireReadHistoryCollectionItem > { [weak self] cell, _, item in @@ -178,405 +178,8 @@ final class FireReadHistoryViewController: UIViewController { } } - func updateTopicRoutePresenter(_ presenter: FireTopicRoutePresenter) { - topicRoutePresenter = presenter - } - - private func configureListController() { - listController.updateCellProvider { [weak self] collectionView, indexPath, item in - guard let self else { - return UICollectionViewCell() - } - return self.cell(collectionView: collectionView, indexPath: indexPath, item: item) - } - listController.updateContextMenuConfigurationProvider { [weak self] item in - self?.contextMenuConfiguration(for: item) - } - } - - private func prepareCellRegistrations() { - _ = stateCellRegistration - _ = bannerCellRegistration - _ = topicCellRegistration - } - - private func installListController() { - addChild(listController) - view.addSubview(listController.view) - listController.view.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - listController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), - listController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), - listController.view.topAnchor.constraint(equalTo: view.topAnchor), - listController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) - listController.didMove(toParent: self) - } - - private func bindViewModel() { - historyViewModel.objectWillChange - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - DispatchQueue.main.async { - self?.render() - } - } - .store(in: &cancellables) - } - - private var baseURLString: String { - let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? "https://linux.do" : trimmed - } - - private var contentVersion: ContentVersion { - ContentVersion( - rows: historyViewModel.rows, - nextPage: historyViewModel.nextPage, - isLoading: historyViewModel.isLoading, - isLoadingMore: historyViewModel.isLoadingMore, - hasLoadedOnce: historyViewModel.hasLoadedOnce, - errorMessage: historyViewModel.errorMessage - ) - } - - private func render() { - let sections = makeSections() - var tokens: [FireReadHistoryCollectionItem: AnyHashable] = [:] - tokens.reserveCapacity(sections.reduce(0) { $0 + $1.items.count }) - for section in sections { - for item in section.items { - tokens[item] = itemContentToken(for: item) - } - } - listController.setSections( - sections, - contentVersion: contentVersion, - itemContentTokens: tokens, - animatingDifferences: true - ) - } - - private func makeSections() - -> [FireListSectionModel] - { - var items: [FireReadHistoryCollectionItem] = [] - - if let errorMessage = historyViewModel.errorMessage, - historyViewModel.hasLoadedOnce { - items.append(.inlineErrorBanner(errorMessage)) - } - - if !historyViewModel.hasLoadedOnce { - if let errorMessage = historyViewModel.errorMessage { - items.append(.blockingError(errorMessage)) - } else { - items.append(.loading) - } - } else if historyViewModel.rows.isEmpty { - items.append(.empty) - } else { - items.append(contentsOf: historyViewModel.rows.map { - .topic($0.topic.id) - }) - - if historyViewModel.isLoadingMore { - items.append(.loadingMore) - } - } - - return [.init(id: .content, items: items)] - } - - private func cell( - collectionView: UICollectionView, - indexPath: IndexPath, - item: FireReadHistoryCollectionItem - ) -> UICollectionViewCell { - switch item { - case .blockingError, .loading, .empty, .loadingMore: - return collectionView.dequeueConfiguredReusableCell( - using: stateCellRegistration, - for: indexPath, - item: item - ) - case .inlineErrorBanner: - return collectionView.dequeueConfiguredReusableCell( - using: bannerCellRegistration, - for: indexPath, - item: item - ) - case .topic: - return collectionView.dequeueConfiguredReusableCell( - using: topicCellRegistration, - for: indexPath, - item: item - ) - } - } - - private func canSelect(_ item: FireReadHistoryCollectionItem) -> Bool { - if case .topic = item { - return true - } - return false - } - - private func handleSelection(_ item: FireReadHistoryCollectionItem) { - guard case let .topic(topicID) = item, - let row = historyViewModel.row(for: topicID) else { return } - presentRoute(.topic(row: row, postNumber: row.topic.lastReadPostNumber)) - } - - private func handleVisibleItemsChanged(_ items: [FireReadHistoryCollectionItem]) { - loadMoreIfNeeded(from: items) - } - - private func loadMoreIfNeeded(from items: [FireReadHistoryCollectionItem]) { - guard let lastTopicID = historyViewModel.lastTopicID else { return } - guard items.contains(.topic(lastTopicID)) || items.contains(.loadingMore) else { return } - loadTask = Task { [weak self] in - await self?.historyViewModel.loadMoreIfNeeded(currentTopicID: lastTopicID) - } - } - - private func contextMenuConfiguration( - for item: FireReadHistoryCollectionItem - ) -> UIContextMenuConfiguration? { - guard case let .topic(topicID) = item, - let row = historyViewModel.row(for: topicID) - else { - return nil - } - let shareURL = row.fireTopicURL(baseURL: baseURLString) - return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in - UIMenu(children: self?.topicMenuActions(row: row, shareURL: shareURL) ?? []) - } - } - - private func topicMenuActions( - row: FireTopicRowPresentation, - shareURL: URL - ) -> [UIAction] { - [ - UIAction(title: "打开话题", image: UIImage(systemName: "arrow.up.right")) { [weak self] _ in - self?.presentRoute(.topic(row: row, postNumber: row.topic.lastReadPostNumber)) - }, - UIAction( - title: row.topic.bookmarkId == nil ? "添加书签" : "编辑书签", - image: UIImage(systemName: row.topic.bookmarkId == nil ? "bookmark" : "bookmark.fill") - ) { [weak self] _ in - self?.presentBookmarkEditor(for: row) - }, - UIAction(title: "分享话题", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in - self?.presentShareSheet(url: shareURL) - }, - UIAction(title: "复制链接", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in - UIPasteboard.general.string = shareURL.absoluteString - self?.showToast("已复制链接", style: .success) - }, - UIAction(title: "静音话题", image: UIImage(systemName: "bell.slash")) { [weak self] _ in - self?.muteTopicFromAction(row) - }, - ] - } - - private func itemContentToken(for item: FireReadHistoryCollectionItem) -> AnyHashable { - switch item { - case let .blockingError(message), let .inlineErrorBanner(message): - return AnyHashable(message) - case .loading: - return AnyHashable(historyViewModel.isLoading) - case .empty: - return AnyHashable(historyViewModel.hasLoadedOnce) - case let .topic(topicID): - guard let row = historyViewModel.row(for: topicID) else { - return AnyHashable("missing|\(topicID)") - } - return AnyHashable(topicRowContentToken(row)) - case .loadingMore: - return AnyHashable(historyViewModel.isLoadingMore) - } - } - - private func topicRowContentToken(_ row: FireTopicRowPresentation) -> String { - let topic = row.topic - let category = appViewModel.categoryPresentation(for: topic.categoryId) - var parts: [String] = [] - parts.reserveCapacity(31) - parts.append(String(topic.id)) - parts.append(topic.title) - parts.append(topic.slug) - parts.append(String(topic.postsCount)) - parts.append(String(topic.replyCount)) - parts.append(String(topic.views)) - parts.append(String(topic.likeCount)) - parts.append(topic.excerpt ?? "") - parts.append(topic.createdAt ?? "") - parts.append(topic.lastPostedAt ?? "") - parts.append(topic.lastPosterUsername ?? "") - parts.append(topic.categoryId.map(String.init) ?? "") - parts.append(String(topic.pinned)) - parts.append(String(topic.closed)) - parts.append(String(topic.archived)) - parts.append(String(topic.unseen)) - parts.append(String(topic.unreadPosts)) - parts.append(String(topic.newPosts)) - parts.append(topic.lastReadPostNumber.map(String.init) ?? "") - parts.append(String(topic.highestPostNumber)) - parts.append(topic.bookmarkedPostNumber.map(String.init) ?? "") - parts.append(topic.bookmarkId.map(String.init) ?? "") - parts.append(topic.bookmarkName ?? "") - parts.append(topic.bookmarkReminderAt ?? "") - parts.append(topic.bookmarkableType ?? "") - parts.append(row.excerptText ?? "") - parts.append(row.originalPosterUsername ?? "") - parts.append(row.originalPosterAvatarTemplate ?? "") - parts.append(row.tagNames.joined(separator: ",")) - parts.append(row.statusLabels.joined(separator: ",")) - parts.append(category.map { "\($0.id)|\($0.displayName)|\($0.colorHex ?? "")" } ?? "") - return parts.joined(separator: "\u{1F}") - } - - private func presentRoute(_ route: FireAppRoute) { - if topicRoutePresenter.present(route) { - return - } - if route.presentsAsSecondaryPage { - FireAppRouteControllerFactory.presentSecondaryRoute( - route, - viewModel: appViewModel, - topicDetailStore: topicDetailStore - ) - } - } - - private func presentBookmarkEditor(for row: FireTopicRowPresentation) { - let context = row.fireBookmarkEditorContext() - let recoveryOriginURL = row.fireTopicURL(baseURL: baseURLString) - let rootView = FireBookmarkEditorSheet( - context: context, - onSave: { [weak self] name, reminderAt in - try await self?.saveBookmark( - context: context, - name: name, - reminderAt: reminderAt, - recoveryOriginURL: recoveryOriginURL - ) - }, - onDelete: context.bookmarkID.map { bookmarkID in - { [weak self] in - try await self?.deleteBookmark( - bookmarkID: bookmarkID, - recoveryOriginURL: recoveryOriginURL, - showSuccessToast: false - ) - } - } - ) - let controller = UIHostingController(rootView: rootView) - if let sheet = controller.sheetPresentationController { - sheet.detents = [.medium(), .large()] - sheet.prefersGrabberVisible = true - } - present(controller, animated: true) - } - - private func saveBookmark( - context: FireBookmarkEditorContext, - name: String?, - reminderAt: String?, - recoveryOriginURL: URL - ) async throws { - if let bookmarkID = context.bookmarkID { - try await appViewModel.topicInteraction.updateBookmark( - bookmarkID: bookmarkID, - name: name, - reminderAt: reminderAt, - recoveryOriginURL: recoveryOriginURL - ) - } else { - _ = try await appViewModel.topicInteraction.createBookmark( - bookmarkableID: context.bookmarkableID, - bookmarkableType: context.bookmarkableType, - name: name, - reminderAt: reminderAt, - recoveryOriginURL: recoveryOriginURL - ) - } - await historyViewModel.refresh() - } - - private func deleteBookmarkFromAction(for row: FireTopicRowPresentation) { - guard let bookmarkID = row.topic.bookmarkId else { return } - let recoveryOriginURL = row.fireTopicURL(baseURL: baseURLString) - loadTask = Task { [weak self] in - do { - try await self?.deleteBookmark( - bookmarkID: bookmarkID, - recoveryOriginURL: recoveryOriginURL, - showSuccessToast: true - ) - } catch { - self?.historyViewModel.reportError(error.localizedDescription) - self?.showToast(error.localizedDescription, style: .error) - } - } - } - - private func deleteBookmark( - bookmarkID: UInt64, - recoveryOriginURL: URL, - showSuccessToast: Bool - ) async throws { - try await appViewModel.topicInteraction.deleteBookmark( - bookmarkID: bookmarkID, - recoveryOriginURL: recoveryOriginURL - ) - await historyViewModel.refresh() - if showSuccessToast { - showToast("已删除书签", style: .success) - } - } - - private func muteTopicFromAction(_ row: FireTopicRowPresentation) { - loadTask = Task { [weak self] in - do { - try await self?.appViewModel.topicInteraction.setTopicNotificationLevel( - topicID: row.topic.id, - notificationLevel: FireTopicNotificationLevelOption.muted.rawValue, - recoveryOriginURL: row.fireTopicURL(baseURL: self?.baseURLString ?? "https://linux.do") - ) - self?.showToast("已静音话题", style: .success) - } catch { - self?.showToast(error.localizedDescription, style: .error) - } - } - } - - private func presentShareSheet(url: URL) { - let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) - if let popover = controller.popoverPresentationController { - popover.sourceView = view - popover.sourceRect = CGRect( - x: view.bounds.midX, - y: view.safeAreaInsets.top + 24, - width: 1, - height: 1 - ) - } - present(controller, animated: true) - } - - private func showToast(_ message: String, style: FireTopicListToastView.Style) { - toastDismissTask?.cancel() - toastView?.removeFromSuperview() - toastView = nil - FireUIKitToast.show(message, style: FireUIKitToast.Style(style), in: view) - } - } -private final class FireReadHistoryControllerReference { +final class FireReadHistoryControllerReference { weak var controller: FireReadHistoryViewController? } diff --git a/apps/ios-app/App/Views/Profile/FireProfileViewController+Binding.swift b/apps/ios-app/App/Views/Profile/FireProfileViewController+Binding.swift new file mode 100644 index 00000000..e2185f36 --- /dev/null +++ b/apps/ios-app/App/Views/Profile/FireProfileViewController+Binding.swift @@ -0,0 +1,36 @@ +import Combine +import SnapKit +import SwiftUI +import UIKit + +@MainActor +extension FireProfileViewController { + func bind() { + profileViewModel.objectWillChange + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.tableView.reloadData() + self?.tableView.refreshControl?.endRefreshing() + } + .store(in: &cancellables) + + navigationState.$selectedTab + .receive(on: DispatchQueue.main) + .sink { [weak self] tab in + guard let self else { return } + self.isActive = tab == 2 + if self.isActive { + self.profileViewModel.syncWithCurrentSession() + } + } + .store(in: &cancellables) + } + + @objc + func handleRefresh() { + Task { [weak self] in + await self?.profileViewModel.refreshAll() + self?.tableView.refreshControl?.endRefreshing() + } + } +} diff --git a/apps/ios-app/App/Views/Profile/FireProfileViewController+Routing.swift b/apps/ios-app/App/Views/Profile/FireProfileViewController+Routing.swift new file mode 100644 index 00000000..f5139756 --- /dev/null +++ b/apps/ios-app/App/Views/Profile/FireProfileViewController+Routing.swift @@ -0,0 +1,112 @@ +import Combine +import SnapKit +import SwiftUI +import UIKit + +@MainActor +extension FireProfileViewController { + func openSettings() { + FireMotionHaptics.selection() + pushFullScreen(FireSettingsViewController(viewModel: appViewModel, canLogout: canLogout)) + } + + func openSocial(_ row: SocialRow) { + FireMotionHaptics.selection() + let kind: FireFollowListViewModel.Kind = row == .following ? .following : .followers + appViewModel.topicRouteLogger()?.info( + "profile tab open follow list kind=\(kind.title) username_length=\(displayUsername.count)" + ) + // UIKit follow list owns profile + topic drill-down. Do not host SwiftUI + // NavigationLink for this path — environment presenters were no-ops after + // follow list → public profile → 最近动态. + let controller = FireFollowListViewController( + viewModel: appViewModel, + topicDetailStore: topicDetailStore, + username: displayUsername, + kind: kind, + topicRoutePresenter: topicRoutePresenter + ) + pushFullScreen(controller) + } + + func openContent(_ row: ContentRow) { + FireMotionHaptics.selection() + switch row { + case .activity: + pushHosting( + FireProfileActivityTimelineView( + viewModel: appViewModel, + profileViewModel: profileViewModel, + topicDetailStore: topicDetailStore + ), + title: "我的动态" + ) + case .bookmarks: + pushFullScreen( + FireBookmarksViewController( + viewModel: appViewModel, + topicDetailStore: topicDetailStore, + username: displayUsername, + topicRoutePresenter: topicRoutePresenter + ) + ) + case .history: + pushFullScreen( + FireReadHistoryViewController( + viewModel: appViewModel, + topicDetailStore: topicDetailStore, + topicRoutePresenter: topicRoutePresenter + ) + ) + case .drafts: + pushFullScreen(FireDraftsViewController(viewModel: appViewModel)) + case .messages: + pushFullScreen( + FirePrivateMessagesViewController( + viewModel: appViewModel, + topicDetailStore: topicDetailStore, + topicRoutePresenter: topicRoutePresenter + ) + ) + case .badges: + pushHosting(FireMyBadgesView(badges: profileViewModel.summary?.badges ?? []), title: "我的勋章") + } + } + + func openAccount(_ row: AccountRow) { + FireMotionHaptics.selection() + switch row { + case .feedback: + FireFeedbackPresenter.present( + from: self, + appViewModel: appViewModel, + source: "profile" + ) + case .invites: + pushHosting(FireInviteLinksView(viewModel: appViewModel, username: displayUsername), title: "邀请链接") + case .ldc: + pushHosting(FireLDCView(viewModel: appViewModel), title: "LDC 信用") + case .cdk: + pushHosting(FireCDKView(viewModel: appViewModel), title: "CDK 连接") + case .settings: + openSettings() + } + } + + func pushFullScreen(_ controller: UIViewController) { + controller.view.backgroundColor = controller.view.backgroundColor ?? FireTheme.uiCanvas + FireRootCoordinator.presentSecondary(controller) + } + + func pushHosting(_ root: Content, title: String? = nil) { + let host = FireHosting.controller( + rootView: root + .environmentObject(navigationState) + .environmentObject(topicDetailStore) + .fireTopicRoutePresenter(topicRoutePresenter) + .navigationBarTitleDisplayMode(.inline), + title: title + ) + pushFullScreen(host) + } +} diff --git a/apps/ios-app/App/Views/Profile/FireProfileViewController+RowProjection.swift b/apps/ios-app/App/Views/Profile/FireProfileViewController+RowProjection.swift new file mode 100644 index 00000000..fbc3f410 --- /dev/null +++ b/apps/ios-app/App/Views/Profile/FireProfileViewController+RowProjection.swift @@ -0,0 +1,42 @@ +import Combine +import SnapKit +import SwiftUI +import UIKit + +@MainActor +extension FireProfileViewController { + var displayUsername: String { + profileViewModel.currentUsername ?? appViewModel.session.profileDisplayName + } + + var displayName: String { + let trimmed = profileViewModel.profile?.name?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? displayUsername : trimmed + } + + var canLogout: Bool { + appViewModel.session.hasLoginSession || appViewModel.session.readiness.canReadAuthenticatedApi + } + + func value(for social: SocialRow) -> String { + switch social { + case .following: + return FireProfileFormat.number(profileViewModel.profile?.totalFollowing ?? 0) + case .followers: + return FireProfileFormat.number(profileViewModel.profile?.totalFollowers ?? 0) + } + } + + func value(for content: ContentRow) -> String? { + switch content { + case .bookmarks: + let count = profileViewModel.summary?.stats.bookmarkCount ?? 0 + return "\(FireProfileFormat.number(count))条" + case .badges: + let count = UInt32(profileViewModel.summary?.badges.count ?? 0) + return "\(FireProfileFormat.number(count))枚" + case .activity, .history, .drafts, .messages: + return nil + } + } +} diff --git a/apps/ios-app/App/Views/Profile/FireProfileViewController+Table.swift b/apps/ios-app/App/Views/Profile/FireProfileViewController+Table.swift new file mode 100644 index 00000000..21750491 --- /dev/null +++ b/apps/ios-app/App/Views/Profile/FireProfileViewController+Table.swift @@ -0,0 +1,199 @@ +import Combine +import SnapKit +import SwiftUI +import UIKit + +@MainActor +extension FireProfileViewController { + func applyGroupedChrome(to cell: UITableViewCell) { + var background = UIBackgroundConfiguration.listGroupedCell() + background.backgroundColor = FireTheme.uiSurface + background.cornerRadius = FireTheme.cornerRadius + cell.backgroundConfiguration = background + cell.tintColor = FireTheme.uiTertiaryInk + } + + func configureMenuRow( + _ cell: FireProfileMenuRowCell, + systemImage: String, + title: String, + value: String? = nil, + iconWellColor: UIColor + ) { + applyGroupedChrome(to: cell) + cell.configure( + systemImage: systemImage, + title: title, + value: value, + iconWellColor: iconWellColor + ) + } +} + +extension FireProfileViewController: UITableViewDataSource, UITableViewDelegate { + func numberOfSections(in tableView: UITableView) -> Int { + Section.allCases.count + } + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + guard let section = Section(rawValue: section) else { return 0 } + switch section { + case .error: + return (profileViewModel.errorMessage ?? appViewModel.errorMessage) == nil ? 0 : 1 + case .header: + return 1 + case .social: + return SocialRow.allCases.count + case .content: + return ContentRow.allCases.count + case .account: + return AccountRow.allCases.count + } + } + + func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + guard let section = Section(rawValue: section) else { return nil } + switch section { + case .social: return "社交" + case .content: return "内容" + case .account: return "账户" + case .error, .header: + return nil + } + } + + func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { + guard let header = view as? UITableViewHeaderFooterView else { return } + header.textLabel?.font = .systemFont(ofSize: 13, weight: .semibold) + header.textLabel?.textColor = FireTheme.uiTertiaryInk + header.textLabel?.text = header.textLabel?.text?.uppercased() + } + + func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { + guard let section = Section(rawValue: section) else { return 0 } + switch section { + case .error, .header: + return CGFloat.leastNormalMagnitude + case .social, .content, .account: + return UITableView.automaticDimension + } + } + + func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { + guard let section = Section(rawValue: section) else { return 6 } + switch section { + case .error: + return CGFloat.leastNormalMagnitude + case .header: + return 4 + case .social, .content, .account: + return 6 + } + } + + func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { + UIView() + } + + func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + guard let section = Section(rawValue: indexPath.section) else { + return UITableView.automaticDimension + } + switch section { + case .social, .content, .account: + return FireProfileMenuRowCell.preferredHeight + case .error, .header: + return UITableView.automaticDimension + } + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + guard let section = Section(rawValue: indexPath.section) else { + return UITableViewCell() + } + switch section { + case .error: + let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) + applyGroupedChrome(to: cell) + var content = cell.defaultContentConfiguration() + content.text = profileViewModel.errorMessage ?? appViewModel.errorMessage + content.textProperties.color = FireTheme.uiError + content.textProperties.font = .preferredFont(forTextStyle: .footnote) + cell.contentConfiguration = content + cell.selectionStyle = .none + return cell + case .header: + let cell = tableView.dequeueReusableCell( + withIdentifier: FireProfileHeaderTableCell.reuseID, + for: indexPath + ) as! FireProfileHeaderTableCell + cell.configure( + displayName: displayName, + username: displayUsername, + avatarTemplate: profileViewModel.profile?.avatarTemplate, + bio: profileViewModel.profile?.bioPlainText, + trustLevel: profileViewModel.profile?.trustLevel, + followers: profileViewModel.profile?.totalFollowers ?? 0, + likes: profileViewModel.summary?.stats.likesReceived ?? 0, + following: profileViewModel.profile?.totalFollowing ?? 0 + ) + return cell + case .social: + let row = SocialRow.allCases[indexPath.row] + let cell = tableView.dequeueReusableCell( + withIdentifier: FireProfileMenuRowCell.reuseID, + for: indexPath + ) as! FireProfileMenuRowCell + configureMenuRow( + cell, + systemImage: row.systemImage, + title: row.title, + value: value(for: row), + iconWellColor: row.iconWellColor + ) + return cell + case .content: + let row = ContentRow.allCases[indexPath.row] + let cell = tableView.dequeueReusableCell( + withIdentifier: FireProfileMenuRowCell.reuseID, + for: indexPath + ) as! FireProfileMenuRowCell + configureMenuRow( + cell, + systemImage: row.systemImage, + title: row.title, + value: value(for: row), + iconWellColor: row.iconWellColor + ) + return cell + case .account: + let row = AccountRow.allCases[indexPath.row] + let cell = tableView.dequeueReusableCell( + withIdentifier: FireProfileMenuRowCell.reuseID, + for: indexPath + ) as! FireProfileMenuRowCell + configureMenuRow( + cell, + systemImage: row.systemImage, + title: row.title, + iconWellColor: row.iconWellColor + ) + return cell + } + } + + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + tableView.deselectRow(at: indexPath, animated: true) + guard let section = Section(rawValue: indexPath.section) else { return } + switch section { + case .error, .header: + break + case .social: + openSocial(SocialRow.allCases[indexPath.row]) + case .content: + openContent(ContentRow.allCases[indexPath.row]) + case .account: + openAccount(AccountRow.allCases[indexPath.row]) + } + } +} diff --git a/apps/ios-app/App/Views/Profile/FireProfileViewController.swift b/apps/ios-app/App/Views/Profile/FireProfileViewController.swift index ec420c8d..9cb5fe0e 100644 --- a/apps/ios-app/App/Views/Profile/FireProfileViewController.swift +++ b/apps/ios-app/App/Views/Profile/FireProfileViewController.swift @@ -6,7 +6,7 @@ import UIKit /// UIKit profile tab hub using the unified black-canvas + elevated-card language. @MainActor final class FireProfileViewController: UIViewController { - private enum Section: Int, CaseIterable { + enum Section: Int, CaseIterable { case error case header case social @@ -14,7 +14,7 @@ final class FireProfileViewController: UIViewController { case account } - private enum SocialRow: Int, CaseIterable { + enum SocialRow: Int, CaseIterable { case following case followers @@ -40,7 +40,7 @@ final class FireProfileViewController: UIViewController { } } - private enum ContentRow: Int, CaseIterable { + enum ContentRow: Int, CaseIterable { case activity case bookmarks case history @@ -83,7 +83,7 @@ final class FireProfileViewController: UIViewController { } } - private enum AccountRow: Int, CaseIterable { + enum AccountRow: Int, CaseIterable { /// Early-beta primary entry: keep first for discoverability. case feedback case invites @@ -122,15 +122,15 @@ final class FireProfileViewController: UIViewController { } } - private let appViewModel: FireAppViewModel - private let navigationState: FireNavigationState - private let profileViewModel: FireProfileViewModel - private let topicDetailStore: FireTopicDetailStore - private let tableView = UITableView(frame: .zero, style: .insetGrouped) - private var cancellables: Set = [] - private var isActive = false + let appViewModel: FireAppViewModel + let navigationState: FireNavigationState + let profileViewModel: FireProfileViewModel + let topicDetailStore: FireTopicDetailStore + let tableView = UITableView(frame: .zero, style: .insetGrouped) + var cancellables: Set = [] + var isActive = false - private var topicRoutePresenter: FireTopicRoutePresenter { + var topicRoutePresenter: FireTopicRoutePresenter { FireTopicRoutePresenter { [weak self] route in guard let self, route.isTopicRoute else { return false } navigationState.presentTopicRoute(route) @@ -202,366 +202,6 @@ final class FireProfileViewController: UIViewController { tableView.reloadData() } - private func bind() { - profileViewModel.objectWillChange - .receive(on: DispatchQueue.main) - .sink { [weak self] _ in - self?.tableView.reloadData() - self?.tableView.refreshControl?.endRefreshing() - } - .store(in: &cancellables) - - navigationState.$selectedTab - .receive(on: DispatchQueue.main) - .sink { [weak self] tab in - guard let self else { return } - self.isActive = tab == 2 - if self.isActive { - self.profileViewModel.syncWithCurrentSession() - } - } - .store(in: &cancellables) - } - - @objc - private func handleRefresh() { - Task { [weak self] in - await self?.profileViewModel.refreshAll() - self?.tableView.refreshControl?.endRefreshing() - } - } - - private var displayUsername: String { - profileViewModel.currentUsername ?? appViewModel.session.profileDisplayName - } - - private var displayName: String { - let trimmed = profileViewModel.profile?.name?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - return trimmed.isEmpty ? displayUsername : trimmed - } - - private var canLogout: Bool { - appViewModel.session.hasLoginSession || appViewModel.session.readiness.canReadAuthenticatedApi - } - - private func value(for social: SocialRow) -> String { - switch social { - case .following: - return FireProfileFormat.number(profileViewModel.profile?.totalFollowing ?? 0) - case .followers: - return FireProfileFormat.number(profileViewModel.profile?.totalFollowers ?? 0) - } - } - /// Trailing count only — no descriptive filler like “已保存”. - private func value(for content: ContentRow) -> String? { - switch content { - case .bookmarks: - let count = profileViewModel.summary?.stats.bookmarkCount ?? 0 - return "\(FireProfileFormat.number(count))条" - case .badges: - let count = UInt32(profileViewModel.summary?.badges.count ?? 0) - return "\(FireProfileFormat.number(count))枚" - case .activity, .history, .drafts, .messages: - return nil - } - } - - private func openSettings() { - FireMotionHaptics.selection() - pushFullScreen(FireSettingsViewController(viewModel: appViewModel, canLogout: canLogout)) - } - - private func openSocial(_ row: SocialRow) { - FireMotionHaptics.selection() - let kind: FireFollowListViewModel.Kind = row == .following ? .following : .followers - appViewModel.topicRouteLogger()?.info( - "profile tab open follow list kind=\(kind.title) username_length=\(displayUsername.count)" - ) - // UIKit follow list owns profile + topic drill-down. Do not host SwiftUI - // NavigationLink for this path — environment presenters were no-ops after - // follow list → public profile → 最近动态. - let controller = FireFollowListViewController( - viewModel: appViewModel, - topicDetailStore: topicDetailStore, - username: displayUsername, - kind: kind, - topicRoutePresenter: topicRoutePresenter - ) - pushFullScreen(controller) - } - - private func openContent(_ row: ContentRow) { - FireMotionHaptics.selection() - switch row { - case .activity: - pushHosting( - FireProfileActivityTimelineView( - viewModel: appViewModel, - profileViewModel: profileViewModel, - topicDetailStore: topicDetailStore - ), - title: "我的动态" - ) - case .bookmarks: - pushFullScreen( - FireBookmarksViewController( - viewModel: appViewModel, - topicDetailStore: topicDetailStore, - username: displayUsername, - topicRoutePresenter: topicRoutePresenter - ) - ) - case .history: - pushFullScreen( - FireReadHistoryViewController( - viewModel: appViewModel, - topicDetailStore: topicDetailStore, - topicRoutePresenter: topicRoutePresenter - ) - ) - case .drafts: - pushFullScreen(FireDraftsViewController(viewModel: appViewModel)) - case .messages: - pushFullScreen( - FirePrivateMessagesViewController( - viewModel: appViewModel, - topicDetailStore: topicDetailStore, - topicRoutePresenter: topicRoutePresenter - ) - ) - case .badges: - pushHosting(FireMyBadgesView(badges: profileViewModel.summary?.badges ?? []), title: "我的勋章") - } - } - - private func openAccount(_ row: AccountRow) { - FireMotionHaptics.selection() - switch row { - case .feedback: - FireFeedbackPresenter.present( - from: self, - appViewModel: appViewModel, - source: "profile" - ) - case .invites: - pushHosting(FireInviteLinksView(viewModel: appViewModel, username: displayUsername), title: "邀请链接") - case .ldc: - pushHosting(FireLDCView(viewModel: appViewModel), title: "LDC 信用") - case .cdk: - pushHosting(FireCDKView(viewModel: appViewModel), title: "CDK 连接") - case .settings: - openSettings() - } - } - /// Full-screen secondary page above the tab shell (covers tab bar; does not hide it). - private func pushFullScreen(_ controller: UIViewController) { - controller.view.backgroundColor = controller.view.backgroundColor ?? FireTheme.uiCanvas - FireRootCoordinator.presentSecondary(controller) - } - - private func pushHosting(_ root: Content, title: String? = nil) { - let host = FireHosting.controller( - rootView: root - .environmentObject(navigationState) - .environmentObject(topicDetailStore) - .fireTopicRoutePresenter(topicRoutePresenter) - .navigationBarTitleDisplayMode(.inline), - title: title - ) - pushFullScreen(host) - } - - private func applyGroupedChrome(to cell: UITableViewCell) { - var background = UIBackgroundConfiguration.listGroupedCell() - background.backgroundColor = FireTheme.uiSurface - background.cornerRadius = FireTheme.cornerRadius - cell.backgroundConfiguration = background - cell.tintColor = FireTheme.uiTertiaryInk - } - - private func configureMenuRow( - _ cell: FireProfileMenuRowCell, - systemImage: String, - title: String, - value: String? = nil, - iconWellColor: UIColor - ) { - applyGroupedChrome(to: cell) - cell.configure( - systemImage: systemImage, - title: title, - value: value, - iconWellColor: iconWellColor - ) - } -} - -extension FireProfileViewController: UITableViewDataSource, UITableViewDelegate { - func numberOfSections(in tableView: UITableView) -> Int { - Section.allCases.count - } - - func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - guard let section = Section(rawValue: section) else { return 0 } - switch section { - case .error: - return (profileViewModel.errorMessage ?? appViewModel.errorMessage) == nil ? 0 : 1 - case .header: - return 1 - case .social: - return SocialRow.allCases.count - case .content: - return ContentRow.allCases.count - case .account: - return AccountRow.allCases.count - } - } - - func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { - guard let section = Section(rawValue: section) else { return nil } - switch section { - case .social: return "社交" - case .content: return "内容" - case .account: return "账户" - case .error, .header: - return nil - } - } - - func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { - guard let header = view as? UITableViewHeaderFooterView else { return } - header.textLabel?.font = .systemFont(ofSize: 13, weight: .semibold) - header.textLabel?.textColor = FireTheme.uiTertiaryInk - header.textLabel?.text = header.textLabel?.text?.uppercased() - } - - func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { - guard let section = Section(rawValue: section) else { return 0 } - switch section { - case .error, .header: - return CGFloat.leastNormalMagnitude - case .social, .content, .account: - return UITableView.automaticDimension - } - } - - func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { - guard let section = Section(rawValue: section) else { return 6 } - switch section { - case .error: - return CGFloat.leastNormalMagnitude - case .header: - return 4 - case .social, .content, .account: - return 6 - } - } - - func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { - UIView() - } - - func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { - guard let section = Section(rawValue: indexPath.section) else { - return UITableView.automaticDimension - } - switch section { - case .social, .content, .account: - return FireProfileMenuRowCell.preferredHeight - case .error, .header: - return UITableView.automaticDimension - } - } - - func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - guard let section = Section(rawValue: indexPath.section) else { - return UITableViewCell() - } - switch section { - case .error: - let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) - applyGroupedChrome(to: cell) - var content = cell.defaultContentConfiguration() - content.text = profileViewModel.errorMessage ?? appViewModel.errorMessage - content.textProperties.color = FireTheme.uiError - content.textProperties.font = .preferredFont(forTextStyle: .footnote) - cell.contentConfiguration = content - cell.selectionStyle = .none - return cell - case .header: - let cell = tableView.dequeueReusableCell( - withIdentifier: FireProfileHeaderTableCell.reuseID, - for: indexPath - ) as! FireProfileHeaderTableCell - cell.configure( - displayName: displayName, - username: displayUsername, - avatarTemplate: profileViewModel.profile?.avatarTemplate, - bio: profileViewModel.profile?.bioPlainText, - trustLevel: profileViewModel.profile?.trustLevel, - followers: profileViewModel.profile?.totalFollowers ?? 0, - likes: profileViewModel.summary?.stats.likesReceived ?? 0, - following: profileViewModel.profile?.totalFollowing ?? 0 - ) - return cell - case .social: - let row = SocialRow.allCases[indexPath.row] - let cell = tableView.dequeueReusableCell( - withIdentifier: FireProfileMenuRowCell.reuseID, - for: indexPath - ) as! FireProfileMenuRowCell - configureMenuRow( - cell, - systemImage: row.systemImage, - title: row.title, - value: value(for: row), - iconWellColor: row.iconWellColor - ) - return cell - case .content: - let row = ContentRow.allCases[indexPath.row] - let cell = tableView.dequeueReusableCell( - withIdentifier: FireProfileMenuRowCell.reuseID, - for: indexPath - ) as! FireProfileMenuRowCell - configureMenuRow( - cell, - systemImage: row.systemImage, - title: row.title, - value: value(for: row), - iconWellColor: row.iconWellColor - ) - return cell - case .account: - let row = AccountRow.allCases[indexPath.row] - let cell = tableView.dequeueReusableCell( - withIdentifier: FireProfileMenuRowCell.reuseID, - for: indexPath - ) as! FireProfileMenuRowCell - configureMenuRow( - cell, - systemImage: row.systemImage, - title: row.title, - iconWellColor: row.iconWellColor - ) - return cell - } - } - - func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - tableView.deselectRow(at: indexPath, animated: true) - guard let section = Section(rawValue: indexPath.section) else { return } - switch section { - case .error, .header: - break - case .social: - openSocial(SocialRow.allCases[indexPath.row]) - case .content: - openContent(ContentRow.allCases[indexPath.row]) - case .account: - openAccount(AccountRow.allCases[indexPath.row]) - } - } } diff --git a/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Inline.swift b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Inline.swift new file mode 100644 index 00000000..308ca3c4 --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Inline.swift @@ -0,0 +1,41 @@ +import UIKit + +extension FireRichTextAttributedStringBuilder { + static func textAttributes( + for context: RenderContext, + overrideColor: UIColor? = nil + ) -> [NSAttributedString.Key: Any] { + var attrs: [NSAttributedString.Key: Any] = [ + .font: context.currentFont, + .foregroundColor: overrideColor ?? context.textColor, + ] + if context.isStrikethrough { + attrs[.strikethroughStyle] = NSUnderlineStyle.single.rawValue + } + return attrs + } + + static func headingParagraphStyle(for font: UIFont) -> NSParagraphStyle { + let paragraph = NSMutableParagraphStyle() + let lineHeight = ceil(font.lineHeight * 1.12) + paragraph.minimumLineHeight = lineHeight + paragraph.maximumLineHeight = lineHeight + paragraph.lineSpacing = max(2, ceil(font.pointSize * 0.12)) + paragraph.paragraphSpacingBefore = 2 + paragraph.paragraphSpacing = 6 + paragraph.lineBreakMode = .byWordWrapping + return paragraph + } + + static func profileURLString(for username: String) -> String { + let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? username + return "fire://profile/\(encodedUsername)" + } + + static func topicURLString(topicId: UInt64, postNumber: UInt32?) -> String { + if let postNumber { + return "fire://topic/\(topicId)/\(postNumber)" + } + return "fire://topic/\(topicId)" + } +} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Lists.swift b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Lists.swift new file mode 100644 index 00000000..48cedb43 --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Lists.swift @@ -0,0 +1,56 @@ +import UIKit + +extension FireRichTextAttributedStringBuilder { + static func appendListItem( + _ item: [FireRichTextNode], + marker: String, + to result: NSMutableAttributedString, + context: RenderContext + ) { + let start = result.length + result.append(NSAttributedString(string: marker, attributes: textAttributes(for: context))) + appendListItemContent(item, to: result, context: context.indented()) + guard result.length > start else { + return + } + result.addAttribute( + .paragraphStyle, + value: listParagraphStyle(marker: marker, context: context), + range: NSRange(location: start, length: result.length - start) + ) + } + + static func appendListItemContent( + _ item: [FireRichTextNode], + to result: NSMutableAttributedString, + context: RenderContext + ) { + guard let first = item.first else { + return + } + + if case .paragraph(let children) = first { + appendNodes(children, to: result, context: context) + let remaining = Array(item.dropFirst()) + if !remaining.isEmpty { + appendNodes(remaining, to: result, context: context) + } + return + } + + appendNodes(item, to: result, context: context) + } + + static func listParagraphStyle(marker: String, context: RenderContext) -> NSParagraphStyle { + let style = NSMutableParagraphStyle() + let baseIndent = CGFloat(context.indentLevel) * 18 + let markerWidth = ceil((marker as NSString).size(withAttributes: [ + .font: context.currentFont, + ]).width) + style.firstLineHeadIndent = baseIndent + style.headIndent = baseIndent + markerWidth + style.paragraphSpacing = 2 + style.lineBreakMode = .byWordWrapping + return style + } +} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Onebox.swift b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Onebox.swift new file mode 100644 index 00000000..384c9926 --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Onebox.swift @@ -0,0 +1,70 @@ +import UIKit + +extension FireRichTextAttributedStringBuilder { + static func oneboxAttributedString( + url: String?, + title: String?, + description: String?, + sourceName: String?, + context: RenderContext + ) -> NSAttributedString { + let result = NSMutableAttributedString() + let captionAttributes: [NSAttributedString.Key: Any] = [ + .font: UIFont.preferredFont(forTextStyle: .caption1), + .foregroundColor: FireTheme.uiSubtleInk, + ] + let trimmedSource = sourceName?.trimmingCharacters(in: .whitespacesAndNewlines) + let source = (trimmedSource?.isEmpty == false ? trimmedSource : nil) + ?? url.flatMap { URL(string: $0)?.host?.replacingOccurrences(of: "www.", with: "") } + if let source, !source.isEmpty { + result.append(NSAttributedString(string: source, attributes: captionAttributes)) + } + + let linkValue: Any? + if let url { + linkValue = URL(string: url) ?? url + } else { + linkValue = nil + } + let titleText = title?.trimmingCharacters(in: .whitespacesAndNewlines) + let descriptionText = description?.trimmingCharacters(in: .whitespacesAndNewlines) + + if let titleText, !titleText.isEmpty { + if result.length > 0 { + result.append(NSAttributedString(string: "\n")) + } + var attrs = textAttributes(for: context.withBold()) + attrs[.foregroundColor] = context.accentColor + if let linkValue { + attrs[.link] = linkValue + } + result.append(NSAttributedString(string: titleText, attributes: attrs)) + } + + if let descriptionText, !descriptionText.isEmpty { + if result.length > 0 { + result.append(NSAttributedString(string: "\n")) + } + result.append(NSAttributedString( + string: descriptionText, + attributes: textAttributes(for: context.withTextColor(FireTheme.uiSubtleInk)) + )) + } else if let url, !url.isEmpty, titleText?.isEmpty != false { + if result.length > 0 { + result.append(NSAttributedString(string: "\n")) + } + var attrs = textAttributes(for: context) + attrs[.foregroundColor] = context.accentColor + if let linkValue { + attrs[.link] = linkValue + } + result.append(NSAttributedString(string: url, attributes: attrs)) + } + + let paragraph = NSMutableParagraphStyle() + paragraph.paragraphSpacing = 6 + paragraph.paragraphSpacingBefore = 4 + result.addAttribute(.paragraphStyle, value: paragraph, range: NSRange(location: 0, length: result.length)) + return result + } +} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Quotes.swift b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Quotes.swift new file mode 100644 index 00000000..36e840f4 --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder+Quotes.swift @@ -0,0 +1,275 @@ +import UIKit + +extension FireRichTextAttributedStringBuilder { + static let replyQuotePreviewLineLimit = 4 + static let replyQuotePreviewCharacterLimit = 220 + + static func quoteBlockAttributedString( + author: String?, + postNumber: UInt32?, + topicId: UInt64?, + children: [FireRichTextNode], + context: RenderContext + ) -> NSAttributedString { + let content = NSMutableAttributedString() + let isReplyQuote = !(author?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true) + || postNumber != nil + + if let header = quoteHeaderAttributedString( + author: author, + postNumber: postNumber, + topicId: topicId, + context: context + ) { + content.append(header) + if !children.isEmpty { + content.append(NSAttributedString(string: "\n")) + } + } + + let body = NSMutableAttributedString() + // Body blockquotes should read like surrounding post text (web Discourse), + // while reply-quotes stay slightly de-emphasized. + let bodyContext = isReplyQuote + ? context.indented().withTextColor(FireTheme.uiSubtleInk) + : context.withTextColor(context.textColor) + appendNodes(children, to: body, context: bodyContext) + if isReplyQuote { + content.append(compactReplyQuoteBody(body)) + } else { + content.append(fullBlockquoteBody(body)) + } + + guard content.length > 0 else { + return content + } + + // Discourse-like filled panel — stronger than canvas so the block reads clearly. + let fill = UIColor { traits in + if traits.userInterfaceStyle == .dark { + return UIColor(red: 0.16, green: 0.17, blue: 0.19, alpha: 1) + } + return UIColor(red: 0.90, green: 0.91, blue: 0.93, alpha: 1) // #E6E8ED + } + let stripe = UIColor { traits in + if traits.userInterfaceStyle == .dark { + return UIColor(white: 0.42, alpha: 1) + } + return UIColor(red: 0.68, green: 0.71, blue: 0.76, alpha: 1) + } + + // Include vertical padding in layout height (CALayer pad alone gets clipped). + let padded = NSMutableAttributedString() + padded.append(quotePaddingLine()) + padded.append(content) + padded.append(quotePaddingLine()) + + let paragraph = NSMutableParagraphStyle() + paragraph.paragraphSpacing = 0 + paragraph.paragraphSpacingBefore = 0 + paragraph.lineSpacing = 3 + paragraph.headIndent = 16 + paragraph.firstLineHeadIndent = 16 + paragraph.tailIndent = -12 + paragraph.lineBreakMode = .byWordWrapping + + padded.addAttributes( + [ + .paragraphStyle: paragraph, + .fireQuotePreviewBlock: true, + .fireQuotePreviewBackgroundColor: fill, + .fireQuotePreviewStripeColor: stripe, + ], + range: NSRange(location: 0, length: padded.length) + ) + return padded + } + + static func quotePaddingLine() -> NSAttributedString { + let style = NSMutableParagraphStyle() + style.minimumLineHeight = 10 + style.maximumLineHeight = 10 + return NSAttributedString( + string: "\u{200B}\n", + attributes: [ + .font: UIFont.systemFont(ofSize: 1), + .foregroundColor: UIColor.clear, + .paragraphStyle: style, + ] + ) + } + + static func fullBlockquoteBody(_ body: NSAttributedString) -> NSAttributedString { + let result = NSMutableAttributedString(attributedString: body) + // Collapse excessive blank lines inside the quote without truncating content. + collapseExcessiveBlankLines(in: result) + if result.length > 0 { + let font = UIFont.preferredFont(forTextStyle: .body) + result.addAttributes( + [ + .font: font, + .foregroundColor: FireTheme.uiInk.withAlphaComponent(0.88), + ], + range: NSRange(location: 0, length: result.length) + ) + } + return result + } + + static func compactReplyQuoteBody(_ body: NSAttributedString) -> NSAttributedString { + let compact = NSMutableAttributedString() + let source = body.string as NSString + let ranges = nonBlankLineRanges(in: source) + let selectedRanges = ranges.isEmpty + ? trimmedRange(in: source, range: NSRange(location: 0, length: source.length)).map { [$0] } ?? [] + : Array(ranges.prefix(replyQuotePreviewLineLimit)) + + for (index, range) in selectedRanges.enumerated() { + if index > 0 { + compact.append(NSAttributedString(string: "\n")) + } + compact.append(body.attributedSubstring(from: range)) + } + + truncateQuoteBody(compact) + if compact.length > 0 { + compact.addAttributes( + [ + .font: UIFont.preferredFont(forTextStyle: .subheadline), + .foregroundColor: FireTheme.uiSubtleInk, + ], + range: NSRange(location: 0, length: compact.length) + ) + } + return compact + } + + static func collapseExcessiveBlankLines(in body: NSMutableAttributedString) { + var text = body.string as NSString + while text.contains("\n\n\n") { + let range = text.range(of: "\n\n\n") + guard range.location != NSNotFound else { break } + body.replaceCharacters(in: range, with: "\n\n") + text = body.string as NSString + } + } + + static func nonBlankLineRanges(in source: NSString) -> [NSRange] { + var ranges: [NSRange] = [] + var lineStart = 0 + while lineStart <= source.length { + let searchRange = NSRange(location: lineStart, length: source.length - lineStart) + let newlineRange = source.range(of: "\n", options: [], range: searchRange) + let lineEnd = newlineRange.location == NSNotFound ? source.length : newlineRange.location + if let range = trimmedRange( + in: source, + range: NSRange(location: lineStart, length: lineEnd - lineStart) + ) { + ranges.append(range) + } + if lineEnd >= source.length { + break + } + lineStart = lineEnd + 1 + } + return ranges + } + + static func trimmedRange(in source: NSString, range: NSRange) -> NSRange? { + var location = range.location + var end = range.location + range.length + let whitespace = CharacterSet.whitespacesAndNewlines + while location < end, + let scalar = UnicodeScalar(source.character(at: location)), + whitespace.contains(scalar) { + location += 1 + } + while end > location, + let scalar = UnicodeScalar(source.character(at: end - 1)), + whitespace.contains(scalar) { + end -= 1 + } + return location < end + ? NSRange(location: location, length: end - location) + : nil + } + + static func truncateQuoteBody(_ body: NSMutableAttributedString) { + let maxLength = replyQuotePreviewCharacterLimit + let ellipsis = "…" + guard body.length > maxLength else { + return + } + body.deleteCharacters(in: NSRange(location: maxLength - ellipsis.count, length: body.length - (maxLength - ellipsis.count))) + while body.length > 0, + let scalar = UnicodeScalar((body.string as NSString).character(at: body.length - 1)), + CharacterSet.whitespacesAndNewlines.contains(scalar) { + body.deleteCharacters(in: NSRange(location: body.length - 1, length: 1)) + } + body.append(NSAttributedString(string: ellipsis)) + } + + static func quoteHeaderAttributedString( + author: String?, + postNumber: UInt32?, + topicId: UInt64?, + context: RenderContext + ) -> NSAttributedString? { + let trimmedAuthor = author?.trimmingCharacters(in: .whitespacesAndNewlines) + guard (trimmedAuthor?.isEmpty == false) || postNumber != nil else { + return nil + } + + let font = UIFont.preferredFont(forTextStyle: .caption1) + let baseAttributes: [NSAttributedString.Key: Any] = [ + .font: font, + .foregroundColor: FireTheme.uiSubtleInk, + ] + let result = NSMutableAttributedString(string: "引用", attributes: baseAttributes) + + if let trimmedAuthor, !trimmedAuthor.isEmpty { + result.append(NSAttributedString(string: " ", attributes: baseAttributes)) + let profileLink: Any = URL(string: profileURLString(for: trimmedAuthor)) ?? profileURLString(for: trimmedAuthor) + result.append(NSAttributedString(string: "@\(trimmedAuthor)", attributes: [ + .font: font, + .foregroundColor: context.accentColor, + .link: profileLink, + ])) + } + + if let postNumber { + result.append(NSAttributedString(string: " · ", attributes: baseAttributes)) + var postAttributes = baseAttributes + postAttributes[.foregroundColor] = context.accentColor + if let topicId { + postAttributes[.link] = URL(string: topicURLString(topicId: topicId, postNumber: postNumber)) + ?? topicURLString(topicId: topicId, postNumber: postNumber) + } + result.append(NSAttributedString(string: "#\(postNumber)", attributes: postAttributes)) + } + + return result + } + + static func prefixedLines( + in attributedString: NSAttributedString, + prefix: NSAttributedString + ) -> NSMutableAttributedString { + let result = NSMutableAttributedString() + let fullString = attributedString.string as NSString + + guard fullString.length > 0 else { + return result + } + + var location = 0 + while location < fullString.length { + let lineRange = fullString.lineRange(for: NSRange(location: location, length: 0)) + result.append(prefix) + result.append(attributedString.attributedSubstring(from: lineRange)) + location = NSMaxRange(lineRange) + } + + return result + } +} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder.swift b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder.swift new file mode 100644 index 00000000..53c07836 --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextAttributedStringBuilder.swift @@ -0,0 +1,402 @@ +import UIKit + + +enum FireRichTextAttributedStringBuilder { + /// Convert parsed nodes into an NSAttributedString suitable for display. + /// Defaults use Fire theme ink tokens (not bare `UIColor.label`) so Texture + /// post cells share the same adaptive palette as the rest of the app. + static func build( + from nodes: [FireRichTextNode], + baseFont: UIFont = .preferredFont(forTextStyle: .subheadline), + textColor: UIColor = FireTheme.uiInk, + accentColor: UIColor = FireTheme.uiAccent, + codeBackgroundColor: UIColor = .secondarySystemBackground + ) -> NSAttributedString { + let result = NSMutableAttributedString() + appendNodes(nodes, to: result, context: RenderContext( + baseFont: baseFont, + textColor: textColor, + accentColor: accentColor, + codeBackgroundColor: codeBackgroundColor, + isBold: false, + isItalic: false, + isStrikethrough: false, + indentLevel: 0 + )) + return result + } + + struct RenderContext { + let baseFont: UIFont + let textColor: UIColor + let accentColor: UIColor + let codeBackgroundColor: UIColor + var isBold: Bool + var isItalic: Bool + var isStrikethrough: Bool + var indentLevel: Int + + var currentFont: UIFont { + var traits: UIFontDescriptor.SymbolicTraits = [] + if isBold { traits.insert(.traitBold) } + if isItalic { traits.insert(.traitItalic) } + if let descriptor = baseFont.fontDescriptor.withSymbolicTraits(traits) { + return UIFont(descriptor: descriptor, size: baseFont.pointSize) + } + return baseFont + } + + func withBold() -> RenderContext { + var ctx = self; ctx.isBold = true; return ctx + } + func withItalic() -> RenderContext { + var ctx = self; ctx.isItalic = true; return ctx + } + func withStrikethrough() -> RenderContext { + var ctx = self; ctx.isStrikethrough = true; return ctx + } + func indented() -> RenderContext { + var ctx = self; ctx.indentLevel += 1; return ctx + } + func withTextColor(_ color: UIColor) -> RenderContext { + RenderContext( + baseFont: baseFont, + textColor: color, + accentColor: accentColor, + codeBackgroundColor: codeBackgroundColor, + isBold: isBold, + isItalic: isItalic, + isStrikethrough: isStrikethrough, + indentLevel: indentLevel + ) + } + } + + // swiftlint:disable:next cyclomatic_complexity function_body_length + static func appendNodes( + _ nodes: [FireRichTextNode], + to result: NSMutableAttributedString, + context: RenderContext + ) { + for node in nodes { + switch node { + case .text(let text): + let attrs = textAttributes(for: context) + result.append(NSAttributedString(string: text, attributes: attrs)) + + case .bold(let children): + appendNodes(children, to: result, context: context.withBold()) + + case .italic(let children): + appendNodes(children, to: result, context: context.withItalic()) + + case .strikethrough(let children): + appendNodes(children, to: result, context: context.withStrikethrough()) + + case .code(let text): + let codeFont = UIFont.monospacedSystemFont( + ofSize: context.baseFont.pointSize - 1, + weight: .regular + ) + var attrs = textAttributes(for: context) + attrs[.font] = codeFont + attrs[.backgroundColor] = context.codeBackgroundColor + result.append(NSAttributedString(string: text, attributes: attrs)) + + case .codeBlock(_, let code): + ensureBlockBoundary(result) + let codeFont = UIFont.monospacedSystemFont( + ofSize: context.baseFont.pointSize - 1, + weight: .regular + ) + let paragraph = NSMutableParagraphStyle() + paragraph.firstLineHeadIndent = 12 + paragraph.headIndent = 12 + paragraph.tailIndent = -12 + let attrs: [NSAttributedString.Key: Any] = [ + .font: codeFont, + .foregroundColor: context.textColor, + .backgroundColor: context.codeBackgroundColor, + .paragraphStyle: paragraph, + ] + result.append(NSAttributedString(string: code.trimmingCharacters(in: .newlines), attributes: attrs)) + + case .link(let url, let children): + let linkText = NSMutableAttributedString() + appendNodes(children, to: linkText, context: context) + let linkValue: Any = URL(string: url) ?? url + // Apply link attribute to entire range + linkText.addAttributes([ + .foregroundColor: context.accentColor, + .underlineStyle: NSUnderlineStyle.single.rawValue, + .link: linkValue, + ], range: NSRange(location: 0, length: linkText.length)) + result.append(linkText) + + case .mention(let username): + let linkValue: Any = URL(string: profileURLString(for: username)) ?? profileURLString(for: username) + let attrs: [NSAttributedString.Key: Any] = [ + .font: context.currentFont, + .foregroundColor: context.accentColor, + .link: linkValue, + ] + result.append(NSAttributedString(string: "@\(username)", attributes: attrs)) + + case .mentionGroup(let name, let url): + let linkValue: Any = URL(string: url) ?? url + let attrs: [NSAttributedString.Key: Any] = [ + .font: context.currentFont, + .foregroundColor: context.accentColor, + .link: linkValue, + ] + result.append(NSAttributedString(string: "@\(name)", attributes: attrs)) + + case .hashtag(let text, let url, _): + let linkValue: Any = URL(string: url) ?? url + let attrs: [NSAttributedString.Key: Any] = [ + .font: context.currentFont, + .foregroundColor: context.accentColor, + .link: linkValue, + ] + result.append(NSAttributedString(string: "#\(text)", attributes: attrs)) + + case .emoji(let url, let fallbackText, let onlyEmoji): + if let attachment = makeEmojiAttachment( + urlString: url, + fallbackText: fallbackText, + font: context.currentFont, + onlyEmoji: onlyEmoji + ) { + result.append(NSAttributedString(attachment: attachment)) + } else { + result.append(NSAttributedString(string: fallbackText, attributes: textAttributes(for: context))) + } + + case .heading(let level, let children): + ensureBlockBoundary(result) + let headingSize: CGFloat + switch level { + case 1: headingSize = context.baseFont.pointSize + 6 + case 2: headingSize = context.baseFont.pointSize + 4 + case 3: headingSize = context.baseFont.pointSize + 2 + default: headingSize = context.baseFont.pointSize + 1 + } + let headingFont = UIFont.systemFont(ofSize: headingSize, weight: .bold) + var headingContext = context + headingContext.isBold = true + let headingResult = NSMutableAttributedString() + appendNodes(children, to: headingResult, context: headingContext) + let headingRange = NSRange(location: 0, length: headingResult.length) + headingResult.addAttributes([ + .font: headingFont, + .paragraphStyle: headingParagraphStyle(for: headingFont), + ], range: headingRange) + result.append(headingResult) + + case .blockquote(let children): + ensureBlockBoundary(result) + let quoteResult = quoteBlockAttributedString( + author: nil, + postNumber: nil, + topicId: nil, + children: children, + context: context + ) + result.append(quoteResult) + ensureBlockBoundary(result) + + case .quote(let author, let postNumber, let topicId, let children): + ensureBlockBoundary(result) + let quoteResult = quoteBlockAttributedString( + author: author, + postNumber: postNumber, + topicId: topicId, + children: children, + context: context + ) + result.append(quoteResult) + ensureBlockBoundary(result) + + case .onebox( + let url, + let title, + let description, + let sourceName, + _, + _, + _, + _ + ): + ensureBlockBoundary(result) + result.append(oneboxAttributedString( + url: url, + title: title, + description: description, + sourceName: sourceName, + context: context + )) + + case .list(let ordered, let items): + ensureBlockBoundary(result) + for (index, item) in items.enumerated() { + if index > 0 { + ensureLineBreak(result) + } + appendListItem( + item, + marker: ordered ? "\(index + 1). " : "• ", + to: result, + context: context + ) + } + + case .listItem(let children): + ensureLineBreak(result) + appendListItem( + children, + marker: "• ", + to: result, + context: context + ) + + case .spoiler(let children): + let spoiler = NSMutableAttributedString() + appendNodes(children, to: spoiler, context: context) + if spoiler.length > 0 { + spoiler.addAttributes([ + .backgroundColor: UIColor.tertiarySystemFill, + .foregroundColor: FireTheme.uiSubtleInk, + ], range: NSRange(location: 0, length: spoiler.length)) + result.append(spoiler) + } + + case .details(let summary, let children): + ensureBlockBoundary(result) + let summaryResult = NSMutableAttributedString( + string: "▾ ", + attributes: textAttributes(for: context) + ) + appendNodes(summary, to: summaryResult, context: context.withBold()) + result.append(summaryResult) + if !children.isEmpty { + ensureLineBreak(result) + appendNodes(children, to: result, context: context.indented()) + } + + case .table(let text): + ensureBlockBoundary(result) + var attrs = textAttributes(for: context) + attrs[.font] = UIFont.monospacedSystemFont( + ofSize: context.baseFont.pointSize - 1, + weight: .regular + ) + attrs[.backgroundColor] = context.codeBackgroundColor + result.append(NSAttributedString(string: text, attributes: attrs)) + + case .video(let url, let title): + let display = title?.isEmpty == false ? title! : url + let linkValue: Any = URL(string: url) ?? url + result.append(NSAttributedString(string: display, attributes: [ + .font: context.currentFont, + .foregroundColor: context.accentColor, + .underlineStyle: NSUnderlineStyle.single.rawValue, + .link: linkValue, + ])) + + case .divider: + ensureBlockBoundary(result) + // Thin hairline separator (avoid dashed ASCII which reads noisy). + let dividerStyle = NSMutableParagraphStyle() + dividerStyle.paragraphSpacingBefore = 10 + dividerStyle.paragraphSpacing = 10 + dividerStyle.maximumLineHeight = 1 + dividerStyle.minimumLineHeight = 1 + result.append(NSAttributedString( + string: "\u{00A0}", + attributes: [ + .font: UIFont.systemFont(ofSize: 1), + .foregroundColor: UIColor.clear, + .backgroundColor: UIColor.separator.withAlphaComponent(0.55), + .paragraphStyle: dividerStyle, + ] + )) + + case .lineBreak: + result.append(NSAttributedString(string: "\n")) + + case .paragraph(let children): + let start = result.length + ensureBlockBoundary(result) + appendNodes(children, to: result, context: context) + // Slightly airier block rhythm closer to Discourse web spacing. + if result.length > start { + let style = NSMutableParagraphStyle() + style.paragraphSpacing = 8 + style.paragraphSpacingBefore = 2 + style.lineSpacing = 2 + style.lineBreakMode = .byWordWrapping + result.addAttribute( + .paragraphStyle, + value: style, + range: NSRange(location: start, length: result.length - start) + ) + } + + case .image: + break // Handled separately via imageAttachments + } + } + } + + + /// Ensures the next block starts after a single blank-line boundary. + static func ensureBlockBoundary(_ result: NSMutableAttributedString) { + trimTrailingSpaces(result) + guard result.length > 0 else { return } + let text = result.string as NSString + let newlineChar: unichar = 10 + var trailingNewlines = 0 + var idx = text.length - 1 + while idx >= 0 && text.character(at: idx) == newlineChar { + trailingNewlines += 1 + idx -= 1 + } + if trailingNewlines > 2 { + let deleteStart = idx + 3 + result.deleteCharacters(in: NSRange(location: deleteStart, length: trailingNewlines - 2)) + } + if trailingNewlines == 0 { + result.append(NSAttributedString(string: "\n\n")) + } else if trailingNewlines == 1 { + result.append(NSAttributedString(string: "\n")) + } + } + + /// Ensures exactly one trailing newline (for line breaks within blocks). + static func ensureLineBreak(_ result: NSMutableAttributedString) { + trimTrailingSpaces(result) + guard result.length > 0 else { return } + let text = result.string as NSString + let newlineChar: unichar = 10 + if text.length > 0 && text.character(at: text.length - 1) != newlineChar { + result.append(NSAttributedString(string: "\n")) + } + } + + /// Removes trailing space and tab characters from the attributed string. + static func trimTrailingSpaces(_ result: NSMutableAttributedString) { + let text = result.string as NSString + let spaceChar: unichar = 32 + let tabChar: unichar = 9 + var end = text.length + while end > 0 { + let char = text.character(at: end - 1) + if char != spaceChar && char != tabChar { break } + end -= 1 + } + if end < text.length { + result.deleteCharacters(in: NSRange(location: end, length: text.length - end)) + } + } + +} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextEmojiAttachment.swift b/apps/ios-app/App/Views/Shared/FireRichTextEmojiAttachment.swift new file mode 100644 index 00000000..b56eac7f --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextEmojiAttachment.swift @@ -0,0 +1,61 @@ +import UIKit + +extension FireRichTextAttributedStringBuilder { + static func makeEmojiAttachment( + urlString: String, + fallbackText: String, + font: UIFont, + onlyEmoji: Bool + ) -> FireRichTextEmojiAttachment? { + guard let url = URL(string: urlString) else { + return nil + } + + let displaySize = onlyEmoji + ? max(font.pointSize * 1.9, font.pointSize + 10) + : max(font.pointSize * 1.15, font.pointSize + 1) + + return FireRichTextEmojiAttachment( + remoteURL: url, + fallbackText: fallbackText, + displaySize: displaySize, + baselineOffset: font.descender - max(displaySize - font.lineHeight, 0) / 2 + ) + } +} + +final class FireRichTextEmojiAttachment: NSTextAttachment { + let remoteURL: URL + let fallbackText: String + let cacheKey: String + let request: FireRemoteImageRequest + + init( + remoteURL: URL, + fallbackText: String, + displaySize: CGFloat, + baselineOffset: CGFloat + ) { + self.remoteURL = remoteURL + self.fallbackText = fallbackText + self.cacheKey = remoteURL.absoluteString + self.request = FireRemoteImageRequest(url: remoteURL) + super.init(data: nil, ofType: nil) + bounds = CGRect(x: 0, y: baselineOffset, width: displaySize, height: displaySize) + image = Self.placeholderImage(size: displaySize) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func applyLoadedImage(_ loadedImage: UIImage) { + image = loadedImage.preparingForDisplay() ?? loadedImage + } + + private static func placeholderImage(size: CGFloat) -> UIImage { + let renderer = UIGraphicsImageRenderer(size: CGSize(width: max(size, 1), height: max(size, 1))) + return renderer.image { _ in } + } +} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextModels.swift b/apps/ios-app/App/Views/Shared/FireRichTextModels.swift new file mode 100644 index 00000000..89548ba3 --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextModels.swift @@ -0,0 +1,49 @@ +import UIKit + +// MARK: - Rich Text Data Model + +/// Native display node adapted from the shared Rust RenderDocument. +/// Designed to be lightweight and Sendable for off-main-thread rendering. +enum FireRichTextNode: Sendable, Equatable { + case text(String) + case bold([FireRichTextNode]) + case italic([FireRichTextNode]) + case strikethrough([FireRichTextNode]) + case code(String) + case codeBlock(language: String?, code: String) + case link(url: String, children: [FireRichTextNode]) + case mention(username: String) + case mentionGroup(name: String, url: String) + case hashtag(text: String, url: String, kind: String?) + case emoji(url: String, fallbackText: String, onlyEmoji: Bool) + case heading(level: Int, children: [FireRichTextNode]) + case blockquote([FireRichTextNode]) + case quote(author: String?, postNumber: UInt32?, topicId: UInt64?, children: [FireRichTextNode]) + case onebox( + url: String?, + title: String?, + description: String?, + sourceName: String?, + iconURL: String?, + thumbnailURL: String?, + thumbnailWidth: UInt32?, + thumbnailHeight: UInt32? + ) + case list(ordered: Bool, items: [[FireRichTextNode]]) + case listItem([FireRichTextNode]) + case spoiler([FireRichTextNode]) + case details(summary: [FireRichTextNode], children: [FireRichTextNode]) + case table(String) + case video(url: String, title: String?) + case divider + case lineBreak + case paragraph([FireRichTextNode]) + case image(src: String, alt: String?, width: CGFloat?, height: CGFloat?) +} + +/// RenderDocument content adapted for native post display. +struct FireRichTextContent: Sendable { + let nodes: [FireRichTextNode] + let plainText: String + let imageAttachments: [FireCookedImage] +} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextRenderer.swift b/apps/ios-app/App/Views/Shared/FireRichTextRenderer.swift deleted file mode 100644 index 304f4e58..00000000 --- a/apps/ios-app/App/Views/Shared/FireRichTextRenderer.swift +++ /dev/null @@ -1,1283 +0,0 @@ -import SwiftUI -import UIKit - -extension NSAttributedString.Key { - static let fireQuotePreviewBlock = NSAttributedString.Key("FireQuotePreviewBlock") - static let fireQuotePreviewBackgroundColor = NSAttributedString.Key("FireQuotePreviewBackgroundColor") - static let fireQuotePreviewStripeColor = NSAttributedString.Key("FireQuotePreviewStripeColor") -} - -// MARK: - Rich Text Data Model - -/// Native display node adapted from the shared Rust RenderDocument. -/// Designed to be lightweight and Sendable for off-main-thread rendering. -enum FireRichTextNode: Sendable, Equatable { - case text(String) - case bold([FireRichTextNode]) - case italic([FireRichTextNode]) - case strikethrough([FireRichTextNode]) - case code(String) - case codeBlock(language: String?, code: String) - case link(url: String, children: [FireRichTextNode]) - case mention(username: String) - case mentionGroup(name: String, url: String) - case hashtag(text: String, url: String, kind: String?) - case emoji(url: String, fallbackText: String, onlyEmoji: Bool) - case heading(level: Int, children: [FireRichTextNode]) - case blockquote([FireRichTextNode]) - case quote(author: String?, postNumber: UInt32?, topicId: UInt64?, children: [FireRichTextNode]) - case onebox( - url: String?, - title: String?, - description: String?, - sourceName: String?, - iconURL: String?, - thumbnailURL: String?, - thumbnailWidth: UInt32?, - thumbnailHeight: UInt32? - ) - case list(ordered: Bool, items: [[FireRichTextNode]]) - case listItem([FireRichTextNode]) - case spoiler([FireRichTextNode]) - case details(summary: [FireRichTextNode], children: [FireRichTextNode]) - case table(String) - case video(url: String, title: String?) - case divider - case lineBreak - case paragraph([FireRichTextNode]) - case image(src: String, alt: String?, width: CGFloat?, height: CGFloat?) -} - -/// RenderDocument content adapted for native post display. -struct FireRichTextContent: Sendable { - let nodes: [FireRichTextNode] - let plainText: String - let imageAttachments: [FireCookedImage] -} - -// MARK: - AttributedString Builder - -enum FireRichTextAttributedStringBuilder { - /// Compact preview only for Discourse reply-quotes that carry an author/floor. - /// Plain body blockquotes (common OP intro blocks) stay full-length like web. - private static let replyQuotePreviewLineLimit = 4 - private static let replyQuotePreviewCharacterLimit = 220 - - /// Convert parsed nodes into an NSAttributedString suitable for display. - /// Defaults use Fire theme ink tokens (not bare `UIColor.label`) so Texture - /// post cells share the same adaptive palette as the rest of the app. - static func build( - from nodes: [FireRichTextNode], - baseFont: UIFont = .preferredFont(forTextStyle: .subheadline), - textColor: UIColor = FireTheme.uiInk, - accentColor: UIColor = FireTheme.uiAccent, - codeBackgroundColor: UIColor = .secondarySystemBackground - ) -> NSAttributedString { - let result = NSMutableAttributedString() - appendNodes(nodes, to: result, context: RenderContext( - baseFont: baseFont, - textColor: textColor, - accentColor: accentColor, - codeBackgroundColor: codeBackgroundColor, - isBold: false, - isItalic: false, - isStrikethrough: false, - indentLevel: 0 - )) - return result - } - - private struct RenderContext { - let baseFont: UIFont - let textColor: UIColor - let accentColor: UIColor - let codeBackgroundColor: UIColor - var isBold: Bool - var isItalic: Bool - var isStrikethrough: Bool - var indentLevel: Int - - var currentFont: UIFont { - var traits: UIFontDescriptor.SymbolicTraits = [] - if isBold { traits.insert(.traitBold) } - if isItalic { traits.insert(.traitItalic) } - if let descriptor = baseFont.fontDescriptor.withSymbolicTraits(traits) { - return UIFont(descriptor: descriptor, size: baseFont.pointSize) - } - return baseFont - } - - func withBold() -> RenderContext { - var ctx = self; ctx.isBold = true; return ctx - } - func withItalic() -> RenderContext { - var ctx = self; ctx.isItalic = true; return ctx - } - func withStrikethrough() -> RenderContext { - var ctx = self; ctx.isStrikethrough = true; return ctx - } - func indented() -> RenderContext { - var ctx = self; ctx.indentLevel += 1; return ctx - } - func withTextColor(_ color: UIColor) -> RenderContext { - RenderContext( - baseFont: baseFont, - textColor: color, - accentColor: accentColor, - codeBackgroundColor: codeBackgroundColor, - isBold: isBold, - isItalic: isItalic, - isStrikethrough: isStrikethrough, - indentLevel: indentLevel - ) - } - } - - // swiftlint:disable:next cyclomatic_complexity function_body_length - private static func appendNodes( - _ nodes: [FireRichTextNode], - to result: NSMutableAttributedString, - context: RenderContext - ) { - for node in nodes { - switch node { - case .text(let text): - let attrs = textAttributes(for: context) - result.append(NSAttributedString(string: text, attributes: attrs)) - - case .bold(let children): - appendNodes(children, to: result, context: context.withBold()) - - case .italic(let children): - appendNodes(children, to: result, context: context.withItalic()) - - case .strikethrough(let children): - appendNodes(children, to: result, context: context.withStrikethrough()) - - case .code(let text): - let codeFont = UIFont.monospacedSystemFont( - ofSize: context.baseFont.pointSize - 1, - weight: .regular - ) - var attrs = textAttributes(for: context) - attrs[.font] = codeFont - attrs[.backgroundColor] = context.codeBackgroundColor - result.append(NSAttributedString(string: text, attributes: attrs)) - - case .codeBlock(_, let code): - ensureBlockBoundary(result) - let codeFont = UIFont.monospacedSystemFont( - ofSize: context.baseFont.pointSize - 1, - weight: .regular - ) - let paragraph = NSMutableParagraphStyle() - paragraph.firstLineHeadIndent = 12 - paragraph.headIndent = 12 - paragraph.tailIndent = -12 - let attrs: [NSAttributedString.Key: Any] = [ - .font: codeFont, - .foregroundColor: context.textColor, - .backgroundColor: context.codeBackgroundColor, - .paragraphStyle: paragraph, - ] - result.append(NSAttributedString(string: code.trimmingCharacters(in: .newlines), attributes: attrs)) - - case .link(let url, let children): - let linkText = NSMutableAttributedString() - appendNodes(children, to: linkText, context: context) - let linkValue: Any = URL(string: url) ?? url - // Apply link attribute to entire range - linkText.addAttributes([ - .foregroundColor: context.accentColor, - .underlineStyle: NSUnderlineStyle.single.rawValue, - .link: linkValue, - ], range: NSRange(location: 0, length: linkText.length)) - result.append(linkText) - - case .mention(let username): - let linkValue: Any = URL(string: profileURLString(for: username)) ?? profileURLString(for: username) - let attrs: [NSAttributedString.Key: Any] = [ - .font: context.currentFont, - .foregroundColor: context.accentColor, - .link: linkValue, - ] - result.append(NSAttributedString(string: "@\(username)", attributes: attrs)) - - case .mentionGroup(let name, let url): - let linkValue: Any = URL(string: url) ?? url - let attrs: [NSAttributedString.Key: Any] = [ - .font: context.currentFont, - .foregroundColor: context.accentColor, - .link: linkValue, - ] - result.append(NSAttributedString(string: "@\(name)", attributes: attrs)) - - case .hashtag(let text, let url, _): - let linkValue: Any = URL(string: url) ?? url - let attrs: [NSAttributedString.Key: Any] = [ - .font: context.currentFont, - .foregroundColor: context.accentColor, - .link: linkValue, - ] - result.append(NSAttributedString(string: "#\(text)", attributes: attrs)) - - case .emoji(let url, let fallbackText, let onlyEmoji): - if let attachment = makeEmojiAttachment( - urlString: url, - fallbackText: fallbackText, - font: context.currentFont, - onlyEmoji: onlyEmoji - ) { - result.append(NSAttributedString(attachment: attachment)) - } else { - result.append(NSAttributedString(string: fallbackText, attributes: textAttributes(for: context))) - } - - case .heading(let level, let children): - ensureBlockBoundary(result) - let headingSize: CGFloat - switch level { - case 1: headingSize = context.baseFont.pointSize + 6 - case 2: headingSize = context.baseFont.pointSize + 4 - case 3: headingSize = context.baseFont.pointSize + 2 - default: headingSize = context.baseFont.pointSize + 1 - } - let headingFont = UIFont.systemFont(ofSize: headingSize, weight: .bold) - var headingContext = context - headingContext.isBold = true - let headingResult = NSMutableAttributedString() - appendNodes(children, to: headingResult, context: headingContext) - let headingRange = NSRange(location: 0, length: headingResult.length) - headingResult.addAttributes([ - .font: headingFont, - .paragraphStyle: headingParagraphStyle(for: headingFont), - ], range: headingRange) - result.append(headingResult) - - case .blockquote(let children): - ensureBlockBoundary(result) - let quoteResult = quoteBlockAttributedString( - author: nil, - postNumber: nil, - topicId: nil, - children: children, - context: context - ) - result.append(quoteResult) - ensureBlockBoundary(result) - - case .quote(let author, let postNumber, let topicId, let children): - ensureBlockBoundary(result) - let quoteResult = quoteBlockAttributedString( - author: author, - postNumber: postNumber, - topicId: topicId, - children: children, - context: context - ) - result.append(quoteResult) - ensureBlockBoundary(result) - - case .onebox( - let url, - let title, - let description, - let sourceName, - _, - _, - _, - _ - ): - ensureBlockBoundary(result) - result.append(oneboxAttributedString( - url: url, - title: title, - description: description, - sourceName: sourceName, - context: context - )) - - case .list(let ordered, let items): - ensureBlockBoundary(result) - for (index, item) in items.enumerated() { - if index > 0 { - ensureLineBreak(result) - } - appendListItem( - item, - marker: ordered ? "\(index + 1). " : "• ", - to: result, - context: context - ) - } - - case .listItem(let children): - ensureLineBreak(result) - appendListItem( - children, - marker: "• ", - to: result, - context: context - ) - - case .spoiler(let children): - let spoiler = NSMutableAttributedString() - appendNodes(children, to: spoiler, context: context) - if spoiler.length > 0 { - spoiler.addAttributes([ - .backgroundColor: UIColor.tertiarySystemFill, - .foregroundColor: FireTheme.uiSubtleInk, - ], range: NSRange(location: 0, length: spoiler.length)) - result.append(spoiler) - } - - case .details(let summary, let children): - ensureBlockBoundary(result) - let summaryResult = NSMutableAttributedString( - string: "▾ ", - attributes: textAttributes(for: context) - ) - appendNodes(summary, to: summaryResult, context: context.withBold()) - result.append(summaryResult) - if !children.isEmpty { - ensureLineBreak(result) - appendNodes(children, to: result, context: context.indented()) - } - - case .table(let text): - ensureBlockBoundary(result) - var attrs = textAttributes(for: context) - attrs[.font] = UIFont.monospacedSystemFont( - ofSize: context.baseFont.pointSize - 1, - weight: .regular - ) - attrs[.backgroundColor] = context.codeBackgroundColor - result.append(NSAttributedString(string: text, attributes: attrs)) - - case .video(let url, let title): - let display = title?.isEmpty == false ? title! : url - let linkValue: Any = URL(string: url) ?? url - result.append(NSAttributedString(string: display, attributes: [ - .font: context.currentFont, - .foregroundColor: context.accentColor, - .underlineStyle: NSUnderlineStyle.single.rawValue, - .link: linkValue, - ])) - - case .divider: - ensureBlockBoundary(result) - // Thin hairline separator (avoid dashed ASCII which reads noisy). - let dividerStyle = NSMutableParagraphStyle() - dividerStyle.paragraphSpacingBefore = 10 - dividerStyle.paragraphSpacing = 10 - dividerStyle.maximumLineHeight = 1 - dividerStyle.minimumLineHeight = 1 - result.append(NSAttributedString( - string: "\u{00A0}", - attributes: [ - .font: UIFont.systemFont(ofSize: 1), - .foregroundColor: UIColor.clear, - .backgroundColor: UIColor.separator.withAlphaComponent(0.55), - .paragraphStyle: dividerStyle, - ] - )) - - case .lineBreak: - result.append(NSAttributedString(string: "\n")) - - case .paragraph(let children): - let start = result.length - ensureBlockBoundary(result) - appendNodes(children, to: result, context: context) - // Slightly airier block rhythm closer to Discourse web spacing. - if result.length > start { - let style = NSMutableParagraphStyle() - style.paragraphSpacing = 8 - style.paragraphSpacingBefore = 2 - style.lineSpacing = 2 - style.lineBreakMode = .byWordWrapping - result.addAttribute( - .paragraphStyle, - value: style, - range: NSRange(location: start, length: result.length - start) - ) - } - - case .image: - break // Handled separately via imageAttachments - } - } - } - - private static func appendListItem( - _ item: [FireRichTextNode], - marker: String, - to result: NSMutableAttributedString, - context: RenderContext - ) { - let start = result.length - result.append(NSAttributedString(string: marker, attributes: textAttributes(for: context))) - appendListItemContent(item, to: result, context: context.indented()) - guard result.length > start else { - return - } - result.addAttribute( - .paragraphStyle, - value: listParagraphStyle(marker: marker, context: context), - range: NSRange(location: start, length: result.length - start) - ) - } - - private static func appendListItemContent( - _ item: [FireRichTextNode], - to result: NSMutableAttributedString, - context: RenderContext - ) { - guard let first = item.first else { - return - } - - if case .paragraph(let children) = first { - appendNodes(children, to: result, context: context) - let remaining = Array(item.dropFirst()) - if !remaining.isEmpty { - appendNodes(remaining, to: result, context: context) - } - return - } - - appendNodes(item, to: result, context: context) - } - - private static func listParagraphStyle(marker: String, context: RenderContext) -> NSParagraphStyle { - let style = NSMutableParagraphStyle() - let baseIndent = CGFloat(context.indentLevel) * 18 - let markerWidth = ceil((marker as NSString).size(withAttributes: [ - .font: context.currentFont, - ]).width) - style.firstLineHeadIndent = baseIndent - style.headIndent = baseIndent + markerWidth - style.paragraphSpacing = 2 - style.lineBreakMode = .byWordWrapping - return style - } - - /// Ensures the next block starts after a single blank-line boundary. - private static func ensureBlockBoundary(_ result: NSMutableAttributedString) { - trimTrailingSpaces(result) - guard result.length > 0 else { return } - let text = result.string as NSString - let newlineChar: unichar = 10 - var trailingNewlines = 0 - var idx = text.length - 1 - while idx >= 0 && text.character(at: idx) == newlineChar { - trailingNewlines += 1 - idx -= 1 - } - if trailingNewlines > 2 { - let deleteStart = idx + 3 - result.deleteCharacters(in: NSRange(location: deleteStart, length: trailingNewlines - 2)) - } - if trailingNewlines == 0 { - result.append(NSAttributedString(string: "\n\n")) - } else if trailingNewlines == 1 { - result.append(NSAttributedString(string: "\n")) - } - } - - /// Ensures exactly one trailing newline (for line breaks within blocks). - private static func ensureLineBreak(_ result: NSMutableAttributedString) { - trimTrailingSpaces(result) - guard result.length > 0 else { return } - let text = result.string as NSString - let newlineChar: unichar = 10 - if text.length > 0 && text.character(at: text.length - 1) != newlineChar { - result.append(NSAttributedString(string: "\n")) - } - } - - /// Removes trailing space and tab characters from the attributed string. - private static func trimTrailingSpaces(_ result: NSMutableAttributedString) { - let text = result.string as NSString - let spaceChar: unichar = 32 - let tabChar: unichar = 9 - var end = text.length - while end > 0 { - let char = text.character(at: end - 1) - if char != spaceChar && char != tabChar { break } - end -= 1 - } - if end < text.length { - result.deleteCharacters(in: NSRange(location: end, length: text.length - end)) - } - } - - private static func textAttributes( - for context: RenderContext, - overrideColor: UIColor? = nil - ) -> [NSAttributedString.Key: Any] { - var attrs: [NSAttributedString.Key: Any] = [ - .font: context.currentFont, - .foregroundColor: overrideColor ?? context.textColor, - ] - if context.isStrikethrough { - attrs[.strikethroughStyle] = NSUnderlineStyle.single.rawValue - } - return attrs - } - - private static func oneboxAttributedString( - url: String?, - title: String?, - description: String?, - sourceName: String?, - context: RenderContext - ) -> NSAttributedString { - let result = NSMutableAttributedString() - let captionAttributes: [NSAttributedString.Key: Any] = [ - .font: UIFont.preferredFont(forTextStyle: .caption1), - .foregroundColor: FireTheme.uiSubtleInk, - ] - let trimmedSource = sourceName?.trimmingCharacters(in: .whitespacesAndNewlines) - let source = (trimmedSource?.isEmpty == false ? trimmedSource : nil) - ?? url.flatMap { URL(string: $0)?.host?.replacingOccurrences(of: "www.", with: "") } - if let source, !source.isEmpty { - result.append(NSAttributedString(string: source, attributes: captionAttributes)) - } - - let linkValue: Any? - if let url { - linkValue = URL(string: url) ?? url - } else { - linkValue = nil - } - let titleText = title?.trimmingCharacters(in: .whitespacesAndNewlines) - let descriptionText = description?.trimmingCharacters(in: .whitespacesAndNewlines) - - if let titleText, !titleText.isEmpty { - if result.length > 0 { - result.append(NSAttributedString(string: "\n")) - } - var attrs = textAttributes(for: context.withBold()) - attrs[.foregroundColor] = context.accentColor - if let linkValue { - attrs[.link] = linkValue - } - result.append(NSAttributedString(string: titleText, attributes: attrs)) - } - - if let descriptionText, !descriptionText.isEmpty { - if result.length > 0 { - result.append(NSAttributedString(string: "\n")) - } - result.append(NSAttributedString( - string: descriptionText, - attributes: textAttributes(for: context.withTextColor(FireTheme.uiSubtleInk)) - )) - } else if let url, !url.isEmpty, titleText?.isEmpty != false { - if result.length > 0 { - result.append(NSAttributedString(string: "\n")) - } - var attrs = textAttributes(for: context) - attrs[.foregroundColor] = context.accentColor - if let linkValue { - attrs[.link] = linkValue - } - result.append(NSAttributedString(string: url, attributes: attrs)) - } - - let paragraph = NSMutableParagraphStyle() - paragraph.paragraphSpacing = 6 - paragraph.paragraphSpacingBefore = 4 - result.addAttribute(.paragraphStyle, value: paragraph, range: NSRange(location: 0, length: result.length)) - return result - } - - private static func headingParagraphStyle(for font: UIFont) -> NSParagraphStyle { - let paragraph = NSMutableParagraphStyle() - let lineHeight = ceil(font.lineHeight * 1.12) - paragraph.minimumLineHeight = lineHeight - paragraph.maximumLineHeight = lineHeight - paragraph.lineSpacing = max(2, ceil(font.pointSize * 0.12)) - paragraph.paragraphSpacingBefore = 2 - paragraph.paragraphSpacing = 6 - paragraph.lineBreakMode = .byWordWrapping - return paragraph - } - - private static func makeEmojiAttachment( - urlString: String, - fallbackText: String, - font: UIFont, - onlyEmoji: Bool - ) -> FireRichTextEmojiAttachment? { - guard let url = URL(string: urlString) else { - return nil - } - - let displaySize = onlyEmoji - ? max(font.pointSize * 1.9, font.pointSize + 10) - : max(font.pointSize * 1.15, font.pointSize + 1) - - return FireRichTextEmojiAttachment( - remoteURL: url, - fallbackText: fallbackText, - displaySize: displaySize, - baselineOffset: font.descender - max(displaySize - font.lineHeight, 0) / 2 - ) - } - - private static func quoteBlockAttributedString( - author: String?, - postNumber: UInt32?, - topicId: UInt64?, - children: [FireRichTextNode], - context: RenderContext - ) -> NSAttributedString { - let content = NSMutableAttributedString() - let isReplyQuote = !(author?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true) - || postNumber != nil - - if let header = quoteHeaderAttributedString( - author: author, - postNumber: postNumber, - topicId: topicId, - context: context - ) { - content.append(header) - if !children.isEmpty { - content.append(NSAttributedString(string: "\n")) - } - } - - let body = NSMutableAttributedString() - // Body blockquotes should read like surrounding post text (web Discourse), - // while reply-quotes stay slightly de-emphasized. - let bodyContext = isReplyQuote - ? context.indented().withTextColor(FireTheme.uiSubtleInk) - : context.withTextColor(context.textColor) - appendNodes(children, to: body, context: bodyContext) - if isReplyQuote { - content.append(compactReplyQuoteBody(body)) - } else { - content.append(fullBlockquoteBody(body)) - } - - guard content.length > 0 else { - return content - } - - // Discourse-like filled panel — stronger than canvas so the block reads clearly. - let fill = UIColor { traits in - if traits.userInterfaceStyle == .dark { - return UIColor(red: 0.16, green: 0.17, blue: 0.19, alpha: 1) - } - return UIColor(red: 0.90, green: 0.91, blue: 0.93, alpha: 1) // #E6E8ED - } - let stripe = UIColor { traits in - if traits.userInterfaceStyle == .dark { - return UIColor(white: 0.42, alpha: 1) - } - return UIColor(red: 0.68, green: 0.71, blue: 0.76, alpha: 1) - } - - // Include vertical padding in layout height (CALayer pad alone gets clipped). - let padded = NSMutableAttributedString() - padded.append(quotePaddingLine()) - padded.append(content) - padded.append(quotePaddingLine()) - - let paragraph = NSMutableParagraphStyle() - paragraph.paragraphSpacing = 0 - paragraph.paragraphSpacingBefore = 0 - paragraph.lineSpacing = 3 - paragraph.headIndent = 16 - paragraph.firstLineHeadIndent = 16 - paragraph.tailIndent = -12 - paragraph.lineBreakMode = .byWordWrapping - - padded.addAttributes( - [ - .paragraphStyle: paragraph, - .fireQuotePreviewBlock: true, - .fireQuotePreviewBackgroundColor: fill, - .fireQuotePreviewStripeColor: stripe, - ], - range: NSRange(location: 0, length: padded.length) - ) - return padded - } - - private static func quotePaddingLine() -> NSAttributedString { - let style = NSMutableParagraphStyle() - style.minimumLineHeight = 10 - style.maximumLineHeight = 10 - return NSAttributedString( - string: "\u{200B}\n", - attributes: [ - .font: UIFont.systemFont(ofSize: 1), - .foregroundColor: UIColor.clear, - .paragraphStyle: style, - ] - ) - } - - private static func fullBlockquoteBody(_ body: NSAttributedString) -> NSAttributedString { - let result = NSMutableAttributedString(attributedString: body) - // Collapse excessive blank lines inside the quote without truncating content. - collapseExcessiveBlankLines(in: result) - if result.length > 0 { - let font = UIFont.preferredFont(forTextStyle: .body) - result.addAttributes( - [ - .font: font, - .foregroundColor: FireTheme.uiInk.withAlphaComponent(0.88), - ], - range: NSRange(location: 0, length: result.length) - ) - } - return result - } - - private static func compactReplyQuoteBody(_ body: NSAttributedString) -> NSAttributedString { - let compact = NSMutableAttributedString() - let source = body.string as NSString - let ranges = nonBlankLineRanges(in: source) - let selectedRanges = ranges.isEmpty - ? trimmedRange(in: source, range: NSRange(location: 0, length: source.length)).map { [$0] } ?? [] - : Array(ranges.prefix(replyQuotePreviewLineLimit)) - - for (index, range) in selectedRanges.enumerated() { - if index > 0 { - compact.append(NSAttributedString(string: "\n")) - } - compact.append(body.attributedSubstring(from: range)) - } - - truncateQuoteBody(compact) - if compact.length > 0 { - compact.addAttributes( - [ - .font: UIFont.preferredFont(forTextStyle: .subheadline), - .foregroundColor: FireTheme.uiSubtleInk, - ], - range: NSRange(location: 0, length: compact.length) - ) - } - return compact - } - - private static func collapseExcessiveBlankLines(in body: NSMutableAttributedString) { - var text = body.string as NSString - while text.contains("\n\n\n") { - let range = text.range(of: "\n\n\n") - guard range.location != NSNotFound else { break } - body.replaceCharacters(in: range, with: "\n\n") - text = body.string as NSString - } - } - - private static func nonBlankLineRanges(in source: NSString) -> [NSRange] { - var ranges: [NSRange] = [] - var lineStart = 0 - while lineStart <= source.length { - let searchRange = NSRange(location: lineStart, length: source.length - lineStart) - let newlineRange = source.range(of: "\n", options: [], range: searchRange) - let lineEnd = newlineRange.location == NSNotFound ? source.length : newlineRange.location - if let range = trimmedRange( - in: source, - range: NSRange(location: lineStart, length: lineEnd - lineStart) - ) { - ranges.append(range) - } - if lineEnd >= source.length { - break - } - lineStart = lineEnd + 1 - } - return ranges - } - - private static func trimmedRange(in source: NSString, range: NSRange) -> NSRange? { - var location = range.location - var end = range.location + range.length - let whitespace = CharacterSet.whitespacesAndNewlines - while location < end, - let scalar = UnicodeScalar(source.character(at: location)), - whitespace.contains(scalar) { - location += 1 - } - while end > location, - let scalar = UnicodeScalar(source.character(at: end - 1)), - whitespace.contains(scalar) { - end -= 1 - } - return location < end - ? NSRange(location: location, length: end - location) - : nil - } - - private static func truncateQuoteBody(_ body: NSMutableAttributedString) { - let maxLength = replyQuotePreviewCharacterLimit - let ellipsis = "…" - guard body.length > maxLength else { - return - } - body.deleteCharacters(in: NSRange(location: maxLength - ellipsis.count, length: body.length - (maxLength - ellipsis.count))) - while body.length > 0, - let scalar = UnicodeScalar((body.string as NSString).character(at: body.length - 1)), - CharacterSet.whitespacesAndNewlines.contains(scalar) { - body.deleteCharacters(in: NSRange(location: body.length - 1, length: 1)) - } - body.append(NSAttributedString(string: ellipsis)) - } - - private static func quoteHeaderAttributedString( - author: String?, - postNumber: UInt32?, - topicId: UInt64?, - context: RenderContext - ) -> NSAttributedString? { - let trimmedAuthor = author?.trimmingCharacters(in: .whitespacesAndNewlines) - guard (trimmedAuthor?.isEmpty == false) || postNumber != nil else { - return nil - } - - let font = UIFont.preferredFont(forTextStyle: .caption1) - let baseAttributes: [NSAttributedString.Key: Any] = [ - .font: font, - .foregroundColor: FireTheme.uiSubtleInk, - ] - let result = NSMutableAttributedString(string: "引用", attributes: baseAttributes) - - if let trimmedAuthor, !trimmedAuthor.isEmpty { - result.append(NSAttributedString(string: " ", attributes: baseAttributes)) - let profileLink: Any = URL(string: profileURLString(for: trimmedAuthor)) ?? profileURLString(for: trimmedAuthor) - result.append(NSAttributedString(string: "@\(trimmedAuthor)", attributes: [ - .font: font, - .foregroundColor: context.accentColor, - .link: profileLink, - ])) - } - - if let postNumber { - result.append(NSAttributedString(string: " · ", attributes: baseAttributes)) - var postAttributes = baseAttributes - postAttributes[.foregroundColor] = context.accentColor - if let topicId { - postAttributes[.link] = URL(string: topicURLString(topicId: topicId, postNumber: postNumber)) - ?? topicURLString(topicId: topicId, postNumber: postNumber) - } - result.append(NSAttributedString(string: "#\(postNumber)", attributes: postAttributes)) - } - - return result - } - - private static func prefixedLines( - in attributedString: NSAttributedString, - prefix: NSAttributedString - ) -> NSMutableAttributedString { - let result = NSMutableAttributedString() - let fullString = attributedString.string as NSString - - guard fullString.length > 0 else { - return result - } - - var location = 0 - while location < fullString.length { - let lineRange = fullString.lineRange(for: NSRange(location: location, length: 0)) - result.append(prefix) - result.append(attributedString.attributedSubstring(from: lineRange)) - location = NSMaxRange(lineRange) - } - - return result - } - - private static func profileURLString(for username: String) -> String { - let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? username - return "fire://profile/\(encodedUsername)" - } - - private static func topicURLString(topicId: UInt64, postNumber: UInt32?) -> String { - if let postNumber { - return "fire://topic/\(topicId)/\(postNumber)" - } - return "fire://topic/\(topicId)" - } -} - -final class FireRichTextEmojiAttachment: NSTextAttachment { - let remoteURL: URL - let fallbackText: String - let cacheKey: String - let request: FireRemoteImageRequest - - init( - remoteURL: URL, - fallbackText: String, - displaySize: CGFloat, - baselineOffset: CGFloat - ) { - self.remoteURL = remoteURL - self.fallbackText = fallbackText - self.cacheKey = remoteURL.absoluteString - self.request = FireRemoteImageRequest(url: remoteURL) - super.init(data: nil, ofType: nil) - bounds = CGRect(x: 0, y: baselineOffset, width: displaySize, height: displaySize) - image = Self.placeholderImage(size: displaySize) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - func applyLoadedImage(_ loadedImage: UIImage) { - image = loadedImage.preparingForDisplay() ?? loadedImage - } - - private static func placeholderImage(size: CGFloat) -> UIImage { - let renderer = UIGraphicsImageRenderer(size: CGSize(width: max(size, 1), height: max(size, 1))) - return renderer.image { _ in } - } -} - -// MARK: - SwiftUI Integration - -/// A UIViewRepresentable that displays rich attributed text with interactive links. -struct FireRichTextView: UIViewRepresentable { - let contentID: String - let attributedString: NSAttributedString - let onLinkTapped: ((URL) -> Void)? - - init( - contentID: String, - attributedString: NSAttributedString, - onLinkTapped: ((URL) -> Void)? = nil - ) { - self.contentID = contentID - self.attributedString = attributedString - self.onLinkTapped = onLinkTapped - } - - func makeUIView(context: Context) -> FireRichTextUIView { - let view = FireRichTextUIView() - view.isEditable = false - view.isScrollEnabled = false - view.textContainerInset = .zero - view.textContainer.lineFragmentPadding = 0 - view.backgroundColor = .clear - view.linkTextAttributes = [ - .foregroundColor: UIColor.systemBlue, - .underlineStyle: NSUnderlineStyle.single.rawValue, - ] - view.delegate = context.coordinator - view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - view.setContentHuggingPriority(.defaultHigh, for: .vertical) - return view - } - - func updateUIView(_ uiView: FireRichTextUIView, context: Context) { - if uiView.renderedContentID != contentID { - uiView.renderedContentID = contentID - uiView.attributedText = attributedString - uiView.invalidateIntrinsicContentSize() - } - context.coordinator.onLinkTapped = onLinkTapped - } - - func makeCoordinator() -> Coordinator { - Coordinator(onLinkTapped: onLinkTapped) - } - - class Coordinator: NSObject, UITextViewDelegate { - var onLinkTapped: ((URL) -> Void)? - - init(onLinkTapped: ((URL) -> Void)?) { - self.onLinkTapped = onLinkTapped - } - - func textView( - _ textView: UITextView, - shouldInteractWith URL: URL, - in characterRange: NSRange, - interaction: UITextItemInteraction - ) -> Bool { - onLinkTapped?(URL) - return false - } - } -} - -class FireRichTextTextView: UITextView { - private var quotePreviewLayers: [CALayer] = [] - - override func layoutSubviews() { - super.layoutSubviews() - updateQuotePreviewLayers() - } - - override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { - super.traitCollectionDidChange(previousTraitCollection) - updateQuotePreviewLayers() - } - - func refreshQuotePreviewLayers() { - updateQuotePreviewLayers() - } - - private func updateQuotePreviewLayers() { - quotePreviewLayers.forEach { $0.removeFromSuperlayer() } - quotePreviewLayers.removeAll() - - guard let attributedText, - attributedText.length > 0, - bounds.width > 1 else { - return - } - - let fullRange = NSRange(location: 0, length: attributedText.length) - attributedText.enumerateAttribute(.fireQuotePreviewBlock, in: fullRange) { [weak self] value, range, _ in - guard let self, value != nil else { - return - } - self.addQuotePreviewLayer(for: range, attributedText: attributedText) - } - } - - private func addQuotePreviewLayer(for characterRange: NSRange, attributedText: NSAttributedString) { - guard characterRange.length > 0 else { - return - } - - layoutManager.ensureLayout(for: textContainer) - let glyphRange = layoutManager.glyphRange( - forCharacterRange: characterRange, - actualCharacterRange: nil - ) - guard glyphRange.length > 0 else { - return - } - - var unionRect = CGRect.null - layoutManager.enumerateLineFragments(forGlyphRange: glyphRange) { _, usedRect, _, lineGlyphRange, _ in - guard NSIntersectionRange(glyphRange, lineGlyphRange).length > 0 else { - return - } - let lineRect = CGRect( - x: self.textContainerInset.left, - y: self.textContainerInset.top + usedRect.minY - self.contentOffset.y, - width: max(self.bounds.width - self.textContainerInset.left - self.textContainerInset.right, 1), - height: usedRect.height - ) - unionRect = unionRect.isNull ? lineRect : unionRect.union(lineRect) - } - - guard !unionRect.isNull else { - return - } - - let backgroundColor = attributedText.attribute( - .fireQuotePreviewBackgroundColor, - at: characterRange.location, - effectiveRange: nil - ) as? UIColor ?? .secondarySystemBackground - let stripeColor = attributedText.attribute( - .fireQuotePreviewStripeColor, - at: characterRange.location, - effectiveRange: nil - ) as? UIColor ?? .tertiaryLabel - - // Background tracks layout glyphs (padding lines already baked into text). - let backgroundRect = CGRect( - x: textContainerInset.left, - y: unionRect.minY - 2, - width: max(bounds.width - textContainerInset.left - textContainerInset.right, 1), - height: unionRect.height + 4 - ).intersection(bounds.insetBy(dx: 0, dy: -2)) - guard !backgroundRect.isNull, backgroundRect.height > 1 else { - return - } - - let backgroundLayer = CAShapeLayer() - backgroundLayer.fillColor = backgroundColor.resolvedColor(with: traitCollection).cgColor - backgroundLayer.path = UIBezierPath( - roundedRect: backgroundRect, - cornerRadius: 8 - ).cgPath - layer.insertSublayer(backgroundLayer, at: 0) - quotePreviewLayers.append(backgroundLayer) - - // Left accent bar (blockquote border-left). - let stripeRect = CGRect( - x: backgroundRect.minX + 8, - y: backgroundRect.minY + 8, - width: 4, - height: max(backgroundRect.height - 16, 1) - ) - let stripeLayer = CAShapeLayer() - stripeLayer.fillColor = stripeColor.resolvedColor(with: traitCollection).cgColor - stripeLayer.path = UIBezierPath( - roundedRect: stripeRect, - cornerRadius: 2 - ).cgPath - layer.insertSublayer(stripeLayer, above: backgroundLayer) - quotePreviewLayers.append(stripeLayer) - } -} - -/// Custom UITextView that sizes itself to content. -final class FireRichTextUIView: FireRichTextTextView { - private static let intrinsicHeightCache = NSCache() - - var renderedContentID: String? - private var emojiLoadTasks: [String: Task] = [:] - private var measuredWidth: CGFloat = 0 - private var cachedIntrinsicHeight: CGFloat? - - deinit { - cancelEmojiLoadTasks() - } - - override var attributedText: NSAttributedString! { - didSet { - resetIntrinsicMeasurement() - cancelEmojiLoadTasks() - loadEmojiAttachmentsIfNeeded() - refreshQuotePreviewLayers() - } - } - - override var intrinsicContentSize: CGSize { - let width = resolvedMeasurementWidth() - if let cachedIntrinsicHeight, abs(width - measuredWidth) < 0.5 { - return CGSize(width: UIView.noIntrinsicMetric, height: cachedIntrinsicHeight) - } - - if let renderedContentID, - let cachedHeight = Self.intrinsicHeightCache.object( - forKey: intrinsicHeightCacheKey(contentID: renderedContentID, width: width) - ) { - measuredWidth = width - cachedIntrinsicHeight = CGFloat(truncating: cachedHeight) - return CGSize(width: UIView.noIntrinsicMetric, height: CGFloat(truncating: cachedHeight)) - } - - let size = sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)) - let resolvedHeight = ceil(size.height) - measuredWidth = width - cachedIntrinsicHeight = resolvedHeight - if let renderedContentID { - Self.intrinsicHeightCache.setObject( - NSNumber(value: resolvedHeight), - forKey: intrinsicHeightCacheKey(contentID: renderedContentID, width: width) - ) - } - return CGSize(width: UIView.noIntrinsicMetric, height: resolvedHeight) - } - - override func layoutSubviews() { - super.layoutSubviews() - let width = resolvedMeasurementWidth() - if abs(width - measuredWidth) >= 0.5 { - cachedIntrinsicHeight = nil - invalidateIntrinsicContentSize() - } - } - - private func resolvedMeasurementWidth() -> CGFloat { - let width = bounds.width > 0 ? bounds.width : UIScreen.main.bounds.width - 80 - return max(width, 1) - } - - private func cancelEmojiLoadTasks() { - emojiLoadTasks.values.forEach { $0.cancel() } - emojiLoadTasks.removeAll() - } - - private func resetIntrinsicMeasurement() { - measuredWidth = 0 - cachedIntrinsicHeight = nil - } - - private func intrinsicHeightCacheKey(contentID: String, width: CGFloat) -> NSString { - let scaledWidth = Int((width * UIScreen.main.scale).rounded()) - return "\(contentID)|w:\(scaledWidth)" as NSString - } - - private func loadEmojiAttachmentsIfNeeded() { - guard attributedText.length > 0 else { - return - } - - let fullRange = NSRange(location: 0, length: attributedText.length) - attributedText.enumerateAttribute(.attachment, in: fullRange) { [weak self] value, _, _ in - guard let self, - let attachment = value as? FireRichTextEmojiAttachment else { - return - } - - let cacheKey = attachment.cacheKey - guard emojiLoadTasks[cacheKey] == nil else { - return - } - - if let cachedImage = FireRemoteImagePipeline.shared.cachedImage(for: attachment.request) { - applyEmojiImage(cachedImage, for: cacheKey) - return - } - - emojiLoadTasks[cacheKey] = Task { [weak self] in - do { - let image = try await FireRemoteImagePipeline.shared.loadImage(for: attachment.request) - guard !Task.isCancelled else { - return - } - await MainActor.run { - guard let self else { - return - } - self.applyEmojiImage(image, for: cacheKey) - self.emojiLoadTasks.removeValue(forKey: cacheKey) - } - } catch { - await MainActor.run { - _ = self?.emojiLoadTasks.removeValue(forKey: cacheKey) - } - } - } - } - } - - private func applyEmojiImage(_ image: UIImage, for cacheKey: String) { - guard textStorage.length > 0 else { - return - } - - let fullRange = NSRange(location: 0, length: textStorage.length) - var changedRange = NSRange(location: NSNotFound, length: 0) - textStorage.beginEditing() - textStorage.enumerateAttribute(.attachment, in: fullRange) { value, range, _ in - guard let attachment = value as? FireRichTextEmojiAttachment, - attachment.cacheKey == cacheKey else { - return - } - attachment.applyLoadedImage(image) - textStorage.addAttribute(.attachment, value: attachment, range: range) - changedRange = changedRange.location == NSNotFound - ? range - : NSUnionRange(changedRange, range) - } - textStorage.endEditing() - - guard changedRange.location != NSNotFound else { - return - } - - layoutManager.invalidateDisplay(forCharacterRange: changedRange) - setNeedsLayout() - } -} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextTextView.swift b/apps/ios-app/App/Views/Shared/FireRichTextTextView.swift new file mode 100644 index 00000000..97745cb7 --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextTextView.swift @@ -0,0 +1,277 @@ +import UIKit + +extension NSAttributedString.Key { + static let fireQuotePreviewBlock = NSAttributedString.Key("FireQuotePreviewBlock") + static let fireQuotePreviewBackgroundColor = NSAttributedString.Key("FireQuotePreviewBackgroundColor") + static let fireQuotePreviewStripeColor = NSAttributedString.Key("FireQuotePreviewStripeColor") +} + +class FireRichTextTextView: UITextView { + private var quotePreviewLayers: [CALayer] = [] + + override func layoutSubviews() { + super.layoutSubviews() + updateQuotePreviewLayers() + } + + override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { + super.traitCollectionDidChange(previousTraitCollection) + updateQuotePreviewLayers() + } + + func refreshQuotePreviewLayers() { + updateQuotePreviewLayers() + } + + private func updateQuotePreviewLayers() { + quotePreviewLayers.forEach { $0.removeFromSuperlayer() } + quotePreviewLayers.removeAll() + + guard let attributedText, + attributedText.length > 0, + bounds.width > 1 else { + return + } + + let fullRange = NSRange(location: 0, length: attributedText.length) + attributedText.enumerateAttribute(.fireQuotePreviewBlock, in: fullRange) { [weak self] value, range, _ in + guard let self, value != nil else { + return + } + self.addQuotePreviewLayer(for: range, attributedText: attributedText) + } + } + + private func addQuotePreviewLayer(for characterRange: NSRange, attributedText: NSAttributedString) { + guard characterRange.length > 0 else { + return + } + + layoutManager.ensureLayout(for: textContainer) + let glyphRange = layoutManager.glyphRange( + forCharacterRange: characterRange, + actualCharacterRange: nil + ) + guard glyphRange.length > 0 else { + return + } + + var unionRect = CGRect.null + layoutManager.enumerateLineFragments(forGlyphRange: glyphRange) { _, usedRect, _, lineGlyphRange, _ in + guard NSIntersectionRange(glyphRange, lineGlyphRange).length > 0 else { + return + } + let lineRect = CGRect( + x: self.textContainerInset.left, + y: self.textContainerInset.top + usedRect.minY - self.contentOffset.y, + width: max(self.bounds.width - self.textContainerInset.left - self.textContainerInset.right, 1), + height: usedRect.height + ) + unionRect = unionRect.isNull ? lineRect : unionRect.union(lineRect) + } + + guard !unionRect.isNull else { + return + } + + let backgroundColor = attributedText.attribute( + .fireQuotePreviewBackgroundColor, + at: characterRange.location, + effectiveRange: nil + ) as? UIColor ?? .secondarySystemBackground + let stripeColor = attributedText.attribute( + .fireQuotePreviewStripeColor, + at: characterRange.location, + effectiveRange: nil + ) as? UIColor ?? .tertiaryLabel + + // Background tracks layout glyphs (padding lines already baked into text). + let backgroundRect = CGRect( + x: textContainerInset.left, + y: unionRect.minY - 2, + width: max(bounds.width - textContainerInset.left - textContainerInset.right, 1), + height: unionRect.height + 4 + ).intersection(bounds.insetBy(dx: 0, dy: -2)) + guard !backgroundRect.isNull, backgroundRect.height > 1 else { + return + } + + let backgroundLayer = CAShapeLayer() + backgroundLayer.fillColor = backgroundColor.resolvedColor(with: traitCollection).cgColor + backgroundLayer.path = UIBezierPath( + roundedRect: backgroundRect, + cornerRadius: 8 + ).cgPath + layer.insertSublayer(backgroundLayer, at: 0) + quotePreviewLayers.append(backgroundLayer) + + // Left accent bar (blockquote border-left). + let stripeRect = CGRect( + x: backgroundRect.minX + 8, + y: backgroundRect.minY + 8, + width: 4, + height: max(backgroundRect.height - 16, 1) + ) + let stripeLayer = CAShapeLayer() + stripeLayer.fillColor = stripeColor.resolvedColor(with: traitCollection).cgColor + stripeLayer.path = UIBezierPath( + roundedRect: stripeRect, + cornerRadius: 2 + ).cgPath + layer.insertSublayer(stripeLayer, above: backgroundLayer) + quotePreviewLayers.append(stripeLayer) + } +} + +/// Custom UITextView that sizes itself to content. +final class FireRichTextUIView: FireRichTextTextView { + private static let intrinsicHeightCache = NSCache() + + var renderedContentID: String? + private var emojiLoadTasks: [String: Task] = [:] + private var measuredWidth: CGFloat = 0 + private var cachedIntrinsicHeight: CGFloat? + + deinit { + cancelEmojiLoadTasks() + } + + override var attributedText: NSAttributedString! { + didSet { + resetIntrinsicMeasurement() + cancelEmojiLoadTasks() + loadEmojiAttachmentsIfNeeded() + refreshQuotePreviewLayers() + } + } + + override var intrinsicContentSize: CGSize { + let width = resolvedMeasurementWidth() + if let cachedIntrinsicHeight, abs(width - measuredWidth) < 0.5 { + return CGSize(width: UIView.noIntrinsicMetric, height: cachedIntrinsicHeight) + } + + if let renderedContentID, + let cachedHeight = Self.intrinsicHeightCache.object( + forKey: intrinsicHeightCacheKey(contentID: renderedContentID, width: width) + ) { + measuredWidth = width + cachedIntrinsicHeight = CGFloat(truncating: cachedHeight) + return CGSize(width: UIView.noIntrinsicMetric, height: CGFloat(truncating: cachedHeight)) + } + + let size = sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)) + let resolvedHeight = ceil(size.height) + measuredWidth = width + cachedIntrinsicHeight = resolvedHeight + if let renderedContentID { + Self.intrinsicHeightCache.setObject( + NSNumber(value: resolvedHeight), + forKey: intrinsicHeightCacheKey(contentID: renderedContentID, width: width) + ) + } + return CGSize(width: UIView.noIntrinsicMetric, height: resolvedHeight) + } + + override func layoutSubviews() { + super.layoutSubviews() + let width = resolvedMeasurementWidth() + if abs(width - measuredWidth) >= 0.5 { + cachedIntrinsicHeight = nil + invalidateIntrinsicContentSize() + } + } + + private func resolvedMeasurementWidth() -> CGFloat { + let width = bounds.width > 0 ? bounds.width : UIScreen.main.bounds.width - 80 + return max(width, 1) + } + + private func cancelEmojiLoadTasks() { + emojiLoadTasks.values.forEach { $0.cancel() } + emojiLoadTasks.removeAll() + } + + private func resetIntrinsicMeasurement() { + measuredWidth = 0 + cachedIntrinsicHeight = nil + } + + private func intrinsicHeightCacheKey(contentID: String, width: CGFloat) -> NSString { + let scaledWidth = Int((width * UIScreen.main.scale).rounded()) + return "\(contentID)|w:\(scaledWidth)" as NSString + } + + private func loadEmojiAttachmentsIfNeeded() { + guard attributedText.length > 0 else { + return + } + + let fullRange = NSRange(location: 0, length: attributedText.length) + attributedText.enumerateAttribute(.attachment, in: fullRange) { [weak self] value, _, _ in + guard let self, + let attachment = value as? FireRichTextEmojiAttachment else { + return + } + + let cacheKey = attachment.cacheKey + guard emojiLoadTasks[cacheKey] == nil else { + return + } + + if let cachedImage = FireRemoteImagePipeline.shared.cachedImage(for: attachment.request) { + applyEmojiImage(cachedImage, for: cacheKey) + return + } + + emojiLoadTasks[cacheKey] = Task { [weak self] in + do { + let image = try await FireRemoteImagePipeline.shared.loadImage(for: attachment.request) + guard !Task.isCancelled else { + return + } + await MainActor.run { + guard let self else { + return + } + self.applyEmojiImage(image, for: cacheKey) + self.emojiLoadTasks.removeValue(forKey: cacheKey) + } + } catch { + await MainActor.run { + _ = self?.emojiLoadTasks.removeValue(forKey: cacheKey) + } + } + } + } + } + + private func applyEmojiImage(_ image: UIImage, for cacheKey: String) { + guard textStorage.length > 0 else { + return + } + + let fullRange = NSRange(location: 0, length: textStorage.length) + var changedRange = NSRange(location: NSNotFound, length: 0) + textStorage.beginEditing() + textStorage.enumerateAttribute(.attachment, in: fullRange) { value, range, _ in + guard let attachment = value as? FireRichTextEmojiAttachment, + attachment.cacheKey == cacheKey else { + return + } + attachment.applyLoadedImage(image) + textStorage.addAttribute(.attachment, value: attachment, range: range) + changedRange = changedRange.location == NSNotFound + ? range + : NSUnionRange(changedRange, range) + } + textStorage.endEditing() + + guard changedRange.location != NSNotFound else { + return + } + + layoutManager.invalidateDisplay(forCharacterRange: changedRange) + setNeedsLayout() + } +} diff --git a/apps/ios-app/App/Views/Shared/FireRichTextView.swift b/apps/ios-app/App/Views/Shared/FireRichTextView.swift new file mode 100644 index 00000000..155dfbfe --- /dev/null +++ b/apps/ios-app/App/Views/Shared/FireRichTextView.swift @@ -0,0 +1,67 @@ +import SwiftUI +import UIKit + +/// A UIViewRepresentable that displays rich attributed text with interactive links. +struct FireRichTextView: UIViewRepresentable { + let contentID: String + let attributedString: NSAttributedString + let onLinkTapped: ((URL) -> Void)? + + init( + contentID: String, + attributedString: NSAttributedString, + onLinkTapped: ((URL) -> Void)? = nil + ) { + self.contentID = contentID + self.attributedString = attributedString + self.onLinkTapped = onLinkTapped + } + + func makeUIView(context: Context) -> FireRichTextUIView { + let view = FireRichTextUIView() + view.isEditable = false + view.isScrollEnabled = false + view.textContainerInset = .zero + view.textContainer.lineFragmentPadding = 0 + view.backgroundColor = .clear + view.linkTextAttributes = [ + .foregroundColor: UIColor.systemBlue, + .underlineStyle: NSUnderlineStyle.single.rawValue, + ] + view.delegate = context.coordinator + view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + view.setContentHuggingPriority(.defaultHigh, for: .vertical) + return view + } + + func updateUIView(_ uiView: FireRichTextUIView, context: Context) { + if uiView.renderedContentID != contentID { + uiView.renderedContentID = contentID + uiView.attributedText = attributedString + uiView.invalidateIntrinsicContentSize() + } + context.coordinator.onLinkTapped = onLinkTapped + } + + func makeCoordinator() -> Coordinator { + Coordinator(onLinkTapped: onLinkTapped) + } + + class Coordinator: NSObject, UITextViewDelegate { + var onLinkTapped: ((URL) -> Void)? + + init(onLinkTapped: ((URL) -> Void)?) { + self.onLinkTapped = onLinkTapped + } + + func textView( + _ textView: UITextView, + shouldInteractWith URL: URL, + in characterRange: NSRange, + interaction: UITextItemInteraction + ) -> Bool { + onLinkTapped?(URL) + return false + } + } +} diff --git a/apps/ios-app/Fire.xcodeproj/project.pbxproj b/apps/ios-app/Fire.xcodeproj/project.pbxproj index 41810659..f30c1a7c 100644 --- a/apps/ios-app/Fire.xcodeproj/project.pbxproj +++ b/apps/ios-app/Fire.xcodeproj/project.pbxproj @@ -8,6 +8,9 @@ /* Begin PBXBuildFile section */ 0006B08A873FC6192E616F01 /* FireApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 996D95DE48DA65385BD587F7 /* FireApp.swift */; }; + 003C84E56BD714FB4E63880A /* FireCapturedLoginState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA0AC514C9C8CDBCF7F7606 /* FireCapturedLoginState.swift */; }; + 0088C39494610623784F8F75 /* FireRichTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6010A6F4219781F54CBD809 /* FireRichTextView.swift */; }; + 010562DD593DC1AB44C95A30 /* FireTopicDetailReplyFooterCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 377285D279E45E4211DC2CEA /* FireTopicDetailReplyFooterCell.swift */; }; 0117AF25FD8334DB2C46A933 /* FirePostBoostManualScrollerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20A1C7BA55C3D9BCB48898A3 /* FirePostBoostManualScrollerView.swift */; }; 025A7AA228A13732EF43828B /* FireUserCardViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B8FD2EBF4867A3E5C5A1EF9 /* FireUserCardViewController.swift */; }; 02880D7A3651EFC8EF3AA607 /* FireTopicDetailSnapshotAssembler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AE3D99CBA147535E68FB7E6 /* FireTopicDetailSnapshotAssembler.swift */; }; @@ -16,116 +19,194 @@ 0344231CB80C3CAD4A0DCBEC /* FireMidSessionReauthOverlayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7299AEA008EC0AE578A1712 /* FireMidSessionReauthOverlayController.swift */; }; 034DDDD09E919D20852775B6 /* FireChatChannelViewController+Load.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7408129F7C65831B92FBCEF7 /* FireChatChannelViewController+Load.swift */; }; 039707A4CADBA6A80DDB0F70 /* FireLoginScriptsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 140FAA0B35B71300049C7E14 /* FireLoginScriptsTests.swift */; }; + 048472E4653C3369CFBA9E8D /* FireChatListSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 519940DDA0A5323D3793D653 /* FireChatListSession.swift */; }; 04AB0C15F52072F2E720E47F /* FireTopicDetailControllerHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDC30347DC7392AAA6A27435 /* FireTopicDetailControllerHost.swift */; }; + 05B47B0532C0792EB8DD065E /* FireTopicDetailViewController+PostManagement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0789B19C92B2B04D685F52AE /* FireTopicDetailViewController+PostManagement.swift */; }; 05F49A82B0CDC6486E7250F9 /* FireTopicDetailStore+Presence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2641F70C8CEAE937D1D4A75D /* FireTopicDetailStore+Presence.swift */; }; + 06481C894DF2A0F311026245 /* FireReadHistoryViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4C08B418B91DCB198040E33 /* FireReadHistoryViewController+Feed.swift */; }; + 06CFAD44C21F19A9DEB208CB /* FireTopicQuickReplyBarView+Appearance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95EE99D01738B2B77B705BCE /* FireTopicQuickReplyBarView+Appearance.swift */; }; + 071F0BD73521F036C04F6EAC /* FireOnboardingCredentialFormView+Fields.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53B37883C9DB898936D74AAF /* FireOnboardingCredentialFormView+Fields.swift */; }; 0738F9AD86263ECE2016A8D4 /* FireTagPickerSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BA62EEC87348A069D789A7E /* FireTagPickerSheet.swift */; }; + 0742DA5CCE3B1147AE444C6D /* FireRichTextTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49DFB8ED64CAE57ADDFABFD6 /* FireRichTextTextView.swift */; }; + 080322BE83553F16044A25D6 /* FireBookmarksViewController+Pagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54C93686EAAB54DE7694FFF1 /* FireBookmarksViewController+Pagination.swift */; }; 0829CF9A9EE33EA119F94468 /* FireWidgetData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4543C11B22E10FA9DA852E16 /* FireWidgetData.swift */; }; 087AF23CD1F909A1BFC87312 /* FireNetworkDiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92C90A87682AF244F048541F /* FireNetworkDiagnosticsView.swift */; }; 0964DB91A22F07DD40FE1ADA /* FireTopicDetailViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 457CCC7AE29267A8B9448BA7 /* FireTopicDetailViewController.swift */; }; + 096FCFD1EBD6F9EFB0A15360 /* FireTopicDetailRuntimeReplyFooterState.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA57FDBE9059EEC76EB630B /* FireTopicDetailRuntimeReplyFooterState.swift */; }; 09D7B4DCFB71311E9D856D59 /* FireTopicDetailRuntimeSnapshotBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5592C6396CAD3B7F3672D0EA /* FireTopicDetailRuntimeSnapshotBuilder.swift */; }; 09DEF34E484D68FE6A3A1AC5 /* FireTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0AA3F1257384BF109634D21 /* FireTheme.swift */; }; + 0A5EDE218163F9336EE58723 /* FirePanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9071081BCCEC2A924CEC92C /* FirePanel.swift */; }; 0A63CF028063304243D985F8 /* FireNotificationListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36AF08512A66853830920C56 /* FireNotificationListCell.swift */; }; 0AABB8FE83B25A7D6D7C67FC /* FireCfClearanceRefreshService.swift in Sources */ = {isa = PBXBuildFile; fileRef = F01E5248AEF9002E2919AC0F /* FireCfClearanceRefreshService.swift */; }; + 0BA0F58971A336C8C7AEAAD2 /* FireAppViewModel+Authentication.swift in Sources */ = {isa = PBXBuildFile; fileRef = 928B370E2F406092C99E5F84 /* FireAppViewModel+Authentication.swift */; }; + 0BC8C37BB8F4054577565B78 /* FireTopicDetailModalRouter+Composer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A75DAF7497176CDFF260E139 /* FireTopicDetailModalRouter+Composer.swift */; }; 0C251ED7E4C214F8E2F7E7C2 /* AsyncDisplayKit.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2349D54A410A25E70102DF84 /* AsyncDisplayKit.xcframework */; }; + 0CA15E19782C812271B1AEB2 /* FireOnboardingViewController+Brand.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30B07CEE7C89CA1C63884E37 /* FireOnboardingViewController+Brand.swift */; }; 0F86EF628BCB2463C97F0863 /* FireRenderPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EDE93D07235A87438E6E563 /* FireRenderPresentation.swift */; }; 0FBE234C009F7BC9A9FA0278 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9AF9AD7F01EDCAC3E2FD1797 /* Assets.xcassets */; }; + 110004A60A7B6F51613A8727 /* FirePostCellNode+LayoutSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = B039AA18094D96411C3C25DB /* FirePostCellNode+LayoutSpec.swift */; }; + 11D1BA4453EE2B867F5FDE9A /* FireRootCoordinator+APM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44C646162E7A938015483CE7 /* FireRootCoordinator+APM.swift */; }; 128C486AB0D36B2CB5936D52 /* FireLDCView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73F4567310A9F3A185F64D4D /* FireLDCView.swift */; }; + 12AC670F3640F22237C123DF /* FireSessionStore+Diagnostics.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C9788FF37F1ED5F1DBB1A8 /* FireSessionStore+Diagnostics.swift */; }; + 1337A7D82BE2B52ABF0B69DD /* FireRichTextModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80B1341445E9FAD6C16A03B8 /* FireRichTextModels.swift */; }; + 13A6AE19C7D233FFB49F12F4 /* FireRichTextAttributedStringBuilder+Onebox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1DFFFE930AD6B28E469534 /* FireRichTextAttributedStringBuilder+Onebox.swift */; }; 13C14E92B46B8FA37CFD3B1A /* FireNetworkTraceDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97FFE2A260FE7B5682493795 /* FireNetworkTraceDetailView.swift */; }; 14B48EF9BD6DF454DF9E3279 /* FireTopicListChips.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EADCA671EA2C50617A86458 /* FireTopicListChips.swift */; }; 154FB30DB3C11D550C5D49A8 /* FireComposerViewController+Draft.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC59D88F80673C24044D7013 /* FireComposerViewController+Draft.swift */; }; + 15CB95AE4A1E2E60B5726527 /* FireDraftsViewController+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 385C82707C8B082E8EEC5268 /* FireDraftsViewController+Setup.swift */; }; + 16A48982DD3892B6A4148C27 /* FireBookmarksViewController+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = A53F58F41E80C0925A409C08 /* FireBookmarksViewController+Setup.swift */; }; 16ACF29E54C873A3B35858BE /* FirePostBoostBarrageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31B8731C1D7A069FB93E3B5B /* FirePostBoostBarrageView.swift */; }; 178E55B850EED60EE530A0F2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9B970247E0258DD4D4F34101 /* Foundation.framework */; }; + 181686B35A7139284A2858D4 /* FireTopicTimelineModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1A1CCCEC0341697385E81E7 /* FireTopicTimelineModels.swift */; }; + 18D104B7EB2A7A8212E3C1B3 /* FireAppViewModel+Recovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9AB8FAB900656D84CA6D7A6 /* FireAppViewModel+Recovery.swift */; }; 18F45B9FD3C30EAB2C985803 /* FireTopicDetailFeedUpdatePipeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C21247110244DC0C9E0BEDA /* FireTopicDetailFeedUpdatePipeline.swift */; }; 19548BBFB9955554D178906B /* FireViewUnreadIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 054E88D925ECEFF053D4F62F /* FireViewUnreadIntent.swift */; }; 1BD783D28E55AAC320B6BB20 /* FireTopicDetailSearchCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56971CD699F6CE264E0EB563 /* FireTopicDetailSearchCoordinator.swift */; }; + 1C49DC0FF7765886CCA5A6F9 /* FireSessionStore+Bootstrap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 395803401D7AD61E67521D16 /* FireSessionStore+Bootstrap.swift */; }; 1CABA3580C29E104B384F323 /* FireComposerValidation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F54F88AB1D407D9E4D5866B9 /* FireComposerValidation.swift */; }; 1D6295052B4A89C0F088705D /* InputBarAccessoryView in Frameworks */ = {isa = PBXBuildFile; productRef = 03CF5F2EF90AAD7D7C6B05A2 /* InputBarAccessoryView */; }; 1E95763ADE4D7A8428718D1A /* FireChatChannelViewController+Interactions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F9FF30F91F4B85033762AFE /* FireChatChannelViewController+Interactions.swift */; }; 1F1EEDCE0B4FEAE2880DC061 /* FireWebViewLoginCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5E5271F93B7DF18859B101F /* FireWebViewLoginCoordinator.swift */; }; 1F34091982CA9E4020CE6186 /* FireInviteLinksView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04449F91CF3EEB51F58E633B /* FireInviteLinksView.swift */; }; + 1F861D3D672F67E8D07815B3 /* FireSessionStore+MessageBus.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEBF84A7DDE1C18A3E021E2D /* FireSessionStore+MessageBus.swift */; }; + 1F9866CE1C15EFB0C30235B9 /* FireTopicRenderProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09C4C0F1BD2B7F38AC26618D /* FireTopicRenderProjection.swift */; }; + 1FB6D001DE414C289B998A2E /* FireTopicDetailAISummaryCellNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9BEB483B26DDDB72FDAF428 /* FireTopicDetailAISummaryCellNode.swift */; }; 1FF5479B50192659F7E4B9C9 /* FireSearchCells.swift in Sources */ = {isa = PBXBuildFile; fileRef = E08837275F0C3B294CFAB57D /* FireSearchCells.swift */; }; + 217CF41F35017C092619A769 /* FireDraftState+Presentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B98E98DFD1E03963E8CF83C /* FireDraftState+Presentation.swift */; }; 21A13575BAABF925D2AF02D0 /* FireHomeCategoryDrawerController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05B0007F349D9B8B718F7F1 /* FireHomeCategoryDrawerController.swift */; }; + 223F642EB1620378ED1DE0CA /* FireOnboardingCredentialFormView+Keyboard.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB9ADE00D1D81B7303F5F355 /* FireOnboardingCredentialFormView+Keyboard.swift */; }; 2264C8107D1350906282A04E /* FireSearchStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B17BF0CB4137B71949AACC0C /* FireSearchStoreTests.swift */; }; + 2275C0EF78146708B7EEB438 /* FireTopicDetailViewController+QuickReply.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15C52722D4C57B1E8C3D6258 /* FireTopicDetailViewController+QuickReply.swift */; }; 22D6B9CAC8373C14BBFA616A /* FireComposerValidationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A67A6C835A2196246871D5FD /* FireComposerValidationTests.swift */; }; + 233FA1179F4BBBD0DC7B3299 /* FireSceneBackground.swift in Sources */ = {isa = PBXBuildFile; fileRef = 882CE51DF4383DDB04EE2E95 /* FireSceneBackground.swift */; }; + 235D4C00DF4D77DB4B135E74 /* FireRichTextAttributedStringBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58E2588F8B8817932933EB55 /* FireRichTextAttributedStringBuilder.swift */; }; + 24188FF66792BCDA314C7671 /* FireTopicDetailViewController+Appearance.swift in Sources */ = {isa = PBXBuildFile; fileRef = B35863D820EC852D3D2222FE /* FireTopicDetailViewController+Appearance.swift */; }; 24F82A793D9593417C1E59EA /* FireTopicDetailModalRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = F90878A611124AD41C0288B7 /* FireTopicDetailModalRouter.swift */; }; 256CB81681004BB26E0431B7 /* FireTopicDetailSharedModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 925CD02F862E958CC79BC60A /* FireTopicDetailSharedModels.swift */; }; 262FDB3EF3B3981F6645B573 /* FireComposerViewController+Mentions.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD366FFC34E7ECB9EAF8B08C /* FireComposerViewController+Mentions.swift */; }; 2693C86EB9B8D438930E1B26 /* FireOnboardingValidatingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A248DED21DCF11B55E331D29 /* FireOnboardingValidatingView.swift */; }; 2697DC8A389656A42CCEE78F /* Nuke in Frameworks */ = {isa = PBXBuildFile; productRef = 3F5DB59F34DC2099A84C0F6F /* Nuke */; }; - 26E51A13E796BFEF885FBD28 /* fire_uniffi_topics.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */; }; 26F6FF8DF720B6F46F3C5226 /* FireTopicDetailToolbarCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB73A3AE7A4D6E47C61CAE52 /* FireTopicDetailToolbarCoordinator.swift */; }; 27D3B7AADEF91C6DE3B41618 /* FireTopicEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 577A99743CDCAA0033E2398C /* FireTopicEditorView.swift */; }; 27EBDDEA2CFC1F6A77718875 /* FireChatChannelViewController+Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6B638F65DBB3B2AF6A3AAE0 /* FireChatChannelViewController+Table.swift */; }; 27F8780AB48C65663BA8CF6A /* FireProfileActivityRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07E3386C6FC3093869C79E57 /* FireProfileActivityRow.swift */; }; 282054CA9D02B4F47B3C0691 /* FireHomePaginationCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A74AEC2739DE5254CD8A23B0 /* FireHomePaginationCoordinator.swift */; }; + 282B6E71ED2FAC10106A40AA /* FireNotificationHistoryViewController+Pagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D9266ECC882A7206C1A2930 /* FireNotificationHistoryViewController+Pagination.swift */; }; + 28856A5854B5C930C12C3726 /* FirePrivateMessagesViewController+Pagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2555F9775C8B3F9310B17AB /* FirePrivateMessagesViewController+Pagination.swift */; }; 28ADE71B45F2298CB7C8DFE6 /* FireMyBadgesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71D0063A5014FEF51FB2B8E8 /* FireMyBadgesView.swift */; }; + 28F30EA23DA3903A07F8297F /* FireFeedKindSelector.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5AC04986AD864B86FEC5271 /* FireFeedKindSelector.swift */; }; + 29A7127B03E0BFCA64F300B2 /* FirePrivateMessagesViewController+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA7708CC55F3C5DF4F0557C6 /* FirePrivateMessagesViewController+Setup.swift */; }; 29F891D31E57BD3D19AB4EBB /* FireBookmarksViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F329C317F6932DC1D07AD03 /* FireBookmarksViewController.swift */; }; + 2A71414E9B514FD38EF45FA1 /* FireTopicDetailModalRouter+Navigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F8D2A6776D4D192A6051BD4 /* FireTopicDetailModalRouter+Navigation.swift */; }; + 2A7F2B1FE5A92E256E36C531 /* FireOnboardingCredentialFormView+LastLoginHint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A7D88710A4E967AB393E736 /* FireOnboardingCredentialFormView+LastLoginHint.swift */; }; 2BB1CFDFB44C42712F173627 /* FireFilteredTopicListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3623960CD988F423E24CCE8C /* FireFilteredTopicListViewController.swift */; }; + 2C6BA8B8DAA40C400DF6AA62 /* FirePostCellNode+QuoteAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 323769D2402BB6DB956BCBA3 /* FirePostCellNode+QuoteAction.swift */; }; + 2D0DD0C8D79306D2DBB0C0F0 /* FireFilteredFeedSelectorCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CAD3D8482640C6E6C636D0A /* FireFilteredFeedSelectorCell.swift */; }; 2E24DA3BD96C8B64D78FFA5D /* FireTopicQuickReplyBarNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 881FCA584D82BEB684F4E2C8 /* FireTopicQuickReplyBarNode.swift */; }; + 2E7A30421594539CBAB161C3 /* FireTopicSearchPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34B1C77D253E343F11117883 /* FireTopicSearchPresentation.swift */; }; 2EF020F79C1B4F20796C610C /* FireProfileTrustLevelPill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A3BEB6E72878BC3AD27B487 /* FireProfileTrustLevelPill.swift */; }; + 2F05FE50B8D1ACFA328C43F5 /* FireTopicReactionPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC47D1BE0D7F65889A8A17A1 /* FireTopicReactionPresentation.swift */; }; + 2F6211BFB88F5925BDD05489 /* FireReadHistoryViewController+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E1E77D84D9FD468BB724B7 /* FireReadHistoryViewController+Setup.swift */; }; + 2FE323867F6202AB2F52AE16 /* FireSessionStore+Observers.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7DE9DC4AD6A5C9B6626E350 /* FireSessionStore+Observers.swift */; }; 3020B851468E970811BC595B /* FireAppRouteControllerFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 149C3D9916D55374B1B4A37C /* FireAppRouteControllerFactory.swift */; }; + 31281614A8A4C6C7E24B1A45 /* FlowLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4741FBBFF6A7C139E90AE6C3 /* FlowLayout.swift */; }; 312F8EA98888FA4D71FA5CA4 /* FireWidgetData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4543C11B22E10FA9DA852E16 /* FireWidgetData.swift */; }; 315F73393DBB4E5F1D472684 /* FireDraftsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8E5B1ECAE617609F235B6A3 /* FireDraftsViewController.swift */; }; 3330A9C7E4C8BA80778F79EB /* FireAppRouteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 299683BEDEC559B03C136C34 /* FireAppRouteTests.swift */; }; 33DC82E96FE6606F38CC0985 /* FirePostLayoutManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D51F8B61796434E964104F72 /* FirePostLayoutManagerTests.swift */; }; + 340AF4FEF56C48FA2CD0080E /* FireTopicDetailFeedCellFactory+BodyState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70F2622FC71DFA7C3DCC8749 /* FireTopicDetailFeedCellFactory+BodyState.swift */; }; 352CD58A1F4D83DC9BE95178 /* FireTopicListMessageBusRefresh.swift in Sources */ = {isa = PBXBuildFile; fileRef = E66E1B11B9D76557B4BB0603 /* FireTopicListMessageBusRefresh.swift */; }; + 35362CA2A814F56208306EDE /* FirePostRepliesSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A4E63528064FF56B534955 /* FirePostRepliesSheet.swift */; }; 354981A2F26D106303FC947D /* FireComposerViewController+Delegates.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD448CA615C795B53ECF62D0 /* FireComposerViewController+Delegates.swift */; }; 355451477523656402E506B8 /* FireExportDiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1127D7C4622ADFEED430046E /* FireExportDiagnosticsView.swift */; }; 35B6F563371260443CDCF46C /* FirePrivateMessagesViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A765149EB821BBD6B81CCE8 /* FirePrivateMessagesViewController.swift */; }; 3629B6712AD67BC02B4288A1 /* FireSearchService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EBE1819A4C585EBED2C8F1C /* FireSearchService.swift */; }; + 369327949DA9B31DD79B2442 /* FireAppViewModel+Startup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 707CDA3897A19341B7B09333 /* FireAppViewModel+Startup.swift */; }; 36AD16D7D4B222FA72598AF0 /* FireComposerViewController+Editor.swift in Sources */ = {isa = PBXBuildFile; fileRef = D34B1A27E213EE85137546A2 /* FireComposerViewController+Editor.swift */; }; 37307D1D50D8438CE90EDE9A /* FireUIKitErrorBannerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4616E00DD2F43C18973E520 /* FireUIKitErrorBannerView.swift */; }; + 37B5A497C6F50115942DC1DF /* FireSessionStore+HomeScope.swift in Sources */ = {isa = PBXBuildFile; fileRef = 190AEA75EC6B05E5FFA7796E /* FireSessionStore+HomeScope.swift */; }; 385A66FC63C5CD7CFD837AFC /* FireBoostInputViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08710076BA9FA07121C0A9C5 /* FireBoostInputViewController.swift */; }; 385B67F8E7B07CD0674E2BEA /* FireComposerViewController+Chrome.swift in Sources */ = {isa = PBXBuildFile; fileRef = 266F4CE0F161C8BF7A9F04C1 /* FireComposerViewController+Chrome.swift */; }; + 38C8EF17FA31254FE367B032 /* FireSessionStore+WritePreflight.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DF5C51601950F6B6B2E84AD /* FireSessionStore+WritePreflight.swift */; }; 390219653B0C0A96C81D8962 /* FireAPMEventStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 373861687BBCD8EB8E350DA4 /* FireAPMEventStore.swift */; }; 3A20BD9A2A4CE944762B0BD7 /* FireReadHistoryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C8AEE7516614D73C079F860 /* FireReadHistoryViewController.swift */; }; 3A339550AA3EE966F7EA50E5 /* FireProfileViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DF67696B342C706CB3FAAFB /* FireProfileViewModel.swift */; }; 3A6947C760E41DBF6A317A21 /* FireTopicListStateCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = E08C81F61BB648C072F7BA9E /* FireTopicListStateCell.swift */; }; - 3AFFAE192ADFE0FE4E054809 /* fire_uniffi_user.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */; }; + 3AB87130FBC77FFBEB228A60 /* FireTopicDetailViewController+SnapshotApplication.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1CB184C209DCD4DB04D3B50 /* FireTopicDetailViewController+SnapshotApplication.swift */; }; + 3AFBACA8C60CB301E1D16A49 /* FireFilteredTopicListViewController+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F908C70A11E537FC1F475DE /* FireFilteredTopicListViewController+Setup.swift */; }; + 3B6102A8903B9E4A790BBE6A /* FireFilteredTopicListViewController+Pagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA2C6D3AD63CA17550149E0C /* FireFilteredTopicListViewController+Pagination.swift */; }; + 3C61095A5DDBDEDD25D31D23 /* Generated/FireUniFfi in Sources */ = {isa = PBXBuildFile; fileRef = 6CB14B164BD5987BA7B8C516 /* Generated/FireUniFfi */; }; 3C9FA7D66DAA4DAE2B1BF45D /* FireProfileActivityTimelineView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFE429D39ACE68653A226FE9 /* FireProfileActivityTimelineView.swift */; }; 3CA9AF0BFA58C32834B441F3 /* FirePresentationIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 019B4B93D3FDB4C799492775 /* FirePresentationIdentity.swift */; }; + 3DCD2D4C807C1D9341D00517 /* FireTopicDetailFeedController+Appearance.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF90E2C1233BB91915E3F138 /* FireTopicDetailFeedController+Appearance.swift */; }; 3E86B05D0E10C74BB865A0F9 /* ConfettiSwiftUI in Frameworks */ = {isa = PBXBuildFile; productRef = 2DFDD7AEF71DAD503CDB00B8 /* ConfettiSwiftUI */; }; 3F1C13559BEAD77AE0EC1F13 /* FireHeadlessExternalLoginEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E406BC86F476DB0FF2E688F /* FireHeadlessExternalLoginEngine.swift */; }; + 3F25189F91AE9BDEF840E62B /* FireMainNavigationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 139A690F74C13E830A6A959E /* FireMainNavigationController.swift */; }; + 3F999AD8DB6BBFC806151939 /* FireRichTextAttributedStringBuilder+Lists.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24C97053064713B8ADD07FE6 /* FireRichTextAttributedStringBuilder+Lists.swift */; }; 3FB0703417FA44B6B90837D5 /* FireProfileMenuRowCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = A65333719DA71EBA1D39F3F3 /* FireProfileMenuRowCell.swift */; }; 3FDB63119BEBEA0BE1CA2E6A /* FireUIKitAppearanceCapsuleControlTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8EF10938994EC780C68B9D4 /* FireUIKitAppearanceCapsuleControlTests.swift */; }; 40B864B25377AE905208F981 /* FireHomeScopeChromeViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48153CE6A692130B4F8D97C5 /* FireHomeScopeChromeViews.swift */; }; 40D915EFFA96678D4BE3B24C /* FireTopicListMetricPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01D95BB10F2DECA7D5F404DE /* FireTopicListMetricPresentation.swift */; }; + 410A0CECE4529C1CF6F6FA82 /* FireDraftsViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 293D79BE540B73D84BDFABF6 /* FireDraftsViewController+Feed.swift */; }; 426EA4818F619C1E65B4DBF6 /* FireSearchViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17A3228BF5A8EB20BA7E43E9 /* FireSearchViewController+Feed.swift */; }; 4291E89FC3D5D35AC9A06898 /* FireOrderedIDList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00DA04AEF775D5BD01FC23AC /* FireOrderedIDList.swift */; }; + 42BDD00E7F1227287204DA01 /* FireOnboardingCredentialFormView+Options.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B596C5C2E8BEF5EB24A7A07 /* FireOnboardingCredentialFormView+Options.swift */; }; 4397ACCD2A571DB3DA0AC8FC /* FireAppRoute.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46CF09F1CBAC6CFAA0E9128A /* FireAppRoute.swift */; }; + 43EE3E937D4EC4F3E5C68D03 /* FireTopicDetailViewController+Reactions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E3BCBF5C07A882EFEF21D2E /* FireTopicDetailViewController+Reactions.swift */; }; 44803F9B07AEA78F2DEC49AB /* FirePostPollRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 929153DAB55DC46B3FDFC5ED /* FirePostPollRenderer.swift */; }; + 44857471ECBD28DFC533CEE7 /* String+FireIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 401B5C6197D90A29EDE33441 /* String+FireIfEmpty.swift */; }; 44F4598A114E7B55EB3A7A5B /* FireChatMessageCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 323125829E4EEA3C5535793D /* FireChatMessageCell.swift */; }; 4690EB1F1DB5AE98F18BB203 /* Toast in Frameworks */ = {isa = PBXBuildFile; productRef = AB9ED5A59ED739DCBDC16339 /* Toast */; }; 47478A1EF4F9D689EFA0FD9E /* FireOnboardingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFB2F0A5B57993299161C5EC /* FireOnboardingView.swift */; }; 47B89C5984DCCAB601B919EE /* FireTopicDetailStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9267FBC4BA4FD365E6F4E371 /* FireTopicDetailStore.swift */; }; 47CA07B15132822B96604FB5 /* FireQuoteMarkdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE76404ADCD8CDEBB2B411C8 /* FireQuoteMarkdown.swift */; }; + 4856BA5A72A6E2417981235C /* FireAppViewModel+MessageBus.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFE7644ABB3B64FDEFBCDC99 /* FireAppViewModel+MessageBus.swift */; }; 489C515305D468C608C7315D /* FirePostCellNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 093EEF1E0EBDB24ED7106CDD /* FirePostCellNode.swift */; }; + 4952AC421EAF266752C5249D /* FireTopicDetailFeedController+DataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E2246CC0E310D95CC9909B0 /* FireTopicDetailFeedController+DataSource.swift */; }; + 4A1A891140E689E79AE3FB5A /* FireNotificationHistoryViewController+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DC8951F1970697D3FBEB8DF /* FireNotificationHistoryViewController+Actions.swift */; }; 4AA62FDF95D9A4E90D07D625 /* FireComposerCategoryGuidance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6245C0A19C0D937131AC08C0 /* FireComposerCategoryGuidance.swift */; }; + 4AC091DD5B35A35D920EC2AF /* FireProfileViewController+RowProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 941B6AAD154632DFD156195E /* FireProfileViewController+RowProjection.swift */; }; + 4B1CDDE39E22C2F79F185853 /* FireTopicRenderModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49FEB500EA67E0649586CB1B /* FireTopicRenderModels.swift */; }; 4B95D21F7985C6991CBBD94A /* FirePrivateMessagesViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86F1E4CC07C33FB00FADD181 /* FirePrivateMessagesViewModel.swift */; }; 4BE99837C15834E6EDEC8290 /* FireComposerViewController+Submit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0544FD6A0AAD16EA24E22160 /* FireComposerViewController+Submit.swift */; }; + 4CD39D25480EB406C29A5AA6 /* FireOnboardingViewController+PasswordAutoLogin.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8B454F22E943FD24E12D526 /* FireOnboardingViewController+PasswordAutoLogin.swift */; }; 4CDAF08E9DD1F41DDA5DCE4B /* FirePrivateMessageCells.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2850469E1F9F91DD6FA787AE /* FirePrivateMessageCells.swift */; }; + 4DEDB607C66E59F7DEFFA164 /* FirePostCellNode+Thread.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFADFB09839E6626FF12E186 /* FirePostCellNode+Thread.swift */; }; + 4E1DC34F72033EA90918DD01 /* FirePostCellNode+Appearance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24AC0E82D4FD3B75E1DEF2A3 /* FirePostCellNode+Appearance.swift */; }; + 4E3F5E45447A999F5CF0FFAC /* FireOnboardingViewController+PhaseRendering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03D05BEAFD5E582B878E18EF /* FireOnboardingViewController+PhaseRendering.swift */; }; 4E69EA800D7956E3C1989CFC /* FireCookieSelfHealingCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = C203C63EB7CB10843B8AB0EC /* FireCookieSelfHealingCoordinator.swift */; }; 4F0305B9162423D8D821A304 /* FireRouteParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46C35F105D036EECAAE7B93D /* FireRouteParserTests.swift */; }; - 4F762CD9E7B43DB0534791C8 /* fire_uniffi.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */; }; + 4F5B0E726AD298783DB3C559 /* FireHomeStyleSkeletonCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5493A60CF66C250B7225025D /* FireHomeStyleSkeletonCell.swift */; }; + 4FA37E1E0084A7DAE6AA83E0 /* FirePostCellNode+ContextMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55A00A8DFE3727573935D235 /* FirePostCellNode+ContextMenu.swift */; }; 4FAD2E2F807F1136D45392CF /* FireHomeShellViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42166EE11327DFA41BF1AE4A /* FireHomeShellViews.swift */; }; + 5192D08A716698686010E397 /* FirePrivateMessagesViewController+Participants.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC289AE43D9253D1617154D9 /* FirePrivateMessagesViewController+Participants.swift */; }; 51D27C6354C43E1E83FEA3FB /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 6958AA64094FA7BB21B5FC36 /* PrivacyInfo.xcprivacy */; }; - 522CA82334EAC05D23624720 /* FireTopicDetailModalViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BC7B03BAACE572DDB87E810 /* FireTopicDetailModalViews.swift */; }; 52CF002705A0E18AAB2E9E62 /* FireTopicDetailRootNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEC29D6B75CD01B9ADD53F1A /* FireTopicDetailRootNode.swift */; }; 536F2C323597D62D2C442732 /* FireTopicListMetricView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9B5923516C20CEBF5727C1B /* FireTopicListMetricView.swift */; }; + 54698B7A3C82B029053281DB /* FireRichTextAttributedStringBuilder+Inline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2604E07D8A130094F4A756B1 /* FireRichTextAttributedStringBuilder+Inline.swift */; }; + 54799FB2DA0FA9EFB73F31F2 /* FirePrivateMessagesViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCAB50E1A2CDADEB2A43A1B4 /* FirePrivateMessagesViewController+Feed.swift */; }; 554CC7F69039A6FD88B5C84E /* FireTopicListMetricEffectCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E3DCC9617583661AAF64366 /* FireTopicListMetricEffectCoordinator.swift */; }; + 56B96EA0F1E94CC1966EE8BA /* FireTopicReplyPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFC129B0275F2EFA770163F5 /* FireTopicReplyPresentation.swift */; }; 56EE60CC67C1D8E444227552 /* FireTopicPresentationTestSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41AECD88340113D3FD81D59B /* FireTopicPresentationTestSupport.swift */; }; 581D7403FE4CDC12F486AAC3 /* FireComposerDraftHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CC70D5009C55B1897598989 /* FireComposerDraftHelpers.swift */; }; + 5A7DF5CE0E54BEA77F4687C0 /* FireTopicDetailViewController+StateProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = D599BADEB91A482BE7179BB2 /* FireTopicDetailViewController+StateProjection.swift */; }; 5A95F9C29909968BF4B17AD7 /* FireAuthCookieKeychainStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = C313FFDD8D569FA6D9B1C0E0 /* FireAuthCookieKeychainStore.swift */; }; 5B02974CC6660AB7D633D41E /* FireAppearanceEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D354D83C07C326288699E3D /* FireAppearanceEnvironment.swift */; }; + 5C044A9555F54C391D5E87AE /* FireTopicImageViewer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D384F4A919803D9BFF1F296F /* FireTopicImageViewer.swift */; }; 5C91256EF203F8B20E1E145E /* FireProfileViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E771E5E48D78AAC476C3A58D /* FireProfileViewController.swift */; }; 5C94B9ACD52AEF20ED7AC39F /* FireBackgroundNotificationAlert.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC5FF075F001E43924A7D188 /* FireBackgroundNotificationAlert.swift */; }; 5CACD8BFBDA8FDF7D7CBF4E7 /* FireMotionReduceMotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA23C0E50E7A412A73AF80E6 /* FireMotionReduceMotion.swift */; }; 5CC59FE0F0C9914237A8DE8E /* FireTopicTimingTrackerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDE93F98F58126B7BEDDB4F7 /* FireTopicTimingTrackerTests.swift */; }; 5CD828950C63379DCA035EDA /* FireComposerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1348CE0E6B9A223627CAE8E8 /* FireComposerViewController.swift */; }; + 5CF0A8A6F2D3170F7875A68C /* FireSessionStore+Search.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99ED84E18DBC3745DEF283C3 /* FireSessionStore+Search.swift */; }; 5D343E985D5E1E682196187C /* JXPhotoBrowser in Frameworks */ = {isa = PBXBuildFile; productRef = 1E653954FC02A5A5CA653296 /* JXPhotoBrowser */; }; 5D7444AAB03F7389410B91F9 /* FireTopicListErrorBannerCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB1A3A3830E2E1A1917F86C0 /* FireTopicListErrorBannerCell.swift */; }; + 5D87A4C492216989AD97443B /* FireAppViewModel+TopicDetail.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5158DC91BBAB977BE1737A7B /* FireAppViewModel+TopicDetail.swift */; }; 5DDBCDFC25C6461A076FE358 /* FireRichTextHeightConsistencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C65C6A52FE7362DF04A8445B /* FireRichTextHeightConsistencyTests.swift */; }; + 5DDFDCACF21FCAFCA87543CC /* FireOnboardingViewController+LoginActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4525E775EE0C86542CD3685 /* FireOnboardingViewController+LoginActions.swift */; }; + 5E54BBB3C72F683B9562CA2D /* FireOnboardingViewController+ExternalAutoLogin.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1B8F0D85F4041E579896617 /* FireOnboardingViewController+ExternalAutoLogin.swift */; }; 5E556FC12993F27449D2B973 /* FireAPMManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 129694A5F35FF78B3F810049 /* FireAPMManager.swift */; }; + 5E559CD8DCDE75AC741319AA /* FireTopicDetailRuntimeConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD9A9C9C69DB5687EF255186 /* FireTopicDetailRuntimeConfiguration.swift */; }; 5E90D968B32A1D692D9351AC /* FireDeveloperToolsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1481ACDF04D249FF61B1D0DF /* FireDeveloperToolsView.swift */; }; 5EB4B72F5561D4340D0B82B1 /* FireUIKitDesignLanguage.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5FFB93F34563ABE34B99183 /* FireUIKitDesignLanguage.swift */; }; 5EF8B30E931B020C7512ACE1 /* FireShimmerModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0182FF50BA5178478278FB01 /* FireShimmerModifier.swift */; }; @@ -137,77 +218,123 @@ 6441B378C0DD7B97553F5BD3 /* FireMotionUIKitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25A9FA3A65196B334165E0C6 /* FireMotionUIKitTests.swift */; }; 648E830146DFA93FD20CC045 /* FireHomeScopePresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFECA37BF8132D011E6B5506 /* FireHomeScopePresentationTests.swift */; }; 6568C3A35CB160E2269A67DD /* FireContextMenus.swift in Sources */ = {isa = PBXBuildFile; fileRef = E650ABD9C06621BC41908D59 /* FireContextMenus.swift */; }; + 65937CFE1219F3DBA4EFF2C8 /* FireFilteredTopicListViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2BD298D3BCD7D884DF020409 /* FireFilteredTopicListViewController+Feed.swift */; }; 65A7971203D5D03D0681E719 /* FirePostFlagSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49784F572BD41F7D9F024F55 /* FirePostFlagSheet.swift */; }; 660EE0478082FB4E3B85C3B2 /* FireSettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3ECAD5FF1893C381DB94E34 /* FireSettingsViewController.swift */; }; 664A20B095CCA3180B765195 /* FireProfileHeaderTableCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CF9D0635D23971967624E4 /* FireProfileHeaderTableCell.swift */; }; + 6851B0EFBCFB27061F5B98B8 /* FireSessionStore+Authentication.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DB484B4F02ECBEE1DEF9A7A /* FireSessionStore+Authentication.swift */; }; + 6878A9CBCFD675E54F884A22 /* UIView+FireHierarchy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D0074D8DEFA2184F2EA3955 /* UIView+FireHierarchy.swift */; }; + 68C959895802DA36652BAE51 /* FireErrorStates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3367E65714661E982001EBCC /* FireErrorStates.swift */; }; + 690169D8E9B68469C21A7484 /* FireTopicUserInfoSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AFA3082D577488D13F57EE2 /* FireTopicUserInfoSheet.swift */; }; 69FCB7426098CEDD059BB09A /* FireTopicInteractionService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E056C5583CA4544A2781E2F /* FireTopicInteractionService.swift */; }; + 6A4192E81E47051D02C269B2 /* FireTopicDetailTextCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CA68AD35F9427999927D825 /* FireTopicDetailTextCell.swift */; }; 6B10F17B6D3AE362E0667530 /* FireComposerTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3CB6CE9186DD244BE17CC51 /* FireComposerTextView.swift */; }; + 6C19E1C54E0B3567EA8905F6 /* FireTopicDetailViewController+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDDE0CA8CFB2A3F8F90194D5 /* FireTopicDetailViewController+Routing.swift */; }; 6C52C8A80C6D33CEEF5F6B18 /* FireTopicDetailPageSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC6AF43B5DBBA0811F63F137 /* FireTopicDetailPageSnapshot.swift */; }; + 6CA4339F385531C17E9ABD71 /* FireTopicDetailModalRouter+Alerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3887899D62CC6BED4D8F686C /* FireTopicDetailModalRouter+Alerts.swift */; }; 6CD842F82A4371F3BCCCF4C5 /* FireEntityIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33FDDDCB91B973C1115A8F6B /* FireEntityIndex.swift */; }; 6CF494A7F630B0996BE26547 /* FireComposerViewController+Render.swift in Sources */ = {isa = PBXBuildFile; fileRef = B604EC2A613A2E5A96896B03 /* FireComposerViewController+Render.swift */; }; 6E1AEE9C40EC41F03E6D5DB3 /* FireSearchHeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC1862EFE9736F5E1E6C9B5D /* FireSearchHeaderView.swift */; }; 6F1F11DDA954EBFD146D0DB2 /* FireUIKitToast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54D532ECF928AC54FE11A47C /* FireUIKitToast.swift */; }; + 6F60EC98C6A1C5B340801891 /* FireTopicDetailStatsCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFF4501C580EB91388A97D24 /* FireTopicDetailStatsCell.swift */; }; 6F88C8AAB2089E7F558EDE67 /* FirePushRegistrationCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52BB1F5B0970DC2504ACD989 /* FirePushRegistrationCoordinator.swift */; }; 70437C5E10A5FA39F05F7E0E /* FireWidgetEntry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E0BF86E469C2F6F845BBC27 /* FireWidgetEntry.swift */; }; + 7084EC3A6B54F932BC42FF86 /* FireTopicDetailViewController+Keyboard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D724BCFA0E3C41156FAF7A3 /* FireTopicDetailViewController+Keyboard.swift */; }; 70D5B41B5FDF1CA7AC72A507 /* FireDraftsControllerHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3824000FAC99E70EA95DD86 /* FireDraftsControllerHost.swift */; }; + 71605DB2EE107989D2DF05B3 /* FireTopicDetailHeaderCellNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = A00A030F05010262BF2FCFEA /* FireTopicDetailHeaderCellNode.swift */; }; + 71EC481DB8E6004445FF65B6 /* FireTopicDetailViewController+TopicVoting.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3E28D0395CEAFF65092C1F3 /* FireTopicDetailViewController+TopicVoting.swift */; }; 720F0DB93AF559449C8EAAE3 /* AsyncDisplayKit.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 2349D54A410A25E70102DF84 /* AsyncDisplayKit.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 72AC7A92BEC5E2B99DEE5ACC /* FireRichTextRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A156E14A65C530B5582956CC /* FireRichTextRenderer.swift */; }; + 747A043BFAD15BA626CB6D8F /* FireTopicDetailViewController+PollVoting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 054BAB7AF7338BAB2ED6782C /* FireTopicDetailViewController+PollVoting.swift */; }; 75942BB0E2A79B55D5D92674 /* FireCaptchaLoginDialogController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 462EB3CAB0AACF4846EA3AC5 /* FireCaptchaLoginDialogController.swift */; }; + 7632BA69586B036FEA62762E /* FirePostCellNode+Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09F2FA662430C8D8F81AF72A /* FirePostCellNode+Configuration.swift */; }; + 763C17574154616F2223D573 /* FireBookmarksViewController+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AC8045F6F7424FF87C85E8F /* FireBookmarksViewController+Routing.swift */; }; 768DC62B26A1D2EF4F545D35 /* FireHomeFeedStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC7384EAE1C43817CAE71D9F /* FireHomeFeedStore.swift */; }; 772EFD83C4DEB77EAC00FD55 /* FirePostCellLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = B220305F1DFD0C508260CFA9 /* FirePostCellLayout.swift */; }; + 774FF2910ECBA13FD231796E /* FireSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F8C73964C70D1D4BE662154 /* FireSkeleton.swift */; }; + 77C50E2260AC5C0D8F3C1D61 /* FireTopicDetailModalRouter+PostModals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C20A920D328CA02A9894274 /* FireTopicDetailModalRouter+PostModals.swift */; }; 77CCEFA72B8E24723A99D9F7 /* FireCloudflareChallengeRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D74211CDB2098D655F1604A /* FireCloudflareChallengeRecoveryTests.swift */; }; 77E848E1359E1F9B69439B7B /* FireNotificationFeedModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B7065BE7533DDF7B2E56700 /* FireNotificationFeedModels.swift */; }; 77FA425E01F1504EB75DA831 /* FireRichTextNodeLinkDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70D03FC864701908D985F621 /* FireRichTextNodeLinkDelegate.swift */; }; 78009659A664B236D8AD3434 /* FireBadgeDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF5B6841F5556D86C606379F /* FireBadgeDetailView.swift */; }; 7848D667BF692B25B4194E57 /* FirePostCellLayoutCalculator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24E7CCCA8B867D5E6B0CE198 /* FirePostCellLayoutCalculator.swift */; }; 790B44E436B0CF137B1FD8A7 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E69013450F80AEC210D5512D /* Security.framework */; }; - 79B77A4E828C4862BE1BAA53 /* fire_uniffi_ldc.swift in Sources */ = {isa = PBXBuildFile; fileRef = A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */; }; + 79B5F008215EFD4E3550D4FA /* FireProfileViewController+Binding.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA0E260E7D126FE6A00AFF62 /* FireProfileViewController+Binding.swift */; }; 7A0A8240B294336D5787C364 /* FirePublicProfileViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D23F3B2881A5E7C08D90A767 /* FirePublicProfileViewController.swift */; }; 7A1883792B3FD63EAEAA8336 /* SessionState+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FC109FBAA1787EF49336258 /* SessionState+Helpers.swift */; }; 7A7A14663C8D777827CA6768 /* FireWidgetSnapshotWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E86F61501D5E51FA1584156 /* FireWidgetSnapshotWriter.swift */; }; 7B1B888CA814A35E5354CA0D /* FireHomeScopePresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = E355FDE3F6E9A5FFB6229374 /* FireHomeScopePresentation.swift */; }; 7B772557813420536690D938 /* FireAppViewModel+Diagnostics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F1F872C6062881E7513980D /* FireAppViewModel+Diagnostics.swift */; }; - 7C8E2507194A4B1C79F2BF4B /* fire_uniffi_session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */; }; + 7B97D416442B9EBDA25A886E /* FireOnboardingViewController+BottomControls.swift in Sources */ = {isa = PBXBuildFile; fileRef = B94F01C860C35AEC1BA7AD42 /* FireOnboardingViewController+BottomControls.swift */; }; + 7C14237FA7BE97CFD9CB2B59 /* FireTopicDetailFeedController+Scrolling.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD91CB19207D14CD1A99BBCE /* FireTopicDetailFeedController+Scrolling.swift */; }; + 7C9D4BF48D243FE6CD356AF7 /* FireTopicPostMerge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02FDEF6C96B3C5C3D5763910 /* FireTopicPostMerge.swift */; }; 7CB85DA7DE5A93B262C29757 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 40B24CD54573A1C053B37121 /* PrivacyInfo.xcprivacy */; }; + 7D84EA4EB6BD0DD074350541 /* FireSessionStore+Ldc.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1815693E5384964FEFF564D9 /* FireSessionStore+Ldc.swift */; }; + 7EB8AAFE71FE4A170D23BB5F /* FireAppViewModel+SessionApply.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88895CD4883C551BA78B1913 /* FireAppViewModel+SessionApply.swift */; }; 7EFB42D38DCA6C0F63720AE3 /* FirePostCellNode+Reactions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A763199D74A1026B2ADB530 /* FirePostCellNode+Reactions.swift */; }; - 800930BED241B0CF61E5FD0A /* fire_uniffi_types.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */; }; + 7F46E3955CDAA150242B9FD2 /* FireOnboardingCredentialFormView+LoginButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 473E5CD558B2D86650E606F2 /* FireOnboardingCredentialFormView+LoginButton.swift */; }; 8146E8382FB40C8617EF19B7 /* FireWebViewCookieActionSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5103D4725A903220359B1C42 /* FireWebViewCookieActionSupportTests.swift */; }; + 8169033D7B7D654CC99ACE4A /* FireOnboardingViewController+StartupRouting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 670A641D02B78D7C613EEDBC /* FireOnboardingViewController+StartupRouting.swift */; }; 8169E3FD365AE9F655517F7C /* FireTopicDetailArticleSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8928D817CE60A917A5BA0C9 /* FireTopicDetailArticleSnapshot.swift */; }; 816DB34CD28CD94ED88EF9C6 /* FirePaginatedStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D0D5E6727E0D21855DDEA2F /* FirePaginatedStore.swift */; }; 819347D8B61069C0E5750CCE /* FireProfileActivityTableCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6E39E0383771E1B2AC6F4DB /* FireProfileActivityTableCell.swift */; }; 819D8580060771998348C810 /* FireHomeViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBBF5C645C888133A5CD57DB /* FireHomeViewController+Feed.swift */; }; + 823246221761BF66B80E68B6 /* FireTopicDetailUiProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99F0AD21E5D4EAE4CBCF21B2 /* FireTopicDetailUiProjection.swift */; }; 83C439B40A75418E1406961F /* FireTopicPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECBDE8779B6F7E32204263F4 /* FireTopicPresentation.swift */; }; 8414458CE31AB953097CF014 /* FireSelectableRichTextNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C08AC6976AD62C1DAB2DBB2F /* FireSelectableRichTextNode.swift */; }; + 8561D2B430C0C5A7A976953F /* FireSessionStoreError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F853E29620466DE5501395D /* FireSessionStoreError.swift */; }; + 859239670E11D700CB5A3F83 /* FireToast.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAD7D1368C3668D205CA1FD8 /* FireToast.swift */; }; 85C70D8DA7E559BB3DA69E17 /* FireBottomInputBarTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B2A79D53BB06F4FE60BE258 /* FireBottomInputBarTests.swift */; }; + 8641FBEF7BF3BCE3AC1BA3FA /* FireTopicDetailToolbarMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41B071F383E0E0129E68BD8A /* FireTopicDetailToolbarMetrics.swift */; }; 86A48A7AD1379516567513F6 /* FireTopicListPalette.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EDB5751E3066F0E94352716 /* FireTopicListPalette.swift */; }; 874B0947FB4673A436444942 /* FireSearchFeedModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 623CAF283DA441336D75B33B /* FireSearchFeedModels.swift */; }; + 8855525F82CD1A65EDB5E84B /* FireSessionStore+Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAE3BC1D85ECB2D04689F7BC /* FireSessionStore+Notifications.swift */; }; + 88CC439CA2AC2CDABAF8919E /* FireRichTextAttributedStringBuilder+Quotes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 550B08C28394AE3DDDC313C8 /* FireRichTextAttributedStringBuilder+Quotes.swift */; }; + 891E74C234722341CEA2B1B8 /* FireTopicDetailRuntimeInteractions.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEA0243549927BE6D9047392 /* FireTopicDetailRuntimeInteractions.swift */; }; 89B0F00FD4AC022A597A8BEB /* FireNotificationBannerCells.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E5E15383418191B6F6074BC /* FireNotificationBannerCells.swift */; }; + 8A8BCF5EB34F5677D4388D0F /* FireProfileViewController+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A7A8FB9455E94256F352A3 /* FireProfileViewController+Routing.swift */; }; 8AEF01149E05D149E2126D99 /* FireMediumWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5619EAAFA6C1DCD6B3E1A15 /* FireMediumWidget.swift */; }; 8C3A84430CB2547E162D940B /* FireUserCardChromeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B3E420F46F18B629C3C78AF /* FireUserCardChromeTests.swift */; }; 8E3E034A3C14BA223E0944AA /* FireAppearanceEnvironmentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00F402E58797F03DFA1F3150 /* FireAppearanceEnvironmentTests.swift */; }; + 8EE144178136B5138204781F /* FireAppViewModel+HomeFeed.swift in Sources */ = {isa = PBXBuildFile; fileRef = A37BC4D564DAC93057917CB8 /* FireAppViewModel+HomeFeed.swift */; }; + 8FC5460F837E1BD21F390B8E /* FireOnboardingViewController+Keyboard.swift in Sources */ = {isa = PBXBuildFile; fileRef = B59CF230508939157DFEEB67 /* FireOnboardingViewController+Keyboard.swift */; }; + 9052C724214E66A6CE1FD18A /* FirePostCellNode+Boosts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A335F6B742BA0318905EA8C4 /* FirePostCellNode+Boosts.swift */; }; 9067EC47DC744246AF243836 /* SkeletonView in Frameworks */ = {isa = PBXBuildFile; productRef = 2D8566296B25A0377177D48D /* SkeletonView */; }; 90E8F901D00245EA9611F1D7 /* FireSearchTopicsIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6073E076839999F32D889101 /* FireSearchTopicsIntent.swift */; }; + 90F6623DB548F76D401CC5EC /* FireReadHistoryViewController+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BB53040DFA59555E1E3A3D7 /* FireReadHistoryViewController+Routing.swift */; }; 91BA9CDF0E86830FEB1951B0 /* FireAPMMainThreadStallMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C20BDF82CCD1BF22BB3C7729 /* FireAPMMainThreadStallMonitor.swift */; }; + 91C55013A07282460B0216D1 /* FireTopicDetailFlagSheetHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E46DB675DCF9A0285F0C2B /* FireTopicDetailFlagSheetHost.swift */; }; + 9277029F7EF49DEA6AA24BC7 /* FireTopicDetailTopicVoteCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 472C217534E3F1AF6720933D /* FireTopicDetailTopicVoteCell.swift */; }; 92865B212211D893E4EFB5D2 /* FireAvatarURLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D2C1B5E7EE9786EBC541FAF /* FireAvatarURLTests.swift */; }; 937A11B4C74174E2B823F917 /* FireSessionStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43F4BF80B28464550781CD36 /* FireSessionStoreTests.swift */; }; 939404BE03A327D4A29B6E33 /* FireDiffableListController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 843289DCC260BF71A9C48DA4 /* FireDiffableListController.swift */; }; 93A13E473610BBA7E04846A9 /* FireWebViewBrowserViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7C061876458A31F793EE975 /* FireWebViewBrowserViewController.swift */; }; + 93C359EFFD6688AF18EF40B2 /* FireNotificationHistoryViewController+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BECDE1E729786B3091B3DE7 /* FireNotificationHistoryViewController+Setup.swift */; }; 94474296599507819BE086D1 /* FireTopicDetailKeyboardLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 456ECA20E14DB2A1CB683621 /* FireTopicDetailKeyboardLayoutTests.swift */; }; + 94A343F928DAB8C01489C153 /* FireRootCoordinator+Authentication.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1017A72525731305BC35831D /* FireRootCoordinator+Authentication.swift */; }; 951E66D7F08A42D93EBFFF18 /* FireComposerEditorModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA4EC81D9B54122E7A2497B5 /* FireComposerEditorModels.swift */; }; 957DADCF16F936D3BCCDE7F5 /* FireAppServiceHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = E083189F2BF692A04EB7CF23 /* FireAppServiceHost.swift */; }; 960DD0761DFC82B776B6D33C /* FireHomeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91329D323F92B400ADCD40F4 /* FireHomeViewController.swift */; }; 9726B24BBA832290EA063E8F /* libiconv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = FD5A94769988E39B8BEA7B56 /* libiconv.tbd */; }; - 974A21358F0BAA6942E6FDFC /* fire_uniffi_messagebus.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */; }; + 97F30164C2F5C24C7936C93D /* FirePrivateMessagesViewController+Composer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AC83F1B4B6C002A60FEEB52 /* FirePrivateMessagesViewController+Composer.swift */; }; + 986F0EDE1C6CD8172FF834E9 /* FireNotificationsViewController+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAE0A825545FD5A253328A8C /* FireNotificationsViewController+Routing.swift */; }; 9912E13751119248F5626F77 /* FireMainTabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CABC863F0E7DDEACF5B980D /* FireMainTabBarController.swift */; }; + 991F273F73D0F03AD90C053E /* FireTopicDetailToolbarTitleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17D7B773A9AD783F4497A63E /* FireTopicDetailToolbarTitleView.swift */; }; 997549C307522F353C2C4354 /* FireWebViewBrowserProfile.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6A1ACC49B5E391857645187 /* FireWebViewBrowserProfile.swift */; }; 9A14649AEF38A8229DF6B1FF /* FireTopicListAvatarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19453B1394642775466CBCB3 /* FireTopicListAvatarView.swift */; }; + 9A97E38621EEBC537BB94146 /* FireChatChannelSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52DE4607A98D640E433550FA /* FireChatChannelSession.swift */; }; + 9AC9DCD6A6661BF9920B5515 /* FireFilteredTopicListViewController+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54A952E724AAB1BD1424F8ED /* FireFilteredTopicListViewController+Actions.swift */; }; + 9B074ED624221BEF55AF50D8 /* FireSessionStore+Chat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52553DB0231CE03479BB0F6D /* FireSessionStore+Chat.swift */; }; 9B0DABDC5BA87A4CAFF3232D /* FireEntityStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BADC2ED47CF65AD5BE795908 /* FireEntityStateTests.swift */; }; + 9B2D39BD19CDBA4B7880E8F7 /* FireMainCardAnimator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB2CB885C9D0A5F0B51A6BD /* FireMainCardAnimator.swift */; }; 9B3FEA7A81A1EA5482AEE24B /* FireFeedbackViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 338CF9CFAF93A14A5775E2C7 /* FireFeedbackViewController.swift */; }; + 9CDDF0194D8EF4264C917F77 /* FireTopicDetailCellTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07931FDEC1838345E81FAD49 /* FireTopicDetailCellTheme.swift */; }; + 9D85EA411B0371A13ABD869E /* FireTopicDetailBodyStateCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0564324D95D8461A44097E7 /* FireTopicDetailBodyStateCell.swift */; }; 9DFCA37A0C4D7498B525A034 /* FireNotificationsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D9F899C209796ED8C0F6E51 /* FireNotificationsViewController.swift */; }; 9E7B9F6741C79AF8E6C3D0DA /* FirePostLayoutManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A1B0239607F0ABAEA1ABCE0 /* FirePostLayoutManager.swift */; }; + 9EC5DDF2734BF3A760698793 /* FireOnboardingErrorBannerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC14DDA188D0FD289D2000C3 /* FireOnboardingErrorBannerView.swift */; }; 9F734046F02B45409AD5F1C6 /* FireTopicListMessageBusRefreshTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 859219285EC36B189AF68256 /* FireTopicListMessageBusRefreshTests.swift */; }; + 9FDF261B636A14B6215D3093 /* FireOfflineBanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E99BED9B41412FD7461E1A0 /* FireOfflineBanner.swift */; }; A04B275253CDF8FAAC9D8C6C /* FireSearchStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25FD219C2BFB0727FD0D3DD2 /* FireSearchStore.swift */; }; - A04F6299B25D5CC6C7D21B14 /* fire_uniffi_chat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */; }; A07A9808A87A0F9C08F72CC3 /* FireAccountStatusView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF475D56C78AFC82413AED55 /* FireAccountStatusView.swift */; }; A21B01B774188E91EC382269 /* FireComposerRoute.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0AFC69C6A22193CA4DFDB81 /* FireComposerRoute.swift */; }; A29E21413FA011161D518004 /* FireSessionStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8834ADE6E3ADB8A03391560C /* FireSessionStore.swift */; }; @@ -215,114 +342,176 @@ A2C954EBAE5163E708B3F189 /* FirePostImageNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8092585A18BAFAC8ECAB670D /* FirePostImageNode.swift */; }; A2F884CB6FB920BCEA213B94 /* FireViewProfileIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = B680C9357B6A7ACD65F6B211 /* FireViewProfileIntent.swift */; }; A31CB94E768166B1D7907774 /* FireProfileHeaderComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631A4F82AE7302B3D139F94C /* FireProfileHeaderComponents.swift */; }; - A37D27214981E5D36E7DFD2C /* fire_uniffi_notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */; }; + A3BF7C908F426C9F0C83A34C /* FireNotificationsViewController+Setup.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7ECF142687E73687732AEA8 /* FireNotificationsViewController+Setup.swift */; }; + A3CDF7BB4BAA265461E2606E /* FireTopicDetailRepliesHeaderCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54FC00148F17D9F9CE877CBA /* FireTopicDetailRepliesHeaderCell.swift */; }; A4ADCCA6165C3D05DE20E902 /* FireNotificationHistoryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A91CF53FF7184DF28FF0E2F /* FireNotificationHistoryViewController.swift */; }; + A5BB22B38DAC407A1D187B0C /* FireTopicDetailViewController+Navigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B46ECBB694DF90DD1B736885 /* FireTopicDetailViewController+Navigation.swift */; }; + A5CE38E41B0771F5A4AFC927 /* FireNotificationHistoryViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5A07BA76E51D7D0BAB7C013 /* FireNotificationHistoryViewController+Feed.swift */; }; + A66C7E27316571DAC519ADA0 /* FireTopicDetailFeedController+Layout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761B77070B1B1BF8B0438494 /* FireTopicDetailFeedController+Layout.swift */; }; + A6AD9D0FE1466E1B0FE0C029 /* FirePostCellNode+Polls.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA155A018F817CE8F0B7141C /* FirePostCellNode+Polls.swift */; }; A7657EA99808CEBE3F038176 /* CrashReporter in Frameworks */ = {isa = PBXBuildFile; productRef = 601B450FB4E87A5243FAE5F9 /* CrashReporter */; }; + A7C95828F3955A2FD5B0908A /* FireSessionStore+Composer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5241911D519DBEC442296F3 /* FireSessionStore+Composer.swift */; }; A9966B571DC43A5E38A3F139 /* FireDraftsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 363FB3988C0F6A9163E8DCCF /* FireDraftsViewModel.swift */; }; + AA9943A647FC27A13AEEEE52 /* FireRichTextEmojiAttachment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0882BBB4BE9599B64DE66089 /* FireRichTextEmojiAttachment.swift */; }; + AB88DD7862C5E0979EF6E823 /* FireTopicDetailViewController+Lifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24D2D61CC4D8148BE8831F17 /* FireTopicDetailViewController+Lifecycle.swift */; }; + ABCA883366F517BBFEF2E517 /* FireTopicQuickReplyBarView+Layout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71B48CBCBA543CBD531D27AE /* FireTopicQuickReplyBarView+Layout.swift */; }; ABCB88B6D78156FB353E922B /* FireDiagnosticsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E4063863B8521F7719DD75F /* FireDiagnosticsViewModel.swift */; }; + AEC7A137DD9872E068311236 /* FireOnboardingCredentialFormView+ExternalMethods.swift in Sources */ = {isa = PBXBuildFile; fileRef = C355C70A7664C459E6631CC2 /* FireOnboardingCredentialFormView+ExternalMethods.swift */; }; AF99074CBA5E53804D47CE50 /* FireMarkdownToolbar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DB72EF6EB80A5AF39040998 /* FireMarkdownToolbar.swift */; }; B07B8B527A970B1D4B6EEBE0 /* FireComposerControllerHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A90C8CDE78010E0AD1C1E8B /* FireComposerControllerHost.swift */; }; B0AA426C24E27249B4AE2E57 /* FireAppViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C063DC3D3814082F9655534 /* FireAppViewModel.swift */; }; B0FEF7BFCBC3AE45FDE9978A /* FireComposerInitialBody.swift in Sources */ = {isa = PBXBuildFile; fileRef = E933C082E54A360ADEADA579 /* FireComposerInitialBody.swift */; }; B16BF4995837FCDDEEE90987 /* FireTopicOneboxNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C32FFB215F2C0CDDE5C1221C /* FireTopicOneboxNode.swift */; }; + B4875D9875C18AE2D66659ED /* FireProfileViewController+Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AB87D75E0B7FBF2E8D7F232 /* FireProfileViewController+Table.swift */; }; B4AA77D05D86AB070BE06A93 /* FireNotificationStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 502CE714A74D91C33212BF57 /* FireNotificationStore.swift */; }; B651E365379EF3DC59BE3CBE /* FireBottomInputBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD777ED45F66FF150D5AD9C0 /* FireBottomInputBar.swift */; }; - B7784C41CA7002BF3223029B /* FireTopicDetailFeedCells.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8A36DF217F215CDEB23FDE1 /* FireTopicDetailFeedCells.swift */; }; B80E44034285312AABCD80A0 /* FireTopicImagePipeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = D411B9ABE5C61805B92A2DD2 /* FireTopicImagePipeline.swift */; }; B82BAD7680591EAC6919F60A /* FireAppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39617F1E70204DE972BD489F /* FireAppDelegate.swift */; }; B89B6092EE3AF8B9374CD027 /* FireLargeWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20B88E94BDB7F6C957A8239E /* FireLargeWidget.swift */; }; - B9E25AF09D46C9889B98E8A2 /* FireComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24186C615A12A722B2ABEE06 /* FireComponents.swift */; }; + B8CF8DA3AEBD7AF33055FB36 /* FireTopicPhotoBrowserController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 485A87123651CCA6DAD12B01 /* FireTopicPhotoBrowserController.swift */; }; + B8F6D0C7D23834F0BBB866C5 /* FireNotificationHistoryViewController+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF38A4FC58E0D45139F5AACF /* FireNotificationHistoryViewController+Routing.swift */; }; + B99A8E7770372257C5958C39 /* FireTopicDetailFeedController+CellApplication.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FD2AD7CEF8F673917DF3851 /* FireTopicDetailFeedController+CellApplication.swift */; }; + B9CAD7B0663CD286E6FDF43B /* FireSessionStore+Lifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73539D771AAD2B50965F5D4A /* FireSessionStore+Lifecycle.swift */; }; + BA7D6DA6F64BDFC24D522582 /* FireAvatarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF54CB25631FF68748DF2BC2 /* FireAvatarView.swift */; }; + BAA1DF9C5F7A1B7565337856 /* FireTopicDetailRuntimeItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4ECEB229DCBFAF26411C7B0 /* FireTopicDetailRuntimeItem.swift */; }; BB4439D1D0537CEC232DF789 /* FireWidgetViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06CDD24C8A021152FA0A67AE /* FireWidgetViews.swift */; }; BB6794B89B439C61B8A5620C /* FireFeedbackPresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F2E6EEDE9F6AACB5DBE9B79 /* FireFeedbackPresenter.swift */; }; + BBE3BEC6A314CBDAE0944679 /* FireButtonStyles.swift in Sources */ = {isa = PBXBuildFile; fileRef = A25446A206207198B6223AD5 /* FireButtonStyles.swift */; }; BBE9EB26A016A92092A4D0F2 /* FireTopicDetailPageSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3C653495E2307C802BB389A /* FireTopicDetailPageSkeleton.swift */; }; BD0F6BE28D1D0143383BAF2A /* FireProfileStatsRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8C1BF19AD44A73E451313B6 /* FireProfileStatsRow.swift */; }; - BD294B1545CC5167CAB3620E /* fire_uniffi_search.swift in Sources */ = {isa = PBXBuildFile; fileRef = C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */; }; BDBF0CEBD8F5F7C1C19769B7 /* FireMessageBusCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C11839708BD8C370EB52334 /* FireMessageBusCoordinator.swift */; }; BE531BCFF96A8C23E0180F6B /* FireLogDiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 429B9F8B7087E197A8366D2D /* FireLogDiagnosticsView.swift */; }; BE820074BC6560ABBCF9BAFB /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 92E5B8F5C5B099E404AB7A52 /* SnapKit */; }; BFAAEB3942767128220C1DB5 /* FireAppViewModelSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 656CE7A291529B78CBAB24D8 /* FireAppViewModelSupport.swift */; }; + C07A47C1DCF02FC547D4B7BC /* FireBookmarksViewController+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CEB32A62402439B885D1FE8 /* FireBookmarksViewController+Actions.swift */; }; C0912C916D7832645283F77D /* FireRootCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97E8BD69061BE8C9E301D9BA /* FireRootCoordinator.swift */; }; C1695FEABEA1A67BA6770CD5 /* FireTopicTimingTracker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6566A1D9FDFFFF7BE5EC2229 /* FireTopicTimingTracker.swift */; }; + C211E1C7C68F2B041C1CB171 /* FireTopicVotersSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 962E25B53FD692FBB3355E30 /* FireTopicVotersSheet.swift */; }; + C2FE5DB96A46D25465DA54CF /* FireReadHistoryViewController+Pagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61CE18B274AC0837CDC5CA15 /* FireReadHistoryViewController+Pagination.swift */; }; C35DE51A41D60111114BD225 /* FireTopicDetailStore+Mutations.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAC35CFD6CB96DD7FF21C14A /* FireTopicDetailStore+Mutations.swift */; }; C393F32FAD3010FF51E3E7F2 /* FireAppRouteDestinationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF328A93631D56CB94E4FA7A /* FireAppRouteDestinationView.swift */; }; + C3B7AC070D948696B25A9B21 /* FireTopicDetailToolbarActionsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A957E674F7B62BDD52A2848 /* FireTopicDetailToolbarActionsView.swift */; }; C4BEC91E66B2FACA4DE02EA4 /* FireTopicDetailStore+Reactions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10DDE042BE2C24CFD782C785 /* FireTopicDetailStore+Reactions.swift */; }; C55AB47E8AAB3E7A47EE95FF /* FireTabRoot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C2060FDF4576F412DA20A94 /* FireTabRoot.swift */; }; C5725D3E49E71B490BB43518 /* FirePostEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41317BCBB3F398437E13997C /* FirePostEditorView.swift */; }; C5CA50A5F7707420F084ABA8 /* FireInlineReactionPickerScrollNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 480E9E260E7348B77576F392 /* FireInlineReactionPickerScrollNode.swift */; }; + C5DFF1757291B54826192D80 /* FirePostCellNode+Quote.swift in Sources */ = {isa = PBXBuildFile; fileRef = 646F2B64E7B33FA47974F858 /* FirePostCellNode+Quote.swift */; }; C61D6B26B2EB49CD2BE88224 /* FireRecipientTokenField.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9105F91929CE3DCF342AF0E /* FireRecipientTokenField.swift */; }; + C6387581E79A086B41CCA3E9 /* FireNotificationsViewController+Pagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70CE6114D9AF123B76BCE75E /* FireNotificationsViewController+Pagination.swift */; }; + C66F576761BCCC1CB8A9F84E /* FireTopicDetailFeedCellFactory+Stats.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7B95F21A4FA49C929C36B12 /* FireTopicDetailFeedCellFactory+Stats.swift */; }; C6B79691FF3C1680A14C9367 /* FireTopicListToastView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F68DA8724D28D640697E8436 /* FireTopicListToastView.swift */; }; C6D4775AD6FB33FB87BCC6B4 /* FireTopicRoutePresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07010E91E6B6DFDF4B69170D /* FireTopicRoutePresenter.swift */; }; + C6DB817EF213E5336F0623A2 /* FireBookmarksViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0A537AD2D1ACD3003637D63 /* FireBookmarksViewController+Feed.swift */; }; C6DE052F7456527185C4F1FC /* FirePrivateMessagesControllerHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = A536DCA3FA0164DB4F77F6BB /* FirePrivateMessagesControllerHost.swift */; }; C71C2D1C073DD5D89D71E445 /* FireRichTextParagraphBoundaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBBEC3D8CF3903B3357395DC /* FireRichTextParagraphBoundaryTests.swift */; }; + C7CB9AC0087AC33C03FA6C49 /* FireSessionStore+Topics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 043D502E77F441A2F52911A0 /* FireSessionStore+Topics.swift */; }; + C81693A346DC274E719130A1 /* FireNotificationsViewController+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73FE111B5A807744619586B8 /* FireNotificationsViewController+Actions.swift */; }; + C884174DCD18AEEB455C8BBD /* FireRootCoordinator+RootPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32F810784CE3691264A9DB4D /* FireRootCoordinator+RootPresentation.swift */; }; C8C0449611CDEF356A42A487 /* FireTopicDetailVisibilityCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A283C548CFC6BEDC0D406679 /* FireTopicDetailVisibilityCoordinator.swift */; }; + C8EE185EB06F31D99545D512 /* FireTopicDetailFeedCellFactory+Replies.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5619A74A64AFA6F08BB4AB25 /* FireTopicDetailFeedCellFactory+Replies.swift */; }; C94AC2F334339FCFEB86CB04 /* FireSceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E41FA85B0FAA4DAF83AA747 /* FireSceneDelegate.swift */; }; C957386748A90B96C74997A7 /* FireNotificationPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 242BD5DA9E84D24E217AFBBB /* FireNotificationPresentation.swift */; }; CB59605E778D5DDE7985CD9A /* FireCDKView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6975FD77F7DBD0670E237842 /* FireCDKView.swift */; }; + CB6AA9F8128F7AFD82BA3C39 /* FirePostCellNode+HitTesting.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F0757F6B558DD57C79DBC8 /* FirePostCellNode+HitTesting.swift */; }; + CD02401A3076D6A59D7F9A62 /* FireTopicDetailPostRepliesHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD5D4AB46FC0CF047C1C614B /* FireTopicDetailPostRepliesHost.swift */; }; CD0EDE3D5D4C6F06272F451A /* FireAppViewModel+Chat.swift in Sources */ = {isa = PBXBuildFile; fileRef = D042B49EA2CBAB217A5011AF /* FireAppViewModel+Chat.swift */; }; - CE0D834262ED55561F6BC409 /* FireTopicDetailInteractionCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = E436AB70851CCBCFCD8B8D96 /* FireTopicDetailInteractionCoordinator.swift */; }; + CE707D075E87B10D143FEAD7 /* FireDraftsViewController+Pagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B5B0DE5F6A7C2D89DFAD0FD /* FireDraftsViewController+Pagination.swift */; }; CEC557CB91456A379F8FE867 /* FireReadHistoryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C71352CB3CEB9F98E23B2696 /* FireReadHistoryView.swift */; }; CF0700843F7CDFE2F9140016 /* FireCloudflareChallengeCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABA36C072D3004B0CFDF73D3 /* FireCloudflareChallengeCoordinator.swift */; }; D0125C21FE7596D530229F97 /* FireDiagnosticsShared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FC1DB73221DE5E0CE4B0BB6 /* FireDiagnosticsShared.swift */; }; D100DFBC749CA19A23E11CD3 /* FireAppViewModel+Profile.swift in Sources */ = {isa = PBXBuildFile; fileRef = F74563DD6B9E870850553DDA /* FireAppViewModel+Profile.swift */; }; D1A666B9F78D411F32B91FFC /* FireTextureAttributedTextTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 548ED4AC247F6D252A3A6FF9 /* FireTextureAttributedTextTests.swift */; }; D201FF0609323A45827C583F /* FireAutoLoginPlanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99B66C15EE15F4C35AE369C7 /* FireAutoLoginPlanner.swift */; }; + D24539084535FE2AB8555D72 /* FireAppViewModel+APM.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC375636258776A9578CE154 /* FireAppViewModel+APM.swift */; }; + D289F51C63C35A835E0A2506 /* FireFilteredTopicListViewController+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39BB529E7AD2BD708612BEC3 /* FireFilteredTopicListViewController+Routing.swift */; }; D2D1EA7C7D1208AEE0932A86 /* FireFollowListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5C18328DFF8C1C3145C2DAC /* FireFollowListViewController.swift */; }; + D3C6A464B16938922AB03ACD /* FireAppViewModel+Logging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E94B3E516D54BE118941E7D /* FireAppViewModel+Logging.swift */; }; D54D0269DD6FBCE6AB9488B2 /* FireSearchViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C941204E1E91FA46FDF5BB4 /* FireSearchViewController.swift */; }; + D5B45852653BAD7CFCBA0B58 /* FireTopicDetailFeedController+CollectionUpdates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 226224E8D45EAD0D7B642A5F /* FireTopicDetailFeedController+CollectionUpdates.swift */; }; D668649DC871BC807613F946 /* FireTopicDetailCommentListSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D0C004FB6FE17D6896FF17C /* FireTopicDetailCommentListSnapshot.swift */; }; + D7B9A41AE9DF1D8ACC730F07 /* FireRootCoordinator+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92339F8BFC0B6325CD871533 /* FireRootCoordinator+Routing.swift */; }; D89E51A2B4024E06147DAEE7 /* FireShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 949B945E18FF2C7CF0F29CB4 /* FireShortcuts.swift */; }; D914CE5CE076533C2C932623 /* FirePushDiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C710FF0F248498E25E02037D /* FirePushDiagnosticsView.swift */; }; DA3519D17B33A6FF56FAD600 /* FireDohSourceViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4AF197F76705D49E465A05B /* FireDohSourceViewController.swift */; }; DA6BD635BF623E34D242CB15 /* FireNavigationState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 627535804DAD392D5972B8FF /* FireNavigationState.swift */; }; + DB074584BFA8A2DF54F2ABD1 /* FireMetadataComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFC8987AC1C508F9F95745CB /* FireMetadataComponents.swift */; }; + DB1AA92F0E0DAD629C20562F /* FireSessionStore+Cookies.swift in Sources */ = {isa = PBXBuildFile; fileRef = 020E46ADD920CD8409FE14E9 /* FireSessionStore+Cookies.swift */; }; + DB9AB4DF8626B88FE8CF1BB1 /* FireSessionStore+Interactions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FD26A8FCD98C1473EF11ABC /* FireSessionStore+Interactions.swift */; }; DBCF9ADF03DFCE13241D06DF /* FireTopicSearchBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = D063576FA04A84CFE3BDB703 /* FireTopicSearchBar.swift */; }; + DC3C8637A4BD25812ED13D76 /* FireAppViewModel+LoginSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD5E566582BFC7E23506727B /* FireAppViewModel+LoginSupport.swift */; }; DC4203187C3CAF0846C2D8BF /* FireRouteParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAE00F2C2E4EB9A7A99D327A /* FireRouteParser.swift */; }; + DC6A06F911EE917F3179C0A2 /* FirePrivateMessagesViewController+Routing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8886BB4189E814D4795086A2 /* FirePrivateMessagesViewController+Routing.swift */; }; DC6D81C14F60EEF01F66375E /* FireSearchViewController+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0CEED040EC2CAA199126136 /* FireSearchViewController+Actions.swift */; }; DE050CA5760E795B145F7235 /* FireHomeViewController+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED6324DE2E06F3F22A7128E4 /* FireHomeViewController+Actions.swift */; }; DEAA3B204324377FFCAA1F1B /* FireWidgetBundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEEAB2E2FBB20FA96A15FD11 /* FireWidgetBundle.swift */; }; DEE5B15E431C1F741C79BA45 /* FireTopicPostStateFixtures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 151CF08DEE9DBAE7D98495AC /* FireTopicPostStateFixtures.swift */; }; DEEB51E5288224C8D0D226FF /* FireMotionTokens.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA2BF3D92E750EF89E6387BF /* FireMotionTokens.swift */; }; DF1806BFA9860F7280CD739E /* FireComposerControlFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 484A8A08BEBA8943BBE7EFDC /* FireComposerControlFactory.swift */; }; + DF61516266D80993C3184825 /* FireHomeFeedSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE6A22C3F511DB107633C1FA /* FireHomeFeedSession.swift */; }; E000C5E75601AB4E99B92D63 /* FireUIKitEmptyStateView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6620F19612B42BD0471BE1CA /* FireUIKitEmptyStateView.swift */; }; E014EA02CB83C92E5821707D /* FirePostCellNode+Body.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D70983A36756650D4B734B7 /* FirePostCellNode+Body.swift */; }; E11AA63F28A66090E98C2C47 /* FireMessageBusCoordinatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F45C6AFED397DB19D9A361E /* FireMessageBusCoordinatorTests.swift */; }; E29EFDDF900994EACCA13358 /* FireTopicDetailStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFBA718C5E89D3669A9C6D22 /* FireTopicDetailStoreTests.swift */; }; E2F0F91B27F48F9BF4F1E7B0 /* FireHomeFeedModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2547B98B07D297221A816B50 /* FireHomeFeedModels.swift */; }; + E3317673E81F0D4D307B84AD /* FireAppViewModel+Composer.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9AC6D8E0A9B700CF2FC9BC5 /* FireAppViewModel+Composer.swift */; }; E38E8CABB24B1AD415D69203 /* FireTopicDetailFeedCellFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = B75BF7A232BBE489EB6CDABA /* FireTopicDetailFeedCellFactory.swift */; }; E3A267AB0EB528EFD43162CC /* FireNavigationDestinationCompat.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADF8658FBC78A5397FF37AB1 /* FireNavigationDestinationCompat.swift */; }; E431DE1C6E0C3646603CE3FC /* FirePostCellNode+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 099F0B014FDD2B7431DFC56F /* FirePostCellNode+Actions.swift */; }; E44A45038AA722685149ACA1 /* FireAPMModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5264103A412DF3C9798D470 /* FireAPMModels.swift */; }; E460D11F2D744411AA61E5A6 /* FireNotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AAA1343DE9FD6BD637BBE1B /* FireNotificationService.swift */; }; + E50D3FE4862B8B80EBB60430 /* FireTopicDetailRuntimeSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 613A01B5246B131A5CD3A99E /* FireTopicDetailRuntimeSnapshot.swift */; }; E5268113A96209626BB13FEA /* FireTopicDetailPaginationCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FCFF26F4042B80F6B91305E /* FireTopicDetailPaginationCoordinator.swift */; }; E5B65BD5052ECA7E877B71A1 /* FireAPMDiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 746AD2CF6410CEA9D5DB74F9 /* FireAPMDiagnosticsView.swift */; }; E60D57A49519AD07A4834489 /* FireAPMResourceSampler.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6DEF53357E681E40E482813 /* FireAPMResourceSampler.swift */; }; E67F86DADDE88559438DE849 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 08F96260D49AF4E41AB4739C /* CoreFoundation.framework */; }; E74952BCA8EF2D8E92C528CD /* FireBookmarksView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96F415BE6AC44D202899B9B /* FireBookmarksView.swift */; }; + E7F23FF3CB239AA080E003BF /* FireOnboardingViewController+Captcha.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB750C99150E0A76CEBC0B5D /* FireOnboardingViewController+Captcha.swift */; }; + E8A5818AB91FF4C3735FBBC4 /* FireNotificationsViewController+Feed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45DB137F375693921473FF5E /* FireNotificationsViewController+Feed.swift */; }; E93FB84668880A48421D81BE /* FireExternalLoginMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = C00286677D3818FE5EE2072A /* FireExternalLoginMethod.swift */; }; E9591B19E852848C660207A3 /* FireMotionUIKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF66373F7EF72A887F722CF0 /* FireMotionUIKit.swift */; }; E96C65EF805B1CE2F1A620B9 /* FireCategoriesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B79252C493DBB0CE379F302 /* FireCategoriesView.swift */; }; + EA08684193B24A12AAC82008 /* FireSessionStore+Doh.swift in Sources */ = {isa = PBXBuildFile; fileRef = B621FD0B2E7202C54E9B4B9F /* FireSessionStore+Doh.swift */; }; EA59151603FB85A3B6582722 /* FireListPaginationAndUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E379AA9200DC2BD19BEC807F /* FireListPaginationAndUpdateTests.swift */; }; - EB9B101FE0204DA532CE4635 /* FireTopicDetailFeedModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 876B49163E31ED5650900346 /* FireTopicDetailFeedModels.swift */; }; ED9CD3DE021ED54FED139F8A /* FireTopicDetailRuntimeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7523D63E40FC490B6E3F1ED /* FireTopicDetailRuntimeTests.swift */; }; + EEDD863006F25189D080ED7C /* FireOnboardingViewController+SecondFactor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1C3EFE270DC9623FA5DC221 /* FireOnboardingViewController+SecondFactor.swift */; }; EFE5CAC3C4B129DAEA3C332D /* FireComposerChromeViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D63C49F5DDB1EA9E4BA685C /* FireComposerChromeViews.swift */; }; + F03E48C56FF19099C6DCDAB5 /* FireTopicDetailFeedCellFactory+Voting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6047D5712F521F24592A4CF3 /* FireTopicDetailFeedCellFactory+Voting.swift */; }; + F03F99AD1742500B251CDC9D /* FireAppViewModel+Binding.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED89C80C5CB679C032ACFEB4 /* FireAppViewModel+Binding.swift */; }; + F0D7E2AB2BEFD5133C95FD90 /* FireHostLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABA70FA7C4807563BD752313 /* FireHostLogger.swift */; }; + F1D1168DA91C4AA5FB54A053 /* FireComposerSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 653F86A9F2FFC5E020ABC640 /* FireComposerSession.swift */; }; + F20DC7DCF067D604DAE1E937 /* FireTopicQuickReplyBarView+Callbacks.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDD9ACD8100B4412387AF29F /* FireTopicQuickReplyBarView+Callbacks.swift */; }; F25C8C5E91D29F5BEDB35E9A /* FireTopicDetailPageState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 301D9A74A8ACFE5A61280A86 /* FireTopicDetailPageState.swift */; }; + F2E9D91E93C3065E91D40332 /* FirePostCellNode+Author.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8CAA39E03B78508E1034EBF /* FirePostCellNode+Author.swift */; }; F31A70760B997F5ADFB7C489 /* FireListSectionModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFB6B1F10783D1D78B2D1F63 /* FireListSectionModel.swift */; }; F388A1165747AC85DEE53FFD /* FireAppViewModel+Network.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67D675A6BC377D2479E2A90B /* FireAppViewModel+Network.swift */; }; F3EE595ECC3F647D419D1833 /* FireSmallWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44E64FAEF7CBC79DBC2491BB /* FireSmallWidget.swift */; }; F41EBD87EC59341D3A7DD381 /* FireOnboardingCredentialFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F112BF5A6A226C1D21861F90 /* FireOnboardingCredentialFormView.swift */; }; F4D3095A5C796DB69B6B51B9 /* FireChatChannelViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D7AF4BC29896B1DF99A4A69 /* FireChatChannelViewController.swift */; }; F4E23711C352DB67C48DDEDA /* FireUIKitSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45FD2D6B300FDC58C2FD04A /* FireUIKitSkeleton.swift */; }; - F53E86700CE39C9DD948CFF6 /* fire_uniffi_diagnostics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */; }; + F5AA1C5969A274475572FEF1 /* FireOnboardingViewController+CloudflareRecovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 678964D1FD04557CF8F6C44E /* FireOnboardingViewController+CloudflareRecovery.swift */; }; + F5B39F3B49CA790F67C4AF9D /* FireTopicFormatting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18BE6FB86454F022528B1834 /* FireTopicFormatting.swift */; }; F5FBD9F006A02C2363D1E559 /* FireMarkdownInsertion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E05E38324216F67C39A17D9 /* FireMarkdownInsertion.swift */; }; F6B73F0BFAB8573C89C89CCA /* FireTextureAttributedText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 852D9E719DC6FE610CC4F084 /* FireTextureAttributedText.swift */; }; F6C8A1554FC2C48FB67706A3 /* FireChatViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D9CBC157BF5867CEBE3B65B /* FireChatViewController.swift */; }; + F7E934B79CE09923F9EBFDFA /* FireReadHistoryViewController+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A2D3C167701F62F404BD425 /* FireReadHistoryViewController+Actions.swift */; }; F7F1533B87EEF235D54BA201 /* FireAppRoutePresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE9014C1B335916BCACBC54 /* FireAppRoutePresentationTests.swift */; }; F8963543E87EACAD49C9B131 /* FireCollectionHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CF84F1E6774BE411D4D2C2E /* FireCollectionHost.swift */; }; + F8BAC393CB1196C57E8B5D8D /* FireTopicDetailViewController+Modals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94F3F34915F01F1E23F405EC /* FireTopicDetailViewController+Modals.swift */; }; + FAC6F57FC96EC506F6E1E5FD /* FireReactionUsersSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73BE2EE62F5BED9A61A8BA2C /* FireReactionUsersSheet.swift */; }; FAD86B64AB552B9E3E9F68A7 /* FireTopicDetailFeedController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5267F5B3B48F8FCBF2B891BD /* FireTopicDetailFeedController.swift */; }; + FB26BC73921DFA1E7AE837FE /* FireTopicTimelineBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44B48D5CD0574D77CA72FAAC /* FireTopicTimelineBuilder.swift */; }; + FB7A168EC8DE8DC53146F911 /* FirePostReactionPickerSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FD8241E21CB2CEED4AA475D /* FirePostReactionPickerSheet.swift */; }; FBB020AA0C3F4A97DC1EFE7F /* FireDraftListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8D1B62331E78430BE857CDC /* FireDraftListCell.swift */; }; + FBD68A1E798F8755191B33FD /* FireRemoteImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B57EFF4CD8BF80A874FFC0D /* FireRemoteImage.swift */; }; FC0D869F1AD372A135EF553C /* FireMotionTransitions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE6E5DFE26A75048F89AEC7 /* FireMotionTransitions.swift */; }; FC414F09420A2C1885EFF6C8 /* FireTopicListTopicCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = B25CA09AFB523413280AC469 /* FireTopicListTopicCell.swift */; }; + FCCE36628F9AA6964E3AD6E0 /* FireOnboardingViewController+AuthLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27E052E3B23A20262188A220 /* FireOnboardingViewController+AuthLog.swift */; }; FD8277139166DCD8F96715A9 /* FireFilteredTopicListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9384B4FECD3434E8DCCB3BA /* FireFilteredTopicListView.swift */; }; FD9B148D42E5E38E033DBF65 /* FireChatChannelsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E8DF8D0D6BD537DBD9D7680 /* FireChatChannelsStore.swift */; }; + FE3D890FE6E4535AB72FBF44 /* FireSessionStore+Profiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CF9E9C32EAE5A0B2CABF569 /* FireSessionStore+Profiles.swift */; }; FE4D4CB7A8E064479B52A132 /* FireProfileBadgeChip.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB21BB9232240035114A9653 /* FireProfileBadgeChip.swift */; }; + FEFFED7F365FE3A5C61274D0 /* FireFilteredTopicListControllerHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EC43A75B6485B9166B63DB9 /* FireFilteredTopicListControllerHost.swift */; }; + FF6B6061AD94BDB64476DBFD /* FireDraftsViewController+ComposerRouting.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCFD5D1037C96C405E403F8D /* FireDraftsViewController+ComposerRouting.swift */; }; FFA9CA2BD6BA97E97C13CCA8 /* FireBookmarkEditorSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 989F3E1E2DDB5711DB78EF19 /* FireBookmarkEditorSheet.swift */; }; FFCC342F97F349220632A787 /* FireTopicPresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9189433D7C9260885742A5BA /* FireTopicPresentationTests.swift */; }; /* End PBXBuildFile section */ @@ -357,16 +546,28 @@ 0182FF50BA5178478278FB01 /* FireShimmerModifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireShimmerModifier.swift; sourceTree = ""; }; 019B4B93D3FDB4C799492775 /* FirePresentationIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePresentationIdentity.swift; sourceTree = ""; }; 01D95BB10F2DECA7D5F404DE /* FireTopicListMetricPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListMetricPresentation.swift; sourceTree = ""; }; + 020E46ADD920CD8409FE14E9 /* FireSessionStore+Cookies.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Cookies.swift"; sourceTree = ""; }; + 02FDEF6C96B3C5C3D5763910 /* FireTopicPostMerge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPostMerge.swift; sourceTree = ""; }; + 03D05BEAFD5E582B878E18EF /* FireOnboardingViewController+PhaseRendering.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+PhaseRendering.swift"; sourceTree = ""; }; + 043D502E77F441A2F52911A0 /* FireSessionStore+Topics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Topics.swift"; sourceTree = ""; }; 04449F91CF3EEB51F58E633B /* FireInviteLinksView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireInviteLinksView.swift; sourceTree = ""; }; 0544FD6A0AAD16EA24E22160 /* FireComposerViewController+Submit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireComposerViewController+Submit.swift"; sourceTree = ""; }; + 054BAB7AF7338BAB2ED6782C /* FireTopicDetailViewController+PollVoting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+PollVoting.swift"; sourceTree = ""; }; 054E88D925ECEFF053D4F62F /* FireViewUnreadIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireViewUnreadIntent.swift; sourceTree = ""; }; 06CDD24C8A021152FA0A67AE /* FireWidgetViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWidgetViews.swift; sourceTree = ""; }; 07010E91E6B6DFDF4B69170D /* FireTopicRoutePresenter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicRoutePresenter.swift; sourceTree = ""; }; + 0789B19C92B2B04D685F52AE /* FireTopicDetailViewController+PostManagement.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+PostManagement.swift"; sourceTree = ""; }; + 07931FDEC1838345E81FAD49 /* FireTopicDetailCellTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailCellTheme.swift; sourceTree = ""; }; 07E3386C6FC3093869C79E57 /* FireProfileActivityRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileActivityRow.swift; sourceTree = ""; }; 08710076BA9FA07121C0A9C5 /* FireBoostInputViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBoostInputViewController.swift; sourceTree = ""; }; + 0882BBB4BE9599B64DE66089 /* FireRichTextEmojiAttachment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextEmojiAttachment.swift; sourceTree = ""; }; + 08A7A8FB9455E94256F352A3 /* FireProfileViewController+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireProfileViewController+Routing.swift"; sourceTree = ""; }; 08F96260D49AF4E41AB4739C /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; }; 093EEF1E0EBDB24ED7106CDD /* FirePostCellNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostCellNode.swift; sourceTree = ""; }; 099F0B014FDD2B7431DFC56F /* FirePostCellNode+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Actions.swift"; sourceTree = ""; }; + 09C4C0F1BD2B7F38AC26618D /* FireTopicRenderProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicRenderProjection.swift; sourceTree = ""; }; + 09F2FA662430C8D8F81AF72A /* FirePostCellNode+Configuration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Configuration.swift"; sourceTree = ""; }; + 0AC83F1B4B6C002A60FEEB52 /* FirePrivateMessagesViewController+Composer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePrivateMessagesViewController+Composer.swift"; sourceTree = ""; }; 0AE6E5DFE26A75048F89AEC7 /* FireMotionTransitions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionTransitions.swift; sourceTree = ""; }; 0AE9014C1B335916BCACBC54 /* FireAppRoutePresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRoutePresentationTests.swift; sourceTree = ""; }; 0C11839708BD8C370EB52334 /* FireMessageBusCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMessageBusCoordinator.swift; sourceTree = ""; }; @@ -375,21 +576,32 @@ 0D70983A36756650D4B734B7 /* FirePostCellNode+Body.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Body.swift"; sourceTree = ""; }; 0D7AF4BC29896B1DF99A4A69 /* FireChatChannelViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireChatChannelViewController.swift; sourceTree = ""; }; 0DB69FD096A581A18D9D16C5 /* Fire-Local-Release.example.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Local-Release.example.xcconfig"; sourceTree = ""; }; - 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_types.swift; sourceTree = ""; }; + 0DC8951F1970697D3FBEB8DF /* FireNotificationHistoryViewController+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationHistoryViewController+Actions.swift"; sourceTree = ""; }; 0F45C6AFED397DB19D9A361E /* FireMessageBusCoordinatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMessageBusCoordinatorTests.swift; sourceTree = ""; }; + 0F853E29620466DE5501395D /* FireSessionStoreError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSessionStoreError.swift; sourceTree = ""; }; + 0F8C73964C70D1D4BE662154 /* FireSkeleton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSkeleton.swift; sourceTree = ""; }; + 1017A72525731305BC35831D /* FireRootCoordinator+Authentication.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireRootCoordinator+Authentication.swift"; sourceTree = ""; }; 10DDE042BE2C24CFD782C785 /* FireTopicDetailStore+Reactions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailStore+Reactions.swift"; sourceTree = ""; }; 1127D7C4622ADFEED430046E /* FireExportDiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireExportDiagnosticsView.swift; sourceTree = ""; }; 129694A5F35FF78B3F810049 /* FireAPMManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMManager.swift; sourceTree = ""; }; 1348CE0E6B9A223627CAE8E8 /* FireComposerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerViewController.swift; sourceTree = ""; }; + 139A690F74C13E830A6A959E /* FireMainNavigationController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMainNavigationController.swift; sourceTree = ""; }; 140FAA0B35B71300049C7E14 /* FireLoginScriptsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireLoginScriptsTests.swift; sourceTree = ""; }; 1481ACDF04D249FF61B1D0DF /* FireDeveloperToolsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDeveloperToolsView.swift; sourceTree = ""; }; 149C3D9916D55374B1B4A37C /* FireAppRouteControllerFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRouteControllerFactory.swift; sourceTree = ""; }; 151CF08DEE9DBAE7D98495AC /* FireTopicPostStateFixtures.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPostStateFixtures.swift; sourceTree = ""; }; + 15C52722D4C57B1E8C3D6258 /* FireTopicDetailViewController+QuickReply.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+QuickReply.swift"; sourceTree = ""; }; 17A3228BF5A8EB20BA7E43E9 /* FireSearchViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSearchViewController+Feed.swift"; sourceTree = ""; }; - 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_diagnostics.swift; sourceTree = ""; }; + 17D7B773A9AD783F4497A63E /* FireTopicDetailToolbarTitleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailToolbarTitleView.swift; sourceTree = ""; }; + 1815693E5384964FEFF564D9 /* FireSessionStore+Ldc.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Ldc.swift"; sourceTree = ""; }; + 18BE6FB86454F022528B1834 /* FireTopicFormatting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicFormatting.swift; sourceTree = ""; }; + 190AEA75EC6B05E5FFA7796E /* FireSessionStore+HomeScope.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+HomeScope.swift"; sourceTree = ""; }; 19453B1394642775466CBCB3 /* FireTopicListAvatarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListAvatarView.swift; sourceTree = ""; }; + 1A7D88710A4E967AB393E736 /* FireOnboardingCredentialFormView+LastLoginHint.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingCredentialFormView+LastLoginHint.swift"; sourceTree = ""; }; + 1A957E674F7B62BDD52A2848 /* FireTopicDetailToolbarActionsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailToolbarActionsView.swift; sourceTree = ""; }; 1CC70D5009C55B1897598989 /* FireComposerDraftHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerDraftHelpers.swift; sourceTree = ""; }; 1D0C004FB6FE17D6896FF17C /* FireTopicDetailCommentListSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailCommentListSnapshot.swift; sourceTree = ""; }; + 1D724BCFA0E3C41156FAF7A3 /* FireTopicDetailViewController+Keyboard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+Keyboard.swift"; sourceTree = ""; }; 1D9F899C209796ED8C0F6E51 /* FireNotificationsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationsViewController.swift; sourceTree = ""; }; 1DB72EF6EB80A5AF39040998 /* FireMarkdownToolbar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMarkdownToolbar.swift; sourceTree = ""; }; 1E05E38324216F67C39A17D9 /* FireMarkdownInsertion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMarkdownInsertion.swift; sourceTree = ""; }; @@ -399,237 +611,383 @@ 1FC1DB73221DE5E0CE4B0BB6 /* FireDiagnosticsShared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDiagnosticsShared.swift; sourceTree = ""; }; 20A1C7BA55C3D9BCB48898A3 /* FirePostBoostManualScrollerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostBoostManualScrollerView.swift; sourceTree = ""; }; 20B88E94BDB7F6C957A8239E /* FireLargeWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireLargeWidget.swift; sourceTree = ""; }; + 226224E8D45EAD0D7B642A5F /* FireTopicDetailFeedController+CollectionUpdates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedController+CollectionUpdates.swift"; sourceTree = ""; }; 2349D54A410A25E70102DF84 /* AsyncDisplayKit.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = AsyncDisplayKit.xcframework; path = LocalPackages/TextureCore/Artifacts/AsyncDisplayKit.xcframework; sourceTree = ""; }; - 24186C615A12A722B2ABEE06 /* FireComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComponents.swift; sourceTree = ""; }; 242BD5DA9E84D24E217AFBBB /* FireNotificationPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationPresentation.swift; sourceTree = ""; }; + 24AC0E82D4FD3B75E1DEF2A3 /* FirePostCellNode+Appearance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Appearance.swift"; sourceTree = ""; }; + 24C97053064713B8ADD07FE6 /* FireRichTextAttributedStringBuilder+Lists.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireRichTextAttributedStringBuilder+Lists.swift"; sourceTree = ""; }; + 24D2D61CC4D8148BE8831F17 /* FireTopicDetailViewController+Lifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+Lifecycle.swift"; sourceTree = ""; }; 24E7CCCA8B867D5E6B0CE198 /* FirePostCellLayoutCalculator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostCellLayoutCalculator.swift; sourceTree = ""; }; 2547B98B07D297221A816B50 /* FireHomeFeedModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeFeedModels.swift; sourceTree = ""; }; - 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_chat.swift; sourceTree = ""; }; 25A9FA3A65196B334165E0C6 /* FireMotionUIKitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionUIKitTests.swift; sourceTree = ""; }; 25FD219C2BFB0727FD0D3DD2 /* FireSearchStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchStore.swift; sourceTree = ""; }; + 2604E07D8A130094F4A756B1 /* FireRichTextAttributedStringBuilder+Inline.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireRichTextAttributedStringBuilder+Inline.swift"; sourceTree = ""; }; 2641F70C8CEAE937D1D4A75D /* FireTopicDetailStore+Presence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailStore+Presence.swift"; sourceTree = ""; }; 266F4CE0F161C8BF7A9F04C1 /* FireComposerViewController+Chrome.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireComposerViewController+Chrome.swift"; sourceTree = ""; }; + 27E052E3B23A20262188A220 /* FireOnboardingViewController+AuthLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+AuthLog.swift"; sourceTree = ""; }; 2850469E1F9F91DD6FA787AE /* FirePrivateMessageCells.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePrivateMessageCells.swift; sourceTree = ""; }; 2933910F4309CBB2CC5F2BEC /* FireAppViewModel+RecoveryURLs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+RecoveryURLs.swift"; sourceTree = ""; }; + 293D79BE540B73D84BDFABF6 /* FireDraftsViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireDraftsViewController+Feed.swift"; sourceTree = ""; }; 2953DE2D6AAF5DB46E77FC4E /* FireTopicDetailStore+Load.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailStore+Load.swift"; sourceTree = ""; }; 299683BEDEC559B03C136C34 /* FireAppRouteTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRouteTests.swift; sourceTree = ""; }; 2A3BEB6E72878BC3AD27B487 /* FireProfileTrustLevelPill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileTrustLevelPill.swift; sourceTree = ""; }; 2A763199D74A1026B2ADB530 /* FirePostCellNode+Reactions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Reactions.swift"; sourceTree = ""; }; + 2AB87D75E0B7FBF2E8D7F232 /* FireProfileViewController+Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireProfileViewController+Table.swift"; sourceTree = ""; }; + 2AC8045F6F7424FF87C85E8F /* FireBookmarksViewController+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireBookmarksViewController+Routing.swift"; sourceTree = ""; }; + 2B596C5C2E8BEF5EB24A7A07 /* FireOnboardingCredentialFormView+Options.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingCredentialFormView+Options.swift"; sourceTree = ""; }; + 2B5B0DE5F6A7C2D89DFAD0FD /* FireDraftsViewController+Pagination.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireDraftsViewController+Pagination.swift"; sourceTree = ""; }; + 2BD298D3BCD7D884DF020409 /* FireFilteredTopicListViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireFilteredTopicListViewController+Feed.swift"; sourceTree = ""; }; 2C2060FDF4576F412DA20A94 /* FireTabRoot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTabRoot.swift; sourceTree = ""; }; 2C8AEE7516614D73C079F860 /* FireReadHistoryViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireReadHistoryViewController.swift; sourceTree = ""; }; 2C941204E1E91FA46FDF5BB4 /* FireSearchViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchViewController.swift; sourceTree = ""; }; + 2CA0AC514C9C8CDBCF7F7606 /* FireCapturedLoginState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCapturedLoginState.swift; sourceTree = ""; }; 2E4063863B8521F7719DD75F /* FireDiagnosticsViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDiagnosticsViewModel.swift; sourceTree = ""; }; 2F329C317F6932DC1D07AD03 /* FireBookmarksViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBookmarksViewController.swift; sourceTree = ""; }; 2FCFF26F4042B80F6B91305E /* FireTopicDetailPaginationCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailPaginationCoordinator.swift; sourceTree = ""; }; 301D9A74A8ACFE5A61280A86 /* FireTopicDetailPageState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailPageState.swift; sourceTree = ""; }; + 30B07CEE7C89CA1C63884E37 /* FireOnboardingViewController+Brand.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+Brand.swift"; sourceTree = ""; }; 30F75C7877A380748026CE06 /* FireWidget.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = FireWidget.entitlements; sourceTree = ""; }; 31B8731C1D7A069FB93E3B5B /* FirePostBoostBarrageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostBoostBarrageView.swift; sourceTree = ""; }; 323125829E4EEA3C5535793D /* FireChatMessageCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireChatMessageCell.swift; sourceTree = ""; }; + 323769D2402BB6DB956BCBA3 /* FirePostCellNode+QuoteAction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+QuoteAction.swift"; sourceTree = ""; }; + 32F810784CE3691264A9DB4D /* FireRootCoordinator+RootPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireRootCoordinator+RootPresentation.swift"; sourceTree = ""; }; + 3367E65714661E982001EBCC /* FireErrorStates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireErrorStates.swift; sourceTree = ""; }; 338CF9CFAF93A14A5775E2C7 /* FireFeedbackViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFeedbackViewController.swift; sourceTree = ""; }; 33CF9D0635D23971967624E4 /* FireProfileHeaderTableCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileHeaderTableCell.swift; sourceTree = ""; }; 33FDDDCB91B973C1115A8F6B /* FireEntityIndex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireEntityIndex.swift; sourceTree = ""; }; + 34B1C77D253E343F11117883 /* FireTopicSearchPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicSearchPresentation.swift; sourceTree = ""; }; 3623960CD988F423E24CCE8C /* FireFilteredTopicListViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFilteredTopicListViewController.swift; sourceTree = ""; }; 363FB3988C0F6A9163E8DCCF /* FireDraftsViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDraftsViewModel.swift; sourceTree = ""; }; 36AF08512A66853830920C56 /* FireNotificationListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationListCell.swift; sourceTree = ""; }; 373861687BBCD8EB8E350DA4 /* FireAPMEventStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMEventStore.swift; sourceTree = ""; }; + 377285D279E45E4211DC2CEA /* FireTopicDetailReplyFooterCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailReplyFooterCell.swift; sourceTree = ""; }; + 385C82707C8B082E8EEC5268 /* FireDraftsViewController+Setup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireDraftsViewController+Setup.swift"; sourceTree = ""; }; + 3887899D62CC6BED4D8F686C /* FireTopicDetailModalRouter+Alerts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailModalRouter+Alerts.swift"; sourceTree = ""; }; + 395803401D7AD61E67521D16 /* FireSessionStore+Bootstrap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Bootstrap.swift"; sourceTree = ""; }; 39617F1E70204DE972BD489F /* FireAppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppDelegate.swift; sourceTree = ""; }; + 39BB529E7AD2BD708612BEC3 /* FireFilteredTopicListViewController+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireFilteredTopicListViewController+Routing.swift"; sourceTree = ""; }; 3A2D87C396EF471305C2712F /* Fire-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "Fire-Info.plist"; sourceTree = ""; }; 3A90C8CDE78010E0AD1C1E8B /* FireComposerControllerHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerControllerHost.swift; sourceTree = ""; }; + 3AFA3082D577488D13F57EE2 /* FireTopicUserInfoSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicUserInfoSheet.swift; sourceTree = ""; }; 3B3E420F46F18B629C3C78AF /* FireUserCardChromeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUserCardChromeTests.swift; sourceTree = ""; }; 3C21247110244DC0C9E0BEDA /* FireTopicDetailFeedUpdatePipeline.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailFeedUpdatePipeline.swift; sourceTree = ""; }; + 3CA68AD35F9427999927D825 /* FireTopicDetailTextCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailTextCell.swift; sourceTree = ""; }; + 3CEB32A62402439B885D1FE8 /* FireBookmarksViewController+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireBookmarksViewController+Actions.swift"; sourceTree = ""; }; + 3D9266ECC882A7206C1A2930 /* FireNotificationHistoryViewController+Pagination.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationHistoryViewController+Pagination.swift"; sourceTree = ""; }; 3E056C5583CA4544A2781E2F /* FireTopicInteractionService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicInteractionService.swift; sourceTree = ""; }; 3E406BC86F476DB0FF2E688F /* FireHeadlessExternalLoginEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHeadlessExternalLoginEngine.swift; sourceTree = ""; }; + 3EC43A75B6485B9166B63DB9 /* FireFilteredTopicListControllerHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFilteredTopicListControllerHost.swift; sourceTree = ""; }; 3EDB5751E3066F0E94352716 /* FireTopicListPalette.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListPalette.swift; sourceTree = ""; }; 3FC109FBAA1787EF49336258 /* SessionState+Helpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SessionState+Helpers.swift"; sourceTree = ""; }; + 401B5C6197D90A29EDE33441 /* String+FireIfEmpty.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+FireIfEmpty.swift"; sourceTree = ""; }; 40B24CD54573A1C053B37121 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; 41317BCBB3F398437E13997C /* FirePostEditorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostEditorView.swift; sourceTree = ""; }; 41AECD88340113D3FD81D59B /* FireTopicPresentationTestSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPresentationTestSupport.swift; sourceTree = ""; }; + 41B071F383E0E0129E68BD8A /* FireTopicDetailToolbarMetrics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailToolbarMetrics.swift; sourceTree = ""; }; 42166EE11327DFA41BF1AE4A /* FireHomeShellViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeShellViews.swift; sourceTree = ""; }; 429B9F8B7087E197A8366D2D /* FireLogDiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireLogDiagnosticsView.swift; sourceTree = ""; }; 43F4BF80B28464550781CD36 /* FireSessionStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSessionStoreTests.swift; sourceTree = ""; }; + 44B48D5CD0574D77CA72FAAC /* FireTopicTimelineBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicTimelineBuilder.swift; sourceTree = ""; }; + 44C646162E7A938015483CE7 /* FireRootCoordinator+APM.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireRootCoordinator+APM.swift"; sourceTree = ""; }; 44E64FAEF7CBC79DBC2491BB /* FireSmallWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSmallWidget.swift; sourceTree = ""; }; 4543C11B22E10FA9DA852E16 /* FireWidgetData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWidgetData.swift; sourceTree = ""; }; 456ECA20E14DB2A1CB683621 /* FireTopicDetailKeyboardLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailKeyboardLayoutTests.swift; sourceTree = ""; }; 457CCC7AE29267A8B9448BA7 /* FireTopicDetailViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailViewController.swift; sourceTree = ""; }; + 45DB137F375693921473FF5E /* FireNotificationsViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationsViewController+Feed.swift"; sourceTree = ""; }; 462EB3CAB0AACF4846EA3AC5 /* FireCaptchaLoginDialogController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCaptchaLoginDialogController.swift; sourceTree = ""; }; 46C35F105D036EECAAE7B93D /* FireRouteParserTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRouteParserTests.swift; sourceTree = ""; }; 46CF09F1CBAC6CFAA0E9128A /* FireAppRoute.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRoute.swift; sourceTree = ""; }; + 472C217534E3F1AF6720933D /* FireTopicDetailTopicVoteCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailTopicVoteCell.swift; sourceTree = ""; }; + 473E5CD558B2D86650E606F2 /* FireOnboardingCredentialFormView+LoginButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingCredentialFormView+LoginButton.swift"; sourceTree = ""; }; + 4741FBBFF6A7C139E90AE6C3 /* FlowLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlowLayout.swift; sourceTree = ""; }; 480E9E260E7348B77576F392 /* FireInlineReactionPickerScrollNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireInlineReactionPickerScrollNode.swift; sourceTree = ""; }; 48153CE6A692130B4F8D97C5 /* FireHomeScopeChromeViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeScopeChromeViews.swift; sourceTree = ""; }; 484A8A08BEBA8943BBE7EFDC /* FireComposerControlFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerControlFactory.swift; sourceTree = ""; }; - 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_session.swift; sourceTree = ""; }; + 485A87123651CCA6DAD12B01 /* FireTopicPhotoBrowserController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPhotoBrowserController.swift; sourceTree = ""; }; 48CAB0E38556929FC140E25D /* Fire.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Fire.app; sourceTree = BUILT_PRODUCTS_DIR; }; 49784F572BD41F7D9F024F55 /* FirePostFlagSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostFlagSheet.swift; sourceTree = ""; }; + 49DFB8ED64CAE57ADDFABFD6 /* FireRichTextTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextTextView.swift; sourceTree = ""; }; + 49FEB500EA67E0649586CB1B /* FireTopicRenderModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicRenderModels.swift; sourceTree = ""; }; 4B2A79D53BB06F4FE60BE258 /* FireBottomInputBarTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBottomInputBarTests.swift; sourceTree = ""; }; 4B79252C493DBB0CE379F302 /* FireCategoriesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCategoriesView.swift; sourceTree = ""; }; + 4DB484B4F02ECBEE1DEF9A7A /* FireSessionStore+Authentication.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Authentication.swift"; sourceTree = ""; }; 4E41FA85B0FAA4DAF83AA747 /* FireSceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSceneDelegate.swift; sourceTree = ""; }; 4E86F61501D5E51FA1584156 /* FireWidgetSnapshotWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWidgetSnapshotWriter.swift; sourceTree = ""; }; 4EADCA671EA2C50617A86458 /* FireTopicListChips.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListChips.swift; sourceTree = ""; }; 4EBE1819A4C585EBED2C8F1C /* FireSearchService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchService.swift; sourceTree = ""; }; 4F2E6EEDE9F6AACB5DBE9B79 /* FireFeedbackPresenter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFeedbackPresenter.swift; sourceTree = ""; }; + 4FD26A8FCD98C1473EF11ABC /* FireSessionStore+Interactions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Interactions.swift"; sourceTree = ""; }; 502CE714A74D91C33212BF57 /* FireNotificationStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationStore.swift; sourceTree = ""; }; 5103D4725A903220359B1C42 /* FireWebViewCookieActionSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWebViewCookieActionSupportTests.swift; sourceTree = ""; }; + 5158DC91BBAB977BE1737A7B /* FireAppViewModel+TopicDetail.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+TopicDetail.swift"; sourceTree = ""; }; + 519940DDA0A5323D3793D653 /* FireChatListSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireChatListSession.swift; sourceTree = ""; }; + 52553DB0231CE03479BB0F6D /* FireSessionStore+Chat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Chat.swift"; sourceTree = ""; }; 5267F5B3B48F8FCBF2B891BD /* FireTopicDetailFeedController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailFeedController.swift; sourceTree = ""; }; 52BB1F5B0970DC2504ACD989 /* FirePushRegistrationCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePushRegistrationCoordinator.swift; sourceTree = ""; }; + 52DE4607A98D640E433550FA /* FireChatChannelSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireChatChannelSession.swift; sourceTree = ""; }; + 53B37883C9DB898936D74AAF /* FireOnboardingCredentialFormView+Fields.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingCredentialFormView+Fields.swift"; sourceTree = ""; }; 548ED4AC247F6D252A3A6FF9 /* FireTextureAttributedTextTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTextureAttributedTextTests.swift; sourceTree = ""; }; + 5493A60CF66C250B7225025D /* FireHomeStyleSkeletonCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeStyleSkeletonCell.swift; sourceTree = ""; }; + 54A952E724AAB1BD1424F8ED /* FireFilteredTopicListViewController+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireFilteredTopicListViewController+Actions.swift"; sourceTree = ""; }; + 54C93686EAAB54DE7694FFF1 /* FireBookmarksViewController+Pagination.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireBookmarksViewController+Pagination.swift"; sourceTree = ""; }; 54D532ECF928AC54FE11A47C /* FireUIKitToast.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitToast.swift; sourceTree = ""; }; + 54FC00148F17D9F9CE877CBA /* FireTopicDetailRepliesHeaderCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRepliesHeaderCell.swift; sourceTree = ""; }; + 550B08C28394AE3DDDC313C8 /* FireRichTextAttributedStringBuilder+Quotes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireRichTextAttributedStringBuilder+Quotes.swift"; sourceTree = ""; }; 5592C6396CAD3B7F3672D0EA /* FireTopicDetailRuntimeSnapshotBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRuntimeSnapshotBuilder.swift; sourceTree = ""; }; + 55A00A8DFE3727573935D235 /* FirePostCellNode+ContextMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+ContextMenu.swift"; sourceTree = ""; }; + 5619A74A64AFA6F08BB4AB25 /* FireTopicDetailFeedCellFactory+Replies.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedCellFactory+Replies.swift"; sourceTree = ""; }; 56971CD699F6CE264E0EB563 /* FireTopicDetailSearchCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailSearchCoordinator.swift; sourceTree = ""; }; 577A99743CDCAA0033E2398C /* FireTopicEditorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicEditorView.swift; sourceTree = ""; }; + 58E2588F8B8817932933EB55 /* FireRichTextAttributedStringBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextAttributedStringBuilder.swift; sourceTree = ""; }; 5AE3D99CBA147535E68FB7E6 /* FireTopicDetailSnapshotAssembler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailSnapshotAssembler.swift; sourceTree = ""; }; 5D74211CDB2098D655F1604A /* FireCloudflareChallengeRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCloudflareChallengeRecoveryTests.swift; sourceTree = ""; }; 5D9CBC157BF5867CEBE3B65B /* FireChatViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireChatViewController.swift; sourceTree = ""; }; 5DF67696B342C706CB3FAAFB /* FireProfileViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileViewModel.swift; sourceTree = ""; }; + 5E94B3E516D54BE118941E7D /* FireAppViewModel+Logging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Logging.swift"; sourceTree = ""; }; + 5E99BED9B41412FD7461E1A0 /* FireOfflineBanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireOfflineBanner.swift; sourceTree = ""; }; + 5F908C70A11E537FC1F475DE /* FireFilteredTopicListViewController+Setup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireFilteredTopicListViewController+Setup.swift"; sourceTree = ""; }; + 6047D5712F521F24592A4CF3 /* FireTopicDetailFeedCellFactory+Voting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedCellFactory+Voting.swift"; sourceTree = ""; }; 6073E076839999F32D889101 /* FireSearchTopicsIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchTopicsIntent.swift; sourceTree = ""; }; + 613A01B5246B131A5CD3A99E /* FireTopicDetailRuntimeSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRuntimeSnapshot.swift; sourceTree = ""; }; 61901919CC904557BB48E7B9 /* FireShakeWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireShakeWindow.swift; sourceTree = ""; }; + 61CE18B274AC0837CDC5CA15 /* FireReadHistoryViewController+Pagination.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireReadHistoryViewController+Pagination.swift"; sourceTree = ""; }; 623CAF283DA441336D75B33B /* FireSearchFeedModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchFeedModels.swift; sourceTree = ""; }; 6245C0A19C0D937131AC08C0 /* FireComposerCategoryGuidance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerCategoryGuidance.swift; sourceTree = ""; }; 627535804DAD392D5972B8FF /* FireNavigationState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNavigationState.swift; sourceTree = ""; }; 631A4F82AE7302B3D139F94C /* FireProfileHeaderComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileHeaderComponents.swift; sourceTree = ""; }; + 646F2B64E7B33FA47974F858 /* FirePostCellNode+Quote.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Quote.swift"; sourceTree = ""; }; + 653F86A9F2FFC5E020ABC640 /* FireComposerSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerSession.swift; sourceTree = ""; }; 6566A1D9FDFFFF7BE5EC2229 /* FireTopicTimingTracker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicTimingTracker.swift; sourceTree = ""; }; 656CE7A291529B78CBAB24D8 /* FireAppViewModelSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppViewModelSupport.swift; sourceTree = ""; }; 6620F19612B42BD0471BE1CA /* FireUIKitEmptyStateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitEmptyStateView.swift; sourceTree = ""; }; + 670A641D02B78D7C613EEDBC /* FireOnboardingViewController+StartupRouting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+StartupRouting.swift"; sourceTree = ""; }; + 678964D1FD04557CF8F6C44E /* FireOnboardingViewController+CloudflareRecovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+CloudflareRecovery.swift"; sourceTree = ""; }; 67D675A6BC377D2479E2A90B /* FireAppViewModel+Network.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Network.swift"; sourceTree = ""; }; 6958AA64094FA7BB21B5FC36 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; 6975FD77F7DBD0670E237842 /* FireCDKView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCDKView.swift; sourceTree = ""; }; 6A765149EB821BBD6B81CCE8 /* FirePrivateMessagesViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePrivateMessagesViewController.swift; sourceTree = ""; }; 6B8FD2EBF4867A3E5C5A1EF9 /* FireUserCardViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUserCardViewController.swift; sourceTree = ""; }; + 6B98E98DFD1E03963E8CF83C /* FireDraftState+Presentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireDraftState+Presentation.swift"; sourceTree = ""; }; 6C063DC3D3814082F9655534 /* FireAppViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppViewModel.swift; sourceTree = ""; }; 6CABC863F0E7DDEACF5B980D /* FireMainTabBarController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMainTabBarController.swift; sourceTree = ""; }; + 6CAD3D8482640C6E6C636D0A /* FireFilteredFeedSelectorCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFilteredFeedSelectorCell.swift; sourceTree = ""; }; + 6D0074D8DEFA2184F2EA3955 /* UIView+FireHierarchy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIView+FireHierarchy.swift"; sourceTree = ""; }; 6D2C1B5E7EE9786EBC541FAF /* FireAvatarURLTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAvatarURLTests.swift; sourceTree = ""; }; + 6DF5C51601950F6B6B2E84AD /* FireSessionStore+WritePreflight.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+WritePreflight.swift"; sourceTree = ""; }; + 6E3BCBF5C07A882EFEF21D2E /* FireTopicDetailViewController+Reactions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+Reactions.swift"; sourceTree = ""; }; + 707CDA3897A19341B7B09333 /* FireAppViewModel+Startup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Startup.swift"; sourceTree = ""; }; + 70CE6114D9AF123B76BCE75E /* FireNotificationsViewController+Pagination.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationsViewController+Pagination.swift"; sourceTree = ""; }; 70D03FC864701908D985F621 /* FireRichTextNodeLinkDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextNodeLinkDelegate.swift; sourceTree = ""; }; + 70F2622FC71DFA7C3DCC8749 /* FireTopicDetailFeedCellFactory+BodyState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedCellFactory+BodyState.swift"; sourceTree = ""; }; 71468CA537E8C6D7E84090CB /* FireChatBusPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireChatBusPayload.swift; sourceTree = ""; }; + 71B48CBCBA543CBD531D27AE /* FireTopicQuickReplyBarView+Layout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicQuickReplyBarView+Layout.swift"; sourceTree = ""; }; 71D0063A5014FEF51FB2B8E8 /* FireMyBadgesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMyBadgesView.swift; sourceTree = ""; }; 7337AE7EB0411AC9B53AD853 /* Fire-Local-Debug.example.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Local-Debug.example.xcconfig"; sourceTree = ""; }; + 73539D771AAD2B50965F5D4A /* FireSessionStore+Lifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Lifecycle.swift"; sourceTree = ""; }; + 73BE2EE62F5BED9A61A8BA2C /* FireReactionUsersSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireReactionUsersSheet.swift; sourceTree = ""; }; 73F4567310A9F3A185F64D4D /* FireLDCView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireLDCView.swift; sourceTree = ""; }; + 73FE111B5A807744619586B8 /* FireNotificationsViewController+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationsViewController+Actions.swift"; sourceTree = ""; }; 7408129F7C65831B92FBCEF7 /* FireChatChannelViewController+Load.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireChatChannelViewController+Load.swift"; sourceTree = ""; }; 746AD2CF6410CEA9D5DB74F9 /* FireAPMDiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMDiagnosticsView.swift; sourceTree = ""; }; + 761B77070B1B1BF8B0438494 /* FireTopicDetailFeedController+Layout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedController+Layout.swift"; sourceTree = ""; }; + 7B1DFFFE930AD6B28E469534 /* FireRichTextAttributedStringBuilder+Onebox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireRichTextAttributedStringBuilder+Onebox.swift"; sourceTree = ""; }; + 7B57EFF4CD8BF80A874FFC0D /* FireRemoteImage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRemoteImage.swift; sourceTree = ""; }; 7BA62EEC87348A069D789A7E /* FireTagPickerSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTagPickerSheet.swift; sourceTree = ""; }; + 7BECDE1E729786B3091B3DE7 /* FireNotificationHistoryViewController+Setup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationHistoryViewController+Setup.swift"; sourceTree = ""; }; 7CF84F1E6774BE411D4D2C2E /* FireCollectionHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCollectionHost.swift; sourceTree = ""; }; + 7DB2CB885C9D0A5F0B51A6BD /* FireMainCardAnimator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMainCardAnimator.swift; sourceTree = ""; }; 7E5E15383418191B6F6074BC /* FireNotificationBannerCells.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationBannerCells.swift; sourceTree = ""; }; 7E8DF8D0D6BD537DBD9D7680 /* FireChatChannelsStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireChatChannelsStore.swift; sourceTree = ""; }; + 7F8D2A6776D4D192A6051BD4 /* FireTopicDetailModalRouter+Navigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailModalRouter+Navigation.swift"; sourceTree = ""; }; + 7FD2AD7CEF8F673917DF3851 /* FireTopicDetailFeedController+CellApplication.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedController+CellApplication.swift"; sourceTree = ""; }; + 7FD8241E21CB2CEED4AA475D /* FirePostReactionPickerSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostReactionPickerSheet.swift; sourceTree = ""; }; 8092585A18BAFAC8ECAB670D /* FirePostImageNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostImageNode.swift; sourceTree = ""; }; + 80B1341445E9FAD6C16A03B8 /* FireRichTextModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextModels.swift; sourceTree = ""; }; 843289DCC260BF71A9C48DA4 /* FireDiffableListController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDiffableListController.swift; sourceTree = ""; }; 852D9E719DC6FE610CC4F084 /* FireTextureAttributedText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTextureAttributedText.swift; sourceTree = ""; }; 859219285EC36B189AF68256 /* FireTopicListMessageBusRefreshTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListMessageBusRefreshTests.swift; sourceTree = ""; }; 86F1E4CC07C33FB00FADD181 /* FirePrivateMessagesViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePrivateMessagesViewModel.swift; sourceTree = ""; }; - 876B49163E31ED5650900346 /* FireTopicDetailFeedModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailFeedModels.swift; sourceTree = ""; }; 881FCA584D82BEB684F4E2C8 /* FireTopicQuickReplyBarNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicQuickReplyBarNode.swift; sourceTree = ""; }; + 882CE51DF4383DDB04EE2E95 /* FireSceneBackground.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSceneBackground.swift; sourceTree = ""; }; 8834ADE6E3ADB8A03391560C /* FireSessionStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSessionStore.swift; sourceTree = ""; }; + 8886BB4189E814D4795086A2 /* FirePrivateMessagesViewController+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePrivateMessagesViewController+Routing.swift"; sourceTree = ""; }; + 88895CD4883C551BA78B1913 /* FireAppViewModel+SessionApply.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+SessionApply.swift"; sourceTree = ""; }; 8A1B0239607F0ABAEA1ABCE0 /* FirePostLayoutManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostLayoutManager.swift; sourceTree = ""; }; + 8A2D3C167701F62F404BD425 /* FireReadHistoryViewController+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireReadHistoryViewController+Actions.swift"; sourceTree = ""; }; 8A91CF53FF7184DF28FF0E2F /* FireNotificationHistoryViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationHistoryViewController.swift; sourceTree = ""; }; 8B7065BE7533DDF7B2E56700 /* FireNotificationFeedModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationFeedModels.swift; sourceTree = ""; }; - 8BC7B03BAACE572DDB87E810 /* FireTopicDetailModalViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailModalViews.swift; sourceTree = ""; }; + 8BB53040DFA59555E1E3A3D7 /* FireReadHistoryViewController+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireReadHistoryViewController+Routing.swift"; sourceTree = ""; }; + 8C20A920D328CA02A9894274 /* FireTopicDetailModalRouter+PostModals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailModalRouter+PostModals.swift"; sourceTree = ""; }; 8D0D5E6727E0D21855DDEA2F /* FirePaginatedStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePaginatedStore.swift; sourceTree = ""; }; + 8E2246CC0E310D95CC9909B0 /* FireTopicDetailFeedController+DataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedController+DataSource.swift"; sourceTree = ""; }; 8E3DCC9617583661AAF64366 /* FireTopicListMetricEffectCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListMetricEffectCoordinator.swift; sourceTree = ""; }; 91329D323F92B400ADCD40F4 /* FireHomeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeViewController.swift; sourceTree = ""; }; 9189433D7C9260885742A5BA /* FireTopicPresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPresentationTests.swift; sourceTree = ""; }; + 92339F8BFC0B6325CD871533 /* FireRootCoordinator+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireRootCoordinator+Routing.swift"; sourceTree = ""; }; 925CD02F862E958CC79BC60A /* FireTopicDetailSharedModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailSharedModels.swift; sourceTree = ""; }; 9267FBC4BA4FD365E6F4E371 /* FireTopicDetailStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailStore.swift; sourceTree = ""; }; + 928B370E2F406092C99E5F84 /* FireAppViewModel+Authentication.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Authentication.swift"; sourceTree = ""; }; 929153DAB55DC46B3FDFC5ED /* FirePostPollRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostPollRenderer.swift; sourceTree = ""; }; 92C90A87682AF244F048541F /* FireNetworkDiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNetworkDiagnosticsView.swift; sourceTree = ""; }; + 941B6AAD154632DFD156195E /* FireProfileViewController+RowProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireProfileViewController+RowProjection.swift"; sourceTree = ""; }; 949B945E18FF2C7CF0F29CB4 /* FireShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireShortcuts.swift; sourceTree = ""; }; + 94F3F34915F01F1E23F405EC /* FireTopicDetailViewController+Modals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+Modals.swift"; sourceTree = ""; }; + 95EE99D01738B2B77B705BCE /* FireTopicQuickReplyBarView+Appearance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicQuickReplyBarView+Appearance.swift"; sourceTree = ""; }; + 962E25B53FD692FBB3355E30 /* FireTopicVotersSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicVotersSheet.swift; sourceTree = ""; }; 97B0FC401C941BC8F73B959A /* Fire-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Release.xcconfig"; sourceTree = ""; }; 97E8BD69061BE8C9E301D9BA /* FireRootCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRootCoordinator.swift; sourceTree = ""; }; 97FFE2A260FE7B5682493795 /* FireNetworkTraceDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNetworkTraceDetailView.swift; sourceTree = ""; }; 989F3E1E2DDB5711DB78EF19 /* FireBookmarkEditorSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBookmarkEditorSheet.swift; sourceTree = ""; }; 996D95DE48DA65385BD587F7 /* FireApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireApp.swift; sourceTree = ""; }; 99B66C15EE15F4C35AE369C7 /* FireAutoLoginPlanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAutoLoginPlanner.swift; sourceTree = ""; }; + 99ED84E18DBC3745DEF283C3 /* FireSessionStore+Search.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Search.swift"; sourceTree = ""; }; + 99F0AD21E5D4EAE4CBCF21B2 /* FireTopicDetailUiProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailUiProjection.swift; sourceTree = ""; }; 9AAA1343DE9FD6BD637BBE1B /* FireNotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationService.swift; sourceTree = ""; }; 9AF9AD7F01EDCAC3E2FD1797 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 9B970247E0258DD4D4F34101 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 9CF9E9C32EAE5A0B2CABF569 /* FireSessionStore+Profiles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Profiles.swift"; sourceTree = ""; }; 9D354D83C07C326288699E3D /* FireAppearanceEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppearanceEnvironment.swift; sourceTree = ""; }; 9E0BF86E469C2F6F845BBC27 /* FireWidgetEntry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWidgetEntry.swift; sourceTree = ""; }; - 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_user.swift; sourceTree = ""; }; 9F51908C9A24B5866A517797 /* FireMotionEffects.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionEffects.swift; sourceTree = ""; }; 9F9FF30F91F4B85033762AFE /* FireChatChannelViewController+Interactions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireChatChannelViewController+Interactions.swift"; sourceTree = ""; }; + A00A030F05010262BF2FCFEA /* FireTopicDetailHeaderCellNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailHeaderCellNode.swift; sourceTree = ""; }; A0AFFF5DCC989B801C9DF88E /* Fire-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Debug.xcconfig"; sourceTree = ""; }; A0CEED040EC2CAA199126136 /* FireSearchViewController+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSearchViewController+Actions.swift"; sourceTree = ""; }; - A156E14A65C530B5582956CC /* FireRichTextRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextRenderer.swift; sourceTree = ""; }; A1F80BACBD3038A4D91BDCCA /* FireWidget-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "FireWidget-Info.plist"; sourceTree = ""; }; A248DED21DCF11B55E331D29 /* FireOnboardingValidatingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireOnboardingValidatingView.swift; sourceTree = ""; }; + A25446A206207198B6223AD5 /* FireButtonStyles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireButtonStyles.swift; sourceTree = ""; }; + A2555F9775C8B3F9310B17AB /* FirePrivateMessagesViewController+Pagination.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePrivateMessagesViewController+Pagination.swift"; sourceTree = ""; }; A283C548CFC6BEDC0D406679 /* FireTopicDetailVisibilityCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailVisibilityCoordinator.swift; sourceTree = ""; }; + A335F6B742BA0318905EA8C4 /* FirePostCellNode+Boosts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Boosts.swift"; sourceTree = ""; }; + A37BC4D564DAC93057917CB8 /* FireAppViewModel+HomeFeed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+HomeFeed.swift"; sourceTree = ""; }; A5264103A412DF3C9798D470 /* FireAPMModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMModels.swift; sourceTree = ""; }; A536DCA3FA0164DB4F77F6BB /* FirePrivateMessagesControllerHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePrivateMessagesControllerHost.swift; sourceTree = ""; }; + A53F58F41E80C0925A409C08 /* FireBookmarksViewController+Setup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireBookmarksViewController+Setup.swift"; sourceTree = ""; }; + A5AC04986AD864B86FEC5271 /* FireFeedKindSelector.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFeedKindSelector.swift; sourceTree = ""; }; + A5F0757F6B558DD57C79DBC8 /* FirePostCellNode+HitTesting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+HitTesting.swift"; sourceTree = ""; }; A65333719DA71EBA1D39F3F3 /* FireProfileMenuRowCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileMenuRowCell.swift; sourceTree = ""; }; A67A6C835A2196246871D5FD /* FireComposerValidationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerValidationTests.swift; sourceTree = ""; }; - A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_ldc.swift; sourceTree = ""; }; A6B638F65DBB3B2AF6A3AAE0 /* FireChatChannelViewController+Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireChatChannelViewController+Table.swift"; sourceTree = ""; }; A74AEC2739DE5254CD8A23B0 /* FireHomePaginationCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomePaginationCoordinator.swift; sourceTree = ""; }; + A75DAF7497176CDFF260E139 /* FireTopicDetailModalRouter+Composer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailModalRouter+Composer.swift"; sourceTree = ""; }; AA736A1F443337C34A6E33D6 /* Fire.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Fire.entitlements; sourceTree = ""; }; AB1A3A3830E2E1A1917F86C0 /* FireTopicListErrorBannerCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListErrorBannerCell.swift; sourceTree = ""; }; + AB750C99150E0A76CEBC0B5D /* FireOnboardingViewController+Captcha.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+Captcha.swift"; sourceTree = ""; }; ABA36C072D3004B0CFDF73D3 /* FireCloudflareChallengeCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCloudflareChallengeCoordinator.swift; sourceTree = ""; }; + ABA70FA7C4807563BD752313 /* FireHostLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHostLogger.swift; sourceTree = ""; }; + ACA57FDBE9059EEC76EB630B /* FireTopicDetailRuntimeReplyFooterState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRuntimeReplyFooterState.swift; sourceTree = ""; }; AD448CA615C795B53ECF62D0 /* FireComposerViewController+Delegates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireComposerViewController+Delegates.swift"; sourceTree = ""; }; AD777ED45F66FF150D5AD9C0 /* FireBottomInputBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBottomInputBar.swift; sourceTree = ""; }; ADF8658FBC78A5397FF37AB1 /* FireNavigationDestinationCompat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNavigationDestinationCompat.swift; sourceTree = ""; }; AE76404ADCD8CDEBB2B411C8 /* FireQuoteMarkdown.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireQuoteMarkdown.swift; sourceTree = ""; }; + AFADFB09839E6626FF12E186 /* FirePostCellNode+Thread.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Thread.swift"; sourceTree = ""; }; AFECA37BF8132D011E6B5506 /* FireHomeScopePresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeScopePresentationTests.swift; sourceTree = ""; }; + B039AA18094D96411C3C25DB /* FirePostCellNode+LayoutSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+LayoutSpec.swift"; sourceTree = ""; }; B17BF0CB4137B71949AACC0C /* FireSearchStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchStoreTests.swift; sourceTree = ""; }; B220305F1DFD0C508260CFA9 /* FirePostCellLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostCellLayout.swift; sourceTree = ""; }; B25CA09AFB523413280AC469 /* FireTopicListTopicCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListTopicCell.swift; sourceTree = ""; }; + B35863D820EC852D3D2222FE /* FireTopicDetailViewController+Appearance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+Appearance.swift"; sourceTree = ""; }; B3C653495E2307C802BB389A /* FireTopicDetailPageSkeleton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailPageSkeleton.swift; sourceTree = ""; }; B3CB6CE9186DD244BE17CC51 /* FireComposerTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerTextView.swift; sourceTree = ""; }; + B46ECBB694DF90DD1B736885 /* FireTopicDetailViewController+Navigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+Navigation.swift"; sourceTree = ""; }; B4F09B0F010E9C41B77F4B40 /* FireHomeScopePanelController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeScopePanelController.swift; sourceTree = ""; }; B5619EAAFA6C1DCD6B3E1A15 /* FireMediumWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMediumWidget.swift; sourceTree = ""; }; + B59CF230508939157DFEEB67 /* FireOnboardingViewController+Keyboard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+Keyboard.swift"; sourceTree = ""; }; + B5A07BA76E51D7D0BAB7C013 /* FireNotificationHistoryViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationHistoryViewController+Feed.swift"; sourceTree = ""; }; B5E5271F93B7DF18859B101F /* FireWebViewLoginCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWebViewLoginCoordinator.swift; sourceTree = ""; }; B604EC2A613A2E5A96896B03 /* FireComposerViewController+Render.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireComposerViewController+Render.swift"; sourceTree = ""; }; + B621FD0B2E7202C54E9B4B9F /* FireSessionStore+Doh.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Doh.swift"; sourceTree = ""; }; B680C9357B6A7ACD65F6B211 /* FireViewProfileIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireViewProfileIntent.swift; sourceTree = ""; }; B7523D63E40FC490B6E3F1ED /* FireTopicDetailRuntimeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRuntimeTests.swift; sourceTree = ""; }; B75BF7A232BBE489EB6CDABA /* FireTopicDetailFeedCellFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailFeedCellFactory.swift; sourceTree = ""; }; B8C1BF19AD44A73E451313B6 /* FireProfileStatsRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileStatsRow.swift; sourceTree = ""; }; + B9071081BCCEC2A924CEC92C /* FirePanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePanel.swift; sourceTree = ""; }; B9105F91929CE3DCF342AF0E /* FireRecipientTokenField.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRecipientTokenField.swift; sourceTree = ""; }; + B94F01C860C35AEC1BA7AD42 /* FireOnboardingViewController+BottomControls.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+BottomControls.swift"; sourceTree = ""; }; BADC2ED47CF65AD5BE795908 /* FireEntityStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireEntityStateTests.swift; sourceTree = ""; }; BBBF5C645C888133A5CD57DB /* FireHomeViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireHomeViewController+Feed.swift"; sourceTree = ""; }; + BEA0243549927BE6D9047392 /* FireTopicDetailRuntimeInteractions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRuntimeInteractions.swift; sourceTree = ""; }; + BEBF84A7DDE1C18A3E021E2D /* FireSessionStore+MessageBus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+MessageBus.swift"; sourceTree = ""; }; BEC29D6B75CD01B9ADD53F1A /* FireTopicDetailRootNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRootNode.swift; sourceTree = ""; }; BEEAB2E2FBB20FA96A15FD11 /* FireWidgetBundle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWidgetBundle.swift; sourceTree = ""; }; BF328A93631D56CB94E4FA7A /* FireAppRouteDestinationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRouteDestinationView.swift; sourceTree = ""; }; + BF54CB25631FF68748DF2BC2 /* FireAvatarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAvatarView.swift; sourceTree = ""; }; BF5B6841F5556D86C606379F /* FireBadgeDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBadgeDetailView.swift; sourceTree = ""; }; BFB2F0A5B57993299161C5EC /* FireOnboardingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireOnboardingView.swift; sourceTree = ""; }; + BFE7644ABB3B64FDEFBCDC99 /* FireAppViewModel+MessageBus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+MessageBus.swift"; sourceTree = ""; }; C00286677D3818FE5EE2072A /* FireExternalLoginMethod.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireExternalLoginMethod.swift; sourceTree = ""; }; + C0564324D95D8461A44097E7 /* FireTopicDetailBodyStateCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailBodyStateCell.swift; sourceTree = ""; }; C05B0007F349D9B8B718F7F1 /* FireHomeCategoryDrawerController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeCategoryDrawerController.swift; sourceTree = ""; }; C08AC6976AD62C1DAB2DBB2F /* FireSelectableRichTextNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSelectableRichTextNode.swift; sourceTree = ""; }; + C1B8F0D85F4041E579896617 /* FireOnboardingViewController+ExternalAutoLogin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+ExternalAutoLogin.swift"; sourceTree = ""; }; + C1C3EFE270DC9623FA5DC221 /* FireOnboardingViewController+SecondFactor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+SecondFactor.swift"; sourceTree = ""; }; C203C63EB7CB10843B8AB0EC /* FireCookieSelfHealingCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCookieSelfHealingCoordinator.swift; sourceTree = ""; }; C20BDF82CCD1BF22BB3C7729 /* FireAPMMainThreadStallMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMMainThreadStallMonitor.swift; sourceTree = ""; }; C313FFDD8D569FA6D9B1C0E0 /* FireAuthCookieKeychainStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAuthCookieKeychainStore.swift; sourceTree = ""; }; C32FFB215F2C0CDDE5C1221C /* FireTopicOneboxNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicOneboxNode.swift; sourceTree = ""; }; - C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_search.swift; sourceTree = ""; }; + C355C70A7664C459E6631CC2 /* FireOnboardingCredentialFormView+ExternalMethods.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingCredentialFormView+ExternalMethods.swift"; sourceTree = ""; }; C3ECAD5FF1893C381DB94E34 /* FireSettingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSettingsViewController.swift; sourceTree = ""; }; + C4525E775EE0C86542CD3685 /* FireOnboardingViewController+LoginActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+LoginActions.swift"; sourceTree = ""; }; + C6010A6F4219781F54CBD809 /* FireRichTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextView.swift; sourceTree = ""; }; C65C6A52FE7362DF04A8445B /* FireRichTextHeightConsistencyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextHeightConsistencyTests.swift; sourceTree = ""; }; C6DEF53357E681E40E482813 /* FireAPMResourceSampler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMResourceSampler.swift; sourceTree = ""; }; C710FF0F248498E25E02037D /* FirePushDiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePushDiagnosticsView.swift; sourceTree = ""; }; C71352CB3CEB9F98E23B2696 /* FireReadHistoryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireReadHistoryView.swift; sourceTree = ""; }; - C8A36DF217F215CDEB23FDE1 /* FireTopicDetailFeedCells.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailFeedCells.swift; sourceTree = ""; }; + C7DE9DC4AD6A5C9B6626E350 /* FireSessionStore+Observers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Observers.swift"; sourceTree = ""; }; C96F415BE6AC44D202899B9B /* FireBookmarksView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBookmarksView.swift; sourceTree = ""; }; + CA155A018F817CE8F0B7141C /* FirePostCellNode+Polls.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Polls.swift"; sourceTree = ""; }; + CA2C6D3AD63CA17550149E0C /* FireFilteredTopicListViewController+Pagination.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireFilteredTopicListViewController+Pagination.swift"; sourceTree = ""; }; + CA7708CC55F3C5DF4F0557C6 /* FirePrivateMessagesViewController+Setup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePrivateMessagesViewController+Setup.swift"; sourceTree = ""; }; CAC35CFD6CB96DD7FF21C14A /* FireTopicDetailStore+Mutations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailStore+Mutations.swift"; sourceTree = ""; }; + CC14DDA188D0FD289D2000C3 /* FireOnboardingErrorBannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireOnboardingErrorBannerView.swift; sourceTree = ""; }; CC6AF43B5DBBA0811F63F137 /* FireTopicDetailPageSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailPageSnapshot.swift; sourceTree = ""; }; + CCAB50E1A2CDADEB2A43A1B4 /* FirePrivateMessagesViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePrivateMessagesViewController+Feed.swift"; sourceTree = ""; }; + CD5E566582BFC7E23506727B /* FireAppViewModel+LoginSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+LoginSupport.swift"; sourceTree = ""; }; + CDD9ACD8100B4412387AF29F /* FireTopicQuickReplyBarView+Callbacks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicQuickReplyBarView+Callbacks.swift"; sourceTree = ""; }; CF62545366AA7AEF22A80748 /* FireChatChannelViewController+Bus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireChatChannelViewController+Bus.swift"; sourceTree = ""; }; + CFC129B0275F2EFA770163F5 /* FireTopicReplyPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicReplyPresentation.swift; sourceTree = ""; }; D042B49EA2CBAB217A5011AF /* FireAppViewModel+Chat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Chat.swift"; sourceTree = ""; }; D063576FA04A84CFE3BDB703 /* FireTopicSearchBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicSearchBar.swift; sourceTree = ""; }; D0AFC69C6A22193CA4DFDB81 /* FireComposerRoute.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerRoute.swift; sourceTree = ""; }; + D1A1CCCEC0341697385E81E7 /* FireTopicTimelineModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicTimelineModels.swift; sourceTree = ""; }; D23F3B2881A5E7C08D90A767 /* FirePublicProfileViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePublicProfileViewController.swift; sourceTree = ""; }; D34B1A27E213EE85137546A2 /* FireComposerViewController+Editor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireComposerViewController+Editor.swift"; sourceTree = ""; }; + D384F4A919803D9BFF1F296F /* FireTopicImageViewer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicImageViewer.swift; sourceTree = ""; }; + D3E28D0395CEAFF65092C1F3 /* FireTopicDetailViewController+TopicVoting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+TopicVoting.swift"; sourceTree = ""; }; D411B9ABE5C61805B92A2DD2 /* FireTopicImagePipeline.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicImagePipeline.swift; sourceTree = ""; }; + D4ECEB229DCBFAF26411C7B0 /* FireTopicDetailRuntimeItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRuntimeItem.swift; sourceTree = ""; }; D51F8B61796434E964104F72 /* FirePostLayoutManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostLayoutManagerTests.swift; sourceTree = ""; }; + D5241911D519DBEC442296F3 /* FireSessionStore+Composer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Composer.swift"; sourceTree = ""; }; + D599BADEB91A482BE7179BB2 /* FireTopicDetailViewController+StateProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+StateProjection.swift"; sourceTree = ""; }; D5C18328DFF8C1C3145C2DAC /* FireFollowListViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFollowListViewController.swift; sourceTree = ""; }; + D7B95F21A4FA49C929C36B12 /* FireTopicDetailFeedCellFactory+Stats.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedCellFactory+Stats.swift"; sourceTree = ""; }; + D7ECF142687E73687732AEA8 /* FireNotificationsViewController+Setup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationsViewController+Setup.swift"; sourceTree = ""; }; + D8B454F22E943FD24E12D526 /* FireOnboardingViewController+PasswordAutoLogin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingViewController+PasswordAutoLogin.swift"; sourceTree = ""; }; + D9AB8FAB900656D84CA6D7A6 /* FireAppViewModel+Recovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Recovery.swift"; sourceTree = ""; }; + D9BEB483B26DDDB72FDAF428 /* FireTopicDetailAISummaryCellNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailAISummaryCellNode.swift; sourceTree = ""; }; + DAD7D1368C3668D205CA1FD8 /* FireToast.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireToast.swift; sourceTree = ""; }; DB73A3AE7A4D6E47C61CAE52 /* FireTopicDetailToolbarCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailToolbarCoordinator.swift; sourceTree = ""; }; + DB9ADE00D1D81B7303F5F355 /* FireOnboardingCredentialFormView+Keyboard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireOnboardingCredentialFormView+Keyboard.swift"; sourceTree = ""; }; DBBEC3D8CF3903B3357395DC /* FireRichTextParagraphBoundaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextParagraphBoundaryTests.swift; sourceTree = ""; }; DC1862EFE9736F5E1E6C9B5D /* FireSearchHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchHeaderView.swift; sourceTree = ""; }; DC59D88F80673C24044D7013 /* FireComposerViewController+Draft.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireComposerViewController+Draft.swift"; sourceTree = ""; }; + DCFD5D1037C96C405E403F8D /* FireDraftsViewController+ComposerRouting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireDraftsViewController+ComposerRouting.swift"; sourceTree = ""; }; DD366FFC34E7ECB9EAF8B08C /* FireComposerViewController+Mentions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireComposerViewController+Mentions.swift"; sourceTree = ""; }; DDC30347DC7392AAA6A27435 /* FireTopicDetailControllerHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailControllerHost.swift; sourceTree = ""; }; - DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_topics.swift; sourceTree = ""; }; + DF90E2C1233BB91915E3F138 /* FireTopicDetailFeedController+Appearance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedController+Appearance.swift"; sourceTree = ""; }; DFBA718C5E89D3669A9C6D22 /* FireTopicDetailStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailStoreTests.swift; sourceTree = ""; }; E083189F2BF692A04EB7CF23 /* FireAppServiceHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppServiceHost.swift; sourceTree = ""; }; E08837275F0C3B294CFAB57D /* FireSearchCells.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchCells.swift; sourceTree = ""; }; E08C81F61BB648C072F7BA9E /* FireTopicListStateCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListStateCell.swift; sourceTree = ""; }; + E0A537AD2D1ACD3003637D63 /* FireBookmarksViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireBookmarksViewController+Feed.swift"; sourceTree = ""; }; E0AA3F1257384BF109634D21 /* FireTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTheme.swift; sourceTree = ""; }; + E1CB184C209DCD4DB04D3B50 /* FireTopicDetailViewController+SnapshotApplication.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+SnapshotApplication.swift"; sourceTree = ""; }; E355FDE3F6E9A5FFB6229374 /* FireHomeScopePresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeScopePresentation.swift; sourceTree = ""; }; E379AA9200DC2BD19BEC807F /* FireListPaginationAndUpdateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireListPaginationAndUpdateTests.swift; sourceTree = ""; }; E3824000FAC99E70EA95DD86 /* FireDraftsControllerHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDraftsControllerHost.swift; sourceTree = ""; }; - E436AB70851CCBCFCD8B8D96 /* FireTopicDetailInteractionCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailInteractionCoordinator.swift; sourceTree = ""; }; + E3C9788FF37F1ED5F1DBB1A8 /* FireSessionStore+Diagnostics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Diagnostics.swift"; sourceTree = ""; }; E4616E00DD2F43C18973E520 /* FireUIKitErrorBannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitErrorBannerView.swift; sourceTree = ""; }; E4AF197F76705D49E465A05B /* FireDohSourceViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDohSourceViewController.swift; sourceTree = ""; }; - E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_messagebus.swift; sourceTree = ""; }; E5FFB93F34563ABE34B99183 /* FireUIKitDesignLanguage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitDesignLanguage.swift; sourceTree = ""; }; E650ABD9C06621BC41908D59 /* FireContextMenus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireContextMenus.swift; sourceTree = ""; }; E66E1B11B9D76557B4BB0603 /* FireTopicListMessageBusRefresh.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListMessageBusRefresh.swift; sourceTree = ""; }; @@ -638,6 +996,9 @@ E6E39E0383771E1B2AC6F4DB /* FireProfileActivityTableCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileActivityTableCell.swift; sourceTree = ""; }; E7299AEA008EC0AE578A1712 /* FireMidSessionReauthOverlayController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMidSessionReauthOverlayController.swift; sourceTree = ""; }; E771E5E48D78AAC476C3A58D /* FireProfileViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileViewController.swift; sourceTree = ""; }; + E7A4E63528064FF56B534955 /* FirePostRepliesSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostRepliesSheet.swift; sourceTree = ""; }; + E7E1E77D84D9FD468BB724B7 /* FireReadHistoryViewController+Setup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireReadHistoryViewController+Setup.swift"; sourceTree = ""; }; + E8CAA39E03B78508E1034EBF /* FirePostCellNode+Author.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Author.swift"; sourceTree = ""; }; E8D1B62331E78430BE857CDC /* FireDraftListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDraftListCell.swift; sourceTree = ""; }; E8E5B1ECAE617609F235B6A3 /* FireDraftsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDraftsViewController.swift; sourceTree = ""; }; E8EF10938994EC780C68B9D4 /* FireUIKitAppearanceCapsuleControlTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitAppearanceCapsuleControlTests.swift; sourceTree = ""; }; @@ -646,34 +1007,62 @@ EA23C0E50E7A412A73AF80E6 /* FireMotionReduceMotion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionReduceMotion.swift; sourceTree = ""; }; EA2BF3D92E750EF89E6387BF /* FireMotionTokens.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionTokens.swift; sourceTree = ""; }; EAE00F2C2E4EB9A7A99D327A /* FireRouteParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRouteParser.swift; sourceTree = ""; }; + EAE0A825545FD5A253328A8C /* FireNotificationsViewController+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationsViewController+Routing.swift"; sourceTree = ""; }; + EC47D1BE0D7F65889A8A17A1 /* FireTopicReactionPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicReactionPresentation.swift; sourceTree = ""; }; EC5FF075F001E43924A7D188 /* FireBackgroundNotificationAlert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBackgroundNotificationAlert.swift; sourceTree = ""; }; EC7384EAE1C43817CAE71D9F /* FireHomeFeedStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeFeedStore.swift; sourceTree = ""; }; ECBDE8779B6F7E32204263F4 /* FireTopicPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPresentation.swift; sourceTree = ""; }; ED6324DE2E06F3F22A7128E4 /* FireHomeViewController+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireHomeViewController+Actions.swift"; sourceTree = ""; }; + ED89C80C5CB679C032ACFEB4 /* FireAppViewModel+Binding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Binding.swift"; sourceTree = ""; }; + EDDE0CA8CFB2A3F8F90194D5 /* FireTopicDetailViewController+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailViewController+Routing.swift"; sourceTree = ""; }; EDE93F98F58126B7BEDDB4F7 /* FireTopicTimingTrackerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicTimingTrackerTests.swift; sourceTree = ""; }; + EF38A4FC58E0D45139F5AACF /* FireNotificationHistoryViewController+Routing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireNotificationHistoryViewController+Routing.swift"; sourceTree = ""; }; EF66373F7EF72A887F722CF0 /* FireMotionUIKit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionUIKit.swift; sourceTree = ""; }; - EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi.swift; sourceTree = ""; }; EFE429D39ACE68653A226FE9 /* FireProfileActivityTimelineView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileActivityTimelineView.swift; sourceTree = ""; }; F01E5248AEF9002E2919AC0F /* FireCfClearanceRefreshService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCfClearanceRefreshService.swift; sourceTree = ""; }; F112BF5A6A226C1D21861F90 /* FireOnboardingCredentialFormView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireOnboardingCredentialFormView.swift; sourceTree = ""; }; F45FD2D6B300FDC58C2FD04A /* FireUIKitSkeleton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitSkeleton.swift; sourceTree = ""; }; + F4C08B418B91DCB198040E33 /* FireReadHistoryViewController+Feed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireReadHistoryViewController+Feed.swift"; sourceTree = ""; }; F54F88AB1D407D9E4D5866B9 /* FireComposerValidation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerValidation.swift; sourceTree = ""; }; F68DA8724D28D640697E8436 /* FireTopicListToastView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListToastView.swift; sourceTree = ""; }; F74563DD6B9E870850553DDA /* FireAppViewModel+Profile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Profile.swift"; sourceTree = ""; }; F7C061876458A31F793EE975 /* FireWebViewBrowserViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWebViewBrowserViewController.swift; sourceTree = ""; }; + F7E46DB675DCF9A0285F0C2B /* FireTopicDetailFlagSheetHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailFlagSheetHost.swift; sourceTree = ""; }; F7F4881067D974AA645C77FC /* FireWidgetExtension.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = FireWidgetExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; F8928D817CE60A917A5BA0C9 /* FireTopicDetailArticleSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailArticleSnapshot.swift; sourceTree = ""; }; F90878A611124AD41C0288B7 /* FireTopicDetailModalRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailModalRouter.swift; sourceTree = ""; }; F9384B4FECD3434E8DCCB3BA /* FireFilteredTopicListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFilteredTopicListView.swift; sourceTree = ""; }; + F9AC6D8E0A9B700CF2FC9BC5 /* FireAppViewModel+Composer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Composer.swift"; sourceTree = ""; }; + FA0E260E7D126FE6A00AFF62 /* FireProfileViewController+Binding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireProfileViewController+Binding.swift"; sourceTree = ""; }; FA4EC81D9B54122E7A2497B5 /* FireComposerEditorModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerEditorModels.swift; sourceTree = ""; }; FA8E7753E3E1BB8E3CD88E96 /* Fire-Shared.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Shared.xcconfig"; sourceTree = ""; }; + FAE3BC1D85ECB2D04689F7BC /* FireSessionStore+Notifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireSessionStore+Notifications.swift"; sourceTree = ""; }; FB21BB9232240035114A9653 /* FireProfileBadgeChip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileBadgeChip.swift; sourceTree = ""; }; + FC289AE43D9253D1617154D9 /* FirePrivateMessagesViewController+Participants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePrivateMessagesViewController+Participants.swift"; sourceTree = ""; }; + FC375636258776A9578CE154 /* FireAppViewModel+APM.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+APM.swift"; sourceTree = ""; }; FD5A94769988E39B8BEA7B56 /* libiconv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libiconv.tbd; path = usr/lib/libiconv.tbd; sourceTree = SDKROOT; }; + FD5D4AB46FC0CF047C1C614B /* FireTopicDetailPostRepliesHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailPostRepliesHost.swift; sourceTree = ""; }; + FD91CB19207D14CD1A99BBCE /* FireTopicDetailFeedController+Scrolling.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailFeedController+Scrolling.swift"; sourceTree = ""; }; + FD9A9C9C69DB5687EF255186 /* FireTopicDetailRuntimeConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailRuntimeConfiguration.swift; sourceTree = ""; }; + FE6A22C3F511DB107633C1FA /* FireHomeFeedSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeFeedSession.swift; sourceTree = ""; }; FF475D56C78AFC82413AED55 /* FireAccountStatusView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAccountStatusView.swift; sourceTree = ""; }; - FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_notifications.swift; sourceTree = ""; }; FFB6B1F10783D1D78B2D1F63 /* FireListSectionModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireListSectionModel.swift; sourceTree = ""; }; + FFC8987AC1C508F9F95745CB /* FireMetadataComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMetadataComponents.swift; sourceTree = ""; }; + FFF4501C580EB91388A97D24 /* FireTopicDetailStatsCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailStatsCell.swift; sourceTree = ""; }; /* End PBXFileReference section */ +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 6CB14B164BD5987BA7B8C516 /* Generated/FireUniFfi */ = { + isa = PBXFileSystemSynchronizedRootGroup; + explicitFileTypes = { + }; + explicitFolders = ( + ); + path = Generated/FireUniFfi; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + /* Begin PBXFrameworksBuildPhase section */ 1E5D1534135BDBC408E23F3B /* Frameworks */ = { isa = PBXFrameworksBuildPhase; @@ -704,6 +1093,11 @@ 989F3E1E2DDB5711DB78EF19 /* FireBookmarkEditorSheet.swift */, C96F415BE6AC44D202899B9B /* FireBookmarksView.swift */, 2F329C317F6932DC1D07AD03 /* FireBookmarksViewController.swift */, + 3CEB32A62402439B885D1FE8 /* FireBookmarksViewController+Actions.swift */, + E0A537AD2D1ACD3003637D63 /* FireBookmarksViewController+Feed.swift */, + 54C93686EAAB54DE7694FFF1 /* FireBookmarksViewController+Pagination.swift */, + 2AC8045F6F7424FF87C85E8F /* FireBookmarksViewController+Routing.swift */, + A53F58F41E80C0925A409C08 /* FireBookmarksViewController+Setup.swift */, ); path = Bookmarks; sourceTree = ""; @@ -736,6 +1130,7 @@ 121455DBB05756FD09B727EA /* Controller */ = { isa = PBXGroup; children = ( + 52DE4607A98D640E433550FA /* FireChatChannelSession.swift */, 0D7AF4BC29896B1DF99A4A69 /* FireChatChannelViewController.swift */, CF62545366AA7AEF22A80748 /* FireChatChannelViewController+Bus.swift */, 9F9FF30F91F4B85033762AFE /* FireChatChannelViewController+Interactions.swift */, @@ -758,6 +1153,9 @@ children = ( BEC29D6B75CD01B9ADD53F1A /* FireTopicDetailRootNode.swift */, 881FCA584D82BEB684F4E2C8 /* FireTopicQuickReplyBarNode.swift */, + 95EE99D01738B2B77B705BCE /* FireTopicQuickReplyBarView+Appearance.swift */, + CDD9ACD8100B4412387AF29F /* FireTopicQuickReplyBarView+Callbacks.swift */, + 71B48CBCBA543CBD531D27AE /* FireTopicQuickReplyBarView+Layout.swift */, ); path = Nodes; sourceTree = ""; @@ -809,12 +1207,34 @@ 2CF8A481ECB4FF480F527B2C /* Controller */ = { isa = PBXGroup; children = ( - E436AB70851CCBCFCD8B8D96 /* FireTopicDetailInteractionCoordinator.swift */, + F7E46DB675DCF9A0285F0C2B /* FireTopicDetailFlagSheetHost.swift */, F90878A611124AD41C0288B7 /* FireTopicDetailModalRouter.swift */, + 3887899D62CC6BED4D8F686C /* FireTopicDetailModalRouter+Alerts.swift */, + A75DAF7497176CDFF260E139 /* FireTopicDetailModalRouter+Composer.swift */, + 7F8D2A6776D4D192A6051BD4 /* FireTopicDetailModalRouter+Navigation.swift */, + 8C20A920D328CA02A9894274 /* FireTopicDetailModalRouter+PostModals.swift */, + FD5D4AB46FC0CF047C1C614B /* FireTopicDetailPostRepliesHost.swift */, 56971CD699F6CE264E0EB563 /* FireTopicDetailSearchCoordinator.swift */, + 1A957E674F7B62BDD52A2848 /* FireTopicDetailToolbarActionsView.swift */, DB73A3AE7A4D6E47C61CAE52 /* FireTopicDetailToolbarCoordinator.swift */, + 41B071F383E0E0129E68BD8A /* FireTopicDetailToolbarMetrics.swift */, + 17D7B773A9AD783F4497A63E /* FireTopicDetailToolbarTitleView.swift */, 457CCC7AE29267A8B9448BA7 /* FireTopicDetailViewController.swift */, + B35863D820EC852D3D2222FE /* FireTopicDetailViewController+Appearance.swift */, + 1D724BCFA0E3C41156FAF7A3 /* FireTopicDetailViewController+Keyboard.swift */, + 24D2D61CC4D8148BE8831F17 /* FireTopicDetailViewController+Lifecycle.swift */, + 94F3F34915F01F1E23F405EC /* FireTopicDetailViewController+Modals.swift */, + B46ECBB694DF90DD1B736885 /* FireTopicDetailViewController+Navigation.swift */, + 054BAB7AF7338BAB2ED6782C /* FireTopicDetailViewController+PollVoting.swift */, + 0789B19C92B2B04D685F52AE /* FireTopicDetailViewController+PostManagement.swift */, + 15C52722D4C57B1E8C3D6258 /* FireTopicDetailViewController+QuickReply.swift */, + 6E3BCBF5C07A882EFEF21D2E /* FireTopicDetailViewController+Reactions.swift */, + EDDE0CA8CFB2A3F8F90194D5 /* FireTopicDetailViewController+Routing.swift */, + E1CB184C209DCD4DB04D3B50 /* FireTopicDetailViewController+SnapshotApplication.swift */, + D599BADEB91A482BE7179BB2 /* FireTopicDetailViewController+StateProjection.swift */, + D3E28D0395CEAFF65092C1F3 /* FireTopicDetailViewController+TopicVoting.swift */, D063576FA04A84CFE3BDB703 /* FireTopicSearchBar.swift */, + 3AFA3082D577488D13F57EE2 /* FireTopicUserInfoSheet.swift */, ); path = Controller; sourceTree = ""; @@ -825,9 +1245,27 @@ 462EB3CAB0AACF4846EA3AC5 /* FireCaptchaLoginDialogController.swift */, 4B79252C493DBB0CE379F302 /* FireCategoriesView.swift */, 04449F91CF3EEB51F58E633B /* FireInviteLinksView.swift */, + CC14DDA188D0FD289D2000C3 /* FireOnboardingErrorBannerView.swift */, BFB2F0A5B57993299161C5EC /* FireOnboardingView.swift */, + 27E052E3B23A20262188A220 /* FireOnboardingViewController+AuthLog.swift */, + B94F01C860C35AEC1BA7AD42 /* FireOnboardingViewController+BottomControls.swift */, + 30B07CEE7C89CA1C63884E37 /* FireOnboardingViewController+Brand.swift */, + AB750C99150E0A76CEBC0B5D /* FireOnboardingViewController+Captcha.swift */, + 678964D1FD04557CF8F6C44E /* FireOnboardingViewController+CloudflareRecovery.swift */, + C1B8F0D85F4041E579896617 /* FireOnboardingViewController+ExternalAutoLogin.swift */, + B59CF230508939157DFEEB67 /* FireOnboardingViewController+Keyboard.swift */, + C4525E775EE0C86542CD3685 /* FireOnboardingViewController+LoginActions.swift */, + D8B454F22E943FD24E12D526 /* FireOnboardingViewController+PasswordAutoLogin.swift */, + 03D05BEAFD5E582B878E18EF /* FireOnboardingViewController+PhaseRendering.swift */, + C1C3EFE270DC9623FA5DC221 /* FireOnboardingViewController+SecondFactor.swift */, + 670A641D02B78D7C613EEDBC /* FireOnboardingViewController+StartupRouting.swift */, C71352CB3CEB9F98E23B2696 /* FireReadHistoryView.swift */, 2C8AEE7516614D73C079F860 /* FireReadHistoryViewController.swift */, + 8A2D3C167701F62F404BD425 /* FireReadHistoryViewController+Actions.swift */, + F4C08B418B91DCB198040E33 /* FireReadHistoryViewController+Feed.swift */, + 61CE18B274AC0837CDC5CA15 /* FireReadHistoryViewController+Pagination.swift */, + 8BB53040DFA59555E1E3A3D7 /* FireReadHistoryViewController+Routing.swift */, + E7E1E77D84D9FD468BB724B7 /* FireReadHistoryViewController+Setup.swift */, 2C2060FDF4576F412DA20A94 /* FireTabRoot.swift */, F7C061876458A31F793EE975 /* FireWebViewBrowserViewController.swift */, ); @@ -838,10 +1276,31 @@ isa = PBXGroup; children = ( C313FFDD8D569FA6D9B1C0E0 /* FireAuthCookieKeychainStore.swift */, + 2CA0AC514C9C8CDBCF7F7606 /* FireCapturedLoginState.swift */, F01E5248AEF9002E2919AC0F /* FireCfClearanceRefreshService.swift */, ABA36C072D3004B0CFDF73D3 /* FireCloudflareChallengeCoordinator.swift */, C203C63EB7CB10843B8AB0EC /* FireCookieSelfHealingCoordinator.swift */, + ABA70FA7C4807563BD752313 /* FireHostLogger.swift */, 8834ADE6E3ADB8A03391560C /* FireSessionStore.swift */, + 4DB484B4F02ECBEE1DEF9A7A /* FireSessionStore+Authentication.swift */, + 395803401D7AD61E67521D16 /* FireSessionStore+Bootstrap.swift */, + 52553DB0231CE03479BB0F6D /* FireSessionStore+Chat.swift */, + D5241911D519DBEC442296F3 /* FireSessionStore+Composer.swift */, + 020E46ADD920CD8409FE14E9 /* FireSessionStore+Cookies.swift */, + E3C9788FF37F1ED5F1DBB1A8 /* FireSessionStore+Diagnostics.swift */, + B621FD0B2E7202C54E9B4B9F /* FireSessionStore+Doh.swift */, + 190AEA75EC6B05E5FFA7796E /* FireSessionStore+HomeScope.swift */, + 4FD26A8FCD98C1473EF11ABC /* FireSessionStore+Interactions.swift */, + 1815693E5384964FEFF564D9 /* FireSessionStore+Ldc.swift */, + 73539D771AAD2B50965F5D4A /* FireSessionStore+Lifecycle.swift */, + BEBF84A7DDE1C18A3E021E2D /* FireSessionStore+MessageBus.swift */, + FAE3BC1D85ECB2D04689F7BC /* FireSessionStore+Notifications.swift */, + C7DE9DC4AD6A5C9B6626E350 /* FireSessionStore+Observers.swift */, + 9CF9E9C32EAE5A0B2CABF569 /* FireSessionStore+Profiles.swift */, + 99ED84E18DBC3745DEF283C3 /* FireSessionStore+Search.swift */, + 043D502E77F441A2F52911A0 /* FireSessionStore+Topics.swift */, + 6DF5C51601950F6B6B2E84AD /* FireSessionStore+WritePreflight.swift */, + 0F853E29620466DE5501395D /* FireSessionStoreError.swift */, E6A1ACC49B5E391857645187 /* FireWebViewBrowserProfile.swift */, B5E5271F93B7DF18859B101F /* FireWebViewLoginCoordinator.swift */, 410518D5B5DA1358F677892E /* APM */, @@ -944,6 +1403,7 @@ FA4EC81D9B54122E7A2497B5 /* FireComposerEditorModels.swift */, E933C082E54A360ADEADA579 /* FireComposerInitialBody.swift */, D0AFC69C6A22193CA4DFDB81 /* FireComposerRoute.swift */, + 653F86A9F2FFC5E020ABC640 /* FireComposerSession.swift */, F54F88AB1D407D9E4D5866B9 /* FireComposerValidation.swift */, ); path = State; @@ -1012,6 +1472,12 @@ 3E406BC86F476DB0FF2E688F /* FireHeadlessExternalLoginEngine.swift */, E7299AEA008EC0AE578A1712 /* FireMidSessionReauthOverlayController.swift */, F112BF5A6A226C1D21861F90 /* FireOnboardingCredentialFormView.swift */, + C355C70A7664C459E6631CC2 /* FireOnboardingCredentialFormView+ExternalMethods.swift */, + 53B37883C9DB898936D74AAF /* FireOnboardingCredentialFormView+Fields.swift */, + DB9ADE00D1D81B7303F5F355 /* FireOnboardingCredentialFormView+Keyboard.swift */, + 1A7D88710A4E967AB393E736 /* FireOnboardingCredentialFormView+LastLoginHint.swift */, + 473E5CD558B2D86650E606F2 /* FireOnboardingCredentialFormView+LoginButton.swift */, + 2B596C5C2E8BEF5EB24A7A07 /* FireOnboardingCredentialFormView+Options.swift */, A248DED21DCF11B55E331D29 /* FireOnboardingValidatingView.swift */, ); path = Startup; @@ -1081,6 +1547,10 @@ B8C1BF19AD44A73E451313B6 /* FireProfileStatsRow.swift */, 2A3BEB6E72878BC3AD27B487 /* FireProfileTrustLevelPill.swift */, E771E5E48D78AAC476C3A58D /* FireProfileViewController.swift */, + FA0E260E7D126FE6A00AFF62 /* FireProfileViewController+Binding.swift */, + 08A7A8FB9455E94256F352A3 /* FireProfileViewController+Routing.swift */, + 941B6AAD154632DFD156195E /* FireProfileViewController+RowProjection.swift */, + 2AB87D75E0B7FBF2E8D7F232 /* FireProfileViewController+Table.swift */, D23F3B2881A5E7C08D90A767 /* FirePublicProfileViewController.swift */, C3ECAD5FF1893C381DB94E34 /* FireSettingsViewController.swift */, 6B8FD2EBF4867A3E5C5A1EF9 /* FireUserCardViewController.swift */, @@ -1095,6 +1565,12 @@ 2850469E1F9F91DD6FA787AE /* FirePrivateMessageCells.swift */, A536DCA3FA0164DB4F77F6BB /* FirePrivateMessagesControllerHost.swift */, 6A765149EB821BBD6B81CCE8 /* FirePrivateMessagesViewController.swift */, + 0AC83F1B4B6C002A60FEEB52 /* FirePrivateMessagesViewController+Composer.swift */, + CCAB50E1A2CDADEB2A43A1B4 /* FirePrivateMessagesViewController+Feed.swift */, + A2555F9775C8B3F9310B17AB /* FirePrivateMessagesViewController+Pagination.swift */, + FC289AE43D9253D1617154D9 /* FirePrivateMessagesViewController+Participants.swift */, + 8886BB4189E814D4795086A2 /* FirePrivateMessagesViewController+Routing.swift */, + CA7708CC55F3C5DF4F0557C6 /* FirePrivateMessagesViewController+Setup.swift */, 86F1E4CC07C33FB00FADD181 /* FirePrivateMessagesViewModel.swift */, B9105F91929CE3DCF342AF0E /* FireRecipientTokenField.swift */, ); @@ -1115,7 +1591,15 @@ children = ( AD777ED45F66FF150D5AD9C0 /* FireBottomInputBar.swift */, 1EDE93D07235A87438E6E563 /* FireRenderPresentation.swift */, - A156E14A65C530B5582956CC /* FireRichTextRenderer.swift */, + 58E2588F8B8817932933EB55 /* FireRichTextAttributedStringBuilder.swift */, + 2604E07D8A130094F4A756B1 /* FireRichTextAttributedStringBuilder+Inline.swift */, + 24C97053064713B8ADD07FE6 /* FireRichTextAttributedStringBuilder+Lists.swift */, + 7B1DFFFE930AD6B28E469534 /* FireRichTextAttributedStringBuilder+Onebox.swift */, + 550B08C28394AE3DDDC313C8 /* FireRichTextAttributedStringBuilder+Quotes.swift */, + 0882BBB4BE9599B64DE66089 /* FireRichTextEmojiAttachment.swift */, + 80B1341445E9FAD6C16A03B8 /* FireRichTextModels.swift */, + 49DFB8ED64CAE57ADDFABFD6 /* FireRichTextTextView.swift */, + C6010A6F4219781F54CBD809 /* FireRichTextView.swift */, ); path = Shared; sourceTree = ""; @@ -1175,7 +1659,17 @@ isa = PBXGroup; children = ( 8A91CF53FF7184DF28FF0E2F /* FireNotificationHistoryViewController.swift */, + 0DC8951F1970697D3FBEB8DF /* FireNotificationHistoryViewController+Actions.swift */, + B5A07BA76E51D7D0BAB7C013 /* FireNotificationHistoryViewController+Feed.swift */, + 3D9266ECC882A7206C1A2930 /* FireNotificationHistoryViewController+Pagination.swift */, + EF38A4FC58E0D45139F5AACF /* FireNotificationHistoryViewController+Routing.swift */, + 7BECDE1E729786B3091B3DE7 /* FireNotificationHistoryViewController+Setup.swift */, 1D9F899C209796ED8C0F6E51 /* FireNotificationsViewController.swift */, + 73FE111B5A807744619586B8 /* FireNotificationsViewController+Actions.swift */, + 45DB137F375693921473FF5E /* FireNotificationsViewController+Feed.swift */, + 70CE6114D9AF123B76BCE75E /* FireNotificationsViewController+Pagination.swift */, + EAE0A825545FD5A253328A8C /* FireNotificationsViewController+Routing.swift */, + D7ECF142687E73687732AEA8 /* FireNotificationsViewController+Setup.swift */, E85C14BF38069A5B98F8CD5E /* Feed */, ); path = Notifications; @@ -1184,13 +1678,35 @@ 9104AB2B5E8F79AB50DBDAA1 /* Feed */ = { isa = PBXGroup; children = ( + D9BEB483B26DDDB72FDAF428 /* FireTopicDetailAISummaryCellNode.swift */, + C0564324D95D8461A44097E7 /* FireTopicDetailBodyStateCell.swift */, + 07931FDEC1838345E81FAD49 /* FireTopicDetailCellTheme.swift */, B75BF7A232BBE489EB6CDABA /* FireTopicDetailFeedCellFactory.swift */, - C8A36DF217F215CDEB23FDE1 /* FireTopicDetailFeedCells.swift */, + 70F2622FC71DFA7C3DCC8749 /* FireTopicDetailFeedCellFactory+BodyState.swift */, + 5619A74A64AFA6F08BB4AB25 /* FireTopicDetailFeedCellFactory+Replies.swift */, + D7B95F21A4FA49C929C36B12 /* FireTopicDetailFeedCellFactory+Stats.swift */, + 6047D5712F521F24592A4CF3 /* FireTopicDetailFeedCellFactory+Voting.swift */, 5267F5B3B48F8FCBF2B891BD /* FireTopicDetailFeedController.swift */, - 876B49163E31ED5650900346 /* FireTopicDetailFeedModels.swift */, + DF90E2C1233BB91915E3F138 /* FireTopicDetailFeedController+Appearance.swift */, + 7FD2AD7CEF8F673917DF3851 /* FireTopicDetailFeedController+CellApplication.swift */, + 226224E8D45EAD0D7B642A5F /* FireTopicDetailFeedController+CollectionUpdates.swift */, + 8E2246CC0E310D95CC9909B0 /* FireTopicDetailFeedController+DataSource.swift */, + 761B77070B1B1BF8B0438494 /* FireTopicDetailFeedController+Layout.swift */, + FD91CB19207D14CD1A99BBCE /* FireTopicDetailFeedController+Scrolling.swift */, 3C21247110244DC0C9E0BEDA /* FireTopicDetailFeedUpdatePipeline.swift */, + A00A030F05010262BF2FCFEA /* FireTopicDetailHeaderCellNode.swift */, 2FCFF26F4042B80F6B91305E /* FireTopicDetailPaginationCoordinator.swift */, + 54FC00148F17D9F9CE877CBA /* FireTopicDetailRepliesHeaderCell.swift */, + 377285D279E45E4211DC2CEA /* FireTopicDetailReplyFooterCell.swift */, + FD9A9C9C69DB5687EF255186 /* FireTopicDetailRuntimeConfiguration.swift */, + BEA0243549927BE6D9047392 /* FireTopicDetailRuntimeInteractions.swift */, + D4ECEB229DCBFAF26411C7B0 /* FireTopicDetailRuntimeItem.swift */, + ACA57FDBE9059EEC76EB630B /* FireTopicDetailRuntimeReplyFooterState.swift */, + 613A01B5246B131A5CD3A99E /* FireTopicDetailRuntimeSnapshot.swift */, 5592C6396CAD3B7F3672D0EA /* FireTopicDetailRuntimeSnapshotBuilder.swift */, + FFF4501C580EB91388A97D24 /* FireTopicDetailStatsCell.swift */, + 3CA68AD35F9427999927D825 /* FireTopicDetailTextCell.swift */, + 472C217534E3F1AF6720933D /* FireTopicDetailTopicVoteCell.swift */, A283C548CFC6BEDC0D406679 /* FireTopicDetailVisibilityCoordinator.swift */, ); path = Feed; @@ -1206,8 +1722,19 @@ 24E7CCCA8B867D5E6B0CE198 /* FirePostCellLayoutCalculator.swift */, 093EEF1E0EBDB24ED7106CDD /* FirePostCellNode.swift */, 099F0B014FDD2B7431DFC56F /* FirePostCellNode+Actions.swift */, + 24AC0E82D4FD3B75E1DEF2A3 /* FirePostCellNode+Appearance.swift */, + E8CAA39E03B78508E1034EBF /* FirePostCellNode+Author.swift */, 0D70983A36756650D4B734B7 /* FirePostCellNode+Body.swift */, + A335F6B742BA0318905EA8C4 /* FirePostCellNode+Boosts.swift */, + 09F2FA662430C8D8F81AF72A /* FirePostCellNode+Configuration.swift */, + 55A00A8DFE3727573935D235 /* FirePostCellNode+ContextMenu.swift */, + A5F0757F6B558DD57C79DBC8 /* FirePostCellNode+HitTesting.swift */, + B039AA18094D96411C3C25DB /* FirePostCellNode+LayoutSpec.swift */, + CA155A018F817CE8F0B7141C /* FirePostCellNode+Polls.swift */, + 646F2B64E7B33FA47974F858 /* FirePostCellNode+Quote.swift */, + 323769D2402BB6DB956BCBA3 /* FirePostCellNode+QuoteAction.swift */, 2A763199D74A1026B2ADB530 /* FirePostCellNode+Reactions.swift */, + AFADFB09839E6626FF12E186 /* FirePostCellNode+Thread.swift */, 8092585A18BAFAC8ECAB670D /* FirePostImageNode.swift */, 8A1B0239607F0ABAEA1ABCE0 /* FirePostLayoutManager.swift */, 929153DAB55DC46B3FDFC5ED /* FirePostPollRenderer.swift */, @@ -1215,10 +1742,31 @@ C08AC6976AD62C1DAB2DBB2F /* FireSelectableRichTextNode.swift */, 852D9E719DC6FE610CC4F084 /* FireTextureAttributedText.swift */, C32FFB215F2C0CDDE5C1221C /* FireTopicOneboxNode.swift */, + 6D0074D8DEFA2184F2EA3955 /* UIView+FireHierarchy.swift */, ); path = TopicDetail; sourceTree = ""; }; + 96E348766323990A54B86191 /* Components */ = { + isa = PBXGroup; + children = ( + BF54CB25631FF68748DF2BC2 /* FireAvatarView.swift */, + A25446A206207198B6223AD5 /* FireButtonStyles.swift */, + 3367E65714661E982001EBCC /* FireErrorStates.swift */, + A5AC04986AD864B86FEC5271 /* FireFeedKindSelector.swift */, + FFC8987AC1C508F9F95745CB /* FireMetadataComponents.swift */, + 5E99BED9B41412FD7461E1A0 /* FireOfflineBanner.swift */, + B9071081BCCEC2A924CEC92C /* FirePanel.swift */, + 7B57EFF4CD8BF80A874FFC0D /* FireRemoteImage.swift */, + 882CE51DF4383DDB04EE2E95 /* FireSceneBackground.swift */, + 0F8C73964C70D1D4BE662154 /* FireSkeleton.swift */, + DAD7D1368C3668D205CA1FD8 /* FireToast.swift */, + 4741FBBFF6A7C139E90AE6C3 /* FlowLayout.swift */, + 401B5C6197D90A29EDE33441 /* String+FireIfEmpty.swift */, + ); + path = Components; + sourceTree = ""; + }; 9B72DE4FF837D770C66332CC /* Controller */ = { isa = PBXGroup; children = ( @@ -1237,8 +1785,8 @@ 73EB36381D2DB9DA74378162 /* App */, BD212BBA5E9DA62F41FF41F4 /* Configs */, 32338F9E71B0E67C5112C300 /* FireAppSession */, - F6A48714E0F87937027A25E4 /* FireUniFfi */, 7044DC07E4881033F1BC8F64 /* FireWidget */, + 6CB14B164BD5987BA7B8C516 /* Generated/FireUniFfi */, 8FCD2C1B029D07F4C1B82746 /* Unit */, 9C9371C0E9747855874B64BD /* Widgets */, D5EBFF4F5452417E0754E6D0 /* Frameworks */, @@ -1283,6 +1831,7 @@ children = ( 71468CA537E8C6D7E84090CB /* FireChatBusPayload.swift */, 7E8DF8D0D6BD537DBD9D7680 /* FireChatChannelsStore.swift */, + 519940DDA0A5323D3793D653 /* FireChatListSession.swift */, 5D9CBC157BF5867CEBE3B65B /* FireChatViewController.swift */, ); path = Chat; @@ -1293,11 +1842,26 @@ children = ( 08710076BA9FA07121C0A9C5 /* FireBoostInputViewController.swift */, 49784F572BD41F7D9F024F55 /* FirePostFlagSheet.swift */, - 8BC7B03BAACE572DDB87E810 /* FireTopicDetailModalViews.swift */, + 7FD8241E21CB2CEED4AA475D /* FirePostReactionPickerSheet.swift */, + E7A4E63528064FF56B534955 /* FirePostRepliesSheet.swift */, + 73BE2EE62F5BED9A61A8BA2C /* FireReactionUsersSheet.swift */, 925CD02F862E958CC79BC60A /* FireTopicDetailSharedModels.swift */, + 99F0AD21E5D4EAE4CBCF21B2 /* FireTopicDetailUiProjection.swift */, + 18BE6FB86454F022528B1834 /* FireTopicFormatting.swift */, D411B9ABE5C61805B92A2DD2 /* FireTopicImagePipeline.swift */, + D384F4A919803D9BFF1F296F /* FireTopicImageViewer.swift */, 01D95BB10F2DECA7D5F404DE /* FireTopicListMetricPresentation.swift */, + 485A87123651CCA6DAD12B01 /* FireTopicPhotoBrowserController.swift */, + 02FDEF6C96B3C5C3D5763910 /* FireTopicPostMerge.swift */, ECBDE8779B6F7E32204263F4 /* FireTopicPresentation.swift */, + EC47D1BE0D7F65889A8A17A1 /* FireTopicReactionPresentation.swift */, + 49FEB500EA67E0649586CB1B /* FireTopicRenderModels.swift */, + 09C4C0F1BD2B7F38AC26618D /* FireTopicRenderProjection.swift */, + CFC129B0275F2EFA770163F5 /* FireTopicReplyPresentation.swift */, + 34B1C77D253E343F11117883 /* FireTopicSearchPresentation.swift */, + 44B48D5CD0574D77CA72FAAC /* FireTopicTimelineBuilder.swift */, + D1A1CCCEC0341697385E81E7 /* FireTopicTimelineModels.swift */, + 962E25B53FD692FBB3355E30 /* FireTopicVotersSheet.swift */, ); path = Support; sourceTree = ""; @@ -1320,12 +1884,20 @@ AED52A2EE8D19079BA80A52A /* Home */ = { isa = PBXGroup; children = ( + 6CAD3D8482640C6E6C636D0A /* FireFilteredFeedSelectorCell.swift */, + 3EC43A75B6485B9166B63DB9 /* FireFilteredTopicListControllerHost.swift */, F9384B4FECD3434E8DCCB3BA /* FireFilteredTopicListView.swift */, 3623960CD988F423E24CCE8C /* FireFilteredTopicListViewController.swift */, + 54A952E724AAB1BD1424F8ED /* FireFilteredTopicListViewController+Actions.swift */, + 2BD298D3BCD7D884DF020409 /* FireFilteredTopicListViewController+Feed.swift */, + CA2C6D3AD63CA17550149E0C /* FireFilteredTopicListViewController+Pagination.swift */, + 39BB529E7AD2BD708612BEC3 /* FireFilteredTopicListViewController+Routing.swift */, + 5F908C70A11E537FC1F475DE /* FireFilteredTopicListViewController+Setup.swift */, C05B0007F349D9B8B718F7F1 /* FireHomeCategoryDrawerController.swift */, 48153CE6A692130B4F8D97C5 /* FireHomeScopeChromeViews.swift */, B4F09B0F010E9C41B77F4B40 /* FireHomeScopePanelController.swift */, E355FDE3F6E9A5FFB6229374 /* FireHomeScopePresentation.swift */, + 5493A60CF66C250B7225025D /* FireHomeStyleSkeletonCell.swift */, ); path = Home; sourceTree = ""; @@ -1335,7 +1907,12 @@ children = ( E8D1B62331E78430BE857CDC /* FireDraftListCell.swift */, E3824000FAC99E70EA95DD86 /* FireDraftsControllerHost.swift */, + 6B98E98DFD1E03963E8CF83C /* FireDraftState+Presentation.swift */, E8E5B1ECAE617609F235B6A3 /* FireDraftsViewController.swift */, + DCFD5D1037C96C405E403F8D /* FireDraftsViewController+ComposerRouting.swift */, + 293D79BE540B73D84BDFABF6 /* FireDraftsViewController+Feed.swift */, + 2B5B0DE5F6A7C2D89DFAD0FD /* FireDraftsViewController+Pagination.swift */, + 385C82707C8B082E8EEC5268 /* FireDraftsViewController+Setup.swift */, 363FB3988C0F6A9163E8DCCF /* FireDraftsViewModel.swift */, ); path = Drafts; @@ -1393,6 +1970,7 @@ CEB7A4EE131ABA30059C2518 /* Stores */ = { isa = PBXGroup; children = ( + FE6A22C3F511DB107633C1FA /* FireHomeFeedSession.swift */, EC7384EAE1C43817CAE71D9F /* FireHomeFeedStore.swift */, 502CE714A74D91C33212BF57 /* FireNotificationStore.swift */, 8D0D5E6727E0D21855DDEA2F /* FirePaginatedStore.swift */, @@ -1471,11 +2049,23 @@ isa = PBXGroup; children = ( 6C063DC3D3814082F9655534 /* FireAppViewModel.swift */, + FC375636258776A9578CE154 /* FireAppViewModel+APM.swift */, + 928B370E2F406092C99E5F84 /* FireAppViewModel+Authentication.swift */, + ED89C80C5CB679C032ACFEB4 /* FireAppViewModel+Binding.swift */, D042B49EA2CBAB217A5011AF /* FireAppViewModel+Chat.swift */, + F9AC6D8E0A9B700CF2FC9BC5 /* FireAppViewModel+Composer.swift */, 1F1F872C6062881E7513980D /* FireAppViewModel+Diagnostics.swift */, + A37BC4D564DAC93057917CB8 /* FireAppViewModel+HomeFeed.swift */, + 5E94B3E516D54BE118941E7D /* FireAppViewModel+Logging.swift */, + CD5E566582BFC7E23506727B /* FireAppViewModel+LoginSupport.swift */, + BFE7644ABB3B64FDEFBCDC99 /* FireAppViewModel+MessageBus.swift */, 67D675A6BC377D2479E2A90B /* FireAppViewModel+Network.swift */, F74563DD6B9E870850553DDA /* FireAppViewModel+Profile.swift */, + D9AB8FAB900656D84CA6D7A6 /* FireAppViewModel+Recovery.swift */, 2933910F4309CBB2CC5F2BEC /* FireAppViewModel+RecoveryURLs.swift */, + 88895CD4883C551BA78B1913 /* FireAppViewModel+SessionApply.swift */, + 707CDA3897A19341B7B09333 /* FireAppViewModel+Startup.swift */, + 5158DC91BBAB977BE1737A7B /* FireAppViewModel+TopicDetail.swift */, 656CE7A291529B78CBAB24D8 /* FireAppViewModelSupport.swift */, 5DF67696B342C706CB3FAAFB /* FireProfileViewModel.swift */, ); @@ -1537,15 +2127,21 @@ children = ( 39617F1E70204DE972BD489F /* FireAppDelegate.swift */, 9D354D83C07C326288699E3D /* FireAppearanceEnvironment.swift */, - 24186C615A12A722B2ABEE06 /* FireComponents.swift */, E650ABD9C06621BC41908D59 /* FireContextMenus.swift */, + 7DB2CB885C9D0A5F0B51A6BD /* FireMainCardAnimator.swift */, + 139A690F74C13E830A6A959E /* FireMainNavigationController.swift */, 6CABC863F0E7DDEACF5B980D /* FireMainTabBarController.swift */, 97E8BD69061BE8C9E301D9BA /* FireRootCoordinator.swift */, + 44C646162E7A938015483CE7 /* FireRootCoordinator+APM.swift */, + 1017A72525731305BC35831D /* FireRootCoordinator+Authentication.swift */, + 32F810784CE3691264A9DB4D /* FireRootCoordinator+RootPresentation.swift */, + 92339F8BFC0B6325CD871533 /* FireRootCoordinator+Routing.swift */, 4E41FA85B0FAA4DAF83AA747 /* FireSceneDelegate.swift */, 0182FF50BA5178478278FB01 /* FireShimmerModifier.swift */, E0AA3F1257384BF109634D21 /* FireTheme.swift */, 8E3DCC9617583661AAF64366 /* FireTopicListMetricEffectCoordinator.swift */, 3FC109FBAA1787EF49336258 /* SessionState+Helpers.swift */, + 96E348766323990A54B86191 /* Components */, 3C38064D8A60C229546F1FCF /* UIKit */, ); path = Core; @@ -1569,25 +2165,6 @@ path = Shell; sourceTree = ""; }; - F6A48714E0F87937027A25E4 /* FireUniFfi */ = { - isa = PBXGroup; - children = ( - 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */, - 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */, - A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */, - E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */, - FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */, - C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */, - 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */, - DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */, - 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */, - 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */, - EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */, - ); - name = FireUniFfi; - path = Generated/FireUniFfi; - sourceTree = ""; - }; FCCF95D9199B06F0685551A5 /* Shell */ = { isa = PBXGroup; children = ( @@ -1632,6 +2209,9 @@ ); dependencies = ( ); + fileSystemSynchronizedGroups = ( + 6CB14B164BD5987BA7B8C516 /* Generated/FireUniFfi */, + ); name = Fire; packageProductDependencies = ( 601B450FB4E87A5243FAE5F9 /* CrashReporter */, @@ -1756,6 +2336,7 @@ ); outputPaths = ( "$(SRCROOT)/Generated/FireUniFfi/fire_uniffi.swift", + "$(SRCROOT)/Generated/FireUniFfi/fire_uniffi_chat.swift", "$(SRCROOT)/Generated/FireUniFfi/fire_uniffi_diagnostics.swift", "$(SRCROOT)/Generated/FireUniFfi/fire_uniffi_ldc.swift", "$(SRCROOT)/Generated/FireUniFfi/fire_uniffi_messagebus.swift", @@ -1833,39 +2414,60 @@ 3020B851468E970811BC595B /* FireAppRouteControllerFactory.swift in Sources */, C393F32FAD3010FF51E3E7F2 /* FireAppRouteDestinationView.swift in Sources */, 957DADCF16F936D3BCCDE7F5 /* FireAppServiceHost.swift in Sources */, + D24539084535FE2AB8555D72 /* FireAppViewModel+APM.swift in Sources */, + 0BA0F58971A336C8C7AEAAD2 /* FireAppViewModel+Authentication.swift in Sources */, + F03F99AD1742500B251CDC9D /* FireAppViewModel+Binding.swift in Sources */, CD0EDE3D5D4C6F06272F451A /* FireAppViewModel+Chat.swift in Sources */, + E3317673E81F0D4D307B84AD /* FireAppViewModel+Composer.swift in Sources */, 7B772557813420536690D938 /* FireAppViewModel+Diagnostics.swift in Sources */, + 8EE144178136B5138204781F /* FireAppViewModel+HomeFeed.swift in Sources */, + D3C6A464B16938922AB03ACD /* FireAppViewModel+Logging.swift in Sources */, + DC3C8637A4BD25812ED13D76 /* FireAppViewModel+LoginSupport.swift in Sources */, + 4856BA5A72A6E2417981235C /* FireAppViewModel+MessageBus.swift in Sources */, F388A1165747AC85DEE53FFD /* FireAppViewModel+Network.swift in Sources */, D100DFBC749CA19A23E11CD3 /* FireAppViewModel+Profile.swift in Sources */, + 18D104B7EB2A7A8212E3C1B3 /* FireAppViewModel+Recovery.swift in Sources */, 5F12EFC296AA350367A07DB5 /* FireAppViewModel+RecoveryURLs.swift in Sources */, + 7EB8AAFE71FE4A170D23BB5F /* FireAppViewModel+SessionApply.swift in Sources */, + 369327949DA9B31DD79B2442 /* FireAppViewModel+Startup.swift in Sources */, + 5D87A4C492216989AD97443B /* FireAppViewModel+TopicDetail.swift in Sources */, B0AA426C24E27249B4AE2E57 /* FireAppViewModel.swift in Sources */, BFAAEB3942767128220C1DB5 /* FireAppViewModelSupport.swift in Sources */, 5B02974CC6660AB7D633D41E /* FireAppearanceEnvironment.swift in Sources */, 5A95F9C29909968BF4B17AD7 /* FireAuthCookieKeychainStore.swift in Sources */, D201FF0609323A45827C583F /* FireAutoLoginPlanner.swift in Sources */, + BA7D6DA6F64BDFC24D522582 /* FireAvatarView.swift in Sources */, 5C94B9ACD52AEF20ED7AC39F /* FireBackgroundNotificationAlert.swift in Sources */, 78009659A664B236D8AD3434 /* FireBadgeDetailView.swift in Sources */, FFA9CA2BD6BA97E97C13CCA8 /* FireBookmarkEditorSheet.swift in Sources */, E74952BCA8EF2D8E92C528CD /* FireBookmarksView.swift in Sources */, + C07A47C1DCF02FC547D4B7BC /* FireBookmarksViewController+Actions.swift in Sources */, + C6DB817EF213E5336F0623A2 /* FireBookmarksViewController+Feed.swift in Sources */, + 080322BE83553F16044A25D6 /* FireBookmarksViewController+Pagination.swift in Sources */, + 763C17574154616F2223D573 /* FireBookmarksViewController+Routing.swift in Sources */, + 16A48982DD3892B6A4148C27 /* FireBookmarksViewController+Setup.swift in Sources */, 29F891D31E57BD3D19AB4EBB /* FireBookmarksViewController.swift in Sources */, 385A66FC63C5CD7CFD837AFC /* FireBoostInputViewController.swift in Sources */, B651E365379EF3DC59BE3CBE /* FireBottomInputBar.swift in Sources */, + BBE3BEC6A314CBDAE0944679 /* FireButtonStyles.swift in Sources */, CB59605E778D5DDE7985CD9A /* FireCDKView.swift in Sources */, 75942BB0E2A79B55D5D92674 /* FireCaptchaLoginDialogController.swift in Sources */, + 003C84E56BD714FB4E63880A /* FireCapturedLoginState.swift in Sources */, E96C65EF805B1CE2F1A620B9 /* FireCategoriesView.swift in Sources */, 0AABB8FE83B25A7D6D7C67FC /* FireCfClearanceRefreshService.swift in Sources */, 615555AD106EE013C19A39E4 /* FireChatBusPayload.swift in Sources */, + 9A97E38621EEBC537BB94146 /* FireChatChannelSession.swift in Sources */, 61BF2592182EDEFA977814F6 /* FireChatChannelViewController+Bus.swift in Sources */, 1E95763ADE4D7A8428718D1A /* FireChatChannelViewController+Interactions.swift in Sources */, 034DDDD09E919D20852775B6 /* FireChatChannelViewController+Load.swift in Sources */, 27EBDDEA2CFC1F6A77718875 /* FireChatChannelViewController+Table.swift in Sources */, F4D3095A5C796DB69B6B51B9 /* FireChatChannelViewController.swift in Sources */, FD9B148D42E5E38E033DBF65 /* FireChatChannelsStore.swift in Sources */, + 048472E4653C3369CFBA9E8D /* FireChatListSession.swift in Sources */, 44F4598A114E7B55EB3A7A5B /* FireChatMessageCell.swift in Sources */, F6C8A1554FC2C48FB67706A3 /* FireChatViewController.swift in Sources */, CF0700843F7CDFE2F9140016 /* FireCloudflareChallengeCoordinator.swift in Sources */, F8963543E87EACAD49C9B131 /* FireCollectionHost.swift in Sources */, - B9E25AF09D46C9889B98E8A2 /* FireComponents.swift in Sources */, 4AA62FDF95D9A4E90D07D625 /* FireComposerCategoryGuidance.swift in Sources */, EFE5CAC3C4B129DAEA3C332D /* FireComposerChromeViews.swift in Sources */, DF1806BFA9860F7280CD739E /* FireComposerControlFactory.swift in Sources */, @@ -1874,6 +2476,7 @@ 951E66D7F08A42D93EBFFF18 /* FireComposerEditorModels.swift in Sources */, B0FEF7BFCBC3AE45FDE9978A /* FireComposerInitialBody.swift in Sources */, A21B01B774188E91EC382269 /* FireComposerRoute.swift in Sources */, + F1D1168DA91C4AA5FB54A053 /* FireComposerSession.swift in Sources */, 6B10F17B6D3AE362E0667530 /* FireComposerTextView.swift in Sources */, 1CABA3580C29E104B384F323 /* FireComposerValidation.swift in Sources */, 385B67F8E7B07CD0674E2BEA /* FireComposerViewController+Chrome.swift in Sources */, @@ -1892,38 +2495,58 @@ 939404BE03A327D4A29B6E33 /* FireDiffableListController.swift in Sources */, DA3519D17B33A6FF56FAD600 /* FireDohSourceViewController.swift in Sources */, FBB020AA0C3F4A97DC1EFE7F /* FireDraftListCell.swift in Sources */, + 217CF41F35017C092619A769 /* FireDraftState+Presentation.swift in Sources */, 70D5B41B5FDF1CA7AC72A507 /* FireDraftsControllerHost.swift in Sources */, + FF6B6061AD94BDB64476DBFD /* FireDraftsViewController+ComposerRouting.swift in Sources */, + 410A0CECE4529C1CF6F6FA82 /* FireDraftsViewController+Feed.swift in Sources */, + CE707D075E87B10D143FEAD7 /* FireDraftsViewController+Pagination.swift in Sources */, + 15CB95AE4A1E2E60B5726527 /* FireDraftsViewController+Setup.swift in Sources */, 315F73393DBB4E5F1D472684 /* FireDraftsViewController.swift in Sources */, A9966B571DC43A5E38A3F139 /* FireDraftsViewModel.swift in Sources */, 6CD842F82A4371F3BCCCF4C5 /* FireEntityIndex.swift in Sources */, + 68C959895802DA36652BAE51 /* FireErrorStates.swift in Sources */, 355451477523656402E506B8 /* FireExportDiagnosticsView.swift in Sources */, E93FB84668880A48421D81BE /* FireExternalLoginMethod.swift in Sources */, + 28F30EA23DA3903A07F8297F /* FireFeedKindSelector.swift in Sources */, BB6794B89B439C61B8A5620C /* FireFeedbackPresenter.swift in Sources */, 9B3FEA7A81A1EA5482AEE24B /* FireFeedbackViewController.swift in Sources */, + 2D0DD0C8D79306D2DBB0C0F0 /* FireFilteredFeedSelectorCell.swift in Sources */, + FEFFED7F365FE3A5C61274D0 /* FireFilteredTopicListControllerHost.swift in Sources */, FD8277139166DCD8F96715A9 /* FireFilteredTopicListView.swift in Sources */, + 9AC9DCD6A6661BF9920B5515 /* FireFilteredTopicListViewController+Actions.swift in Sources */, + 65937CFE1219F3DBA4EFF2C8 /* FireFilteredTopicListViewController+Feed.swift in Sources */, + 3B6102A8903B9E4A790BBE6A /* FireFilteredTopicListViewController+Pagination.swift in Sources */, + D289F51C63C35A835E0A2506 /* FireFilteredTopicListViewController+Routing.swift in Sources */, + 3AFBACA8C60CB301E1D16A49 /* FireFilteredTopicListViewController+Setup.swift in Sources */, 2BB1CFDFB44C42712F173627 /* FireFilteredTopicListViewController.swift in Sources */, D2D1EA7C7D1208AEE0932A86 /* FireFollowListViewController.swift in Sources */, 3F1C13559BEAD77AE0EC1F13 /* FireHeadlessExternalLoginEngine.swift in Sources */, 21A13575BAABF925D2AF02D0 /* FireHomeCategoryDrawerController.swift in Sources */, E2F0F91B27F48F9BF4F1E7B0 /* FireHomeFeedModels.swift in Sources */, + DF61516266D80993C3184825 /* FireHomeFeedSession.swift in Sources */, 768DC62B26A1D2EF4F545D35 /* FireHomeFeedStore.swift in Sources */, 282054CA9D02B4F47B3C0691 /* FireHomePaginationCoordinator.swift in Sources */, 40B864B25377AE905208F981 /* FireHomeScopeChromeViews.swift in Sources */, 03270A2669E87643C2507254 /* FireHomeScopePanelController.swift in Sources */, 7B1B888CA814A35E5354CA0D /* FireHomeScopePresentation.swift in Sources */, 4FAD2E2F807F1136D45392CF /* FireHomeShellViews.swift in Sources */, + 4F5B0E726AD298783DB3C559 /* FireHomeStyleSkeletonCell.swift in Sources */, DE050CA5760E795B145F7235 /* FireHomeViewController+Actions.swift in Sources */, 819D8580060771998348C810 /* FireHomeViewController+Feed.swift in Sources */, 960DD0761DFC82B776B6D33C /* FireHomeViewController.swift in Sources */, + F0D7E2AB2BEFD5133C95FD90 /* FireHostLogger.swift in Sources */, C5CA50A5F7707420F084ABA8 /* FireInlineReactionPickerScrollNode.swift in Sources */, 1F34091982CA9E4020CE6186 /* FireInviteLinksView.swift in Sources */, 128C486AB0D36B2CB5936D52 /* FireLDCView.swift in Sources */, F31A70760B997F5ADFB7C489 /* FireListSectionModel.swift in Sources */, BE531BCFF96A8C23E0180F6B /* FireLogDiagnosticsView.swift in Sources */, + 9B2D39BD19CDBA4B7880E8F7 /* FireMainCardAnimator.swift in Sources */, + 3F25189F91AE9BDEF840E62B /* FireMainNavigationController.swift in Sources */, 9912E13751119248F5626F77 /* FireMainTabBarController.swift in Sources */, F5FBD9F006A02C2363D1E559 /* FireMarkdownInsertion.swift in Sources */, AF99074CBA5E53804D47CE50 /* FireMarkdownToolbar.swift in Sources */, BDBF0CEBD8F5F7C1C19769B7 /* FireMessageBusCoordinator.swift in Sources */, + DB074584BFA8A2DF54F2ABD1 /* FireMetadataComponents.swift in Sources */, 0344231CB80C3CAD4A0DCBEC /* FireMidSessionReauthOverlayController.swift in Sources */, A2BA00121D5BF00E4543EF13 /* FireMotionEffects.swift in Sources */, 5CACD8BFBDA8FDF7D7CBF4E7 /* FireMotionReduceMotion.swift in Sources */, @@ -1937,33 +2560,83 @@ 13C14E92B46B8FA37CFD3B1A /* FireNetworkTraceDetailView.swift in Sources */, 89B0F00FD4AC022A597A8BEB /* FireNotificationBannerCells.swift in Sources */, 77E848E1359E1F9B69439B7B /* FireNotificationFeedModels.swift in Sources */, + 4A1A891140E689E79AE3FB5A /* FireNotificationHistoryViewController+Actions.swift in Sources */, + A5CE38E41B0771F5A4AFC927 /* FireNotificationHistoryViewController+Feed.swift in Sources */, + 282B6E71ED2FAC10106A40AA /* FireNotificationHistoryViewController+Pagination.swift in Sources */, + B8F6D0C7D23834F0BBB866C5 /* FireNotificationHistoryViewController+Routing.swift in Sources */, + 93C359EFFD6688AF18EF40B2 /* FireNotificationHistoryViewController+Setup.swift in Sources */, A4ADCCA6165C3D05DE20E902 /* FireNotificationHistoryViewController.swift in Sources */, 0A63CF028063304243D985F8 /* FireNotificationListCell.swift in Sources */, C957386748A90B96C74997A7 /* FireNotificationPresentation.swift in Sources */, E460D11F2D744411AA61E5A6 /* FireNotificationService.swift in Sources */, B4AA77D05D86AB070BE06A93 /* FireNotificationStore.swift in Sources */, + C81693A346DC274E719130A1 /* FireNotificationsViewController+Actions.swift in Sources */, + E8A5818AB91FF4C3735FBBC4 /* FireNotificationsViewController+Feed.swift in Sources */, + C6387581E79A086B41CCA3E9 /* FireNotificationsViewController+Pagination.swift in Sources */, + 986F0EDE1C6CD8172FF834E9 /* FireNotificationsViewController+Routing.swift in Sources */, + A3BF7C908F426C9F0C83A34C /* FireNotificationsViewController+Setup.swift in Sources */, 9DFCA37A0C4D7498B525A034 /* FireNotificationsViewController.swift in Sources */, + 9FDF261B636A14B6215D3093 /* FireOfflineBanner.swift in Sources */, + AEC7A137DD9872E068311236 /* FireOnboardingCredentialFormView+ExternalMethods.swift in Sources */, + 071F0BD73521F036C04F6EAC /* FireOnboardingCredentialFormView+Fields.swift in Sources */, + 223F642EB1620378ED1DE0CA /* FireOnboardingCredentialFormView+Keyboard.swift in Sources */, + 2A7F2B1FE5A92E256E36C531 /* FireOnboardingCredentialFormView+LastLoginHint.swift in Sources */, + 7F46E3955CDAA150242B9FD2 /* FireOnboardingCredentialFormView+LoginButton.swift in Sources */, + 42BDD00E7F1227287204DA01 /* FireOnboardingCredentialFormView+Options.swift in Sources */, F41EBD87EC59341D3A7DD381 /* FireOnboardingCredentialFormView.swift in Sources */, + 9EC5DDF2734BF3A760698793 /* FireOnboardingErrorBannerView.swift in Sources */, 2693C86EB9B8D438930E1B26 /* FireOnboardingValidatingView.swift in Sources */, 47478A1EF4F9D689EFA0FD9E /* FireOnboardingView.swift in Sources */, + FCCE36628F9AA6964E3AD6E0 /* FireOnboardingViewController+AuthLog.swift in Sources */, + 7B97D416442B9EBDA25A886E /* FireOnboardingViewController+BottomControls.swift in Sources */, + 0CA15E19782C812271B1AEB2 /* FireOnboardingViewController+Brand.swift in Sources */, + E7F23FF3CB239AA080E003BF /* FireOnboardingViewController+Captcha.swift in Sources */, + F5AA1C5969A274475572FEF1 /* FireOnboardingViewController+CloudflareRecovery.swift in Sources */, + 5E54BBB3C72F683B9562CA2D /* FireOnboardingViewController+ExternalAutoLogin.swift in Sources */, + 8FC5460F837E1BD21F390B8E /* FireOnboardingViewController+Keyboard.swift in Sources */, + 5DDFDCACF21FCAFCA87543CC /* FireOnboardingViewController+LoginActions.swift in Sources */, + 4CD39D25480EB406C29A5AA6 /* FireOnboardingViewController+PasswordAutoLogin.swift in Sources */, + 4E3F5E45447A999F5CF0FFAC /* FireOnboardingViewController+PhaseRendering.swift in Sources */, + EEDD863006F25189D080ED7C /* FireOnboardingViewController+SecondFactor.swift in Sources */, + 8169033D7B7D654CC99ACE4A /* FireOnboardingViewController+StartupRouting.swift in Sources */, 4291E89FC3D5D35AC9A06898 /* FireOrderedIDList.swift in Sources */, 816DB34CD28CD94ED88EF9C6 /* FirePaginatedStore.swift in Sources */, + 0A5EDE218163F9336EE58723 /* FirePanel.swift in Sources */, 16ACF29E54C873A3B35858BE /* FirePostBoostBarrageView.swift in Sources */, 0117AF25FD8334DB2C46A933 /* FirePostBoostManualScrollerView.swift in Sources */, 772EFD83C4DEB77EAC00FD55 /* FirePostCellLayout.swift in Sources */, 7848D667BF692B25B4194E57 /* FirePostCellLayoutCalculator.swift in Sources */, E431DE1C6E0C3646603CE3FC /* FirePostCellNode+Actions.swift in Sources */, + 4E1DC34F72033EA90918DD01 /* FirePostCellNode+Appearance.swift in Sources */, + F2E9D91E93C3065E91D40332 /* FirePostCellNode+Author.swift in Sources */, E014EA02CB83C92E5821707D /* FirePostCellNode+Body.swift in Sources */, + 9052C724214E66A6CE1FD18A /* FirePostCellNode+Boosts.swift in Sources */, + 7632BA69586B036FEA62762E /* FirePostCellNode+Configuration.swift in Sources */, + 4FA37E1E0084A7DAE6AA83E0 /* FirePostCellNode+ContextMenu.swift in Sources */, + CB6AA9F8128F7AFD82BA3C39 /* FirePostCellNode+HitTesting.swift in Sources */, + 110004A60A7B6F51613A8727 /* FirePostCellNode+LayoutSpec.swift in Sources */, + A6AD9D0FE1466E1B0FE0C029 /* FirePostCellNode+Polls.swift in Sources */, + C5DFF1757291B54826192D80 /* FirePostCellNode+Quote.swift in Sources */, + 2C6BA8B8DAA40C400DF6AA62 /* FirePostCellNode+QuoteAction.swift in Sources */, 7EFB42D38DCA6C0F63720AE3 /* FirePostCellNode+Reactions.swift in Sources */, + 4DEDB607C66E59F7DEFFA164 /* FirePostCellNode+Thread.swift in Sources */, 489C515305D468C608C7315D /* FirePostCellNode.swift in Sources */, C5725D3E49E71B490BB43518 /* FirePostEditorView.swift in Sources */, 65A7971203D5D03D0681E719 /* FirePostFlagSheet.swift in Sources */, A2C954EBAE5163E708B3F189 /* FirePostImageNode.swift in Sources */, 9E7B9F6741C79AF8E6C3D0DA /* FirePostLayoutManager.swift in Sources */, 44803F9B07AEA78F2DEC49AB /* FirePostPollRenderer.swift in Sources */, + FB7A168EC8DE8DC53146F911 /* FirePostReactionPickerSheet.swift in Sources */, + 35362CA2A814F56208306EDE /* FirePostRepliesSheet.swift in Sources */, 3CA9AF0BFA58C32834B441F3 /* FirePresentationIdentity.swift in Sources */, 4CDAF08E9DD1F41DDA5DCE4B /* FirePrivateMessageCells.swift in Sources */, C6DE052F7456527185C4F1FC /* FirePrivateMessagesControllerHost.swift in Sources */, + 97F30164C2F5C24C7936C93D /* FirePrivateMessagesViewController+Composer.swift in Sources */, + 54799FB2DA0FA9EFB73F31F2 /* FirePrivateMessagesViewController+Feed.swift in Sources */, + 28856A5854B5C930C12C3726 /* FirePrivateMessagesViewController+Pagination.swift in Sources */, + 5192D08A716698686010E397 /* FirePrivateMessagesViewController+Participants.swift in Sources */, + DC6A06F911EE917F3179C0A2 /* FirePrivateMessagesViewController+Routing.swift in Sources */, + 29A7127B03E0BFCA64F300B2 /* FirePrivateMessagesViewController+Setup.swift in Sources */, 35B6F563371260443CDCF46C /* FirePrivateMessagesViewController.swift in Sources */, 4B95D21F7985C6991CBBD94A /* FirePrivateMessagesViewModel.swift in Sources */, 27F8780AB48C65663BA8CF6A /* FireProfileActivityRow.swift in Sources */, @@ -1975,20 +2648,44 @@ 3FB0703417FA44B6B90837D5 /* FireProfileMenuRowCell.swift in Sources */, BD0F6BE28D1D0143383BAF2A /* FireProfileStatsRow.swift in Sources */, 2EF020F79C1B4F20796C610C /* FireProfileTrustLevelPill.swift in Sources */, + 79B5F008215EFD4E3550D4FA /* FireProfileViewController+Binding.swift in Sources */, + 8A8BCF5EB34F5677D4388D0F /* FireProfileViewController+Routing.swift in Sources */, + 4AC091DD5B35A35D920EC2AF /* FireProfileViewController+RowProjection.swift in Sources */, + B4875D9875C18AE2D66659ED /* FireProfileViewController+Table.swift in Sources */, 5C91256EF203F8B20E1E145E /* FireProfileViewController.swift in Sources */, 3A339550AA3EE966F7EA50E5 /* FireProfileViewModel.swift in Sources */, 7A0A8240B294336D5787C364 /* FirePublicProfileViewController.swift in Sources */, D914CE5CE076533C2C932623 /* FirePushDiagnosticsView.swift in Sources */, 6F88C8AAB2089E7F558EDE67 /* FirePushRegistrationCoordinator.swift in Sources */, 47CA07B15132822B96604FB5 /* FireQuoteMarkdown.swift in Sources */, + FAC6F57FC96EC506F6E1E5FD /* FireReactionUsersSheet.swift in Sources */, CEC557CB91456A379F8FE867 /* FireReadHistoryView.swift in Sources */, + F7E934B79CE09923F9EBFDFA /* FireReadHistoryViewController+Actions.swift in Sources */, + 06481C894DF2A0F311026245 /* FireReadHistoryViewController+Feed.swift in Sources */, + C2FE5DB96A46D25465DA54CF /* FireReadHistoryViewController+Pagination.swift in Sources */, + 90F6623DB548F76D401CC5EC /* FireReadHistoryViewController+Routing.swift in Sources */, + 2F6211BFB88F5925BDD05489 /* FireReadHistoryViewController+Setup.swift in Sources */, 3A20BD9A2A4CE944762B0BD7 /* FireReadHistoryViewController.swift in Sources */, C61D6B26B2EB49CD2BE88224 /* FireRecipientTokenField.swift in Sources */, + FBD68A1E798F8755191B33FD /* FireRemoteImage.swift in Sources */, 0F86EF628BCB2463C97F0863 /* FireRenderPresentation.swift in Sources */, + 54698B7A3C82B029053281DB /* FireRichTextAttributedStringBuilder+Inline.swift in Sources */, + 3F999AD8DB6BBFC806151939 /* FireRichTextAttributedStringBuilder+Lists.swift in Sources */, + 13A6AE19C7D233FFB49F12F4 /* FireRichTextAttributedStringBuilder+Onebox.swift in Sources */, + 88CC439CA2AC2CDABAF8919E /* FireRichTextAttributedStringBuilder+Quotes.swift in Sources */, + 235D4C00DF4D77DB4B135E74 /* FireRichTextAttributedStringBuilder.swift in Sources */, + AA9943A647FC27A13AEEEE52 /* FireRichTextEmojiAttachment.swift in Sources */, + 1337A7D82BE2B52ABF0B69DD /* FireRichTextModels.swift in Sources */, 77FA425E01F1504EB75DA831 /* FireRichTextNodeLinkDelegate.swift in Sources */, - 72AC7A92BEC5E2B99DEE5ACC /* FireRichTextRenderer.swift in Sources */, + 0742DA5CCE3B1147AE444C6D /* FireRichTextTextView.swift in Sources */, + 0088C39494610623784F8F75 /* FireRichTextView.swift in Sources */, + 11D1BA4453EE2B867F5FDE9A /* FireRootCoordinator+APM.swift in Sources */, + 94A343F928DAB8C01489C153 /* FireRootCoordinator+Authentication.swift in Sources */, + C884174DCD18AEEB455C8BBD /* FireRootCoordinator+RootPresentation.swift in Sources */, + D7B9A41AE9DF1D8ACC730F07 /* FireRootCoordinator+Routing.swift in Sources */, C0912C916D7832645283F77D /* FireRootCoordinator.swift in Sources */, DC4203187C3CAF0846C2D8BF /* FireRouteParser.swift in Sources */, + 233FA1179F4BBBD0DC7B3299 /* FireSceneBackground.swift in Sources */, C94AC2F334339FCFEB86CB04 /* FireSceneDelegate.swift in Sources */, 1FF5479B50192659F7E4B9C9 /* FireSearchCells.swift in Sources */, 874B0947FB4673A436444942 /* FireSearchFeedModels.swift in Sources */, @@ -2000,45 +2697,111 @@ 426EA4818F619C1E65B4DBF6 /* FireSearchViewController+Feed.swift in Sources */, D54D0269DD6FBCE6AB9488B2 /* FireSearchViewController.swift in Sources */, 8414458CE31AB953097CF014 /* FireSelectableRichTextNode.swift in Sources */, + 6851B0EFBCFB27061F5B98B8 /* FireSessionStore+Authentication.swift in Sources */, + 1C49DC0FF7765886CCA5A6F9 /* FireSessionStore+Bootstrap.swift in Sources */, + 9B074ED624221BEF55AF50D8 /* FireSessionStore+Chat.swift in Sources */, + A7C95828F3955A2FD5B0908A /* FireSessionStore+Composer.swift in Sources */, + DB1AA92F0E0DAD629C20562F /* FireSessionStore+Cookies.swift in Sources */, + 12AC670F3640F22237C123DF /* FireSessionStore+Diagnostics.swift in Sources */, + EA08684193B24A12AAC82008 /* FireSessionStore+Doh.swift in Sources */, + 37B5A497C6F50115942DC1DF /* FireSessionStore+HomeScope.swift in Sources */, + DB9AB4DF8626B88FE8CF1BB1 /* FireSessionStore+Interactions.swift in Sources */, + 7D84EA4EB6BD0DD074350541 /* FireSessionStore+Ldc.swift in Sources */, + B9CAD7B0663CD286E6FDF43B /* FireSessionStore+Lifecycle.swift in Sources */, + 1F861D3D672F67E8D07815B3 /* FireSessionStore+MessageBus.swift in Sources */, + 8855525F82CD1A65EDB5E84B /* FireSessionStore+Notifications.swift in Sources */, + 2FE323867F6202AB2F52AE16 /* FireSessionStore+Observers.swift in Sources */, + FE3D890FE6E4535AB72FBF44 /* FireSessionStore+Profiles.swift in Sources */, + 5CF0A8A6F2D3170F7875A68C /* FireSessionStore+Search.swift in Sources */, + C7CB9AC0087AC33C03FA6C49 /* FireSessionStore+Topics.swift in Sources */, + 38C8EF17FA31254FE367B032 /* FireSessionStore+WritePreflight.swift in Sources */, A29E21413FA011161D518004 /* FireSessionStore.swift in Sources */, + 8561D2B430C0C5A7A976953F /* FireSessionStoreError.swift in Sources */, 660EE0478082FB4E3B85C3B2 /* FireSettingsViewController.swift in Sources */, 028F38D6EAB5FAC769AF93EC /* FireShakeWindow.swift in Sources */, 5EF8B30E931B020C7512ACE1 /* FireShimmerModifier.swift in Sources */, D89E51A2B4024E06147DAEE7 /* FireShortcuts.swift in Sources */, + 774FF2910ECBA13FD231796E /* FireSkeleton.swift in Sources */, C55AB47E8AAB3E7A47EE95FF /* FireTabRoot.swift in Sources */, 0738F9AD86263ECE2016A8D4 /* FireTagPickerSheet.swift in Sources */, F6B73F0BFAB8573C89C89CCA /* FireTextureAttributedText.swift in Sources */, 09DEF34E484D68FE6A3A1AC5 /* FireTheme.swift in Sources */, + 859239670E11D700CB5A3F83 /* FireToast.swift in Sources */, + 1FB6D001DE414C289B998A2E /* FireTopicDetailAISummaryCellNode.swift in Sources */, 8169E3FD365AE9F655517F7C /* FireTopicDetailArticleSnapshot.swift in Sources */, + 9D85EA411B0371A13ABD869E /* FireTopicDetailBodyStateCell.swift in Sources */, + 9CDDF0194D8EF4264C917F77 /* FireTopicDetailCellTheme.swift in Sources */, D668649DC871BC807613F946 /* FireTopicDetailCommentListSnapshot.swift in Sources */, 04AB0C15F52072F2E720E47F /* FireTopicDetailControllerHost.swift in Sources */, + 340AF4FEF56C48FA2CD0080E /* FireTopicDetailFeedCellFactory+BodyState.swift in Sources */, + C8EE185EB06F31D99545D512 /* FireTopicDetailFeedCellFactory+Replies.swift in Sources */, + C66F576761BCCC1CB8A9F84E /* FireTopicDetailFeedCellFactory+Stats.swift in Sources */, + F03E48C56FF19099C6DCDAB5 /* FireTopicDetailFeedCellFactory+Voting.swift in Sources */, E38E8CABB24B1AD415D69203 /* FireTopicDetailFeedCellFactory.swift in Sources */, - B7784C41CA7002BF3223029B /* FireTopicDetailFeedCells.swift in Sources */, + 3DCD2D4C807C1D9341D00517 /* FireTopicDetailFeedController+Appearance.swift in Sources */, + B99A8E7770372257C5958C39 /* FireTopicDetailFeedController+CellApplication.swift in Sources */, + D5B45852653BAD7CFCBA0B58 /* FireTopicDetailFeedController+CollectionUpdates.swift in Sources */, + 4952AC421EAF266752C5249D /* FireTopicDetailFeedController+DataSource.swift in Sources */, + A66C7E27316571DAC519ADA0 /* FireTopicDetailFeedController+Layout.swift in Sources */, + 7C14237FA7BE97CFD9CB2B59 /* FireTopicDetailFeedController+Scrolling.swift in Sources */, FAD86B64AB552B9E3E9F68A7 /* FireTopicDetailFeedController.swift in Sources */, - EB9B101FE0204DA532CE4635 /* FireTopicDetailFeedModels.swift in Sources */, 18F45B9FD3C30EAB2C985803 /* FireTopicDetailFeedUpdatePipeline.swift in Sources */, - CE0D834262ED55561F6BC409 /* FireTopicDetailInteractionCoordinator.swift in Sources */, + 91C55013A07282460B0216D1 /* FireTopicDetailFlagSheetHost.swift in Sources */, + 71605DB2EE107989D2DF05B3 /* FireTopicDetailHeaderCellNode.swift in Sources */, + 6CA4339F385531C17E9ABD71 /* FireTopicDetailModalRouter+Alerts.swift in Sources */, + 0BC8C37BB8F4054577565B78 /* FireTopicDetailModalRouter+Composer.swift in Sources */, + 2A71414E9B514FD38EF45FA1 /* FireTopicDetailModalRouter+Navigation.swift in Sources */, + 77C50E2260AC5C0D8F3C1D61 /* FireTopicDetailModalRouter+PostModals.swift in Sources */, 24F82A793D9593417C1E59EA /* FireTopicDetailModalRouter.swift in Sources */, - 522CA82334EAC05D23624720 /* FireTopicDetailModalViews.swift in Sources */, BBE9EB26A016A92092A4D0F2 /* FireTopicDetailPageSkeleton.swift in Sources */, 6C52C8A80C6D33CEEF5F6B18 /* FireTopicDetailPageSnapshot.swift in Sources */, F25C8C5E91D29F5BEDB35E9A /* FireTopicDetailPageState.swift in Sources */, E5268113A96209626BB13FEA /* FireTopicDetailPaginationCoordinator.swift in Sources */, + CD02401A3076D6A59D7F9A62 /* FireTopicDetailPostRepliesHost.swift in Sources */, + A3CDF7BB4BAA265461E2606E /* FireTopicDetailRepliesHeaderCell.swift in Sources */, + 010562DD593DC1AB44C95A30 /* FireTopicDetailReplyFooterCell.swift in Sources */, 52CF002705A0E18AAB2E9E62 /* FireTopicDetailRootNode.swift in Sources */, + 5E559CD8DCDE75AC741319AA /* FireTopicDetailRuntimeConfiguration.swift in Sources */, + 891E74C234722341CEA2B1B8 /* FireTopicDetailRuntimeInteractions.swift in Sources */, + BAA1DF9C5F7A1B7565337856 /* FireTopicDetailRuntimeItem.swift in Sources */, + 096FCFD1EBD6F9EFB0A15360 /* FireTopicDetailRuntimeReplyFooterState.swift in Sources */, + E50D3FE4862B8B80EBB60430 /* FireTopicDetailRuntimeSnapshot.swift in Sources */, 09D7B4DCFB71311E9D856D59 /* FireTopicDetailRuntimeSnapshotBuilder.swift in Sources */, 1BD783D28E55AAC320B6BB20 /* FireTopicDetailSearchCoordinator.swift in Sources */, 256CB81681004BB26E0431B7 /* FireTopicDetailSharedModels.swift in Sources */, 02880D7A3651EFC8EF3AA607 /* FireTopicDetailSnapshotAssembler.swift in Sources */, + 6F60EC98C6A1C5B340801891 /* FireTopicDetailStatsCell.swift in Sources */, 620E6C8613CE05B48E562CB7 /* FireTopicDetailStore+Load.swift in Sources */, C35DE51A41D60111114BD225 /* FireTopicDetailStore+Mutations.swift in Sources */, 05F49A82B0CDC6486E7250F9 /* FireTopicDetailStore+Presence.swift in Sources */, C4BEC91E66B2FACA4DE02EA4 /* FireTopicDetailStore+Reactions.swift in Sources */, 47B89C5984DCCAB601B919EE /* FireTopicDetailStore.swift in Sources */, + 6A4192E81E47051D02C269B2 /* FireTopicDetailTextCell.swift in Sources */, + C3B7AC070D948696B25A9B21 /* FireTopicDetailToolbarActionsView.swift in Sources */, 26F6FF8DF720B6F46F3C5226 /* FireTopicDetailToolbarCoordinator.swift in Sources */, + 8641FBEF7BF3BCE3AC1BA3FA /* FireTopicDetailToolbarMetrics.swift in Sources */, + 991F273F73D0F03AD90C053E /* FireTopicDetailToolbarTitleView.swift in Sources */, + 9277029F7EF49DEA6AA24BC7 /* FireTopicDetailTopicVoteCell.swift in Sources */, + 823246221761BF66B80E68B6 /* FireTopicDetailUiProjection.swift in Sources */, + 24188FF66792BCDA314C7671 /* FireTopicDetailViewController+Appearance.swift in Sources */, + 7084EC3A6B54F932BC42FF86 /* FireTopicDetailViewController+Keyboard.swift in Sources */, + AB88DD7862C5E0979EF6E823 /* FireTopicDetailViewController+Lifecycle.swift in Sources */, + F8BAC393CB1196C57E8B5D8D /* FireTopicDetailViewController+Modals.swift in Sources */, + A5BB22B38DAC407A1D187B0C /* FireTopicDetailViewController+Navigation.swift in Sources */, + 747A043BFAD15BA626CB6D8F /* FireTopicDetailViewController+PollVoting.swift in Sources */, + 05B47B0532C0792EB8DD065E /* FireTopicDetailViewController+PostManagement.swift in Sources */, + 2275C0EF78146708B7EEB438 /* FireTopicDetailViewController+QuickReply.swift in Sources */, + 43EE3E937D4EC4F3E5C68D03 /* FireTopicDetailViewController+Reactions.swift in Sources */, + 6C19E1C54E0B3567EA8905F6 /* FireTopicDetailViewController+Routing.swift in Sources */, + 3AB87130FBC77FFBEB228A60 /* FireTopicDetailViewController+SnapshotApplication.swift in Sources */, + 5A7DF5CE0E54BEA77F4687C0 /* FireTopicDetailViewController+StateProjection.swift in Sources */, + 71EC481DB8E6004445FF65B6 /* FireTopicDetailViewController+TopicVoting.swift in Sources */, 0964DB91A22F07DD40FE1ADA /* FireTopicDetailViewController.swift in Sources */, C8C0449611CDEF356A42A487 /* FireTopicDetailVisibilityCoordinator.swift in Sources */, 27D3B7AADEF91C6DE3B41618 /* FireTopicEditorView.swift in Sources */, + F5B39F3B49CA790F67C4AF9D /* FireTopicFormatting.swift in Sources */, B80E44034285312AABCD80A0 /* FireTopicImagePipeline.swift in Sources */, + 5C044A9555F54C391D5E87AE /* FireTopicImageViewer.swift in Sources */, 69FCB7426098CEDD059BB09A /* FireTopicInteractionService.swift in Sources */, 9A14649AEF38A8229DF6B1FF /* FireTopicListAvatarView.swift in Sources */, 14B48EF9BD6DF454DF9E3279 /* FireTopicListChips.swift in Sources */, @@ -2052,16 +2815,31 @@ C6B79691FF3C1680A14C9367 /* FireTopicListToastView.swift in Sources */, FC414F09420A2C1885EFF6C8 /* FireTopicListTopicCell.swift in Sources */, B16BF4995837FCDDEEE90987 /* FireTopicOneboxNode.swift in Sources */, + B8CF8DA3AEBD7AF33055FB36 /* FireTopicPhotoBrowserController.swift in Sources */, + 7C9D4BF48D243FE6CD356AF7 /* FireTopicPostMerge.swift in Sources */, 83C439B40A75418E1406961F /* FireTopicPresentation.swift in Sources */, 2E24DA3BD96C8B64D78FFA5D /* FireTopicQuickReplyBarNode.swift in Sources */, + 06CFAD44C21F19A9DEB208CB /* FireTopicQuickReplyBarView+Appearance.swift in Sources */, + F20DC7DCF067D604DAE1E937 /* FireTopicQuickReplyBarView+Callbacks.swift in Sources */, + ABCA883366F517BBFEF2E517 /* FireTopicQuickReplyBarView+Layout.swift in Sources */, + 2F05FE50B8D1ACFA328C43F5 /* FireTopicReactionPresentation.swift in Sources */, + 4B1CDDE39E22C2F79F185853 /* FireTopicRenderModels.swift in Sources */, + 1F9866CE1C15EFB0C30235B9 /* FireTopicRenderProjection.swift in Sources */, + 56B96EA0F1E94CC1966EE8BA /* FireTopicReplyPresentation.swift in Sources */, C6D4775AD6FB33FB87BCC6B4 /* FireTopicRoutePresenter.swift in Sources */, DBCF9ADF03DFCE13241D06DF /* FireTopicSearchBar.swift in Sources */, + 2E7A30421594539CBAB161C3 /* FireTopicSearchPresentation.swift in Sources */, + FB26BC73921DFA1E7AE837FE /* FireTopicTimelineBuilder.swift in Sources */, + 181686B35A7139284A2858D4 /* FireTopicTimelineModels.swift in Sources */, C1695FEABEA1A67BA6770CD5 /* FireTopicTimingTracker.swift in Sources */, + 690169D8E9B68469C21A7484 /* FireTopicUserInfoSheet.swift in Sources */, + C211E1C7C68F2B041C1CB171 /* FireTopicVotersSheet.swift in Sources */, 5EB4B72F5561D4340D0B82B1 /* FireUIKitDesignLanguage.swift in Sources */, E000C5E75601AB4E99B92D63 /* FireUIKitEmptyStateView.swift in Sources */, 37307D1D50D8438CE90EDE9A /* FireUIKitErrorBannerView.swift in Sources */, F4E23711C352DB67C48DDEDA /* FireUIKitSkeleton.swift in Sources */, 6F1F11DDA954EBFD146D0DB2 /* FireUIKitToast.swift in Sources */, + 3C61095A5DDBDEDD25D31D23 /* Generated/FireUniFfi in Sources */, 025A7AA228A13732EF43828B /* FireUserCardViewController.swift in Sources */, A2F884CB6FB920BCEA213B94 /* FireViewProfileIntent.swift in Sources */, 19548BBFB9955554D178906B /* FireViewUnreadIntent.swift in Sources */, @@ -2070,18 +2848,10 @@ 1F1EEDCE0B4FEAE2880DC061 /* FireWebViewLoginCoordinator.swift in Sources */, 0829CF9A9EE33EA119F94468 /* FireWidgetData.swift in Sources */, 7A7A14663C8D777827CA6768 /* FireWidgetSnapshotWriter.swift in Sources */, + 31281614A8A4C6C7E24B1A45 /* FlowLayout.swift in Sources */, 7A1883792B3FD63EAEAA8336 /* SessionState+Helpers.swift in Sources */, - 4F762CD9E7B43DB0534791C8 /* fire_uniffi.swift in Sources */, - A04F6299B25D5CC6C7D21B14 /* fire_uniffi_chat.swift in Sources */, - F53E86700CE39C9DD948CFF6 /* fire_uniffi_diagnostics.swift in Sources */, - 79B77A4E828C4862BE1BAA53 /* fire_uniffi_ldc.swift in Sources */, - 974A21358F0BAA6942E6FDFC /* fire_uniffi_messagebus.swift in Sources */, - A37D27214981E5D36E7DFD2C /* fire_uniffi_notifications.swift in Sources */, - BD294B1545CC5167CAB3620E /* fire_uniffi_search.swift in Sources */, - 7C8E2507194A4B1C79F2BF4B /* fire_uniffi_session.swift in Sources */, - 26E51A13E796BFEF885FBD28 /* fire_uniffi_topics.swift in Sources */, - 800930BED241B0CF61E5FD0A /* fire_uniffi_types.swift in Sources */, - 3AFFAE192ADFE0FE4E054809 /* fire_uniffi_user.swift in Sources */, + 44857471ECBD28DFC533CEE7 /* String+FireIfEmpty.swift in Sources */, + 6878A9CBCFD675E54F884A22 /* UIView+FireHierarchy.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/apps/ios-app/README.md b/apps/ios-app/README.md index df9f75c9..bdc9cc87 100644 --- a/apps/ios-app/README.md +++ b/apps/ios-app/README.md @@ -367,7 +367,7 @@ Release artifact note: - `./scripts/ios/archive_release.sh` prepares Release UniFFI generated sources for `iphoneos` before running XcodeGen, because the generated Swift files must exist before the optional `Generated/FireUniFfi` source group is written into `Fire.xcodeproj`. - `just ios-release-info`, `just ios-release-tag`, `just ios-testflight-dry-run`, and `just ios-testflight-upload` are the local release helpers for coordinating version/build/tag and workflow dispatch. - The TestFlight lane requires App Store Connect API key secrets and an Apple team id. Optional certificate/profile secrets can install explicit signing assets on GitHub runners; local machines should keep signing overrides in ignored `Fire-Local-Release.xcconfig`. -- The full production release contract lives in `docs/architecture/ios-testflight-release.md`. +- The full production release contract lives in `docs/release/testflight-setup.md`. Current build note: diff --git a/apps/ios-app/Sources/FireAppSession/FireCapturedLoginState.swift b/apps/ios-app/Sources/FireAppSession/FireCapturedLoginState.swift new file mode 100644 index 00000000..af62c147 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireCapturedLoginState.swift @@ -0,0 +1,26 @@ +import Foundation + +public struct FireCapturedLoginState: Sendable, Equatable { + public let currentURL: String? + public let username: String? + public let csrfToken: String? + public let homeHTML: String? + public let browserUserAgent: String? + public let cookies: [PlatformCookieState] + + public init( + currentURL: String?, + username: String?, + csrfToken: String?, + homeHTML: String?, + browserUserAgent: String?, + cookies: [PlatformCookieState] + ) { + self.currentURL = currentURL + self.username = username + self.csrfToken = csrfToken + self.homeHTML = homeHTML + self.browserUserAgent = browserUserAgent + self.cookies = cookies + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireHostLogger.swift b/apps/ios-app/Sources/FireAppSession/FireHostLogger.swift new file mode 100644 index 00000000..4d52db63 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireHostLogger.swift @@ -0,0 +1,34 @@ +import Foundation + +public struct FireHostLogger: Sendable { + private let target: String + private let writeEntry: @Sendable (HostLogLevelState, String, String) -> Void + + init( + target: String, + writeEntry: @escaping @Sendable (HostLogLevelState, String, String) -> Void + ) { + self.target = target + self.writeEntry = writeEntry + } + + public func debug(_ message: @autoclosure () -> String) { + writeEntry(.debug, target, message()) + } + + public func info(_ message: @autoclosure () -> String) { + writeEntry(.info, target, message()) + } + + public func notice(_ message: @autoclosure () -> String) { + writeEntry(.info, target, message()) + } + + public func warning(_ message: @autoclosure () -> String) { + writeEntry(.warn, target, message()) + } + + public func error(_ message: @autoclosure () -> String) { + writeEntry(.error, target, message()) + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Authentication.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Authentication.swift new file mode 100644 index 00000000..b13d4827 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Authentication.swift @@ -0,0 +1,121 @@ +import Foundation + +extension FireSessionStore { + public func determineLoginState() -> LoginStateDeterminationState { + (try? core.session().determineLoginState()) ?? .notLoggedIn + } + + public func determineLoginStateWithProbe() async throws -> LoginStateDeterminationState { + let state = try await core.session().determineLoginStateWithProbe() + try persistCurrentSessionIfNeeded() + return state + } + + public func loadSavedCredential() throws -> FireSavedCredential? { + try authCookieStore.loadCredential() + } + + public func saveLoginCredential(username: String, password: String) throws { + guard let credential = FireSavedCredential(username: username, password: password) else { + return + } + try authCookieStore.saveCredential(credential) + } + + public func clearSavedCredential() throws { + try authCookieStore.clearCredential() + } + + public func loadLastLoginMethod() throws -> FireLastLoginMethod? { + try authCookieStore.loadLastLoginMethod() + } + + public func saveLastLoginMethod(_ method: FireLastLoginMethod) throws { + try authCookieStore.saveLastLoginMethod(method) + } + + public func clearLastLoginMethod() throws { + try authCookieStore.clearLastLoginMethod() + } + + public func recordFingerprintDone() { + core.session().recordFingerprintDone() + } + + @discardableResult + public func finalizeLoginFromWebView( + _ captured: FireCapturedLoginState, + allowLowConfidenceSessionCookies: Bool = false + ) throws -> LoginFinalizationResultState { + let result = try core.session().finalizeLoginFromWebview( + username: captured.username ?? "", + csrfToken: captured.csrfToken, + rawPreloadedHtml: captured.homeHTML, + browserUserAgent: captured.browserUserAgent, + cookies: captured.cookies, + allowLowConfidenceSessionCookies: allowLowConfidenceSessionCookies + ) + try persistCurrentSessionIfNeeded() + return result + } + + public func cloudflareClearanceIsTrusted() throws -> Bool { + try core.session().cloudflareClearanceIsTrusted() + } + + public func noteCloudflareClearanceRejected() throws { + try core.session().noteCloudflareClearanceRejected() + } + + public func finalizeLoginReady() async throws -> SessionState { + let state = try await core.session().finalizeLoginReady() + try persistCurrentSessionIfNeeded() + return state + } + + public func classifyWebViewLoginResult( + _ result: WebViewLoginJsResultState + ) throws -> WebViewLoginDecisionState { + try core.session().classifyWebviewLoginResult(result: result) + } + + @discardableResult + public func completeCloudflareChallenge( + cookies: [PlatformCookieState], + freshCfClearance: String?, + browserUserAgent: String? + ) throws -> SessionState { + let state = try core.session().completeCloudflareChallenge( + cookies: cookies, + freshCfClearance: { + let trimmed = freshCfClearance?.trimmingCharacters(in: .whitespacesAndNewlines) + return (trimmed?.isEmpty == false) ? trimmed : nil + }(), + browserUserAgent: browserUserAgent + ) + try persistCurrentSessionIfNeeded() + return state + } + + @discardableResult + public func logoutLocal(preserveCfClearance: Bool = true) throws -> SessionState { + let state = try core.session().logoutLocal(preserveCfClearance: preserveCfClearance) + try authCookieStore.clear(preserveCfClearance: preserveCfClearance) + try persistCurrentSessionIfNeeded() + return state + } + + @discardableResult + public func logout() async throws -> SessionState { + let current = try core.session().snapshot() + if current.readiness.canReadAuthenticatedApi && !current.readiness.hasCurrentUser { + _ = try await refreshBootstrapIfNeeded() + } + let state = try await core.session().logoutRemote(preserveCfClearance: true) + try authCookieStore.save(FireAuthCookieSecrets(cookieState: state.cookies)) + let persistenceState = try currentSessionPersistenceState() + lastPersistedAuthCookieRevision = persistenceState.authCookieRevision + try clearPersistedSession() + return state + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Bootstrap.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Bootstrap.swift new file mode 100644 index 00000000..e92258a3 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Bootstrap.swift @@ -0,0 +1,59 @@ +import Foundation + +extension FireSessionStore { + public func ensurePreloadedDataLoaded() async throws { + try await core.session().ensurePreloadedDataLoaded() + try persistCurrentSessionIfNeeded() + } + + public func awaitPreloadedData() async throws -> PreloadedDataStateState { + let state = try await core.session().awaitPreloadedData() + try persistCurrentSessionIfNeeded() + return state + } + + public func currentUserDefaults() -> CurrentUserSnapshotState? { + try? core.session().currentUserSnapshot() + } + + public func cachedUser() -> CurrentUserSnapshotState? { + try? core.session().cachedUser() + } + + public func triggerAppStateRefresh(_ trigger: RefreshTriggerState) async throws { + try await core.session().triggerAppStateRefresh(trigger: trigger) + try persistCurrentSessionIfNeeded() + } + + public func triggerAppStateRefresh( + _ trigger: RefreshTriggerState, + handler: any AppStateRefreshHandler + ) async throws { + try await core.session().triggerAppStateRefreshWithHandler( + trigger: trigger, + handler: handler + ) + try persistCurrentSessionIfNeeded() + } + + @discardableResult + public func refreshBootstrapIfNeeded() async throws -> SessionState { + let refreshed = try await core.session().refreshBootstrapIfNeeded() + try persistCurrentSessionIfNeeded() + return refreshed + } + + @discardableResult + public func refreshCsrfTokenIfNeeded() async throws -> SessionState { + let refreshed = try await core.session().refreshCsrfTokenIfNeeded() + try persistCurrentSessionIfNeeded() + return refreshed + } + + @discardableResult + public func refreshBootstrap() async throws -> SessionState { + let refreshed = try await core.session().refreshBootstrap() + try persistCurrentSessionIfNeeded() + return refreshed + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Chat.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Chat.swift new file mode 100644 index 00000000..01d4a471 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Chat.swift @@ -0,0 +1,204 @@ +import Foundation + +extension FireSessionStore { + public func fetchMyChatChannels() async throws -> MyChatChannelsState { + try await runPersistingSessionChanges { + try await core.chat().fetchMyChatChannels() + } + } + + public func cachedMyChatChannels() throws -> MyChatChannelsState? { + try core.chat().cachedMyChatChannels() + } + + public func cachedChatMessages(channelID: UInt64, threadID: UInt64?) throws -> ChatMessagesState? { + try core.chat().cachedChatMessages(channelId: channelID, threadId: threadID) + } + + public func fetchChatChannel(channelID: UInt64) async throws -> ChatChannelState { + try await runPersistingSessionChanges { + try await core.chat().fetchChatChannel(channelId: channelID) + } + } + + public func createDirectMessageChannel( + request: CreateDirectMessageChannelRequestState + ) async throws -> ChatChannelState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().createDirectMessageChannel(request: request) + } + } + + public func fetchChatMessages(query: ChatMessagesQueryState) async throws -> ChatMessagesState { + try await runPersistingSessionChanges { + try await core.chat().fetchChatMessages(query: query) + } + } + + public func sendChatMessage( + request: SendChatMessageRequestState + ) async throws -> SendChatMessageResultState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().sendChatMessage(request: request) + } + } + + public func markChatChannelRead(channelID: UInt64, messageID: UInt64? = nil) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().markChatChannelRead(channelId: channelID, messageId: messageID) + } + } + + public func browseChatChannels( + query: BrowseChatChannelsQueryState + ) async throws -> [ChatChannelState] { + try await runPersistingSessionChanges { + try await core.chat().browseChatChannels(query: query) + } + } + + public func joinChatChannel(channelID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().joinChatChannel(channelId: channelID) + } + } + + public func leaveChatChannel(channelID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().leaveChatChannel(channelId: channelID) + } + } + + public func starChatChannel(channelID: UInt64, starred: Bool) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().starChatChannel(channelId: channelID, starred: starred) + } + } + + public func updateChatChannelNotifications( + channelID: UInt64, + muted: Bool? = nil, + notificationLevel: String? = nil + ) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().updateChatChannelNotifications( + channelId: channelID, + muted: muted, + notificationLevel: notificationLevel + ) + } + } + + public func editChatMessage( + channelID: UInt64, + messageID: UInt64, + message: String, + uploadIDs: [UInt64]? = nil + ) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().editChatMessage( + channelId: channelID, + messageId: messageID, + message: message, + uploadIds: uploadIDs + ) + } + } + + public func deleteChatMessage(channelID: UInt64, messageID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().deleteChatMessage(channelId: channelID, messageId: messageID) + } + } + + public func reactChatMessage( + channelID: UInt64, + messageID: UInt64, + emoji: String, + reactAction: String + ) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().reactChatMessage( + channelId: channelID, + messageId: messageID, + emoji: emoji, + reactAction: reactAction + ) + } + } + + public func fetchChatChannelMembers( + channelID: UInt64, + offset: UInt32? = nil, + limit: UInt32? = nil, + username: String? = nil + ) async throws -> [ChatChannelMemberState] { + try await runPersistingSessionChanges { + try await core.chat().fetchChatChannelMembers( + channelId: channelID, + offset: offset, + limit: limit, + username: username + ) + } + } + + public func searchChatMessages(query: ChatSearchQueryState) async throws -> ChatSearchResultState { + try await runPersistingSessionChanges { + try await core.chat().searchChatMessages(query: query) + } + } + + public func fetchChatChannelPins(channelID: UInt64) async throws -> [ChatMessageState] { + try await runPersistingSessionChanges { + try await core.chat().fetchChatChannelPins(channelId: channelID) + } + } + + public func pinChatMessage(channelID: UInt64, messageID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().pinChatMessage(channelId: channelID, messageId: messageID) + } + } + + public func unpinChatMessage(channelID: UInt64, messageID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().unpinChatMessage(channelId: channelID, messageId: messageID) + } + } + + public func markChatChannelPinsRead(channelID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().markChatChannelPinsRead(channelId: channelID) + } + } + + public func createChatThread(channelID: UInt64, originalMessageID: UInt64) async throws -> UInt64 { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().createChatThread( + channelId: channelID, + originalMessageId: originalMessageID + ) + } + } + + public func fetchChatThreadMessages( + channelID: UInt64, + threadID: UInt64, + query: ChatMessagesQueryState + ) async throws -> ChatMessagesState { + try await runPersistingSessionChanges { + try await core.chat().fetchChatThreadMessages( + channelId: channelID, + threadId: threadID, + query: query + ) + } + } + + public func markChatThreadRead(channelID: UInt64, threadID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.chat().markChatThreadRead(channelId: channelID, threadId: threadID) + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Composer.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Composer.swift new file mode 100644 index 00000000..cd2b3328 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Composer.swift @@ -0,0 +1,155 @@ +import Foundation + +extension FireSessionStore { + public func fetchDrafts( + offset: UInt32? = nil, + limit: UInt32? = nil + ) async throws -> DraftListResponseState { + try await runPersistingSessionChanges { + try await core.notifications().fetchDrafts(offset: offset, limit: limit) + } + } + + public func fetchDraft(draftKey: String) async throws -> DraftState? { + try await runPersistingSessionChanges { + try await core.notifications().fetchDraft(draftKey: draftKey) + } + } + + public func saveDraft( + draftKey: String, + data: DraftDataState, + sequence: UInt32 + ) async throws -> UInt32 { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.notifications().saveDraft(draftKey: draftKey, data: data, sequence: sequence) + } + } + + public func deleteDraft( + draftKey: String, + sequence: UInt32? = nil + ) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.notifications().deleteDraft(draftKey: draftKey, sequence: sequence) + } + } + + public func createReply( + topicID: UInt64, + raw: String, + replyToPostNumber: UInt32? + ) async throws -> TopicPostState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().createReply( + input: TopicReplyRequestState( + topicId: topicID, + raw: raw, + replyToPostNumber: replyToPostNumber + ) + ) + } + } + + public func updatePost( + postID: UInt64, + raw: String, + editReason: String? = nil + ) async throws -> TopicPostState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().updatePost( + input: PostUpdateRequestState( + postId: postID, + raw: raw, + editReason: editReason + ) + ) + } + } + + public func deletePost(postID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().deletePost(postId: postID) + } + } + + public func recoverPost(postID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().recoverPost(postId: postID) + } + } + + public func createTopic( + title: String, + raw: String, + categoryID: UInt64, + tags: [String] + ) async throws -> UInt64 { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().createTopic( + input: TopicCreateRequestState( + title: title, + raw: raw, + categoryId: categoryID, + tags: tags + ) + ) + } + } + + public func createPrivateMessage( + title: String, + raw: String, + targetRecipients: [String] + ) async throws -> UInt64 { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().createPrivateMessage( + input: PrivateMessageCreateRequestState( + title: title, + raw: raw, + targetRecipients: targetRecipients + ) + ) + } + } + + public func updateTopic( + topicID: UInt64, + title: String, + categoryID: UInt64, + tags: [String] + ) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().updateTopic( + input: TopicUpdateRequestState( + topicId: topicID, + title: title, + categoryId: categoryID, + tags: tags + ) + ) + } + } + + public func uploadImage( + fileName: String, + mimeType: String?, + bytes: Data + ) async throws -> UploadResultState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().uploadImage( + input: UploadImageRequestState( + fileName: fileName, + mimeType: mimeType, + bytes: bytes + ) + ) + } + } + + public func lookupUploadUrls(shortUrls: [String]) async throws -> [ResolvedUploadUrlState] { + try await runPersistingSessionChanges { + try await core.topics().lookupUploadUrls(shortUrls: shortUrls) + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Cookies.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Cookies.swift new file mode 100644 index 00000000..64a904c8 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Cookies.swift @@ -0,0 +1,86 @@ +import Foundation + +extension FireSessionStore { + public func cookieReplayQueue() throws -> [CookieReplayEntryState] { + try core.session().cookieReplayQueue() + } + + public func clearCookieReplayQueue() throws { + try core.session().clearCookieReplayQueue() + } + + @discardableResult + public func mergePlatformCookies(_ cookies: [PlatformCookieState]) throws -> SessionState { + let state = try core.session().mergePlatformCookies(cookies: cookies) + try persistCurrentSessionIfNeeded() + return state + } + + public func webViewPrimingPayload( + targetURL: String? = nil + ) throws -> [WebViewCookieActionState] { + try core.session().webviewPrimingPayload(targetUrl: targetURL) + } + + public func cookieSweepPlan( + targetURL: String? = nil, + name: String, + webViewCookies: [WebViewCookieInfoState] + ) throws -> CookieSweepPlanState { + try core.session().cookieSweepPlan( + targetUrl: targetURL, + name: name, + webviewCookies: webViewCookies + ) + } + + public func cookieNuclearResetPlan( + targetURL: String? = nil, + webViewCookies: [WebViewCookieInfoState] + ) throws -> NuclearResetPlanState { + try core.session().cookieNuclearResetPlan( + targetUrl: targetURL, + webviewCookies: webViewCookies + ) + } + + @discardableResult + public func commitCookieSweepResult( + targetURL: String? = nil, + name: String, + intent: CookieSweepIntentState, + webViewCookies: [WebViewCookieInfoState] + ) throws -> SessionState { + let state = try core.session().commitCookieSweepResult( + targetUrl: targetURL, + name: name, + intent: intent, + webviewCookies: webViewCookies + ) + try persistCurrentSessionIfNeeded() + return state + } + + @discardableResult + public func syncLoginContext(_ captured: FireCapturedLoginState) throws -> SessionState { + let state = try core.session().syncLoginContext( + context: LoginSyncState( + currentUrl: captured.currentURL, + username: captured.username, + csrfToken: captured.csrfToken, + homeHtml: captured.homeHTML, + browserUserAgent: captured.browserUserAgent, + cookies: captured.cookies + ) + ) + try persistCurrentSessionIfNeeded() + return state + } + + @discardableResult + public func applyPlatformCookies(_ cookies: [PlatformCookieState]) throws -> SessionState { + let state = try core.session().applyPlatformCookies(cookies: cookies) + try persistCurrentSessionIfNeeded() + return state + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Diagnostics.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Diagnostics.swift new file mode 100644 index 00000000..bb198635 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Diagnostics.swift @@ -0,0 +1,146 @@ +import Foundation + +extension FireSessionStore { + public func listLogFiles() async throws -> [LogFileSummaryState] { + let core = self.core + let diagnosticsQueue = self.diagnosticsQueue + return try await withCheckedThrowingContinuation { continuation in + diagnosticsQueue.async { + continuation.resume(with: Result { try core.diagnostics().listLogFiles() }) + } + } + } + + public func readLogFile(relativePath: String) async throws -> LogFileDetailState { + let core = self.core + let diagnosticsQueue = self.diagnosticsQueue + return try await withCheckedThrowingContinuation { continuation in + diagnosticsQueue.async { + continuation.resume(with: Result { try core.diagnostics().readLogFile(relativePath: relativePath) }) + } + } + } + + public func readLogFilePage( + relativePath: String, + cursor: UInt64? = nil, + maxBytes: UInt64? = nil, + direction: DiagnosticsPageDirectionState + ) async throws -> LogFilePageState { + let core = self.core + let diagnosticsQueue = self.diagnosticsQueue + return try await withCheckedThrowingContinuation { continuation in + diagnosticsQueue.async { + continuation.resume( + with: Result { + try core.diagnostics().readLogFilePage( + relativePath: relativePath, + cursor: cursor, + maxBytes: maxBytes, + direction: direction + ) + } + ) + } + } + } + + public func listNetworkTraces(limit: UInt64 = 200) throws -> [NetworkTraceSummaryState] { + try core.diagnostics().listNetworkTraces(limit: limit) + } + + public func networkTraceDetail(traceID: UInt64) throws -> NetworkTraceDetailState? { + try core.diagnostics().networkTraceDetail(traceId: traceID) + } + + public func networkTraceBodyPage( + traceID: UInt64, + cursor: UInt64? = nil, + maxBytes: UInt64? = nil, + direction: DiagnosticsPageDirectionState + ) async throws -> NetworkTraceBodyPageState? { + let core = self.core + let diagnosticsQueue = self.diagnosticsQueue + return try await withCheckedThrowingContinuation { continuation in + diagnosticsQueue.async { + continuation.resume( + with: Result { + try core.diagnostics().networkTraceBodyPage( + traceId: traceID, + cursor: cursor, + maxBytes: maxBytes, + direction: direction + ) + } + ) + } + } + } + + public func diagnosticSessionID() throws -> String { + try core.diagnostics().diagnosticSessionId() + } + + public func exportSupportBundle( + platform: String, + appVersion: String?, + buildNumber: String?, + scenePhase: String? + ) async throws -> SupportBundleExportState { + let core = self.core + let diagnosticsQueue = self.diagnosticsQueue + return try await withCheckedThrowingContinuation { continuation in + diagnosticsQueue.async { + continuation.resume( + with: Result { + try core.diagnostics().exportSupportBundle( + hostContext: SupportBundleHostContextState( + platform: platform, + appVersion: appVersion, + buildNumber: buildNumber, + scenePhase: scenePhase + ) + ) + } + ) + } + } + } + + /// Redacted diagnostics package safe to leave the device (feedback share / upload). + public func exportFeedbackBundle( + platform: String, + appVersion: String?, + buildNumber: String?, + scenePhase: String? + ) async throws -> SupportBundleExportState { + let core = self.core + let diagnosticsQueue = self.diagnosticsQueue + return try await withCheckedThrowingContinuation { continuation in + diagnosticsQueue.async { + continuation.resume( + with: Result { + try core.diagnostics().exportFeedbackBundle( + hostContext: SupportBundleHostContextState( + platform: platform, + appVersion: appVersion, + buildNumber: buildNumber, + scenePhase: scenePhase + ) + ) + } + ) + } + } + } + + public func flushLogs(sync: Bool = true) async throws { + let core = self.core + let diagnosticsQueue = self.diagnosticsQueue + try await withCheckedThrowingContinuation { continuation in + diagnosticsQueue.async { + continuation.resume(with: Result { try core.diagnostics().flushLogs(sync: sync) }) + } + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Doh.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Doh.swift new file mode 100644 index 00000000..96416f20 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Doh.swift @@ -0,0 +1,23 @@ +import Foundation + +extension FireSessionStore { + public func listDohPresets() throws -> [DohPresetState] { + try core.session().listDohPresets() + } + + public func getDohSettings() throws -> DohSettingsState { + try core.session().getDohSettings() + } + + @discardableResult + public func setDohSettings(_ settings: DohSettingsState) throws -> DohSettingsState { + try core.session().setDohSettings(settings: settings) + } + + public func probeDohSettings( + _ settings: DohSettingsState, + host: String? = nil + ) async throws -> DohProbeResultState { + try await core.session().probeDohSettings(settings: settings, host: host) + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+HomeScope.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+HomeScope.swift new file mode 100644 index 00000000..220bdcb8 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+HomeScope.swift @@ -0,0 +1,14 @@ +import Foundation + +extension FireSessionStore { + public func currentHomeTopicListScope() throws -> HomeTopicListScopeState { + try core.session().currentHomeTopicListScope() + } + + @discardableResult + public func setCurrentHomeTopicListScope( + _ scope: HomeTopicListScopeState + ) throws -> HomeTopicListScopeState { + try core.session().setCurrentHomeTopicListScope(scope: scope) + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Interactions.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Interactions.swift new file mode 100644 index 00000000..b65bbc58 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Interactions.swift @@ -0,0 +1,170 @@ +import Foundation + +extension FireSessionStore { + public func fetchBookmarks( + username: String, + page: UInt32? = nil + ) async throws -> TopicListState { + try await runPersistingSessionChanges { + try await core.notifications().fetchBookmarks(username: username, page: page) + } + } + + public func createBoost(postID: UInt64, raw: String) async throws -> TopicPostBoostState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().createBoost(postId: postID, raw: raw) + } + } + + public func deleteBoost(boostID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().deleteBoost(boostId: boostID) + } + } + + public func flagPost( + postID: UInt64, + flagTypeID: UInt32, + message: String? = nil + ) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().flagPost( + input: PostFlagRequestState( + postId: postID, + flagTypeId: flagTypeID, + message: message + ) + ) + } + } + + public func fetchPostActionTypes() async throws -> [PostActionTypeState] { + try await runPersistingSessionChanges { + try await core.topics().fetchPostActionTypes() + } + } + + public func reportTopicTimings( + input: TopicTimingsRequestState + ) async throws -> Bool { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().reportTopicTimings(input: input) + } + } + + public func likePost(postID: UInt64) async throws -> PostReactionUpdateState? { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().likePost(postId: postID) + } + } + + public func unlikePost(postID: UInt64) async throws -> PostReactionUpdateState? { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().unlikePost(postId: postID) + } + } + + public func togglePostReaction( + postID: UInt64, + reactionID: String + ) async throws -> PostReactionUpdateState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().togglePostReaction(postId: postID, reactionId: reactionID) + } + } + + public func fetchReactionUsers(postID: UInt64) async throws -> [ReactionUsersGroupState] { + try await runPersistingSessionChanges { + try await core.topics().fetchReactionUsers(postId: postID) + } + } + + public func votePoll( + postID: UInt64, + pollName: String, + options: [String] + ) async throws -> PollState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().votePoll(postId: postID, pollName: pollName, options: options) + } + } + + public func unvotePoll( + postID: UInt64, + pollName: String + ) async throws -> PollState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().unvotePoll(postId: postID, pollName: pollName) + } + } + + public func voteTopic(topicID: UInt64) async throws -> VoteResponseState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().voteTopic(topicId: topicID) + } + } + + public func unvoteTopic(topicID: UInt64) async throws -> VoteResponseState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.topics().unvoteTopic(topicId: topicID) + } + } + + public func fetchTopicVoters(topicID: UInt64) async throws -> [VotedUserState] { + try await runPersistingSessionChanges { + try await core.topics().fetchTopicVoters(topicId: topicID) + } + } + + public func createBookmark( + bookmarkableID: UInt64, + bookmarkableType: String, + name: String? = nil, + reminderAt: String? = nil, + autoDeletePreference: Int32? = nil + ) async throws -> UInt64 { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.notifications().createBookmark( + bookmarkableId: bookmarkableID, + bookmarkableType: bookmarkableType, + name: name, + reminderAt: reminderAt, + autoDeletePreference: autoDeletePreference + ) + } + } + + public func updateBookmark( + bookmarkID: UInt64, + name: String? = nil, + reminderAt: String? = nil, + autoDeletePreference: Int32? = nil + ) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.notifications().updateBookmark( + bookmarkId: bookmarkID, + name: name, + reminderAt: reminderAt, + autoDeletePreference: autoDeletePreference + ) + } + } + + public func deleteBookmark(bookmarkID: UInt64) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.notifications().deleteBookmark(bookmarkId: bookmarkID) + } + } + + public func setTopicNotificationLevel( + topicID: UInt64, + notificationLevel: Int32 + ) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.notifications().setTopicNotificationLevel( + topicId: topicID, + notificationLevel: notificationLevel + ) + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Ldc.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Ldc.swift new file mode 100644 index 00000000..7cbe9a23 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Ldc.swift @@ -0,0 +1,75 @@ +import Foundation + +extension FireSessionStore { + public func ldcAuthorizationUrl() async throws -> LdcAuthorizationUrlState { + try await runPersistingSessionChanges { + try await core.ldc().ldcAuthorizationUrl() + } + } + + public func ldcApprovalLink(authorizationURL: String) async throws -> String { + try await runPersistingSessionChanges { + try await core.ldc().ldcApprovalLink(authorizationUrl: authorizationURL) + } + } + + public func ldcApprove(approvePath: String) async throws -> LdcApprovalStatusState { + try await runPersistingSessionChanges { + try await core.ldc().ldcApprove(approvePath: approvePath) + } + } + + public func ldcCallback(code: String, state: String) async throws { + try await runPersistingSessionChanges { + try await core.ldc().ldcCallback(code: code, state: state) + } + } + + public func ldcUserInfo() async throws -> LdcUserInfoState { + try await runPersistingSessionChanges { + try await core.ldc().ldcUserInfo() + } + } + + public func ldcLogout() async throws { + try await runPersistingSessionChanges { + try await core.ldc().ldcLogout() + } + } + + public func cdkAuthorizationUrl() async throws -> CdkAuthorizationUrlState { + try await runPersistingSessionChanges { + try await core.ldc().cdkAuthorizationUrl() + } + } + + public func cdkApprovalLink(authorizationURL: String) async throws -> String { + try await runPersistingSessionChanges { + try await core.ldc().cdkApprovalLink(authorizationUrl: authorizationURL) + } + } + + public func cdkApprove(approvePath: String) async throws -> LdcApprovalStatusState { + try await runPersistingSessionChanges { + try await core.ldc().cdkApprove(approvePath: approvePath) + } + } + + public func cdkCallback(code: String, state: String) async throws { + try await runPersistingSessionChanges { + try await core.ldc().cdkCallback(code: code, state: state) + } + } + + public func cdkUserInfo() async throws -> CdkUserInfoState { + try await runPersistingSessionChanges { + try await core.ldc().cdkUserInfo() + } + } + + public func cdkLogout() async throws { + try await runPersistingSessionChanges { + try await core.ldc().cdkLogout() + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Lifecycle.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Lifecycle.swift new file mode 100644 index 00000000..102eef14 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Lifecycle.swift @@ -0,0 +1,185 @@ +import Foundation + +extension FireSessionStore { + public func completeReadPathLogin(generation: UInt64, succeeded: Bool) throws { + try core.session().completeReadPathLogin(generation: generation, succeeded: succeeded) + } + + /// Topic-detail session open/cancel/close only touch UniFFI/`core` and must stay + /// callable from `@MainActor` hosts without hopping onto the session actor. + public func restorePersistedSessionIfAvailable() throws -> SessionState? { + guard FileManager.default.fileExists(atPath: sessionFilePath) else { + return nil + } + let state = try core.session().loadSessionFromPath(path: sessionFilePath) + let persistenceState = try currentSessionPersistenceState() + lastPersistedSnapshotRevision = persistenceState.snapshotRevision + return state + } + + @discardableResult + public func prepareStartupSession() async throws -> SessionState { + try await restoreColdStartSession() + } + + @discardableResult + public func restoreColdStartSession() async throws -> SessionState { + try await restoreColdStartSession( + refreshBootstrapIfNeeded: { + try await self.refreshBootstrapIfNeeded() + }, + refreshBootstrapDuringRestore: false + ) + } + + @discardableResult + func restoreColdStartSession( + refreshBootstrapIfNeeded: () async throws -> SessionState, + refreshBootstrapDuringRestore: Bool = false + ) async throws -> SessionState { + _ = try restorePersistedSessionIfAvailable() + let secureSecrets = try authCookieStore.load() + + if !secureSecrets.isEmpty { + _ = try applyPlatformCookies(secureSecrets.platformCookies(baseURL: baseURL)) + } + + let current = try core.session().snapshot() + if !current.readiness.canReadAuthenticatedApi && shouldDiscardRestoredBootstrap(current) { + logHost( + level: .warn, + target: "session.cold_start", + message: "Cold-start session has valid user bootstrap but platform cookies are missing/expired. Preserving session to allow recovery." + ) + } + + guard refreshBootstrapDuringRestore else { + return current + } + + return try await refreshBootstrapIfNeeded() + } + + public func persistCurrentSession() throws { + try persistCurrentSession(force: true) + } + + func persistCurrentSessionIfNeeded() throws { + try persistCurrentSession(force: false) + } + + private func persistCurrentSession(force: Bool) throws { + let persistenceState = try currentSessionPersistenceState() + try persistCurrentAuthCookies(persistenceState: persistenceState, force: force) + try persistSessionFile(persistenceState: persistenceState, force: force) + } + + public func exportSessionJSON() throws -> String { + try core.session().exportSessionJson() + } + + public func clearPersistedSession() throws { + try core.session().clearSessionPath(path: sessionFilePath) + lastPersistedSnapshotRevision = 0 + } + + public static func defaultWorkspacePath(fileManager: FileManager = .default) throws -> String { + guard let directory = try fileManager.url( + for: .applicationSupportDirectory, + in: .userDomainMask, + appropriateFor: nil, + create: true + ) as URL? else { + throw FireSessionStoreError.missingApplicationSupportDirectory + } + + let fireDirectory = directory.appendingPathComponent("Fire", isDirectory: true) + try fileManager.createDirectory( + at: fireDirectory, + withIntermediateDirectories: true, + attributes: nil + ) + try repairDiagnosticsDirectoryIfNeeded( + workspaceDirectory: fireDirectory, + fileManager: fileManager + ) + return fireDirectory.path + } + + private static func repairDiagnosticsDirectoryIfNeeded( + workspaceDirectory: URL, + fileManager: FileManager + ) throws { + let diagnosticsDirectory = workspaceDirectory.appendingPathComponent( + "diagnostics", + isDirectory: true + ) + let diagnosticsPath = diagnosticsDirectory.path + guard fileManager.fileExists(atPath: diagnosticsPath) else { + return + } + guard fileManager.isWritableFile(atPath: diagnosticsPath) == false else { + return + } + try fileManager.removeItem(at: diagnosticsDirectory) + try fileManager.createDirectory( + at: diagnosticsDirectory, + withIntermediateDirectories: true, + attributes: nil + ) + } + + public static func defaultSessionFilePath(fileManager: FileManager = .default) throws -> String { + let workspacePath = try defaultWorkspacePath(fileManager: fileManager) + return URL(fileURLWithPath: workspacePath) + .appendingPathComponent("session.json", isDirectory: false) + .path + } + + private func shouldDiscardRestoredBootstrap(_ session: SessionState) -> Bool { + session.readiness.hasCurrentUser + || session.readiness.hasPreloadedData + || session.readiness.hasSharedSessionKey + } + + func currentSessionPersistenceState() throws -> SessionPersistenceState { + try core.session().sessionPersistenceState() + } + + private func persistCurrentAuthCookies( + persistenceState: SessionPersistenceState, + force: Bool + ) throws { + guard force || persistenceState.authCookieRevision != lastPersistedAuthCookieRevision else { + return + } + + try authCookieStore.save(FireAuthCookieSecrets(cookieState: try core.session().snapshot().cookies)) + lastPersistedAuthCookieRevision = persistenceState.authCookieRevision + } + + private func persistSessionFile( + persistenceState: SessionPersistenceState, + force: Bool + ) throws { + guard force || persistenceState.snapshotRevision != lastPersistedSnapshotRevision else { + return + } + + try core.session().saveSessionToPath(path: sessionFilePath) + lastPersistedSnapshotRevision = persistenceState.snapshotRevision + } + + public func currentSessionEpoch() throws -> UInt64 { + try core.session().sessionEpoch() + } + + @discardableResult + public func restoreSessionJSON(_ json: String) throws -> SessionState { + let state = try core.session().restoreSessionJson(json: json) + try persistCurrentSessionIfNeeded() + return state + } + + // MARK: - MessageBus +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+MessageBus.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+MessageBus.swift new file mode 100644 index 00000000..a6539c1a --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+MessageBus.swift @@ -0,0 +1,136 @@ +import Foundation + +extension FireSessionStore { + public func stopMessageBus(clearSubscriptions: Bool = false) throws { + try core.messagebus().stopMessageBus(clearSubscriptions: clearSubscriptions) + } + + public func subscribeTopicDetailChannel( + topicId: UInt64, + ownerToken: String, + lastMessageId: Int64? + ) throws { + try core.messagebus().subscribeChannel( + subscription: MessageBusSubscriptionState( + ownerToken: ownerToken, + channel: "/topic/\(topicId)", + lastMessageId: lastMessageId, + scope: .transient + ) + ) + } + + public func unsubscribeTopicDetailChannel(topicId: UInt64, ownerToken: String) throws { + try core.messagebus().unsubscribeChannel(ownerToken: ownerToken, channel: "/topic/\(topicId)") + } + + public func subscribeTopicReactionChannel(topicId: UInt64, ownerToken: String) throws { + try core.messagebus().subscribeChannel( + subscription: MessageBusSubscriptionState( + ownerToken: ownerToken, + channel: "/topic/\(topicId)/reactions", + lastMessageId: nil, + scope: .transient + ) + ) + } + + public func unsubscribeTopicReactionChannel(topicId: UInt64, ownerToken: String) throws { + try core.messagebus().unsubscribeChannel(ownerToken: ownerToken, channel: "/topic/\(topicId)/reactions") + } + + public func subscribeTopicPollsChannel(topicId: UInt64, ownerToken: String) throws { + try core.messagebus().subscribeChannel( + subscription: MessageBusSubscriptionState( + ownerToken: ownerToken, + channel: "/polls/\(topicId)", + lastMessageId: 0, + scope: .transient + ) + ) + } + + public func unsubscribeTopicPollsChannel(topicId: UInt64, ownerToken: String) throws { + try core.messagebus().unsubscribeChannel(ownerToken: ownerToken, channel: "/polls/\(topicId)") + } + + public func subscribeMessageBusChannel( + channel: String, + ownerToken: String, + lastMessageId: Int64?, + scope: MessageBusSubscriptionScopeState = .transient + ) throws { + try core.messagebus().subscribeChannel( + subscription: MessageBusSubscriptionState( + ownerToken: ownerToken, + channel: channel, + lastMessageId: lastMessageId, + scope: scope + ) + ) + } + + public func unsubscribeMessageBusChannel(channel: String, ownerToken: String) throws { + try core.messagebus().unsubscribeChannel(ownerToken: ownerToken, channel: channel) + } + + public func topicReplyPresenceState(topicId: UInt64) throws -> TopicPresenceState { + try core.messagebus().topicReplyPresenceState(topicId: topicId) + } + + public func bootstrapTopicReplyPresence( + topicId: UInt64, + ownerToken: String + ) async throws -> TopicPresenceState { + try await runPersistingSessionChanges { + try await core.messagebus().bootstrapTopicReplyPresence(topicId: topicId, ownerToken: ownerToken) + } + } + + public func unsubscribeTopicReplyPresenceChannel(topicId: UInt64, ownerToken: String) throws { + try core.messagebus().unsubscribeChannel( + ownerToken: ownerToken, + channel: "/presence/discourse-presence/reply/\(topicId)" + ) + } + + public func updateTopicReplyPresence(topicId: UInt64, active: Bool) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.messagebus().updateTopicReplyPresence(topicId: topicId, active: active) + } + } + + // MARK: - Logout + + private func topicTrackingStateMetaForMessageBus() throws -> [String: Int64]? { + let raw = try core.session().snapshot().bootstrap.topicTrackingStateMeta? + .trimmingCharacters(in: .whitespacesAndNewlines) + guard let raw, !raw.isEmpty else { + return nil + } + let data = Data(raw.utf8) + guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { + return nil + } + var result: [String: Int64] = [:] + for (key, value) in object { + if let number = value as? NSNumber { + result[key] = number.int64Value + } else if let text = value as? String, let number = Int64(text) { + result[key] = number + } + } + return result.isEmpty ? nil : result + } + + @discardableResult + public func startMessageBus(handler: any MessageBusEventHandler) async throws -> String { + try await runPersistingSessionChanges { + try await core.messagebus().startMessageBus( + mode: .foreground, + handler: handler, + topicTrackingStateMeta: try topicTrackingStateMetaForMessageBus() + ) + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Notifications.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Notifications.swift new file mode 100644 index 00000000..a3391497 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Notifications.swift @@ -0,0 +1,44 @@ +import Foundation + +extension FireSessionStore { + public func notificationState() throws -> NotificationCenterState { + try core.notifications().notificationState() + } + + public func fetchRecentNotifications(limit: UInt32? = nil) async throws -> NotificationListState { + try await runPersistingSessionChanges { + try await core.notifications().fetchRecentNotifications(limit: limit) + } + } + + public func fetchNotifications( + limit: UInt32? = nil, + offset: UInt32? = nil + ) async throws -> NotificationListState { + try await runPersistingSessionChanges { + try await core.notifications().fetchNotifications(limit: limit, offset: offset) + } + } + + public func markNotificationRead(id: UInt64) async throws -> NotificationCenterState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.notifications().markNotificationRead(notificationId: id) + } + } + + public func markAllNotificationsRead() async throws -> NotificationCenterState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.notifications().markAllNotificationsRead() + } + } + + public func pollNotificationAlertOnce( + lastMessageId: Int64 + ) async throws -> NotificationAlertPollResultState { + try await runPersistingSessionChanges { + try await core.messagebus().pollNotificationAlertOnce(lastMessageId: lastMessageId) + } + } + + // MARK: - Chat +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Observers.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Observers.swift new file mode 100644 index 00000000..0dcf9369 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Observers.swift @@ -0,0 +1,45 @@ +import Foundation + +extension FireSessionStore { + public func registerStateObserver(_ observer: any StateObserver) { + core.registerStateObserver(observer: observer) + } + + public func unregisterStateObserver() { + core.unregisterStateObserver() + } + + public func registerCloudflareChallengeHandler( + _ handler: any CloudflareChallengeHandler + ) throws { + try core.session().registerCloudflareChallengeHandler(handler: handler) + } + + public func unregisterCloudflareChallengeHandler() throws { + try core.session().unregisterCloudflareChallengeHandler() + } + + public func registerCloudflareClearanceResolvedHandler( + _ handler: any CloudflareClearanceResolvedHandler + ) throws { + try core.session().registerCloudflareClearanceResolvedHandler(handler: handler) + } + + public func unregisterCloudflareClearanceResolvedHandler() throws { + try core.session().unregisterCloudflareClearanceResolvedHandler() + } + + public func cloudflareClearanceResolvedGeneration() throws -> UInt64 { + try core.session().cloudflareClearanceResolvedGeneration() + } + + public func registerCookieSelfHealingHandler( + _ handler: any CookieSelfHealingHandler + ) throws { + try core.session().registerCookieSelfHealingHandler(handler: handler) + } + + public func unregisterCookieSelfHealingHandler() throws { + try core.session().unregisterCookieSelfHealingHandler() + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Profiles.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Profiles.swift new file mode 100644 index 00000000..851ca42e --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Profiles.swift @@ -0,0 +1,79 @@ +import Foundation + +extension FireSessionStore { + public func fetchUserProfile(username: String) async throws -> UserProfileState { + try await runPersistingSessionChanges { + try await core.user().fetchUserProfile(username: username) + } + } + + public func fetchUserSummary(username: String) async throws -> UserSummaryState { + try await runPersistingSessionChanges { + try await core.user().fetchUserSummary(username: username) + } + } + + public func fetchUserActions( + username: String, + offset: UInt32?, + filter: String? + ) async throws -> [UserActionState] { + try await runPersistingSessionChanges { + try await core.user().fetchUserActions(username: username, offset: offset, filter: filter) + } + } + + public func fetchFollowing(username: String) async throws -> [FollowUserState] { + try await runPersistingSessionChanges { + try await core.user().fetchFollowing(username: username) + } + } + + public func fetchFollowers(username: String) async throws -> [FollowUserState] { + try await runPersistingSessionChanges { + try await core.user().fetchFollowers(username: username) + } + } + + public func followUser(username: String) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.user().followUser(username: username) + } + } + + public func unfollowUser(username: String) async throws { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.user().unfollowUser(username: username) + } + } + + public func fetchPendingInvites(username: String) async throws -> [InviteLinkState] { + try await runPersistingSessionChanges { + try await core.user().fetchPendingInvites(username: username) + } + } + + public func createInviteLink( + maxRedemptionsAllowed: UInt32, + expiresAt: String? = nil, + description: String? = nil, + email: String? = nil + ) async throws -> InviteLinkState { + try await runAuthenticatedWritePersistingSessionChanges { + try await core.user().createInviteLink( + input: InviteCreateRequestState( + maxRedemptionsAllowed: maxRedemptionsAllowed, + expiresAt: expiresAt, + description: description, + email: email + ) + ) + } + } + + public func fetchBadgeDetail(badgeID: UInt64) async throws -> BadgeState { + try await runPersistingSessionChanges { + try await core.user().fetchBadgeDetail(badgeId: badgeID) + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Search.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Search.swift new file mode 100644 index 00000000..da5384bb --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Search.swift @@ -0,0 +1,21 @@ +import Foundation + +extension FireSessionStore { + public func search(query: SearchQueryState) async throws -> SearchResultState { + try await runPersistingSessionChanges { + try await core.search().search(query: query) + } + } + + public func searchTags(query: TagSearchQueryState) async throws -> TagSearchResultState { + try await runPersistingSessionChanges { + try await core.search().searchTags(query: query) + } + } + + public func searchUsers(query: UserMentionQueryState) async throws -> UserMentionResultState { + try await runPersistingSessionChanges { + try await core.search().searchUsers(query: query) + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+Topics.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Topics.swift new file mode 100644 index 00000000..fd4f53d8 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+Topics.swift @@ -0,0 +1,84 @@ +import Foundation + +extension FireSessionStore { + public nonisolated func cancelTopicDetailHttp() { + try? core.topics().cancelTopicDetailHttp() + } + + public nonisolated func closeAllTopicDetailSessions() { + try? core.topics().closeAllTopicDetailSessions() + } + + public nonisolated func openTopicDetail( + request: TopicDetailOpenRequestState, + observer: TopicDetailObserver + ) throws -> TopicDetailSessionHandle { + try core.topics().openTopicDetail(request: request, observer: observer) + } + + public func fetchReadHistory(page: UInt32? = nil) async throws -> TopicListState { + try await runPersistingSessionChanges { + try await core.notifications().fetchReadHistory(page: page) + } + } + + public func fetchTopicList(query: TopicListQueryState) async throws -> TopicListState { + try await runPersistingSessionChanges { + try await core.topics().fetchTopicList(query: query) + } + } + + public func fetchTopicList(kind: TopicListKindState) async throws -> TopicListState { + try await fetchTopicList( + query: TopicListQueryState( + kind: kind, + page: nil, + topicIds: [], + order: nil, + ascending: nil, + categorySlug: nil, + categoryId: nil, + parentCategorySlug: nil, + tag: nil, + additionalTags: [], + matchAllTags: false + ) + ) + } + + public func fetchTopicPosts(topicID: UInt64, postIDs: [UInt64]) async throws -> [TopicPostState] { + try await runPersistingSessionChanges { + try await core.topics().fetchTopicPosts(topicId: topicID, postIds: postIDs) + } + } + + public func fetchTopicAiSummary( + topicID: UInt64, + skipAgeCheck: Bool = false + ) async throws -> TopicAiSummaryState? { + try await runPersistingSessionChanges { + try await core.topics().fetchTopicAiSummary( + topicId: topicID, + skipAgeCheck: skipAgeCheck + ) + } + } + + public func fetchPost(postID: UInt64) async throws -> TopicPostState { + try await runPersistingSessionChanges { + try await core.topics().fetchPost(postId: postID) + } + } + + public func fetchPostReplyIds(postID: UInt64) async throws -> [UInt64] { + try await runPersistingSessionChanges { + try await core.topics().fetchPostReplyIds(postId: postID) + } + } + + public func fetchPostReplyHistory(postID: UInt64) async throws -> [TopicPostState] { + try await runPersistingSessionChanges { + try await core.topics().fetchPostReplyHistory(postId: postID) + } + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore+WritePreflight.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore+WritePreflight.swift new file mode 100644 index 00000000..7c904e11 --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore+WritePreflight.swift @@ -0,0 +1,190 @@ +import Foundation + +extension FireSessionStore { + typealias AuthenticatedWriteHostResyncProvider = @MainActor @Sendable () async throws -> [PlatformCookieState]? + + struct AuthenticatedWritePreflightContext: Sendable { + let sessionEpoch: UInt64 + let authRecoveryHint: AuthRecoveryHintState? + } + + func setAuthenticatedWriteHostResyncProvider( + _ provider: AuthenticatedWriteHostResyncProvider? + ) { + authenticatedWriteHostResyncProvider = provider + } + + private func authenticatedWritePreflightContext() throws -> AuthenticatedWritePreflightContext { + AuthenticatedWritePreflightContext( + sessionEpoch: try core.session().sessionEpoch(), + authRecoveryHint: try core.session().authRecoveryHint() + ) + } + + /// Read-side helper: returns the current shared session epoch so callers can + /// detect whether a host cookie resync actually replaced the auth cookies. + private func refreshCsrfTokenForAuthenticatedWritePreflight() async throws -> AuthenticatedWritePreflightContext { + _ = try await refreshCsrfTokenIfNeeded() + return try authenticatedWritePreflightContext() + } + + private func applyPlatformCookiesForAuthenticatedWritePreflight( + _ cookies: [PlatformCookieState] + ) async throws -> AuthenticatedWritePreflightContext { + guard Self.containsActiveAuthCookies(in: cookies) else { + logHost( + level: .info, + target: "session.auth_write_preflight", + message: "Skipping authoritative platform cookie apply because host resync returned partial auth cookies." + ) + return try authenticatedWritePreflightContext() + } + _ = try applyPlatformCookies(cookies) + return try authenticatedWritePreflightContext() + } + + nonisolated private static func containsActiveAuthCookies( + in cookies: [PlatformCookieState] + ) -> Bool { + let activeCookies = cookies.filter { cookie in + let value = cookie.value.trimmingCharacters(in: .whitespacesAndNewlines) + return !value.isEmpty && !(cookie.expiresAtUnixMs.map { $0 <= currentUnixMs() } ?? false) + } + + return activeCookies.contains(where: { $0.name == "_t" }) + && activeCookies.contains(where: { $0.name == "_forum_session" }) + } + + nonisolated private static func currentUnixMs() -> Int64 { + Int64(Date().timeIntervalSince1970 * 1000) + } + + private func runAuthenticatedWritePreflight() async throws { + try await runAuthenticatedWritePreflight( + readContext: { + try await self.authenticatedWritePreflightContext() + }, + refreshCsrfTokenIfNeeded: { + try await self.refreshCsrfTokenForAuthenticatedWritePreflight() + }, + applyPlatformCookies: { cookies in + try await self.applyPlatformCookiesForAuthenticatedWritePreflight(cookies) + }, + hostResyncProvider: authenticatedWriteHostResyncProvider + ) + } + + func runAuthenticatedWritePreflight( + readContext: @escaping @Sendable () async throws -> AuthenticatedWritePreflightContext, + refreshCsrfTokenIfNeeded: @escaping @Sendable () async throws -> AuthenticatedWritePreflightContext, + applyPlatformCookies: @escaping @Sendable ([PlatformCookieState]) async throws -> AuthenticatedWritePreflightContext, + hostResyncProvider: AuthenticatedWriteHostResyncProvider? + ) async throws { + let initialContext = try await readContext() + let refreshedContext = try await refreshCsrfTokenIfNeeded() + + guard + let recoveryHint = initialContext.authRecoveryHint, + recoveryHint.observedEpoch == initialContext.sessionEpoch, + refreshedContext.sessionEpoch == initialContext.sessionEpoch, + let refreshedHint = refreshedContext.authRecoveryHint, + refreshedHint.observedEpoch == initialContext.sessionEpoch + else { + return + } + + guard let hostResyncProvider else { + return + } + + await runAuthenticatedWriteHostResyncIfNeeded( + for: initialContext.sessionEpoch, + readContext: readContext, + applyPlatformCookies: applyPlatformCookies, + hostResyncProvider: hostResyncProvider + ) + _ = try await refreshCsrfTokenIfNeeded() + } + + private func runAuthenticatedWriteHostResyncIfNeeded( + for sessionEpoch: UInt64, + readContext: @escaping @Sendable () async throws -> AuthenticatedWritePreflightContext, + applyPlatformCookies: @escaping @Sendable ([PlatformCookieState]) async throws -> AuthenticatedWritePreflightContext, + hostResyncProvider: @escaping AuthenticatedWriteHostResyncProvider + ) async { + if let existingTask = authenticatedWriteHostResyncTasks[sessionEpoch] { + await existingTask.value + return + } + + guard !authenticatedWriteHostResyncAttemptedEpochs.contains(sessionEpoch) else { + return + } + + authenticatedWriteHostResyncAttemptedEpochs.insert(sessionEpoch) + let task = Task { [self] in + do { + try await executeAuthenticatedWriteHostResync( + for: sessionEpoch, + readContext: readContext, + applyPlatformCookies: applyPlatformCookies, + hostResyncProvider: hostResyncProvider + ) + } catch { + } + clearAuthenticatedWriteHostResyncTask(for: sessionEpoch) + } + authenticatedWriteHostResyncTasks[sessionEpoch] = task + await task.value + } + + private func executeAuthenticatedWriteHostResync( + for sessionEpoch: UInt64, + readContext: @escaping @Sendable () async throws -> AuthenticatedWritePreflightContext, + applyPlatformCookies: @escaping @Sendable ([PlatformCookieState]) async throws -> AuthenticatedWritePreflightContext, + hostResyncProvider: @escaping AuthenticatedWriteHostResyncProvider + ) async throws { + let beforeProviderContext = try await readContext() + guard + beforeProviderContext.sessionEpoch == sessionEpoch, + let recoveryHint = beforeProviderContext.authRecoveryHint, + recoveryHint.observedEpoch == sessionEpoch + else { + return + } + + guard let platformCookies = try await hostResyncProvider(), !platformCookies.isEmpty else { + return + } + + let beforeApplyContext = try await readContext() + guard + beforeApplyContext.sessionEpoch == sessionEpoch, + let recoveryHint = beforeApplyContext.authRecoveryHint, + recoveryHint.observedEpoch == sessionEpoch + else { + return + } + + _ = try await applyPlatformCookies(platformCookies) + } + + private func clearAuthenticatedWriteHostResyncTask(for sessionEpoch: UInt64) { + authenticatedWriteHostResyncTasks.removeValue(forKey: sessionEpoch) + } + + func runAuthenticatedWritePersistingSessionChanges( + _ operation: () async throws -> T + ) async throws -> T { + try await runAuthenticatedWritePreflight() + return try await runPersistingSessionChanges(operation) + } + + func runPersistingSessionChanges( + _ operation: () async throws -> T + ) async throws -> T { + let result = try await operation() + try persistCurrentSessionIfNeeded() + return result + } +} diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStore.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStore.swift index ff3ec6d9..a37fdcf6 100644 --- a/apps/ios-app/Sources/FireAppSession/FireSessionStore.swift +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStore.swift @@ -1,87 +1,18 @@ import Foundation -public enum FireSessionStoreError: Error { - case missingApplicationSupportDirectory -} - -public struct FireCapturedLoginState: Sendable, Equatable { - public let currentURL: String? - public let username: String? - public let csrfToken: String? - public let homeHTML: String? - public let browserUserAgent: String? - public let cookies: [PlatformCookieState] - - public init( - currentURL: String?, - username: String?, - csrfToken: String?, - homeHTML: String?, - browserUserAgent: String?, - cookies: [PlatformCookieState] - ) { - self.currentURL = currentURL - self.username = username - self.csrfToken = csrfToken - self.homeHTML = homeHTML - self.browserUserAgent = browserUserAgent - self.cookies = cookies - } -} - -public struct FireHostLogger: Sendable { - private let target: String - private let writeEntry: @Sendable (HostLogLevelState, String, String) -> Void - - fileprivate init( - target: String, - writeEntry: @escaping @Sendable (HostLogLevelState, String, String) -> Void - ) { - self.target = target - self.writeEntry = writeEntry - } - - public func debug(_ message: @autoclosure () -> String) { - writeEntry(.debug, target, message()) - } - - public func info(_ message: @autoclosure () -> String) { - writeEntry(.info, target, message()) - } - - public func notice(_ message: @autoclosure () -> String) { - writeEntry(.info, target, message()) - } - - public func warning(_ message: @autoclosure () -> String) { - writeEntry(.warn, target, message()) - } - - public func error(_ message: @autoclosure () -> String) { - writeEntry(.error, target, message()) - } -} - public actor FireSessionStore { - typealias AuthenticatedWriteHostResyncProvider = @MainActor @Sendable () async throws -> [PlatformCookieState]? - - struct AuthenticatedWritePreflightContext: Sendable { - let sessionEpoch: UInt64 - let authRecoveryHint: AuthRecoveryHintState? - } - - nonisolated private let core: FireAppCore - private let baseURL: URL - private let workspacePath: String - private let sessionFilePath: String - private let authCookieStore: any FireAuthCookieSecureStore - private var authenticatedWriteHostResyncProvider: AuthenticatedWriteHostResyncProvider? - private var authenticatedWriteHostResyncTasks: [UInt64: Task] = [:] - private var authenticatedWriteHostResyncAttemptedEpochs: Set = [] - private var lastPersistedSnapshotRevision: UInt64 - private var lastPersistedAuthCookieRevision: UInt64 + nonisolated let core: FireAppCore + let baseURL: URL + let workspacePath: String + let sessionFilePath: String + let authCookieStore: any FireAuthCookieSecureStore + var authenticatedWriteHostResyncProvider: AuthenticatedWriteHostResyncProvider? + var authenticatedWriteHostResyncTasks: [UInt64: Task] = [:] + var authenticatedWriteHostResyncAttemptedEpochs: Set = [] + var lastPersistedSnapshotRevision: UInt64 + var lastPersistedAuthCookieRevision: UInt64 // Keep blocking diagnostics IO off elevated Swift concurrency executors. - private let diagnosticsQueue = DispatchQueue( + let diagnosticsQueue = DispatchQueue( label: "com.fire.session-store.diagnostics", qos: .utility ) @@ -113,424 +44,14 @@ public actor FireSessionStore { self.lastPersistedAuthCookieRevision = persistenceState.authCookieRevision } - public func completeReadPathLogin(generation: UInt64, succeeded: Bool) throws { - try core.session().completeReadPathLogin(generation: generation, succeeded: succeeded) - } - - /// Topic-detail session open/cancel/close only touch UniFFI/`core` and must stay - /// callable from `@MainActor` hosts without hopping onto the session actor. - public nonisolated func cancelTopicDetailHttp() { - try? core.topics().cancelTopicDetailHttp() - } - - public nonisolated func closeAllTopicDetailSessions() { - try? core.topics().closeAllTopicDetailSessions() - } - - public nonisolated func openTopicDetail( - request: TopicDetailOpenRequestState, - observer: TopicDetailObserver - ) throws -> TopicDetailSessionHandle { - try core.topics().openTopicDetail(request: request, observer: observer) - } - public func snapshot() throws -> SessionState { try core.session().snapshot() } - public func registerStateObserver(_ observer: any StateObserver) { - core.registerStateObserver(observer: observer) - } - - public func unregisterStateObserver() { - core.unregisterStateObserver() - } - - public func registerCloudflareChallengeHandler( - _ handler: any CloudflareChallengeHandler - ) throws { - try core.session().registerCloudflareChallengeHandler(handler: handler) - } - - public func unregisterCloudflareChallengeHandler() throws { - try core.session().unregisterCloudflareChallengeHandler() - } - - public func registerCloudflareClearanceResolvedHandler( - _ handler: any CloudflareClearanceResolvedHandler - ) throws { - try core.session().registerCloudflareClearanceResolvedHandler(handler: handler) - } - - public func unregisterCloudflareClearanceResolvedHandler() throws { - try core.session().unregisterCloudflareClearanceResolvedHandler() - } - - public func cloudflareClearanceResolvedGeneration() throws -> UInt64 { - try core.session().cloudflareClearanceResolvedGeneration() - } - - public func registerCookieSelfHealingHandler( - _ handler: any CookieSelfHealingHandler - ) throws { - try core.session().registerCookieSelfHealingHandler(handler: handler) - } - - public func unregisterCookieSelfHealingHandler() throws { - try core.session().unregisterCookieSelfHealingHandler() - } - - public func ensurePreloadedDataLoaded() async throws { - try await core.session().ensurePreloadedDataLoaded() - try persistCurrentSessionIfNeeded() - } - - public func awaitPreloadedData() async throws -> PreloadedDataStateState { - let state = try await core.session().awaitPreloadedData() - try persistCurrentSessionIfNeeded() - return state - } - - public func currentUserDefaults() -> CurrentUserSnapshotState? { - try? core.session().currentUserSnapshot() - } - - public func cachedUser() -> CurrentUserSnapshotState? { - try? core.session().cachedUser() - } - - public func determineLoginState() -> LoginStateDeterminationState { - (try? core.session().determineLoginState()) ?? .notLoggedIn - } - - public func currentHomeTopicListScope() throws -> HomeTopicListScopeState { - try core.session().currentHomeTopicListScope() - } - - public func listDohPresets() throws -> [DohPresetState] { - try core.session().listDohPresets() - } - - public func getDohSettings() throws -> DohSettingsState { - try core.session().getDohSettings() - } - - @discardableResult - public func setDohSettings(_ settings: DohSettingsState) throws -> DohSettingsState { - try core.session().setDohSettings(settings: settings) - } - - public func probeDohSettings( - _ settings: DohSettingsState, - host: String? = nil - ) async throws -> DohProbeResultState { - try await core.session().probeDohSettings(settings: settings, host: host) - } - - @discardableResult - public func setCurrentHomeTopicListScope( - _ scope: HomeTopicListScopeState - ) throws -> HomeTopicListScopeState { - try core.session().setCurrentHomeTopicListScope(scope: scope) - } - - public func determineLoginStateWithProbe() async throws -> LoginStateDeterminationState { - let state = try await core.session().determineLoginStateWithProbe() - try persistCurrentSessionIfNeeded() - return state - } - - public func triggerAppStateRefresh(_ trigger: RefreshTriggerState) async throws { - try await core.session().triggerAppStateRefresh(trigger: trigger) - try persistCurrentSessionIfNeeded() - } - - public func triggerAppStateRefresh( - _ trigger: RefreshTriggerState, - handler: any AppStateRefreshHandler - ) async throws { - try await core.session().triggerAppStateRefreshWithHandler( - trigger: trigger, - handler: handler - ) - try persistCurrentSessionIfNeeded() - } - - public func restorePersistedSessionIfAvailable() throws -> SessionState? { - guard FileManager.default.fileExists(atPath: sessionFilePath) else { - return nil - } - let state = try core.session().loadSessionFromPath(path: sessionFilePath) - let persistenceState = try currentSessionPersistenceState() - lastPersistedSnapshotRevision = persistenceState.snapshotRevision - return state - } - - @discardableResult - public func prepareStartupSession() async throws -> SessionState { - try await restoreColdStartSession() - } - - @discardableResult - public func restoreColdStartSession() async throws -> SessionState { - try await restoreColdStartSession( - refreshBootstrapIfNeeded: { - try await self.refreshBootstrapIfNeeded() - }, - refreshBootstrapDuringRestore: false - ) - } - - @discardableResult - func restoreColdStartSession( - refreshBootstrapIfNeeded: () async throws -> SessionState, - refreshBootstrapDuringRestore: Bool = false - ) async throws -> SessionState { - _ = try restorePersistedSessionIfAvailable() - let secureSecrets = try authCookieStore.load() - - if !secureSecrets.isEmpty { - _ = try applyPlatformCookies(secureSecrets.platformCookies(baseURL: baseURL)) - } - - let current = try core.session().snapshot() - if !current.readiness.canReadAuthenticatedApi && shouldDiscardRestoredBootstrap(current) { - logHost( - level: .warn, - target: "session.cold_start", - message: "Cold-start session has valid user bootstrap but platform cookies are missing/expired. Preserving session to allow recovery." - ) - } - - guard refreshBootstrapDuringRestore else { - return current - } - - return try await refreshBootstrapIfNeeded() - } - - @discardableResult - public func syncLoginContext(_ captured: FireCapturedLoginState) throws -> SessionState { - let state = try core.session().syncLoginContext( - context: LoginSyncState( - currentUrl: captured.currentURL, - username: captured.username, - csrfToken: captured.csrfToken, - homeHtml: captured.homeHTML, - browserUserAgent: captured.browserUserAgent, - cookies: captured.cookies - ) - ) - try persistCurrentSessionIfNeeded() - return state - } - - public func cookieReplayQueue() throws -> [CookieReplayEntryState] { - try core.session().cookieReplayQueue() - } - - public func clearCookieReplayQueue() throws { - try core.session().clearCookieReplayQueue() - } - - public func loadSavedCredential() throws -> FireSavedCredential? { - try authCookieStore.loadCredential() - } - - public func saveLoginCredential(username: String, password: String) throws { - guard let credential = FireSavedCredential(username: username, password: password) else { - return - } - try authCookieStore.saveCredential(credential) - } - - public func clearSavedCredential() throws { - try authCookieStore.clearCredential() - } - - public func loadLastLoginMethod() throws -> FireLastLoginMethod? { - try authCookieStore.loadLastLoginMethod() - } - - public func saveLastLoginMethod(_ method: FireLastLoginMethod) throws { - try authCookieStore.saveLastLoginMethod(method) - } - - public func clearLastLoginMethod() throws { - try authCookieStore.clearLastLoginMethod() - } - - public func recordFingerprintDone() { - core.session().recordFingerprintDone() - } - - @discardableResult - public func finalizeLoginFromWebView( - _ captured: FireCapturedLoginState, - allowLowConfidenceSessionCookies: Bool = false - ) throws -> LoginFinalizationResultState { - let result = try core.session().finalizeLoginFromWebview( - username: captured.username ?? "", - csrfToken: captured.csrfToken, - rawPreloadedHtml: captured.homeHTML, - browserUserAgent: captured.browserUserAgent, - cookies: captured.cookies, - allowLowConfidenceSessionCookies: allowLowConfidenceSessionCookies - ) - try persistCurrentSessionIfNeeded() - return result - } - - @discardableResult - public func applyPlatformCookies(_ cookies: [PlatformCookieState]) throws -> SessionState { - let state = try core.session().applyPlatformCookies(cookies: cookies) - try persistCurrentSessionIfNeeded() - return state - } - - @discardableResult - public func mergePlatformCookies(_ cookies: [PlatformCookieState]) throws -> SessionState { - let state = try core.session().mergePlatformCookies(cookies: cookies) - try persistCurrentSessionIfNeeded() - return state - } - - @discardableResult - public func completeCloudflareChallenge( - cookies: [PlatformCookieState], - freshCfClearance: String?, - browserUserAgent: String? - ) throws -> SessionState { - let state = try core.session().completeCloudflareChallenge( - cookies: cookies, - freshCfClearance: { - let trimmed = freshCfClearance?.trimmingCharacters(in: .whitespacesAndNewlines) - return (trimmed?.isEmpty == false) ? trimmed : nil - }(), - browserUserAgent: browserUserAgent - ) - try persistCurrentSessionIfNeeded() - return state - } - - public func cloudflareClearanceIsTrusted() throws -> Bool { - try core.session().cloudflareClearanceIsTrusted() - } - - public func noteCloudflareClearanceRejected() throws { - try core.session().noteCloudflareClearanceRejected() - } - - public func finalizeLoginReady() async throws -> SessionState { - let state = try await core.session().finalizeLoginReady() - try persistCurrentSessionIfNeeded() - return state - } - - public func classifyWebViewLoginResult( - _ result: WebViewLoginJsResultState - ) throws -> WebViewLoginDecisionState { - try core.session().classifyWebviewLoginResult(result: result) - } - - public func webViewPrimingPayload( - targetURL: String? = nil - ) throws -> [WebViewCookieActionState] { - try core.session().webviewPrimingPayload(targetUrl: targetURL) - } - - public func cookieSweepPlan( - targetURL: String? = nil, - name: String, - webViewCookies: [WebViewCookieInfoState] - ) throws -> CookieSweepPlanState { - try core.session().cookieSweepPlan( - targetUrl: targetURL, - name: name, - webviewCookies: webViewCookies - ) - } - - public func cookieNuclearResetPlan( - targetURL: String? = nil, - webViewCookies: [WebViewCookieInfoState] - ) throws -> NuclearResetPlanState { - try core.session().cookieNuclearResetPlan( - targetUrl: targetURL, - webviewCookies: webViewCookies - ) - } - - @discardableResult - public func commitCookieSweepResult( - targetURL: String? = nil, - name: String, - intent: CookieSweepIntentState, - webViewCookies: [WebViewCookieInfoState] - ) throws -> SessionState { - let state = try core.session().commitCookieSweepResult( - targetUrl: targetURL, - name: name, - intent: intent, - webviewCookies: webViewCookies - ) - try persistCurrentSessionIfNeeded() - return state - } - - @discardableResult - public func logoutLocal(preserveCfClearance: Bool = true) throws -> SessionState { - let state = try core.session().logoutLocal(preserveCfClearance: preserveCfClearance) - try authCookieStore.clear(preserveCfClearance: preserveCfClearance) - try persistCurrentSessionIfNeeded() - return state - } - - @discardableResult - public func refreshBootstrap() async throws -> SessionState { - let refreshed = try await core.session().refreshBootstrap() - try persistCurrentSessionIfNeeded() - return refreshed - } - - @discardableResult - public func refreshBootstrapIfNeeded() async throws -> SessionState { - let refreshed = try await core.session().refreshBootstrapIfNeeded() - try persistCurrentSessionIfNeeded() - return refreshed - } - - @discardableResult - public func refreshCsrfTokenIfNeeded() async throws -> SessionState { - let refreshed = try await core.session().refreshCsrfTokenIfNeeded() - try persistCurrentSessionIfNeeded() - return refreshed - } - - public func persistCurrentSession() throws { - try persistCurrentSession(force: true) - } - - private func persistCurrentSessionIfNeeded() throws { - try persistCurrentSession(force: false) - } - - private func persistCurrentSession(force: Bool) throws { - let persistenceState = try currentSessionPersistenceState() - try persistCurrentAuthCookies(persistenceState: persistenceState, force: force) - try persistSessionFile(persistenceState: persistenceState, force: force) - } - public func workspacePathValue() -> String { workspacePath } - func setAuthenticatedWriteHostResyncProvider( - _ provider: AuthenticatedWriteHostResyncProvider? - ) { - authenticatedWriteHostResyncProvider = provider - } - public nonisolated func logHost(level: HostLogLevelState, target: String, message: String) { try? core.diagnostics().logHost(level: level, target: target, message: message) } @@ -541,1370 +62,4 @@ public actor FireSessionStore { try? core.diagnostics().logHost(level: level, target: target, message: message) } } - - public func listLogFiles() async throws -> [LogFileSummaryState] { - let core = self.core - let diagnosticsQueue = self.diagnosticsQueue - return try await withCheckedThrowingContinuation { continuation in - diagnosticsQueue.async { - continuation.resume(with: Result { try core.diagnostics().listLogFiles() }) - } - } - } - - public func readLogFile(relativePath: String) async throws -> LogFileDetailState { - let core = self.core - let diagnosticsQueue = self.diagnosticsQueue - return try await withCheckedThrowingContinuation { continuation in - diagnosticsQueue.async { - continuation.resume(with: Result { try core.diagnostics().readLogFile(relativePath: relativePath) }) - } - } - } - - public func readLogFilePage( - relativePath: String, - cursor: UInt64? = nil, - maxBytes: UInt64? = nil, - direction: DiagnosticsPageDirectionState - ) async throws -> LogFilePageState { - let core = self.core - let diagnosticsQueue = self.diagnosticsQueue - return try await withCheckedThrowingContinuation { continuation in - diagnosticsQueue.async { - continuation.resume( - with: Result { - try core.diagnostics().readLogFilePage( - relativePath: relativePath, - cursor: cursor, - maxBytes: maxBytes, - direction: direction - ) - } - ) - } - } - } - - public func listNetworkTraces(limit: UInt64 = 200) throws -> [NetworkTraceSummaryState] { - try core.diagnostics().listNetworkTraces(limit: limit) - } - - public func networkTraceDetail(traceID: UInt64) throws -> NetworkTraceDetailState? { - try core.diagnostics().networkTraceDetail(traceId: traceID) - } - - public func networkTraceBodyPage( - traceID: UInt64, - cursor: UInt64? = nil, - maxBytes: UInt64? = nil, - direction: DiagnosticsPageDirectionState - ) async throws -> NetworkTraceBodyPageState? { - let core = self.core - let diagnosticsQueue = self.diagnosticsQueue - return try await withCheckedThrowingContinuation { continuation in - diagnosticsQueue.async { - continuation.resume( - with: Result { - try core.diagnostics().networkTraceBodyPage( - traceId: traceID, - cursor: cursor, - maxBytes: maxBytes, - direction: direction - ) - } - ) - } - } - } - - public func diagnosticSessionID() throws -> String { - try core.diagnostics().diagnosticSessionId() - } - - public func exportSupportBundle( - platform: String, - appVersion: String?, - buildNumber: String?, - scenePhase: String? - ) async throws -> SupportBundleExportState { - let core = self.core - let diagnosticsQueue = self.diagnosticsQueue - return try await withCheckedThrowingContinuation { continuation in - diagnosticsQueue.async { - continuation.resume( - with: Result { - try core.diagnostics().exportSupportBundle( - hostContext: SupportBundleHostContextState( - platform: platform, - appVersion: appVersion, - buildNumber: buildNumber, - scenePhase: scenePhase - ) - ) - } - ) - } - } - } - - /// Redacted diagnostics package safe to leave the device (feedback share / upload). - public func exportFeedbackBundle( - platform: String, - appVersion: String?, - buildNumber: String?, - scenePhase: String? - ) async throws -> SupportBundleExportState { - let core = self.core - let diagnosticsQueue = self.diagnosticsQueue - return try await withCheckedThrowingContinuation { continuation in - diagnosticsQueue.async { - continuation.resume( - with: Result { - try core.diagnostics().exportFeedbackBundle( - hostContext: SupportBundleHostContextState( - platform: platform, - appVersion: appVersion, - buildNumber: buildNumber, - scenePhase: scenePhase - ) - ) - } - ) - } - } - } - - public func flushLogs(sync: Bool = true) async throws { - let core = self.core - let diagnosticsQueue = self.diagnosticsQueue - try await withCheckedThrowingContinuation { continuation in - diagnosticsQueue.async { - continuation.resume(with: Result { try core.diagnostics().flushLogs(sync: sync) }) - } - } - } - - public func exportSessionJSON() throws -> String { - try core.session().exportSessionJson() - } - - public func notificationState() throws -> NotificationCenterState { - try core.notifications().notificationState() - } - - public func fetchRecentNotifications(limit: UInt32? = nil) async throws -> NotificationListState { - try await runPersistingSessionChanges { - try await core.notifications().fetchRecentNotifications(limit: limit) - } - } - - public func fetchNotifications( - limit: UInt32? = nil, - offset: UInt32? = nil - ) async throws -> NotificationListState { - try await runPersistingSessionChanges { - try await core.notifications().fetchNotifications(limit: limit, offset: offset) - } - } - - public func markNotificationRead(id: UInt64) async throws -> NotificationCenterState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.notifications().markNotificationRead(notificationId: id) - } - } - - public func markAllNotificationsRead() async throws -> NotificationCenterState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.notifications().markAllNotificationsRead() - } - } - - public func fetchBookmarks( - username: String, - page: UInt32? = nil - ) async throws -> TopicListState { - try await runPersistingSessionChanges { - try await core.notifications().fetchBookmarks(username: username, page: page) - } - } - - public func fetchReadHistory(page: UInt32? = nil) async throws -> TopicListState { - try await runPersistingSessionChanges { - try await core.notifications().fetchReadHistory(page: page) - } - } - - public func fetchDrafts( - offset: UInt32? = nil, - limit: UInt32? = nil - ) async throws -> DraftListResponseState { - try await runPersistingSessionChanges { - try await core.notifications().fetchDrafts(offset: offset, limit: limit) - } - } - - public func fetchDraft(draftKey: String) async throws -> DraftState? { - try await runPersistingSessionChanges { - try await core.notifications().fetchDraft(draftKey: draftKey) - } - } - - public func saveDraft( - draftKey: String, - data: DraftDataState, - sequence: UInt32 - ) async throws -> UInt32 { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.notifications().saveDraft(draftKey: draftKey, data: data, sequence: sequence) - } - } - - public func deleteDraft( - draftKey: String, - sequence: UInt32? = nil - ) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.notifications().deleteDraft(draftKey: draftKey, sequence: sequence) - } - } - - public func pollNotificationAlertOnce( - lastMessageId: Int64 - ) async throws -> NotificationAlertPollResultState { - try await runPersistingSessionChanges { - try await core.messagebus().pollNotificationAlertOnce(lastMessageId: lastMessageId) - } - } - - // MARK: - Chat - - public func fetchMyChatChannels() async throws -> MyChatChannelsState { - try await runPersistingSessionChanges { - try await core.chat().fetchMyChatChannels() - } - } - - public func cachedMyChatChannels() throws -> MyChatChannelsState? { - try core.chat().cachedMyChatChannels() - } - - public func cachedChatMessages(channelID: UInt64, threadID: UInt64?) throws -> ChatMessagesState? { - try core.chat().cachedChatMessages(channelId: channelID, threadId: threadID) - } - - public func fetchChatChannel(channelID: UInt64) async throws -> ChatChannelState { - try await runPersistingSessionChanges { - try await core.chat().fetchChatChannel(channelId: channelID) - } - } - - public func createDirectMessageChannel( - request: CreateDirectMessageChannelRequestState - ) async throws -> ChatChannelState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().createDirectMessageChannel(request: request) - } - } - - public func fetchChatMessages(query: ChatMessagesQueryState) async throws -> ChatMessagesState { - try await runPersistingSessionChanges { - try await core.chat().fetchChatMessages(query: query) - } - } - - public func sendChatMessage( - request: SendChatMessageRequestState - ) async throws -> SendChatMessageResultState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().sendChatMessage(request: request) - } - } - - public func markChatChannelRead(channelID: UInt64, messageID: UInt64? = nil) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().markChatChannelRead(channelId: channelID, messageId: messageID) - } - } - - public func browseChatChannels( - query: BrowseChatChannelsQueryState - ) async throws -> [ChatChannelState] { - try await runPersistingSessionChanges { - try await core.chat().browseChatChannels(query: query) - } - } - - public func joinChatChannel(channelID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().joinChatChannel(channelId: channelID) - } - } - - public func leaveChatChannel(channelID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().leaveChatChannel(channelId: channelID) - } - } - - public func starChatChannel(channelID: UInt64, starred: Bool) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().starChatChannel(channelId: channelID, starred: starred) - } - } - - public func updateChatChannelNotifications( - channelID: UInt64, - muted: Bool? = nil, - notificationLevel: String? = nil - ) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().updateChatChannelNotifications( - channelId: channelID, - muted: muted, - notificationLevel: notificationLevel - ) - } - } - - public func editChatMessage( - channelID: UInt64, - messageID: UInt64, - message: String, - uploadIDs: [UInt64]? = nil - ) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().editChatMessage( - channelId: channelID, - messageId: messageID, - message: message, - uploadIds: uploadIDs - ) - } - } - - public func deleteChatMessage(channelID: UInt64, messageID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().deleteChatMessage(channelId: channelID, messageId: messageID) - } - } - - public func reactChatMessage( - channelID: UInt64, - messageID: UInt64, - emoji: String, - reactAction: String - ) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().reactChatMessage( - channelId: channelID, - messageId: messageID, - emoji: emoji, - reactAction: reactAction - ) - } - } - - public func fetchChatChannelMembers( - channelID: UInt64, - offset: UInt32? = nil, - limit: UInt32? = nil, - username: String? = nil - ) async throws -> [ChatChannelMemberState] { - try await runPersistingSessionChanges { - try await core.chat().fetchChatChannelMembers( - channelId: channelID, - offset: offset, - limit: limit, - username: username - ) - } - } - - public func searchChatMessages(query: ChatSearchQueryState) async throws -> ChatSearchResultState { - try await runPersistingSessionChanges { - try await core.chat().searchChatMessages(query: query) - } - } - - public func fetchChatChannelPins(channelID: UInt64) async throws -> [ChatMessageState] { - try await runPersistingSessionChanges { - try await core.chat().fetchChatChannelPins(channelId: channelID) - } - } - - public func pinChatMessage(channelID: UInt64, messageID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().pinChatMessage(channelId: channelID, messageId: messageID) - } - } - - public func unpinChatMessage(channelID: UInt64, messageID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().unpinChatMessage(channelId: channelID, messageId: messageID) - } - } - - public func markChatChannelPinsRead(channelID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().markChatChannelPinsRead(channelId: channelID) - } - } - - public func createChatThread(channelID: UInt64, originalMessageID: UInt64) async throws -> UInt64 { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().createChatThread( - channelId: channelID, - originalMessageId: originalMessageID - ) - } - } - - public func fetchChatThreadMessages( - channelID: UInt64, - threadID: UInt64, - query: ChatMessagesQueryState - ) async throws -> ChatMessagesState { - try await runPersistingSessionChanges { - try await core.chat().fetchChatThreadMessages( - channelId: channelID, - threadId: threadID, - query: query - ) - } - } - - public func markChatThreadRead(channelID: UInt64, threadID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.chat().markChatThreadRead(channelId: channelID, threadId: threadID) - } - } - - public func search(query: SearchQueryState) async throws -> SearchResultState { - try await runPersistingSessionChanges { - try await core.search().search(query: query) - } - } - - public func searchTags(query: TagSearchQueryState) async throws -> TagSearchResultState { - try await runPersistingSessionChanges { - try await core.search().searchTags(query: query) - } - } - - public func searchUsers(query: UserMentionQueryState) async throws -> UserMentionResultState { - try await runPersistingSessionChanges { - try await core.search().searchUsers(query: query) - } - } - - public func fetchTopicList(query: TopicListQueryState) async throws -> TopicListState { - try await runPersistingSessionChanges { - try await core.topics().fetchTopicList(query: query) - } - } - - public func fetchTopicList(kind: TopicListKindState) async throws -> TopicListState { - try await fetchTopicList( - query: TopicListQueryState( - kind: kind, - page: nil, - topicIds: [], - order: nil, - ascending: nil, - categorySlug: nil, - categoryId: nil, - parentCategorySlug: nil, - tag: nil, - additionalTags: [], - matchAllTags: false - ) - ) - } - - public func fetchTopicPosts(topicID: UInt64, postIDs: [UInt64]) async throws -> [TopicPostState] { - try await runPersistingSessionChanges { - try await core.topics().fetchTopicPosts(topicId: topicID, postIds: postIDs) - } - } - - public func fetchTopicAiSummary( - topicID: UInt64, - skipAgeCheck: Bool = false - ) async throws -> TopicAiSummaryState? { - try await runPersistingSessionChanges { - try await core.topics().fetchTopicAiSummary( - topicId: topicID, - skipAgeCheck: skipAgeCheck - ) - } - } - - public func fetchPost(postID: UInt64) async throws -> TopicPostState { - try await runPersistingSessionChanges { - try await core.topics().fetchPost(postId: postID) - } - } - - public func fetchPostReplyIds(postID: UInt64) async throws -> [UInt64] { - try await runPersistingSessionChanges { - try await core.topics().fetchPostReplyIds(postId: postID) - } - } - - public func fetchPostReplyHistory(postID: UInt64) async throws -> [TopicPostState] { - try await runPersistingSessionChanges { - try await core.topics().fetchPostReplyHistory(postId: postID) - } - } - - public func createReply( - topicID: UInt64, - raw: String, - replyToPostNumber: UInt32? - ) async throws -> TopicPostState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().createReply( - input: TopicReplyRequestState( - topicId: topicID, - raw: raw, - replyToPostNumber: replyToPostNumber - ) - ) - } - } - - public func createBoost(postID: UInt64, raw: String) async throws -> TopicPostBoostState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().createBoost(postId: postID, raw: raw) - } - } - - public func deleteBoost(boostID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().deleteBoost(boostId: boostID) - } - } - - public func updatePost( - postID: UInt64, - raw: String, - editReason: String? = nil - ) async throws -> TopicPostState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().updatePost( - input: PostUpdateRequestState( - postId: postID, - raw: raw, - editReason: editReason - ) - ) - } - } - - public func deletePost(postID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().deletePost(postId: postID) - } - } - - public func recoverPost(postID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().recoverPost(postId: postID) - } - } - - public func flagPost( - postID: UInt64, - flagTypeID: UInt32, - message: String? = nil - ) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().flagPost( - input: PostFlagRequestState( - postId: postID, - flagTypeId: flagTypeID, - message: message - ) - ) - } - } - - public func fetchPostActionTypes() async throws -> [PostActionTypeState] { - try await runPersistingSessionChanges { - try await core.topics().fetchPostActionTypes() - } - } - - public func createTopic( - title: String, - raw: String, - categoryID: UInt64, - tags: [String] - ) async throws -> UInt64 { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().createTopic( - input: TopicCreateRequestState( - title: title, - raw: raw, - categoryId: categoryID, - tags: tags - ) - ) - } - } - - public func createPrivateMessage( - title: String, - raw: String, - targetRecipients: [String] - ) async throws -> UInt64 { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().createPrivateMessage( - input: PrivateMessageCreateRequestState( - title: title, - raw: raw, - targetRecipients: targetRecipients - ) - ) - } - } - - public func updateTopic( - topicID: UInt64, - title: String, - categoryID: UInt64, - tags: [String] - ) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().updateTopic( - input: TopicUpdateRequestState( - topicId: topicID, - title: title, - categoryId: categoryID, - tags: tags - ) - ) - } - } - - public func uploadImage( - fileName: String, - mimeType: String?, - bytes: Data - ) async throws -> UploadResultState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().uploadImage( - input: UploadImageRequestState( - fileName: fileName, - mimeType: mimeType, - bytes: bytes - ) - ) - } - } - - public func lookupUploadUrls(shortUrls: [String]) async throws -> [ResolvedUploadUrlState] { - try await runPersistingSessionChanges { - try await core.topics().lookupUploadUrls(shortUrls: shortUrls) - } - } - - public func reportTopicTimings( - input: TopicTimingsRequestState - ) async throws -> Bool { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().reportTopicTimings(input: input) - } - } - - public func likePost(postID: UInt64) async throws -> PostReactionUpdateState? { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().likePost(postId: postID) - } - } - - public func unlikePost(postID: UInt64) async throws -> PostReactionUpdateState? { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().unlikePost(postId: postID) - } - } - - public func togglePostReaction( - postID: UInt64, - reactionID: String - ) async throws -> PostReactionUpdateState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().togglePostReaction(postId: postID, reactionId: reactionID) - } - } - - public func fetchReactionUsers(postID: UInt64) async throws -> [ReactionUsersGroupState] { - try await runPersistingSessionChanges { - try await core.topics().fetchReactionUsers(postId: postID) - } - } - - public func votePoll( - postID: UInt64, - pollName: String, - options: [String] - ) async throws -> PollState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().votePoll(postId: postID, pollName: pollName, options: options) - } - } - - public func unvotePoll( - postID: UInt64, - pollName: String - ) async throws -> PollState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().unvotePoll(postId: postID, pollName: pollName) - } - } - - public func voteTopic(topicID: UInt64) async throws -> VoteResponseState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().voteTopic(topicId: topicID) - } - } - - public func unvoteTopic(topicID: UInt64) async throws -> VoteResponseState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.topics().unvoteTopic(topicId: topicID) - } - } - - public func fetchTopicVoters(topicID: UInt64) async throws -> [VotedUserState] { - try await runPersistingSessionChanges { - try await core.topics().fetchTopicVoters(topicId: topicID) - } - } - - public func createBookmark( - bookmarkableID: UInt64, - bookmarkableType: String, - name: String? = nil, - reminderAt: String? = nil, - autoDeletePreference: Int32? = nil - ) async throws -> UInt64 { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.notifications().createBookmark( - bookmarkableId: bookmarkableID, - bookmarkableType: bookmarkableType, - name: name, - reminderAt: reminderAt, - autoDeletePreference: autoDeletePreference - ) - } - } - - public func updateBookmark( - bookmarkID: UInt64, - name: String? = nil, - reminderAt: String? = nil, - autoDeletePreference: Int32? = nil - ) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.notifications().updateBookmark( - bookmarkId: bookmarkID, - name: name, - reminderAt: reminderAt, - autoDeletePreference: autoDeletePreference - ) - } - } - - public func deleteBookmark(bookmarkID: UInt64) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.notifications().deleteBookmark(bookmarkId: bookmarkID) - } - } - - public func setTopicNotificationLevel( - topicID: UInt64, - notificationLevel: Int32 - ) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.notifications().setTopicNotificationLevel( - topicId: topicID, - notificationLevel: notificationLevel - ) - } - } - - public func fetchUserProfile(username: String) async throws -> UserProfileState { - try await runPersistingSessionChanges { - try await core.user().fetchUserProfile(username: username) - } - } - - public func fetchUserSummary(username: String) async throws -> UserSummaryState { - try await runPersistingSessionChanges { - try await core.user().fetchUserSummary(username: username) - } - } - - public func fetchUserActions( - username: String, - offset: UInt32?, - filter: String? - ) async throws -> [UserActionState] { - try await runPersistingSessionChanges { - try await core.user().fetchUserActions(username: username, offset: offset, filter: filter) - } - } - - public func fetchFollowing(username: String) async throws -> [FollowUserState] { - try await runPersistingSessionChanges { - try await core.user().fetchFollowing(username: username) - } - } - - public func fetchFollowers(username: String) async throws -> [FollowUserState] { - try await runPersistingSessionChanges { - try await core.user().fetchFollowers(username: username) - } - } - - public func followUser(username: String) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.user().followUser(username: username) - } - } - - public func unfollowUser(username: String) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.user().unfollowUser(username: username) - } - } - - public func fetchPendingInvites(username: String) async throws -> [InviteLinkState] { - try await runPersistingSessionChanges { - try await core.user().fetchPendingInvites(username: username) - } - } - - public func createInviteLink( - maxRedemptionsAllowed: UInt32, - expiresAt: String? = nil, - description: String? = nil, - email: String? = nil - ) async throws -> InviteLinkState { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.user().createInviteLink( - input: InviteCreateRequestState( - maxRedemptionsAllowed: maxRedemptionsAllowed, - expiresAt: expiresAt, - description: description, - email: email - ) - ) - } - } - - public func fetchBadgeDetail(badgeID: UInt64) async throws -> BadgeState { - try await runPersistingSessionChanges { - try await core.user().fetchBadgeDetail(badgeId: badgeID) - } - } - - public func ldcAuthorizationUrl() async throws -> LdcAuthorizationUrlState { - try await runPersistingSessionChanges { - try await core.ldc().ldcAuthorizationUrl() - } - } - - public func ldcApprovalLink(authorizationURL: String) async throws -> String { - try await runPersistingSessionChanges { - try await core.ldc().ldcApprovalLink(authorizationUrl: authorizationURL) - } - } - - public func ldcApprove(approvePath: String) async throws -> LdcApprovalStatusState { - try await runPersistingSessionChanges { - try await core.ldc().ldcApprove(approvePath: approvePath) - } - } - - public func ldcCallback(code: String, state: String) async throws { - try await runPersistingSessionChanges { - try await core.ldc().ldcCallback(code: code, state: state) - } - } - - public func ldcUserInfo() async throws -> LdcUserInfoState { - try await runPersistingSessionChanges { - try await core.ldc().ldcUserInfo() - } - } - - public func ldcLogout() async throws { - try await runPersistingSessionChanges { - try await core.ldc().ldcLogout() - } - } - - public func cdkAuthorizationUrl() async throws -> CdkAuthorizationUrlState { - try await runPersistingSessionChanges { - try await core.ldc().cdkAuthorizationUrl() - } - } - - public func cdkApprovalLink(authorizationURL: String) async throws -> String { - try await runPersistingSessionChanges { - try await core.ldc().cdkApprovalLink(authorizationUrl: authorizationURL) - } - } - - public func cdkApprove(approvePath: String) async throws -> LdcApprovalStatusState { - try await runPersistingSessionChanges { - try await core.ldc().cdkApprove(approvePath: approvePath) - } - } - - public func cdkCallback(code: String, state: String) async throws { - try await runPersistingSessionChanges { - try await core.ldc().cdkCallback(code: code, state: state) - } - } - - public func cdkUserInfo() async throws -> CdkUserInfoState { - try await runPersistingSessionChanges { - try await core.ldc().cdkUserInfo() - } - } - - public func cdkLogout() async throws { - try await runPersistingSessionChanges { - try await core.ldc().cdkLogout() - } - } - - @discardableResult - public func restoreSessionJSON(_ json: String) throws -> SessionState { - let state = try core.session().restoreSessionJson(json: json) - try persistCurrentSessionIfNeeded() - return state - } - - // MARK: - MessageBus - - @discardableResult - public func startMessageBus(handler: any MessageBusEventHandler) async throws -> String { - try await runPersistingSessionChanges { - try await core.messagebus().startMessageBus( - mode: .foreground, - handler: handler, - topicTrackingStateMeta: try topicTrackingStateMetaForMessageBus() - ) - } - } - - public func stopMessageBus(clearSubscriptions: Bool = false) throws { - try core.messagebus().stopMessageBus(clearSubscriptions: clearSubscriptions) - } - - public func subscribeTopicDetailChannel( - topicId: UInt64, - ownerToken: String, - lastMessageId: Int64? - ) throws { - try core.messagebus().subscribeChannel( - subscription: MessageBusSubscriptionState( - ownerToken: ownerToken, - channel: "/topic/\(topicId)", - lastMessageId: lastMessageId, - scope: .transient - ) - ) - } - - public func unsubscribeTopicDetailChannel(topicId: UInt64, ownerToken: String) throws { - try core.messagebus().unsubscribeChannel(ownerToken: ownerToken, channel: "/topic/\(topicId)") - } - - public func subscribeTopicReactionChannel(topicId: UInt64, ownerToken: String) throws { - try core.messagebus().subscribeChannel( - subscription: MessageBusSubscriptionState( - ownerToken: ownerToken, - channel: "/topic/\(topicId)/reactions", - lastMessageId: nil, - scope: .transient - ) - ) - } - - public func unsubscribeTopicReactionChannel(topicId: UInt64, ownerToken: String) throws { - try core.messagebus().unsubscribeChannel(ownerToken: ownerToken, channel: "/topic/\(topicId)/reactions") - } - - public func subscribeTopicPollsChannel(topicId: UInt64, ownerToken: String) throws { - try core.messagebus().subscribeChannel( - subscription: MessageBusSubscriptionState( - ownerToken: ownerToken, - channel: "/polls/\(topicId)", - lastMessageId: 0, - scope: .transient - ) - ) - } - - public func unsubscribeTopicPollsChannel(topicId: UInt64, ownerToken: String) throws { - try core.messagebus().unsubscribeChannel(ownerToken: ownerToken, channel: "/polls/\(topicId)") - } - - public func subscribeMessageBusChannel( - channel: String, - ownerToken: String, - lastMessageId: Int64?, - scope: MessageBusSubscriptionScopeState = .transient - ) throws { - try core.messagebus().subscribeChannel( - subscription: MessageBusSubscriptionState( - ownerToken: ownerToken, - channel: channel, - lastMessageId: lastMessageId, - scope: scope - ) - ) - } - - public func unsubscribeMessageBusChannel(channel: String, ownerToken: String) throws { - try core.messagebus().unsubscribeChannel(ownerToken: ownerToken, channel: channel) - } - - public func topicReplyPresenceState(topicId: UInt64) throws -> TopicPresenceState { - try core.messagebus().topicReplyPresenceState(topicId: topicId) - } - - public func bootstrapTopicReplyPresence( - topicId: UInt64, - ownerToken: String - ) async throws -> TopicPresenceState { - try await runPersistingSessionChanges { - try await core.messagebus().bootstrapTopicReplyPresence(topicId: topicId, ownerToken: ownerToken) - } - } - - public func unsubscribeTopicReplyPresenceChannel(topicId: UInt64, ownerToken: String) throws { - try core.messagebus().unsubscribeChannel( - ownerToken: ownerToken, - channel: "/presence/discourse-presence/reply/\(topicId)" - ) - } - - public func updateTopicReplyPresence(topicId: UInt64, active: Bool) async throws { - try await runAuthenticatedWritePersistingSessionChanges { - try await core.messagebus().updateTopicReplyPresence(topicId: topicId, active: active) - } - } - - // MARK: - Logout - - @discardableResult - public func logout() async throws -> SessionState { - let current = try core.session().snapshot() - if current.readiness.canReadAuthenticatedApi && !current.readiness.hasCurrentUser { - _ = try await refreshBootstrapIfNeeded() - } - let state = try await core.session().logoutRemote(preserveCfClearance: true) - try authCookieStore.save(FireAuthCookieSecrets(cookieState: state.cookies)) - let persistenceState = try currentSessionPersistenceState() - lastPersistedAuthCookieRevision = persistenceState.authCookieRevision - try clearPersistedSession() - return state - } - - public func clearPersistedSession() throws { - try core.session().clearSessionPath(path: sessionFilePath) - lastPersistedSnapshotRevision = 0 - } - - public static func defaultWorkspacePath(fileManager: FileManager = .default) throws -> String { - guard let directory = try fileManager.url( - for: .applicationSupportDirectory, - in: .userDomainMask, - appropriateFor: nil, - create: true - ) as URL? else { - throw FireSessionStoreError.missingApplicationSupportDirectory - } - - let fireDirectory = directory.appendingPathComponent("Fire", isDirectory: true) - try fileManager.createDirectory( - at: fireDirectory, - withIntermediateDirectories: true, - attributes: nil - ) - try repairDiagnosticsDirectoryIfNeeded( - workspaceDirectory: fireDirectory, - fileManager: fileManager - ) - return fireDirectory.path - } - - private static func repairDiagnosticsDirectoryIfNeeded( - workspaceDirectory: URL, - fileManager: FileManager - ) throws { - let diagnosticsDirectory = workspaceDirectory.appendingPathComponent( - "diagnostics", - isDirectory: true - ) - let diagnosticsPath = diagnosticsDirectory.path - guard fileManager.fileExists(atPath: diagnosticsPath) else { - return - } - guard fileManager.isWritableFile(atPath: diagnosticsPath) == false else { - return - } - try fileManager.removeItem(at: diagnosticsDirectory) - try fileManager.createDirectory( - at: diagnosticsDirectory, - withIntermediateDirectories: true, - attributes: nil - ) - } - - public static func defaultSessionFilePath(fileManager: FileManager = .default) throws -> String { - let workspacePath = try defaultWorkspacePath(fileManager: fileManager) - return URL(fileURLWithPath: workspacePath) - .appendingPathComponent("session.json", isDirectory: false) - .path - } - - private func shouldDiscardRestoredBootstrap(_ session: SessionState) -> Bool { - session.readiness.hasCurrentUser - || session.readiness.hasPreloadedData - || session.readiness.hasSharedSessionKey - } - - private func currentSessionPersistenceState() throws -> SessionPersistenceState { - try core.session().sessionPersistenceState() - } - - private func topicTrackingStateMetaForMessageBus() throws -> [String: Int64]? { - let raw = try core.session().snapshot().bootstrap.topicTrackingStateMeta? - .trimmingCharacters(in: .whitespacesAndNewlines) - guard let raw, !raw.isEmpty else { - return nil - } - let data = Data(raw.utf8) - guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { - return nil - } - var result: [String: Int64] = [:] - for (key, value) in object { - if let number = value as? NSNumber { - result[key] = number.int64Value - } else if let text = value as? String, let number = Int64(text) { - result[key] = number - } - } - return result.isEmpty ? nil : result - } - - private func persistCurrentAuthCookies( - persistenceState: SessionPersistenceState, - force: Bool - ) throws { - guard force || persistenceState.authCookieRevision != lastPersistedAuthCookieRevision else { - return - } - - try authCookieStore.save(FireAuthCookieSecrets(cookieState: try core.session().snapshot().cookies)) - lastPersistedAuthCookieRevision = persistenceState.authCookieRevision - } - - private func persistSessionFile( - persistenceState: SessionPersistenceState, - force: Bool - ) throws { - guard force || persistenceState.snapshotRevision != lastPersistedSnapshotRevision else { - return - } - - try core.session().saveSessionToPath(path: sessionFilePath) - lastPersistedSnapshotRevision = persistenceState.snapshotRevision - } - - private func authenticatedWritePreflightContext() throws -> AuthenticatedWritePreflightContext { - AuthenticatedWritePreflightContext( - sessionEpoch: try core.session().sessionEpoch(), - authRecoveryHint: try core.session().authRecoveryHint() - ) - } - - /// Read-side helper: returns the current shared session epoch so callers can - /// detect whether a host cookie resync actually replaced the auth cookies. - public func currentSessionEpoch() throws -> UInt64 { - try core.session().sessionEpoch() - } - - private func refreshCsrfTokenForAuthenticatedWritePreflight() async throws -> AuthenticatedWritePreflightContext { - _ = try await refreshCsrfTokenIfNeeded() - return try authenticatedWritePreflightContext() - } - - private func applyPlatformCookiesForAuthenticatedWritePreflight( - _ cookies: [PlatformCookieState] - ) async throws -> AuthenticatedWritePreflightContext { - guard Self.containsActiveAuthCookies(in: cookies) else { - logHost( - level: .info, - target: "session.auth_write_preflight", - message: "Skipping authoritative platform cookie apply because host resync returned partial auth cookies." - ) - return try authenticatedWritePreflightContext() - } - _ = try applyPlatformCookies(cookies) - return try authenticatedWritePreflightContext() - } - - nonisolated private static func containsActiveAuthCookies( - in cookies: [PlatformCookieState] - ) -> Bool { - let activeCookies = cookies.filter { cookie in - let value = cookie.value.trimmingCharacters(in: .whitespacesAndNewlines) - return !value.isEmpty && !(cookie.expiresAtUnixMs.map { $0 <= currentUnixMs() } ?? false) - } - - return activeCookies.contains(where: { $0.name == "_t" }) - && activeCookies.contains(where: { $0.name == "_forum_session" }) - } - - nonisolated private static func currentUnixMs() -> Int64 { - Int64(Date().timeIntervalSince1970 * 1000) - } - - private func runAuthenticatedWritePreflight() async throws { - try await runAuthenticatedWritePreflight( - readContext: { - try await self.authenticatedWritePreflightContext() - }, - refreshCsrfTokenIfNeeded: { - try await self.refreshCsrfTokenForAuthenticatedWritePreflight() - }, - applyPlatformCookies: { cookies in - try await self.applyPlatformCookiesForAuthenticatedWritePreflight(cookies) - }, - hostResyncProvider: authenticatedWriteHostResyncProvider - ) - } - - func runAuthenticatedWritePreflight( - readContext: @escaping @Sendable () async throws -> AuthenticatedWritePreflightContext, - refreshCsrfTokenIfNeeded: @escaping @Sendable () async throws -> AuthenticatedWritePreflightContext, - applyPlatformCookies: @escaping @Sendable ([PlatformCookieState]) async throws -> AuthenticatedWritePreflightContext, - hostResyncProvider: AuthenticatedWriteHostResyncProvider? - ) async throws { - let initialContext = try await readContext() - let refreshedContext = try await refreshCsrfTokenIfNeeded() - - guard - let recoveryHint = initialContext.authRecoveryHint, - recoveryHint.observedEpoch == initialContext.sessionEpoch, - refreshedContext.sessionEpoch == initialContext.sessionEpoch, - let refreshedHint = refreshedContext.authRecoveryHint, - refreshedHint.observedEpoch == initialContext.sessionEpoch - else { - return - } - - guard let hostResyncProvider else { - return - } - - await runAuthenticatedWriteHostResyncIfNeeded( - for: initialContext.sessionEpoch, - readContext: readContext, - applyPlatformCookies: applyPlatformCookies, - hostResyncProvider: hostResyncProvider - ) - _ = try await refreshCsrfTokenIfNeeded() - } - - private func runAuthenticatedWriteHostResyncIfNeeded( - for sessionEpoch: UInt64, - readContext: @escaping @Sendable () async throws -> AuthenticatedWritePreflightContext, - applyPlatformCookies: @escaping @Sendable ([PlatformCookieState]) async throws -> AuthenticatedWritePreflightContext, - hostResyncProvider: @escaping AuthenticatedWriteHostResyncProvider - ) async { - if let existingTask = authenticatedWriteHostResyncTasks[sessionEpoch] { - await existingTask.value - return - } - - guard !authenticatedWriteHostResyncAttemptedEpochs.contains(sessionEpoch) else { - return - } - - authenticatedWriteHostResyncAttemptedEpochs.insert(sessionEpoch) - let task = Task { [self] in - do { - try await executeAuthenticatedWriteHostResync( - for: sessionEpoch, - readContext: readContext, - applyPlatformCookies: applyPlatformCookies, - hostResyncProvider: hostResyncProvider - ) - } catch { - } - clearAuthenticatedWriteHostResyncTask(for: sessionEpoch) - } - authenticatedWriteHostResyncTasks[sessionEpoch] = task - await task.value - } - - private func executeAuthenticatedWriteHostResync( - for sessionEpoch: UInt64, - readContext: @escaping @Sendable () async throws -> AuthenticatedWritePreflightContext, - applyPlatformCookies: @escaping @Sendable ([PlatformCookieState]) async throws -> AuthenticatedWritePreflightContext, - hostResyncProvider: @escaping AuthenticatedWriteHostResyncProvider - ) async throws { - let beforeProviderContext = try await readContext() - guard - beforeProviderContext.sessionEpoch == sessionEpoch, - let recoveryHint = beforeProviderContext.authRecoveryHint, - recoveryHint.observedEpoch == sessionEpoch - else { - return - } - - guard let platformCookies = try await hostResyncProvider(), !platformCookies.isEmpty else { - return - } - - let beforeApplyContext = try await readContext() - guard - beforeApplyContext.sessionEpoch == sessionEpoch, - let recoveryHint = beforeApplyContext.authRecoveryHint, - recoveryHint.observedEpoch == sessionEpoch - else { - return - } - - _ = try await applyPlatformCookies(platformCookies) - } - - private func clearAuthenticatedWriteHostResyncTask(for sessionEpoch: UInt64) { - authenticatedWriteHostResyncTasks.removeValue(forKey: sessionEpoch) - } - - private func runAuthenticatedWritePersistingSessionChanges( - _ operation: () async throws -> T - ) async throws -> T { - try await runAuthenticatedWritePreflight() - return try await runPersistingSessionChanges(operation) - } - - private func runPersistingSessionChanges( - _ operation: () async throws -> T - ) async throws -> T { - let result = try await operation() - try persistCurrentSessionIfNeeded() - return result - } } diff --git a/apps/ios-app/Sources/FireAppSession/FireSessionStoreError.swift b/apps/ios-app/Sources/FireAppSession/FireSessionStoreError.swift new file mode 100644 index 00000000..82e1cd7a --- /dev/null +++ b/apps/ios-app/Sources/FireAppSession/FireSessionStoreError.swift @@ -0,0 +1,5 @@ +import Foundation + +public enum FireSessionStoreError: Error { + case missingApplicationSupportDirectory +} diff --git a/apps/ios-app/project.yml b/apps/ios-app/project.yml index 4f606bea..18b82d14 100644 --- a/apps/ios-app/project.yml +++ b/apps/ios-app/project.yml @@ -70,7 +70,7 @@ targets: - path: Sources/FireAppSession - path: Generated/FireUniFfi optional: true - type: group + type: syncedFolder buildPhase: sources - path: Configs/PrivacyInfo.xcprivacy buildPhase: resources @@ -140,6 +140,7 @@ targets: - $(SRCROOT)/../../crates/fire-uniffi/uniffi.toml outputFiles: - $(SRCROOT)/Generated/FireUniFfi/fire_uniffi.swift + - $(SRCROOT)/Generated/FireUniFfi/fire_uniffi_chat.swift - $(SRCROOT)/Generated/FireUniFfi/fire_uniffi_diagnostics.swift - $(SRCROOT)/Generated/FireUniFfi/fire_uniffi_ldc.swift - $(SRCROOT)/Generated/FireUniFfi/fire_uniffi_messagebus.swift diff --git a/crates/fire-core/src/chat_payloads.rs b/crates/fire-core/src/chat_payloads.rs deleted file mode 100644 index 6574631a..00000000 --- a/crates/fire-core/src/chat_payloads.rs +++ /dev/null @@ -1,812 +0,0 @@ -use fire_models::{ - ChatBusEvent, ChatBusLastIdEntry, ChatChannel, ChatChannelBusLastIds, ChatChannelMember, - ChatChannelMembership, ChatChannelTrackingEntry, ChatMessage, ChatMessageBookmark, - ChatMessageReaction, ChatMessageReplyRef, ChatMessagesResponse, ChatReactionAction, - ChatSearchResult, ChatThreadRef, ChatUpload, ChatUser, MyChatChannelsResponse, -}; -use serde_json::Value; -use tracing::warn; - -use crate::json_helpers::{ - boolean, integer_i32, integer_i64, integer_u32, integer_u64, invalid_json, object_field, - parse_array_items_lossy, scalar_string, -}; - -pub(crate) fn parse_my_chat_channels_response_value( - value: Value, -) -> Result { - require_object(&value, "my chat channels response root was not an object")?; - - let public_channels = optional_array_field(&value, "public_channels") - .map(|items| parse_array_items_lossy(items, "public chat channel", parse_chat_channel)) - .unwrap_or_default(); - let direct_message_channels = optional_array_field(&value, "direct_message_channels") - .map(|items| { - parse_array_items_lossy(items, "direct message chat channel", parse_chat_channel) - }) - .unwrap_or_default(); - - let channel_tracking = object_field(&value, "tracking") - .and_then(|tracking| object_field(tracking, "channel_tracking")) - .and_then(Value::as_object) - .map(|map| { - map.iter() - .filter_map(|(key, entry)| { - let channel_id = key.parse::().ok()?; - let unread_count = - integer_u32(object_field(entry, "unread_count")).unwrap_or(0); - let mention_count = - integer_u32(object_field(entry, "mention_count")).unwrap_or(0); - Some(ChatChannelTrackingEntry { - channel_id, - unread_count, - mention_count, - }) - }) - .collect::>() - }) - .unwrap_or_default(); - - let global_bus_last_ids = object_field(&value, "meta") - .and_then(|meta| object_field(meta, "message_bus_last_ids")) - .and_then(Value::as_object) - .map(|map| { - map.iter() - .filter_map(|(channel, last_id)| { - let last_id = integer_i64(Some(last_id))?; - Some(ChatBusLastIdEntry { - channel: channel.clone(), - last_id, - }) - }) - .collect::>() - }) - .unwrap_or_default(); - - Ok(MyChatChannelsResponse { - public_channels, - direct_message_channels, - channel_tracking, - global_bus_last_ids, - }) -} - -pub(crate) fn parse_chat_channel_response_value( - value: Value, -) -> Result { - require_object(&value, "chat channel response root was not an object")?; - let channel_value = object_field(&value, "channel").unwrap_or(&value); - parse_chat_channel(channel_value) -} - -pub(crate) fn parse_chat_messages_response_value( - value: Value, - channel_id: u64, - base_url: &str, -) -> Result { - require_object(&value, "chat messages response root was not an object")?; - - let mut messages = optional_array_field(&value, "messages") - .map(|items| { - parse_array_items_lossy(items, "chat message", |item| { - parse_chat_message(item, Some(channel_id)) - }) - }) - .unwrap_or_default(); - for message in &mut messages { - crate::attach_chat_message_presentation(message, base_url); - } - - let meta = object_field(&value, "meta"); - Ok(ChatMessagesResponse { - messages, - can_load_more_past: boolean(meta.and_then(|meta| object_field(meta, "can_load_more_past"))), - can_load_more_future: boolean( - meta.and_then(|meta| object_field(meta, "can_load_more_future")), - ), - target_message_id: meta - .and_then(|meta| integer_u64(object_field(meta, "target_message_id"))), - }) -} - -pub(crate) fn parse_browse_chat_channels_value( - value: Value, -) -> Result, serde_json::Error> { - require_object( - &value, - "browse chat channels response root was not an object", - )?; - Ok(optional_array_field(&value, "channels") - .map(|items| parse_array_items_lossy(items, "browse chat channel", parse_chat_channel)) - .unwrap_or_default()) -} - -pub(crate) fn parse_chat_channel_members_value( - value: Value, -) -> Result, serde_json::Error> { - require_object( - &value, - "chat channel members response root was not an object", - )?; - Ok(optional_array_field(&value, "memberships") - .map(|items| { - parse_array_items_lossy(items, "chat channel member", parse_chat_channel_member) - }) - .unwrap_or_default()) -} - -pub(crate) fn parse_chat_search_result_value( - value: Value, -) -> Result { - require_object(&value, "chat search response root was not an object")?; - let messages = optional_array_field(&value, "messages") - .map(|items| { - parse_array_items_lossy(items, "chat search message", |item| { - parse_chat_message(item, None) - }) - }) - .unwrap_or_default(); - let has_more = - boolean(object_field(&value, "meta").and_then(|meta| object_field(meta, "has_more"))); - Ok(ChatSearchResult { messages, has_more }) -} - -pub(crate) fn parse_send_chat_message_id(value: &Value) -> Option { - integer_u64(object_field(value, "message_id")) -} - -pub(crate) fn parse_chat_thread_id_value(value: &Value) -> Option { - object_field(value, "thread") - .and_then(|thread| integer_u64(object_field(thread, "id"))) - .or_else(|| integer_u64(object_field(value, "id"))) -} - -pub(crate) fn parse_chat_channel_pins_value( - value: Value, - channel_id: u64, -) -> Result, serde_json::Error> { - require_object(&value, "chat pins response root was not an object")?; - Ok(optional_array_field(&value, "pinned_messages") - .map(|items| { - parse_array_items_lossy(items, "pinned chat message", |item| { - // pin envelope may be { message: {...} } - let message_value = object_field(item, "message").unwrap_or(item); - parse_chat_message(message_value, Some(channel_id)) - }) - }) - .unwrap_or_default()) -} - -/// Best-effort MessageBus envelope → domain message. -/// -/// Accepts `{ chat_message }`, `{ message }`, or a bare message object. -/// Parse failure is absence: live bus events must not fail the host. -pub fn chat_message_from_bus_payload( - payload_json: &str, - fallback_channel_id: Option, - base_url: &str, -) -> Option { - let value: Value = serde_json::from_str(payload_json).ok()?; - if !value.is_object() { - return None; - } - let message = object_field(&value, "chat_message") - .or_else(|| object_field(&value, "message")) - .unwrap_or(&value); - let mut parsed = parse_chat_message(message, fallback_channel_id).ok()?; - crate::attach_chat_message_presentation(&mut parsed, base_url); - Some(parsed) -} - -/// Typed chat MessageBus payload. `event_type` is the bus detail type when known. -pub fn chat_bus_event_from_payload( - payload_json: &str, - event_type: Option<&str>, - fallback_channel_id: Option, - base_url: &str, -) -> ChatBusEvent { - let Ok(value) = serde_json::from_str::(payload_json) else { - return ChatBusEvent::Ignored; - }; - if !value.is_object() { - return ChatBusEvent::Ignored; - } - - let kind = event_type.unwrap_or("").trim(); - match kind { - "delete" => { - if let Some(id) = integer_u64(object_field(&value, "deleted_id")) { - return ChatBusEvent::MessageDeleted { id }; - } - } - "reaction" => { - if let Some(event) = parse_chat_reaction_event(&value) { - return event; - } - } - "sent" - | "edit" - | "processed" - | "refresh" - | "restore" - | "thread_created" - | "update_thread_original_message" - | "pin" - | "unpin" => { - if let Some(message) = - chat_message_from_bus_payload(payload_json, fallback_channel_id, base_url) - { - return ChatBusEvent::MessageUpsert { - message: Box::new(message), - }; - } - } - _ => {} - } - - if integer_u64(object_field(&value, "deleted_id")).is_some() && kind.is_empty() { - if let Some(id) = integer_u64(object_field(&value, "deleted_id")) { - return ChatBusEvent::MessageDeleted { id }; - } - } - if object_field(&value, "unread_count").is_some() - || object_field(&value, "mention_count").is_some() - { - return ChatBusEvent::Tracking { - channel_id: integer_u64(object_field(&value, "channel_id")).unwrap_or(0), - unread: integer_u32(object_field(&value, "unread_count")).unwrap_or(0), - mention: integer_u32(object_field(&value, "mention_count")).unwrap_or(0), - thread_id: integer_u64(object_field(&value, "thread_id")), - }; - } - if let Some(channel) = chat_channel_from_bus_payload(payload_json, base_url) { - if channel.id > 0 { - return ChatBusEvent::ChannelUpsert { - channel: Box::new(channel), - }; - } - } - if object_field(&value, "type").is_some() || object_field(&value, "message").is_some() { - let message = object_field(&value, "message") - .and_then(|item| parse_chat_message(item, fallback_channel_id).ok()) - .map(|mut message| { - crate::attach_chat_message_presentation(&mut message, base_url); - message - }); - let actor_id = message - .as_ref() - .and_then(|item| item.user.as_ref().map(|user| user.id)); - return ChatBusEvent::NewMessages { - channel_id: fallback_channel_id - .or_else(|| integer_u64(object_field(&value, "channel_id"))) - .unwrap_or(0), - is_channel_level: scalar_string(object_field(&value, "type")) - .is_none_or(|value| value == "channel"), - message: message.map(Box::new), - actor_id, - }; - } - if let Some(event) = parse_chat_reaction_event(&value) { - return event; - } - ChatBusEvent::Ignored -} - -fn parse_chat_reaction_event(value: &Value) -> Option { - let message_id = integer_u64(object_field(value, "chat_message_id"))?; - let emoji = scalar_string(object_field(value, "emoji"))?; - let action = match scalar_string(object_field(value, "action")) - .unwrap_or_default() - .as_str() - { - "add" => ChatReactionAction::Add, - "remove" => ChatReactionAction::Remove, - _ => return None, - }; - let actor_id = - object_field(value, "user").and_then(|user| integer_u64(object_field(user, "id"))); - Some(ChatBusEvent::Reaction { - message_id, - emoji, - action, - actor_id, - }) -} - -/// Best-effort MessageBus envelope → domain channel, including last_message. -pub fn chat_channel_from_bus_payload(payload_json: &str, base_url: &str) -> Option { - let value: Value = serde_json::from_str(payload_json).ok()?; - if !value.is_object() { - return None; - } - let channel = object_field(&value, "channel").unwrap_or(&value); - let mut parsed = parse_chat_channel(channel).ok()?; - if let Some(message) = parsed.last_message.as_mut() { - crate::attach_chat_message_presentation(message, base_url); - } - Some(parsed) -} - -fn parse_chat_channel(value: &Value) -> Result { - require_object(value, "chat channel was not an object")?; - - let channel_id = required_u64_field(value, "id", "chat channel did not contain a valid id")?; - let chatable = object_field(value, "chatable"); - let membership = object_field(value, "current_user_membership"); - let last_message = object_field(value, "last_message"); - let meta = object_field(value, "meta"); - let bus_last_ids = meta - .and_then(|meta| object_field(meta, "message_bus_last_ids")) - .map(parse_bus_last_ids) - .unwrap_or_default(); - - let has_last_message = last_message - .and_then(|message| integer_u64(object_field(message, "id"))) - .is_some(); - - Ok(ChatChannel { - id: channel_id, - title: scalar_string(object_field(value, "title")), - unicode_title: scalar_string(object_field(value, "unicode_title")), - slug: scalar_string(object_field(value, "slug")), - description: scalar_string(object_field(value, "description")), - chatable_type: scalar_string(object_field(value, "chatable_type")).unwrap_or_default(), - status: scalar_string(object_field(value, "status")), - threading_enabled: boolean(object_field(value, "threading_enabled")), - memberships_count: integer_u32(object_field(value, "memberships_count")), - is_group_dm: boolean(chatable.and_then(|chatable| object_field(chatable, "group"))), - dm_users: chatable - .and_then(|chatable| optional_array_field(chatable, "users")) - .map(|items| parse_array_items_lossy(items, "chat dm user", parse_chat_user)) - .unwrap_or_default(), - category_color: chatable - .and_then(|chatable| scalar_string(object_field(chatable, "color"))), - category_name: chatable.and_then(|chatable| scalar_string(object_field(chatable, "name"))), - emoji: scalar_string(object_field(value, "emoji")), - current_user_membership: membership.map(parse_membership).transpose()?.flatten(), - last_message: if has_last_message { - last_message - .map(|message| parse_chat_message(message, Some(channel_id))) - .transpose()? - } else { - None - }, - bus_last_ids, - can_moderate: boolean(meta.and_then(|meta| object_field(meta, "can_moderate"))), - can_manage_pins: boolean(meta.and_then(|meta| object_field(meta, "can_manage_pins"))), - can_delete_self: boolean(meta.and_then(|meta| object_field(meta, "can_delete_self"))), - can_delete_others: boolean(meta.and_then(|meta| object_field(meta, "can_delete_others"))), - can_remove_members: boolean(meta.and_then(|meta| object_field(meta, "can_remove_members"))), - can_flag: boolean(meta.and_then(|meta| object_field(meta, "can_flag"))), - }) -} - -fn parse_membership(value: &Value) -> Result, serde_json::Error> { - if !value.is_object() { - return Ok(None); - } - Ok(Some(ChatChannelMembership { - following: boolean(object_field(value, "following")), - muted: boolean(object_field(value, "muted")), - starred: boolean(object_field(value, "starred")), - notification_level: scalar_string(object_field(value, "notification_level")), - last_read_message_id: integer_u64(object_field(value, "last_read_message_id")), - last_viewed_at: scalar_string(object_field(value, "last_viewed_at")), - })) -} - -fn parse_bus_last_ids(value: &Value) -> ChatChannelBusLastIds { - ChatChannelBusLastIds { - channel_message_bus_last_id: integer_i64(object_field( - value, - "channel_message_bus_last_id", - )), - new_messages: integer_i64(object_field(value, "new_messages")), - new_mentions: integer_i64(object_field(value, "new_mentions")), - kick: integer_i64(object_field(value, "kick")), - } -} - -fn parse_chat_message( - value: &Value, - fallback_channel_id: Option, -) -> Result { - require_object(value, "chat message was not an object")?; - - let user = object_field(value, "user") - .map(parse_chat_user) - .transpose()?; - let in_reply_to = object_field(value, "in_reply_to") - .map(parse_reply_ref) - .transpose()? - .flatten(); - let thread = object_field(value, "thread") - .map(parse_thread_ref) - .transpose()? - .flatten(); - let bookmark = object_field(value, "bookmark") - .map(parse_bookmark) - .transpose()? - .flatten(); - - Ok(ChatMessage { - id: integer_u64(object_field(value, "id")).unwrap_or(0), - channel_id: integer_u64(object_field(value, "chat_channel_id")) - .or_else(|| integer_u64(object_field(value, "channel_id"))) - .or(fallback_channel_id) - .unwrap_or(0), - message: scalar_string(object_field(value, "message")).unwrap_or_default(), - cooked: scalar_string(object_field(value, "cooked")).unwrap_or_default(), - excerpt: scalar_string(object_field(value, "excerpt")), - created_at: scalar_string(object_field(value, "created_at")), - deleted_at: scalar_string(object_field(value, "deleted_at")), - deleted_by_id: integer_u64(object_field(value, "deleted_by_id")), - edited: boolean(object_field(value, "edited")), - thread_id: integer_u64(object_field(value, "thread_id")), - thread, - user, - mentioned_users: optional_array_field(value, "mentioned_users") - .map(|items| parse_array_items_lossy(items, "mentioned chat user", parse_chat_user)) - .unwrap_or_default(), - reactions: optional_array_field(value, "reactions") - .map(|items| parse_array_items_lossy(items, "chat message reaction", parse_reaction)) - .unwrap_or_default(), - uploads: optional_array_field(value, "uploads") - .map(|items| parse_array_items_lossy(items, "chat upload", parse_upload)) - .unwrap_or_default(), - in_reply_to, - streaming: boolean(object_field(value, "streaming")), - available_flags: optional_array_field(value, "available_flags") - .map(|items| { - items - .iter() - .filter_map(|item| scalar_string(Some(item))) - .collect() - }) - .unwrap_or_default(), - user_flag_status: integer_i32(object_field(value, "user_flag_status")), - bookmark, - pinned: boolean(object_field(value, "pinned")), - presented: Default::default(), - }) -} - -fn parse_chat_user(value: &Value) -> Result { - require_object(value, "chat user was not an object")?; - Ok(ChatUser { - id: integer_u64(object_field(value, "id")).unwrap_or(0), - username: scalar_string(object_field(value, "username")).unwrap_or_default(), - name: scalar_string(object_field(value, "name")), - avatar_template: scalar_string(object_field(value, "avatar_template")), - }) -} - -fn parse_reaction(value: &Value) -> Result { - require_object(value, "chat reaction was not an object")?; - Ok(ChatMessageReaction { - emoji: scalar_string(object_field(value, "emoji")).unwrap_or_default(), - count: integer_u32(object_field(value, "count")).unwrap_or(0), - reacted: boolean(object_field(value, "reacted")), - users: optional_array_field(value, "users") - .map(|items| parse_array_items_lossy(items, "reaction user", parse_chat_user)) - .unwrap_or_default(), - }) -} - -fn parse_upload(value: &Value) -> Result { - require_object(value, "chat upload was not an object")?; - Ok(ChatUpload { - id: integer_u64(object_field(value, "id")).unwrap_or(0), - url: scalar_string(object_field(value, "url")), - short_url: scalar_string(object_field(value, "short_url")), - original_filename: scalar_string(object_field(value, "original_filename")), - extension: scalar_string(object_field(value, "extension")), - width: integer_u32(object_field(value, "width")), - height: integer_u32(object_field(value, "height")), - thumbnail_width: integer_u32(object_field(value, "thumbnail_width")), - thumbnail_height: integer_u32(object_field(value, "thumbnail_height")), - dominant_color: scalar_string(object_field(value, "dominant_color")), - }) -} - -fn parse_reply_ref(value: &Value) -> Result, serde_json::Error> { - if !value.is_object() { - return Ok(None); - } - let user = object_field(value, "user") - .map(parse_chat_user) - .transpose()?; - Ok(Some(ChatMessageReplyRef { - id: integer_u64(object_field(value, "id")).unwrap_or(0), - excerpt: scalar_string(object_field(value, "excerpt")), - user, - })) -} - -fn parse_thread_ref(value: &Value) -> Result, serde_json::Error> { - if !value.is_object() { - return Ok(None); - } - let preview = object_field(value, "preview"); - let last_reply_user = preview - .and_then(|preview| object_field(preview, "last_reply_user")) - .map(parse_chat_user) - .transpose()?; - Ok(Some(ChatThreadRef { - id: integer_u64(object_field(value, "id")).unwrap_or(0), - title: scalar_string(object_field(value, "title")), - reply_count: integer_u32(object_field(value, "reply_count")) - .or_else(|| { - preview.and_then(|preview| integer_u32(object_field(preview, "reply_count"))) - }) - .unwrap_or(0), - last_reply_created_at: preview - .and_then(|preview| scalar_string(object_field(preview, "last_reply_created_at"))), - last_reply_excerpt: preview - .and_then(|preview| scalar_string(object_field(preview, "last_reply_excerpt"))), - last_reply_user, - participants: preview - .and_then(|preview| optional_array_field(preview, "participant_users")) - .map(|items| parse_array_items_lossy(items, "thread participant", parse_chat_user)) - .unwrap_or_default(), - })) -} - -fn parse_bookmark(value: &Value) -> Result, serde_json::Error> { - if !value.is_object() { - return Ok(None); - } - Ok(Some(ChatMessageBookmark { - id: integer_u64(object_field(value, "id")).unwrap_or(0), - name: scalar_string(object_field(value, "name")), - reminder_at: scalar_string(object_field(value, "reminder_at")), - })) -} - -fn parse_chat_channel_member(value: &Value) -> Result { - require_object(value, "chat channel member was not an object")?; - let user_value = object_field(value, "user") - .ok_or_else(|| invalid_json("chat channel member did not contain a user object"))?; - Ok(ChatChannelMember { - user: parse_chat_user(user_value)?, - following: boolean(object_field(value, "following")), - muted: boolean(object_field(value, "muted")), - }) -} - -fn require_object(value: &Value, details: impl Into) -> Result<(), serde_json::Error> { - if value.is_object() { - Ok(()) - } else { - Err(invalid_json(details)) - } -} - -fn optional_array_field<'a>(value: &'a Value, key: &str) -> Option<&'a [Value]> { - match object_field(value, key) { - Some(Value::Array(items)) => Some(items.as_slice()), - Some(_) => { - warn!( - key, - "chat payload field was not an array; treating as empty" - ); - None - } - None => None, - } -} - -fn required_u64_field( - value: &Value, - key: &str, - details: impl Into, -) -> Result { - integer_u64(object_field(value, key)).ok_or_else(|| invalid_json(details)) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn parses_my_channels_with_tracking_and_dm() { - let value = json!({ - "public_channels": [{ - "id": 10, - "title": "general", - "chatable_type": "Category", - "chatable": {"name": "General", "color": "0088CC"}, - "current_user_membership": { - "following": true, - "muted": false, - "starred": true, - "last_read_message_id": 99 - }, - "meta": { - "can_flag": true, - "message_bus_last_ids": { - "new_messages": 12 - } - } - }], - "direct_message_channels": [{ - "id": 20, - "title": "@alice", - "unicode_title": "@alice", - "chatable_type": "DirectMessage", - "chatable": { - "group": false, - "users": [{ - "id": 2, - "username": "alice", - "name": "Alice", - "avatar_template": "/user_avatar/alice/{size}.png" - }] - }, - "last_message": { - "id": 5, - "message": "hello", - "cooked": "

hello

", - "user": {"id": 2, "username": "alice"} - } - }], - "tracking": { - "channel_tracking": { - "10": {"unread_count": 0, "mention_count": 1}, - "20": {"unread_count": 2, "mention_count": 0} - } - }, - "meta": { - "message_bus_last_ids": { - "user_tracking_state": 3, - "new_channel": 4 - } - } - }); - - let parsed = parse_my_chat_channels_response_value(value).expect("parse"); - assert_eq!(parsed.public_channels.len(), 1); - assert_eq!(parsed.direct_message_channels.len(), 1); - assert!(parsed.direct_message_channels[0].is_direct_message()); - assert_eq!( - parsed.direct_message_channels[0].dm_users[0].username, - "alice" - ); - assert_eq!( - parsed.direct_message_channels[0] - .last_message - .as_ref() - .map(|m| m.message.as_str()), - Some("hello") - ); - assert_eq!(parsed.channel_tracking.len(), 2); - assert_eq!(parsed.total_unread_badge(), 3); // mention 1 + dm unread 2 - assert_eq!(parsed.global_bus_last_ids.len(), 2); - assert_eq!( - parsed.public_channels[0].bus_last_ids.new_messages, - Some(12) - ); - } - - #[test] - fn parses_messages_page_meta() { - let value = json!({ - "messages": [{ - "id": 1, - "chat_channel_id": 20, - "message": "hi", - "cooked": "

hi

", - "edited": false, - "reactions": [{"emoji": "heart", "count": 1, "reacted": true}], - "uploads": [] - }], - "meta": { - "can_load_more_past": true, - "can_load_more_future": false, - "target_message_id": 1 - } - }); - let parsed = - parse_chat_messages_response_value(value, 20, "https://linux.do").expect("parse"); - assert_eq!(parsed.messages.len(), 1); - assert!(parsed.can_load_more_past); - assert!(!parsed.can_load_more_future); - assert_eq!(parsed.target_message_id, Some(1)); - assert_eq!(parsed.messages[0].reactions[0].emoji, "heart"); - } - - #[test] - fn chat_message_from_bus_payload_reads_nested_and_bare_objects() { - let nested = - r#"{"chat_message":{"id":7,"chat_channel_id":3,"message":"hi","cooked":"

hi

"}}"#; - let nested_message = chat_message_from_bus_payload(nested, Some(9), "https://linux.do") - .expect("nested chat_message"); - assert_eq!(nested_message.id, 7); - assert_eq!(nested_message.channel_id, 3); - assert_eq!(nested_message.cooked, "

hi

"); - - let aliased = r#"{"message":{"id":8,"message":"yo","cooked":"

yo

"}}"#; - let aliased_message = chat_message_from_bus_payload(aliased, Some(4), "https://linux.do") - .expect("message alias"); - assert_eq!(aliased_message.id, 8); - assert_eq!(aliased_message.channel_id, 4); - - assert!(chat_message_from_bus_payload("[]", None, "https://linux.do").is_none()); - assert!(chat_message_from_bus_payload("not-json", None, "https://linux.do").is_none()); - } - - #[test] - fn chat_channel_from_bus_payload_reads_last_message() { - let payload = r#"{ - "channel": { - "id": 20, - "title": "@alice", - "chatable_type": "DirectMessage", - "last_message": { - "id": 5, - "message": "hello", - "cooked": "

hello

" - } - } - }"#; - let channel = chat_channel_from_bus_payload(payload, "https://linux.do").expect("channel"); - assert!(channel.is_direct_message()); - assert_eq!( - channel.last_message.as_ref().map(|message| message.id), - Some(5) - ); - assert_eq!( - channel - .last_message - .as_ref() - .map(|message| message.cooked.as_str()), - Some("

hello

") - ); - } - - #[test] - fn chat_bus_event_reads_delete_reaction_and_tracking() { - let deleted = chat_bus_event_from_payload( - r#"{"deleted_id":42}"#, - Some("delete"), - None, - "https://linux.do", - ); - assert!(matches!( - deleted, - fire_models::ChatBusEvent::MessageDeleted { id: 42 } - )); - - let reaction = chat_bus_event_from_payload( - r#"{"chat_message_id":9,"emoji":"heart","action":"add","user":{"id":3}}"#, - Some("reaction"), - None, - "https://linux.do", - ); - assert!(matches!( - reaction, - fire_models::ChatBusEvent::Reaction { - message_id: 9, - actor_id: Some(3), - .. - } - )); - - let tracking = chat_bus_event_from_payload( - r#"{"channel_id":8,"unread_count":2,"mention_count":1}"#, - None, - None, - "https://linux.do", - ); - assert!(matches!( - tracking, - fire_models::ChatBusEvent::Tracking { - channel_id: 8, - unread: 2, - mention: 1, - thread_id: None, - } - )); - } -} diff --git a/crates/fire-core/src/chat_payloads/bus.rs b/crates/fire-core/src/chat_payloads/bus.rs new file mode 100644 index 00000000..45eb5509 --- /dev/null +++ b/crates/fire-core/src/chat_payloads/bus.rs @@ -0,0 +1,136 @@ +/// Best-effort MessageBus envelope → domain message. +/// +/// Accepts `{ chat_message }`, `{ message }`, or a bare message object. +/// Parse failure is absence: live bus events must not fail the host. +pub fn chat_message_from_bus_payload( + payload_json: &str, + fallback_channel_id: Option, + base_url: &str, +) -> Option { + let value: Value = serde_json::from_str(payload_json).ok()?; + if !value.is_object() { + return None; + } + let message = object_field(&value, "chat_message") + .or_else(|| object_field(&value, "message")) + .unwrap_or(&value); + let mut parsed = parse_chat_message(message, fallback_channel_id).ok()?; + crate::attach_chat_message_presentation(&mut parsed, base_url); + Some(parsed) +} + +/// Typed chat MessageBus payload. `event_type` is the bus detail type when known. +pub fn chat_bus_event_from_payload( + payload_json: &str, + event_type: Option<&str>, + fallback_channel_id: Option, + base_url: &str, +) -> ChatBusEvent { + let Ok(value) = serde_json::from_str::(payload_json) else { + return ChatBusEvent::Ignored; + }; + if !value.is_object() { + return ChatBusEvent::Ignored; + } + + let kind = event_type.unwrap_or("").trim(); + match kind { + "delete" => { + if let Some(id) = integer_u64(object_field(&value, "deleted_id")) { + return ChatBusEvent::MessageDeleted { id }; + } + } + "reaction" => { + if let Some(event) = parse_chat_reaction_event(&value) { + return event; + } + } + "sent" + | "edit" + | "processed" + | "refresh" + | "restore" + | "thread_created" + | "update_thread_original_message" + | "pin" + | "unpin" => { + if let Some(message) = + chat_message_from_bus_payload(payload_json, fallback_channel_id, base_url) + { + return ChatBusEvent::MessageUpsert { + message: Box::new(message), + }; + } + } + _ => {} + } + + if integer_u64(object_field(&value, "deleted_id")).is_some() && kind.is_empty() { + if let Some(id) = integer_u64(object_field(&value, "deleted_id")) { + return ChatBusEvent::MessageDeleted { id }; + } + } + if object_field(&value, "unread_count").is_some() + || object_field(&value, "mention_count").is_some() + { + return ChatBusEvent::Tracking { + channel_id: integer_u64(object_field(&value, "channel_id")).unwrap_or(0), + unread: integer_u32(object_field(&value, "unread_count")).unwrap_or(0), + mention: integer_u32(object_field(&value, "mention_count")).unwrap_or(0), + thread_id: integer_u64(object_field(&value, "thread_id")), + }; + } + if let Some(channel) = chat_channel_from_bus_payload(payload_json, base_url) { + if channel.id > 0 { + return ChatBusEvent::ChannelUpsert { + channel: Box::new(channel), + }; + } + } + if object_field(&value, "type").is_some() || object_field(&value, "message").is_some() { + let message = object_field(&value, "message") + .and_then(|item| parse_chat_message(item, fallback_channel_id).ok()) + .map(|mut message| { + crate::attach_chat_message_presentation(&mut message, base_url); + message + }); + let actor_id = message + .as_ref() + .and_then(|item| item.user.as_ref().map(|user| user.id)); + return ChatBusEvent::NewMessages { + channel_id: fallback_channel_id + .or_else(|| integer_u64(object_field(&value, "channel_id"))) + .unwrap_or(0), + is_channel_level: scalar_string(object_field(&value, "type")) + .is_none_or(|value| value == "channel"), + message: message.map(Box::new), + actor_id, + }; + } + if let Some(event) = parse_chat_reaction_event(&value) { + return event; + } + ChatBusEvent::Ignored +} + +fn parse_chat_reaction_event(value: &Value) -> Option { + let message_id = integer_u64(object_field(value, "chat_message_id"))?; + let emoji = scalar_string(object_field(value, "emoji"))?; + let action = match scalar_string(object_field(value, "action")) + .unwrap_or_default() + .as_str() + { + "add" => ChatReactionAction::Add, + "remove" => ChatReactionAction::Remove, + _ => return None, + }; + let actor_id = + object_field(value, "user").and_then(|user| integer_u64(object_field(user, "id"))); + Some(ChatBusEvent::Reaction { + message_id, + emoji, + action, + actor_id, + }) +} + diff --git a/crates/fire-core/src/chat_payloads/channels.rs b/crates/fire-core/src/chat_payloads/channels.rs new file mode 100644 index 00000000..10f0bacb --- /dev/null +++ b/crates/fire-core/src/chat_payloads/channels.rs @@ -0,0 +1,195 @@ +pub(crate) fn parse_my_chat_channels_response_value( + value: Value, +) -> Result { + require_object(&value, "my chat channels response root was not an object")?; + + let public_channels = optional_array_field(&value, "public_channels") + .map(|items| parse_array_items_lossy(items, "public chat channel", parse_chat_channel)) + .unwrap_or_default(); + let direct_message_channels = optional_array_field(&value, "direct_message_channels") + .map(|items| { + parse_array_items_lossy(items, "direct message chat channel", parse_chat_channel) + }) + .unwrap_or_default(); + + let channel_tracking = object_field(&value, "tracking") + .and_then(|tracking| object_field(tracking, "channel_tracking")) + .and_then(Value::as_object) + .map(|map| { + map.iter() + .filter_map(|(key, entry)| { + let channel_id = key.parse::().ok()?; + let unread_count = + integer_u32(object_field(entry, "unread_count")).unwrap_or(0); + let mention_count = + integer_u32(object_field(entry, "mention_count")).unwrap_or(0); + Some(ChatChannelTrackingEntry { + channel_id, + unread_count, + mention_count, + }) + }) + .collect::>() + }) + .unwrap_or_default(); + + let global_bus_last_ids = object_field(&value, "meta") + .and_then(|meta| object_field(meta, "message_bus_last_ids")) + .and_then(Value::as_object) + .map(|map| { + map.iter() + .filter_map(|(channel, last_id)| { + let last_id = integer_i64(Some(last_id))?; + Some(ChatBusLastIdEntry { + channel: channel.clone(), + last_id, + }) + }) + .collect::>() + }) + .unwrap_or_default(); + + Ok(MyChatChannelsResponse { + public_channels, + direct_message_channels, + channel_tracking, + global_bus_last_ids, + }) +} + +pub(crate) fn parse_chat_channel_response_value( + value: Value, +) -> Result { + require_object(&value, "chat channel response root was not an object")?; + let channel_value = object_field(&value, "channel").unwrap_or(&value); + parse_chat_channel(channel_value) +} + +pub(crate) fn parse_browse_chat_channels_value( + value: Value, +) -> Result, serde_json::Error> { + require_object( + &value, + "browse chat channels response root was not an object", + )?; + Ok(optional_array_field(&value, "channels") + .map(|items| parse_array_items_lossy(items, "browse chat channel", parse_chat_channel)) + .unwrap_or_default()) +} + +pub(crate) fn parse_chat_thread_id_value(value: &Value) -> Option { + object_field(value, "thread") + .and_then(|thread| integer_u64(object_field(thread, "id"))) + .or_else(|| integer_u64(object_field(value, "id"))) +} + +pub(crate) fn parse_chat_channel_pins_value( + value: Value, + channel_id: u64, +) -> Result, serde_json::Error> { + require_object(&value, "chat pins response root was not an object")?; + Ok(optional_array_field(&value, "pinned_messages") + .map(|items| { + parse_array_items_lossy(items, "pinned chat message", |item| { + // pin envelope may be { message: {...} } + let message_value = object_field(item, "message").unwrap_or(item); + parse_chat_message(message_value, Some(channel_id)) + }) + }) + .unwrap_or_default()) +} + +/// Best-effort MessageBus envelope → domain channel, including last_message. +pub fn chat_channel_from_bus_payload(payload_json: &str, base_url: &str) -> Option { + let value: Value = serde_json::from_str(payload_json).ok()?; + if !value.is_object() { + return None; + } + let channel = object_field(&value, "channel").unwrap_or(&value); + let mut parsed = parse_chat_channel(channel).ok()?; + if let Some(message) = parsed.last_message.as_mut() { + crate::attach_chat_message_presentation(message, base_url); + } + Some(parsed) +} + +fn parse_chat_channel(value: &Value) -> Result { + require_object(value, "chat channel was not an object")?; + + let channel_id = required_u64_field(value, "id", "chat channel did not contain a valid id")?; + let chatable = object_field(value, "chatable"); + let membership = object_field(value, "current_user_membership"); + let last_message = object_field(value, "last_message"); + let meta = object_field(value, "meta"); + let bus_last_ids = meta + .and_then(|meta| object_field(meta, "message_bus_last_ids")) + .map(parse_bus_last_ids) + .unwrap_or_default(); + + let has_last_message = last_message + .and_then(|message| integer_u64(object_field(message, "id"))) + .is_some(); + + Ok(ChatChannel { + id: channel_id, + title: scalar_string(object_field(value, "title")), + unicode_title: scalar_string(object_field(value, "unicode_title")), + slug: scalar_string(object_field(value, "slug")), + description: scalar_string(object_field(value, "description")), + chatable_type: scalar_string(object_field(value, "chatable_type")).unwrap_or_default(), + status: scalar_string(object_field(value, "status")), + threading_enabled: boolean(object_field(value, "threading_enabled")), + memberships_count: integer_u32(object_field(value, "memberships_count")), + is_group_dm: boolean(chatable.and_then(|chatable| object_field(chatable, "group"))), + dm_users: chatable + .and_then(|chatable| optional_array_field(chatable, "users")) + .map(|items| parse_array_items_lossy(items, "chat dm user", parse_chat_user)) + .unwrap_or_default(), + category_color: chatable + .and_then(|chatable| scalar_string(object_field(chatable, "color"))), + category_name: chatable.and_then(|chatable| scalar_string(object_field(chatable, "name"))), + emoji: scalar_string(object_field(value, "emoji")), + current_user_membership: membership.map(parse_membership).transpose()?.flatten(), + last_message: if has_last_message { + last_message + .map(|message| parse_chat_message(message, Some(channel_id))) + .transpose()? + } else { + None + }, + bus_last_ids, + can_moderate: boolean(meta.and_then(|meta| object_field(meta, "can_moderate"))), + can_manage_pins: boolean(meta.and_then(|meta| object_field(meta, "can_manage_pins"))), + can_delete_self: boolean(meta.and_then(|meta| object_field(meta, "can_delete_self"))), + can_delete_others: boolean(meta.and_then(|meta| object_field(meta, "can_delete_others"))), + can_remove_members: boolean(meta.and_then(|meta| object_field(meta, "can_remove_members"))), + can_flag: boolean(meta.and_then(|meta| object_field(meta, "can_flag"))), + }) +} + +fn parse_membership(value: &Value) -> Result, serde_json::Error> { + if !value.is_object() { + return Ok(None); + } + Ok(Some(ChatChannelMembership { + following: boolean(object_field(value, "following")), + muted: boolean(object_field(value, "muted")), + starred: boolean(object_field(value, "starred")), + notification_level: scalar_string(object_field(value, "notification_level")), + last_read_message_id: integer_u64(object_field(value, "last_read_message_id")), + last_viewed_at: scalar_string(object_field(value, "last_viewed_at")), + })) +} + +fn parse_bus_last_ids(value: &Value) -> ChatChannelBusLastIds { + ChatChannelBusLastIds { + channel_message_bus_last_id: integer_i64(object_field( + value, + "channel_message_bus_last_id", + )), + new_messages: integer_i64(object_field(value, "new_messages")), + new_mentions: integer_i64(object_field(value, "new_mentions")), + kick: integer_i64(object_field(value, "kick")), + } +} + diff --git a/crates/fire-core/src/chat_payloads/helpers.rs b/crates/fire-core/src/chat_payloads/helpers.rs new file mode 100644 index 00000000..b7a7a18a --- /dev/null +++ b/crates/fire-core/src/chat_payloads/helpers.rs @@ -0,0 +1,30 @@ +fn require_object(value: &Value, details: impl Into) -> Result<(), serde_json::Error> { + if value.is_object() { + Ok(()) + } else { + Err(invalid_json(details)) + } +} + +fn optional_array_field<'a>(value: &'a Value, key: &str) -> Option<&'a [Value]> { + match object_field(value, key) { + Some(Value::Array(items)) => Some(items.as_slice()), + Some(_) => { + warn!( + key, + "chat payload field was not an array; treating as empty" + ); + None + } + None => None, + } +} + +fn required_u64_field( + value: &Value, + key: &str, + details: impl Into, +) -> Result { + integer_u64(object_field(value, key)).ok_or_else(|| invalid_json(details)) +} + diff --git a/crates/fire-core/src/chat_payloads/members.rs b/crates/fire-core/src/chat_payloads/members.rs new file mode 100644 index 00000000..c084b9b9 --- /dev/null +++ b/crates/fire-core/src/chat_payloads/members.rs @@ -0,0 +1,25 @@ +pub(crate) fn parse_chat_channel_members_value( + value: Value, +) -> Result, serde_json::Error> { + require_object( + &value, + "chat channel members response root was not an object", + )?; + Ok(optional_array_field(&value, "memberships") + .map(|items| { + parse_array_items_lossy(items, "chat channel member", parse_chat_channel_member) + }) + .unwrap_or_default()) +} + +fn parse_chat_channel_member(value: &Value) -> Result { + require_object(value, "chat channel member was not an object")?; + let user_value = object_field(value, "user") + .ok_or_else(|| invalid_json("chat channel member did not contain a user object"))?; + Ok(ChatChannelMember { + user: parse_chat_user(user_value)?, + following: boolean(object_field(value, "following")), + muted: boolean(object_field(value, "muted")), + }) +} + diff --git a/crates/fire-core/src/chat_payloads/messages.rs b/crates/fire-core/src/chat_payloads/messages.rs new file mode 100644 index 00000000..f6548bd2 --- /dev/null +++ b/crates/fire-core/src/chat_payloads/messages.rs @@ -0,0 +1,114 @@ +pub(crate) fn parse_chat_messages_response_value( + value: Value, + channel_id: u64, + base_url: &str, +) -> Result { + require_object(&value, "chat messages response root was not an object")?; + + let mut messages = optional_array_field(&value, "messages") + .map(|items| { + parse_array_items_lossy(items, "chat message", |item| { + parse_chat_message(item, Some(channel_id)) + }) + }) + .unwrap_or_default(); + for message in &mut messages { + crate::attach_chat_message_presentation(message, base_url); + } + + let meta = object_field(&value, "meta"); + Ok(ChatMessagesResponse { + messages, + can_load_more_past: boolean(meta.and_then(|meta| object_field(meta, "can_load_more_past"))), + can_load_more_future: boolean( + meta.and_then(|meta| object_field(meta, "can_load_more_future")), + ), + target_message_id: meta + .and_then(|meta| integer_u64(object_field(meta, "target_message_id"))), + }) +} + +pub(crate) fn parse_chat_search_result_value( + value: Value, +) -> Result { + require_object(&value, "chat search response root was not an object")?; + let messages = optional_array_field(&value, "messages") + .map(|items| { + parse_array_items_lossy(items, "chat search message", |item| { + parse_chat_message(item, None) + }) + }) + .unwrap_or_default(); + let has_more = + boolean(object_field(&value, "meta").and_then(|meta| object_field(meta, "has_more"))); + Ok(ChatSearchResult { messages, has_more }) +} + +pub(crate) fn parse_send_chat_message_id(value: &Value) -> Option { + integer_u64(object_field(value, "message_id")) +} + +fn parse_chat_message( + value: &Value, + fallback_channel_id: Option, +) -> Result { + require_object(value, "chat message was not an object")?; + + let user = object_field(value, "user") + .map(parse_chat_user) + .transpose()?; + let in_reply_to = object_field(value, "in_reply_to") + .map(parse_reply_ref) + .transpose()? + .flatten(); + let thread = object_field(value, "thread") + .map(parse_thread_ref) + .transpose()? + .flatten(); + let bookmark = object_field(value, "bookmark") + .map(parse_bookmark) + .transpose()? + .flatten(); + + Ok(ChatMessage { + id: integer_u64(object_field(value, "id")).unwrap_or(0), + channel_id: integer_u64(object_field(value, "chat_channel_id")) + .or_else(|| integer_u64(object_field(value, "channel_id"))) + .or(fallback_channel_id) + .unwrap_or(0), + message: scalar_string(object_field(value, "message")).unwrap_or_default(), + cooked: scalar_string(object_field(value, "cooked")).unwrap_or_default(), + excerpt: scalar_string(object_field(value, "excerpt")), + created_at: scalar_string(object_field(value, "created_at")), + deleted_at: scalar_string(object_field(value, "deleted_at")), + deleted_by_id: integer_u64(object_field(value, "deleted_by_id")), + edited: boolean(object_field(value, "edited")), + thread_id: integer_u64(object_field(value, "thread_id")), + thread, + user, + mentioned_users: optional_array_field(value, "mentioned_users") + .map(|items| parse_array_items_lossy(items, "mentioned chat user", parse_chat_user)) + .unwrap_or_default(), + reactions: optional_array_field(value, "reactions") + .map(|items| parse_array_items_lossy(items, "chat message reaction", parse_reaction)) + .unwrap_or_default(), + uploads: optional_array_field(value, "uploads") + .map(|items| parse_array_items_lossy(items, "chat upload", parse_upload)) + .unwrap_or_default(), + in_reply_to, + streaming: boolean(object_field(value, "streaming")), + available_flags: optional_array_field(value, "available_flags") + .map(|items| { + items + .iter() + .filter_map(|item| scalar_string(Some(item))) + .collect() + }) + .unwrap_or_default(), + user_flag_status: integer_i32(object_field(value, "user_flag_status")), + bookmark, + pinned: boolean(object_field(value, "pinned")), + presented: Default::default(), + }) +} + diff --git a/crates/fire-core/src/chat_payloads/mod.rs b/crates/fire-core/src/chat_payloads/mod.rs new file mode 100644 index 00000000..3ec94ac1 --- /dev/null +++ b/crates/fire-core/src/chat_payloads/mod.rs @@ -0,0 +1,21 @@ +use fire_models::{ + ChatBusEvent, ChatBusLastIdEntry, ChatChannel, ChatChannelBusLastIds, ChatChannelMember, + ChatChannelMembership, ChatChannelTrackingEntry, ChatMessage, ChatMessageBookmark, + ChatMessageReaction, ChatMessageReplyRef, ChatMessagesResponse, ChatReactionAction, + ChatSearchResult, ChatThreadRef, ChatUpload, ChatUser, MyChatChannelsResponse, +}; +use serde_json::Value; +use tracing::warn; + +use crate::json_helpers::{ + boolean, integer_i32, integer_i64, integer_u32, integer_u64, invalid_json, object_field, + parse_array_items_lossy, scalar_string, +}; + +include!("channels.rs"); +include!("messages.rs"); +include!("members.rs"); +include!("bus.rs"); +include!("nested.rs"); +include!("helpers.rs"); +include!("tests.rs"); diff --git a/crates/fire-core/src/chat_payloads/nested.rs b/crates/fire-core/src/chat_payloads/nested.rs new file mode 100644 index 00000000..3b5a95b5 --- /dev/null +++ b/crates/fire-core/src/chat_payloads/nested.rs @@ -0,0 +1,92 @@ +fn parse_chat_user(value: &Value) -> Result { + require_object(value, "chat user was not an object")?; + Ok(ChatUser { + id: integer_u64(object_field(value, "id")).unwrap_or(0), + username: scalar_string(object_field(value, "username")).unwrap_or_default(), + name: scalar_string(object_field(value, "name")), + avatar_template: scalar_string(object_field(value, "avatar_template")), + }) +} + +fn parse_reaction(value: &Value) -> Result { + require_object(value, "chat reaction was not an object")?; + Ok(ChatMessageReaction { + emoji: scalar_string(object_field(value, "emoji")).unwrap_or_default(), + count: integer_u32(object_field(value, "count")).unwrap_or(0), + reacted: boolean(object_field(value, "reacted")), + users: optional_array_field(value, "users") + .map(|items| parse_array_items_lossy(items, "reaction user", parse_chat_user)) + .unwrap_or_default(), + }) +} + +fn parse_upload(value: &Value) -> Result { + require_object(value, "chat upload was not an object")?; + Ok(ChatUpload { + id: integer_u64(object_field(value, "id")).unwrap_or(0), + url: scalar_string(object_field(value, "url")), + short_url: scalar_string(object_field(value, "short_url")), + original_filename: scalar_string(object_field(value, "original_filename")), + extension: scalar_string(object_field(value, "extension")), + width: integer_u32(object_field(value, "width")), + height: integer_u32(object_field(value, "height")), + thumbnail_width: integer_u32(object_field(value, "thumbnail_width")), + thumbnail_height: integer_u32(object_field(value, "thumbnail_height")), + dominant_color: scalar_string(object_field(value, "dominant_color")), + }) +} + +fn parse_reply_ref(value: &Value) -> Result, serde_json::Error> { + if !value.is_object() { + return Ok(None); + } + let user = object_field(value, "user") + .map(parse_chat_user) + .transpose()?; + Ok(Some(ChatMessageReplyRef { + id: integer_u64(object_field(value, "id")).unwrap_or(0), + excerpt: scalar_string(object_field(value, "excerpt")), + user, + })) +} + +fn parse_thread_ref(value: &Value) -> Result, serde_json::Error> { + if !value.is_object() { + return Ok(None); + } + let preview = object_field(value, "preview"); + let last_reply_user = preview + .and_then(|preview| object_field(preview, "last_reply_user")) + .map(parse_chat_user) + .transpose()?; + Ok(Some(ChatThreadRef { + id: integer_u64(object_field(value, "id")).unwrap_or(0), + title: scalar_string(object_field(value, "title")), + reply_count: integer_u32(object_field(value, "reply_count")) + .or_else(|| { + preview.and_then(|preview| integer_u32(object_field(preview, "reply_count"))) + }) + .unwrap_or(0), + last_reply_created_at: preview + .and_then(|preview| scalar_string(object_field(preview, "last_reply_created_at"))), + last_reply_excerpt: preview + .and_then(|preview| scalar_string(object_field(preview, "last_reply_excerpt"))), + last_reply_user, + participants: preview + .and_then(|preview| optional_array_field(preview, "participant_users")) + .map(|items| parse_array_items_lossy(items, "thread participant", parse_chat_user)) + .unwrap_or_default(), + })) +} + +fn parse_bookmark(value: &Value) -> Result, serde_json::Error> { + if !value.is_object() { + return Ok(None); + } + Ok(Some(ChatMessageBookmark { + id: integer_u64(object_field(value, "id")).unwrap_or(0), + name: scalar_string(object_field(value, "name")), + reminder_at: scalar_string(object_field(value, "reminder_at")), + })) +} + diff --git a/crates/fire-core/src/chat_payloads/tests.rs b/crates/fire-core/src/chat_payloads/tests.rs new file mode 100644 index 00000000..c43b9379 --- /dev/null +++ b/crates/fire-core/src/chat_payloads/tests.rs @@ -0,0 +1,206 @@ +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn parses_my_channels_with_tracking_and_dm() { + let value = json!({ + "public_channels": [{ + "id": 10, + "title": "general", + "chatable_type": "Category", + "chatable": {"name": "General", "color": "0088CC"}, + "current_user_membership": { + "following": true, + "muted": false, + "starred": true, + "last_read_message_id": 99 + }, + "meta": { + "can_flag": true, + "message_bus_last_ids": { + "new_messages": 12 + } + } + }], + "direct_message_channels": [{ + "id": 20, + "title": "@alice", + "unicode_title": "@alice", + "chatable_type": "DirectMessage", + "chatable": { + "group": false, + "users": [{ + "id": 2, + "username": "alice", + "name": "Alice", + "avatar_template": "/user_avatar/alice/{size}.png" + }] + }, + "last_message": { + "id": 5, + "message": "hello", + "cooked": "

hello

", + "user": {"id": 2, "username": "alice"} + } + }], + "tracking": { + "channel_tracking": { + "10": {"unread_count": 0, "mention_count": 1}, + "20": {"unread_count": 2, "mention_count": 0} + } + }, + "meta": { + "message_bus_last_ids": { + "user_tracking_state": 3, + "new_channel": 4 + } + } + }); + + let parsed = parse_my_chat_channels_response_value(value).expect("parse"); + assert_eq!(parsed.public_channels.len(), 1); + assert_eq!(parsed.direct_message_channels.len(), 1); + assert!(parsed.direct_message_channels[0].is_direct_message()); + assert_eq!( + parsed.direct_message_channels[0].dm_users[0].username, + "alice" + ); + assert_eq!( + parsed.direct_message_channels[0] + .last_message + .as_ref() + .map(|m| m.message.as_str()), + Some("hello") + ); + assert_eq!(parsed.channel_tracking.len(), 2); + assert_eq!(parsed.total_unread_badge(), 3); // mention 1 + dm unread 2 + assert_eq!(parsed.global_bus_last_ids.len(), 2); + assert_eq!( + parsed.public_channels[0].bus_last_ids.new_messages, + Some(12) + ); + } + + #[test] + fn parses_messages_page_meta() { + let value = json!({ + "messages": [{ + "id": 1, + "chat_channel_id": 20, + "message": "hi", + "cooked": "

hi

", + "edited": false, + "reactions": [{"emoji": "heart", "count": 1, "reacted": true}], + "uploads": [] + }], + "meta": { + "can_load_more_past": true, + "can_load_more_future": false, + "target_message_id": 1 + } + }); + let parsed = + parse_chat_messages_response_value(value, 20, "https://linux.do").expect("parse"); + assert_eq!(parsed.messages.len(), 1); + assert!(parsed.can_load_more_past); + assert!(!parsed.can_load_more_future); + assert_eq!(parsed.target_message_id, Some(1)); + assert_eq!(parsed.messages[0].reactions[0].emoji, "heart"); + } + + #[test] + fn chat_message_from_bus_payload_reads_nested_and_bare_objects() { + let nested = + r#"{"chat_message":{"id":7,"chat_channel_id":3,"message":"hi","cooked":"

hi

"}}"#; + let nested_message = chat_message_from_bus_payload(nested, Some(9), "https://linux.do") + .expect("nested chat_message"); + assert_eq!(nested_message.id, 7); + assert_eq!(nested_message.channel_id, 3); + assert_eq!(nested_message.cooked, "

hi

"); + + let aliased = r#"{"message":{"id":8,"message":"yo","cooked":"

yo

"}}"#; + let aliased_message = chat_message_from_bus_payload(aliased, Some(4), "https://linux.do") + .expect("message alias"); + assert_eq!(aliased_message.id, 8); + assert_eq!(aliased_message.channel_id, 4); + + assert!(chat_message_from_bus_payload("[]", None, "https://linux.do").is_none()); + assert!(chat_message_from_bus_payload("not-json", None, "https://linux.do").is_none()); + } + + #[test] + fn chat_channel_from_bus_payload_reads_last_message() { + let payload = r#"{ + "channel": { + "id": 20, + "title": "@alice", + "chatable_type": "DirectMessage", + "last_message": { + "id": 5, + "message": "hello", + "cooked": "

hello

" + } + } + }"#; + let channel = chat_channel_from_bus_payload(payload, "https://linux.do").expect("channel"); + assert!(channel.is_direct_message()); + assert_eq!( + channel.last_message.as_ref().map(|message| message.id), + Some(5) + ); + assert_eq!( + channel + .last_message + .as_ref() + .map(|message| message.cooked.as_str()), + Some("

hello

") + ); + } + + #[test] + fn chat_bus_event_reads_delete_reaction_and_tracking() { + let deleted = chat_bus_event_from_payload( + r#"{"deleted_id":42}"#, + Some("delete"), + None, + "https://linux.do", + ); + assert!(matches!( + deleted, + fire_models::ChatBusEvent::MessageDeleted { id: 42 } + )); + + let reaction = chat_bus_event_from_payload( + r#"{"chat_message_id":9,"emoji":"heart","action":"add","user":{"id":3}}"#, + Some("reaction"), + None, + "https://linux.do", + ); + assert!(matches!( + reaction, + fire_models::ChatBusEvent::Reaction { + message_id: 9, + actor_id: Some(3), + .. + } + )); + + let tracking = chat_bus_event_from_payload( + r#"{"channel_id":8,"unread_count":2,"mention_count":1}"#, + None, + None, + "https://linux.do", + ); + assert!(matches!( + tracking, + fire_models::ChatBusEvent::Tracking { + channel_id: 8, + unread: 2, + mention: 1, + thread_id: None, + } + )); + } +} diff --git a/crates/fire-core/src/cookies.rs b/crates/fire-core/src/cookies.rs deleted file mode 100644 index 3aafb731..00000000 --- a/crates/fire-core/src/cookies.rs +++ /dev/null @@ -1,860 +0,0 @@ -use std::collections::HashSet; -use std::sync::{Arc, Mutex, RwLock}; - -use fire_models::{ - CanonicalCookie, CanonicalCookieStore, CookieSameSite, CookieSnapshot, CookieSource, - CookieTrust, -}; -use http::header::HeaderValue; -use openwire::CookieJar; -use time::{format_description::well_known::Rfc2822, OffsetDateTime}; -use tracing::warn; -use url::Url; - -use crate::core::{ - mutate_runtime_session_tracking_auth_change, FireAuthChangeSource, FireSessionRuntimeState, -}; -use crate::sync_utils::{read_rwlock, write_rwlock}; - -#[derive(Clone)] -pub(crate) struct FireSessionCookieJar { - base_url: Url, - session: Arc>, - store: Option>>, -} - -impl FireSessionCookieJar { - pub(crate) fn new( - base_url: Url, - session: Arc>, - store: Option>>, - ) -> Self { - Self { - base_url, - session, - store, - } - } -} - -tokio::task_local! { - pub(crate) static FIRE_REQUEST_EPOCH: u64; -} - -tokio::task_local! { - pub(crate) static FIRE_REQUEST_TRACE_ID: u64; -} - -impl CookieJar for FireSessionCookieJar { - fn set_cookies(&self, cookie_headers: &mut dyn Iterator, url: &Url) { - if !same_site_scope(&self.base_url, url) { - return; - } - - let request_epoch = FIRE_REQUEST_EPOCH.try_with(|epoch| *epoch).ok(); - if is_stale_request_epoch(&self.session, request_epoch) { - return; - } - - let mut patch = CookieSnapshot::default(); - let mut canonical_writes = Vec::new(); - let mut canonical_deletes = Vec::new(); - let mut replay_entries: Vec<(String, String, String)> = Vec::new(); - for header in cookie_headers { - let Ok(value) = header.to_str() else { - continue; - }; - let Some(cookie) = parse_set_cookie(value, url) else { - continue; - }; - let canonical_cookie = parse_set_cookie_canonical(value, url); - - if should_ignore_network_auth_cookie_deletion(&cookie) { - continue; - } - - if cookie.value.is_empty() || cookie.is_expired_now() { - canonical_deletes.push(cookie.name.clone()); - } else if let Some(canonical_cookie) = canonical_cookie { - canonical_writes.push(canonical_cookie); - } - - match cookie.name.as_str() { - "_t" => patch.t_token = Some(cookie.value.clone()), - "_forum_session" => patch.forum_session = Some(cookie.value.clone()), - "cf_clearance" => patch.cf_clearance = Some(cookie.value.clone()), - _ => {} - } - // cf_clearance must not be replayed jar → WebView. Only browser/WebView - // authored clearance is trustworthy; Set-Cookie replay can drop - // Partitioned and create a ghost variant. - if !cookie.name.eq_ignore_ascii_case("cf_clearance") { - let replay_domain = cookie - .domain - .as_deref() - .map(|d| d.trim_start_matches('.').to_string()) - .unwrap_or_default(); - replay_entries.push((value.to_string(), cookie.name.clone(), replay_domain)); - } - patch.platform_cookies.push(cookie); - } - - if patch == CookieSnapshot::default() - && canonical_writes.is_empty() - && canonical_deletes.is_empty() - { - return; - } - - let mut session = write_rwlock(&self.session, "session"); - mutate_runtime_session_tracking_auth_change( - &mut session, - FireAuthChangeSource::NetworkIngress, - "network set-cookie ingress", - |snapshot| { - snapshot.cookies.merge_patch(&patch); - for name in &canonical_deletes { - snapshot.cookies.delete_canonical_cookie_by_name(url, name); - } - if !canonical_writes.is_empty() { - snapshot.cookies.merge_canonical_cookies( - url, - &canonical_writes, - CookieTrust::Trusted, - ); - } - }, - ); - - if let Some(store) = self.store.as_ref() { - let Ok(store) = store.lock() else { - return; - }; - for (raw_set_cookie, cookie_name, domain) in replay_entries { - let url = self.base_url.as_str(); - if let Err(error) = store.cookie_replay_enqueue( - url, - &raw_set_cookie, - &cookie_name, - &domain, - fire_models::current_unix_ms() as u64, - ) { - warn!( - cookie_name = %cookie_name, - %error, - "failed to enqueue Set-Cookie into replay queue" - ); - } - } - } - } - - fn cookies(&self, url: &Url) -> Option { - let session = read_rwlock(&self.session, "session"); - let snapshot = &session.snapshot; - if snapshot.cookies.platform_cookies.is_empty() - && snapshot.cookies.canonical_cookies.is_empty() - { - if !same_origin_scope(&self.base_url, url) { - return None; - } - } else if !same_site_scope(&self.base_url, url) { - return None; - } - - let cookies = build_cookie_header(&snapshot.cookies, &self.base_url, url); - if cookies.is_empty() { - return None; - } - - HeaderValue::from_str(&cookies).ok() - } -} - -fn should_ignore_network_auth_cookie_deletion(cookie: &fire_models::PlatformCookie) -> bool { - cookie.value.is_empty() && matches!(cookie.name.as_str(), "_t" | "_forum_session") -} - -fn same_origin_scope(base_url: &Url, request_url: &Url) -> bool { - base_url.scheme() == request_url.scheme() - && base_url.host_str() == request_url.host_str() - && base_url.port_or_known_default() == request_url.port_or_known_default() -} - -fn same_site_scope(base_url: &Url, request_url: &Url) -> bool { - base_url.scheme() == request_url.scheme() - && hosts_share_base_domain(base_url.host_str(), request_url.host_str()) -} - -fn hosts_share_base_domain(base_host: Option<&str>, request_host: Option<&str>) -> bool { - let Some(base_host) = base_host.map(|value| value.trim_start_matches('.').to_ascii_lowercase()) - else { - return false; - }; - let Some(request_host) = - request_host.map(|value| value.trim_start_matches('.').to_ascii_lowercase()) - else { - return false; - }; - request_host == base_host || request_host.ends_with(&format!(".{base_host}")) -} - -fn build_cookie_header(cookies: &CookieSnapshot, base_url: &Url, request_url: &Url) -> String { - let canonical_known_names = canonical_cookie_names(cookies); - let canonical_header = build_canonical_cookie_header(cookies, request_url); - if !canonical_header.is_empty() && cookies.platform_cookies.is_empty() { - return canonical_header; - } - - if !cookies.platform_cookies.is_empty() { - let request_host = request_url - .host_str() - .map(|value| value.to_ascii_lowercase()); - let mut matching = cookies - .platform_cookies - .iter() - .enumerate() - .filter(|(_, cookie)| { - !canonical_known_names.contains(&cookie.name) - && cookie_matches_url(cookie, base_url, request_url) - }) - .collect::>(); - matching.sort_by(|(left_index, left), (right_index, right)| { - let left_path_len = left.path.as_deref().unwrap_or("/").len(); - let right_path_len = right.path.as_deref().unwrap_or("/").len(); - right_path_len - .cmp(&left_path_len) - .then_with(|| { - cookie_send_precedence(right, request_host.as_deref()) - .cmp(&cookie_send_precedence(left, request_host.as_deref())) - }) - .then_with(|| right_index.cmp(left_index)) - }); - - let mut seen = HashSet::new(); - let joined = matching - .into_iter() - .filter_map(|(_, cookie)| { - let value = cookie.value.trim(); - if value.is_empty() { - return None; - } - - let dedupe_key = ( - cookie.name.clone(), - cookie.path.as_deref().unwrap_or("/").to_string(), - ); - if !seen.insert(dedupe_key) { - return None; - } - - Some(format!("{}={}", cookie.name, value)) - }) - .collect::>() - .join("; "); - return join_cookie_headers(&canonical_header, &joined); - } - - if !canonical_header.is_empty() { - return canonical_header; - } - - let mut pairs = Vec::new(); - if !canonical_known_names.contains("_t") { - push_cookie_pair(&mut pairs, "_t", cookies.t_token.as_deref()); - } - if !canonical_known_names.contains("_forum_session") { - push_cookie_pair( - &mut pairs, - "_forum_session", - cookies.forum_session.as_deref(), - ); - } - if !canonical_known_names.contains("cf_clearance") { - push_cookie_pair(&mut pairs, "cf_clearance", cookies.cf_clearance.as_deref()); - } - pairs.join("; ") -} - -fn build_canonical_cookie_header(cookies: &CookieSnapshot, request_url: &Url) -> String { - if cookies.canonical_cookies.is_empty() { - return String::new(); - } - - let store = CanonicalCookieStore::from_cookies(cookies.canonical_cookies.clone()); - let mut seen_critical_names = HashSet::new(); - store - .load_for_request(request_url) - .into_iter() - .filter_map(|cookie| { - let value = cookie.value.trim(); - if value.is_empty() { - return None; - } - if is_critical_cookie_name(&cookie.name) - && !seen_critical_names.insert(cookie.name.clone()) - { - return None; - } - Some(format!("{}={}", cookie.name, value)) - }) - .collect::>() - .join("; ") -} - -fn canonical_cookie_names(cookies: &CookieSnapshot) -> HashSet { - cookies - .canonical_cookies - .iter() - .filter(|cookie| !cookie.is_expired_now() && !cookie.value.trim().is_empty()) - .map(|cookie| cookie.name.clone()) - .collect() -} - -fn join_cookie_headers(left: &str, right: &str) -> String { - match (left.is_empty(), right.is_empty()) { - (true, true) => String::new(), - (false, true) => left.to_string(), - (true, false) => right.to_string(), - (false, false) => format!("{left}; {right}"), - } -} - -fn is_critical_cookie_name(name: &str) -> bool { - matches!( - name, - "_t" | "_forum_session" | "cf_clearance" | "_cfuvid" | "h_captcha_temp_id" - ) -} - -fn push_cookie_pair(pairs: &mut Vec, name: &str, value: Option<&str>) { - let Some(value) = value.filter(|value| !value.is_empty()) else { - return; - }; - pairs.push(format!("{name}={value}")); -} - -fn is_stale_request_epoch( - session: &Arc>, - request_epoch: Option, -) -> bool { - let Some(request_epoch) = request_epoch else { - return false; - }; - let current_epoch = read_rwlock(session, "session").epoch; - current_epoch != request_epoch -} - -fn cookie_send_precedence( - cookie: &fire_models::PlatformCookie, - request_host: Option<&str>, -) -> (u8, usize) { - let Some(domain) = cookie - .domain - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - else { - return (3, request_host.map_or(0, str::len)); - }; - - let normalized_domain = domain.trim_start_matches('.'); - let exact_host_match = request_host - .is_some_and(|request_host| request_host.eq_ignore_ascii_case(normalized_domain)); - let rank = if domain.starts_with('.') { - if exact_host_match { - 2 - } else { - 1 - } - } else if exact_host_match { - 3 - } else { - 2 - }; - (rank, normalized_domain.len()) -} - -fn cookie_matches_url( - cookie: &fire_models::PlatformCookie, - base_url: &Url, - request_url: &Url, -) -> bool { - if cookie.is_expired_now() { - return false; - } - - if request_url.scheme() != base_url.scheme() { - return false; - } - - let Some(request_host) = request_url - .host_str() - .map(|value| value.to_ascii_lowercase()) - else { - return false; - }; - let base_host = base_url.host_str().map(|value| value.to_ascii_lowercase()); - let raw_cookie_domain = cookie - .domain - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(|value| value.to_ascii_lowercase()); - let allows_subdomains = raw_cookie_domain - .as_deref() - .is_some_and(|value| value.starts_with('.')); - let cookie_domain = raw_cookie_domain - .as_deref() - .map(|value| value.trim_start_matches('.').to_string()) - .or(base_host); - - let Some(cookie_domain) = cookie_domain else { - return false; - }; - if allows_subdomains { - if request_host != cookie_domain && !request_host.ends_with(&format!(".{cookie_domain}")) { - return false; - } - } else if request_host != cookie_domain { - return false; - } - - let request_path = request_url.path(); - let cookie_path = cookie.path.as_deref().unwrap_or("/"); - request_path.starts_with(cookie_path) -} - -fn parse_set_cookie(value: &str, url: &Url) -> Option { - let now_unix_ms = now_unix_ms(); - let mut parts = value.split(';'); - let first = parts.next()?.trim(); - let (name, value) = first.split_once('=')?; - let mut domain = url.host_str().map(|value| value.to_ascii_lowercase()); - let mut path = Some(default_cookie_path(url.path())); - let mut expires_at_unix_ms = None; - let mut max_age_expires_at_unix_ms = None; - let mut has_domain_attribute = false; - - for attribute in parts { - let attribute = attribute.trim(); - if let Some((key, raw_value)) = attribute.split_once('=') { - let key = key.trim(); - let raw_value = raw_value.trim(); - if key.eq_ignore_ascii_case("domain") && !raw_value.is_empty() { - has_domain_attribute = true; - let normalized = raw_value.trim_start_matches('.').to_ascii_lowercase(); - if !normalized.is_empty() { - domain = Some(format!(".{normalized}")); - } - } else if key.eq_ignore_ascii_case("path") && !raw_value.is_empty() { - path = Some(raw_value.to_string()); - } else if key.eq_ignore_ascii_case("expires") && !raw_value.is_empty() { - expires_at_unix_ms = parse_cookie_expires_at_unix_ms(raw_value); - } else if key.eq_ignore_ascii_case("max-age") && !raw_value.is_empty() { - max_age_expires_at_unix_ms = - parse_cookie_max_age_expires_at_unix_ms(raw_value, now_unix_ms); - } - } - } - - if let Some(max_age_expires_at_unix_ms) = max_age_expires_at_unix_ms { - expires_at_unix_ms = Some(max_age_expires_at_unix_ms); - } - - if !has_domain_attribute { - domain = url.host_str().map(|value| value.to_ascii_lowercase()); - } - - let value = if value.trim().is_empty() - || value.eq_ignore_ascii_case("del") - || expires_at_unix_ms.is_some_and(|expires_at_unix_ms| expires_at_unix_ms <= now_unix_ms) - { - String::new() - } else { - value.trim().to_string() - }; - - Some(fire_models::PlatformCookie { - name: name.trim().to_string(), - value, - domain, - path, - expires_at_unix_ms, - same_site: None, - }) -} - -fn parse_set_cookie_canonical(value: &str, url: &Url) -> Option { - let now_unix_ms = now_unix_ms(); - let mut parts = value.split(';'); - let first = parts.next()?.trim(); - let (name, raw_cookie_value) = first.split_once('=')?; - let name = name.trim(); - if name.is_empty() { - return None; - } - - let mut cookie = CanonicalCookie::new(name, raw_cookie_value.trim(), url.as_str()); - cookie.path = default_cookie_path(url.path()); - cookie.creation_time_unix_ms = now_unix_ms; - cookie.last_access_time_unix_ms = now_unix_ms; - cookie.source = CookieSource::NetworkSetCookie; - cookie.raw_set_cookie = Some(value.to_string()); - let mut max_age_expires_at_unix_ms = None; - - for attribute in parts { - let attribute = attribute.trim(); - if attribute.eq_ignore_ascii_case("secure") { - cookie.secure = true; - continue; - } - if attribute.eq_ignore_ascii_case("httponly") { - cookie.http_only = true; - continue; - } - if attribute.eq_ignore_ascii_case("partitioned") { - cookie.partitioned = true; - continue; - } - - let Some((key, raw_value)) = attribute.split_once('=') else { - continue; - }; - let key = key.trim(); - let raw_value = raw_value.trim(); - if key.eq_ignore_ascii_case("domain") && !raw_value.is_empty() { - let normalized = raw_value.trim_start_matches('.').to_ascii_lowercase(); - if !normalized.is_empty() { - cookie.host_only = false; - cookie.domain = Some(format!(".{normalized}")); - } - } else if key.eq_ignore_ascii_case("path") && !raw_value.is_empty() { - cookie.path = raw_value.to_string(); - } else if key.eq_ignore_ascii_case("expires") && !raw_value.is_empty() { - cookie.expires_at_unix_ms = parse_cookie_expires_at_unix_ms(raw_value); - } else if key.eq_ignore_ascii_case("max-age") && !raw_value.is_empty() { - if let Ok(max_age_seconds) = raw_value.parse::() { - cookie.max_age_seconds = Some(max_age_seconds); - max_age_expires_at_unix_ms = - parse_cookie_max_age_expires_at_unix_ms(raw_value, now_unix_ms); - } - } else if key.eq_ignore_ascii_case("samesite") && !raw_value.is_empty() { - cookie.same_site = parse_cookie_same_site(raw_value); - } - } - - if let Some(max_age_expires_at_unix_ms) = max_age_expires_at_unix_ms { - cookie.expires_at_unix_ms = Some(max_age_expires_at_unix_ms); - } - - if raw_cookie_value.trim().is_empty() - || raw_cookie_value.eq_ignore_ascii_case("del") - || cookie.is_expired_at(now_unix_ms) - { - cookie.value.clear(); - } - - Some(cookie) -} - -fn parse_cookie_same_site(value: &str) -> CookieSameSite { - if value.eq_ignore_ascii_case("lax") { - CookieSameSite::Lax - } else if value.eq_ignore_ascii_case("strict") { - CookieSameSite::Strict - } else if value.eq_ignore_ascii_case("none") { - CookieSameSite::None - } else { - CookieSameSite::Unspecified - } -} - -fn default_cookie_path(request_path: &str) -> String { - if request_path.is_empty() || request_path == "/" { - return "/".to_string(); - } - match request_path.rsplit_once('/') { - Some(("", _)) | None => "/".to_string(), - Some((prefix, _)) => format!("{prefix}/"), - } -} - -fn parse_cookie_expires_at_unix_ms(value: &str) -> Option { - let expires_at = OffsetDateTime::parse(value, &Rfc2822).ok()?; - Some(expires_at.unix_timestamp().saturating_mul(1000)) -} - -fn parse_cookie_max_age_expires_at_unix_ms(value: &str, now_unix_ms: i64) -> Option { - let seconds = value.parse::().ok()?; - if seconds <= 0 { - return Some(now_unix_ms.saturating_sub(1)); - } - - Some(now_unix_ms.saturating_add(seconds.saturating_mul(1000))) -} - -fn now_unix_ms() -> i64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |duration| duration.as_millis() as i64) -} - -#[cfg(test)] -mod tests { - use url::Url; - - use super::{ - build_cookie_header, cookie_matches_url, now_unix_ms, parse_set_cookie, - parse_set_cookie_canonical, - }; - use fire_models::{CanonicalCookie, CookieSameSite, CookieSnapshot, PlatformCookie}; - - #[test] - fn parse_set_cookie_preserves_leading_dot_and_expiry() { - let url = Url::parse("https://linux.do/latest").expect("url"); - let cookie = parse_set_cookie( - "_t=fresh; Domain=.linux.do; Path=/; Expires=Tue, 01 Jan 2030 00:00:00 GMT", - &url, - ) - .expect("cookie"); - - assert_eq!(cookie.domain.as_deref(), Some(".linux.do")); - assert_eq!(cookie.path.as_deref(), Some("/")); - assert!(cookie.expires_at_unix_ms.is_some()); - } - - #[test] - fn parse_set_cookie_prefers_max_age_over_expires() { - let url = Url::parse("https://linux.do/latest").expect("url"); - let cookie = parse_set_cookie( - "_t=fresh; Expires=Tue, 01 Jan 2030 00:00:00 GMT; Max-Age=1", - &url, - ) - .expect("cookie"); - - let expires_at_unix_ms = cookie.expires_at_unix_ms.expect("max-age expiry"); - let now_unix_ms = super::now_unix_ms(); - assert!(expires_at_unix_ms >= now_unix_ms); - assert!(expires_at_unix_ms <= now_unix_ms + 5_000); - } - - #[test] - fn parse_set_cookie_canonicalizes_domain_attribute_without_leading_dot() { - let url = Url::parse("https://linux.do/latest").expect("url"); - let cookie = parse_set_cookie("_t=fresh; Domain=linux.do; Path=/", &url).expect("cookie"); - - assert_eq!(cookie.domain.as_deref(), Some(".linux.do")); - } - - #[test] - fn parse_set_cookie_clears_immediately_expired_auth_values() { - let url = Url::parse("https://linux.do/latest").expect("url"); - let cookie = parse_set_cookie("_t=fresh; Max-Age=0; Path=/", &url).expect("cookie"); - - assert!(cookie.value.is_empty()); - assert!(cookie - .expires_at_unix_ms - .is_some_and(|expires_at_unix_ms| expires_at_unix_ms < now_unix_ms())); - } - - #[test] - fn parse_set_cookie_canonical_preserves_browser_metadata() { - let url = Url::parse("https://linux.do/latest").expect("url"); - let cookie = parse_set_cookie_canonical( - "cf_clearance=fresh; Domain=.linux.do; Path=/; Max-Age=120; Secure; HttpOnly; SameSite=None; Partitioned", - &url, - ) - .expect("cookie"); - - assert_eq!(cookie.name, "cf_clearance"); - assert_eq!(cookie.value, "fresh"); - assert_eq!(cookie.domain.as_deref(), Some(".linux.do")); - assert!(!cookie.host_only); - assert!(cookie.secure); - assert!(cookie.http_only); - assert_eq!(cookie.same_site, CookieSameSite::None); - assert!(cookie.partitioned); - assert_eq!(cookie.max_age_seconds, Some(120)); - assert!(cookie.expires_at_unix_ms.is_some()); - assert_eq!( - cookie.raw_set_cookie.as_deref(), - Some("cf_clearance=fresh; Domain=.linux.do; Path=/; Max-Age=120; Secure; HttpOnly; SameSite=None; Partitioned") - ); - } - - #[test] - fn cookie_matching_distinguishes_host_only_and_domain_scope() { - let base_url = Url::parse("https://linux.do").expect("base url"); - let request_url = Url::parse("https://meta.linux.do/latest").expect("request url"); - let host_only_cookie = PlatformCookie { - name: "_t".into(), - value: "host-only".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - let domain_cookie = PlatformCookie { - name: "_t".into(), - value: "domain-scope".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - - assert!(!cookie_matches_url( - &host_only_cookie, - &base_url, - &request_url - )); - assert!(cookie_matches_url(&domain_cookie, &base_url, &request_url)); - } - - #[test] - fn build_cookie_header_skips_expired_platform_cookies() { - let base_url = Url::parse("https://linux.do").expect("base url"); - let request_url = Url::parse("https://linux.do/latest").expect("request url"); - let cookies = CookieSnapshot { - platform_cookies: vec![ - fire_models::PlatformCookie { - name: "_t".into(), - value: "expired".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: Some(1), - same_site: None, - }, - fire_models::PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - ], - ..CookieSnapshot::default() - }; - - assert_eq!( - build_cookie_header(&cookies, &base_url, &request_url), - "_forum_session=forum" - ); - } - - #[test] - fn build_cookie_header_does_not_fallback_to_stale_scalar_auth_fields() { - let base_url = Url::parse("https://linux.do").expect("base url"); - let request_url = Url::parse("https://linux.do/latest").expect("request url"); - let cookies = CookieSnapshot { - t_token: Some("stale-token".into()), - forum_session: Some("stale-forum".into()), - platform_cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "expired".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: Some(1), - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "expired".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: Some(1), - same_site: None, - }, - ], - ..CookieSnapshot::default() - }; - - assert!(build_cookie_header(&cookies, &base_url, &request_url).is_empty()); - } - - #[test] - fn build_cookie_header_prefers_host_only_cookie_over_domain_variant_with_same_name_and_path() { - let base_url = Url::parse("https://linux.do").expect("base url"); - let request_url = Url::parse("https://linux.do/latest").expect("request url"); - let cookies = CookieSnapshot { - platform_cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "fresh-host".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_t".into(), - value: "stale-domain".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - ], - ..CookieSnapshot::default() - }; - - let header = build_cookie_header(&cookies, &base_url, &request_url); - let t_pairs = header - .split("; ") - .filter(|pair| pair.starts_with("_t=")) - .collect::>(); - - assert_eq!(t_pairs, vec!["_t=fresh-host"]); - assert!(!header.contains("stale-domain")); - assert!(header - .split("; ") - .any(|pair| pair == "_forum_session=forum")); - } - - #[test] - fn build_cookie_header_prefers_canonical_and_blocks_legacy_same_name_leak() { - let base_url = Url::parse("https://linux.do").expect("base url"); - let main_url = Url::parse("https://linux.do/latest").expect("request url"); - let subdomain_url = Url::parse("https://connect.linux.do/latest").expect("request url"); - - let mut canonical_t = CanonicalCookie::new("_t", "fresh-host", "https://linux.do/"); - canonical_t.host_only = true; - canonical_t.path = "/".into(); - let mut canonical_cf = CanonicalCookie::new("cf_clearance", "clear", "https://linux.do/"); - canonical_cf.host_only = false; - canonical_cf.domain = Some(".linux.do".into()); - canonical_cf.path = "/".into(); - - let cookies = CookieSnapshot { - platform_cookies: vec![PlatformCookie { - name: "_t".into(), - value: "legacy-domain".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }], - canonical_cookies: vec![canonical_t, canonical_cf], - ..CookieSnapshot::default() - }; - - let main_header = build_cookie_header(&cookies, &base_url, &main_url); - assert!(main_header.contains("_t=fresh-host")); - assert!(main_header.contains("cf_clearance=clear")); - assert!(!main_header.contains("legacy-domain")); - - let subdomain_header = build_cookie_header(&cookies, &base_url, &subdomain_url); - assert_eq!(subdomain_header, "cf_clearance=clear"); - } -} diff --git a/crates/fire-core/src/cookies/ingress.rs b/crates/fire-core/src/cookies/ingress.rs new file mode 100644 index 00000000..72c613b9 --- /dev/null +++ b/crates/fire-core/src/cookies/ingress.rs @@ -0,0 +1,155 @@ +#[derive(Clone)] +pub(crate) struct FireSessionCookieJar { + base_url: Url, + session: Arc>, + store: Option>>, +} + +impl FireSessionCookieJar { + pub(crate) fn new( + base_url: Url, + session: Arc>, + store: Option>>, + ) -> Self { + Self { + base_url, + session, + store, + } + } +} + +tokio::task_local! { + pub(crate) static FIRE_REQUEST_EPOCH: u64; +} + +tokio::task_local! { + pub(crate) static FIRE_REQUEST_TRACE_ID: u64; +} + +impl CookieJar for FireSessionCookieJar { + fn set_cookies(&self, cookie_headers: &mut dyn Iterator, url: &Url) { + if !same_site_scope(&self.base_url, url) { + return; + } + + let request_epoch = FIRE_REQUEST_EPOCH.try_with(|epoch| *epoch).ok(); + if is_stale_request_epoch(&self.session, request_epoch) { + return; + } + + let mut patch = CookieSnapshot::default(); + let mut canonical_writes = Vec::new(); + let mut canonical_deletes = Vec::new(); + let mut replay_entries: Vec<(String, String, String)> = Vec::new(); + for header in cookie_headers { + let Ok(value) = header.to_str() else { + continue; + }; + let Some(cookie) = parse_set_cookie(value, url) else { + continue; + }; + let canonical_cookie = parse_set_cookie_canonical(value, url); + + if should_ignore_network_auth_cookie_deletion(&cookie) { + continue; + } + + if cookie.value.is_empty() || cookie.is_expired_now() { + canonical_deletes.push(cookie.name.clone()); + } else if let Some(canonical_cookie) = canonical_cookie { + canonical_writes.push(canonical_cookie); + } + + match cookie.name.as_str() { + "_t" => patch.t_token = Some(cookie.value.clone()), + "_forum_session" => patch.forum_session = Some(cookie.value.clone()), + "cf_clearance" => patch.cf_clearance = Some(cookie.value.clone()), + _ => {} + } + // cf_clearance must not be replayed jar → WebView. Only browser/WebView + // authored clearance is trustworthy; Set-Cookie replay can drop + // Partitioned and create a ghost variant. + if !cookie.name.eq_ignore_ascii_case("cf_clearance") { + let replay_domain = cookie + .domain + .as_deref() + .map(|d| d.trim_start_matches('.').to_string()) + .unwrap_or_default(); + replay_entries.push((value.to_string(), cookie.name.clone(), replay_domain)); + } + patch.platform_cookies.push(cookie); + } + + if patch == CookieSnapshot::default() + && canonical_writes.is_empty() + && canonical_deletes.is_empty() + { + return; + } + + let mut session = write_rwlock(&self.session, "session"); + mutate_runtime_session_tracking_auth_change( + &mut session, + FireAuthChangeSource::NetworkIngress, + "network set-cookie ingress", + |snapshot| { + snapshot.cookies.merge_patch(&patch); + for name in &canonical_deletes { + snapshot.cookies.delete_canonical_cookie_by_name(url, name); + } + if !canonical_writes.is_empty() { + snapshot.cookies.merge_canonical_cookies( + url, + &canonical_writes, + CookieTrust::Trusted, + ); + } + }, + ); + + if let Some(store) = self.store.as_ref() { + let Ok(store) = store.lock() else { + return; + }; + for (raw_set_cookie, cookie_name, domain) in replay_entries { + let url = self.base_url.as_str(); + if let Err(error) = store.cookie_replay_enqueue( + url, + &raw_set_cookie, + &cookie_name, + &domain, + fire_models::current_unix_ms() as u64, + ) { + warn!( + cookie_name = %cookie_name, + %error, + "failed to enqueue Set-Cookie into replay queue" + ); + } + } + } + } + + fn cookies(&self, url: &Url) -> Option { + let session = read_rwlock(&self.session, "session"); + let snapshot = &session.snapshot; + if snapshot.cookies.platform_cookies.is_empty() + && snapshot.cookies.canonical_cookies.is_empty() + { + if !same_origin_scope(&self.base_url, url) { + return None; + } + } else if !same_site_scope(&self.base_url, url) { + return None; + } + + let cookies = build_cookie_header(&snapshot.cookies, &self.base_url, url); + if cookies.is_empty() { + return None; + } + + HeaderValue::from_str(&cookies).ok() + } +} + diff --git a/crates/fire-core/src/cookies/matching.rs b/crates/fire-core/src/cookies/matching.rs new file mode 100644 index 00000000..8a22698e --- /dev/null +++ b/crates/fire-core/src/cookies/matching.rs @@ -0,0 +1,50 @@ +fn cookie_matches_url( + cookie: &fire_models::PlatformCookie, + base_url: &Url, + request_url: &Url, +) -> bool { + if cookie.is_expired_now() { + return false; + } + + if request_url.scheme() != base_url.scheme() { + return false; + } + + let Some(request_host) = request_url + .host_str() + .map(|value| value.to_ascii_lowercase()) + else { + return false; + }; + let base_host = base_url.host_str().map(|value| value.to_ascii_lowercase()); + let raw_cookie_domain = cookie + .domain + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(|value| value.to_ascii_lowercase()); + let allows_subdomains = raw_cookie_domain + .as_deref() + .is_some_and(|value| value.starts_with('.')); + let cookie_domain = raw_cookie_domain + .as_deref() + .map(|value| value.trim_start_matches('.').to_string()) + .or(base_host); + + let Some(cookie_domain) = cookie_domain else { + return false; + }; + if allows_subdomains { + if request_host != cookie_domain && !request_host.ends_with(&format!(".{cookie_domain}")) { + return false; + } + } else if request_host != cookie_domain { + return false; + } + + let request_path = request_url.path(); + let cookie_path = cookie.path.as_deref().unwrap_or("/"); + request_path.starts_with(cookie_path) +} + diff --git a/crates/fire-core/src/cookies/mod.rs b/crates/fire-core/src/cookies/mod.rs new file mode 100644 index 00000000..2a7f2f94 --- /dev/null +++ b/crates/fire-core/src/cookies/mod.rs @@ -0,0 +1,23 @@ +use std::collections::HashSet; +use std::sync::{Arc, Mutex, RwLock}; + +use fire_models::{ + CanonicalCookie, CanonicalCookieStore, CookieSameSite, CookieSnapshot, CookieSource, + CookieTrust, +}; +use http::header::HeaderValue; +use openwire::CookieJar; +use time::{format_description::well_known::Rfc2822, OffsetDateTime}; +use tracing::warn; +use url::Url; + +use crate::core::{ + mutate_runtime_session_tracking_auth_change, FireAuthChangeSource, FireSessionRuntimeState, +}; +use crate::sync_utils::{read_rwlock, write_rwlock}; + +include!("ingress.rs"); +include!("request.rs"); +include!("matching.rs"); +include!("parse.rs"); +include!("tests.rs"); diff --git a/crates/fire-core/src/cookies/parse.rs b/crates/fire-core/src/cookies/parse.rs new file mode 100644 index 00000000..adcf06df --- /dev/null +++ b/crates/fire-core/src/cookies/parse.rs @@ -0,0 +1,175 @@ +fn parse_set_cookie(value: &str, url: &Url) -> Option { + let now_unix_ms = now_unix_ms(); + let mut parts = value.split(';'); + let first = parts.next()?.trim(); + let (name, value) = first.split_once('=')?; + let mut domain = url.host_str().map(|value| value.to_ascii_lowercase()); + let mut path = Some(default_cookie_path(url.path())); + let mut expires_at_unix_ms = None; + let mut max_age_expires_at_unix_ms = None; + let mut has_domain_attribute = false; + + for attribute in parts { + let attribute = attribute.trim(); + if let Some((key, raw_value)) = attribute.split_once('=') { + let key = key.trim(); + let raw_value = raw_value.trim(); + if key.eq_ignore_ascii_case("domain") && !raw_value.is_empty() { + has_domain_attribute = true; + let normalized = raw_value.trim_start_matches('.').to_ascii_lowercase(); + if !normalized.is_empty() { + domain = Some(format!(".{normalized}")); + } + } else if key.eq_ignore_ascii_case("path") && !raw_value.is_empty() { + path = Some(raw_value.to_string()); + } else if key.eq_ignore_ascii_case("expires") && !raw_value.is_empty() { + expires_at_unix_ms = parse_cookie_expires_at_unix_ms(raw_value); + } else if key.eq_ignore_ascii_case("max-age") && !raw_value.is_empty() { + max_age_expires_at_unix_ms = + parse_cookie_max_age_expires_at_unix_ms(raw_value, now_unix_ms); + } + } + } + + if let Some(max_age_expires_at_unix_ms) = max_age_expires_at_unix_ms { + expires_at_unix_ms = Some(max_age_expires_at_unix_ms); + } + + if !has_domain_attribute { + domain = url.host_str().map(|value| value.to_ascii_lowercase()); + } + + let value = if value.trim().is_empty() + || value.eq_ignore_ascii_case("del") + || expires_at_unix_ms.is_some_and(|expires_at_unix_ms| expires_at_unix_ms <= now_unix_ms) + { + String::new() + } else { + value.trim().to_string() + }; + + Some(fire_models::PlatformCookie { + name: name.trim().to_string(), + value, + domain, + path, + expires_at_unix_ms, + same_site: None, + }) +} + +fn parse_set_cookie_canonical(value: &str, url: &Url) -> Option { + let now_unix_ms = now_unix_ms(); + let mut parts = value.split(';'); + let first = parts.next()?.trim(); + let (name, raw_cookie_value) = first.split_once('=')?; + let name = name.trim(); + if name.is_empty() { + return None; + } + + let mut cookie = CanonicalCookie::new(name, raw_cookie_value.trim(), url.as_str()); + cookie.path = default_cookie_path(url.path()); + cookie.creation_time_unix_ms = now_unix_ms; + cookie.last_access_time_unix_ms = now_unix_ms; + cookie.source = CookieSource::NetworkSetCookie; + cookie.raw_set_cookie = Some(value.to_string()); + let mut max_age_expires_at_unix_ms = None; + + for attribute in parts { + let attribute = attribute.trim(); + if attribute.eq_ignore_ascii_case("secure") { + cookie.secure = true; + continue; + } + if attribute.eq_ignore_ascii_case("httponly") { + cookie.http_only = true; + continue; + } + if attribute.eq_ignore_ascii_case("partitioned") { + cookie.partitioned = true; + continue; + } + + let Some((key, raw_value)) = attribute.split_once('=') else { + continue; + }; + let key = key.trim(); + let raw_value = raw_value.trim(); + if key.eq_ignore_ascii_case("domain") && !raw_value.is_empty() { + let normalized = raw_value.trim_start_matches('.').to_ascii_lowercase(); + if !normalized.is_empty() { + cookie.host_only = false; + cookie.domain = Some(format!(".{normalized}")); + } + } else if key.eq_ignore_ascii_case("path") && !raw_value.is_empty() { + cookie.path = raw_value.to_string(); + } else if key.eq_ignore_ascii_case("expires") && !raw_value.is_empty() { + cookie.expires_at_unix_ms = parse_cookie_expires_at_unix_ms(raw_value); + } else if key.eq_ignore_ascii_case("max-age") && !raw_value.is_empty() { + if let Ok(max_age_seconds) = raw_value.parse::() { + cookie.max_age_seconds = Some(max_age_seconds); + max_age_expires_at_unix_ms = + parse_cookie_max_age_expires_at_unix_ms(raw_value, now_unix_ms); + } + } else if key.eq_ignore_ascii_case("samesite") && !raw_value.is_empty() { + cookie.same_site = parse_cookie_same_site(raw_value); + } + } + + if let Some(max_age_expires_at_unix_ms) = max_age_expires_at_unix_ms { + cookie.expires_at_unix_ms = Some(max_age_expires_at_unix_ms); + } + + if raw_cookie_value.trim().is_empty() + || raw_cookie_value.eq_ignore_ascii_case("del") + || cookie.is_expired_at(now_unix_ms) + { + cookie.value.clear(); + } + + Some(cookie) +} + +fn parse_cookie_same_site(value: &str) -> CookieSameSite { + if value.eq_ignore_ascii_case("lax") { + CookieSameSite::Lax + } else if value.eq_ignore_ascii_case("strict") { + CookieSameSite::Strict + } else if value.eq_ignore_ascii_case("none") { + CookieSameSite::None + } else { + CookieSameSite::Unspecified + } +} + +fn default_cookie_path(request_path: &str) -> String { + if request_path.is_empty() || request_path == "/" { + return "/".to_string(); + } + match request_path.rsplit_once('/') { + Some(("", _)) | None => "/".to_string(), + Some((prefix, _)) => format!("{prefix}/"), + } +} + +fn parse_cookie_expires_at_unix_ms(value: &str) -> Option { + let expires_at = OffsetDateTime::parse(value, &Rfc2822).ok()?; + Some(expires_at.unix_timestamp().saturating_mul(1000)) +} + +fn parse_cookie_max_age_expires_at_unix_ms(value: &str, now_unix_ms: i64) -> Option { + let seconds = value.parse::().ok()?; + if seconds <= 0 { + return Some(now_unix_ms.saturating_sub(1)); + } + + Some(now_unix_ms.saturating_add(seconds.saturating_mul(1000))) +} + +fn now_unix_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |duration| duration.as_millis() as i64) +} + diff --git a/crates/fire-core/src/cookies/request.rs b/crates/fire-core/src/cookies/request.rs new file mode 100644 index 00000000..6c2b2349 --- /dev/null +++ b/crates/fire-core/src/cookies/request.rs @@ -0,0 +1,204 @@ +fn should_ignore_network_auth_cookie_deletion(cookie: &fire_models::PlatformCookie) -> bool { + cookie.value.is_empty() && matches!(cookie.name.as_str(), "_t" | "_forum_session") +} + +fn same_origin_scope(base_url: &Url, request_url: &Url) -> bool { + base_url.scheme() == request_url.scheme() + && base_url.host_str() == request_url.host_str() + && base_url.port_or_known_default() == request_url.port_or_known_default() +} + +fn same_site_scope(base_url: &Url, request_url: &Url) -> bool { + base_url.scheme() == request_url.scheme() + && hosts_share_base_domain(base_url.host_str(), request_url.host_str()) +} + +fn hosts_share_base_domain(base_host: Option<&str>, request_host: Option<&str>) -> bool { + let Some(base_host) = base_host.map(|value| value.trim_start_matches('.').to_ascii_lowercase()) + else { + return false; + }; + let Some(request_host) = + request_host.map(|value| value.trim_start_matches('.').to_ascii_lowercase()) + else { + return false; + }; + request_host == base_host || request_host.ends_with(&format!(".{base_host}")) +} + +fn build_cookie_header(cookies: &CookieSnapshot, base_url: &Url, request_url: &Url) -> String { + let canonical_known_names = canonical_cookie_names(cookies); + let canonical_header = build_canonical_cookie_header(cookies, request_url); + if !canonical_header.is_empty() && cookies.platform_cookies.is_empty() { + return canonical_header; + } + + if !cookies.platform_cookies.is_empty() { + let request_host = request_url + .host_str() + .map(|value| value.to_ascii_lowercase()); + let mut matching = cookies + .platform_cookies + .iter() + .enumerate() + .filter(|(_, cookie)| { + !canonical_known_names.contains(&cookie.name) + && cookie_matches_url(cookie, base_url, request_url) + }) + .collect::>(); + matching.sort_by(|(left_index, left), (right_index, right)| { + let left_path_len = left.path.as_deref().unwrap_or("/").len(); + let right_path_len = right.path.as_deref().unwrap_or("/").len(); + right_path_len + .cmp(&left_path_len) + .then_with(|| { + cookie_send_precedence(right, request_host.as_deref()) + .cmp(&cookie_send_precedence(left, request_host.as_deref())) + }) + .then_with(|| right_index.cmp(left_index)) + }); + + let mut seen = HashSet::new(); + let joined = matching + .into_iter() + .filter_map(|(_, cookie)| { + let value = cookie.value.trim(); + if value.is_empty() { + return None; + } + + let dedupe_key = ( + cookie.name.clone(), + cookie.path.as_deref().unwrap_or("/").to_string(), + ); + if !seen.insert(dedupe_key) { + return None; + } + + Some(format!("{}={}", cookie.name, value)) + }) + .collect::>() + .join("; "); + return join_cookie_headers(&canonical_header, &joined); + } + + if !canonical_header.is_empty() { + return canonical_header; + } + + let mut pairs = Vec::new(); + if !canonical_known_names.contains("_t") { + push_cookie_pair(&mut pairs, "_t", cookies.t_token.as_deref()); + } + if !canonical_known_names.contains("_forum_session") { + push_cookie_pair( + &mut pairs, + "_forum_session", + cookies.forum_session.as_deref(), + ); + } + if !canonical_known_names.contains("cf_clearance") { + push_cookie_pair(&mut pairs, "cf_clearance", cookies.cf_clearance.as_deref()); + } + pairs.join("; ") +} + +fn build_canonical_cookie_header(cookies: &CookieSnapshot, request_url: &Url) -> String { + if cookies.canonical_cookies.is_empty() { + return String::new(); + } + + let store = CanonicalCookieStore::from_cookies(cookies.canonical_cookies.clone()); + let mut seen_critical_names = HashSet::new(); + store + .load_for_request(request_url) + .into_iter() + .filter_map(|cookie| { + let value = cookie.value.trim(); + if value.is_empty() { + return None; + } + if is_critical_cookie_name(&cookie.name) + && !seen_critical_names.insert(cookie.name.clone()) + { + return None; + } + Some(format!("{}={}", cookie.name, value)) + }) + .collect::>() + .join("; ") +} + +fn canonical_cookie_names(cookies: &CookieSnapshot) -> HashSet { + cookies + .canonical_cookies + .iter() + .filter(|cookie| !cookie.is_expired_now() && !cookie.value.trim().is_empty()) + .map(|cookie| cookie.name.clone()) + .collect() +} + +fn join_cookie_headers(left: &str, right: &str) -> String { + match (left.is_empty(), right.is_empty()) { + (true, true) => String::new(), + (false, true) => left.to_string(), + (true, false) => right.to_string(), + (false, false) => format!("{left}; {right}"), + } +} + +fn is_critical_cookie_name(name: &str) -> bool { + matches!( + name, + "_t" | "_forum_session" | "cf_clearance" | "_cfuvid" | "h_captcha_temp_id" + ) +} + +fn push_cookie_pair(pairs: &mut Vec, name: &str, value: Option<&str>) { + let Some(value) = value.filter(|value| !value.is_empty()) else { + return; + }; + pairs.push(format!("{name}={value}")); +} + +fn is_stale_request_epoch( + session: &Arc>, + request_epoch: Option, +) -> bool { + let Some(request_epoch) = request_epoch else { + return false; + }; + let current_epoch = read_rwlock(session, "session").epoch; + current_epoch != request_epoch +} + +fn cookie_send_precedence( + cookie: &fire_models::PlatformCookie, + request_host: Option<&str>, +) -> (u8, usize) { + let Some(domain) = cookie + .domain + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + else { + return (3, request_host.map_or(0, str::len)); + }; + + let normalized_domain = domain.trim_start_matches('.'); + let exact_host_match = request_host + .is_some_and(|request_host| request_host.eq_ignore_ascii_case(normalized_domain)); + let rank = if domain.starts_with('.') { + if exact_host_match { + 2 + } else { + 1 + } + } else if exact_host_match { + 3 + } else { + 2 + }; + (rank, normalized_domain.len()) +} + diff --git a/crates/fire-core/src/cookies/tests.rs b/crates/fire-core/src/cookies/tests.rs new file mode 100644 index 00000000..b0e542af --- /dev/null +++ b/crates/fire-core/src/cookies/tests.rs @@ -0,0 +1,258 @@ +#[cfg(test)] +mod tests { + use url::Url; + + use super::{ + build_cookie_header, cookie_matches_url, now_unix_ms, parse_set_cookie, + parse_set_cookie_canonical, + }; + use fire_models::{CanonicalCookie, CookieSameSite, CookieSnapshot, PlatformCookie}; + + #[test] + fn parse_set_cookie_preserves_leading_dot_and_expiry() { + let url = Url::parse("https://linux.do/latest").expect("url"); + let cookie = parse_set_cookie( + "_t=fresh; Domain=.linux.do; Path=/; Expires=Tue, 01 Jan 2030 00:00:00 GMT", + &url, + ) + .expect("cookie"); + + assert_eq!(cookie.domain.as_deref(), Some(".linux.do")); + assert_eq!(cookie.path.as_deref(), Some("/")); + assert!(cookie.expires_at_unix_ms.is_some()); + } + + #[test] + fn parse_set_cookie_prefers_max_age_over_expires() { + let url = Url::parse("https://linux.do/latest").expect("url"); + let cookie = parse_set_cookie( + "_t=fresh; Expires=Tue, 01 Jan 2030 00:00:00 GMT; Max-Age=1", + &url, + ) + .expect("cookie"); + + let expires_at_unix_ms = cookie.expires_at_unix_ms.expect("max-age expiry"); + let now_unix_ms = super::now_unix_ms(); + assert!(expires_at_unix_ms >= now_unix_ms); + assert!(expires_at_unix_ms <= now_unix_ms + 5_000); + } + + #[test] + fn parse_set_cookie_canonicalizes_domain_attribute_without_leading_dot() { + let url = Url::parse("https://linux.do/latest").expect("url"); + let cookie = parse_set_cookie("_t=fresh; Domain=linux.do; Path=/", &url).expect("cookie"); + + assert_eq!(cookie.domain.as_deref(), Some(".linux.do")); + } + + #[test] + fn parse_set_cookie_clears_immediately_expired_auth_values() { + let url = Url::parse("https://linux.do/latest").expect("url"); + let cookie = parse_set_cookie("_t=fresh; Max-Age=0; Path=/", &url).expect("cookie"); + + assert!(cookie.value.is_empty()); + assert!(cookie + .expires_at_unix_ms + .is_some_and(|expires_at_unix_ms| expires_at_unix_ms < now_unix_ms())); + } + + #[test] + fn parse_set_cookie_canonical_preserves_browser_metadata() { + let url = Url::parse("https://linux.do/latest").expect("url"); + let cookie = parse_set_cookie_canonical( + "cf_clearance=fresh; Domain=.linux.do; Path=/; Max-Age=120; Secure; HttpOnly; SameSite=None; Partitioned", + &url, + ) + .expect("cookie"); + + assert_eq!(cookie.name, "cf_clearance"); + assert_eq!(cookie.value, "fresh"); + assert_eq!(cookie.domain.as_deref(), Some(".linux.do")); + assert!(!cookie.host_only); + assert!(cookie.secure); + assert!(cookie.http_only); + assert_eq!(cookie.same_site, CookieSameSite::None); + assert!(cookie.partitioned); + assert_eq!(cookie.max_age_seconds, Some(120)); + assert!(cookie.expires_at_unix_ms.is_some()); + assert_eq!( + cookie.raw_set_cookie.as_deref(), + Some("cf_clearance=fresh; Domain=.linux.do; Path=/; Max-Age=120; Secure; HttpOnly; SameSite=None; Partitioned") + ); + } + + #[test] + fn cookie_matching_distinguishes_host_only_and_domain_scope() { + let base_url = Url::parse("https://linux.do").expect("base url"); + let request_url = Url::parse("https://meta.linux.do/latest").expect("request url"); + let host_only_cookie = PlatformCookie { + name: "_t".into(), + value: "host-only".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }; + let domain_cookie = PlatformCookie { + name: "_t".into(), + value: "domain-scope".into(), + domain: Some(".linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }; + + assert!(!cookie_matches_url( + &host_only_cookie, + &base_url, + &request_url + )); + assert!(cookie_matches_url(&domain_cookie, &base_url, &request_url)); + } + + #[test] + fn build_cookie_header_skips_expired_platform_cookies() { + let base_url = Url::parse("https://linux.do").expect("base url"); + let request_url = Url::parse("https://linux.do/latest").expect("request url"); + let cookies = CookieSnapshot { + platform_cookies: vec![ + fire_models::PlatformCookie { + name: "_t".into(), + value: "expired".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: Some(1), + same_site: None, + }, + fire_models::PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + ], + ..CookieSnapshot::default() + }; + + assert_eq!( + build_cookie_header(&cookies, &base_url, &request_url), + "_forum_session=forum" + ); + } + + #[test] + fn build_cookie_header_does_not_fallback_to_stale_scalar_auth_fields() { + let base_url = Url::parse("https://linux.do").expect("base url"); + let request_url = Url::parse("https://linux.do/latest").expect("request url"); + let cookies = CookieSnapshot { + t_token: Some("stale-token".into()), + forum_session: Some("stale-forum".into()), + platform_cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "expired".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: Some(1), + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "expired".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: Some(1), + same_site: None, + }, + ], + ..CookieSnapshot::default() + }; + + assert!(build_cookie_header(&cookies, &base_url, &request_url).is_empty()); + } + + #[test] + fn build_cookie_header_prefers_host_only_cookie_over_domain_variant_with_same_name_and_path() { + let base_url = Url::parse("https://linux.do").expect("base url"); + let request_url = Url::parse("https://linux.do/latest").expect("request url"); + let cookies = CookieSnapshot { + platform_cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "fresh-host".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_t".into(), + value: "stale-domain".into(), + domain: Some(".linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + ], + ..CookieSnapshot::default() + }; + + let header = build_cookie_header(&cookies, &base_url, &request_url); + let t_pairs = header + .split("; ") + .filter(|pair| pair.starts_with("_t=")) + .collect::>(); + + assert_eq!(t_pairs, vec!["_t=fresh-host"]); + assert!(!header.contains("stale-domain")); + assert!(header + .split("; ") + .any(|pair| pair == "_forum_session=forum")); + } + + #[test] + fn build_cookie_header_prefers_canonical_and_blocks_legacy_same_name_leak() { + let base_url = Url::parse("https://linux.do").expect("base url"); + let main_url = Url::parse("https://linux.do/latest").expect("request url"); + let subdomain_url = Url::parse("https://connect.linux.do/latest").expect("request url"); + + let mut canonical_t = CanonicalCookie::new("_t", "fresh-host", "https://linux.do/"); + canonical_t.host_only = true; + canonical_t.path = "/".into(); + let mut canonical_cf = CanonicalCookie::new("cf_clearance", "clear", "https://linux.do/"); + canonical_cf.host_only = false; + canonical_cf.domain = Some(".linux.do".into()); + canonical_cf.path = "/".into(); + + let cookies = CookieSnapshot { + platform_cookies: vec![PlatformCookie { + name: "_t".into(), + value: "legacy-domain".into(), + domain: Some(".linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }], + canonical_cookies: vec![canonical_t, canonical_cf], + ..CookieSnapshot::default() + }; + + let main_header = build_cookie_header(&cookies, &base_url, &main_url); + assert!(main_header.contains("_t=fresh-host")); + assert!(main_header.contains("cf_clearance=clear")); + assert!(!main_header.contains("legacy-domain")); + + let subdomain_header = build_cookie_header(&cookies, &base_url, &subdomain_url); + assert_eq!(subdomain_header, "cf_clearance=clear"); + } +} diff --git a/crates/fire-core/src/core/auth.rs b/crates/fire-core/src/core/auth.rs deleted file mode 100644 index 04451d18..00000000 --- a/crates/fire-core/src/core/auth.rs +++ /dev/null @@ -1,681 +0,0 @@ -use std::future::Future; -use std::sync::OnceLock; - -use fire_models::{ - AuthRuntimeSignal, AuthRuntimeSignalKind, AuthRuntimeSignalSource, AuthRuntimeSignalStrength, - BootstrapArtifacts, CookieSnapshot, PassiveLogoutTrigger, ProbeResult, SessionSnapshot, - SignalStrength, -}; -use http::{Method, StatusCode}; -use serde_json::Value; -use tokio::runtime::{Builder, Handle, Runtime}; -use tracing::{debug, info, warn}; - -use super::{ - auth_strike::StrikeDecision, - messagebus::message_bus_requires_shared_session_key, - network::{classify_http_status_error, expect_success, header_value, is_bad_csrf_body}, - FireCore, -}; -use crate::parsing::{parse_home_state, parse_site_metadata_json}; -use crate::{ - error::FireCoreError, - json_helpers::{invalid_json, scalar_string}, - sync_utils::{read_rwlock, write_rwlock}, -}; - -impl FireCore { - /// After cookie handoff during login: try bootstrap refresh with a hard - /// timeout, but never leave the UI stuck if bootstrap is slow. Cookie auth - /// alone is enough to enter the app (fluxdo LoginReady finally semantics). - pub async fn finalize_login_ready(&self) -> Result { - const LOGIN_READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8); - - self.clear_cloudflare_clearance_rejected(); - - if !self.snapshot().cookies.has_login_session() { - return Ok(self.snapshot()); - } - - match tokio::time::timeout(LOGIN_READY_TIMEOUT, self.refresh_bootstrap_if_needed()).await { - Ok(Ok(snapshot)) => Ok(snapshot), - Ok(Err(error)) => { - warn!(error = %error, "login-ready bootstrap refresh failed; continuing with cookies"); - Ok(self.snapshot()) - } - Err(_) => { - warn!("login-ready bootstrap refresh timed out; continuing with cookies"); - Ok(self.snapshot()) - } - } - } - - /// After CF success: publish resolved generation, force bootstrap + full - /// app-state refresh when logged in, then notify platform subscribers - /// (MessageBus restart / banner clear / login continue). - /// Safe to call from sync UniFFI paths (falls back when no Tokio handle). - pub(crate) fn schedule_post_challenge_session_rebuild(&self) { - // Manual path bumps here; network path bumps in finish(true) right after. - let generation_hint = self.publish_clearance_resolved_if_idle(); - let has_login = self.snapshot().cookies.has_login_session(); - let core = self.clone(); - spawn_post_challenge_task(async move { - // Allow network finish(true) to publish generation before we notify. - tokio::time::sleep(std::time::Duration::from_millis(30)).await; - - if !has_login { - let generation = core - .cloudflare_clearance_resolved_generation() - .max(generation_hint); - core.notify_clearance_resolved(generation); - return; - } - - // Let cookie merge settle before the rebuild wave. - let settle = { - let runtime = core - .cloudflare_challenge_runtime - .lock() - .expect("cloudflare challenge runtime mutex poisoned"); - runtime.trust_settle_remaining() - }; - if let Some(remaining) = settle { - tokio::time::sleep(remaining).await; - } - - match core.refresh_bootstrap().await { - Ok(_) => { - info!("post-challenge bootstrap rebuild complete"); - } - Err(error) => { - warn!(error = %error, "post-challenge bootstrap rebuild failed"); - } - } - - // Bootstrap alone is not enough to keep writes healthy after CF: - // Set-Cookie may rotate `_forum_session`/`_t` (stale CSRF cleared), - // while home HTML may omit `` (interstitial / - // redirect / partial page). Force a `/session/csrf` realign so - // `can_write_authenticated_api` recovers before hosts act on the - // clearance-resolved event. Failures stay soft — BAD CSRF retry - // remains the last line of defense. - if core.snapshot().cookies.can_authenticate_requests() { - match core.refresh_csrf_token().await { - Ok(_) => info!("post-challenge CSRF realigned"), - Err(error) => { - warn!(error = %error, "post-challenge CSRF refresh failed") - } - } - } - - core.state_observers().notify_session(core.snapshot()); - - // Force a full loginCompleted-style batch so CF mid-refresh does not - // leave home/notifications stuck on a partial failure. - if let Err(error) = core - .app_state_refresher() - .refresh_all_forced(fire_models::RefreshTrigger::CloudflareResolved) - .await - { - warn!(error = %error, "post-challenge app state refresh failed"); - } - - let generation = core - .cloudflare_clearance_resolved_generation() - .max(generation_hint); - core.notify_clearance_resolved(generation); - }); - } - - pub async fn refresh_bootstrap_if_needed(&self) -> Result { - let current = self.snapshot(); - let readiness = current.readiness(); - let requires_shared_session_key = - message_bus_requires_shared_session_key(&self.base_url, ¤t.bootstrap)?; - let needs_site_metadata = !current.bootstrap.has_site_metadata; - let needs_bootstrap_refresh = !current.bootstrap.has_preloaded_data - || !current.bootstrap.has_site_settings - || !readiness.has_current_user - || (requires_shared_session_key && !readiness.has_shared_session_key); - - if !readiness.can_read_authenticated_api { - return Ok(current); - } - - if needs_site_metadata && !needs_bootstrap_refresh { - if let Some(site_metadata_patch) = self.fetch_site_metadata_fallback().await { - let snapshot = self.update_session(|session| { - session.bootstrap.merge_patch(&site_metadata_patch); - debug!( - phase = ?session.login_phase(), - readiness = ?session.readiness(), - "applied site metadata fallback without home refresh" - ); - }); - self.sync_preloaded_data_cache(&snapshot.bootstrap); - return Ok(snapshot); - } - - return self.refresh_bootstrap().await; - } - - if needs_bootstrap_refresh { - self.refresh_bootstrap().await - } else { - Ok(current) - } - } - - pub async fn refresh_bootstrap(&self) -> Result { - info!("refreshing bootstrap via home page request"); - let traced = self.build_home_request("refresh bootstrap")?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "refresh bootstrap", trace_id, response).await?; - let response_username = header_value(response.headers(), "x-discourse-username"); - let html = self.read_response_text(trace_id, response).await?; - let parsed = parse_home_state(self.base_url(), &html); - let site_metadata_patch = if parsed.bootstrap_patch.has_site_metadata { - None - } else { - self.fetch_site_metadata_fallback().await - }; - - let result = self.update_session(|session| { - session.cookies.merge_patch(&parsed.cookies_patch); - session.bootstrap.merge_patch(&parsed.bootstrap_patch); - if let Some(site_metadata_patch) = site_metadata_patch.clone() { - session.bootstrap.merge_patch(&site_metadata_patch); - } - if let Some(response_username) = response_username.clone() { - session.bootstrap.merge_patch(&BootstrapArtifacts { - current_username: Some(response_username), - ..BootstrapArtifacts::default() - }); - } - debug!( - phase = ?session.login_phase(), - readiness = ?session.readiness(), - "refreshed bootstrap over network" - ); - }); - info!( - username = ?result.bootstrap.current_username, - has_preloaded = result.bootstrap.has_preloaded_data, - has_site_metadata = result.bootstrap.has_site_metadata, - "bootstrap refresh complete" - ); - self.sync_preloaded_data_cache(&result.bootstrap); - Ok(result) - } - - pub async fn refresh_csrf_token_if_needed(&self) -> Result { - let current = self.snapshot(); - if current.cookies.csrf_token.is_some() { - return Ok(current); - } - if !current.cookies.can_authenticate_requests() { - debug!("skipping CSRF refresh because authenticated cookies are unavailable"); - return Ok(current); - } - - let _refresh_guard = self.csrf_refresh.lock().await; - let current = self.snapshot(); - if current.cookies.csrf_token.is_some() { - return Ok(current); - } - if !current.cookies.can_authenticate_requests() { - debug!("skipping CSRF refresh because authenticated cookies became unavailable"); - return Ok(current); - } - - self.refresh_csrf_token_without_dedupe().await - } - - pub async fn refresh_csrf_token(&self) -> Result { - let _refresh_guard = self.csrf_refresh.lock().await; - self.refresh_csrf_token_without_dedupe().await - } - - async fn refresh_csrf_token_without_dedupe(&self) -> Result { - info!("refreshing CSRF token"); - let traced = - self.build_api_request("refresh csrf token", Method::GET, "/session/csrf", false)?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "refresh csrf token", trace_id, response).await?; - let payload: Value = self - .read_response_json("refresh csrf token", trace_id, response) - .await?; - let csrf = parse_csrf_token_response(&payload).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "refresh csrf token", - source, - } - })?; - if csrf.is_empty() { - self.diagnostics.record_parse_error( - trace_id, - "CSRF response did not contain a usable token".to_string(), - "csrf token was empty".to_string(), - ); - return Err(FireCoreError::InvalidCsrfResponse); - } - - let result = self.update_session(|session| { - session.cookies.merge_patch(&CookieSnapshot { - csrf_token: Some(csrf.clone()), - last_challenged_cf_clearance: None, - ..CookieSnapshot::default() - }); - debug!( - phase = ?session.login_phase(), - readiness = ?session.readiness(), - "refreshed csrf token over network" - ); - }); - self.clear_auth_recovery_hint("refresh csrf token"); - info!("CSRF token refreshed successfully"); - Ok(result) - } - - pub async fn logout_remote( - &self, - preserve_cf_clearance: bool, - ) -> Result { - let username = self - .snapshot() - .bootstrap - .current_username - .ok_or(FireCoreError::MissingCurrentUsername)?; - info!(username = %username, preserve_cf_clearance, "initiating remote logout"); - - if !self.snapshot().cookies.has_csrf_token() { - let _ = self.refresh_csrf_token_if_needed().await?; - } - - let path = format!("/session/{username}"); - let traced = self.build_api_request("logout", Method::DELETE, &path, true)?; - let (trace_id, response) = self.execute_request(traced).await?; - - if response.status() == StatusCode::FORBIDDEN { - let response_headers = response.headers().clone(); - let body = self.read_response_text(trace_id, response).await?; - self.diagnostics.record_http_status_error( - trace_id, - StatusCode::FORBIDDEN.as_u16(), - &body, - ); - if is_bad_csrf_body(&body) { - warn!("logout received BAD CSRF, refreshing token and retrying once"); - let _ = self.clear_csrf_token(); - let _ = self.refresh_csrf_token_if_needed().await?; - let retry = self.build_api_request("logout", Method::DELETE, &path, true)?; - let (retry_trace_id, response) = self.execute_request(retry).await?; - let response = expect_success(self, "logout", retry_trace_id, response).await?; - let _ = self.read_response_text(retry_trace_id, response).await?; - return Ok(self.logout_local(preserve_cf_clearance)); - } - - return Err(classify_http_status_error( - "logout", - StatusCode::FORBIDDEN.as_u16(), - &response_headers, - body, - )); - } - - let response = expect_success(self, "logout", trace_id, response).await?; - let _ = self.read_response_text(trace_id, response).await?; - Ok(self.logout_local(preserve_cf_clearance)) - } -} - -impl FireCore { - async fn fetch_site_metadata_fallback(&self) -> Option { - info!("bootstrap missing site metadata, fetching /site.json fallback"); - let traced = - match self.build_json_get_request("fetch site metadata", "/site.json", Vec::new(), &[]) - { - Ok(traced) => traced, - Err(error) => { - warn!(error = %error, "failed to build site metadata fallback request"); - return None; - } - }; - let (trace_id, response) = match self.execute_request(traced).await { - Ok(result) => result, - Err(error) => { - warn!(error = %error, "site metadata fallback request failed"); - return None; - } - }; - let response = match expect_success(self, "fetch site metadata", trace_id, response).await { - Ok(response) => response, - Err(error) => { - warn!(error = %error, "site metadata fallback returned non-success status"); - return None; - } - }; - let payload: Value = match self - .read_response_json("fetch site metadata", trace_id, response) - .await - { - Ok(payload) => payload, - Err(error) => { - warn!(error = %error, "failed to decode site metadata fallback response"); - return None; - } - }; - let payload_json = match serde_json::to_string(&payload) { - Ok(payload_json) => payload_json, - Err(error) => { - warn!(error = %error, "failed to serialize site metadata fallback response"); - return None; - } - }; - let patch = parse_site_metadata_json(self.base_url(), &payload_json); - if !patch.has_site_metadata { - warn!("site metadata fallback completed but did not contain categories/tag metadata"); - return None; - } - Some(patch) - } -} - -fn parse_csrf_token_response(value: &Value) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("csrf response root was not an object"))?; - Ok(scalar_string(object.get("csrf")).unwrap_or_default()) -} - -impl FireCore { - pub async fn probe_session(&self) -> Result { - let traced = - self.build_json_get_request("probe_session", "/session/current.json", Vec::new(), &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let status = response.status(); - if status.as_u16() == 404 { - return Ok(ProbeResult::Invalid); - } - let body = self.read_response_text(trace_id, response).await; - match body { - Ok(text) => { - let json: Value = serde_json::from_str(&text).unwrap_or_default(); - if let Some(user) = json.get("current_user") { - let username = user - .get("username") - .and_then(|u| u.as_str()) - .unwrap_or("") - .to_string(); - if !username.is_empty() { - return Ok(ProbeResult::Valid { username }); - } - } - if status.is_success() { - Ok(ProbeResult::Invalid) - } else { - Ok(ProbeResult::Inconclusive) - } - } - Err(_) => Ok(ProbeResult::Inconclusive), - } - } - - pub async fn passive_logout(&self, trigger: PassiveLogoutTrigger) -> Result<(), FireCoreError> { - info!( - source = %trigger.source, - signal_strength = ?trigger.signal_strength, - "initiating passive logout" - ); - { - let mut state = write_rwlock(&self.session, "session"); - state.auth_strike.record_passive_logout(); - state.epoch = state.epoch.saturating_add(1); - } - self.logout_local(true); - Ok(()) - } - - pub fn is_logging_out(&self) -> bool { - read_rwlock(&self.session, "session") - .auth_strike - .logging_out - } - - pub fn handle_server_forced_logout(&self, user_id: u64) -> bool { - { - let mut state = write_rwlock(&self.session, "session"); - if state.auth_strike.logging_out { - return false; - } - if state.snapshot.bootstrap.current_user_id != Some(user_id) { - return false; - } - if !state.snapshot.cookies.can_authenticate_requests() - && !state.snapshot.readiness().can_read_authenticated_api - { - return false; - } - info!(user_id, "handling server-forced logout"); - state.auth_strike.record_passive_logout(); - state.epoch = state.epoch.saturating_add(1); - } - let _ = self.logout_local(true); - true - } - - pub(crate) fn record_auth_runtime_signal(&self, signal: AuthRuntimeSignal) { - let signal_kind = signal.kind.clone(); - let signal_strength = signal.strength; - let signal_source = signal.source; - let operation = signal.operation.clone(); - let status = signal.status; - { - let mut state = write_rwlock(&self.session, "session"); - state.last_auth_runtime_signal = Some(signal); - } - info!( - kind = ?signal_kind, - strength = ?signal_strength, - source = ?signal_source, - operation = ?operation, - status = ?status, - "recorded auth runtime signal" - ); - } - - pub(crate) async fn process_auth_runtime_signal( - &self, - signal: AuthRuntimeSignal, - operation: &'static str, - ) -> Option { - let strike_strength = match signal.kind { - AuthRuntimeSignalKind::NotLoggedInBody - | AuthRuntimeSignalKind::DiscourseLoggedOutHeader => Some(SignalStrength::Strong), - AuthRuntimeSignalKind::MixedLoggedOutHeader - | AuthRuntimeSignalKind::MixedSignalCookieDeletionBlocked => Some(SignalStrength::Weak), - _ => None, - }; - self.record_auth_runtime_signal(signal); - match strike_strength { - Some(strength) => self.process_auth_strike_signal(strength, operation).await, - None => None, - } - } - - pub(crate) async fn process_auth_strike_signal( - &self, - strength: SignalStrength, - operation: &'static str, - ) -> Option { - let decision = { - let mut state = write_rwlock(&self.session, "session"); - state.auth_strike.receive_auth_signal(strength.clone()) - }; - match decision { - StrikeDecision::ProbeNeeded => { - { - let mut state = write_rwlock(&self.session, "session"); - state.auth_strike.probe_in_progress = true; - } - let probe_result = self.probe_session().await; - { - let mut state = write_rwlock(&self.session, "session"); - state.auth_strike.probe_in_progress = false; - } - match probe_result { - Ok(ProbeResult::Valid { .. }) => { - self.record_auth_runtime_signal(AuthRuntimeSignal { - kind: AuthRuntimeSignalKind::ProbeValid, - strength: AuthRuntimeSignalStrength::Terminal, - source: AuthRuntimeSignalSource::Probe, - operation: Some(operation.to_string()), - status: None, - }); - info!( - operation, - "probe confirmed session valid, resetting strikes" - ); - { - let mut state = write_rwlock(&self.session, "session"); - state.auth_strike.reset_strikes(); - } - None - } - Ok(ProbeResult::Invalid) => { - self.record_auth_runtime_signal(AuthRuntimeSignal { - kind: AuthRuntimeSignalKind::ProbeInvalid, - strength: AuthRuntimeSignalStrength::Terminal, - source: AuthRuntimeSignalSource::Probe, - operation: Some(operation.to_string()), - status: None, - }); - info!( - operation, - "probe confirmed session invalid, triggering passive logout" - ); - let _ = self - .passive_logout(PassiveLogoutTrigger { - source: format!("strike_probe_invalid:{operation}"), - signal_strength: strength, - cookie_diagnostic: String::new(), - }) - .await; - Some(FireCoreError::LoginRequired { - operation, - message: "登录状态已失效,请重新登录。".to_string(), - }) - } - Ok(ProbeResult::Inconclusive) => { - let strikes = { - let state = read_rwlock(&self.session, "session"); - state.auth_strike.strike_count - }; - if strikes >= 2 { - self.record_auth_runtime_signal(AuthRuntimeSignal { - kind: AuthRuntimeSignalKind::ProbeInconclusiveEscalated, - strength: AuthRuntimeSignalStrength::Terminal, - source: AuthRuntimeSignalSource::Probe, - operation: Some(operation.to_string()), - status: None, - }); - info!( - operation, - strikes, - "probe inconclusive with enough strikes, triggering passive logout" - ); - let _ = self - .passive_logout(PassiveLogoutTrigger { - source: format!("strike_probe_inconclusive:{operation}"), - signal_strength: strength, - cookie_diagnostic: String::new(), - }) - .await; - Some(FireCoreError::LoginRequired { - operation, - message: "登录状态已失效,请重新登录。".to_string(), - }) - } else { - self.record_auth_runtime_signal(AuthRuntimeSignal { - kind: AuthRuntimeSignalKind::ProbeInconclusive, - strength: AuthRuntimeSignalStrength::Diagnostic, - source: AuthRuntimeSignalSource::Probe, - operation: Some(operation.to_string()), - status: None, - }); - info!( - operation, - strikes, "probe inconclusive with few strikes, entering cooldown" - ); - let mut state = write_rwlock(&self.session, "session"); - state.auth_strike.enter_inconclusive_cooldown(); - Some(FireCoreError::LoginRequired { - operation, - message: "登录状态已失效,请重新登录。".to_string(), - }) - } - } - Err(_) => { - let strikes = { - let state = read_rwlock(&self.session, "session"); - state.auth_strike.strike_count - }; - if strikes >= 2 { - self.record_auth_runtime_signal(AuthRuntimeSignal { - kind: AuthRuntimeSignalKind::ProbeInconclusiveEscalated, - strength: AuthRuntimeSignalStrength::Terminal, - source: AuthRuntimeSignalSource::Probe, - operation: Some(operation.to_string()), - status: None, - }); - let _ = self - .passive_logout(PassiveLogoutTrigger { - source: format!("strike_probe_error:{operation}"), - signal_strength: strength, - cookie_diagnostic: String::new(), - }) - .await; - } else { - self.record_auth_runtime_signal(AuthRuntimeSignal { - kind: AuthRuntimeSignalKind::ProbeInconclusive, - strength: AuthRuntimeSignalStrength::Diagnostic, - source: AuthRuntimeSignalSource::Probe, - operation: Some(operation.to_string()), - status: None, - }); - let mut state = write_rwlock(&self.session, "session"); - state.auth_strike.enter_inconclusive_cooldown(); - } - Some(FireCoreError::LoginRequired { - operation, - message: "登录状态已失效,请重新登录。".to_string(), - }) - } - } - } - StrikeDecision::Accumulated { .. } | StrikeDecision::Ignore => None, - } - } -} - -fn post_challenge_runtime() -> &'static Runtime { - static RUNTIME: OnceLock = OnceLock::new(); - RUNTIME.get_or_init(|| { - Builder::new_multi_thread() - .enable_all() - .thread_name("fire-post-challenge") - .build() - .expect("failed to create post-challenge runtime") - }) -} - -fn spawn_post_challenge_task(future: F) -where - F: Future + Send + 'static, -{ - if let Ok(handle) = Handle::try_current() { - handle.spawn(future); - } else { - post_challenge_runtime().spawn(future); - } -} diff --git a/crates/fire-core/src/core/auth_strike.rs b/crates/fire-core/src/core/auth/auth_strike.rs similarity index 100% rename from crates/fire-core/src/core/auth_strike.rs rename to crates/fire-core/src/core/auth/auth_strike.rs diff --git a/crates/fire-core/src/core/auth/bootstrap.rs b/crates/fire-core/src/core/auth/bootstrap.rs new file mode 100644 index 00000000..5f201fdb --- /dev/null +++ b/crates/fire-core/src/core/auth/bootstrap.rs @@ -0,0 +1,148 @@ +use fire_models::{BootstrapArtifacts, SessionSnapshot}; +use serde_json::Value; +use tracing::{debug, info, warn}; + +use super::super::{ + messagebus::message_bus_requires_shared_session_key, + network::{expect_success, header_value}, + FireCore, +}; +use crate::{ + error::FireCoreError, + parsing::{parse_home_state, parse_site_metadata_json}, +}; + +impl FireCore { + pub async fn refresh_bootstrap_if_needed(&self) -> Result { + let current = self.snapshot(); + let readiness = current.readiness(); + let requires_shared_session_key = + message_bus_requires_shared_session_key(&self.base_url, ¤t.bootstrap)?; + let needs_site_metadata = !current.bootstrap.has_site_metadata; + let needs_bootstrap_refresh = !current.bootstrap.has_preloaded_data + || !current.bootstrap.has_site_settings + || !readiness.has_current_user + || (requires_shared_session_key && !readiness.has_shared_session_key); + + if !readiness.can_read_authenticated_api { + return Ok(current); + } + + if needs_site_metadata && !needs_bootstrap_refresh { + if let Some(site_metadata_patch) = self.fetch_site_metadata_fallback().await { + let snapshot = self.update_session(|session| { + session.bootstrap.merge_patch(&site_metadata_patch); + debug!( + phase = ?session.login_phase(), + readiness = ?session.readiness(), + "applied site metadata fallback without home refresh" + ); + }); + self.sync_preloaded_data_cache(&snapshot.bootstrap); + return Ok(snapshot); + } + + return self.refresh_bootstrap().await; + } + + if needs_bootstrap_refresh { + self.refresh_bootstrap().await + } else { + Ok(current) + } + } + + pub async fn refresh_bootstrap(&self) -> Result { + info!("refreshing bootstrap via home page request"); + let traced = self.build_home_request("refresh bootstrap")?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "refresh bootstrap", trace_id, response).await?; + let response_username = header_value(response.headers(), "x-discourse-username"); + let html = self.read_response_text(trace_id, response).await?; + let parsed = parse_home_state(self.base_url(), &html); + let site_metadata_patch = if parsed.bootstrap_patch.has_site_metadata { + None + } else { + self.fetch_site_metadata_fallback().await + }; + + let result = self.update_session(|session| { + session.cookies.merge_patch(&parsed.cookies_patch); + session.bootstrap.merge_patch(&parsed.bootstrap_patch); + if let Some(site_metadata_patch) = site_metadata_patch.clone() { + session.bootstrap.merge_patch(&site_metadata_patch); + } + if let Some(response_username) = response_username.clone() { + session.bootstrap.merge_patch(&BootstrapArtifacts { + current_username: Some(response_username), + ..BootstrapArtifacts::default() + }); + } + debug!( + phase = ?session.login_phase(), + readiness = ?session.readiness(), + "refreshed bootstrap over network" + ); + }); + info!( + username = ?result.bootstrap.current_username, + has_preloaded = result.bootstrap.has_preloaded_data, + has_site_metadata = result.bootstrap.has_site_metadata, + "bootstrap refresh complete" + ); + self.sync_preloaded_data_cache(&result.bootstrap); + Ok(result) + } +} + +impl FireCore { + async fn fetch_site_metadata_fallback(&self) -> Option { + info!("bootstrap missing site metadata, fetching /site.json fallback"); + let traced = + match self.build_json_get_request("fetch site metadata", "/site.json", Vec::new(), &[]) + { + Ok(traced) => traced, + Err(error) => { + warn!(error = %error, "failed to build site metadata fallback request"); + return None; + } + }; + let (trace_id, response) = match self.execute_request(traced).await { + Ok(result) => result, + Err(error) => { + warn!(error = %error, "site metadata fallback request failed"); + return None; + } + }; + let response = match expect_success(self, "fetch site metadata", trace_id, response).await { + Ok(response) => response, + Err(error) => { + warn!(error = %error, "site metadata fallback returned non-success status"); + return None; + } + }; + let payload: Value = match self + .read_response_json("fetch site metadata", trace_id, response) + .await + { + Ok(payload) => payload, + Err(error) => { + warn!(error = %error, "failed to decode site metadata fallback response"); + return None; + } + }; + let payload_json = match serde_json::to_string(&payload) { + Ok(payload_json) => payload_json, + Err(error) => { + warn!(error = %error, "failed to serialize site metadata fallback response"); + return None; + } + }; + let patch = parse_site_metadata_json(self.base_url(), &payload_json); + if !patch.has_site_metadata { + warn!("site metadata fallback completed but did not contain categories/tag metadata"); + return None; + } + Some(patch) + } +} diff --git a/crates/fire-core/src/core/auth/csrf.rs b/crates/fire-core/src/core/auth/csrf.rs new file mode 100644 index 00000000..c652bb2c --- /dev/null +++ b/crates/fire-core/src/core/auth/csrf.rs @@ -0,0 +1,88 @@ +use fire_models::{CookieSnapshot, SessionSnapshot}; +use http::Method; +use serde_json::Value; +use tracing::{debug, info}; + +use super::super::{network::expect_success, FireCore}; +use crate::{ + error::FireCoreError, + json_helpers::{invalid_json, scalar_string}, +}; + +impl FireCore { + pub async fn refresh_csrf_token_if_needed(&self) -> Result { + let current = self.snapshot(); + if current.cookies.csrf_token.is_some() { + return Ok(current); + } + if !current.cookies.can_authenticate_requests() { + debug!("skipping CSRF refresh because authenticated cookies are unavailable"); + return Ok(current); + } + + let _refresh_guard = self.csrf_refresh.lock().await; + let current = self.snapshot(); + if current.cookies.csrf_token.is_some() { + return Ok(current); + } + if !current.cookies.can_authenticate_requests() { + debug!("skipping CSRF refresh because authenticated cookies became unavailable"); + return Ok(current); + } + + self.refresh_csrf_token_without_dedupe().await + } + + pub async fn refresh_csrf_token(&self) -> Result { + let _refresh_guard = self.csrf_refresh.lock().await; + self.refresh_csrf_token_without_dedupe().await + } + + async fn refresh_csrf_token_without_dedupe(&self) -> Result { + info!("refreshing CSRF token"); + let traced = + self.build_api_request("refresh csrf token", Method::GET, "/session/csrf", false)?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "refresh csrf token", trace_id, response).await?; + let payload: Value = self + .read_response_json("refresh csrf token", trace_id, response) + .await?; + let csrf = parse_csrf_token_response(&payload).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "refresh csrf token", + source, + } + })?; + if csrf.is_empty() { + self.diagnostics.record_parse_error( + trace_id, + "CSRF response did not contain a usable token".to_string(), + "csrf token was empty".to_string(), + ); + return Err(FireCoreError::InvalidCsrfResponse); + } + + let result = self.update_session(|session| { + session.cookies.merge_patch(&CookieSnapshot { + csrf_token: Some(csrf.clone()), + last_challenged_cf_clearance: None, + ..CookieSnapshot::default() + }); + debug!( + phase = ?session.login_phase(), + readiness = ?session.readiness(), + "refreshed csrf token over network" + ); + }); + self.clear_auth_recovery_hint("refresh csrf token"); + info!("CSRF token refreshed successfully"); + Ok(result) + } +} + +fn parse_csrf_token_response(value: &Value) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("csrf response root was not an object"))?; + Ok(scalar_string(object.get("csrf")).unwrap_or_default()) +} diff --git a/crates/fire-core/src/core/auth/login_ready.rs b/crates/fire-core/src/core/auth/login_ready.rs new file mode 100644 index 00000000..8d967086 --- /dev/null +++ b/crates/fire-core/src/core/auth/login_ready.rs @@ -0,0 +1,32 @@ +use fire_models::SessionSnapshot; +use tracing::warn; + +use super::super::FireCore; +use crate::error::FireCoreError; + +impl FireCore { + /// After cookie handoff during login: try bootstrap refresh with a hard + /// timeout, but never leave the UI stuck if bootstrap is slow. Cookie auth + /// alone is enough to enter the app (fluxdo LoginReady finally semantics). + pub async fn finalize_login_ready(&self) -> Result { + const LOGIN_READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8); + + self.clear_cloudflare_clearance_rejected(); + + if !self.snapshot().cookies.has_login_session() { + return Ok(self.snapshot()); + } + + match tokio::time::timeout(LOGIN_READY_TIMEOUT, self.refresh_bootstrap_if_needed()).await { + Ok(Ok(snapshot)) => Ok(snapshot), + Ok(Err(error)) => { + warn!(error = %error, "login-ready bootstrap refresh failed; continuing with cookies"); + Ok(self.snapshot()) + } + Err(_) => { + warn!("login-ready bootstrap refresh timed out; continuing with cookies"); + Ok(self.snapshot()) + } + } + } +} diff --git a/crates/fire-core/src/core/auth/logout.rs b/crates/fire-core/src/core/auth/logout.rs new file mode 100644 index 00000000..3a7a9f50 --- /dev/null +++ b/crates/fire-core/src/core/auth/logout.rs @@ -0,0 +1,110 @@ +use fire_models::{PassiveLogoutTrigger, SessionSnapshot}; +use http::{Method, StatusCode}; +use tracing::{info, warn}; + +use super::super::{ + network::{classify_http_status_error, expect_success, is_bad_csrf_body}, + FireCore, +}; +use crate::{ + error::FireCoreError, + sync_utils::{read_rwlock, write_rwlock}, +}; + +impl FireCore { + pub async fn logout_remote( + &self, + preserve_cf_clearance: bool, + ) -> Result { + let username = self + .snapshot() + .bootstrap + .current_username + .ok_or(FireCoreError::MissingCurrentUsername)?; + info!(username = %username, preserve_cf_clearance, "initiating remote logout"); + + if !self.snapshot().cookies.has_csrf_token() { + let _ = self.refresh_csrf_token_if_needed().await?; + } + + let path = format!("/session/{username}"); + let traced = self.build_api_request("logout", Method::DELETE, &path, true)?; + let (trace_id, response) = self.execute_request(traced).await?; + + if response.status() == StatusCode::FORBIDDEN { + let response_headers = response.headers().clone(); + let body = self.read_response_text(trace_id, response).await?; + self.diagnostics.record_http_status_error( + trace_id, + StatusCode::FORBIDDEN.as_u16(), + &body, + ); + if is_bad_csrf_body(&body) { + warn!("logout received BAD CSRF, refreshing token and retrying once"); + let _ = self.clear_csrf_token(); + let _ = self.refresh_csrf_token_if_needed().await?; + let retry = self.build_api_request("logout", Method::DELETE, &path, true)?; + let (retry_trace_id, response) = self.execute_request(retry).await?; + let response = expect_success(self, "logout", retry_trace_id, response).await?; + let _ = self.read_response_text(retry_trace_id, response).await?; + return Ok(self.logout_local(preserve_cf_clearance)); + } + + return Err(classify_http_status_error( + "logout", + StatusCode::FORBIDDEN.as_u16(), + &response_headers, + body, + )); + } + + let response = expect_success(self, "logout", trace_id, response).await?; + let _ = self.read_response_text(trace_id, response).await?; + Ok(self.logout_local(preserve_cf_clearance)) + } +} + +impl FireCore { + pub async fn passive_logout(&self, trigger: PassiveLogoutTrigger) -> Result<(), FireCoreError> { + info!( + source = %trigger.source, + signal_strength = ?trigger.signal_strength, + "initiating passive logout" + ); + { + let mut state = write_rwlock(&self.session, "session"); + state.auth_strike.record_passive_logout(); + state.epoch = state.epoch.saturating_add(1); + } + self.logout_local(true); + Ok(()) + } + + pub fn is_logging_out(&self) -> bool { + read_rwlock(&self.session, "session") + .auth_strike + .logging_out + } + + pub fn handle_server_forced_logout(&self, user_id: u64) -> bool { + { + let mut state = write_rwlock(&self.session, "session"); + if state.auth_strike.logging_out { + return false; + } + if state.snapshot.bootstrap.current_user_id != Some(user_id) { + return false; + } + if !state.snapshot.cookies.can_authenticate_requests() + && !state.snapshot.readiness().can_read_authenticated_api + { + return false; + } + info!(user_id, "handling server-forced logout"); + state.auth_strike.record_passive_logout(); + state.epoch = state.epoch.saturating_add(1); + } + let _ = self.logout_local(true); + true + } +} diff --git a/crates/fire-core/src/core/auth/mod.rs b/crates/fire-core/src/core/auth/mod.rs new file mode 100644 index 00000000..fac343b0 --- /dev/null +++ b/crates/fire-core/src/core/auth/mod.rs @@ -0,0 +1,10 @@ +mod auth_strike; +mod bootstrap; +mod csrf; +mod login_ready; +mod logout; +mod post_challenge; +mod probe; +mod signals; + +pub(crate) use auth_strike::{AuthStrikeState, StrikeDecision}; diff --git a/crates/fire-core/src/core/auth/post_challenge.rs b/crates/fire-core/src/core/auth/post_challenge.rs new file mode 100644 index 00000000..710193d8 --- /dev/null +++ b/crates/fire-core/src/core/auth/post_challenge.rs @@ -0,0 +1,107 @@ +use std::{future::Future, sync::OnceLock}; + +use tokio::runtime::{Builder, Handle, Runtime}; +use tracing::{info, warn}; + +use super::super::FireCore; + +impl FireCore { + /// After CF success: publish resolved generation, force bootstrap + full + /// app-state refresh when logged in, then notify platform subscribers + /// (MessageBus restart / banner clear / login continue). + /// Safe to call from sync UniFFI paths (falls back when no Tokio handle). + pub(crate) fn schedule_post_challenge_session_rebuild(&self) { + // Manual path bumps here; network path bumps in finish(true) right after. + let generation_hint = self.publish_clearance_resolved_if_idle(); + let has_login = self.snapshot().cookies.has_login_session(); + let core = self.clone(); + spawn_post_challenge_task(async move { + // Allow network finish(true) to publish generation before we notify. + tokio::time::sleep(std::time::Duration::from_millis(30)).await; + + if !has_login { + let generation = core + .cloudflare_clearance_resolved_generation() + .max(generation_hint); + core.notify_clearance_resolved(generation); + return; + } + + // Let cookie merge settle before the rebuild wave. + let settle = { + let runtime = core + .cloudflare_challenge_runtime + .lock() + .expect("cloudflare challenge runtime mutex poisoned"); + runtime.trust_settle_remaining() + }; + if let Some(remaining) = settle { + tokio::time::sleep(remaining).await; + } + + match core.refresh_bootstrap().await { + Ok(_) => { + info!("post-challenge bootstrap rebuild complete"); + } + Err(error) => { + warn!(error = %error, "post-challenge bootstrap rebuild failed"); + } + } + + // Bootstrap alone is not enough to keep writes healthy after CF: + // Set-Cookie may rotate `_forum_session`/`_t` (stale CSRF cleared), + // while home HTML may omit `` (interstitial / + // redirect / partial page). Force a `/session/csrf` realign so + // `can_write_authenticated_api` recovers before hosts act on the + // clearance-resolved event. Failures stay soft — BAD CSRF retry + // remains the last line of defense. + if core.snapshot().cookies.can_authenticate_requests() { + match core.refresh_csrf_token().await { + Ok(_) => info!("post-challenge CSRF realigned"), + Err(error) => { + warn!(error = %error, "post-challenge CSRF refresh failed") + } + } + } + + core.state_observers().notify_session(core.snapshot()); + + // Force a full loginCompleted-style batch so CF mid-refresh does not + // leave home/notifications stuck on a partial failure. + if let Err(error) = core + .app_state_refresher() + .refresh_all_forced(fire_models::RefreshTrigger::CloudflareResolved) + .await + { + warn!(error = %error, "post-challenge app state refresh failed"); + } + + let generation = core + .cloudflare_clearance_resolved_generation() + .max(generation_hint); + core.notify_clearance_resolved(generation); + }); + } +} + +fn post_challenge_runtime() -> &'static Runtime { + static RUNTIME: OnceLock = OnceLock::new(); + RUNTIME.get_or_init(|| { + Builder::new_multi_thread() + .enable_all() + .thread_name("fire-post-challenge") + .build() + .expect("failed to create post-challenge runtime") + }) +} + +fn spawn_post_challenge_task(future: F) +where + F: Future + Send + 'static, +{ + if let Ok(handle) = Handle::try_current() { + handle.spawn(future); + } else { + post_challenge_runtime().spawn(future); + } +} diff --git a/crates/fire-core/src/core/auth/probe.rs b/crates/fire-core/src/core/auth/probe.rs new file mode 100644 index 00000000..3f9ca1ed --- /dev/null +++ b/crates/fire-core/src/core/auth/probe.rs @@ -0,0 +1,39 @@ +use fire_models::ProbeResult; +use serde_json::Value; + +use super::super::FireCore; +use crate::error::FireCoreError; + +impl FireCore { + pub async fn probe_session(&self) -> Result { + let traced = + self.build_json_get_request("probe_session", "/session/current.json", Vec::new(), &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let status = response.status(); + if status.as_u16() == 404 { + return Ok(ProbeResult::Invalid); + } + let body = self.read_response_text(trace_id, response).await; + match body { + Ok(text) => { + let json: Value = serde_json::from_str(&text).unwrap_or_default(); + if let Some(user) = json.get("current_user") { + let username = user + .get("username") + .and_then(|u| u.as_str()) + .unwrap_or("") + .to_string(); + if !username.is_empty() { + return Ok(ProbeResult::Valid { username }); + } + } + if status.is_success() { + Ok(ProbeResult::Invalid) + } else { + Ok(ProbeResult::Inconclusive) + } + } + Err(_) => Ok(ProbeResult::Inconclusive), + } + } +} diff --git a/crates/fire-core/src/core/auth/signals.rs b/crates/fire-core/src/core/auth/signals.rs new file mode 100644 index 00000000..7488e7d1 --- /dev/null +++ b/crates/fire-core/src/core/auth/signals.rs @@ -0,0 +1,207 @@ +use fire_models::{ + AuthRuntimeSignal, AuthRuntimeSignalKind, AuthRuntimeSignalSource, AuthRuntimeSignalStrength, + PassiveLogoutTrigger, ProbeResult, SignalStrength, +}; +use tracing::info; + +use super::super::FireCore; +use super::StrikeDecision; +use crate::{ + error::FireCoreError, + sync_utils::{read_rwlock, write_rwlock}, +}; + +impl FireCore { + pub(crate) fn record_auth_runtime_signal(&self, signal: AuthRuntimeSignal) { + let signal_kind = signal.kind.clone(); + let signal_strength = signal.strength; + let signal_source = signal.source; + let operation = signal.operation.clone(); + let status = signal.status; + { + let mut state = write_rwlock(&self.session, "session"); + state.last_auth_runtime_signal = Some(signal); + } + info!( + kind = ?signal_kind, + strength = ?signal_strength, + source = ?signal_source, + operation = ?operation, + status = ?status, + "recorded auth runtime signal" + ); + } + + pub(crate) async fn process_auth_runtime_signal( + &self, + signal: AuthRuntimeSignal, + operation: &'static str, + ) -> Option { + let strike_strength = match signal.kind { + AuthRuntimeSignalKind::NotLoggedInBody + | AuthRuntimeSignalKind::DiscourseLoggedOutHeader => Some(SignalStrength::Strong), + AuthRuntimeSignalKind::MixedLoggedOutHeader + | AuthRuntimeSignalKind::MixedSignalCookieDeletionBlocked => Some(SignalStrength::Weak), + _ => None, + }; + self.record_auth_runtime_signal(signal); + match strike_strength { + Some(strength) => self.process_auth_strike_signal(strength, operation).await, + None => None, + } + } + + pub(crate) async fn process_auth_strike_signal( + &self, + strength: SignalStrength, + operation: &'static str, + ) -> Option { + let decision = { + let mut state = write_rwlock(&self.session, "session"); + state.auth_strike.receive_auth_signal(strength.clone()) + }; + match decision { + StrikeDecision::ProbeNeeded => { + { + let mut state = write_rwlock(&self.session, "session"); + state.auth_strike.probe_in_progress = true; + } + let probe_result = self.probe_session().await; + { + let mut state = write_rwlock(&self.session, "session"); + state.auth_strike.probe_in_progress = false; + } + match probe_result { + Ok(ProbeResult::Valid { .. }) => { + self.record_auth_runtime_signal(AuthRuntimeSignal { + kind: AuthRuntimeSignalKind::ProbeValid, + strength: AuthRuntimeSignalStrength::Terminal, + source: AuthRuntimeSignalSource::Probe, + operation: Some(operation.to_string()), + status: None, + }); + info!( + operation, + "probe confirmed session valid, resetting strikes" + ); + { + let mut state = write_rwlock(&self.session, "session"); + state.auth_strike.reset_strikes(); + } + None + } + Ok(ProbeResult::Invalid) => { + self.record_auth_runtime_signal(AuthRuntimeSignal { + kind: AuthRuntimeSignalKind::ProbeInvalid, + strength: AuthRuntimeSignalStrength::Terminal, + source: AuthRuntimeSignalSource::Probe, + operation: Some(operation.to_string()), + status: None, + }); + info!( + operation, + "probe confirmed session invalid, triggering passive logout" + ); + let _ = self + .passive_logout(PassiveLogoutTrigger { + source: format!("strike_probe_invalid:{operation}"), + signal_strength: strength, + cookie_diagnostic: String::new(), + }) + .await; + Some(FireCoreError::LoginRequired { + operation, + message: "登录状态已失效,请重新登录。".to_string(), + }) + } + Ok(ProbeResult::Inconclusive) => { + let strikes = { + let state = read_rwlock(&self.session, "session"); + state.auth_strike.strike_count + }; + if strikes >= 2 { + self.record_auth_runtime_signal(AuthRuntimeSignal { + kind: AuthRuntimeSignalKind::ProbeInconclusiveEscalated, + strength: AuthRuntimeSignalStrength::Terminal, + source: AuthRuntimeSignalSource::Probe, + operation: Some(operation.to_string()), + status: None, + }); + info!( + operation, + strikes, + "probe inconclusive with enough strikes, triggering passive logout" + ); + let _ = self + .passive_logout(PassiveLogoutTrigger { + source: format!("strike_probe_inconclusive:{operation}"), + signal_strength: strength, + cookie_diagnostic: String::new(), + }) + .await; + Some(FireCoreError::LoginRequired { + operation, + message: "登录状态已失效,请重新登录。".to_string(), + }) + } else { + self.record_auth_runtime_signal(AuthRuntimeSignal { + kind: AuthRuntimeSignalKind::ProbeInconclusive, + strength: AuthRuntimeSignalStrength::Diagnostic, + source: AuthRuntimeSignalSource::Probe, + operation: Some(operation.to_string()), + status: None, + }); + info!( + operation, + strikes, "probe inconclusive with few strikes, entering cooldown" + ); + let mut state = write_rwlock(&self.session, "session"); + state.auth_strike.enter_inconclusive_cooldown(); + Some(FireCoreError::LoginRequired { + operation, + message: "登录状态已失效,请重新登录。".to_string(), + }) + } + } + Err(_) => { + let strikes = { + let state = read_rwlock(&self.session, "session"); + state.auth_strike.strike_count + }; + if strikes >= 2 { + self.record_auth_runtime_signal(AuthRuntimeSignal { + kind: AuthRuntimeSignalKind::ProbeInconclusiveEscalated, + strength: AuthRuntimeSignalStrength::Terminal, + source: AuthRuntimeSignalSource::Probe, + operation: Some(operation.to_string()), + status: None, + }); + let _ = self + .passive_logout(PassiveLogoutTrigger { + source: format!("strike_probe_error:{operation}"), + signal_strength: strength, + cookie_diagnostic: String::new(), + }) + .await; + } else { + self.record_auth_runtime_signal(AuthRuntimeSignal { + kind: AuthRuntimeSignalKind::ProbeInconclusive, + strength: AuthRuntimeSignalStrength::Diagnostic, + source: AuthRuntimeSignalSource::Probe, + operation: Some(operation.to_string()), + status: None, + }); + let mut state = write_rwlock(&self.session, "session"); + state.auth_strike.enter_inconclusive_cooldown(); + } + Some(FireCoreError::LoginRequired { + operation, + message: "登录状态已失效,请重新登录。".to_string(), + }) + } + } + } + StrikeDecision::Accumulated { .. } | StrikeDecision::Ignore => None, + } + } +} diff --git a/crates/fire-core/src/core/creation.rs b/crates/fire-core/src/core/creation.rs deleted file mode 100644 index 32a8854c..00000000 --- a/crates/fire-core/src/core/creation.rs +++ /dev/null @@ -1,437 +0,0 @@ -use std::time::{SystemTime, UNIX_EPOCH}; - -use fire_models::{ - Draft, DraftData, DraftListResponse, PrivateMessageCreateRequest, ResolvedUploadUrl, - TopicCreateRequest, UploadResult, -}; -use http::{Method, StatusCode}; -use openwire::RequestBody; -use serde_json::{json, Value}; -use tracing::{info, warn}; -use url::form_urlencoded::byte_serialize; - -use super::{messagebus::upload_client_id, network::expect_success, FireCore}; -use crate::{ - creation_payloads::{ - parse_draft_detail_response_value, parse_draft_list_response_value, - parse_resolved_upload_urls_value, parse_upload_result_value, - }, - error::FireCoreError, - json_helpers::{integer_u32, integer_u64, invalid_json}, -}; - -impl FireCore { - pub async fn fetch_drafts( - &self, - offset: Option, - limit: Option, - ) -> Result { - info!(offset = ?offset, limit = ?limit, "fetching drafts"); - - let mut params = Vec::new(); - if let Some(offset) = offset { - params.push(("offset", offset.to_string())); - } - if let Some(limit) = limit.filter(|value| *value > 0) { - params.push(("limit", limit.to_string())); - } - - let traced = self.build_json_get_request("fetch drafts", "/drafts.json", params, &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch drafts", trace_id, response).await?; - let raw: Value = self - .read_response_json("fetch drafts", trace_id, response) - .await?; - parse_draft_list_response_value(raw).map_err(|source| FireCoreError::ResponseDeserialize { - operation: "fetch drafts", - source, - }) - } - - pub async fn fetch_draft(&self, draft_key: &str) -> Result, FireCoreError> { - info!(draft_key, "fetching draft"); - - let path = format!("/drafts/{}.json", encode_path_segment(draft_key)); - let traced = self.build_json_get_request("fetch draft", &path, vec![], &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - if response.status() == StatusCode::NOT_FOUND { - let _ = self.read_response_text(trace_id, response).await?; - return Ok(None); - } - - let response = expect_success(self, "fetch draft", trace_id, response).await?; - let raw: Value = self - .read_response_json("fetch draft", trace_id, response) - .await?; - parse_draft_detail_response_value(raw, draft_key).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch draft", - source, - } - }) - } - - pub async fn save_draft( - &self, - draft_key: &str, - data: DraftData, - sequence: u32, - ) -> Result { - info!( - draft_key, - sequence, - has_content = data.has_content(), - "saving draft" - ); - - let payload = serde_json::to_string(&data).map_err(FireCoreError::DiagnosticsSerialize)?; - let fields = vec![ - ("draft_key", draft_key.to_string()), - ("data", payload), - ("sequence", sequence.to_string()), - ]; - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("save draft", || { - self.build_form_request( - "save draft", - Method::POST, - "/drafts.json", - fields.clone(), - true, - ) - }) - .await?; - if response.status() == StatusCode::CONFLICT { - let raw: Value = self - .read_response_json("save draft", trace_id, response) - .await?; - return Ok(integer_u32( - raw.as_object() - .and_then(|object| object.get("draft_sequence")), - ) - .unwrap_or(sequence)); - } - - let response = expect_success(self, "save draft", trace_id, response).await?; - let raw: Value = self - .read_response_json("save draft", trace_id, response) - .await?; - Ok(integer_u32( - raw.as_object() - .and_then(|object| object.get("draft_sequence")), - ) - .unwrap_or(sequence.saturating_add(1))) - } - - pub async fn delete_draft( - &self, - draft_key: &str, - sequence: Option, - ) -> Result<(), FireCoreError> { - info!(draft_key, sequence = ?sequence, "deleting draft"); - - let path = if let Some(sequence) = sequence { - format!( - "/drafts/{}.json?sequence={sequence}", - encode_path_segment(draft_key) - ) - } else { - format!("/drafts/{}.json", encode_path_segment(draft_key)) - }; - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("delete draft", || { - self.build_api_request("delete draft", Method::DELETE, &path, true) - }) - .await?; - if response.status() == StatusCode::NOT_FOUND { - let _ = self.read_response_text(trace_id, response).await?; - return Ok(()); - } - - let response = expect_success(self, "delete draft", trace_id, response).await?; - let _ = self.read_response_text(trace_id, response).await?; - Ok(()) - } - - pub async fn lookup_upload_urls( - &self, - short_urls: Vec, - ) -> Result, FireCoreError> { - if short_urls.is_empty() { - return Ok(Vec::new()); - } - - info!( - short_urls_count = short_urls.len(), - "looking up upload urls" - ); - - let body = json!({ "short_urls": short_urls }).to_string(); - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("lookup upload urls", || { - self.build_api_request_with_body( - "lookup upload urls", - Method::POST, - "/uploads/lookup-urls", - Some("application/json; charset=utf-8"), - RequestBody::from(body.clone()), - true, - ) - }) - .await?; - let response = expect_success(self, "lookup upload urls", trace_id, response).await?; - let raw: Value = self - .read_response_json("lookup upload urls", trace_id, response) - .await?; - parse_resolved_upload_urls_value(raw).map_err(|source| FireCoreError::ResponseDeserialize { - operation: "lookup upload urls", - source, - }) - } - - pub async fn upload_image( - &self, - file_name: &str, - mime_type: Option<&str>, - bytes: Vec, - ) -> Result { - info!( - file_name, - has_mime_type = mime_type.is_some(), - bytes_len = bytes.len(), - "uploading composer image" - ); - - let client_id = upload_client_id(&self.message_bus); - let boundary = multipart_boundary(); - let content_type = format!("multipart/form-data; boundary={boundary}"); - let path = format!("/uploads.json?client_id={client_id}"); - let request_body = multipart_upload_body( - &boundary, - file_name, - mime_type.unwrap_or("application/octet-stream"), - &bytes, - ); - - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("upload image", || { - self.build_api_request_with_body( - "upload image", - Method::POST, - &path, - Some(&content_type), - RequestBody::from(request_body.clone()), - true, - ) - }) - .await?; - let response = expect_success(self, "upload image", trace_id, response).await?; - let raw: Value = self - .read_response_json("upload image", trace_id, response) - .await?; - parse_upload_result_value(raw).map_err(|source| FireCoreError::ResponseDeserialize { - operation: "upload image", - source, - }) - } - - pub async fn create_topic(&self, input: TopicCreateRequest) -> Result { - info!( - category_id = input.category_id, - tags_count = input.tags.len(), - title_len = input.title.len(), - raw_len = input.raw.len(), - "creating topic" - ); - - let mut fields = vec![ - ("title", input.title), - ("raw", input.raw), - ("category", input.category_id.to_string()), - ("archetype", "regular".to_string()), - ]; - for tag in input - .tags - .into_iter() - .filter(|value| !value.trim().is_empty()) - { - fields.push(("tags[]", tag)); - } - - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("create topic", || { - self.build_form_request( - "create topic", - Method::POST, - "/posts.json", - fields.clone(), - true, - ) - }) - .await?; - let response = expect_success(self, "create topic", trace_id, response).await?; - let raw: Value = self - .read_response_json("create topic", trace_id, response) - .await?; - let result = parse_create_topic_response(raw); - match &result { - Ok(topic_id) => info!(topic_id, "topic created successfully"), - Err(error) => warn!(error = %error, "topic creation failed during response parsing"), - } - result - } - - pub async fn create_private_message( - &self, - input: PrivateMessageCreateRequest, - ) -> Result { - info!( - recipients_count = input.target_recipients.len(), - title_len = input.title.len(), - raw_len = input.raw.len(), - "creating private message" - ); - - let mut fields = vec![ - ("title", input.title), - ("raw", input.raw), - ("archetype", "private_message".to_string()), - ("target_recipients", input.target_recipients.join(",")), - ]; - fields.retain(|(_, value)| !value.trim().is_empty()); - - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("create private message", || { - self.build_form_request( - "create private message", - Method::POST, - "/posts.json", - fields.clone(), - true, - ) - }) - .await?; - let response = expect_success(self, "create private message", trace_id, response).await?; - let raw: Value = self - .read_response_json("create private message", trace_id, response) - .await?; - let result = parse_create_topic_response(raw); - match &result { - Ok(topic_id) => info!(topic_id, "private message created successfully"), - Err(error) => warn!( - error = %error, - "private message creation failed during response parsing" - ), - } - result - } -} - -fn parse_create_topic_response(value: Value) -> Result { - let Value::Object(object) = value else { - return Err(FireCoreError::ResponseDeserialize { - operation: "create topic", - source: invalid_json("create topic response root was not an object"), - }); - }; - - if object - .get("action") - .and_then(Value::as_str) - .is_some_and(|action| action == "enqueued") - { - return Err(FireCoreError::PostEnqueued { - pending_count: integer_u32(object.get("pending_count")).unwrap_or(0), - }); - } - - if let Some(topic_id) = object - .get("post") - .and_then(Value::as_object) - .and_then(|post| integer_u64(post.get("topic_id"))) - { - return Ok(topic_id); - } - - if let Some(topic_id) = integer_u64(object.get("topic_id")) { - return Ok(topic_id); - } - - if let Some(error) = response_error("create topic", &object) { - return Err(error); - } - - Err(FireCoreError::ResponseDeserialize { - operation: "create topic", - source: invalid_json("create topic response did not contain a topic_id"), - }) -} - -fn response_error( - operation: &'static str, - object: &serde_json::Map, -) -> Option { - if !object - .get("success") - .is_some_and(|value| matches!(value, Value::Bool(false))) - { - return None; - } - - let body = match object.get("errors") { - Some(Value::Array(items)) => items - .iter() - .filter_map(|item| item.as_str()) - .collect::>() - .join("\n"), - Some(Value::String(value)) => value.clone(), - Some(value) => value.to_string(), - None => String::new(), - }; - - Some(FireCoreError::HttpStatus { - operation, - status: StatusCode::OK.as_u16(), - body, - }) -} - -fn multipart_boundary() -> String { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|value| value.as_nanos()) - .unwrap_or(0); - format!("fire-boundary-{nanos}") -} - -fn multipart_upload_body( - boundary: &str, - file_name: &str, - mime_type: &str, - bytes: &[u8], -) -> Vec { - let sanitized_file_name = file_name.replace(['"', '\r', '\n'], "_"); - let mut body = Vec::new(); - body.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); - body.extend_from_slice(b"Content-Disposition: form-data; name=\"upload_type\"\r\n\r\n"); - body.extend_from_slice(b"composer\r\n"); - body.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); - body.extend_from_slice(b"Content-Disposition: form-data; name=\"synchronous\"\r\n\r\n"); - body.extend_from_slice(b"true\r\n"); - body.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); - body.extend_from_slice( - format!( - "Content-Disposition: form-data; name=\"file\"; filename=\"{sanitized_file_name}\"\r\n" - ) - .as_bytes(), - ); - body.extend_from_slice(format!("Content-Type: {mime_type}\r\n\r\n").as_bytes()); - body.extend_from_slice(bytes); - body.extend_from_slice(b"\r\n"); - body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes()); - body -} - -fn encode_path_segment(value: &str) -> String { - byte_serialize(value.as_bytes()).collect() -} diff --git a/crates/fire-core/src/core/creation/drafts.rs b/crates/fire-core/src/core/creation/drafts.rs new file mode 100644 index 00000000..b3892297 --- /dev/null +++ b/crates/fire-core/src/core/creation/drafts.rs @@ -0,0 +1,133 @@ +impl FireCore { + pub async fn fetch_drafts( + &self, + offset: Option, + limit: Option, + ) -> Result { + info!(offset = ?offset, limit = ?limit, "fetching drafts"); + + let mut params = Vec::new(); + if let Some(offset) = offset { + params.push(("offset", offset.to_string())); + } + if let Some(limit) = limit.filter(|value| *value > 0) { + params.push(("limit", limit.to_string())); + } + + let traced = self.build_json_get_request("fetch drafts", "/drafts.json", params, &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch drafts", trace_id, response).await?; + let raw: Value = self + .read_response_json("fetch drafts", trace_id, response) + .await?; + parse_draft_list_response_value(raw).map_err(|source| FireCoreError::ResponseDeserialize { + operation: "fetch drafts", + source, + }) + } + + pub async fn fetch_draft(&self, draft_key: &str) -> Result, FireCoreError> { + info!(draft_key, "fetching draft"); + + let path = format!("/drafts/{}.json", encode_path_segment(draft_key)); + let traced = self.build_json_get_request("fetch draft", &path, vec![], &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + if response.status() == StatusCode::NOT_FOUND { + let _ = self.read_response_text(trace_id, response).await?; + return Ok(None); + } + + let response = expect_success(self, "fetch draft", trace_id, response).await?; + let raw: Value = self + .read_response_json("fetch draft", trace_id, response) + .await?; + parse_draft_detail_response_value(raw, draft_key).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch draft", + source, + } + }) + } + + pub async fn save_draft( + &self, + draft_key: &str, + data: DraftData, + sequence: u32, + ) -> Result { + info!( + draft_key, + sequence, + has_content = data.has_content(), + "saving draft" + ); + + let payload = serde_json::to_string(&data).map_err(FireCoreError::DiagnosticsSerialize)?; + let fields = vec![ + ("draft_key", draft_key.to_string()), + ("data", payload), + ("sequence", sequence.to_string()), + ]; + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("save draft", || { + self.build_form_request( + "save draft", + Method::POST, + "/drafts.json", + fields.clone(), + true, + ) + }) + .await?; + if response.status() == StatusCode::CONFLICT { + let raw: Value = self + .read_response_json("save draft", trace_id, response) + .await?; + return Ok(integer_u32( + raw.as_object() + .and_then(|object| object.get("draft_sequence")), + ) + .unwrap_or(sequence)); + } + + let response = expect_success(self, "save draft", trace_id, response).await?; + let raw: Value = self + .read_response_json("save draft", trace_id, response) + .await?; + Ok(integer_u32( + raw.as_object() + .and_then(|object| object.get("draft_sequence")), + ) + .unwrap_or(sequence.saturating_add(1))) + } + + pub async fn delete_draft( + &self, + draft_key: &str, + sequence: Option, + ) -> Result<(), FireCoreError> { + info!(draft_key, sequence = ?sequence, "deleting draft"); + + let path = if let Some(sequence) = sequence { + format!( + "/drafts/{}.json?sequence={sequence}", + encode_path_segment(draft_key) + ) + } else { + format!("/drafts/{}.json", encode_path_segment(draft_key)) + }; + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("delete draft", || { + self.build_api_request("delete draft", Method::DELETE, &path, true) + }) + .await?; + if response.status() == StatusCode::NOT_FOUND { + let _ = self.read_response_text(trace_id, response).await?; + return Ok(()); + } + + let response = expect_success(self, "delete draft", trace_id, response).await?; + let _ = self.read_response_text(trace_id, response).await?; + Ok(()) + } +} diff --git a/crates/fire-core/src/core/creation/mod.rs b/crates/fire-core/src/core/creation/mod.rs new file mode 100644 index 00000000..52bfffd2 --- /dev/null +++ b/crates/fire-core/src/core/creation/mod.rs @@ -0,0 +1,134 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +use fire_models::{ + Draft, DraftData, DraftListResponse, PrivateMessageCreateRequest, ResolvedUploadUrl, + TopicCreateRequest, UploadResult, +}; +use http::{Method, StatusCode}; +use openwire::RequestBody; +use serde_json::{json, Value}; +use tracing::{info, warn}; +use url::form_urlencoded::byte_serialize; + +use super::{messagebus::upload_client_id, network::expect_success, FireCore}; +use crate::{ + creation_payloads::{ + parse_draft_detail_response_value, parse_draft_list_response_value, + parse_resolved_upload_urls_value, parse_upload_result_value, + }, + error::FireCoreError, + json_helpers::{integer_u32, integer_u64, invalid_json}, +}; + +include!("drafts.rs"); +include!("uploads.rs"); +include!("topics.rs"); +include!("private_messages.rs"); +fn parse_create_topic_response(value: Value) -> Result { + let Value::Object(object) = value else { + return Err(FireCoreError::ResponseDeserialize { + operation: "create topic", + source: invalid_json("create topic response root was not an object"), + }); + }; + + if object + .get("action") + .and_then(Value::as_str) + .is_some_and(|action| action == "enqueued") + { + return Err(FireCoreError::PostEnqueued { + pending_count: integer_u32(object.get("pending_count")).unwrap_or(0), + }); + } + + if let Some(topic_id) = object + .get("post") + .and_then(Value::as_object) + .and_then(|post| integer_u64(post.get("topic_id"))) + { + return Ok(topic_id); + } + + if let Some(topic_id) = integer_u64(object.get("topic_id")) { + return Ok(topic_id); + } + + if let Some(error) = response_error("create topic", &object) { + return Err(error); + } + + Err(FireCoreError::ResponseDeserialize { + operation: "create topic", + source: invalid_json("create topic response did not contain a topic_id"), + }) +} + +fn response_error( + operation: &'static str, + object: &serde_json::Map, +) -> Option { + if !object + .get("success") + .is_some_and(|value| matches!(value, Value::Bool(false))) + { + return None; + } + + let body = match object.get("errors") { + Some(Value::Array(items)) => items + .iter() + .filter_map(|item| item.as_str()) + .collect::>() + .join("\n"), + Some(Value::String(value)) => value.clone(), + Some(value) => value.to_string(), + None => String::new(), + }; + + Some(FireCoreError::HttpStatus { + operation, + status: StatusCode::OK.as_u16(), + body, + }) +} + +fn multipart_boundary() -> String { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|value| value.as_nanos()) + .unwrap_or(0); + format!("fire-boundary-{nanos}") +} + +fn multipart_upload_body( + boundary: &str, + file_name: &str, + mime_type: &str, + bytes: &[u8], +) -> Vec { + let sanitized_file_name = file_name.replace(['"', '\r', '\n'], "_"); + let mut body = Vec::new(); + body.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); + body.extend_from_slice(b"Content-Disposition: form-data; name=\"upload_type\"\r\n\r\n"); + body.extend_from_slice(b"composer\r\n"); + body.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); + body.extend_from_slice(b"Content-Disposition: form-data; name=\"synchronous\"\r\n\r\n"); + body.extend_from_slice(b"true\r\n"); + body.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); + body.extend_from_slice( + format!( + "Content-Disposition: form-data; name=\"file\"; filename=\"{sanitized_file_name}\"\r\n" + ) + .as_bytes(), + ); + body.extend_from_slice(format!("Content-Type: {mime_type}\r\n\r\n").as_bytes()); + body.extend_from_slice(bytes); + body.extend_from_slice(b"\r\n"); + body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes()); + body +} + +fn encode_path_segment(value: &str) -> String { + byte_serialize(value.as_bytes()).collect() +} diff --git a/crates/fire-core/src/core/creation/private_messages.rs b/crates/fire-core/src/core/creation/private_messages.rs new file mode 100644 index 00000000..afb2fd80 --- /dev/null +++ b/crates/fire-core/src/core/creation/private_messages.rs @@ -0,0 +1,46 @@ +impl FireCore { + pub async fn create_private_message( + &self, + input: PrivateMessageCreateRequest, + ) -> Result { + info!( + recipients_count = input.target_recipients.len(), + title_len = input.title.len(), + raw_len = input.raw.len(), + "creating private message" + ); + + let mut fields = vec![ + ("title", input.title), + ("raw", input.raw), + ("archetype", "private_message".to_string()), + ("target_recipients", input.target_recipients.join(",")), + ]; + fields.retain(|(_, value)| !value.trim().is_empty()); + + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("create private message", || { + self.build_form_request( + "create private message", + Method::POST, + "/posts.json", + fields.clone(), + true, + ) + }) + .await?; + let response = expect_success(self, "create private message", trace_id, response).await?; + let raw: Value = self + .read_response_json("create private message", trace_id, response) + .await?; + let result = parse_create_topic_response(raw); + match &result { + Ok(topic_id) => info!(topic_id, "private message created successfully"), + Err(error) => warn!( + error = %error, + "private message creation failed during response parsing" + ), + } + result + } +} diff --git a/crates/fire-core/src/core/creation/topics.rs b/crates/fire-core/src/core/creation/topics.rs new file mode 100644 index 00000000..a4d9ab2d --- /dev/null +++ b/crates/fire-core/src/core/creation/topics.rs @@ -0,0 +1,48 @@ +impl FireCore { + pub async fn create_topic(&self, input: TopicCreateRequest) -> Result { + info!( + category_id = input.category_id, + tags_count = input.tags.len(), + title_len = input.title.len(), + raw_len = input.raw.len(), + "creating topic" + ); + + let mut fields = vec![ + ("title", input.title), + ("raw", input.raw), + ("category", input.category_id.to_string()), + ("archetype", "regular".to_string()), + ]; + for tag in input + .tags + .into_iter() + .filter(|value| !value.trim().is_empty()) + { + fields.push(("tags[]", tag)); + } + + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("create topic", || { + self.build_form_request( + "create topic", + Method::POST, + "/posts.json", + fields.clone(), + true, + ) + }) + .await?; + let response = expect_success(self, "create topic", trace_id, response).await?; + let raw: Value = self + .read_response_json("create topic", trace_id, response) + .await?; + let result = parse_create_topic_response(raw); + match &result { + Ok(topic_id) => info!(topic_id, "topic created successfully"), + Err(error) => warn!(error = %error, "topic creation failed during response parsing"), + } + result + } + +} diff --git a/crates/fire-core/src/core/creation/uploads.rs b/crates/fire-core/src/core/creation/uploads.rs new file mode 100644 index 00000000..ddaa1302 --- /dev/null +++ b/crates/fire-core/src/core/creation/uploads.rs @@ -0,0 +1,84 @@ +impl FireCore { + pub async fn lookup_upload_urls( + &self, + short_urls: Vec, + ) -> Result, FireCoreError> { + if short_urls.is_empty() { + return Ok(Vec::new()); + } + + info!( + short_urls_count = short_urls.len(), + "looking up upload urls" + ); + + let body = json!({ "short_urls": short_urls }).to_string(); + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("lookup upload urls", || { + self.build_api_request_with_body( + "lookup upload urls", + Method::POST, + "/uploads/lookup-urls", + Some("application/json; charset=utf-8"), + RequestBody::from(body.clone()), + true, + ) + }) + .await?; + let response = expect_success(self, "lookup upload urls", trace_id, response).await?; + let raw: Value = self + .read_response_json("lookup upload urls", trace_id, response) + .await?; + parse_resolved_upload_urls_value(raw).map_err(|source| FireCoreError::ResponseDeserialize { + operation: "lookup upload urls", + source, + }) + } + + pub async fn upload_image( + &self, + file_name: &str, + mime_type: Option<&str>, + bytes: Vec, + ) -> Result { + info!( + file_name, + has_mime_type = mime_type.is_some(), + bytes_len = bytes.len(), + "uploading composer image" + ); + + let client_id = upload_client_id(&self.message_bus); + let boundary = multipart_boundary(); + let content_type = format!("multipart/form-data; boundary={boundary}"); + let path = format!("/uploads.json?client_id={client_id}"); + let request_body = multipart_upload_body( + &boundary, + file_name, + mime_type.unwrap_or("application/octet-stream"), + &bytes, + ); + + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("upload image", || { + self.build_api_request_with_body( + "upload image", + Method::POST, + &path, + Some(&content_type), + RequestBody::from(request_body.clone()), + true, + ) + }) + .await?; + let response = expect_success(self, "upload image", trace_id, response).await?; + let raw: Value = self + .read_response_json("upload image", trace_id, response) + .await?; + parse_upload_result_value(raw).map_err(|source| FireCoreError::ResponseDeserialize { + operation: "upload image", + source, + }) + } + +} diff --git a/crates/fire-core/src/core/mod.rs b/crates/fire-core/src/core/mod.rs index b612c777..3bac0693 100644 --- a/crates/fire-core/src/core/mod.rs +++ b/crates/fire-core/src/core/mod.rs @@ -1,5 +1,4 @@ mod auth; -mod auth_strike; mod cdk; mod cf_challenge; mod chat; @@ -142,7 +141,7 @@ pub(crate) struct FireSessionRuntimeState { pub(crate) auth_cookie_revision: u64, pub(crate) auth_recovery_hint: Option, pub(crate) last_response_auth_change: Option, - pub(crate) auth_strike: auth_strike::AuthStrikeState, + pub(crate) auth_strike: auth::AuthStrikeState, pub(crate) last_auth_runtime_signal: Option, pub(crate) read_path_login_request: Option, pub(crate) read_path_login_generation: u64, @@ -204,7 +203,7 @@ impl FireCore { auth_cookie_revision: 1, auth_recovery_hint: None, last_response_auth_change: None, - auth_strike: auth_strike::AuthStrikeState::default(), + auth_strike: auth::AuthStrikeState::default(), last_auth_runtime_signal: None, read_path_login_request: None, read_path_login_generation: 0, diff --git a/crates/fire-core/src/core/network/body.rs b/crates/fire-core/src/core/network/body.rs index 93dab344..604fbd3d 100644 --- a/crates/fire-core/src/core/network/body.rs +++ b/crates/fire-core/src/core/network/body.rs @@ -10,7 +10,7 @@ use super::auth_signals::{ response_login_invalidation_signal, success_auth_runtime_signal, }; use super::challenge::is_cloudflare_challenge_response; -use super::execute::{response_epoch_context, stale_response_error, take_trace_cancellation_guard}; +use super::profile::{response_epoch_context, stale_response_error, take_trace_cancellation_guard}; use crate::error::{CloudflareChallengeFailureReason, FireCoreError}; impl FireCore { diff --git a/crates/fire-core/src/core/network/execute.rs b/crates/fire-core/src/core/network/execute.rs index 6a109371..20dff24d 100644 --- a/crates/fire-core/src/core/network/execute.rs +++ b/crates/fire-core/src/core/network/execute.rs @@ -1,41 +1,26 @@ use std::sync::{Arc, Mutex, RwLock}; -use fire_models::{ - AuthRuntimeSignal, AuthRuntimeSignalKind, AuthRuntimeSignalSource, AuthRuntimeSignalStrength, - CloudflareChallengeRequest, -}; -use http::header::COOKIE; -use http::{Response, StatusCode}; +use http::Response; #[cfg(debug_assertions)] use openwire::ProxyRules; -use openwire::{Call, CallOptions, Client, DnsResolver, ResponseBody}; +use openwire::{CallOptions, Client, DnsResolver, ResponseBody}; use tracing::{debug, warn}; use url::Url; use super::super::{ - FireCore, CLIENT_MAX_CONNECTIONS_PER_HOST, CLIENT_POOL_MAX_IDLE_PER_HOST, - MESSAGE_BUS_CALL_TIMEOUT, MESSAGE_BUS_HTTP2_KEEP_ALIVE_INTERVAL, NETWORK_CALL_TIMEOUT, - NETWORK_CONNECT_TIMEOUT, -}; -use super::challenge::{ - is_cloudflare_challenge_response, should_present_foreground_challenge, - CloudflareChallengeFinishGuard, + CLIENT_MAX_CONNECTIONS_PER_HOST, CLIENT_POOL_MAX_IDLE_PER_HOST, + MESSAGE_BUS_HTTP2_KEEP_ALIVE_INTERVAL, NETWORK_CALL_TIMEOUT, NETWORK_CONNECT_TIMEOUT, }; use super::client::{ apply_platform_tls, fire_openwire_logger_interceptor, FireCommonHeaderInterceptor, FireTraceSnapshotInterceptor, }; -use super::heal::FireCookieSelfHealingTarget; -use super::traced::{ - clone_request_for_retry, request_origin_url, request_url_string, response_from_parts, - FireSkipCloudflareBlock, FireSkipCookieSelfHeal, TracedRequest, -}; +use super::profile::apply_call_profile; +use super::traced::{FireSkipCloudflareBlock, TracedRequest}; use super::{FireCallProfile, FireNetworkLayer, FireRequestEpoch, FireResponseEpochContext}; use crate::cookies::{FireSessionCookieJar, FIRE_REQUEST_EPOCH, FIRE_REQUEST_TRACE_ID}; -use crate::diagnostics::{ - FireDiagnosticsStore, FireNetworkTraceCancellationGuard, FireNetworkTraceEventListenerFactory, -}; -use crate::error::{CloudflareChallengeFailureReason, FireCoreError}; +use crate::diagnostics::{FireDiagnosticsStore, FireNetworkTraceEventListenerFactory}; +use crate::error::FireCoreError; use crate::sync_utils::read_rwlock; impl FireNetworkLayer { @@ -211,293 +196,3 @@ impl FireNetworkLayer { read_rwlock(&self.session, "session").last_response_auth_change } } - -pub(crate) fn take_trace_cancellation_guard( - response: &mut Response, -) -> Option { - response - .extensions_mut() - .remove::() -} - -pub(super) fn response_epoch_context( - response: &Response, -) -> Option { - response - .extensions() - .get::() - .copied() -} - -pub(super) fn stale_response_error( - core: &FireCore, - diagnostics: &Arc, - trace_id: u64, - context: FireResponseEpochContext, -) -> Option { - let current_epoch = core.current_session_epoch(); - if current_epoch == context.request_epoch { - return None; - } - - diagnostics.record_cancelled_if_in_progress( - trace_id, - "Session superseded", - Some(&format!( - "Discarded `{}` response after session epoch advanced from {} to {}", - context.operation, context.request_epoch, current_epoch - )), - ); - Some(FireCoreError::StaleSessionResponse { - operation: context.operation, - }) -} - -pub(super) fn apply_call_profile(call: Call, profile: FireCallProfile) -> Call { - call.options(call_options_for_profile(profile)) -} - -pub(super) fn call_options_for_profile(profile: FireCallProfile) -> CallOptions { - match profile { - FireCallProfile::DefaultApi => CallOptions::default(), - FireCallProfile::MessageBusPoll => { - CallOptions::default().call_timeout(MESSAGE_BUS_CALL_TIMEOUT) - } - } -} - -impl FireCore { - pub(crate) async fn execute_request( - &self, - traced: TracedRequest, - ) -> Result<(u64, Response), FireCoreError> { - self.execute_request_with_options(traced, CallOptions::default()) - .await - } - - pub(crate) async fn execute_request_with_options( - &self, - traced: TracedRequest, - options: CallOptions, - ) -> Result<(u64, Response), FireCoreError> { - let has_challenge_handler = self.cloudflare_challenge_handler.get().is_some(); - let has_cookie_healing_handler = self.cookie_self_healing_handler.get().is_some(); - let skip_cookie_self_heal = traced - .request - .extensions() - .get::() - .is_some(); - let skip_cloudflare_block = traced - .request - .extensions() - .get::() - .is_some(); - let sent_cf_clearance = traced - .request - .headers() - .get(COOKIE) - .and_then(|value| value.to_str().ok()) - .and_then(fire_models::extract_cf_clearance_from_cookie_header); - let retry_request = - if has_challenge_handler || (has_cookie_healing_handler && !skip_cookie_self_heal) { - clone_request_for_retry(&traced.request) - } else { - None - }; - let request_url = request_url_string(&traced.request); - let origin_url = request_origin_url(&self.base_url, &traced.request); - let is_foreground = should_present_foreground_challenge( - traced.operation, - FireCallProfile::DefaultApi, - &traced.request, - ); - let operation = traced.operation; - let (trace_id, response) = self - .network - .execute_traced_with_options(traced, FireCallProfile::DefaultApi, options) - .await?; - - let response = if has_challenge_handler - && matches!( - response.status(), - StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS - ) { - let status = response.status(); - let (parts, body) = response.into_parts(); - let body = body - .bytes() - .await - .map_err(|source| FireCoreError::Network { source })?; - let body_text = String::from_utf8_lossy(&body); - if !is_cloudflare_challenge_response(status.as_u16(), &parts.headers, &body_text) { - self.complete_pending_clearance_retry_if_needed(); - response_from_parts(parts, body) - } else { - self.diagnostics - .record_http_status_error(trace_id, status.as_u16(), &body_text); - self.record_auth_runtime_signal(AuthRuntimeSignal { - kind: AuthRuntimeSignalKind::CloudflareChallenge, - strength: AuthRuntimeSignalStrength::Diagnostic, - source: AuthRuntimeSignalSource::HttpResponse, - operation: Some(operation.to_string()), - status: Some(status.as_u16()), - }); - // Local clearance (if any) was just rejected by the edge. - let challenged = sent_cf_clearance.clone().or_else(|| { - self.snapshot() - .cookies - .cf_clearance - .as_deref() - .map(fire_models::normalize_cf_clearance_value) - .filter(|value| !value.is_empty()) - }); - self.note_cf_clearance_challenged(challenged.as_deref()); - self.note_cloudflare_clearance_rejected(); - if skip_cloudflare_block { - self.mark_ineffective_cloudflare_cooldown(); - return Ok((trace_id, response_from_parts(parts, body))); - } - self.capture_turnstile_sitekey_from_challenge_body(&body_text); - let handler = match self.cloudflare_challenge_handler.get() { - Some(handler) => handler, - None => { - return Ok((trace_id, response_from_parts(parts, body))); - } - }; - - let begin = { - let mut runtime = self - .cloudflare_challenge_runtime - .lock() - .expect("cloudflare challenge runtime mutex poisoned"); - runtime.begin_or_join(is_foreground) - }; - - match begin { - super::super::cf_challenge::CloudflareChallengeBegin::Cooldown => { - return Err(FireCoreError::CloudflareChallenge { - operation, - reason: CloudflareChallengeFailureReason::Cooldown, - }); - } - super::super::cf_challenge::CloudflareChallengeBegin::BackgroundSuppressed => { - return Err(FireCoreError::CloudflareChallenge { - operation, - reason: CloudflareChallengeFailureReason::BackgroundSuppressed, - }); - } - super::super::cf_challenge::CloudflareChallengeBegin::Join(join_rx) => { - return self - .await_shared_cloudflare_challenge_and_retry( - operation, - join_rx, - retry_request, - options, - ) - .await; - } - super::super::cf_challenge::CloudflareChallengeBegin::Start => {} - } - - let mut finish_guard = CloudflareChallengeFinishGuard { - runtime: Arc::clone(&self.cloudflare_challenge_runtime), - finished: false, - }; - - let challenge_result = handler(CloudflareChallengeRequest { - operation: operation.to_string(), - request_url: request_url.clone(), - origin_url: origin_url.clone(), - is_foreground, - session_epoch: self.current_session_epoch(), - }) - .await; - - let failure_reason = if challenge_result.user_cancelled { - Some(CloudflareChallengeFailureReason::Cancelled) - } else if !challenge_result.completed { - Some(CloudflareChallengeFailureReason::Failed) - } else { - None - }; - - let accepted = if failure_reason.is_some() { - false - } else { - let fresh_clearance = challenge_result - .fresh_cf_clearance - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_string); - { - let mut runtime = self - .cloudflare_challenge_runtime - .lock() - .expect("cloudflare challenge runtime mutex poisoned"); - runtime.mark_pending_retry(); - } - let _ = self.complete_cloudflare_challenge( - challenge_result.cookies, - fresh_clearance, - challenge_result.browser_user_agent, - ); - true - }; - - // Joiners may retry now. Recovery is published only after the - // original request retry proves the page-clear was usable. - if accepted { - finish_guard.finish_page_clear(); - // Don't wait for the API retry to hydrate identity. Profile - // and MessageBus need current_username even when the retry - // is still proving recovery or later hits cooldown. - let snapshot = self.snapshot(); - if snapshot.cookies.has_login_session() - && (!snapshot.readiness().has_current_user - || !snapshot.bootstrap.has_preloaded_data) - { - self.schedule_post_challenge_session_rebuild(); - } - } else { - finish_guard.finish(false); - } - - if !accepted { - return Err(FireCoreError::CloudflareChallenge { - operation, - reason: failure_reason.unwrap_or(CloudflareChallengeFailureReason::Failed), - }); - } - - // complete_cloudflare_challenge already schedules post-challenge - // bootstrap rebuild when a login session is present. - - return self - .retry_after_cloudflare_challenge(operation, retry_request, options) - .await; - } - } else { - self.complete_pending_clearance_retry_if_needed(); - response - }; - - if has_cookie_healing_handler && !skip_cookie_self_heal { - return self - .maybe_self_heal_response( - operation, - FireCookieSelfHealingTarget { - request_url, - origin_url, - }, - trace_id, - response, - retry_request, - options, - ) - .await; - } - - Ok((trace_id, response)) - } -} diff --git a/crates/fire-core/src/core/network/mod.rs b/crates/fire-core/src/core/network/mod.rs index 2895c27c..2dacb285 100644 --- a/crates/fire-core/src/core/network/mod.rs +++ b/crates/fire-core/src/core/network/mod.rs @@ -9,6 +9,8 @@ mod csrf; mod execute; mod headers; mod heal; +mod profile; +mod recovery; mod request; mod traced; @@ -27,9 +29,9 @@ pub(crate) use challenge::{ extract_turnstile_sitekey, is_cloudflare_challenge_body, is_cloudflare_challenge_response, }; pub(crate) use client::apply_platform_tls; -pub(crate) use execute::take_trace_cancellation_guard; #[allow(unused_imports)] pub(crate) use headers::{request_origin, request_referer}; +pub(crate) use profile::take_trace_cancellation_guard; #[allow(unused_imports)] pub(crate) use traced::{ FireSkipCloudflareBlock, FireSkipCookieSelfHeal, FireSkipCsrfHeader, TracedRequest, diff --git a/crates/fire-core/src/core/network/profile.rs b/crates/fire-core/src/core/network/profile.rs new file mode 100644 index 00000000..959c35fb --- /dev/null +++ b/crates/fire-core/src/core/network/profile.rs @@ -0,0 +1,63 @@ +use std::sync::Arc; + +use http::Response; +use openwire::{Call, CallOptions, ResponseBody}; + +use super::super::{FireCore, MESSAGE_BUS_CALL_TIMEOUT}; +use super::{FireCallProfile, FireResponseEpochContext}; +use crate::diagnostics::{FireDiagnosticsStore, FireNetworkTraceCancellationGuard}; +use crate::error::FireCoreError; + +pub(crate) fn take_trace_cancellation_guard( + response: &mut Response, +) -> Option { + response + .extensions_mut() + .remove::() +} + +pub(super) fn response_epoch_context( + response: &Response, +) -> Option { + response + .extensions() + .get::() + .copied() +} + +pub(super) fn stale_response_error( + core: &FireCore, + diagnostics: &Arc, + trace_id: u64, + context: FireResponseEpochContext, +) -> Option { + let current_epoch = core.current_session_epoch(); + if current_epoch == context.request_epoch { + return None; + } + + diagnostics.record_cancelled_if_in_progress( + trace_id, + "Session superseded", + Some(&format!( + "Discarded `{}` response after session epoch advanced from {} to {}", + context.operation, context.request_epoch, current_epoch + )), + ); + Some(FireCoreError::StaleSessionResponse { + operation: context.operation, + }) +} + +pub(super) fn apply_call_profile(call: Call, profile: FireCallProfile) -> Call { + call.options(call_options_for_profile(profile)) +} + +pub(super) fn call_options_for_profile(profile: FireCallProfile) -> CallOptions { + match profile { + FireCallProfile::DefaultApi => CallOptions::default(), + FireCallProfile::MessageBusPoll => { + CallOptions::default().call_timeout(MESSAGE_BUS_CALL_TIMEOUT) + } + } +} diff --git a/crates/fire-core/src/core/network/recovery.rs b/crates/fire-core/src/core/network/recovery.rs new file mode 100644 index 00000000..0ffb0bc5 --- /dev/null +++ b/crates/fire-core/src/core/network/recovery.rs @@ -0,0 +1,257 @@ +use std::sync::Arc; + +use fire_models::{ + AuthRuntimeSignal, AuthRuntimeSignalKind, AuthRuntimeSignalSource, AuthRuntimeSignalStrength, + CloudflareChallengeRequest, +}; +use http::{header::COOKIE, Response, StatusCode}; +use openwire::{CallOptions, ResponseBody}; + +use super::super::FireCore; +use super::challenge::{ + is_cloudflare_challenge_response, should_present_foreground_challenge, + CloudflareChallengeFinishGuard, +}; +use super::heal::FireCookieSelfHealingTarget; +use super::traced::{ + clone_request_for_retry, request_origin_url, request_url_string, response_from_parts, + FireSkipCloudflareBlock, FireSkipCookieSelfHeal, TracedRequest, +}; +use super::FireCallProfile; +use crate::error::{CloudflareChallengeFailureReason, FireCoreError}; + +impl FireCore { + pub(crate) async fn execute_request( + &self, + traced: TracedRequest, + ) -> Result<(u64, Response), FireCoreError> { + self.execute_request_with_options(traced, CallOptions::default()) + .await + } + + pub(crate) async fn execute_request_with_options( + &self, + traced: TracedRequest, + options: CallOptions, + ) -> Result<(u64, Response), FireCoreError> { + let has_challenge_handler = self.cloudflare_challenge_handler.get().is_some(); + let has_cookie_healing_handler = self.cookie_self_healing_handler.get().is_some(); + let skip_cookie_self_heal = traced + .request + .extensions() + .get::() + .is_some(); + let skip_cloudflare_block = traced + .request + .extensions() + .get::() + .is_some(); + let sent_cf_clearance = traced + .request + .headers() + .get(COOKIE) + .and_then(|value| value.to_str().ok()) + .and_then(fire_models::extract_cf_clearance_from_cookie_header); + let retry_request = + if has_challenge_handler || (has_cookie_healing_handler && !skip_cookie_self_heal) { + clone_request_for_retry(&traced.request) + } else { + None + }; + let request_url = request_url_string(&traced.request); + let origin_url = request_origin_url(&self.base_url, &traced.request); + let is_foreground = should_present_foreground_challenge( + traced.operation, + FireCallProfile::DefaultApi, + &traced.request, + ); + let operation = traced.operation; + let (trace_id, response) = self + .network + .execute_traced_with_options(traced, FireCallProfile::DefaultApi, options) + .await?; + + let response = if has_challenge_handler + && matches!( + response.status(), + StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS + ) { + let status = response.status(); + let (parts, body) = response.into_parts(); + let body = body + .bytes() + .await + .map_err(|source| FireCoreError::Network { source })?; + let body_text = String::from_utf8_lossy(&body); + if !is_cloudflare_challenge_response(status.as_u16(), &parts.headers, &body_text) { + self.complete_pending_clearance_retry_if_needed(); + response_from_parts(parts, body) + } else { + self.diagnostics + .record_http_status_error(trace_id, status.as_u16(), &body_text); + self.record_auth_runtime_signal(AuthRuntimeSignal { + kind: AuthRuntimeSignalKind::CloudflareChallenge, + strength: AuthRuntimeSignalStrength::Diagnostic, + source: AuthRuntimeSignalSource::HttpResponse, + operation: Some(operation.to_string()), + status: Some(status.as_u16()), + }); + // Local clearance (if any) was just rejected by the edge. + let challenged = sent_cf_clearance.clone().or_else(|| { + self.snapshot() + .cookies + .cf_clearance + .as_deref() + .map(fire_models::normalize_cf_clearance_value) + .filter(|value| !value.is_empty()) + }); + self.note_cf_clearance_challenged(challenged.as_deref()); + self.note_cloudflare_clearance_rejected(); + if skip_cloudflare_block { + self.mark_ineffective_cloudflare_cooldown(); + return Ok((trace_id, response_from_parts(parts, body))); + } + self.capture_turnstile_sitekey_from_challenge_body(&body_text); + let handler = match self.cloudflare_challenge_handler.get() { + Some(handler) => handler, + None => { + return Ok((trace_id, response_from_parts(parts, body))); + } + }; + + let begin = { + let mut runtime = self + .cloudflare_challenge_runtime + .lock() + .expect("cloudflare challenge runtime mutex poisoned"); + runtime.begin_or_join(is_foreground) + }; + + match begin { + super::super::cf_challenge::CloudflareChallengeBegin::Cooldown => { + return Err(FireCoreError::CloudflareChallenge { + operation, + reason: CloudflareChallengeFailureReason::Cooldown, + }); + } + super::super::cf_challenge::CloudflareChallengeBegin::BackgroundSuppressed => { + return Err(FireCoreError::CloudflareChallenge { + operation, + reason: CloudflareChallengeFailureReason::BackgroundSuppressed, + }); + } + super::super::cf_challenge::CloudflareChallengeBegin::Join(join_rx) => { + return self + .await_shared_cloudflare_challenge_and_retry( + operation, + join_rx, + retry_request, + options, + ) + .await; + } + super::super::cf_challenge::CloudflareChallengeBegin::Start => {} + } + + let mut finish_guard = CloudflareChallengeFinishGuard { + runtime: Arc::clone(&self.cloudflare_challenge_runtime), + finished: false, + }; + + let challenge_result = handler(CloudflareChallengeRequest { + operation: operation.to_string(), + request_url: request_url.clone(), + origin_url: origin_url.clone(), + is_foreground, + session_epoch: self.current_session_epoch(), + }) + .await; + + let failure_reason = if challenge_result.user_cancelled { + Some(CloudflareChallengeFailureReason::Cancelled) + } else if !challenge_result.completed { + Some(CloudflareChallengeFailureReason::Failed) + } else { + None + }; + + let accepted = if failure_reason.is_some() { + false + } else { + let fresh_clearance = challenge_result + .fresh_cf_clearance + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string); + { + let mut runtime = self + .cloudflare_challenge_runtime + .lock() + .expect("cloudflare challenge runtime mutex poisoned"); + runtime.mark_pending_retry(); + } + let _ = self.complete_cloudflare_challenge( + challenge_result.cookies, + fresh_clearance, + challenge_result.browser_user_agent, + ); + true + }; + + // Joiners may retry now. Recovery is published only after the + // original request retry proves the page-clear was usable. + if accepted { + finish_guard.finish_page_clear(); + // Don't wait for the API retry to hydrate identity. Profile + // and MessageBus need current_username even when the retry + // is still proving recovery or later hits cooldown. + let snapshot = self.snapshot(); + if snapshot.cookies.has_login_session() + && (!snapshot.readiness().has_current_user + || !snapshot.bootstrap.has_preloaded_data) + { + self.schedule_post_challenge_session_rebuild(); + } + } else { + finish_guard.finish(false); + } + + if !accepted { + return Err(FireCoreError::CloudflareChallenge { + operation, + reason: failure_reason.unwrap_or(CloudflareChallengeFailureReason::Failed), + }); + } + + // complete_cloudflare_challenge already schedules post-challenge + // bootstrap rebuild when a login session is present. + + return self + .retry_after_cloudflare_challenge(operation, retry_request, options) + .await; + } + } else { + self.complete_pending_clearance_retry_if_needed(); + response + }; + + if has_cookie_healing_handler && !skip_cookie_self_heal { + return self + .maybe_self_heal_response( + operation, + FireCookieSelfHealingTarget { + request_url, + origin_url, + }, + trace_id, + response, + retry_request, + options, + ) + .await; + } + + Ok((trace_id, response)) + } +} diff --git a/crates/fire-core/src/core/network/tests.rs b/crates/fire-core/src/core/network/tests.rs index 9b930b59..b344c83c 100644 --- a/crates/fire-core/src/core/network/tests.rs +++ b/crates/fire-core/src/core/network/tests.rs @@ -8,8 +8,8 @@ use super::super::{FireCore, MESSAGE_BUS_CALL_TIMEOUT}; use super::challenge::extract_turnstile_sitekey; use super::client::FireCommonProfileHeaderContext; use super::constants::MISSING_CSRF_TOKEN_PLACEHOLDER; -use super::execute::call_options_for_profile; use super::headers::apply_common_profile_headers; +use super::profile::call_options_for_profile; use super::traced::clone_request_for_retry; use super::*; use crate::diagnostics::FireDiagnosticsStore; diff --git a/crates/fire-core/src/core/topic_detail/mutations.rs b/crates/fire-core/src/core/topic_detail/mutations.rs deleted file mode 100644 index 6d91562d..00000000 --- a/crates/fire-core/src/core/topic_detail/mutations.rs +++ /dev/null @@ -1,444 +0,0 @@ -use fire_models::{TopicReplyRequest, TopicUpdateRequest}; -use tokio::sync::mpsc; - -use super::super::FireCore; -use super::*; -use crate::error::FireCoreError; - -impl ActorState { - pub(super) async fn submit_reply( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - raw: String, - reply_to_post_number: Option, - scroll_to_created: bool, - ) -> Result<(), FireCoreError> { - if raw.trim().is_empty() { - return Err(FireCoreError::InvalidArgument { - operation: "submit reply", - details: "reply body is empty".to_string(), - }); - } - self.submitting = true; - self.publish(core, false); - let created = core - .create_reply(TopicReplyRequest { - topic_id: self.topic_id, - raw, - reply_to_post_number, - }) - .await; - self.submitting = false; - let post = match created { - Ok(post) => post, - Err(error) => { - self.publish(core, false); - return Err(error); - } - }; - let post_number = post.post_number; - let previous_len = core - .with_topic_source_session_mut(self.topic_id, None, |session| session.raw_stream_len()) - .unwrap_or(0); - core.with_topic_source_session_mut(self.topic_id, None, |session| { - let is_new = session.append_stream_post(post); - if is_new { - let stream_len = u32::try_from(session.raw_stream_len()).unwrap_or(u32::MAX); - let header = session.header_mut(); - header.posts_count = header.posts_count.saturating_add(1).max(stream_len); - header.reply_count = header - .reply_count - .saturating_add(1) - .max(header.posts_count.saturating_sub(1)); - header.highest_post_number = header.highest_post_number.max(post_number); - header.last_read_post_number = - Some(header.last_read_post_number.unwrap_or(0).max(post_number)); - } - }); - if self.window.requested.end >= previous_len { - self.window.requested.end = self.window.requested.end.saturating_add(1); - } - if scroll_to_created { - self.scroll_target = Some(post_number); - self.scroll_exhausted = false; - } - self.capture_header(core); - self.publish(core, true); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn create_boost( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - raw: String, - ) -> Result<(), FireCoreError> { - let boost = core.create_boost(post_id, raw).await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - if let Some(post) = session.post_mut(post_id) { - if !post.boosts.iter().any(|existing| existing.id == boost.id) { - post.boosts.push(boost); - } - post.can_boost = false; - } - }); - self.publish(core, true); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn delete_boost( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - boost_id: u64, - ) -> Result<(), FireCoreError> { - core.delete_boost(boost_id).await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - if let Some(post) = session.post_mut(post_id) { - post.boosts.retain(|boost| boost.id != boost_id); - } - }); - self.publish(core, true); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn update_post( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - raw: String, - edit_reason: Option, - ) -> Result<(), FireCoreError> { - let updated = core - .update_post(fire_models::PostUpdateRequest { - post_id, - raw, - edit_reason, - }) - .await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - session.merge_posts(std::iter::once(updated)); - }); - self.publish(core, false); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn delete_post( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - ) -> Result<(), FireCoreError> { - core.delete_post(post_id).await?; - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn recover_post( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - ) -> Result<(), FireCoreError> { - core.recover_post(post_id).await?; - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn flag_post( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - flag_type_id: u32, - message: Option, - ) -> Result<(), FireCoreError> { - core.flag_post(fire_models::PostFlagRequest { - post_id, - flag_type_id, - message, - }) - .await?; - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn vote_poll( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - poll_name: String, - options: Vec, - ) -> Result<(), FireCoreError> { - let poll = core.vote_poll(post_id, &poll_name, options).await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - if let Some(post) = session.post_mut(post_id) { - if let Some(slot) = post.polls.iter_mut().find(|item| item.name == poll.name) { - *slot = poll; - } - } - }); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn unvote_poll( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - poll_name: String, - ) -> Result<(), FireCoreError> { - let poll = core.unvote_poll(post_id, &poll_name).await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - if let Some(post) = session.post_mut(post_id) { - if let Some(slot) = post.polls.iter_mut().find(|item| item.name == poll.name) { - *slot = poll; - } - } - }); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn vote_topic( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - voted: bool, - ) -> Result<(), FireCoreError> { - let response = if voted { - core.vote_topic(self.topic_id).await? - } else { - core.unvote_topic(self.topic_id).await? - }; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - let header = session.header_mut(); - header.vote_count = response.vote_count; - header.can_vote = response.can_vote; - header.user_voted = voted; - }); - self.capture_header(core); - self.publish(core, false); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn accept_solution( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - post_id: u64, - accepted: bool, - ) -> Result<(), FireCoreError> { - if accepted { - core.accept_solution(post_id).await?; - } else { - core.unaccept_solution(post_id).await?; - } - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - #[allow(clippy::too_many_arguments)] - pub(super) async fn create_bookmark( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - bookmarkable_id: u64, - bookmarkable_type: String, - name: Option, - reminder_at: Option, - auto_delete_preference: Option, - ) -> Result<(), FireCoreError> { - let bookmark_id = core - .create_bookmark( - bookmarkable_id, - &bookmarkable_type, - name.as_deref(), - reminder_at.as_deref(), - auto_delete_preference, - ) - .await?; - let is_topic = bookmarkable_type.eq_ignore_ascii_case("Topic"); - core.with_topic_source_session_mut(self.topic_id, None, |session| { - if is_topic { - let header = session.header_mut(); - header.bookmarked = true; - header.bookmark_id = Some(bookmark_id); - header.bookmark_name = name.clone(); - header.bookmark_reminder_at = reminder_at.clone(); - } else if let Some(post) = session.post_mut(bookmarkable_id) { - post.bookmarked = true; - post.bookmark_id = Some(bookmark_id); - post.bookmark_name = name.clone(); - post.bookmark_reminder_at = reminder_at.clone(); - } - }); - self.capture_header(core); - self.publish(core, false); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn update_bookmark( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - bookmark_id: u64, - name: Option, - reminder_at: Option, - auto_delete_preference: Option, - ) -> Result<(), FireCoreError> { - core.update_bookmark( - bookmark_id, - name.clone(), - reminder_at.clone(), - auto_delete_preference, - ) - .await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - if session.header().bookmark_id == Some(bookmark_id) { - let header = session.header_mut(); - header.bookmark_name = name.clone(); - header.bookmark_reminder_at = reminder_at.clone(); - } - let post_ids = session - .raw_stream_ids() - .iter() - .copied() - .filter(|post_id| { - session - .post(*post_id) - .is_some_and(|post| post.bookmark_id == Some(bookmark_id)) - }) - .collect::>(); - for post_id in post_ids { - if let Some(post) = session.post_mut(post_id) { - post.bookmark_name = name.clone(); - post.bookmark_reminder_at = reminder_at.clone(); - } - } - }); - self.capture_header(core); - self.publish(core, false); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn delete_bookmark( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - bookmark_id: u64, - ) -> Result<(), FireCoreError> { - core.delete_bookmark(bookmark_id).await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - if session.header().bookmark_id == Some(bookmark_id) { - let header = session.header_mut(); - header.bookmarked = false; - header.bookmark_id = None; - header.bookmark_name = None; - header.bookmark_reminder_at = None; - } - let post_ids = session - .raw_stream_ids() - .iter() - .copied() - .filter(|post_id| { - session - .post(*post_id) - .is_some_and(|post| post.bookmark_id == Some(bookmark_id)) - }) - .collect::>(); - for post_id in post_ids { - if let Some(post) = session.post_mut(post_id) { - post.bookmarked = false; - post.bookmark_id = None; - post.bookmark_name = None; - post.bookmark_reminder_at = None; - } - } - }); - self.capture_header(core); - self.publish(core, false); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn set_notification_level( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - level: i32, - ) -> Result<(), FireCoreError> { - core.set_topic_notification_level(self.topic_id, level) - .await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - session.header_mut().details.notification_level = Some(level); - }); - self.capture_header(core); - self.publish(core, false); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } - - pub(super) async fn update_topic( - &mut self, - core: &FireCore, - tx: &mpsc::UnboundedSender, - title: String, - category_id: u64, - tags: Vec, - ) -> Result<(), FireCoreError> { - core.update_topic(TopicUpdateRequest { - topic_id: self.topic_id, - title: title.clone(), - category_id, - tags: tags.clone(), - }) - .await?; - core.with_topic_source_session_mut(self.topic_id, None, |session| { - let header = session.header_mut(); - header.title = title; - header.category_id = Some(category_id); - header.tags = tags - .into_iter() - .map(|name| fire_models::TopicTag { - id: None, - name, - slug: None, - }) - .collect(); - }); - self.capture_header(core); - self.publish(core, false); - self.load_http(core, tx, None, false, false, false, false) - .await; - Ok(()) - } -} diff --git a/crates/fire-core/src/core/topic_detail/mutations/bookmarks.rs b/crates/fire-core/src/core/topic_detail/mutations/bookmarks.rs new file mode 100644 index 00000000..539f65ce --- /dev/null +++ b/crates/fire-core/src/core/topic_detail/mutations/bookmarks.rs @@ -0,0 +1,131 @@ +impl ActorState { + #[allow(clippy::too_many_arguments)] + pub(super) async fn create_bookmark( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + bookmarkable_id: u64, + bookmarkable_type: String, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireCoreError> { + let bookmark_id = core + .create_bookmark( + bookmarkable_id, + &bookmarkable_type, + name.as_deref(), + reminder_at.as_deref(), + auto_delete_preference, + ) + .await?; + let is_topic = bookmarkable_type.eq_ignore_ascii_case("Topic"); + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if is_topic { + let header = session.header_mut(); + header.bookmarked = true; + header.bookmark_id = Some(bookmark_id); + header.bookmark_name = name.clone(); + header.bookmark_reminder_at = reminder_at.clone(); + } else if let Some(post) = session.post_mut(bookmarkable_id) { + post.bookmarked = true; + post.bookmark_id = Some(bookmark_id); + post.bookmark_name = name.clone(); + post.bookmark_reminder_at = reminder_at.clone(); + } + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn update_bookmark( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + bookmark_id: u64, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireCoreError> { + core.update_bookmark( + bookmark_id, + name.clone(), + reminder_at.clone(), + auto_delete_preference, + ) + .await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if session.header().bookmark_id == Some(bookmark_id) { + let header = session.header_mut(); + header.bookmark_name = name.clone(); + header.bookmark_reminder_at = reminder_at.clone(); + } + let post_ids = session + .raw_stream_ids() + .iter() + .copied() + .filter(|post_id| { + session + .post(*post_id) + .is_some_and(|post| post.bookmark_id == Some(bookmark_id)) + }) + .collect::>(); + for post_id in post_ids { + if let Some(post) = session.post_mut(post_id) { + post.bookmark_name = name.clone(); + post.bookmark_reminder_at = reminder_at.clone(); + } + } + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn delete_bookmark( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + bookmark_id: u64, + ) -> Result<(), FireCoreError> { + core.delete_bookmark(bookmark_id).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if session.header().bookmark_id == Some(bookmark_id) { + let header = session.header_mut(); + header.bookmarked = false; + header.bookmark_id = None; + header.bookmark_name = None; + header.bookmark_reminder_at = None; + } + let post_ids = session + .raw_stream_ids() + .iter() + .copied() + .filter(|post_id| { + session + .post(*post_id) + .is_some_and(|post| post.bookmark_id == Some(bookmark_id)) + }) + .collect::>(); + for post_id in post_ids { + if let Some(post) = session.post_mut(post_id) { + post.bookmarked = false; + post.bookmark_id = None; + post.bookmark_name = None; + post.bookmark_reminder_at = None; + } + } + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + +} diff --git a/crates/fire-core/src/core/topic_detail/mutations/boosts.rs b/crates/fire-core/src/core/topic_detail/mutations/boosts.rs new file mode 100644 index 00000000..ed5b6902 --- /dev/null +++ b/crates/fire-core/src/core/topic_detail/mutations/boosts.rs @@ -0,0 +1,43 @@ +impl ActorState { + pub(super) async fn create_boost( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + raw: String, + ) -> Result<(), FireCoreError> { + let boost = core.create_boost(post_id, raw).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + if !post.boosts.iter().any(|existing| existing.id == boost.id) { + post.boosts.push(boost); + } + post.can_boost = false; + } + }); + self.publish(core, true); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn delete_boost( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + boost_id: u64, + ) -> Result<(), FireCoreError> { + core.delete_boost(boost_id).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + post.boosts.retain(|boost| boost.id != boost_id); + } + }); + self.publish(core, true); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + +} diff --git a/crates/fire-core/src/core/topic_detail/mutations/mod.rs b/crates/fire-core/src/core/topic_detail/mutations/mod.rs new file mode 100644 index 00000000..059ca9cc --- /dev/null +++ b/crates/fire-core/src/core/topic_detail/mutations/mod.rs @@ -0,0 +1,14 @@ +use fire_models::{TopicReplyRequest, TopicUpdateRequest}; +use tokio::sync::mpsc; + +use super::super::FireCore; +use super::*; +use crate::error::FireCoreError; + +include!("posts.rs"); +include!("boosts.rs"); +include!("polls.rs"); +include!("votes.rs"); +include!("solutions.rs"); +include!("bookmarks.rs"); +include!("topic.rs"); diff --git a/crates/fire-core/src/core/topic_detail/mutations/polls.rs b/crates/fire-core/src/core/topic_detail/mutations/polls.rs new file mode 100644 index 00000000..1de91809 --- /dev/null +++ b/crates/fire-core/src/core/topic_detail/mutations/polls.rs @@ -0,0 +1,43 @@ +impl ActorState { + pub(super) async fn vote_poll( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + poll_name: String, + options: Vec, + ) -> Result<(), FireCoreError> { + let poll = core.vote_poll(post_id, &poll_name, options).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + if let Some(slot) = post.polls.iter_mut().find(|item| item.name == poll.name) { + *slot = poll; + } + } + }); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn unvote_poll( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + poll_name: String, + ) -> Result<(), FireCoreError> { + let poll = core.unvote_poll(post_id, &poll_name).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + if let Some(slot) = post.polls.iter_mut().find(|item| item.name == poll.name) { + *slot = poll; + } + } + }); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + +} diff --git a/crates/fire-core/src/core/topic_detail/mutations/posts.rs b/crates/fire-core/src/core/topic_detail/mutations/posts.rs new file mode 100644 index 00000000..12fcc98b --- /dev/null +++ b/crates/fire-core/src/core/topic_detail/mutations/posts.rs @@ -0,0 +1,133 @@ +impl ActorState { + pub(super) async fn submit_reply( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + raw: String, + reply_to_post_number: Option, + scroll_to_created: bool, + ) -> Result<(), FireCoreError> { + if raw.trim().is_empty() { + return Err(FireCoreError::InvalidArgument { + operation: "submit reply", + details: "reply body is empty".to_string(), + }); + } + self.submitting = true; + self.publish(core, false); + let created = core + .create_reply(TopicReplyRequest { + topic_id: self.topic_id, + raw, + reply_to_post_number, + }) + .await; + self.submitting = false; + let post = match created { + Ok(post) => post, + Err(error) => { + self.publish(core, false); + return Err(error); + } + }; + let post_number = post.post_number; + let previous_len = core + .with_topic_source_session_mut(self.topic_id, None, |session| session.raw_stream_len()) + .unwrap_or(0); + core.with_topic_source_session_mut(self.topic_id, None, |session| { + let is_new = session.append_stream_post(post); + if is_new { + let stream_len = u32::try_from(session.raw_stream_len()).unwrap_or(u32::MAX); + let header = session.header_mut(); + header.posts_count = header.posts_count.saturating_add(1).max(stream_len); + header.reply_count = header + .reply_count + .saturating_add(1) + .max(header.posts_count.saturating_sub(1)); + header.highest_post_number = header.highest_post_number.max(post_number); + header.last_read_post_number = + Some(header.last_read_post_number.unwrap_or(0).max(post_number)); + } + }); + if self.window.requested.end >= previous_len { + self.window.requested.end = self.window.requested.end.saturating_add(1); + } + if scroll_to_created { + self.scroll_target = Some(post_number); + self.scroll_exhausted = false; + } + self.capture_header(core); + self.publish(core, true); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn update_post( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + raw: String, + edit_reason: Option, + ) -> Result<(), FireCoreError> { + let updated = core + .update_post(fire_models::PostUpdateRequest { + post_id, + raw, + edit_reason, + }) + .await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.merge_posts(std::iter::once(updated)); + }); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn delete_post( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + ) -> Result<(), FireCoreError> { + core.delete_post(post_id).await?; + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn recover_post( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + ) -> Result<(), FireCoreError> { + core.recover_post(post_id).await?; + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn flag_post( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + flag_type_id: u32, + message: Option, + ) -> Result<(), FireCoreError> { + core.flag_post(fire_models::PostFlagRequest { + post_id, + flag_type_id, + message, + }) + .await?; + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + +} diff --git a/crates/fire-core/src/core/topic_detail/mutations/solutions.rs b/crates/fire-core/src/core/topic_detail/mutations/solutions.rs new file mode 100644 index 00000000..7552b42b --- /dev/null +++ b/crates/fire-core/src/core/topic_detail/mutations/solutions.rs @@ -0,0 +1,19 @@ +impl ActorState { + pub(super) async fn accept_solution( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + accepted: bool, + ) -> Result<(), FireCoreError> { + if accepted { + core.accept_solution(post_id).await?; + } else { + core.unaccept_solution(post_id).await?; + } + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + +} diff --git a/crates/fire-core/src/core/topic_detail/mutations/topic.rs b/crates/fire-core/src/core/topic_detail/mutations/topic.rs new file mode 100644 index 00000000..238c7ce3 --- /dev/null +++ b/crates/fire-core/src/core/topic_detail/mutations/topic.rs @@ -0,0 +1,54 @@ +impl ActorState { + pub(super) async fn set_notification_level( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + level: i32, + ) -> Result<(), FireCoreError> { + core.set_topic_notification_level(self.topic_id, level) + .await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.header_mut().details.notification_level = Some(level); + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn update_topic( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + title: String, + category_id: u64, + tags: Vec, + ) -> Result<(), FireCoreError> { + core.update_topic(TopicUpdateRequest { + topic_id: self.topic_id, + title: title.clone(), + category_id, + tags: tags.clone(), + }) + .await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + let header = session.header_mut(); + header.title = title; + header.category_id = Some(category_id); + header.tags = tags + .into_iter() + .map(|name| fire_models::TopicTag { + id: None, + name, + slug: None, + }) + .collect(); + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } +} diff --git a/crates/fire-core/src/core/topic_detail/mutations/votes.rs b/crates/fire-core/src/core/topic_detail/mutations/votes.rs new file mode 100644 index 00000000..59c179a8 --- /dev/null +++ b/crates/fire-core/src/core/topic_detail/mutations/votes.rs @@ -0,0 +1,26 @@ +impl ActorState { + pub(super) async fn vote_topic( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + voted: bool, + ) -> Result<(), FireCoreError> { + let response = if voted { + core.vote_topic(self.topic_id).await? + } else { + core.unvote_topic(self.topic_id).await? + }; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + let header = session.header_mut(); + header.vote_count = response.vote_count; + header.can_vote = response.can_vote; + header.user_voted = voted; + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + +} diff --git a/crates/fire-core/src/core/users.rs b/crates/fire-core/src/core/users.rs deleted file mode 100644 index 7be6651d..00000000 --- a/crates/fire-core/src/core/users.rs +++ /dev/null @@ -1,416 +0,0 @@ -use fire_models::{ - Badge, FollowUser, InviteCreateRequest, InviteLink, TopicListResponse, UserAction, UserProfile, - UserReactionsResponse, UserSummaryResponse, -}; -use http::Method; -use openwire::RequestBody; -use serde_json::{json, Value}; -use tracing::info; - -use super::{network::expect_success, FireCore}; -use crate::{ - error::FireCoreError, - topic_payloads::RawTopicListResponse, - user_payloads::{ - parse_badge_value, parse_follow_users_value, parse_invite_link_value, - parse_invite_links_value, parse_user_actions_value, parse_user_profile_value, - parse_user_reactions_value, parse_user_summary_value, - }, -}; - -impl FireCore { - pub async fn fetch_read_history( - &self, - page: Option, - ) -> Result { - info!(?page, "fetching read history"); - let mut params = Vec::new(); - if let Some(page) = page.filter(|page| *page > 0) { - params.push(("page", page.to_string())); - } - let traced = - self.build_json_get_request("fetch read history", "/read.json", params, &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch read history", trace_id, response).await?; - let raw: RawTopicListResponse = self - .read_response_json("fetch read history", trace_id, response) - .await?; - let result: TopicListResponse = raw.into(); - info!( - topic_count = result.topics.len(), - has_more = result.more_topics_url.is_some(), - "read history fetched successfully" - ); - Ok(result) - } - - pub async fn fetch_bookmarks( - &self, - username: &str, - page: Option, - ) -> Result { - info!(username, ?page, "fetching user bookmarks"); - let path = format!("/u/{username}/bookmarks.json"); - let mut params = Vec::new(); - if let Some(page) = page { - if page > 0 { - params.push(("page", page.to_string())); - } - } - let traced = self.build_json_get_request("fetch bookmarks", &path, params, &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch bookmarks", trace_id, response).await?; - let raw: RawTopicListResponse = self - .read_response_json("fetch bookmarks", trace_id, response) - .await?; - let result: TopicListResponse = raw.into(); - info!( - username, - topic_count = result.topics.len(), - has_more = result.more_topics_url.is_some(), - "user bookmarks fetched successfully" - ); - Ok(result) - } - - pub async fn fetch_following(&self, username: &str) -> Result, FireCoreError> { - self.fetch_follow_users(username, "following").await - } - - pub async fn fetch_followers(&self, username: &str) -> Result, FireCoreError> { - self.fetch_follow_users(username, "followers").await - } - - pub async fn follow_user(&self, username: &str) -> Result<(), FireCoreError> { - info!(username, "following user"); - let path = format!("/follow/{username}"); - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("follow user", || { - self.build_api_request("follow user", Method::PUT, &path, true) - }) - .await?; - let response = expect_success(self, "follow user", trace_id, response).await?; - let _ = self.read_response_text(trace_id, response).await?; - Ok(()) - } - - pub async fn unfollow_user(&self, username: &str) -> Result<(), FireCoreError> { - info!(username, "unfollowing user"); - let path = format!("/follow/{username}"); - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("unfollow user", || { - self.build_api_request("unfollow user", Method::DELETE, &path, true) - }) - .await?; - let response = expect_success(self, "unfollow user", trace_id, response).await?; - let _ = self.read_response_text(trace_id, response).await?; - Ok(()) - } - - pub async fn set_user_notification_level( - &self, - username: &str, - notification_level: &str, - expiring_at: Option<&str>, - ) -> Result<(), FireCoreError> { - let notification_level = normalized_user_notification_level(notification_level)?; - info!( - username, - notification_level, - has_expiring_at = expiring_at.is_some(), - "setting user notification level" - ); - - let path = format!("/u/{username}/notification_level.json"); - let mut body = serde_json::Map::new(); - body.insert( - "notification_level".to_string(), - Value::String(notification_level.to_string()), - ); - if let Some(expiring_at) = expiring_at { - body.insert( - "expiring_at".to_string(), - Value::String(expiring_at.to_string()), - ); - } - let body = serde_json::to_vec(&Value::Object(body)).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "set user notification level", - source, - } - })?; - - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("set user notification level", || { - self.build_api_request_with_body( - "set user notification level", - Method::PUT, - &path, - Some("application/json; charset=utf-8"), - RequestBody::from(body.clone()), - true, - ) - }) - .await?; - let response = - expect_success(self, "set user notification level", trace_id, response).await?; - let _ = self.read_response_text(trace_id, response).await?; - Ok(()) - } - - pub async fn fetch_pending_invites( - &self, - username: &str, - ) -> Result, FireCoreError> { - info!(username, "fetching pending invites"); - let path = format!("/u/{username}/invited/pending"); - let traced = self.build_json_get_request("fetch pending invites", &path, vec![], &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch pending invites", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch pending invites", trace_id, response) - .await?; - let invites = parse_invite_links_value(value).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch pending invites", - source, - } - })?; - info!( - username, - invite_count = invites.len(), - "pending invites fetched successfully" - ); - Ok(invites) - } - - pub async fn create_invite_link( - &self, - input: InviteCreateRequest, - ) -> Result { - info!( - max_redemptions_allowed = input.max_redemptions_allowed, - has_expires_at = input.expires_at.is_some(), - has_description = input.description.is_some(), - has_email = input.email.is_some(), - "creating invite link" - ); - - let body = json!({ - "max_redemptions_allowed": input.max_redemptions_allowed, - "expires_at": input.expires_at, - "description": input.description, - "email": input.email, - }); - let body = - serde_json::to_vec(&body).map_err(|source| FireCoreError::ResponseDeserialize { - operation: "create invite link", - source, - })?; - - let (trace_id, response) = self - .execute_api_request_with_csrf_retry("create invite link", || { - self.build_api_request_with_body( - "create invite link", - Method::POST, - "/invites", - Some("application/json; charset=utf-8"), - openwire::RequestBody::from(body.clone()), - true, - ) - }) - .await?; - let response = expect_success(self, "create invite link", trace_id, response).await?; - let value: Value = self - .read_response_json("create invite link", trace_id, response) - .await?; - parse_invite_link_value(value).map_err(|source| FireCoreError::ResponseDeserialize { - operation: "create invite link", - source, - }) - } - - pub async fn fetch_user_profile(&self, username: &str) -> Result { - info!(username, "fetching user profile"); - let path = format!("/u/{username}.json"); - let traced = self.build_json_get_request("fetch user profile", &path, vec![], &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch user profile", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch user profile", trace_id, response) - .await?; - let profile = parse_user_profile_value(value).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch user profile", - source, - } - })?; - info!( - username, - user_id = profile.id, - "user profile fetched successfully" - ); - Ok(profile) - } - - pub async fn fetch_user_summary( - &self, - username: &str, - ) -> Result { - info!(username, "fetching user summary"); - let path = format!("/u/{username}/summary.json"); - let traced = self.build_json_get_request("fetch user summary", &path, vec![], &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch user summary", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch user summary", trace_id, response) - .await?; - let summary = parse_user_summary_value(value).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch user summary", - source, - } - })?; - info!( - username, - badge_count = summary.badges.len(), - top_topic_count = summary.top_topics.len(), - "user summary fetched successfully" - ); - Ok(summary) - } - - pub async fn fetch_badge_detail(&self, badge_id: u64) -> Result { - info!(badge_id, "fetching badge detail"); - let path = format!("/badges/{badge_id}.json"); - let traced = self.build_json_get_request("fetch badge detail", &path, vec![], &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch badge detail", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch badge detail", trace_id, response) - .await?; - let badge = - parse_badge_value(value).map_err(|source| FireCoreError::ResponseDeserialize { - operation: "fetch badge detail", - source, - })?; - info!(badge_id = badge.id, badge_name = %badge.name, "badge detail fetched successfully"); - Ok(badge) - } - - pub async fn fetch_user_actions( - &self, - username: &str, - offset: Option, - filter: Option<&str>, - ) -> Result, FireCoreError> { - info!(username, ?offset, ?filter, "fetching user actions"); - let mut params: Vec<(&str, String)> = vec![("username", username.to_string())]; - if let Some(offset) = offset { - params.push(("offset", offset.to_string())); - } - if let Some(filter) = filter { - params.push(("filter", filter.to_string())); - } - let traced = - self.build_json_get_request("fetch user actions", "/user_actions.json", params, &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch user actions", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch user actions", trace_id, response) - .await?; - let actions = parse_user_actions_value(value).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch user actions", - source, - } - })?; - info!( - username, - action_count = actions.len(), - "user actions fetched successfully" - ); - Ok(actions) - } - - pub async fn fetch_user_reactions( - &self, - username: &str, - before_reaction_user_id: Option, - ) -> Result { - info!( - username, - ?before_reaction_user_id, - "fetching user reactions" - ); - let mut params: Vec<(&str, String)> = vec![("username", username.to_string())]; - if let Some(before_reaction_user_id) = before_reaction_user_id { - params.push(( - "before_reaction_user_id", - before_reaction_user_id.to_string(), - )); - } - let traced = self.build_json_get_request( - "fetch user reactions", - "/discourse-reactions/posts/reactions.json", - params, - &[], - )?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch user reactions", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch user reactions", trace_id, response) - .await?; - let result = parse_user_reactions_value(value).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch user reactions", - source, - } - })?; - info!( - username, - reaction_count = result.reactions.len(), - "user reactions fetched successfully" - ); - Ok(result) - } - - async fn fetch_follow_users( - &self, - username: &str, - kind: &'static str, - ) -> Result, FireCoreError> { - info!(username, kind, "fetching follow users"); - let path = format!("/u/{username}/follow/{kind}"); - let traced = self.build_json_get_request("fetch follow users", &path, vec![], &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch follow users", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch follow users", trace_id, response) - .await?; - let users = parse_follow_users_value(value).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch follow users", - source, - } - })?; - info!( - username, - kind, - user_count = users.len(), - "follow users fetched successfully" - ); - Ok(users) - } -} - -fn normalized_user_notification_level(level: &str) -> Result<&'static str, FireCoreError> { - match level.trim().to_ascii_lowercase().as_str() { - "normal" => Ok("normal"), - "mute" => Ok("mute"), - "ignore" => Ok("ignore"), - other => Err(FireCoreError::InvalidUserNotificationLevel { - level: other.to_string(), - }), - } -} diff --git a/crates/fire-core/src/core/users/activity.rs b/crates/fire-core/src/core/users/activity.rs new file mode 100644 index 00000000..37ecbc15 --- /dev/null +++ b/crates/fire-core/src/core/users/activity.rs @@ -0,0 +1,106 @@ +impl FireCore { + pub async fn fetch_user_actions( + &self, + username: &str, + offset: Option, + filter: Option<&str>, + ) -> Result, FireCoreError> { + info!(username, ?offset, ?filter, "fetching user actions"); + let mut params: Vec<(&str, String)> = vec![("username", username.to_string())]; + if let Some(offset) = offset { + params.push(("offset", offset.to_string())); + } + if let Some(filter) = filter { + params.push(("filter", filter.to_string())); + } + let traced = + self.build_json_get_request("fetch user actions", "/user_actions.json", params, &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch user actions", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch user actions", trace_id, response) + .await?; + let actions = parse_user_actions_value(value).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch user actions", + source, + } + })?; + info!( + username, + action_count = actions.len(), + "user actions fetched successfully" + ); + Ok(actions) + } + + pub async fn fetch_user_reactions( + &self, + username: &str, + before_reaction_user_id: Option, + ) -> Result { + info!( + username, + ?before_reaction_user_id, + "fetching user reactions" + ); + let mut params: Vec<(&str, String)> = vec![("username", username.to_string())]; + if let Some(before_reaction_user_id) = before_reaction_user_id { + params.push(( + "before_reaction_user_id", + before_reaction_user_id.to_string(), + )); + } + let traced = self.build_json_get_request( + "fetch user reactions", + "/discourse-reactions/posts/reactions.json", + params, + &[], + )?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch user reactions", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch user reactions", trace_id, response) + .await?; + let result = parse_user_reactions_value(value).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch user reactions", + source, + } + })?; + info!( + username, + reaction_count = result.reactions.len(), + "user reactions fetched successfully" + ); + Ok(result) + } + + async fn fetch_follow_users( + &self, + username: &str, + kind: &'static str, + ) -> Result, FireCoreError> { + info!(username, kind, "fetching follow users"); + let path = format!("/u/{username}/follow/{kind}"); + let traced = self.build_json_get_request("fetch follow users", &path, vec![], &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch follow users", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch follow users", trace_id, response) + .await?; + let users = parse_follow_users_value(value).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch follow users", + source, + } + })?; + info!( + username, + kind, + user_count = users.len(), + "follow users fetched successfully" + ); + Ok(users) + } +} diff --git a/crates/fire-core/src/core/users/badges.rs b/crates/fire-core/src/core/users/badges.rs new file mode 100644 index 00000000..ae7f3ece --- /dev/null +++ b/crates/fire-core/src/core/users/badges.rs @@ -0,0 +1,20 @@ +impl FireCore { + pub async fn fetch_badge_detail(&self, badge_id: u64) -> Result { + info!(badge_id, "fetching badge detail"); + let path = format!("/badges/{badge_id}.json"); + let traced = self.build_json_get_request("fetch badge detail", &path, vec![], &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch badge detail", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch badge detail", trace_id, response) + .await?; + let badge = + parse_badge_value(value).map_err(|source| FireCoreError::ResponseDeserialize { + operation: "fetch badge detail", + source, + })?; + info!(badge_id = badge.id, badge_name = %badge.name, "badge detail fetched successfully"); + Ok(badge) + } + +} diff --git a/crates/fire-core/src/core/users/history.rs b/crates/fire-core/src/core/users/history.rs new file mode 100644 index 00000000..e0e38dbf --- /dev/null +++ b/crates/fire-core/src/core/users/history.rs @@ -0,0 +1,55 @@ +impl FireCore { + pub async fn fetch_read_history( + &self, + page: Option, + ) -> Result { + info!(?page, "fetching read history"); + let mut params = Vec::new(); + if let Some(page) = page.filter(|page| *page > 0) { + params.push(("page", page.to_string())); + } + let traced = + self.build_json_get_request("fetch read history", "/read.json", params, &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch read history", trace_id, response).await?; + let raw: RawTopicListResponse = self + .read_response_json("fetch read history", trace_id, response) + .await?; + let result: TopicListResponse = raw.into(); + info!( + topic_count = result.topics.len(), + has_more = result.more_topics_url.is_some(), + "read history fetched successfully" + ); + Ok(result) + } + + pub async fn fetch_bookmarks( + &self, + username: &str, + page: Option, + ) -> Result { + info!(username, ?page, "fetching user bookmarks"); + let path = format!("/u/{username}/bookmarks.json"); + let mut params = Vec::new(); + if let Some(page) = page { + if page > 0 { + params.push(("page", page.to_string())); + } + } + let traced = self.build_json_get_request("fetch bookmarks", &path, params, &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch bookmarks", trace_id, response).await?; + let raw: RawTopicListResponse = self + .read_response_json("fetch bookmarks", trace_id, response) + .await?; + let result: TopicListResponse = raw.into(); + info!( + username, + topic_count = result.topics.len(), + has_more = result.more_topics_url.is_some(), + "user bookmarks fetched successfully" + ); + Ok(result) + } +} diff --git a/crates/fire-core/src/core/users/invites.rs b/crates/fire-core/src/core/users/invites.rs new file mode 100644 index 00000000..8c6e7edd --- /dev/null +++ b/crates/fire-core/src/core/users/invites.rs @@ -0,0 +1,74 @@ +impl FireCore { + pub async fn fetch_pending_invites( + &self, + username: &str, + ) -> Result, FireCoreError> { + info!(username, "fetching pending invites"); + let path = format!("/u/{username}/invited/pending"); + let traced = self.build_json_get_request("fetch pending invites", &path, vec![], &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch pending invites", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch pending invites", trace_id, response) + .await?; + let invites = parse_invite_links_value(value).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch pending invites", + source, + } + })?; + info!( + username, + invite_count = invites.len(), + "pending invites fetched successfully" + ); + Ok(invites) + } + + pub async fn create_invite_link( + &self, + input: InviteCreateRequest, + ) -> Result { + info!( + max_redemptions_allowed = input.max_redemptions_allowed, + has_expires_at = input.expires_at.is_some(), + has_description = input.description.is_some(), + has_email = input.email.is_some(), + "creating invite link" + ); + + let body = json!({ + "max_redemptions_allowed": input.max_redemptions_allowed, + "expires_at": input.expires_at, + "description": input.description, + "email": input.email, + }); + let body = + serde_json::to_vec(&body).map_err(|source| FireCoreError::ResponseDeserialize { + operation: "create invite link", + source, + })?; + + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("create invite link", || { + self.build_api_request_with_body( + "create invite link", + Method::POST, + "/invites", + Some("application/json; charset=utf-8"), + openwire::RequestBody::from(body.clone()), + true, + ) + }) + .await?; + let response = expect_success(self, "create invite link", trace_id, response).await?; + let value: Value = self + .read_response_json("create invite link", trace_id, response) + .await?; + parse_invite_link_value(value).map_err(|source| FireCoreError::ResponseDeserialize { + operation: "create invite link", + source, + }) + } + +} diff --git a/crates/fire-core/src/core/users/mod.rs b/crates/fire-core/src/core/users/mod.rs new file mode 100644 index 00000000..ce7542ec --- /dev/null +++ b/crates/fire-core/src/core/users/mod.rs @@ -0,0 +1,36 @@ +use fire_models::{ + Badge, FollowUser, InviteCreateRequest, InviteLink, TopicListResponse, UserAction, UserProfile, + UserReactionsResponse, UserSummaryResponse, +}; +use http::Method; +use openwire::RequestBody; +use serde_json::{json, Value}; +use tracing::info; + +use super::{network::expect_success, FireCore}; +use crate::{ + error::FireCoreError, + topic_payloads::RawTopicListResponse, + user_payloads::{ + parse_badge_value, parse_follow_users_value, parse_invite_link_value, + parse_invite_links_value, parse_user_actions_value, parse_user_profile_value, + parse_user_reactions_value, parse_user_summary_value, + }, +}; + +include!("history.rs"); +include!("social.rs"); +include!("invites.rs"); +include!("profile.rs"); +include!("badges.rs"); +include!("activity.rs"); +fn normalized_user_notification_level(level: &str) -> Result<&'static str, FireCoreError> { + match level.trim().to_ascii_lowercase().as_str() { + "normal" => Ok("normal"), + "mute" => Ok("mute"), + "ignore" => Ok("ignore"), + other => Err(FireCoreError::InvalidUserNotificationLevel { + level: other.to_string(), + }), + } +} diff --git a/crates/fire-core/src/core/users/profile.rs b/crates/fire-core/src/core/users/profile.rs new file mode 100644 index 00000000..687952b8 --- /dev/null +++ b/crates/fire-core/src/core/users/profile.rs @@ -0,0 +1,52 @@ +impl FireCore { + pub async fn fetch_user_profile(&self, username: &str) -> Result { + info!(username, "fetching user profile"); + let path = format!("/u/{username}.json"); + let traced = self.build_json_get_request("fetch user profile", &path, vec![], &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch user profile", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch user profile", trace_id, response) + .await?; + let profile = parse_user_profile_value(value).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch user profile", + source, + } + })?; + info!( + username, + user_id = profile.id, + "user profile fetched successfully" + ); + Ok(profile) + } + + pub async fn fetch_user_summary( + &self, + username: &str, + ) -> Result { + info!(username, "fetching user summary"); + let path = format!("/u/{username}/summary.json"); + let traced = self.build_json_get_request("fetch user summary", &path, vec![], &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch user summary", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch user summary", trace_id, response) + .await?; + let summary = parse_user_summary_value(value).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch user summary", + source, + } + })?; + info!( + username, + badge_count = summary.badges.len(), + top_topic_count = summary.top_topics.len(), + "user summary fetched successfully" + ); + Ok(summary) + } + +} diff --git a/crates/fire-core/src/core/users/social.rs b/crates/fire-core/src/core/users/social.rs new file mode 100644 index 00000000..c9ad3f0b --- /dev/null +++ b/crates/fire-core/src/core/users/social.rs @@ -0,0 +1,87 @@ +impl FireCore { + pub async fn fetch_following(&self, username: &str) -> Result, FireCoreError> { + self.fetch_follow_users(username, "following").await + } + + pub async fn fetch_followers(&self, username: &str) -> Result, FireCoreError> { + self.fetch_follow_users(username, "followers").await + } + + pub async fn follow_user(&self, username: &str) -> Result<(), FireCoreError> { + info!(username, "following user"); + let path = format!("/follow/{username}"); + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("follow user", || { + self.build_api_request("follow user", Method::PUT, &path, true) + }) + .await?; + let response = expect_success(self, "follow user", trace_id, response).await?; + let _ = self.read_response_text(trace_id, response).await?; + Ok(()) + } + + pub async fn unfollow_user(&self, username: &str) -> Result<(), FireCoreError> { + info!(username, "unfollowing user"); + let path = format!("/follow/{username}"); + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("unfollow user", || { + self.build_api_request("unfollow user", Method::DELETE, &path, true) + }) + .await?; + let response = expect_success(self, "unfollow user", trace_id, response).await?; + let _ = self.read_response_text(trace_id, response).await?; + Ok(()) + } + + pub async fn set_user_notification_level( + &self, + username: &str, + notification_level: &str, + expiring_at: Option<&str>, + ) -> Result<(), FireCoreError> { + let notification_level = normalized_user_notification_level(notification_level)?; + info!( + username, + notification_level, + has_expiring_at = expiring_at.is_some(), + "setting user notification level" + ); + + let path = format!("/u/{username}/notification_level.json"); + let mut body = serde_json::Map::new(); + body.insert( + "notification_level".to_string(), + Value::String(notification_level.to_string()), + ); + if let Some(expiring_at) = expiring_at { + body.insert( + "expiring_at".to_string(), + Value::String(expiring_at.to_string()), + ); + } + let body = serde_json::to_vec(&Value::Object(body)).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "set user notification level", + source, + } + })?; + + let (trace_id, response) = self + .execute_api_request_with_csrf_retry("set user notification level", || { + self.build_api_request_with_body( + "set user notification level", + Method::PUT, + &path, + Some("application/json; charset=utf-8"), + RequestBody::from(body.clone()), + true, + ) + }) + .await?; + let response = + expect_success(self, "set user notification level", trace_id, response).await?; + let _ = self.read_response_text(trace_id, response).await?; + Ok(()) + } + +} diff --git a/crates/fire-core/src/parsing.rs b/crates/fire-core/src/parsing.rs deleted file mode 100644 index 0282824b..00000000 --- a/crates/fire-core/src/parsing.rs +++ /dev/null @@ -1,739 +0,0 @@ -use std::sync::OnceLock; - -use fire_models::{BootstrapArtifacts, CookieSnapshot, RequiredTagGroup, TopicCategory}; -use regex::Regex; -use serde_json::Value; -use tracing::warn; - -use crate::json_helpers::{integer_i32, integer_i64, positive_u32, positive_u64}; - -#[derive(Debug, Default)] -pub(crate) struct ParsedHomeState { - pub(crate) cookies_patch: CookieSnapshot, - pub(crate) bootstrap_patch: BootstrapArtifacts, -} - -pub(crate) fn parse_home_state(base_url: &str, html: &str) -> ParsedHomeState { - let mut parsed = ParsedHomeState { - bootstrap_patch: BootstrapArtifacts { - base_url: base_url.to_string(), - ..BootstrapArtifacts::default() - }, - ..ParsedHomeState::default() - }; - - parsed.cookies_patch.csrf_token = find_meta_content(html, "csrf-token"); - parsed.bootstrap_patch.shared_session_key = find_meta_content(html, "shared_session_key"); - parsed.bootstrap_patch.current_username = find_meta_content(html, "current-username"); - parsed.bootstrap_patch.discourse_base_uri = find_meta_content(html, "discourse-base-uri"); - parsed.bootstrap_patch.turnstile_sitekey = find_first_attr(html, "data-sitekey"); - - if let Some(preloaded_json) = find_first_attr(html, "data-preloaded") { - parsed.bootstrap_patch.preloaded_json = Some(preloaded_json.clone()); - parsed.bootstrap_patch.has_preloaded_data = true; - hydrate_preloaded_fields(&preloaded_json, &mut parsed.bootstrap_patch); - } - - parsed -} - -pub(crate) fn hydrate_preloaded_fields(preloaded_json: &str, bootstrap: &mut BootstrapArtifacts) { - let Some(preloaded) = parse_preloaded_payload(preloaded_json) else { - return; - }; - - if let Some(username) = preloaded - .get("currentUser") - .and_then(|value| value.get("username")) - .and_then(Value::as_str) - .filter(|value| !value.is_empty()) - { - bootstrap.current_username = Some(username.to_string()); - } - - if let Some(current_user_id) = preloaded - .get("currentUser") - .and_then(|value| value.get("id")) - .and_then(|value| positive_u64(Some(value))) - { - bootstrap.current_user_id = Some(current_user_id); - } - - if let Some(notification_channel_position) = preloaded - .get("currentUser") - .and_then(|value| value.get("notification_channel_position")) - .and_then(|value| integer_i64(Some(value))) - { - bootstrap.notification_channel_position = Some(notification_channel_position); - } - - if let Some(long_polling_base_url) = preloaded - .get("siteSettings") - .and_then(|value| value.get("long_polling_base_url")) - .and_then(Value::as_str) - .filter(|value| !value.is_empty()) - { - bootstrap.long_polling_base_url = Some(long_polling_base_url.to_string()); - } - - if let Some(meta) = preloaded.get("topicTrackingStateMeta") { - if !meta.is_null() { - bootstrap.topic_tracking_state_meta = serde_json::to_string(meta).ok(); - } - } - - hydrate_site_metadata_fields(&preloaded, bootstrap); - hydrate_site_settings_fields(&preloaded, bootstrap); -} - -pub(crate) fn parse_preloaded_payload(preloaded_json: &str) -> Option { - let Ok(preloaded) = serde_json::from_str::(preloaded_json) else { - warn!("failed to parse data-preloaded json"); - return None; - }; - Some(normalize_preloaded_payload(&preloaded)) -} - -fn normalize_preloaded_payload(preloaded: &Value) -> Value { - let Some(object) = preloaded.as_object() else { - return preloaded.clone(); - }; - - let mut normalized = object.clone(); - for key in [ - "currentUser", - "siteSettings", - "site", - "topicTrackingStateMeta", - "topicTrackingStates", - ] { - let Some(value) = normalized.get(key).cloned() else { - continue; - }; - let Some(decoded) = decode_embedded_json_payload(&value) else { - continue; - }; - normalized.insert(key.to_string(), decoded); - } - - Value::Object(normalized) -} - -fn decode_embedded_json_payload(value: &Value) -> Option { - let raw = value.as_str()?.trim(); - let first = raw.chars().next()?; - if first != '{' && first != '[' { - return None; - } - serde_json::from_str(raw).ok() -} - -pub(crate) fn parse_site_metadata_json(base_url: &str, json: &str) -> BootstrapArtifacts { - let mut bootstrap = BootstrapArtifacts { - base_url: base_url.to_string(), - ..BootstrapArtifacts::default() - }; - let Ok(value) = serde_json::from_str::(json) else { - warn!("failed to parse site.json payload"); - return bootstrap; - }; - hydrate_site_metadata_fields(&value, &mut bootstrap); - bootstrap -} - -pub(crate) fn hydrate_site_metadata_fields(source: &Value, bootstrap: &mut BootstrapArtifacts) { - bootstrap.has_site_metadata = has_site_metadata(source); - bootstrap.top_tags = top_tags_from_preloaded(source); - bootstrap.can_tag_topics = can_tag_topics_from_preloaded(source).unwrap_or(false); - bootstrap.categories = categories_from_preloaded(source); -} - -pub(crate) fn hydrate_site_settings_fields(source: &Value, bootstrap: &mut BootstrapArtifacts) { - bootstrap.has_site_settings = has_site_settings(source); - bootstrap.enabled_reaction_ids = enabled_reaction_ids_from_preloaded(source); - bootstrap.min_post_length = min_post_length_from_preloaded(source); - bootstrap.min_topic_title_length = min_topic_title_length_from_preloaded(source); - bootstrap.min_first_post_length = min_first_post_length_from_preloaded(source); - bootstrap.min_personal_message_title_length = - min_personal_message_title_length_from_preloaded(source); - bootstrap.min_personal_message_post_length = - min_personal_message_post_length_from_preloaded(source); - bootstrap.default_composer_category = default_composer_category_from_preloaded(source); -} - -fn find_meta_content(html: &str, target_name: &str) -> Option { - for tag in all_tags(html) { - if !tag.starts_with(" Option { - for tag in all_tags(html) { - if let Some(value) = extract_attr(tag, attribute_name) { - return Some(decode_html_entities(&value)); - } - } - - None -} - -fn all_tags(html: &str) -> impl Iterator { - static TAG_RE: OnceLock = OnceLock::new(); - // NOTE: This lightweight scanner is intentionally scoped to Discourse bootstrap tags. - // If parsing expands beyond meta/data-* extraction, switch to a real HTML parser. - let regex = TAG_RE.get_or_init(|| Regex::new(r"(?is)<[^>]+>").expect("tag regex")); - regex.find_iter(html).map(|matched| matched.as_str()) -} - -fn extract_attr(tag: &str, attribute_name: &str) -> Option { - static ATTR_RE: OnceLock = OnceLock::new(); - let regex = ATTR_RE.get_or_init(|| { - Regex::new( - r#"(?is)\b([a-zA-Z0-9:_-]+)\s*=\s*"([^"]*)"|\b([a-zA-Z0-9:_-]+)\s*=\s*'([^']*)'"#, - ) - .expect("attr regex") - }); - - for captures in regex.captures_iter(tag) { - let (name, value) = if let (Some(name), Some(value)) = (captures.get(1), captures.get(2)) { - (name.as_str(), value.as_str()) - } else if let (Some(name), Some(value)) = (captures.get(3), captures.get(4)) { - (name.as_str(), value.as_str()) - } else { - continue; - }; - - if !name.eq_ignore_ascii_case(attribute_name) { - continue; - } - return Some(value.to_string()); - } - - None -} - -pub(crate) fn decode_html_entities(raw: &str) -> String { - let mut decoded = String::with_capacity(raw.len()); - let mut cursor = raw; - - while let Some(start) = cursor.find('&') { - decoded.push_str(&cursor[..start]); - let entity_start = &cursor[start..]; - - let Some(end) = entity_start.find(';') else { - decoded.push_str(entity_start); - return decoded; - }; - - let entity = &entity_start[1..end]; - if let Some(ch) = decode_html_entity(entity) { - decoded.push(ch); - } else { - decoded.push_str(&entity_start[..=end]); - } - - cursor = &entity_start[end + 1..]; - } - - decoded.push_str(cursor); - decoded -} - -fn decode_html_entity(entity: &str) -> Option { - match entity { - "nbsp" | "#160" => Some(' '), - "quot" => Some('"'), - "amp" => Some('&'), - "lt" => Some('<'), - "gt" => Some('>'), - "apos" | "#39" => Some('\''), - _ => decode_numeric_html_entity(entity), - } -} - -fn decode_numeric_html_entity(entity: &str) -> Option { - let value = if let Some(hex) = entity - .strip_prefix("#x") - .or_else(|| entity.strip_prefix("#X")) - { - u32::from_str_radix(hex, 16).ok()? - } else { - let decimal = entity.strip_prefix('#')?; - decimal.parse::().ok()? - }; - - char::from_u32(value) -} - -fn categories_from_preloaded(preloaded: &Value) -> Vec { - category_candidates(preloaded) - .find_map(category_values_from_candidate) - .map(|values| { - values - .iter() - .filter_map(topic_category_from_value) - .collect() - }) - .unwrap_or_default() -} - -fn category_candidates(preloaded: &Value) -> impl Iterator { - [ - preloaded - .get("site") - .and_then(Value::as_object) - .and_then(|site| site.get("categories")), - preloaded - .get("site") - .and_then(Value::as_object) - .and_then(|site| site.get("category_list")), - preloaded.get("categories"), - preloaded.get("category_list"), - ] - .into_iter() - .flatten() -} - -fn has_site_metadata(preloaded: &Value) -> bool { - category_candidates(preloaded).next().is_some() - || site_candidates(preloaded, "top_tags").next().is_some() - || site_candidates(preloaded, "can_tag_topics") - .next() - .is_some() -} - -fn has_site_settings(preloaded: &Value) -> bool { - preloaded - .get("siteSettings") - .is_some_and(|value| value.is_object()) -} - -fn site_candidates<'a>(preloaded: &'a Value, key: &'static str) -> impl Iterator { - [ - preloaded - .get("site") - .and_then(Value::as_object) - .and_then(|site| site.get(key)), - preloaded.get(key), - ] - .into_iter() - .flatten() -} - -fn category_values_from_candidate(candidate: &Value) -> Option<&Vec> { - if let Some(values) = candidate.as_array() { - return Some(values); - } - - candidate - .as_object() - .and_then(|value| value.get("categories")) - .and_then(Value::as_array) -} - -fn topic_category_from_value(value: &Value) -> Option { - let object = value.as_object()?; - Some(TopicCategory { - id: positive_u64(object.get("id"))?, - name: scalar_string_or_empty(object.get("name")), - slug: scalar_string_or_empty(object.get("slug")), - parent_category_id: positive_u64(object.get("parent_category_id")), - color_hex: object - .get("color") - .and_then(optional_scalar_string) - .filter(|value| !value.is_empty()), - text_color_hex: object - .get("text_color") - .and_then(optional_scalar_string) - .filter(|value| !value.is_empty()), - topic_template: object - .get("topic_template") - .and_then(optional_scalar_string) - .filter(|value| !value.is_empty()), - minimum_required_tags: positive_u32(object.get("minimum_required_tags")).unwrap_or(0), - required_tag_groups: required_tag_groups_from_value(object.get("required_tag_groups")), - allowed_tags: string_array_from_value(object.get("allowed_tags")), - permission: positive_u32(object.get("permission")), - notification_level: integer_i32(object.get("notification_level")), - }) -} - -fn top_tags_from_preloaded(preloaded: &Value) -> Vec { - site_candidates(preloaded, "top_tags") - .find_map(top_tag_names_from_candidate) - .unwrap_or_default() -} - -fn top_tag_names_from_candidate(candidate: &Value) -> Option> { - let values = candidate.as_array()?; - Some( - values - .iter() - .filter_map(top_tag_name_from_value) - .collect::>(), - ) -} - -fn top_tag_name_from_value(value: &Value) -> Option { - match value { - Value::String(value) => { - let trimmed = value.trim(); - if trimmed.is_empty() { - None - } else { - Some(trimmed.to_string()) - } - } - Value::Object(value) => value - .get("name") - .and_then(optional_scalar_string) - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()), - _ => None, - } -} - -fn can_tag_topics_from_preloaded(preloaded: &Value) -> Option { - site_candidates(preloaded, "can_tag_topics").find_map(can_tag_topics_from_value) -} - -fn can_tag_topics_from_value(value: &Value) -> Option { - match value { - Value::Bool(value) => Some(*value), - Value::String(value) => match value.trim() { - "true" => Some(true), - "false" => Some(false), - _ => None, - }, - Value::Number(value) => value.as_u64().map(|value| value > 0), - _ => None, - } -} - -fn enabled_reaction_ids_from_preloaded(preloaded: &Value) -> Vec { - let Some(raw) = preloaded - .get("siteSettings") - .and_then(Value::as_object) - .and_then(|settings| settings.get("discourse_reactions_enabled_reactions")) - .and_then(optional_scalar_string) - else { - return vec!["heart".to_string()]; - }; - - let mut ids = Vec::new(); - for part in raw - .split('|') - .map(str::trim) - .filter(|value| !value.is_empty()) - { - if ids.iter().any(|existing| existing == part) { - continue; - } - ids.push(part.to_string()); - } - - if ids.is_empty() { - vec!["heart".to_string()] - } else { - ids - } -} - -fn min_post_length_from_preloaded(preloaded: &Value) -> u32 { - site_setting_u32(preloaded, "min_post_length").unwrap_or(1) -} - -fn min_topic_title_length_from_preloaded(preloaded: &Value) -> u32 { - site_setting_u32(preloaded, "min_topic_title_length").unwrap_or(15) -} - -fn min_first_post_length_from_preloaded(preloaded: &Value) -> u32 { - site_setting_u32(preloaded, "min_first_post_length") - .or_else(|| site_setting_u32(preloaded, "min_post_length")) - .unwrap_or(20) -} - -fn min_personal_message_title_length_from_preloaded(preloaded: &Value) -> u32 { - site_setting_u32(preloaded, "min_personal_message_title_length").unwrap_or(2) -} - -fn min_personal_message_post_length_from_preloaded(preloaded: &Value) -> u32 { - site_setting_u32(preloaded, "min_personal_message_post_length").unwrap_or(10) -} - -fn default_composer_category_from_preloaded(preloaded: &Value) -> Option { - preloaded - .get("siteSettings") - .and_then(Value::as_object) - .and_then(|settings| settings.get("default_composer_category")) - .and_then(|value| positive_u64(Some(value))) -} - -fn site_setting_u32(preloaded: &Value, key: &str) -> Option { - preloaded - .get("siteSettings") - .and_then(Value::as_object) - .and_then(|settings| settings.get(key)) - .and_then(|value| positive_u32(Some(value))) -} - -fn string_array_from_value(value: Option<&Value>) -> Vec { - value - .and_then(Value::as_array) - .map(|items| { - items - .iter() - .filter_map(optional_scalar_string) - .map(|item| item.trim().to_string()) - .filter(|item| !item.is_empty()) - .collect::>() - }) - .unwrap_or_default() -} - -fn required_tag_groups_from_value(value: Option<&Value>) -> Vec { - value - .and_then(Value::as_array) - .map(|items| { - items - .iter() - .filter_map(required_tag_group_from_value) - .collect::>() - }) - .unwrap_or_default() -} - -fn required_tag_group_from_value(value: &Value) -> Option { - let object = value.as_object()?; - let name = object - .get("name") - .and_then(optional_scalar_string) - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty())?; - Some(RequiredTagGroup { - name, - min_count: positive_u32(object.get("min_count")).unwrap_or(0), - }) -} - -fn optional_scalar_string(value: &Value) -> Option { - match value { - Value::String(value) => Some(value.clone()), - Value::Bool(value) => Some(value.to_string()), - Value::Number(value) => Some(value.to_string()), - _ => None, - } -} - -fn scalar_string_or_empty(value: Option<&Value>) -> String { - value.and_then(optional_scalar_string).unwrap_or_default() -} - -#[cfg(test)] -mod tests { - use fire_models::BootstrapArtifacts; - - use super::{ - decode_html_entities, hydrate_preloaded_fields, parse_home_state, parse_site_metadata_json, - }; - - #[test] - fn parse_home_state_skips_meta_tags_without_name() { - let html = r#" - - - - - - - - - - - -"#; - - let parsed = parse_home_state("https://linux.do/", html); - - assert_eq!( - parsed.cookies_patch.csrf_token.as_deref(), - Some("csrf-token") - ); - assert_eq!( - parsed.bootstrap_patch.shared_session_key.as_deref(), - Some("shared-session") - ); - assert_eq!( - parsed.bootstrap_patch.current_username.as_deref(), - Some("alice") - ); - assert_eq!( - parsed.bootstrap_patch.discourse_base_uri.as_deref(), - Some("/") - ); - } - - #[test] - fn parse_home_state_decodes_preloaded_json_once() { - let html = r#" - - - -
- - -"#; - - let parsed = parse_home_state("https://linux.do/", html); - - assert_eq!( - parsed.bootstrap_patch.preloaded_json.as_deref(), - Some( - r###"{"siteSettings":{"title":"A & B","min_post_length":18,"min_topic_title_length":15,"min_first_post_length":24,"default_composer_category":7,"discourse_reactions_enabled_reactions":"heart|clap"},"site":{"categories":[{"id":7,"name":"Rust","slug":"rust","color":"FFFFFF","text_color":"000000","topic_template":"## Template","minimum_required_tags":2,"required_tag_groups":[{"name":"platform","min_count":1}],"allowed_tags":["swift","rust"],"permission":1,"notification_level":"4"}],"top_tags":[{"name":"swift"},"rust"],"can_tag_topics":true}}"### - ) - ); - assert!(parsed.bootstrap_patch.has_site_settings); - assert_eq!(parsed.bootstrap_patch.min_post_length, 18); - assert_eq!(parsed.bootstrap_patch.min_topic_title_length, 15); - assert_eq!(parsed.bootstrap_patch.min_first_post_length, 24); - assert_eq!(parsed.bootstrap_patch.default_composer_category, Some(7)); - assert_eq!( - parsed.bootstrap_patch.enabled_reaction_ids, - vec!["heart", "clap"] - ); - assert!(parsed.bootstrap_patch.has_site_metadata); - assert_eq!(parsed.bootstrap_patch.top_tags, vec!["swift", "rust"]); - assert!(parsed.bootstrap_patch.can_tag_topics); - assert_eq!(parsed.bootstrap_patch.categories.len(), 1); - assert_eq!(parsed.bootstrap_patch.categories[0].id, 7); - assert_eq!( - parsed.bootstrap_patch.categories[0] - .topic_template - .as_deref(), - Some("## Template") - ); - assert_eq!( - parsed.bootstrap_patch.categories[0].minimum_required_tags, - 2 - ); - assert_eq!( - parsed.bootstrap_patch.categories[0] - .required_tag_groups - .len(), - 1 - ); - assert_eq!( - parsed.bootstrap_patch.categories[0].allowed_tags, - vec!["swift", "rust"] - ); - assert_eq!(parsed.bootstrap_patch.categories[0].permission, Some(1)); - assert_eq!( - parsed.bootstrap_patch.categories[0].notification_level, - Some(4) - ); - } - - #[test] - fn parse_home_state_marks_partial_preloaded_without_site_as_incomplete() { - let html = r#" - - - -
- - -"#; - - let parsed = parse_home_state("https://linux.do/", html); - - assert!(parsed.bootstrap_patch.has_preloaded_data); - assert!(!parsed.bootstrap_patch.has_site_metadata); - assert!(!parsed.bootstrap_patch.has_site_settings); - assert_eq!(parsed.bootstrap_patch.categories, Vec::new()); - assert_eq!(parsed.bootstrap_patch.top_tags, Vec::::new()); - assert!(!parsed.bootstrap_patch.can_tag_topics); - } - - #[test] - fn hydrate_preloaded_fields_unwraps_stringified_root_payloads() { - let mut bootstrap = BootstrapArtifacts::default(); - hydrate_preloaded_fields( - r###"{ - "currentUser":"{\"id\":341628,\"username\":\"alice\",\"notification_channel_position\":11}", - "siteSettings":"{\"long_polling_base_url\":\"https://ping.linux.do\",\"min_post_length\":18,\"min_topic_title_length\":15,\"min_first_post_length\":24,\"default_composer_category\":7,\"discourse_reactions_enabled_reactions\":\"heart|clap\"}", - "site":"{\"categories\":[{\"id\":7,\"name\":\"Rust\",\"slug\":\"rust\",\"color\":\"FFFFFF\",\"text_color\":\"000000\",\"topic_template\":\"## Template\",\"minimum_required_tags\":2,\"required_tag_groups\":[{\"name\":\"platform\",\"min_count\":1}],\"allowed_tags\":[\"swift\",\"rust\"],\"permission\":1,\"notification_level\":3}],\"top_tags\":[{\"name\":\"swift\"},\"rust\"],\"can_tag_topics\":true}", - "topicTrackingStateMeta":"{\"/latest\":42,\"/new\":8}" -}"###, - &mut bootstrap, - ); - - assert_eq!(bootstrap.current_username.as_deref(), Some("alice")); - assert_eq!(bootstrap.current_user_id, Some(341628)); - assert_eq!(bootstrap.notification_channel_position, Some(11)); - assert_eq!( - bootstrap.long_polling_base_url.as_deref(), - Some("https://ping.linux.do") - ); - assert_eq!( - bootstrap.topic_tracking_state_meta.as_deref(), - Some(r#"{"/latest":42,"/new":8}"#) - ); - assert!(bootstrap.has_site_metadata); - assert_eq!(bootstrap.top_tags, vec!["swift", "rust"]); - assert!(bootstrap.can_tag_topics); - assert_eq!(bootstrap.categories.len(), 1); - assert_eq!(bootstrap.categories[0].id, 7); - assert!(bootstrap.has_site_settings); - assert_eq!(bootstrap.enabled_reaction_ids, vec!["heart", "clap"]); - assert_eq!(bootstrap.min_post_length, 18); - assert_eq!(bootstrap.min_topic_title_length, 15); - assert_eq!(bootstrap.min_first_post_length, 24); - assert_eq!(bootstrap.default_composer_category, Some(7)); - assert_eq!(bootstrap.categories[0].minimum_required_tags, 2); - assert_eq!(bootstrap.categories[0].permission, Some(1)); - assert_eq!(bootstrap.categories[0].notification_level, Some(3)); - } - - #[test] - fn parse_site_metadata_json_reads_root_site_json_shape() { - let parsed = parse_site_metadata_json( - "https://linux.do/", - r#"{ - "categories": [ - {"id": 7, "name": "Rust", "slug": "rust", "color": "FFFFFF", "text_color": "000000"} - ], - "top_tags": [{"name": "swift"}, "rust"], - "can_tag_topics": true - }"#, - ); - - assert!(parsed.has_site_metadata); - assert_eq!(parsed.categories.len(), 1); - assert_eq!(parsed.top_tags, vec!["swift", "rust"]); - assert!(parsed.can_tag_topics); - assert_eq!(parsed.base_url, "https://linux.do/"); - } - - #[test] - fn decode_html_entities_supports_named_and_numeric_forms() { - assert_eq!( - decode_html_entities(""&<>''AA"), - "\"&<>''AA" - ); - } -} diff --git a/crates/fire-core/src/parsing/home.rs b/crates/fire-core/src/parsing/home.rs new file mode 100644 index 00000000..6efe2f50 --- /dev/null +++ b/crates/fire-core/src/parsing/home.rs @@ -0,0 +1,36 @@ +use fire_models::{BootstrapArtifacts, CookieSnapshot}; + +use super::{ + html_meta::{find_first_attr, find_meta_content}, + preloaded::hydrate_preloaded_fields, +}; + +#[derive(Debug, Default)] +pub(crate) struct ParsedHomeState { + pub(crate) cookies_patch: CookieSnapshot, + pub(crate) bootstrap_patch: BootstrapArtifacts, +} + +pub(crate) fn parse_home_state(base_url: &str, html: &str) -> ParsedHomeState { + let mut parsed = ParsedHomeState { + bootstrap_patch: BootstrapArtifacts { + base_url: base_url.to_string(), + ..BootstrapArtifacts::default() + }, + ..ParsedHomeState::default() + }; + + parsed.cookies_patch.csrf_token = find_meta_content(html, "csrf-token"); + parsed.bootstrap_patch.shared_session_key = find_meta_content(html, "shared_session_key"); + parsed.bootstrap_patch.current_username = find_meta_content(html, "current-username"); + parsed.bootstrap_patch.discourse_base_uri = find_meta_content(html, "discourse-base-uri"); + parsed.bootstrap_patch.turnstile_sitekey = find_first_attr(html, "data-sitekey"); + + if let Some(preloaded_json) = find_first_attr(html, "data-preloaded") { + parsed.bootstrap_patch.preloaded_json = Some(preloaded_json.clone()); + parsed.bootstrap_patch.has_preloaded_data = true; + hydrate_preloaded_fields(&preloaded_json, &mut parsed.bootstrap_patch); + } + + parsed +} diff --git a/crates/fire-core/src/parsing/html_meta.rs b/crates/fire-core/src/parsing/html_meta.rs new file mode 100644 index 00000000..462c118b --- /dev/null +++ b/crates/fire-core/src/parsing/html_meta.rs @@ -0,0 +1,122 @@ +use std::sync::OnceLock; + +use regex::Regex; + +pub(super) fn find_meta_content(html: &str, target_name: &str) -> Option { + for tag in all_tags(html) { + if !tag.starts_with(" Option { + for tag in all_tags(html) { + if let Some(value) = extract_attr(tag, attribute_name) { + return Some(decode_html_entities(&value)); + } + } + + None +} + +fn all_tags(html: &str) -> impl Iterator { + static TAG_RE: OnceLock = OnceLock::new(); + // NOTE: This lightweight scanner is intentionally scoped to Discourse bootstrap tags. + // If parsing expands beyond meta/data-* extraction, switch to a real HTML parser. + let regex = TAG_RE.get_or_init(|| Regex::new(r"(?is)<[^>]+>").expect("tag regex")); + regex.find_iter(html).map(|matched| matched.as_str()) +} + +fn extract_attr(tag: &str, attribute_name: &str) -> Option { + static ATTR_RE: OnceLock = OnceLock::new(); + let regex = ATTR_RE.get_or_init(|| { + Regex::new( + r#"(?is)\b([a-zA-Z0-9:_-]+)\s*=\s*"([^"]*)"|\b([a-zA-Z0-9:_-]+)\s*=\s*'([^']*)'"#, + ) + .expect("attr regex") + }); + + for captures in regex.captures_iter(tag) { + let (name, value) = if let (Some(name), Some(value)) = (captures.get(1), captures.get(2)) { + (name.as_str(), value.as_str()) + } else if let (Some(name), Some(value)) = (captures.get(3), captures.get(4)) { + (name.as_str(), value.as_str()) + } else { + continue; + }; + + if !name.eq_ignore_ascii_case(attribute_name) { + continue; + } + return Some(value.to_string()); + } + + None +} + +pub(crate) fn decode_html_entities(raw: &str) -> String { + let mut decoded = String::with_capacity(raw.len()); + let mut cursor = raw; + + while let Some(start) = cursor.find('&') { + decoded.push_str(&cursor[..start]); + let entity_start = &cursor[start..]; + + let Some(end) = entity_start.find(';') else { + decoded.push_str(entity_start); + return decoded; + }; + + let entity = &entity_start[1..end]; + if let Some(ch) = decode_html_entity(entity) { + decoded.push(ch); + } else { + decoded.push_str(&entity_start[..=end]); + } + + cursor = &entity_start[end + 1..]; + } + + decoded.push_str(cursor); + decoded +} + +fn decode_html_entity(entity: &str) -> Option { + match entity { + "nbsp" | "#160" => Some(' '), + "quot" => Some('"'), + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "apos" | "#39" => Some('\''), + _ => decode_numeric_html_entity(entity), + } +} + +fn decode_numeric_html_entity(entity: &str) -> Option { + let value = if let Some(hex) = entity + .strip_prefix("#x") + .or_else(|| entity.strip_prefix("#X")) + { + u32::from_str_radix(hex, 16).ok()? + } else { + let decimal = entity.strip_prefix('#')?; + decimal.parse::().ok()? + }; + + char::from_u32(value) +} diff --git a/crates/fire-core/src/parsing/mod.rs b/crates/fire-core/src/parsing/mod.rs new file mode 100644 index 00000000..7c94411a --- /dev/null +++ b/crates/fire-core/src/parsing/mod.rs @@ -0,0 +1,18 @@ +mod home; +mod html_meta; +mod preloaded; +mod site_metadata; +mod site_settings; + +#[allow(unused_imports)] +pub(crate) use home::{parse_home_state, ParsedHomeState}; +#[allow(unused_imports)] +pub(crate) use html_meta::decode_html_entities; +pub(crate) use preloaded::{hydrate_preloaded_fields, parse_preloaded_payload}; +#[allow(unused_imports)] +pub(crate) use site_metadata::{hydrate_site_metadata_fields, parse_site_metadata_json}; +#[allow(unused_imports)] +pub(crate) use site_settings::hydrate_site_settings_fields; + +#[cfg(test)] +mod tests; diff --git a/crates/fire-core/src/parsing/preloaded.rs b/crates/fire-core/src/parsing/preloaded.rs new file mode 100644 index 00000000..696a2eb1 --- /dev/null +++ b/crates/fire-core/src/parsing/preloaded.rs @@ -0,0 +1,99 @@ +use fire_models::BootstrapArtifacts; +use serde_json::Value; +use tracing::warn; + +use super::{ + site_metadata::hydrate_site_metadata_fields, site_settings::hydrate_site_settings_fields, +}; +use crate::json_helpers::{integer_i64, positive_u64}; + +pub(crate) fn hydrate_preloaded_fields(preloaded_json: &str, bootstrap: &mut BootstrapArtifacts) { + let Some(preloaded) = parse_preloaded_payload(preloaded_json) else { + return; + }; + + if let Some(username) = preloaded + .get("currentUser") + .and_then(|value| value.get("username")) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + { + bootstrap.current_username = Some(username.to_string()); + } + + if let Some(current_user_id) = preloaded + .get("currentUser") + .and_then(|value| value.get("id")) + .and_then(|value| positive_u64(Some(value))) + { + bootstrap.current_user_id = Some(current_user_id); + } + + if let Some(notification_channel_position) = preloaded + .get("currentUser") + .and_then(|value| value.get("notification_channel_position")) + .and_then(|value| integer_i64(Some(value))) + { + bootstrap.notification_channel_position = Some(notification_channel_position); + } + + if let Some(long_polling_base_url) = preloaded + .get("siteSettings") + .and_then(|value| value.get("long_polling_base_url")) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + { + bootstrap.long_polling_base_url = Some(long_polling_base_url.to_string()); + } + + if let Some(meta) = preloaded.get("topicTrackingStateMeta") { + if !meta.is_null() { + bootstrap.topic_tracking_state_meta = serde_json::to_string(meta).ok(); + } + } + + hydrate_site_metadata_fields(&preloaded, bootstrap); + hydrate_site_settings_fields(&preloaded, bootstrap); +} + +pub(crate) fn parse_preloaded_payload(preloaded_json: &str) -> Option { + let Ok(preloaded) = serde_json::from_str::(preloaded_json) else { + warn!("failed to parse data-preloaded json"); + return None; + }; + Some(normalize_preloaded_payload(&preloaded)) +} + +fn normalize_preloaded_payload(preloaded: &Value) -> Value { + let Some(object) = preloaded.as_object() else { + return preloaded.clone(); + }; + + let mut normalized = object.clone(); + for key in [ + "currentUser", + "siteSettings", + "site", + "topicTrackingStateMeta", + "topicTrackingStates", + ] { + let Some(value) = normalized.get(key).cloned() else { + continue; + }; + let Some(decoded) = decode_embedded_json_payload(&value) else { + continue; + }; + normalized.insert(key.to_string(), decoded); + } + + Value::Object(normalized) +} + +fn decode_embedded_json_payload(value: &Value) -> Option { + let raw = value.as_str()?.trim(); + let first = raw.chars().next()?; + if first != '{' && first != '[' { + return None; + } + serde_json::from_str(raw).ok() +} diff --git a/crates/fire-core/src/parsing/site_metadata.rs b/crates/fire-core/src/parsing/site_metadata.rs new file mode 100644 index 00000000..b4e3f84b --- /dev/null +++ b/crates/fire-core/src/parsing/site_metadata.rs @@ -0,0 +1,216 @@ +use fire_models::{BootstrapArtifacts, RequiredTagGroup, TopicCategory}; +use serde_json::Value; +use tracing::warn; + +use crate::json_helpers::{integer_i32, positive_u32, positive_u64}; + +pub(crate) fn parse_site_metadata_json(base_url: &str, json: &str) -> BootstrapArtifacts { + let mut bootstrap = BootstrapArtifacts { + base_url: base_url.to_string(), + ..BootstrapArtifacts::default() + }; + let Ok(value) = serde_json::from_str::(json) else { + warn!("failed to parse site.json payload"); + return bootstrap; + }; + hydrate_site_metadata_fields(&value, &mut bootstrap); + bootstrap +} + +pub(crate) fn hydrate_site_metadata_fields(source: &Value, bootstrap: &mut BootstrapArtifacts) { + bootstrap.has_site_metadata = has_site_metadata(source); + bootstrap.top_tags = top_tags_from_preloaded(source); + bootstrap.can_tag_topics = can_tag_topics_from_preloaded(source).unwrap_or(false); + bootstrap.categories = categories_from_preloaded(source); +} + +fn categories_from_preloaded(preloaded: &Value) -> Vec { + category_candidates(preloaded) + .find_map(category_values_from_candidate) + .map(|values| { + values + .iter() + .filter_map(topic_category_from_value) + .collect() + }) + .unwrap_or_default() +} + +fn category_candidates(preloaded: &Value) -> impl Iterator { + [ + preloaded + .get("site") + .and_then(Value::as_object) + .and_then(|site| site.get("categories")), + preloaded + .get("site") + .and_then(Value::as_object) + .and_then(|site| site.get("category_list")), + preloaded.get("categories"), + preloaded.get("category_list"), + ] + .into_iter() + .flatten() +} + +fn has_site_metadata(preloaded: &Value) -> bool { + category_candidates(preloaded).next().is_some() + || site_candidates(preloaded, "top_tags").next().is_some() + || site_candidates(preloaded, "can_tag_topics") + .next() + .is_some() +} + +fn site_candidates<'a>(preloaded: &'a Value, key: &'static str) -> impl Iterator { + [ + preloaded + .get("site") + .and_then(Value::as_object) + .and_then(|site| site.get(key)), + preloaded.get(key), + ] + .into_iter() + .flatten() +} + +fn category_values_from_candidate(candidate: &Value) -> Option<&Vec> { + if let Some(values) = candidate.as_array() { + return Some(values); + } + + candidate + .as_object() + .and_then(|value| value.get("categories")) + .and_then(Value::as_array) +} + +fn topic_category_from_value(value: &Value) -> Option { + let object = value.as_object()?; + Some(TopicCategory { + id: positive_u64(object.get("id"))?, + name: scalar_string_or_empty(object.get("name")), + slug: scalar_string_or_empty(object.get("slug")), + parent_category_id: positive_u64(object.get("parent_category_id")), + color_hex: object + .get("color") + .and_then(optional_scalar_string) + .filter(|value| !value.is_empty()), + text_color_hex: object + .get("text_color") + .and_then(optional_scalar_string) + .filter(|value| !value.is_empty()), + topic_template: object + .get("topic_template") + .and_then(optional_scalar_string) + .filter(|value| !value.is_empty()), + minimum_required_tags: positive_u32(object.get("minimum_required_tags")).unwrap_or(0), + required_tag_groups: required_tag_groups_from_value(object.get("required_tag_groups")), + allowed_tags: string_array_from_value(object.get("allowed_tags")), + permission: positive_u32(object.get("permission")), + notification_level: integer_i32(object.get("notification_level")), + }) +} + +fn top_tags_from_preloaded(preloaded: &Value) -> Vec { + site_candidates(preloaded, "top_tags") + .find_map(top_tag_names_from_candidate) + .unwrap_or_default() +} + +fn top_tag_names_from_candidate(candidate: &Value) -> Option> { + let values = candidate.as_array()?; + Some( + values + .iter() + .filter_map(top_tag_name_from_value) + .collect::>(), + ) +} + +fn top_tag_name_from_value(value: &Value) -> Option { + match value { + Value::String(value) => { + let trimmed = value.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } + } + Value::Object(value) => value + .get("name") + .and_then(optional_scalar_string) + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()), + _ => None, + } +} + +fn can_tag_topics_from_preloaded(preloaded: &Value) -> Option { + site_candidates(preloaded, "can_tag_topics").find_map(can_tag_topics_from_value) +} + +fn can_tag_topics_from_value(value: &Value) -> Option { + match value { + Value::Bool(value) => Some(*value), + Value::String(value) => match value.trim() { + "true" => Some(true), + "false" => Some(false), + _ => None, + }, + Value::Number(value) => value.as_u64().map(|value| value > 0), + _ => None, + } +} + +fn string_array_from_value(value: Option<&Value>) -> Vec { + value + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(optional_scalar_string) + .map(|item| item.trim().to_string()) + .filter(|item| !item.is_empty()) + .collect::>() + }) + .unwrap_or_default() +} + +fn required_tag_groups_from_value(value: Option<&Value>) -> Vec { + value + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(required_tag_group_from_value) + .collect::>() + }) + .unwrap_or_default() +} + +fn required_tag_group_from_value(value: &Value) -> Option { + let object = value.as_object()?; + let name = object + .get("name") + .and_then(optional_scalar_string) + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty())?; + Some(RequiredTagGroup { + name, + min_count: positive_u32(object.get("min_count")).unwrap_or(0), + }) +} + +pub(super) fn optional_scalar_string(value: &Value) -> Option { + match value { + Value::String(value) => Some(value.clone()), + Value::Bool(value) => Some(value.to_string()), + Value::Number(value) => Some(value.to_string()), + _ => None, + } +} + +fn scalar_string_or_empty(value: Option<&Value>) -> String { + value.and_then(optional_scalar_string).unwrap_or_default() +} diff --git a/crates/fire-core/src/parsing/site_settings.rs b/crates/fire-core/src/parsing/site_settings.rs new file mode 100644 index 00000000..394a846e --- /dev/null +++ b/crates/fire-core/src/parsing/site_settings.rs @@ -0,0 +1,89 @@ +use fire_models::BootstrapArtifacts; +use serde_json::Value; + +use super::site_metadata::optional_scalar_string; +use crate::json_helpers::{positive_u32, positive_u64}; + +pub(crate) fn hydrate_site_settings_fields(source: &Value, bootstrap: &mut BootstrapArtifacts) { + bootstrap.has_site_settings = has_site_settings(source); + bootstrap.enabled_reaction_ids = enabled_reaction_ids_from_preloaded(source); + bootstrap.min_post_length = min_post_length_from_preloaded(source); + bootstrap.min_topic_title_length = min_topic_title_length_from_preloaded(source); + bootstrap.min_first_post_length = min_first_post_length_from_preloaded(source); + bootstrap.min_personal_message_title_length = + min_personal_message_title_length_from_preloaded(source); + bootstrap.min_personal_message_post_length = + min_personal_message_post_length_from_preloaded(source); + bootstrap.default_composer_category = default_composer_category_from_preloaded(source); +} +fn has_site_settings(preloaded: &Value) -> bool { + preloaded + .get("siteSettings") + .is_some_and(|value| value.is_object()) +} +fn enabled_reaction_ids_from_preloaded(preloaded: &Value) -> Vec { + let Some(raw) = preloaded + .get("siteSettings") + .and_then(Value::as_object) + .and_then(|settings| settings.get("discourse_reactions_enabled_reactions")) + .and_then(optional_scalar_string) + else { + return vec!["heart".to_string()]; + }; + + let mut ids = Vec::new(); + for part in raw + .split('|') + .map(str::trim) + .filter(|value| !value.is_empty()) + { + if ids.iter().any(|existing| existing == part) { + continue; + } + ids.push(part.to_string()); + } + + if ids.is_empty() { + vec!["heart".to_string()] + } else { + ids + } +} + +fn min_post_length_from_preloaded(preloaded: &Value) -> u32 { + site_setting_u32(preloaded, "min_post_length").unwrap_or(1) +} + +fn min_topic_title_length_from_preloaded(preloaded: &Value) -> u32 { + site_setting_u32(preloaded, "min_topic_title_length").unwrap_or(15) +} + +fn min_first_post_length_from_preloaded(preloaded: &Value) -> u32 { + site_setting_u32(preloaded, "min_first_post_length") + .or_else(|| site_setting_u32(preloaded, "min_post_length")) + .unwrap_or(20) +} + +fn min_personal_message_title_length_from_preloaded(preloaded: &Value) -> u32 { + site_setting_u32(preloaded, "min_personal_message_title_length").unwrap_or(2) +} + +fn min_personal_message_post_length_from_preloaded(preloaded: &Value) -> u32 { + site_setting_u32(preloaded, "min_personal_message_post_length").unwrap_or(10) +} + +fn default_composer_category_from_preloaded(preloaded: &Value) -> Option { + preloaded + .get("siteSettings") + .and_then(Value::as_object) + .and_then(|settings| settings.get("default_composer_category")) + .and_then(|value| positive_u64(Some(value))) +} + +fn site_setting_u32(preloaded: &Value, key: &str) -> Option { + preloaded + .get("siteSettings") + .and_then(Value::as_object) + .and_then(|settings| settings.get(key)) + .and_then(|value| positive_u32(Some(value))) +} diff --git a/crates/fire-core/src/parsing/tests.rs b/crates/fire-core/src/parsing/tests.rs new file mode 100644 index 00000000..a552255e --- /dev/null +++ b/crates/fire-core/src/parsing/tests.rs @@ -0,0 +1,190 @@ +use fire_models::BootstrapArtifacts; + +use super::{ + decode_html_entities, hydrate_preloaded_fields, parse_home_state, parse_site_metadata_json, +}; + +#[test] +fn parse_home_state_skips_meta_tags_without_name() { + let html = r#" + + + + + + + + + + + +"#; + + let parsed = parse_home_state("https://linux.do/", html); + + assert_eq!( + parsed.cookies_patch.csrf_token.as_deref(), + Some("csrf-token") + ); + assert_eq!( + parsed.bootstrap_patch.shared_session_key.as_deref(), + Some("shared-session") + ); + assert_eq!( + parsed.bootstrap_patch.current_username.as_deref(), + Some("alice") + ); + assert_eq!( + parsed.bootstrap_patch.discourse_base_uri.as_deref(), + Some("/") + ); +} + +#[test] +fn parse_home_state_decodes_preloaded_json_once() { + let html = r#" + + + +
+ + +"#; + + let parsed = parse_home_state("https://linux.do/", html); + + assert_eq!( + parsed.bootstrap_patch.preloaded_json.as_deref(), + Some( + r###"{"siteSettings":{"title":"A & B","min_post_length":18,"min_topic_title_length":15,"min_first_post_length":24,"default_composer_category":7,"discourse_reactions_enabled_reactions":"heart|clap"},"site":{"categories":[{"id":7,"name":"Rust","slug":"rust","color":"FFFFFF","text_color":"000000","topic_template":"## Template","minimum_required_tags":2,"required_tag_groups":[{"name":"platform","min_count":1}],"allowed_tags":["swift","rust"],"permission":1,"notification_level":"4"}],"top_tags":[{"name":"swift"},"rust"],"can_tag_topics":true}}"### + ) + ); + assert!(parsed.bootstrap_patch.has_site_settings); + assert_eq!(parsed.bootstrap_patch.min_post_length, 18); + assert_eq!(parsed.bootstrap_patch.min_topic_title_length, 15); + assert_eq!(parsed.bootstrap_patch.min_first_post_length, 24); + assert_eq!(parsed.bootstrap_patch.default_composer_category, Some(7)); + assert_eq!( + parsed.bootstrap_patch.enabled_reaction_ids, + vec!["heart", "clap"] + ); + assert!(parsed.bootstrap_patch.has_site_metadata); + assert_eq!(parsed.bootstrap_patch.top_tags, vec!["swift", "rust"]); + assert!(parsed.bootstrap_patch.can_tag_topics); + assert_eq!(parsed.bootstrap_patch.categories.len(), 1); + assert_eq!(parsed.bootstrap_patch.categories[0].id, 7); + assert_eq!( + parsed.bootstrap_patch.categories[0] + .topic_template + .as_deref(), + Some("## Template") + ); + assert_eq!( + parsed.bootstrap_patch.categories[0].minimum_required_tags, + 2 + ); + assert_eq!( + parsed.bootstrap_patch.categories[0] + .required_tag_groups + .len(), + 1 + ); + assert_eq!( + parsed.bootstrap_patch.categories[0].allowed_tags, + vec!["swift", "rust"] + ); + assert_eq!(parsed.bootstrap_patch.categories[0].permission, Some(1)); + assert_eq!( + parsed.bootstrap_patch.categories[0].notification_level, + Some(4) + ); +} + +#[test] +fn parse_home_state_marks_partial_preloaded_without_site_as_incomplete() { + let html = r#" + + + +
+ + +"#; + + let parsed = parse_home_state("https://linux.do/", html); + + assert!(parsed.bootstrap_patch.has_preloaded_data); + assert!(!parsed.bootstrap_patch.has_site_metadata); + assert!(!parsed.bootstrap_patch.has_site_settings); + assert_eq!(parsed.bootstrap_patch.categories, Vec::new()); + assert_eq!(parsed.bootstrap_patch.top_tags, Vec::::new()); + assert!(!parsed.bootstrap_patch.can_tag_topics); +} + +#[test] +fn hydrate_preloaded_fields_unwraps_stringified_root_payloads() { + let mut bootstrap = BootstrapArtifacts::default(); + hydrate_preloaded_fields( + r###"{ + "currentUser":"{\"id\":341628,\"username\":\"alice\",\"notification_channel_position\":11}", + "siteSettings":"{\"long_polling_base_url\":\"https://ping.linux.do\",\"min_post_length\":18,\"min_topic_title_length\":15,\"min_first_post_length\":24,\"default_composer_category\":7,\"discourse_reactions_enabled_reactions\":\"heart|clap\"}", + "site":"{\"categories\":[{\"id\":7,\"name\":\"Rust\",\"slug\":\"rust\",\"color\":\"FFFFFF\",\"text_color\":\"000000\",\"topic_template\":\"## Template\",\"minimum_required_tags\":2,\"required_tag_groups\":[{\"name\":\"platform\",\"min_count\":1}],\"allowed_tags\":[\"swift\",\"rust\"],\"permission\":1,\"notification_level\":3}],\"top_tags\":[{\"name\":\"swift\"},\"rust\"],\"can_tag_topics\":true}", + "topicTrackingStateMeta":"{\"/latest\":42,\"/new\":8}" +}"###, + &mut bootstrap, + ); + + assert_eq!(bootstrap.current_username.as_deref(), Some("alice")); + assert_eq!(bootstrap.current_user_id, Some(341628)); + assert_eq!(bootstrap.notification_channel_position, Some(11)); + assert_eq!( + bootstrap.long_polling_base_url.as_deref(), + Some("https://ping.linux.do") + ); + assert_eq!( + bootstrap.topic_tracking_state_meta.as_deref(), + Some(r#"{"/latest":42,"/new":8}"#) + ); + assert!(bootstrap.has_site_metadata); + assert_eq!(bootstrap.top_tags, vec!["swift", "rust"]); + assert!(bootstrap.can_tag_topics); + assert_eq!(bootstrap.categories.len(), 1); + assert_eq!(bootstrap.categories[0].id, 7); + assert!(bootstrap.has_site_settings); + assert_eq!(bootstrap.enabled_reaction_ids, vec!["heart", "clap"]); + assert_eq!(bootstrap.min_post_length, 18); + assert_eq!(bootstrap.min_topic_title_length, 15); + assert_eq!(bootstrap.min_first_post_length, 24); + assert_eq!(bootstrap.default_composer_category, Some(7)); + assert_eq!(bootstrap.categories[0].minimum_required_tags, 2); + assert_eq!(bootstrap.categories[0].permission, Some(1)); + assert_eq!(bootstrap.categories[0].notification_level, Some(3)); +} + +#[test] +fn parse_site_metadata_json_reads_root_site_json_shape() { + let parsed = parse_site_metadata_json( + "https://linux.do/", + r#"{ + "categories": [ + {"id": 7, "name": "Rust", "slug": "rust", "color": "FFFFFF", "text_color": "000000"} + ], + "top_tags": [{"name": "swift"}, "rust"], + "can_tag_topics": true + }"#, + ); + + assert!(parsed.has_site_metadata); + assert_eq!(parsed.categories.len(), 1); + assert_eq!(parsed.top_tags, vec!["swift", "rust"]); + assert!(parsed.can_tag_topics); + assert_eq!(parsed.base_url, "https://linux.do/"); +} + +#[test] +fn decode_html_entities_supports_named_and_numeric_forms() { + assert_eq!( + decode_html_entities(""&<>''AA"), + "\"&<>''AA" + ); +} diff --git a/crates/fire-core/src/rich_text.rs b/crates/fire-core/src/rich_text.rs deleted file mode 100644 index 5467633c..00000000 --- a/crates/fire-core/src/rich_text.rs +++ /dev/null @@ -1,798 +0,0 @@ -use std::collections::BTreeMap; - -use ego_tree::NodeRef; -use fire_models::{CookedHtmlDocument, CookedHtmlNode, CookedHtmlNodeKind, RenderDocument}; -use std::sync::Arc; - -use fire_models::{ - AttachedPresentation, ChatMessage, PresentedDocument, TopicPost, TopicPostBoost, -}; -use fire_rich_text::{present_owned_document, render_document as shared_render_document}; -use html5ever::tendril::TendrilSink; -use html5ever::{local_name, ns, QualName}; -use scraper::{ElementRef, Html, HtmlTreeSink, Node as ScraperNode}; - -pub fn parse_cooked_html(raw_html: &str) -> CookedHtmlDocument { - let html = parse_fragment(raw_html); - let mut builder = CookedHtmlBuilder::default(); - let root_id = builder.push_node(None, 0, CookedHtmlNodeKind::Document, NodeMeta::default()); - - let root = html.root_element(); - for child in root.children() { - builder.visit_node(child, root_id, 0, TextMode::Normal); - } - - builder.finish() -} - -pub fn render_cooked_html(raw_html: &str, base_url: &str) -> RenderDocument { - let document = parse_cooked_html(raw_html); - shared_render_document(&document, base_url) -} - -/// Parse cooked HTML and produce the host display plan. -/// -/// Empty input is absence, not an empty presentation. The returned -/// [`PresentedDocument`] keeps the IR for a future handle; callers that only -/// cross UniFFI should lift `into_presentation()`. -pub fn present_cooked_html(raw_html: &str, base_url: &str) -> Option { - let trimmed = raw_html.trim(); - if trimmed.is_empty() { - None - } else { - Some(present_owned_document(render_cooked_html( - trimmed, base_url, - ))) - } -} - -pub fn attach_post_presentation(post: &mut TopicPost, base_url: &str) { - if post.presented.get().is_none() { - post.presented = present_cooked_html(&post.cooked, base_url) - .map(|document| AttachedPresentation::some(Arc::new(document))) - .unwrap_or_default(); - } - for boost in &mut post.boosts { - attach_boost_presentation(boost, base_url); - } -} - -pub fn attach_boost_presentation(boost: &mut TopicPostBoost, base_url: &str) { - if boost.presented.get().is_some() { - return; - } - boost.presented = present_cooked_html(&boost.cooked, base_url) - .map(|document| AttachedPresentation::some(Arc::new(document))) - .unwrap_or_default(); -} - -pub fn attach_chat_message_presentation(message: &mut ChatMessage, base_url: &str) { - if message.presented.get().is_some() { - return; - } - message.presented = present_cooked_html(&message.cooked, base_url) - .map(|document| AttachedPresentation::some(Arc::new(document))) - .unwrap_or_default(); -} - -pub fn attach_posts_presentation(posts: &mut [TopicPost], base_url: &str) { - for post in posts { - attach_post_presentation(post, base_url); - } -} - -fn parse_fragment(raw_html: &str) -> Html { - let parser = html5ever::parse_fragment( - HtmlTreeSink::new(Html::new_fragment()), - html5ever::ParseOpts::default(), - QualName::new(None, ns!(html), local_name!("body")), - Vec::new(), - false, - ); - parser.one(raw_html) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum TextMode { - Normal, - Preformatted, -} - -#[derive(Default)] -struct CookedHtmlBuilder { - next_id: u32, - nodes: Vec, - plain_text: String, - pending_inline_space: bool, - image_urls: Vec, - link_urls: Vec, -} - -impl CookedHtmlBuilder { - fn finish(mut self) -> CookedHtmlDocument { - self.trim_plain_text(); - CookedHtmlDocument { - nodes: self.nodes, - plain_text: self.plain_text, - image_urls: dedupe_preserving_order(self.image_urls), - link_urls: dedupe_preserving_order(self.link_urls), - } - } - - fn visit_node( - &mut self, - node: NodeRef<'_, ScraperNode>, - parent_id: u32, - depth: u32, - text_mode: TextMode, - ) { - match node.value() { - ScraperNode::Text(text) => self.push_text_node(&text.text, parent_id, depth, text_mode), - ScraperNode::Element(_) => { - if let Some(element) = ElementRef::wrap(node) { - self.visit_element(element, parent_id, depth, text_mode); - } - } - _ => {} - } - } - - fn visit_element( - &mut self, - element: ElementRef<'_>, - parent_id: u32, - depth: u32, - text_mode: TextMode, - ) { - let tag = element.value().name(); - if matches!(tag, "script" | "style") { - return; - } - - let classes = element.attr("class").unwrap_or_default(); - // Polls are rendered by native Poll UI from structured post.polls. - // Walking their cooked children leaks option lists + vote labels into body text. - if is_poll_container(tag, classes) { - return; - } - let kind = node_kind_for_element(tag, classes); - let next_text_mode = if tag == "pre" { - TextMode::Preformatted - } else { - text_mode - }; - - if tag == "br" { - let id = self.push_node( - Some(parent_id), - depth + 1, - CookedHtmlNodeKind::LineBreak, - NodeMeta::from_element(element), - ); - self.ensure_line_break(); - self.visit_children(element, id, depth + 1, next_text_mode); - return; - } - - let starts_block = starts_plain_text_block(kind); - let ends_block = ends_plain_text_block(kind); - if starts_block { - self.ensure_block_boundary(); - } - - let effective_parent_id = if let Some(kind) = kind { - let mut meta = NodeMeta::from_element(element); - apply_element_metadata(tag, classes, element, kind, &mut meta); - if let Some(url) = meta.url.as_ref() { - match kind { - CookedHtmlNodeKind::Image | CookedHtmlNodeKind::Emoji => { - self.image_urls.push(url.clone()); - } - CookedHtmlNodeKind::Link - | CookedHtmlNodeKind::Mention - | CookedHtmlNodeKind::Hashtag - | CookedHtmlNodeKind::Attachment - | CookedHtmlNodeKind::Onebox - | CookedHtmlNodeKind::Iframe => { - self.link_urls.push(url.clone()); - } - _ => {} - } - } - - let id = self.push_node(Some(parent_id), depth + 1, kind, meta); - if matches!(kind, CookedHtmlNodeKind::Image | CookedHtmlNodeKind::Emoji) { - self.append_media_alt_text(element); - } - id - } else { - parent_id - }; - - self.visit_children(element, effective_parent_id, depth + 1, next_text_mode); - - match kind { - Some(CookedHtmlNodeKind::ListItem) => self.ensure_line_break(), - Some(CookedHtmlNodeKind::TableCell) => self.append_plain_separator(" "), - Some(CookedHtmlNodeKind::TableRow) => self.ensure_line_break(), - _ if ends_block => self.ensure_block_boundary(), - _ => {} - } - } - - fn visit_children( - &mut self, - element: ElementRef<'_>, - parent_id: u32, - depth: u32, - text_mode: TextMode, - ) { - for child in element.children() { - self.visit_node(child, parent_id, depth, text_mode); - } - } - - fn push_node( - &mut self, - parent_id: Option, - depth: u32, - kind: CookedHtmlNodeKind, - meta: NodeMeta, - ) -> u32 { - let id = self.next_id; - self.next_id += 1; - self.nodes.push(CookedHtmlNode { - id, - parent_id, - kind, - depth, - text: meta.text, - url: meta.url, - title: meta.title, - alt: meta.alt, - level: meta.level, - ordered: meta.ordered, - attributes: meta.attributes, - }); - id - } - - fn push_text_node(&mut self, raw_text: &str, parent_id: u32, depth: u32, text_mode: TextMode) { - let text = if text_mode == TextMode::Preformatted { - normalize_preformatted_text(raw_text) - } else { - normalize_inline_text(raw_text) - }; - if text.is_empty() { - if raw_text.chars().any(char::is_whitespace) { - self.pending_inline_space = true; - } - return; - } - - let id = self.push_node( - Some(parent_id), - depth + 1, - CookedHtmlNodeKind::Text, - NodeMeta { - text: Some(text.clone()), - ..NodeMeta::default() - }, - ); - debug_assert!(self.nodes.iter().any(|node| node.id == id)); - - if text_mode == TextMode::Preformatted { - self.append_preformatted_text(&text); - } else { - self.append_inline_text(raw_text, &text); - } - } - - fn append_media_alt_text(&mut self, element: ElementRef<'_>) { - let alt = element - .attr("alt") - .or_else(|| element.attr("title")) - .map(str::trim) - .filter(|value| !value.is_empty()); - if let Some(alt) = alt { - self.append_inline_text(alt, &normalize_inline_text(alt)); - } - } - - fn append_inline_text(&mut self, raw_text: &str, text: &str) { - if text.is_empty() { - return; - } - - let had_leading_space = raw_text - .chars() - .next() - .is_some_and(|character| character.is_whitespace() || character == '\u{a0}'); - let had_trailing_space = raw_text - .chars() - .last() - .is_some_and(|character| character.is_whitespace() || character == '\u{a0}'); - - if (had_leading_space || self.pending_inline_space) - && !self.plain_text.is_empty() - && !self.plain_text.ends_with(char::is_whitespace) - && !starts_with_closing_punctuation(text) - { - self.plain_text.push(' '); - } - - self.plain_text.push_str(text); - self.pending_inline_space = had_trailing_space; - } - - fn append_preformatted_text(&mut self, text: &str) { - if text.is_empty() { - return; - } - if self.pending_inline_space - && !self.plain_text.is_empty() - && !self.plain_text.ends_with(char::is_whitespace) - { - self.plain_text.push(' '); - } - self.plain_text.push_str(text); - self.pending_inline_space = false; - } - - fn append_plain_separator(&mut self, separator: &str) { - if self.plain_text.is_empty() || self.plain_text.ends_with(char::is_whitespace) { - return; - } - self.plain_text.push_str(separator); - self.pending_inline_space = false; - } - - fn ensure_line_break(&mut self) { - self.trim_plain_text_end(); - if !self.plain_text.is_empty() && !self.plain_text.ends_with('\n') { - self.plain_text.push('\n'); - } - self.pending_inline_space = false; - } - - fn ensure_block_boundary(&mut self) { - self.trim_plain_text_end(); - if self.plain_text.is_empty() { - self.pending_inline_space = false; - return; - } - - let trailing_newlines = self - .plain_text - .chars() - .rev() - .take_while(|character| *character == '\n') - .count(); - for _ in trailing_newlines..2 { - self.plain_text.push('\n'); - } - self.pending_inline_space = false; - } - - fn trim_plain_text_end(&mut self) { - while self - .plain_text - .chars() - .last() - .is_some_and(|character| character == ' ' || character == '\t') - { - self.plain_text.pop(); - } - } - - fn trim_plain_text(&mut self) { - while self - .plain_text - .chars() - .last() - .is_some_and(char::is_whitespace) - { - self.plain_text.pop(); - } - } -} - -#[derive(Default)] -struct NodeMeta { - text: Option, - url: Option, - title: Option, - alt: Option, - level: Option, - ordered: Option, - attributes: BTreeMap, -} - -impl NodeMeta { - fn from_element(element: ElementRef<'_>) -> Self { - let mut attributes = BTreeMap::new(); - for (name, value) in element.value().attrs() { - attributes.insert(name.to_string(), value.to_string()); - } - Self { - title: element.attr("title").map(ToOwned::to_owned), - alt: element.attr("alt").map(ToOwned::to_owned), - attributes, - ..Self::default() - } - } -} - -fn apply_element_metadata( - tag: &str, - classes: &str, - element: ElementRef<'_>, - kind: CookedHtmlNodeKind, - meta: &mut NodeMeta, -) { - match kind { - CookedHtmlNodeKind::Heading => { - meta.level = tag - .strip_prefix('h') - .and_then(|value| value.parse::().ok()); - } - CookedHtmlNodeKind::List => { - meta.ordered = Some(tag == "ol"); - } - CookedHtmlNodeKind::Link - | CookedHtmlNodeKind::Mention - | CookedHtmlNodeKind::Hashtag - | CookedHtmlNodeKind::Attachment => { - meta.url = element.attr("href").map(ToOwned::to_owned); - } - CookedHtmlNodeKind::Image | CookedHtmlNodeKind::Emoji => { - meta.url = element.attr("src").map(ToOwned::to_owned); - } - CookedHtmlNodeKind::Iframe => { - meta.url = element.attr("src").map(ToOwned::to_owned); - } - CookedHtmlNodeKind::Onebox => { - meta.url = element - .attr("href") - .or_else(|| element.attr("data-onebox-src")) - .or_else(|| element.attr("data-original-href")) - .map(ToOwned::to_owned); - if meta.title.is_none() { - meta.title = first_meaningful_text(element); - } - } - CookedHtmlNodeKind::DiscourseQuote => { - meta.title = element - .attr("data-username") - .or_else(|| element.attr("data-user-card")) - .map(ToOwned::to_owned) - .or_else(|| first_meaningful_text(element)); - } - _ => {} - } - - if classes - .split_ascii_whitespace() - .any(|class| class == "onebox" || class.ends_with("-onebox")) - && meta.url.is_none() - { - meta.url = element - .attr("href") - .or_else(|| element.attr("data-onebox-src")) - .or_else(|| element.attr("data-original-href")) - .map(ToOwned::to_owned); - } -} - -fn first_meaningful_text(element: ElementRef<'_>) -> Option { - let text = normalize_inline_text(&element.text().collect::>().join(" ")); - if text.is_empty() { - None - } else { - Some(text) - } -} - -fn node_kind_for_element(tag: &str, classes: &str) -> Option { - let has_class = |target: &str| { - classes - .split_ascii_whitespace() - .any(|class| class == target) - }; - let has_class_suffix = |suffix: &str| { - classes - .split_ascii_whitespace() - .any(|class| class.ends_with(suffix)) - }; - - if has_class("spoiler") || has_class("blur") { - return Some(CookedHtmlNodeKind::Spoiler); - } - // `inline-onebox` is an inline title link, not a preview card. The `-onebox` - // suffix would otherwise swallow it and drop the surrounding sentence. - let is_inline_onebox = has_class("inline-onebox") || has_class("inline-onebox-loading"); - if !is_inline_onebox && (has_class("onebox") || has_class_suffix("-onebox")) { - return Some(CookedHtmlNodeKind::Onebox); - } - if has_class("mention") { - return Some(CookedHtmlNodeKind::Mention); - } - if has_class("hashtag") { - return Some(CookedHtmlNodeKind::Hashtag); - } - if has_class("emoji") { - return Some(CookedHtmlNodeKind::Emoji); - } - if has_class("attachment") { - return Some(CookedHtmlNodeKind::Attachment); - } - - match tag { - "p" => Some(CookedHtmlNodeKind::Paragraph), - "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => Some(CookedHtmlNodeKind::Heading), - "br" => Some(CookedHtmlNodeKind::LineBreak), - "strong" | "b" => Some(CookedHtmlNodeKind::Strong), - "em" | "i" => Some(CookedHtmlNodeKind::Emphasis), - "s" | "del" | "strike" => Some(CookedHtmlNodeKind::Strikethrough), - "a" => Some(CookedHtmlNodeKind::Link), - "img" => Some(CookedHtmlNodeKind::Image), - "code" => Some(CookedHtmlNodeKind::Code), - "pre" => Some(CookedHtmlNodeKind::CodeBlock), - "blockquote" => Some(CookedHtmlNodeKind::Blockquote), - "aside" if has_class("quote") => Some(CookedHtmlNodeKind::DiscourseQuote), - "aside" => Some(CookedHtmlNodeKind::Onebox), - "hr" => Some(CookedHtmlNodeKind::Divider), - "ul" | "ol" => Some(CookedHtmlNodeKind::List), - "li" => Some(CookedHtmlNodeKind::ListItem), - "details" => Some(CookedHtmlNodeKind::Details), - "table" => Some(CookedHtmlNodeKind::Table), - "tr" => Some(CookedHtmlNodeKind::TableRow), - "td" | "th" => Some(CookedHtmlNodeKind::TableCell), - "iframe" | "video" => Some(CookedHtmlNodeKind::Iframe), - _ => None, - } -} - -fn is_poll_container(tag: &str, classes: &str) -> bool { - let has_class = |target: &str| { - classes - .split_whitespace() - .any(|class| class.eq_ignore_ascii_case(target)) - }; - // Discourse poll markup variants seen in the wild. - has_class("poll") - || has_class("poll-container") - || has_class("poll-area") - || (tag.eq_ignore_ascii_case("div") && has_class("polls")) -} - -fn starts_plain_text_block(kind: Option) -> bool { - matches!( - kind, - Some( - CookedHtmlNodeKind::Paragraph - | CookedHtmlNodeKind::Heading - | CookedHtmlNodeKind::Blockquote - | CookedHtmlNodeKind::DiscourseQuote - | CookedHtmlNodeKind::List - | CookedHtmlNodeKind::CodeBlock - | CookedHtmlNodeKind::Details - | CookedHtmlNodeKind::Table - | CookedHtmlNodeKind::Onebox - ) - ) -} - -fn ends_plain_text_block(kind: Option) -> bool { - starts_plain_text_block(kind) -} - -fn normalize_inline_text(raw: &str) -> String { - raw.replace('\u{a0}', " ") - .split_whitespace() - .collect::>() - .join(" ") -} - -fn normalize_preformatted_text(raw: &str) -> String { - raw.replace("\r\n", "\n").replace('\u{a0}', " ") -} - -fn starts_with_closing_punctuation(text: &str) -> bool { - text.chars().next().is_some_and(|character| { - matches!( - character, - '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}' - ) - }) -} - -fn dedupe_preserving_order(values: Vec) -> Vec { - let mut result = Vec::new(); - for value in values { - if value.trim().is_empty() || result.contains(&value) { - continue; - } - result.push(value); - } - result -} - -#[cfg(test)] -mod tests { - use fire_models::{CookedHtmlNodeKind, TopicPost}; - - use super::{ - attach_post_presentation, parse_cooked_html, present_cooked_html, render_cooked_html, - }; - - #[test] - fn parses_common_discourse_cooked_html_into_nodes() { - let document = parse_cooked_html( - r#" -

Hello Fire
topic

-

diagram

-
  • Rust
  • Android
- "#, - ); - - assert_eq!( - document.plain_text, - "Hello Fire\ntopic\n\ndiagram\n\nRust\nAndroid" - ); - assert_eq!( - document.image_urls, - vec!["/uploads/default/original/1X/fire.png".to_string()] - ); - assert_eq!(document.link_urls, vec!["/t/123/4".to_string()]); - assert!(document - .nodes - .iter() - .any(|node| node.kind == CookedHtmlNodeKind::Strong)); - assert!(document - .nodes - .iter() - .any(|node| node.kind == CookedHtmlNodeKind::ListItem)); - } - - #[test] - fn skips_poll_container_markup_so_native_poll_ui_is_not_duplicated() { - let document = parse_cooked_html( - r#" -

开个贴看看

-
-
    -
  • 0-10
  • -
  • 11-20
  • -
  • 61以上
  • -
-
1175 投票人
-
-

补充说明

- "#, - ); - - assert_eq!(document.plain_text, "开个贴看看\n\n补充说明"); - assert!(!document.plain_text.contains("0-10")); - assert!(!document.plain_text.contains("投票人")); - assert!(!document - .nodes - .iter() - .any(|node| node.kind == CookedHtmlNodeKind::ListItem)); - } - - #[test] - fn parses_discourse_quote_details_table_and_onebox_metadata() { - let document = parse_cooked_html( - r#" - -
More

hidden text

-
AB
- - "#, - ); - - let quote = document - .nodes - .iter() - .find(|node| node.kind == CookedHtmlNodeKind::DiscourseQuote) - .expect("quote node"); - assert_eq!(quote.title.as_deref(), Some("alice")); - assert_eq!( - quote.attributes.get("data-post").map(String::as_str), - Some("2") - ); - assert!(document - .nodes - .iter() - .any(|node| node.kind == CookedHtmlNodeKind::Details)); - assert!(document - .nodes - .iter() - .any(|node| node.kind == CookedHtmlNodeKind::TableCell)); - assert!(document.nodes.iter().any(|node| { - node.kind == CookedHtmlNodeKind::Onebox - && node.url.as_deref() == Some("https://example.com/card") - })); - } - - #[test] - fn inline_onebox_stays_a_link_and_block_onebox_keeps_chrome_out_of_images() { - let rendered = render_cooked_html( - r#" - -

后文 GitHub Topics Clock

- "#, - "https://linux.do", - ); - - assert!(rendered.image_attachments.is_empty()); - assert!(rendered.blocks.iter().any(|block| matches!( - &block.kind, - fire_models::RenderBlockKind::Onebox { - source_name: Some(source_name), - icon_url: Some(icon_url), - thumbnail_url: Some(thumbnail_url), - title: Some(title), - .. - } if source_name == "bilibili.com" - && icon_url == "https://www.bilibili.com/favicon.ico" - && thumbnail_url == "https://i0.hdslb.com/bfs/archive/cover.jpg" - && title == "开源神器" - ))); - assert!(rendered.blocks.iter().any(|block| matches!( - &block.kind, - fire_models::RenderBlockKind::Link { url } if url == "https://github.com/topics/clock" - ))); - assert_eq!( - rendered - .blocks - .iter() - .filter(|block| matches!(block.kind, fire_models::RenderBlockKind::Onebox { .. })) - .count(), - 1 - ); - let segments = fire_rich_text::display_segments(&rendered); - assert!(segments - .iter() - .all(|segment| !matches!(segment, fire_models::RenderUiSegment::Image(_)))); - } - - #[test] - fn present_cooked_html_skips_blank_input_and_keeps_ui_plan() { - assert!(present_cooked_html(" ", "https://linux.do").is_none()); - - let presented = present_cooked_html("

Hello Fire

", "https://linux.do") - .expect("non-empty cooked html should present"); - assert_eq!(presented.presentation().plain_text, "Hello Fire"); - assert!(!presented.presentation().segments.is_empty()); - } - - #[test] - fn attach_post_presentation_reuses_arc_when_cooked_is_unchanged() { - let mut first = TopicPost { - cooked: "

Hello Fire

".to_string(), - ..TopicPost::default() - }; - attach_post_presentation(&mut first, "https://linux.do"); - let original = first.presented.arc().expect("presented"); - - let mut second = first.clone(); - second.like_count = 4; - second.reuse_presentation_from(&first); - let reused = second.presented.arc().expect("reused"); - assert!(std::sync::Arc::ptr_eq(&original, &reused)); - } -} diff --git a/crates/fire-core/src/rich_text/attach.rs b/crates/fire-core/src/rich_text/attach.rs new file mode 100644 index 00000000..744f9191 --- /dev/null +++ b/crates/fire-core/src/rich_text/attach.rs @@ -0,0 +1,35 @@ +pub fn attach_post_presentation(post: &mut TopicPost, base_url: &str) { + if post.presented.get().is_none() { + post.presented = present_cooked_html(&post.cooked, base_url) + .map(|document| AttachedPresentation::some(Arc::new(document))) + .unwrap_or_default(); + } + for boost in &mut post.boosts { + attach_boost_presentation(boost, base_url); + } +} + +pub fn attach_boost_presentation(boost: &mut TopicPostBoost, base_url: &str) { + if boost.presented.get().is_some() { + return; + } + boost.presented = present_cooked_html(&boost.cooked, base_url) + .map(|document| AttachedPresentation::some(Arc::new(document))) + .unwrap_or_default(); +} + +pub fn attach_chat_message_presentation(message: &mut ChatMessage, base_url: &str) { + if message.presented.get().is_some() { + return; + } + message.presented = present_cooked_html(&message.cooked, base_url) + .map(|document| AttachedPresentation::some(Arc::new(document))) + .unwrap_or_default(); +} + +pub fn attach_posts_presentation(posts: &mut [TopicPost], base_url: &str) { + for post in posts { + attach_post_presentation(post, base_url); + } +} + diff --git a/crates/fire-core/src/rich_text/builder.rs b/crates/fire-core/src/rich_text/builder.rs new file mode 100644 index 00000000..f482c992 --- /dev/null +++ b/crates/fire-core/src/rich_text/builder.rs @@ -0,0 +1,305 @@ +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum TextMode { + Normal, + Preformatted, +} + +#[derive(Default)] +struct CookedHtmlBuilder { + next_id: u32, + nodes: Vec, + plain_text: String, + pending_inline_space: bool, + image_urls: Vec, + link_urls: Vec, +} + +impl CookedHtmlBuilder { + fn finish(mut self) -> CookedHtmlDocument { + self.trim_plain_text(); + CookedHtmlDocument { + nodes: self.nodes, + plain_text: self.plain_text, + image_urls: dedupe_preserving_order(self.image_urls), + link_urls: dedupe_preserving_order(self.link_urls), + } + } + + fn visit_node( + &mut self, + node: NodeRef<'_, ScraperNode>, + parent_id: u32, + depth: u32, + text_mode: TextMode, + ) { + match node.value() { + ScraperNode::Text(text) => self.push_text_node(&text.text, parent_id, depth, text_mode), + ScraperNode::Element(_) => { + if let Some(element) = ElementRef::wrap(node) { + self.visit_element(element, parent_id, depth, text_mode); + } + } + _ => {} + } + } + + fn visit_element( + &mut self, + element: ElementRef<'_>, + parent_id: u32, + depth: u32, + text_mode: TextMode, + ) { + let tag = element.value().name(); + if matches!(tag, "script" | "style") { + return; + } + + let classes = element.attr("class").unwrap_or_default(); + // Polls are rendered by native Poll UI from structured post.polls. + // Walking their cooked children leaks option lists + vote labels into body text. + if is_poll_container(tag, classes) { + return; + } + let kind = node_kind_for_element(tag, classes); + let next_text_mode = if tag == "pre" { + TextMode::Preformatted + } else { + text_mode + }; + + if tag == "br" { + let id = self.push_node( + Some(parent_id), + depth + 1, + CookedHtmlNodeKind::LineBreak, + NodeMeta::from_element(element), + ); + self.ensure_line_break(); + self.visit_children(element, id, depth + 1, next_text_mode); + return; + } + + let starts_block = starts_plain_text_block(kind); + let ends_block = ends_plain_text_block(kind); + if starts_block { + self.ensure_block_boundary(); + } + + let effective_parent_id = if let Some(kind) = kind { + let mut meta = NodeMeta::from_element(element); + apply_element_metadata(tag, classes, element, kind, &mut meta); + if let Some(url) = meta.url.as_ref() { + match kind { + CookedHtmlNodeKind::Image | CookedHtmlNodeKind::Emoji => { + self.image_urls.push(url.clone()); + } + CookedHtmlNodeKind::Link + | CookedHtmlNodeKind::Mention + | CookedHtmlNodeKind::Hashtag + | CookedHtmlNodeKind::Attachment + | CookedHtmlNodeKind::Onebox + | CookedHtmlNodeKind::Iframe => { + self.link_urls.push(url.clone()); + } + _ => {} + } + } + + let id = self.push_node(Some(parent_id), depth + 1, kind, meta); + if matches!(kind, CookedHtmlNodeKind::Image | CookedHtmlNodeKind::Emoji) { + self.append_media_alt_text(element); + } + id + } else { + parent_id + }; + + self.visit_children(element, effective_parent_id, depth + 1, next_text_mode); + + match kind { + Some(CookedHtmlNodeKind::ListItem) => self.ensure_line_break(), + Some(CookedHtmlNodeKind::TableCell) => self.append_plain_separator(" "), + Some(CookedHtmlNodeKind::TableRow) => self.ensure_line_break(), + _ if ends_block => self.ensure_block_boundary(), + _ => {} + } + } + + fn visit_children( + &mut self, + element: ElementRef<'_>, + parent_id: u32, + depth: u32, + text_mode: TextMode, + ) { + for child in element.children() { + self.visit_node(child, parent_id, depth, text_mode); + } + } + + fn push_node( + &mut self, + parent_id: Option, + depth: u32, + kind: CookedHtmlNodeKind, + meta: NodeMeta, + ) -> u32 { + let id = self.next_id; + self.next_id += 1; + self.nodes.push(CookedHtmlNode { + id, + parent_id, + kind, + depth, + text: meta.text, + url: meta.url, + title: meta.title, + alt: meta.alt, + level: meta.level, + ordered: meta.ordered, + attributes: meta.attributes, + }); + id + } + + fn push_text_node(&mut self, raw_text: &str, parent_id: u32, depth: u32, text_mode: TextMode) { + let text = if text_mode == TextMode::Preformatted { + normalize_preformatted_text(raw_text) + } else { + normalize_inline_text(raw_text) + }; + if text.is_empty() { + if raw_text.chars().any(char::is_whitespace) { + self.pending_inline_space = true; + } + return; + } + + let id = self.push_node( + Some(parent_id), + depth + 1, + CookedHtmlNodeKind::Text, + NodeMeta { + text: Some(text.clone()), + ..NodeMeta::default() + }, + ); + debug_assert!(self.nodes.iter().any(|node| node.id == id)); + + if text_mode == TextMode::Preformatted { + self.append_preformatted_text(&text); + } else { + self.append_inline_text(raw_text, &text); + } + } + + fn append_media_alt_text(&mut self, element: ElementRef<'_>) { + let alt = element + .attr("alt") + .or_else(|| element.attr("title")) + .map(str::trim) + .filter(|value| !value.is_empty()); + if let Some(alt) = alt { + self.append_inline_text(alt, &normalize_inline_text(alt)); + } + } + + fn append_inline_text(&mut self, raw_text: &str, text: &str) { + if text.is_empty() { + return; + } + + let had_leading_space = raw_text + .chars() + .next() + .is_some_and(|character| character.is_whitespace() || character == '\u{a0}'); + let had_trailing_space = raw_text + .chars() + .last() + .is_some_and(|character| character.is_whitespace() || character == '\u{a0}'); + + if (had_leading_space || self.pending_inline_space) + && !self.plain_text.is_empty() + && !self.plain_text.ends_with(char::is_whitespace) + && !starts_with_closing_punctuation(text) + { + self.plain_text.push(' '); + } + + self.plain_text.push_str(text); + self.pending_inline_space = had_trailing_space; + } + + fn append_preformatted_text(&mut self, text: &str) { + if text.is_empty() { + return; + } + if self.pending_inline_space + && !self.plain_text.is_empty() + && !self.plain_text.ends_with(char::is_whitespace) + { + self.plain_text.push(' '); + } + self.plain_text.push_str(text); + self.pending_inline_space = false; + } + + fn append_plain_separator(&mut self, separator: &str) { + if self.plain_text.is_empty() || self.plain_text.ends_with(char::is_whitespace) { + return; + } + self.plain_text.push_str(separator); + self.pending_inline_space = false; + } + + fn ensure_line_break(&mut self) { + self.trim_plain_text_end(); + if !self.plain_text.is_empty() && !self.plain_text.ends_with('\n') { + self.plain_text.push('\n'); + } + self.pending_inline_space = false; + } + + fn ensure_block_boundary(&mut self) { + self.trim_plain_text_end(); + if self.plain_text.is_empty() { + self.pending_inline_space = false; + return; + } + + let trailing_newlines = self + .plain_text + .chars() + .rev() + .take_while(|character| *character == '\n') + .count(); + for _ in trailing_newlines..2 { + self.plain_text.push('\n'); + } + self.pending_inline_space = false; + } + + fn trim_plain_text_end(&mut self) { + while self + .plain_text + .chars() + .last() + .is_some_and(|character| character == ' ' || character == '\t') + { + self.plain_text.pop(); + } + } + + fn trim_plain_text(&mut self) { + while self + .plain_text + .chars() + .last() + .is_some_and(char::is_whitespace) + { + self.plain_text.pop(); + } + } +} + diff --git a/crates/fire-core/src/rich_text/classify.rs b/crates/fire-core/src/rich_text/classify.rs new file mode 100644 index 00000000..cd8cb5db --- /dev/null +++ b/crates/fire-core/src/rich_text/classify.rs @@ -0,0 +1,125 @@ +fn node_kind_for_element(tag: &str, classes: &str) -> Option { + let has_class = |target: &str| { + classes + .split_ascii_whitespace() + .any(|class| class == target) + }; + let has_class_suffix = |suffix: &str| { + classes + .split_ascii_whitespace() + .any(|class| class.ends_with(suffix)) + }; + + if has_class("spoiler") || has_class("blur") { + return Some(CookedHtmlNodeKind::Spoiler); + } + // `inline-onebox` is an inline title link, not a preview card. The `-onebox` + // suffix would otherwise swallow it and drop the surrounding sentence. + let is_inline_onebox = has_class("inline-onebox") || has_class("inline-onebox-loading"); + if !is_inline_onebox && (has_class("onebox") || has_class_suffix("-onebox")) { + return Some(CookedHtmlNodeKind::Onebox); + } + if has_class("mention") { + return Some(CookedHtmlNodeKind::Mention); + } + if has_class("hashtag") { + return Some(CookedHtmlNodeKind::Hashtag); + } + if has_class("emoji") { + return Some(CookedHtmlNodeKind::Emoji); + } + if has_class("attachment") { + return Some(CookedHtmlNodeKind::Attachment); + } + + match tag { + "p" => Some(CookedHtmlNodeKind::Paragraph), + "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => Some(CookedHtmlNodeKind::Heading), + "br" => Some(CookedHtmlNodeKind::LineBreak), + "strong" | "b" => Some(CookedHtmlNodeKind::Strong), + "em" | "i" => Some(CookedHtmlNodeKind::Emphasis), + "s" | "del" | "strike" => Some(CookedHtmlNodeKind::Strikethrough), + "a" => Some(CookedHtmlNodeKind::Link), + "img" => Some(CookedHtmlNodeKind::Image), + "code" => Some(CookedHtmlNodeKind::Code), + "pre" => Some(CookedHtmlNodeKind::CodeBlock), + "blockquote" => Some(CookedHtmlNodeKind::Blockquote), + "aside" if has_class("quote") => Some(CookedHtmlNodeKind::DiscourseQuote), + "aside" => Some(CookedHtmlNodeKind::Onebox), + "hr" => Some(CookedHtmlNodeKind::Divider), + "ul" | "ol" => Some(CookedHtmlNodeKind::List), + "li" => Some(CookedHtmlNodeKind::ListItem), + "details" => Some(CookedHtmlNodeKind::Details), + "table" => Some(CookedHtmlNodeKind::Table), + "tr" => Some(CookedHtmlNodeKind::TableRow), + "td" | "th" => Some(CookedHtmlNodeKind::TableCell), + "iframe" | "video" => Some(CookedHtmlNodeKind::Iframe), + _ => None, + } +} + +fn is_poll_container(tag: &str, classes: &str) -> bool { + let has_class = |target: &str| { + classes + .split_whitespace() + .any(|class| class.eq_ignore_ascii_case(target)) + }; + // Discourse poll markup variants seen in the wild. + has_class("poll") + || has_class("poll-container") + || has_class("poll-area") + || (tag.eq_ignore_ascii_case("div") && has_class("polls")) +} + +fn starts_plain_text_block(kind: Option) -> bool { + matches!( + kind, + Some( + CookedHtmlNodeKind::Paragraph + | CookedHtmlNodeKind::Heading + | CookedHtmlNodeKind::Blockquote + | CookedHtmlNodeKind::DiscourseQuote + | CookedHtmlNodeKind::List + | CookedHtmlNodeKind::CodeBlock + | CookedHtmlNodeKind::Details + | CookedHtmlNodeKind::Table + | CookedHtmlNodeKind::Onebox + ) + ) +} + +fn ends_plain_text_block(kind: Option) -> bool { + starts_plain_text_block(kind) +} + +fn normalize_inline_text(raw: &str) -> String { + raw.replace('\u{a0}', " ") + .split_whitespace() + .collect::>() + .join(" ") +} + +fn normalize_preformatted_text(raw: &str) -> String { + raw.replace("\r\n", "\n").replace('\u{a0}', " ") +} + +fn starts_with_closing_punctuation(text: &str) -> bool { + text.chars().next().is_some_and(|character| { + matches!( + character, + '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}' + ) + }) +} + +fn dedupe_preserving_order(values: Vec) -> Vec { + let mut result = Vec::new(); + for value in values { + if value.trim().is_empty() || result.contains(&value) { + continue; + } + result.push(value); + } + result +} + diff --git a/crates/fire-core/src/rich_text/metadata.rs b/crates/fire-core/src/rich_text/metadata.rs new file mode 100644 index 00000000..7549cec8 --- /dev/null +++ b/crates/fire-core/src/rich_text/metadata.rs @@ -0,0 +1,96 @@ +#[derive(Default)] +struct NodeMeta { + text: Option, + url: Option, + title: Option, + alt: Option, + level: Option, + ordered: Option, + attributes: BTreeMap, +} + +impl NodeMeta { + fn from_element(element: ElementRef<'_>) -> Self { + let mut attributes = BTreeMap::new(); + for (name, value) in element.value().attrs() { + attributes.insert(name.to_string(), value.to_string()); + } + Self { + title: element.attr("title").map(ToOwned::to_owned), + alt: element.attr("alt").map(ToOwned::to_owned), + attributes, + ..Self::default() + } + } +} + +fn apply_element_metadata( + tag: &str, + classes: &str, + element: ElementRef<'_>, + kind: CookedHtmlNodeKind, + meta: &mut NodeMeta, +) { + match kind { + CookedHtmlNodeKind::Heading => { + meta.level = tag + .strip_prefix('h') + .and_then(|value| value.parse::().ok()); + } + CookedHtmlNodeKind::List => { + meta.ordered = Some(tag == "ol"); + } + CookedHtmlNodeKind::Link + | CookedHtmlNodeKind::Mention + | CookedHtmlNodeKind::Hashtag + | CookedHtmlNodeKind::Attachment => { + meta.url = element.attr("href").map(ToOwned::to_owned); + } + CookedHtmlNodeKind::Image | CookedHtmlNodeKind::Emoji => { + meta.url = element.attr("src").map(ToOwned::to_owned); + } + CookedHtmlNodeKind::Iframe => { + meta.url = element.attr("src").map(ToOwned::to_owned); + } + CookedHtmlNodeKind::Onebox => { + meta.url = element + .attr("href") + .or_else(|| element.attr("data-onebox-src")) + .or_else(|| element.attr("data-original-href")) + .map(ToOwned::to_owned); + if meta.title.is_none() { + meta.title = first_meaningful_text(element); + } + } + CookedHtmlNodeKind::DiscourseQuote => { + meta.title = element + .attr("data-username") + .or_else(|| element.attr("data-user-card")) + .map(ToOwned::to_owned) + .or_else(|| first_meaningful_text(element)); + } + _ => {} + } + + if classes + .split_ascii_whitespace() + .any(|class| class == "onebox" || class.ends_with("-onebox")) + && meta.url.is_none() + { + meta.url = element + .attr("href") + .or_else(|| element.attr("data-onebox-src")) + .or_else(|| element.attr("data-original-href")) + .map(ToOwned::to_owned); + } +} + +fn first_meaningful_text(element: ElementRef<'_>) -> Option { + let text = normalize_inline_text(&element.text().collect::>().join(" ")); + if text.is_empty() { + None + } else { + Some(text) + } +} + diff --git a/crates/fire-core/src/rich_text/mod.rs b/crates/fire-core/src/rich_text/mod.rs new file mode 100644 index 00000000..03292aa8 --- /dev/null +++ b/crates/fire-core/src/rich_text/mod.rs @@ -0,0 +1,20 @@ +use std::collections::BTreeMap; + +use ego_tree::NodeRef; +use fire_models::{CookedHtmlDocument, CookedHtmlNode, CookedHtmlNodeKind, RenderDocument}; +use std::sync::Arc; + +use fire_models::{ + AttachedPresentation, ChatMessage, PresentedDocument, TopicPost, TopicPostBoost, +}; +use fire_rich_text::{present_owned_document, render_document as shared_render_document}; +use html5ever::tendril::TendrilSink; +use html5ever::{local_name, ns, QualName}; +use scraper::{ElementRef, Html, HtmlTreeSink, Node as ScraperNode}; + +include!("parse.rs"); +include!("attach.rs"); +include!("builder.rs"); +include!("metadata.rs"); +include!("classify.rs"); +include!("tests.rs"); diff --git a/crates/fire-core/src/rich_text/parse.rs b/crates/fire-core/src/rich_text/parse.rs new file mode 100644 index 00000000..1c2d9a92 --- /dev/null +++ b/crates/fire-core/src/rich_text/parse.rs @@ -0,0 +1,45 @@ +pub fn parse_cooked_html(raw_html: &str) -> CookedHtmlDocument { + let html = parse_fragment(raw_html); + let mut builder = CookedHtmlBuilder::default(); + let root_id = builder.push_node(None, 0, CookedHtmlNodeKind::Document, NodeMeta::default()); + + let root = html.root_element(); + for child in root.children() { + builder.visit_node(child, root_id, 0, TextMode::Normal); + } + + builder.finish() +} + +pub fn render_cooked_html(raw_html: &str, base_url: &str) -> RenderDocument { + let document = parse_cooked_html(raw_html); + shared_render_document(&document, base_url) +} + +/// Parse cooked HTML and produce the host display plan. +/// +/// Empty input is absence, not an empty presentation. The returned +/// [`PresentedDocument`] keeps the IR for a future handle; callers that only +/// cross UniFFI should lift `into_presentation()`. +pub fn present_cooked_html(raw_html: &str, base_url: &str) -> Option { + let trimmed = raw_html.trim(); + if trimmed.is_empty() { + None + } else { + Some(present_owned_document(render_cooked_html( + trimmed, base_url, + ))) + } +} + +fn parse_fragment(raw_html: &str) -> Html { + let parser = html5ever::parse_fragment( + HtmlTreeSink::new(Html::new_fragment()), + html5ever::ParseOpts::default(), + QualName::new(None, ns!(html), local_name!("body")), + Vec::new(), + false, + ); + parser.one(raw_html) +} + diff --git a/crates/fire-core/src/rich_text/tests.rs b/crates/fire-core/src/rich_text/tests.rs new file mode 100644 index 00000000..59e5d5b2 --- /dev/null +++ b/crates/fire-core/src/rich_text/tests.rs @@ -0,0 +1,178 @@ +#[cfg(test)] +mod tests { + use fire_models::{CookedHtmlNodeKind, TopicPost}; + + use super::{ + attach_post_presentation, parse_cooked_html, present_cooked_html, render_cooked_html, + }; + + #[test] + fn parses_common_discourse_cooked_html_into_nodes() { + let document = parse_cooked_html( + r#" +

Hello Fire
topic

+

diagram

+
  • Rust
  • Android
+ "#, + ); + + assert_eq!( + document.plain_text, + "Hello Fire\ntopic\n\ndiagram\n\nRust\nAndroid" + ); + assert_eq!( + document.image_urls, + vec!["/uploads/default/original/1X/fire.png".to_string()] + ); + assert_eq!(document.link_urls, vec!["/t/123/4".to_string()]); + assert!(document + .nodes + .iter() + .any(|node| node.kind == CookedHtmlNodeKind::Strong)); + assert!(document + .nodes + .iter() + .any(|node| node.kind == CookedHtmlNodeKind::ListItem)); + } + + #[test] + fn skips_poll_container_markup_so_native_poll_ui_is_not_duplicated() { + let document = parse_cooked_html( + r#" +

开个贴看看

+
+
    +
  • 0-10
  • +
  • 11-20
  • +
  • 61以上
  • +
+
1175 投票人
+
+

补充说明

+ "#, + ); + + assert_eq!(document.plain_text, "开个贴看看\n\n补充说明"); + assert!(!document.plain_text.contains("0-10")); + assert!(!document.plain_text.contains("投票人")); + assert!(!document + .nodes + .iter() + .any(|node| node.kind == CookedHtmlNodeKind::ListItem)); + } + + #[test] + fn parses_discourse_quote_details_table_and_onebox_metadata() { + let document = parse_cooked_html( + r#" + +
More

hidden text

+
AB
+ + "#, + ); + + let quote = document + .nodes + .iter() + .find(|node| node.kind == CookedHtmlNodeKind::DiscourseQuote) + .expect("quote node"); + assert_eq!(quote.title.as_deref(), Some("alice")); + assert_eq!( + quote.attributes.get("data-post").map(String::as_str), + Some("2") + ); + assert!(document + .nodes + .iter() + .any(|node| node.kind == CookedHtmlNodeKind::Details)); + assert!(document + .nodes + .iter() + .any(|node| node.kind == CookedHtmlNodeKind::TableCell)); + assert!(document.nodes.iter().any(|node| { + node.kind == CookedHtmlNodeKind::Onebox + && node.url.as_deref() == Some("https://example.com/card") + })); + } + + #[test] + fn inline_onebox_stays_a_link_and_block_onebox_keeps_chrome_out_of_images() { + let rendered = render_cooked_html( + r#" + +

后文 GitHub Topics Clock

+ "#, + "https://linux.do", + ); + + assert!(rendered.image_attachments.is_empty()); + assert!(rendered.blocks.iter().any(|block| matches!( + &block.kind, + fire_models::RenderBlockKind::Onebox { + source_name: Some(source_name), + icon_url: Some(icon_url), + thumbnail_url: Some(thumbnail_url), + title: Some(title), + .. + } if source_name == "bilibili.com" + && icon_url == "https://www.bilibili.com/favicon.ico" + && thumbnail_url == "https://i0.hdslb.com/bfs/archive/cover.jpg" + && title == "开源神器" + ))); + assert!(rendered.blocks.iter().any(|block| matches!( + &block.kind, + fire_models::RenderBlockKind::Link { url } if url == "https://github.com/topics/clock" + ))); + assert_eq!( + rendered + .blocks + .iter() + .filter(|block| matches!(block.kind, fire_models::RenderBlockKind::Onebox { .. })) + .count(), + 1 + ); + let segments = fire_rich_text::display_segments(&rendered); + assert!(segments + .iter() + .all(|segment| !matches!(segment, fire_models::RenderUiSegment::Image(_)))); + } + + #[test] + fn present_cooked_html_skips_blank_input_and_keeps_ui_plan() { + assert!(present_cooked_html(" ", "https://linux.do").is_none()); + + let presented = present_cooked_html("

Hello Fire

", "https://linux.do") + .expect("non-empty cooked html should present"); + assert_eq!(presented.presentation().plain_text, "Hello Fire"); + assert!(!presented.presentation().segments.is_empty()); + } + + #[test] + fn attach_post_presentation_reuses_arc_when_cooked_is_unchanged() { + let mut first = TopicPost { + cooked: "

Hello Fire

".to_string(), + ..TopicPost::default() + }; + attach_post_presentation(&mut first, "https://linux.do"); + let original = first.presented.arc().expect("presented"); + + let mut second = first.clone(); + second.like_count = 4; + second.reuse_presentation_from(&first); + let reused = second.presented.arc().expect("reused"); + assert!(std::sync::Arc::ptr_eq(&original, &reused)); + } +} diff --git a/crates/fire-core/src/topic_payloads/list/bookmarks.rs b/crates/fire-core/src/topic_payloads/list/bookmarks.rs new file mode 100644 index 00000000..2e5d4259 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/list/bookmarks.rs @@ -0,0 +1,171 @@ +#[derive(Debug, Default, Deserialize)] +struct RawTopicUser { + #[serde(default, deserialize_with = "deserialize_default_u64")] + id: u64, + #[serde(default, deserialize_with = "deserialize_default_string")] + username: String, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + avatar_template: Option, +} + +impl From for TopicUser { + fn from(value: RawTopicUser) -> Self { + Self { + id: value.id, + username: value.username, + avatar_template: value.avatar_template, + } + } +} + +#[derive(Debug, Default, Deserialize)] +struct RawUserBookmarkEntry { + #[serde(default, deserialize_with = "deserialize_default_u64")] + id: u64, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + name: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + reminder_at: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + bookmarkable_type: Option, + #[serde(default, deserialize_with = "deserialize_optional_u64")] + bookmarkable_id: Option, + #[serde(default, deserialize_with = "deserialize_optional_u64")] + topic_id: Option, + #[serde(default, deserialize_with = "deserialize_optional_u32")] + linked_post_number: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + title: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + fancy_title: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + slug: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + excerpt: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + created_at: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + bumped_at: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + last_posted_at: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + last_poster_username: Option, + #[serde(default, deserialize_with = "deserialize_optional_u64")] + category_id: Option, + #[serde(default, deserialize_with = "deserialize_optional_u32")] + posts_count: Option, + #[serde(default, deserialize_with = "deserialize_optional_u32")] + reply_count: Option, + #[serde(default, deserialize_with = "deserialize_optional_u32")] + highest_post_number: Option, + #[serde(default, deserialize_with = "deserialize_default_u32")] + views: u32, + #[serde(default, deserialize_with = "deserialize_default_u32")] + like_count: u32, + #[serde(default, deserialize_with = "deserialize_default_bool")] + pinned: bool, + #[serde( + default = "default_visible", + deserialize_with = "deserialize_default_true_bool" + )] + visible: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + closed: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + archived: bool, + #[serde(default, deserialize_with = "deserialize_topic_tags")] + tags: Vec, + #[serde(default, deserialize_with = "deserialize_optional_u32")] + last_read_post_number: Option, + #[serde(default, deserialize_with = "deserialize_optional_record")] + user: Option, +} + +impl RawUserBookmarkEntry { + fn into_topic_summary(self, users: &mut Vec) -> Option { + let topic_id = self.topic_id.or_else(|| { + if self.bookmarkable_type.as_deref() == Some("Topic") { + self.bookmarkable_id + } else { + None + } + })?; + if topic_id == 0 { + return None; + } + + let bookmark_name = normalized_scalar(self.name.as_deref()); + let title = normalized_scalar(self.title.as_deref()) + .or_else(|| normalized_scalar(self.fancy_title.as_deref())) + .or_else(|| bookmark_name.clone()) + .unwrap_or_else(|| format!("Topic {topic_id}")); + let posts_count = self + .posts_count + .or(self.highest_post_number) + .unwrap_or(1) + .max(1); + let reply_count = self + .reply_count + .unwrap_or_else(|| posts_count.saturating_sub(1)); + let bookmarked_post_number = match self.bookmarkable_type.as_deref() { + Some("Post") => self.linked_post_number, + _ => None, + }; + + let user = self.user; + let last_poster_username = self + .last_poster_username + .or_else(|| user.as_ref().map(|user| user.username.clone())); + let posters = user + .as_ref() + .map(|user| { + vec![RawTopicPoster { + user_id: user.id, + description: Some("Original Poster".into()), + extras: Some("latest".into()), + }] + }) + .unwrap_or_default(); + + if let Some(user) = user { + if !users.iter().any(|existing| existing.id == user.id) { + users.push(user); + } + } + + Some(RawTopicSummary { + id: topic_id, + title, + slug: self.slug.unwrap_or_default(), + posts_count, + reply_count, + views: self.views, + like_count: self.like_count, + excerpt: self.excerpt, + created_at: self.created_at.clone(), + last_posted_at: self.last_posted_at.or(self.bumped_at).or(self.created_at), + last_poster_username, + category_id: self.category_id, + pinned: self.pinned, + visible: self.visible, + closed: self.closed, + archived: self.archived, + tags: self.tags, + posters, + participants: Vec::new(), + unseen: false, + unread_posts: 0, + new_posts: 0, + last_read_post_number: self.last_read_post_number, + highest_post_number: self.highest_post_number.unwrap_or(posts_count), + bookmarked_post_number, + bookmark_id: Some(self.id), + bookmark_name, + bookmark_reminder_at: self.reminder_at, + bookmarkable_type: self.bookmarkable_type, + has_accepted_answer: false, + can_have_answer: false, + }) + } +} + diff --git a/crates/fire-core/src/topic_payloads/list/mod.rs b/crates/fire-core/src/topic_payloads/list/mod.rs new file mode 100644 index 00000000..e4977f95 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/list/mod.rs @@ -0,0 +1,19 @@ +use fire_models::{ + TopicListResponse, TopicParticipant, TopicPoster, TopicRow, TopicSummary, TopicTag, TopicUser, +}; +use serde::Deserialize; +use std::collections::HashMap; +use time::{format_description::well_known::Rfc3339, OffsetDateTime}; + +use super::deser::{ + deserialize_default_bool, deserialize_default_record, deserialize_default_sequence, + deserialize_default_string, deserialize_default_true_bool, deserialize_default_u32, + deserialize_default_u64, deserialize_optional_record, deserialize_optional_scalar_string, + deserialize_optional_u32, deserialize_optional_u64, deserialize_topic_tags, +}; +use crate::preview_text_from_html; +use crate::topic_status_labels; + +include!("topics.rs"); +include!("bookmarks.rs"); +include!("participants.rs"); diff --git a/crates/fire-core/src/topic_payloads/list/participants.rs b/crates/fire-core/src/topic_payloads/list/participants.rs new file mode 100644 index 00000000..06cfbde1 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/list/participants.rs @@ -0,0 +1,48 @@ +#[derive(Debug, Default, Deserialize)] +struct RawTopicPoster { + #[serde(default, deserialize_with = "deserialize_default_u64")] + user_id: u64, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + description: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + extras: Option, +} + +impl From for TopicPoster { + fn from(value: RawTopicPoster) -> Self { + Self { + user_id: value.user_id, + description: value.description, + extras: value.extras, + } + } +} + +#[derive(Debug, Default, Deserialize)] +pub(super) struct RawTopicParticipant { + #[serde( + default, + alias = "id", + alias = "user_id", + deserialize_with = "deserialize_default_u64" + )] + user_id: u64, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + username: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + name: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + avatar_template: Option, +} + +impl From for TopicParticipant { + fn from(value: RawTopicParticipant) -> Self { + Self { + user_id: value.user_id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + diff --git a/crates/fire-core/src/topic_payloads/list.rs b/crates/fire-core/src/topic_payloads/list/topics.rs similarity index 57% rename from crates/fire-core/src/topic_payloads/list.rs rename to crates/fire-core/src/topic_payloads/list/topics.rs index 9af2ed03..6b7c3ed7 100644 --- a/crates/fire-core/src/topic_payloads/list.rs +++ b/crates/fire-core/src/topic_payloads/list/topics.rs @@ -1,19 +1,3 @@ -use fire_models::{ - TopicListResponse, TopicParticipant, TopicPoster, TopicRow, TopicSummary, TopicTag, TopicUser, -}; -use serde::Deserialize; -use std::collections::HashMap; -use time::{format_description::well_known::Rfc3339, OffsetDateTime}; - -use super::deser::{ - deserialize_default_bool, deserialize_default_record, deserialize_default_sequence, - deserialize_default_string, deserialize_default_true_bool, deserialize_default_u32, - deserialize_default_u64, deserialize_optional_record, deserialize_optional_scalar_string, - deserialize_optional_u32, deserialize_optional_u64, deserialize_topic_tags, -}; -use crate::preview_text_from_html; -use crate::topic_status_labels; - #[derive(Debug, Default, Deserialize)] pub(crate) struct RawTopicListResponse { #[serde(default, deserialize_with = "deserialize_default_record")] @@ -84,225 +68,6 @@ struct RawUserBookmarkList { more_bookmarks_url: Option, } -#[derive(Debug, Default, Deserialize)] -struct RawTopicUser { - #[serde(default, deserialize_with = "deserialize_default_u64")] - id: u64, - #[serde(default, deserialize_with = "deserialize_default_string")] - username: String, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - avatar_template: Option, -} - -impl From for TopicUser { - fn from(value: RawTopicUser) -> Self { - Self { - id: value.id, - username: value.username, - avatar_template: value.avatar_template, - } - } -} - -#[derive(Debug, Default, Deserialize)] -struct RawUserBookmarkEntry { - #[serde(default, deserialize_with = "deserialize_default_u64")] - id: u64, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - name: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - reminder_at: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - bookmarkable_type: Option, - #[serde(default, deserialize_with = "deserialize_optional_u64")] - bookmarkable_id: Option, - #[serde(default, deserialize_with = "deserialize_optional_u64")] - topic_id: Option, - #[serde(default, deserialize_with = "deserialize_optional_u32")] - linked_post_number: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - title: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - fancy_title: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - slug: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - excerpt: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - created_at: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - bumped_at: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - last_posted_at: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - last_poster_username: Option, - #[serde(default, deserialize_with = "deserialize_optional_u64")] - category_id: Option, - #[serde(default, deserialize_with = "deserialize_optional_u32")] - posts_count: Option, - #[serde(default, deserialize_with = "deserialize_optional_u32")] - reply_count: Option, - #[serde(default, deserialize_with = "deserialize_optional_u32")] - highest_post_number: Option, - #[serde(default, deserialize_with = "deserialize_default_u32")] - views: u32, - #[serde(default, deserialize_with = "deserialize_default_u32")] - like_count: u32, - #[serde(default, deserialize_with = "deserialize_default_bool")] - pinned: bool, - #[serde( - default = "default_visible", - deserialize_with = "deserialize_default_true_bool" - )] - visible: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - closed: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - archived: bool, - #[serde(default, deserialize_with = "deserialize_topic_tags")] - tags: Vec, - #[serde(default, deserialize_with = "deserialize_optional_u32")] - last_read_post_number: Option, - #[serde(default, deserialize_with = "deserialize_optional_record")] - user: Option, -} - -impl RawUserBookmarkEntry { - fn into_topic_summary(self, users: &mut Vec) -> Option { - let topic_id = self.topic_id.or_else(|| { - if self.bookmarkable_type.as_deref() == Some("Topic") { - self.bookmarkable_id - } else { - None - } - })?; - if topic_id == 0 { - return None; - } - - let bookmark_name = normalized_scalar(self.name.as_deref()); - let title = normalized_scalar(self.title.as_deref()) - .or_else(|| normalized_scalar(self.fancy_title.as_deref())) - .or_else(|| bookmark_name.clone()) - .unwrap_or_else(|| format!("Topic {topic_id}")); - let posts_count = self - .posts_count - .or(self.highest_post_number) - .unwrap_or(1) - .max(1); - let reply_count = self - .reply_count - .unwrap_or_else(|| posts_count.saturating_sub(1)); - let bookmarked_post_number = match self.bookmarkable_type.as_deref() { - Some("Post") => self.linked_post_number, - _ => None, - }; - - let user = self.user; - let last_poster_username = self - .last_poster_username - .or_else(|| user.as_ref().map(|user| user.username.clone())); - let posters = user - .as_ref() - .map(|user| { - vec![RawTopicPoster { - user_id: user.id, - description: Some("Original Poster".into()), - extras: Some("latest".into()), - }] - }) - .unwrap_or_default(); - - if let Some(user) = user { - if !users.iter().any(|existing| existing.id == user.id) { - users.push(user); - } - } - - Some(RawTopicSummary { - id: topic_id, - title, - slug: self.slug.unwrap_or_default(), - posts_count, - reply_count, - views: self.views, - like_count: self.like_count, - excerpt: self.excerpt, - created_at: self.created_at.clone(), - last_posted_at: self.last_posted_at.or(self.bumped_at).or(self.created_at), - last_poster_username, - category_id: self.category_id, - pinned: self.pinned, - visible: self.visible, - closed: self.closed, - archived: self.archived, - tags: self.tags, - posters, - participants: Vec::new(), - unseen: false, - unread_posts: 0, - new_posts: 0, - last_read_post_number: self.last_read_post_number, - highest_post_number: self.highest_post_number.unwrap_or(posts_count), - bookmarked_post_number, - bookmark_id: Some(self.id), - bookmark_name, - bookmark_reminder_at: self.reminder_at, - bookmarkable_type: self.bookmarkable_type, - has_accepted_answer: false, - can_have_answer: false, - }) - } -} - -#[derive(Debug, Default, Deserialize)] -struct RawTopicPoster { - #[serde(default, deserialize_with = "deserialize_default_u64")] - user_id: u64, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - description: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - extras: Option, -} - -impl From for TopicPoster { - fn from(value: RawTopicPoster) -> Self { - Self { - user_id: value.user_id, - description: value.description, - extras: value.extras, - } - } -} - -#[derive(Debug, Default, Deserialize)] -pub(super) struct RawTopicParticipant { - #[serde( - default, - alias = "id", - alias = "user_id", - deserialize_with = "deserialize_default_u64" - )] - user_id: u64, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - username: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - name: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - avatar_template: Option, -} - -impl From for TopicParticipant { - fn from(value: RawTopicParticipant) -> Self { - Self { - user_id: value.user_id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - #[derive(Debug, Default, Deserialize)] struct RawTopicSummary { #[serde(default, deserialize_with = "deserialize_default_u64")] diff --git a/crates/fire-core/src/topic_payloads/mod.rs b/crates/fire-core/src/topic_payloads/mod.rs index dfb63334..959b5bfa 100644 --- a/crates/fire-core/src/topic_payloads/mod.rs +++ b/crates/fire-core/src/topic_payloads/mod.rs @@ -18,189 +18,4 @@ pub(crate) use post::{ }; #[cfg(test)] -mod tests { - use super::*; - use fire_models::TopicThread; - use serde_json::json; - - fn sample_raw_topic_detail() -> RawTopicDetail { - serde_json::from_value(json!({ - "id": 42, - "title": "Topic", - "slug": "topic", - "posts_count": 2, - "post_stream": { - "posts": [ - { - "id": 101, - "username": "alice", - "cooked": "

root

", - "post_number": 1, - "reply_count": 1, - "can_boost": true, - "boosts": [ - { - "id": 501, - "cooked": "

Hello \":wave:\"

", - "user": { - "id": 7, - "username": "carol", - "name": "Carol", - "avatar_template": "/user_avatar/linux.do/carol/{size}/1.png" - }, - "can_delete": true, - "can_flag": true, - "user_flag_status": 0, - "available_flags": ["off_topic", 9] - } - ] - }, - { - "id": 102, - "username": "bob", - "cooked": "

reply

", - "post_number": 2, - "reply_to_post_number": 1 - } - ], - "stream": [101, 102] - }, - "details": {} - })) - .expect("sample topic detail should deserialize") - } - - #[test] - fn lightweight_topic_detail_skips_thread_state() { - let detail = sample_raw_topic_detail().into_topic_detail(false, "https://linux.do"); - - assert_eq!(detail.thread, TopicThread::default()); - assert!(detail.flat_posts.is_empty()); - assert!(detail.timeline_entries.is_empty()); - assert_eq!(detail.post_stream.posts.len(), 2); - } - - #[test] - fn full_topic_detail_preserves_thread_state() { - let detail = sample_raw_topic_detail().into_topic_detail(true, "https://linux.do"); - - assert_eq!(detail.thread.original_post_number, Some(1)); - assert_eq!(detail.flat_posts.len(), 2); - assert!(detail.timeline_entries.is_empty()); - } - - #[test] - fn parse_topic_post_boost_value_accepts_wrapped_and_flat_payloads() { - let wrapped = serde_json::json!({ - "boost": { - "id": 42, - "cooked": "

nice

", - "user": { "id": 7, "username": "alice", "name": "Alice" }, - "can_delete": true, - "can_flag": false - } - }); - let boost = parse_topic_post_boost_value(wrapped).expect("wrapped boost"); - assert_eq!(boost.id, 42); - assert_eq!(boost.user.username, "alice"); - assert!(boost.can_delete); - - let flat = serde_json::json!({ - "id": 43, - "cooked": "

🔥

", - "user": { "id": 8, "username": "bob" } - }); - let boost = parse_topic_post_boost_value(flat).expect("flat boost"); - assert_eq!(boost.id, 43); - assert_eq!(boost.user.username, "bob"); - } - - #[test] - fn topic_post_boosts_parse_display_text_and_permissions() { - let detail = sample_raw_topic_detail().into_topic_detail(false, "https://linux.do"); - let post = detail - .post_stream - .posts - .iter() - .find(|post| post.id == 101) - .expect("root post"); - - assert!(post.can_boost); - assert_eq!(post.boosts.len(), 1); - let boost = &post.boosts[0]; - assert_eq!(boost.id, 501); - assert_eq!(boost.display_text, "Hello :wave:"); - assert_eq!(boost.user.username, "carol"); - assert_eq!(boost.user.name.as_deref(), Some("Carol")); - assert!(boost.can_delete); - assert!(boost.can_flag); - assert_eq!(boost.user_flag_status, Some(0)); - assert_eq!(boost.available_flags, ["off_topic", "9"]); - } - - #[test] - fn topic_post_boost_display_text_normalizes_emoji_images_without_alt() { - let detail = serde_json::from_value::(json!({ - "id": 42, - "title": "Topic", - "slug": "topic", - "post_stream": { - "posts": [ - { - "id": 101, - "username": "alice", - "cooked": "

root

", - "post_number": 1, - "boosts": [ - { - "id": 501, - "cooked": "

🎉

", - "user": {"id": 7, "username": "carol"} - } - ] - } - ], - "stream": [101] - }, - "details": {} - })) - .expect("sample topic detail should deserialize") - .into_topic_detail(false, "https://linux.do"); - let boost = &detail.post_stream.posts[0].boosts[0]; - - assert_eq!(boost.display_text, ":smile: :wave:t3: 🎉"); - } - - #[test] - fn topic_post_boost_display_text_strips_leading_attribution() { - let detail = serde_json::from_value::(json!({ - "id": 42, - "title": "Topic", - "slug": "topic", - "post_stream": { - "posts": [ - { - "id": 101, - "username": "alice", - "cooked": "

root

", - "post_number": 1, - "boosts": [ - { - "id": 501, - "cooked": "

@carol: Thanks for the detail

", - "user": {"id": 7, "username": "carol", "name": "Carol"} - } - ] - } - ], - "stream": [101] - }, - "details": {} - })) - .expect("sample topic detail should deserialize") - .into_topic_detail(false, "https://linux.do"); - let boost = &detail.post_stream.posts[0].boosts[0]; - - assert_eq!(boost.display_text, "Thanks for the detail"); - } -} +mod tests; diff --git a/crates/fire-core/src/topic_payloads/post.rs b/crates/fire-core/src/topic_payloads/post.rs deleted file mode 100644 index e7ad2910..00000000 --- a/crates/fire-core/src/topic_payloads/post.rs +++ /dev/null @@ -1,596 +0,0 @@ -use fire_models::{ - Poll, PostReactionUpdate, ReactionUser, ReactionUsersGroup, TopicPost, TopicPostAuthorMetadata, - TopicPostBoost, TopicPostBoostUser, TopicReaction, TopicReplyToUser, -}; -use serde::Deserialize; -use serde_json::Value; -use std::collections::HashMap; - -use super::deser::{ - deserialize_default_bool, deserialize_default_i32, deserialize_default_record, - deserialize_default_sequence, deserialize_default_string, deserialize_default_string_sequence, - deserialize_default_u32, deserialize_default_u64, deserialize_optional_bool, - deserialize_optional_i32, deserialize_optional_record, deserialize_optional_scalar_string, - deserialize_optional_string_sequence_map, deserialize_optional_u32, deserialize_optional_u64, -}; -use super::list::normalized_scalar; -use super::poll::RawPoll; -use crate::json_helpers::{ - integer_u32, integer_u64, invalid_json, parse_array_items_lossy, scalar_string, -}; - -fn boost_display_text(cooked: &str, user: &RawTopicPostBoostUser) -> String { - let plain_text = crate::present_cooked_html(cooked, "https://linux.do") - .map(|presented| presented.presentation().plain_text.clone()) - .unwrap_or_default(); - let body_text = strip_boost_leading_attribution(&plain_text, user); - separate_boost_emoji_shortcodes(&body_text) - .split_whitespace() - .collect::>() - .join(" ") -} - -fn strip_boost_leading_attribution(value: &str, user: &RawTopicPostBoostUser) -> String { - let trimmed = value.trim_start(); - if trimmed.is_empty() { - return String::new(); - } - - let candidates = [ - normalized_scalar(Some(user.username.as_str())).map(|username| format!("@{username}:")), - normalized_scalar(Some(user.username.as_str())).map(|username| format!("{username}:")), - normalized_scalar(user.name.as_deref()).map(|name| format!("{name}:")), - normalized_scalar(Some(user.username.as_str())).map(|username| format!("@{username}:")), - normalized_scalar(Some(user.username.as_str())).map(|username| format!("{username}:")), - normalized_scalar(user.name.as_deref()).map(|name| format!("{name}:")), - ]; - - for candidate in candidates.into_iter().flatten() { - if trimmed - .get(..candidate.len()) - .is_some_and(|prefix| prefix.eq_ignore_ascii_case(&candidate)) - { - return trimmed[candidate.len()..].trim_start().to_string(); - } - } - - let Some(rest) = trimmed.strip_prefix('@') else { - return trimmed.to_string(); - }; - let Some(colon_index_after_at) = rest.find([':', ':']) else { - return trimmed.to_string(); - }; - let username = &rest[..colon_index_after_at]; - if !username.is_empty() - && username.len() <= 40 - && username.chars().all(|character| !character.is_whitespace()) - { - let colon_width = rest[colon_index_after_at..] - .chars() - .next() - .map(char::len_utf8) - .unwrap_or(1); - let colon_end_index = 1 + colon_index_after_at + colon_width; - return trimmed[colon_end_index..].trim_start().to_string(); - } - - trimmed.to_string() -} - -fn separate_boost_emoji_shortcodes(value: &str) -> String { - let mut result = String::with_capacity(value.len()); - let mut index = 0; - - while index < value.len() { - let remaining = &value[index..]; - if let Some((shortcode, next_index)) = boost_emoji_shortcode_at(value, index) { - if result - .chars() - .last() - .is_some_and(|character| !character.is_whitespace()) - { - result.push(' '); - } - result.push_str(shortcode); - if value[next_index..] - .chars() - .next() - .is_some_and(|character| !character.is_whitespace()) - { - result.push(' '); - } - index = next_index; - continue; - } - - let character = remaining - .chars() - .next() - .expect("remaining string is non-empty"); - result.push(character); - index += character.len_utf8(); - } - - result -} - -fn boost_emoji_shortcode_at(value: &str, index: usize) -> Option<(&str, usize)> { - let remaining = value.get(index..)?; - let after_open = remaining.strip_prefix(':')?; - for (end, character) in after_open.char_indices() { - if character != ':' { - continue; - } - let name = &after_open[..end]; - if !is_boost_emoji_shortcode_name(name) { - continue; - } - let next_index = index + end + 2; - let next_character = value[next_index..].chars().next(); - if next_character.is_some_and(is_boost_emoji_shortcode_component_character) { - continue; - } - return Some((&value[index..next_index], next_index)); - } - None -} - -fn is_boost_emoji_shortcode_name(value: &str) -> bool { - !value.is_empty() - && value.split(':').all(|component| { - !component.is_empty() - && component - .chars() - .all(is_boost_emoji_shortcode_component_character) - }) -} - -fn is_boost_emoji_shortcode_component_character(character: char) -> bool { - character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '+') -} - -#[derive(Debug, Default, Deserialize)] -struct RawTopicReaction { - #[serde(default, deserialize_with = "deserialize_default_string")] - id: String, - #[serde(rename = "type")] - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - kind: Option, - #[serde(default, deserialize_with = "deserialize_default_u32")] - count: u32, - #[serde(default, deserialize_with = "deserialize_optional_bool")] - can_undo: Option, -} - -impl From for TopicReaction { - fn from(value: RawTopicReaction) -> Self { - Self { - id: value.id, - kind: value.kind, - count: value.count, - can_undo: value.can_undo, - } - } -} - -#[derive(Debug, Default, Deserialize)] -struct RawPostReactionUpdate { - #[serde(default, deserialize_with = "deserialize_default_sequence")] - reactions: Vec, - #[serde(default, deserialize_with = "deserialize_optional_record")] - current_user_reaction: Option, -} - -impl From for PostReactionUpdate { - fn from(value: RawPostReactionUpdate) -> Self { - Self { - reactions: value.reactions.into_iter().map(Into::into).collect(), - current_user_reaction: value.current_user_reaction.map(Into::into), - } - } -} - -#[derive(Debug, Default, Deserialize)] -struct RawTopicReplyToUser { - #[serde(default, deserialize_with = "deserialize_default_string")] - username: String, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - name: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - avatar_template: Option, -} - -impl From for TopicReplyToUser { - fn from(value: RawTopicReplyToUser) -> Self { - Self { - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -#[derive(Debug, Default, Deserialize)] -struct RawTopicPostUserStatus { - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - emoji: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - description: Option, -} - -#[derive(Debug, Default, Deserialize)] -struct RawTopicPostBoostUser { - #[serde(default, deserialize_with = "deserialize_default_u64")] - id: u64, - #[serde(default, deserialize_with = "deserialize_default_string")] - username: String, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - name: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - avatar_template: Option, -} - -impl From for TopicPostBoostUser { - fn from(value: RawTopicPostBoostUser) -> Self { - Self { - id: value.id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -#[derive(Debug, Default, Deserialize)] -struct RawTopicPostBoost { - #[serde(default, deserialize_with = "deserialize_default_u64")] - id: u64, - #[serde(default, deserialize_with = "deserialize_default_string")] - cooked: String, - #[serde(default, deserialize_with = "deserialize_default_record")] - user: RawTopicPostBoostUser, - #[serde(default, deserialize_with = "deserialize_default_bool")] - can_delete: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - can_flag: bool, - #[serde(default, deserialize_with = "deserialize_optional_i32")] - user_flag_status: Option, - #[serde(default, deserialize_with = "deserialize_default_string_sequence")] - available_flags: Vec, -} - -impl From for TopicPostBoost { - fn from(value: RawTopicPostBoost) -> Self { - let presented = crate::present_cooked_html(&value.cooked, "https://linux.do"); - let display_text = presented - .as_ref() - .map(|document| { - let body_text = strip_boost_leading_attribution( - &document.presentation().plain_text, - &value.user, - ); - separate_boost_emoji_shortcodes(&body_text) - .split_whitespace() - .collect::>() - .join(" ") - }) - .unwrap_or_else(|| boost_display_text(&value.cooked, &value.user)); - Self { - id: value.id, - cooked: value.cooked, - display_text, - user: value.user.into(), - can_delete: value.can_delete, - can_flag: value.can_flag, - user_flag_status: value.user_flag_status, - available_flags: value.available_flags, - presented: presented - .map(|document| { - fire_models::AttachedPresentation::some(std::sync::Arc::new(document)) - }) - .unwrap_or_default(), - } - } -} - -#[derive(Debug, Default, Deserialize)] -pub(super) struct RawTopicPost { - #[serde(default, deserialize_with = "deserialize_default_u64")] - id: u64, - #[serde(default, deserialize_with = "deserialize_default_string")] - username: String, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - name: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - avatar_template: Option, - #[serde(default, deserialize_with = "deserialize_optional_u64")] - user_id: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - user_title: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - primary_group_name: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - flair_url: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - flair_name: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - flair_bg_color: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - flair_color: Option, - #[serde(default, deserialize_with = "deserialize_optional_u64")] - flair_group_id: Option, - #[serde(default, deserialize_with = "deserialize_default_bool")] - moderator: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - admin: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - group_moderator: bool, - #[serde(default, deserialize_with = "deserialize_optional_record")] - user_status: Option, - #[serde(default, deserialize_with = "deserialize_default_string")] - cooked: String, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - raw: Option, - #[serde(default, deserialize_with = "deserialize_default_u32")] - post_number: u32, - #[serde( - default = "default_post_type", - deserialize_with = "deserialize_default_i32" - )] - post_type: i32, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - created_at: Option, - #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] - updated_at: Option, - #[serde(default, deserialize_with = "deserialize_default_u32")] - like_count: u32, - #[serde(default, deserialize_with = "deserialize_default_u32")] - reply_count: u32, - #[serde(default, deserialize_with = "deserialize_optional_u32")] - reply_to_post_number: Option, - #[serde(default, deserialize_with = "deserialize_optional_record")] - reply_to_user: Option, - #[serde(default, deserialize_with = "deserialize_default_bool")] - bookmarked: bool, - #[serde(default, deserialize_with = "deserialize_optional_u64")] - bookmark_id: Option, - #[serde( - default, - rename = "_bookmark_name", - deserialize_with = "deserialize_optional_scalar_string" - )] - bookmark_name: Option, - #[serde( - default, - rename = "_bookmark_reminder_at", - deserialize_with = "deserialize_optional_scalar_string" - )] - bookmark_reminder_at: Option, - #[serde(default, deserialize_with = "deserialize_default_sequence")] - reactions: Vec, - #[serde(default, deserialize_with = "deserialize_optional_record")] - current_user_reaction: Option, - #[serde(default, deserialize_with = "deserialize_default_sequence")] - boosts: Vec, - #[serde(default, deserialize_with = "deserialize_default_bool")] - can_boost: bool, - #[serde(default, deserialize_with = "deserialize_default_sequence")] - polls: Vec, - #[serde(default, deserialize_with = "deserialize_optional_string_sequence_map")] - polls_votes: Option>>, - #[serde(default, deserialize_with = "deserialize_default_bool")] - accepted_answer: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - can_accept_answer: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - can_unaccept_answer: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - can_edit: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - can_delete: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - can_recover: bool, - #[serde(default, deserialize_with = "deserialize_default_bool")] - hidden: bool, -} - -impl From for TopicPost { - fn from(value: RawTopicPost) -> Self { - let poll_votes = value.polls_votes.unwrap_or_default(); - let polls = value - .polls - .into_iter() - .map(|poll| { - let mut parsed: Poll = poll.into(); - parsed.user_votes = poll_votes.get(&parsed.name).cloned().unwrap_or_default(); - parsed - }) - .collect(); - - Self { - id: value.id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - author_metadata: TopicPostAuthorMetadata { - user_id: value.user_id, - user_title: value.user_title, - primary_group_name: value.primary_group_name, - flair_url: value.flair_url, - flair_name: value.flair_name, - flair_bg_color: value.flair_bg_color, - flair_color: value.flair_color, - flair_group_id: value.flair_group_id, - moderator: value.moderator, - admin: value.admin, - group_moderator: value.group_moderator, - user_status_emoji: value - .user_status - .as_ref() - .and_then(|status| status.emoji.clone()), - user_status_description: value.user_status.and_then(|status| status.description), - }, - cooked: value.cooked, - raw: value.raw, - post_number: value.post_number, - post_type: value.post_type, - created_at: value.created_at, - updated_at: value.updated_at, - like_count: value.like_count, - reply_count: value.reply_count, - reply_to_post_number: value.reply_to_post_number, - reply_to_user: value.reply_to_user.map(Into::into), - bookmarked: value.bookmarked, - bookmark_id: value.bookmark_id, - bookmark_name: value.bookmark_name, - bookmark_reminder_at: value.bookmark_reminder_at, - reactions: value.reactions.into_iter().map(Into::into).collect(), - current_user_reaction: value.current_user_reaction.map(Into::into), - boosts: value.boosts.into_iter().map(Into::into).collect(), - can_boost: value.can_boost, - polls, - accepted_answer: value.accepted_answer, - can_accept_answer: value.can_accept_answer, - can_unaccept_answer: value.can_unaccept_answer, - can_edit: value.can_edit, - can_delete: value.can_delete, - can_recover: value.can_recover, - hidden: value.hidden, - presented: Default::default(), - } - } -} - -pub(crate) fn parse_topic_post_boost_value( - value: Value, -) -> Result { - let value = match value { - Value::Object(mut object) => object.remove("boost").unwrap_or(Value::Object(object)), - other => other, - }; - let raw: RawTopicPostBoost = serde_json::from_value(value)?; - Ok(raw.into()) -} - -pub(crate) fn parse_topic_post_value( - value: Value, - base_url: &str, -) -> Result { - let value = match value { - Value::Object(mut object) => object.remove("post").unwrap_or(Value::Object(object)), - value => value, - }; - let mut post: TopicPost = RawTopicPost::deserialize(value)?.into(); - crate::attach_post_presentation(&mut post, base_url); - Ok(post) -} - -pub(crate) fn parse_topic_post_list_value( - value: Value, - base_url: &str, -) -> Result, serde_json::Error> { - let mut posts: Vec = Vec::::deserialize(value)? - .into_iter() - .map(Into::into) - .collect(); - crate::attach_posts_presentation(&mut posts, base_url); - Ok(posts) -} - -pub(crate) fn parse_post_reply_ids_value(value: Value) -> Result, serde_json::Error> { - let items = match value { - Value::Array(items) => items, - value => { - return Err(invalid_json(format!( - "post reply ids root was {}, expected array", - value_kind(&value) - ))); - } - }; - - Ok(items - .iter() - .filter_map(|item| match item { - Value::Object(object) => integer_u64(object.get("id")), - value => integer_u64(Some(value)), - }) - .filter(|id| *id > 0) - .collect()) -} - -pub(crate) fn parse_post_reaction_update_value( - value: Value, -) -> Result { - RawPostReactionUpdate::deserialize(value).map(Into::into) -} - -pub(crate) fn parse_reaction_users_groups_value( - value: Value, -) -> Result, serde_json::Error> { - let items = match value { - Value::Array(items) => items, - Value::Object(object) => object - .get("reaction_users") - .or_else(|| object.get("reactions")) - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(), - _ => Vec::new(), - }; - - Ok(parse_array_items_lossy( - &items, - "reaction users group", - parse_reaction_users_group_value, - )) -} - -fn parse_reaction_users_group_value( - value: &Value, -) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("reaction users group was not an object"))?; - let id = scalar_string(object.get("id")) - .ok_or_else(|| invalid_json("reaction users group did not contain an id"))?; - let users = object - .get("users") - .and_then(Value::as_array) - .map(|items| { - parse_array_items_lossy(items, "reaction user entry", parse_reaction_user_value) - }) - .unwrap_or_default(); - let count = integer_u32(object.get("count")).unwrap_or(users.len() as u32); - - Ok(ReactionUsersGroup { id, count, users }) -} - -fn parse_reaction_user_value(value: &Value) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("reaction user entry was not an object"))?; - let username = scalar_string(object.get("username")) - .ok_or_else(|| invalid_json("reaction user entry did not contain a username"))?; - - Ok(ReactionUser { - id: integer_u64(object.get("id")).unwrap_or_default(), - username, - name: scalar_string(object.get("name")), - avatar_template: scalar_string(object.get("avatar_template")), - }) -} - -fn value_kind(value: &Value) -> &'static str { - match value { - Value::Null => "null", - Value::Bool(_) => "bool", - Value::Number(_) => "number", - Value::String(_) => "string", - Value::Array(_) => "array", - Value::Object(_) => "object", - } -} - -fn default_post_type() -> i32 { - 1 -} diff --git a/crates/fire-core/src/topic_payloads/post/boosts.rs b/crates/fire-core/src/topic_payloads/post/boosts.rs new file mode 100644 index 00000000..c09694c7 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/post/boosts.rs @@ -0,0 +1,224 @@ +fn boost_display_text(cooked: &str, user: &RawTopicPostBoostUser) -> String { + let plain_text = crate::present_cooked_html(cooked, "https://linux.do") + .map(|presented| presented.presentation().plain_text.clone()) + .unwrap_or_default(); + let body_text = strip_boost_leading_attribution(&plain_text, user); + separate_boost_emoji_shortcodes(&body_text) + .split_whitespace() + .collect::>() + .join(" ") +} + +fn strip_boost_leading_attribution(value: &str, user: &RawTopicPostBoostUser) -> String { + let trimmed = value.trim_start(); + if trimmed.is_empty() { + return String::new(); + } + + let candidates = [ + normalized_scalar(Some(user.username.as_str())).map(|username| format!("@{username}:")), + normalized_scalar(Some(user.username.as_str())).map(|username| format!("{username}:")), + normalized_scalar(user.name.as_deref()).map(|name| format!("{name}:")), + normalized_scalar(Some(user.username.as_str())).map(|username| format!("@{username}:")), + normalized_scalar(Some(user.username.as_str())).map(|username| format!("{username}:")), + normalized_scalar(user.name.as_deref()).map(|name| format!("{name}:")), + ]; + + for candidate in candidates.into_iter().flatten() { + if trimmed + .get(..candidate.len()) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case(&candidate)) + { + return trimmed[candidate.len()..].trim_start().to_string(); + } + } + + let Some(rest) = trimmed.strip_prefix('@') else { + return trimmed.to_string(); + }; + let Some(colon_index_after_at) = rest.find([':', ':']) else { + return trimmed.to_string(); + }; + let username = &rest[..colon_index_after_at]; + if !username.is_empty() + && username.len() <= 40 + && username.chars().all(|character| !character.is_whitespace()) + { + let colon_width = rest[colon_index_after_at..] + .chars() + .next() + .map(char::len_utf8) + .unwrap_or(1); + let colon_end_index = 1 + colon_index_after_at + colon_width; + return trimmed[colon_end_index..].trim_start().to_string(); + } + + trimmed.to_string() +} + +fn separate_boost_emoji_shortcodes(value: &str) -> String { + let mut result = String::with_capacity(value.len()); + let mut index = 0; + + while index < value.len() { + let remaining = &value[index..]; + if let Some((shortcode, next_index)) = boost_emoji_shortcode_at(value, index) { + if result + .chars() + .last() + .is_some_and(|character| !character.is_whitespace()) + { + result.push(' '); + } + result.push_str(shortcode); + if value[next_index..] + .chars() + .next() + .is_some_and(|character| !character.is_whitespace()) + { + result.push(' '); + } + index = next_index; + continue; + } + + let character = remaining + .chars() + .next() + .expect("remaining string is non-empty"); + result.push(character); + index += character.len_utf8(); + } + + result +} + +fn boost_emoji_shortcode_at(value: &str, index: usize) -> Option<(&str, usize)> { + let remaining = value.get(index..)?; + let after_open = remaining.strip_prefix(':')?; + for (end, character) in after_open.char_indices() { + if character != ':' { + continue; + } + let name = &after_open[..end]; + if !is_boost_emoji_shortcode_name(name) { + continue; + } + let next_index = index + end + 2; + let next_character = value[next_index..].chars().next(); + if next_character.is_some_and(is_boost_emoji_shortcode_component_character) { + continue; + } + return Some((&value[index..next_index], next_index)); + } + None +} + +fn is_boost_emoji_shortcode_name(value: &str) -> bool { + !value.is_empty() + && value.split(':').all(|component| { + !component.is_empty() + && component + .chars() + .all(is_boost_emoji_shortcode_component_character) + }) +} + +fn is_boost_emoji_shortcode_component_character(character: char) -> bool { + character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '+') +} + +#[derive(Debug, Default, Deserialize)] +struct RawTopicPostUserStatus { + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + emoji: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + description: Option, +} + +#[derive(Debug, Default, Deserialize)] +struct RawTopicPostBoostUser { + #[serde(default, deserialize_with = "deserialize_default_u64")] + id: u64, + #[serde(default, deserialize_with = "deserialize_default_string")] + username: String, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + name: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + avatar_template: Option, +} + +impl From for TopicPostBoostUser { + fn from(value: RawTopicPostBoostUser) -> Self { + Self { + id: value.id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +#[derive(Debug, Default, Deserialize)] +struct RawTopicPostBoost { + #[serde(default, deserialize_with = "deserialize_default_u64")] + id: u64, + #[serde(default, deserialize_with = "deserialize_default_string")] + cooked: String, + #[serde(default, deserialize_with = "deserialize_default_record")] + user: RawTopicPostBoostUser, + #[serde(default, deserialize_with = "deserialize_default_bool")] + can_delete: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + can_flag: bool, + #[serde(default, deserialize_with = "deserialize_optional_i32")] + user_flag_status: Option, + #[serde(default, deserialize_with = "deserialize_default_string_sequence")] + available_flags: Vec, +} + +impl From for TopicPostBoost { + fn from(value: RawTopicPostBoost) -> Self { + let presented = crate::present_cooked_html(&value.cooked, "https://linux.do"); + let display_text = presented + .as_ref() + .map(|document| { + let body_text = strip_boost_leading_attribution( + &document.presentation().plain_text, + &value.user, + ); + separate_boost_emoji_shortcodes(&body_text) + .split_whitespace() + .collect::>() + .join(" ") + }) + .unwrap_or_else(|| boost_display_text(&value.cooked, &value.user)); + Self { + id: value.id, + cooked: value.cooked, + display_text, + user: value.user.into(), + can_delete: value.can_delete, + can_flag: value.can_flag, + user_flag_status: value.user_flag_status, + available_flags: value.available_flags, + presented: presented + .map(|document| { + fire_models::AttachedPresentation::some(std::sync::Arc::new(document)) + }) + .unwrap_or_default(), + } + } +} + +pub(crate) fn parse_topic_post_boost_value( + value: Value, +) -> Result { + let value = match value { + Value::Object(mut object) => object.remove("boost").unwrap_or(Value::Object(object)), + other => other, + }; + let raw: RawTopicPostBoost = serde_json::from_value(value)?; + Ok(raw.into()) +} + diff --git a/crates/fire-core/src/topic_payloads/post/mod.rs b/crates/fire-core/src/topic_payloads/post/mod.rs new file mode 100644 index 00000000..a24ae0f2 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/post/mod.rs @@ -0,0 +1,25 @@ +use fire_models::{ + Poll, PostReactionUpdate, ReactionUser, ReactionUsersGroup, TopicPost, TopicPostAuthorMetadata, + TopicPostBoost, TopicPostBoostUser, TopicReaction, TopicReplyToUser, +}; +use serde::Deserialize; +use serde_json::Value; +use std::collections::HashMap; + +use super::deser::{ + deserialize_default_bool, deserialize_default_i32, deserialize_default_record, + deserialize_default_sequence, deserialize_default_string, deserialize_default_string_sequence, + deserialize_default_u32, deserialize_default_u64, deserialize_optional_bool, + deserialize_optional_i32, deserialize_optional_record, deserialize_optional_scalar_string, + deserialize_optional_string_sequence_map, deserialize_optional_u32, deserialize_optional_u64, +}; +use super::list::normalized_scalar; +use super::poll::RawPoll; +use crate::json_helpers::{ + integer_u32, integer_u64, invalid_json, parse_array_items_lossy, scalar_string, +}; + +include!("model.rs"); +include!("boosts.rs"); +include!("reactions.rs"); +include!("replies.rs"); diff --git a/crates/fire-core/src/topic_payloads/post/model.rs b/crates/fire-core/src/topic_payloads/post/model.rs new file mode 100644 index 00000000..6f69d745 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/post/model.rs @@ -0,0 +1,207 @@ +#[derive(Debug, Default, Deserialize)] +pub(super) struct RawTopicPost { + #[serde(default, deserialize_with = "deserialize_default_u64")] + id: u64, + #[serde(default, deserialize_with = "deserialize_default_string")] + username: String, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + name: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + avatar_template: Option, + #[serde(default, deserialize_with = "deserialize_optional_u64")] + user_id: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + user_title: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + primary_group_name: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + flair_url: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + flair_name: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + flair_bg_color: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + flair_color: Option, + #[serde(default, deserialize_with = "deserialize_optional_u64")] + flair_group_id: Option, + #[serde(default, deserialize_with = "deserialize_default_bool")] + moderator: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + admin: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + group_moderator: bool, + #[serde(default, deserialize_with = "deserialize_optional_record")] + user_status: Option, + #[serde(default, deserialize_with = "deserialize_default_string")] + cooked: String, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + raw: Option, + #[serde(default, deserialize_with = "deserialize_default_u32")] + post_number: u32, + #[serde( + default = "default_post_type", + deserialize_with = "deserialize_default_i32" + )] + post_type: i32, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + created_at: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + updated_at: Option, + #[serde(default, deserialize_with = "deserialize_default_u32")] + like_count: u32, + #[serde(default, deserialize_with = "deserialize_default_u32")] + reply_count: u32, + #[serde(default, deserialize_with = "deserialize_optional_u32")] + reply_to_post_number: Option, + #[serde(default, deserialize_with = "deserialize_optional_record")] + reply_to_user: Option, + #[serde(default, deserialize_with = "deserialize_default_bool")] + bookmarked: bool, + #[serde(default, deserialize_with = "deserialize_optional_u64")] + bookmark_id: Option, + #[serde( + default, + rename = "_bookmark_name", + deserialize_with = "deserialize_optional_scalar_string" + )] + bookmark_name: Option, + #[serde( + default, + rename = "_bookmark_reminder_at", + deserialize_with = "deserialize_optional_scalar_string" + )] + bookmark_reminder_at: Option, + #[serde(default, deserialize_with = "deserialize_default_sequence")] + reactions: Vec, + #[serde(default, deserialize_with = "deserialize_optional_record")] + current_user_reaction: Option, + #[serde(default, deserialize_with = "deserialize_default_sequence")] + boosts: Vec, + #[serde(default, deserialize_with = "deserialize_default_bool")] + can_boost: bool, + #[serde(default, deserialize_with = "deserialize_default_sequence")] + polls: Vec, + #[serde(default, deserialize_with = "deserialize_optional_string_sequence_map")] + polls_votes: Option>>, + #[serde(default, deserialize_with = "deserialize_default_bool")] + accepted_answer: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + can_accept_answer: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + can_unaccept_answer: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + can_edit: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + can_delete: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + can_recover: bool, + #[serde(default, deserialize_with = "deserialize_default_bool")] + hidden: bool, +} + +impl From for TopicPost { + fn from(value: RawTopicPost) -> Self { + let poll_votes = value.polls_votes.unwrap_or_default(); + let polls = value + .polls + .into_iter() + .map(|poll| { + let mut parsed: Poll = poll.into(); + parsed.user_votes = poll_votes.get(&parsed.name).cloned().unwrap_or_default(); + parsed + }) + .collect(); + + Self { + id: value.id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + author_metadata: TopicPostAuthorMetadata { + user_id: value.user_id, + user_title: value.user_title, + primary_group_name: value.primary_group_name, + flair_url: value.flair_url, + flair_name: value.flair_name, + flair_bg_color: value.flair_bg_color, + flair_color: value.flair_color, + flair_group_id: value.flair_group_id, + moderator: value.moderator, + admin: value.admin, + group_moderator: value.group_moderator, + user_status_emoji: value + .user_status + .as_ref() + .and_then(|status| status.emoji.clone()), + user_status_description: value.user_status.and_then(|status| status.description), + }, + cooked: value.cooked, + raw: value.raw, + post_number: value.post_number, + post_type: value.post_type, + created_at: value.created_at, + updated_at: value.updated_at, + like_count: value.like_count, + reply_count: value.reply_count, + reply_to_post_number: value.reply_to_post_number, + reply_to_user: value.reply_to_user.map(Into::into), + bookmarked: value.bookmarked, + bookmark_id: value.bookmark_id, + bookmark_name: value.bookmark_name, + bookmark_reminder_at: value.bookmark_reminder_at, + reactions: value.reactions.into_iter().map(Into::into).collect(), + current_user_reaction: value.current_user_reaction.map(Into::into), + boosts: value.boosts.into_iter().map(Into::into).collect(), + can_boost: value.can_boost, + polls, + accepted_answer: value.accepted_answer, + can_accept_answer: value.can_accept_answer, + can_unaccept_answer: value.can_unaccept_answer, + can_edit: value.can_edit, + can_delete: value.can_delete, + can_recover: value.can_recover, + hidden: value.hidden, + presented: Default::default(), + } + } +} + +pub(crate) fn parse_topic_post_value( + value: Value, + base_url: &str, +) -> Result { + let value = match value { + Value::Object(mut object) => object.remove("post").unwrap_or(Value::Object(object)), + value => value, + }; + let mut post: TopicPost = RawTopicPost::deserialize(value)?.into(); + crate::attach_post_presentation(&mut post, base_url); + Ok(post) +} + +pub(crate) fn parse_topic_post_list_value( + value: Value, + base_url: &str, +) -> Result, serde_json::Error> { + let mut posts: Vec = Vec::::deserialize(value)? + .into_iter() + .map(Into::into) + .collect(); + crate::attach_posts_presentation(&mut posts, base_url); + Ok(posts) +} + +fn value_kind(value: &Value) -> &'static str { + match value { + Value::Null => "null", + Value::Bool(_) => "bool", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + } +} + +fn default_post_type() -> i32 { + 1 +} diff --git a/crates/fire-core/src/topic_payloads/post/reactions.rs b/crates/fire-core/src/topic_payloads/post/reactions.rs new file mode 100644 index 00000000..dafa5d23 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/post/reactions.rs @@ -0,0 +1,103 @@ +#[derive(Debug, Default, Deserialize)] +struct RawTopicReaction { + #[serde(default, deserialize_with = "deserialize_default_string")] + id: String, + #[serde(rename = "type")] + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + kind: Option, + #[serde(default, deserialize_with = "deserialize_default_u32")] + count: u32, + #[serde(default, deserialize_with = "deserialize_optional_bool")] + can_undo: Option, +} + +impl From for TopicReaction { + fn from(value: RawTopicReaction) -> Self { + Self { + id: value.id, + kind: value.kind, + count: value.count, + can_undo: value.can_undo, + } + } +} + +#[derive(Debug, Default, Deserialize)] +struct RawPostReactionUpdate { + #[serde(default, deserialize_with = "deserialize_default_sequence")] + reactions: Vec, + #[serde(default, deserialize_with = "deserialize_optional_record")] + current_user_reaction: Option, +} + +impl From for PostReactionUpdate { + fn from(value: RawPostReactionUpdate) -> Self { + Self { + reactions: value.reactions.into_iter().map(Into::into).collect(), + current_user_reaction: value.current_user_reaction.map(Into::into), + } + } +} + +pub(crate) fn parse_post_reaction_update_value( + value: Value, +) -> Result { + RawPostReactionUpdate::deserialize(value).map(Into::into) +} + +pub(crate) fn parse_reaction_users_groups_value( + value: Value, +) -> Result, serde_json::Error> { + let items = match value { + Value::Array(items) => items, + Value::Object(object) => object + .get("reaction_users") + .or_else(|| object.get("reactions")) + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(), + _ => Vec::new(), + }; + + Ok(parse_array_items_lossy( + &items, + "reaction users group", + parse_reaction_users_group_value, + )) +} + +fn parse_reaction_users_group_value( + value: &Value, +) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("reaction users group was not an object"))?; + let id = scalar_string(object.get("id")) + .ok_or_else(|| invalid_json("reaction users group did not contain an id"))?; + let users = object + .get("users") + .and_then(Value::as_array) + .map(|items| { + parse_array_items_lossy(items, "reaction user entry", parse_reaction_user_value) + }) + .unwrap_or_default(); + let count = integer_u32(object.get("count")).unwrap_or(users.len() as u32); + + Ok(ReactionUsersGroup { id, count, users }) +} + +fn parse_reaction_user_value(value: &Value) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("reaction user entry was not an object"))?; + let username = scalar_string(object.get("username")) + .ok_or_else(|| invalid_json("reaction user entry did not contain a username"))?; + + Ok(ReactionUser { + id: integer_u64(object.get("id")).unwrap_or_default(), + username, + name: scalar_string(object.get("name")), + avatar_template: scalar_string(object.get("avatar_template")), + }) +} + diff --git a/crates/fire-core/src/topic_payloads/post/replies.rs b/crates/fire-core/src/topic_payloads/post/replies.rs new file mode 100644 index 00000000..78bd89b1 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/post/replies.rs @@ -0,0 +1,41 @@ +#[derive(Debug, Default, Deserialize)] +struct RawTopicReplyToUser { + #[serde(default, deserialize_with = "deserialize_default_string")] + username: String, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + name: Option, + #[serde(default, deserialize_with = "deserialize_optional_scalar_string")] + avatar_template: Option, +} + +impl From for TopicReplyToUser { + fn from(value: RawTopicReplyToUser) -> Self { + Self { + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +pub(crate) fn parse_post_reply_ids_value(value: Value) -> Result, serde_json::Error> { + let items = match value { + Value::Array(items) => items, + value => { + return Err(invalid_json(format!( + "post reply ids root was {}, expected array", + value_kind(&value) + ))); + } + }; + + Ok(items + .iter() + .filter_map(|item| match item { + Value::Object(object) => integer_u64(object.get("id")), + value => integer_u64(Some(value)), + }) + .filter(|id| *id > 0) + .collect()) +} + diff --git a/crates/fire-core/src/topic_payloads/tests.rs b/crates/fire-core/src/topic_payloads/tests.rs new file mode 100644 index 00000000..fd84de39 --- /dev/null +++ b/crates/fire-core/src/topic_payloads/tests.rs @@ -0,0 +1,185 @@ +#[cfg(test)] +use super::*; +use fire_models::TopicThread; +use serde_json::json; + +fn sample_raw_topic_detail() -> RawTopicDetail { + serde_json::from_value(json!({ + "id": 42, + "title": "Topic", + "slug": "topic", + "posts_count": 2, + "post_stream": { + "posts": [ + { + "id": 101, + "username": "alice", + "cooked": "

root

", + "post_number": 1, + "reply_count": 1, + "can_boost": true, + "boosts": [ + { + "id": 501, + "cooked": "

Hello \":wave:\"

", + "user": { + "id": 7, + "username": "carol", + "name": "Carol", + "avatar_template": "/user_avatar/linux.do/carol/{size}/1.png" + }, + "can_delete": true, + "can_flag": true, + "user_flag_status": 0, + "available_flags": ["off_topic", 9] + } + ] + }, + { + "id": 102, + "username": "bob", + "cooked": "

reply

", + "post_number": 2, + "reply_to_post_number": 1 + } + ], + "stream": [101, 102] + }, + "details": {} + })) + .expect("sample topic detail should deserialize") +} + +#[test] +fn lightweight_topic_detail_skips_thread_state() { + let detail = sample_raw_topic_detail().into_topic_detail(false, "https://linux.do"); + + assert_eq!(detail.thread, TopicThread::default()); + assert!(detail.flat_posts.is_empty()); + assert!(detail.timeline_entries.is_empty()); + assert_eq!(detail.post_stream.posts.len(), 2); +} + +#[test] +fn full_topic_detail_preserves_thread_state() { + let detail = sample_raw_topic_detail().into_topic_detail(true, "https://linux.do"); + + assert_eq!(detail.thread.original_post_number, Some(1)); + assert_eq!(detail.flat_posts.len(), 2); + assert!(detail.timeline_entries.is_empty()); +} + +#[test] +fn parse_topic_post_boost_value_accepts_wrapped_and_flat_payloads() { + let wrapped = serde_json::json!({ + "boost": { + "id": 42, + "cooked": "

nice

", + "user": { "id": 7, "username": "alice", "name": "Alice" }, + "can_delete": true, + "can_flag": false + } + }); + let boost = parse_topic_post_boost_value(wrapped).expect("wrapped boost"); + assert_eq!(boost.id, 42); + assert_eq!(boost.user.username, "alice"); + assert!(boost.can_delete); + + let flat = serde_json::json!({ + "id": 43, + "cooked": "

🔥

", + "user": { "id": 8, "username": "bob" } + }); + let boost = parse_topic_post_boost_value(flat).expect("flat boost"); + assert_eq!(boost.id, 43); + assert_eq!(boost.user.username, "bob"); +} + +#[test] +fn topic_post_boosts_parse_display_text_and_permissions() { + let detail = sample_raw_topic_detail().into_topic_detail(false, "https://linux.do"); + let post = detail + .post_stream + .posts + .iter() + .find(|post| post.id == 101) + .expect("root post"); + + assert!(post.can_boost); + assert_eq!(post.boosts.len(), 1); + let boost = &post.boosts[0]; + assert_eq!(boost.id, 501); + assert_eq!(boost.display_text, "Hello :wave:"); + assert_eq!(boost.user.username, "carol"); + assert_eq!(boost.user.name.as_deref(), Some("Carol")); + assert!(boost.can_delete); + assert!(boost.can_flag); + assert_eq!(boost.user_flag_status, Some(0)); + assert_eq!(boost.available_flags, ["off_topic", "9"]); +} + +#[test] +fn topic_post_boost_display_text_normalizes_emoji_images_without_alt() { + let detail = serde_json::from_value::(json!({ + "id": 42, + "title": "Topic", + "slug": "topic", + "post_stream": { + "posts": [ + { + "id": 101, + "username": "alice", + "cooked": "

root

", + "post_number": 1, + "boosts": [ + { + "id": 501, + "cooked": "

🎉

", + "user": {"id": 7, "username": "carol"} + } + ] + } + ], + "stream": [101] + }, + "details": {} + })) + .expect("sample topic detail should deserialize") + .into_topic_detail(false, "https://linux.do"); + let boost = &detail.post_stream.posts[0].boosts[0]; + + assert_eq!(boost.display_text, ":smile: :wave:t3: 🎉"); +} + +#[test] +fn topic_post_boost_display_text_strips_leading_attribution() { + let detail = serde_json::from_value::(json!({ + "id": 42, + "title": "Topic", + "slug": "topic", + "post_stream": { + "posts": [ + { + "id": 101, + "username": "alice", + "cooked": "

root

", + "post_number": 1, + "boosts": [ + { + "id": 501, + "cooked": "

@carol: Thanks for the detail

", + "user": {"id": 7, "username": "carol", "name": "Carol"} + } + ] + } + ], + "stream": [101] + }, + "details": {} + })) + .expect("sample topic detail should deserialize") + .into_topic_detail(false, "https://linux.do"); + let boost = &detail.post_stream.posts[0].boosts[0]; + + assert_eq!(boost.display_text, "Thanks for the detail"); +} diff --git a/crates/fire-core/src/user_payloads.rs b/crates/fire-core/src/user_payloads.rs deleted file mode 100644 index fbdbf7ad..00000000 --- a/crates/fire-core/src/user_payloads.rs +++ /dev/null @@ -1,875 +0,0 @@ -use fire_models::{ - Badge, FollowUser, InviteLink, InviteLinkDetails, ProfileSummaryLink, ProfileSummaryReply, - ProfileSummaryTopCategory, ProfileSummaryTopic, ProfileSummaryUserReference, UserAction, - UserProfile, UserReaction, UserReactionsResponse, UserSummaryResponse, UserSummaryStats, -}; -use serde_json::{Map, Value}; - -use crate::json_helpers::{ - boolean, integer_i32, integer_u32, integer_u64, invalid_json, optional_boolean, - parse_array_items_lossy, scalar_string, -}; - -pub(crate) fn parse_user_profile_value(value: Value) -> Result { - let user_value = match value { - Value::Object(ref obj) if obj.contains_key("user") => { - obj.get("user").cloned().unwrap_or(value.clone()) - } - other => other, - }; - let Value::Object(object) = user_value else { - return Err(invalid_json("user profile response root was not an object")); - }; - - Ok(UserProfile { - id: integer_u64(object.get("id")).unwrap_or_default(), - username: scalar_string(object.get("username")).unwrap_or_default(), - name: scalar_string(object.get("name")), - avatar_template: scalar_string(object.get("avatar_template")), - trust_level: integer_u32(object.get("trust_level")), - bio_cooked: scalar_string(object.get("bio_cooked")), - bio_plain_text: scalar_string(object.get("bio_cooked")).and_then(|html| { - let plain = crate::plain_text_from_html(&html); - let trimmed = plain.trim(); - if trimmed.is_empty() { - None - } else { - Some(trimmed.to_string()) - } - }), - created_at: scalar_string(object.get("created_at")), - last_seen_at: scalar_string(object.get("last_seen_at")), - last_posted_at: scalar_string(object.get("last_posted_at")), - flair_name: scalar_string(object.get("flair_name")), - flair_url: scalar_string(object.get("flair_url")), - flair_bg_color: scalar_string(object.get("flair_bg_color")), - flair_color: scalar_string(object.get("flair_color")), - profile_background_upload_url: scalar_string(object.get("profile_background_upload_url")), - card_background_upload_url: scalar_string(object.get("card_background_upload_url")), - total_followers: integer_u32(object.get("total_followers")), - total_following: integer_u32(object.get("total_following")), - can_follow: optional_boolean(object.get("can_follow")), - is_followed: optional_boolean(object.get("is_followed")), - can_send_private_message_to_user: optional_boolean( - object.get("can_send_private_message_to_user"), - ), - muted: optional_boolean(object.get("muted")), - ignored: optional_boolean(object.get("ignored")), - can_mute_user: optional_boolean(object.get("can_mute_user")), - can_ignore_user: optional_boolean(object.get("can_ignore_user")), - gamification_score: integer_u32(object.get("gamification_score")), - suspended_till: scalar_string(object.get("suspended_till")), - silenced_till: scalar_string(object.get("silenced_till")), - }) -} - -pub(crate) fn parse_user_summary_value( - value: Value, -) -> Result { - let root = match &value { - Value::Object(obj) => obj, - _ => return Err(invalid_json("user summary response root was not an object")), - }; - - let empty = Map::new(); - let summary_obj = root - .get("user_summary") - .and_then(Value::as_object) - .unwrap_or(&empty); - let stats = parse_user_summary_stats_object(summary_obj); - let top_replies = parse_array_items_lossy( - array_items( - summary_obj - .get("replies") - .or_else(|| summary_obj.get("top_replies")), - ), - "profile summary reply", - parse_profile_summary_reply_value, - ); - let top_links = parse_array_items_lossy( - array_items( - summary_obj - .get("links") - .or_else(|| summary_obj.get("top_links")), - ), - "profile summary link", - parse_profile_summary_link_value, - ); - let top_categories = parse_array_items_lossy( - array_items(summary_obj.get("top_categories")), - "profile summary top category", - parse_profile_summary_top_category_value, - ); - let most_replied_to_users = parse_array_items_lossy( - array_items(summary_obj.get("most_replied_to_users")), - "profile summary user reference", - parse_profile_summary_user_reference_value, - ); - let most_liked_by_users = parse_array_items_lossy( - array_items(summary_obj.get("most_liked_by_users")), - "profile summary user reference", - parse_profile_summary_user_reference_value, - ); - let most_liked_users = parse_array_items_lossy( - array_items(summary_obj.get("most_liked_users")), - "profile summary user reference", - parse_profile_summary_user_reference_value, - ); - let top_topics = parse_array_items_lossy( - array_items(root.get("topics")), - "profile summary topic", - parse_profile_summary_topic_value, - ); - let badges = - parse_array_items_lossy(array_items(root.get("badges")), "badge", parse_badge_item); - - Ok(UserSummaryResponse { - stats, - top_topics, - top_replies, - top_links, - top_categories, - most_replied_to_users, - most_liked_by_users, - most_liked_users, - badges, - }) -} - -pub(crate) fn parse_user_actions_value(value: Value) -> Result, serde_json::Error> { - let actions_value = match value { - Value::Object(ref obj) if obj.contains_key("user_actions") => obj - .get("user_actions") - .cloned() - .unwrap_or(Value::Array(Vec::new())), - Value::Array(_) => value, - _ => Value::Array(Vec::new()), - }; - Ok(parse_array_items_lossy( - array_items(Some(&actions_value)), - "user action item", - parse_user_action_value, - )) -} - -pub(crate) fn parse_user_reactions_value( - value: Value, -) -> Result { - let reactions_value = match value { - Value::Array(_) => value, - Value::Object(ref obj) => obj - .get("reactions") - .or_else(|| obj.get("posts")) - .cloned() - .unwrap_or(Value::Array(Vec::new())), - _ => Value::Array(Vec::new()), - }; - - Ok(UserReactionsResponse { - reactions: parse_array_items_lossy( - array_items(Some(&reactions_value)), - "user reaction item", - parse_user_reaction_value, - ), - }) -} - -pub(crate) fn parse_badge_value(value: Value) -> Result { - let badge_value = match value { - Value::Object(ref obj) if obj.contains_key("badge") => { - obj.get("badge").cloned().unwrap_or(value.clone()) - } - other => other, - }; - parse_badge_item(&badge_value) -} - -pub(crate) fn parse_follow_users_value(value: Value) -> Result, serde_json::Error> { - let list_value = match value { - Value::Array(_) => value, - Value::Object(ref obj) => obj - .get("users") - .or_else(|| obj.get("following")) - .or_else(|| obj.get("followers")) - .cloned() - .unwrap_or(Value::Array(Vec::new())), - _ => Value::Array(Vec::new()), - }; - Ok(parse_array_items_lossy( - array_items(Some(&list_value)), - "follow user item", - parse_follow_user_value, - )) -} - -pub(crate) fn parse_invite_links_value(value: Value) -> Result, serde_json::Error> { - let mut items = Vec::new(); - match value { - Value::Array(values) => items.extend(values), - Value::Object(object) => { - let invites = object - .get("invites") - .or_else(|| object.get("pending_invites")) - .or_else(|| object.get("invited")) - .or_else(|| object.get("pending")) - .cloned(); - if let Some(Value::Array(values)) = invites { - items.extend(values); - } else if object.contains_key("invite") - || object.contains_key("invite_link") - || object.contains_key("invite_key") - || object.contains_key("invite_url") - || object.contains_key("url") - || object.contains_key("link") - { - items.push(Value::Object(object)); - } - } - _ => {} - } - - Ok(parse_array_items_lossy( - &items, - "invite link item", - |item| parse_invite_link_value(item.clone()), - )) -} - -pub(crate) fn parse_invite_link_value(value: Value) -> Result { - let Value::Object(mut object) = value else { - return Err(invalid_json("invite link response root was not an object")); - }; - - let invite_link = scalar_string(object.get("invite_link")) - .or_else(|| scalar_string(object.get("invite_url"))) - .or_else(|| scalar_string(object.get("url"))) - .or_else(|| scalar_string(object.get("link"))) - .unwrap_or_default(); - - let invite = match object.remove("invite") { - Some(Value::Object(invite_object)) => { - Some(parse_invite_link_details_object(&invite_object)) - } - Some(_) => None, - None => { - if object.contains_key("invite_key") - || object.contains_key("expires_at") - || object.contains_key("max_redemptions_allowed") - { - Some(parse_invite_link_details_object(&object)) - } else { - None - } - } - }; - - Ok(InviteLink { - invite_link, - invite, - }) -} - -fn parse_invite_link_details_object(object: &serde_json::Map) -> InviteLinkDetails { - InviteLinkDetails { - id: integer_u64(object.get("id")), - invite_key: scalar_string(object.get("invite_key")), - max_redemptions_allowed: integer_u32(object.get("max_redemptions_allowed")), - redemption_count: integer_u32(object.get("redemption_count")), - expired: object.get("expired").map(|value| boolean(Some(value))), - created_at: scalar_string(object.get("created_at")), - expires_at: scalar_string(object.get("expires_at")), - } -} - -fn parse_user_summary_stats_object(object: &Map) -> UserSummaryStats { - UserSummaryStats { - days_visited: integer_u32(object.get("days_visited")).unwrap_or_default(), - posts_read_count: integer_u32(object.get("posts_read_count")).unwrap_or_default(), - likes_received: integer_u32(object.get("likes_received")).unwrap_or_default(), - likes_given: integer_u32(object.get("likes_given")).unwrap_or_default(), - topic_count: integer_u32(object.get("topic_count")).unwrap_or_default(), - post_count: integer_u32(object.get("post_count")).unwrap_or_default(), - time_read: integer_u64(object.get("time_read")).unwrap_or_default(), - bookmark_count: integer_u32(object.get("bookmark_count")).unwrap_or_default(), - } -} - -fn parse_profile_summary_topic_value( - value: &Value, -) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("profile summary topic item was not an object"))?; - let id = integer_u64(object.get("id")) - .ok_or_else(|| invalid_json("profile summary topic item did not contain an id"))?; - Ok(ProfileSummaryTopic { - id, - title: scalar_string(object.get("title")).unwrap_or_default(), - slug: scalar_string(object.get("slug")), - like_count: integer_u32(object.get("like_count")).unwrap_or_default(), - category_id: integer_u64(object.get("category_id")), - created_at: scalar_string(object.get("created_at")), - }) -} - -fn parse_profile_summary_reply_value( - value: &Value, -) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("profile summary reply item was not an object"))?; - let id = integer_u64(object.get("id")) - .ok_or_else(|| invalid_json("profile summary reply item did not contain an id"))?; - let topic_id = integer_u64(object.get("topic_id")) - .ok_or_else(|| invalid_json("profile summary reply item did not contain a topic_id"))?; - Ok(ProfileSummaryReply { - id, - topic_id, - title: scalar_string(object.get("title")), - like_count: integer_u32(object.get("like_count")).unwrap_or_default(), - created_at: scalar_string(object.get("created_at")), - post_number: integer_u32(object.get("post_number")), - }) -} - -fn parse_profile_summary_link_value( - value: &Value, -) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("profile summary link item was not an object"))?; - let url = scalar_string(object.get("url")) - .ok_or_else(|| invalid_json("profile summary link item did not contain a url"))?; - Ok(ProfileSummaryLink { - url, - title: scalar_string(object.get("title")), - clicks: integer_u32(object.get("clicks")).unwrap_or_default(), - topic_id: integer_u64(object.get("topic_id")), - post_number: integer_u32(object.get("post_number")), - }) -} - -fn parse_profile_summary_top_category_value( - value: &Value, -) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("profile summary top category item was not an object"))?; - let id = integer_u64(object.get("id")) - .ok_or_else(|| invalid_json("profile summary top category item did not contain an id"))?; - Ok(ProfileSummaryTopCategory { - id, - name: scalar_string(object.get("name")), - topic_count: integer_u32(object.get("topic_count")).unwrap_or_default(), - post_count: integer_u32(object.get("post_count")).unwrap_or_default(), - }) -} - -fn parse_profile_summary_user_reference_value( - value: &Value, -) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("profile summary user reference item was not an object"))?; - let id = integer_u64(object.get("id")).unwrap_or_default(); - let username = scalar_string(object.get("username")).unwrap_or_default(); - if id == 0 && username.is_empty() { - return Err(invalid_json( - "profile summary user reference item did not contain an id or username", - )); - } - Ok(ProfileSummaryUserReference { - id, - username, - avatar_template: scalar_string(object.get("avatar_template")), - count: integer_u32(object.get("count")).unwrap_or_default(), - }) -} - -fn parse_badge_item(value: &Value) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("badge response root was not an object"))?; - Ok(Badge { - id: integer_u64(object.get("id")).unwrap_or_default(), - name: scalar_string(object.get("name")).unwrap_or_default(), - description: scalar_string(object.get("description")), - badge_type_id: integer_u32(object.get("badge_type_id")).unwrap_or_default(), - image_url: scalar_string(object.get("image_url")), - icon: scalar_string(object.get("icon")), - slug: scalar_string(object.get("slug")), - grant_count: integer_u32(object.get("grant_count")).unwrap_or_default(), - long_description: scalar_string(object.get("long_description")), - }) -} - -fn parse_user_action_value(value: &Value) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("user action item was not an object"))?; - Ok(UserAction { - action_type: integer_i32(object.get("action_type")), - topic_id: integer_u64(object.get("topic_id")), - post_id: integer_u64(object.get("post_id")), - post_number: integer_u32(object.get("post_number")), - title: scalar_string(object.get("title")), - slug: scalar_string(object.get("slug")), - username: scalar_string(object.get("username")), - acting_username: scalar_string(object.get("acting_username")), - acting_avatar_template: scalar_string(object.get("acting_avatar_template")), - category_id: integer_u64(object.get("category_id")), - excerpt: scalar_string(object.get("excerpt")), - created_at: scalar_string(object.get("created_at")), - }) -} - -fn parse_user_reaction_value(value: &Value) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("user reaction item was not an object"))?; - let post_object = object.get("post").and_then(Value::as_object); - let reaction_object = object.get("reaction").and_then(Value::as_object); - let id = integer_u64(object.get("id")) - .ok_or_else(|| invalid_json("user reaction item did not contain an id"))?; - let post_id = integer_u64(object.get("post_id")) - .or_else(|| post_object.and_then(|post| integer_u64(post.get("id")))) - .ok_or_else(|| invalid_json("user reaction item did not contain a post_id"))?; - - Ok(UserReaction { - id, - post_id, - topic_id: post_object - .and_then(|post| integer_u64(post.get("topic_id"))) - .or_else(|| integer_u64(object.get("topic_id"))) - .unwrap_or_default(), - post_number: post_object - .and_then(|post| integer_u32(post.get("post_number"))) - .or_else(|| integer_u32(object.get("post_number"))), - topic_title: post_object - .and_then(|post| scalar_string(post.get("topic_title"))) - .or_else(|| scalar_string(object.get("topic_title"))) - .or_else(|| scalar_string(object.get("title"))), - excerpt: post_object - .and_then(|post| scalar_string(post.get("excerpt"))) - .or_else(|| scalar_string(object.get("excerpt"))), - reaction_value: reaction_object - .and_then(|reaction| scalar_string(reaction.get("reaction_value"))) - .or_else(|| scalar_string(object.get("reaction_value"))), - created_at: scalar_string(object.get("created_at")), - }) -} - -fn parse_follow_user_value(value: &Value) -> Result { - let object = value - .as_object() - .ok_or_else(|| invalid_json("follow user item was not an object"))?; - let id = integer_u64(object.get("id")).unwrap_or_default(); - let username = scalar_string(object.get("username")).unwrap_or_default(); - if id == 0 && username.is_empty() { - return Err(invalid_json( - "follow user item did not contain an id or username", - )); - } - Ok(FollowUser { - id, - username, - name: scalar_string(object.get("name")), - avatar_template: scalar_string(object.get("avatar_template")), - }) -} - -fn array_items(value: Option<&Value>) -> &[Value] { - match value { - Some(Value::Array(items)) => items.as_slice(), - _ => &[], - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn test_parse_user_profile_unwraps_user_envelope() { - let value = json!({ - "user": { - "id": 42, - "username": "alice", - "trust_level": 3, - "bio_cooked": "

Hello

" - } - }); - let profile = parse_user_profile_value(value).unwrap(); - assert_eq!(profile.id, 42); - assert_eq!(profile.username, "alice"); - assert_eq!(profile.trust_level, Some(3)); - assert_eq!(profile.bio_cooked.as_deref(), Some("

Hello

")); - assert_eq!(profile.bio_plain_text.as_deref(), Some("Hello")); - } - - #[test] - fn test_parse_user_profile_bare_fallback() { - let value = json!({ - "id": 99, - "username": "bob", - "name": "Bob Smith" - }); - let profile = parse_user_profile_value(value).unwrap(); - assert_eq!(profile.id, 99); - assert_eq!(profile.username, "bob"); - assert_eq!(profile.name.as_deref(), Some("Bob Smith")); - } - - #[test] - fn test_parse_user_profile_nullable_follow_fields() { - let value = json!({ - "user": { - "id": 1, - "username": "test" - } - }); - let profile = parse_user_profile_value(value).unwrap(); - assert_eq!(profile.can_follow, None); - assert_eq!(profile.is_followed, None); - assert_eq!(profile.total_followers, None); - assert_eq!(profile.total_following, None); - } - - #[test] - fn test_parse_user_profile_coerces_scalar_fields() { - let value = json!({ - "user": { - "id": "7", - "username": "alice", - "trust_level": "3", - "total_followers": "12", - "total_following": 5, - "can_follow": "1", - "is_followed": 0, - "muted": "1", - "ignored": false, - "can_mute_user": true, - "can_ignore_user": "0" - } - }); - let profile = parse_user_profile_value(value).unwrap(); - assert_eq!(profile.id, 7); - assert_eq!(profile.trust_level, Some(3)); - assert_eq!(profile.total_followers, Some(12)); - assert_eq!(profile.total_following, Some(5)); - assert_eq!(profile.can_follow, Some(true)); - assert_eq!(profile.is_followed, Some(false)); - assert_eq!(profile.muted, Some(true)); - assert_eq!(profile.ignored, Some(false)); - assert_eq!(profile.can_mute_user, Some(true)); - assert_eq!(profile.can_ignore_user, Some(false)); - } - - #[test] - fn test_parse_user_summary_sideload_structure() { - let value = json!({ - "user_summary": { - "days_visited": 100, - "posts_read_count": 500, - "likes_received": 200, - "likes_given": 150, - "topic_count": 30, - "post_count": 80, - "time_read": 36000, - "bookmark_count": 5, - "replies": [ - {"id": 1, "topic_id": 10, "like_count": 5} - ], - "top_categories": [ - {"id": 1, "name": "General", "topic_count": 10, "post_count": 20} - ] - }, - "topics": [ - {"id": 100, "title": "My Topic", "like_count": 10} - ], - "badges": [ - {"id": 1, "name": "First Post", "badge_type_id": 3, "grant_count": 1} - ] - }); - let summary = parse_user_summary_value(value).unwrap(); - assert_eq!(summary.stats.days_visited, 100); - assert_eq!(summary.stats.likes_received, 200); - assert_eq!(summary.top_topics.len(), 1); - assert_eq!(summary.top_topics[0].title, "My Topic"); - assert_eq!(summary.badges.len(), 1); - assert_eq!(summary.badges[0].name, "First Post"); - assert_eq!(summary.top_replies.len(), 1); - assert_eq!(summary.top_categories.len(), 1); - } - - #[test] - fn test_parse_user_summary_skips_malformed_items_and_coerces_stats() { - let value = json!({ - "user_summary": { - "days_visited": "100", - "posts_read_count": "500", - "likes_received": "200", - "likes_given": 150, - "topic_count": "30", - "post_count": "80", - "time_read": "36000", - "bookmark_count": "5", - "replies": [ - 1, - {"id": "1", "topic_id": "10", "like_count": "5"} - ], - "top_categories": [ - {"name": "missing id"}, - {"id": "1", "name": "General", "topic_count": "10", "post_count": "20"} - ], - "most_liked_users": [ - {"username": "alice", "count": "3"} - ] - }, - "topics": [ - {"title": "missing id"}, - {"id": "100", "title": "My Topic", "like_count": "10"} - ], - "badges": [ - 1, - {"id": "1", "name": "First Post", "badge_type_id": "3", "grant_count": "1"} - ] - }); - let summary = parse_user_summary_value(value).unwrap(); - assert_eq!(summary.stats.days_visited, 100); - assert_eq!(summary.stats.time_read, 36_000); - assert_eq!(summary.top_topics.len(), 1); - assert_eq!(summary.top_topics[0].id, 100); - assert_eq!(summary.top_replies.len(), 1); - assert_eq!(summary.top_replies[0].topic_id, 10); - assert_eq!(summary.top_categories.len(), 1); - assert_eq!(summary.top_categories[0].id, 1); - assert_eq!(summary.most_liked_users.len(), 1); - assert_eq!(summary.most_liked_users[0].username, "alice"); - assert_eq!(summary.badges.len(), 1); - assert_eq!(summary.badges[0].badge_type_id, 3); - } - - #[test] - fn test_parse_user_actions_array() { - let value = json!({ - "user_actions": [ - { - "action_type": 4, - "topic_id": 100, - "title": "My Topic", - "slug": "my-topic", - "username": "alice", - "created_at": "2024-01-01T00:00:00.000Z" - }, - { - "action_type": 5, - "topic_id": 200, - "title": "Other Topic" - } - ] - }); - let actions = parse_user_actions_value(value).unwrap(); - assert_eq!(actions.len(), 2); - assert_eq!(actions[0].action_type, Some(4)); - assert_eq!(actions[0].title.as_deref(), Some("My Topic")); - assert_eq!(actions[1].action_type, Some(5)); - } - - #[test] - fn test_parse_user_actions_skip_malformed_items() { - let value = json!({ - "user_actions": [ - 1, - { - "action_type": "4", - "topic_id": "100", - "title": "My Topic" - } - ] - }); - let actions = parse_user_actions_value(value).unwrap(); - assert_eq!(actions.len(), 1); - assert_eq!(actions[0].action_type, Some(4)); - assert_eq!(actions[0].topic_id, Some(100)); - } - - #[test] - fn test_parse_user_reactions_accepts_wrapper_payload() { - let value = json!({ - "reactions": [ - { - "id": "77", - "post_id": "9001", - "post": { - "topic_id": "123", - "post_number": "4", - "topic_title": "Fire topic", - "excerpt": "

Hello Fire

" - }, - "reaction": { - "reaction_value": "heart" - }, - "created_at": "2026-05-01T00:00:00Z" - } - ] - }); - - let response = parse_user_reactions_value(value).unwrap(); - assert_eq!(response.reactions.len(), 1); - let reaction = &response.reactions[0]; - assert_eq!(reaction.id, 77); - assert_eq!(reaction.post_id, 9001); - assert_eq!(reaction.topic_id, 123); - assert_eq!(reaction.post_number, Some(4)); - assert_eq!(reaction.topic_title.as_deref(), Some("Fire topic")); - assert_eq!(reaction.excerpt.as_deref(), Some("

Hello Fire

")); - assert_eq!(reaction.reaction_value.as_deref(), Some("heart")); - assert_eq!(reaction.created_at.as_deref(), Some("2026-05-01T00:00:00Z")); - } - - #[test] - fn test_parse_user_reactions_accepts_array_and_skips_malformed_items() { - let value = json!([ - 1, - { - "id": 78, - "post_id": 9002, - "topic_id": 124, - "post_number": 2, - "topic_title": "Flat topic", - "excerpt": "flat excerpt", - "reaction_value": "clap" - } - ]); - - let response = parse_user_reactions_value(value).unwrap(); - assert_eq!(response.reactions.len(), 1); - let reaction = &response.reactions[0]; - assert_eq!(reaction.id, 78); - assert_eq!(reaction.post_id, 9002); - assert_eq!(reaction.topic_id, 124); - assert_eq!(reaction.post_number, Some(2)); - assert_eq!(reaction.topic_title.as_deref(), Some("Flat topic")); - assert_eq!(reaction.reaction_value.as_deref(), Some("clap")); - } - - #[test] - fn test_parse_badge_value_unwraps_badge_envelope() { - let value = json!({ - "badge": { - "id": 7, - "name": "Great Reply", - "badge_type_id": 1, - "grant_count": 12, - "long_description": "

Detailed

" - } - }); - let badge = parse_badge_value(value).unwrap(); - assert_eq!(badge.id, 7); - assert_eq!(badge.name, "Great Reply"); - assert_eq!(badge.badge_type_id, 1); - assert_eq!(badge.grant_count, 12); - assert_eq!(badge.long_description.as_deref(), Some("

Detailed

")); - } - - #[test] - fn test_parse_follow_users_value_accepts_array_payload() { - let value = json!([ - { - "id": 1, - "username": "alice", - "name": "Alice", - "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" - } - ]); - let users = parse_follow_users_value(value).unwrap(); - assert_eq!(users.len(), 1); - assert_eq!(users[0].username, "alice"); - } - - #[test] - fn test_parse_follow_users_value_skips_malformed_items_and_coerces_scalars() { - let value = json!({ - "users": [ - 1, - { - "id": "1", - "username": "alice", - "name": "Alice" - } - ] - }); - let users = parse_follow_users_value(value).unwrap(); - assert_eq!(users.len(), 1); - assert_eq!(users[0].id, 1); - assert_eq!(users[0].username, "alice"); - } - - #[test] - fn test_parse_invite_links_value_accepts_pending_wrapper() { - let value = json!({ - "pending_invites": [ - { - "invite_url": "https://linux.do/invites/fire", - "invite": { - "id": 9, - "invite_key": "fire", - "max_redemptions_allowed": 5, - "redemption_count": 1, - "expired": false - } - } - ] - }); - let invites = parse_invite_links_value(value).unwrap(); - assert_eq!(invites.len(), 1); - assert_eq!(invites[0].invite_link, "https://linux.do/invites/fire"); - assert_eq!( - invites[0].invite.as_ref().and_then(|invite| invite.id), - Some(9) - ); - } - - #[test] - fn test_parse_invite_links_value_skips_malformed_items() { - let value = json!({ - "pending_invites": [ - 1, - { - "invite_url": "https://linux.do/invites/fire", - "invite": { - "id": "9", - "invite_key": "fire" - } - } - ] - }); - let invites = parse_invite_links_value(value).unwrap(); - assert_eq!(invites.len(), 1); - assert_eq!(invites[0].invite_link, "https://linux.do/invites/fire"); - assert_eq!( - invites[0].invite.as_ref().and_then(|invite| invite.id), - Some(9) - ); - } - - #[test] - fn test_parse_invite_link_value_promotes_flat_payload() { - let value = json!({ - "invite_key": "fire", - "max_redemptions_allowed": 3, - "redemption_count": 0 - }); - let invite = parse_invite_link_value(value).unwrap(); - assert_eq!(invite.invite_link, ""); - assert_eq!( - invite - .invite - .as_ref() - .and_then(|details| details.invite_key.as_deref()), - Some("fire") - ); - } -} diff --git a/crates/fire-core/src/user_payloads/activity.rs b/crates/fire-core/src/user_payloads/activity.rs new file mode 100644 index 00000000..dfb69bcd --- /dev/null +++ b/crates/fire-core/src/user_payloads/activity.rs @@ -0,0 +1,36 @@ +pub(crate) fn parse_user_actions_value(value: Value) -> Result, serde_json::Error> { + let actions_value = match value { + Value::Object(ref obj) if obj.contains_key("user_actions") => obj + .get("user_actions") + .cloned() + .unwrap_or(Value::Array(Vec::new())), + Value::Array(_) => value, + _ => Value::Array(Vec::new()), + }; + Ok(parse_array_items_lossy( + array_items(Some(&actions_value)), + "user action item", + parse_user_action_value, + )) +} + +fn parse_user_action_value(value: &Value) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("user action item was not an object"))?; + Ok(UserAction { + action_type: integer_i32(object.get("action_type")), + topic_id: integer_u64(object.get("topic_id")), + post_id: integer_u64(object.get("post_id")), + post_number: integer_u32(object.get("post_number")), + title: scalar_string(object.get("title")), + slug: scalar_string(object.get("slug")), + username: scalar_string(object.get("username")), + acting_username: scalar_string(object.get("acting_username")), + acting_avatar_template: scalar_string(object.get("acting_avatar_template")), + category_id: integer_u64(object.get("category_id")), + excerpt: scalar_string(object.get("excerpt")), + created_at: scalar_string(object.get("created_at")), + }) +} + diff --git a/crates/fire-core/src/user_payloads/badges.rs b/crates/fire-core/src/user_payloads/badges.rs new file mode 100644 index 00000000..ae796ba8 --- /dev/null +++ b/crates/fire-core/src/user_payloads/badges.rs @@ -0,0 +1,27 @@ +pub(crate) fn parse_badge_value(value: Value) -> Result { + let badge_value = match value { + Value::Object(ref obj) if obj.contains_key("badge") => { + obj.get("badge").cloned().unwrap_or(value.clone()) + } + other => other, + }; + parse_badge_item(&badge_value) +} + +fn parse_badge_item(value: &Value) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("badge response root was not an object"))?; + Ok(Badge { + id: integer_u64(object.get("id")).unwrap_or_default(), + name: scalar_string(object.get("name")).unwrap_or_default(), + description: scalar_string(object.get("description")), + badge_type_id: integer_u32(object.get("badge_type_id")).unwrap_or_default(), + image_url: scalar_string(object.get("image_url")), + icon: scalar_string(object.get("icon")), + slug: scalar_string(object.get("slug")), + grant_count: integer_u32(object.get("grant_count")).unwrap_or_default(), + long_description: scalar_string(object.get("long_description")), + }) +} + diff --git a/crates/fire-core/src/user_payloads/helpers.rs b/crates/fire-core/src/user_payloads/helpers.rs new file mode 100644 index 00000000..3b40c452 --- /dev/null +++ b/crates/fire-core/src/user_payloads/helpers.rs @@ -0,0 +1,7 @@ +fn array_items(value: Option<&Value>) -> &[Value] { + match value { + Some(Value::Array(items)) => items.as_slice(), + _ => &[], + } +} + diff --git a/crates/fire-core/src/user_payloads/invites.rs b/crates/fire-core/src/user_payloads/invites.rs new file mode 100644 index 00000000..fb15c86c --- /dev/null +++ b/crates/fire-core/src/user_payloads/invites.rs @@ -0,0 +1,79 @@ +pub(crate) fn parse_invite_links_value(value: Value) -> Result, serde_json::Error> { + let mut items = Vec::new(); + match value { + Value::Array(values) => items.extend(values), + Value::Object(object) => { + let invites = object + .get("invites") + .or_else(|| object.get("pending_invites")) + .or_else(|| object.get("invited")) + .or_else(|| object.get("pending")) + .cloned(); + if let Some(Value::Array(values)) = invites { + items.extend(values); + } else if object.contains_key("invite") + || object.contains_key("invite_link") + || object.contains_key("invite_key") + || object.contains_key("invite_url") + || object.contains_key("url") + || object.contains_key("link") + { + items.push(Value::Object(object)); + } + } + _ => {} + } + + Ok(parse_array_items_lossy( + &items, + "invite link item", + |item| parse_invite_link_value(item.clone()), + )) +} + +pub(crate) fn parse_invite_link_value(value: Value) -> Result { + let Value::Object(mut object) = value else { + return Err(invalid_json("invite link response root was not an object")); + }; + + let invite_link = scalar_string(object.get("invite_link")) + .or_else(|| scalar_string(object.get("invite_url"))) + .or_else(|| scalar_string(object.get("url"))) + .or_else(|| scalar_string(object.get("link"))) + .unwrap_or_default(); + + let invite = match object.remove("invite") { + Some(Value::Object(invite_object)) => { + Some(parse_invite_link_details_object(&invite_object)) + } + Some(_) => None, + None => { + if object.contains_key("invite_key") + || object.contains_key("expires_at") + || object.contains_key("max_redemptions_allowed") + { + Some(parse_invite_link_details_object(&object)) + } else { + None + } + } + }; + + Ok(InviteLink { + invite_link, + invite, + }) +} + +fn parse_invite_link_details_object(object: &serde_json::Map) -> InviteLinkDetails { + InviteLinkDetails { + id: integer_u64(object.get("id")), + invite_key: scalar_string(object.get("invite_key")), + max_redemptions_allowed: integer_u32(object.get("max_redemptions_allowed")), + redemption_count: integer_u32(object.get("redemption_count")), + expired: object.get("expired").map(|value| boolean(Some(value))), + created_at: scalar_string(object.get("created_at")), + expires_at: scalar_string(object.get("expires_at")), + } +} + diff --git a/crates/fire-core/src/user_payloads/mod.rs b/crates/fire-core/src/user_payloads/mod.rs new file mode 100644 index 00000000..466cbcba --- /dev/null +++ b/crates/fire-core/src/user_payloads/mod.rs @@ -0,0 +1,21 @@ +use fire_models::{ + Badge, FollowUser, InviteLink, InviteLinkDetails, ProfileSummaryLink, ProfileSummaryReply, + ProfileSummaryTopCategory, ProfileSummaryTopic, ProfileSummaryUserReference, UserAction, + UserProfile, UserReaction, UserReactionsResponse, UserSummaryResponse, UserSummaryStats, +}; +use serde_json::{Map, Value}; + +use crate::json_helpers::{ + boolean, integer_i32, integer_u32, integer_u64, invalid_json, optional_boolean, + parse_array_items_lossy, scalar_string, +}; + +include!("profile.rs"); +include!("summary.rs"); +include!("activity.rs"); +include!("reactions.rs"); +include!("badges.rs"); +include!("social.rs"); +include!("invites.rs"); +include!("helpers.rs"); +include!("tests.rs"); diff --git a/crates/fire-core/src/user_payloads/profile.rs b/crates/fire-core/src/user_payloads/profile.rs new file mode 100644 index 00000000..9f45eac0 --- /dev/null +++ b/crates/fire-core/src/user_payloads/profile.rs @@ -0,0 +1,53 @@ +pub(crate) fn parse_user_profile_value(value: Value) -> Result { + let user_value = match value { + Value::Object(ref obj) if obj.contains_key("user") => { + obj.get("user").cloned().unwrap_or(value.clone()) + } + other => other, + }; + let Value::Object(object) = user_value else { + return Err(invalid_json("user profile response root was not an object")); + }; + + Ok(UserProfile { + id: integer_u64(object.get("id")).unwrap_or_default(), + username: scalar_string(object.get("username")).unwrap_or_default(), + name: scalar_string(object.get("name")), + avatar_template: scalar_string(object.get("avatar_template")), + trust_level: integer_u32(object.get("trust_level")), + bio_cooked: scalar_string(object.get("bio_cooked")), + bio_plain_text: scalar_string(object.get("bio_cooked")).and_then(|html| { + let plain = crate::plain_text_from_html(&html); + let trimmed = plain.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } + }), + created_at: scalar_string(object.get("created_at")), + last_seen_at: scalar_string(object.get("last_seen_at")), + last_posted_at: scalar_string(object.get("last_posted_at")), + flair_name: scalar_string(object.get("flair_name")), + flair_url: scalar_string(object.get("flair_url")), + flair_bg_color: scalar_string(object.get("flair_bg_color")), + flair_color: scalar_string(object.get("flair_color")), + profile_background_upload_url: scalar_string(object.get("profile_background_upload_url")), + card_background_upload_url: scalar_string(object.get("card_background_upload_url")), + total_followers: integer_u32(object.get("total_followers")), + total_following: integer_u32(object.get("total_following")), + can_follow: optional_boolean(object.get("can_follow")), + is_followed: optional_boolean(object.get("is_followed")), + can_send_private_message_to_user: optional_boolean( + object.get("can_send_private_message_to_user"), + ), + muted: optional_boolean(object.get("muted")), + ignored: optional_boolean(object.get("ignored")), + can_mute_user: optional_boolean(object.get("can_mute_user")), + can_ignore_user: optional_boolean(object.get("can_ignore_user")), + gamification_score: integer_u32(object.get("gamification_score")), + suspended_till: scalar_string(object.get("suspended_till")), + silenced_till: scalar_string(object.get("silenced_till")), + }) +} + diff --git a/crates/fire-core/src/user_payloads/reactions.rs b/crates/fire-core/src/user_payloads/reactions.rs new file mode 100644 index 00000000..680d97cf --- /dev/null +++ b/crates/fire-core/src/user_payloads/reactions.rs @@ -0,0 +1,58 @@ +pub(crate) fn parse_user_reactions_value( + value: Value, +) -> Result { + let reactions_value = match value { + Value::Array(_) => value, + Value::Object(ref obj) => obj + .get("reactions") + .or_else(|| obj.get("posts")) + .cloned() + .unwrap_or(Value::Array(Vec::new())), + _ => Value::Array(Vec::new()), + }; + + Ok(UserReactionsResponse { + reactions: parse_array_items_lossy( + array_items(Some(&reactions_value)), + "user reaction item", + parse_user_reaction_value, + ), + }) +} + +fn parse_user_reaction_value(value: &Value) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("user reaction item was not an object"))?; + let post_object = object.get("post").and_then(Value::as_object); + let reaction_object = object.get("reaction").and_then(Value::as_object); + let id = integer_u64(object.get("id")) + .ok_or_else(|| invalid_json("user reaction item did not contain an id"))?; + let post_id = integer_u64(object.get("post_id")) + .or_else(|| post_object.and_then(|post| integer_u64(post.get("id")))) + .ok_or_else(|| invalid_json("user reaction item did not contain a post_id"))?; + + Ok(UserReaction { + id, + post_id, + topic_id: post_object + .and_then(|post| integer_u64(post.get("topic_id"))) + .or_else(|| integer_u64(object.get("topic_id"))) + .unwrap_or_default(), + post_number: post_object + .and_then(|post| integer_u32(post.get("post_number"))) + .or_else(|| integer_u32(object.get("post_number"))), + topic_title: post_object + .and_then(|post| scalar_string(post.get("topic_title"))) + .or_else(|| scalar_string(object.get("topic_title"))) + .or_else(|| scalar_string(object.get("title"))), + excerpt: post_object + .and_then(|post| scalar_string(post.get("excerpt"))) + .or_else(|| scalar_string(object.get("excerpt"))), + reaction_value: reaction_object + .and_then(|reaction| scalar_string(reaction.get("reaction_value"))) + .or_else(|| scalar_string(object.get("reaction_value"))), + created_at: scalar_string(object.get("created_at")), + }) +} + diff --git a/crates/fire-core/src/user_payloads/social.rs b/crates/fire-core/src/user_payloads/social.rs new file mode 100644 index 00000000..fca84bb0 --- /dev/null +++ b/crates/fire-core/src/user_payloads/social.rs @@ -0,0 +1,37 @@ +pub(crate) fn parse_follow_users_value(value: Value) -> Result, serde_json::Error> { + let list_value = match value { + Value::Array(_) => value, + Value::Object(ref obj) => obj + .get("users") + .or_else(|| obj.get("following")) + .or_else(|| obj.get("followers")) + .cloned() + .unwrap_or(Value::Array(Vec::new())), + _ => Value::Array(Vec::new()), + }; + Ok(parse_array_items_lossy( + array_items(Some(&list_value)), + "follow user item", + parse_follow_user_value, + )) +} + +fn parse_follow_user_value(value: &Value) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("follow user item was not an object"))?; + let id = integer_u64(object.get("id")).unwrap_or_default(); + let username = scalar_string(object.get("username")).unwrap_or_default(); + if id == 0 && username.is_empty() { + return Err(invalid_json( + "follow user item did not contain an id or username", + )); + } + Ok(FollowUser { + id, + username, + name: scalar_string(object.get("name")), + avatar_template: scalar_string(object.get("avatar_template")), + }) +} + diff --git a/crates/fire-core/src/user_payloads/summary.rs b/crates/fire-core/src/user_payloads/summary.rs new file mode 100644 index 00000000..31442c72 --- /dev/null +++ b/crates/fire-core/src/user_payloads/summary.rs @@ -0,0 +1,178 @@ +pub(crate) fn parse_user_summary_value( + value: Value, +) -> Result { + let root = match &value { + Value::Object(obj) => obj, + _ => return Err(invalid_json("user summary response root was not an object")), + }; + + let empty = Map::new(); + let summary_obj = root + .get("user_summary") + .and_then(Value::as_object) + .unwrap_or(&empty); + let stats = parse_user_summary_stats_object(summary_obj); + let top_replies = parse_array_items_lossy( + array_items( + summary_obj + .get("replies") + .or_else(|| summary_obj.get("top_replies")), + ), + "profile summary reply", + parse_profile_summary_reply_value, + ); + let top_links = parse_array_items_lossy( + array_items( + summary_obj + .get("links") + .or_else(|| summary_obj.get("top_links")), + ), + "profile summary link", + parse_profile_summary_link_value, + ); + let top_categories = parse_array_items_lossy( + array_items(summary_obj.get("top_categories")), + "profile summary top category", + parse_profile_summary_top_category_value, + ); + let most_replied_to_users = parse_array_items_lossy( + array_items(summary_obj.get("most_replied_to_users")), + "profile summary user reference", + parse_profile_summary_user_reference_value, + ); + let most_liked_by_users = parse_array_items_lossy( + array_items(summary_obj.get("most_liked_by_users")), + "profile summary user reference", + parse_profile_summary_user_reference_value, + ); + let most_liked_users = parse_array_items_lossy( + array_items(summary_obj.get("most_liked_users")), + "profile summary user reference", + parse_profile_summary_user_reference_value, + ); + let top_topics = parse_array_items_lossy( + array_items(root.get("topics")), + "profile summary topic", + parse_profile_summary_topic_value, + ); + let badges = + parse_array_items_lossy(array_items(root.get("badges")), "badge", parse_badge_item); + + Ok(UserSummaryResponse { + stats, + top_topics, + top_replies, + top_links, + top_categories, + most_replied_to_users, + most_liked_by_users, + most_liked_users, + badges, + }) +} + +fn parse_user_summary_stats_object(object: &Map) -> UserSummaryStats { + UserSummaryStats { + days_visited: integer_u32(object.get("days_visited")).unwrap_or_default(), + posts_read_count: integer_u32(object.get("posts_read_count")).unwrap_or_default(), + likes_received: integer_u32(object.get("likes_received")).unwrap_or_default(), + likes_given: integer_u32(object.get("likes_given")).unwrap_or_default(), + topic_count: integer_u32(object.get("topic_count")).unwrap_or_default(), + post_count: integer_u32(object.get("post_count")).unwrap_or_default(), + time_read: integer_u64(object.get("time_read")).unwrap_or_default(), + bookmark_count: integer_u32(object.get("bookmark_count")).unwrap_or_default(), + } +} + +fn parse_profile_summary_topic_value( + value: &Value, +) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("profile summary topic item was not an object"))?; + let id = integer_u64(object.get("id")) + .ok_or_else(|| invalid_json("profile summary topic item did not contain an id"))?; + Ok(ProfileSummaryTopic { + id, + title: scalar_string(object.get("title")).unwrap_or_default(), + slug: scalar_string(object.get("slug")), + like_count: integer_u32(object.get("like_count")).unwrap_or_default(), + category_id: integer_u64(object.get("category_id")), + created_at: scalar_string(object.get("created_at")), + }) +} + +fn parse_profile_summary_reply_value( + value: &Value, +) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("profile summary reply item was not an object"))?; + let id = integer_u64(object.get("id")) + .ok_or_else(|| invalid_json("profile summary reply item did not contain an id"))?; + let topic_id = integer_u64(object.get("topic_id")) + .ok_or_else(|| invalid_json("profile summary reply item did not contain a topic_id"))?; + Ok(ProfileSummaryReply { + id, + topic_id, + title: scalar_string(object.get("title")), + like_count: integer_u32(object.get("like_count")).unwrap_or_default(), + created_at: scalar_string(object.get("created_at")), + post_number: integer_u32(object.get("post_number")), + }) +} + +fn parse_profile_summary_link_value( + value: &Value, +) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("profile summary link item was not an object"))?; + let url = scalar_string(object.get("url")) + .ok_or_else(|| invalid_json("profile summary link item did not contain a url"))?; + Ok(ProfileSummaryLink { + url, + title: scalar_string(object.get("title")), + clicks: integer_u32(object.get("clicks")).unwrap_or_default(), + topic_id: integer_u64(object.get("topic_id")), + post_number: integer_u32(object.get("post_number")), + }) +} + +fn parse_profile_summary_top_category_value( + value: &Value, +) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("profile summary top category item was not an object"))?; + let id = integer_u64(object.get("id")) + .ok_or_else(|| invalid_json("profile summary top category item did not contain an id"))?; + Ok(ProfileSummaryTopCategory { + id, + name: scalar_string(object.get("name")), + topic_count: integer_u32(object.get("topic_count")).unwrap_or_default(), + post_count: integer_u32(object.get("post_count")).unwrap_or_default(), + }) +} + +fn parse_profile_summary_user_reference_value( + value: &Value, +) -> Result { + let object = value + .as_object() + .ok_or_else(|| invalid_json("profile summary user reference item was not an object"))?; + let id = integer_u64(object.get("id")).unwrap_or_default(); + let username = scalar_string(object.get("username")).unwrap_or_default(); + if id == 0 && username.is_empty() { + return Err(invalid_json( + "profile summary user reference item did not contain an id or username", + )); + } + Ok(ProfileSummaryUserReference { + id, + username, + avatar_template: scalar_string(object.get("avatar_template")), + count: integer_u32(object.get("count")).unwrap_or_default(), + }) +} + diff --git a/crates/fire-core/src/user_payloads/tests.rs b/crates/fire-core/src/user_payloads/tests.rs new file mode 100644 index 00000000..276b7d23 --- /dev/null +++ b/crates/fire-core/src/user_payloads/tests.rs @@ -0,0 +1,388 @@ +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn test_parse_user_profile_unwraps_user_envelope() { + let value = json!({ + "user": { + "id": 42, + "username": "alice", + "trust_level": 3, + "bio_cooked": "

Hello

" + } + }); + let profile = parse_user_profile_value(value).unwrap(); + assert_eq!(profile.id, 42); + assert_eq!(profile.username, "alice"); + assert_eq!(profile.trust_level, Some(3)); + assert_eq!(profile.bio_cooked.as_deref(), Some("

Hello

")); + assert_eq!(profile.bio_plain_text.as_deref(), Some("Hello")); + } + + #[test] + fn test_parse_user_profile_bare_fallback() { + let value = json!({ + "id": 99, + "username": "bob", + "name": "Bob Smith" + }); + let profile = parse_user_profile_value(value).unwrap(); + assert_eq!(profile.id, 99); + assert_eq!(profile.username, "bob"); + assert_eq!(profile.name.as_deref(), Some("Bob Smith")); + } + + #[test] + fn test_parse_user_profile_nullable_follow_fields() { + let value = json!({ + "user": { + "id": 1, + "username": "test" + } + }); + let profile = parse_user_profile_value(value).unwrap(); + assert_eq!(profile.can_follow, None); + assert_eq!(profile.is_followed, None); + assert_eq!(profile.total_followers, None); + assert_eq!(profile.total_following, None); + } + + #[test] + fn test_parse_user_profile_coerces_scalar_fields() { + let value = json!({ + "user": { + "id": "7", + "username": "alice", + "trust_level": "3", + "total_followers": "12", + "total_following": 5, + "can_follow": "1", + "is_followed": 0, + "muted": "1", + "ignored": false, + "can_mute_user": true, + "can_ignore_user": "0" + } + }); + let profile = parse_user_profile_value(value).unwrap(); + assert_eq!(profile.id, 7); + assert_eq!(profile.trust_level, Some(3)); + assert_eq!(profile.total_followers, Some(12)); + assert_eq!(profile.total_following, Some(5)); + assert_eq!(profile.can_follow, Some(true)); + assert_eq!(profile.is_followed, Some(false)); + assert_eq!(profile.muted, Some(true)); + assert_eq!(profile.ignored, Some(false)); + assert_eq!(profile.can_mute_user, Some(true)); + assert_eq!(profile.can_ignore_user, Some(false)); + } + + #[test] + fn test_parse_user_summary_sideload_structure() { + let value = json!({ + "user_summary": { + "days_visited": 100, + "posts_read_count": 500, + "likes_received": 200, + "likes_given": 150, + "topic_count": 30, + "post_count": 80, + "time_read": 36000, + "bookmark_count": 5, + "replies": [ + {"id": 1, "topic_id": 10, "like_count": 5} + ], + "top_categories": [ + {"id": 1, "name": "General", "topic_count": 10, "post_count": 20} + ] + }, + "topics": [ + {"id": 100, "title": "My Topic", "like_count": 10} + ], + "badges": [ + {"id": 1, "name": "First Post", "badge_type_id": 3, "grant_count": 1} + ] + }); + let summary = parse_user_summary_value(value).unwrap(); + assert_eq!(summary.stats.days_visited, 100); + assert_eq!(summary.stats.likes_received, 200); + assert_eq!(summary.top_topics.len(), 1); + assert_eq!(summary.top_topics[0].title, "My Topic"); + assert_eq!(summary.badges.len(), 1); + assert_eq!(summary.badges[0].name, "First Post"); + assert_eq!(summary.top_replies.len(), 1); + assert_eq!(summary.top_categories.len(), 1); + } + + #[test] + fn test_parse_user_summary_skips_malformed_items_and_coerces_stats() { + let value = json!({ + "user_summary": { + "days_visited": "100", + "posts_read_count": "500", + "likes_received": "200", + "likes_given": 150, + "topic_count": "30", + "post_count": "80", + "time_read": "36000", + "bookmark_count": "5", + "replies": [ + 1, + {"id": "1", "topic_id": "10", "like_count": "5"} + ], + "top_categories": [ + {"name": "missing id"}, + {"id": "1", "name": "General", "topic_count": "10", "post_count": "20"} + ], + "most_liked_users": [ + {"username": "alice", "count": "3"} + ] + }, + "topics": [ + {"title": "missing id"}, + {"id": "100", "title": "My Topic", "like_count": "10"} + ], + "badges": [ + 1, + {"id": "1", "name": "First Post", "badge_type_id": "3", "grant_count": "1"} + ] + }); + let summary = parse_user_summary_value(value).unwrap(); + assert_eq!(summary.stats.days_visited, 100); + assert_eq!(summary.stats.time_read, 36_000); + assert_eq!(summary.top_topics.len(), 1); + assert_eq!(summary.top_topics[0].id, 100); + assert_eq!(summary.top_replies.len(), 1); + assert_eq!(summary.top_replies[0].topic_id, 10); + assert_eq!(summary.top_categories.len(), 1); + assert_eq!(summary.top_categories[0].id, 1); + assert_eq!(summary.most_liked_users.len(), 1); + assert_eq!(summary.most_liked_users[0].username, "alice"); + assert_eq!(summary.badges.len(), 1); + assert_eq!(summary.badges[0].badge_type_id, 3); + } + + #[test] + fn test_parse_user_actions_array() { + let value = json!({ + "user_actions": [ + { + "action_type": 4, + "topic_id": 100, + "title": "My Topic", + "slug": "my-topic", + "username": "alice", + "created_at": "2024-01-01T00:00:00.000Z" + }, + { + "action_type": 5, + "topic_id": 200, + "title": "Other Topic" + } + ] + }); + let actions = parse_user_actions_value(value).unwrap(); + assert_eq!(actions.len(), 2); + assert_eq!(actions[0].action_type, Some(4)); + assert_eq!(actions[0].title.as_deref(), Some("My Topic")); + assert_eq!(actions[1].action_type, Some(5)); + } + + #[test] + fn test_parse_user_actions_skip_malformed_items() { + let value = json!({ + "user_actions": [ + 1, + { + "action_type": "4", + "topic_id": "100", + "title": "My Topic" + } + ] + }); + let actions = parse_user_actions_value(value).unwrap(); + assert_eq!(actions.len(), 1); + assert_eq!(actions[0].action_type, Some(4)); + assert_eq!(actions[0].topic_id, Some(100)); + } + + #[test] + fn test_parse_user_reactions_accepts_wrapper_payload() { + let value = json!({ + "reactions": [ + { + "id": "77", + "post_id": "9001", + "post": { + "topic_id": "123", + "post_number": "4", + "topic_title": "Fire topic", + "excerpt": "

Hello Fire

" + }, + "reaction": { + "reaction_value": "heart" + }, + "created_at": "2026-05-01T00:00:00Z" + } + ] + }); + + let response = parse_user_reactions_value(value).unwrap(); + assert_eq!(response.reactions.len(), 1); + let reaction = &response.reactions[0]; + assert_eq!(reaction.id, 77); + assert_eq!(reaction.post_id, 9001); + assert_eq!(reaction.topic_id, 123); + assert_eq!(reaction.post_number, Some(4)); + assert_eq!(reaction.topic_title.as_deref(), Some("Fire topic")); + assert_eq!(reaction.excerpt.as_deref(), Some("

Hello Fire

")); + assert_eq!(reaction.reaction_value.as_deref(), Some("heart")); + assert_eq!(reaction.created_at.as_deref(), Some("2026-05-01T00:00:00Z")); + } + + #[test] + fn test_parse_user_reactions_accepts_array_and_skips_malformed_items() { + let value = json!([ + 1, + { + "id": 78, + "post_id": 9002, + "topic_id": 124, + "post_number": 2, + "topic_title": "Flat topic", + "excerpt": "flat excerpt", + "reaction_value": "clap" + } + ]); + + let response = parse_user_reactions_value(value).unwrap(); + assert_eq!(response.reactions.len(), 1); + let reaction = &response.reactions[0]; + assert_eq!(reaction.id, 78); + assert_eq!(reaction.post_id, 9002); + assert_eq!(reaction.topic_id, 124); + assert_eq!(reaction.post_number, Some(2)); + assert_eq!(reaction.topic_title.as_deref(), Some("Flat topic")); + assert_eq!(reaction.reaction_value.as_deref(), Some("clap")); + } + + #[test] + fn test_parse_badge_value_unwraps_badge_envelope() { + let value = json!({ + "badge": { + "id": 7, + "name": "Great Reply", + "badge_type_id": 1, + "grant_count": 12, + "long_description": "

Detailed

" + } + }); + let badge = parse_badge_value(value).unwrap(); + assert_eq!(badge.id, 7); + assert_eq!(badge.name, "Great Reply"); + assert_eq!(badge.badge_type_id, 1); + assert_eq!(badge.grant_count, 12); + assert_eq!(badge.long_description.as_deref(), Some("

Detailed

")); + } + + #[test] + fn test_parse_follow_users_value_accepts_array_payload() { + let value = json!([ + { + "id": 1, + "username": "alice", + "name": "Alice", + "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" + } + ]); + let users = parse_follow_users_value(value).unwrap(); + assert_eq!(users.len(), 1); + assert_eq!(users[0].username, "alice"); + } + + #[test] + fn test_parse_follow_users_value_skips_malformed_items_and_coerces_scalars() { + let value = json!({ + "users": [ + 1, + { + "id": "1", + "username": "alice", + "name": "Alice" + } + ] + }); + let users = parse_follow_users_value(value).unwrap(); + assert_eq!(users.len(), 1); + assert_eq!(users[0].id, 1); + assert_eq!(users[0].username, "alice"); + } + + #[test] + fn test_parse_invite_links_value_accepts_pending_wrapper() { + let value = json!({ + "pending_invites": [ + { + "invite_url": "https://linux.do/invites/fire", + "invite": { + "id": 9, + "invite_key": "fire", + "max_redemptions_allowed": 5, + "redemption_count": 1, + "expired": false + } + } + ] + }); + let invites = parse_invite_links_value(value).unwrap(); + assert_eq!(invites.len(), 1); + assert_eq!(invites[0].invite_link, "https://linux.do/invites/fire"); + assert_eq!( + invites[0].invite.as_ref().and_then(|invite| invite.id), + Some(9) + ); + } + + #[test] + fn test_parse_invite_links_value_skips_malformed_items() { + let value = json!({ + "pending_invites": [ + 1, + { + "invite_url": "https://linux.do/invites/fire", + "invite": { + "id": "9", + "invite_key": "fire" + } + } + ] + }); + let invites = parse_invite_links_value(value).unwrap(); + assert_eq!(invites.len(), 1); + assert_eq!(invites[0].invite_link, "https://linux.do/invites/fire"); + assert_eq!( + invites[0].invite.as_ref().and_then(|invite| invite.id), + Some(9) + ); + } + + #[test] + fn test_parse_invite_link_value_promotes_flat_payload() { + let value = json!({ + "invite_key": "fire", + "max_redemptions_allowed": 3, + "redemption_count": 0 + }); + let invite = parse_invite_link_value(value).unwrap(); + assert_eq!(invite.invite_link, ""); + assert_eq!( + invite + .invite + .as_ref() + .and_then(|details| details.invite_key.as_deref()), + Some("fire") + ); + } +} diff --git a/crates/fire-core/tests/network.rs b/crates/fire-core/tests/network.rs index f6b73252..147e5ade 100644 --- a/crates/fire-core/tests/network.rs +++ b/crates/fire-core/tests/network.rs @@ -23,4837 +23,19 @@ use tokio::{ time::{sleep, Duration}, }; -#[tokio::test] -async fn fetch_topic_list_parses_latest_payload() { - let responses = vec![raw_json_response( - 200, - "application/json", - &sample_latest_json(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("topic list"); - let _ = server.shutdown().await; - - assert_eq!(response.topics.len(), 1); - assert_eq!(response.topics[0].id, 123); - assert_eq!(response.topics[0].title, "Fire topic"); - assert_eq!( - response.topics[0].tags, - vec![ - TopicTag { - id: None, - name: "rust".into(), - slug: None, - }, - TopicTag { - id: None, - name: "linuxdo".into(), - slug: None, - }, - ] - ); - assert_eq!(response.users[0].username, "alice"); - assert_eq!(response.more_topics_url.as_deref(), Some("/latest?page=1")); - assert_eq!(response.next_page, Some(1)); - assert_eq!(response.rows.len(), 1); - assert_eq!(response.rows[0].topic.id, 123); - assert_eq!( - response.rows[0].excerpt_text.as_deref(), - Some("topic excerpt") - ); - assert_eq!( - response.rows[0].original_poster_username.as_deref(), - Some("alice") - ); - assert_eq!( - response.rows[0].original_poster_avatar_template.as_deref(), - Some("/user_avatar/linux.do/alice/{size}/1_2.png") - ); - assert_eq!(response.rows[0].tag_names, vec!["rust", "linuxdo"]); - assert_eq!( - response.rows[0].status_labels, - vec!["Unread 2".to_string(), "New 1".to_string()] - ); - assert!(!response.rows[0].is_pinned); - assert!(!response.rows[0].is_closed); - assert!(!response.rows[0].is_archived); - assert!(!response.rows[0].has_accepted_answer); - assert!(response.rows[0].has_unread_posts); - assert_eq!( - response.rows[0].created_timestamp_unix_ms, - Some(1_774_656_000_000) - ); - assert_eq!( - response.rows[0].activity_timestamp_unix_ms, - Some(1_774_659_600_000) - ); - assert_eq!( - response.rows[0].last_poster_username.as_deref(), - Some("alice") - ); - assert!(!response.is_cached); -} - -#[tokio::test] -async fn fetch_topic_list_returns_cached_page_on_network_error() { - let responses = vec![raw_json_response( - 200, - "application/json", - &sample_latest_json(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let live = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("live topic list"); - assert!(!live.is_cached); - - let cached = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("cached topic list"); - let _ = server.shutdown().await; - - assert!(cached.is_cached); - assert_eq!(cached.rows.len(), 1); - assert_eq!(cached.rows[0].topic.id, live.rows[0].topic.id); -} - -#[tokio::test] -async fn fetch_topic_list_category_scope_sends_primary_and_additional_tags() { - let responses = vec![raw_json_response( - 200, - "application/json", - &sample_latest_json(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - page: Some(2), - category_slug: Some("rust".into()), - category_id: Some(2), - parent_category_slug: Some("dev".into()), - tag: Some("swift".into()), - additional_tags: vec!["ios".into()], - match_all_tags: true, - ..TopicListQuery::default() - }) - .await - .expect("topic list"); - let requests = server.shutdown_with_requests().await; - - assert!(requests[0].contains( - "GET /c/dev/rust/2/l/latest.json?no_definitions=true&page=2&tags%5B%5D=swift&tags%5B%5D=ios&match_all_tags=true HTTP/1.1" - )); -} - -#[tokio::test] -async fn fetch_private_message_mailboxes_use_username_routes_and_parse_participants() { - let payload = r#"{ - "topic_list": { - "topics": [ - { - "id": 456, - "title": "Fire private message", - "slug": "fire-private-message", - "posts_count": 3, - "reply_count": 2, - "views": 12, - "like_count": 1, - "excerpt": "hello from bob", - "created_at": "2026-04-11T00:00:00Z", - "last_posted_at": "2026-04-11T00:05:00Z", - "last_poster_username": "bob", - "pinned": false, - "visible": true, - "closed": false, - "archived": false, - "tags": [], - "posters": [], - "participants": [ - { - "id": 1, - "username": "alice", - "name": "Alice", - "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" - }, - { - "id": 2, - "username": "bob", - "name": "Bob", - "avatar_template": "/user_avatar/linux.do/bob/{size}/1_2.png" - } - ], - "unseen": false, - "unread_posts": 1, - "new_posts": 0, - "highest_post_number": 3 - } - ], - "more_topics_url": "/topics/private-messages/alice?page=2" - }, - "users": [ - { - "id": 2, - "username": "bob", - "avatar_template": "/user_avatar/linux.do/bob/{size}/1_2.png" - } - ] -}"#; - let server = TestServer::spawn(vec![ - raw_json_response(200, "application/json", payload), - raw_json_response(200, "application/json", payload), - ]) - .await - .expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let inbox = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::PrivateMessagesInbox, - page: Some(2), - ..TopicListQuery::default() - }) - .await - .expect("pm inbox"); - let sent = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::PrivateMessagesSent, - page: Some(3), - ..TopicListQuery::default() - }) - .await - .expect("pm sent"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(inbox.topics.len(), 1); - assert_eq!(inbox.topics[0].participants.len(), 2); - assert_eq!( - inbox.topics[0].participants[0].username.as_deref(), - Some("alice") - ); - assert_eq!(inbox.topics[0].participants[1].name.as_deref(), Some("Bob")); - assert_eq!( - inbox.rows[0].topic.participants[1] - .avatar_template - .as_deref(), - Some("/user_avatar/linux.do/bob/{size}/1_2.png") - ); - assert_eq!(inbox.next_page, Some(2)); - assert_eq!(sent.topics[0].id, 456); - assert_eq!(requests.len(), 2); - assert!(requests[0] - .contains("GET /topics/private-messages/alice.json?no_definitions=true&page=2 HTTP/1.1")); - assert!(requests[1].contains( - "GET /topics/private-messages-sent/alice.json?no_definitions=true&page=3 HTTP/1.1" - )); -} - -#[tokio::test] -async fn fetch_topic_list_tolerates_object_poster_metadata_fields() { - let payload = sample_latest_json() - .replace( - r#""description": "Original Poster""#, - r#""description": {"localized": "Original Poster"}"#, - ) - .replace(r#""extras": "latest""#, r#""extras": {"role": "latest"}"#); - let responses = vec![raw_json_response(200, "application/json", &payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("topic list"); - let _ = server.shutdown().await; - - assert_eq!(response.topics.len(), 1); - assert_eq!(response.topics[0].posters.len(), 1); - assert_eq!(response.topics[0].posters[0].description, None); - assert_eq!(response.topics[0].posters[0].extras, None); -} - -#[tokio::test] -async fn fetch_topic_list_tolerates_object_tags_and_null_counters() { - let payload = sample_latest_json() - .replace( - r#""tags": ["rust", "linuxdo"]"#, - r#""tags": [{"id": 1451, "name": "Rust", "slug": "rust"}, {"id": 99, "name": "LinuxDo", "slug": "linuxdo"}]"#, - ) - .replace(r#""unread_posts": 2"#, r#""unread_posts": null"#) - .replace(r#""new_posts": 1"#, r#""new_posts": null"#) - .replace(r#""can_have_answer": true"#, r#""can_have_answer": null"#); - let responses = vec![raw_json_response(200, "application/json", &payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("topic list"); - let _ = server.shutdown().await; - - assert_eq!(response.topics.len(), 1); - assert_eq!( - response.topics[0].tags, - vec![ - TopicTag { - id: Some(1451), - name: "Rust".into(), - slug: Some("rust".into()), - }, - TopicTag { - id: Some(99), - name: "LinuxDo".into(), - slug: Some("linuxdo".into()), - }, - ] - ); - assert_eq!(response.topics[0].unread_posts, 0); - assert_eq!(response.topics[0].new_posts, 0); - assert!(!response.topics[0].can_have_answer); - assert_eq!(response.rows[0].tag_names, vec!["Rust", "LinuxDo"]); -} - -#[tokio::test] -async fn fetch_topic_list_builds_plain_text_excerpt_for_rows() { - let payload = sample_latest_json().replace( - r#""excerpt": "topic excerpt""#, - r#""excerpt": "

Hello Fire

""#, - ); - let responses = vec![raw_json_response(200, "application/json", &payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("topic list"); - let _ = server.shutdown().await; - - assert_eq!(response.rows[0].excerpt_text.as_deref(), Some("Hello Fire")); -} - -#[tokio::test] -async fn fetch_bookmarks_parses_bookmark_metadata_fields() { - let payload = sample_latest_json() - .replace( - r#""highest_post_number": 12,"#, - r#""highest_post_number": 12, "_bookmarked_post_number": 7, "_bookmark_id": 901, "_bookmark_name": "稍后细读", "_bookmark_reminder_at": "2026-03-29T09:00:00Z", "_bookmarkable_type": "Post","#, - ); - let responses = vec![raw_json_response(200, "application/json", &payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let response = core - .fetch_bookmarks("alice", Some(2)) - .await - .expect("bookmarks"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.topics.len(), 1); - assert_eq!(response.topics[0].bookmarked_post_number, Some(7)); - assert_eq!(response.topics[0].bookmark_id, Some(901)); - assert_eq!( - response.topics[0].bookmark_name.as_deref(), - Some("稍后细读") - ); - assert_eq!( - response.topics[0].bookmark_reminder_at.as_deref(), - Some("2026-03-29T09:00:00Z") - ); - assert_eq!( - response.topics[0].bookmarkable_type.as_deref(), - Some("Post") - ); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("GET /u/alice/bookmarks.json?page=2 HTTP/1.1")); -} - -#[tokio::test] -async fn fetch_bookmarks_parses_user_bookmark_list_payload() { - let payload = r#"{ - "user_bookmark_list": { - "more_bookmarks_url": "/u/alice/bookmarks.json?page=2", - "bookmarks": [ - { - "id": 901, - "name": "稍后细读", - "reminder_at": "2026-03-29T09:00:00Z", - "bookmarkable_type": "Post", - "bookmarkable_id": 7007, - "topic_id": 1001, - "linked_post_number": 7, - "title": "真实书签响应", - "slug": "real-bookmark", - "excerpt": "

Hello Fire

", - "created_at": "2026-03-28T00:00:00Z", - "bumped_at": "2026-03-28T01:00:00Z", - "category_id": 42, - "highest_post_number": 12, - "views": 88, - "user": { - "id": 12, - "username": "alice", - "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" - } - } - ] - } -}"#; - let responses = vec![raw_json_response(200, "application/json", payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let response = core - .fetch_bookmarks("alice", None) - .await - .expect("bookmarks"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.topics.len(), 1); - assert_eq!(response.rows.len(), 1); - assert_eq!(response.next_page, Some(2)); - assert_eq!(response.topics[0].id, 1001); - assert_eq!(response.topics[0].title, "真实书签响应"); - assert_eq!(response.topics[0].reply_count, 11); - assert_eq!(response.topics[0].bookmarked_post_number, Some(7)); - assert_eq!(response.topics[0].bookmark_id, Some(901)); - assert_eq!( - response.topics[0].bookmark_name.as_deref(), - Some("稍后细读") - ); - assert_eq!( - response.topics[0].bookmark_reminder_at.as_deref(), - Some("2026-03-29T09:00:00Z") - ); - assert_eq!(response.rows[0].excerpt_text.as_deref(), Some("Hello Fire")); - assert_eq!( - response.rows[0].original_poster_username.as_deref(), - Some("alice") - ); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("GET /u/alice/bookmarks.json HTTP/1.1")); -} - -#[tokio::test] -async fn fetch_topic_list_surfaces_cloudflare_challenge_error() { - let responses = vec![raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("cloudflare challenge should surface as an error"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::CloudflareChallenge { - operation: "fetch topic list", - .. - } - )); -} - -#[tokio::test] -async fn fetch_topic_list_retries_once_after_cloudflare_challenge_completion() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - core.set_cloudflare_challenge_handler(|request| async move { - assert_eq!(request.operation, "fetch topic list"); - assert!(request.request_url.contains("/latest.json")); - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: Some("new-clearance".into()), - cookies: vec![ - PlatformCookie { - name: "cf_clearance".into(), - value: "new-clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "stale-clearance".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - ], - browser_user_agent: Some("FireBrowser/1.0".into()), - } - }); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("cloudflare challenge should retry once"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.rows.len(), 1); - assert_eq!(requests.len(), 2); - let retry_request = &requests[1]; - let retry_request_lower = retry_request.to_ascii_lowercase(); - assert!( - retry_request_lower.contains("cookie: cf_clearance=new-clearance"), - "retry request should send fresh cf_clearance:\n{retry_request}" - ); - assert!( - !retry_request.contains("stale-clearance"), - "retry request must not send stale cf_clearance:\n{retry_request}" - ); - assert!( - retry_request_lower.contains("user-agent: firebrowser/1.0"), - "retry request should use challenge WebView user agent:\n{retry_request}" - ); - let snapshot = core.snapshot(); - assert_eq!( - snapshot.cookies.cf_clearance.as_deref(), - Some("new-clearance") - ); - assert_eq!( - snapshot.browser_user_agent.as_deref(), - Some("FireBrowser/1.0") - ); -} - -#[tokio::test] -async fn fetch_topic_list_retries_after_page_clear_without_fresh_clearance() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - core.set_cloudflare_challenge_handler(|_| async move { - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: None, - cookies: vec![], - browser_user_agent: None, - } - }); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("page-clear without a new cookie should still retry"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.rows.len(), 1); - assert_eq!(requests.len(), 2); -} - -#[tokio::test] -async fn page_clear_with_login_cookies_rebuilds_missing_bootstrap() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_json_response(200, "application/json", &sample_latest_json()), - raw_text_response(200, &sample_home_html()), - raw_json_response(200, "application/json", r#"{"csrf":"csrf-token"}"#), - raw_text_response(200, &sample_home_html()), - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let _ = core.apply_platform_cookies(vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ]); - assert!(core.snapshot().bootstrap.current_username.is_none()); - core.set_cloudflare_challenge_handler(|_| async move { - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: None, - cookies: vec![], - browser_user_agent: None, - } - }); - - let _ = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("page-clear retry should succeed"); - - for _ in 0..80 { - if core.snapshot().bootstrap.current_username.as_deref() == Some("alice") { - break; - } - sleep(Duration::from_millis(25)).await; - } - - let snapshot = core.snapshot(); - let _ = server.shutdown().await; - assert_eq!( - snapshot.bootstrap.current_username.as_deref(), - Some("alice") - ); - assert!(snapshot.bootstrap.has_preloaded_data); -} - -#[tokio::test] -async fn retry_still_challenged_marks_incumbent_and_skips_second_presentation() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let _ = core.apply_platform_cookies(vec![PlatformCookie { - name: "cf_clearance".into(), - value: "working".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }]); - let challenge_calls = Arc::new(AtomicUsize::new(0)); - { - let challenge_calls = Arc::clone(&challenge_calls); - core.set_cloudflare_challenge_handler(move |_| { - challenge_calls.fetch_add(1, Ordering::SeqCst); - async move { - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: None, - cookies: vec![], - browser_user_agent: None, - } - } - }); - } - - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("retry that is still CF should fail"); - let requests = server.shutdown_with_requests().await; - - assert!(matches!( - error, - FireCoreError::CloudflareChallenge { - operation: "fetch topic list", - .. - } - )); - assert_eq!(requests.len(), 2); - assert_eq!(challenge_calls.load(Ordering::SeqCst), 1); - assert_eq!( - core.snapshot() - .cookies - .last_challenged_cf_clearance - .as_deref(), - Some("working") - ); -} - -#[tokio::test] -async fn cloudflare_challenge_retry_synthesizes_confirmed_clearance_when_snapshot_missing() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - core.set_cloudflare_challenge_handler(|_| async move { - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: Some("confirmed-clearance".into()), - cookies: vec![], - browser_user_agent: None, - } - }); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("confirmed clearance should be synthesized for retry"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.rows.len(), 1); - assert_eq!(requests.len(), 2); - assert!( - requests[1] - .to_ascii_lowercase() - .contains("cookie: cf_clearance=confirmed-clearance"), - "retry request should send synthesized cf_clearance:\n{}", - requests[1] - ); - assert_eq!( - core.snapshot().cookies.cf_clearance.as_deref(), - Some("confirmed-clearance") - ); -} - -#[tokio::test] -async fn cloudflare_challenge_retry_synthesizes_confirmed_clearance_when_snapshot_scope_is_wrong() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - core.set_cloudflare_challenge_handler(|_| async move { - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: Some("wrong-scope-clearance".into()), - cookies: vec![PlatformCookie { - name: "cf_clearance".into(), - value: "wrong-scope-clearance".into(), - domain: Some("unrelated.example".into()), - path: Some("/challenge".into()), - expires_at_unix_ms: None, - same_site: None, - }], - browser_user_agent: None, - } - }); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("confirmed wrong-scope clearance should be synthesized for retry"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.rows.len(), 1); - assert_eq!(requests.len(), 2); - assert!( - requests[1] - .to_ascii_lowercase() - .contains("cookie: cf_clearance=wrong-scope-clearance"), - "retry request should send synthesized cf_clearance:\n{}", - requests[1] - ); - let snapshot = core.snapshot(); - let clearance_cookie = snapshot - .cookies - .platform_cookies - .iter() - .find(|cookie| cookie.name == "cf_clearance") - .expect("cf_clearance platform cookie"); - assert_eq!(clearance_cookie.path.as_deref(), Some("/")); - assert_ne!( - clearance_cookie.domain.as_deref(), - Some("unrelated.example") - ); -} - -#[tokio::test] -async fn cloudflare_challenge_retry_accepts_platform_confirmed_existing_clearance() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let snapshot = core.apply_platform_cookies(vec![PlatformCookie { - name: "cf_clearance".into(), - value: "stable-clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }]); - assert_eq!( - snapshot.cookies.cf_clearance.as_deref(), - Some("stable-clearance") - ); - core.set_cloudflare_challenge_handler(|_| async move { - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: Some("stable-clearance".into()), - cookies: vec![PlatformCookie { - name: "cf_clearance".into(), - value: "stable-clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }], - browser_user_agent: None, - } - }); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("platform-confirmed clearance should unblock retry"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.rows.len(), 1); - assert_eq!(requests.len(), 2); - assert_eq!( - core.snapshot().cookies.cf_clearance.as_deref(), - Some("stable-clearance") - ); -} - -#[tokio::test] -async fn business_request_is_blocked_while_cloudflare_challenge_is_in_progress() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let challenge_started = Arc::new(Notify::new()); - let release_challenge = Arc::new(Notify::new()); - { - let challenge_started = Arc::clone(&challenge_started); - let release_challenge = Arc::clone(&release_challenge); - core.set_cloudflare_challenge_handler(move |_| { - let challenge_started = Arc::clone(&challenge_started); - let release_challenge = Arc::clone(&release_challenge); - async move { - challenge_started.notify_waiters(); - release_challenge.notified().await; - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: Some("new-clearance".into()), - cookies: vec![PlatformCookie { - name: "cf_clearance".into(), - value: "new-clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }], - browser_user_agent: None, - } - } - }); - } - - let first_core = core.clone(); - let first = tokio::spawn(async move { - first_core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - }); - challenge_started.notified().await; - - // New outbound traffic that has not yet hit CF is frozen at dispatch. - let blocked = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("business request should be blocked locally"); - - assert!(matches!( - blocked, - FireCoreError::CloudflareChallengeInProgress { - operation: "fetch topic list" - } - )); - - release_challenge.notify_waiters(); - let response = first - .await - .expect("task should finish") - .expect("first request should retry after challenge"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.rows.len(), 1); - assert_eq!(requests.len(), 2); -} - -#[tokio::test] -async fn concurrent_cloudflare_challenges_join_and_retry_after_shared_success() { - let challenge_body = - r#"Just a moment...__cf_chl_opt"#; - let server = TestServer::spawn_scripted(vec![ - // Delay both CF bodies so the two clients are already in-flight before - // either enters the challenge owner/join path. - TestServerStep::delayed( - raw_cloudflare_challenge_response(403, challenge_body), - Duration::from_millis(80), - ), - TestServerStep::delayed( - raw_cloudflare_challenge_response(403, challenge_body), - Duration::from_millis(80), - ), - TestServerStep::immediate(raw_json_response( - 200, - "application/json", - &sample_latest_json(), - )), - TestServerStep::immediate(raw_json_response( - 200, - "application/json", - &sample_latest_json(), - )), - ]) - .await - .expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let challenge_calls = Arc::new(AtomicUsize::new(0)); - let challenge_started = Arc::new(Notify::new()); - let release_challenge = Arc::new(Notify::new()); - { - let challenge_calls = Arc::clone(&challenge_calls); - let challenge_started = Arc::clone(&challenge_started); - let release_challenge = Arc::clone(&release_challenge); - core.set_cloudflare_challenge_handler(move |_| { - let challenge_calls = Arc::clone(&challenge_calls); - let challenge_started = Arc::clone(&challenge_started); - let release_challenge = Arc::clone(&release_challenge); - async move { - challenge_calls.fetch_add(1, Ordering::SeqCst); - challenge_started.notify_waiters(); - release_challenge.notified().await; - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: Some("joined-clearance".into()), - cookies: vec![PlatformCookie { - name: "cf_clearance".into(), - value: "joined-clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }], - browser_user_agent: None, - } - } - }); - } - - let first_core = core.clone(); - let first = tokio::spawn(async move { - first_core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - }); - let second_core = core.clone(); - let second = tokio::spawn(async move { - second_core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - }); - - challenge_started.notified().await; - // Let the second CF victim reach the shared join wait. - sleep(Duration::from_millis(40)).await; - release_challenge.notify_waiters(); - - let first_response = first - .await - .expect("first task") - .expect("first request should succeed after shared challenge"); - let second_response = second - .await - .expect("second task") - .expect("joined request should retry after shared challenge"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(first_response.rows.len(), 1); - assert_eq!(second_response.rows.len(), 1); - assert_eq!(challenge_calls.load(Ordering::SeqCst), 1); - assert_eq!(requests.len(), 4); -} - -#[tokio::test] -async fn foreground_retry_bypasses_cloudflare_failure_cooldown() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let challenge_calls = Arc::new(AtomicUsize::new(0)); - { - let challenge_calls = Arc::clone(&challenge_calls); - core.set_cloudflare_challenge_handler(move |_| { - challenge_calls.fetch_add(1, Ordering::SeqCst); - async move { - fire_models::CloudflareChallengeResult { - completed: false, - user_cancelled: false, - fresh_cf_clearance: None, - cookies: vec![], - browser_user_agent: None, - } - } - }); - } - - for _ in 0..2 { - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("challenge should remain unresolved"); - assert!(matches!( - error, - FireCoreError::CloudflareChallenge { - operation: "fetch topic list", - .. - } - )); - } - let requests = server.shutdown_with_requests().await; - - assert_eq!(requests.len(), 2); - assert_eq!(challenge_calls.load(Ordering::SeqCst), 2); -} - -#[tokio::test] -async fn fetch_topic_list_self_heals_unauthorized_with_sweep_retry() { - let responses = vec![ - raw_json_response( - 401, - "application/json", - r#"{"errors":["session cookie state is stale"]}"#, - ), - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let calls = Arc::new(Mutex::new(Vec::new())); - { - let calls = Arc::clone(&calls); - core.set_cookie_self_healing_handler(move |request| { - let calls = Arc::clone(&calls); - async move { - calls - .lock() - .expect("calls mutex") - .push((request.phase, request.attempt)); - CookieSelfHealingResult { - completed: true, - session_epoch: request.session_epoch, - } - } - }); - } - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("self-healed request should retry"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.rows.len(), 1); - assert_eq!(requests.len(), 2); - assert_eq!( - calls.lock().expect("calls mutex").as_slice(), - &[(CookieSelfHealingPhase::Sweep, 1)] - ); -} - -#[tokio::test] -async fn fetch_topic_list_does_not_self_heal_cloudflare_challenge_without_handler() { - let responses = vec![raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let calls = Arc::new(AtomicUsize::new(0)); - { - let calls = Arc::clone(&calls); - core.set_cookie_self_healing_handler(move |request| { - calls.fetch_add(1, Ordering::SeqCst); - async move { - CookieSelfHealingResult { - completed: true, - session_epoch: request.session_epoch, - } - } - }); - } - - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("cloudflare challenge must not trigger cookie healing"); - let requests = server.shutdown_with_requests().await; - - assert!(matches!( - error, - FireCoreError::CloudflareChallenge { - operation: "fetch topic list", - .. - } - )); - assert_eq!(calls.load(Ordering::SeqCst), 0); - assert_eq!(requests.len(), 1); -} - -#[tokio::test] -async fn fetch_topic_list_does_not_self_heal_explicit_not_logged_in() { - let body = r#"{"errors":["You need to log in."],"error_type":"not_logged_in"}"#; - let responses = vec![raw_json_response(401, "application/json", body)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let calls = Arc::new(AtomicUsize::new(0)); - { - let calls = Arc::clone(&calls); - core.set_cookie_self_healing_handler(move |request| { - calls.fetch_add(1, Ordering::SeqCst); - async move { - CookieSelfHealingResult { - completed: true, - session_epoch: request.session_epoch, - } - } - }); - } - - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("explicit not_logged_in must surface as login required"); - let requests = server.shutdown_with_requests().await; - - assert!(matches!(error, FireCoreError::LoginRequired { .. })); - assert_eq!(calls.load(Ordering::SeqCst), 0); - assert_eq!(requests.len(), 1); -} - -#[tokio::test] -async fn fetch_topic_list_self_healing_escalates_to_nuclear_reset() { - let unauthorized = raw_json_response( - 401, - "application/json", - r#"{"errors":["session cookie state is stale"]}"#, - ); - let responses = vec![ - unauthorized.clone(), - unauthorized.clone(), - unauthorized, - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let calls = Arc::new(Mutex::new(Vec::new())); - { - let calls = Arc::clone(&calls); - core.set_cookie_self_healing_handler(move |request| { - let calls = Arc::clone(&calls); - async move { - calls - .lock() - .expect("calls mutex") - .push((request.phase, request.attempt)); - CookieSelfHealingResult { - completed: true, - session_epoch: request.session_epoch, - } - } - }); - } - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect("nuclear reset should retry once"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(response.rows.len(), 1); - assert_eq!(requests.len(), 4); - assert_eq!( - calls.lock().expect("calls mutex").as_slice(), - &[ - (CookieSelfHealingPhase::Sweep, 1), - (CookieSelfHealingPhase::Sweep, 2), - (CookieSelfHealingPhase::NuclearReset, 1), - ] - ); -} - -#[tokio::test] -async fn fetch_topic_list_surfaces_rate_limited_cloudflare_challenge_error() { - let responses = vec![raw_cloudflare_challenge_response( - 429, - r#"Just a moment...__cf_chl_opt"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("429 Cloudflare challenge should surface as a challenge error"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::CloudflareChallenge { - operation: "fetch topic list", - .. - } - )); -} - -#[tokio::test] -async fn fetch_topic_list_accepts_cf_mitigated_challenge_without_html_content_type() { - let body = "managed challenge"; - let responses = vec![format!( - "HTTP/1.1 429 TEST\r\nServer: cloudflare\r\nContent-Type: text/plain; charset=utf-8\r\nCf-Mitigated: challenge\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("cf-mitigated challenge should not require HTML content type"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::CloudflareChallenge { - operation: "fetch topic list", - .. - } - )); -} - -#[tokio::test] -async fn fetch_topic_list_does_not_treat_non_cloudflare_403_body_as_challenge() { - let responses = vec![raw_json_response( - 403, - "text/html; charset=utf-8", - r#"Just a moment...__cf_chl_opt"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("non-cloudflare 403 should surface as a plain HTTP error"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::HttpStatus { - operation: "fetch topic list", - status: 403, - .. - } - )); -} - -#[tokio::test] -async fn fetch_topic_list_keeps_local_login_when_success_response_only_clears_auth_cookies() { - let body = sample_latest_json(); - let response = format!( - "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nSet-Cookie: _t=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nSet-Cookie: _forum_session=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let server = TestServer::spawn(vec![response]).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let _response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - page: Some(1), - ..TopicListQuery::default() - }) - .await - .expect("auth-cookie deletion alone should not invalidate login"); - let _ = server.shutdown().await; - - let snapshot = core.snapshot(); - assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); - assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); - assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("csrf-token")); - assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); - assert_eq!( - snapshot.bootstrap.current_username.as_deref(), - Some("alice") - ); - assert!(snapshot.bootstrap.has_preloaded_data); -} - -#[tokio::test] -async fn fetch_topic_posts_keeps_local_login_when_forbidden_invalid_access_sets_logged_out_header() -{ - let body = r#"{"errors":["您没有权限查看请求的资源。"],"error_type":"invalid_access"}"#; - let response = format!( - "HTTP/1.1 403 TEST\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nDiscourse-Logged-Out: 1\r\nSet-Cookie: _t=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let server = TestServer::spawn(vec![response]).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - let before_epoch = core.session_epoch(); - - let error = core - .fetch_topic_posts(2_270_621, vec![18_408_024]) - .await - .expect_err("ordinary invalid_access 403 should not invalidate login"); - let requests = server.shutdown_with_requests().await; - - assert!(matches!( - error, - FireCoreError::HttpStatus { - operation: "fetch topic posts", - status: 403, - body, - } if body.contains("\"error_type\":\"invalid_access\"") - )); - assert_eq!(core.session_epoch(), before_epoch); - - let snapshot = core.snapshot(); - assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); - assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); - assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("csrf-token")); - assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); - assert_eq!( - snapshot.bootstrap.current_username.as_deref(), - Some("alice") - ); - assert!(snapshot.bootstrap.has_preloaded_data); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains( - "GET /t/2270621/posts.json?post_ids%5B%5D=18408024&include_suggested=false HTTP/1.1" - )); -} - -#[tokio::test] -async fn fetch_topic_detail_partial_auth_rotation_advances_epoch_and_clears_csrf() { - let body = sample_topic_detail_json(); - let response = format!( - "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nSet-Cookie: _forum_session=rotated-forum; path=/; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let server = TestServer::spawn(vec![response]).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - let before_epoch = core.session_epoch(); - - let detail = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: true, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let requests = server.shutdown_with_requests().await; - - let snapshot = core.snapshot(); - let after_epoch = core.session_epoch(); - assert_eq!(detail.id, 123); - assert_eq!(after_epoch, before_epoch + 1); - assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); - assert_eq!( - snapshot.cookies.forum_session.as_deref(), - Some("rotated-forum") - ); - assert_eq!(snapshot.cookies.csrf_token, None); - assert!(!snapshot.readiness().can_write_authenticated_api); - assert_eq!( - core.auth_recovery_hint(), - Some(FireAuthRecoveryHint { - observed_epoch: after_epoch, - reason: FireAuthRecoveryHintReason::ForumSessionOnlyRotation, - }) - ); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("GET /t/123.json?track_visit=true HTTP/1.1")); -} - -#[tokio::test] -async fn fetch_topic_list_preserves_local_login_when_success_response_reports_logged_out() { - let body = sample_latest_json(); - let response = format!( - "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nDiscourse-Logged-Out: 1\r\nSet-Cookie: _t=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let server = TestServer::spawn(vec![response]).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let response = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - page: Some(1), - ..TopicListQuery::default() - }) - .await - .expect("successful response should not force login invalidation"); - let _ = server.shutdown().await; - - assert_eq!(response.rows.len(), 1); - - let snapshot = core.snapshot(); - assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); - assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); - assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("csrf-token")); - assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); - assert_eq!( - snapshot.bootstrap.current_username.as_deref(), - Some("alice") - ); - assert!(snapshot.bootstrap.has_preloaded_data); -} - -#[tokio::test] -async fn fetch_topic_list_surfaces_login_required_and_preserves_local_state_for_not_logged_in_error( -) { - let body = r#"{"errors":["需要登录才能执行此操作。"],"error_type":"not_logged_in"}"#; - let probe_body = r#"{"current_user":{"username":"alice"}}"#; - let server = TestServer::spawn(vec![ - raw_json_response(403, "application/json", body), - raw_json_response(200, "application/json", probe_body), - ]) - .await - .expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let error = core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - .expect_err("login-required error should surface"); - let _ = server.shutdown().await; - - assert!(matches!(error, FireCoreError::LoginRequired { .. })); - - let snapshot = core.snapshot(); - assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); - assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); - assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("csrf-token")); - assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); - assert_eq!( - snapshot.bootstrap.current_username.as_deref(), - Some("alice") - ); - assert!(snapshot.bootstrap.has_preloaded_data); -} - -#[tokio::test] -async fn stale_response_is_discarded_after_local_logout() { - let body = sample_latest_json(); - let response = format!( - "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nSet-Cookie: _t=stale-token; path=/; SameSite=Lax\r\nSet-Cookie: _forum_session=stale-forum; path=/; SameSite=Lax\r\nSet-Cookie: __cf_bm=stale-browser-context; path=/; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let server = TestServer::spawn_scripted(vec![TestServerStep::delayed( - response, - Duration::from_millis(150), - )]) - .await - .expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let request_core = core.clone(); - let task = tokio::spawn(async move { - request_core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - }); - - sleep(Duration::from_millis(40)).await; - let cleared = core.logout_local(true); - assert!(!cleared.cookies.has_login_session()); - - let error = task - .await - .expect("task join") - .expect_err("stale response should be discarded"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::StaleSessionResponse { - operation: "fetch topic list" - } - )); - let snapshot = core.snapshot(); - assert_eq!(snapshot.cookies.t_token, None); - assert_eq!(snapshot.cookies.forum_session, None); - assert_eq!(snapshot.cookies.cf_clearance, None); - assert!(!snapshot - .cookies - .platform_cookies - .iter() - .any(|cookie| cookie.name == "__cf_bm")); -} - -#[tokio::test] -async fn stale_response_is_discarded_after_session_rotation() { - let body = sample_latest_json(); - let response = format!( - "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nSet-Cookie: _t=stale-token; path=/; SameSite=Lax\r\nSet-Cookie: _forum_session=stale-forum; path=/; SameSite=Lax\r\nSet-Cookie: __cf_bm=stale-browser-context; path=/; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let server = TestServer::spawn_scripted(vec![TestServerStep::delayed( - response, - Duration::from_millis(150), - )]) - .await - .expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "old-token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "old-forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let request_core = core.clone(); - let task = tokio::spawn(async move { - request_core - .fetch_topic_list(TopicListQuery { - kind: TopicListKind::Latest, - ..TopicListQuery::default() - }) - .await - }); - - sleep(Duration::from_millis(40)).await; - let rotated = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "fresh-token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "fresh-forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - assert_eq!(rotated.cookies.t_token.as_deref(), Some("fresh-token")); - - let error = task - .await - .expect("task join") - .expect_err("stale response should be discarded"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::StaleSessionResponse { - operation: "fetch topic list" - } - )); - let snapshot = core.snapshot(); - assert_eq!(snapshot.cookies.t_token.as_deref(), Some("fresh-token")); - assert_eq!( - snapshot.cookies.forum_session.as_deref(), - Some("fresh-forum") - ); - assert!(!snapshot - .cookies - .platform_cookies - .iter() - .any(|cookie| cookie.name == "__cf_bm")); -} - -#[tokio::test] -async fn fetch_topic_detail_parses_detail_payload() { - let responses = vec![raw_json_response( - 200, - "application/json", - &sample_topic_detail_json(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let detail = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: true, - force_load: true, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(detail.id, 123); - assert_eq!(detail.title, "Fire topic"); - assert!(requests[0].contains("GET /t/123.json?track_visit=true&forceLoad=true HTTP/1.1")); - assert_eq!( - detail.tags, - vec![ - TopicTag { - id: None, - name: "rust".into(), - slug: None, - }, - TopicTag { - id: None, - name: "linuxdo".into(), - slug: None, - }, - ] - ); - assert_eq!(detail.post_stream.posts.len(), 1); - assert_eq!(detail.post_stream.posts[0].username, "alice"); - assert_eq!(detail.thread.original_post_number, Some(1)); - assert_eq!(detail.thread.reply_sections.len(), 0); - assert_eq!(detail.flat_posts.len(), 1); - assert!(detail.flat_posts[0].is_original_post); - assert_eq!(detail.flat_posts[0].post.post_number, 1); - assert!(!detail.flat_posts[0].shows_thread_line); - assert_eq!( - detail - .details - .created_by - .as_ref() - .map(|value| value.username.as_str()), - Some("alice") - ); -} - -#[tokio::test] -async fn fetch_topic_detail_parses_post_author_metadata() { - let mut payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail payload json"); - let post = payload - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .and_then(|stream| stream.get_mut("posts")) - .and_then(Value::as_array_mut) - .and_then(|posts| posts.first_mut()) - .and_then(Value::as_object_mut) - .expect("first post"); - post.insert("user_id".into(), json!(42)); - post.insert("user_title".into(), json!("Core Team")); - post.insert("primary_group_name".into(), json!("staff")); - post.insert("flair_url".into(), json!("/images/flair/staff.svg")); - post.insert("flair_name".into(), json!("Staff")); - post.insert("flair_bg_color".into(), json!("0057ff")); - post.insert("flair_color".into(), json!("ffffff")); - post.insert("flair_group_id".into(), json!("7")); - post.insert("moderator".into(), json!(true)); - post.insert("admin".into(), json!(false)); - post.insert("group_moderator".into(), json!(true)); - post.insert( - "user_status".into(), - json!({ - "emoji": "coffee", - "description": "Reviewing patches" - }), - ); - - let responses = vec![raw_json_response( - 200, - "application/json", - &payload.to_string(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let detail = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: true, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let _ = server.shutdown().await; - - let metadata = &detail.post_stream.posts[0].author_metadata; - assert_eq!(metadata.user_id, Some(42)); - assert_eq!(metadata.user_title.as_deref(), Some("Core Team")); - assert_eq!(metadata.primary_group_name.as_deref(), Some("staff")); - assert_eq!( - metadata.flair_url.as_deref(), - Some("/images/flair/staff.svg") - ); - assert_eq!(metadata.flair_name.as_deref(), Some("Staff")); - assert_eq!(metadata.flair_bg_color.as_deref(), Some("0057ff")); - assert_eq!(metadata.flair_color.as_deref(), Some("ffffff")); - assert_eq!(metadata.flair_group_id, Some(7)); - assert!(metadata.moderator); - assert!(!metadata.admin); - assert!(metadata.group_moderator); - assert_eq!(metadata.user_status_emoji.as_deref(), Some("coffee")); - assert_eq!( - metadata.user_status_description.as_deref(), - Some("Reviewing patches") - ); -} - -#[tokio::test] -async fn fetch_topic_detail_rejects_mismatched_topic_identity() { - let payload = sample_topic_detail_json().replace("\"id\": 123", "\"id\": 999"); - let responses = vec![raw_json_response(200, "application/json", &payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let error = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: false, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect_err("mismatched topic id should fail"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::UnexpectedTopicDetail { - requested_topic_id: 123, - actual_topic_id: 999, - } - )); -} - -#[tokio::test] -async fn fetch_topic_detail_source_snapshot_tracks_visit_headers_and_force_load_query() { - let responses = vec![raw_json_response( - 200, - "application/json", - &sample_topic_detail_json(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let snapshot = core - .fetch_topic_detail_source_snapshot(TopicDetailSourceQuery { - topic_id: 123, - target_post_number: None, - allow_suggested_unread_root: false, - track_visit: true, - force_load: true, - initial_batch_size: 40, - load_more_batch_size: 40, - max_auto_batches_per_gesture: 3, - max_auto_posts_per_gesture: 120, - }) - .await - .expect("topic source snapshot"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(snapshot.body.post.post_number, 1); - assert_eq!(snapshot.loaded_posts.len(), 1); - assert_eq!(requests.len(), 1); - let first_request_headers = requests[0].to_ascii_lowercase(); - assert!(requests[0].contains("GET /t/123.json?track_visit=true&forceLoad=true HTTP/1.1")); - assert!(first_request_headers.contains("discourse-track-view: 1")); - assert!(first_request_headers.contains("discourse-track-view-topic-id: 123")); -} - -#[tokio::test] -async fn fetch_topic_detail_source_snapshot_recovers_missing_body_via_stream_head_post_ids() { - // Notification deep-links open `/t/{id}/{N}.json`. Large topics return a - // nearby posts chunk without OP/post #1. Body must be recovered from - // stream[0] via post_ids[] instead of hard-failing posts.json?post_number=1. - let target_post_number = 200_u32; - let body_post = json!({ - "id": 1001, - "username": "op", - "cooked": "

Original post

", - "post_number": 1, - "reply_to_post_number": null, - "reply_count": 5 - }); - let target_post = json!({ - "id": 1200, - "username": "replier", - "cooked": "

Deep reply

", - "post_number": target_post_number, - "reply_to_post_number": 1, - "reply_count": 0 - }); - let stream = (1_u64..=220).map(|n| 1000 + n).collect::>(); - let mid_topic_payload = json!({ - "id": 123, - "title": "Large topic", - "slug": "large-topic", - "posts_count": 220, - "post_stream": { - "posts": [target_post.clone()], - "stream": stream - } - }); - let body_by_ids = json!({ - "post_stream": { - "posts": [body_post.clone()], - "stream": [1001] - } - }); - // Remaining initial stream ids (1002..1010) after body recovery. - let initial_batch_posts = (2_u32..=10) - .map(|post_number| { - json!({ - "id": 1000 + u64::from(post_number), - "username": format!("u{post_number}"), - "cooked": format!("

r{post_number}

"), - "post_number": post_number, - "reply_to_post_number": 1, - "reply_count": 0 - }) - }) - .collect::>(); - let initial_batch = json!({ - "post_stream": { - "posts": initial_batch_posts, - "stream": (1002_u64..=1010).collect::>() - } - }); - - let server = TestServer::spawn(vec![ - raw_json_response(200, "application/json", &mid_topic_payload.to_string()), - // resolve_topic_body_post: stream head via post_ids[] - raw_json_response(200, "application/json", &body_by_ids.to_string()), - // initial batch hydration for missing stream ids - raw_json_response(200, "application/json", &initial_batch.to_string()), - ]) - .await - .expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let snapshot = core - .fetch_topic_detail_source_snapshot(TopicDetailSourceQuery { - topic_id: 123, - target_post_number: Some(target_post_number), - allow_suggested_unread_root: false, - track_visit: true, - force_load: true, - initial_batch_size: 10, - load_more_batch_size: 10, - max_auto_batches_per_gesture: 3, - max_auto_posts_per_gesture: 120, - }) - .await - .expect("topic source snapshot should recover missing body"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(snapshot.body.post.post_number, 1); - assert_eq!(snapshot.body.post.id, 1001); - assert!(snapshot - .loaded_posts - .iter() - .any(|post| post.post_number == target_post_number)); - assert!(requests[0].contains("GET /t/123/200.json")); - assert!( - requests.iter().any(|request| { - request.contains("GET /t/123/posts.json") && request.contains("post_ids%5B%5D=1001") - || request.contains("post_ids[]=1001") - }), - "expected OP recovery via post_ids[] stream head, requests={requests:?}" - ); -} - -#[tokio::test] -async fn fetch_topic_detail_source_snapshot_preserves_target_anchor_and_source_cursor() { - let target_post_number = 14_u32; - let mut detail_payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - detail_payload - .as_object_mut() - .expect("detail fixture object") - .insert("posts_count".into(), json!(26)); - - let root_posts = (2_u32..=26) - .map(|post_number| { - json!({ - "id": 9000 + u64::from(post_number), - "username": format!("user-{post_number}"), - "cooked": format!("

Reply {post_number}

"), - "post_number": post_number, - "reply_to_post_number": 1, - "reply_count": 0 - }) - }) - .collect::>(); - let root_stream = root_posts - .iter() - .map(|post| { - post.get("id") - .and_then(Value::as_u64) - .expect("root post id") - }) - .collect::>(); - let target_root = root_posts - .iter() - .find(|post| { - post.get("post_number").and_then(Value::as_u64) == Some(u64::from(target_post_number)) - }) - .cloned() - .expect("target root post"); - let body_post = detail_payload - .get("post_stream") - .and_then(Value::as_object) - .and_then(|post_stream| post_stream.get("posts")) - .and_then(Value::as_array) - .and_then(|posts| posts.first()) - .cloned() - .expect("body post"); - let mut top_level_payload = detail_payload.clone(); - top_level_payload - .as_object_mut() - .expect("top-level fixture object") - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .expect("top-level post stream object") - .extend([ - ("posts".into(), Value::Array(vec![body_post])), - ("stream".into(), json!(root_stream.clone())), - ]); - - let responses = vec![ - raw_json_response(200, "application/json", &top_level_payload.to_string()), - raw_json_response( - 200, - "application/json", - &json!({ - "post_stream": { - "posts": [target_root], - "stream": [9014] - } - }) - .to_string(), - ), - raw_json_response( - 200, - "application/json", - &json!({ - "post_stream": { - "posts": root_posts.iter().take(10).cloned().collect::>(), - "stream": root_stream.iter().take(10).copied().collect::>() - } - }) - .to_string(), - ), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let snapshot = core - .fetch_topic_detail_source_snapshot(TopicDetailSourceQuery { - topic_id: 123, - target_post_number: Some(target_post_number), - allow_suggested_unread_root: false, - track_visit: true, - force_load: true, - initial_batch_size: 10, - load_more_batch_size: 10, - max_auto_batches_per_gesture: 3, - max_auto_posts_per_gesture: 120, - }) - .await - .expect("topic source snapshot"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(snapshot.focused_post_number, Some(target_post_number)); - assert!(snapshot - .loaded_posts - .iter() - .any(|post| post.post_number == target_post_number)); - let next_cursor = snapshot.source_cursor.expect("next source cursor"); - assert_eq!(next_cursor.topic_id, 123); - assert_eq!(next_cursor.next_stream_offset, 10); - assert_eq!(next_cursor.batch_size, 10); - assert_eq!(requests.len(), 3); - assert!(requests[0].contains("GET /t/123/14.json?track_visit=true&forceLoad=true HTTP/1.1")); - assert!(requests[1].contains("GET /t/123/posts.json")); - assert!(requests[1].contains("post_number=14")); - assert!(requests[1].contains("asc=true")); - assert!(requests[2].contains("GET /t/123/posts.json")); -} - -#[tokio::test] -async fn fetch_topic_detail_page_auto_extends_to_first_unread_root() { - let mut detail_payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - detail_payload - .as_object_mut() - .expect("detail fixture object") - .extend([ - ("posts_count".into(), json!(12)), - ("last_read_post_number".into(), json!(6)), - ]); - - let root_posts = (2_u32..=12) - .map(|post_number| { - json!({ - "id": 9000 + u64::from(post_number), - "username": format!("user-{post_number}"), - "cooked": format!("

Reply {post_number}

"), - "post_number": post_number, - "reply_to_post_number": 1, - "reply_count": 0 - }) - }) - .collect::>(); - let root_stream = root_posts - .iter() - .map(|post| { - post.get("id") - .and_then(Value::as_u64) - .expect("root post id") - }) - .collect::>(); - let body_post = detail_payload - .get("post_stream") - .and_then(Value::as_object) - .and_then(|post_stream| post_stream.get("posts")) - .and_then(Value::as_array) - .and_then(|posts| posts.first()) - .cloned() - .expect("body post"); - detail_payload - .as_object_mut() - .expect("detail fixture object") - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .expect("post stream object") - .extend([ - ("posts".into(), Value::Array(vec![body_post])), - ("stream".into(), json!(root_stream)), - ]); - - let responses = vec![ - raw_json_response(200, "application/json", &detail_payload.to_string()), - raw_json_response( - 200, - "application/json", - &json!({ - "post_stream": { - "posts": root_posts.iter().take(3).cloned().collect::>(), - "stream": root_posts - .iter() - .take(3) - .filter_map(|post| post.get("id").and_then(Value::as_u64)) - .collect::>() - } - }) - .to_string(), - ), - raw_json_response( - 200, - "application/json", - &json!({ - "post_stream": { - "posts": root_posts.iter().skip(3).take(3).cloned().collect::>(), - "stream": root_posts - .iter() - .skip(3) - .take(3) - .filter_map(|post| post.get("id").and_then(Value::as_u64)) - .collect::>() - } - }) - .to_string(), - ), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let page = core - .fetch_topic_detail_page(TopicDetailSourceQuery { - topic_id: 123, - target_post_number: None, - allow_suggested_unread_root: true, - track_visit: true, - force_load: true, - initial_batch_size: 3, - load_more_batch_size: 3, - max_auto_batches_per_gesture: 3, - max_auto_posts_per_gesture: 120, - }) - .await - .expect("topic detail page"); - let requests = server.shutdown_with_requests().await; - - assert_eq!( - page.tree_presentation.first_unread_root_post_number, - Some(7) - ); - assert!(page - .source_snapshot - .loaded_posts - .iter() - .any(|post| post.post_number == 7)); - assert_eq!( - page.source_snapshot - .source_cursor - .expect("next source cursor") - .next_stream_offset, - 6 - ); - assert_eq!(requests.len(), 3); - assert!(requests[0].contains("GET /t/123.json?track_visit=true&forceLoad=true HTTP/1.1")); - assert!(requests[1].contains("post_ids%5B%5D=9002")); - assert!(requests[1].contains("post_ids%5B%5D=9004")); - assert!(requests[2].contains("post_ids%5B%5D=9005")); - assert!(requests[2].contains("post_ids%5B%5D=9007")); -} - -#[tokio::test] -async fn fetch_topic_detail_page_skips_unread_root_auto_extend_when_not_allowed() { - let mut detail_payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - detail_payload - .as_object_mut() - .expect("detail fixture object") - .extend([ - ("posts_count".into(), json!(12)), - ("last_read_post_number".into(), json!(6)), - ]); - - let root_posts = (2_u32..=12) - .map(|post_number| { - json!({ - "id": 9000 + u64::from(post_number), - "username": format!("user-{post_number}"), - "cooked": format!("

Reply {post_number}

"), - "post_number": post_number, - "reply_to_post_number": 1, - "reply_count": 0 - }) - }) - .collect::>(); - let root_stream = root_posts - .iter() - .map(|post| { - post.get("id") - .and_then(Value::as_u64) - .expect("root post id") - }) - .collect::>(); - let body_post = detail_payload - .get("post_stream") - .and_then(Value::as_object) - .and_then(|post_stream| post_stream.get("posts")) - .and_then(Value::as_array) - .and_then(|posts| posts.first()) - .cloned() - .expect("body post"); - detail_payload - .as_object_mut() - .expect("detail fixture object") - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .expect("post stream object") - .extend([ - ("posts".into(), Value::Array(vec![body_post])), - ("stream".into(), json!(root_stream)), - ]); - - let responses = vec![ - raw_json_response(200, "application/json", &detail_payload.to_string()), - raw_json_response( - 200, - "application/json", - &json!({ - "post_stream": { - "posts": root_posts.iter().take(3).cloned().collect::>(), - "stream": root_posts - .iter() - .take(3) - .filter_map(|post| post.get("id").and_then(Value::as_u64)) - .collect::>() - } - }) - .to_string(), - ), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let page = core - .fetch_topic_detail_page(TopicDetailSourceQuery { - topic_id: 123, - target_post_number: None, - allow_suggested_unread_root: false, - track_visit: true, - force_load: true, - initial_batch_size: 3, - load_more_batch_size: 3, - max_auto_batches_per_gesture: 3, - max_auto_posts_per_gesture: 120, - }) - .await - .expect("topic detail page"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(page.tree_presentation.first_unread_root_post_number, None); - assert!(!page - .source_snapshot - .loaded_posts - .iter() - .any(|post| post.post_number == 7)); - assert_eq!(requests.len(), 2); - assert!(requests[0].contains("GET /t/123.json?track_visit=true&forceLoad=true HTTP/1.1")); - assert!(requests[1].contains("post_ids%5B%5D=9002")); - assert!(requests[1].contains("post_ids%5B%5D=9004")); -} - -#[tokio::test] -async fn fetch_topic_ai_summary_parses_payload_and_query_params() { - let body = r#"{ - "ai_topic_summary": { - "summarized_text": "Fire summary", - "algorithm": "linuxdo-ai", - "outdated": "true", - "can_regenerate": false, - "new_posts_since_summary": "3", - "updated_at": "2026-03-26T00:00:00Z" - } -}"#; - let responses = vec![raw_json_response(200, "application/json", body)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let summary = core - .fetch_topic_ai_summary(123, true) - .await - .expect("topic ai summary") - .expect("summary payload"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(summary.summarized_text, "Fire summary"); - assert_eq!(summary.algorithm.as_deref(), Some("linuxdo-ai")); - assert!(summary.outdated); - assert!(!summary.can_regenerate); - assert_eq!(summary.new_posts_since_summary, 3); - assert_eq!(summary.updated_at.as_deref(), Some("2026-03-26T00:00:00Z")); - assert_eq!(requests.len(), 1); - assert!( - requests[0].contains("GET /discourse-ai/summarization/t/123?skip_age_check=true HTTP/1.1") - ); -} - -#[tokio::test] -async fn fetch_topic_ai_summary_returns_none_for_unavailable_statuses() { - for status in [403, 404] { - let responses = vec![raw_json_response( - status, - "application/json", - r#"{"errors":["no summary"]}"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let summary = core - .fetch_topic_ai_summary(123, false) - .await - .expect("topic ai summary"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(summary, None); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("GET /discourse-ai/summarization/t/123 HTTP/1.1")); - } -} - -#[tokio::test] -async fn fetch_topic_ai_summary_surfaces_cloudflare_challenge() { - let responses = vec![raw_cloudflare_challenge_response( - 403, - "Just a moment", - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let error = core - .fetch_topic_ai_summary(123, false) - .await - .expect_err("cloudflare challenge"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::CloudflareChallenge { - operation: "fetch topic ai summary", - .. - } - )); -} - -#[tokio::test] -async fn fetch_private_message_detail_parses_detail_participants() { - let mut payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - let object = payload.as_object_mut().expect("detail fixture object"); - object.insert("archetype".into(), json!("private_message")); - object - .get_mut("details") - .and_then(Value::as_object_mut) - .expect("detail metadata") - .insert( - "participants".into(), - json!([ - { - "id": 1, - "username": "alice", - "name": "Alice", - "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" - }, - { - "id": 2, - "username": "bob", - "name": "Bob", - "avatar_template": "/user_avatar/linux.do/bob/{size}/1_2.png" - } - ]), - ); - - let responses = vec![raw_json_response( - 200, - "application/json", - &payload.to_string(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let detail = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: false, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let _ = server.shutdown().await; - - assert_eq!(detail.archetype.as_deref(), Some("private_message")); - assert_eq!(detail.details.participants.len(), 2); - assert_eq!( - detail.details.participants[1].username.as_deref(), - Some("bob") - ); - assert_eq!(detail.details.participants[1].name.as_deref(), Some("Bob")); -} - -#[tokio::test] -async fn fetch_topic_detail_hydrates_missing_posts_from_stream() { - let mut detail_payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - let object = detail_payload - .as_object_mut() - .expect("detail fixture object"); - object.insert("posts_count".into(), json!(3)); - object - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .expect("post stream object") - .insert("stream".into(), json!([9001, 9002, 9003])); - - let extra_posts_payload = json!({ - "post_stream": { - "posts": [ - { - "id": 9003, - "username": "carol", - "cooked": "

Nested reply

", - "post_number": 3, - "reply_to_post_number": 2 - }, - { - "id": 9002, - "username": "bob", - "cooked": "

First reply

", - "post_number": 2, - "reply_to_post_number": 1 - } - ], - "stream": [9002, 9003] - } - }) - .to_string(); - - let responses = vec![ - raw_json_response(200, "application/json", &detail_payload.to_string()), - raw_json_response(200, "application/json", &extra_posts_payload), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let detail = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: false, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(detail.post_stream.stream, vec![9001, 9002, 9003]); - assert_eq!( - detail - .post_stream - .posts - .iter() - .map(|post| post.post_number) - .collect::>(), - vec![1, 2, 3] - ); - assert_eq!( - detail - .flat_posts - .iter() - .map(|post| post.post.post_number) - .collect::>(), - vec![1, 2, 3] - ); - assert_eq!(detail.flat_posts[1].depth, 0); - assert_eq!(detail.flat_posts[2].depth, 1); - assert_eq!(detail.flat_posts[2].parent_post_number, Some(2)); - assert_eq!(requests.len(), 2); - assert!(requests[0].contains("GET /t/123.json HTTP/1.1")); - assert!(requests[1] - .contains("GET /t/123/posts.json?post_ids%5B%5D=9002&post_ids%5B%5D=9003&include_suggested=false HTTP/1.1")); -} - -#[tokio::test] -async fn fetch_topic_detail_initial_keeps_partial_post_stream() { - let mut detail_payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - detail_payload - .as_object_mut() - .expect("detail fixture object") - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .expect("post stream object") - .insert("stream".into(), json!([9001, 9002, 9003])); - - let responses = vec![raw_json_response( - 200, - "application/json", - &detail_payload.to_string(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let detail = core - .fetch_topic_detail_initial(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: false, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(detail.post_stream.posts.len(), 1); - assert_eq!(detail.post_stream.stream, vec![9001, 9002, 9003]); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("GET /t/123.json HTTP/1.1")); -} - -#[tokio::test] -async fn fetch_topic_posts_parses_batch_response() { - let payload = json!({ - "post_stream": { - "posts": [ - { - "id": 9003, - "username": "carol", - "cooked": "

Nested reply

", - "post_number": 3, - "reply_to_post_number": 2 - }, - { - "id": 9002, - "username": "bob", - "cooked": "

First reply

", - "post_number": 2, - "reply_to_post_number": 1 - } - ], - "stream": [9002, 9003] - } - }) - .to_string(); - - let responses = vec![raw_json_response(200, "application/json", &payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let posts = core - .fetch_topic_posts(123, vec![9002, 9003]) - .await - .expect("posts"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(posts.len(), 2); - assert_eq!(posts[0].id, 9003); - assert_eq!(posts[1].reply_to_post_number, Some(1)); - assert_eq!(requests.len(), 1); - assert!(requests[0] - .contains("GET /t/123/posts.json?post_ids%5B%5D=9002&post_ids%5B%5D=9003&include_suggested=false HTTP/1.1")); -} - -#[tokio::test] -async fn fetch_topic_posts_reuses_active_topic_response_session_cache() { - let mut top_level_payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - let body_post = top_level_payload - .as_object() - .expect("detail fixture object") - .get("post_stream") - .and_then(Value::as_object) - .and_then(|post_stream| post_stream.get("posts")) - .and_then(Value::as_array) - .and_then(|posts| posts.first()) - .cloned() - .expect("body post"); - top_level_payload - .as_object_mut() - .expect("detail fixture object") - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .expect("post stream object") - .extend([ - ("stream".into(), json!([9002])), - ( - "posts".into(), - json!([ - body_post, - { - "id": 9002, - "username": "bob", - "cooked": "

First reply

", - "post_number": 2, - "reply_to_post_number": 1, - "reply_count": 0 - } - ]), - ), - ]); - let post_payload = json!({ - "post_stream": { - "posts": [ - { - "id": 9003, - "username": "carol", - "cooked": "

Nested reply

", - "post_number": 3, - "reply_to_post_number": 2 - } - ], - "stream": [9003] - } - }) - .to_string(); - let responses = vec![ - raw_json_response(200, "application/json", &top_level_payload.to_string()), - raw_json_response(200, "application/json", &post_payload), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _snapshot = core - .fetch_topic_detail_source_snapshot(TopicDetailSourceQuery { - topic_id: 123, - target_post_number: None, - allow_suggested_unread_root: false, - track_visit: true, - force_load: true, - initial_batch_size: 1, - load_more_batch_size: 40, - max_auto_batches_per_gesture: 3, - max_auto_posts_per_gesture: 120, - }) - .await - .expect("topic source snapshot"); - let posts = core - .fetch_topic_posts(123, vec![9002, 9003]) - .await - .expect("posts"); - let cached_posts = core - .fetch_topic_posts(123, vec![9002, 9003]) - .await - .expect("cached posts"); - let requests = server.shutdown_with_requests().await; - - assert_eq!( - posts.iter().map(|post| post.id).collect::>(), - vec![9002, 9003] - ); - assert_eq!( - cached_posts.iter().map(|post| post.id).collect::>(), - vec![9002, 9003] - ); - assert_eq!(requests.len(), 2); - assert!(requests[1] - .contains("GET /t/123/posts.json?post_ids%5B%5D=9003&include_suggested=false HTTP/1.1")); - assert!(!requests[1].contains("post_ids%5B%5D=9002")); -} - -#[tokio::test] -async fn fetch_topic_detail_tolerates_object_bookmarks_and_accepted_answer_metadata() { - let mut payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - let object = payload.as_object_mut().expect("detail fixture object"); - object.insert( - "bookmarks".into(), - json!([ - { - "id": 1240, - "bookmarkable_type": "Topic", - "bookmarkable_id": 123 - }, - { - "id": 1241, - "bookmarkable_type": "Post", - "bookmarkable_id": 9001 - } - ]), - ); - object.insert( - "accepted_answer".into(), - json!({ - "post_number": 5, - "username": "alice" - }), - ); - object.insert("has_accepted_answer".into(), json!(true)); - let payload = payload.to_string(); - - let responses = vec![raw_json_response(200, "application/json", &payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let detail = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: true, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let _ = server.shutdown().await; - - assert_eq!(detail.bookmarks, vec![1240, 1241]); - assert!(detail.bookmarked); - assert_eq!(detail.bookmark_id, Some(1240)); - assert!(detail.post_stream.posts[0].bookmarked); - assert_eq!(detail.post_stream.posts[0].bookmark_id, Some(1241)); - assert!(detail.accepted_answer); - assert!(detail.has_accepted_answer); -} - -#[tokio::test] -async fn fetch_badge_detail_parses_badge_envelope() { - let payload = r#"{ - "badge": { - "id": 7, - "name": "Great Reply", - "description": "

Short

", - "badge_type_id": 1, - "grant_count": 12, - "long_description": "

Long

", - "slug": "great-reply" - } - }"#; - let responses = vec![raw_json_response(200, "application/json", payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let badge = core.fetch_badge_detail(7).await.expect("badge detail"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(badge.id, 7); - assert_eq!(badge.name, "Great Reply"); - assert_eq!(badge.grant_count, 12); - assert_eq!(badge.long_description.as_deref(), Some("

Long

")); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("GET /badges/7.json HTTP/1.1")); -} - -#[tokio::test] -async fn fetch_topic_detail_tolerates_null_scalars_and_null_details() { - let mut payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); - let object = payload.as_object_mut().expect("detail fixture object"); - object.insert("title".into(), Value::Null); - object.insert("category_id".into(), json!("2")); - object.insert("details".into(), Value::Null); - - let post = object - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .and_then(|stream| stream.get_mut("posts")) - .and_then(Value::as_array_mut) - .and_then(|posts| posts.first_mut()) - .and_then(Value::as_object_mut) - .expect("first post"); - post.insert("username".into(), Value::Null); - post.insert("cooked".into(), Value::Null); - post.insert("post_type".into(), json!("1")); - post.insert("like_count".into(), Value::Null); - post.insert("reply_count".into(), Value::Null); - post.insert("reply_to_post_number".into(), json!("12")); - post.insert("bookmarked".into(), Value::Null); - post.insert("accepted_answer".into(), Value::Null); - post.insert("can_edit".into(), Value::Null); - post.insert("can_delete".into(), Value::Null); - post.insert("can_recover".into(), Value::Null); - post.insert("hidden".into(), Value::Null); - post.insert("reactions".into(), Value::Null); - - let payload = payload.to_string(); - - let responses = vec![raw_json_response(200, "application/json", &payload)]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let detail = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: true, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let _ = server.shutdown().await; - - assert_eq!(detail.title, ""); - assert_eq!(detail.category_id, Some(2)); - assert_eq!(detail.details.notification_level, None); - assert_eq!(detail.details.created_by, None); - assert!(!detail.details.can_edit); - assert_eq!(detail.post_stream.posts[0].username, ""); - assert_eq!(detail.post_stream.posts[0].cooked, ""); - assert_eq!(detail.post_stream.posts[0].reply_to_post_number, Some(12)); - assert_eq!(detail.post_stream.posts[0].reactions.len(), 0); - assert_eq!(detail.post_stream.posts[0].like_count, 0); - assert_eq!(detail.post_stream.posts[0].reply_count, 0); -} - -#[tokio::test] -async fn fetch_topic_detail_tolerates_malformed_optional_nested_records() { - let mut payload: Value = - serde_json::from_str(&sample_topic_detail_json()).expect("detail payload json"); - let object = payload.as_object_mut().expect("detail fixture object"); - object.insert( - "details".into(), - json!({ - "notification_level": "1", - "can_edit": "1", - "created_by": "unexpected" - }), - ); - - let post = object - .get_mut("post_stream") - .and_then(Value::as_object_mut) - .and_then(|stream| stream.get_mut("posts")) - .and_then(Value::as_array_mut) - .and_then(|posts| posts.first_mut()) - .and_then(Value::as_object_mut) - .expect("first post"); - post.insert( - "current_user_reaction".into(), - Value::String("unexpected".into()), - ); - - let responses = vec![raw_json_response( - 200, - "application/json", - &payload.to_string(), - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let detail = core - .fetch_topic_detail(TopicDetailQuery { - topic_id: 123, - post_number: None, - track_visit: true, - force_load: false, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }) - .await - .expect("detail"); - let _ = server.shutdown().await; - - assert_eq!(detail.details.notification_level, Some(1)); - assert!(detail.details.can_edit); - assert_eq!(detail.details.created_by, None); - assert_eq!(detail.post_stream.posts[0].current_user_reaction, None); -} - -#[tokio::test] -async fn refresh_csrf_token_updates_session_from_network() { - let responses = vec![raw_json_response( - 200, - "application/json", - r#"{"csrf":"fresh-csrf"}"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let snapshot = core.refresh_csrf_token().await.expect("csrf refresh"); - server.shutdown().await; - - assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("fresh-csrf")); -} - -#[tokio::test] -async fn refresh_csrf_token_preserves_login_when_success_response_reports_logged_out() { - let body = r#"{"csrf":"fresh-csrf"}"#; - let response = format!( - "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nDiscourse-Logged-Out: 1\r\nSet-Cookie: _t=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let server = TestServer::spawn(vec![response]).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: None, - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let snapshot = core - .refresh_csrf_token_if_needed() - .await - .expect("successful csrf response should be usable"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("fresh-csrf")); - assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); - assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); - assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); - assert_eq!(requests.len(), 1); - let request = requests[0].to_ascii_lowercase(); - assert!(request.contains("get /session/csrf http/1.1")); - assert!(request.contains("discourse-logged-in: true")); - assert!(request.contains("_t=token")); - assert!(request.contains("_forum_session=forum")); -} - -#[tokio::test] -async fn refresh_csrf_token_accepts_scalar_tokens() { - let responses = vec![raw_json_response( - 200, - "application/json", - r#"{"csrf":12345}"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let snapshot = core.refresh_csrf_token().await.expect("csrf refresh"); - server.shutdown().await; - - assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("12345")); -} - -#[tokio::test] -async fn concurrent_csrf_refresh_if_needed_shares_in_flight_request() { - let server = TestServer::spawn_scripted(vec![TestServerStep::delayed( - raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), - Duration::from_millis(50), - )]) - .await - .expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: None, - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let (first, second) = tokio::join!( - core.refresh_csrf_token_if_needed(), - core.refresh_csrf_token_if_needed() - ); - let first = first.expect("first csrf refresh"); - let second = second.expect("second csrf refresh"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(first.cookies.csrf_token.as_deref(), Some("fresh-csrf")); - assert_eq!(second.cookies.csrf_token.as_deref(), Some("fresh-csrf")); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("GET /session/csrf HTTP/1.1")); -} - -#[tokio::test] -async fn queued_csrf_refresh_if_needed_does_not_retry_after_session_logout() { - let server = TestServer::spawn_scripted(vec![TestServerStep::delayed( - raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), - Duration::from_millis(120), - )]) - .await - .expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: None, - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let first_core = core.clone(); - let first = tokio::spawn(async move { first_core.refresh_csrf_token_if_needed().await }); - sleep(Duration::from_millis(20)).await; - - let second_core = core.clone(); - let second = tokio::spawn(async move { second_core.refresh_csrf_token_if_needed().await }); - sleep(Duration::from_millis(20)).await; - - let logged_out = core.logout_local(true); - assert!(!logged_out.cookies.can_authenticate_requests()); - - let first = first.await.expect("first task"); - let second = second.await.expect("second task"); - let requests = server.shutdown_with_requests().await; - - assert!(matches!( - first, - Err(FireCoreError::StaleSessionResponse { - operation: "refresh csrf token" - }) - )); - let second = second.expect("queued csrf refresh should skip after logout"); - assert_eq!(second.cookies.csrf_token, None); - assert!(!second.cookies.can_authenticate_requests()); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("GET /session/csrf HTTP/1.1")); -} - -#[tokio::test] -async fn logout_remote_retries_after_bad_csrf() { - let responses = vec![ - raw_text_response(403, r#"["BAD CSRF"]"#), - raw_json_response(200, "application/json", r#"{"csrf":"retry-csrf"}"#), - raw_text_response(200, "{}"), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("stale-csrf".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let snapshot = core.logout_remote(true).await.expect("logout"); - let requests = server.shutdown().await; - - assert!(!snapshot.cookies.has_login_session()); - assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); - assert_eq!(requests.load(Ordering::SeqCst), 3); -} - -#[tokio::test] -async fn refresh_bootstrap_fetches_home_html() { - let responses = vec![raw_text_response(200, &sample_home_html())]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let snapshot = core.refresh_bootstrap().await.expect("bootstrap refresh"); - let requests = server.shutdown_with_requests().await; - let trace = core.network_trace_detail(1).expect("network trace detail"); - - assert_eq!( - snapshot.bootstrap.current_username.as_deref(), - Some("alice") - ); - assert!(snapshot.bootstrap.has_preloaded_data); - assert_eq!(requests.len(), 1); - - let wire_request = requests[0].to_ascii_lowercase(); - assert!(wire_request.contains("get / http/1.1")); - assert!(wire_request.contains("accept: text/html")); - assert!(wire_request.contains("accept-language: zh-cn,zh;q=0.9,en;q=0.8")); - assert!(wire_request.contains("user-agent: mozilla/5.0")); - - assert!(trace - .request_headers - .iter() - .any(|header| header.name == "user-agent" && header.value.starts_with("Mozilla/5.0"))); - assert!(trace.request_headers.iter().any(|header| { - header.name == "accept-language" && header.value == "zh-CN,zh;q=0.9,en;q=0.8" - })); -} - -#[tokio::test] -async fn refresh_bootstrap_falls_back_to_site_json_when_home_lacks_site_metadata() { - let home_html = r#" - - - - - - - - -
- - -"#; - let site_json = r#"{ - "categories": [ - { - "id": 2, - "name": "Rust", - "slug": "rust", - "parent_category_id": 1, - "color": "FFFFFF", - "text_color": "000000" - } - ], - "top_tags": [ - {"name": "swift"}, - "rust" - ], - "can_tag_topics": true -}"#; - let responses = vec![ - raw_text_response(200, home_html), - raw_json_response(200, "application/json", site_json), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let snapshot = core.refresh_bootstrap().await.expect("bootstrap refresh"); - let requests = server.shutdown_with_requests().await; - - assert_eq!( - snapshot.bootstrap.current_username.as_deref(), - Some("alice") - ); - assert!(snapshot.bootstrap.has_preloaded_data); - assert!(snapshot.bootstrap.has_site_settings); - assert!(snapshot.bootstrap.has_site_metadata); - assert_eq!(snapshot.bootstrap.categories.len(), 1); - assert_eq!(snapshot.bootstrap.top_tags, vec!["swift", "rust"]); - assert!(snapshot.bootstrap.can_tag_topics); - assert_eq!(requests.len(), 2); - assert!(requests[0].to_ascii_lowercase().contains("get / http/1.1")); - assert!(requests[1] - .to_ascii_lowercase() - .contains("get /site.json http/1.1")); -} - -#[tokio::test] -async fn refresh_bootstrap_uses_browser_user_agent_and_full_platform_cookies() { - let responses = vec![raw_text_response(200, &sample_home_html())]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: None, - current_url: Some(server.base_url()), - browser_user_agent: Some("Mozilla/5.0 Exact WKWebView".into()), - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "__cf_bm".into(), - value: "browser-context".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let _ = core.refresh_bootstrap().await.expect("bootstrap refresh"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(requests.len(), 1); - let wire_request = requests[0].to_ascii_lowercase(); - assert!(wire_request.contains("user-agent: mozilla/5.0 exact wkwebview")); - let cookie_header = wire_request - .lines() - .find(|line| line.starts_with("cookie: ")) - .expect("cookie header"); - assert!(cookie_header.contains("_t=token")); - assert!(cookie_header.contains("_forum_session=forum")); - assert!(cookie_header.contains("__cf_bm=browser-context")); -} - -#[tokio::test] -async fn create_reply_refreshes_csrf_and_parses_wrapped_post_payload() { - let responses = vec![ - raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), - raw_json_response( - 200, - "application/json", - r#"{ - "post": { - "id": 9010, - "username": "alice", - "name": "Alice", - "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png", - "cooked": "

Reply body

", - "post_number": 2, - "post_type": 1, - "created_at": "2026-03-28T00:10:00Z", - "updated_at": "2026-03-28T00:10:00Z", - "like_count": 0, - "reply_count": 0, - "reply_to_post_number": 1, - "bookmarked": false, - "bookmark_id": null, - "reactions": [], - "current_user_reaction": null, - "accepted_answer": false, - "can_edit": true, - "can_delete": true, - "can_recover": false, - "hidden": false - } - }"#, - ), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: None, - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let post = core - .create_reply(TopicReplyRequest { - topic_id: 123, - raw: "Reply body".into(), - reply_to_post_number: Some(1), - }) - .await - .expect("create reply"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(post.id, 9010); - assert_eq!(post.post_number, 2); - assert_eq!(post.reply_to_post_number, Some(1)); - assert_eq!(requests.len(), 2); - assert!(requests[0].contains("GET /session/csrf HTTP/1.1")); - assert!(requests[1].contains("POST /posts.json HTTP/1.1")); - assert!(requests[1] - .to_ascii_lowercase() - .contains("x-csrf-token: fresh-csrf")); - assert!(requests[1].contains("topic_id=123&raw=Reply+body&reply_to_post_number=1")); - assert_eq!( - core.snapshot().cookies.csrf_token.as_deref(), - Some("fresh-csrf") - ); -} - -#[tokio::test] -async fn create_reply_refreshes_csrf_before_logged_out_header_handling() { - let bad_csrf_body = r#"["BAD CSRF"]"#; - let bad_csrf_response = format!( - "HTTP/1.1 403 TEST\r\nContent-Type: application/json; charset=utf-8\r\nDiscourse-Logged-Out: 1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{bad_csrf_body}", - bad_csrf_body.len() - ); - let responses = vec![ - bad_csrf_response, - raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), - raw_json_response( - 200, - "application/json", - r#"{ - "post": { - "id": 9010, - "username": "alice", - "name": "Alice", - "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png", - "cooked": "

Reply body

", - "post_number": 2, - "post_type": 1, - "created_at": "2026-03-28T00:10:00Z", - "updated_at": "2026-03-28T00:10:00Z", - "like_count": 0, - "reply_count": 0, - "reply_to_post_number": 1, - "bookmarked": false, - "bookmark_id": null, - "reactions": [], - "current_user_reaction": null, - "accepted_answer": false, - "can_edit": true, - "can_delete": true, - "can_recover": false, - "hidden": false - } - }"#, - ), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: Some("stale-csrf".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let post = core - .create_reply(TopicReplyRequest { - topic_id: 123, - raw: "Reply body".into(), - reply_to_post_number: Some(1), - }) - .await - .expect("create reply after BAD CSRF refresh"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(post.id, 9010); - assert_eq!(requests.len(), 3); - assert!(requests[0].contains("POST /posts.json HTTP/1.1")); - assert!(requests[1].contains("GET /session/csrf HTTP/1.1")); - assert!(requests[2].contains("POST /posts.json HTTP/1.1")); - assert!(requests[2] - .to_ascii_lowercase() - .contains("x-csrf-token: fresh-csrf")); - assert_eq!( - core.snapshot().cookies.csrf_token.as_deref(), - Some("fresh-csrf") - ); -} - -#[tokio::test] -async fn create_reply_cloudflare_retry_rebuilds_stale_csrf_header() { - let responses = vec![ - raw_cloudflare_challenge_response( - 403, - r#"Just a moment...__cf_chl_opt"#, - ), - raw_json_response( - 200, - "application/json", - r#"{ - "post": { - "id": 9010, - "username": "alice", - "name": "Alice", - "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png", - "cooked": "

Reply body

", - "post_number": 2, - "post_type": 1, - "created_at": "2026-03-28T00:10:00Z", - "updated_at": "2026-03-28T00:10:00Z", - "like_count": 0, - "reply_count": 0, - "reply_to_post_number": 1, - "bookmarked": false, - "bookmark_id": null, - "reactions": [], - "current_user_reaction": null, - "accepted_answer": false, - "can_edit": true, - "can_delete": true, - "can_recover": false, - "hidden": false - } - }"#, - ), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: Some("stale-csrf".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - { - let handler_core = core.clone(); - core.set_cloudflare_challenge_handler(move |_| { - let core = handler_core.clone(); - async move { - let _ = core.apply_csrf_token("fresh-csrf".into()); - fire_models::CloudflareChallengeResult { - completed: true, - user_cancelled: false, - fresh_cf_clearance: Some("new-clearance".into()), - cookies: vec![PlatformCookie { - name: "cf_clearance".into(), - value: "new-clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }], - browser_user_agent: None, - } - } - }); - } - - let post = core - .create_reply(TopicReplyRequest { - topic_id: 123, - raw: "Reply body".into(), - reply_to_post_number: Some(1), - }) - .await - .expect("create reply after challenge"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(post.id, 9010); - assert_eq!(requests.len(), 2); - assert!(requests[0] - .to_ascii_lowercase() - .contains("x-csrf-token: stale-csrf")); - assert!(requests[1] - .to_ascii_lowercase() - .contains("x-csrf-token: fresh-csrf")); - assert!( - !requests[1] - .to_ascii_lowercase() - .contains("x-csrf-token: stale-csrf"), - "retry must not replay stale CSRF header:\n{}", - requests[1] - ); -} - -/// Post-challenge rebuild must force `/session/csrf` after bootstrap when home -/// HTML lacks csrf meta and Set-Cookie rotated the forum session (which clears -/// the cached CSRF via auth rotation). Without this, writes stay blocked on -/// `can_write_authenticated_api == false` until a later opportunistic refresh. -#[tokio::test] -async fn complete_cloudflare_challenge_realigns_csrf_after_bootstrap_without_meta() { - let home_without_csrf = r#" - - - - - - - - -
- - -"#; - let rotating_home = format!( - "HTTP/1.1 200 TEST\r\nContent-Type: text/html\r\nContent-Length: {}\r\nSet-Cookie: _forum_session=rotated-forum; path=/; SameSite=Lax\r\nConnection: close\r\n\r\n{home_without_csrf}", - home_without_csrf.len() - ); - let home_again = format!( - "HTTP/1.1 200 TEST\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{home_without_csrf}", - home_without_csrf.len() - ); - let responses = vec![ - // schedule_post_challenge: refresh_bootstrap - rotating_home, - // schedule_post_challenge: forced refresh_csrf_token - raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), - // refresh_all_forced core: refresh_bootstrap again - home_again, - // refresh_all_forced core: home topic list - raw_json_response(200, "application/json", &sample_latest_json()), - ]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: Some("stale-csrf".into()), - current_url: Some(server.base_url()), - browser_user_agent: Some("FireTests/1.0".into()), - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "old-clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - assert_eq!( - core.snapshot().cookies.csrf_token.as_deref(), - Some("stale-csrf") - ); - assert!(core.snapshot().readiness().can_write_authenticated_api); - - let _ = core.complete_cloudflare_challenge( - vec![PlatformCookie { - name: "cf_clearance".into(), - value: "fresh-clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: Some("None".into()), - }], - Some("fresh-clearance".into()), - Some("FireTests/1.0".into()), - ); - - // Post-challenge task: 30ms + trust settle (~400ms) + bootstrap + csrf. - let mut realigned = false; - for _ in 0..80 { - let snapshot = core.snapshot(); - if snapshot.cookies.csrf_token.as_deref() == Some("fresh-csrf") - && snapshot.cookies.forum_session.as_deref() == Some("rotated-forum") - && snapshot.readiness().can_write_authenticated_api - { - realigned = true; - break; - } - sleep(Duration::from_millis(50)).await; - } - - let requests = server.shutdown_with_requests().await; - let snapshot = core.snapshot(); - - assert!( - realigned, - "expected post-challenge CSRF realign; csrf={:?} forum={:?} can_write={}", - snapshot.cookies.csrf_token, - snapshot.cookies.forum_session, - snapshot.readiness().can_write_authenticated_api - ); - assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); - assert_eq!( - snapshot.cookies.cf_clearance.as_deref(), - Some("fresh-clearance") - ); - assert!( - requests - .iter() - .any(|request| { request.to_ascii_lowercase().contains("get /session/csrf") }), - "post-challenge rebuild must call /session/csrf:\n{requests:#?}" - ); -} - -#[tokio::test] -async fn create_reply_surfaces_pending_review_state() { - let responses = vec![raw_json_response( - 200, - "application/json", - r#"{"action":"enqueued","pending_count":2}"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let error = core - .create_reply(TopicReplyRequest { - topic_id: 123, - raw: "Reply body".into(), - reply_to_post_number: None, - }) - .await - .expect_err("create reply should enqueue"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::PostEnqueued { pending_count: 2 } - )); -} - -#[tokio::test] -async fn create_reply_surfaces_cloudflare_challenge_error() { - let responses = vec![raw_cloudflare_challenge_response( - 403, - r#"

Just a moment

"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: None, - csrf_token: Some("csrf".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let error = core - .create_reply(TopicReplyRequest { - topic_id: 123, - raw: "Reply body".into(), - reply_to_post_number: Some(1), - }) - .await - .expect_err("cloudflare challenge should surface as an error"); - let _ = server.shutdown().await; - - assert!(matches!( - error, - FireCoreError::CloudflareChallenge { - operation: "create reply", - .. - } - )); -} - -#[tokio::test] -async fn toggle_post_reaction_parses_reaction_update_payload() { - let responses = vec![raw_json_response( - 200, - "application/json", - r#"{ - "reactions": [ - { "id": "heart", "type": "emoji", "count": 4 }, - { "id": "laughing", "type": "emoji", "count": 1 } - ], - "current_user_reaction": { "id": "laughing", "type": "emoji", "count": 1, "can_undo": true } - }"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let update = core - .toggle_post_reaction(9001, "laughing".into()) - .await - .expect("toggle post reaction"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(update.reactions.len(), 2); - assert_eq!(update.reactions[0].id, "heart"); - assert_eq!( - update - .current_user_reaction - .as_ref() - .map(|reaction| reaction.id.as_str()), - Some("laughing") - ); - assert_eq!( - update - .current_user_reaction - .as_ref() - .and_then(|reaction| reaction.can_undo), - Some(true) - ); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains( - "PUT /discourse-reactions/posts/9001/custom-reactions/laughing/toggle.json HTTP/1.1" - )); - assert!(requests[0] - .to_ascii_lowercase() - .contains("x-csrf-token: csrf-token")); - assert!(requests[0] - .to_ascii_lowercase() - .contains("content-length: 0")); -} - -#[tokio::test] -async fn toggle_post_reaction_tolerates_malformed_current_user_reaction() { - let responses = vec![raw_json_response( - 200, - "application/json", - r#"{ - "reactions": [ - { "id": "heart", "type": "emoji", "count": 4 } - ], - "current_user_reaction": "unexpected" - }"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let update = core - .toggle_post_reaction(9001, "laughing".into()) - .await - .expect("toggle post reaction"); - - let _ = server.shutdown().await; - assert_eq!(update.reactions.len(), 1); - assert_eq!(update.current_user_reaction, None); -} - -#[tokio::test] -async fn toggle_post_reaction_encodes_reaction_path_segment() { - let responses = vec![raw_json_response( - 200, - "application/json", - r#"{ - "reactions": [ - { "id": "+1", "type": "emoji", "count": 1 } - ], - "current_user_reaction": { "id": "+1", "type": "emoji", "count": 1, "can_undo": true } - }"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let update = core - .toggle_post_reaction(9001, "+1".into()) - .await - .expect("toggle post reaction"); - let requests = server.shutdown_with_requests().await; - - assert_eq!( - update - .current_user_reaction - .as_ref() - .map(|reaction| reaction.id.as_str()), - Some("+1") - ); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains( - "PUT /discourse-reactions/posts/9001/custom-reactions/%2B1/toggle.json HTTP/1.1" - )); -} - -#[tokio::test] -async fn fetch_reaction_users_uses_reactions_users_endpoint_and_skips_malformed_items() { - let responses = vec![raw_json_response( - 200, - "application/json", - r#"{ - "reaction_users": [ - { - "id": "heart", - "count": "2", - "users": [ - { - "id": "1", - "username": "alice", - "name": "Alice", - "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" - }, - { "bad": "ignored" } - ] - }, - 1, - { - "id": "clap", - "users": [ - { "username": "bob" } - ] - } - ] - }"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let groups = core - .fetch_reaction_users(9001) - .await - .expect("reaction users"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(groups.len(), 2); - assert_eq!(groups[0].id, "heart"); - assert_eq!(groups[0].count, 2); - assert_eq!(groups[0].users.len(), 1); - assert_eq!(groups[0].users[0].id, 1); - assert_eq!(groups[0].users[0].username, "alice"); - assert_eq!(groups[0].users[0].name.as_deref(), Some("Alice")); - assert_eq!( - groups[0].users[0].avatar_template.as_deref(), - Some("/user_avatar/linux.do/alice/{size}/1_2.png") - ); - assert_eq!(groups[1].id, "clap"); - assert_eq!(groups[1].count, 1); - assert_eq!(groups[1].users.len(), 1); - assert_eq!(groups[1].users[0].id, 0); - assert_eq!(groups[1].users[0].username, "bob"); - assert_eq!(requests.len(), 1); - assert!( - requests[0].contains("GET /discourse-reactions/posts/9001/reactions-users.json HTTP/1.1") - ); -} - -#[tokio::test] -async fn like_post_uses_post_actions_endpoint() { - let responses = vec![raw_text_response(200, "{}")]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let update = core.like_post(9001).await.expect("like post"); - let requests = server.shutdown_with_requests().await; - - assert!(update.is_none()); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("POST /post_actions HTTP/1.1")); - assert!(requests[0] - .to_ascii_lowercase() - .contains("x-csrf-token: csrf-token")); - assert!(requests[0].contains("id=9001&post_action_type_id=2")); -} - -#[tokio::test] -async fn like_post_without_auth_session_does_not_send_undefined_csrf_request() { - let server = TestServer::spawn(Vec::new()).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let error = core - .like_post(9001) - .await - .expect_err("write without an auth session should fail before network"); - let requests = server.shutdown_with_requests().await; - - assert!(matches!(error, FireCoreError::MissingLoginSession)); - assert!(requests.is_empty()); -} - -#[tokio::test] -async fn like_post_parses_reaction_update_when_response_includes_reaction_fields() { - let responses = vec![raw_json_response( - 200, - "application/json", - r#"{ - "id": 9001, - "post_number": 1, - "like_count": 15, - "reactions": [ - { "id": "heart", "type": "emoji", "count": 15 } - ], - "current_user_reaction": { "id": "heart", "type": "emoji", "count": 15, "can_undo": true } - }"#, - )]; - let server = TestServer::spawn(responses).await.expect("server"); - let core = FireCore::new(FireCoreConfig { - base_url: server.base_url(), - workspace_path: None, - }) - .expect("core"); - - let _ = core.sync_login_context(LoginSyncInput { - username: Some("alice".into()), - home_html: Some(sample_home_html()), - csrf_token: Some("csrf-token".into()), - current_url: Some(server.base_url()), - browser_user_agent: None, - cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ], - }); - - let update = core - .like_post(9001) - .await - .expect("like post") - .expect("reaction update"); - let requests = server.shutdown_with_requests().await; - - assert_eq!(update.reactions.len(), 1); - assert_eq!(update.reactions[0].id, "heart"); - assert_eq!(update.reactions[0].count, 15); - assert_eq!( - update - .current_user_reaction - .as_ref() - .map(|reaction| reaction.id.as_str()), - Some("heart") - ); - assert_eq!( - update - .current_user_reaction - .as_ref() - .and_then(|reaction| reaction.can_undo), - Some(true) - ); - assert_eq!(requests.len(), 1); - assert!(requests[0].contains("POST /post_actions HTTP/1.1")); -} +#[path = "network/auth_rotation.rs"] +mod auth_rotation; +#[path = "network/cloudflare.rs"] +mod cloudflare; +#[path = "network/cookie_healing.rs"] +mod cookie_healing; +#[path = "network/mutations.rs"] +mod mutations; +#[path = "network/session_refresh.rs"] +mod session_refresh; +#[path = "network/stale_responses.rs"] +mod stale_responses; +#[path = "network/topic_detail.rs"] +mod topic_detail; +#[path = "network/topic_list.rs"] +mod topic_list; diff --git a/crates/fire-core/tests/network/auth_rotation.rs b/crates/fire-core/tests/network/auth_rotation.rs new file mode 100644 index 00000000..13aaeca2 --- /dev/null +++ b/crates/fire-core/tests/network/auth_rotation.rs @@ -0,0 +1,224 @@ +use super::*; + +#[tokio::test] +async fn fetch_topic_detail_partial_auth_rotation_advances_epoch_and_clears_csrf() { + let body = sample_topic_detail_json(); + let response = format!( + "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nSet-Cookie: _forum_session=rotated-forum; path=/; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let server = TestServer::spawn(vec![response]).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + let before_epoch = core.session_epoch(); + + let detail = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: true, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let requests = server.shutdown_with_requests().await; + + let snapshot = core.snapshot(); + let after_epoch = core.session_epoch(); + assert_eq!(detail.id, 123); + assert_eq!(after_epoch, before_epoch + 1); + assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); + assert_eq!( + snapshot.cookies.forum_session.as_deref(), + Some("rotated-forum") + ); + assert_eq!(snapshot.cookies.csrf_token, None); + assert!(!snapshot.readiness().can_write_authenticated_api); + assert_eq!( + core.auth_recovery_hint(), + Some(FireAuthRecoveryHint { + observed_epoch: after_epoch, + reason: FireAuthRecoveryHintReason::ForumSessionOnlyRotation, + }) + ); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("GET /t/123.json?track_visit=true HTTP/1.1")); +} + +#[tokio::test] +async fn fetch_topic_list_preserves_local_login_when_success_response_reports_logged_out() { + let body = sample_latest_json(); + let response = format!( + "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nDiscourse-Logged-Out: 1\r\nSet-Cookie: _t=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let server = TestServer::spawn(vec![response]).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + page: Some(1), + ..TopicListQuery::default() + }) + .await + .expect("successful response should not force login invalidation"); + let _ = server.shutdown().await; + + assert_eq!(response.rows.len(), 1); + + let snapshot = core.snapshot(); + assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); + assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); + assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("csrf-token")); + assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); + assert_eq!( + snapshot.bootstrap.current_username.as_deref(), + Some("alice") + ); + assert!(snapshot.bootstrap.has_preloaded_data); +} + +#[tokio::test] +async fn fetch_topic_list_surfaces_login_required_and_preserves_local_state_for_not_logged_in_error( +) { + let body = r#"{"errors":["需要登录才能执行此操作。"],"error_type":"not_logged_in"}"#; + let probe_body = r#"{"current_user":{"username":"alice"}}"#; + let server = TestServer::spawn(vec![ + raw_json_response(403, "application/json", body), + raw_json_response(200, "application/json", probe_body), + ]) + .await + .expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("login-required error should surface"); + let _ = server.shutdown().await; + + assert!(matches!(error, FireCoreError::LoginRequired { .. })); + + let snapshot = core.snapshot(); + assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); + assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); + assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("csrf-token")); + assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); + assert_eq!( + snapshot.bootstrap.current_username.as_deref(), + Some("alice") + ); + assert!(snapshot.bootstrap.has_preloaded_data); +} diff --git a/crates/fire-core/tests/network/cloudflare.rs b/crates/fire-core/tests/network/cloudflare.rs new file mode 100644 index 00000000..31b2e705 --- /dev/null +++ b/crates/fire-core/tests/network/cloudflare.rs @@ -0,0 +1,1000 @@ +use super::*; + +#[tokio::test] +async fn fetch_topic_list_surfaces_cloudflare_challenge_error() { + let responses = vec![raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("cloudflare challenge should surface as an error"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::CloudflareChallenge { + operation: "fetch topic list", + .. + } + )); +} + +#[tokio::test] +async fn fetch_topic_list_retries_once_after_cloudflare_challenge_completion() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + core.set_cloudflare_challenge_handler(|request| async move { + assert_eq!(request.operation, "fetch topic list"); + assert!(request.request_url.contains("/latest.json")); + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: Some("new-clearance".into()), + cookies: vec![ + PlatformCookie { + name: "cf_clearance".into(), + value: "new-clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "stale-clearance".into(), + domain: Some(".linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + ], + browser_user_agent: Some("FireBrowser/1.0".into()), + } + }); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("cloudflare challenge should retry once"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.rows.len(), 1); + assert_eq!(requests.len(), 2); + let retry_request = &requests[1]; + let retry_request_lower = retry_request.to_ascii_lowercase(); + assert!( + retry_request_lower.contains("cookie: cf_clearance=new-clearance"), + "retry request should send fresh cf_clearance:\n{retry_request}" + ); + assert!( + !retry_request.contains("stale-clearance"), + "retry request must not send stale cf_clearance:\n{retry_request}" + ); + assert!( + retry_request_lower.contains("user-agent: firebrowser/1.0"), + "retry request should use challenge WebView user agent:\n{retry_request}" + ); + let snapshot = core.snapshot(); + assert_eq!( + snapshot.cookies.cf_clearance.as_deref(), + Some("new-clearance") + ); + assert_eq!( + snapshot.browser_user_agent.as_deref(), + Some("FireBrowser/1.0") + ); +} + +#[tokio::test] +async fn fetch_topic_list_retries_after_page_clear_without_fresh_clearance() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + core.set_cloudflare_challenge_handler(|_| async move { + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: None, + cookies: vec![], + browser_user_agent: None, + } + }); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("page-clear without a new cookie should still retry"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.rows.len(), 1); + assert_eq!(requests.len(), 2); +} + +#[tokio::test] +async fn page_clear_with_login_cookies_rebuilds_missing_bootstrap() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_json_response(200, "application/json", &sample_latest_json()), + raw_text_response(200, &sample_home_html()), + raw_json_response(200, "application/json", r#"{"csrf":"csrf-token"}"#), + raw_text_response(200, &sample_home_html()), + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let _ = core.apply_platform_cookies(vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ]); + assert!(core.snapshot().bootstrap.current_username.is_none()); + core.set_cloudflare_challenge_handler(|_| async move { + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: None, + cookies: vec![], + browser_user_agent: None, + } + }); + + let _ = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("page-clear retry should succeed"); + + for _ in 0..80 { + if core.snapshot().bootstrap.current_username.as_deref() == Some("alice") { + break; + } + sleep(Duration::from_millis(25)).await; + } + + let snapshot = core.snapshot(); + let _ = server.shutdown().await; + assert_eq!( + snapshot.bootstrap.current_username.as_deref(), + Some("alice") + ); + assert!(snapshot.bootstrap.has_preloaded_data); +} + +#[tokio::test] +async fn retry_still_challenged_marks_incumbent_and_skips_second_presentation() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let _ = core.apply_platform_cookies(vec![PlatformCookie { + name: "cf_clearance".into(), + value: "working".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }]); + let challenge_calls = Arc::new(AtomicUsize::new(0)); + { + let challenge_calls = Arc::clone(&challenge_calls); + core.set_cloudflare_challenge_handler(move |_| { + challenge_calls.fetch_add(1, Ordering::SeqCst); + async move { + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: None, + cookies: vec![], + browser_user_agent: None, + } + } + }); + } + + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("retry that is still CF should fail"); + let requests = server.shutdown_with_requests().await; + + assert!(matches!( + error, + FireCoreError::CloudflareChallenge { + operation: "fetch topic list", + .. + } + )); + assert_eq!(requests.len(), 2); + assert_eq!(challenge_calls.load(Ordering::SeqCst), 1); + assert_eq!( + core.snapshot() + .cookies + .last_challenged_cf_clearance + .as_deref(), + Some("working") + ); +} + +#[tokio::test] +async fn cloudflare_challenge_retry_synthesizes_confirmed_clearance_when_snapshot_missing() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + core.set_cloudflare_challenge_handler(|_| async move { + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: Some("confirmed-clearance".into()), + cookies: vec![], + browser_user_agent: None, + } + }); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("confirmed clearance should be synthesized for retry"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.rows.len(), 1); + assert_eq!(requests.len(), 2); + assert!( + requests[1] + .to_ascii_lowercase() + .contains("cookie: cf_clearance=confirmed-clearance"), + "retry request should send synthesized cf_clearance:\n{}", + requests[1] + ); + assert_eq!( + core.snapshot().cookies.cf_clearance.as_deref(), + Some("confirmed-clearance") + ); +} + +#[tokio::test] +async fn cloudflare_challenge_retry_synthesizes_confirmed_clearance_when_snapshot_scope_is_wrong() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + core.set_cloudflare_challenge_handler(|_| async move { + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: Some("wrong-scope-clearance".into()), + cookies: vec![PlatformCookie { + name: "cf_clearance".into(), + value: "wrong-scope-clearance".into(), + domain: Some("unrelated.example".into()), + path: Some("/challenge".into()), + expires_at_unix_ms: None, + same_site: None, + }], + browser_user_agent: None, + } + }); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("confirmed wrong-scope clearance should be synthesized for retry"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.rows.len(), 1); + assert_eq!(requests.len(), 2); + assert!( + requests[1] + .to_ascii_lowercase() + .contains("cookie: cf_clearance=wrong-scope-clearance"), + "retry request should send synthesized cf_clearance:\n{}", + requests[1] + ); + let snapshot = core.snapshot(); + let clearance_cookie = snapshot + .cookies + .platform_cookies + .iter() + .find(|cookie| cookie.name == "cf_clearance") + .expect("cf_clearance platform cookie"); + assert_eq!(clearance_cookie.path.as_deref(), Some("/")); + assert_ne!( + clearance_cookie.domain.as_deref(), + Some("unrelated.example") + ); +} + +#[tokio::test] +async fn cloudflare_challenge_retry_accepts_platform_confirmed_existing_clearance() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let snapshot = core.apply_platform_cookies(vec![PlatformCookie { + name: "cf_clearance".into(), + value: "stable-clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }]); + assert_eq!( + snapshot.cookies.cf_clearance.as_deref(), + Some("stable-clearance") + ); + core.set_cloudflare_challenge_handler(|_| async move { + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: Some("stable-clearance".into()), + cookies: vec![PlatformCookie { + name: "cf_clearance".into(), + value: "stable-clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }], + browser_user_agent: None, + } + }); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("platform-confirmed clearance should unblock retry"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.rows.len(), 1); + assert_eq!(requests.len(), 2); + assert_eq!( + core.snapshot().cookies.cf_clearance.as_deref(), + Some("stable-clearance") + ); +} + +#[tokio::test] +async fn business_request_is_blocked_while_cloudflare_challenge_is_in_progress() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let challenge_started = Arc::new(Notify::new()); + let release_challenge = Arc::new(Notify::new()); + { + let challenge_started = Arc::clone(&challenge_started); + let release_challenge = Arc::clone(&release_challenge); + core.set_cloudflare_challenge_handler(move |_| { + let challenge_started = Arc::clone(&challenge_started); + let release_challenge = Arc::clone(&release_challenge); + async move { + challenge_started.notify_waiters(); + release_challenge.notified().await; + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: Some("new-clearance".into()), + cookies: vec![PlatformCookie { + name: "cf_clearance".into(), + value: "new-clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }], + browser_user_agent: None, + } + } + }); + } + + let first_core = core.clone(); + let first = tokio::spawn(async move { + first_core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + }); + challenge_started.notified().await; + + // New outbound traffic that has not yet hit CF is frozen at dispatch. + let blocked = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("business request should be blocked locally"); + + assert!(matches!( + blocked, + FireCoreError::CloudflareChallengeInProgress { + operation: "fetch topic list" + } + )); + + release_challenge.notify_waiters(); + let response = first + .await + .expect("task should finish") + .expect("first request should retry after challenge"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.rows.len(), 1); + assert_eq!(requests.len(), 2); +} + +#[tokio::test] +async fn concurrent_cloudflare_challenges_join_and_retry_after_shared_success() { + let challenge_body = + r#"Just a moment...__cf_chl_opt"#; + let server = TestServer::spawn_scripted(vec![ + // Delay both CF bodies so the two clients are already in-flight before + // either enters the challenge owner/join path. + TestServerStep::delayed( + raw_cloudflare_challenge_response(403, challenge_body), + Duration::from_millis(80), + ), + TestServerStep::delayed( + raw_cloudflare_challenge_response(403, challenge_body), + Duration::from_millis(80), + ), + TestServerStep::immediate(raw_json_response( + 200, + "application/json", + &sample_latest_json(), + )), + TestServerStep::immediate(raw_json_response( + 200, + "application/json", + &sample_latest_json(), + )), + ]) + .await + .expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let challenge_calls = Arc::new(AtomicUsize::new(0)); + let challenge_started = Arc::new(Notify::new()); + let release_challenge = Arc::new(Notify::new()); + { + let challenge_calls = Arc::clone(&challenge_calls); + let challenge_started = Arc::clone(&challenge_started); + let release_challenge = Arc::clone(&release_challenge); + core.set_cloudflare_challenge_handler(move |_| { + let challenge_calls = Arc::clone(&challenge_calls); + let challenge_started = Arc::clone(&challenge_started); + let release_challenge = Arc::clone(&release_challenge); + async move { + challenge_calls.fetch_add(1, Ordering::SeqCst); + challenge_started.notify_waiters(); + release_challenge.notified().await; + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: Some("joined-clearance".into()), + cookies: vec![PlatformCookie { + name: "cf_clearance".into(), + value: "joined-clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }], + browser_user_agent: None, + } + } + }); + } + + let first_core = core.clone(); + let first = tokio::spawn(async move { + first_core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + }); + let second_core = core.clone(); + let second = tokio::spawn(async move { + second_core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + }); + + challenge_started.notified().await; + // Let the second CF victim reach the shared join wait. + sleep(Duration::from_millis(40)).await; + release_challenge.notify_waiters(); + + let first_response = first + .await + .expect("first task") + .expect("first request should succeed after shared challenge"); + let second_response = second + .await + .expect("second task") + .expect("joined request should retry after shared challenge"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(first_response.rows.len(), 1); + assert_eq!(second_response.rows.len(), 1); + assert_eq!(challenge_calls.load(Ordering::SeqCst), 1); + assert_eq!(requests.len(), 4); +} + +#[tokio::test] +async fn foreground_retry_bypasses_cloudflare_failure_cooldown() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let challenge_calls = Arc::new(AtomicUsize::new(0)); + { + let challenge_calls = Arc::clone(&challenge_calls); + core.set_cloudflare_challenge_handler(move |_| { + challenge_calls.fetch_add(1, Ordering::SeqCst); + async move { + fire_models::CloudflareChallengeResult { + completed: false, + user_cancelled: false, + fresh_cf_clearance: None, + cookies: vec![], + browser_user_agent: None, + } + } + }); + } + + for _ in 0..2 { + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("challenge should remain unresolved"); + assert!(matches!( + error, + FireCoreError::CloudflareChallenge { + operation: "fetch topic list", + .. + } + )); + } + let requests = server.shutdown_with_requests().await; + + assert_eq!(requests.len(), 2); + assert_eq!(challenge_calls.load(Ordering::SeqCst), 2); +} + +#[tokio::test] +async fn fetch_topic_list_self_heals_unauthorized_with_sweep_retry() { + let responses = vec![ + raw_json_response( + 401, + "application/json", + r#"{"errors":["session cookie state is stale"]}"#, + ), + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let calls = Arc::new(Mutex::new(Vec::new())); + { + let calls = Arc::clone(&calls); + core.set_cookie_self_healing_handler(move |request| { + let calls = Arc::clone(&calls); + async move { + calls + .lock() + .expect("calls mutex") + .push((request.phase, request.attempt)); + CookieSelfHealingResult { + completed: true, + session_epoch: request.session_epoch, + } + } + }); + } + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("self-healed request should retry"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.rows.len(), 1); + assert_eq!(requests.len(), 2); + assert_eq!( + calls.lock().expect("calls mutex").as_slice(), + &[(CookieSelfHealingPhase::Sweep, 1)] + ); +} + +#[tokio::test] +async fn fetch_topic_list_does_not_self_heal_cloudflare_challenge_without_handler() { + let responses = vec![raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let calls = Arc::new(AtomicUsize::new(0)); + { + let calls = Arc::clone(&calls); + core.set_cookie_self_healing_handler(move |request| { + calls.fetch_add(1, Ordering::SeqCst); + async move { + CookieSelfHealingResult { + completed: true, + session_epoch: request.session_epoch, + } + } + }); + } + + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("cloudflare challenge must not trigger cookie healing"); + let requests = server.shutdown_with_requests().await; + + assert!(matches!( + error, + FireCoreError::CloudflareChallenge { + operation: "fetch topic list", + .. + } + )); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!(requests.len(), 1); +} + +#[tokio::test] +async fn fetch_topic_list_does_not_self_heal_explicit_not_logged_in() { + let body = r#"{"errors":["You need to log in."],"error_type":"not_logged_in"}"#; + let responses = vec![raw_json_response(401, "application/json", body)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let calls = Arc::new(AtomicUsize::new(0)); + { + let calls = Arc::clone(&calls); + core.set_cookie_self_healing_handler(move |request| { + calls.fetch_add(1, Ordering::SeqCst); + async move { + CookieSelfHealingResult { + completed: true, + session_epoch: request.session_epoch, + } + } + }); + } + + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("explicit not_logged_in must surface as login required"); + let requests = server.shutdown_with_requests().await; + + assert!(matches!(error, FireCoreError::LoginRequired { .. })); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert_eq!(requests.len(), 1); +} + +#[tokio::test] +async fn fetch_topic_list_self_healing_escalates_to_nuclear_reset() { + let unauthorized = raw_json_response( + 401, + "application/json", + r#"{"errors":["session cookie state is stale"]}"#, + ); + let responses = vec![ + unauthorized.clone(), + unauthorized.clone(), + unauthorized, + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let calls = Arc::new(Mutex::new(Vec::new())); + { + let calls = Arc::clone(&calls); + core.set_cookie_self_healing_handler(move |request| { + let calls = Arc::clone(&calls); + async move { + calls + .lock() + .expect("calls mutex") + .push((request.phase, request.attempt)); + CookieSelfHealingResult { + completed: true, + session_epoch: request.session_epoch, + } + } + }); + } + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("nuclear reset should retry once"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.rows.len(), 1); + assert_eq!(requests.len(), 4); + assert_eq!( + calls.lock().expect("calls mutex").as_slice(), + &[ + (CookieSelfHealingPhase::Sweep, 1), + (CookieSelfHealingPhase::Sweep, 2), + (CookieSelfHealingPhase::NuclearReset, 1), + ] + ); +} + +#[tokio::test] +async fn fetch_topic_list_surfaces_rate_limited_cloudflare_challenge_error() { + let responses = vec![raw_cloudflare_challenge_response( + 429, + r#"Just a moment...__cf_chl_opt"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("429 Cloudflare challenge should surface as a challenge error"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::CloudflareChallenge { + operation: "fetch topic list", + .. + } + )); +} + +#[tokio::test] +async fn fetch_topic_list_accepts_cf_mitigated_challenge_without_html_content_type() { + let body = "managed challenge"; + let responses = vec![format!( + "HTTP/1.1 429 TEST\r\nServer: cloudflare\r\nContent-Type: text/plain; charset=utf-8\r\nCf-Mitigated: challenge\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("cf-mitigated challenge should not require HTML content type"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::CloudflareChallenge { + operation: "fetch topic list", + .. + } + )); +} + +#[tokio::test] +async fn fetch_topic_list_does_not_treat_non_cloudflare_403_body_as_challenge() { + let responses = vec![raw_json_response( + 403, + "text/html; charset=utf-8", + r#"Just a moment...__cf_chl_opt"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let error = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect_err("non-cloudflare 403 should surface as a plain HTTP error"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::HttpStatus { + operation: "fetch topic list", + status: 403, + .. + } + )); +} diff --git a/crates/fire-core/tests/network/cookie_healing.rs b/crates/fire-core/tests/network/cookie_healing.rs new file mode 100644 index 00000000..c149e6cd --- /dev/null +++ b/crates/fire-core/tests/network/cookie_healing.rs @@ -0,0 +1,153 @@ +use super::*; + +#[tokio::test] +async fn fetch_topic_list_keeps_local_login_when_success_response_only_clears_auth_cookies() { + let body = sample_latest_json(); + let response = format!( + "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nSet-Cookie: _t=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nSet-Cookie: _forum_session=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let server = TestServer::spawn(vec![response]).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let _response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + page: Some(1), + ..TopicListQuery::default() + }) + .await + .expect("auth-cookie deletion alone should not invalidate login"); + let _ = server.shutdown().await; + + let snapshot = core.snapshot(); + assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); + assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); + assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("csrf-token")); + assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); + assert_eq!( + snapshot.bootstrap.current_username.as_deref(), + Some("alice") + ); + assert!(snapshot.bootstrap.has_preloaded_data); +} + +#[tokio::test] +async fn fetch_topic_posts_keeps_local_login_when_forbidden_invalid_access_sets_logged_out_header() +{ + let body = r#"{"errors":["您没有权限查看请求的资源。"],"error_type":"invalid_access"}"#; + let response = format!( + "HTTP/1.1 403 TEST\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nDiscourse-Logged-Out: 1\r\nSet-Cookie: _t=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let server = TestServer::spawn(vec![response]).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + let before_epoch = core.session_epoch(); + + let error = core + .fetch_topic_posts(2_270_621, vec![18_408_024]) + .await + .expect_err("ordinary invalid_access 403 should not invalidate login"); + let requests = server.shutdown_with_requests().await; + + assert!(matches!( + error, + FireCoreError::HttpStatus { + operation: "fetch topic posts", + status: 403, + body, + } if body.contains("\"error_type\":\"invalid_access\"") + )); + assert_eq!(core.session_epoch(), before_epoch); + + let snapshot = core.snapshot(); + assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); + assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); + assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("csrf-token")); + assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); + assert_eq!( + snapshot.bootstrap.current_username.as_deref(), + Some("alice") + ); + assert!(snapshot.bootstrap.has_preloaded_data); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains( + "GET /t/2270621/posts.json?post_ids%5B%5D=18408024&include_suggested=false HTTP/1.1" + )); +} diff --git a/crates/fire-core/tests/network/mutations.rs b/crates/fire-core/tests/network/mutations.rs new file mode 100644 index 00000000..770f7be3 --- /dev/null +++ b/crates/fire-core/tests/network/mutations.rs @@ -0,0 +1,991 @@ +use super::*; + +#[tokio::test] +async fn create_reply_refreshes_csrf_and_parses_wrapped_post_payload() { + let responses = vec![ + raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), + raw_json_response( + 200, + "application/json", + r#"{ + "post": { + "id": 9010, + "username": "alice", + "name": "Alice", + "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png", + "cooked": "

Reply body

", + "post_number": 2, + "post_type": 1, + "created_at": "2026-03-28T00:10:00Z", + "updated_at": "2026-03-28T00:10:00Z", + "like_count": 0, + "reply_count": 0, + "reply_to_post_number": 1, + "bookmarked": false, + "bookmark_id": null, + "reactions": [], + "current_user_reaction": null, + "accepted_answer": false, + "can_edit": true, + "can_delete": true, + "can_recover": false, + "hidden": false + } + }"#, + ), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: None, + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let post = core + .create_reply(TopicReplyRequest { + topic_id: 123, + raw: "Reply body".into(), + reply_to_post_number: Some(1), + }) + .await + .expect("create reply"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(post.id, 9010); + assert_eq!(post.post_number, 2); + assert_eq!(post.reply_to_post_number, Some(1)); + assert_eq!(requests.len(), 2); + assert!(requests[0].contains("GET /session/csrf HTTP/1.1")); + assert!(requests[1].contains("POST /posts.json HTTP/1.1")); + assert!(requests[1] + .to_ascii_lowercase() + .contains("x-csrf-token: fresh-csrf")); + assert!(requests[1].contains("topic_id=123&raw=Reply+body&reply_to_post_number=1")); + assert_eq!( + core.snapshot().cookies.csrf_token.as_deref(), + Some("fresh-csrf") + ); +} + +#[tokio::test] +async fn create_reply_refreshes_csrf_before_logged_out_header_handling() { + let bad_csrf_body = r#"["BAD CSRF"]"#; + let bad_csrf_response = format!( + "HTTP/1.1 403 TEST\r\nContent-Type: application/json; charset=utf-8\r\nDiscourse-Logged-Out: 1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{bad_csrf_body}", + bad_csrf_body.len() + ); + let responses = vec![ + bad_csrf_response, + raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), + raw_json_response( + 200, + "application/json", + r#"{ + "post": { + "id": 9010, + "username": "alice", + "name": "Alice", + "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png", + "cooked": "

Reply body

", + "post_number": 2, + "post_type": 1, + "created_at": "2026-03-28T00:10:00Z", + "updated_at": "2026-03-28T00:10:00Z", + "like_count": 0, + "reply_count": 0, + "reply_to_post_number": 1, + "bookmarked": false, + "bookmark_id": null, + "reactions": [], + "current_user_reaction": null, + "accepted_answer": false, + "can_edit": true, + "can_delete": true, + "can_recover": false, + "hidden": false + } + }"#, + ), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: Some("stale-csrf".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let post = core + .create_reply(TopicReplyRequest { + topic_id: 123, + raw: "Reply body".into(), + reply_to_post_number: Some(1), + }) + .await + .expect("create reply after BAD CSRF refresh"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(post.id, 9010); + assert_eq!(requests.len(), 3); + assert!(requests[0].contains("POST /posts.json HTTP/1.1")); + assert!(requests[1].contains("GET /session/csrf HTTP/1.1")); + assert!(requests[2].contains("POST /posts.json HTTP/1.1")); + assert!(requests[2] + .to_ascii_lowercase() + .contains("x-csrf-token: fresh-csrf")); + assert_eq!( + core.snapshot().cookies.csrf_token.as_deref(), + Some("fresh-csrf") + ); +} + +#[tokio::test] +async fn create_reply_cloudflare_retry_rebuilds_stale_csrf_header() { + let responses = vec![ + raw_cloudflare_challenge_response( + 403, + r#"Just a moment...__cf_chl_opt"#, + ), + raw_json_response( + 200, + "application/json", + r#"{ + "post": { + "id": 9010, + "username": "alice", + "name": "Alice", + "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png", + "cooked": "

Reply body

", + "post_number": 2, + "post_type": 1, + "created_at": "2026-03-28T00:10:00Z", + "updated_at": "2026-03-28T00:10:00Z", + "like_count": 0, + "reply_count": 0, + "reply_to_post_number": 1, + "bookmarked": false, + "bookmark_id": null, + "reactions": [], + "current_user_reaction": null, + "accepted_answer": false, + "can_edit": true, + "can_delete": true, + "can_recover": false, + "hidden": false + } + }"#, + ), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: Some("stale-csrf".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + { + let handler_core = core.clone(); + core.set_cloudflare_challenge_handler(move |_| { + let core = handler_core.clone(); + async move { + let _ = core.apply_csrf_token("fresh-csrf".into()); + fire_models::CloudflareChallengeResult { + completed: true, + user_cancelled: false, + fresh_cf_clearance: Some("new-clearance".into()), + cookies: vec![PlatformCookie { + name: "cf_clearance".into(), + value: "new-clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }], + browser_user_agent: None, + } + } + }); + } + + let post = core + .create_reply(TopicReplyRequest { + topic_id: 123, + raw: "Reply body".into(), + reply_to_post_number: Some(1), + }) + .await + .expect("create reply after challenge"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(post.id, 9010); + assert_eq!(requests.len(), 2); + assert!(requests[0] + .to_ascii_lowercase() + .contains("x-csrf-token: stale-csrf")); + assert!(requests[1] + .to_ascii_lowercase() + .contains("x-csrf-token: fresh-csrf")); + assert!( + !requests[1] + .to_ascii_lowercase() + .contains("x-csrf-token: stale-csrf"), + "retry must not replay stale CSRF header:\n{}", + requests[1] + ); +} + +/// Post-challenge rebuild must force `/session/csrf` after bootstrap when home +/// HTML lacks csrf meta and Set-Cookie rotated the forum session (which clears +/// the cached CSRF via auth rotation). Without this, writes stay blocked on +/// `can_write_authenticated_api == false` until a later opportunistic refresh. +#[tokio::test] +async fn complete_cloudflare_challenge_realigns_csrf_after_bootstrap_without_meta() { + let home_without_csrf = r#" + + + + + + + + +
+ + +"#; + let rotating_home = format!( + "HTTP/1.1 200 TEST\r\nContent-Type: text/html\r\nContent-Length: {}\r\nSet-Cookie: _forum_session=rotated-forum; path=/; SameSite=Lax\r\nConnection: close\r\n\r\n{home_without_csrf}", + home_without_csrf.len() + ); + let home_again = format!( + "HTTP/1.1 200 TEST\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{home_without_csrf}", + home_without_csrf.len() + ); + let responses = vec![ + // schedule_post_challenge: refresh_bootstrap + rotating_home, + // schedule_post_challenge: forced refresh_csrf_token + raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), + // refresh_all_forced core: refresh_bootstrap again + home_again, + // refresh_all_forced core: home topic list + raw_json_response(200, "application/json", &sample_latest_json()), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: Some("stale-csrf".into()), + current_url: Some(server.base_url()), + browser_user_agent: Some("FireTests/1.0".into()), + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "old-clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + assert_eq!( + core.snapshot().cookies.csrf_token.as_deref(), + Some("stale-csrf") + ); + assert!(core.snapshot().readiness().can_write_authenticated_api); + + let _ = core.complete_cloudflare_challenge( + vec![PlatformCookie { + name: "cf_clearance".into(), + value: "fresh-clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: Some("None".into()), + }], + Some("fresh-clearance".into()), + Some("FireTests/1.0".into()), + ); + + // Post-challenge task: 30ms + trust settle (~400ms) + bootstrap + csrf. + let mut realigned = false; + for _ in 0..80 { + let snapshot = core.snapshot(); + if snapshot.cookies.csrf_token.as_deref() == Some("fresh-csrf") + && snapshot.cookies.forum_session.as_deref() == Some("rotated-forum") + && snapshot.readiness().can_write_authenticated_api + { + realigned = true; + break; + } + sleep(Duration::from_millis(50)).await; + } + + let requests = server.shutdown_with_requests().await; + let snapshot = core.snapshot(); + + assert!( + realigned, + "expected post-challenge CSRF realign; csrf={:?} forum={:?} can_write={}", + snapshot.cookies.csrf_token, + snapshot.cookies.forum_session, + snapshot.readiness().can_write_authenticated_api + ); + assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); + assert_eq!( + snapshot.cookies.cf_clearance.as_deref(), + Some("fresh-clearance") + ); + assert!( + requests + .iter() + .any(|request| { request.to_ascii_lowercase().contains("get /session/csrf") }), + "post-challenge rebuild must call /session/csrf:\n{requests:#?}" + ); +} + +#[tokio::test] +async fn create_reply_surfaces_pending_review_state() { + let responses = vec![raw_json_response( + 200, + "application/json", + r#"{"action":"enqueued","pending_count":2}"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let error = core + .create_reply(TopicReplyRequest { + topic_id: 123, + raw: "Reply body".into(), + reply_to_post_number: None, + }) + .await + .expect_err("create reply should enqueue"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::PostEnqueued { pending_count: 2 } + )); +} + +#[tokio::test] +async fn create_reply_surfaces_cloudflare_challenge_error() { + let responses = vec![raw_cloudflare_challenge_response( + 403, + r#"

Just a moment

"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: Some("csrf".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let error = core + .create_reply(TopicReplyRequest { + topic_id: 123, + raw: "Reply body".into(), + reply_to_post_number: Some(1), + }) + .await + .expect_err("cloudflare challenge should surface as an error"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::CloudflareChallenge { + operation: "create reply", + .. + } + )); +} + +#[tokio::test] +async fn toggle_post_reaction_parses_reaction_update_payload() { + let responses = vec![raw_json_response( + 200, + "application/json", + r#"{ + "reactions": [ + { "id": "heart", "type": "emoji", "count": 4 }, + { "id": "laughing", "type": "emoji", "count": 1 } + ], + "current_user_reaction": { "id": "laughing", "type": "emoji", "count": 1, "can_undo": true } + }"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let update = core + .toggle_post_reaction(9001, "laughing".into()) + .await + .expect("toggle post reaction"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(update.reactions.len(), 2); + assert_eq!(update.reactions[0].id, "heart"); + assert_eq!( + update + .current_user_reaction + .as_ref() + .map(|reaction| reaction.id.as_str()), + Some("laughing") + ); + assert_eq!( + update + .current_user_reaction + .as_ref() + .and_then(|reaction| reaction.can_undo), + Some(true) + ); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains( + "PUT /discourse-reactions/posts/9001/custom-reactions/laughing/toggle.json HTTP/1.1" + )); + assert!(requests[0] + .to_ascii_lowercase() + .contains("x-csrf-token: csrf-token")); + assert!(requests[0] + .to_ascii_lowercase() + .contains("content-length: 0")); +} + +#[tokio::test] +async fn toggle_post_reaction_tolerates_malformed_current_user_reaction() { + let responses = vec![raw_json_response( + 200, + "application/json", + r#"{ + "reactions": [ + { "id": "heart", "type": "emoji", "count": 4 } + ], + "current_user_reaction": "unexpected" + }"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let update = core + .toggle_post_reaction(9001, "laughing".into()) + .await + .expect("toggle post reaction"); + + let _ = server.shutdown().await; + assert_eq!(update.reactions.len(), 1); + assert_eq!(update.current_user_reaction, None); +} + +#[tokio::test] +async fn toggle_post_reaction_encodes_reaction_path_segment() { + let responses = vec![raw_json_response( + 200, + "application/json", + r#"{ + "reactions": [ + { "id": "+1", "type": "emoji", "count": 1 } + ], + "current_user_reaction": { "id": "+1", "type": "emoji", "count": 1, "can_undo": true } + }"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let update = core + .toggle_post_reaction(9001, "+1".into()) + .await + .expect("toggle post reaction"); + let requests = server.shutdown_with_requests().await; + + assert_eq!( + update + .current_user_reaction + .as_ref() + .map(|reaction| reaction.id.as_str()), + Some("+1") + ); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains( + "PUT /discourse-reactions/posts/9001/custom-reactions/%2B1/toggle.json HTTP/1.1" + )); +} + +#[tokio::test] +async fn fetch_reaction_users_uses_reactions_users_endpoint_and_skips_malformed_items() { + let responses = vec![raw_json_response( + 200, + "application/json", + r#"{ + "reaction_users": [ + { + "id": "heart", + "count": "2", + "users": [ + { + "id": "1", + "username": "alice", + "name": "Alice", + "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" + }, + { "bad": "ignored" } + ] + }, + 1, + { + "id": "clap", + "users": [ + { "username": "bob" } + ] + } + ] + }"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let groups = core + .fetch_reaction_users(9001) + .await + .expect("reaction users"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(groups.len(), 2); + assert_eq!(groups[0].id, "heart"); + assert_eq!(groups[0].count, 2); + assert_eq!(groups[0].users.len(), 1); + assert_eq!(groups[0].users[0].id, 1); + assert_eq!(groups[0].users[0].username, "alice"); + assert_eq!(groups[0].users[0].name.as_deref(), Some("Alice")); + assert_eq!( + groups[0].users[0].avatar_template.as_deref(), + Some("/user_avatar/linux.do/alice/{size}/1_2.png") + ); + assert_eq!(groups[1].id, "clap"); + assert_eq!(groups[1].count, 1); + assert_eq!(groups[1].users.len(), 1); + assert_eq!(groups[1].users[0].id, 0); + assert_eq!(groups[1].users[0].username, "bob"); + assert_eq!(requests.len(), 1); + assert!( + requests[0].contains("GET /discourse-reactions/posts/9001/reactions-users.json HTTP/1.1") + ); +} + +#[tokio::test] +async fn like_post_uses_post_actions_endpoint() { + let responses = vec![raw_text_response(200, "{}")]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let update = core.like_post(9001).await.expect("like post"); + let requests = server.shutdown_with_requests().await; + + assert!(update.is_none()); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("POST /post_actions HTTP/1.1")); + assert!(requests[0] + .to_ascii_lowercase() + .contains("x-csrf-token: csrf-token")); + assert!(requests[0].contains("id=9001&post_action_type_id=2")); +} + +#[tokio::test] +async fn like_post_without_auth_session_does_not_send_undefined_csrf_request() { + let server = TestServer::spawn(Vec::new()).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let error = core + .like_post(9001) + .await + .expect_err("write without an auth session should fail before network"); + let requests = server.shutdown_with_requests().await; + + assert!(matches!(error, FireCoreError::MissingLoginSession)); + assert!(requests.is_empty()); +} + +#[tokio::test] +async fn like_post_parses_reaction_update_when_response_includes_reaction_fields() { + let responses = vec![raw_json_response( + 200, + "application/json", + r#"{ + "id": 9001, + "post_number": 1, + "like_count": 15, + "reactions": [ + { "id": "heart", "type": "emoji", "count": 15 } + ], + "current_user_reaction": { "id": "heart", "type": "emoji", "count": 15, "can_undo": true } + }"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let update = core + .like_post(9001) + .await + .expect("like post") + .expect("reaction update"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(update.reactions.len(), 1); + assert_eq!(update.reactions[0].id, "heart"); + assert_eq!(update.reactions[0].count, 15); + assert_eq!( + update + .current_user_reaction + .as_ref() + .map(|reaction| reaction.id.as_str()), + Some("heart") + ); + assert_eq!( + update + .current_user_reaction + .as_ref() + .and_then(|reaction| reaction.can_undo), + Some(true) + ); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("POST /post_actions HTTP/1.1")); +} diff --git a/crates/fire-core/tests/network/session_refresh.rs b/crates/fire-core/tests/network/session_refresh.rs new file mode 100644 index 00000000..eb9c7dd9 --- /dev/null +++ b/crates/fire-core/tests/network/session_refresh.rs @@ -0,0 +1,441 @@ +use super::*; + +#[tokio::test] +async fn refresh_csrf_token_updates_session_from_network() { + let responses = vec![raw_json_response( + 200, + "application/json", + r#"{"csrf":"fresh-csrf"}"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let snapshot = core.refresh_csrf_token().await.expect("csrf refresh"); + server.shutdown().await; + + assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("fresh-csrf")); +} + +#[tokio::test] +async fn refresh_csrf_token_preserves_login_when_success_response_reports_logged_out() { + let body = r#"{"csrf":"fresh-csrf"}"#; + let response = format!( + "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nDiscourse-Logged-Out: 1\r\nSet-Cookie: _t=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let server = TestServer::spawn(vec![response]).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: None, + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let snapshot = core + .refresh_csrf_token_if_needed() + .await + .expect("successful csrf response should be usable"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("fresh-csrf")); + assert_eq!(snapshot.cookies.t_token.as_deref(), Some("token")); + assert_eq!(snapshot.cookies.forum_session.as_deref(), Some("forum")); + assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); + assert_eq!(requests.len(), 1); + let request = requests[0].to_ascii_lowercase(); + assert!(request.contains("get /session/csrf http/1.1")); + assert!(request.contains("discourse-logged-in: true")); + assert!(request.contains("_t=token")); + assert!(request.contains("_forum_session=forum")); +} + +#[tokio::test] +async fn refresh_csrf_token_accepts_scalar_tokens() { + let responses = vec![raw_json_response( + 200, + "application/json", + r#"{"csrf":12345}"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let snapshot = core.refresh_csrf_token().await.expect("csrf refresh"); + server.shutdown().await; + + assert_eq!(snapshot.cookies.csrf_token.as_deref(), Some("12345")); +} + +#[tokio::test] +async fn concurrent_csrf_refresh_if_needed_shares_in_flight_request() { + let server = TestServer::spawn_scripted(vec![TestServerStep::delayed( + raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), + Duration::from_millis(50), + )]) + .await + .expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: None, + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let (first, second) = tokio::join!( + core.refresh_csrf_token_if_needed(), + core.refresh_csrf_token_if_needed() + ); + let first = first.expect("first csrf refresh"); + let second = second.expect("second csrf refresh"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(first.cookies.csrf_token.as_deref(), Some("fresh-csrf")); + assert_eq!(second.cookies.csrf_token.as_deref(), Some("fresh-csrf")); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("GET /session/csrf HTTP/1.1")); +} + +#[tokio::test] +async fn queued_csrf_refresh_if_needed_does_not_retry_after_session_logout() { + let server = TestServer::spawn_scripted(vec![TestServerStep::delayed( + raw_json_response(200, "application/json", r#"{"csrf":"fresh-csrf"}"#), + Duration::from_millis(120), + )]) + .await + .expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: None, + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let first_core = core.clone(); + let first = tokio::spawn(async move { first_core.refresh_csrf_token_if_needed().await }); + sleep(Duration::from_millis(20)).await; + + let second_core = core.clone(); + let second = tokio::spawn(async move { second_core.refresh_csrf_token_if_needed().await }); + sleep(Duration::from_millis(20)).await; + + let logged_out = core.logout_local(true); + assert!(!logged_out.cookies.can_authenticate_requests()); + + let first = first.await.expect("first task"); + let second = second.await.expect("second task"); + let requests = server.shutdown_with_requests().await; + + assert!(matches!( + first, + Err(FireCoreError::StaleSessionResponse { + operation: "refresh csrf token" + }) + )); + let second = second.expect("queued csrf refresh should skip after logout"); + assert_eq!(second.cookies.csrf_token, None); + assert!(!second.cookies.can_authenticate_requests()); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("GET /session/csrf HTTP/1.1")); +} + +#[tokio::test] +async fn logout_remote_retries_after_bad_csrf() { + let responses = vec![ + raw_text_response(403, r#"["BAD CSRF"]"#), + raw_json_response(200, "application/json", r#"{"csrf":"retry-csrf"}"#), + raw_text_response(200, "{}"), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("stale-csrf".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let snapshot = core.logout_remote(true).await.expect("logout"); + let requests = server.shutdown().await; + + assert!(!snapshot.cookies.has_login_session()); + assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); + assert_eq!(requests.load(Ordering::SeqCst), 3); +} + +#[tokio::test] +async fn refresh_bootstrap_fetches_home_html() { + let responses = vec![raw_text_response(200, &sample_home_html())]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let snapshot = core.refresh_bootstrap().await.expect("bootstrap refresh"); + let requests = server.shutdown_with_requests().await; + let trace = core.network_trace_detail(1).expect("network trace detail"); + + assert_eq!( + snapshot.bootstrap.current_username.as_deref(), + Some("alice") + ); + assert!(snapshot.bootstrap.has_preloaded_data); + assert_eq!(requests.len(), 1); + + let wire_request = requests[0].to_ascii_lowercase(); + assert!(wire_request.contains("get / http/1.1")); + assert!(wire_request.contains("accept: text/html")); + assert!(wire_request.contains("accept-language: zh-cn,zh;q=0.9,en;q=0.8")); + assert!(wire_request.contains("user-agent: mozilla/5.0")); + + assert!(trace + .request_headers + .iter() + .any(|header| header.name == "user-agent" && header.value.starts_with("Mozilla/5.0"))); + assert!(trace.request_headers.iter().any(|header| { + header.name == "accept-language" && header.value == "zh-CN,zh;q=0.9,en;q=0.8" + })); +} + +#[tokio::test] +async fn refresh_bootstrap_falls_back_to_site_json_when_home_lacks_site_metadata() { + let home_html = r#" + + + + + + + + +
+ + +"#; + let site_json = r#"{ + "categories": [ + { + "id": 2, + "name": "Rust", + "slug": "rust", + "parent_category_id": 1, + "color": "FFFFFF", + "text_color": "000000" + } + ], + "top_tags": [ + {"name": "swift"}, + "rust" + ], + "can_tag_topics": true +}"#; + let responses = vec![ + raw_text_response(200, home_html), + raw_json_response(200, "application/json", site_json), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let snapshot = core.refresh_bootstrap().await.expect("bootstrap refresh"); + let requests = server.shutdown_with_requests().await; + + assert_eq!( + snapshot.bootstrap.current_username.as_deref(), + Some("alice") + ); + assert!(snapshot.bootstrap.has_preloaded_data); + assert!(snapshot.bootstrap.has_site_settings); + assert!(snapshot.bootstrap.has_site_metadata); + assert_eq!(snapshot.bootstrap.categories.len(), 1); + assert_eq!(snapshot.bootstrap.top_tags, vec!["swift", "rust"]); + assert!(snapshot.bootstrap.can_tag_topics); + assert_eq!(requests.len(), 2); + assert!(requests[0].to_ascii_lowercase().contains("get / http/1.1")); + assert!(requests[1] + .to_ascii_lowercase() + .contains("get /site.json http/1.1")); +} + +#[tokio::test] +async fn refresh_bootstrap_uses_browser_user_agent_and_full_platform_cookies() { + let responses = vec![raw_text_response(200, &sample_home_html())]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: None, + csrf_token: None, + current_url: Some(server.base_url()), + browser_user_agent: Some("Mozilla/5.0 Exact WKWebView".into()), + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "__cf_bm".into(), + value: "browser-context".into(), + domain: None, + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let _ = core.refresh_bootstrap().await.expect("bootstrap refresh"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(requests.len(), 1); + let wire_request = requests[0].to_ascii_lowercase(); + assert!(wire_request.contains("user-agent: mozilla/5.0 exact wkwebview")); + let cookie_header = wire_request + .lines() + .find(|line| line.starts_with("cookie: ")) + .expect("cookie header"); + assert!(cookie_header.contains("_t=token")); + assert!(cookie_header.contains("_forum_session=forum")); + assert!(cookie_header.contains("__cf_bm=browser-context")); +} diff --git a/crates/fire-core/tests/network/stale_responses.rs b/crates/fire-core/tests/network/stale_responses.rs new file mode 100644 index 00000000..951e2d8b --- /dev/null +++ b/crates/fire-core/tests/network/stale_responses.rs @@ -0,0 +1,191 @@ +use super::*; + +#[tokio::test] +async fn stale_response_is_discarded_after_local_logout() { + let body = sample_latest_json(); + let response = format!( + "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nSet-Cookie: _t=stale-token; path=/; SameSite=Lax\r\nSet-Cookie: _forum_session=stale-forum; path=/; SameSite=Lax\r\nSet-Cookie: __cf_bm=stale-browser-context; path=/; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let server = TestServer::spawn_scripted(vec![TestServerStep::delayed( + response, + Duration::from_millis(150), + )]) + .await + .expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let request_core = core.clone(); + let task = tokio::spawn(async move { + request_core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + }); + + sleep(Duration::from_millis(40)).await; + let cleared = core.logout_local(true); + assert!(!cleared.cookies.has_login_session()); + + let error = task + .await + .expect("task join") + .expect_err("stale response should be discarded"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::StaleSessionResponse { + operation: "fetch topic list" + } + )); + let snapshot = core.snapshot(); + assert_eq!(snapshot.cookies.t_token, None); + assert_eq!(snapshot.cookies.forum_session, None); + assert_eq!(snapshot.cookies.cf_clearance, None); + assert!(!snapshot + .cookies + .platform_cookies + .iter() + .any(|cookie| cookie.name == "__cf_bm")); +} + +#[tokio::test] +async fn stale_response_is_discarded_after_session_rotation() { + let body = sample_latest_json(); + let response = format!( + "HTTP/1.1 200 TEST\r\nContent-Type: application/json\r\nContent-Length: {}\r\nSet-Cookie: _t=stale-token; path=/; SameSite=Lax\r\nSet-Cookie: _forum_session=stale-forum; path=/; SameSite=Lax\r\nSet-Cookie: __cf_bm=stale-browser-context; path=/; SameSite=Lax\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let server = TestServer::spawn_scripted(vec![TestServerStep::delayed( + response, + Duration::from_millis(150), + )]) + .await + .expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "old-token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "old-forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let request_core = core.clone(); + let task = tokio::spawn(async move { + request_core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + }); + + sleep(Duration::from_millis(40)).await; + let rotated = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "fresh-token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "fresh-forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + assert_eq!(rotated.cookies.t_token.as_deref(), Some("fresh-token")); + + let error = task + .await + .expect("task join") + .expect_err("stale response should be discarded"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::StaleSessionResponse { + operation: "fetch topic list" + } + )); + let snapshot = core.snapshot(); + assert_eq!(snapshot.cookies.t_token.as_deref(), Some("fresh-token")); + assert_eq!( + snapshot.cookies.forum_session.as_deref(), + Some("fresh-forum") + ); + assert!(!snapshot + .cookies + .platform_cookies + .iter() + .any(|cookie| cookie.name == "__cf_bm")); +} diff --git a/crates/fire-core/tests/network/topic_detail.rs b/crates/fire-core/tests/network/topic_detail.rs new file mode 100644 index 00000000..cf8d843a --- /dev/null +++ b/crates/fire-core/tests/network/topic_detail.rs @@ -0,0 +1,1339 @@ +use super::*; + +#[tokio::test] +async fn fetch_topic_detail_parses_detail_payload() { + let responses = vec![raw_json_response( + 200, + "application/json", + &sample_topic_detail_json(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let detail = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: true, + force_load: true, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(detail.id, 123); + assert_eq!(detail.title, "Fire topic"); + assert!(requests[0].contains("GET /t/123.json?track_visit=true&forceLoad=true HTTP/1.1")); + assert_eq!( + detail.tags, + vec![ + TopicTag { + id: None, + name: "rust".into(), + slug: None, + }, + TopicTag { + id: None, + name: "linuxdo".into(), + slug: None, + }, + ] + ); + assert_eq!(detail.post_stream.posts.len(), 1); + assert_eq!(detail.post_stream.posts[0].username, "alice"); + assert_eq!(detail.thread.original_post_number, Some(1)); + assert_eq!(detail.thread.reply_sections.len(), 0); + assert_eq!(detail.flat_posts.len(), 1); + assert!(detail.flat_posts[0].is_original_post); + assert_eq!(detail.flat_posts[0].post.post_number, 1); + assert!(!detail.flat_posts[0].shows_thread_line); + assert_eq!( + detail + .details + .created_by + .as_ref() + .map(|value| value.username.as_str()), + Some("alice") + ); +} + +#[tokio::test] +async fn fetch_topic_detail_parses_post_author_metadata() { + let mut payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail payload json"); + let post = payload + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .and_then(|stream| stream.get_mut("posts")) + .and_then(Value::as_array_mut) + .and_then(|posts| posts.first_mut()) + .and_then(Value::as_object_mut) + .expect("first post"); + post.insert("user_id".into(), json!(42)); + post.insert("user_title".into(), json!("Core Team")); + post.insert("primary_group_name".into(), json!("staff")); + post.insert("flair_url".into(), json!("/images/flair/staff.svg")); + post.insert("flair_name".into(), json!("Staff")); + post.insert("flair_bg_color".into(), json!("0057ff")); + post.insert("flair_color".into(), json!("ffffff")); + post.insert("flair_group_id".into(), json!("7")); + post.insert("moderator".into(), json!(true)); + post.insert("admin".into(), json!(false)); + post.insert("group_moderator".into(), json!(true)); + post.insert( + "user_status".into(), + json!({ + "emoji": "coffee", + "description": "Reviewing patches" + }), + ); + + let responses = vec![raw_json_response( + 200, + "application/json", + &payload.to_string(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let detail = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: true, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let _ = server.shutdown().await; + + let metadata = &detail.post_stream.posts[0].author_metadata; + assert_eq!(metadata.user_id, Some(42)); + assert_eq!(metadata.user_title.as_deref(), Some("Core Team")); + assert_eq!(metadata.primary_group_name.as_deref(), Some("staff")); + assert_eq!( + metadata.flair_url.as_deref(), + Some("/images/flair/staff.svg") + ); + assert_eq!(metadata.flair_name.as_deref(), Some("Staff")); + assert_eq!(metadata.flair_bg_color.as_deref(), Some("0057ff")); + assert_eq!(metadata.flair_color.as_deref(), Some("ffffff")); + assert_eq!(metadata.flair_group_id, Some(7)); + assert!(metadata.moderator); + assert!(!metadata.admin); + assert!(metadata.group_moderator); + assert_eq!(metadata.user_status_emoji.as_deref(), Some("coffee")); + assert_eq!( + metadata.user_status_description.as_deref(), + Some("Reviewing patches") + ); +} + +#[tokio::test] +async fn fetch_topic_detail_rejects_mismatched_topic_identity() { + let payload = sample_topic_detail_json().replace("\"id\": 123", "\"id\": 999"); + let responses = vec![raw_json_response(200, "application/json", &payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let error = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: false, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect_err("mismatched topic id should fail"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::UnexpectedTopicDetail { + requested_topic_id: 123, + actual_topic_id: 999, + } + )); +} + +#[tokio::test] +async fn fetch_topic_detail_source_snapshot_tracks_visit_headers_and_force_load_query() { + let responses = vec![raw_json_response( + 200, + "application/json", + &sample_topic_detail_json(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let snapshot = core + .fetch_topic_detail_source_snapshot(TopicDetailSourceQuery { + topic_id: 123, + target_post_number: None, + allow_suggested_unread_root: false, + track_visit: true, + force_load: true, + initial_batch_size: 40, + load_more_batch_size: 40, + max_auto_batches_per_gesture: 3, + max_auto_posts_per_gesture: 120, + }) + .await + .expect("topic source snapshot"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(snapshot.body.post.post_number, 1); + assert_eq!(snapshot.loaded_posts.len(), 1); + assert_eq!(requests.len(), 1); + let first_request_headers = requests[0].to_ascii_lowercase(); + assert!(requests[0].contains("GET /t/123.json?track_visit=true&forceLoad=true HTTP/1.1")); + assert!(first_request_headers.contains("discourse-track-view: 1")); + assert!(first_request_headers.contains("discourse-track-view-topic-id: 123")); +} + +#[tokio::test] +async fn fetch_topic_detail_source_snapshot_recovers_missing_body_via_stream_head_post_ids() { + // Notification deep-links open `/t/{id}/{N}.json`. Large topics return a + // nearby posts chunk without OP/post #1. Body must be recovered from + // stream[0] via post_ids[] instead of hard-failing posts.json?post_number=1. + let target_post_number = 200_u32; + let body_post = json!({ + "id": 1001, + "username": "op", + "cooked": "

Original post

", + "post_number": 1, + "reply_to_post_number": null, + "reply_count": 5 + }); + let target_post = json!({ + "id": 1200, + "username": "replier", + "cooked": "

Deep reply

", + "post_number": target_post_number, + "reply_to_post_number": 1, + "reply_count": 0 + }); + let stream = (1_u64..=220).map(|n| 1000 + n).collect::>(); + let mid_topic_payload = json!({ + "id": 123, + "title": "Large topic", + "slug": "large-topic", + "posts_count": 220, + "post_stream": { + "posts": [target_post.clone()], + "stream": stream + } + }); + let body_by_ids = json!({ + "post_stream": { + "posts": [body_post.clone()], + "stream": [1001] + } + }); + // Remaining initial stream ids (1002..1010) after body recovery. + let initial_batch_posts = (2_u32..=10) + .map(|post_number| { + json!({ + "id": 1000 + u64::from(post_number), + "username": format!("u{post_number}"), + "cooked": format!("

r{post_number}

"), + "post_number": post_number, + "reply_to_post_number": 1, + "reply_count": 0 + }) + }) + .collect::>(); + let initial_batch = json!({ + "post_stream": { + "posts": initial_batch_posts, + "stream": (1002_u64..=1010).collect::>() + } + }); + + let server = TestServer::spawn(vec![ + raw_json_response(200, "application/json", &mid_topic_payload.to_string()), + // resolve_topic_body_post: stream head via post_ids[] + raw_json_response(200, "application/json", &body_by_ids.to_string()), + // initial batch hydration for missing stream ids + raw_json_response(200, "application/json", &initial_batch.to_string()), + ]) + .await + .expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let snapshot = core + .fetch_topic_detail_source_snapshot(TopicDetailSourceQuery { + topic_id: 123, + target_post_number: Some(target_post_number), + allow_suggested_unread_root: false, + track_visit: true, + force_load: true, + initial_batch_size: 10, + load_more_batch_size: 10, + max_auto_batches_per_gesture: 3, + max_auto_posts_per_gesture: 120, + }) + .await + .expect("topic source snapshot should recover missing body"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(snapshot.body.post.post_number, 1); + assert_eq!(snapshot.body.post.id, 1001); + assert!(snapshot + .loaded_posts + .iter() + .any(|post| post.post_number == target_post_number)); + assert!(requests[0].contains("GET /t/123/200.json")); + assert!( + requests.iter().any(|request| { + request.contains("GET /t/123/posts.json") && request.contains("post_ids%5B%5D=1001") + || request.contains("post_ids[]=1001") + }), + "expected OP recovery via post_ids[] stream head, requests={requests:?}" + ); +} + +#[tokio::test] +async fn fetch_topic_detail_source_snapshot_preserves_target_anchor_and_source_cursor() { + let target_post_number = 14_u32; + let mut detail_payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + detail_payload + .as_object_mut() + .expect("detail fixture object") + .insert("posts_count".into(), json!(26)); + + let root_posts = (2_u32..=26) + .map(|post_number| { + json!({ + "id": 9000 + u64::from(post_number), + "username": format!("user-{post_number}"), + "cooked": format!("

Reply {post_number}

"), + "post_number": post_number, + "reply_to_post_number": 1, + "reply_count": 0 + }) + }) + .collect::>(); + let root_stream = root_posts + .iter() + .map(|post| { + post.get("id") + .and_then(Value::as_u64) + .expect("root post id") + }) + .collect::>(); + let target_root = root_posts + .iter() + .find(|post| { + post.get("post_number").and_then(Value::as_u64) == Some(u64::from(target_post_number)) + }) + .cloned() + .expect("target root post"); + let body_post = detail_payload + .get("post_stream") + .and_then(Value::as_object) + .and_then(|post_stream| post_stream.get("posts")) + .and_then(Value::as_array) + .and_then(|posts| posts.first()) + .cloned() + .expect("body post"); + let mut top_level_payload = detail_payload.clone(); + top_level_payload + .as_object_mut() + .expect("top-level fixture object") + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .expect("top-level post stream object") + .extend([ + ("posts".into(), Value::Array(vec![body_post])), + ("stream".into(), json!(root_stream.clone())), + ]); + + let responses = vec![ + raw_json_response(200, "application/json", &top_level_payload.to_string()), + raw_json_response( + 200, + "application/json", + &json!({ + "post_stream": { + "posts": [target_root], + "stream": [9014] + } + }) + .to_string(), + ), + raw_json_response( + 200, + "application/json", + &json!({ + "post_stream": { + "posts": root_posts.iter().take(10).cloned().collect::>(), + "stream": root_stream.iter().take(10).copied().collect::>() + } + }) + .to_string(), + ), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let snapshot = core + .fetch_topic_detail_source_snapshot(TopicDetailSourceQuery { + topic_id: 123, + target_post_number: Some(target_post_number), + allow_suggested_unread_root: false, + track_visit: true, + force_load: true, + initial_batch_size: 10, + load_more_batch_size: 10, + max_auto_batches_per_gesture: 3, + max_auto_posts_per_gesture: 120, + }) + .await + .expect("topic source snapshot"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(snapshot.focused_post_number, Some(target_post_number)); + assert!(snapshot + .loaded_posts + .iter() + .any(|post| post.post_number == target_post_number)); + let next_cursor = snapshot.source_cursor.expect("next source cursor"); + assert_eq!(next_cursor.topic_id, 123); + assert_eq!(next_cursor.next_stream_offset, 10); + assert_eq!(next_cursor.batch_size, 10); + assert_eq!(requests.len(), 3); + assert!(requests[0].contains("GET /t/123/14.json?track_visit=true&forceLoad=true HTTP/1.1")); + assert!(requests[1].contains("GET /t/123/posts.json")); + assert!(requests[1].contains("post_number=14")); + assert!(requests[1].contains("asc=true")); + assert!(requests[2].contains("GET /t/123/posts.json")); +} + +#[tokio::test] +async fn fetch_topic_detail_page_auto_extends_to_first_unread_root() { + let mut detail_payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + detail_payload + .as_object_mut() + .expect("detail fixture object") + .extend([ + ("posts_count".into(), json!(12)), + ("last_read_post_number".into(), json!(6)), + ]); + + let root_posts = (2_u32..=12) + .map(|post_number| { + json!({ + "id": 9000 + u64::from(post_number), + "username": format!("user-{post_number}"), + "cooked": format!("

Reply {post_number}

"), + "post_number": post_number, + "reply_to_post_number": 1, + "reply_count": 0 + }) + }) + .collect::>(); + let root_stream = root_posts + .iter() + .map(|post| { + post.get("id") + .and_then(Value::as_u64) + .expect("root post id") + }) + .collect::>(); + let body_post = detail_payload + .get("post_stream") + .and_then(Value::as_object) + .and_then(|post_stream| post_stream.get("posts")) + .and_then(Value::as_array) + .and_then(|posts| posts.first()) + .cloned() + .expect("body post"); + detail_payload + .as_object_mut() + .expect("detail fixture object") + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .expect("post stream object") + .extend([ + ("posts".into(), Value::Array(vec![body_post])), + ("stream".into(), json!(root_stream)), + ]); + + let responses = vec![ + raw_json_response(200, "application/json", &detail_payload.to_string()), + raw_json_response( + 200, + "application/json", + &json!({ + "post_stream": { + "posts": root_posts.iter().take(3).cloned().collect::>(), + "stream": root_posts + .iter() + .take(3) + .filter_map(|post| post.get("id").and_then(Value::as_u64)) + .collect::>() + } + }) + .to_string(), + ), + raw_json_response( + 200, + "application/json", + &json!({ + "post_stream": { + "posts": root_posts.iter().skip(3).take(3).cloned().collect::>(), + "stream": root_posts + .iter() + .skip(3) + .take(3) + .filter_map(|post| post.get("id").and_then(Value::as_u64)) + .collect::>() + } + }) + .to_string(), + ), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let page = core + .fetch_topic_detail_page(TopicDetailSourceQuery { + topic_id: 123, + target_post_number: None, + allow_suggested_unread_root: true, + track_visit: true, + force_load: true, + initial_batch_size: 3, + load_more_batch_size: 3, + max_auto_batches_per_gesture: 3, + max_auto_posts_per_gesture: 120, + }) + .await + .expect("topic detail page"); + let requests = server.shutdown_with_requests().await; + + assert_eq!( + page.tree_presentation.first_unread_root_post_number, + Some(7) + ); + assert!(page + .source_snapshot + .loaded_posts + .iter() + .any(|post| post.post_number == 7)); + assert_eq!( + page.source_snapshot + .source_cursor + .expect("next source cursor") + .next_stream_offset, + 6 + ); + assert_eq!(requests.len(), 3); + assert!(requests[0].contains("GET /t/123.json?track_visit=true&forceLoad=true HTTP/1.1")); + assert!(requests[1].contains("post_ids%5B%5D=9002")); + assert!(requests[1].contains("post_ids%5B%5D=9004")); + assert!(requests[2].contains("post_ids%5B%5D=9005")); + assert!(requests[2].contains("post_ids%5B%5D=9007")); +} + +#[tokio::test] +async fn fetch_topic_detail_page_skips_unread_root_auto_extend_when_not_allowed() { + let mut detail_payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + detail_payload + .as_object_mut() + .expect("detail fixture object") + .extend([ + ("posts_count".into(), json!(12)), + ("last_read_post_number".into(), json!(6)), + ]); + + let root_posts = (2_u32..=12) + .map(|post_number| { + json!({ + "id": 9000 + u64::from(post_number), + "username": format!("user-{post_number}"), + "cooked": format!("

Reply {post_number}

"), + "post_number": post_number, + "reply_to_post_number": 1, + "reply_count": 0 + }) + }) + .collect::>(); + let root_stream = root_posts + .iter() + .map(|post| { + post.get("id") + .and_then(Value::as_u64) + .expect("root post id") + }) + .collect::>(); + let body_post = detail_payload + .get("post_stream") + .and_then(Value::as_object) + .and_then(|post_stream| post_stream.get("posts")) + .and_then(Value::as_array) + .and_then(|posts| posts.first()) + .cloned() + .expect("body post"); + detail_payload + .as_object_mut() + .expect("detail fixture object") + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .expect("post stream object") + .extend([ + ("posts".into(), Value::Array(vec![body_post])), + ("stream".into(), json!(root_stream)), + ]); + + let responses = vec![ + raw_json_response(200, "application/json", &detail_payload.to_string()), + raw_json_response( + 200, + "application/json", + &json!({ + "post_stream": { + "posts": root_posts.iter().take(3).cloned().collect::>(), + "stream": root_posts + .iter() + .take(3) + .filter_map(|post| post.get("id").and_then(Value::as_u64)) + .collect::>() + } + }) + .to_string(), + ), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let page = core + .fetch_topic_detail_page(TopicDetailSourceQuery { + topic_id: 123, + target_post_number: None, + allow_suggested_unread_root: false, + track_visit: true, + force_load: true, + initial_batch_size: 3, + load_more_batch_size: 3, + max_auto_batches_per_gesture: 3, + max_auto_posts_per_gesture: 120, + }) + .await + .expect("topic detail page"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(page.tree_presentation.first_unread_root_post_number, None); + assert!(!page + .source_snapshot + .loaded_posts + .iter() + .any(|post| post.post_number == 7)); + assert_eq!(requests.len(), 2); + assert!(requests[0].contains("GET /t/123.json?track_visit=true&forceLoad=true HTTP/1.1")); + assert!(requests[1].contains("post_ids%5B%5D=9002")); + assert!(requests[1].contains("post_ids%5B%5D=9004")); +} + +#[tokio::test] +async fn fetch_topic_ai_summary_parses_payload_and_query_params() { + let body = r#"{ + "ai_topic_summary": { + "summarized_text": "Fire summary", + "algorithm": "linuxdo-ai", + "outdated": "true", + "can_regenerate": false, + "new_posts_since_summary": "3", + "updated_at": "2026-03-26T00:00:00Z" + } +}"#; + let responses = vec![raw_json_response(200, "application/json", body)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let summary = core + .fetch_topic_ai_summary(123, true) + .await + .expect("topic ai summary") + .expect("summary payload"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(summary.summarized_text, "Fire summary"); + assert_eq!(summary.algorithm.as_deref(), Some("linuxdo-ai")); + assert!(summary.outdated); + assert!(!summary.can_regenerate); + assert_eq!(summary.new_posts_since_summary, 3); + assert_eq!(summary.updated_at.as_deref(), Some("2026-03-26T00:00:00Z")); + assert_eq!(requests.len(), 1); + assert!( + requests[0].contains("GET /discourse-ai/summarization/t/123?skip_age_check=true HTTP/1.1") + ); +} + +#[tokio::test] +async fn fetch_topic_ai_summary_returns_none_for_unavailable_statuses() { + for status in [403, 404] { + let responses = vec![raw_json_response( + status, + "application/json", + r#"{"errors":["no summary"]}"#, + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let summary = core + .fetch_topic_ai_summary(123, false) + .await + .expect("topic ai summary"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(summary, None); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("GET /discourse-ai/summarization/t/123 HTTP/1.1")); + } +} + +#[tokio::test] +async fn fetch_topic_ai_summary_surfaces_cloudflare_challenge() { + let responses = vec![raw_cloudflare_challenge_response( + 403, + "Just a moment", + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let error = core + .fetch_topic_ai_summary(123, false) + .await + .expect_err("cloudflare challenge"); + let _ = server.shutdown().await; + + assert!(matches!( + error, + FireCoreError::CloudflareChallenge { + operation: "fetch topic ai summary", + .. + } + )); +} + +#[tokio::test] +async fn fetch_private_message_detail_parses_detail_participants() { + let mut payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + let object = payload.as_object_mut().expect("detail fixture object"); + object.insert("archetype".into(), json!("private_message")); + object + .get_mut("details") + .and_then(Value::as_object_mut) + .expect("detail metadata") + .insert( + "participants".into(), + json!([ + { + "id": 1, + "username": "alice", + "name": "Alice", + "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" + }, + { + "id": 2, + "username": "bob", + "name": "Bob", + "avatar_template": "/user_avatar/linux.do/bob/{size}/1_2.png" + } + ]), + ); + + let responses = vec![raw_json_response( + 200, + "application/json", + &payload.to_string(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let detail = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: false, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let _ = server.shutdown().await; + + assert_eq!(detail.archetype.as_deref(), Some("private_message")); + assert_eq!(detail.details.participants.len(), 2); + assert_eq!( + detail.details.participants[1].username.as_deref(), + Some("bob") + ); + assert_eq!(detail.details.participants[1].name.as_deref(), Some("Bob")); +} + +#[tokio::test] +async fn fetch_topic_detail_hydrates_missing_posts_from_stream() { + let mut detail_payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + let object = detail_payload + .as_object_mut() + .expect("detail fixture object"); + object.insert("posts_count".into(), json!(3)); + object + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .expect("post stream object") + .insert("stream".into(), json!([9001, 9002, 9003])); + + let extra_posts_payload = json!({ + "post_stream": { + "posts": [ + { + "id": 9003, + "username": "carol", + "cooked": "

Nested reply

", + "post_number": 3, + "reply_to_post_number": 2 + }, + { + "id": 9002, + "username": "bob", + "cooked": "

First reply

", + "post_number": 2, + "reply_to_post_number": 1 + } + ], + "stream": [9002, 9003] + } + }) + .to_string(); + + let responses = vec![ + raw_json_response(200, "application/json", &detail_payload.to_string()), + raw_json_response(200, "application/json", &extra_posts_payload), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let detail = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: false, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(detail.post_stream.stream, vec![9001, 9002, 9003]); + assert_eq!( + detail + .post_stream + .posts + .iter() + .map(|post| post.post_number) + .collect::>(), + vec![1, 2, 3] + ); + assert_eq!( + detail + .flat_posts + .iter() + .map(|post| post.post.post_number) + .collect::>(), + vec![1, 2, 3] + ); + assert_eq!(detail.flat_posts[1].depth, 0); + assert_eq!(detail.flat_posts[2].depth, 1); + assert_eq!(detail.flat_posts[2].parent_post_number, Some(2)); + assert_eq!(requests.len(), 2); + assert!(requests[0].contains("GET /t/123.json HTTP/1.1")); + assert!(requests[1] + .contains("GET /t/123/posts.json?post_ids%5B%5D=9002&post_ids%5B%5D=9003&include_suggested=false HTTP/1.1")); +} + +#[tokio::test] +async fn fetch_topic_detail_initial_keeps_partial_post_stream() { + let mut detail_payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + detail_payload + .as_object_mut() + .expect("detail fixture object") + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .expect("post stream object") + .insert("stream".into(), json!([9001, 9002, 9003])); + + let responses = vec![raw_json_response( + 200, + "application/json", + &detail_payload.to_string(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let detail = core + .fetch_topic_detail_initial(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: false, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(detail.post_stream.posts.len(), 1); + assert_eq!(detail.post_stream.stream, vec![9001, 9002, 9003]); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("GET /t/123.json HTTP/1.1")); +} + +#[tokio::test] +async fn fetch_topic_posts_parses_batch_response() { + let payload = json!({ + "post_stream": { + "posts": [ + { + "id": 9003, + "username": "carol", + "cooked": "

Nested reply

", + "post_number": 3, + "reply_to_post_number": 2 + }, + { + "id": 9002, + "username": "bob", + "cooked": "

First reply

", + "post_number": 2, + "reply_to_post_number": 1 + } + ], + "stream": [9002, 9003] + } + }) + .to_string(); + + let responses = vec![raw_json_response(200, "application/json", &payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let posts = core + .fetch_topic_posts(123, vec![9002, 9003]) + .await + .expect("posts"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(posts.len(), 2); + assert_eq!(posts[0].id, 9003); + assert_eq!(posts[1].reply_to_post_number, Some(1)); + assert_eq!(requests.len(), 1); + assert!(requests[0] + .contains("GET /t/123/posts.json?post_ids%5B%5D=9002&post_ids%5B%5D=9003&include_suggested=false HTTP/1.1")); +} + +#[tokio::test] +async fn fetch_topic_posts_reuses_active_topic_response_session_cache() { + let mut top_level_payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + let body_post = top_level_payload + .as_object() + .expect("detail fixture object") + .get("post_stream") + .and_then(Value::as_object) + .and_then(|post_stream| post_stream.get("posts")) + .and_then(Value::as_array) + .and_then(|posts| posts.first()) + .cloned() + .expect("body post"); + top_level_payload + .as_object_mut() + .expect("detail fixture object") + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .expect("post stream object") + .extend([ + ("stream".into(), json!([9002])), + ( + "posts".into(), + json!([ + body_post, + { + "id": 9002, + "username": "bob", + "cooked": "

First reply

", + "post_number": 2, + "reply_to_post_number": 1, + "reply_count": 0 + } + ]), + ), + ]); + let post_payload = json!({ + "post_stream": { + "posts": [ + { + "id": 9003, + "username": "carol", + "cooked": "

Nested reply

", + "post_number": 3, + "reply_to_post_number": 2 + } + ], + "stream": [9003] + } + }) + .to_string(); + let responses = vec![ + raw_json_response(200, "application/json", &top_level_payload.to_string()), + raw_json_response(200, "application/json", &post_payload), + ]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _snapshot = core + .fetch_topic_detail_source_snapshot(TopicDetailSourceQuery { + topic_id: 123, + target_post_number: None, + allow_suggested_unread_root: false, + track_visit: true, + force_load: true, + initial_batch_size: 1, + load_more_batch_size: 40, + max_auto_batches_per_gesture: 3, + max_auto_posts_per_gesture: 120, + }) + .await + .expect("topic source snapshot"); + let posts = core + .fetch_topic_posts(123, vec![9002, 9003]) + .await + .expect("posts"); + let cached_posts = core + .fetch_topic_posts(123, vec![9002, 9003]) + .await + .expect("cached posts"); + let requests = server.shutdown_with_requests().await; + + assert_eq!( + posts.iter().map(|post| post.id).collect::>(), + vec![9002, 9003] + ); + assert_eq!( + cached_posts.iter().map(|post| post.id).collect::>(), + vec![9002, 9003] + ); + assert_eq!(requests.len(), 2); + assert!(requests[1] + .contains("GET /t/123/posts.json?post_ids%5B%5D=9003&include_suggested=false HTTP/1.1")); + assert!(!requests[1].contains("post_ids%5B%5D=9002")); +} + +#[tokio::test] +async fn fetch_topic_detail_tolerates_object_bookmarks_and_accepted_answer_metadata() { + let mut payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + let object = payload.as_object_mut().expect("detail fixture object"); + object.insert( + "bookmarks".into(), + json!([ + { + "id": 1240, + "bookmarkable_type": "Topic", + "bookmarkable_id": 123 + }, + { + "id": 1241, + "bookmarkable_type": "Post", + "bookmarkable_id": 9001 + } + ]), + ); + object.insert( + "accepted_answer".into(), + json!({ + "post_number": 5, + "username": "alice" + }), + ); + object.insert("has_accepted_answer".into(), json!(true)); + let payload = payload.to_string(); + + let responses = vec![raw_json_response(200, "application/json", &payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let detail = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: true, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let _ = server.shutdown().await; + + assert_eq!(detail.bookmarks, vec![1240, 1241]); + assert!(detail.bookmarked); + assert_eq!(detail.bookmark_id, Some(1240)); + assert!(detail.post_stream.posts[0].bookmarked); + assert_eq!(detail.post_stream.posts[0].bookmark_id, Some(1241)); + assert!(detail.accepted_answer); + assert!(detail.has_accepted_answer); +} + +#[tokio::test] +async fn fetch_badge_detail_parses_badge_envelope() { + let payload = r#"{ + "badge": { + "id": 7, + "name": "Great Reply", + "description": "

Short

", + "badge_type_id": 1, + "grant_count": 12, + "long_description": "

Long

", + "slug": "great-reply" + } + }"#; + let responses = vec![raw_json_response(200, "application/json", payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let badge = core.fetch_badge_detail(7).await.expect("badge detail"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(badge.id, 7); + assert_eq!(badge.name, "Great Reply"); + assert_eq!(badge.grant_count, 12); + assert_eq!(badge.long_description.as_deref(), Some("

Long

")); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("GET /badges/7.json HTTP/1.1")); +} + +#[tokio::test] +async fn fetch_topic_detail_tolerates_null_scalars_and_null_details() { + let mut payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail fixture json"); + let object = payload.as_object_mut().expect("detail fixture object"); + object.insert("title".into(), Value::Null); + object.insert("category_id".into(), json!("2")); + object.insert("details".into(), Value::Null); + + let post = object + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .and_then(|stream| stream.get_mut("posts")) + .and_then(Value::as_array_mut) + .and_then(|posts| posts.first_mut()) + .and_then(Value::as_object_mut) + .expect("first post"); + post.insert("username".into(), Value::Null); + post.insert("cooked".into(), Value::Null); + post.insert("post_type".into(), json!("1")); + post.insert("like_count".into(), Value::Null); + post.insert("reply_count".into(), Value::Null); + post.insert("reply_to_post_number".into(), json!("12")); + post.insert("bookmarked".into(), Value::Null); + post.insert("accepted_answer".into(), Value::Null); + post.insert("can_edit".into(), Value::Null); + post.insert("can_delete".into(), Value::Null); + post.insert("can_recover".into(), Value::Null); + post.insert("hidden".into(), Value::Null); + post.insert("reactions".into(), Value::Null); + + let payload = payload.to_string(); + + let responses = vec![raw_json_response(200, "application/json", &payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let detail = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: true, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let _ = server.shutdown().await; + + assert_eq!(detail.title, ""); + assert_eq!(detail.category_id, Some(2)); + assert_eq!(detail.details.notification_level, None); + assert_eq!(detail.details.created_by, None); + assert!(!detail.details.can_edit); + assert_eq!(detail.post_stream.posts[0].username, ""); + assert_eq!(detail.post_stream.posts[0].cooked, ""); + assert_eq!(detail.post_stream.posts[0].reply_to_post_number, Some(12)); + assert_eq!(detail.post_stream.posts[0].reactions.len(), 0); + assert_eq!(detail.post_stream.posts[0].like_count, 0); + assert_eq!(detail.post_stream.posts[0].reply_count, 0); +} + +#[tokio::test] +async fn fetch_topic_detail_tolerates_malformed_optional_nested_records() { + let mut payload: Value = + serde_json::from_str(&sample_topic_detail_json()).expect("detail payload json"); + let object = payload.as_object_mut().expect("detail fixture object"); + object.insert( + "details".into(), + json!({ + "notification_level": "1", + "can_edit": "1", + "created_by": "unexpected" + }), + ); + + let post = object + .get_mut("post_stream") + .and_then(Value::as_object_mut) + .and_then(|stream| stream.get_mut("posts")) + .and_then(Value::as_array_mut) + .and_then(|posts| posts.first_mut()) + .and_then(Value::as_object_mut) + .expect("first post"); + post.insert( + "current_user_reaction".into(), + Value::String("unexpected".into()), + ); + + let responses = vec![raw_json_response( + 200, + "application/json", + &payload.to_string(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let detail = core + .fetch_topic_detail(TopicDetailQuery { + topic_id: 123, + post_number: None, + track_visit: true, + force_load: false, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }) + .await + .expect("detail"); + let _ = server.shutdown().await; + + assert_eq!(detail.details.notification_level, Some(1)); + assert!(detail.details.can_edit); + assert_eq!(detail.details.created_by, None); + assert_eq!(detail.post_stream.posts[0].current_user_reaction, None); +} diff --git a/crates/fire-core/tests/network/topic_list.rs b/crates/fire-core/tests/network/topic_list.rs new file mode 100644 index 00000000..b8a0161e --- /dev/null +++ b/crates/fire-core/tests/network/topic_list.rs @@ -0,0 +1,504 @@ +use super::*; + +#[tokio::test] +async fn fetch_topic_list_parses_latest_payload() { + let responses = vec![raw_json_response( + 200, + "application/json", + &sample_latest_json(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("topic list"); + let _ = server.shutdown().await; + + assert_eq!(response.topics.len(), 1); + assert_eq!(response.topics[0].id, 123); + assert_eq!(response.topics[0].title, "Fire topic"); + assert_eq!( + response.topics[0].tags, + vec![ + TopicTag { + id: None, + name: "rust".into(), + slug: None, + }, + TopicTag { + id: None, + name: "linuxdo".into(), + slug: None, + }, + ] + ); + assert_eq!(response.users[0].username, "alice"); + assert_eq!(response.more_topics_url.as_deref(), Some("/latest?page=1")); + assert_eq!(response.next_page, Some(1)); + assert_eq!(response.rows.len(), 1); + assert_eq!(response.rows[0].topic.id, 123); + assert_eq!( + response.rows[0].excerpt_text.as_deref(), + Some("topic excerpt") + ); + assert_eq!( + response.rows[0].original_poster_username.as_deref(), + Some("alice") + ); + assert_eq!( + response.rows[0].original_poster_avatar_template.as_deref(), + Some("/user_avatar/linux.do/alice/{size}/1_2.png") + ); + assert_eq!(response.rows[0].tag_names, vec!["rust", "linuxdo"]); + assert_eq!( + response.rows[0].status_labels, + vec!["Unread 2".to_string(), "New 1".to_string()] + ); + assert!(!response.rows[0].is_pinned); + assert!(!response.rows[0].is_closed); + assert!(!response.rows[0].is_archived); + assert!(!response.rows[0].has_accepted_answer); + assert!(response.rows[0].has_unread_posts); + assert_eq!( + response.rows[0].created_timestamp_unix_ms, + Some(1_774_656_000_000) + ); + assert_eq!( + response.rows[0].activity_timestamp_unix_ms, + Some(1_774_659_600_000) + ); + assert_eq!( + response.rows[0].last_poster_username.as_deref(), + Some("alice") + ); + assert!(!response.is_cached); +} + +#[tokio::test] +async fn fetch_topic_list_returns_cached_page_on_network_error() { + let responses = vec![raw_json_response( + 200, + "application/json", + &sample_latest_json(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let live = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("live topic list"); + assert!(!live.is_cached); + + let cached = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("cached topic list"); + let _ = server.shutdown().await; + + assert!(cached.is_cached); + assert_eq!(cached.rows.len(), 1); + assert_eq!(cached.rows[0].topic.id, live.rows[0].topic.id); +} + +#[tokio::test] +async fn fetch_topic_list_category_scope_sends_primary_and_additional_tags() { + let responses = vec![raw_json_response( + 200, + "application/json", + &sample_latest_json(), + )]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + page: Some(2), + category_slug: Some("rust".into()), + category_id: Some(2), + parent_category_slug: Some("dev".into()), + tag: Some("swift".into()), + additional_tags: vec!["ios".into()], + match_all_tags: true, + ..TopicListQuery::default() + }) + .await + .expect("topic list"); + let requests = server.shutdown_with_requests().await; + + assert!(requests[0].contains( + "GET /c/dev/rust/2/l/latest.json?no_definitions=true&page=2&tags%5B%5D=swift&tags%5B%5D=ios&match_all_tags=true HTTP/1.1" + )); +} + +#[tokio::test] +async fn fetch_private_message_mailboxes_use_username_routes_and_parse_participants() { + let payload = r#"{ + "topic_list": { + "topics": [ + { + "id": 456, + "title": "Fire private message", + "slug": "fire-private-message", + "posts_count": 3, + "reply_count": 2, + "views": 12, + "like_count": 1, + "excerpt": "hello from bob", + "created_at": "2026-04-11T00:00:00Z", + "last_posted_at": "2026-04-11T00:05:00Z", + "last_poster_username": "bob", + "pinned": false, + "visible": true, + "closed": false, + "archived": false, + "tags": [], + "posters": [], + "participants": [ + { + "id": 1, + "username": "alice", + "name": "Alice", + "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" + }, + { + "id": 2, + "username": "bob", + "name": "Bob", + "avatar_template": "/user_avatar/linux.do/bob/{size}/1_2.png" + } + ], + "unseen": false, + "unread_posts": 1, + "new_posts": 0, + "highest_post_number": 3 + } + ], + "more_topics_url": "/topics/private-messages/alice?page=2" + }, + "users": [ + { + "id": 2, + "username": "bob", + "avatar_template": "/user_avatar/linux.do/bob/{size}/1_2.png" + } + ] +}"#; + let server = TestServer::spawn(vec![ + raw_json_response(200, "application/json", payload), + raw_json_response(200, "application/json", payload), + ]) + .await + .expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let _ = core.sync_login_context(LoginSyncInput { + username: Some("alice".into()), + home_html: Some(sample_home_html()), + csrf_token: Some("csrf-token".into()), + current_url: Some(server.base_url()), + browser_user_agent: None, + cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ], + }); + + let inbox = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::PrivateMessagesInbox, + page: Some(2), + ..TopicListQuery::default() + }) + .await + .expect("pm inbox"); + let sent = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::PrivateMessagesSent, + page: Some(3), + ..TopicListQuery::default() + }) + .await + .expect("pm sent"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(inbox.topics.len(), 1); + assert_eq!(inbox.topics[0].participants.len(), 2); + assert_eq!( + inbox.topics[0].participants[0].username.as_deref(), + Some("alice") + ); + assert_eq!(inbox.topics[0].participants[1].name.as_deref(), Some("Bob")); + assert_eq!( + inbox.rows[0].topic.participants[1] + .avatar_template + .as_deref(), + Some("/user_avatar/linux.do/bob/{size}/1_2.png") + ); + assert_eq!(inbox.next_page, Some(2)); + assert_eq!(sent.topics[0].id, 456); + assert_eq!(requests.len(), 2); + assert!(requests[0] + .contains("GET /topics/private-messages/alice.json?no_definitions=true&page=2 HTTP/1.1")); + assert!(requests[1].contains( + "GET /topics/private-messages-sent/alice.json?no_definitions=true&page=3 HTTP/1.1" + )); +} + +#[tokio::test] +async fn fetch_topic_list_tolerates_object_poster_metadata_fields() { + let payload = sample_latest_json() + .replace( + r#""description": "Original Poster""#, + r#""description": {"localized": "Original Poster"}"#, + ) + .replace(r#""extras": "latest""#, r#""extras": {"role": "latest"}"#); + let responses = vec![raw_json_response(200, "application/json", &payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("topic list"); + let _ = server.shutdown().await; + + assert_eq!(response.topics.len(), 1); + assert_eq!(response.topics[0].posters.len(), 1); + assert_eq!(response.topics[0].posters[0].description, None); + assert_eq!(response.topics[0].posters[0].extras, None); +} + +#[tokio::test] +async fn fetch_topic_list_tolerates_object_tags_and_null_counters() { + let payload = sample_latest_json() + .replace( + r#""tags": ["rust", "linuxdo"]"#, + r#""tags": [{"id": 1451, "name": "Rust", "slug": "rust"}, {"id": 99, "name": "LinuxDo", "slug": "linuxdo"}]"#, + ) + .replace(r#""unread_posts": 2"#, r#""unread_posts": null"#) + .replace(r#""new_posts": 1"#, r#""new_posts": null"#) + .replace(r#""can_have_answer": true"#, r#""can_have_answer": null"#); + let responses = vec![raw_json_response(200, "application/json", &payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("topic list"); + let _ = server.shutdown().await; + + assert_eq!(response.topics.len(), 1); + assert_eq!( + response.topics[0].tags, + vec![ + TopicTag { + id: Some(1451), + name: "Rust".into(), + slug: Some("rust".into()), + }, + TopicTag { + id: Some(99), + name: "LinuxDo".into(), + slug: Some("linuxdo".into()), + }, + ] + ); + assert_eq!(response.topics[0].unread_posts, 0); + assert_eq!(response.topics[0].new_posts, 0); + assert!(!response.topics[0].can_have_answer); + assert_eq!(response.rows[0].tag_names, vec!["Rust", "LinuxDo"]); +} + +#[tokio::test] +async fn fetch_topic_list_builds_plain_text_excerpt_for_rows() { + let payload = sample_latest_json().replace( + r#""excerpt": "topic excerpt""#, + r#""excerpt": "

Hello Fire

""#, + ); + let responses = vec![raw_json_response(200, "application/json", &payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let response = core + .fetch_topic_list(TopicListQuery { + kind: TopicListKind::Latest, + ..TopicListQuery::default() + }) + .await + .expect("topic list"); + let _ = server.shutdown().await; + + assert_eq!(response.rows[0].excerpt_text.as_deref(), Some("Hello Fire")); +} + +#[tokio::test] +async fn fetch_bookmarks_parses_bookmark_metadata_fields() { + let payload = sample_latest_json() + .replace( + r#""highest_post_number": 12,"#, + r#""highest_post_number": 12, "_bookmarked_post_number": 7, "_bookmark_id": 901, "_bookmark_name": "稍后细读", "_bookmark_reminder_at": "2026-03-29T09:00:00Z", "_bookmarkable_type": "Post","#, + ); + let responses = vec![raw_json_response(200, "application/json", &payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let response = core + .fetch_bookmarks("alice", Some(2)) + .await + .expect("bookmarks"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.topics.len(), 1); + assert_eq!(response.topics[0].bookmarked_post_number, Some(7)); + assert_eq!(response.topics[0].bookmark_id, Some(901)); + assert_eq!( + response.topics[0].bookmark_name.as_deref(), + Some("稍后细读") + ); + assert_eq!( + response.topics[0].bookmark_reminder_at.as_deref(), + Some("2026-03-29T09:00:00Z") + ); + assert_eq!( + response.topics[0].bookmarkable_type.as_deref(), + Some("Post") + ); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("GET /u/alice/bookmarks.json?page=2 HTTP/1.1")); +} + +#[tokio::test] +async fn fetch_bookmarks_parses_user_bookmark_list_payload() { + let payload = r#"{ + "user_bookmark_list": { + "more_bookmarks_url": "/u/alice/bookmarks.json?page=2", + "bookmarks": [ + { + "id": 901, + "name": "稍后细读", + "reminder_at": "2026-03-29T09:00:00Z", + "bookmarkable_type": "Post", + "bookmarkable_id": 7007, + "topic_id": 1001, + "linked_post_number": 7, + "title": "真实书签响应", + "slug": "real-bookmark", + "excerpt": "

Hello Fire

", + "created_at": "2026-03-28T00:00:00Z", + "bumped_at": "2026-03-28T01:00:00Z", + "category_id": 42, + "highest_post_number": 12, + "views": 88, + "user": { + "id": 12, + "username": "alice", + "avatar_template": "/user_avatar/linux.do/alice/{size}/1_2.png" + } + } + ] + } +}"#; + let responses = vec![raw_json_response(200, "application/json", payload)]; + let server = TestServer::spawn(responses).await.expect("server"); + let core = FireCore::new(FireCoreConfig { + base_url: server.base_url(), + workspace_path: None, + }) + .expect("core"); + + let response = core + .fetch_bookmarks("alice", None) + .await + .expect("bookmarks"); + let requests = server.shutdown_with_requests().await; + + assert_eq!(response.topics.len(), 1); + assert_eq!(response.rows.len(), 1); + assert_eq!(response.next_page, Some(2)); + assert_eq!(response.topics[0].id, 1001); + assert_eq!(response.topics[0].title, "真实书签响应"); + assert_eq!(response.topics[0].reply_count, 11); + assert_eq!(response.topics[0].bookmarked_post_number, Some(7)); + assert_eq!(response.topics[0].bookmark_id, Some(901)); + assert_eq!( + response.topics[0].bookmark_name.as_deref(), + Some("稍后细读") + ); + assert_eq!( + response.topics[0].bookmark_reminder_at.as_deref(), + Some("2026-03-29T09:00:00Z") + ); + assert_eq!(response.rows[0].excerpt_text.as_deref(), Some("Hello Fire")); + assert_eq!( + response.rows[0].original_poster_username.as_deref(), + Some("alice") + ); + assert_eq!(requests.len(), 1); + assert!(requests[0].contains("GET /u/alice/bookmarks.json HTTP/1.1")); +} diff --git a/crates/fire-models/src/chat.rs b/crates/fire-models/src/chat.rs deleted file mode 100644 index b19be7a8..00000000 --- a/crates/fire-models/src/chat.rs +++ /dev/null @@ -1,584 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use crate::rich_text::AttachedPresentation; - -/// Discourse Chat 用户摘要(频道成员 / 消息作者)。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatUser { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -/// 当前用户在频道上的成员关系。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatChannelMembership { - pub following: bool, - pub muted: bool, - pub starred: bool, - pub notification_level: Option, - pub last_read_message_id: Option, - pub last_viewed_at: Option, -} - -/// 频道 MessageBus 订阅起始位点(`meta.message_bus_last_ids`)。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatChannelBusLastIds { - pub channel_message_bus_last_id: Option, - pub new_messages: Option, - pub new_mentions: Option, - pub kick: Option, -} - -/// 单频道未读 tracking。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatChannelTracking { - pub unread_count: u32, - pub mention_count: u32, -} - -/// Chat 频道(公共 Category 频道或 DirectMessage)。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatChannel { - pub id: u64, - pub title: Option, - pub unicode_title: Option, - pub slug: Option, - pub description: Option, - /// `DirectMessage` 或 `Category` - pub chatable_type: String, - pub status: Option, - pub threading_enabled: bool, - pub memberships_count: Option, - pub is_group_dm: bool, - pub dm_users: Vec, - pub category_color: Option, - pub category_name: Option, - pub emoji: Option, - pub current_user_membership: Option, - pub last_message: Option, - pub bus_last_ids: ChatChannelBusLastIds, - pub can_moderate: bool, - pub can_manage_pins: bool, - pub can_delete_self: bool, - pub can_delete_others: bool, - pub can_remove_members: bool, - pub can_flag: bool, -} - -impl ChatChannel { - pub fn is_direct_message(&self) -> bool { - self.chatable_type.eq_ignore_ascii_case("DirectMessage") - } - - pub fn is_public_channel(&self) -> bool { - self.chatable_type.eq_ignore_ascii_case("Category") - } - - pub fn display_title(&self) -> String { - let title = self - .unicode_title - .as_ref() - .or(self.title.as_ref()) - .cloned() - .filter(|value| !value.trim().is_empty()) - .unwrap_or_else(|| format!("#{}", self.id)); - let Some(emoji) = self.formatted_emoji() else { - return title; - }; - if title.contains(&emoji) || title.contains(&format!(":{}:", emoji.trim_matches(':'))) { - return title; - } - format!("{emoji} {title}") - } - - /// Leading glyph for public-channel inbox rows (unicode or `:shortcode:`). - pub fn formatted_emoji(&self) -> Option { - let raw = self.emoji.as_deref()?.trim(); - if raw.is_empty() { - return None; - } - let name = raw.trim_matches(':'); - if name - .chars() - .any(|ch| !ch.is_ascii_alphanumeric() && ch != '_') - { - return Some(name.to_string()); - } - Some( - emoji_shortcode_to_unicode(name) - .map(str::to_string) - .unwrap_or_else(|| format!(":{name}:")), - ) - } - - pub fn last_activity_at(&self) -> Option<&str> { - self.last_message - .as_ref() - .and_then(|message| message.created_at.as_deref()) - } -} - -fn emoji_shortcode_to_unicode(name: &str) -> Option<&'static str> { - Some(match name { - "smile" | "slightly_smiling_face" => "🙂", - "grinning" | "grin" => "😀", - "joy" => "😂", - "heart" | "red_heart" => "❤️", - "fire" => "🔥", - "tada" => "🎉", - "rocket" => "🚀", - "star" => "⭐", - "warning" => "⚠️", - "speech_balloon" | "speech_left" => "💬", - "loudspeaker" | "mega" => "📢", - "bell" => "🔔", - "bulb" => "💡", - "computer" | "desktop_computer" => "💻", - "earth_asia" | "globe_with_meridians" => "🌏", - "link" => "🔗", - "memo" | "pencil" => "📝", - "books" => "📚", - "gear" => "⚙️", - "hammer_and_wrench" | "hammer" => "🛠️", - "bug" => "🐛", - "tv" => "📺", - "game_die" | "video_game" => "🎮", - "coffee" => "☕", - "seedling" => "🌱", - "pushpin" => "📌", - "eyes" => "👀", - "wave" => "👋", - "thumbsup" | "+1" => "👍", - "clap" => "👏", - "100" => "💯", - _ => return None, - }) -} - -/// GET `/chat/api/me/channels` 响应。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct MyChatChannelsResponse { - pub public_channels: Vec, - pub direct_message_channels: Vec, - /// channel_id → tracking - pub channel_tracking: Vec, - /// 全局 MessageBus 通道起始位点(key/value 扁平列表) - pub global_bus_last_ids: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatChannelTrackingEntry { - pub channel_id: u64, - pub unread_count: u32, - pub mention_count: u32, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatBusLastIdEntry { - pub channel: String, - pub last_id: i64, -} - -impl MyChatChannelsResponse { - /// 底栏徽章口径(对齐官方 web / fluxdo): - /// - DM:unread + mention - /// - 公共频道:仅 mention - /// - muted 不计 - pub fn total_unread_badge(&self) -> u32 { - let tracking_for = |channel_id: u64| -> (u32, u32) { - self.channel_tracking - .iter() - .find(|entry| entry.channel_id == channel_id) - .map(|entry| (entry.unread_count, entry.mention_count)) - .unwrap_or((0, 0)) - }; - - let mut sum = 0u32; - for channel in &self.direct_message_channels { - if channel - .current_user_membership - .as_ref() - .is_some_and(|m| m.muted) - { - continue; - } - let (unread, mention) = tracking_for(channel.id); - sum = sum.saturating_add(unread).saturating_add(mention); - } - for channel in &self.public_channels { - if channel - .current_user_membership - .as_ref() - .is_some_and(|m| m.muted) - { - continue; - } - let (_, mention) = tracking_for(channel.id); - sum = sum.saturating_add(mention); - } - sum - } - - /// WeChat-style inbox: DMs and public channels sorted by last activity. - pub fn inbox_channels(&self) -> Vec<&ChatChannel> { - let mut channels: Vec<&ChatChannel> = self - .direct_message_channels - .iter() - .chain(self.public_channels.iter()) - .collect(); - channels.sort_by(|left, right| { - right - .last_activity_at() - .unwrap_or("") - .cmp(left.last_activity_at().unwrap_or("")) - .then_with(|| right.id.cmp(&left.id)) - }); - channels - } -} - -/// Chat 消息附件。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatUpload { - pub id: u64, - pub url: Option, - pub short_url: Option, - pub original_filename: Option, - pub extension: Option, - pub width: Option, - pub height: Option, - pub thumbnail_width: Option, - pub thumbnail_height: Option, - pub dominant_color: Option, -} - -/// 消息表情回应聚合。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatMessageReaction { - pub emoji: String, - pub count: u32, - pub reacted: bool, - pub users: Vec, -} - -/// 被回复消息摘要。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatMessageReplyRef { - pub id: u64, - pub excerpt: Option, - pub user: Option, -} - -/// 消息串摘要。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatThreadRef { - pub id: u64, - pub title: Option, - pub reply_count: u32, - pub last_reply_created_at: Option, - pub last_reply_excerpt: Option, - pub last_reply_user: Option, - pub participants: Vec, -} - -/// 消息收藏。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatMessageBookmark { - pub id: u64, - pub name: Option, - pub reminder_at: Option, -} - -/// Chat 消息。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatMessage { - pub id: u64, - pub channel_id: u64, - pub message: String, - pub cooked: String, - pub excerpt: Option, - pub created_at: Option, - pub deleted_at: Option, - pub deleted_by_id: Option, - pub edited: bool, - pub thread_id: Option, - pub thread: Option, - pub user: Option, - pub mentioned_users: Vec, - pub reactions: Vec, - pub uploads: Vec, - pub in_reply_to: Option, - pub streaming: bool, - pub available_flags: Vec, - pub user_flag_status: Option, - pub bookmark: Option, - pub pinned: bool, - #[serde(default)] - pub presented: AttachedPresentation, -} - -impl ChatMessage { - pub fn reuse_presentation_from(&mut self, previous: &Self) { - if self.cooked == previous.cooked { - if let Some(presented) = previous.presented.arc() { - self.presented = AttachedPresentation::some(presented); - } - } - } - - pub fn is_deleted(&self) -> bool { - self.deleted_at.is_some() - } - - pub fn preview_text(&self) -> String { - if let Some(excerpt) = self - .excerpt - .as_ref() - .map(|value| value.trim()) - .filter(|value| !value.is_empty()) - { - return excerpt.to_string(); - } - let plain = self.message.trim(); - if !plain.is_empty() { - return plain.to_string(); - } - if !self.uploads.is_empty() { - return "[附件]".to_string(); - } - String::new() - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ChatReactionAction { - Add, - Remove, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ChatBusEvent { - MessageUpsert { - message: Box, - }, - MessageDeleted { - id: u64, - }, - Reaction { - message_id: u64, - emoji: String, - action: ChatReactionAction, - actor_id: Option, - }, - Tracking { - channel_id: u64, - unread: u32, - mention: u32, - thread_id: Option, - }, - ChannelUpsert { - channel: Box, - }, - NewMessages { - channel_id: u64, - is_channel_level: bool, - message: Option>, - actor_id: Option, - }, - Ignored, -} - -/// GET `/chat/api/channels/:id/messages` 响应。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatMessagesResponse { - pub messages: Vec, - pub can_load_more_past: bool, - pub can_load_more_future: bool, - pub target_message_id: Option, -} - -/// 消息列表查询。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatMessagesQuery { - pub channel_id: u64, - pub direction: Option, - pub target_message_id: Option, - pub fetch_from_last_read: bool, - pub page_size: Option, -} - -/// 创建/复用 DM 频道。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct CreateDirectMessageChannelRequest { - pub target_usernames: Vec, - pub name: Option, - pub upsert: bool, -} - -/// 发送消息。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SendChatMessageRequest { - pub channel_id: u64, - pub message: String, - pub staged_id: Option, - pub in_reply_to_id: Option, - pub thread_id: Option, - pub upload_ids: Vec, -} - -/// 发送消息结果。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SendChatMessageResult { - pub message_id: Option, -} - -/// 频道成员。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatChannelMember { - pub user: ChatUser, - pub following: bool, - pub muted: bool, -} - -/// 浏览公共频道查询。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct BrowseChatChannelsQuery { - pub filter: Option, - pub offset: Option, - pub limit: Option, -} - -/// 搜索聊天消息。 -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatSearchQuery { - pub query: String, - pub channel_id: Option, - pub offset: Option, - pub limit: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ChatSearchResult { - pub messages: Vec, - pub has_more: bool, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn total_unread_badge_matches_official_rules() { - let response = MyChatChannelsResponse { - public_channels: vec![ChatChannel { - id: 1, - chatable_type: "Category".into(), - current_user_membership: Some(ChatChannelMembership { - muted: false, - ..Default::default() - }), - ..Default::default() - }], - direct_message_channels: vec![ - ChatChannel { - id: 2, - chatable_type: "DirectMessage".into(), - current_user_membership: Some(ChatChannelMembership { - muted: false, - ..Default::default() - }), - ..Default::default() - }, - ChatChannel { - id: 3, - chatable_type: "DirectMessage".into(), - current_user_membership: Some(ChatChannelMembership { - muted: true, - ..Default::default() - }), - ..Default::default() - }, - ], - channel_tracking: vec![ - ChatChannelTrackingEntry { - channel_id: 1, - unread_count: 9, - mention_count: 2, - }, - ChatChannelTrackingEntry { - channel_id: 2, - unread_count: 3, - mention_count: 1, - }, - ChatChannelTrackingEntry { - channel_id: 3, - unread_count: 100, - mention_count: 50, - }, - ], - global_bus_last_ids: Vec::new(), - }; - - // public: only mention (2); dm2: 3+1; muted dm3: 0 → 6 - assert_eq!(response.total_unread_badge(), 6); - } - - #[test] - fn display_title_prefixes_channel_emoji() { - let channel = ChatChannel { - id: 8, - title: Some("公告".into()), - emoji: Some("loudspeaker".into()), - chatable_type: "Category".into(), - ..Default::default() - }; - assert_eq!(channel.display_title(), "📢 公告"); - assert_eq!(channel.formatted_emoji().as_deref(), Some("📢")); - } - - #[test] - fn display_title_does_not_duplicate_unicode_emoji() { - let channel = ChatChannel { - id: 8, - unicode_title: Some("🔥 热点".into()), - emoji: Some("fire".into()), - chatable_type: "Category".into(), - ..Default::default() - }; - assert_eq!(channel.display_title(), "🔥 热点"); - } - - #[test] - fn inbox_channels_sort_by_last_activity() { - let older = ChatMessage { - created_at: Some("2026-01-01T00:00:00.000Z".into()), - ..Default::default() - }; - let newer = ChatMessage { - created_at: Some("2026-08-01T00:00:00.000Z".into()), - ..Default::default() - }; - let response = MyChatChannelsResponse { - public_channels: vec![ChatChannel { - id: 1, - chatable_type: "Category".into(), - last_message: Some(older), - ..Default::default() - }], - direct_message_channels: vec![ChatChannel { - id: 2, - chatable_type: "DirectMessage".into(), - last_message: Some(newer), - ..Default::default() - }], - ..Default::default() - }; - let inbox = response.inbox_channels(); - assert_eq!( - inbox.iter().map(|channel| channel.id).collect::>(), - vec![2, 1] - ); - } -} diff --git a/crates/fire-models/src/chat/bus.rs b/crates/fire-models/src/chat/bus.rs new file mode 100644 index 00000000..8c2cb436 --- /dev/null +++ b/crates/fire-models/src/chat/bus.rs @@ -0,0 +1,38 @@ +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ChatReactionAction { + Add, + Remove, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ChatBusEvent { + MessageUpsert { + message: Box, + }, + MessageDeleted { + id: u64, + }, + Reaction { + message_id: u64, + emoji: String, + action: ChatReactionAction, + actor_id: Option, + }, + Tracking { + channel_id: u64, + unread: u32, + mention: u32, + thread_id: Option, + }, + ChannelUpsert { + channel: Box, + }, + NewMessages { + channel_id: u64, + is_channel_level: bool, + message: Option>, + actor_id: Option, + }, + Ignored, +} + diff --git a/crates/fire-models/src/chat/channels.rs b/crates/fire-models/src/chat/channels.rs new file mode 100644 index 00000000..0e53a5c3 --- /dev/null +++ b/crates/fire-models/src/chat/channels.rs @@ -0,0 +1,237 @@ +/// Discourse Chat 用户摘要(频道成员 / 消息作者)。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatUser { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +/// 当前用户在频道上的成员关系。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatChannelMembership { + pub following: bool, + pub muted: bool, + pub starred: bool, + pub notification_level: Option, + pub last_read_message_id: Option, + pub last_viewed_at: Option, +} + +/// 频道 MessageBus 订阅起始位点(`meta.message_bus_last_ids`)。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatChannelBusLastIds { + pub channel_message_bus_last_id: Option, + pub new_messages: Option, + pub new_mentions: Option, + pub kick: Option, +} + +/// 单频道未读 tracking。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatChannelTracking { + pub unread_count: u32, + pub mention_count: u32, +} + +/// Chat 频道(公共 Category 频道或 DirectMessage)。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatChannel { + pub id: u64, + pub title: Option, + pub unicode_title: Option, + pub slug: Option, + pub description: Option, + /// `DirectMessage` 或 `Category` + pub chatable_type: String, + pub status: Option, + pub threading_enabled: bool, + pub memberships_count: Option, + pub is_group_dm: bool, + pub dm_users: Vec, + pub category_color: Option, + pub category_name: Option, + pub emoji: Option, + pub current_user_membership: Option, + pub last_message: Option, + pub bus_last_ids: ChatChannelBusLastIds, + pub can_moderate: bool, + pub can_manage_pins: bool, + pub can_delete_self: bool, + pub can_delete_others: bool, + pub can_remove_members: bool, + pub can_flag: bool, +} + +impl ChatChannel { + pub fn is_direct_message(&self) -> bool { + self.chatable_type.eq_ignore_ascii_case("DirectMessage") + } + + pub fn is_public_channel(&self) -> bool { + self.chatable_type.eq_ignore_ascii_case("Category") + } + + pub fn display_title(&self) -> String { + let title = self + .unicode_title + .as_ref() + .or(self.title.as_ref()) + .cloned() + .filter(|value| !value.trim().is_empty()) + .unwrap_or_else(|| format!("#{}", self.id)); + let Some(emoji) = self.formatted_emoji() else { + return title; + }; + if title.contains(&emoji) || title.contains(&format!(":{}:", emoji.trim_matches(':'))) { + return title; + } + format!("{emoji} {title}") + } + + /// Leading glyph for public-channel inbox rows (unicode or `:shortcode:`). + pub fn formatted_emoji(&self) -> Option { + let raw = self.emoji.as_deref()?.trim(); + if raw.is_empty() { + return None; + } + let name = raw.trim_matches(':'); + if name + .chars() + .any(|ch| !ch.is_ascii_alphanumeric() && ch != '_') + { + return Some(name.to_string()); + } + Some( + emoji_shortcode_to_unicode(name) + .map(str::to_string) + .unwrap_or_else(|| format!(":{name}:")), + ) + } + + pub fn last_activity_at(&self) -> Option<&str> { + self.last_message + .as_ref() + .and_then(|message| message.created_at.as_deref()) + } +} + +fn emoji_shortcode_to_unicode(name: &str) -> Option<&'static str> { + Some(match name { + "smile" | "slightly_smiling_face" => "🙂", + "grinning" | "grin" => "😀", + "joy" => "😂", + "heart" | "red_heart" => "❤️", + "fire" => "🔥", + "tada" => "🎉", + "rocket" => "🚀", + "star" => "⭐", + "warning" => "⚠️", + "speech_balloon" | "speech_left" => "💬", + "loudspeaker" | "mega" => "📢", + "bell" => "🔔", + "bulb" => "💡", + "computer" | "desktop_computer" => "💻", + "earth_asia" | "globe_with_meridians" => "🌏", + "link" => "🔗", + "memo" | "pencil" => "📝", + "books" => "📚", + "gear" => "⚙️", + "hammer_and_wrench" | "hammer" => "🛠️", + "bug" => "🐛", + "tv" => "📺", + "game_die" | "video_game" => "🎮", + "coffee" => "☕", + "seedling" => "🌱", + "pushpin" => "📌", + "eyes" => "👀", + "wave" => "👋", + "thumbsup" | "+1" => "👍", + "clap" => "👏", + "100" => "💯", + _ => return None, + }) +} + +/// GET `/chat/api/me/channels` 响应。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MyChatChannelsResponse { + pub public_channels: Vec, + pub direct_message_channels: Vec, + /// channel_id → tracking + pub channel_tracking: Vec, + /// 全局 MessageBus 通道起始位点(key/value 扁平列表) + pub global_bus_last_ids: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatChannelTrackingEntry { + pub channel_id: u64, + pub unread_count: u32, + pub mention_count: u32, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatBusLastIdEntry { + pub channel: String, + pub last_id: i64, +} + +impl MyChatChannelsResponse { + /// 底栏徽章口径(对齐官方 web / fluxdo): + /// - DM:unread + mention + /// - 公共频道:仅 mention + /// - muted 不计 + pub fn total_unread_badge(&self) -> u32 { + let tracking_for = |channel_id: u64| -> (u32, u32) { + self.channel_tracking + .iter() + .find(|entry| entry.channel_id == channel_id) + .map(|entry| (entry.unread_count, entry.mention_count)) + .unwrap_or((0, 0)) + }; + + let mut sum = 0u32; + for channel in &self.direct_message_channels { + if channel + .current_user_membership + .as_ref() + .is_some_and(|m| m.muted) + { + continue; + } + let (unread, mention) = tracking_for(channel.id); + sum = sum.saturating_add(unread).saturating_add(mention); + } + for channel in &self.public_channels { + if channel + .current_user_membership + .as_ref() + .is_some_and(|m| m.muted) + { + continue; + } + let (_, mention) = tracking_for(channel.id); + sum = sum.saturating_add(mention); + } + sum + } + + /// WeChat-style inbox: DMs and public channels sorted by last activity. + pub fn inbox_channels(&self) -> Vec<&ChatChannel> { + let mut channels: Vec<&ChatChannel> = self + .direct_message_channels + .iter() + .chain(self.public_channels.iter()) + .collect(); + channels.sort_by(|left, right| { + right + .last_activity_at() + .unwrap_or("") + .cmp(left.last_activity_at().unwrap_or("")) + .then_with(|| right.id.cmp(&left.id)) + }); + channels + } +} + diff --git a/crates/fire-models/src/chat/messages.rs b/crates/fire-models/src/chat/messages.rs new file mode 100644 index 00000000..56e34a93 --- /dev/null +++ b/crates/fire-models/src/chat/messages.rs @@ -0,0 +1,113 @@ +/// Chat 消息附件。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatUpload { + pub id: u64, + pub url: Option, + pub short_url: Option, + pub original_filename: Option, + pub extension: Option, + pub width: Option, + pub height: Option, + pub thumbnail_width: Option, + pub thumbnail_height: Option, + pub dominant_color: Option, +} + +/// 消息表情回应聚合。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatMessageReaction { + pub emoji: String, + pub count: u32, + pub reacted: bool, + pub users: Vec, +} + +/// 被回复消息摘要。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatMessageReplyRef { + pub id: u64, + pub excerpt: Option, + pub user: Option, +} + +/// 消息串摘要。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatThreadRef { + pub id: u64, + pub title: Option, + pub reply_count: u32, + pub last_reply_created_at: Option, + pub last_reply_excerpt: Option, + pub last_reply_user: Option, + pub participants: Vec, +} + +/// 消息收藏。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatMessageBookmark { + pub id: u64, + pub name: Option, + pub reminder_at: Option, +} + +/// Chat 消息。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatMessage { + pub id: u64, + pub channel_id: u64, + pub message: String, + pub cooked: String, + pub excerpt: Option, + pub created_at: Option, + pub deleted_at: Option, + pub deleted_by_id: Option, + pub edited: bool, + pub thread_id: Option, + pub thread: Option, + pub user: Option, + pub mentioned_users: Vec, + pub reactions: Vec, + pub uploads: Vec, + pub in_reply_to: Option, + pub streaming: bool, + pub available_flags: Vec, + pub user_flag_status: Option, + pub bookmark: Option, + pub pinned: bool, + #[serde(default)] + pub presented: AttachedPresentation, +} + +impl ChatMessage { + pub fn reuse_presentation_from(&mut self, previous: &Self) { + if self.cooked == previous.cooked { + if let Some(presented) = previous.presented.arc() { + self.presented = AttachedPresentation::some(presented); + } + } + } + + pub fn is_deleted(&self) -> bool { + self.deleted_at.is_some() + } + + pub fn preview_text(&self) -> String { + if let Some(excerpt) = self + .excerpt + .as_ref() + .map(|value| value.trim()) + .filter(|value| !value.is_empty()) + { + return excerpt.to_string(); + } + let plain = self.message.trim(); + if !plain.is_empty() { + return plain.to_string(); + } + if !self.uploads.is_empty() { + return "[附件]".to_string(); + } + String::new() + } +} + diff --git a/crates/fire-models/src/chat/mod.rs b/crates/fire-models/src/chat/mod.rs new file mode 100644 index 00000000..4de54b88 --- /dev/null +++ b/crates/fire-models/src/chat/mod.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +use crate::rich_text::AttachedPresentation; + +include!("channels.rs"); +include!("messages.rs"); +include!("bus.rs"); +include!("requests.rs"); +include!("tests.rs"); diff --git a/crates/fire-models/src/chat/requests.rs b/crates/fire-models/src/chat/requests.rs new file mode 100644 index 00000000..ddd05de0 --- /dev/null +++ b/crates/fire-models/src/chat/requests.rs @@ -0,0 +1,75 @@ +/// GET `/chat/api/channels/:id/messages` 响应。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatMessagesResponse { + pub messages: Vec, + pub can_load_more_past: bool, + pub can_load_more_future: bool, + pub target_message_id: Option, +} + +/// 消息列表查询。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatMessagesQuery { + pub channel_id: u64, + pub direction: Option, + pub target_message_id: Option, + pub fetch_from_last_read: bool, + pub page_size: Option, +} + +/// 创建/复用 DM 频道。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CreateDirectMessageChannelRequest { + pub target_usernames: Vec, + pub name: Option, + pub upsert: bool, +} + +/// 发送消息。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SendChatMessageRequest { + pub channel_id: u64, + pub message: String, + pub staged_id: Option, + pub in_reply_to_id: Option, + pub thread_id: Option, + pub upload_ids: Vec, +} + +/// 发送消息结果。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SendChatMessageResult { + pub message_id: Option, +} + +/// 频道成员。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatChannelMember { + pub user: ChatUser, + pub following: bool, + pub muted: bool, +} + +/// 浏览公共频道查询。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct BrowseChatChannelsQuery { + pub filter: Option, + pub offset: Option, + pub limit: Option, +} + +/// 搜索聊天消息。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatSearchQuery { + pub query: String, + pub channel_id: Option, + pub offset: Option, + pub limit: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatSearchResult { + pub messages: Vec, + pub has_more: bool, +} + diff --git a/crates/fire-models/src/chat/tests.rs b/crates/fire-models/src/chat/tests.rs new file mode 100644 index 00000000..31d4867a --- /dev/null +++ b/crates/fire-models/src/chat/tests.rs @@ -0,0 +1,117 @@ +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn total_unread_badge_matches_official_rules() { + let response = MyChatChannelsResponse { + public_channels: vec![ChatChannel { + id: 1, + chatable_type: "Category".into(), + current_user_membership: Some(ChatChannelMembership { + muted: false, + ..Default::default() + }), + ..Default::default() + }], + direct_message_channels: vec![ + ChatChannel { + id: 2, + chatable_type: "DirectMessage".into(), + current_user_membership: Some(ChatChannelMembership { + muted: false, + ..Default::default() + }), + ..Default::default() + }, + ChatChannel { + id: 3, + chatable_type: "DirectMessage".into(), + current_user_membership: Some(ChatChannelMembership { + muted: true, + ..Default::default() + }), + ..Default::default() + }, + ], + channel_tracking: vec![ + ChatChannelTrackingEntry { + channel_id: 1, + unread_count: 9, + mention_count: 2, + }, + ChatChannelTrackingEntry { + channel_id: 2, + unread_count: 3, + mention_count: 1, + }, + ChatChannelTrackingEntry { + channel_id: 3, + unread_count: 100, + mention_count: 50, + }, + ], + global_bus_last_ids: Vec::new(), + }; + + // public: only mention (2); dm2: 3+1; muted dm3: 0 → 6 + assert_eq!(response.total_unread_badge(), 6); + } + + #[test] + fn display_title_prefixes_channel_emoji() { + let channel = ChatChannel { + id: 8, + title: Some("公告".into()), + emoji: Some("loudspeaker".into()), + chatable_type: "Category".into(), + ..Default::default() + }; + assert_eq!(channel.display_title(), "📢 公告"); + assert_eq!(channel.formatted_emoji().as_deref(), Some("📢")); + } + + #[test] + fn display_title_does_not_duplicate_unicode_emoji() { + let channel = ChatChannel { + id: 8, + unicode_title: Some("🔥 热点".into()), + emoji: Some("fire".into()), + chatable_type: "Category".into(), + ..Default::default() + }; + assert_eq!(channel.display_title(), "🔥 热点"); + } + + #[test] + fn inbox_channels_sort_by_last_activity() { + let older = ChatMessage { + created_at: Some("2026-01-01T00:00:00.000Z".into()), + ..Default::default() + }; + let newer = ChatMessage { + created_at: Some("2026-08-01T00:00:00.000Z".into()), + ..Default::default() + }; + let response = MyChatChannelsResponse { + public_channels: vec![ChatChannel { + id: 1, + chatable_type: "Category".into(), + last_message: Some(older), + ..Default::default() + }], + direct_message_channels: vec![ChatChannel { + id: 2, + chatable_type: "DirectMessage".into(), + last_message: Some(newer), + ..Default::default() + }], + ..Default::default() + }; + let inbox = response.inbox_channels(); + assert_eq!( + inbox.iter().map(|channel| channel.id).collect::>(), + vec![2, 1] + ); + } +} diff --git a/crates/fire-models/src/cookie/tests.rs b/crates/fire-models/src/cookie/tests.rs index 7670fb4f..f7528032 100644 --- a/crates/fire-models/src/cookie/tests.rs +++ b/crates/fire-models/src/cookie/tests.rs @@ -677,3 +677,318 @@ fn platform_apply_keeps_healthy_incumbent_clearance() { assert_eq!(snapshot.cf_clearance.as_deref(), Some("working")); } + +#[test] +fn platform_cookie_merge_updates_known_auth_fields() { + let mut cookies = CookieSnapshot::default(); + cookies.merge_platform_cookies(&[ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ]); + + assert!(cookies.has_login_session()); + assert!(cookies.has_forum_session()); + assert!(cookies.has_cloudflare_clearance()); +} + +#[test] +fn platform_cookie_merge_keeps_existing_values_when_batch_has_only_empty_values() { + let mut cookies = CookieSnapshot { + t_token: Some("token".into()), + forum_session: Some("forum".into()), + cf_clearance: Some("clearance".into()), + csrf_token: None, + last_challenged_cf_clearance: None, + platform_cookies: Vec::new(), + canonical_cookies: Vec::new(), + }; + + cookies.merge_platform_cookies(&[ + PlatformCookie { + name: "_t".into(), + value: String::new(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: String::new(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ]); + + assert_eq!(cookies.t_token.as_deref(), Some("token")); + assert_eq!(cookies.forum_session.as_deref(), Some("forum")); + assert_eq!(cookies.cf_clearance.as_deref(), Some("clearance")); +} + +#[test] +fn platform_cookie_merge_uses_latest_non_empty_value_per_cookie_name() { + let mut cookies = CookieSnapshot::default(); + + cookies.merge_platform_cookies(&[ + PlatformCookie { + name: "_t".into(), + value: "stale".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_t".into(), + value: String::new(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_t".into(), + value: "fresh".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ]); + + assert_eq!(cookies.t_token.as_deref(), Some("fresh")); +} + +#[test] +fn platform_cookie_apply_replaces_known_auth_fields() { + let mut cookies = CookieSnapshot { + t_token: Some("stale-token".into()), + forum_session: Some("stale-forum".into()), + cf_clearance: Some("stale-clearance".into()), + csrf_token: Some("csrf".into()), + last_challenged_cf_clearance: None, + platform_cookies: Vec::new(), + canonical_cookies: Vec::new(), + }; + + cookies.apply_platform_cookies(&[ + PlatformCookie { + name: "_t".into(), + value: "fresh-token".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "fresh-clearance".into(), + domain: None, + path: None, + expires_at_unix_ms: None, + same_site: None, + }, + ]); + + assert_eq!(cookies.t_token.as_deref(), Some("fresh-token")); + assert_eq!(cookies.forum_session, None); + assert_eq!(cookies.cf_clearance.as_deref(), Some("stale-clearance")); + assert_eq!(cookies.csrf_token.as_deref(), Some("csrf")); +} + +#[test] +fn platform_cookie_apply_preserves_full_browser_cookie_batch() { + let mut cookies = CookieSnapshot::default(); + + cookies.apply_platform_cookies(&[ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "__cf_bm".into(), + value: "browser-context".into(), + domain: Some(".linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + ]); + + assert_eq!(cookies.platform_cookies.len(), 2); + assert!(cookies + .platform_cookies + .iter() + .any(|cookie| cookie.name == "__cf_bm" && cookie.value == "browser-context")); +} + +#[test] +fn empty_patch_clears_cookie_fields() { + let mut cookies = CookieSnapshot { + t_token: Some("token".into()), + forum_session: Some("forum".into()), + cf_clearance: Some("clearance".into()), + csrf_token: Some("csrf".into()), + last_challenged_cf_clearance: None, + platform_cookies: Vec::new(), + canonical_cookies: Vec::new(), + }; + + cookies.merge_patch(&CookieSnapshot { + forum_session: Some(String::new()), + csrf_token: Some(String::new()), + last_challenged_cf_clearance: None, + ..CookieSnapshot::default() + }); + + assert_eq!(cookies.t_token.as_deref(), Some("token")); + assert_eq!(cookies.forum_session, None); + assert_eq!(cookies.csrf_token, None); + assert_eq!(cookies.cf_clearance.as_deref(), Some("clearance")); +} + +#[test] +fn clear_login_state_keeps_non_auth_platform_cookies() { + let mut cookies = CookieSnapshot::default(); + cookies.apply_platform_cookies(&[ + PlatformCookie { + name: "_t".into(), + value: "token".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "__cf_bm".into(), + value: "browser-context".into(), + domain: Some(".linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + ]); + + cookies.clear_login_state(true); + + assert_eq!(cookies.t_token, None); + assert_eq!(cookies.forum_session, None); + assert_eq!(cookies.cf_clearance.as_deref(), Some("clearance")); + assert!(cookies + .platform_cookies + .iter() + .all(|cookie| cookie.name != "_t" && cookie.name != "_forum_session")); + assert!(cookies + .platform_cookies + .iter() + .any(|cookie| cookie.name == "cf_clearance")); + assert!(cookies + .platform_cookies + .iter() + .any(|cookie| cookie.name == "__cf_bm")); +} + +#[test] +fn platform_cookie_apply_drops_expired_cookie_entries() { + let mut cookies = CookieSnapshot::default(); + + cookies.apply_platform_cookies(&[ + PlatformCookie { + name: "_t".into(), + value: "expired-token".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: Some(1), + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "forum".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + ]); + + assert_eq!(cookies.t_token, None); + assert_eq!(cookies.forum_session.as_deref(), Some("forum")); + assert_eq!(cookies.platform_cookies.len(), 1); + assert_eq!(cookies.platform_cookies[0].name, "_forum_session"); +} + +#[test] +fn platform_cookie_apply_replaces_same_normalized_domain_variant() { + let mut cookies = CookieSnapshot::default(); + + cookies.apply_platform_cookies(&[ + PlatformCookie { + name: "_t".into(), + value: "host-only".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + PlatformCookie { + name: "_t".into(), + value: "domain-scope".into(), + domain: Some(".linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: None, + same_site: None, + }, + ]); + + assert_eq!(cookies.platform_cookies.len(), 1); + assert_eq!(cookies.t_token.as_deref(), Some("domain-scope")); + assert_eq!( + cookies.platform_cookies[0].domain.as_deref(), + Some(".linux.do") + ); + assert_eq!(cookies.platform_cookies[0].value, "domain-scope"); +} diff --git a/crates/fire-models/src/lib.rs b/crates/fire-models/src/lib.rs index b6c47f24..fb0defb2 100644 --- a/crates/fire-models/src/lib.rs +++ b/crates/fire-models/src/lib.rs @@ -27,959 +27,3 @@ pub use topic::*; pub use topic_detail::*; pub use topic_detail_ui::*; pub use user::*; - -#[cfg(test)] -mod tests { - use super::{ - BootstrapArtifacts, CookieSnapshot, CurrentUserSnapshot, LoginPhase, PlatformCookie, - SessionSnapshot, TopicCategory, TopicDetail, TopicListKind, TopicListQuery, TopicPost, - TopicPostStream, TopicReaction, TopicThread, TopicThreadFlatPost, - }; - - #[test] - fn platform_cookie_merge_updates_known_auth_fields() { - let mut cookies = CookieSnapshot::default(); - cookies.merge_platform_cookies(&[ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ]); - - assert!(cookies.has_login_session()); - assert!(cookies.has_forum_session()); - assert!(cookies.has_cloudflare_clearance()); - } - - #[test] - fn platform_cookie_merge_keeps_existing_values_when_batch_has_only_empty_values() { - let mut cookies = CookieSnapshot { - t_token: Some("token".into()), - forum_session: Some("forum".into()), - cf_clearance: Some("clearance".into()), - csrf_token: None, - last_challenged_cf_clearance: None, - platform_cookies: Vec::new(), - canonical_cookies: Vec::new(), - }; - - cookies.merge_platform_cookies(&[ - PlatformCookie { - name: "_t".into(), - value: String::new(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: String::new(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ]); - - assert_eq!(cookies.t_token.as_deref(), Some("token")); - assert_eq!(cookies.forum_session.as_deref(), Some("forum")); - assert_eq!(cookies.cf_clearance.as_deref(), Some("clearance")); - } - - #[test] - fn platform_cookie_merge_uses_latest_non_empty_value_per_cookie_name() { - let mut cookies = CookieSnapshot::default(); - - cookies.merge_platform_cookies(&[ - PlatformCookie { - name: "_t".into(), - value: "stale".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_t".into(), - value: String::new(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_t".into(), - value: "fresh".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ]); - - assert_eq!(cookies.t_token.as_deref(), Some("fresh")); - } - - #[test] - fn platform_cookie_apply_replaces_known_auth_fields() { - let mut cookies = CookieSnapshot { - t_token: Some("stale-token".into()), - forum_session: Some("stale-forum".into()), - cf_clearance: Some("stale-clearance".into()), - csrf_token: Some("csrf".into()), - last_challenged_cf_clearance: None, - platform_cookies: Vec::new(), - canonical_cookies: Vec::new(), - }; - - cookies.apply_platform_cookies(&[ - PlatformCookie { - name: "_t".into(), - value: "fresh-token".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "fresh-clearance".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }, - ]); - - assert_eq!(cookies.t_token.as_deref(), Some("fresh-token")); - assert_eq!(cookies.forum_session, None); - assert_eq!(cookies.cf_clearance.as_deref(), Some("stale-clearance")); - assert_eq!(cookies.csrf_token.as_deref(), Some("csrf")); - } - - #[test] - fn platform_cookie_apply_preserves_full_browser_cookie_batch() { - let mut cookies = CookieSnapshot::default(); - - cookies.apply_platform_cookies(&[ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "__cf_bm".into(), - value: "browser-context".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - ]); - - assert_eq!(cookies.platform_cookies.len(), 2); - assert!(cookies - .platform_cookies - .iter() - .any(|cookie| cookie.name == "__cf_bm" && cookie.value == "browser-context")); - } - - #[test] - fn empty_patch_clears_cookie_fields() { - let mut cookies = CookieSnapshot { - t_token: Some("token".into()), - forum_session: Some("forum".into()), - cf_clearance: Some("clearance".into()), - csrf_token: Some("csrf".into()), - last_challenged_cf_clearance: None, - platform_cookies: Vec::new(), - canonical_cookies: Vec::new(), - }; - - cookies.merge_patch(&CookieSnapshot { - forum_session: Some(String::new()), - csrf_token: Some(String::new()), - last_challenged_cf_clearance: None, - ..CookieSnapshot::default() - }); - - assert_eq!(cookies.t_token.as_deref(), Some("token")); - assert_eq!(cookies.forum_session, None); - assert_eq!(cookies.csrf_token, None); - assert_eq!(cookies.cf_clearance.as_deref(), Some("clearance")); - } - - #[test] - fn clear_login_state_keeps_non_auth_platform_cookies() { - let mut cookies = CookieSnapshot::default(); - cookies.apply_platform_cookies(&[ - PlatformCookie { - name: "_t".into(), - value: "token".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "__cf_bm".into(), - value: "browser-context".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - ]); - - cookies.clear_login_state(true); - - assert_eq!(cookies.t_token, None); - assert_eq!(cookies.forum_session, None); - assert_eq!(cookies.cf_clearance.as_deref(), Some("clearance")); - assert!(cookies - .platform_cookies - .iter() - .all(|cookie| cookie.name != "_t" && cookie.name != "_forum_session")); - assert!(cookies - .platform_cookies - .iter() - .any(|cookie| cookie.name == "cf_clearance")); - assert!(cookies - .platform_cookies - .iter() - .any(|cookie| cookie.name == "__cf_bm")); - } - - #[test] - fn platform_cookie_apply_drops_expired_cookie_entries() { - let mut cookies = CookieSnapshot::default(); - - cookies.apply_platform_cookies(&[ - PlatformCookie { - name: "_t".into(), - value: "expired-token".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: Some(1), - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "forum".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - ]); - - assert_eq!(cookies.t_token, None); - assert_eq!(cookies.forum_session.as_deref(), Some("forum")); - assert_eq!(cookies.platform_cookies.len(), 1); - assert_eq!(cookies.platform_cookies[0].name, "_forum_session"); - } - - #[test] - fn platform_cookie_apply_replaces_same_normalized_domain_variant() { - let mut cookies = CookieSnapshot::default(); - - cookies.apply_platform_cookies(&[ - PlatformCookie { - name: "_t".into(), - value: "host-only".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - PlatformCookie { - name: "_t".into(), - value: "domain-scope".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, - ]); - - assert_eq!(cookies.platform_cookies.len(), 1); - assert_eq!(cookies.t_token.as_deref(), Some("domain-scope")); - assert_eq!( - cookies.platform_cookies[0].domain.as_deref(), - Some(".linux.do") - ); - assert_eq!(cookies.platform_cookies[0].value, "domain-scope"); - } - - #[test] - fn readiness_ignores_expired_platform_auth_cookies() { - let cookies = CookieSnapshot { - t_token: Some("stale-token".into()), - forum_session: Some("stale-forum".into()), - cf_clearance: Some("stale-clearance".into()), - csrf_token: None, - last_challenged_cf_clearance: None, - platform_cookies: vec![ - PlatformCookie { - name: "_t".into(), - value: "expired-token".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: Some(1), - same_site: None, - }, - PlatformCookie { - name: "_forum_session".into(), - value: "expired-forum".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: Some(1), - same_site: None, - }, - PlatformCookie { - name: "cf_clearance".into(), - value: "expired-clearance".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: Some(1), - same_site: None, - }, - ], - canonical_cookies: Vec::new(), - }; - - assert!(!cookies.has_login_session()); - assert!(!cookies.has_forum_session()); - assert!(!cookies.has_cloudflare_clearance()); - assert!(!cookies.can_authenticate_requests()); - } - - #[test] - fn login_phase_advances_with_bootstrap_and_csrf() { - let mut snapshot = SessionSnapshot::default(); - assert_eq!(snapshot.login_phase(), LoginPhase::Anonymous); - - snapshot.cookies.t_token = Some("token".into()); - assert_eq!(snapshot.login_phase(), LoginPhase::CookiesCaptured); - - snapshot.cookies.forum_session = Some("forum".into()); - snapshot.bootstrap.current_username = Some("alice".into()); - assert_eq!(snapshot.login_phase(), LoginPhase::BootstrapCaptured); - - snapshot.cookies.csrf_token = Some("csrf".into()); - snapshot.bootstrap.preloaded_json = - Some("{\"currentUser\":{\"username\":\"alice\"}}".into()); - snapshot.bootstrap.has_preloaded_data = true; - snapshot.bootstrap.has_site_metadata = true; - snapshot.bootstrap.has_site_settings = true; - assert_eq!(snapshot.login_phase(), LoginPhase::Ready); - } - - #[test] - fn merge_patch_keeps_existing_site_metadata_when_partial_preloaded_lacks_site() { - let mut bootstrap = BootstrapArtifacts { - preloaded_json: Some("{\"site\":{\"categories\":[{\"id\":2}]}}".into()), - has_preloaded_data: true, - has_site_metadata: true, - top_tags: vec!["swift".into()], - can_tag_topics: true, - categories: vec![TopicCategory { - id: 2, - name: "Rust".into(), - slug: "rust".into(), - parent_category_id: None, - color_hex: Some("FFFFFF".into()), - text_color_hex: Some("000000".into()), - ..TopicCategory::default() - }], - has_site_settings: true, - enabled_reaction_ids: vec!["heart".into(), "clap".into()], - min_post_length: 20, - min_topic_title_length: 15, - min_first_post_length: 20, - default_composer_category: Some(2), - ..BootstrapArtifacts::default() - }; - - bootstrap.merge_patch(&BootstrapArtifacts { - preloaded_json: Some("{\"currentUser\":{\"username\":\"alice\"}}".into()), - has_preloaded_data: true, - ..BootstrapArtifacts::default() - }); - - assert!(bootstrap.has_site_metadata); - assert_eq!(bootstrap.top_tags, vec!["swift"]); - assert!(bootstrap.can_tag_topics); - assert_eq!(bootstrap.categories.len(), 1); - assert!(bootstrap.has_site_settings); - assert_eq!(bootstrap.enabled_reaction_ids, vec!["heart", "clap"]); - assert_eq!(bootstrap.min_post_length, 20); - assert_eq!(bootstrap.min_topic_title_length, 15); - assert_eq!(bootstrap.min_first_post_length, 20); - assert_eq!(bootstrap.default_composer_category, Some(2)); - } - - #[test] - fn merge_patch_updates_site_metadata_and_settings_when_present() { - let mut bootstrap = BootstrapArtifacts::default(); - - bootstrap.merge_patch(&BootstrapArtifacts { - preloaded_json: Some("{\"site\":{},\"siteSettings\":{}}".into()), - has_preloaded_data: true, - has_site_metadata: true, - top_tags: vec!["rust".into(), "swift".into(), "rust".into()], - can_tag_topics: true, - categories: vec![TopicCategory { - id: 2, - name: "Rust".into(), - slug: "rust".into(), - parent_category_id: None, - color_hex: None, - text_color_hex: None, - ..TopicCategory::default() - }], - has_site_settings: true, - enabled_reaction_ids: vec!["heart".into(), "clap".into(), "heart".into()], - min_post_length: 18, - min_topic_title_length: 16, - min_first_post_length: 24, - default_composer_category: Some(2), - ..BootstrapArtifacts::default() - }); - - assert!(bootstrap.has_site_metadata); - assert_eq!(bootstrap.top_tags, vec!["rust", "swift"]); - assert!(bootstrap.can_tag_topics); - assert_eq!(bootstrap.categories.len(), 1); - assert!(bootstrap.has_site_settings); - assert_eq!(bootstrap.enabled_reaction_ids, vec!["heart", "clap"]); - assert_eq!(bootstrap.min_post_length, 18); - assert_eq!(bootstrap.min_topic_title_length, 16); - assert_eq!(bootstrap.min_first_post_length, 24); - assert_eq!(bootstrap.default_composer_category, Some(2)); - } - - #[test] - fn merge_patch_applies_site_metadata_without_preloaded_payload() { - let mut bootstrap = BootstrapArtifacts { - preloaded_json: Some("{\"currentUser\":{\"username\":\"alice\"}}".into()), - has_preloaded_data: true, - ..BootstrapArtifacts::default() - }; - - bootstrap.merge_patch(&BootstrapArtifacts { - has_site_metadata: true, - top_tags: vec!["rust".into(), "swift".into()], - can_tag_topics: true, - categories: vec![TopicCategory { - id: 2, - name: "Rust".into(), - slug: "rust".into(), - parent_category_id: None, - color_hex: None, - text_color_hex: None, - ..TopicCategory::default() - }], - ..BootstrapArtifacts::default() - }); - - assert!(bootstrap.has_site_metadata); - assert_eq!(bootstrap.top_tags, vec!["rust", "swift"]); - assert!(bootstrap.can_tag_topics); - assert_eq!(bootstrap.categories.len(), 1); - assert!(bootstrap.has_preloaded_data); - } - - #[test] - fn topic_detail_interaction_count_adds_non_heart_reactions_to_topic_likes() { - let detail = TopicDetail { - like_count: 21, - post_stream: TopicPostStream { - posts: vec![ - TopicPost { - reactions: vec![ - TopicReaction { - id: "heart".into(), - count: 5, - ..TopicReaction::default() - }, - TopicReaction { - id: "clap".into(), - count: 2, - ..TopicReaction::default() - }, - ], - ..TopicPost::default() - }, - TopicPost { - reactions: vec![TopicReaction { - id: "TADA".into(), - count: 3, - ..TopicReaction::default() - }], - ..TopicPost::default() - }, - ], - ..TopicPostStream::default() - }, - ..TopicDetail::default() - }; - - assert_eq!(detail.interaction_count(), 26); - } - - #[test] - fn same_origin_message_bus_does_not_require_shared_session_key() { - let snapshot = SessionSnapshot { - cookies: CookieSnapshot { - t_token: Some("token".into()), - forum_session: Some("forum".into()), - ..CookieSnapshot::default() - }, - bootstrap: BootstrapArtifacts { - base_url: "https://linux.do".into(), - long_polling_base_url: Some("https://linux.do".into()), - current_username: Some("alice".into()), - preloaded_json: Some("{\"currentUser\":{\"username\":\"alice\"}}".into()), - has_preloaded_data: true, - ..BootstrapArtifacts::default() - }, - browser_user_agent: None, - read_path_login_request: None, - }; - - let readiness = snapshot.readiness(); - - assert!(!readiness.has_shared_session_key); - assert!(readiness.can_open_message_bus); - } - - #[test] - fn cross_origin_message_bus_requires_shared_session_key() { - let snapshot = SessionSnapshot { - cookies: CookieSnapshot { - t_token: Some("token".into()), - forum_session: Some("forum".into()), - ..CookieSnapshot::default() - }, - bootstrap: BootstrapArtifacts { - base_url: "https://linux.do".into(), - long_polling_base_url: Some("https://poll.linux.do".into()), - current_username: Some("alice".into()), - preloaded_json: Some("{\"currentUser\":{\"username\":\"alice\"}}".into()), - has_preloaded_data: true, - ..BootstrapArtifacts::default() - }, - browser_user_agent: None, - read_path_login_request: None, - }; - - let readiness = snapshot.readiness(); - - assert!(!readiness.has_shared_session_key); - assert!(!readiness.can_open_message_bus); - } - - #[test] - fn clear_login_state_preserves_cf_when_requested() { - let mut snapshot = SessionSnapshot { - cookies: CookieSnapshot { - t_token: Some("token".into()), - forum_session: Some("forum".into()), - cf_clearance: Some("clearance".into()), - csrf_token: Some("csrf".into()), - last_challenged_cf_clearance: None, - platform_cookies: Vec::new(), - canonical_cookies: Vec::new(), - }, - bootstrap: BootstrapArtifacts { - base_url: "https://linux.do".into(), - discourse_base_uri: Some("/".into()), - shared_session_key: Some("shared".into()), - current_username: Some("alice".into()), - current_user_id: Some(1), - notification_channel_position: Some(42), - long_polling_base_url: Some("https://linux.do".into()), - turnstile_sitekey: Some("sitekey".into()), - topic_tracking_state_meta: Some("{\"seq\":1}".into()), - preloaded_json: Some("{\"ok\":true}".into()), - has_preloaded_data: true, - has_site_metadata: true, - top_tags: vec!["rust".into()], - can_tag_topics: true, - categories: Vec::new(), - has_site_settings: true, - enabled_reaction_ids: vec!["heart".into(), "clap".into()], - min_post_length: 20, - min_topic_title_length: 15, - min_first_post_length: 20, - min_personal_message_title_length: 2, - min_personal_message_post_length: 10, - default_composer_category: Some(2), - }, - browser_user_agent: None, - read_path_login_request: None, - }; - - snapshot.clear_login_state(true); - - assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); - assert_eq!(snapshot.cookies.t_token, None); - assert_eq!(snapshot.bootstrap.current_username, None); - assert_eq!(snapshot.bootstrap.current_user_id, None); - assert_eq!(snapshot.bootstrap.notification_channel_position, None); - assert_eq!(snapshot.bootstrap.shared_session_key, None); - assert_eq!(snapshot.bootstrap.preloaded_json, None); - assert!(!snapshot.bootstrap.has_preloaded_data); - assert_eq!( - snapshot.bootstrap.turnstile_sitekey.as_deref(), - Some("sitekey") - ); - assert!(!snapshot.bootstrap.has_site_metadata); - assert_eq!(snapshot.bootstrap.top_tags, Vec::::new()); - assert!(!snapshot.bootstrap.can_tag_topics); - assert_eq!(snapshot.bootstrap.categories, Vec::new()); - assert!(!snapshot.bootstrap.has_site_settings); - assert_eq!(snapshot.bootstrap.enabled_reaction_ids, vec!["heart"]); - assert_eq!(snapshot.bootstrap.min_post_length, 1); - assert_eq!(snapshot.bootstrap.min_topic_title_length, 15); - assert_eq!(snapshot.bootstrap.min_first_post_length, 20); - assert_eq!(snapshot.bootstrap.default_composer_category, None); - } - - #[test] - fn topic_thread_groups_nested_replies_without_duplication() { - let thread = TopicThread::from_posts(&[ - topic_post(1, None), - topic_post(2, Some(1)), - topic_post(3, Some(2)), - topic_post(4, Some(3)), - topic_post(5, Some(1)), - topic_post(6, Some(99)), - ]); - - assert_eq!(thread.original_post_number, Some(1)); - assert_eq!( - thread - .reply_sections - .iter() - .map(|section| section.anchor_post_number) - .collect::>(), - vec![2, 5, 6] - ); - assert_eq!( - thread.reply_sections[0] - .replies - .iter() - .map(|reply| reply.post_number) - .collect::>(), - vec![3, 4] - ); - assert_eq!( - thread.reply_sections[0] - .replies - .iter() - .map(|reply| reply.depth) - .collect::>(), - vec![1, 2] - ); - } - - #[test] - fn topic_thread_flattens_to_display_order_posts() { - let posts = vec![ - topic_post(1, None), - topic_post(2, Some(1)), - topic_post(3, Some(2)), - topic_post(4, Some(3)), - topic_post(5, Some(1)), - topic_post(6, Some(99)), - ]; - let thread = TopicThread::from_posts(&posts); - - assert_eq!( - thread - .flatten(&posts) - .into_iter() - .map(|flat_post: TopicThreadFlatPost| ( - flat_post.post.post_number, - flat_post.depth, - flat_post.parent_post_number, - flat_post.shows_thread_line, - flat_post.is_original_post, - )) - .collect::>(), - vec![ - (1, 0, None, true, true), - (2, 0, None, true, false), - (3, 1, Some(2), true, false), - (4, 2, Some(3), true, false), - (5, 0, None, true, false), - (6, 0, None, false, false), - ] - ); - } - - #[test] - fn topic_list_query_api_path_global() { - let query = TopicListQuery { - kind: TopicListKind::Latest, - ..Default::default() - }; - assert_eq!(query.api_path(), "/latest.json"); - assert_eq!(query.html_path(), "/latest"); - - let query = TopicListQuery { - kind: TopicListKind::Hot, - ..Default::default() - }; - assert_eq!(query.api_path(), "/hot.json"); - assert_eq!(query.html_path(), "/hot"); - } - - #[test] - fn topic_list_query_api_path_category() { - let query = TopicListQuery { - kind: TopicListKind::Latest, - category_slug: Some("dev".into()), - category_id: Some(42), - ..Default::default() - }; - assert_eq!(query.api_path(), "/c/dev/42/l/latest.json"); - assert_eq!(query.html_path(), "/c/dev/42/l/latest"); - } - - #[test] - fn topic_list_query_api_path_subcategory() { - let query = TopicListQuery { - kind: TopicListKind::New, - category_slug: Some("rust".into()), - category_id: Some(99), - parent_category_slug: Some("dev".into()), - ..Default::default() - }; - assert_eq!(query.api_path(), "/c/dev/rust/99/l/new.json"); - assert_eq!(query.html_path(), "/c/dev/rust/99/l/new"); - } - - #[test] - fn topic_list_query_api_path_tag() { - let query = TopicListQuery { - kind: TopicListKind::Top, - tag: Some("swift".into()), - ..Default::default() - }; - assert_eq!(query.api_path(), "/tag/swift/l/top.json"); - assert_eq!(query.html_path(), "/tag/swift/l/top"); - } - - #[test] - fn topic_list_query_api_path_category_slug_only() { - let query = TopicListQuery { - kind: TopicListKind::Latest, - category_slug: Some("dev".into()), - ..Default::default() - }; - assert_eq!(query.api_path(), "/c/dev.json"); - assert_eq!(query.html_path(), "/c/dev"); - } - - #[test] - fn topic_list_query_api_path_topic_ids_override() { - let query = TopicListQuery { - kind: TopicListKind::New, - topic_ids: vec![1, 2, 3], - ..Default::default() - }; - assert_eq!(query.api_path(), "/latest.json"); - assert_eq!(query.html_path(), "/latest"); - } - - #[test] - fn topic_list_query_html_path_private_messages() { - let query = TopicListQuery { - kind: TopicListKind::PrivateMessagesInbox, - ..Default::default() - }; - assert_eq!(query.html_path(), "/my/messages"); - - let query = TopicListQuery { - kind: TopicListKind::PrivateMessagesSent, - ..Default::default() - }; - assert_eq!(query.html_path(), "/my/messages/sent"); - } - - #[test] - fn timeline_entries_floor_order_with_full_post_set() { - let posts = vec![ - topic_post(1, None), - topic_post(2, Some(1)), - topic_post(3, Some(2)), - topic_post(4, Some(1)), - ]; - let mut detail = TopicDetail { - post_stream: TopicPostStream { - posts, - stream: vec![1, 2, 3, 4], - }, - ..Default::default() - }; - detail.rebuild_timeline_entries(); - - assert_eq!(detail.timeline_entries.len(), 4); - assert_eq!(detail.timeline_entries[0].post_number, 1); - assert_eq!(detail.timeline_entries[0].depth, 0); - assert!(detail.timeline_entries[0].is_original_post); - assert_eq!(detail.timeline_entries[1].post_number, 2); - assert_eq!(detail.timeline_entries[1].depth, 1); - assert_eq!(detail.timeline_entries[1].parent_post_number, Some(1)); - assert_eq!(detail.timeline_entries[2].post_number, 3); - assert_eq!(detail.timeline_entries[2].depth, 2); - assert_eq!(detail.timeline_entries[2].parent_post_number, Some(2)); - assert_eq!(detail.timeline_entries[3].post_number, 4); - assert_eq!(detail.timeline_entries[3].depth, 1); - assert_eq!(detail.timeline_entries[3].parent_post_number, Some(1)); - } - - #[test] - fn timeline_entries_partial_set_falls_back_depth_for_missing_parents() { - // Simulate an anchored load that only has posts 5-7, where 5 replies to 3 (not loaded). - let posts = vec![ - topic_post(5, Some(3)), - topic_post(6, Some(5)), - topic_post(7, None), - ]; - let mut detail = TopicDetail { - post_stream: TopicPostStream { - posts, - stream: vec![1, 2, 3, 4, 5, 6, 7], - }, - ..Default::default() - }; - detail.rebuild_timeline_entries(); - - assert_eq!(detail.timeline_entries.len(), 3); - // Post 5 replies to 3 (not loaded) — depth falls back to 1. - assert_eq!(detail.timeline_entries[0].post_number, 5); - assert_eq!(detail.timeline_entries[0].depth, 1); - assert_eq!(detail.timeline_entries[0].parent_post_number, Some(3)); - assert!(detail.timeline_entries[0].is_original_post); // min in partial set - // Post 6 replies to 5 (loaded) — depth is 2. - assert_eq!(detail.timeline_entries[1].post_number, 6); - assert_eq!(detail.timeline_entries[1].depth, 2); - // Post 7 has no parent — depth is 0. - assert_eq!(detail.timeline_entries[2].post_number, 7); - assert_eq!(detail.timeline_entries[2].depth, 0); - } - - #[test] - fn timeline_entries_depth_self_corrects_after_hydration() { - // First: partial set with missing parent. - let partial_posts = vec![topic_post(5, Some(3)), topic_post(6, Some(5))]; - let mut detail = TopicDetail { - post_stream: TopicPostStream { - posts: partial_posts, - stream: vec![1, 2, 3, 4, 5, 6], - }, - ..Default::default() - }; - detail.rebuild_timeline_entries(); - assert_eq!(detail.timeline_entries[0].depth, 1); // fallback - - // Now hydrate: add post 3 (which replies to 1, also not loaded yet). - detail.post_stream.posts.insert(0, topic_post(3, Some(1))); - detail.rebuild_timeline_entries(); - - let entry5 = detail - .timeline_entries - .iter() - .find(|e| e.post_number == 5) - .unwrap(); - // Post 5 → parent 3 (loaded, depth 1 because 3's parent 1 is not loaded) → depth 2. - assert_eq!(entry5.depth, 2); - } - - fn topic_post(post_number: u32, reply_to_post_number: Option) -> TopicPost { - TopicPost { - id: u64::from(post_number), - username: format!("user-{post_number}"), - name: None, - avatar_template: None, - author_metadata: Default::default(), - cooked: format!("

{post_number}

"), - raw: None, - post_number, - post_type: 1, - created_at: None, - updated_at: None, - like_count: 0, - reply_count: 0, - reply_to_post_number, - reply_to_user: None, - bookmarked: false, - bookmark_id: None, - bookmark_name: None, - bookmark_reminder_at: None, - reactions: Vec::new(), - current_user_reaction: None, - boosts: Vec::new(), - can_boost: false, - polls: Vec::new(), - accepted_answer: false, - can_accept_answer: false, - can_unaccept_answer: false, - can_edit: false, - can_delete: false, - can_recover: false, - hidden: false, - presented: Default::default(), - } - } - - #[test] - fn current_user_snapshot_default_notification_channel_position() { - let snapshot = CurrentUserSnapshot::default(); - assert_eq!(snapshot.notification_channel_position, -1); - } -} diff --git a/crates/fire-models/src/rich_text.rs b/crates/fire-models/src/rich_text.rs deleted file mode 100644 index aa9b33dd..00000000 --- a/crates/fire-models/src/rich_text.rs +++ /dev/null @@ -1,646 +0,0 @@ -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum CookedHtmlNodeKind { - #[default] - Document, - Text, - Paragraph, - Heading, - LineBreak, - Strong, - Emphasis, - Strikethrough, - Link, - Image, - Emoji, - Code, - CodeBlock, - Blockquote, - DiscourseQuote, - Divider, - List, - ListItem, - Spoiler, - Details, - Table, - TableRow, - TableCell, - Onebox, - Iframe, - Mention, - Hashtag, - Attachment, - Unknown, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct CookedHtmlNode { - pub id: u32, - pub parent_id: Option, - pub kind: CookedHtmlNodeKind, - pub depth: u32, - pub text: Option, - pub url: Option, - pub title: Option, - pub alt: Option, - pub level: Option, - pub ordered: Option, - pub attributes: BTreeMap, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct CookedHtmlDocument { - pub nodes: Vec, - pub plain_text: String, - pub image_urls: Vec, - pub link_urls: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct RenderBlock { - pub id: u32, - pub parent_id: Option, - pub depth: u32, - pub kind: RenderBlockKind, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum RenderBlockKind { - Document, - Text { - content: String, - }, - Paragraph, - Heading { - level: u8, - }, - LineBreak, - Bold, - Italic, - Strikethrough, - InlineCode { - code: String, - }, - CodeBlock { - language: Option, - code: String, - }, - Link { - url: String, - }, - Mention { - username: String, - }, - MentionGroup { - name: String, - url: String, - }, - Hashtag { - text: String, - url: String, - kind: Option, - }, - Emoji { - url: String, - fallback_text: String, - only_emoji: bool, - }, - Image { - url: String, - alt: Option, - width: Option, - height: Option, - }, - Blockquote, - Quote { - author: Option, - post_number: Option, - topic_id: Option, - }, - List { - ordered: bool, - }, - ListItem, - Spoiler, - Details, - DetailsSummary, - Table { - text: String, - }, - Onebox { - url: Option, - title: Option, - description: Option, - #[serde(default)] - source_name: Option, - #[serde(default)] - icon_url: Option, - #[serde(default)] - thumbnail_url: Option, - #[serde(default)] - thumbnail_width: Option, - #[serde(default)] - thumbnail_height: Option, - }, - Video { - url: String, - title: Option, - }, - Divider, - #[default] - Unknown, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct RenderImageAttachment { - pub url: String, - pub alt_text: Option, - pub width: Option, - pub height: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct RenderDocument { - pub blocks: Vec, - pub plain_text: String, - pub image_attachments: Vec, -} - -/// Onebox card extracted as a first-class layout segment. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct RenderOneboxCard { - pub url: Option, - pub title: Option, - pub description: Option, - pub source_name: Option, - pub icon_url: Option, - pub thumbnail_url: Option, - pub thumbnail_width: Option, - pub thumbnail_height: Option, -} - -/// Host-drawable rich node. Isomorphic to iOS/Android `FireRichTextNode`. -/// -/// This is a tree, not a flattened `RenderBlock` list: quote / list / details -/// keep their nesting so hosts map mechanically and do not rebuild IR. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum RenderRichNode { - Text { - content: String, - }, - Bold { - children: Vec, - }, - Italic { - children: Vec, - }, - Strikethrough { - children: Vec, - }, - Code { - code: String, - }, - CodeBlock { - language: Option, - code: String, - }, - Link { - url: String, - children: Vec, - }, - Mention { - username: String, - }, - MentionGroup { - name: String, - url: String, - }, - Hashtag { - text: String, - url: String, - kind: Option, - }, - Emoji { - url: String, - fallback_text: String, - only_emoji: bool, - }, - Heading { - level: u8, - children: Vec, - }, - Blockquote { - children: Vec, - }, - Quote { - author: Option, - post_number: Option, - topic_id: Option, - children: Vec, - }, - List { - ordered: bool, - items: Vec>, - }, - ListItem { - children: Vec, - }, - Spoiler { - children: Vec, - }, - Details { - summary: Vec, - children: Vec, - }, - Table { - text: String, - }, - Video { - url: String, - title: Option, - }, - Divider, - LineBreak, - Paragraph { - children: Vec, - }, - Image { - url: String, - alt: Option, - width: Option, - height: Option, - }, - Onebox(RenderOneboxCard), -} - -/// Host layout segment. Image and onebox are independent cells; everything -/// else stays in a rich node run. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum RenderUiSegment { - Rich { nodes: Vec }, - Image(RenderImageAttachment), - Onebox(RenderOneboxCard), -} - -/// UI-ready body produced from a `RenderDocument`. -/// -/// `checksum` is written once in `finish` and is the only content identity -/// hosts may cache on. `image_attachments` is still cloned from the IR in -/// Stage 1; Stage 2 can share the same allocation. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct RenderPresentation { - pub checksum: u64, - pub plain_text: String, - pub image_attachments: Vec, - pub segments: Vec, -} - -impl RenderPresentation { - pub fn finish( - plain_text: String, - image_attachments: Vec, - segments: Vec, - ) -> Self { - let checksum = presentation_checksum(&plain_text, &image_attachments, &segments); - Self { - checksum, - plain_text, - image_attachments, - segments, - } - } - - pub fn is_empty(&self) -> bool { - self.segments.is_empty() && self.plain_text.trim().is_empty() - } -} - -/// Runtime owner of render IR plus the host UI plan. -/// -/// Lives on domain posts as `Arc`. Serde caches must skip -/// it and re-present from `cooked` on cold start. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PresentedDocument { - document: RenderDocument, - presentation: RenderPresentation, -} - -impl PresentedDocument { - pub fn new(document: RenderDocument, presentation: RenderPresentation) -> Self { - Self { - document, - presentation, - } - } - - pub fn document(&self) -> &RenderDocument { - &self.document - } - - pub fn presentation(&self) -> &RenderPresentation { - &self.presentation - } - - pub fn into_presentation(self) -> RenderPresentation { - self.presentation - } -} - -/// Cache slot for a presented body. Invisible to `PartialEq` / serde so record -/// identity stays `cooked` + metadata. -#[derive(Debug, Clone, Default)] -pub struct AttachedPresentation { - inner: Option>, -} - -impl AttachedPresentation { - pub fn none() -> Self { - Self { inner: None } - } - - pub fn some(document: std::sync::Arc) -> Self { - Self { - inner: Some(document), - } - } - - pub fn get(&self) -> Option<&PresentedDocument> { - self.inner.as_deref() - } - - pub fn arc(&self) -> Option> { - self.inner.clone() - } -} - -impl PartialEq for AttachedPresentation { - fn eq(&self, _: &Self) -> bool { - true - } -} - -impl Eq for AttachedPresentation {} - -impl Serialize for AttachedPresentation { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_none() - } -} - -impl<'de> Deserialize<'de> for AttachedPresentation { - fn deserialize>(_: D) -> Result { - Ok(Self::none()) - } -} - -const FNV_OFFSET: u64 = 0xcbf29ce484222325; -const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; - -fn fnv1a_update(hash: &mut u64, bytes: &[u8]) { - for byte in bytes { - *hash ^= u64::from(*byte); - *hash = hash.wrapping_mul(FNV_PRIME); - } -} - -fn hash_u64(hash: &mut u64, value: u64) { - fnv1a_update(hash, &value.to_le_bytes()); -} - -fn hash_u32(hash: &mut u64, value: u32) { - hash_u64(hash, u64::from(value)); -} - -fn hash_bool(hash: &mut u64, value: bool) { - hash_u64(hash, u64::from(value)); -} - -fn hash_str(hash: &mut u64, value: &str) { - hash_u64(hash, value.len() as u64); - fnv1a_update(hash, value.as_bytes()); -} - -fn hash_opt_str(hash: &mut u64, value: Option<&str>) { - match value { - Some(text) => { - hash_u64(hash, 1); - hash_str(hash, text); - } - None => hash_u64(hash, 0), - } -} - -fn hash_opt_u32(hash: &mut u64, value: Option) { - match value { - Some(number) => { - hash_u64(hash, 1); - hash_u32(hash, number); - } - None => hash_u64(hash, 0), - } -} - -fn hash_opt_u64(hash: &mut u64, value: Option) { - match value { - Some(number) => { - hash_u64(hash, 1); - hash_u64(hash, number); - } - None => hash_u64(hash, 0), - } -} - -pub fn presentation_checksum( - plain_text: &str, - image_attachments: &[RenderImageAttachment], - segments: &[RenderUiSegment], -) -> u64 { - let mut hash = FNV_OFFSET; - hash_str(&mut hash, plain_text); - hash_u64(&mut hash, image_attachments.len() as u64); - for attachment in image_attachments { - hash_str(&mut hash, &attachment.url); - hash_opt_str(&mut hash, attachment.alt_text.as_deref()); - hash_opt_u32(&mut hash, attachment.width); - hash_opt_u32(&mut hash, attachment.height); - } - hash_u64(&mut hash, segments.len() as u64); - for segment in segments { - hash_ui_segment(&mut hash, segment); - } - hash -} - -fn hash_ui_segment(hash: &mut u64, segment: &RenderUiSegment) { - match segment { - RenderUiSegment::Image(image) => { - hash_u64(hash, 1); - hash_str(hash, &image.url); - hash_opt_str(hash, image.alt_text.as_deref()); - hash_opt_u32(hash, image.width); - hash_opt_u32(hash, image.height); - } - RenderUiSegment::Onebox(card) => { - hash_u64(hash, 2); - hash_onebox_card(hash, card); - } - RenderUiSegment::Rich { nodes } => { - hash_u64(hash, 3); - hash_rich_children(hash, nodes); - } - } -} - -fn hash_onebox_card(hash: &mut u64, card: &RenderOneboxCard) { - hash_opt_str(hash, card.url.as_deref()); - hash_opt_str(hash, card.title.as_deref()); - hash_opt_str(hash, card.description.as_deref()); - hash_opt_str(hash, card.source_name.as_deref()); - hash_opt_str(hash, card.icon_url.as_deref()); - hash_opt_str(hash, card.thumbnail_url.as_deref()); - hash_opt_u32(hash, card.thumbnail_width); - hash_opt_u32(hash, card.thumbnail_height); -} - -fn hash_rich_children(hash: &mut u64, nodes: &[RenderRichNode]) { - hash_u64(hash, nodes.len() as u64); - for node in nodes { - hash_rich_node(hash, node); - } -} - -fn hash_rich_node(hash: &mut u64, node: &RenderRichNode) { - match node { - RenderRichNode::Text { content } => { - hash_u64(hash, 1); - hash_str(hash, content); - } - RenderRichNode::Bold { children } => { - hash_u64(hash, 2); - hash_rich_children(hash, children); - } - RenderRichNode::Italic { children } => { - hash_u64(hash, 3); - hash_rich_children(hash, children); - } - RenderRichNode::Strikethrough { children } => { - hash_u64(hash, 4); - hash_rich_children(hash, children); - } - RenderRichNode::Code { code } => { - hash_u64(hash, 5); - hash_str(hash, code); - } - RenderRichNode::CodeBlock { language, code } => { - hash_u64(hash, 6); - hash_opt_str(hash, language.as_deref()); - hash_str(hash, code); - } - RenderRichNode::Link { url, children } => { - hash_u64(hash, 7); - hash_str(hash, url); - hash_rich_children(hash, children); - } - RenderRichNode::Mention { username } => { - hash_u64(hash, 8); - hash_str(hash, username); - } - RenderRichNode::MentionGroup { name, url } => { - hash_u64(hash, 9); - hash_str(hash, name); - hash_str(hash, url); - } - RenderRichNode::Hashtag { text, url, kind } => { - hash_u64(hash, 10); - hash_str(hash, text); - hash_str(hash, url); - hash_opt_str(hash, kind.as_deref()); - } - RenderRichNode::Emoji { - url, - fallback_text, - only_emoji, - } => { - hash_u64(hash, 11); - hash_str(hash, url); - hash_str(hash, fallback_text); - hash_bool(hash, *only_emoji); - } - RenderRichNode::Heading { level, children } => { - hash_u64(hash, 12); - hash_u64(hash, u64::from(*level)); - hash_rich_children(hash, children); - } - RenderRichNode::Blockquote { children } => { - hash_u64(hash, 13); - hash_rich_children(hash, children); - } - RenderRichNode::Quote { - author, - post_number, - topic_id, - children, - } => { - hash_u64(hash, 14); - hash_opt_str(hash, author.as_deref()); - hash_opt_u32(hash, *post_number); - hash_opt_u64(hash, *topic_id); - hash_rich_children(hash, children); - } - RenderRichNode::List { ordered, items } => { - hash_u64(hash, 15); - hash_bool(hash, *ordered); - hash_u64(hash, items.len() as u64); - for item in items { - hash_rich_children(hash, item); - } - } - RenderRichNode::ListItem { children } => { - hash_u64(hash, 16); - hash_rich_children(hash, children); - } - RenderRichNode::Spoiler { children } => { - hash_u64(hash, 17); - hash_rich_children(hash, children); - } - RenderRichNode::Details { summary, children } => { - hash_u64(hash, 18); - hash_rich_children(hash, summary); - hash_rich_children(hash, children); - } - RenderRichNode::Table { text } => { - hash_u64(hash, 19); - hash_str(hash, text); - } - RenderRichNode::Video { url, title } => { - hash_u64(hash, 20); - hash_str(hash, url); - hash_opt_str(hash, title.as_deref()); - } - RenderRichNode::Divider => hash_u64(hash, 21), - RenderRichNode::LineBreak => hash_u64(hash, 22), - RenderRichNode::Paragraph { children } => { - hash_u64(hash, 23); - hash_rich_children(hash, children); - } - RenderRichNode::Image { - url, - alt, - width, - height, - } => { - hash_u64(hash, 24); - hash_str(hash, url); - hash_opt_str(hash, alt.as_deref()); - hash_opt_u32(hash, *width); - hash_opt_u32(hash, *height); - } - RenderRichNode::Onebox(card) => { - hash_u64(hash, 25); - hash_onebox_card(hash, card); - } - } -} diff --git a/crates/fire-models/src/rich_text/checksum.rs b/crates/fire-models/src/rich_text/checksum.rs new file mode 100644 index 00000000..6906c099 --- /dev/null +++ b/crates/fire-models/src/rich_text/checksum.rs @@ -0,0 +1,248 @@ +const FNV_OFFSET: u64 = 0xcbf29ce484222325; +const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; + +fn fnv1a_update(hash: &mut u64, bytes: &[u8]) { + for byte in bytes { + *hash ^= u64::from(*byte); + *hash = hash.wrapping_mul(FNV_PRIME); + } +} + +fn hash_u64(hash: &mut u64, value: u64) { + fnv1a_update(hash, &value.to_le_bytes()); +} + +fn hash_u32(hash: &mut u64, value: u32) { + hash_u64(hash, u64::from(value)); +} + +fn hash_bool(hash: &mut u64, value: bool) { + hash_u64(hash, u64::from(value)); +} + +fn hash_str(hash: &mut u64, value: &str) { + hash_u64(hash, value.len() as u64); + fnv1a_update(hash, value.as_bytes()); +} + +fn hash_opt_str(hash: &mut u64, value: Option<&str>) { + match value { + Some(text) => { + hash_u64(hash, 1); + hash_str(hash, text); + } + None => hash_u64(hash, 0), + } +} + +fn hash_opt_u32(hash: &mut u64, value: Option) { + match value { + Some(number) => { + hash_u64(hash, 1); + hash_u32(hash, number); + } + None => hash_u64(hash, 0), + } +} + +fn hash_opt_u64(hash: &mut u64, value: Option) { + match value { + Some(number) => { + hash_u64(hash, 1); + hash_u64(hash, number); + } + None => hash_u64(hash, 0), + } +} + +pub fn presentation_checksum( + plain_text: &str, + image_attachments: &[RenderImageAttachment], + segments: &[RenderUiSegment], +) -> u64 { + let mut hash = FNV_OFFSET; + hash_str(&mut hash, plain_text); + hash_u64(&mut hash, image_attachments.len() as u64); + for attachment in image_attachments { + hash_str(&mut hash, &attachment.url); + hash_opt_str(&mut hash, attachment.alt_text.as_deref()); + hash_opt_u32(&mut hash, attachment.width); + hash_opt_u32(&mut hash, attachment.height); + } + hash_u64(&mut hash, segments.len() as u64); + for segment in segments { + hash_ui_segment(&mut hash, segment); + } + hash +} + +fn hash_ui_segment(hash: &mut u64, segment: &RenderUiSegment) { + match segment { + RenderUiSegment::Image(image) => { + hash_u64(hash, 1); + hash_str(hash, &image.url); + hash_opt_str(hash, image.alt_text.as_deref()); + hash_opt_u32(hash, image.width); + hash_opt_u32(hash, image.height); + } + RenderUiSegment::Onebox(card) => { + hash_u64(hash, 2); + hash_onebox_card(hash, card); + } + RenderUiSegment::Rich { nodes } => { + hash_u64(hash, 3); + hash_rich_children(hash, nodes); + } + } +} + +fn hash_onebox_card(hash: &mut u64, card: &RenderOneboxCard) { + hash_opt_str(hash, card.url.as_deref()); + hash_opt_str(hash, card.title.as_deref()); + hash_opt_str(hash, card.description.as_deref()); + hash_opt_str(hash, card.source_name.as_deref()); + hash_opt_str(hash, card.icon_url.as_deref()); + hash_opt_str(hash, card.thumbnail_url.as_deref()); + hash_opt_u32(hash, card.thumbnail_width); + hash_opt_u32(hash, card.thumbnail_height); +} + +fn hash_rich_children(hash: &mut u64, nodes: &[RenderRichNode]) { + hash_u64(hash, nodes.len() as u64); + for node in nodes { + hash_rich_node(hash, node); + } +} + +fn hash_rich_node(hash: &mut u64, node: &RenderRichNode) { + match node { + RenderRichNode::Text { content } => { + hash_u64(hash, 1); + hash_str(hash, content); + } + RenderRichNode::Bold { children } => { + hash_u64(hash, 2); + hash_rich_children(hash, children); + } + RenderRichNode::Italic { children } => { + hash_u64(hash, 3); + hash_rich_children(hash, children); + } + RenderRichNode::Strikethrough { children } => { + hash_u64(hash, 4); + hash_rich_children(hash, children); + } + RenderRichNode::Code { code } => { + hash_u64(hash, 5); + hash_str(hash, code); + } + RenderRichNode::CodeBlock { language, code } => { + hash_u64(hash, 6); + hash_opt_str(hash, language.as_deref()); + hash_str(hash, code); + } + RenderRichNode::Link { url, children } => { + hash_u64(hash, 7); + hash_str(hash, url); + hash_rich_children(hash, children); + } + RenderRichNode::Mention { username } => { + hash_u64(hash, 8); + hash_str(hash, username); + } + RenderRichNode::MentionGroup { name, url } => { + hash_u64(hash, 9); + hash_str(hash, name); + hash_str(hash, url); + } + RenderRichNode::Hashtag { text, url, kind } => { + hash_u64(hash, 10); + hash_str(hash, text); + hash_str(hash, url); + hash_opt_str(hash, kind.as_deref()); + } + RenderRichNode::Emoji { + url, + fallback_text, + only_emoji, + } => { + hash_u64(hash, 11); + hash_str(hash, url); + hash_str(hash, fallback_text); + hash_bool(hash, *only_emoji); + } + RenderRichNode::Heading { level, children } => { + hash_u64(hash, 12); + hash_u64(hash, u64::from(*level)); + hash_rich_children(hash, children); + } + RenderRichNode::Blockquote { children } => { + hash_u64(hash, 13); + hash_rich_children(hash, children); + } + RenderRichNode::Quote { + author, + post_number, + topic_id, + children, + } => { + hash_u64(hash, 14); + hash_opt_str(hash, author.as_deref()); + hash_opt_u32(hash, *post_number); + hash_opt_u64(hash, *topic_id); + hash_rich_children(hash, children); + } + RenderRichNode::List { ordered, items } => { + hash_u64(hash, 15); + hash_bool(hash, *ordered); + hash_u64(hash, items.len() as u64); + for item in items { + hash_rich_children(hash, item); + } + } + RenderRichNode::ListItem { children } => { + hash_u64(hash, 16); + hash_rich_children(hash, children); + } + RenderRichNode::Spoiler { children } => { + hash_u64(hash, 17); + hash_rich_children(hash, children); + } + RenderRichNode::Details { summary, children } => { + hash_u64(hash, 18); + hash_rich_children(hash, summary); + hash_rich_children(hash, children); + } + RenderRichNode::Table { text } => { + hash_u64(hash, 19); + hash_str(hash, text); + } + RenderRichNode::Video { url, title } => { + hash_u64(hash, 20); + hash_str(hash, url); + hash_opt_str(hash, title.as_deref()); + } + RenderRichNode::Divider => hash_u64(hash, 21), + RenderRichNode::LineBreak => hash_u64(hash, 22), + RenderRichNode::Paragraph { children } => { + hash_u64(hash, 23); + hash_rich_children(hash, children); + } + RenderRichNode::Image { + url, + alt, + width, + height, + } => { + hash_u64(hash, 24); + hash_str(hash, url); + hash_opt_str(hash, alt.as_deref()); + hash_opt_u32(hash, *width); + hash_opt_u32(hash, *height); + } + RenderRichNode::Onebox(card) => { + hash_u64(hash, 25); + hash_onebox_card(hash, card); + } + } +} diff --git a/crates/fire-models/src/rich_text/cooked.rs b/crates/fire-models/src/rich_text/cooked.rs new file mode 100644 index 00000000..35760512 --- /dev/null +++ b/crates/fire-models/src/rich_text/cooked.rs @@ -0,0 +1,57 @@ +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum CookedHtmlNodeKind { + #[default] + Document, + Text, + Paragraph, + Heading, + LineBreak, + Strong, + Emphasis, + Strikethrough, + Link, + Image, + Emoji, + Code, + CodeBlock, + Blockquote, + DiscourseQuote, + Divider, + List, + ListItem, + Spoiler, + Details, + Table, + TableRow, + TableCell, + Onebox, + Iframe, + Mention, + Hashtag, + Attachment, + Unknown, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CookedHtmlNode { + pub id: u32, + pub parent_id: Option, + pub kind: CookedHtmlNodeKind, + pub depth: u32, + pub text: Option, + pub url: Option, + pub title: Option, + pub alt: Option, + pub level: Option, + pub ordered: Option, + pub attributes: BTreeMap, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CookedHtmlDocument { + pub nodes: Vec, + pub plain_text: String, + pub image_urls: Vec, + pub link_urls: Vec, +} + diff --git a/crates/fire-models/src/rich_text/mod.rs b/crates/fire-models/src/rich_text/mod.rs new file mode 100644 index 00000000..60d3f151 --- /dev/null +++ b/crates/fire-models/src/rich_text/mod.rs @@ -0,0 +1,9 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +include!("cooked.rs"); +include!("render_ir.rs"); +include!("ui.rs"); +include!("presentation.rs"); +include!("checksum.rs"); diff --git a/crates/fire-models/src/rich_text/presentation.rs b/crates/fire-models/src/rich_text/presentation.rs new file mode 100644 index 00000000..27ce43ec --- /dev/null +++ b/crates/fire-models/src/rich_text/presentation.rs @@ -0,0 +1,78 @@ +/// Runtime owner of render IR plus the host UI plan. +/// +/// Lives on domain posts as `Arc`. Serde caches must skip +/// it and re-present from `cooked` on cold start. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PresentedDocument { + document: RenderDocument, + presentation: RenderPresentation, +} + +impl PresentedDocument { + pub fn new(document: RenderDocument, presentation: RenderPresentation) -> Self { + Self { + document, + presentation, + } + } + + pub fn document(&self) -> &RenderDocument { + &self.document + } + + pub fn presentation(&self) -> &RenderPresentation { + &self.presentation + } + + pub fn into_presentation(self) -> RenderPresentation { + self.presentation + } +} + +/// Cache slot for a presented body. Invisible to `PartialEq` / serde so record +/// identity stays `cooked` + metadata. +#[derive(Debug, Clone, Default)] +pub struct AttachedPresentation { + inner: Option>, +} + +impl AttachedPresentation { + pub fn none() -> Self { + Self { inner: None } + } + + pub fn some(document: std::sync::Arc) -> Self { + Self { + inner: Some(document), + } + } + + pub fn get(&self) -> Option<&PresentedDocument> { + self.inner.as_deref() + } + + pub fn arc(&self) -> Option> { + self.inner.clone() + } +} + +impl PartialEq for AttachedPresentation { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl Eq for AttachedPresentation {} + +impl Serialize for AttachedPresentation { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_none() + } +} + +impl<'de> Deserialize<'de> for AttachedPresentation { + fn deserialize>(_: D) -> Result { + Ok(Self::none()) + } +} + diff --git a/crates/fire-models/src/rich_text/render_ir.rs b/crates/fire-models/src/rich_text/render_ir.rs new file mode 100644 index 00000000..49633226 --- /dev/null +++ b/crates/fire-models/src/rich_text/render_ir.rs @@ -0,0 +1,217 @@ +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RenderBlock { + pub id: u32, + pub parent_id: Option, + pub depth: u32, + pub kind: RenderBlockKind, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum RenderBlockKind { + Document, + Text { + content: String, + }, + Paragraph, + Heading { + level: u8, + }, + LineBreak, + Bold, + Italic, + Strikethrough, + InlineCode { + code: String, + }, + CodeBlock { + language: Option, + code: String, + }, + Link { + url: String, + }, + Mention { + username: String, + }, + MentionGroup { + name: String, + url: String, + }, + Hashtag { + text: String, + url: String, + kind: Option, + }, + Emoji { + url: String, + fallback_text: String, + only_emoji: bool, + }, + Image { + url: String, + alt: Option, + width: Option, + height: Option, + }, + Blockquote, + Quote { + author: Option, + post_number: Option, + topic_id: Option, + }, + List { + ordered: bool, + }, + ListItem, + Spoiler, + Details, + DetailsSummary, + Table { + text: String, + }, + Onebox { + url: Option, + title: Option, + description: Option, + #[serde(default)] + source_name: Option, + #[serde(default)] + icon_url: Option, + #[serde(default)] + thumbnail_url: Option, + #[serde(default)] + thumbnail_width: Option, + #[serde(default)] + thumbnail_height: Option, + }, + Video { + url: String, + title: Option, + }, + Divider, + #[default] + Unknown, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RenderImageAttachment { + pub url: String, + pub alt_text: Option, + pub width: Option, + pub height: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RenderDocument { + pub blocks: Vec, + pub plain_text: String, + pub image_attachments: Vec, +} + +/// Onebox card extracted as a first-class layout segment. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RenderOneboxCard { + pub url: Option, + pub title: Option, + pub description: Option, + pub source_name: Option, + pub icon_url: Option, + pub thumbnail_url: Option, + pub thumbnail_width: Option, + pub thumbnail_height: Option, +} + +/// Host-drawable rich node. Isomorphic to iOS/Android `FireRichTextNode`. +/// +/// This is a tree, not a flattened `RenderBlock` list: quote / list / details +/// keep their nesting so hosts map mechanically and do not rebuild IR. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum RenderRichNode { + Text { + content: String, + }, + Bold { + children: Vec, + }, + Italic { + children: Vec, + }, + Strikethrough { + children: Vec, + }, + Code { + code: String, + }, + CodeBlock { + language: Option, + code: String, + }, + Link { + url: String, + children: Vec, + }, + Mention { + username: String, + }, + MentionGroup { + name: String, + url: String, + }, + Hashtag { + text: String, + url: String, + kind: Option, + }, + Emoji { + url: String, + fallback_text: String, + only_emoji: bool, + }, + Heading { + level: u8, + children: Vec, + }, + Blockquote { + children: Vec, + }, + Quote { + author: Option, + post_number: Option, + topic_id: Option, + children: Vec, + }, + List { + ordered: bool, + items: Vec>, + }, + ListItem { + children: Vec, + }, + Spoiler { + children: Vec, + }, + Details { + summary: Vec, + children: Vec, + }, + Table { + text: String, + }, + Video { + url: String, + title: Option, + }, + Divider, + LineBreak, + Paragraph { + children: Vec, + }, + Image { + url: String, + alt: Option, + width: Option, + height: Option, + }, + Onebox(RenderOneboxCard), +} + diff --git a/crates/fire-models/src/rich_text/ui.rs b/crates/fire-models/src/rich_text/ui.rs new file mode 100644 index 00000000..96adabe1 --- /dev/null +++ b/crates/fire-models/src/rich_text/ui.rs @@ -0,0 +1,42 @@ +/// Host layout segment. Image and onebox are independent cells; everything +/// else stays in a rich node run. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum RenderUiSegment { + Rich { nodes: Vec }, + Image(RenderImageAttachment), + Onebox(RenderOneboxCard), +} + +/// UI-ready body produced from a `RenderDocument`. +/// +/// `checksum` is written once in `finish` and is the only content identity +/// hosts may cache on. `image_attachments` is still cloned from the IR in +/// Stage 1; Stage 2 can share the same allocation. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RenderPresentation { + pub checksum: u64, + pub plain_text: String, + pub image_attachments: Vec, + pub segments: Vec, +} + +impl RenderPresentation { + pub fn finish( + plain_text: String, + image_attachments: Vec, + segments: Vec, + ) -> Self { + let checksum = presentation_checksum(&plain_text, &image_attachments, &segments); + Self { + checksum, + plain_text, + image_attachments, + segments, + } + } + + pub fn is_empty(&self) -> bool { + self.segments.is_empty() && self.plain_text.trim().is_empty() + } +} + diff --git a/crates/fire-models/src/session.rs b/crates/fire-models/src/session.rs deleted file mode 100644 index 1ed86552..00000000 --- a/crates/fire-models/src/session.rs +++ /dev/null @@ -1,670 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use url::Url; - -use crate::cookie::{is_non_empty, merge_string_patch, CookieSnapshot, PlatformCookie}; -use crate::topic::TopicCategory; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct BootstrapArtifacts { - pub base_url: String, - pub discourse_base_uri: Option, - pub shared_session_key: Option, - pub current_username: Option, - pub current_user_id: Option, - pub notification_channel_position: Option, - pub long_polling_base_url: Option, - pub turnstile_sitekey: Option, - pub topic_tracking_state_meta: Option, - pub preloaded_json: Option, - pub has_preloaded_data: bool, - #[serde(default)] - pub has_site_metadata: bool, - #[serde(default)] - pub top_tags: Vec, - #[serde(default)] - pub can_tag_topics: bool, - #[serde(default)] - pub categories: Vec, - #[serde(default)] - pub has_site_settings: bool, - #[serde(default = "default_enabled_reaction_ids")] - pub enabled_reaction_ids: Vec, - #[serde(default = "default_min_post_length")] - pub min_post_length: u32, - #[serde(default = "default_min_topic_title_length")] - pub min_topic_title_length: u32, - #[serde(default = "default_min_first_post_length")] - pub min_first_post_length: u32, - #[serde(default = "default_min_personal_message_title_length")] - pub min_personal_message_title_length: u32, - #[serde(default = "default_min_personal_message_post_length")] - pub min_personal_message_post_length: u32, - pub default_composer_category: Option, -} - -impl Default for BootstrapArtifacts { - fn default() -> Self { - Self { - base_url: String::new(), - discourse_base_uri: None, - shared_session_key: None, - current_username: None, - current_user_id: None, - notification_channel_position: None, - long_polling_base_url: None, - turnstile_sitekey: None, - topic_tracking_state_meta: None, - preloaded_json: None, - has_preloaded_data: false, - has_site_metadata: false, - top_tags: Vec::new(), - can_tag_topics: false, - categories: Vec::new(), - has_site_settings: false, - enabled_reaction_ids: default_enabled_reaction_ids(), - min_post_length: default_min_post_length(), - min_topic_title_length: default_min_topic_title_length(), - min_first_post_length: default_min_first_post_length(), - min_personal_message_title_length: default_min_personal_message_title_length(), - min_personal_message_post_length: default_min_personal_message_post_length(), - default_composer_category: None, - } - } -} - -impl BootstrapArtifacts { - pub fn has_identity(&self) -> bool { - is_non_empty(self.current_username.as_deref()) - } - - pub fn merge_patch(&mut self, patch: &Self) { - if !patch.base_url.is_empty() { - self.base_url = patch.base_url.clone(); - } - - merge_string_patch( - &mut self.discourse_base_uri, - patch.discourse_base_uri.clone(), - ); - merge_string_patch( - &mut self.shared_session_key, - patch.shared_session_key.clone(), - ); - merge_string_patch(&mut self.current_username, patch.current_username.clone()); - merge_number_patch(&mut self.current_user_id, patch.current_user_id); - merge_number_patch( - &mut self.notification_channel_position, - patch.notification_channel_position, - ); - merge_string_patch( - &mut self.long_polling_base_url, - patch.long_polling_base_url.clone(), - ); - merge_string_patch(&mut self.turnstile_sitekey, patch.turnstile_sitekey.clone()); - merge_string_patch( - &mut self.topic_tracking_state_meta, - patch.topic_tracking_state_meta.clone(), - ); - - if let Some(preloaded_json) = patch.preloaded_json.clone() { - if preloaded_json.is_empty() { - self.preloaded_json = None; - self.has_preloaded_data = false; - self.has_site_metadata = false; - self.top_tags = Vec::new(); - self.can_tag_topics = false; - self.categories = Vec::new(); - self.has_site_settings = false; - self.enabled_reaction_ids = default_enabled_reaction_ids(); - self.min_post_length = default_min_post_length(); - self.min_topic_title_length = default_min_topic_title_length(); - self.min_first_post_length = default_min_first_post_length(); - self.min_personal_message_title_length = - default_min_personal_message_title_length(); - self.min_personal_message_post_length = default_min_personal_message_post_length(); - self.default_composer_category = None; - } else { - self.preloaded_json = Some(preloaded_json); - self.has_preloaded_data = true; - if patch.has_site_metadata { - self.has_site_metadata = true; - self.top_tags = normalized_top_tags(patch.top_tags.clone()); - self.can_tag_topics = patch.can_tag_topics; - self.categories = patch.categories.clone(); - } - if patch.has_site_settings { - self.has_site_settings = true; - self.enabled_reaction_ids = - normalized_enabled_reaction_ids(patch.enabled_reaction_ids.clone()); - self.min_post_length = patch.min_post_length.max(1); - self.min_topic_title_length = patch.min_topic_title_length.max(1); - self.min_first_post_length = patch.min_first_post_length.max(1); - self.min_personal_message_title_length = - patch.min_personal_message_title_length.max(1); - self.min_personal_message_post_length = - patch.min_personal_message_post_length.max(1); - self.default_composer_category = patch.default_composer_category; - } - } - } else if patch.has_preloaded_data { - self.has_preloaded_data = true; - if patch.has_site_metadata { - self.has_site_metadata = true; - self.top_tags = normalized_top_tags(patch.top_tags.clone()); - self.can_tag_topics = patch.can_tag_topics; - self.categories = patch.categories.clone(); - } - if patch.has_site_settings { - self.has_site_settings = true; - self.enabled_reaction_ids = - normalized_enabled_reaction_ids(patch.enabled_reaction_ids.clone()); - self.min_post_length = patch.min_post_length.max(1); - self.min_topic_title_length = patch.min_topic_title_length.max(1); - self.min_first_post_length = patch.min_first_post_length.max(1); - self.min_personal_message_title_length = - patch.min_personal_message_title_length.max(1); - self.min_personal_message_post_length = - patch.min_personal_message_post_length.max(1); - self.default_composer_category = patch.default_composer_category; - } - } - - if patch.preloaded_json.is_none() && !patch.has_preloaded_data { - if patch.has_site_metadata { - self.has_site_metadata = true; - self.top_tags = normalized_top_tags(patch.top_tags.clone()); - self.can_tag_topics = patch.can_tag_topics; - self.categories = patch.categories.clone(); - } - if patch.has_site_settings { - self.has_site_settings = true; - self.enabled_reaction_ids = - normalized_enabled_reaction_ids(patch.enabled_reaction_ids.clone()); - self.min_post_length = patch.min_post_length.max(1); - self.min_topic_title_length = patch.min_topic_title_length.max(1); - self.min_first_post_length = patch.min_first_post_length.max(1); - self.min_personal_message_title_length = - patch.min_personal_message_title_length.max(1); - self.min_personal_message_post_length = - patch.min_personal_message_post_length.max(1); - self.default_composer_category = patch.default_composer_category; - } - } - } - - pub fn clear_login_state(&mut self) { - self.shared_session_key = None; - self.current_username = None; - self.current_user_id = None; - self.notification_channel_position = None; - self.long_polling_base_url = None; - self.topic_tracking_state_meta = None; - self.preloaded_json = None; - self.has_preloaded_data = false; - self.has_site_metadata = false; - self.top_tags = Vec::new(); - self.can_tag_topics = false; - self.categories = Vec::new(); - self.has_site_settings = false; - self.enabled_reaction_ids = default_enabled_reaction_ids(); - self.min_post_length = default_min_post_length(); - self.min_topic_title_length = default_min_topic_title_length(); - self.min_first_post_length = default_min_first_post_length(); - self.min_personal_message_title_length = default_min_personal_message_title_length(); - self.min_personal_message_post_length = default_min_personal_message_post_length(); - self.default_composer_category = None; - } -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum LoginPhase { - #[default] - Anonymous, - CookiesCaptured, - BootstrapCaptured, - Ready, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SessionReadiness { - pub has_login_cookie: bool, - pub has_forum_session: bool, - pub has_cloudflare_clearance: bool, - pub has_csrf_token: bool, - pub has_current_user: bool, - pub has_preloaded_data: bool, - pub has_shared_session_key: bool, - pub can_read_authenticated_api: bool, - pub can_write_authenticated_api: bool, - pub can_open_message_bus: bool, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct LoginSyncInput { - pub current_url: Option, - pub username: Option, - pub csrf_token: Option, - pub home_html: Option, - #[serde(default)] - pub browser_user_agent: Option, - pub cookies: Vec, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum WebViewLoginPhase { - Csrf, - Hcaptcha, - Session, - Exception, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct WebViewLoginJsResult { - pub phase: WebViewLoginPhase, - pub status: u16, - pub body: String, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum LoginFailureKind { - InvalidCredentials, - NotActivated, - NotApproved, - PasswordExpired, - Network, - Unknown, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct LoginFailure { - pub kind: LoginFailureKind, - pub message: Option, - pub sent_to_email: Option, - pub current_email: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SecondFactorRequirement { - pub totp_enabled: bool, - pub security_key_enabled: bool, - pub backup_enabled: bool, - pub message: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum WebViewLoginDecision { - Success, - NeedSecondFactor(SecondFactorRequirement), - RetryCloudflare, - Failure(LoginFailure), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum CloudflareRequestMode { - Silent, - Action, - Data, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SessionSnapshot { - pub cookies: CookieSnapshot, - pub bootstrap: BootstrapArtifacts, - #[serde(default)] - pub browser_user_agent: Option, - /// Wake-up copy for `SessionState::from_snapshot`. Not persisted and not part of - /// `snapshot_revision`. The authoritative value lives on `FireSessionRuntimeState`. - #[serde(skip)] - pub read_path_login_request: Option, -} - -impl SessionSnapshot { - pub fn readiness(&self) -> SessionReadiness { - let has_login_cookie = self.cookies.has_login_session(); - let has_forum_session = self.cookies.has_forum_session(); - let has_cloudflare_clearance = self.cookies.has_cloudflare_clearance(); - let has_csrf_token = self.cookies.has_csrf_token(); - let has_current_user = self.bootstrap.has_identity(); - let has_preloaded_data = self.bootstrap.has_preloaded_data; - let has_shared_session_key = is_non_empty(self.bootstrap.shared_session_key.as_deref()); - let can_read_authenticated_api = self.cookies.can_authenticate_requests(); - let can_write_authenticated_api = can_read_authenticated_api && has_csrf_token; - let can_open_message_bus = can_read_authenticated_api - && (!message_bus_requires_shared_session_key(&self.bootstrap) - || has_shared_session_key); - - SessionReadiness { - has_login_cookie, - has_forum_session, - has_cloudflare_clearance, - has_csrf_token, - has_current_user, - has_preloaded_data, - has_shared_session_key, - can_read_authenticated_api, - can_write_authenticated_api, - can_open_message_bus, - } - } - - pub fn login_phase(&self) -> LoginPhase { - let readiness = self.readiness(); - if !readiness.has_login_cookie { - return LoginPhase::Anonymous; - } - if !readiness.can_read_authenticated_api || !readiness.has_current_user { - return LoginPhase::CookiesCaptured; - } - if !readiness.can_write_authenticated_api - || !readiness.has_preloaded_data - || !self.bootstrap.has_site_metadata - || !self.bootstrap.has_site_settings - { - return LoginPhase::BootstrapCaptured; - } - LoginPhase::Ready - } - - pub fn profile_display_name(&self) -> String { - if let Some(current_username) = self - .bootstrap - .current_username - .as_deref() - .filter(|value| !value.is_empty()) - { - return current_username.to_string(); - } - - let readiness = self.readiness(); - if readiness.can_read_authenticated_api || self.cookies.has_login_session() { - "会话已连接".to_string() - } else { - "未登录".to_string() - } - } - - pub fn login_phase_label(&self) -> String { - let readiness = self.readiness(); - if readiness.can_read_authenticated_api && !readiness.has_current_user { - "账号信息同步中".to_string() - } else { - self.login_phase().title().to_string() - } - } - - pub fn clear_login_state(&mut self, preserve_cf_clearance: bool) { - self.cookies.clear_login_state(preserve_cf_clearance); - self.bootstrap.clear_login_state(); - } -} - -impl LoginPhase { - pub fn title(self) -> &'static str { - match self { - Self::Anonymous => "未登录", - Self::CookiesCaptured => "Cookie 已同步", - Self::BootstrapCaptured => "会话初始化中", - Self::Ready => "已就绪", - } - } -} - -fn merge_number_patch(slot: &mut Option, patch: Option) -where - T: Copy, -{ - if let Some(value) = patch { - *slot = Some(value); - } -} - -fn message_bus_requires_shared_session_key(bootstrap: &BootstrapArtifacts) -> bool { - let Some(base_origin) = request_origin(&bootstrap.base_url) else { - return false; - }; - let Some(long_polling_base_url) = bootstrap - .long_polling_base_url - .as_deref() - .filter(|value| !value.is_empty()) - else { - return false; - }; - let Some(poll_origin) = request_origin(long_polling_base_url) else { - return false; - }; - - base_origin != poll_origin -} - -fn request_origin(value: &str) -> Option { - let mut url = Url::parse(value).ok()?; - url.set_path(""); - url.set_query(None); - url.set_fragment(None); - Some(url.as_str().trim_end_matches('/').to_string()) -} - -fn default_enabled_reaction_ids() -> Vec { - vec!["heart".to_string()] -} - -fn default_min_post_length() -> u32 { - 1 -} - -fn default_min_topic_title_length() -> u32 { - 15 -} - -fn default_min_first_post_length() -> u32 { - 20 -} - -fn default_min_personal_message_title_length() -> u32 { - 2 -} - -fn default_min_personal_message_post_length() -> u32 { - 10 -} - -fn normalized_enabled_reaction_ids(ids: Vec) -> Vec { - let mut normalized = Vec::new(); - for id in ids { - let trimmed = id.trim(); - if trimmed.is_empty() || normalized.iter().any(|existing| existing == trimmed) { - continue; - } - normalized.push(trimmed.to_string()); - } - - if normalized.is_empty() { - default_enabled_reaction_ids() - } else { - normalized - } -} - -fn normalized_top_tags(tags: Vec) -> Vec { - let mut normalized = Vec::new(); - for tag in tags { - let trimmed = tag.trim(); - if trimmed.is_empty() || normalized.iter().any(|existing| existing == trimmed) { - continue; - } - normalized.push(trimmed.to_string()); - } - normalized -} - -#[derive(Debug, Clone)] -pub struct LoginFinalizationResult { - pub success: bool, - pub session: SessionSnapshot, - pub t_token_verified: bool, - pub fingerprint_wait_needed: bool, -} - -#[derive(Debug, Clone)] -pub struct PassiveLogoutTrigger { - pub source: String, - pub signal_strength: SignalStrength, - pub cookie_diagnostic: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum SignalStrength { - Strong, - Weak, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum AuthRuntimeSignalStrength { - Diagnostic, - Weak, - Strong, - Terminal, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum AuthRuntimeSignalSource { - HttpResponse, - SetCookieIngress, - Probe, - StartupAuthority, - PlatformSync, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum AuthRuntimeSignalKind { - NotLoggedInBody, - DiscourseLoggedOutHeader, - MixedLoggedOutHeader, - AuthCookieDeletion, - MixedSignalCookieDeletionBlocked, - InvalidAccessForbidden, - BadCsrf, - CloudflareChallenge, - RateLimit, - ProbeValid, - ProbeInvalid, - ProbeInconclusive, - ProbeInconclusiveEscalated, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct AuthRuntimeSignal { - pub kind: AuthRuntimeSignalKind, - pub strength: AuthRuntimeSignalStrength, - pub source: AuthRuntimeSignalSource, - pub operation: Option, - pub status: Option, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum ProbeResult { - Valid { username: String }, - Invalid, - Inconclusive, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CloudflareChallengeRequest { - pub operation: String, - pub request_url: String, - pub origin_url: Option, - pub is_foreground: bool, - pub session_epoch: u64, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CloudflareChallengeResult { - pub completed: bool, - pub user_cancelled: bool, - pub fresh_cf_clearance: Option, - pub cookies: Vec, - pub browser_user_agent: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum CookieSelfHealingPhase { - Sweep, - NuclearReset, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CookieSelfHealingRequest { - pub operation: String, - pub request_url: String, - pub target_url: String, - pub phase: CookieSelfHealingPhase, - pub attempt: u8, - pub cookie_names: Vec, - pub session_epoch: u64, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CookieSelfHealingResult { - pub completed: bool, - pub session_epoch: u64, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct PreloadedDataResult { - pub current_user: Option, - pub site_settings: Option, - pub site: Option, - pub topic_tracking_state_meta: Option>, - pub topic_tracking_states: Option>, - pub custom_emoji: Option>, - pub topic_list: Option, - pub enabled_reaction_ids: Vec, - pub categories: Vec, - pub top_tags: Vec, - pub can_tag_topics: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PreloadedDataState { - NotStarted, - Loading, - Ready, - Failed, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RefreshTrigger { - LoginCompleted, - LogoutCompleted, - SessionRestored, - /// Full session rebuild after a successful Cloudflare challenge. - CloudflareResolved, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CloudflareClearanceResolvedEvent { - pub generation: u64, - pub has_login_session: bool, - pub can_open_message_bus: bool, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RefreshBatch { - Core, - Secondary, -} - -#[derive(Debug, Clone)] -pub struct AppStateRefreshEvent { - pub batch: RefreshBatch, - pub trigger: RefreshTrigger, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum LoginStateDetermination { - LoggedIn { username: String, user_id: u64 }, - NotLoggedIn, - SessionExpired, - NetworkErrorPreserveState, -} diff --git a/crates/fire-models/src/session/auth_signal.rs b/crates/fire-models/src/session/auth_signal.rs new file mode 100644 index 00000000..43b22faa --- /dev/null +++ b/crates/fire-models/src/session/auth_signal.rs @@ -0,0 +1,64 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone)] +pub struct PassiveLogoutTrigger { + pub source: String, + pub signal_strength: SignalStrength, + pub cookie_diagnostic: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum SignalStrength { + Strong, + Weak, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthRuntimeSignalStrength { + Diagnostic, + Weak, + Strong, + Terminal, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthRuntimeSignalSource { + HttpResponse, + SetCookieIngress, + Probe, + StartupAuthority, + PlatformSync, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthRuntimeSignalKind { + NotLoggedInBody, + DiscourseLoggedOutHeader, + MixedLoggedOutHeader, + AuthCookieDeletion, + MixedSignalCookieDeletionBlocked, + InvalidAccessForbidden, + BadCsrf, + CloudflareChallenge, + RateLimit, + ProbeValid, + ProbeInvalid, + ProbeInconclusive, + ProbeInconclusiveEscalated, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AuthRuntimeSignal { + pub kind: AuthRuntimeSignalKind, + pub strength: AuthRuntimeSignalStrength, + pub source: AuthRuntimeSignalSource, + pub operation: Option, + pub status: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ProbeResult { + Valid { username: String }, + Invalid, + Inconclusive, +} diff --git a/crates/fire-models/src/session/bootstrap.rs b/crates/fire-models/src/session/bootstrap.rs new file mode 100644 index 00000000..0846d545 --- /dev/null +++ b/crates/fire-models/src/session/bootstrap.rs @@ -0,0 +1,278 @@ +use serde::{Deserialize, Serialize}; + +use crate::cookie::{is_non_empty, merge_string_patch}; +use crate::topic::TopicCategory; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct BootstrapArtifacts { + pub base_url: String, + pub discourse_base_uri: Option, + pub shared_session_key: Option, + pub current_username: Option, + pub current_user_id: Option, + pub notification_channel_position: Option, + pub long_polling_base_url: Option, + pub turnstile_sitekey: Option, + pub topic_tracking_state_meta: Option, + pub preloaded_json: Option, + pub has_preloaded_data: bool, + #[serde(default)] + pub has_site_metadata: bool, + #[serde(default)] + pub top_tags: Vec, + #[serde(default)] + pub can_tag_topics: bool, + #[serde(default)] + pub categories: Vec, + #[serde(default)] + pub has_site_settings: bool, + #[serde(default = "default_enabled_reaction_ids")] + pub enabled_reaction_ids: Vec, + #[serde(default = "default_min_post_length")] + pub min_post_length: u32, + #[serde(default = "default_min_topic_title_length")] + pub min_topic_title_length: u32, + #[serde(default = "default_min_first_post_length")] + pub min_first_post_length: u32, + #[serde(default = "default_min_personal_message_title_length")] + pub min_personal_message_title_length: u32, + #[serde(default = "default_min_personal_message_post_length")] + pub min_personal_message_post_length: u32, + pub default_composer_category: Option, +} + +impl Default for BootstrapArtifacts { + fn default() -> Self { + Self { + base_url: String::new(), + discourse_base_uri: None, + shared_session_key: None, + current_username: None, + current_user_id: None, + notification_channel_position: None, + long_polling_base_url: None, + turnstile_sitekey: None, + topic_tracking_state_meta: None, + preloaded_json: None, + has_preloaded_data: false, + has_site_metadata: false, + top_tags: Vec::new(), + can_tag_topics: false, + categories: Vec::new(), + has_site_settings: false, + enabled_reaction_ids: default_enabled_reaction_ids(), + min_post_length: default_min_post_length(), + min_topic_title_length: default_min_topic_title_length(), + min_first_post_length: default_min_first_post_length(), + min_personal_message_title_length: default_min_personal_message_title_length(), + min_personal_message_post_length: default_min_personal_message_post_length(), + default_composer_category: None, + } + } +} + +impl BootstrapArtifacts { + pub fn has_identity(&self) -> bool { + is_non_empty(self.current_username.as_deref()) + } + + pub fn merge_patch(&mut self, patch: &Self) { + if !patch.base_url.is_empty() { + self.base_url = patch.base_url.clone(); + } + + merge_string_patch( + &mut self.discourse_base_uri, + patch.discourse_base_uri.clone(), + ); + merge_string_patch( + &mut self.shared_session_key, + patch.shared_session_key.clone(), + ); + merge_string_patch(&mut self.current_username, patch.current_username.clone()); + merge_number_patch(&mut self.current_user_id, patch.current_user_id); + merge_number_patch( + &mut self.notification_channel_position, + patch.notification_channel_position, + ); + merge_string_patch( + &mut self.long_polling_base_url, + patch.long_polling_base_url.clone(), + ); + merge_string_patch(&mut self.turnstile_sitekey, patch.turnstile_sitekey.clone()); + merge_string_patch( + &mut self.topic_tracking_state_meta, + patch.topic_tracking_state_meta.clone(), + ); + + if let Some(preloaded_json) = patch.preloaded_json.clone() { + if preloaded_json.is_empty() { + self.preloaded_json = None; + self.has_preloaded_data = false; + self.has_site_metadata = false; + self.top_tags = Vec::new(); + self.can_tag_topics = false; + self.categories = Vec::new(); + self.has_site_settings = false; + self.enabled_reaction_ids = default_enabled_reaction_ids(); + self.min_post_length = default_min_post_length(); + self.min_topic_title_length = default_min_topic_title_length(); + self.min_first_post_length = default_min_first_post_length(); + self.min_personal_message_title_length = + default_min_personal_message_title_length(); + self.min_personal_message_post_length = default_min_personal_message_post_length(); + self.default_composer_category = None; + } else { + self.preloaded_json = Some(preloaded_json); + self.has_preloaded_data = true; + if patch.has_site_metadata { + self.has_site_metadata = true; + self.top_tags = normalized_top_tags(patch.top_tags.clone()); + self.can_tag_topics = patch.can_tag_topics; + self.categories = patch.categories.clone(); + } + if patch.has_site_settings { + self.has_site_settings = true; + self.enabled_reaction_ids = + normalized_enabled_reaction_ids(patch.enabled_reaction_ids.clone()); + self.min_post_length = patch.min_post_length.max(1); + self.min_topic_title_length = patch.min_topic_title_length.max(1); + self.min_first_post_length = patch.min_first_post_length.max(1); + self.min_personal_message_title_length = + patch.min_personal_message_title_length.max(1); + self.min_personal_message_post_length = + patch.min_personal_message_post_length.max(1); + self.default_composer_category = patch.default_composer_category; + } + } + } else if patch.has_preloaded_data { + self.has_preloaded_data = true; + if patch.has_site_metadata { + self.has_site_metadata = true; + self.top_tags = normalized_top_tags(patch.top_tags.clone()); + self.can_tag_topics = patch.can_tag_topics; + self.categories = patch.categories.clone(); + } + if patch.has_site_settings { + self.has_site_settings = true; + self.enabled_reaction_ids = + normalized_enabled_reaction_ids(patch.enabled_reaction_ids.clone()); + self.min_post_length = patch.min_post_length.max(1); + self.min_topic_title_length = patch.min_topic_title_length.max(1); + self.min_first_post_length = patch.min_first_post_length.max(1); + self.min_personal_message_title_length = + patch.min_personal_message_title_length.max(1); + self.min_personal_message_post_length = + patch.min_personal_message_post_length.max(1); + self.default_composer_category = patch.default_composer_category; + } + } + + if patch.preloaded_json.is_none() && !patch.has_preloaded_data { + if patch.has_site_metadata { + self.has_site_metadata = true; + self.top_tags = normalized_top_tags(patch.top_tags.clone()); + self.can_tag_topics = patch.can_tag_topics; + self.categories = patch.categories.clone(); + } + if patch.has_site_settings { + self.has_site_settings = true; + self.enabled_reaction_ids = + normalized_enabled_reaction_ids(patch.enabled_reaction_ids.clone()); + self.min_post_length = patch.min_post_length.max(1); + self.min_topic_title_length = patch.min_topic_title_length.max(1); + self.min_first_post_length = patch.min_first_post_length.max(1); + self.min_personal_message_title_length = + patch.min_personal_message_title_length.max(1); + self.min_personal_message_post_length = + patch.min_personal_message_post_length.max(1); + self.default_composer_category = patch.default_composer_category; + } + } + } + + pub fn clear_login_state(&mut self) { + self.shared_session_key = None; + self.current_username = None; + self.current_user_id = None; + self.notification_channel_position = None; + self.long_polling_base_url = None; + self.topic_tracking_state_meta = None; + self.preloaded_json = None; + self.has_preloaded_data = false; + self.has_site_metadata = false; + self.top_tags = Vec::new(); + self.can_tag_topics = false; + self.categories = Vec::new(); + self.has_site_settings = false; + self.enabled_reaction_ids = default_enabled_reaction_ids(); + self.min_post_length = default_min_post_length(); + self.min_topic_title_length = default_min_topic_title_length(); + self.min_first_post_length = default_min_first_post_length(); + self.min_personal_message_title_length = default_min_personal_message_title_length(); + self.min_personal_message_post_length = default_min_personal_message_post_length(); + self.default_composer_category = None; + } +} + +fn merge_number_patch(slot: &mut Option, patch: Option) +where + T: Copy, +{ + if let Some(value) = patch { + *slot = Some(value); + } +} + +fn default_enabled_reaction_ids() -> Vec { + vec!["heart".to_string()] +} + +fn default_min_post_length() -> u32 { + 1 +} + +fn default_min_topic_title_length() -> u32 { + 15 +} + +fn default_min_first_post_length() -> u32 { + 20 +} + +fn default_min_personal_message_title_length() -> u32 { + 2 +} + +fn default_min_personal_message_post_length() -> u32 { + 10 +} + +fn normalized_enabled_reaction_ids(ids: Vec) -> Vec { + let mut normalized = Vec::new(); + for id in ids { + let trimmed = id.trim(); + if trimmed.is_empty() || normalized.iter().any(|existing| existing == trimmed) { + continue; + } + normalized.push(trimmed.to_string()); + } + + if normalized.is_empty() { + default_enabled_reaction_ids() + } else { + normalized + } +} + +fn normalized_top_tags(tags: Vec) -> Vec { + let mut normalized = Vec::new(); + for tag in tags { + let trimmed = tag.trim(); + if trimmed.is_empty() || normalized.iter().any(|existing| existing == trimmed) { + continue; + } + normalized.push(trimmed.to_string()); + } + normalized +} diff --git a/crates/fire-models/src/session/challenge.rs b/crates/fire-models/src/session/challenge.rs new file mode 100644 index 00000000..5cb62f81 --- /dev/null +++ b/crates/fire-models/src/session/challenge.rs @@ -0,0 +1,35 @@ +use serde::{Deserialize, Serialize}; + +use crate::cookie::PlatformCookie; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum CloudflareRequestMode { + Silent, + Action, + Data, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CloudflareChallengeRequest { + pub operation: String, + pub request_url: String, + pub origin_url: Option, + pub is_foreground: bool, + pub session_epoch: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CloudflareChallengeResult { + pub completed: bool, + pub user_cancelled: bool, + pub fresh_cf_clearance: Option, + pub cookies: Vec, + pub browser_user_agent: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CloudflareClearanceResolvedEvent { + pub generation: u64, + pub has_login_session: bool, + pub can_open_message_bus: bool, +} diff --git a/crates/fire-models/src/session/healing.rs b/crates/fire-models/src/session/healing.rs new file mode 100644 index 00000000..e8e0bd81 --- /dev/null +++ b/crates/fire-models/src/session/healing.rs @@ -0,0 +1,24 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum CookieSelfHealingPhase { + Sweep, + NuclearReset, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CookieSelfHealingRequest { + pub operation: String, + pub request_url: String, + pub target_url: String, + pub phase: CookieSelfHealingPhase, + pub attempt: u8, + pub cookie_names: Vec, + pub session_epoch: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CookieSelfHealingResult { + pub completed: bool, + pub session_epoch: u64, +} diff --git a/crates/fire-models/src/session/login.rs b/crates/fire-models/src/session/login.rs new file mode 100644 index 00000000..84de8ec9 --- /dev/null +++ b/crates/fire-models/src/session/login.rs @@ -0,0 +1,80 @@ +use serde::{Deserialize, Serialize}; + +use super::snapshot::SessionSnapshot; +use crate::cookie::PlatformCookie; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct LoginSyncInput { + pub current_url: Option, + pub username: Option, + pub csrf_token: Option, + pub home_html: Option, + #[serde(default)] + pub browser_user_agent: Option, + pub cookies: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum WebViewLoginPhase { + Csrf, + Hcaptcha, + Session, + Exception, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WebViewLoginJsResult { + pub phase: WebViewLoginPhase, + pub status: u16, + pub body: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum LoginFailureKind { + InvalidCredentials, + NotActivated, + NotApproved, + PasswordExpired, + Network, + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LoginFailure { + pub kind: LoginFailureKind, + pub message: Option, + pub sent_to_email: Option, + pub current_email: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SecondFactorRequirement { + pub totp_enabled: bool, + pub security_key_enabled: bool, + pub backup_enabled: bool, + pub message: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum WebViewLoginDecision { + Success, + NeedSecondFactor(SecondFactorRequirement), + RetryCloudflare, + Failure(LoginFailure), +} + +#[derive(Debug, Clone)] +pub struct LoginFinalizationResult { + pub success: bool, + pub session: SessionSnapshot, + pub t_token_verified: bool, + pub fingerprint_wait_needed: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum LoginStateDetermination { + LoggedIn { username: String, user_id: u64 }, + NotLoggedIn, + SessionExpired, + NetworkErrorPreserveState, +} diff --git a/crates/fire-models/src/session/mod.rs b/crates/fire-models/src/session/mod.rs new file mode 100644 index 00000000..847b149f --- /dev/null +++ b/crates/fire-models/src/session/mod.rs @@ -0,0 +1,18 @@ +mod auth_signal; +mod bootstrap; +mod challenge; +mod healing; +mod login; +mod refresh; +mod snapshot; + +pub use auth_signal::*; +pub use bootstrap::*; +pub use challenge::*; +pub use healing::*; +pub use login::*; +pub use refresh::*; +pub use snapshot::*; + +#[cfg(test)] +mod tests; diff --git a/crates/fire-models/src/session/refresh.rs b/crates/fire-models/src/session/refresh.rs new file mode 100644 index 00000000..2ed0f0fe --- /dev/null +++ b/crates/fire-models/src/session/refresh.rs @@ -0,0 +1,49 @@ +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +use crate::topic::TopicCategory; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct PreloadedDataResult { + pub current_user: Option, + pub site_settings: Option, + pub site: Option, + pub topic_tracking_state_meta: Option>, + pub topic_tracking_states: Option>, + pub custom_emoji: Option>, + pub topic_list: Option, + pub enabled_reaction_ids: Vec, + pub categories: Vec, + pub top_tags: Vec, + pub can_tag_topics: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PreloadedDataState { + NotStarted, + Loading, + Ready, + Failed, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RefreshTrigger { + LoginCompleted, + LogoutCompleted, + SessionRestored, + /// Full session rebuild after a successful Cloudflare challenge. + CloudflareResolved, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RefreshBatch { + Core, + Secondary, +} + +#[derive(Debug, Clone)] +pub struct AppStateRefreshEvent { + pub batch: RefreshBatch, + pub trigger: RefreshTrigger, +} diff --git a/crates/fire-models/src/session/snapshot.rs b/crates/fire-models/src/session/snapshot.rs new file mode 100644 index 00000000..f54d4d0d --- /dev/null +++ b/crates/fire-models/src/session/snapshot.rs @@ -0,0 +1,157 @@ +use serde::{Deserialize, Serialize}; +use url::Url; + +use super::bootstrap::BootstrapArtifacts; +use crate::cookie::{is_non_empty, CookieSnapshot}; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum LoginPhase { + #[default] + Anonymous, + CookiesCaptured, + BootstrapCaptured, + Ready, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionReadiness { + pub has_login_cookie: bool, + pub has_forum_session: bool, + pub has_cloudflare_clearance: bool, + pub has_csrf_token: bool, + pub has_current_user: bool, + pub has_preloaded_data: bool, + pub has_shared_session_key: bool, + pub can_read_authenticated_api: bool, + pub can_write_authenticated_api: bool, + pub can_open_message_bus: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionSnapshot { + pub cookies: CookieSnapshot, + pub bootstrap: BootstrapArtifacts, + #[serde(default)] + pub browser_user_agent: Option, + /// Wake-up copy for `SessionState::from_snapshot`. Not persisted and not part of + /// `snapshot_revision`. The authoritative value lives on `FireSessionRuntimeState`. + #[serde(skip)] + pub read_path_login_request: Option, +} + +impl SessionSnapshot { + pub fn readiness(&self) -> SessionReadiness { + let has_login_cookie = self.cookies.has_login_session(); + let has_forum_session = self.cookies.has_forum_session(); + let has_cloudflare_clearance = self.cookies.has_cloudflare_clearance(); + let has_csrf_token = self.cookies.has_csrf_token(); + let has_current_user = self.bootstrap.has_identity(); + let has_preloaded_data = self.bootstrap.has_preloaded_data; + let has_shared_session_key = is_non_empty(self.bootstrap.shared_session_key.as_deref()); + let can_read_authenticated_api = self.cookies.can_authenticate_requests(); + let can_write_authenticated_api = can_read_authenticated_api && has_csrf_token; + let can_open_message_bus = can_read_authenticated_api + && (!message_bus_requires_shared_session_key(&self.bootstrap) + || has_shared_session_key); + + SessionReadiness { + has_login_cookie, + has_forum_session, + has_cloudflare_clearance, + has_csrf_token, + has_current_user, + has_preloaded_data, + has_shared_session_key, + can_read_authenticated_api, + can_write_authenticated_api, + can_open_message_bus, + } + } + + pub fn login_phase(&self) -> LoginPhase { + let readiness = self.readiness(); + if !readiness.has_login_cookie { + return LoginPhase::Anonymous; + } + if !readiness.can_read_authenticated_api || !readiness.has_current_user { + return LoginPhase::CookiesCaptured; + } + if !readiness.can_write_authenticated_api + || !readiness.has_preloaded_data + || !self.bootstrap.has_site_metadata + || !self.bootstrap.has_site_settings + { + return LoginPhase::BootstrapCaptured; + } + LoginPhase::Ready + } + + pub fn profile_display_name(&self) -> String { + if let Some(current_username) = self + .bootstrap + .current_username + .as_deref() + .filter(|value| !value.is_empty()) + { + return current_username.to_string(); + } + + let readiness = self.readiness(); + if readiness.can_read_authenticated_api || self.cookies.has_login_session() { + "会话已连接".to_string() + } else { + "未登录".to_string() + } + } + + pub fn login_phase_label(&self) -> String { + let readiness = self.readiness(); + if readiness.can_read_authenticated_api && !readiness.has_current_user { + "账号信息同步中".to_string() + } else { + self.login_phase().title().to_string() + } + } + + pub fn clear_login_state(&mut self, preserve_cf_clearance: bool) { + self.cookies.clear_login_state(preserve_cf_clearance); + self.bootstrap.clear_login_state(); + } +} + +impl LoginPhase { + pub fn title(self) -> &'static str { + match self { + Self::Anonymous => "未登录", + Self::CookiesCaptured => "Cookie 已同步", + Self::BootstrapCaptured => "会话初始化中", + Self::Ready => "已就绪", + } + } +} + +fn message_bus_requires_shared_session_key(bootstrap: &BootstrapArtifacts) -> bool { + let Some(base_origin) = request_origin(&bootstrap.base_url) else { + return false; + }; + let Some(long_polling_base_url) = bootstrap + .long_polling_base_url + .as_deref() + .filter(|value| !value.is_empty()) + else { + return false; + }; + let Some(poll_origin) = request_origin(long_polling_base_url) else { + return false; + }; + + base_origin != poll_origin +} + +fn request_origin(value: &str) -> Option { + let mut url = Url::parse(value).ok()?; + url.set_path(""); + url.set_query(None); + url.set_fragment(None); + Some(url.as_str().trim_end_matches('/').to_string()) +} diff --git a/crates/fire-models/src/session/tests.rs b/crates/fire-models/src/session/tests.rs new file mode 100644 index 00000000..63441010 --- /dev/null +++ b/crates/fire-models/src/session/tests.rs @@ -0,0 +1,299 @@ +use super::*; +use crate::{CookieSnapshot, PlatformCookie, TopicCategory}; + +#[test] +fn readiness_ignores_expired_platform_auth_cookies() { + let cookies = CookieSnapshot { + t_token: Some("stale-token".into()), + forum_session: Some("stale-forum".into()), + cf_clearance: Some("stale-clearance".into()), + csrf_token: None, + last_challenged_cf_clearance: None, + platform_cookies: vec![ + PlatformCookie { + name: "_t".into(), + value: "expired-token".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: Some(1), + same_site: None, + }, + PlatformCookie { + name: "_forum_session".into(), + value: "expired-forum".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: Some(1), + same_site: None, + }, + PlatformCookie { + name: "cf_clearance".into(), + value: "expired-clearance".into(), + domain: Some("linux.do".into()), + path: Some("/".into()), + expires_at_unix_ms: Some(1), + same_site: None, + }, + ], + canonical_cookies: Vec::new(), + }; + + assert!(!cookies.has_login_session()); + assert!(!cookies.has_forum_session()); + assert!(!cookies.has_cloudflare_clearance()); + assert!(!cookies.can_authenticate_requests()); +} + +#[test] +fn login_phase_advances_with_bootstrap_and_csrf() { + let mut snapshot = SessionSnapshot::default(); + assert_eq!(snapshot.login_phase(), LoginPhase::Anonymous); + + snapshot.cookies.t_token = Some("token".into()); + assert_eq!(snapshot.login_phase(), LoginPhase::CookiesCaptured); + + snapshot.cookies.forum_session = Some("forum".into()); + snapshot.bootstrap.current_username = Some("alice".into()); + assert_eq!(snapshot.login_phase(), LoginPhase::BootstrapCaptured); + + snapshot.cookies.csrf_token = Some("csrf".into()); + snapshot.bootstrap.preloaded_json = Some("{\"currentUser\":{\"username\":\"alice\"}}".into()); + snapshot.bootstrap.has_preloaded_data = true; + snapshot.bootstrap.has_site_metadata = true; + snapshot.bootstrap.has_site_settings = true; + assert_eq!(snapshot.login_phase(), LoginPhase::Ready); +} + +#[test] +fn merge_patch_keeps_existing_site_metadata_when_partial_preloaded_lacks_site() { + let mut bootstrap = BootstrapArtifacts { + preloaded_json: Some("{\"site\":{\"categories\":[{\"id\":2}]}}".into()), + has_preloaded_data: true, + has_site_metadata: true, + top_tags: vec!["swift".into()], + can_tag_topics: true, + categories: vec![TopicCategory { + id: 2, + name: "Rust".into(), + slug: "rust".into(), + parent_category_id: None, + color_hex: Some("FFFFFF".into()), + text_color_hex: Some("000000".into()), + ..TopicCategory::default() + }], + has_site_settings: true, + enabled_reaction_ids: vec!["heart".into(), "clap".into()], + min_post_length: 20, + min_topic_title_length: 15, + min_first_post_length: 20, + default_composer_category: Some(2), + ..BootstrapArtifacts::default() + }; + + bootstrap.merge_patch(&BootstrapArtifacts { + preloaded_json: Some("{\"currentUser\":{\"username\":\"alice\"}}".into()), + has_preloaded_data: true, + ..BootstrapArtifacts::default() + }); + + assert!(bootstrap.has_site_metadata); + assert_eq!(bootstrap.top_tags, vec!["swift"]); + assert!(bootstrap.can_tag_topics); + assert_eq!(bootstrap.categories.len(), 1); + assert!(bootstrap.has_site_settings); + assert_eq!(bootstrap.enabled_reaction_ids, vec!["heart", "clap"]); + assert_eq!(bootstrap.min_post_length, 20); + assert_eq!(bootstrap.min_topic_title_length, 15); + assert_eq!(bootstrap.min_first_post_length, 20); + assert_eq!(bootstrap.default_composer_category, Some(2)); +} + +#[test] +fn merge_patch_updates_site_metadata_and_settings_when_present() { + let mut bootstrap = BootstrapArtifacts::default(); + + bootstrap.merge_patch(&BootstrapArtifacts { + preloaded_json: Some("{\"site\":{},\"siteSettings\":{}}".into()), + has_preloaded_data: true, + has_site_metadata: true, + top_tags: vec!["rust".into(), "swift".into(), "rust".into()], + can_tag_topics: true, + categories: vec![TopicCategory { + id: 2, + name: "Rust".into(), + slug: "rust".into(), + parent_category_id: None, + color_hex: None, + text_color_hex: None, + ..TopicCategory::default() + }], + has_site_settings: true, + enabled_reaction_ids: vec!["heart".into(), "clap".into(), "heart".into()], + min_post_length: 18, + min_topic_title_length: 16, + min_first_post_length: 24, + default_composer_category: Some(2), + ..BootstrapArtifacts::default() + }); + + assert!(bootstrap.has_site_metadata); + assert_eq!(bootstrap.top_tags, vec!["rust", "swift"]); + assert!(bootstrap.can_tag_topics); + assert_eq!(bootstrap.categories.len(), 1); + assert!(bootstrap.has_site_settings); + assert_eq!(bootstrap.enabled_reaction_ids, vec!["heart", "clap"]); + assert_eq!(bootstrap.min_post_length, 18); + assert_eq!(bootstrap.min_topic_title_length, 16); + assert_eq!(bootstrap.min_first_post_length, 24); + assert_eq!(bootstrap.default_composer_category, Some(2)); +} + +#[test] +fn merge_patch_applies_site_metadata_without_preloaded_payload() { + let mut bootstrap = BootstrapArtifacts { + preloaded_json: Some("{\"currentUser\":{\"username\":\"alice\"}}".into()), + has_preloaded_data: true, + ..BootstrapArtifacts::default() + }; + + bootstrap.merge_patch(&BootstrapArtifacts { + has_site_metadata: true, + top_tags: vec!["rust".into(), "swift".into()], + can_tag_topics: true, + categories: vec![TopicCategory { + id: 2, + name: "Rust".into(), + slug: "rust".into(), + parent_category_id: None, + color_hex: None, + text_color_hex: None, + ..TopicCategory::default() + }], + ..BootstrapArtifacts::default() + }); + + assert!(bootstrap.has_site_metadata); + assert_eq!(bootstrap.top_tags, vec!["rust", "swift"]); + assert!(bootstrap.can_tag_topics); + assert_eq!(bootstrap.categories.len(), 1); + assert!(bootstrap.has_preloaded_data); +} + +#[test] +fn same_origin_message_bus_does_not_require_shared_session_key() { + let snapshot = SessionSnapshot { + cookies: CookieSnapshot { + t_token: Some("token".into()), + forum_session: Some("forum".into()), + ..CookieSnapshot::default() + }, + bootstrap: BootstrapArtifacts { + base_url: "https://linux.do".into(), + long_polling_base_url: Some("https://linux.do".into()), + current_username: Some("alice".into()), + preloaded_json: Some("{\"currentUser\":{\"username\":\"alice\"}}".into()), + has_preloaded_data: true, + ..BootstrapArtifacts::default() + }, + browser_user_agent: None, + read_path_login_request: None, + }; + + let readiness = snapshot.readiness(); + + assert!(!readiness.has_shared_session_key); + assert!(readiness.can_open_message_bus); +} + +#[test] +fn cross_origin_message_bus_requires_shared_session_key() { + let snapshot = SessionSnapshot { + cookies: CookieSnapshot { + t_token: Some("token".into()), + forum_session: Some("forum".into()), + ..CookieSnapshot::default() + }, + bootstrap: BootstrapArtifacts { + base_url: "https://linux.do".into(), + long_polling_base_url: Some("https://poll.linux.do".into()), + current_username: Some("alice".into()), + preloaded_json: Some("{\"currentUser\":{\"username\":\"alice\"}}".into()), + has_preloaded_data: true, + ..BootstrapArtifacts::default() + }, + browser_user_agent: None, + read_path_login_request: None, + }; + + let readiness = snapshot.readiness(); + + assert!(!readiness.has_shared_session_key); + assert!(!readiness.can_open_message_bus); +} + +#[test] +fn clear_login_state_preserves_cf_when_requested() { + let mut snapshot = SessionSnapshot { + cookies: CookieSnapshot { + t_token: Some("token".into()), + forum_session: Some("forum".into()), + cf_clearance: Some("clearance".into()), + csrf_token: Some("csrf".into()), + last_challenged_cf_clearance: None, + platform_cookies: Vec::new(), + canonical_cookies: Vec::new(), + }, + bootstrap: BootstrapArtifacts { + base_url: "https://linux.do".into(), + discourse_base_uri: Some("/".into()), + shared_session_key: Some("shared".into()), + current_username: Some("alice".into()), + current_user_id: Some(1), + notification_channel_position: Some(42), + long_polling_base_url: Some("https://linux.do".into()), + turnstile_sitekey: Some("sitekey".into()), + topic_tracking_state_meta: Some("{\"seq\":1}".into()), + preloaded_json: Some("{\"ok\":true}".into()), + has_preloaded_data: true, + has_site_metadata: true, + top_tags: vec!["rust".into()], + can_tag_topics: true, + categories: Vec::new(), + has_site_settings: true, + enabled_reaction_ids: vec!["heart".into(), "clap".into()], + min_post_length: 20, + min_topic_title_length: 15, + min_first_post_length: 20, + min_personal_message_title_length: 2, + min_personal_message_post_length: 10, + default_composer_category: Some(2), + }, + browser_user_agent: None, + read_path_login_request: None, + }; + + snapshot.clear_login_state(true); + + assert_eq!(snapshot.cookies.cf_clearance.as_deref(), Some("clearance")); + assert_eq!(snapshot.cookies.t_token, None); + assert_eq!(snapshot.bootstrap.current_username, None); + assert_eq!(snapshot.bootstrap.current_user_id, None); + assert_eq!(snapshot.bootstrap.notification_channel_position, None); + assert_eq!(snapshot.bootstrap.shared_session_key, None); + assert_eq!(snapshot.bootstrap.preloaded_json, None); + assert!(!snapshot.bootstrap.has_preloaded_data); + assert_eq!( + snapshot.bootstrap.turnstile_sitekey.as_deref(), + Some("sitekey") + ); + assert!(!snapshot.bootstrap.has_site_metadata); + assert_eq!(snapshot.bootstrap.top_tags, Vec::::new()); + assert!(!snapshot.bootstrap.can_tag_topics); + assert_eq!(snapshot.bootstrap.categories, Vec::new()); + assert!(!snapshot.bootstrap.has_site_settings); + assert_eq!(snapshot.bootstrap.enabled_reaction_ids, vec!["heart"]); + assert_eq!(snapshot.bootstrap.min_post_length, 1); + assert_eq!(snapshot.bootstrap.min_topic_title_length, 15); + assert_eq!(snapshot.bootstrap.min_first_post_length, 20); + assert_eq!(snapshot.bootstrap.default_composer_category, None); +} diff --git a/crates/fire-models/src/topic.rs b/crates/fire-models/src/topic.rs index bccd7a28..372df3a1 100644 --- a/crates/fire-models/src/topic.rs +++ b/crates/fire-models/src/topic.rs @@ -267,3 +267,98 @@ pub struct TopicListResponse { #[serde(default)] pub is_cached: bool, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn topic_list_query_api_path_global() { + let query = TopicListQuery { + kind: TopicListKind::Latest, + ..Default::default() + }; + assert_eq!(query.api_path(), "/latest.json"); + assert_eq!(query.html_path(), "/latest"); + + let query = TopicListQuery { + kind: TopicListKind::Hot, + ..Default::default() + }; + assert_eq!(query.api_path(), "/hot.json"); + assert_eq!(query.html_path(), "/hot"); + } + + #[test] + fn topic_list_query_api_path_category() { + let query = TopicListQuery { + kind: TopicListKind::Latest, + category_slug: Some("dev".into()), + category_id: Some(42), + ..Default::default() + }; + assert_eq!(query.api_path(), "/c/dev/42/l/latest.json"); + assert_eq!(query.html_path(), "/c/dev/42/l/latest"); + } + + #[test] + fn topic_list_query_api_path_subcategory() { + let query = TopicListQuery { + kind: TopicListKind::New, + category_slug: Some("rust".into()), + category_id: Some(99), + parent_category_slug: Some("dev".into()), + ..Default::default() + }; + assert_eq!(query.api_path(), "/c/dev/rust/99/l/new.json"); + assert_eq!(query.html_path(), "/c/dev/rust/99/l/new"); + } + + #[test] + fn topic_list_query_api_path_tag() { + let query = TopicListQuery { + kind: TopicListKind::Top, + tag: Some("swift".into()), + ..Default::default() + }; + assert_eq!(query.api_path(), "/tag/swift/l/top.json"); + assert_eq!(query.html_path(), "/tag/swift/l/top"); + } + + #[test] + fn topic_list_query_api_path_category_slug_only() { + let query = TopicListQuery { + kind: TopicListKind::Latest, + category_slug: Some("dev".into()), + ..Default::default() + }; + assert_eq!(query.api_path(), "/c/dev.json"); + assert_eq!(query.html_path(), "/c/dev"); + } + + #[test] + fn topic_list_query_api_path_topic_ids_override() { + let query = TopicListQuery { + kind: TopicListKind::New, + topic_ids: vec![1, 2, 3], + ..Default::default() + }; + assert_eq!(query.api_path(), "/latest.json"); + assert_eq!(query.html_path(), "/latest"); + } + + #[test] + fn topic_list_query_html_path_private_messages() { + let query = TopicListQuery { + kind: TopicListKind::PrivateMessagesInbox, + ..Default::default() + }; + assert_eq!(query.html_path(), "/my/messages"); + + let query = TopicListQuery { + kind: TopicListKind::PrivateMessagesSent, + ..Default::default() + }; + assert_eq!(query.html_path(), "/my/messages/sent"); + } +} diff --git a/crates/fire-models/src/topic_detail.rs b/crates/fire-models/src/topic_detail.rs deleted file mode 100644 index 20f2e6a4..00000000 --- a/crates/fire-models/src/topic_detail.rs +++ /dev/null @@ -1,882 +0,0 @@ -use std::collections::HashSet; - -use serde::{Deserialize, Serialize}; - -use crate::cookie::is_non_empty; -use crate::rich_text::AttachedPresentation; -use crate::topic::{TopicParticipant, TopicTag}; - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicDetailQuery { - pub topic_id: u64, - pub post_number: Option, - pub track_visit: bool, - pub force_load: bool, - pub filter: Option, - pub username_filters: Option, - pub filter_top_level_replies: bool, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicReaction { - pub id: String, - #[serde(default, alias = "type")] - pub kind: Option, - pub count: u32, - #[serde(default)] - pub can_undo: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct PollOption { - pub id: String, - pub html: String, - #[serde(default)] - pub plain_text: String, - pub votes: u32, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Poll { - pub id: u64, - pub name: String, - #[serde(default, alias = "type")] - pub kind: String, - pub status: String, - pub results: String, - #[serde(default)] - pub options: Vec, - pub voters: u32, - #[serde(default)] - pub user_votes: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicReplyRequest { - pub topic_id: u64, - pub raw: String, - pub reply_to_post_number: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicCreateRequest { - pub title: String, - pub raw: String, - pub category_id: u64, - #[serde(default)] - pub tags: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct PrivateMessageCreateRequest { - pub title: String, - pub raw: String, - #[serde(default)] - pub target_recipients: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicUpdateRequest { - pub topic_id: u64, - pub title: String, - pub category_id: u64, - #[serde(default)] - pub tags: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct PostUpdateRequest { - pub post_id: u64, - pub raw: String, - pub edit_reason: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct PostFlagRequest { - pub post_id: u64, - pub flag_type_id: u32, - pub message: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct PostActionType { - pub id: u32, - pub name_key: String, - pub name: String, - pub description: String, - pub short_description: Option, - pub is_flag: bool, - pub require_message: bool, - pub enabled: bool, - pub position: i32, - #[serde(default)] - pub applies_to: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct InviteCreateRequest { - pub max_redemptions_allowed: u32, - pub expires_at: Option, - pub description: Option, - pub email: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct DraftData { - pub reply: Option, - pub title: Option, - #[serde(rename = "categoryId", alias = "category_id")] - pub category_id: Option, - #[serde(default)] - pub tags: Vec, - #[serde(rename = "replyToPostNumber", alias = "reply_to_post_number")] - pub reply_to_post_number: Option, - pub action: Option, - #[serde(default)] - pub recipients: Vec, - #[serde(rename = "archetypeId", alias = "archetype_id")] - pub archetype_id: Option, - #[serde(rename = "composerTime", alias = "composer_time")] - pub composer_time: Option, - #[serde(rename = "typingTime", alias = "typing_time")] - pub typing_time: Option, -} - -impl DraftData { - pub fn has_content(&self) -> bool { - is_non_empty(self.reply.as_deref()) || is_non_empty(self.title.as_deref()) - } -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Draft { - pub draft_key: String, - pub data: DraftData, - pub sequence: u32, - pub title: Option, - pub excerpt: Option, - pub updated_at: Option, - pub username: Option, - pub avatar_template: Option, - pub topic_id: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct DraftListResponse { - #[serde(default)] - pub drafts: Vec, - #[serde(default)] - pub has_more: bool, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct UploadResult { - /// Discourse upload id (used by Chat `upload_ids` and similar write APIs). - pub id: Option, - pub short_url: String, - pub url: Option, - pub original_filename: Option, - pub width: Option, - pub height: Option, - pub thumbnail_width: Option, - pub thumbnail_height: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ResolvedUploadUrl { - pub short_url: String, - pub short_path: Option, - pub url: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicTimingEntry { - pub post_number: u32, - pub milliseconds: u32, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicTimingsRequest { - pub topic_id: u64, - pub topic_time_ms: u32, - pub timings: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct PostReactionUpdate { - pub reactions: Vec, - pub current_user_reaction: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ReactionUser { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ReactionUsersGroup { - pub id: String, - pub count: u32, - pub users: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicReplyToUser { - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicPostBoostUser { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicPostBoost { - pub id: u64, - pub cooked: String, - pub display_text: String, - pub user: TopicPostBoostUser, - pub can_delete: bool, - pub can_flag: bool, - pub user_flag_status: Option, - pub available_flags: Vec, - #[serde(default)] - pub presented: AttachedPresentation, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicPostAuthorMetadata { - pub user_id: Option, - pub user_title: Option, - pub primary_group_name: Option, - pub flair_url: Option, - pub flair_name: Option, - pub flair_bg_color: Option, - pub flair_color: Option, - pub flair_group_id: Option, - pub moderator: bool, - pub admin: bool, - pub group_moderator: bool, - pub user_status_emoji: Option, - pub user_status_description: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicPost { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, - pub author_metadata: TopicPostAuthorMetadata, - pub cooked: String, - pub raw: Option, - pub post_number: u32, - pub post_type: i32, - pub created_at: Option, - pub updated_at: Option, - pub like_count: u32, - pub reply_count: u32, - pub reply_to_post_number: Option, - pub reply_to_user: Option, - pub bookmarked: bool, - pub bookmark_id: Option, - pub bookmark_name: Option, - pub bookmark_reminder_at: Option, - pub reactions: Vec, - pub current_user_reaction: Option, - pub boosts: Vec, - pub can_boost: bool, - pub polls: Vec, - pub accepted_answer: bool, - pub can_accept_answer: bool, - pub can_unaccept_answer: bool, - pub can_edit: bool, - pub can_delete: bool, - pub can_recover: bool, - pub hidden: bool, - #[serde(default)] - pub presented: AttachedPresentation, -} - -impl TopicPost { - pub fn reuse_presentation_from(&mut self, previous: &Self) { - if self.cooked == previous.cooked { - if let Some(presented) = previous.presented.arc() { - self.presented = AttachedPresentation::some(presented); - } - } - for boost in &mut self.boosts { - if let Some(previous_boost) = previous.boosts.iter().find(|item| item.id == boost.id) { - boost.reuse_presentation_from(previous_boost); - } - } - } -} - -impl TopicPostBoost { - pub fn reuse_presentation_from(&mut self, previous: &Self) { - if self.cooked == previous.cooked { - if let Some(presented) = previous.presented.arc() { - self.presented = AttachedPresentation::some(presented); - } - } - } -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicPostStream { - pub posts: Vec, - pub stream: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicDetailSourceQuery { - pub topic_id: u64, - pub target_post_number: Option, - pub allow_suggested_unread_root: bool, - pub track_visit: bool, - pub force_load: bool, - pub initial_batch_size: u16, - pub load_more_batch_size: u16, - pub max_auto_batches_per_gesture: u8, - pub max_auto_posts_per_gesture: u16, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicHeader { - pub topic_id: u64, - pub message_bus_last_id: Option, - pub title: String, - pub slug: String, - pub category_id: Option, - pub tags: Vec, - pub views: u32, - pub like_count: u32, - pub posts_count: u32, - pub reply_count: u32, - pub highest_post_number: u32, - pub created_at: Option, - pub last_read_post_number: Option, - pub bookmarks: Vec, - pub bookmarked: bool, - pub bookmark_id: Option, - pub bookmark_name: Option, - pub bookmark_reminder_at: Option, - pub accepted_answer: bool, - pub has_accepted_answer: bool, - pub can_vote: bool, - pub vote_count: i32, - pub user_voted: bool, - pub summarizable: bool, - pub has_cached_summary: bool, - pub has_summary: bool, - pub archetype: Option, - pub details: TopicDetailMeta, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicBody { - pub post: TopicPost, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicLoadedRange { - pub start_offset: u32, - pub end_offset_exclusive: u32, - pub first_post_id: u64, - pub last_post_id: u64, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicDetailSourceSnapshot { - pub header: TopicHeader, - pub body: TopicBody, - pub raw_stream_ids: Vec, - pub loaded_posts: Vec, - pub loaded_ranges: Vec, - pub source_cursor: Option, - pub source_exhausted: bool, - pub focused_post_number: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicDetailPage { - pub source_snapshot: TopicDetailSourceSnapshot, - pub tree_presentation: TopicTreePresentation, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicSourceCursor { - pub topic_id: u64, - pub session_id: u64, - pub next_stream_offset: u32, - pub last_loaded_post_id: Option, - pub batch_size: u16, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct LoadMoreTopicPostsQuery { - pub cursor: TopicSourceCursor, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicDetailSourceAppend { - pub appended_posts: Vec, - pub loaded_ranges: Vec, - pub source_cursor: Option, - pub source_exhausted: bool, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicTreePresentationQuery { - pub body_post: TopicPost, - pub raw_stream_ids: Vec, - pub loaded_posts: Vec, - pub focused_post_number: Option, - pub last_read_post_number: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicTreePresentation { - pub original_post_id: u64, - pub original_post_number: u32, - pub reply_rows: Vec, - pub total_loaded_post_count: u32, - pub visible_root_post_numbers: Vec, - pub first_unread_root_post_number: Option, - pub gained_new_root_progress: bool, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicTreeRow { - pub post_id: u64, - pub post_number: u32, - pub root_post_number: u32, - pub parent_post_number: Option, - pub depth: u16, - pub preorder_index: u32, - pub has_children: bool, - pub sibling_index: u16, - pub is_last_sibling: bool, - pub descendant_count: u32, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum TopicLoadMoreStopReason { - #[default] - GainedVisibleRootProgress, - SourceExhausted, - MaxAutoBatchesReached, - MaxAutoPostsReached, - RequestFailed, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicLoadMoreOutcome { - pub source_snapshot: TopicDetailSourceSnapshot, - pub appended_posts: Vec, - pub tree_presentation: TopicTreePresentation, - pub chained_batches: u8, - pub chained_posts: u16, - pub stop_reason: TopicLoadMoreStopReason, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicThreadReply { - pub post_number: u32, - pub depth: u32, - pub parent_post_number: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicThreadSection { - pub anchor_post_number: u32, - pub replies: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicThread { - pub original_post_number: Option, - pub reply_sections: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicThreadFlatPost { - pub post: TopicPost, - pub depth: u32, - pub parent_post_number: Option, - pub shows_thread_line: bool, - pub is_original_post: bool, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicTimelineEntry { - pub post_id: u64, - pub post_number: u32, - pub parent_post_number: Option, - pub depth: u32, - pub is_original_post: bool, -} - -impl TopicThread { - pub fn from_posts(posts: &[TopicPost]) -> Self { - let Some(original_post) = posts.iter().min_by_key(|post| post.post_number) else { - return Self::default(); - }; - - let root_post_number = original_post.post_number; - let post_numbers: std::collections::HashSet = - posts.iter().map(|post| post.post_number).collect(); - let mut children_by_parent: std::collections::BTreeMap> = - std::collections::BTreeMap::new(); - - for post in posts - .iter() - .filter(|post| post.post_number != root_post_number) - { - let Some(parent_post_number) = normalized_reply_target(post.reply_to_post_number) - else { - continue; - }; - if parent_post_number == post.post_number { - continue; - } - children_by_parent - .entry(parent_post_number) - .or_default() - .push(post); - } - - let mut consumed_post_numbers = std::collections::HashSet::from([root_post_number]); - let mut reply_sections = Vec::new(); - - for post in posts - .iter() - .filter(|post| post.post_number != root_post_number) - { - if consumed_post_numbers.contains(&post.post_number) { - continue; - } - - let normalized_parent = normalized_reply_target(post.reply_to_post_number); - let should_start_section = normalized_parent.is_none() - || normalized_parent == Some(root_post_number) - || normalized_parent.is_some_and(|parent| !post_numbers.contains(&parent)); - if !should_start_section { - continue; - } - - consumed_post_numbers.insert(post.post_number); - let mut branch_visited = std::collections::HashSet::from([post.post_number]); - let replies = flatten_thread_replies( - post.post_number, - 1, - &children_by_parent, - &mut consumed_post_numbers, - &mut branch_visited, - ); - reply_sections.push(TopicThreadSection { - anchor_post_number: post.post_number, - replies, - }); - } - - let remaining_post_numbers: Vec = posts - .iter() - .filter(|post| post.post_number != root_post_number) - .map(|post| post.post_number) - .filter(|post_number| !consumed_post_numbers.contains(post_number)) - .collect(); - - for post_number in remaining_post_numbers { - let Some(post) = posts.iter().find(|post| post.post_number == post_number) else { - continue; - }; - consumed_post_numbers.insert(post.post_number); - let mut branch_visited = std::collections::HashSet::from([post.post_number]); - let replies = flatten_thread_replies( - post.post_number, - 1, - &children_by_parent, - &mut consumed_post_numbers, - &mut branch_visited, - ); - reply_sections.push(TopicThreadSection { - anchor_post_number: post.post_number, - replies, - }); - } - - Self { - original_post_number: Some(root_post_number), - reply_sections, - } - } - - pub fn flatten(&self, posts: &[TopicPost]) -> Vec { - let posts_by_number: std::collections::HashMap = - posts.iter().map(|post| (post.post_number, post)).collect(); - let mut result = Vec::new(); - - if let Some(original_post) = self - .original_post_number - .and_then(|post_number| posts_by_number.get(&post_number)) - { - result.push(TopicThreadFlatPost { - post: (*original_post).clone(), - depth: 0, - parent_post_number: None, - shows_thread_line: !self.reply_sections.is_empty(), - is_original_post: true, - }); - } - - for (section_index, section) in self.reply_sections.iter().enumerate() { - let is_last_section = section_index == self.reply_sections.len() - 1; - let has_nested_replies = !section.replies.is_empty(); - - let Some(anchor_post) = posts_by_number.get(§ion.anchor_post_number) else { - continue; - }; - - result.push(TopicThreadFlatPost { - post: (*anchor_post).clone(), - depth: 0, - parent_post_number: None, - shows_thread_line: has_nested_replies || !is_last_section, - is_original_post: false, - }); - - for (reply_index, reply) in section.replies.iter().enumerate() { - let Some(reply_post) = posts_by_number.get(&reply.post_number) else { - continue; - }; - let is_last_reply = reply_index == section.replies.len() - 1; - result.push(TopicThreadFlatPost { - post: (*reply_post).clone(), - depth: reply.depth, - parent_post_number: reply.parent_post_number, - shows_thread_line: !is_last_reply || !is_last_section, - is_original_post: false, - }); - } - } - - result - } -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicDetailCreatedBy { - pub id: u64, - pub username: String, - pub avatar_template: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicDetailMeta { - pub notification_level: Option, - pub can_edit: bool, - pub created_by: Option, - #[serde(default)] - pub participants: Vec, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicAiSummary { - pub summarized_text: String, - pub algorithm: Option, - pub outdated: bool, - pub can_regenerate: bool, - pub new_posts_since_summary: u32, - pub updated_at: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TopicDetail { - pub id: u64, - pub message_bus_last_id: Option, - pub title: String, - pub slug: String, - pub posts_count: u32, - pub category_id: Option, - pub tags: Vec, - pub views: u32, - pub like_count: u32, - pub created_at: Option, - pub highest_post_number: u32, - pub last_read_post_number: Option, - pub bookmarks: Vec, - pub bookmarked: bool, - pub bookmark_id: Option, - pub bookmark_name: Option, - pub bookmark_reminder_at: Option, - pub accepted_answer: bool, - pub has_accepted_answer: bool, - pub can_vote: bool, - pub vote_count: i32, - pub user_voted: bool, - pub summarizable: bool, - pub has_cached_summary: bool, - pub has_summary: bool, - pub archetype: Option, - pub post_stream: TopicPostStream, - #[serde(default)] - pub thread: TopicThread, - #[serde(default)] - pub flat_posts: Vec, - #[serde(default)] - pub timeline_entries: Vec, - pub details: TopicDetailMeta, -} - -impl TopicDetail { - pub fn rebuild_timeline_entries(&mut self) { - self.timeline_entries = build_floor_timeline_entries(&self.post_stream.posts); - } - - pub fn reply_count(&self) -> u32 { - self.posts_count.saturating_sub(1) - } - - pub fn header(&self) -> TopicHeader { - TopicHeader { - topic_id: self.id, - message_bus_last_id: self.message_bus_last_id, - title: self.title.clone(), - slug: self.slug.clone(), - category_id: self.category_id, - tags: self.tags.clone(), - views: self.views, - like_count: self.like_count, - posts_count: self.posts_count, - reply_count: self.reply_count(), - highest_post_number: self.highest_post_number, - created_at: self.created_at.clone(), - last_read_post_number: self.last_read_post_number, - bookmarks: self.bookmarks.clone(), - bookmarked: self.bookmarked, - bookmark_id: self.bookmark_id, - bookmark_name: self.bookmark_name.clone(), - bookmark_reminder_at: self.bookmark_reminder_at.clone(), - accepted_answer: self.accepted_answer, - has_accepted_answer: self.has_accepted_answer, - can_vote: self.can_vote, - vote_count: self.vote_count, - user_voted: self.user_voted, - summarizable: self.summarizable, - has_cached_summary: self.has_cached_summary, - has_summary: self.has_summary, - archetype: self.archetype.clone(), - details: self.details.clone(), - } - } - - pub fn interaction_count(&self) -> u32 { - self.like_count.saturating_add( - self.post_stream - .posts - .iter() - .flat_map(|post| post.reactions.iter()) - .filter(|reaction| !reaction.id.eq_ignore_ascii_case("heart")) - .fold(0_u32, |total, reaction| { - total.saturating_add(reaction.count) - }), - ) - } -} - -fn normalized_reply_target(reply_to_post_number: Option) -> Option { - reply_to_post_number.filter(|post_number| *post_number > 0) -} - -fn build_floor_timeline_entries(posts: &[TopicPost]) -> Vec { - let post_numbers: HashSet = posts.iter().map(|p| p.post_number).collect(); - let min_pn = posts.iter().map(|p| p.post_number).min().unwrap_or(0); - let mut sorted: Vec<&TopicPost> = posts.iter().collect(); - sorted.sort_by_key(|p| (p.post_number, p.id)); - - sorted - .iter() - .map(|post| { - let parent = normalized_reply_target(post.reply_to_post_number); - let depth = match parent { - Some(pn) if pn != post.post_number => { - compute_depth_walk(pn, posts, &post_numbers, 1) - } - _ => 0, - }; - TopicTimelineEntry { - post_id: post.id, - post_number: post.post_number, - parent_post_number: parent, - depth, - is_original_post: post.post_number == min_pn, - } - }) - .collect() -} - -fn compute_depth_walk( - parent_pn: u32, - posts: &[TopicPost], - loaded: &HashSet, - current_depth: u32, -) -> u32 { - if !loaded.contains(&parent_pn) { - return current_depth; - } - match posts.iter().find(|p| p.post_number == parent_pn) { - Some(p) => match normalized_reply_target(p.reply_to_post_number) { - Some(gp) if gp != parent_pn => compute_depth_walk(gp, posts, loaded, current_depth + 1), - _ => current_depth, - }, - None => current_depth, - } -} - -fn flatten_thread_replies( - parent_post_number: u32, - depth: u32, - children_by_parent: &std::collections::BTreeMap>, - consumed_post_numbers: &mut std::collections::HashSet, - branch_visited: &mut std::collections::HashSet, -) -> Vec { - let Some(children) = children_by_parent.get(&parent_post_number) else { - return Vec::new(); - }; - - let mut replies = Vec::new(); - for child in children { - if branch_visited.contains(&child.post_number) { - continue; - } - - consumed_post_numbers.insert(child.post_number); - replies.push(TopicThreadReply { - post_number: child.post_number, - depth, - parent_post_number: normalized_reply_target(child.reply_to_post_number), - }); - - branch_visited.insert(child.post_number); - replies.extend(flatten_thread_replies( - child.post_number, - depth + 1, - children_by_parent, - consumed_post_numbers, - branch_visited, - )); - branch_visited.remove(&child.post_number); - } - - replies -} diff --git a/crates/fire-models/src/topic_detail/detail.rs b/crates/fire-models/src/topic_detail/detail.rs new file mode 100644 index 00000000..e541fbfb --- /dev/null +++ b/crates/fire-models/src/topic_detail/detail.rs @@ -0,0 +1,128 @@ +use serde::{Deserialize, Serialize}; + +use super::{ + post::TopicPostStream, + source::TopicHeader, + tree::{build_floor_timeline_entries, TopicThread, TopicThreadFlatPost, TopicTimelineEntry}, +}; +use crate::topic::{TopicParticipant, TopicTag}; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicDetailCreatedBy { + pub id: u64, + pub username: String, + pub avatar_template: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicDetailMeta { + pub notification_level: Option, + pub can_edit: bool, + pub created_by: Option, + #[serde(default)] + pub participants: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicAiSummary { + pub summarized_text: String, + pub algorithm: Option, + pub outdated: bool, + pub can_regenerate: bool, + pub new_posts_since_summary: u32, + pub updated_at: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicDetail { + pub id: u64, + pub message_bus_last_id: Option, + pub title: String, + pub slug: String, + pub posts_count: u32, + pub category_id: Option, + pub tags: Vec, + pub views: u32, + pub like_count: u32, + pub created_at: Option, + pub highest_post_number: u32, + pub last_read_post_number: Option, + pub bookmarks: Vec, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub accepted_answer: bool, + pub has_accepted_answer: bool, + pub can_vote: bool, + pub vote_count: i32, + pub user_voted: bool, + pub summarizable: bool, + pub has_cached_summary: bool, + pub has_summary: bool, + pub archetype: Option, + pub post_stream: TopicPostStream, + #[serde(default)] + pub thread: TopicThread, + #[serde(default)] + pub flat_posts: Vec, + #[serde(default)] + pub timeline_entries: Vec, + pub details: TopicDetailMeta, +} + +impl TopicDetail { + pub fn rebuild_timeline_entries(&mut self) { + self.timeline_entries = build_floor_timeline_entries(&self.post_stream.posts); + } + + pub fn reply_count(&self) -> u32 { + self.posts_count.saturating_sub(1) + } + + pub fn header(&self) -> TopicHeader { + TopicHeader { + topic_id: self.id, + message_bus_last_id: self.message_bus_last_id, + title: self.title.clone(), + slug: self.slug.clone(), + category_id: self.category_id, + tags: self.tags.clone(), + views: self.views, + like_count: self.like_count, + posts_count: self.posts_count, + reply_count: self.reply_count(), + highest_post_number: self.highest_post_number, + created_at: self.created_at.clone(), + last_read_post_number: self.last_read_post_number, + bookmarks: self.bookmarks.clone(), + bookmarked: self.bookmarked, + bookmark_id: self.bookmark_id, + bookmark_name: self.bookmark_name.clone(), + bookmark_reminder_at: self.bookmark_reminder_at.clone(), + accepted_answer: self.accepted_answer, + has_accepted_answer: self.has_accepted_answer, + can_vote: self.can_vote, + vote_count: self.vote_count, + user_voted: self.user_voted, + summarizable: self.summarizable, + has_cached_summary: self.has_cached_summary, + has_summary: self.has_summary, + archetype: self.archetype.clone(), + details: self.details.clone(), + } + } + + pub fn interaction_count(&self) -> u32 { + self.like_count.saturating_add( + self.post_stream + .posts + .iter() + .flat_map(|post| post.reactions.iter()) + .filter(|reaction| !reaction.id.eq_ignore_ascii_case("heart")) + .fold(0_u32, |total, reaction| { + total.saturating_add(reaction.count) + }), + ) + } +} diff --git a/crates/fire-models/src/topic_detail/drafts.rs b/crates/fire-models/src/topic_detail/drafts.rs new file mode 100644 index 00000000..bb3863e2 --- /dev/null +++ b/crates/fire-models/src/topic_detail/drafts.rs @@ -0,0 +1,51 @@ +use serde::{Deserialize, Serialize}; + +use crate::cookie::is_non_empty; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct DraftData { + pub reply: Option, + pub title: Option, + #[serde(rename = "categoryId", alias = "category_id")] + pub category_id: Option, + #[serde(default)] + pub tags: Vec, + #[serde(rename = "replyToPostNumber", alias = "reply_to_post_number")] + pub reply_to_post_number: Option, + pub action: Option, + #[serde(default)] + pub recipients: Vec, + #[serde(rename = "archetypeId", alias = "archetype_id")] + pub archetype_id: Option, + #[serde(rename = "composerTime", alias = "composer_time")] + pub composer_time: Option, + #[serde(rename = "typingTime", alias = "typing_time")] + pub typing_time: Option, +} + +impl DraftData { + pub fn has_content(&self) -> bool { + is_non_empty(self.reply.as_deref()) || is_non_empty(self.title.as_deref()) + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Draft { + pub draft_key: String, + pub data: DraftData, + pub sequence: u32, + pub title: Option, + pub excerpt: Option, + pub updated_at: Option, + pub username: Option, + pub avatar_template: Option, + pub topic_id: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct DraftListResponse { + #[serde(default)] + pub drafts: Vec, + #[serde(default)] + pub has_more: bool, +} diff --git a/crates/fire-models/src/topic_detail/mod.rs b/crates/fire-models/src/topic_detail/mod.rs new file mode 100644 index 00000000..1c05441d --- /dev/null +++ b/crates/fire-models/src/topic_detail/mod.rs @@ -0,0 +1,18 @@ +mod detail; +mod drafts; +mod post; +mod requests; +mod source; +mod tree; +mod uploads; + +pub use detail::*; +pub use drafts::*; +pub use post::*; +pub use requests::*; +pub use source::*; +pub use tree::*; +pub use uploads::*; + +#[cfg(test)] +mod tests; diff --git a/crates/fire-models/src/topic_detail/post.rs b/crates/fire-models/src/topic_detail/post.rs new file mode 100644 index 00000000..208bd16b --- /dev/null +++ b/crates/fire-models/src/topic_detail/post.rs @@ -0,0 +1,172 @@ +use serde::{Deserialize, Serialize}; + +use crate::rich_text::AttachedPresentation; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicReaction { + pub id: String, + #[serde(default, alias = "type")] + pub kind: Option, + pub count: u32, + #[serde(default)] + pub can_undo: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PollOption { + pub id: String, + pub html: String, + #[serde(default)] + pub plain_text: String, + pub votes: u32, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Poll { + pub id: u64, + pub name: String, + #[serde(default, alias = "type")] + pub kind: String, + pub status: String, + pub results: String, + #[serde(default)] + pub options: Vec, + pub voters: u32, + #[serde(default)] + pub user_votes: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PostReactionUpdate { + pub reactions: Vec, + pub current_user_reaction: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReactionUser { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReactionUsersGroup { + pub id: String, + pub count: u32, + pub users: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicReplyToUser { + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicPostBoostUser { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicPostBoost { + pub id: u64, + pub cooked: String, + pub display_text: String, + pub user: TopicPostBoostUser, + pub can_delete: bool, + pub can_flag: bool, + pub user_flag_status: Option, + pub available_flags: Vec, + #[serde(default)] + pub presented: AttachedPresentation, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicPostAuthorMetadata { + pub user_id: Option, + pub user_title: Option, + pub primary_group_name: Option, + pub flair_url: Option, + pub flair_name: Option, + pub flair_bg_color: Option, + pub flair_color: Option, + pub flair_group_id: Option, + pub moderator: bool, + pub admin: bool, + pub group_moderator: bool, + pub user_status_emoji: Option, + pub user_status_description: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicPost { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, + pub author_metadata: TopicPostAuthorMetadata, + pub cooked: String, + pub raw: Option, + pub post_number: u32, + pub post_type: i32, + pub created_at: Option, + pub updated_at: Option, + pub like_count: u32, + pub reply_count: u32, + pub reply_to_post_number: Option, + pub reply_to_user: Option, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub reactions: Vec, + pub current_user_reaction: Option, + pub boosts: Vec, + pub can_boost: bool, + pub polls: Vec, + pub accepted_answer: bool, + pub can_accept_answer: bool, + pub can_unaccept_answer: bool, + pub can_edit: bool, + pub can_delete: bool, + pub can_recover: bool, + pub hidden: bool, + #[serde(default)] + pub presented: AttachedPresentation, +} + +impl TopicPost { + pub fn reuse_presentation_from(&mut self, previous: &Self) { + if self.cooked == previous.cooked { + if let Some(presented) = previous.presented.arc() { + self.presented = AttachedPresentation::some(presented); + } + } + for boost in &mut self.boosts { + if let Some(previous_boost) = previous.boosts.iter().find(|item| item.id == boost.id) { + boost.reuse_presentation_from(previous_boost); + } + } + } +} + +impl TopicPostBoost { + pub fn reuse_presentation_from(&mut self, previous: &Self) { + if self.cooked == previous.cooked { + if let Some(presented) = previous.presented.arc() { + self.presented = AttachedPresentation::some(presented); + } + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicPostStream { + pub posts: Vec, + pub stream: Vec, +} diff --git a/crates/fire-models/src/topic_detail/requests.rs b/crates/fire-models/src/topic_detail/requests.rs new file mode 100644 index 00000000..5057617f --- /dev/null +++ b/crates/fire-models/src/topic_detail/requests.rs @@ -0,0 +1,95 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicDetailQuery { + pub topic_id: u64, + pub post_number: Option, + pub track_visit: bool, + pub force_load: bool, + pub filter: Option, + pub username_filters: Option, + pub filter_top_level_replies: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicReplyRequest { + pub topic_id: u64, + pub raw: String, + pub reply_to_post_number: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicCreateRequest { + pub title: String, + pub raw: String, + pub category_id: u64, + #[serde(default)] + pub tags: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PrivateMessageCreateRequest { + pub title: String, + pub raw: String, + #[serde(default)] + pub target_recipients: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicUpdateRequest { + pub topic_id: u64, + pub title: String, + pub category_id: u64, + #[serde(default)] + pub tags: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PostUpdateRequest { + pub post_id: u64, + pub raw: String, + pub edit_reason: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PostFlagRequest { + pub post_id: u64, + pub flag_type_id: u32, + pub message: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PostActionType { + pub id: u32, + pub name_key: String, + pub name: String, + pub description: String, + pub short_description: Option, + pub is_flag: bool, + pub require_message: bool, + pub enabled: bool, + pub position: i32, + #[serde(default)] + pub applies_to: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct InviteCreateRequest { + pub max_redemptions_allowed: u32, + pub expires_at: Option, + pub description: Option, + pub email: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicTimingEntry { + pub post_number: u32, + pub milliseconds: u32, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicTimingsRequest { + pub topic_id: u64, + pub topic_time_ms: u32, + pub timings: Vec, +} diff --git a/crates/fire-models/src/topic_detail/source.rs b/crates/fire-models/src/topic_detail/source.rs new file mode 100644 index 00000000..4dff3cda --- /dev/null +++ b/crates/fire-models/src/topic_detail/source.rs @@ -0,0 +1,122 @@ +use serde::{Deserialize, Serialize}; + +use super::{detail::TopicDetailMeta, post::TopicPost, tree::TopicTreePresentation}; +use crate::topic::TopicTag; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicDetailSourceQuery { + pub topic_id: u64, + pub target_post_number: Option, + pub allow_suggested_unread_root: bool, + pub track_visit: bool, + pub force_load: bool, + pub initial_batch_size: u16, + pub load_more_batch_size: u16, + pub max_auto_batches_per_gesture: u8, + pub max_auto_posts_per_gesture: u16, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicHeader { + pub topic_id: u64, + pub message_bus_last_id: Option, + pub title: String, + pub slug: String, + pub category_id: Option, + pub tags: Vec, + pub views: u32, + pub like_count: u32, + pub posts_count: u32, + pub reply_count: u32, + pub highest_post_number: u32, + pub created_at: Option, + pub last_read_post_number: Option, + pub bookmarks: Vec, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub accepted_answer: bool, + pub has_accepted_answer: bool, + pub can_vote: bool, + pub vote_count: i32, + pub user_voted: bool, + pub summarizable: bool, + pub has_cached_summary: bool, + pub has_summary: bool, + pub archetype: Option, + pub details: TopicDetailMeta, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicBody { + pub post: TopicPost, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicLoadedRange { + pub start_offset: u32, + pub end_offset_exclusive: u32, + pub first_post_id: u64, + pub last_post_id: u64, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicDetailSourceSnapshot { + pub header: TopicHeader, + pub body: TopicBody, + pub raw_stream_ids: Vec, + pub loaded_posts: Vec, + pub loaded_ranges: Vec, + pub source_cursor: Option, + pub source_exhausted: bool, + pub focused_post_number: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicDetailPage { + pub source_snapshot: TopicDetailSourceSnapshot, + pub tree_presentation: TopicTreePresentation, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicSourceCursor { + pub topic_id: u64, + pub session_id: u64, + pub next_stream_offset: u32, + pub last_loaded_post_id: Option, + pub batch_size: u16, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct LoadMoreTopicPostsQuery { + pub cursor: TopicSourceCursor, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicDetailSourceAppend { + pub appended_posts: Vec, + pub loaded_ranges: Vec, + pub source_cursor: Option, + pub source_exhausted: bool, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum TopicLoadMoreStopReason { + #[default] + GainedVisibleRootProgress, + SourceExhausted, + MaxAutoBatchesReached, + MaxAutoPostsReached, + RequestFailed, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicLoadMoreOutcome { + pub source_snapshot: TopicDetailSourceSnapshot, + pub appended_posts: Vec, + pub tree_presentation: TopicTreePresentation, + pub chained_batches: u8, + pub chained_posts: u16, + pub stop_reason: TopicLoadMoreStopReason, +} diff --git a/crates/fire-models/src/topic_detail/tests.rs b/crates/fire-models/src/topic_detail/tests.rs new file mode 100644 index 00000000..538ba1a4 --- /dev/null +++ b/crates/fire-models/src/topic_detail/tests.rs @@ -0,0 +1,239 @@ +use super::*; + +#[test] +fn topic_detail_interaction_count_adds_non_heart_reactions_to_topic_likes() { + let detail = TopicDetail { + like_count: 21, + post_stream: TopicPostStream { + posts: vec![ + TopicPost { + reactions: vec![ + TopicReaction { + id: "heart".into(), + count: 5, + ..TopicReaction::default() + }, + TopicReaction { + id: "clap".into(), + count: 2, + ..TopicReaction::default() + }, + ], + ..TopicPost::default() + }, + TopicPost { + reactions: vec![TopicReaction { + id: "TADA".into(), + count: 3, + ..TopicReaction::default() + }], + ..TopicPost::default() + }, + ], + ..TopicPostStream::default() + }, + ..TopicDetail::default() + }; + + assert_eq!(detail.interaction_count(), 26); +} + +#[test] +fn topic_thread_groups_nested_replies_without_duplication() { + let thread = TopicThread::from_posts(&[ + topic_post(1, None), + topic_post(2, Some(1)), + topic_post(3, Some(2)), + topic_post(4, Some(3)), + topic_post(5, Some(1)), + topic_post(6, Some(99)), + ]); + + assert_eq!(thread.original_post_number, Some(1)); + assert_eq!( + thread + .reply_sections + .iter() + .map(|section| section.anchor_post_number) + .collect::>(), + vec![2, 5, 6] + ); + assert_eq!( + thread.reply_sections[0] + .replies + .iter() + .map(|reply| reply.post_number) + .collect::>(), + vec![3, 4] + ); + assert_eq!( + thread.reply_sections[0] + .replies + .iter() + .map(|reply| reply.depth) + .collect::>(), + vec![1, 2] + ); +} + +#[test] +fn topic_thread_flattens_to_display_order_posts() { + let posts = vec![ + topic_post(1, None), + topic_post(2, Some(1)), + topic_post(3, Some(2)), + topic_post(4, Some(3)), + topic_post(5, Some(1)), + topic_post(6, Some(99)), + ]; + let thread = TopicThread::from_posts(&posts); + + assert_eq!( + thread + .flatten(&posts) + .into_iter() + .map(|flat_post: TopicThreadFlatPost| ( + flat_post.post.post_number, + flat_post.depth, + flat_post.parent_post_number, + flat_post.shows_thread_line, + flat_post.is_original_post, + )) + .collect::>(), + vec![ + (1, 0, None, true, true), + (2, 0, None, true, false), + (3, 1, Some(2), true, false), + (4, 2, Some(3), true, false), + (5, 0, None, true, false), + (6, 0, None, false, false), + ] + ); +} + +#[test] +fn timeline_entries_floor_order_with_full_post_set() { + let posts = vec![ + topic_post(1, None), + topic_post(2, Some(1)), + topic_post(3, Some(2)), + topic_post(4, Some(1)), + ]; + let mut detail = TopicDetail { + post_stream: TopicPostStream { + posts, + stream: vec![1, 2, 3, 4], + }, + ..Default::default() + }; + detail.rebuild_timeline_entries(); + + assert_eq!(detail.timeline_entries.len(), 4); + assert_eq!(detail.timeline_entries[0].post_number, 1); + assert_eq!(detail.timeline_entries[0].depth, 0); + assert!(detail.timeline_entries[0].is_original_post); + assert_eq!(detail.timeline_entries[1].post_number, 2); + assert_eq!(detail.timeline_entries[1].depth, 1); + assert_eq!(detail.timeline_entries[1].parent_post_number, Some(1)); + assert_eq!(detail.timeline_entries[2].post_number, 3); + assert_eq!(detail.timeline_entries[2].depth, 2); + assert_eq!(detail.timeline_entries[2].parent_post_number, Some(2)); + assert_eq!(detail.timeline_entries[3].post_number, 4); + assert_eq!(detail.timeline_entries[3].depth, 1); + assert_eq!(detail.timeline_entries[3].parent_post_number, Some(1)); +} + +#[test] +fn timeline_entries_partial_set_falls_back_depth_for_missing_parents() { + // Simulate an anchored load that only has posts 5-7, where 5 replies to 3 (not loaded). + let posts = vec![ + topic_post(5, Some(3)), + topic_post(6, Some(5)), + topic_post(7, None), + ]; + let mut detail = TopicDetail { + post_stream: TopicPostStream { + posts, + stream: vec![1, 2, 3, 4, 5, 6, 7], + }, + ..Default::default() + }; + detail.rebuild_timeline_entries(); + + assert_eq!(detail.timeline_entries.len(), 3); + // Post 5 replies to 3 (not loaded) — depth falls back to 1. + assert_eq!(detail.timeline_entries[0].post_number, 5); + assert_eq!(detail.timeline_entries[0].depth, 1); + assert_eq!(detail.timeline_entries[0].parent_post_number, Some(3)); + assert!(detail.timeline_entries[0].is_original_post); // min in partial set + // Post 6 replies to 5 (loaded) — depth is 2. + assert_eq!(detail.timeline_entries[1].post_number, 6); + assert_eq!(detail.timeline_entries[1].depth, 2); + // Post 7 has no parent — depth is 0. + assert_eq!(detail.timeline_entries[2].post_number, 7); + assert_eq!(detail.timeline_entries[2].depth, 0); +} + +#[test] +fn timeline_entries_depth_self_corrects_after_hydration() { + // First: partial set with missing parent. + let partial_posts = vec![topic_post(5, Some(3)), topic_post(6, Some(5))]; + let mut detail = TopicDetail { + post_stream: TopicPostStream { + posts: partial_posts, + stream: vec![1, 2, 3, 4, 5, 6], + }, + ..Default::default() + }; + detail.rebuild_timeline_entries(); + assert_eq!(detail.timeline_entries[0].depth, 1); // fallback + + // Now hydrate: add post 3 (which replies to 1, also not loaded yet). + detail.post_stream.posts.insert(0, topic_post(3, Some(1))); + detail.rebuild_timeline_entries(); + + let entry5 = detail + .timeline_entries + .iter() + .find(|e| e.post_number == 5) + .unwrap(); + // Post 5 → parent 3 (loaded, depth 1 because 3's parent 1 is not loaded) → depth 2. + assert_eq!(entry5.depth, 2); +} + +fn topic_post(post_number: u32, reply_to_post_number: Option) -> TopicPost { + TopicPost { + id: u64::from(post_number), + username: format!("user-{post_number}"), + name: None, + avatar_template: None, + author_metadata: Default::default(), + cooked: format!("

{post_number}

"), + raw: None, + post_number, + post_type: 1, + created_at: None, + updated_at: None, + like_count: 0, + reply_count: 0, + reply_to_post_number, + reply_to_user: None, + bookmarked: false, + bookmark_id: None, + bookmark_name: None, + bookmark_reminder_at: None, + reactions: Vec::new(), + current_user_reaction: None, + boosts: Vec::new(), + can_boost: false, + polls: Vec::new(), + accepted_answer: false, + can_accept_answer: false, + can_unaccept_answer: false, + can_edit: false, + can_delete: false, + can_recover: false, + hidden: false, + presented: Default::default(), + } +} diff --git a/crates/fire-models/src/topic_detail/tree.rs b/crates/fire-models/src/topic_detail/tree.rs new file mode 100644 index 00000000..afdafd76 --- /dev/null +++ b/crates/fire-models/src/topic_detail/tree.rs @@ -0,0 +1,311 @@ +use std::collections::HashSet; + +use serde::{Deserialize, Serialize}; + +use super::post::TopicPost; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicTreePresentationQuery { + pub body_post: TopicPost, + pub raw_stream_ids: Vec, + pub loaded_posts: Vec, + pub focused_post_number: Option, + pub last_read_post_number: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicTreePresentation { + pub original_post_id: u64, + pub original_post_number: u32, + pub reply_rows: Vec, + pub total_loaded_post_count: u32, + pub visible_root_post_numbers: Vec, + pub first_unread_root_post_number: Option, + pub gained_new_root_progress: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicTreeRow { + pub post_id: u64, + pub post_number: u32, + pub root_post_number: u32, + pub parent_post_number: Option, + pub depth: u16, + pub preorder_index: u32, + pub has_children: bool, + pub sibling_index: u16, + pub is_last_sibling: bool, + pub descendant_count: u32, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicThreadReply { + pub post_number: u32, + pub depth: u32, + pub parent_post_number: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicThreadSection { + pub anchor_post_number: u32, + pub replies: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicThread { + pub original_post_number: Option, + pub reply_sections: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicThreadFlatPost { + pub post: TopicPost, + pub depth: u32, + pub parent_post_number: Option, + pub shows_thread_line: bool, + pub is_original_post: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TopicTimelineEntry { + pub post_id: u64, + pub post_number: u32, + pub parent_post_number: Option, + pub depth: u32, + pub is_original_post: bool, +} + +impl TopicThread { + pub fn from_posts(posts: &[TopicPost]) -> Self { + let Some(original_post) = posts.iter().min_by_key(|post| post.post_number) else { + return Self::default(); + }; + + let root_post_number = original_post.post_number; + let post_numbers: std::collections::HashSet = + posts.iter().map(|post| post.post_number).collect(); + let mut children_by_parent: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); + + for post in posts + .iter() + .filter(|post| post.post_number != root_post_number) + { + let Some(parent_post_number) = normalized_reply_target(post.reply_to_post_number) + else { + continue; + }; + if parent_post_number == post.post_number { + continue; + } + children_by_parent + .entry(parent_post_number) + .or_default() + .push(post); + } + + let mut consumed_post_numbers = std::collections::HashSet::from([root_post_number]); + let mut reply_sections = Vec::new(); + + for post in posts + .iter() + .filter(|post| post.post_number != root_post_number) + { + if consumed_post_numbers.contains(&post.post_number) { + continue; + } + + let normalized_parent = normalized_reply_target(post.reply_to_post_number); + let should_start_section = normalized_parent.is_none() + || normalized_parent == Some(root_post_number) + || normalized_parent.is_some_and(|parent| !post_numbers.contains(&parent)); + if !should_start_section { + continue; + } + + consumed_post_numbers.insert(post.post_number); + let mut branch_visited = std::collections::HashSet::from([post.post_number]); + let replies = flatten_thread_replies( + post.post_number, + 1, + &children_by_parent, + &mut consumed_post_numbers, + &mut branch_visited, + ); + reply_sections.push(TopicThreadSection { + anchor_post_number: post.post_number, + replies, + }); + } + + let remaining_post_numbers: Vec = posts + .iter() + .filter(|post| post.post_number != root_post_number) + .map(|post| post.post_number) + .filter(|post_number| !consumed_post_numbers.contains(post_number)) + .collect(); + + for post_number in remaining_post_numbers { + let Some(post) = posts.iter().find(|post| post.post_number == post_number) else { + continue; + }; + consumed_post_numbers.insert(post.post_number); + let mut branch_visited = std::collections::HashSet::from([post.post_number]); + let replies = flatten_thread_replies( + post.post_number, + 1, + &children_by_parent, + &mut consumed_post_numbers, + &mut branch_visited, + ); + reply_sections.push(TopicThreadSection { + anchor_post_number: post.post_number, + replies, + }); + } + + Self { + original_post_number: Some(root_post_number), + reply_sections, + } + } + + pub fn flatten(&self, posts: &[TopicPost]) -> Vec { + let posts_by_number: std::collections::HashMap = + posts.iter().map(|post| (post.post_number, post)).collect(); + let mut result = Vec::new(); + + if let Some(original_post) = self + .original_post_number + .and_then(|post_number| posts_by_number.get(&post_number)) + { + result.push(TopicThreadFlatPost { + post: (*original_post).clone(), + depth: 0, + parent_post_number: None, + shows_thread_line: !self.reply_sections.is_empty(), + is_original_post: true, + }); + } + + for (section_index, section) in self.reply_sections.iter().enumerate() { + let is_last_section = section_index == self.reply_sections.len() - 1; + let has_nested_replies = !section.replies.is_empty(); + + let Some(anchor_post) = posts_by_number.get(§ion.anchor_post_number) else { + continue; + }; + + result.push(TopicThreadFlatPost { + post: (*anchor_post).clone(), + depth: 0, + parent_post_number: None, + shows_thread_line: has_nested_replies || !is_last_section, + is_original_post: false, + }); + + for (reply_index, reply) in section.replies.iter().enumerate() { + let Some(reply_post) = posts_by_number.get(&reply.post_number) else { + continue; + }; + let is_last_reply = reply_index == section.replies.len() - 1; + result.push(TopicThreadFlatPost { + post: (*reply_post).clone(), + depth: reply.depth, + parent_post_number: reply.parent_post_number, + shows_thread_line: !is_last_reply || !is_last_section, + is_original_post: false, + }); + } + } + + result + } +} + +pub(super) fn normalized_reply_target(reply_to_post_number: Option) -> Option { + reply_to_post_number.filter(|post_number| *post_number > 0) +} + +pub(super) fn build_floor_timeline_entries(posts: &[TopicPost]) -> Vec { + let post_numbers: HashSet = posts.iter().map(|p| p.post_number).collect(); + let min_pn = posts.iter().map(|p| p.post_number).min().unwrap_or(0); + let mut sorted: Vec<&TopicPost> = posts.iter().collect(); + sorted.sort_by_key(|p| (p.post_number, p.id)); + + sorted + .iter() + .map(|post| { + let parent = normalized_reply_target(post.reply_to_post_number); + let depth = match parent { + Some(pn) if pn != post.post_number => { + compute_depth_walk(pn, posts, &post_numbers, 1) + } + _ => 0, + }; + TopicTimelineEntry { + post_id: post.id, + post_number: post.post_number, + parent_post_number: parent, + depth, + is_original_post: post.post_number == min_pn, + } + }) + .collect() +} + +pub(super) fn compute_depth_walk( + parent_pn: u32, + posts: &[TopicPost], + loaded: &HashSet, + current_depth: u32, +) -> u32 { + if !loaded.contains(&parent_pn) { + return current_depth; + } + match posts.iter().find(|p| p.post_number == parent_pn) { + Some(p) => match normalized_reply_target(p.reply_to_post_number) { + Some(gp) if gp != parent_pn => compute_depth_walk(gp, posts, loaded, current_depth + 1), + _ => current_depth, + }, + None => current_depth, + } +} + +pub(super) fn flatten_thread_replies( + parent_post_number: u32, + depth: u32, + children_by_parent: &std::collections::BTreeMap>, + consumed_post_numbers: &mut std::collections::HashSet, + branch_visited: &mut std::collections::HashSet, +) -> Vec { + let Some(children) = children_by_parent.get(&parent_post_number) else { + return Vec::new(); + }; + + let mut replies = Vec::new(); + for child in children { + if branch_visited.contains(&child.post_number) { + continue; + } + + consumed_post_numbers.insert(child.post_number); + replies.push(TopicThreadReply { + post_number: child.post_number, + depth, + parent_post_number: normalized_reply_target(child.reply_to_post_number), + }); + + branch_visited.insert(child.post_number); + replies.extend(flatten_thread_replies( + child.post_number, + depth + 1, + children_by_parent, + consumed_post_numbers, + branch_visited, + )); + branch_visited.remove(&child.post_number); + } + + replies +} diff --git a/crates/fire-models/src/topic_detail/uploads.rs b/crates/fire-models/src/topic_detail/uploads.rs new file mode 100644 index 00000000..dee0468f --- /dev/null +++ b/crates/fire-models/src/topic_detail/uploads.rs @@ -0,0 +1,21 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct UploadResult { + /// Discourse upload id (used by Chat `upload_ids` and similar write APIs). + pub id: Option, + pub short_url: String, + pub url: Option, + pub original_filename: Option, + pub width: Option, + pub height: Option, + pub thumbnail_width: Option, + pub thumbnail_height: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedUploadUrl { + pub short_url: String, + pub short_path: Option, + pub url: Option, +} diff --git a/crates/fire-models/src/user.rs b/crates/fire-models/src/user.rs index 51682e46..7028531e 100644 --- a/crates/fire-models/src/user.rs +++ b/crates/fire-models/src/user.rs @@ -301,3 +301,14 @@ impl Default for CurrentUserSnapshot { fn default_notification_channel_position() -> i64 { -1 } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn current_user_snapshot_default_notification_channel_position() { + let snapshot = CurrentUserSnapshot::default(); + assert_eq!(snapshot.notification_channel_position, -1); + } +} diff --git a/crates/fire-uniffi-chat/src/handle/channels.rs b/crates/fire-uniffi-chat/src/handle/channels.rs new file mode 100644 index 00000000..84b28cf7 --- /dev/null +++ b/crates/fire-uniffi-chat/src/handle/channels.rs @@ -0,0 +1,143 @@ +#[uniffi::export] +impl FireChatHandle { + pub async fn fetch_my_chat_channels(&self) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_my_chat_channels", panic_state, async move { + let base_url = inner.base_url().to_string(); + let channels = inner.fetch_my_chat_channels().await?; + Ok::<_, fire_core::FireCoreError>((base_url, channels)) + }) + .await?; + Ok(ChatStateMapper::new(&response.0).my_channels(response.1)) + } + + pub fn cached_my_chat_channels(&self) -> Result, FireUniFfiError> { + run_infallible( + &self.shared.panic_state, + &self.shared.core, + "cached_my_chat_channels", + |inner| { + let base_url = inner.base_url().to_string(); + inner + .cached_my_chat_channels() + .map(|channels| ChatStateMapper::new(&base_url).my_channels(channels)) + }, + ) + } + + pub async fn fetch_chat_channel( + &self, + channel_id: u64, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_chat_channel", panic_state, async move { + let base_url = inner.base_url().to_string(); + let channel = inner.fetch_chat_channel(channel_id).await?; + Ok::<_, fire_core::FireCoreError>((base_url, channel)) + }) + .await?; + Ok(ChatStateMapper::new(&response.0).channel(response.1)) + } + + pub async fn create_direct_message_channel( + &self, + request: CreateDirectMessageChannelRequestState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = + run_on_ffi_runtime("create_direct_message_channel", panic_state, async move { + let base_url = inner.base_url().to_string(); + let channel = inner.create_direct_message_channel(request.into()).await?; + Ok::<_, fire_core::FireCoreError>((base_url, channel)) + }) + .await?; + Ok(ChatStateMapper::new(&response.0).channel(response.1)) + } + + pub async fn mark_chat_channel_read( + &self, + channel_id: u64, + message_id: Option, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("mark_chat_channel_read", panic_state, async move { + inner.mark_chat_channel_read(channel_id, message_id).await + }) + .await + } + + pub async fn browse_chat_channels( + &self, + query: BrowseChatChannelsQueryState, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("browse_chat_channels", panic_state, async move { + let base_url = inner.base_url().to_string(); + let channels = inner.browse_chat_channels(query.into()).await?; + Ok::<_, fire_core::FireCoreError>((base_url, channels)) + }) + .await?; + Ok(response + .1 + .into_iter() + .map(|channel| ChatStateMapper::new(&response.0).channel(channel)) + .collect()) + } + + pub async fn join_chat_channel(&self, channel_id: u64) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("join_chat_channel", panic_state, async move { + inner.join_chat_channel(channel_id).await + }) + .await + } + + pub async fn leave_chat_channel(&self, channel_id: u64) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("leave_chat_channel", panic_state, async move { + inner.leave_chat_channel(channel_id).await + }) + .await + } + + pub async fn star_chat_channel( + &self, + channel_id: u64, + starred: bool, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("star_chat_channel", panic_state, async move { + inner.star_chat_channel(channel_id, starred).await + }) + .await + } + + pub async fn update_chat_channel_notifications( + &self, + channel_id: u64, + muted: Option, + notification_level: Option, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime( + "update_chat_channel_notifications", + panic_state, + async move { + inner + .update_chat_channel_notifications(channel_id, muted, notification_level) + .await + }, + ) + .await + } + +} diff --git a/crates/fire-uniffi-chat/src/handle/members.rs b/crates/fire-uniffi-chat/src/handle/members.rs new file mode 100644 index 00000000..56dbe65a --- /dev/null +++ b/crates/fire-uniffi-chat/src/handle/members.rs @@ -0,0 +1,36 @@ +#[uniffi::export] +impl FireChatHandle { + pub async fn fetch_chat_channel_members( + &self, + channel_id: u64, + offset: Option, + limit: Option, + username: Option, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_chat_channel_members", panic_state, async move { + inner + .fetch_chat_channel_members(channel_id, offset, limit, username) + .await + }) + .await?; + Ok(response.into_iter().map(Into::into).collect()) + } + + pub async fn search_chat_messages( + &self, + query: ChatSearchQueryState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("search_chat_messages", panic_state, async move { + let base_url = inner.base_url().to_string(); + let result = inner.search_chat_messages(query.into()).await?; + Ok::<_, fire_core::FireCoreError>((base_url, result)) + }) + .await?; + Ok(ChatStateMapper::new(&response.0).search_result(response.1)) + } + +} diff --git a/crates/fire-uniffi-chat/src/handle/messages.rs b/crates/fire-uniffi-chat/src/handle/messages.rs new file mode 100644 index 00000000..f8abc515 --- /dev/null +++ b/crates/fire-uniffi-chat/src/handle/messages.rs @@ -0,0 +1,96 @@ +#[uniffi::export] +impl FireChatHandle { + pub async fn fetch_chat_messages( + &self, + query: ChatMessagesQueryState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_chat_messages", panic_state, async move { + let base_url = inner.base_url().to_string(); + let messages = inner.fetch_chat_messages(query.into()).await?; + Ok::<_, fire_core::FireCoreError>((base_url, messages)) + }) + .await?; + Ok(ChatStateMapper::new(&response.0).messages(response.1)) + } + + pub fn cached_chat_messages( + &self, + channel_id: u64, + thread_id: Option, + ) -> Result, FireUniFfiError> { + run_infallible( + &self.shared.panic_state, + &self.shared.core, + "cached_chat_messages", + move |inner| { + let base_url = inner.base_url().to_string(); + inner + .cached_chat_messages(channel_id, thread_id.unwrap_or(0)) + .map(|messages| ChatStateMapper::new(&base_url).messages(messages)) + }, + ) + } + + pub async fn send_chat_message( + &self, + request: SendChatMessageRequestState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("send_chat_message", panic_state, async move { + inner.send_chat_message(request.into()).await + }) + .await?; + Ok(response.into()) + } + + pub async fn edit_chat_message( + &self, + channel_id: u64, + message_id: u64, + message: String, + upload_ids: Option>, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("edit_chat_message", panic_state, async move { + inner + .edit_chat_message(channel_id, message_id, message, upload_ids) + .await + }) + .await + } + + pub async fn delete_chat_message( + &self, + channel_id: u64, + message_id: u64, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("delete_chat_message", panic_state, async move { + inner.delete_chat_message(channel_id, message_id).await + }) + .await + } + + pub async fn react_chat_message( + &self, + channel_id: u64, + message_id: u64, + emoji: String, + react_action: String, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("react_chat_message", panic_state, async move { + inner + .react_chat_message(channel_id, message_id, emoji, react_action) + .await + }) + .await + } + +} diff --git a/crates/fire-uniffi-chat/src/handle/pins.rs b/crates/fire-uniffi-chat/src/handle/pins.rs new file mode 100644 index 00000000..07ed3e85 --- /dev/null +++ b/crates/fire-uniffi-chat/src/handle/pins.rs @@ -0,0 +1,60 @@ +#[uniffi::export] +impl FireChatHandle { + pub async fn fetch_chat_channel_pins( + &self, + channel_id: u64, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_chat_channel_pins", panic_state, async move { + let base_url = inner.base_url().to_string(); + let messages = inner.fetch_chat_channel_pins(channel_id).await?; + Ok::<_, fire_core::FireCoreError>((base_url, messages)) + }) + .await?; + Ok(response + .1 + .into_iter() + .map(|message| ChatStateMapper::new(&response.0).message(message)) + .collect()) + } + + pub async fn pin_chat_message( + &self, + channel_id: u64, + message_id: u64, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("pin_chat_message", panic_state, async move { + inner.pin_chat_message(channel_id, message_id).await + }) + .await + } + + pub async fn unpin_chat_message( + &self, + channel_id: u64, + message_id: u64, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("unpin_chat_message", panic_state, async move { + inner.unpin_chat_message(channel_id, message_id).await + }) + .await + } + + pub async fn mark_chat_channel_pins_read( + &self, + channel_id: u64, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("mark_chat_channel_pins_read", panic_state, async move { + inner.mark_chat_channel_pins_read(channel_id).await + }) + .await + } + +} diff --git a/crates/fire-uniffi-chat/src/handle/threads.rs b/crates/fire-uniffi-chat/src/handle/threads.rs new file mode 100644 index 00000000..32b0e581 --- /dev/null +++ b/crates/fire-uniffi-chat/src/handle/threads.rs @@ -0,0 +1,49 @@ +#[uniffi::export] +impl FireChatHandle { + pub async fn create_chat_thread( + &self, + channel_id: u64, + original_message_id: u64, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("create_chat_thread", panic_state, async move { + inner + .create_chat_thread(channel_id, original_message_id) + .await + }) + .await + } + + pub async fn fetch_chat_thread_messages( + &self, + channel_id: u64, + thread_id: u64, + query: ChatMessagesQueryState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_chat_thread_messages", panic_state, async move { + let base_url = inner.base_url().to_string(); + let messages = inner + .fetch_chat_thread_messages(channel_id, thread_id, query.into()) + .await?; + Ok::<_, fire_core::FireCoreError>((base_url, messages)) + }) + .await?; + Ok(ChatStateMapper::new(&response.0).messages(response.1)) + } + + pub async fn mark_chat_thread_read( + &self, + channel_id: u64, + thread_id: u64, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("mark_chat_thread_read", panic_state, async move { + inner.mark_chat_thread_read(channel_id, thread_id).await + }) + .await + } +} diff --git a/crates/fire-uniffi-chat/src/lib.rs b/crates/fire-uniffi-chat/src/lib.rs index 553a7656..67f9a4ce 100644 --- a/crates/fire-uniffi-chat/src/lib.rs +++ b/crates/fire-uniffi-chat/src/lib.rs @@ -29,379 +29,11 @@ impl FireChatHandle { } } -#[uniffi::export] -impl FireChatHandle { - pub async fn fetch_my_chat_channels(&self) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_my_chat_channels", panic_state, async move { - let base_url = inner.base_url().to_string(); - let channels = inner.fetch_my_chat_channels().await?; - Ok::<_, fire_core::FireCoreError>((base_url, channels)) - }) - .await?; - Ok(ChatStateMapper::new(&response.0).my_channels(response.1)) - } - - pub fn cached_my_chat_channels(&self) -> Result, FireUniFfiError> { - run_infallible( - &self.shared.panic_state, - &self.shared.core, - "cached_my_chat_channels", - |inner| { - let base_url = inner.base_url().to_string(); - inner - .cached_my_chat_channels() - .map(|channels| ChatStateMapper::new(&base_url).my_channels(channels)) - }, - ) - } - - pub async fn fetch_chat_channel( - &self, - channel_id: u64, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_chat_channel", panic_state, async move { - let base_url = inner.base_url().to_string(); - let channel = inner.fetch_chat_channel(channel_id).await?; - Ok::<_, fire_core::FireCoreError>((base_url, channel)) - }) - .await?; - Ok(ChatStateMapper::new(&response.0).channel(response.1)) - } - - pub async fn create_direct_message_channel( - &self, - request: CreateDirectMessageChannelRequestState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = - run_on_ffi_runtime("create_direct_message_channel", panic_state, async move { - let base_url = inner.base_url().to_string(); - let channel = inner.create_direct_message_channel(request.into()).await?; - Ok::<_, fire_core::FireCoreError>((base_url, channel)) - }) - .await?; - Ok(ChatStateMapper::new(&response.0).channel(response.1)) - } - - pub async fn fetch_chat_messages( - &self, - query: ChatMessagesQueryState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_chat_messages", panic_state, async move { - let base_url = inner.base_url().to_string(); - let messages = inner.fetch_chat_messages(query.into()).await?; - Ok::<_, fire_core::FireCoreError>((base_url, messages)) - }) - .await?; - Ok(ChatStateMapper::new(&response.0).messages(response.1)) - } - - pub fn cached_chat_messages( - &self, - channel_id: u64, - thread_id: Option, - ) -> Result, FireUniFfiError> { - run_infallible( - &self.shared.panic_state, - &self.shared.core, - "cached_chat_messages", - move |inner| { - let base_url = inner.base_url().to_string(); - inner - .cached_chat_messages(channel_id, thread_id.unwrap_or(0)) - .map(|messages| ChatStateMapper::new(&base_url).messages(messages)) - }, - ) - } - - pub async fn send_chat_message( - &self, - request: SendChatMessageRequestState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("send_chat_message", panic_state, async move { - inner.send_chat_message(request.into()).await - }) - .await?; - Ok(response.into()) - } - - pub async fn mark_chat_channel_read( - &self, - channel_id: u64, - message_id: Option, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("mark_chat_channel_read", panic_state, async move { - inner.mark_chat_channel_read(channel_id, message_id).await - }) - .await - } - - pub async fn browse_chat_channels( - &self, - query: BrowseChatChannelsQueryState, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("browse_chat_channels", panic_state, async move { - let base_url = inner.base_url().to_string(); - let channels = inner.browse_chat_channels(query.into()).await?; - Ok::<_, fire_core::FireCoreError>((base_url, channels)) - }) - .await?; - Ok(response - .1 - .into_iter() - .map(|channel| ChatStateMapper::new(&response.0).channel(channel)) - .collect()) - } - - pub async fn join_chat_channel(&self, channel_id: u64) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("join_chat_channel", panic_state, async move { - inner.join_chat_channel(channel_id).await - }) - .await - } - - pub async fn leave_chat_channel(&self, channel_id: u64) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("leave_chat_channel", panic_state, async move { - inner.leave_chat_channel(channel_id).await - }) - .await - } - - pub async fn star_chat_channel( - &self, - channel_id: u64, - starred: bool, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("star_chat_channel", panic_state, async move { - inner.star_chat_channel(channel_id, starred).await - }) - .await - } - - pub async fn update_chat_channel_notifications( - &self, - channel_id: u64, - muted: Option, - notification_level: Option, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime( - "update_chat_channel_notifications", - panic_state, - async move { - inner - .update_chat_channel_notifications(channel_id, muted, notification_level) - .await - }, - ) - .await - } - - pub async fn edit_chat_message( - &self, - channel_id: u64, - message_id: u64, - message: String, - upload_ids: Option>, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("edit_chat_message", panic_state, async move { - inner - .edit_chat_message(channel_id, message_id, message, upload_ids) - .await - }) - .await - } - - pub async fn delete_chat_message( - &self, - channel_id: u64, - message_id: u64, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("delete_chat_message", panic_state, async move { - inner.delete_chat_message(channel_id, message_id).await - }) - .await - } - - pub async fn react_chat_message( - &self, - channel_id: u64, - message_id: u64, - emoji: String, - react_action: String, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("react_chat_message", panic_state, async move { - inner - .react_chat_message(channel_id, message_id, emoji, react_action) - .await - }) - .await - } - - pub async fn fetch_chat_channel_members( - &self, - channel_id: u64, - offset: Option, - limit: Option, - username: Option, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_chat_channel_members", panic_state, async move { - inner - .fetch_chat_channel_members(channel_id, offset, limit, username) - .await - }) - .await?; - Ok(response.into_iter().map(Into::into).collect()) - } - - pub async fn search_chat_messages( - &self, - query: ChatSearchQueryState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("search_chat_messages", panic_state, async move { - let base_url = inner.base_url().to_string(); - let result = inner.search_chat_messages(query.into()).await?; - Ok::<_, fire_core::FireCoreError>((base_url, result)) - }) - .await?; - Ok(ChatStateMapper::new(&response.0).search_result(response.1)) - } - - pub async fn fetch_chat_channel_pins( - &self, - channel_id: u64, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_chat_channel_pins", panic_state, async move { - let base_url = inner.base_url().to_string(); - let messages = inner.fetch_chat_channel_pins(channel_id).await?; - Ok::<_, fire_core::FireCoreError>((base_url, messages)) - }) - .await?; - Ok(response - .1 - .into_iter() - .map(|message| ChatStateMapper::new(&response.0).message(message)) - .collect()) - } - - pub async fn pin_chat_message( - &self, - channel_id: u64, - message_id: u64, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("pin_chat_message", panic_state, async move { - inner.pin_chat_message(channel_id, message_id).await - }) - .await - } - - pub async fn unpin_chat_message( - &self, - channel_id: u64, - message_id: u64, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("unpin_chat_message", panic_state, async move { - inner.unpin_chat_message(channel_id, message_id).await - }) - .await - } - - pub async fn mark_chat_channel_pins_read( - &self, - channel_id: u64, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("mark_chat_channel_pins_read", panic_state, async move { - inner.mark_chat_channel_pins_read(channel_id).await - }) - .await - } - - pub async fn create_chat_thread( - &self, - channel_id: u64, - original_message_id: u64, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("create_chat_thread", panic_state, async move { - inner - .create_chat_thread(channel_id, original_message_id) - .await - }) - .await - } - - pub async fn fetch_chat_thread_messages( - &self, - channel_id: u64, - thread_id: u64, - query: ChatMessagesQueryState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_chat_thread_messages", panic_state, async move { - let base_url = inner.base_url().to_string(); - let messages = inner - .fetch_chat_thread_messages(channel_id, thread_id, query.into()) - .await?; - Ok::<_, fire_core::FireCoreError>((base_url, messages)) - }) - .await?; - Ok(ChatStateMapper::new(&response.0).messages(response.1)) - } - - pub async fn mark_chat_thread_read( - &self, - channel_id: u64, - thread_id: u64, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("mark_chat_thread_read", panic_state, async move { - inner.mark_chat_thread_read(channel_id, thread_id).await - }) - .await - } -} - +include!("handle/channels.rs"); +include!("handle/messages.rs"); +include!("handle/members.rs"); +include!("handle/pins.rs"); +include!("handle/threads.rs"); /// Lift a live chat MessageBus payload into a UI-ready message. /// /// Hosts must not parse cooked HTML or synthesize presentation themselves. diff --git a/crates/fire-uniffi-chat/src/records.rs b/crates/fire-uniffi-chat/src/records.rs deleted file mode 100644 index 4263f490..00000000 --- a/crates/fire-uniffi-chat/src/records.rs +++ /dev/null @@ -1,659 +0,0 @@ -use std::sync::Arc; - -use fire_models::{ - BrowseChatChannelsQuery, ChatBusEvent, ChatBusLastIdEntry, ChatChannel, ChatChannelBusLastIds, - ChatChannelMember, ChatChannelMembership, ChatChannelTrackingEntry, ChatMessage, - ChatMessageBookmark, ChatMessageReaction, ChatMessageReplyRef, ChatMessagesQuery, - ChatMessagesResponse, ChatReactionAction, ChatSearchQuery, ChatSearchResult, ChatThreadRef, - ChatUpload, ChatUser, CreateDirectMessageChannelRequest, MyChatChannelsResponse, - SendChatMessageRequest, SendChatMessageResult, -}; -use fire_uniffi_types::{intern_presented_handle, RenderDocumentHandle}; - -#[derive(Clone, Copy)] -pub(crate) struct ChatStateMapper<'a> { - base_url: &'a str, -} - -impl<'a> ChatStateMapper<'a> { - pub(crate) fn new(base_url: &'a str) -> Self { - Self { base_url } - } - - pub(crate) fn message(&self, value: ChatMessage) -> ChatMessageState { - chat_message_state_from_model(value, self.base_url) - } - - pub(crate) fn channel(&self, value: ChatChannel) -> ChatChannelState { - chat_channel_state_from_model(value, self.base_url) - } - - pub(crate) fn messages(&self, value: ChatMessagesResponse) -> ChatMessagesState { - ChatMessagesState { - messages: value - .messages - .into_iter() - .map(|message| self.message(message)) - .collect(), - can_load_more_past: value.can_load_more_past, - can_load_more_future: value.can_load_more_future, - target_message_id: value.target_message_id, - } - } - - pub(crate) fn my_channels(&self, value: MyChatChannelsResponse) -> MyChatChannelsState { - let total_unread_badge = value.total_unread_badge(); - let inbox_channels = value - .inbox_channels() - .into_iter() - .cloned() - .map(|channel| self.channel(channel)) - .collect(); - MyChatChannelsState { - public_channels: value - .public_channels - .into_iter() - .map(|channel| self.channel(channel)) - .collect(), - direct_message_channels: value - .direct_message_channels - .into_iter() - .map(|channel| self.channel(channel)) - .collect(), - inbox_channels, - channel_tracking: value.channel_tracking.into_iter().map(Into::into).collect(), - global_bus_last_ids: value - .global_bus_last_ids - .into_iter() - .map(Into::into) - .collect(), - total_unread_badge, - } - } - - pub(crate) fn search_result(&self, value: ChatSearchResult) -> ChatSearchResultState { - ChatSearchResultState { - messages: value - .messages - .into_iter() - .map(|message| self.message(message)) - .collect(), - has_more: value.has_more, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatUserState { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -impl From for ChatUserState { - fn from(value: ChatUser) -> Self { - Self { - id: value.id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatChannelMembershipState { - pub following: bool, - pub muted: bool, - pub starred: bool, - pub notification_level: Option, - pub last_read_message_id: Option, - pub last_viewed_at: Option, -} - -impl From for ChatChannelMembershipState { - fn from(value: ChatChannelMembership) -> Self { - Self { - following: value.following, - muted: value.muted, - starred: value.starred, - notification_level: value.notification_level, - last_read_message_id: value.last_read_message_id, - last_viewed_at: value.last_viewed_at, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatChannelBusLastIdsState { - pub channel_message_bus_last_id: Option, - pub new_messages: Option, - pub new_mentions: Option, - pub kick: Option, -} - -impl From for ChatChannelBusLastIdsState { - fn from(value: ChatChannelBusLastIds) -> Self { - Self { - channel_message_bus_last_id: value.channel_message_bus_last_id, - new_messages: value.new_messages, - new_mentions: value.new_mentions, - kick: value.kick, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatUploadState { - pub id: u64, - pub url: Option, - pub short_url: Option, - pub original_filename: Option, - pub extension: Option, - pub width: Option, - pub height: Option, - pub thumbnail_width: Option, - pub thumbnail_height: Option, - pub dominant_color: Option, -} - -impl From for ChatUploadState { - fn from(value: ChatUpload) -> Self { - Self { - id: value.id, - url: value.url, - short_url: value.short_url, - original_filename: value.original_filename, - extension: value.extension, - width: value.width, - height: value.height, - thumbnail_width: value.thumbnail_width, - thumbnail_height: value.thumbnail_height, - dominant_color: value.dominant_color, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatMessageReactionState { - pub emoji: String, - pub count: u32, - pub reacted: bool, - pub users: Vec, -} - -impl From for ChatMessageReactionState { - fn from(value: ChatMessageReaction) -> Self { - Self { - emoji: value.emoji, - count: value.count, - reacted: value.reacted, - users: value.users.into_iter().map(Into::into).collect(), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatMessageReplyRefState { - pub id: u64, - pub excerpt: Option, - pub user: Option, -} - -impl From for ChatMessageReplyRefState { - fn from(value: ChatMessageReplyRef) -> Self { - Self { - id: value.id, - excerpt: value.excerpt, - user: value.user.map(Into::into), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatThreadRefState { - pub id: u64, - pub title: Option, - pub reply_count: u32, - pub last_reply_created_at: Option, - pub last_reply_excerpt: Option, - pub last_reply_user: Option, - pub participants: Vec, -} - -impl From for ChatThreadRefState { - fn from(value: ChatThreadRef) -> Self { - Self { - id: value.id, - title: value.title, - reply_count: value.reply_count, - last_reply_created_at: value.last_reply_created_at, - last_reply_excerpt: value.last_reply_excerpt, - last_reply_user: value.last_reply_user.map(Into::into), - participants: value.participants.into_iter().map(Into::into).collect(), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatMessageBookmarkState { - pub id: u64, - pub name: Option, - pub reminder_at: Option, -} - -impl From for ChatMessageBookmarkState { - fn from(value: ChatMessageBookmark) -> Self { - Self { - id: value.id, - name: value.name, - reminder_at: value.reminder_at, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatMessageState { - pub id: u64, - pub channel_id: u64, - pub message: String, - pub presentation: Option>, - pub excerpt: Option, - pub preview_text: String, - pub created_at: Option, - pub deleted_at: Option, - pub deleted_by_id: Option, - pub edited: bool, - pub thread_id: Option, - pub thread: Option, - pub user: Option, - pub mentioned_users: Vec, - pub reactions: Vec, - pub uploads: Vec, - pub in_reply_to: Option, - pub streaming: bool, - pub available_flags: Vec, - pub user_flag_status: Option, - pub bookmark: Option, - pub pinned: bool, - pub is_deleted: bool, -} - -fn chat_message_state_from_model(value: ChatMessage, _base_url: &str) -> ChatMessageState { - let preview_text = value.preview_text(); - let is_deleted = value.is_deleted(); - let presentation = value.presented.arc().map(intern_presented_handle); - ChatMessageState { - id: value.id, - channel_id: value.channel_id, - message: value.message, - presentation, - excerpt: value.excerpt, - preview_text, - created_at: value.created_at, - deleted_at: value.deleted_at, - deleted_by_id: value.deleted_by_id, - edited: value.edited, - thread_id: value.thread_id, - thread: value.thread.map(Into::into), - user: value.user.map(Into::into), - mentioned_users: value.mentioned_users.into_iter().map(Into::into).collect(), - reactions: value.reactions.into_iter().map(Into::into).collect(), - uploads: value.uploads.into_iter().map(Into::into).collect(), - in_reply_to: value.in_reply_to.map(Into::into), - streaming: value.streaming, - available_flags: value.available_flags, - user_flag_status: value.user_flag_status, - bookmark: value.bookmark.map(Into::into), - pinned: value.pinned, - is_deleted, - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatChannelState { - pub id: u64, - pub title: Option, - pub unicode_title: Option, - pub display_title: String, - pub slug: Option, - pub description: Option, - pub chatable_type: String, - pub status: Option, - pub threading_enabled: bool, - pub memberships_count: Option, - pub is_group_dm: bool, - pub is_direct_message: bool, - pub is_public_channel: bool, - pub dm_users: Vec, - pub category_color: Option, - pub category_name: Option, - pub emoji: Option, - pub formatted_emoji: Option, - pub current_user_membership: Option, - pub last_message: Option, - pub bus_last_ids: ChatChannelBusLastIdsState, - pub can_moderate: bool, - pub can_manage_pins: bool, - pub can_delete_self: bool, - pub can_delete_others: bool, - pub can_remove_members: bool, - pub can_flag: bool, -} - -fn chat_channel_state_from_model(value: ChatChannel, base_url: &str) -> ChatChannelState { - let display_title = value.display_title(); - let is_direct_message = value.is_direct_message(); - let is_public_channel = value.is_public_channel(); - let formatted_emoji = value.formatted_emoji(); - ChatChannelState { - id: value.id, - title: value.title, - unicode_title: value.unicode_title, - display_title, - slug: value.slug, - description: value.description, - chatable_type: value.chatable_type, - status: value.status, - threading_enabled: value.threading_enabled, - memberships_count: value.memberships_count, - is_group_dm: value.is_group_dm, - is_direct_message, - is_public_channel, - dm_users: value.dm_users.into_iter().map(Into::into).collect(), - category_color: value.category_color, - category_name: value.category_name, - emoji: value.emoji, - formatted_emoji, - current_user_membership: value.current_user_membership.map(Into::into), - last_message: value - .last_message - .map(|message| chat_message_state_from_model(message, base_url)), - bus_last_ids: value.bus_last_ids.into(), - can_moderate: value.can_moderate, - can_manage_pins: value.can_manage_pins, - can_delete_self: value.can_delete_self, - can_delete_others: value.can_delete_others, - can_remove_members: value.can_remove_members, - can_flag: value.can_flag, - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatChannelTrackingEntryState { - pub channel_id: u64, - pub unread_count: u32, - pub mention_count: u32, -} - -impl From for ChatChannelTrackingEntryState { - fn from(value: ChatChannelTrackingEntry) -> Self { - Self { - channel_id: value.channel_id, - unread_count: value.unread_count, - mention_count: value.mention_count, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatBusLastIdEntryState { - pub channel: String, - pub last_id: i64, -} - -impl From for ChatBusLastIdEntryState { - fn from(value: ChatBusLastIdEntry) -> Self { - Self { - channel: value.channel, - last_id: value.last_id, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct MyChatChannelsState { - pub public_channels: Vec, - pub direct_message_channels: Vec, - pub inbox_channels: Vec, - pub channel_tracking: Vec, - pub global_bus_last_ids: Vec, - pub total_unread_badge: u32, -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatMessagesQueryState { - pub channel_id: u64, - pub direction: Option, - pub target_message_id: Option, - pub fetch_from_last_read: bool, - pub page_size: Option, -} - -impl From for ChatMessagesQuery { - fn from(value: ChatMessagesQueryState) -> Self { - Self { - channel_id: value.channel_id, - direction: value.direction, - target_message_id: value.target_message_id, - fetch_from_last_read: value.fetch_from_last_read, - page_size: value.page_size, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatMessagesState { - pub messages: Vec, - pub can_load_more_past: bool, - pub can_load_more_future: bool, - pub target_message_id: Option, -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct CreateDirectMessageChannelRequestState { - pub target_usernames: Vec, - pub name: Option, - pub upsert: bool, -} - -impl From for CreateDirectMessageChannelRequest { - fn from(value: CreateDirectMessageChannelRequestState) -> Self { - Self { - target_usernames: value.target_usernames, - name: value.name, - upsert: value.upsert, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct SendChatMessageRequestState { - pub channel_id: u64, - pub message: String, - pub staged_id: Option, - pub in_reply_to_id: Option, - pub thread_id: Option, - pub upload_ids: Vec, -} - -impl From for SendChatMessageRequest { - fn from(value: SendChatMessageRequestState) -> Self { - Self { - channel_id: value.channel_id, - message: value.message, - staged_id: value.staged_id, - in_reply_to_id: value.in_reply_to_id, - thread_id: value.thread_id, - upload_ids: value.upload_ids, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct SendChatMessageResultState { - pub message_id: Option, -} - -impl From for SendChatMessageResultState { - fn from(value: SendChatMessageResult) -> Self { - Self { - message_id: value.message_id, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct BrowseChatChannelsQueryState { - pub filter: Option, - pub offset: Option, - pub limit: Option, -} - -impl From for BrowseChatChannelsQuery { - fn from(value: BrowseChatChannelsQueryState) -> Self { - Self { - filter: value.filter, - offset: value.offset, - limit: value.limit, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatChannelMemberState { - pub user: ChatUserState, - pub following: bool, - pub muted: bool, -} - -impl From for ChatChannelMemberState { - fn from(value: ChatChannelMember) -> Self { - Self { - user: value.user.into(), - following: value.following, - muted: value.muted, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatSearchQueryState { - pub query: String, - pub channel_id: Option, - pub offset: Option, - pub limit: Option, -} - -impl From for ChatSearchQuery { - fn from(value: ChatSearchQueryState) -> Self { - Self { - query: value.query, - channel_id: value.channel_id, - offset: value.offset, - limit: value.limit, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ChatSearchResultState { - pub messages: Vec, - pub has_more: bool, -} - -#[derive(uniffi::Enum, Debug, Clone, Copy)] -pub enum ChatReactionActionState { - Add, - Remove, -} - -impl From for ChatReactionActionState { - fn from(value: ChatReactionAction) -> Self { - match value { - ChatReactionAction::Add => Self::Add, - ChatReactionAction::Remove => Self::Remove, - } - } -} - -#[derive(uniffi::Enum, Debug, Clone)] -pub enum ChatBusEventState { - MessageUpsert { - message: ChatMessageState, - }, - MessageDeleted { - id: u64, - }, - Reaction { - message_id: u64, - emoji: String, - action: ChatReactionActionState, - actor_id: Option, - }, - Tracking { - channel_id: u64, - unread: u32, - mention: u32, - thread_id: Option, - }, - ChannelUpsert { - channel: ChatChannelState, - }, - NewMessages { - channel_id: u64, - is_channel_level: bool, - message: Option, - actor_id: Option, - }, - Ignored, -} - -impl ChatStateMapper<'_> { - pub(crate) fn bus_event(&self, value: ChatBusEvent) -> ChatBusEventState { - match value { - ChatBusEvent::MessageUpsert { message } => ChatBusEventState::MessageUpsert { - message: self.message(*message), - }, - ChatBusEvent::MessageDeleted { id } => ChatBusEventState::MessageDeleted { id }, - ChatBusEvent::Reaction { - message_id, - emoji, - action, - actor_id, - } => ChatBusEventState::Reaction { - message_id, - emoji, - action: action.into(), - actor_id, - }, - ChatBusEvent::Tracking { - channel_id, - unread, - mention, - thread_id, - } => ChatBusEventState::Tracking { - channel_id, - unread, - mention, - thread_id, - }, - ChatBusEvent::ChannelUpsert { channel } => ChatBusEventState::ChannelUpsert { - channel: self.channel(*channel), - }, - ChatBusEvent::NewMessages { - channel_id, - is_channel_level, - message, - actor_id, - } => ChatBusEventState::NewMessages { - channel_id, - is_channel_level, - message: message.map(|item| self.message(*item)), - actor_id, - }, - ChatBusEvent::Ignored => ChatBusEventState::Ignored, - } - } -} diff --git a/crates/fire-uniffi-chat/src/records/attachments.rs b/crates/fire-uniffi-chat/src/records/attachments.rs new file mode 100644 index 00000000..a23e7dd8 --- /dev/null +++ b/crates/fire-uniffi-chat/src/records/attachments.rs @@ -0,0 +1,109 @@ +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatUploadState { + pub id: u64, + pub url: Option, + pub short_url: Option, + pub original_filename: Option, + pub extension: Option, + pub width: Option, + pub height: Option, + pub thumbnail_width: Option, + pub thumbnail_height: Option, + pub dominant_color: Option, +} + +impl From for ChatUploadState { + fn from(value: ChatUpload) -> Self { + Self { + id: value.id, + url: value.url, + short_url: value.short_url, + original_filename: value.original_filename, + extension: value.extension, + width: value.width, + height: value.height, + thumbnail_width: value.thumbnail_width, + thumbnail_height: value.thumbnail_height, + dominant_color: value.dominant_color, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatMessageReactionState { + pub emoji: String, + pub count: u32, + pub reacted: bool, + pub users: Vec, +} + +impl From for ChatMessageReactionState { + fn from(value: ChatMessageReaction) -> Self { + Self { + emoji: value.emoji, + count: value.count, + reacted: value.reacted, + users: value.users.into_iter().map(Into::into).collect(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatMessageReplyRefState { + pub id: u64, + pub excerpt: Option, + pub user: Option, +} + +impl From for ChatMessageReplyRefState { + fn from(value: ChatMessageReplyRef) -> Self { + Self { + id: value.id, + excerpt: value.excerpt, + user: value.user.map(Into::into), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatThreadRefState { + pub id: u64, + pub title: Option, + pub reply_count: u32, + pub last_reply_created_at: Option, + pub last_reply_excerpt: Option, + pub last_reply_user: Option, + pub participants: Vec, +} + +impl From for ChatThreadRefState { + fn from(value: ChatThreadRef) -> Self { + Self { + id: value.id, + title: value.title, + reply_count: value.reply_count, + last_reply_created_at: value.last_reply_created_at, + last_reply_excerpt: value.last_reply_excerpt, + last_reply_user: value.last_reply_user.map(Into::into), + participants: value.participants.into_iter().map(Into::into).collect(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatMessageBookmarkState { + pub id: u64, + pub name: Option, + pub reminder_at: Option, +} + +impl From for ChatMessageBookmarkState { + fn from(value: ChatMessageBookmark) -> Self { + Self { + id: value.id, + name: value.name, + reminder_at: value.reminder_at, + } + } +} + diff --git a/crates/fire-uniffi-chat/src/records/bus.rs b/crates/fire-uniffi-chat/src/records/bus.rs new file mode 100644 index 00000000..aee8494f --- /dev/null +++ b/crates/fire-uniffi-chat/src/records/bus.rs @@ -0,0 +1,94 @@ +#[derive(uniffi::Enum, Debug, Clone, Copy)] +pub enum ChatReactionActionState { + Add, + Remove, +} + +impl From for ChatReactionActionState { + fn from(value: ChatReactionAction) -> Self { + match value { + ChatReactionAction::Add => Self::Add, + ChatReactionAction::Remove => Self::Remove, + } + } +} + +#[derive(uniffi::Enum, Debug, Clone)] +pub enum ChatBusEventState { + MessageUpsert { + message: ChatMessageState, + }, + MessageDeleted { + id: u64, + }, + Reaction { + message_id: u64, + emoji: String, + action: ChatReactionActionState, + actor_id: Option, + }, + Tracking { + channel_id: u64, + unread: u32, + mention: u32, + thread_id: Option, + }, + ChannelUpsert { + channel: ChatChannelState, + }, + NewMessages { + channel_id: u64, + is_channel_level: bool, + message: Option, + actor_id: Option, + }, + Ignored, +} + +impl ChatStateMapper<'_> { + pub(crate) fn bus_event(&self, value: ChatBusEvent) -> ChatBusEventState { + match value { + ChatBusEvent::MessageUpsert { message } => ChatBusEventState::MessageUpsert { + message: self.message(*message), + }, + ChatBusEvent::MessageDeleted { id } => ChatBusEventState::MessageDeleted { id }, + ChatBusEvent::Reaction { + message_id, + emoji, + action, + actor_id, + } => ChatBusEventState::Reaction { + message_id, + emoji, + action: action.into(), + actor_id, + }, + ChatBusEvent::Tracking { + channel_id, + unread, + mention, + thread_id, + } => ChatBusEventState::Tracking { + channel_id, + unread, + mention, + thread_id, + }, + ChatBusEvent::ChannelUpsert { channel } => ChatBusEventState::ChannelUpsert { + channel: self.channel(*channel), + }, + ChatBusEvent::NewMessages { + channel_id, + is_channel_level, + message, + actor_id, + } => ChatBusEventState::NewMessages { + channel_id, + is_channel_level, + message: message.map(|item| self.message(*item)), + actor_id, + }, + ChatBusEvent::Ignored => ChatBusEventState::Ignored, + } + } +} diff --git a/crates/fire-uniffi-chat/src/records/channels.rs b/crates/fire-uniffi-chat/src/records/channels.rs new file mode 100644 index 00000000..97f796ea --- /dev/null +++ b/crates/fire-uniffi-chat/src/records/channels.rs @@ -0,0 +1,162 @@ +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatChannelState { + pub id: u64, + pub title: Option, + pub unicode_title: Option, + pub display_title: String, + pub slug: Option, + pub description: Option, + pub chatable_type: String, + pub status: Option, + pub threading_enabled: bool, + pub memberships_count: Option, + pub is_group_dm: bool, + pub is_direct_message: bool, + pub is_public_channel: bool, + pub dm_users: Vec, + pub category_color: Option, + pub category_name: Option, + pub emoji: Option, + pub formatted_emoji: Option, + pub current_user_membership: Option, + pub last_message: Option, + pub bus_last_ids: ChatChannelBusLastIdsState, + pub can_moderate: bool, + pub can_manage_pins: bool, + pub can_delete_self: bool, + pub can_delete_others: bool, + pub can_remove_members: bool, + pub can_flag: bool, +} + +fn chat_channel_state_from_model(value: ChatChannel, base_url: &str) -> ChatChannelState { + let display_title = value.display_title(); + let is_direct_message = value.is_direct_message(); + let is_public_channel = value.is_public_channel(); + let formatted_emoji = value.formatted_emoji(); + ChatChannelState { + id: value.id, + title: value.title, + unicode_title: value.unicode_title, + display_title, + slug: value.slug, + description: value.description, + chatable_type: value.chatable_type, + status: value.status, + threading_enabled: value.threading_enabled, + memberships_count: value.memberships_count, + is_group_dm: value.is_group_dm, + is_direct_message, + is_public_channel, + dm_users: value.dm_users.into_iter().map(Into::into).collect(), + category_color: value.category_color, + category_name: value.category_name, + emoji: value.emoji, + formatted_emoji, + current_user_membership: value.current_user_membership.map(Into::into), + last_message: value + .last_message + .map(|message| chat_message_state_from_model(message, base_url)), + bus_last_ids: value.bus_last_ids.into(), + can_moderate: value.can_moderate, + can_manage_pins: value.can_manage_pins, + can_delete_self: value.can_delete_self, + can_delete_others: value.can_delete_others, + can_remove_members: value.can_remove_members, + can_flag: value.can_flag, + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatChannelTrackingEntryState { + pub channel_id: u64, + pub unread_count: u32, + pub mention_count: u32, +} + +impl From for ChatChannelTrackingEntryState { + fn from(value: ChatChannelTrackingEntry) -> Self { + Self { + channel_id: value.channel_id, + unread_count: value.unread_count, + mention_count: value.mention_count, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatBusLastIdEntryState { + pub channel: String, + pub last_id: i64, +} + +impl From for ChatBusLastIdEntryState { + fn from(value: ChatBusLastIdEntry) -> Self { + Self { + channel: value.channel, + last_id: value.last_id, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct MyChatChannelsState { + pub public_channels: Vec, + pub direct_message_channels: Vec, + pub inbox_channels: Vec, + pub channel_tracking: Vec, + pub global_bus_last_ids: Vec, + pub total_unread_badge: u32, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct CreateDirectMessageChannelRequestState { + pub target_usernames: Vec, + pub name: Option, + pub upsert: bool, +} + +impl From for CreateDirectMessageChannelRequest { + fn from(value: CreateDirectMessageChannelRequestState) -> Self { + Self { + target_usernames: value.target_usernames, + name: value.name, + upsert: value.upsert, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct BrowseChatChannelsQueryState { + pub filter: Option, + pub offset: Option, + pub limit: Option, +} + +impl From for BrowseChatChannelsQuery { + fn from(value: BrowseChatChannelsQueryState) -> Self { + Self { + filter: value.filter, + offset: value.offset, + limit: value.limit, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatChannelMemberState { + pub user: ChatUserState, + pub following: bool, + pub muted: bool, +} + +impl From for ChatChannelMemberState { + fn from(value: ChatChannelMember) -> Self { + Self { + user: value.user.into(), + following: value.following, + muted: value.muted, + } + } +} + diff --git a/crates/fire-uniffi-chat/src/records/mapper.rs b/crates/fire-uniffi-chat/src/records/mapper.rs new file mode 100644 index 00000000..51954885 --- /dev/null +++ b/crates/fire-uniffi-chat/src/records/mapper.rs @@ -0,0 +1,73 @@ +#[derive(Clone, Copy)] +pub(crate) struct ChatStateMapper<'a> { + base_url: &'a str, +} + +impl<'a> ChatStateMapper<'a> { + pub(crate) fn new(base_url: &'a str) -> Self { + Self { base_url } + } + + pub(crate) fn message(&self, value: ChatMessage) -> ChatMessageState { + chat_message_state_from_model(value, self.base_url) + } + + pub(crate) fn channel(&self, value: ChatChannel) -> ChatChannelState { + chat_channel_state_from_model(value, self.base_url) + } + + pub(crate) fn messages(&self, value: ChatMessagesResponse) -> ChatMessagesState { + ChatMessagesState { + messages: value + .messages + .into_iter() + .map(|message| self.message(message)) + .collect(), + can_load_more_past: value.can_load_more_past, + can_load_more_future: value.can_load_more_future, + target_message_id: value.target_message_id, + } + } + + pub(crate) fn my_channels(&self, value: MyChatChannelsResponse) -> MyChatChannelsState { + let total_unread_badge = value.total_unread_badge(); + let inbox_channels = value + .inbox_channels() + .into_iter() + .cloned() + .map(|channel| self.channel(channel)) + .collect(); + MyChatChannelsState { + public_channels: value + .public_channels + .into_iter() + .map(|channel| self.channel(channel)) + .collect(), + direct_message_channels: value + .direct_message_channels + .into_iter() + .map(|channel| self.channel(channel)) + .collect(), + inbox_channels, + channel_tracking: value.channel_tracking.into_iter().map(Into::into).collect(), + global_bus_last_ids: value + .global_bus_last_ids + .into_iter() + .map(Into::into) + .collect(), + total_unread_badge, + } + } + + pub(crate) fn search_result(&self, value: ChatSearchResult) -> ChatSearchResultState { + ChatSearchResultState { + messages: value + .messages + .into_iter() + .map(|message| self.message(message)) + .collect(), + has_more: value.has_more, + } + } +} + diff --git a/crates/fire-uniffi-chat/src/records/messages.rs b/crates/fire-uniffi-chat/src/records/messages.rs new file mode 100644 index 00000000..56f526e8 --- /dev/null +++ b/crates/fire-uniffi-chat/src/records/messages.rs @@ -0,0 +1,123 @@ +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatMessageState { + pub id: u64, + pub channel_id: u64, + pub message: String, + pub presentation: Option>, + pub excerpt: Option, + pub preview_text: String, + pub created_at: Option, + pub deleted_at: Option, + pub deleted_by_id: Option, + pub edited: bool, + pub thread_id: Option, + pub thread: Option, + pub user: Option, + pub mentioned_users: Vec, + pub reactions: Vec, + pub uploads: Vec, + pub in_reply_to: Option, + pub streaming: bool, + pub available_flags: Vec, + pub user_flag_status: Option, + pub bookmark: Option, + pub pinned: bool, + pub is_deleted: bool, +} + +fn chat_message_state_from_model(value: ChatMessage, _base_url: &str) -> ChatMessageState { + let preview_text = value.preview_text(); + let is_deleted = value.is_deleted(); + let presentation = value.presented.arc().map(intern_presented_handle); + ChatMessageState { + id: value.id, + channel_id: value.channel_id, + message: value.message, + presentation, + excerpt: value.excerpt, + preview_text, + created_at: value.created_at, + deleted_at: value.deleted_at, + deleted_by_id: value.deleted_by_id, + edited: value.edited, + thread_id: value.thread_id, + thread: value.thread.map(Into::into), + user: value.user.map(Into::into), + mentioned_users: value.mentioned_users.into_iter().map(Into::into).collect(), + reactions: value.reactions.into_iter().map(Into::into).collect(), + uploads: value.uploads.into_iter().map(Into::into).collect(), + in_reply_to: value.in_reply_to.map(Into::into), + streaming: value.streaming, + available_flags: value.available_flags, + user_flag_status: value.user_flag_status, + bookmark: value.bookmark.map(Into::into), + pinned: value.pinned, + is_deleted, + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatMessagesQueryState { + pub channel_id: u64, + pub direction: Option, + pub target_message_id: Option, + pub fetch_from_last_read: bool, + pub page_size: Option, +} + +impl From for ChatMessagesQuery { + fn from(value: ChatMessagesQueryState) -> Self { + Self { + channel_id: value.channel_id, + direction: value.direction, + target_message_id: value.target_message_id, + fetch_from_last_read: value.fetch_from_last_read, + page_size: value.page_size, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatMessagesState { + pub messages: Vec, + pub can_load_more_past: bool, + pub can_load_more_future: bool, + pub target_message_id: Option, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct SendChatMessageRequestState { + pub channel_id: u64, + pub message: String, + pub staged_id: Option, + pub in_reply_to_id: Option, + pub thread_id: Option, + pub upload_ids: Vec, +} + +impl From for SendChatMessageRequest { + fn from(value: SendChatMessageRequestState) -> Self { + Self { + channel_id: value.channel_id, + message: value.message, + staged_id: value.staged_id, + in_reply_to_id: value.in_reply_to_id, + thread_id: value.thread_id, + upload_ids: value.upload_ids, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct SendChatMessageResultState { + pub message_id: Option, +} + +impl From for SendChatMessageResultState { + fn from(value: SendChatMessageResult) -> Self { + Self { + message_id: value.message_id, + } + } +} + diff --git a/crates/fire-uniffi-chat/src/records/mod.rs b/crates/fire-uniffi-chat/src/records/mod.rs new file mode 100644 index 00000000..66cf4264 --- /dev/null +++ b/crates/fire-uniffi-chat/src/records/mod.rs @@ -0,0 +1,19 @@ +use std::sync::Arc; + +use fire_models::{ + BrowseChatChannelsQuery, ChatBusEvent, ChatBusLastIdEntry, ChatChannel, ChatChannelBusLastIds, + ChatChannelMember, ChatChannelMembership, ChatChannelTrackingEntry, ChatMessage, + ChatMessageBookmark, ChatMessageReaction, ChatMessageReplyRef, ChatMessagesQuery, + ChatMessagesResponse, ChatReactionAction, ChatSearchQuery, ChatSearchResult, ChatThreadRef, + ChatUpload, ChatUser, CreateDirectMessageChannelRequest, MyChatChannelsResponse, + SendChatMessageRequest, SendChatMessageResult, +}; +use fire_uniffi_types::{intern_presented_handle, RenderDocumentHandle}; + +include!("mapper.rs"); +include!("users.rs"); +include!("attachments.rs"); +include!("messages.rs"); +include!("channels.rs"); +include!("requests.rs"); +include!("bus.rs"); diff --git a/crates/fire-uniffi-chat/src/records/requests.rs b/crates/fire-uniffi-chat/src/records/requests.rs new file mode 100644 index 00000000..f1f7ebeb --- /dev/null +++ b/crates/fire-uniffi-chat/src/records/requests.rs @@ -0,0 +1,25 @@ +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatSearchQueryState { + pub query: String, + pub channel_id: Option, + pub offset: Option, + pub limit: Option, +} + +impl From for ChatSearchQuery { + fn from(value: ChatSearchQueryState) -> Self { + Self { + query: value.query, + channel_id: value.channel_id, + offset: value.offset, + limit: value.limit, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatSearchResultState { + pub messages: Vec, + pub has_more: bool, +} + diff --git a/crates/fire-uniffi-chat/src/records/users.rs b/crates/fire-uniffi-chat/src/records/users.rs new file mode 100644 index 00000000..bd16c6a7 --- /dev/null +++ b/crates/fire-uniffi-chat/src/records/users.rs @@ -0,0 +1,61 @@ +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatUserState { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +impl From for ChatUserState { + fn from(value: ChatUser) -> Self { + Self { + id: value.id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatChannelMembershipState { + pub following: bool, + pub muted: bool, + pub starred: bool, + pub notification_level: Option, + pub last_read_message_id: Option, + pub last_viewed_at: Option, +} + +impl From for ChatChannelMembershipState { + fn from(value: ChatChannelMembership) -> Self { + Self { + following: value.following, + muted: value.muted, + starred: value.starred, + notification_level: value.notification_level, + last_read_message_id: value.last_read_message_id, + last_viewed_at: value.last_viewed_at, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ChatChannelBusLastIdsState { + pub channel_message_bus_last_id: Option, + pub new_messages: Option, + pub new_mentions: Option, + pub kick: Option, +} + +impl From for ChatChannelBusLastIdsState { + fn from(value: ChatChannelBusLastIds) -> Self { + Self { + channel_message_bus_last_id: value.channel_message_bus_last_id, + new_messages: value.new_messages, + new_mentions: value.new_mentions, + kick: value.kick, + } + } +} + diff --git a/crates/fire-uniffi-topics/src/handle/creation.rs b/crates/fire-uniffi-topics/src/handle/creation.rs new file mode 100644 index 00000000..52d95478 --- /dev/null +++ b/crates/fire-uniffi-topics/src/handle/creation.rs @@ -0,0 +1,80 @@ +#[uniffi::export] +impl FireTopicsHandle { + pub async fn create_topic( + &self, + input: TopicCreateRequestState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("create_topic", panic_state, async move { + inner.create_topic(input.into()).await + }) + .await + } + + pub async fn create_private_message( + &self, + input: PrivateMessageCreateRequestState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("create_private_message", panic_state, async move { + inner.create_private_message(input.into()).await + }) + .await + } + + pub async fn update_topic( + &self, + input: TopicUpdateRequestState, + ) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("update_topic", panic_state, async move { + inner.update_topic(input.into()).await + }) + .await + } + + pub async fn upload_image( + &self, + input: UploadImageRequestState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("upload_image", panic_state, async move { + inner + .upload_image(&input.file_name, input.mime_type.as_deref(), input.bytes) + .await + }) + .await?; + Ok(response.into()) + } + + pub async fn lookup_upload_urls( + &self, + short_urls: Vec, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("lookup_upload_urls", panic_state, async move { + inner.lookup_upload_urls(short_urls).await + }) + .await?; + Ok(response.into_iter().map(Into::into).collect()) + } + + pub async fn report_topic_timings( + &self, + input: TopicTimingsRequestState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let accepted = run_on_ffi_runtime("report_topic_timings", panic_state, async move { + inner.report_topic_timings(input.into()).await + }) + .await?; + Ok(accepted) + } + +} diff --git a/crates/fire-uniffi-topics/src/handle/lists.rs b/crates/fire-uniffi-topics/src/handle/lists.rs new file mode 100644 index 00000000..5253ad96 --- /dev/null +++ b/crates/fire-uniffi-topics/src/handle/lists.rs @@ -0,0 +1,19 @@ +#[uniffi::export] +impl FireTopicsHandle { + pub async fn fetch_topic_list( + &self, + query: TopicListQueryState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_topic_list", panic_state, async move { + inner.fetch_topic_list(query.into()).await + }) + .await?; + // Hosts apply direct topic-list fetch results themselves. Broadcasting + // every page through the global observer causes home feeds to treat + // paginated slices as authoritative full-list snapshots. + Ok(response.into()) + } + +} diff --git a/crates/fire-uniffi-topics/src/handle/polls.rs b/crates/fire-uniffi-topics/src/handle/polls.rs new file mode 100644 index 00000000..634fbbc3 --- /dev/null +++ b/crates/fire-uniffi-topics/src/handle/polls.rs @@ -0,0 +1,64 @@ +#[uniffi::export] +impl FireTopicsHandle { + pub async fn vote_poll( + &self, + post_id: u64, + poll_name: String, + options: Vec, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("vote_poll", panic_state, async move { + inner.vote_poll(post_id, &poll_name, options).await + }) + .await?; + Ok(response.into()) + } + + pub async fn unvote_poll( + &self, + post_id: u64, + poll_name: String, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("unvote_poll", panic_state, async move { + inner.unvote_poll(post_id, &poll_name).await + }) + .await?; + Ok(response.into()) + } + + pub async fn vote_topic(&self, topic_id: u64) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("vote_topic", panic_state, async move { + inner.vote_topic(topic_id).await + }) + .await?; + Ok(response.into()) + } + + pub async fn unvote_topic(&self, topic_id: u64) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("unvote_topic", panic_state, async move { + inner.unvote_topic(topic_id).await + }) + .await?; + Ok(response.into()) + } + + pub async fn fetch_topic_voters( + &self, + topic_id: u64, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_topic_voters", panic_state, async move { + inner.fetch_topic_voters(topic_id).await + }) + .await?; + Ok(response.into_iter().map(Into::into).collect()) + } +} diff --git a/crates/fire-uniffi-topics/src/handle/posts.rs b/crates/fire-uniffi-topics/src/handle/posts.rs new file mode 100644 index 00000000..5027e622 --- /dev/null +++ b/crates/fire-uniffi-topics/src/handle/posts.rs @@ -0,0 +1,203 @@ +#[uniffi::export] +impl FireTopicsHandle { + pub async fn fetch_topic_posts( + &self, + topic_id: u64, + post_ids: Vec, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_topic_posts", panic_state, async move { + let base_url = inner.base_url().to_string(); + let posts = inner.fetch_topic_posts(topic_id, post_ids).await?; + Ok::<_, fire_core::FireCoreError>((base_url, posts)) + }) + .await?; + Ok(response + .1 + .into_iter() + .map(|post| records::topic_post_state_from_model(post, &response.0)) + .collect()) + } + + pub async fn fetch_topic_ai_summary( + &self, + topic_id: u64, + skip_age_check: bool, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_topic_ai_summary", panic_state, async move { + inner.fetch_topic_ai_summary(topic_id, skip_age_check).await + }) + .await?; + Ok(response.map(Into::into)) + } + + pub async fn create_reply( + &self, + input: TopicReplyRequestState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("create_reply", panic_state, async move { + let base_url = inner.base_url().to_string(); + let post = inner.create_reply(input.into()).await?; + Ok::<_, fire_core::FireCoreError>((base_url, post)) + }) + .await?; + Ok(records::topic_post_state_from_model( + response.1, + &response.0, + )) + } + + pub async fn create_boost( + &self, + post_id: u64, + raw: String, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("create_boost", panic_state, async move { + let base_url = inner.base_url().to_string(); + let boost = inner.create_boost(post_id, raw).await?; + Ok::<_, fire_core::FireCoreError>((base_url, boost)) + }) + .await?; + Ok(records::topic_post_boost_state_from_model( + response.1, + &response.0, + )) + } + + pub async fn delete_boost(&self, boost_id: u64) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("delete_boost", panic_state, async move { + inner.delete_boost(boost_id).await + }) + .await + } + + pub async fn fetch_post(&self, post_id: u64) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_post", panic_state, async move { + let base_url = inner.base_url().to_string(); + let post = inner.fetch_post(post_id).await?; + Ok::<_, fire_core::FireCoreError>((base_url, post)) + }) + .await?; + Ok(records::topic_post_state_from_model_with_raw( + response.1, + &response.0, + )) + } + + pub async fn fetch_post_replies( + &self, + post_id: u64, + after: Option, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_post_replies", panic_state, async move { + let base_url = inner.base_url().to_string(); + let posts = inner.fetch_post_replies(post_id, after).await?; + Ok::<_, fire_core::FireCoreError>((base_url, posts)) + }) + .await?; + Ok(response + .1 + .into_iter() + .map(|post| records::topic_post_state_from_model(post, &response.0)) + .collect()) + } + + pub async fn fetch_post_reply_ids(&self, post_id: u64) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("fetch_post_reply_ids", panic_state, async move { + inner.fetch_post_reply_ids(post_id).await + }) + .await + } + + pub async fn fetch_post_reply_history( + &self, + post_id: u64, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_post_reply_history", panic_state, async move { + let base_url = inner.base_url().to_string(); + let posts = inner.fetch_post_reply_history(post_id).await?; + Ok::<_, fire_core::FireCoreError>((base_url, posts)) + }) + .await?; + Ok(response + .1 + .into_iter() + .map(|post| records::topic_post_state_from_model(post, &response.0)) + .collect()) + } + + pub async fn update_post( + &self, + input: PostUpdateRequestState, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("update_post", panic_state, async move { + let base_url = inner.base_url().to_string(); + let post = inner.update_post(input.into()).await?; + Ok::<_, fire_core::FireCoreError>((base_url, post)) + }) + .await?; + Ok(records::topic_post_state_from_model( + response.1, + &response.0, + )) + } + + pub async fn delete_post(&self, post_id: u64) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("delete_post", panic_state, async move { + inner.delete_post(post_id).await + }) + .await + } + + pub async fn recover_post(&self, post_id: u64) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("recover_post", panic_state, async move { + inner.recover_post(post_id).await + }) + .await + } + + pub async fn flag_post(&self, input: PostFlagRequestState) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("flag_post", panic_state, async move { + inner.flag_post(input.into()).await + }) + .await + } + + pub async fn fetch_post_action_types( + &self, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("fetch_post_action_types", panic_state, async move { + inner.fetch_post_action_types().await + }) + .await?; + Ok(response.into_iter().map(Into::into).collect()) + } + +} diff --git a/crates/fire-uniffi-topics/src/handle/reactions.rs b/crates/fire-uniffi-topics/src/handle/reactions.rs new file mode 100644 index 00000000..fac443e3 --- /dev/null +++ b/crates/fire-uniffi-topics/src/handle/reactions.rs @@ -0,0 +1,56 @@ +#[uniffi::export] +impl FireTopicsHandle { + pub async fn like_post( + &self, + post_id: u64, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("like_post", panic_state, async move { + inner.like_post(post_id).await + }) + .await?; + Ok(response.map(Into::into)) + } + + pub async fn unlike_post( + &self, + post_id: u64, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("unlike_post", panic_state, async move { + inner.unlike_post(post_id).await + }) + .await?; + Ok(response.map(Into::into)) + } + + pub async fn toggle_post_reaction( + &self, + post_id: u64, + reaction_id: String, + ) -> Result { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let response = run_on_ffi_runtime("toggle_post_reaction", panic_state, async move { + inner.toggle_post_reaction(post_id, reaction_id).await + }) + .await?; + Ok(response.into()) + } + + pub async fn fetch_reaction_users( + &self, + post_id: u64, + ) -> Result, FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + let groups = run_on_ffi_runtime("fetch_reaction_users", panic_state, async move { + inner.fetch_reaction_users(post_id).await + }) + .await?; + Ok(groups.into_iter().map(Into::into).collect()) + } + +} diff --git a/crates/fire-uniffi-topics/src/handle/solutions.rs b/crates/fire-uniffi-topics/src/handle/solutions.rs new file mode 100644 index 00000000..3a180342 --- /dev/null +++ b/crates/fire-uniffi-topics/src/handle/solutions.rs @@ -0,0 +1,21 @@ +#[uniffi::export] +impl FireTopicsHandle { + pub async fn accept_solution(&self, post_id: u64) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("accept_solution", panic_state, async move { + inner.accept_solution(post_id).await + }) + .await + } + + pub async fn unaccept_solution(&self, post_id: u64) -> Result<(), FireUniFfiError> { + let inner = self.shared.core.clone(); + let panic_state = self.shared.panic_state.clone(); + run_on_ffi_runtime("unaccept_solution", panic_state, async move { + inner.unaccept_solution(post_id).await + }) + .await + } + +} diff --git a/crates/fire-uniffi-topics/src/lib.rs b/crates/fire-uniffi-topics/src/lib.rs index fe36c5e7..bc2af6ea 100644 --- a/crates/fire-uniffi-topics/src/lib.rs +++ b/crates/fire-uniffi-topics/src/lib.rs @@ -44,431 +44,9 @@ impl FireTopicsHandle { } } -#[uniffi::export] -impl FireTopicsHandle { - pub async fn fetch_topic_list( - &self, - query: TopicListQueryState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_topic_list", panic_state, async move { - inner.fetch_topic_list(query.into()).await - }) - .await?; - // Hosts apply direct topic-list fetch results themselves. Broadcasting - // every page through the global observer causes home feeds to treat - // paginated slices as authoritative full-list snapshots. - Ok(response.into()) - } - - pub async fn fetch_topic_posts( - &self, - topic_id: u64, - post_ids: Vec, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_topic_posts", panic_state, async move { - let base_url = inner.base_url().to_string(); - let posts = inner.fetch_topic_posts(topic_id, post_ids).await?; - Ok::<_, fire_core::FireCoreError>((base_url, posts)) - }) - .await?; - Ok(response - .1 - .into_iter() - .map(|post| records::topic_post_state_from_model(post, &response.0)) - .collect()) - } - - pub async fn fetch_topic_ai_summary( - &self, - topic_id: u64, - skip_age_check: bool, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_topic_ai_summary", panic_state, async move { - inner.fetch_topic_ai_summary(topic_id, skip_age_check).await - }) - .await?; - Ok(response.map(Into::into)) - } - - pub async fn create_reply( - &self, - input: TopicReplyRequestState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("create_reply", panic_state, async move { - let base_url = inner.base_url().to_string(); - let post = inner.create_reply(input.into()).await?; - Ok::<_, fire_core::FireCoreError>((base_url, post)) - }) - .await?; - Ok(records::topic_post_state_from_model( - response.1, - &response.0, - )) - } - - pub async fn create_boost( - &self, - post_id: u64, - raw: String, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("create_boost", panic_state, async move { - let base_url = inner.base_url().to_string(); - let boost = inner.create_boost(post_id, raw).await?; - Ok::<_, fire_core::FireCoreError>((base_url, boost)) - }) - .await?; - Ok(records::topic_post_boost_state_from_model( - response.1, - &response.0, - )) - } - - pub async fn delete_boost(&self, boost_id: u64) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("delete_boost", panic_state, async move { - inner.delete_boost(boost_id).await - }) - .await - } - - pub async fn fetch_post(&self, post_id: u64) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_post", panic_state, async move { - let base_url = inner.base_url().to_string(); - let post = inner.fetch_post(post_id).await?; - Ok::<_, fire_core::FireCoreError>((base_url, post)) - }) - .await?; - Ok(records::topic_post_state_from_model_with_raw( - response.1, - &response.0, - )) - } - - pub async fn fetch_post_replies( - &self, - post_id: u64, - after: Option, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_post_replies", panic_state, async move { - let base_url = inner.base_url().to_string(); - let posts = inner.fetch_post_replies(post_id, after).await?; - Ok::<_, fire_core::FireCoreError>((base_url, posts)) - }) - .await?; - Ok(response - .1 - .into_iter() - .map(|post| records::topic_post_state_from_model(post, &response.0)) - .collect()) - } - - pub async fn fetch_post_reply_ids(&self, post_id: u64) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("fetch_post_reply_ids", panic_state, async move { - inner.fetch_post_reply_ids(post_id).await - }) - .await - } - - pub async fn fetch_post_reply_history( - &self, - post_id: u64, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_post_reply_history", panic_state, async move { - let base_url = inner.base_url().to_string(); - let posts = inner.fetch_post_reply_history(post_id).await?; - Ok::<_, fire_core::FireCoreError>((base_url, posts)) - }) - .await?; - Ok(response - .1 - .into_iter() - .map(|post| records::topic_post_state_from_model(post, &response.0)) - .collect()) - } - - pub async fn update_post( - &self, - input: PostUpdateRequestState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("update_post", panic_state, async move { - let base_url = inner.base_url().to_string(); - let post = inner.update_post(input.into()).await?; - Ok::<_, fire_core::FireCoreError>((base_url, post)) - }) - .await?; - Ok(records::topic_post_state_from_model( - response.1, - &response.0, - )) - } - - pub async fn delete_post(&self, post_id: u64) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("delete_post", panic_state, async move { - inner.delete_post(post_id).await - }) - .await - } - - pub async fn recover_post(&self, post_id: u64) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("recover_post", panic_state, async move { - inner.recover_post(post_id).await - }) - .await - } - - pub async fn flag_post(&self, input: PostFlagRequestState) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("flag_post", panic_state, async move { - inner.flag_post(input.into()).await - }) - .await - } - - pub async fn fetch_post_action_types( - &self, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_post_action_types", panic_state, async move { - inner.fetch_post_action_types().await - }) - .await?; - Ok(response.into_iter().map(Into::into).collect()) - } - - pub async fn create_topic( - &self, - input: TopicCreateRequestState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("create_topic", panic_state, async move { - inner.create_topic(input.into()).await - }) - .await - } - - pub async fn create_private_message( - &self, - input: PrivateMessageCreateRequestState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("create_private_message", panic_state, async move { - inner.create_private_message(input.into()).await - }) - .await - } - - pub async fn update_topic( - &self, - input: TopicUpdateRequestState, - ) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("update_topic", panic_state, async move { - inner.update_topic(input.into()).await - }) - .await - } - - pub async fn upload_image( - &self, - input: UploadImageRequestState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("upload_image", panic_state, async move { - inner - .upload_image(&input.file_name, input.mime_type.as_deref(), input.bytes) - .await - }) - .await?; - Ok(response.into()) - } - - pub async fn lookup_upload_urls( - &self, - short_urls: Vec, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("lookup_upload_urls", panic_state, async move { - inner.lookup_upload_urls(short_urls).await - }) - .await?; - Ok(response.into_iter().map(Into::into).collect()) - } - - pub async fn report_topic_timings( - &self, - input: TopicTimingsRequestState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let accepted = run_on_ffi_runtime("report_topic_timings", panic_state, async move { - inner.report_topic_timings(input.into()).await - }) - .await?; - Ok(accepted) - } - - pub async fn like_post( - &self, - post_id: u64, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("like_post", panic_state, async move { - inner.like_post(post_id).await - }) - .await?; - Ok(response.map(Into::into)) - } - - pub async fn unlike_post( - &self, - post_id: u64, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("unlike_post", panic_state, async move { - inner.unlike_post(post_id).await - }) - .await?; - Ok(response.map(Into::into)) - } - - pub async fn toggle_post_reaction( - &self, - post_id: u64, - reaction_id: String, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("toggle_post_reaction", panic_state, async move { - inner.toggle_post_reaction(post_id, reaction_id).await - }) - .await?; - Ok(response.into()) - } - - pub async fn fetch_reaction_users( - &self, - post_id: u64, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let groups = run_on_ffi_runtime("fetch_reaction_users", panic_state, async move { - inner.fetch_reaction_users(post_id).await - }) - .await?; - Ok(groups.into_iter().map(Into::into).collect()) - } - - pub async fn accept_solution(&self, post_id: u64) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("accept_solution", panic_state, async move { - inner.accept_solution(post_id).await - }) - .await - } - - pub async fn unaccept_solution(&self, post_id: u64) -> Result<(), FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - run_on_ffi_runtime("unaccept_solution", panic_state, async move { - inner.unaccept_solution(post_id).await - }) - .await - } - - pub async fn vote_poll( - &self, - post_id: u64, - poll_name: String, - options: Vec, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("vote_poll", panic_state, async move { - inner.vote_poll(post_id, &poll_name, options).await - }) - .await?; - Ok(response.into()) - } - - pub async fn unvote_poll( - &self, - post_id: u64, - poll_name: String, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("unvote_poll", panic_state, async move { - inner.unvote_poll(post_id, &poll_name).await - }) - .await?; - Ok(response.into()) - } - - pub async fn vote_topic(&self, topic_id: u64) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("vote_topic", panic_state, async move { - inner.vote_topic(topic_id).await - }) - .await?; - Ok(response.into()) - } - - pub async fn unvote_topic(&self, topic_id: u64) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("unvote_topic", panic_state, async move { - inner.unvote_topic(topic_id).await - }) - .await?; - Ok(response.into()) - } - - pub async fn fetch_topic_voters( - &self, - topic_id: u64, - ) -> Result, FireUniFfiError> { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_topic_voters", panic_state, async move { - inner.fetch_topic_voters(topic_id).await - }) - .await?; - Ok(response.into_iter().map(Into::into).collect()) - } -} +include!("handle/lists.rs"); +include!("handle/posts.rs"); +include!("handle/creation.rs"); +include!("handle/reactions.rs"); +include!("handle/solutions.rs"); +include!("handle/polls.rs"); diff --git a/crates/fire-uniffi/src/handle/construct.rs b/crates/fire-uniffi/src/handle/construct.rs new file mode 100644 index 00000000..0dffb097 --- /dev/null +++ b/crates/fire-uniffi/src/handle/construct.rs @@ -0,0 +1,23 @@ +#[uniffi::export] +impl FireAppCore { + #[uniffi::constructor] + pub fn new( + base_url: Option, + workspace_path: Option, + ) -> Result, FireUniFfiError> { + let shared = Arc::new(SharedFireCore::bootstrap(base_url, workspace_path)?); + Ok(Arc::new(Self { + shared: shared.clone(), + chat: FireChatHandle::from_shared(shared.clone()), + diagnostics: FireDiagnosticsHandle::from_shared(shared.clone()), + ldc: FireLdcHandle::from_shared(shared.clone()), + messagebus: FireMessageBusHandle::from_shared(shared.clone()), + notifications: FireNotificationsHandle::from_shared(shared.clone()), + search: FireSearchHandle::from_shared(shared.clone()), + session: FireSessionHandle::from_shared(shared.clone()), + topics: FireTopicsHandle::from_shared(shared.clone()), + user: FireUserHandle::from_shared(shared), + })) + } + +} diff --git a/crates/fire-uniffi/src/handle/domains.rs b/crates/fire-uniffi/src/handle/domains.rs new file mode 100644 index 00000000..7b4bc6dc --- /dev/null +++ b/crates/fire-uniffi/src/handle/domains.rs @@ -0,0 +1,39 @@ +#[uniffi::export] +impl FireAppCore { + pub fn chat(&self) -> Arc { + self.chat.clone() + } + + pub fn diagnostics(&self) -> Arc { + self.diagnostics.clone() + } + + pub fn ldc(&self) -> Arc { + self.ldc.clone() + } + + pub fn messagebus(&self) -> Arc { + self.messagebus.clone() + } + + pub fn notifications(&self) -> Arc { + self.notifications.clone() + } + + pub fn search(&self) -> Arc { + self.search.clone() + } + + pub fn session(&self) -> Arc { + self.session.clone() + } + + pub fn topics(&self) -> Arc { + self.topics.clone() + } + + pub fn user(&self) -> Arc { + self.user.clone() + } + +} diff --git a/crates/fire-uniffi/src/handle/observers.rs b/crates/fire-uniffi/src/handle/observers.rs new file mode 100644 index 00000000..683f7ddb --- /dev/null +++ b/crates/fire-uniffi/src/handle/observers.rs @@ -0,0 +1,192 @@ +#[uniffi::export] +impl FireAppCore { + pub fn register_state_observer(&self, observer: Arc) { + let session_observer = observer.clone(); + let topic_list_observer = observer.clone(); + let notification_observer = observer; + self.shared + .core + .state_observers() + .set(FireStateObserverCallbacks { + session: Arc::new(move |snapshot| { + session_observer.on_session_snapshot(SessionState::from_snapshot(snapshot)); + }), + topic_list: Arc::new(move |snapshot| { + topic_list_observer.on_topic_list_snapshot(snapshot.into()); + }), + notification_center: Arc::new(move |snapshot| { + notification_observer.on_notification_center_snapshot(snapshot.into()); + }), + }); + } + + pub fn unregister_state_observer(&self) { + self.shared.core.state_observers().clear(); + } +} + +#[cfg(test)] +mod tests { + use crate::{parse_cooked_html, CookedHtmlNodeKindState}; + use fire_uniffi_types::{ + ffi_runtime, run_infallible, run_on_ffi_runtime, FireUniFfiError, PanicState, + SharedFireCore, + }; + + #[test] + fn parse_cooked_html_exposes_shared_ast_record() { + let document = parse_cooked_html( + r#"

Hello topic

fire"# + .to_string(), + ); + + assert_eq!(document.plain_text, "Hello topic\n\nfire"); + assert_eq!(document.image_urls, vec!["/uploads/fire.png".to_string()]); + assert_eq!(document.link_urls, vec!["/t/123/4".to_string()]); + assert!(document + .nodes + .iter() + .any(|node| node.kind == CookedHtmlNodeKindState::Link + && node.url.as_deref() == Some("/t/123/4"))); + } + + #[test] + fn maps_http_status_errors_without_flattening() { + let error = FireUniFfiError::from(fire_core::FireCoreError::HttpStatus { + operation: "fetch topic list", + status: 429, + body: "slow down".to_string(), + }); + + assert!(matches!( + error, + FireUniFfiError::HttpStatus { + operation, + status: 429, + body, + } if operation == "fetch topic list" && body == "slow down" + )); + } + + #[test] + fn maps_cloudflare_challenge_errors_to_dedicated_variant() { + let error = FireUniFfiError::from(fire_core::FireCoreError::CloudflareChallenge { + operation: "create reply", + reason: fire_core::CloudflareChallengeFailureReason::Required, + }); + + assert!(matches!( + error, + FireUniFfiError::CloudflareChallenge { reason } + if reason == "required" + )); + } + + #[test] + fn maps_login_required_errors_to_dedicated_variant() { + let error = FireUniFfiError::from(fire_core::FireCoreError::LoginRequired { + operation: "report topic timings", + message: "您需要登录才能执行此操作。".to_string(), + }); + + assert!(matches!( + error, + FireUniFfiError::LoginRequired { details } + if details == "您需要登录才能执行此操作。" + )); + } + + #[test] + fn maps_stale_session_response_errors_to_dedicated_variant() { + let error = FireUniFfiError::from(fire_core::FireCoreError::StaleSessionResponse { + operation: "fetch topic list", + }); + + assert!(matches!( + error, + FireUniFfiError::StaleSessionResponse { operation } + if operation == "fetch topic list" + )); + } + + #[test] + fn maps_storage_errors_to_storage_variant() { + use std::{io, path::PathBuf}; + + let error = FireUniFfiError::from(fire_core::FireCoreError::PersistIo { + path: PathBuf::from("/tmp/session.json"), + source: io::Error::new(io::ErrorKind::PermissionDenied, "denied"), + }); + + assert!(matches!( + error, + FireUniFfiError::Storage { details } + if details.contains("/tmp/session.json") && details.contains("denied") + )); + } + + #[test] + fn runs_async_work_on_ffi_runtime() { + let panic_state = std::sync::Arc::new(PanicState::default()); + let value = ffi_runtime() + .block_on(run_on_ffi_runtime( + "test_async_success", + std::sync::Arc::clone(&panic_state), + async { Ok::<_, fire_core::FireCoreError>(42_u8) }, + )) + .expect("ffi runtime should resolve async work"); + + assert_eq!(value, 42); + } + + #[test] + fn converts_sync_panic_to_internal_error_and_poisoned_handle() { + let shared = std::sync::Arc::new(SharedFireCore::bootstrap(None, None).expect("bootstrap")); + + let error = + run_infallible::<(), _>(&shared.panic_state, &shared.core, "test_sync_panic", |_| { + panic!("boom") + }) + .expect_err("panic should map to an internal error"); + + assert!(matches!( + error, + FireUniFfiError::Internal { details } if details.contains("test_sync_panic panicked: boom") + )); + assert!(matches!( + shared.panic_state.ensure_healthy("snapshot"), + Err(FireUniFfiError::Internal { details }) + if details.contains("poisoned by a previous panic") + && details.contains("test_sync_panic panicked: boom") + )); + } + + #[test] + fn converts_async_panic_to_internal_error_and_poisoned_handle() { + let panic_state = std::sync::Arc::new(PanicState::default()); + + let error = ffi_runtime() + .block_on(run_on_ffi_runtime( + "test_async_panic", + std::sync::Arc::clone(&panic_state), + async { + panic!("async boom"); + #[allow(unreachable_code)] + Ok::<(), fire_core::FireCoreError>(()) + }, + )) + .expect_err("panic should map to an internal error"); + + assert!(matches!( + error, + FireUniFfiError::Internal { details } + if details.contains("test_async_panic panicked: async boom") + )); + assert!(matches!( + panic_state.ensure_healthy("fetch_topic_list"), + Err(FireUniFfiError::Internal { details }) + if details.contains("poisoned by a previous panic") + && details.contains("test_async_panic panicked: async boom") + )); + } +} diff --git a/crates/fire-uniffi/src/lib.rs b/crates/fire-uniffi/src/lib.rs index efe0093c..96e1dec1 100644 --- a/crates/fire-uniffi/src/lib.rs +++ b/crates/fire-uniffi/src/lib.rs @@ -21,166 +21,7 @@ use fire_uniffi_topics::FireTopicsHandle; use fire_uniffi_types::{FireUniFfiError, SharedFireCore, TopicListState}; use fire_uniffi_user::FireUserHandle; -#[uniffi::export] -pub fn plain_text_from_html(raw_html: String) -> String { - shared_plain_text_from_html(&raw_html) -} - -#[uniffi::export] -pub fn parse_cooked_html(raw_html: String) -> CookedHtmlDocumentState { - shared_parse_cooked_html(&raw_html).into() -} - -#[uniffi::export] -pub fn present_cooked_html( - raw_html: String, - base_url: String, -) -> Option> { - shared_present_cooked_html(&raw_html, &base_url) - .map(std::sync::Arc::new) - .map(fire_uniffi_types::intern_presented_handle) -} - -#[uniffi::export] -pub fn preview_text_from_html(raw_html: Option) -> Option { - shared_preview_text_from_html(raw_html.as_deref()) -} - -#[uniffi::export] -pub fn monogram_for_username(username: String) -> String { - shared_monogram_for_username(&username) -} - -#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq)] -pub enum CookedHtmlNodeKindState { - Document, - Text, - Paragraph, - Heading, - LineBreak, - Strong, - Emphasis, - Strikethrough, - Link, - Image, - Emoji, - Code, - CodeBlock, - Blockquote, - DiscourseQuote, - Divider, - List, - ListItem, - Spoiler, - Details, - Table, - TableRow, - TableCell, - Onebox, - Iframe, - Mention, - Hashtag, - Attachment, - Unknown, -} - -impl From for CookedHtmlNodeKindState { - fn from(value: CookedHtmlNodeKind) -> Self { - match value { - CookedHtmlNodeKind::Document => Self::Document, - CookedHtmlNodeKind::Text => Self::Text, - CookedHtmlNodeKind::Paragraph => Self::Paragraph, - CookedHtmlNodeKind::Heading => Self::Heading, - CookedHtmlNodeKind::LineBreak => Self::LineBreak, - CookedHtmlNodeKind::Strong => Self::Strong, - CookedHtmlNodeKind::Emphasis => Self::Emphasis, - CookedHtmlNodeKind::Strikethrough => Self::Strikethrough, - CookedHtmlNodeKind::Link => Self::Link, - CookedHtmlNodeKind::Image => Self::Image, - CookedHtmlNodeKind::Emoji => Self::Emoji, - CookedHtmlNodeKind::Code => Self::Code, - CookedHtmlNodeKind::CodeBlock => Self::CodeBlock, - CookedHtmlNodeKind::Blockquote => Self::Blockquote, - CookedHtmlNodeKind::DiscourseQuote => Self::DiscourseQuote, - CookedHtmlNodeKind::Divider => Self::Divider, - CookedHtmlNodeKind::List => Self::List, - CookedHtmlNodeKind::ListItem => Self::ListItem, - CookedHtmlNodeKind::Spoiler => Self::Spoiler, - CookedHtmlNodeKind::Details => Self::Details, - CookedHtmlNodeKind::Table => Self::Table, - CookedHtmlNodeKind::TableRow => Self::TableRow, - CookedHtmlNodeKind::TableCell => Self::TableCell, - CookedHtmlNodeKind::Onebox => Self::Onebox, - CookedHtmlNodeKind::Iframe => Self::Iframe, - CookedHtmlNodeKind::Mention => Self::Mention, - CookedHtmlNodeKind::Hashtag => Self::Hashtag, - CookedHtmlNodeKind::Attachment => Self::Attachment, - CookedHtmlNodeKind::Unknown => Self::Unknown, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct CookedHtmlAttributeState { - pub name: String, - pub value: String, -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct CookedHtmlNodeState { - pub id: u32, - pub parent_id: Option, - pub kind: CookedHtmlNodeKindState, - pub depth: u32, - pub text: Option, - pub url: Option, - pub title: Option, - pub alt: Option, - pub level: Option, - pub ordered: Option, - pub attributes: Vec, -} - -impl From for CookedHtmlNodeState { - fn from(value: CookedHtmlNode) -> Self { - Self { - id: value.id, - parent_id: value.parent_id, - kind: value.kind.into(), - depth: value.depth, - text: value.text, - url: value.url, - title: value.title, - alt: value.alt, - level: value.level, - ordered: value.ordered, - attributes: value - .attributes - .into_iter() - .map(|(name, value)| CookedHtmlAttributeState { name, value }) - .collect(), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct CookedHtmlDocumentState { - pub nodes: Vec, - pub plain_text: String, - pub image_urls: Vec, - pub link_urls: Vec, -} - -impl From for CookedHtmlDocumentState { - fn from(value: CookedHtmlDocument) -> Self { - Self { - nodes: value.nodes.into_iter().map(Into::into).collect(), - plain_text: value.plain_text, - image_urls: value.image_urls, - link_urls: value.link_urls, - } - } -} +include!("records/rich_text.rs"); #[uniffi::export(with_foreign)] pub trait StateObserver: Send + Sync { @@ -203,251 +44,6 @@ pub struct FireAppCore { user: Arc, } -#[uniffi::export] -impl FireAppCore { - #[uniffi::constructor] - pub fn new( - base_url: Option, - workspace_path: Option, - ) -> Result, FireUniFfiError> { - let shared = Arc::new(SharedFireCore::bootstrap(base_url, workspace_path)?); - Ok(Arc::new(Self { - shared: shared.clone(), - chat: FireChatHandle::from_shared(shared.clone()), - diagnostics: FireDiagnosticsHandle::from_shared(shared.clone()), - ldc: FireLdcHandle::from_shared(shared.clone()), - messagebus: FireMessageBusHandle::from_shared(shared.clone()), - notifications: FireNotificationsHandle::from_shared(shared.clone()), - search: FireSearchHandle::from_shared(shared.clone()), - session: FireSessionHandle::from_shared(shared.clone()), - topics: FireTopicsHandle::from_shared(shared.clone()), - user: FireUserHandle::from_shared(shared), - })) - } - - pub fn chat(&self) -> Arc { - self.chat.clone() - } - - pub fn diagnostics(&self) -> Arc { - self.diagnostics.clone() - } - - pub fn ldc(&self) -> Arc { - self.ldc.clone() - } - - pub fn messagebus(&self) -> Arc { - self.messagebus.clone() - } - - pub fn notifications(&self) -> Arc { - self.notifications.clone() - } - - pub fn search(&self) -> Arc { - self.search.clone() - } - - pub fn session(&self) -> Arc { - self.session.clone() - } - - pub fn topics(&self) -> Arc { - self.topics.clone() - } - - pub fn user(&self) -> Arc { - self.user.clone() - } - - pub fn register_state_observer(&self, observer: Arc) { - let session_observer = observer.clone(); - let topic_list_observer = observer.clone(); - let notification_observer = observer; - self.shared - .core - .state_observers() - .set(FireStateObserverCallbacks { - session: Arc::new(move |snapshot| { - session_observer.on_session_snapshot(SessionState::from_snapshot(snapshot)); - }), - topic_list: Arc::new(move |snapshot| { - topic_list_observer.on_topic_list_snapshot(snapshot.into()); - }), - notification_center: Arc::new(move |snapshot| { - notification_observer.on_notification_center_snapshot(snapshot.into()); - }), - }); - } - - pub fn unregister_state_observer(&self) { - self.shared.core.state_observers().clear(); - } -} - -#[cfg(test)] -mod tests { - use crate::{parse_cooked_html, CookedHtmlNodeKindState}; - use fire_uniffi_types::{ - ffi_runtime, run_infallible, run_on_ffi_runtime, FireUniFfiError, PanicState, - SharedFireCore, - }; - - #[test] - fn parse_cooked_html_exposes_shared_ast_record() { - let document = parse_cooked_html( - r#"

Hello topic

fire"# - .to_string(), - ); - - assert_eq!(document.plain_text, "Hello topic\n\nfire"); - assert_eq!(document.image_urls, vec!["/uploads/fire.png".to_string()]); - assert_eq!(document.link_urls, vec!["/t/123/4".to_string()]); - assert!(document - .nodes - .iter() - .any(|node| node.kind == CookedHtmlNodeKindState::Link - && node.url.as_deref() == Some("/t/123/4"))); - } - - #[test] - fn maps_http_status_errors_without_flattening() { - let error = FireUniFfiError::from(fire_core::FireCoreError::HttpStatus { - operation: "fetch topic list", - status: 429, - body: "slow down".to_string(), - }); - - assert!(matches!( - error, - FireUniFfiError::HttpStatus { - operation, - status: 429, - body, - } if operation == "fetch topic list" && body == "slow down" - )); - } - - #[test] - fn maps_cloudflare_challenge_errors_to_dedicated_variant() { - let error = FireUniFfiError::from(fire_core::FireCoreError::CloudflareChallenge { - operation: "create reply", - reason: fire_core::CloudflareChallengeFailureReason::Required, - }); - - assert!(matches!( - error, - FireUniFfiError::CloudflareChallenge { reason } - if reason == "required" - )); - } - - #[test] - fn maps_login_required_errors_to_dedicated_variant() { - let error = FireUniFfiError::from(fire_core::FireCoreError::LoginRequired { - operation: "report topic timings", - message: "您需要登录才能执行此操作。".to_string(), - }); - - assert!(matches!( - error, - FireUniFfiError::LoginRequired { details } - if details == "您需要登录才能执行此操作。" - )); - } - - #[test] - fn maps_stale_session_response_errors_to_dedicated_variant() { - let error = FireUniFfiError::from(fire_core::FireCoreError::StaleSessionResponse { - operation: "fetch topic list", - }); - - assert!(matches!( - error, - FireUniFfiError::StaleSessionResponse { operation } - if operation == "fetch topic list" - )); - } - - #[test] - fn maps_storage_errors_to_storage_variant() { - use std::{io, path::PathBuf}; - - let error = FireUniFfiError::from(fire_core::FireCoreError::PersistIo { - path: PathBuf::from("/tmp/session.json"), - source: io::Error::new(io::ErrorKind::PermissionDenied, "denied"), - }); - - assert!(matches!( - error, - FireUniFfiError::Storage { details } - if details.contains("/tmp/session.json") && details.contains("denied") - )); - } - - #[test] - fn runs_async_work_on_ffi_runtime() { - let panic_state = std::sync::Arc::new(PanicState::default()); - let value = ffi_runtime() - .block_on(run_on_ffi_runtime( - "test_async_success", - std::sync::Arc::clone(&panic_state), - async { Ok::<_, fire_core::FireCoreError>(42_u8) }, - )) - .expect("ffi runtime should resolve async work"); - - assert_eq!(value, 42); - } - - #[test] - fn converts_sync_panic_to_internal_error_and_poisoned_handle() { - let shared = std::sync::Arc::new(SharedFireCore::bootstrap(None, None).expect("bootstrap")); - - let error = - run_infallible::<(), _>(&shared.panic_state, &shared.core, "test_sync_panic", |_| { - panic!("boom") - }) - .expect_err("panic should map to an internal error"); - - assert!(matches!( - error, - FireUniFfiError::Internal { details } if details.contains("test_sync_panic panicked: boom") - )); - assert!(matches!( - shared.panic_state.ensure_healthy("snapshot"), - Err(FireUniFfiError::Internal { details }) - if details.contains("poisoned by a previous panic") - && details.contains("test_sync_panic panicked: boom") - )); - } - - #[test] - fn converts_async_panic_to_internal_error_and_poisoned_handle() { - let panic_state = std::sync::Arc::new(PanicState::default()); - - let error = ffi_runtime() - .block_on(run_on_ffi_runtime( - "test_async_panic", - std::sync::Arc::clone(&panic_state), - async { - panic!("async boom"); - #[allow(unreachable_code)] - Ok::<(), fire_core::FireCoreError>(()) - }, - )) - .expect_err("panic should map to an internal error"); - - assert!(matches!( - error, - FireUniFfiError::Internal { details } - if details.contains("test_async_panic panicked: async boom") - )); - assert!(matches!( - panic_state.ensure_healthy("fetch_topic_list"), - Err(FireUniFfiError::Internal { details }) - if details.contains("poisoned by a previous panic") - && details.contains("test_async_panic panicked: async boom") - )); - } -} +include!("handle/construct.rs"); +include!("handle/domains.rs"); +include!("handle/observers.rs"); diff --git a/crates/fire-uniffi/src/records/rich_text.rs b/crates/fire-uniffi/src/records/rich_text.rs new file mode 100644 index 00000000..5d1a421d --- /dev/null +++ b/crates/fire-uniffi/src/records/rich_text.rs @@ -0,0 +1,160 @@ +#[uniffi::export] +pub fn plain_text_from_html(raw_html: String) -> String { + shared_plain_text_from_html(&raw_html) +} + +#[uniffi::export] +pub fn parse_cooked_html(raw_html: String) -> CookedHtmlDocumentState { + shared_parse_cooked_html(&raw_html).into() +} + +#[uniffi::export] +pub fn present_cooked_html( + raw_html: String, + base_url: String, +) -> Option> { + shared_present_cooked_html(&raw_html, &base_url) + .map(std::sync::Arc::new) + .map(fire_uniffi_types::intern_presented_handle) +} + +#[uniffi::export] +pub fn preview_text_from_html(raw_html: Option) -> Option { + shared_preview_text_from_html(raw_html.as_deref()) +} + +#[uniffi::export] +pub fn monogram_for_username(username: String) -> String { + shared_monogram_for_username(&username) +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum CookedHtmlNodeKindState { + Document, + Text, + Paragraph, + Heading, + LineBreak, + Strong, + Emphasis, + Strikethrough, + Link, + Image, + Emoji, + Code, + CodeBlock, + Blockquote, + DiscourseQuote, + Divider, + List, + ListItem, + Spoiler, + Details, + Table, + TableRow, + TableCell, + Onebox, + Iframe, + Mention, + Hashtag, + Attachment, + Unknown, +} + +impl From for CookedHtmlNodeKindState { + fn from(value: CookedHtmlNodeKind) -> Self { + match value { + CookedHtmlNodeKind::Document => Self::Document, + CookedHtmlNodeKind::Text => Self::Text, + CookedHtmlNodeKind::Paragraph => Self::Paragraph, + CookedHtmlNodeKind::Heading => Self::Heading, + CookedHtmlNodeKind::LineBreak => Self::LineBreak, + CookedHtmlNodeKind::Strong => Self::Strong, + CookedHtmlNodeKind::Emphasis => Self::Emphasis, + CookedHtmlNodeKind::Strikethrough => Self::Strikethrough, + CookedHtmlNodeKind::Link => Self::Link, + CookedHtmlNodeKind::Image => Self::Image, + CookedHtmlNodeKind::Emoji => Self::Emoji, + CookedHtmlNodeKind::Code => Self::Code, + CookedHtmlNodeKind::CodeBlock => Self::CodeBlock, + CookedHtmlNodeKind::Blockquote => Self::Blockquote, + CookedHtmlNodeKind::DiscourseQuote => Self::DiscourseQuote, + CookedHtmlNodeKind::Divider => Self::Divider, + CookedHtmlNodeKind::List => Self::List, + CookedHtmlNodeKind::ListItem => Self::ListItem, + CookedHtmlNodeKind::Spoiler => Self::Spoiler, + CookedHtmlNodeKind::Details => Self::Details, + CookedHtmlNodeKind::Table => Self::Table, + CookedHtmlNodeKind::TableRow => Self::TableRow, + CookedHtmlNodeKind::TableCell => Self::TableCell, + CookedHtmlNodeKind::Onebox => Self::Onebox, + CookedHtmlNodeKind::Iframe => Self::Iframe, + CookedHtmlNodeKind::Mention => Self::Mention, + CookedHtmlNodeKind::Hashtag => Self::Hashtag, + CookedHtmlNodeKind::Attachment => Self::Attachment, + CookedHtmlNodeKind::Unknown => Self::Unknown, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct CookedHtmlAttributeState { + pub name: String, + pub value: String, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct CookedHtmlNodeState { + pub id: u32, + pub parent_id: Option, + pub kind: CookedHtmlNodeKindState, + pub depth: u32, + pub text: Option, + pub url: Option, + pub title: Option, + pub alt: Option, + pub level: Option, + pub ordered: Option, + pub attributes: Vec, +} + +impl From for CookedHtmlNodeState { + fn from(value: CookedHtmlNode) -> Self { + Self { + id: value.id, + parent_id: value.parent_id, + kind: value.kind.into(), + depth: value.depth, + text: value.text, + url: value.url, + title: value.title, + alt: value.alt, + level: value.level, + ordered: value.ordered, + attributes: value + .attributes + .into_iter() + .map(|(name, value)| CookedHtmlAttributeState { name, value }) + .collect(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct CookedHtmlDocumentState { + pub nodes: Vec, + pub plain_text: String, + pub image_urls: Vec, + pub link_urls: Vec, +} + +impl From for CookedHtmlDocumentState { + fn from(value: CookedHtmlDocument) -> Self { + Self { + nodes: value.nodes.into_iter().map(Into::into).collect(), + plain_text: value.plain_text, + image_urls: value.image_urls, + link_urls: value.link_urls, + } + } +} diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..3a502775 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,11 @@ +# Docs + +只放长期仍要读的材料。代码是行为真相源;文档描述当前口径,不堆积已完成的执行清单。 + +| 目录 | 留下什么 | +| --- | --- | +| `knowledge/` | 后端协议。栈无关,按观测行为写。 | +| `architecture/` | 当前系统怎么切:所有权、模块边界、渲染出站、反馈。 | +| `release/` | 发版、商店、签名、证据表。 | + +不要往仓库里再加:已落地的分阶段计划、调研笔记、被取代的设计稿、只为勾选任务存在的 roadmap 副本。 diff --git a/docs/architecture/2026-06-05-rich-text-and-state-observer-design.md b/docs/architecture/2026-06-05-rich-text-and-state-observer-design.md deleted file mode 100644 index bc1db941..00000000 --- a/docs/architecture/2026-06-05-rich-text-and-state-observer-design.md +++ /dev/null @@ -1,299 +0,0 @@ -# Fire Rich Text + StateObserver 实施说明 - -> 日期: 2026-06-05 -> 状态: Implemented(富文本出站形状已被 2026-09-19 取代) -> 范围: `fire-rich-text`、UniFFI 富文本/observer 边界、iOS/Android 双端接入 -> 结论: 富文本语义已收口到 Rust;StateObserver 已落到当前可稳定消费的 snapshot 边界;未引入并行渲染路径或平台回退路径 -> 备注: 文中早期提到的 `TopicDetailFeedSnapshotState` 已在 2026-06-06 的 topic-detail source/presentation 收口中被 `TopicDetailSourceSnapshotState + TopicTreePresentationState` 取代;2026-06-07 起 topic-detail poll option 纯文本也由 Rust payload 提供,平台 cell/layout 路径不再同步解析 option HTML。2026-09-19 起宿主只消费 `RenderDocumentHandle`(`checksum` / `plainText` / `segment(i)`),不再消费 `cooked` 或整包 `RenderPresentationState`。当前边界见 `docs/architecture/2026-09-19-render-presentation.md`。本文件保留为富文本与 observer 设计的历史实现记录。 - ---- - -## 1. 本次交付落地了什么 - -### 1.1 Rust 统一富文本主路径 - -- 新增 `crates/fire-rich-text/` -- 新增共享模型: - - `fire-models::RenderBlockKind` - - `fire-models::RenderBlock` - - `fire-models::RenderDocument` - - `fire-models::RenderImageAttachment` -- `fire-core` 保留 `render_cooked_html(raw_html, base_url)` 作为内部 IR 入口;`present_cooked_html` 是面向宿主的展示计划入口。`parse_cooked_html(raw_html)` 是 Rust 内部 parser / AST 单测入口,不是平台渲染入口 - -### 1.2 FFI 边界 - -- `fire-uniffi-types` 新增: - - `RenderBlockKindState` - - `RenderBlockState` - - `RenderDocumentState` - - `RenderImageAttachmentState` -- 顶层 `fire-uniffi` 当前出站: - - `present_cooked_html(raw_html, base_url) -> Option>`(仅测试夹具;现网见 `2026-09-19-render-presentation.md`) - - `StateObserver` callback interface -- `fire-uniffi-topics::TopicPostState` / `TopicPostBoostState` 与 `ChatMessageState` 携带 `presentation` - -### 1.3 双端接入 - -- iOS: - - 删除平台侧 cooked HTML 解析路径 - - 只消费 `TopicPostState.presentation` / `RenderDocumentHandle` - - `FireRenderPresentation` 把预计算 segment 映射成 `FireRichTextNode` - - `FireTopicPresentation.renderContent(from post:)` 缺少 `presentation` 时返回空,不再从 cooked 生成正文 fallback -- Android: - - 删除平台侧 cooked HTML 解析路径 - - 只消费 `TopicPostState.presentation` / `RenderDocumentHandle` - - `FireRenderPresentation` 把预计算 segment 映射成 `FireRichTextBlock` - - `PostViewHolder` / `TopicDetailViewModel` 缺少 `presentation` 时不显示伪造正文 - -### 1.4 StateObserver - -- `FireAppCore` 提供统一 `register_state_observer()` / `unregister_state_observer()` -- Rust 内部通过 `fire-core/src/state_observer.rs` 维护单一 observer 注册点 -- 同一 snapshot 域通过 100ms debounce 合并连续更新,只推最新值 -- observer callback 使用 `catch_unwind` 做错误隔离,单个回调异常不会污染其他域 -- 当前会主动推送的 snapshot 边界: - - `SessionState` - - `TopicListState` - - `NotificationCenterState` - -### 1.5 Topic detail poll option boundary - -- `PollOption` / `PollOptionState` 现在携带 Rust 侧生成的 `plain_text` / `plainText`。 -- iOS `FirePostPollRenderModel` 和 Android `PostViewHolder` 直接消费这个纯文本标题,空值才回退到 option id。 -- poll-bearing cell configure、layout key、layout precompute 路径不得调用 `render_cooked_html` 或任何平台 HTML parser 来同步解析 option HTML。 - ---- - -## 2. 实际采用的设计 - -### 2.1 为什么不是递归 RenderBlock tree FFI - -最终没有把 FFI 设计成递归 `children: Vec`,而是采用了扁平文档: - -```rust -pub struct RenderDocument { - pub blocks: Vec, - pub plain_text: String, - pub image_attachments: Vec, -} - -pub struct RenderBlock { - pub id: u32, - pub parent_id: Option, - pub depth: u32, - pub kind: RenderBlockKind, -} -``` - -原因: - -1. 当前双端本来就已经有轻量 parent/child 重建逻辑,保留这一步几乎没有维护成本 -2. UniFFI 对扁平 record 的代码生成和平台调试更直接 -3. 真正需要收口的是“语义判断”和“URL/quote/details/image attachment 规则”,不是平台内的 `childrenByParentId` 映射 - -这次交付的目标是消灭双端语义分叉,而不是为了数据结构形式强行重写平台渲染器。 - -### 2.2 RenderBlockKind 以“当前原生渲染语义”对齐 - -实现没有强行追求抽象过度的 block taxonomy,而是直接对齐当前双端原生渲染需要: - -- 文本与样式:`Text` / `Bold` / `Italic` / `Strikethrough` / `InlineCode` / `CodeBlock` -- 结构:`Paragraph` / `Heading` / `LineBreak` / `List` / `ListItem` -- 链接语义:`Link` / `Mention` / `MentionGroup` / `Hashtag` -- 媒体:`Image` / `Emoji` / `Video` / `Onebox` -- 论坛特有结构:`Quote` / `Blockquote` / `Spoiler` / `Details` / `DetailsSummary` -- 降级块:`Table { text }` / `Divider` / `Unknown` - -这样做的结果是: - -- 平台端只做轻映射 -- quote/details/emoji/attachment/lightbox 规则只有 Rust 一处 -- onebox 标题/描述/来源/站标/缩略图提取也只有 Rust 一处,平台不抓取或解析 Open Graph / HTML preview -- 现有 iOS `NSAttributedString` / Android `Spannable` 渲染器可以直接复用 - -### 2.3 图片附件提取也回到 Rust - -`RenderDocument.image_attachments` 现在由 Rust 统一生成,包含: - -- lightbox 优先取祖先链接 URL -- emoji 不进入附件列表 -- avatar / quote avatar / thumbnail 被统一过滤 -- 宽高在 Rust 侧标准化成 `Option` - -平台端不再各自维护一套附件提取和去重规则。 - -2026-06-08 起,双端 topic detail 以 `RenderBlockKind::Image` 保留图片在正文中的顺序,但图片展示 URL -以 Rust 生成的 `RenderDocument.image_attachments` 为准:lightbox / generic linked image 场景优先使用 -original URL,正文缩略展示和点击预览因此共享同一个缓存键。平台端只负责按节点顺序切分 text/image segment、 -选择显示尺寸、展示加载/失败/重试状态,以及打开原生图片预览。 - -如果 Rust 已经给出 `image_attachments`,但当前 render tree 没有对应 `Image` block(例如服务端 HTML 清洗或 -block 映射遗漏导致的旧数据形状),平台可以按 Rust attachment 列表补齐尚未消费的图片 segment。这个补齐只以 -`RenderDocument.image_attachments` 为数据源并按 URL 去重,不能重新解析 `post.cooked`,也不能恢复平台侧附件提取规则。 - -图片附件旁的上传元信息 chrome 也只在 Rust 侧过滤。匹配规则不依赖 `image` 这种固定前缀,前缀可以是文件名、 -hash 或其他服务器输出字符串;只有末尾满足“尺寸 + 文件大小”的附件说明会被剥离,普通 caption / 正文文本必须保留。 - -Quote / onebox preview 的语义同样在 Rust 侧收口。Rust 会移除 Discourse quote chrome/avatar,并从 onebox -节点树提取标题、描述、来源域名、站标和缩略图。onebox 内部的 `site-icon` / `thumbnail` 不属于帖子图片, -不会进入 `image_attachments`,因此也不会被平台当成文末大图补上。iOS / Android 只负责把共享节点映射成 -可点击的 onebox 卡片(站标保持小图标,缩略图在标题旁)和紧凑引用预览,不保留平台侧 link-preview fetcher -或 HTML fallback。行内 `inline-onebox` 仍是链接,不会被收成卡片。 - -### 2.4 展示派生留在 Rust - -图片列表、纯文本和 display segment 现在随 `RenderPresentation` 一次算完。宿主不再把 `RenderDocumentState` 回传 Rust 做第二次 `collect_images` / `plain_text` / segment 拆分。`PresentedDocument` 同时持有 IR,供后续 `RenderDocumentHandle` 按需暴露派生视图。 - ---- - -## 3. StateObserver 的当前边界 - -### 3.1 Rust 内触发点 - -当前 observer 不是“全状态自动广播”,而是基于已经稳定存在的 snapshot 边界推送: - -- `AppStateRefresher` - - `refresh_bootstrap()` 后推 `SessionState` - - 当前 home 话题列表刷新成功后推 `TopicListState` - - 二阶段通知刷新后推 `NotificationCenterState` -- `FireTopicsHandle` - - `fetch_topic_list()` 后推 `TopicListState` -- `FireNotificationsHandle` - - `fetch_recent_notifications()` / `fetch_notifications()` 后推 `NotificationCenterState` - - `mark_notification_read()` / `mark_all_notifications_read()` 后推 `NotificationCenterState` - -### 3.2 双端当前消费方式 - -#### iOS - -- `FireAppViewModel` 注册 `StateObserver` -- observer 直接驱动: - - `applySession` - - `FireHomeFeedStore.applyTopicList` - - `FireNotificationStore.apply` -- 旧的 `AppStateRefreshEvent` 拉取型处理保留了接口,但不再承担 home/notification 的主刷新路径 - -#### Android - -- `FireSessionStore` 初始化时自动注册 `FireStateObserverRepository` -- 当前已直接消费: - - `HomeViewModel` 监听 `sessionSnapshots` - - `NotificationsViewModel` 监听 `notificationCenterSnapshots` -- `topicDetailFeedSnapshots` 已暴露,但 Android 话题详情列表仍沿用现有 screen/paging 组装路径 - -### 3.3 这次没有做的事 - -以下项目不属于这次 merge 的实现边界: - -- 不把 Android home `PagingSource` 整体改成 snapshot-backed 列表 -- 不把 topic detail 的 MessageBus 触发器整体下沉进 Rust observer 自动刷新 -- 不移除所有同步 fetch API - -原因不是“保留回退”,而是这些路径当前仍承担: - -- 分页命令 -- 显式刷新命令 -- Cloudflare 恢复入口 -- screen-owned 生命周期控制 - -本次变更已经把 observer 建成 authoritative push boundary;剩余部分应在后续单独围绕分页和 MessageBus 编排继续收口,而不是把这次改造成大范围控制流重写。 - ---- - -## 4. 双端渲染落地结果 - -### 4.1 iOS - -当前链路: - -```text -TopicPostState.presentation / present_cooked_html() - -> FireRenderPresentation - -> [FireRichTextNode] / FireTopicPostRenderSegment - -> ASTextNode / Nuke-backed 原生图片节点 / JXPhotoBrowser preview -``` - -保留下来的平台职责: - -- 原生字体、颜色、交互样式 -- `NSAttributedString` 生成 -- Texture 节点布局、图片显示尺寸、失败重试和 JXPhotoBrowser 图片预览手势 - -已移出平台的职责: - -- mention / mention-group / hashtag 语义识别 -- quote 标准化 -- details summary/body 拆分 -- onebox 标题/描述/来源/站标/缩略图提取;站标和缩略图不进入帖子图片列表 -- emoji fallback 解析;正文 leftover `:shortcode:` 收成 Emoji 节点(标准 twitter URL),代码块不展开 -- image attachment 选择与过滤,包括图片元信息文本和 quote chrome/avatar 过滤 -- 相对 URL 解析 -- 平台本地从 cooked HTML 合成 RenderDocument 的路径 - -### 4.2 Android - -当前链路: - -```text -TopicPostState.presentation / present_cooked_html() - -> FireRenderPresentation - -> [FireRichTextBlock] - -> FireRichTextView / Coil-backed ImageView / ZoomImage preview -``` - -保留下来的平台职责: - -- `Spannable` span 组合 -- 文本/链接/代码块样式 -- `TextView` / `ImageView` 展示、图片失败重试和 ZoomImage 预览手势 - -已移出平台的职责与 iOS 相同,语义解析不再双写。 - ---- - -## 5. 文档与代码对齐后的结论 - -### 5.1 已完成 - -- [x] 新增 `fire-rich-text` -- [x] 新增共享 RenderDocument 模型 -- [x] 新增 FFI `present_cooked_html` -- [x] 展示派生(图片 / 纯文本 / segment)随 `RenderPresentation` 一次出站 -- [x] `TopicPostState` 携带 `presentation` -- [x] iOS 富文本改为消费 `RenderPresentationState` -- [x] Android 富文本改为消费 `RenderPresentationState` -- [x] 双端提取出 RenderDocument builder 分层,平台 parser 不再承担语义映射 -- [x] 删除双端 topic detail 正文 cooked HTML fallback;平台缺少 `presentation` 时暴露缺口,不伪造正文 -- [x] 新增统一 `StateObserver` -- [x] Rust 内部建立 observer 注册与推送机制 -- [x] Rust observer 推送具备 debounce 与 callback 错误隔离 -- [x] iOS 接入 session/topic-list/notification/topic-detail-feed observer 消费入口 -- [x] Android 接入 session/notification observer 消费入口 - -### 5.2 当前明确保留的边界 - -- [x] 保留平台原生显示适配器,不引入并行 renderer 或 cooked HTML fallback -- [x] 保留显式分页/刷新命令 -- [x] Rust 内部保留 `parse_cooked_html()` 作为 parser / AST 单测入口;平台不得调用它来渲染 topic body -- [x] 不把 observer 扩大成无边界的“任何状态变化都广播” - ---- - -## 6. 验证 - -本次实现已通过以下验证: - -- `cargo test -p fire-rich-text -p fire-uniffi-types -p fire-uniffi-topics -p fire-uniffi --lib` -- `cargo test -p fire-uniffi -p fire-uniffi-topics -p fire-uniffi-notifications -p fire-core --lib` -- `xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire -sdk iphonesimulator -configuration Debug build CODE_SIGNING_ALLOWED=NO` -- `cd apps/android-app && ./gradlew compileDebugKotlin` - ---- - -## 7. 后续演进方向 - -后续如果继续收口,可以沿这三条线推进,而不需要回退本次结构: - -1. Android home 改成 observer-fed snapshot + adapter diff,而不是 PagingSource refresh -2. topic detail 继续维持 source snapshot + tree presentation 的显式双层契约,而不是重新引入 processed feed snapshot -3. profile bio 读 `bio_plain_text`;bookmark / 其他活动摘录仍可本地折 HTML。正文热路径只消费 `RenderDocumentHandle` diff --git a/docs/architecture/2026-06-17-unified-onboarding-launch-design.md b/docs/architecture/2026-06-17-unified-onboarding-launch-design.md deleted file mode 100644 index 47f4950a..00000000 --- a/docs/architecture/2026-06-17-unified-onboarding-launch-design.md +++ /dev/null @@ -1,528 +0,0 @@ -# 统一启动登录页设计 - -> 日期:2026-06-17 -> 状态:已确认,待实现(rev 3 — 对齐启动会话恢复语义与 validation 时序) -> 范围:iOS 启动流程 UI 合并,逻辑层保持解耦 - -## 修订记录 - -- **rev 3(本次)**:根据 `9a6fe30` 的启动会话恢复更新,修正 `performStartupValidation()` 设计:validation 必须自己拥有 `prepareStartupSession → awaitPreloadedData → completeStartupAfterPreheat` 全链路,不能依赖 `RootCoordinator.start()` 中的 `loadInitialState()` 先完成;`awaitPreloadedData()` 失败时需沿用当前 PreheatGate 的会话保留规则,存在 `canReadAuthenticatedApi` 或 `hasLoginCookie` 时继续完成启动判定,避免把仍需判定的本地会话直接判为启动失败。 -- **rev 2**:根据对实际源码的二次核实修正四处 P1 缺陷与两处 P2。原 rev 1 误判 `isBootstrappingSession` 已覆盖校验全链路,且忽略了删除 preheat/auth modal 后 `completeStartupAfterPreheat()` 失去驱动方、captcha dialog 失去 dismiss 路径、saved credential 失去加载入口三个回归。详见各节"⚠️ rev 2 修正"标记。 - -## 背景与问题 - -当前 iOS 启动阶段存在三段式割裂体验,用户需要多次手动跳转和点击才能进入登录表单: - -``` -PreheatGate 页 (logo + loading "正在校验登录态…") - │ 校验失败 - ▼ -点击 "登录 LinuxDo" 按钮 ← 多一次手动点击 - ▼ -FireLoginViewController (logo + 账号密码表单 + 登录按钮) ← 又一个 logo,又一个页面 - │ 点击 "登录" 按钮 - ▼ -hCaptcha dialog → 登录完成 -``` - -割裂的根因是三个页面服务于两个独立的 root kind 状态加一个 modal present 路径: - -| 控制器 | 角色 | 触发条件 | -|---|---|---| -| `FirePreheatGateWaitingViewController`(含 `FirePreheatGateViewController`) | root kind `.preheat`,校验本地登录态 | 冷启动 | -| `FireOnboardingViewController` | root kind `.onboarding`,未认证的等待页 | preheat 完成且未认证 | -| `FireLoginViewController` | modal 全屏页,账号密码表单 | `authPresentationState == .login` | - -三套 UI 各自重复了 logo + title + subtitle + button 布局,违反 AGENTS.md "prefer one authoritative implementation path per feature" 原则。 - -## 目标 - -将启动校验态、账号密码表单、登录中态合并到单一页面(`FireOnboardingViewController`),通过内部状态机切换中间内容区域,消除用户的手动跳转和重复点击。逻辑层(`FireSessionStore`、`FireWebViewLoginCoordinator`、`FireCaptchaLoginDialogController`、`FireAppViewModel` 登录编排方法)保持不动。 - -## 非目标 - -- 不改动 `FireSessionStore`、`FireWebViewLoginCoordinator`、`FireCaptchaLoginDialogController` 的任何 public API。 -- 不改动 `FireAppViewModel` 的登录编排方法签名(`ensureCloudflareClearance`、`loginCoordinatorForDialog`、`classifyLoginResult`、`completeMinimalLogin`、`recoverLoginCloudflareChallenge`)。 -- 不引入 SwiftUI(保持与现有 UIKit 启动页惯例一致)。 - -## 设计 - -### §1 状态模型 - -#### Root Coordinator 状态简化 - -`FireRootCoordinator.RootKind` 从三态简化为两态: - -```swift -private enum RootKind: Equatable { - case launch // 合并原 .preheat + .onboarding - case main -} -``` - -删除 `preheatComplete` 布尔标记。`updateRoot(animated:)` 由 `currentAuthenticationState` 直接驱动:未认证 → `.launch`,已认证 → `.main`。 - -#### Onboarding 页内部状态机 - -新增纯 UI 状态枚举,由 viewModel 的 `@Published` 派生: - -```swift -enum FireOnboardingPhase: Equatable { - case validating // 正在校验登录态(loading) - case credential // 显示账号密码表单 - case loggingIn // 登录请求中(表单 disabled + loading overlay) -} -``` - -派生规则(在 onboarding 页 `bindState` 里组合 viewModel 状态): - -| viewModel 状态组合 | phase | -|---|---| -| `isStartupValidationComplete == false` | `.validating` | -| `isStartupValidationComplete == true` 且未认证 | `.credential` | -| `isSyncingLoginSession == true` 或 captchaDialog 已 present | `.loggingIn` | - -`.validating → .credential` 的切换不需要用户点击,纯响应式。 - -#### ⚠️ rev 2 修正:启动校验状态必须覆盖全链路 - -原 rev 1 用 `isBootstrappingSession` 派生 `.validating`,经代码核实**不成立**: - -- `loadInitialState()`(`FireAppViewModel.swift:126-174`)只调用 `sessionStore.prepareStartupSession()` 并调度 `ensurePreloadedDataLoaded()`,**不调用 `determineLoginStateWithProbe()` 或 `applySession()`**。 -- `isBootstrappingSession` 在 `finishInitialStateLoading(generation:)`(`FireAppViewModel.swift:1114`)翻为 false,这发生在 `prepareStartupSession` 返回时,**早于**登录态判定。 -- 真正的登录态判定(`determineLoginStateWithProbe` + `applySession`)在 `completeStartupAfterPreheat()`(`FireAppViewModel.swift:176`),当前唯一驱动方是 `FirePreheatGateViewController.awaitPreloadedData()` 的 `onComplete` 回调 → `FireRootCoordinator.completePreheat()`(`FireRootCoordinator.swift:340`)。 -- PreheatGate 实际等待两个阶段:`prepareStartupSession()` **和** `awaitPreloadedData()`(`FirePreheatGateViewController.swift:46-63`),rev 1 只覆盖前者。 -- `9a6fe30` 后,`awaitPreloadedData()` 失败不再等同于启动校验失败:当前 PreheatGate 会读取 `sessionStore.snapshot().readiness`,只要 `canReadAuthenticatedApi == true` 或 `hasLoginCookie == true`,就保留本地会话并继续 `onComplete`,让 `completeStartupAfterPreheat()` 做最终登录态分流。 - -**修正方案**:新增 viewModel 状态与方法,把"校验完成"语义收口到 viewModel,由 onboarding VC 在 `viewDidLoad` 时触发。`performStartupValidation()` 是新的启动校验权威路径,自己执行 `prepareStartupSession()`,不依赖 `RootCoordinator.start()` 中的 `loadInitialState()` 先完成。 - -```swift -// FireAppViewModel 新增 -@Published private(set) var isStartupValidationComplete = false -private var isStartupValidationInFlight = false - -/// 替代 PreheatGate 的 prepareStartupSession + awaitPreloadedData -/// + completeStartupAfterPreheat 链路。 -/// 由 onboarding VC 在 viewDidLoad 触发一次(冷启动 root == .launch 时)。 -func performStartupValidation() async { - guard !isStartupValidationComplete else { return } - guard !isStartupValidationInFlight else { return } - - isStartupValidationInFlight = true - defer { - isStartupValidationInFlight = false - isStartupValidationComplete = true - } - - do { - let sessionStore = try await sessionStoreValue() - _ = try await sessionStore.prepareStartupSession() - do { - _ = try await sessionStore.awaitPreloadedData() - } catch { - let readiness = try? sessionStore.snapshot().readiness - guard readiness?.canReadAuthenticatedApi == true - || readiness?.hasLoginCookie == true - else { - throw error - } - } - await completeStartupAfterPreheat() - } catch { - completeStartupAfterPreheatFailure(message: "网络异常,请重新登录") - } -} -``` - -`isBootstrappingSession` 保留原语义(仅标记 `prepareStartupSession` 阶段),不再用于 onboarding phase 派生。onboarding phase 的 `.validating` 完全由 `isStartupValidationComplete == false` 决定。 - -`loadInitialState()` 不再是冷启动 root 的前置条件,避免 onboarding `viewDidLoad` 早于 `RootCoordinator.start()` 后半段执行时出现 validation 先于 prepare 的竞态。该方法保留给开发者工具/诊断入口继续使用;启动页只调用 `performStartupValidation()`。 - -#### `authPresentationState` 弃用(不删除) - -`openLogin()` 和 `dismissAuthPresentation()` 保留方法定义,但 onboarding 页不再调用 `openLogin()`(表单内嵌)。`completeMinimalLogin` / `completeLogin` 成功时 `setAuthPresentationState(nil)` 不再驱动 modal dismiss——dismiss 责任迁移到 onboarding VC 的 `isSyncingLoginSession` 监听(见 §4 "登录成功后必须显式清理")。`dismissAuthPresentation()` 的唯一调用方(login VC 关闭按钮)随 login VC 删除而消失,保留方法不删除以避免连锁改动。 - -### §2 页面结构与视图拆分 - -#### 整体布局 - -``` -┌──────────────────────────────────┐ -│ [dev tools] (nav) │ 保留现有开发者工具入口 -├──────────────────────────────────┤ -│ 🔥 (logo) │ Hero 区(固定,所有 phase 共享) -│ Fire │ -│ LinuxDo 原生客户端 │ -├──────────────────────────────────┤ -│ ┌──────────────────────────┐ │ -│ │ 可替换的中间内容区 │ │ PhaseContainerView -│ │ (loading / 表单 / 空) │ │ -│ └──────────────────────────┘ │ -├──────────────────────────────────┤ -│ [error banner] (有错才显示) │ 复用现有 FireOnboardingErrorBannerView -└──────────────────────────────────┘ -``` - -#### 子视图拆分 - -为避免 `FireOnboardingViewController` 变胖,中间内容区拆成三个子 `UIView`: - -1. **`FireOnboardingValidatingView`**(新建,约 40 行) - - `UIActivityIndicatorView` + `UILabel`("正在校验登录态…")。 - - 从现有 `FireStartupOnboardingStatusView.showLoading` 抽取,纯展示。 - -2. **`FireOnboardingCredentialFormView`**(从 `FireLoginViewController` 迁移,持续迭代) - - 包含:用户名输入、密码输入(右侧 eye 明文切换)、记住密码圆形勾选(`circle` / `checkmark.circle.fill`,字号 13,与右侧蓝色「忘记密码?」链接同一行)、登录按钮、官方第三方登录 icon 行(Google / GitHub / X / Discord / Apple / Passkey)。 - - **保留 `UIScrollView` + `contentView` 容器结构**,以适配小屏键盘遮挡:`scrollView.keyboardDismissMode = .interactive`、`contentView.widthAnchor == scrollView.frameLayoutGuide.widthAnchor` 保证竖向滚动 + 横向不溢出。 - - 外层 onboarding VC 将品牌区固定在 safe area 顶部的紧凑头部,`phaseContainerView` 占满品牌下方到 safe area / 键盘上方的可用空间,避免 logo 居中挤压账号密码和其他登录方式。 - - 监听键盘 `willChangeFrame` / `willHide` 通知,外层移动表单容器到键盘上方,表单内部按本地坐标补充 `scrollView.contentInset.bottom`,并支持点空白、拖动、Return/Go、输入工具栏"完成"关闭键盘。 - - 不持有 viewModel,通过闭包回调:`onLoginTapped(identifier:password:remember:)`、`onForgotPassword`、`onExternalLogin(FireExternalLoginMethod)`。 - - 第三方登录不在 App 内自建 OAuth Client:icon 点击后由 onboarding VC present `FireWebViewBrowserViewController(url: /login, autoStartExternalLogin:)`,页面 `didFinish` 后注入脚本点击 Discourse `#login-buttons` 中对应 `button.btn-social.{provider}` 或 `button.passkey-login-button`,形成 native 入口 + WebView 完成 IdP 的效果。 - - 登录成功后本地记录 `FireLastLoginMethod`(Keychain,host-scoped):密码路径写 `.password`,第三方 WebView 路径写对应 provider;`prepareLoginForm()` 读回并通过 `applyLastLoginMethod` 高亮上次使用的 icon。 - - 暴露 `applySavedCredential(_:)`:仅在对应输入框为空时回填 Keychain 凭据;`nil` 绝不清空当前输入(人机验证失败 / 密码错误后需保留可改内容)。 - - 暴露 `setLoggingIn(_:)` 用于 disable/enable 表单。 - - 登录失败(含 captcha panel 失败、invalid credentials)不清理已输入账号密码。 - - **不包含 error banner**(见下方"error banner 职责统一")。 - -3. **`.loggingIn` phase(无独立 overlay 视图)** - - 保留 `FireOnboardingCredentialFormView`,仅 `setLoggingIn(true)`:禁用输入并在登录按钮上显示 spinner /「登录中…」。 - - 不再使用半透明灰色遮罩(避免闪一下灰 container);安全验证 sheet 弹出后回到 `.credential`。 - -#### PhaseContainerView 切换逻辑 - -onboarding VC 持有 `phaseContainerView`,根据 phase 切换子视图: - -| phase | container 内容 | -|---|---| -| `.validating` | `FireOnboardingValidatingView` | -| `.credential` | `FireOnboardingCredentialFormView` | -| `.loggingIn` | `FireOnboardingCredentialFormView`(disabled + 按钮 spinner) | - -切换用 `UIView.transition` crossDissolve,duration 0.22(与 root 切换一致)。 - -#### Hero 区复用 - -`FireOnboardingViewController.configureBrand()` 的 logo + title + subtitle 作为所有 phase 共享的固定头部,但布局必须靠近 safe area 顶部并保持紧凑,给 `.credential` phase 留出完整表单高度。 - -#### error banner 职责统一 - -合并前存在两个 error banner: - -- `FireLoginViewController` 的顶部红色横幅(`setupErrorBanner`,自动 4 秒消失)——用于登录流程中的即时失败提示(如"密码错误"、"网络验证失败")。 -- `FireOnboardingViewController` 的底部 `FireOnboardingErrorBannerView`(可手动关闭)——用于 viewModel.errorMessage。 - -合并后**统一使用 onboarding VC 的 error banner**(底部、可关闭),但增加自动消失能力(4 秒)。`FireOnboardingCredentialFormView` 不内嵌 error banner,登录失败消息通过 onboarding VC 的 `showErrorBanner(_:)` 方法统一展示。这样消除重复 UI,且错误提示位置在所有 phase 一致。 - -### §3 Root Coordinator 改动 - -#### 删除的状态与方法 - -```swift -private var preheatComplete = false // 删除 -private weak var preheatController: FirePreheatGateWaitingViewController? // 删除 -private var preheatSessionStoreTask: Task? // 删除 -private weak var authController: UIViewController? // 删除 - -private func makePreheatController() -> UIViewController // 删除 -private func preparePreheatSessionStoreIfNeeded() // 删除 -private func completePreheat() // 删除 -private func requestLoginAfterPreheatFailure(message: String?) // 删除 -private func syncAuthPresentation(_ state: FireAuthPresentationState?) // 删除 -``` - -所有删除的方法和状态都只在 `FireRootCoordinator` 内部被调用,无外部依赖。 - -#### `updateRoot` 简化 - -```swift -private func updateRoot(animated: Bool) { - let nextKind: RootKind = currentAuthenticationState ? .main : .launch - guard rootKind != nextKind else { return } - rootKind = nextKind - let controller: UIViewController - switch nextKind { - case .launch: - controller = makeOnboardingController() - case .main: - controller = makeMainTabBarController() - } - // 现有 window transition 逻辑不变 -} -``` - -#### `start()` 简化 - -```swift -func start() { - guard let window else { return } - Self.activeCoordinator = self - bindState() - updatePreferredAppearance() - updateRoot(animated: false) - window.makeKeyAndVisible() - homeFeedStore.setSceneActive(false) - FireAPMManager.shared.setScenePhase(ScenePhaseLabel.inactive.rawValue) - updateTopLevelAPMRoute() - // 删除 viewModel.loadInitialState() - // 删除 preparePreheatSessionStoreIfNeeded() -} -``` - -`viewModel.loadInitialState()` 也从 `start()` 删除。统一启动页创建后由 `FireOnboardingViewController.viewDidLoad` 调用 `viewModel.performStartupValidation()`,避免 RootCoordinator 和 onboarding VC 同时驱动 session restore / preload。 - -#### `bindState` 简化 - -删除两个 binding: - -- `viewModel.$authPresentationState` 的 `syncAuthPresentation` binding(登录表单不再 modal present)。 -- `viewModel.$session` 的 `handleAuthenticationChange` **保留**(这是 `.launch → .main` 的唯一驱动)。 - -`syncTopicPresentation` 里的 `guard authController == nil` 守卫(`FireRootCoordinator.swift:381`)删除。 - -### §4 Onboarding VC 登录编排 - -#### 迁移自 `FireLoginViewController` 的方法 - -以下方法原样迁移到 `FireOnboardingViewController`(逻辑不变,宿主变化): - -- `performLogin()` — `ensureCloudflareClearance` → `loginCoordinatorForDialog` → `presentCaptchaDialog` -- `presentCaptchaDialog(loginCoordinator:)` — 构造 `FireCaptchaLoginDialogController`,设置 `classifyResult` 回调 -- `dialogResult(from:)` / `handleDialogResult(_:)` — success / needSecondFactor / retryCloudflare / failure 分发 -- `completeLoginFromDialog()` — `viewModel.completeMinimalLogin(...)` -- `showSecondFactorPrompt(requirement:)` — `UIAlertController` 6 位验证码 -- `recoverCloudflare()` — `cfRetryUsed` 单次重试 -- `presentWebViewBrowser(url:autoStartExternalLogin:)` — 忘记密码 / 第三方登录的 WKWebView 兜底;第三方入口会携带 `FireExternalLoginMethod` 以自动点击官方按钮 -- `setLoginLoading(_:)` / `showErrorBanner(_:)` / `hideErrorBanner()` / `dismissCaptchaDialog()` - -所有 viewModel 调用的方法签名不变。 - -#### `FireCaptchaLoginDialogController` 的 present 宿主变化 - -现在由 onboarding VC present(而非 login VC)。`captchaDialog` 持有变量、`present(dialog, animated: true)` 调用点不变。dialog 内部逻辑(hCaptcha、JS login、cookie 提取)零改动。 - -#### 表单触发流程 - -``` -onboarding phase == .credential - → 用户在 FireOnboardingCredentialFormView 填账号密码 - → 点击登录按钮 → formView.onLoginTapped(identifier:password:remember:) 闭包 - → onboarding VC: - pendingIdentifier = identifier - pendingPassword = password - pendingRememberCredential = remember - cfRetryUsed = false - hasShownSecondFactor = false - phase = .loggingIn - Task { await performLogin() } -``` - -`.loggingIn` 状态下 `FireOnboardingLoggingInView` overlay 显示,表单 disabled。 - -#### ⚠️ rev 2 修正:saved credential 必须显式加载 - -原 rev 1 说迁移 `$savedLoginCredential` 订阅即可回填表单。经代码核实**不成立**: - -`loadSavedCredential()` 只在 `openLogin()`(`FireAppViewModel.swift:236-244`)的 Task 里调用。`$savedLoginCredential` 订阅本身不触发加载,只在 viewModel 已发布值时回调。onboarding 页不调用 `openLogin()`,则 `savedLoginCredential` 永远为初始值 `nil`,表单无法回填。 - -**修正方案**:从 `openLogin()` 抽出登录表单准备逻辑为独立方法,onboarding VC 在进入 `.credential` phase 时调用: - -```swift -// FireAppViewModel 新增(从 openLogin L236-244 抽取) -func prepareLoginForm() async { - do { - let sessionStore = try await sessionStoreValue() - savedLoginCredential = try await sessionStore.loadSavedCredential() - _ = try await loginCoordinatorValue() // 预热 coordinator - } catch { - errorMessage = error.localizedDescription - } -} -``` - -onboarding VC 的 phase 派生逻辑里,当 `isStartupValidationComplete == true` 且未认证(即将进入或已在 `.credential`)时触发一次: - -```swift -private func applyPhase(_ next: FireOnboardingPhase) { - if next == .credential, phase != .credential { - Task { await viewModel.prepareLoginForm() } - } - phase = next - // ...container view 切换 -} -``` - -`openLogin()` 保留供其他入口(开发者工具等,实现阶段确认 call site),但其内部的 credential 加载逻辑改为调用 `prepareLoginForm()` 以避免重复。 - -#### errorMessage 绑定 - -现有 `FireOnboardingView.swift:113-118` 的 `viewModel.$errorMessage` 订阅保留。当 `phase == .loggingIn` 时收到 errorMessage,走与 `handleDialogResult(.failure)` 相同的 dismiss + showErrorBanner 路径(迁移自 `FireLoginViewController.swift:95-105`),并让 phase 回到 `.credential`。 - -#### ⚠️ rev 2 修正:登录成功后必须显式清理 captcha dialog 与 loggingIn phase - -原 rev 1 称 `setAuthPresentationState(nil)` 变成 no-op "无害"。经代码核实**有害**: - -当前成功路径 `completeMinimalLogin`(`FireAppViewModel.swift:324`)调用 `setAuthPresentationState(nil)`,RootCoordinator 的 `syncAuthPresentation(nil)`(`FireRootCoordinator.swift:368-377`)负责 `authController.dismiss(animated:)`,**这个 dismiss 同时移除了 login VC 及其 present 的 captcha dialog**。 - -删除 `syncAuthPresentation` binding 后,onboarding 页成为 captcha dialog 的 present 宿主。成功路径不再有任何代码 dismiss dialog 或退出 `.loggingIn` phase。 - -**修正方案**:在 onboarding VC 监听 `viewModel.$isSyncingLoginSession` 的 false 翻转,作为登录完成的权威信号: - -```swift -viewModel.$isSyncingLoginSession - .receive(on: RunLoop.main) - .sink { [weak self] isSyncing in - guard let self else { return } - guard !isSyncing, self.phase == .loggingIn else { return } - self.setLoginLoading(false) - self.dismissCaptchaDialog() // 显式关闭 hCaptcha dialog - // phase 无需手动复位:root 即将切到 .main,onboarding VC 随之销毁。 - // 若登录失败(未切 root),completeMinimalLogin 的 catch 分支会 - // 通过 errorMessage 绑定走 dismiss + showErrorBanner 路径。 - } - .store(in: &cancellables) -``` - -`dismissCaptchaDialog()` 迁移自 `FireLoginViewController`,负责 `captchaDialog?.dismiss(animated:)` + 置空持有变量。 - -登录失败路径(未切 root)由上文 errorMessage 绑定处理:`setLoginLoading(false)` + `dismissCaptchaDialog()` + `showErrorBanner(message)`,phase 回到 `.credential`。 - -### §5 ViewModel 改动 - -> ⚠️ rev 3:原 rev 1 称"不新增 `@Published`"。经核实需新增启动校验完成状态、single-flight guard 与两个方法,否则 preheat 链路断裂或产生时序竞态(见 §1 修正说明)。 - -#### 新增的状态与方法 - -| 新增 | 用途 | -|---|---| -| `@Published private(set) var isStartupValidationComplete` | onboarding phase `.validating` ↔ `.credential` 的权威派生源(替代语义不符的 `isBootstrappingSession`) | -| `private var isStartupValidationInFlight` | 保证 startup validation single-flight,避免重复 `viewDidLoad` / 重渲染触发并发校验 | -| `func performStartupValidation() async` | 替代 PreheatGate 的 `prepareStartupSession + awaitPreloadedData + completeStartupAfterPreheat` 链路,由 onboarding VC viewDidLoad 触发 | -| `func prepareLoginForm() async` | 从 `openLogin()` 抽取,负责 `loadSavedCredential` + coordinator 预热,由 onboarding VC 进入 `.credential` phase 时触发 | - -`openLogin()` 的内部 credential 加载逻辑改为调用 `prepareLoginForm()` 以避免重复。 - -#### 不改动的部分 - -- `FireSessionStore` 全部 public API(含 `awaitPreloadedData`) -- `FireWebViewLoginCoordinator` 全部 public API -- `FireCaptchaLoginDialogController` 全部 API -- `loadInitialState()` 的方法签名和核心逻辑不变,但不再由 `RootCoordinator.start()` 驱动冷启动;保留给 Developer Tools / 诊断重新加载入口。 -- `completeStartupAfterPreheat()` / `completeStartupAfterPreheatFailure()` 的**方法签名和核心逻辑**不变(`performStartupValidation` 内部调用它们,不重写) -- 所有登录编排方法签名 - -#### `authPresentationState` 弃用 - -`openLogin()` 保留但 onboarding 页不再调用(credential 加载逻辑已抽出到 `prepareLoginForm()`)。`dismissAuthPresentation()` 保留但无调用方(login VC 删除后)。这两个方法标记为后续清理,不在本次删除。 - -#### call site 影响清单 - -| 被删除的调用方 | 被调用的方法 | 处理 | -|---|---|---| -| `FireRootCoordinator.requestLoginAfterPreheatFailure` | `openLogin()` | 删除调用方 | -| `FireOnboardingView` 登录按钮 | `openLogin()` | 改为直接切到 `.credential` phase | -| `FireLoginViewController.closeTapped` | `dismissAuthPresentation()` | 删除调用方 | -| `FireRootCoordinator.syncAuthPresentation` | `FireLoginViewController` 构造 | 删除整个方法 | - -### §6 迁移步骤与验证 - -每个 Step 是独立 commit,可独立编译验证。 - -#### Step 1 — 新建子视图(纯增量) - -新建 `FireOnboardingValidatingView`、`FireOnboardingCredentialFormView`、`FireOnboardingLoggingInView`。内容从现有文件抽取,先不接入 onboarding VC。 - -验证:`xcodebuild` 编译通过。 - -#### Step 2 — Onboarding VC 接入 phase 状态机 + viewModel 新增 - -先在 `FireAppViewModel` 新增 `isStartupValidationComplete` / `isStartupValidationInFlight` / `performStartupValidation()` / `prepareLoginForm()`(见 §5)。再在 `FireOnboardingViewController` 加 `phase` 属性 + `bindState` 派生逻辑(用 `isStartupValidationComplete` 而非 `isBootstrappingSession`)。中间区域换成 `phaseContainerView`,挂载 Step 1 的子视图。hero 区和 error banner 保留。onboarding VC 的 `viewDidLoad` 触发 `Task { await viewModel.performStartupValidation() }`,`applyPhase(.credential)` 时触发 `viewModel.prepareLoginForm()`。迁移 `savedLoginCredential` / `errorMessage` / `isSyncingLoginSession` 绑定。 - -验证:onboarding 页能显示 loading 态,校验结束后能切到表单且表单有已保存凭据回填;构造 `awaitPreloadedData()` 失败但 snapshot readiness 仍有 `canReadAuthenticatedApi` 或 `hasLoginCookie` 的场景时,不能直接显示启动失败,而应继续执行 `completeStartupAfterPreheat()`,再由 `determineLoginStateWithProbe()` 决定进入 `.main` 还是留在 `.credential`。只有本次 preload 明确拿到 fresh `currentUser` 时才允许跳过 probe;持久化 session 里的旧 `currentUser` 不能单独作为冷启动登录态凭据。 - -#### Step 3 — 迁移登录编排逻辑 - -把 `performLogin` / `presentCaptchaDialog` / `handleDialogResult` / `showSecondFactorPrompt` / `recoverCloudflare` / `presentWebViewBrowser` / `setLoginLoading` / `showErrorBanner` / `hideErrorBanner` / `dismissCaptchaDialog` 迁移到 onboarding VC。`FireOnboardingCredentialFormView` 的 `onLoginTapped` 闭包接到这些方法。 - -验证:onboarding 页的 `.credential` 态能完整跑通登录流程(hCaptcha → second factor → cloudflare retry → 成功)。 - -#### Step 4 — Root Coordinator 简化 - -删除 `preheatComplete` / `preheatController` / `preheatSessionStoreTask` / `authController`。删除 `makePreheatController` / `preparePreheatSessionStoreIfNeeded` / `completePreheat` / `requestLoginAfterPreheatFailure` / `syncAuthPresentation`。`RootKind` 改为 `.launch` / `.main`。`bindState` 删除 `authPresentationState` binding。`start()` 删除 `viewModel.loadInitialState()` 和 preheat 调用。 - -验证:冷启动直接进 `.launch`,onboarding `viewDidLoad` 后只启动一条 validation task,校验成功自动切 `.main`,不可恢复校验失败自动切表单。 - -#### Step 5 — 删除废弃文件 - -删除 `App/Startup/FirePreheatGateWaitingViewController.swift`、`App/Startup/FirePreheatGateViewController.swift`、`App/Views/Other/FireLoginViewController.swift`。 - -验证:`xcodebuild` 编译通过,无残留引用。 - -#### Step 6 — 文档同步 - -> ⚠️ rev 2:扩大同步范围。原 rev 1 只提 architecture 文档。 - -删除 `FireLoginViewController` / PreheatGate 后,以下文档都引用了它们,必须一并更新: - -- `docs/architecture/fire-native-architecture.md`: - - L253 `FireRootCoordinator.swift` 注释(删 "preheat"、保留 "root/auth/route")。 - - L307 `FireLoginViewController.swift` 条目删除,改为 onboarding 合并后的条目。 - - L1000 登录/Cloudflare auth 段落,把 `FireLoginViewController` 替换为 onboarding VC 内嵌表单的描述。 -- `apps/ios-app/README.md`: - - L77 `App/Views/Other/FireLoginViewController.swift` 文件清单条目删除,补 `FireOnboardingCredentialFormView` 等新文件。 - - L93 RootCoordinator 职责描述(删 "auth modal presentation")。 - - L103 onboarding/PreheatGate 段落改为统一启动页描述。 - - L274-275 UX note 改为反映单页多 phase 体验。 -- 全仓 grep `FirePreheatGate`、`FireLoginViewController`、`authPresentationState`、`PreheatGate`,确认无其他残留引用。 - -#### 验证命令 - -每个 Step 完成后: - -```bash -xcodegen generate --spec apps/ios-app/project.yml -xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire \ - -destination 'generic/platform=iOS Simulator' build -``` - -Step 2-4 还应跑现有单元测试: - -```bash -xcodebuild test -project apps/ios-app/Fire.xcodeproj -scheme Fire \ - -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -``` - -特别关注 `FireSessionStoreTests`、`FireAppRouteTests`、`FireLoginScriptsTests`(预计不受影响,因为逻辑层未动)。 - -#### 风险与回退 - -- **主要风险**(rev 3 更新):`completeStartupAfterPreheat()` 失去 RootCoordinator 驱动方,需由 `performStartupValidation()` 接管;若遗漏 `prepareStartupSession()`、`awaitPreloadedData()` 的可恢复失败分支,或 `determineLoginStateWithProbe()`,校验链路会断裂或把仍需判定的本地会话直接推到启动失败/登录表单。**缓解**:Step 2 的验证项必须确认冷启动能走完 `prepareStartupSession → awaitPreloadedData → determineLoginStateWithProbe → applySession` 全链路,并覆盖 `awaitPreloadedData` 失败但 snapshot readiness 仍可恢复的场景。 -- **次要风险**:登录成功后 captcha dialog 不 dismiss。**缓解**:Step 3 验证项必须覆盖"成功登录 → dialog 消失 → root 切 .main"完整路径。 -- **回退**:每个 Step 是独立 commit,任何一步出问题可 revert 单步。 - -## 文件变更摘要 - -### 新建 - -| 文件 | 内容 | 行数估算 | -|---|---|---| -| `App/Startup/FireOnboardingValidatingView.swift` | 校验中 loading 视图 | ~40 | -| `App/Startup/FireOnboardingCredentialFormView.swift` | 账号密码表单(含 scrollView + 键盘适配,从 login VC 迁移) | ~280 | -| `App/Startup/FireOnboardingLoggingInView.swift` | 登录中 overlay 视图 | ~30 | - -### 修改 - -| 文件 | 改动 | -|---|---| -| `App/ViewModels/FireAppViewModel.swift` | 新增 `isStartupValidationComplete` / `isStartupValidationInFlight` / `performStartupValidation()` / `prepareLoginForm()`(rev 3) | -| `App/Views/Other/FireOnboardingView.swift` | 接入 phase 状态机、phaseContainerView、登录编排逻辑迁移、`performStartupValidation` 触发 | -| `App/Core/FireRootCoordinator.swift` | RootKind 两态化,删除 preheat/auth presentation 路径 | - -### 删除 - -| 文件 | 行数 | -|---|---| -| `App/Startup/FirePreheatGateWaitingViewController.swift` | 72 | -| `App/Startup/FirePreheatGateViewController.swift`(含 `FireStartupOnboardingStatusView`) | 221 | -| `App/Views/Other/FireLoginViewController.swift` | 622 | - -净删除约 900 行,新增约 370 行(含 onboarding VC 增量约 200 行、viewModel 增量约 30 行、表单 view 含 scrollView 增量约 30 行)。 diff --git a/docs/architecture/2026-07-21-ios-uikit-ux-modernization.md b/docs/architecture/2026-07-21-ios-uikit-ux-modernization.md deleted file mode 100644 index de89a023..00000000 --- a/docs/architecture/2026-07-21-ios-uikit-ux-modernization.md +++ /dev/null @@ -1,112 +0,0 @@ -# iOS UIKit-First UX Modernization - -## Goal - -Improve perceived polish (visual consistency, micro-interactions, loading chrome) without rewriting the app stack. Product UI is UIKit-first; topic-detail posts remain Texture-only. - -## Unified dark design language (2026-07-21) - -Reference style (consumer iOS dark settings / profile cards) is adopted **app-wide**, not only Profile/Settings: - -- **Canvas:** pure black in dark / OLED (`FireTheme.uiCanvas`) -- **Cards / grouped rows:** elevated charcoal (`uiSurface` ~`#1C1C1E`, `uiSurfaceSecondary` ~`#2C2C2E`) -- **Icon language:** colored rounded icon wells + white SF Symbols on profile/settings rows; brand accent remains Fire orange -- **Corners:** tighter continuous radii (`cornerRadius` 14 / `medium` 12 / `small` 10) — direct and clear, not overly bubbly -- **User cards:** shared `FireUserCard` sheet (chat, home, topic-detail avatars) stays a compact detent with a horizontal 13pt action row; do not restack full-width capsule `filled`/`bordered` buttons -- **Chrome:** nav/tab use theme canvas + material via `FireTheme.applyGlobalAppearances()` -- **Profile / Settings:** reference-style cards with colored wells, compact top inset, capsule appearance control, independent sign-out card, footer version -- **Home topic rows:** metric chips stay muted by default; notable/high values lift color weight (likes use the same 3-tier ladder as replies — not more); view *surge* (young + high velocity) shows a static 🔥/🚀 badge **after the count** so icon→number spacing stays constant, plus a short finite pulse on the badge; high likes can emit a one-shot 2-heart balloon. Micro-animations only run after the list is **settled** (~220ms after scroll stop / first paint) and **once per topic ID per session** via `FireTopicListMetricEffectCoordinator` (scrolling back does not replay). Reduce Motion disables motion entirely. - -Shared helpers live in `App/Core/UIKit/FireUIKitDesignLanguage.swift`. - -## Constraints - -1. Prefer mature open-source libraries over hand-rolled animation/toast/skeleton engines. -2. Prefer UIKit over SwiftUI for product surfaces. -3. Do not reintroduce SwiftUI post-row fallbacks in topic detail. -4. Cap new UI SPM packages; always access them through Fire facades. - -## Dependencies (UI chrome) - -| Package | Version | Facade | -|---------|---------|--------| -| Juanpe/SkeletonView | 1.31.0 | `FireUIKitSkeleton` | -| BastiaanJansen/toast-swift | 2.1.3 | `FireUIKitToast` | -| SnapKit | 5.7.1 | used by shared empty/error views | -| Texture / Nuke / JXPhotoBrowser | existing | unchanged hard-problem stack | - -System APIs remain authoritative for: `UIRefreshControl`, `UIVisualEffectView` / bar appearances, `UISheetPresentationController`, haptics (`FireMotionHaptics`), and diffable list animations. - -## Design tokens - -`FireTheme` exposes: - -- `ui*` `UIColor` accessors for UIKit -- matching SwiftUI `Color` wrappers from the same adaptive factories (including OLED) - -`FireTopicListPalette` is a temporary compatibility forwarder to `FireTheme.ui*`. - -## Motion - -- Tokens: `FireMotionTokens` -- UIKit helpers: `FireMotionUIKit` -- Haptics: `FireMotionHaptics` -- SwiftUI modifiers remain for residual SwiftUI screens only - -## Migration order - -1. Theme + toast + skeleton facades on existing UIKit lists — **done** -2. Filtered topic list → ListKit UIKit VC (`FireFilteredTopicListViewController`) — **done** -3. Profile tab + public profile → UIKit VCs (`FireProfileViewController`, `FirePublicProfileViewController`) — **done** - - Profile menu rows use `FireProfileMenuRowCell`: colored icon wells + white SF Symbols, 48pt single-line rows, trailing count left of chevron (e.g. `15条`) - - Header sits tight under the nav bar; three equal stat columns (粉丝 / 获赞 / 关注) on a soft secondary strip - - Follow / followers lists are UIKit (`FireFollowListViewController`) pushed on the secondary stack; user rows push `FirePublicProfileViewController` with a **stack-aware** topic presenter - - Public profile **最近动态** uses `FireAppRouteControllerFactory.present` cascade (preferred presenter → live nav / secondary stack → root secondary). Never `_ = presenter.present` with the SwiftUI environment default `.local` (that only produced cell selection animation) - - Route cascade logs via `ios.topic-route` (`route present cascade start/outcome=…`); missing `topic_id` on activity rows logs a warning - - Residual SwiftUI `FireFollowListView` is a thin host of the UIKit controller (no `NavigationLink` profile drill-down) -4. Topic detail chrome polish (nav material, theme colors, reaction haptics; Texture cells untouched) — **done** -5. Topic detail quick-reply bar: WeChat-style opaque full-width bottom strip — **done** - - **Pure UIKit** bar (`FireTopicQuickReplyBarView`) layered above Texture feed — not a Texture overlay - (Texture compositing was still letting feed text show through the left side) - - Growing input is `FireBottomInputBar` (`InputBarAccessoryView` 6.5.1 as a **subview**, never `inputAccessoryView` / `KeyboardManager`) so long text wraps, the capsule grows to 5 lines, then scrolls - - Library plugins: image paste + attachment strip, `@` mention autocomplete via `searchUsers` - - Solid opaque canvas chrome; resting pad = home indicator; keyboard pad = 8pt flush above keyboard - - Keyboard lifts via bottom Auto Layout constraint; feed `contentInset.bottom = barHeight + keyboardOverlap`; bar height now tracks wrapped draft / attachments - - Keyboard frame handling is synchronous on the posting thread (no `receive(on:)` hop) so swipe-to-reply keeps the bar locked to the keyboard animation; `presentQuickReplyInput()` commits bar geometry before `becomeFirstResponder()` -6. Residual SwiftUI cleanup + docs — **in progress / progressive** -7. Topic detail interaction polish — **done** - - Shared press bounce: `UIControl.fireBindPressBounce` / `ASButtonNode.fireBindPressBounce` (`.button` / `.compact` / `.chip`) used on login, send, submit, empty-state, composer, feed chips, reactions, polls, etc. - - Reaction chips: press bounce + optimistic local update with network rollback on failure; chips stay tappable while request is in-flight - - Topic detail nav bar uses **opaque** canvas chrome so light-mode image content cannot bleed through as a black bar - - Topic detail toolbar chrome: no generic `话题` title; real topic title pins centered after the in-feed header title scrolls away; trailing actions collapse inline into `...` once on first pin (teaching affordance), then stay compact + title stays pinned unless the user expands manually; manual expand auto-collapses after idle (`FireTopicDetailToolbarCoordinator`); titleView claims expanded/leftover width only (never content-sized), so long titles truncate instead of shoving the trailing icon capsule off-screen - - Boost chips align with Fluxdo: compact continuous pills with leading **avatar + plain body only** (no bolt glyph, no `@username` text prefix); body still strips leading attribution from Rust `displayText` - - Author metadata aligns with Fluxdo post header: primary line keeps staff role chips only; secondary line is `@username` + humanized `user_title` (e.g. `trust_lv_3` → `L3 活跃用户`) + status; primary group / flair names are not dumped as raw text chips - - Topic-detail post density: tighter header/meta spacing; reply context (`回复 @user`) sits on the username row; `@handle`/title stay on the secondary row; reply-thread bubble toggle uses accent orange for both icon and count when expanded; OP has no cell overflow `...` (nav toolbar owns topic actions); reply bottom chrome keeps bubble + reactions + overflow `...` (toolbar-aligned horizontal fade expand, auto-collapse); reaction pills are compact (12pt emoji / 11pt count, 5pt gutters, 5pt wrap line gap; idle = clear/hairline, mine = soft accent; dark uses faint glass fill); left-swipe reveals reply - - Collapsed post body: blank-line runs (`\n\n`) are normalized before ASTextNode truncation so empty lines no longer burn the 4-line budget / look like huge row gaps; collapsed height is measured with the same ASTextNode max-lines path -8. Topic detail Texture **color appearance** hardening — **done** - - Root cause: `ASTextNode` async display can resolve dynamic `UIColor.label` / `uiCanvas` against the wrong `userInterfaceStyle` (often light), baking near-black glyphs onto the pure-black dark canvas — body and primary username disappear while mid-gray `@handle` / titles remain faintly visible. Runtime theme switch previously only flipped `window.overrideUserInterfaceStyle` + global chrome; post cells / render-bound attributed strings were not re-baked. - - Fix: rich text + post meta use `FireTheme.uiInk` / `uiSubtleInk` (not bare system labels); `FireTextureAttributedText` resolves dynamic colors with an explicitly captured trait collection before binding to Texture; `FirePostCellRenderPayload.colorTraits` is captured on the main thread in the feed node-block; body/username ASTextNodes prefer sync display; `didEnterVisibleState` re-bakes from live hierarchy traits. - - Appearance bus: `FireTopicDetailViewController` listens for `fireAppearancePreferenceDidChange` and `traitCollectionDidChange` → `feedController.refreshColorAppearance()` (visible post cells soft rebind + `reloadData` for one-shot factory nodes) and refreshes nav / quick-reply chrome. - - Follow-up (light-theme + images): color rebind must **not** clear `contentSegmentSignature` / rebuild `FirePostImageNode` mid-load (blank image placeholders); factory chrome text (`回复`/`浏览`/`互动` stats, replies header, title) sets `isOpaque = false` + clear background so Texture's default opaque fill does not leave pure-black bars on light paper; stats/header cells bake resolved canvas; image nodes prefer sync display and bake status ink. - - Appearance environment (complete): `FireAppearanceEnvironment.applyPreference` / `syncFromStorage` own window + publish; `FireAppearanceSnapshot` is the Texture bake bag; topic-detail payload carries `appearance` (token soft-rebind); shell re-asserts on bus / PTR / snapshot apply; settings + topic detail implement `FireAppearanceApplying`. - - Tests: `FireTextureAttributedTextTests` + `FireAppearanceEnvironmentTests` cover tokens, luminance, OLED, snapshot equality, and attributed resolve. - -### Residual SwiftUI (allowed) - -- Widgets extension -- Developer tools -- Secondary profile destinations still pushed as hosts: badges, LDC/CDK, invites, activity timeline, settings -- Follow / followers lists are UIKit (`FireFollowListViewController`); residual SwiftUI only hosts that controller -- Temporary composer/editor sheets -- Category browser sheet shell (filtered list content is UIKit) — scheduled to be replaced by the UIKit home scope panel in `docs/architecture/2026-07-26-home-feed-filter-chrome-design.md` - -### Next polish target - -- Home feed filter chrome redesign: **iOS revised** — leading parent-category drawer + home status bar; category arrow opens subcategory sheet when children exist (`FireHomeCategoryDrawerController` / `FireHomeSubcategoryPanelController`). Remaining: recent parents, Android parity. Design: `docs/architecture/2026-07-26-home-feed-filter-chrome-design.md`. - -## Explicit non-goals - -- Full SwiftUI rewrite or full Texture rewrite of all lists -- Cross-platform pixel animation parity with Android -- MJRefresh-class pull-to-refresh libraries -- Custom navigation transition engines when system interactive pop is sufficient diff --git a/docs/architecture/2026-07-25-main-thread-and-threading-audit.md b/docs/architecture/2026-07-25-main-thread-and-threading-audit.md deleted file mode 100644 index acf4e4e7..00000000 --- a/docs/architecture/2026-07-25-main-thread-and-threading-audit.md +++ /dev/null @@ -1,102 +0,0 @@ -# Main-thread / background threading audit (iOS) - -Date: 2026-07-25 -Scope: Fire iOS host (`apps/ios-app`), with Rust/UniFFI ownership notes. - -## Goal - -- Main thread: UI only (view hierarchy, gesture, Texture layout application, snapshot apply). -- Background: parsing, measurement, merge/dedup, render-cache build, FFI-adjacent transforms. -- Rust: protocol orchestration, tree presentation, list models, session authority — keep expanding this surface instead of growing Swift business logic. - -## Already in good shape - -| Area | Pattern | -|------|---------| -| Topic cooked → render cache | `FireTopicPresentation.detailRenderCache` via `Task.detached` in `FireTopicDetailStore` | -| Post cell layout height | `FirePostLayoutManager` background queue + main publication | -| Topic detail feed snapshot items | `FireTopicDetailSnapshotAssembler.buildSnapshot` in `Task.detached` from VC | -| Topic tree / page fetch | Rust `fetchTopicDetailPage` returns `sourceSnapshot` + `treePresentation` | -| Home topic rows | Mostly Rust-generated row models; host formats timestamps | -| UniFFI session/network | `async` boundary; not blocking UI runloop with sync FFI | -| Texture node-block UIKit | Hardened 2026-07-25: no `.view`/layer in off-main configure | - -## Residual main-thread work (by severity) - -### P1 — completed / remaining - -1. **`FireTopicDetailStore` page apply** ✅ - `prepareTopicDetailPagePayload` runs tree dedupe + detail synthesis + post lookup in `Task.detached`; main only commits maps and kicks render. - -2. **Cooked display-segment IR** ✅ (2026-07-25 follow-up) - Rust `fire_rich_text::present_document` owns image/text/onebox segment splitting. Hosts lift `RenderDocumentHandle.segment(i)` only. - Swift deleted `rawRenderSegments` / container walk; host only maps rich mini-docs → `NSAttributedString` and images → cells. - Checksum no longer uses `String(reflecting:)`. - -3. **Home feed dirty-row token rebuild** ✅ - `FireHomeFeedStore.prepareTopicRowsMerge` snapshots indexes then merges + rebuilds content tokens in `Task.detached`. - Main only assigns `topicRows` / tokens / visibility. Single-row `patchTopicCounts` stays sync (cheap). - -### P2 — acceptable on main for now - -| Area | Why OK | -|------|--------| -| Diffable / Texture snapshot apply | Must be main; keep diffs small via content tokens | -| Captcha sheet detent animation | UIKit sheet API is main-only; height measure is JS → main debounced | -| Quick-reply / toolbar chrome | Thin UIKit | -| Login form / onboarding | UI-bound | -| Keychain credential load | Short; already in async prepareLoginForm | - -### P3 — watch / measure - -- `FireDiffableListController` large `reconfigureItems` batches during scroll idle. -- Message-bus fan-in onto MainActor stores (debounce already present for some paths). -- Image decode is generally off main; keep UIImage assignment on main only. - -## Threading rules (host) - -1. **Texture `nodeBlock` / `configure`:** node properties only. Any `UIView` / `CALayer` / gesture attach → `didLoad` or `performOnMain`. -2. **Never** `DispatchQueue.main.sync` from Texture workers (deadlock risk). -3. **Pure transforms** (`unique*`, merge posts, synthesize detail, render cache) → `nonisolated` / `Task.detached` / dedicated queue. -4. **Rust owns** pagination cursors, tree presentation, missing-post windows, session classification — do not reimplement in Swift “for convenience”. -5. **Main actor stores** may *orchestrate* async work but should not *compute* large collections inline. - -## Concrete changes - -### Pass 1 -- `FireTopicDetailStore.applyTopicDetailPagePayload` off-main prepare. - -### Pass 2 -- **Home feed:** `mergeTopicRows` + content-token rebuild are `nonisolated static`; list load/apply paths await `prepareTopicRowsMerge` on a detached task. -- **Cooked IR:** Rust `RenderDisplaySegment` + `display_segments`; UniFFI export; Swift presentation uses it and drops the old segment walker. -- **Sendable indexes:** `FireEntityIndex` / `FireOrderedIDList` require `Sendable` entity/id. - -## Suggested follow-ups (ordered) - -1. Instrument detached prepare ms vs main commit ms for topic detail + home feed. -2. Split remaining `FireTopicDetailStore` pure helpers into a Sendable reducer module. -3. Further thin Swift attributed-string builder once Android shares the same display-segment IR. -4. Optional: main-thread hang detector in DEBUG (os_signpost / MetricKit) behind developer tools. - -## Related fixes (same day) - -- Off-main UIKit in `FirePostCellNode` (hang root cause during topic open). -- Captcha sheet height debounce / phase-1 hide on challenge open. -- Login loading: button spinner only (no dim overlay). - -## Follow-up: Texture color appearance (dark-mode body/username) - -- Dynamic colors bound into `ASTextNode` must not rely on the Texture display-queue trait environment. -- Capture `UITraitCollection` on the main thread (loaded collection view / window override) and bake with `FireTextureAttributedText.resolvingDynamicColors`. -- Theme preference changes must call a host refresh path (`refreshColorAppearance`); updating only `window.overrideUserInterfaceStyle` is insufficient for Texture bitmaps. -- Keep pure transforms (render-cache HTML → attributed string) off-main; resolve-for-Texture stays at bind time on the UI path. -- Color rebind is soft: never tear down inline image nodes solely for palette changes; only re-bake text / action chrome when the appearance token flips. -- Factory `ASTextNode`s used for topic chrome (stats, replies header, title) must set `isOpaque = false` and clear backgrounds — Texture's opaque default paints pure black and shows as black bars after light-theme switch. - -### Appearance Environment (complete) - -- **`FireAppearanceEnvironment`** owns preference apply (`applyPreference` / `syncFromStorage`): UserDefaults, `window.overrideUserInterfaceStyle`, global UIKit chrome, snapshot publish (`snapshotPublisher` + `.fireAppearancePreferenceDidChange`). -- **`FireAppearanceSnapshot`**: resolved canvas/ink/accent/divider + stable `token` (`light` / `dark` / `oled`). -- Contract: UIKit may use dynamic `FireTheme.ui*`; Texture/`ASDisplayNode` must paint snapshot colors via `FireAppearanceTexture`. -- Topic detail: `FirePostCellRenderPayload.appearance` is the bake bag; factory cells take `appearance:`; shell re-asserts on theme bus, snapshot apply, and pull-to-refresh. -- Conformers: `FireTopicDetailViewController`, `FireSettingsViewController` (`FireAppearanceApplying`). diff --git a/docs/architecture/2026-07-26-home-feed-filter-chrome-design.md b/docs/architecture/2026-07-26-home-feed-filter-chrome-design.md deleted file mode 100644 index 83237206..00000000 --- a/docs/architecture/2026-07-26-home-feed-filter-chrome-design.md +++ /dev/null @@ -1,477 +0,0 @@ -# Home Feed Filter Chrome Design - -Date: 2026-07-26 -Status: iOS revised — leading parent drawer + home category-arrow subcategory sheet; Android parity pending -Scope: iOS home first; Android should share the same state model and panel IA - -## Problem - -Current home chrome stacks three always-visible filter rows: - -1. parent-category chips (`全部 / 未分类 / 开发调优 / …`) -2. list-kind chips (`最新 / 最新发布 / 未读 / 未看 / 热门 / 精华`) -3. tag entry (`+ 标签`) - -User feedback and the current UI both point at the same gaps: - -- too much vertical chrome before the first topic -- parent categories are hard to scan in a long horizontal strip -- subcategories are effectively second-class (sheet + `Menu`) -- category / kind / tag compete at equal visual weight even though they are different jobs - -## Goals - -1. Make “what am I browsing?” readable in one glance. -2. Make parent + child category selection first-class. -3. Keep list content as the primary surface. -4. Reuse the existing home scope pipeline (`kind + categoryId + tags`) instead of inventing a parallel filter path. -5. Keep one authoritative interaction model on iOS and Android. - -## Non-goals - -- Left-edge drawer as the iOS primary entry -- Multi-category multi-select -- Replacing Discourse list kinds -- Pixel-matching web or Fluxdo -- Building a second filtered-list stack beside `FireHomeFeedStore` - -## Design summary - -> Leading drawer picks parent category / 全部 only. -> Home status bar shows current scope; category arrow opens subcategory sheet when children exist. -> Kind stays a lightweight menu on the status bar. - -```text -Before After ------- ----- -[cat chips............] [ 开发调优 / Rust ▾ ] [最新 ▾] [#tag ×] -[kind chips...........] [ 全部 | Rust | 前端 | 更多 ] // only when parent has children -[+ 标签] [ topic rows ... ] -[topic rows...] -``` - -## Information architecture - -| Layer | Surface | Role | -|---|---|---| -| L0 | Scope status bar | Always visible current category path, kind, selected tags | -| L1 | Subcategory shortcut strip | Only when selected parent has children | -| L2 | Scope panel | Full parent list + children + search + tags | -| L3 | Kind menu | Lightweight menu from the kind capsule | - -### Why not a left drawer as default - -A left drawer is a reasonable container for parent categories, but: - -- iOS edge gestures fight interactive pop / system back affordances -- discovery is weaker than an explicit status capsule -- it encourages platform-split shells - -Preferred container: - -- **iOS:** sheet / half-screen panel from the category capsule -- **Android:** same panel IA; optional navigation-drawer shell later, same view-model - -## Wireframes - -### 1) Default home - -```text -┌──────────────────────────────────────┐ -│ 首页 ✎ 🔍 │ -├──────────────────────────────────────┤ -│ [ 全部 ▾ ] [ 最新 ▾ ] │ ← L0 status bar -├──────────────────────────────────────┤ -│ topic │ -│ topic │ -│ topic │ -└──────────────────────────────────────┘ -``` - -Notes: - -- no subcategory strip -- no tag row -- kind is secondary, not a full chip runway - -### 2) Parent selected, has children - -```text -┌──────────────────────────────────────┐ -│ 首页 ✎ 🔍 │ -├──────────────────────────────────────┤ -│ [ 开发调优 ▾ ] [ 最新 ▾ ] │ -│ [全部] [Rust] [前端] [求职] [更多] │ ← L1 shortcut strip -├──────────────────────────────────────┤ -│ topic │ -└──────────────────────────────────────┘ -``` - -Rules: - -- `全部` means the parent category itself -- selecting a child updates the status capsule to `开发调优 / Rust` -- `更多` opens the full panel focused on that parent - -### 3) Child + tags selected - -```text -┌──────────────────────────────────────┐ -│ [ 开发调优 / Rust ▾ ] [最新▾] [#rust×]│ -│ [全部] [Rust✓] [前端] [求职] [更多] │ -├──────────────────────────────────────┤ -│ topic │ -└──────────────────────────────────────┘ -``` - -Rules: - -- selected tags appear only when non-empty -- tag chip delete removes one tag -- long-press / trailing clear on category capsule clears category path (and optionally tags) - -### 4) Scope panel (L2) - -```text -┌──────────────────────────────────────┐ -│ 选择范围 完成 │ -│ [ 搜索分类或标签... ] │ -├──────────────┬───────────────────────┤ -│ 全部 │ 开发调优 │ -│ 未分类 │ ----------------------│ -│ 开发调优 ✓ │ ○ 全部 开发调优 │ -│ 国产替代 │ ● Rust │ -│ 资源聚合 │ ○ 前端 │ -│ 运营反馈 │ ○ 求职 │ -│ ... │ │ -│ │ 热门标签 │ -│ │ #rust #swift #ai │ -└──────────────┴───────────────────────┘ -``` - -Interaction: - -1. Left pane lists parents + synthetic `全部` -2. Right pane lists: - - parent-as-all row - - children of the highlighted parent - - optional hot tags for the current scope -3. Search filters parents/children/tags in one list -4. Selection applies immediately and refreshes home scope -5. Panel may auto-dismiss on category pick; tag toggles can keep it open - -### 5) Kind menu - -```text -[最新 ▾] - • 最新 - 最新发布 - 未读 - 未看 - 热门 - 精华 -``` - -Keep current `TopicListKindState.orderedCases`; only change presentation. - -## State model - -### Existing store fields to keep - -From `FireHomeFeedStore`: - -```text -selectedTopicKind: TopicListKindState -selectedHomeCategoryId: UInt64? -selectedHomeTags: [String] -allCategories: [FireTopicCategoryPresentation] -topTags: [String] -``` - -Existing query assembly already supports child categories via: - -- `categoryId` -- `categorySlug` -- `parentCategorySlug` derived from `parentCategoryId` - -So **subcategory filtering is mostly a UI/IA gap**, not a backend-protocol gap. - -### Presentation model to add (UI-facing, derived) - -```swift -struct FireHomeScopePresentation: Equatable { - var kind: TopicListKindState - var categoryID: UInt64? - var tags: [String] - - /// `nil` = 全部 - var selectedCategory: FireTopicCategoryPresentation? - /// If selected is a child, this is its parent; if selected is parent, equal to selected. - var selectedParent: FireTopicCategoryPresentation? - var selectedChild: FireTopicCategoryPresentation? - var categoryPathTitle: String // "全部" | "开发调优" | "开发调优 / Rust" - var kindTitle: String // localized kind label - var childShortcuts: [FireHomeChildShortcut] - var showsChildShortcutStrip: Bool -} - -struct FireHomeChildShortcut: Equatable, Identifiable { - var id: UInt64? // nil = parent-all - var title: String - var isSelected: Bool -} -``` - -Derivation rules: - -```text -selectedHomeCategoryId == nil - -> path "全部" - -> no child strip - -selected is parent P - -> path P.name - -> child strip = [全部(P), ...children(P)] if children non-empty - -> selected shortcut = 全部(P) - -selected is child C of parent P - -> path "P.name / C.name" - -> child strip for P - -> selected shortcut = C -``` - -### Panel view state - -```swift -struct FireHomeScopePanelState: Equatable { - var searchText: String - var highlightedParentID: UInt64? // left-pane highlight; nil = 全部 - var selectedCategoryID: UInt64? // committed home scope - var selectedTags: [String] - var recentParentIDs: [UInt64] // local-only, max ~6 -} -``` - -Notes: - -- `highlightedParentID` can differ from committed selection while browsing the panel -- committing still goes through store methods, not a second source of truth - -### Store API shape - -Keep mutations centralized on `FireHomeFeedStore`: - -```text -selectTopicKind(kind) -selectHomeCategory(categoryId) -addHomeTag / removeHomeTag / clearHomeTags -``` - -Add thin helpers (no new network concepts): - -```text -clearHomeCategory() // select nil -selectHomeParent(parentId) // select parent id -selectHomeChild(childId) // select child id -clearHomeScopeFilters() // category nil + tags [] -scopePresentation() -> FireHomeScopePresentation -children(of parentId) -> [Category] -parents() -> [Category] -``` - -Optional local persistence later: - -```text -recentParentCategoryIDs: [UInt64] // UserDefaults / app prefs -``` - -Do **not** move kind/category/tags ownership into the view controller. - -## UI composition - -### iOS - -Replace in `FireHomeView` / home collection header: - -| Remove / demote | Replacement | -|---|---| -| `FireHomeCategoryTabsCell` always-on runway | `FireHomeScopeStatusBar` | -| `FireHomeFeedSelectorCell` full chip row | kind capsule + menu | -| always-on `FireHomeTagChipsCell` | selected-tag chips in status bar; picker inside panel | -| `FireCategoryBrowserSheet` grid + menu | `FireHomeScopePanelController` dual-pane | - -Suggested ownership: - -```text -FireHomeViewController - ├─ FireHomeScopeStatusBarView // L0 - ├─ FireHomeChildShortcutBarView // L1 conditional - ├─ topic list... - └─ presents FireHomeScopePanelController -``` - -Implementation preference: - -- pure UIKit for status/shortcut/panel (home is already UIKit-first) -- retire SwiftUI category browser shell for this path once panel lands -- one authoritative panel path; no SwiftUI fallback - -### Android - -Mirror the same L0/L1/L2 model with Jetpack UI, sharing labels and selection rules. -A drawer shell is optional and must bind the same scope state. - -## Behavior details - -### Selection - -- Choosing a category commits immediately and triggers existing debounced refresh (`scheduleDebouncedRefresh`) -- Choosing a category currently clears tags (`selectHomeCategory` already does this) — **keep** that unless product later wants sticky tags -- Kind changes do not clear category/tags -- Tag add/remove keep category - -### Status bar - -- Category capsule opens scope panel -- Kind capsule opens kind menu -- Tag chips are removable -- If filters are non-default, show a subtle clear affordance - -### Child shortcut strip - -- Appears only when committed parent has children -- Horizontal, compact, single line -- Does not replace the panel for deep browsing - -### Search in panel - -Priority match order: - -1. parent title -2. child title -3. tag - -Empty search shows hierarchy; non-empty search shows flat grouped results. - -### Empty / error - -Reuse current home empty/error surfaces. -When scope is narrow and empty, CTA options: - -- 查看大类全部 -- 清除筛选 - -### Accessibility - -- category color is decoration only -- selected rows expose traits / checkmarks -- status capsules need labels like `分类:开发调优 / Rust`、`排序:最新` -- child strip is a selectable tab-like control group - -## Mapping to current code - -### Already good - -| Piece | Location | Notes | -|---|---|---| -| scope fields | `FireHomeFeedStore` | kind/category/tags already authoritative | -| rust home scope sync | `setCurrentHomeTopicListScope` | keep | -| child category query | `parentCategorySlug` derivation in `loadTopics` | already works if child id selected | -| category metadata | bootstrap `allCategories` + `parentCategoryId` | enough for dual-pane | -| kind enum | `TopicListKindState` | reuse labels | - -### Needs UI rewrite - -| Piece | Change | -|---|---| -| `FireHomeCategoryTabsCell` | replace with status bar + optional child strip | -| `FireHomeFeedSelectorCell` | demote to menu | -| `FireHomeTagChipsCell` | only selected tags / move picker into panel | -| `FireCategoryBrowserSheet` | replace with dual-pane panel | -| home snapshot sections | drop always-on 3 filter sections; add status/shortcut items | - -### Needs small store/presentation additions - -| Piece | Change | -|---|---| -| `FireHomeScopePresentation` | pure derivation helper | -| recent parents | optional local prefs | -| clear helpers | convenience wrappers over existing selects | - -### Likely unchanged - -- `TopicListQueryState` shape -- MessageBus incremental refresh rules -- topic row rendering -- composer initial category/tags handoff from current scope - -## Implementation plan - -### P0 — structure and subcategory parity - -1. [x] Add `FireHomeScopePresentation` derivation + unit tests. -2. [x] Build `FireHomeScopeStatusBarCell` and wire kind menu. -3. [x] Build `FireHomeScopePanelController` dual-pane with parent/child selection. -4. [x] Remove always-visible category/kind/tag chip runways from home snapshot. -5. [x] Ensure selecting a child category uses existing `selectHomeCategory(childId)` path end-to-end. -6. [x] Update iOS README + this doc status when landed. -7. [x] Conditional child shortcut strip (pulled forward from P1 for usable subcategory access). - -### P1 — shortcuts and polish - -1. Child shortcut strip after parent selection. -2. Selected tag chips in status bar. -3. Panel search. -4. Clear-scope affordance + empty-scope CTAs. -5. Recent parent ordering. - -### P2 — platform parity / optional shells - -1. Android same IA. -2. Optional Android drawer container around the same panel state. -3. Only if needed: iOS navbar `line.3.horizontal` opens the **same** panel (not a second hierarchy). - -## Test plan - -### Unit - -- path title: - - nil -> `全部` - - parent -> parent name - - child -> `parent / child` -- child shortcuts: - - none when no children - - includes parent-all + children - - selected states -- query regression: - - child selection still produces `categoryId=child` + `parentCategorySlug=parent` - -### UI / manual - -1. Default home shows one status row only. -2. Open panel, select parent with children, strip appears. -3. Select child from strip and from panel; both same result. -4. Long category names truncate in capsule; panel shows full names. -5. Kind menu changes only kind. -6. Tags selectable from panel; removable from status bar. -7. Changing category clears tags (current behavior). -8. Dynamic type / small phone: status bar wraps or compresses without covering topic rows incorrectly. - -## Open product choices - -Defaults below are recommended if not overridden: - -1. **Panel dismiss:** auto-dismiss on category commit; stay open for tag toggles. -2. **Sticky tags across category changes:** no. -3. **Remember last scope across launches:** yes for kind + category; tags optional later. -4. **Synthetic “未分类”:** keep if bootstrap/API already exposes it as a real category; do not special-case a fake chip runway. - -## Decision - -Accepted direction: - -- **No iOS-primary left drawer** -- **Yes dual-pane category panel** -- **Yes single status bar as the standing chrome** -- **Yes conditional subcategory shortcuts** -- **Reuse `FireHomeFeedStore` scope, do not fork feed filtering** diff --git a/docs/architecture/2026-08-09-chat-tab-design.md b/docs/architecture/2026-08-09-chat-tab-design.md deleted file mode 100644 index 3364a1b3..00000000 --- a/docs/architecture/2026-08-09-chat-tab-design.md +++ /dev/null @@ -1,56 +0,0 @@ -# Chat Tab(Discourse Chat)落地说明 - -日期:2026-08-09 -状态:已实现(REST 首版) - -## 范围 - -在 iOS / Android 主壳新增 **聊天** tab,对接 Discourse Chat 插件(不是论坛私信 topic 列表)。 - -| 层 | 路径 | -|----|------| -| 协议知识 | `docs/knowledge/api/15-chat.md` | -| 模型 | `fire-models::chat` | -| Core | `fire-core::core::chat` + `chat_payloads` | -| UniFFI | `fire-uniffi-chat` → `FireAppCore.chat()` | -| iOS | `App/Views/Chat/*` + tab shell 第 3 项 | -| Android | `ui/chat/*` + bottom nav `chatFragment` | - -## 产品行为 - -1. 频道列表:私信与公共频道合并为一条 inbox(按最近消息时间),不再分段 -2. 未读徽章:DM = unread+mention;公共 = 仅 mention;muted 不计 -3. 进入会话:拉消息(`fetch_from_last_read`)、发送、上报已读。iOS 会话页通过 `FireRootCoordinator.presentSecondary` 盖住 tab shell(与贴文详情同一套全屏二级栈,根页可右滑关掉);Android 会话本来就是独立 `ChatChannelActivity` -4. 新建 DM:`POST /chat/api/direct-message-channels`(1:1 默认 upsert) -5. 滑动操作:标记已读、退出会话(iOS) - -## UI 风格 - -| 区域 | 风格 | 说明 | -|------|------|------| -| 消息流 | Discord 频道日志 | 左头像 + 用户名/时间 + 全文正文;同作者连续消息折叠头像/标题;时间升序、新消息靠底 | -| 输入条 | 微信底栏 | 全宽不透明条、顶部分割线、胶囊输入框(自动换行、最高 5 行)、左侧附件、右侧圆形发送、粘贴图片进附件条、`@` 补全 | -| 正文 | cooked 富文本 | Rust `RenderDocumentHandle` → 平台 RichText builder(链接/代码/emoji/图片) | -| 头像 | 统一图片管线 | iOS `FireTopicListAvatarView` + Nuke;Android `FireAvatarUrls` + Coil `FireImageLoader` | -| 用户卡片 | 紧凑 sheet | 点击消息头像/用户名弹出共享 `FireUserCard` / `FireUserCardSheet`:约 292pt 高度、横排小按钮(主页 / 私信 / 聊天),不是半屏大按钮栈。贴文详情头像/显示名走同一张卡片;Texture 帖子行在 cell 自身上识别头像/`meta` 命中(与左滑回复同一层),不把点击挂在子节点 `ASControlNode` 上 | - -iOS:`FireChatMessageCell`(`FireRichTextUIView` + `FireTopicListAvatarView`)+ `FireBottomInputBar`(InputBarAccessoryView,微信底栏:换行长高、附件条、粘贴图、`@` 补全)。键盘仍由会话页 bottom constraint 跟踪,不用库的 `KeyboardManager`。 -Android:`item_chat_message` body container(`FireRichTextView`)+ 底栏。 - -## 实时与增强(已实现) - - -- **MessageBus**:`MessageBusEventKind::Chat`;列表订阅 `/chat/new-channel`、`/chat/user-tracking-state/{userId}`、逐频道 `/chat/{id}/new-messages`;会话订阅 `/chat/{id}` 或 `/chat/{id}/thread/{tid}`。消息/频道 envelope 由 Rust `chat_message_from_bus_payload` / `chat_channel_from_bus_payload` 解析并带上 `presentation`,宿主不再从 bus JSON 拼 cooked 正文。 -- **Thread**:`create_chat_thread` / `fetch_chat_thread_messages` / `mark_chat_thread_read` + 原生线程页 -- **置顶**:pins 列表、pin/unpin、顶栏 banner -- **表情回应**:消息操作面板(heart/tada/laughing/+1/eyes) -- **图片直发**:相册选择 → 既有 `uploadImage` → `send` with `upload_ids` - -## 验证 - -```bash -cargo fmt --all --check -cargo clippy --keep-going -p fire-models -p fire-core -p fire-uniffi --all-targets --no-deps -- -D warnings -cargo test -p fire-models -p fire-core -p fire-uniffi --all-targets -xcodegen generate --spec apps/ios-app/project.yml -``` diff --git a/docs/architecture/2026-08-22-ios-button-press-motion-research.md b/docs/architecture/2026-08-22-ios-button-press-motion-research.md deleted file mode 100644 index 6134eda2..00000000 --- a/docs/architecture/2026-08-22-ios-button-press-motion-research.md +++ /dev/null @@ -1,81 +0,0 @@ -# iOS Button Press Motion Research - -Date: 2026-08-22 - -Scope: open-source iOS implementations and official Apple API docs only. The goal is to extract concrete values for press scale, release behavior, spring timing, damping, and the separation between press-down and release/overshoot. - -## Source Findings - -### Apple API Baselines - -- SwiftUI `Animation.interactiveSpring(response:dampingFraction:blendDuration:)` defaults to `response: 0.15`, `dampingFraction: 0.86`, `blendDuration: 0.25`, and Apple describes it as a spring with lower response intended for interactive animations. Source: [Apple Developer Documentation](https://developer.apple.com/documentation/swiftui/animation/interactivespring%28response%3Adampingfraction%3Ablendduration%3A%29). -- SwiftUI `Animation.spring(response:dampingFraction:blendDuration:)` defaults to `response: 0.5`, `dampingFraction: 0.825`, `blendDuration: 0`, preserves velocity when successive spring animations replace one another, and treats response as approximate stiffness/duration. Source: [Apple Developer Documentation](https://developer.apple.com/documentation/swiftui/animation/spring%28response%3Adampingfraction%3Ablendduration%3A%29). -- SwiftUI `Animation.default` is currently a spring with `response: 0.55`, `dampingFraction: 1.0`, `blendDuration: 0.0`; Apple notes older OS releases used ease-in-out. Source: [Apple Developer Documentation](https://developer.apple.com/documentation/swiftui/animation/default). -- UIKit `UIView.animate(... usingSpringWithDamping:initialSpringVelocity:)` defines damping ratio `1` as smooth/no oscillation, with values closer to `0` increasing oscillation; initial velocity is normalized to the animation distance per second. Source: [Apple Developer Documentation](https://developer.apple.com/documentation/uikit/uiview/animate%28withduration%3Adelay%3Ausingspringwithdamping%3Ainitialspringvelocity%3Aoptions%3Aanimations%3Acompletion%3A%29). - -### nathangitter/fluid-interfaces - -This repo is a UIKit implementation inspired by Apple's WWDC18 "Designing Fluid Interfaces" talk. The README explicitly positions `CalculatorButton.swift` as an iOS Calculator-like button and `FlashlightButton.swift` as an iPhone X lock-screen flashlight-like button. Source: [fluid-interfaces README](https://github.com/nathangitter/fluid-interfaces). - -- `CalculatorButton` does not scale. It reacts on `.touchDown` and `.touchDragEnter` by stopping the previous animator and immediately switching to a highlighted color. It releases on `.touchUpInside`, `.touchDragExit`, and `.touchCancel` with `UIViewPropertyAnimator(duration: 0.5, curve: .easeOut)` back to the normal color. Source: [CalculatorButton.swift](https://github.com/nathangitter/fluid-interfaces/blob/master/FluidInterfaces/FluidInterfaces/CalculatorButton.swift). -- `FlashlightButton` uses direct manipulation while the finger is down: scale is computed from force as `1 + (maxWidth / minWidth - 1) * force` with `minWidth: 50` and `maxWidth: 92`, so full force maps to about `1.84x`. Release calls `animateToRest()` with `UISpringTimingParameters(damping: 0.4, response: 0.2)` and an interruptible `UIViewPropertyAnimator`, targeting `transform = scale(1, 1)`. Source: [FlashlightButton.swift](https://github.com/nathangitter/fluid-interfaces/blob/master/FluidInterfaces/FluidInterfaces/FlashlightButton.swift). -- Its `Spring.swift` demo exposes design-friendly spring parameters: damping range `0.1...1`, response range `0.1...2`, defaults `dampingRatio: 0.5` and `frequencyResponse: 1`. Its helper maps `response` and `damping` to `UISpringTimingParameters(mass: 1, stiffness: (2pi / response)^2, damping: 4pi * damping / response)`. Source: [Spring.swift](https://github.com/nathangitter/fluid-interfaces/blob/master/FluidInterfaces/FluidInterfaces/Spring.swift). - -### aheze/Prism - -Prism's SwiftUI example utilities define reusable button styles with separate press-down and release spring values. - -- `ScalingButtonStyle` defaults to `scale = 0.95`, applies `opacity = 0.95` while pressed, and uses different springs for the two directions: press-down `response: 0.19`, `dampingFraction: 0.45`, `blendDuration: 1`; release `response: 0.4`, `dampingFraction: 0.4`, `blendDuration: 1`. Source: [Utilities.swift](https://github.com/aheze/Prism/blob/main/Example/PrismExample/PrismExample/Utilities.swift). -- `PressedButtonStyle` uses an even faster state update spring when pressed (`response: 0.1`, `dampingFraction: 0.6`, `blendDuration: 1`) and the same slower, bouncier release spring (`response: 0.4`, `dampingFraction: 0.4`, `blendDuration: 1`). Source: [Utilities.swift](https://github.com/aheze/Prism/blob/main/Example/PrismExample/PrismExample/Utilities.swift). - -### hallee/neumorphic-style - -`NeumorphicButtonStyle` is a SwiftUI package style. It changes shadow geometry and only uses a very small scale delta. - -- Pressed scale is `0.99`, not a large shrink. It uses `interactiveSpring` with press `response: 0.24`, release `response: 0.3`, shared `dampingFraction: 0.4`, and `blendDuration: 0.6`. Source: [NeumorphicButtonStyle.swift](https://github.com/hallee/neumorphic-style/blob/master/Sources/NeumorphicStyle/NeumorphicButtonStyle.swift). - -### SagerNet/sing-box-for-apple - -This real SwiftUI iOS app is conservative for bar/button chrome. - -- `BarItemButtonStyle` does not scale. It drops opacity to `0.5` while pressed and animates with `.easeOut(duration: 0.12)`. Source: [MainView.swift](https://github.com/SagerNet/sing-box-for-apple/blob/dev/SFI/MainView.swift). -- The same file uses `.spring(response: 0.35, dampingFraction: 0.8)` for bottom accessory view transitions, not for direct button press. Source: [MainView.swift](https://github.com/SagerNet/sing-box-for-apple/blob/dev/SFI/MainView.swift). - -### Telegram-iOS - -Telegram's Texture/AsyncDisplayKit UI often uses opacity highlight rather than scale for small chrome. - -- `ChatPinnedMessageTitlePanelNode` uses `HighlightTrackingButtonNode`/`HighlightableButtonNode` callbacks. Pressing immediately lowers text/line/button alpha to `0.4`; release restores alpha to `1.0` using `animateAlpha(... duration: 0.2)`. Source: [ChatPinnedMessageTitlePanelNode.swift](https://github.com/TelegramMessenger/Telegram-iOS/blob/master/submodules/TelegramUI/Sources/ChatPinnedMessageTitlePanelNode.swift). - -### Spring Engine References - -These are not button-specific, but they reinforce how iOS-style spring systems structure values for touch-driven interactions. - -- Wave's README uses `Spring(dampingRatio: 0.68, response: 0.80)` for a gesture release and passes gesture lift-off velocity into the animation; the example also animates scale to `1.1`. Source: [Wave README](https://github.com/jtrivedi/Wave). -- Motion's README example configures a spring with `response: 0.30`, `damping: 0.64`, and explicit velocity. It also warns not to mix stiffness/damping with response/dampingRatio because they are different parameterizations. Source: [Motion README](https://github.com/b3ll/Motion). -- Pop's README emphasizes retargeting a running `POPSpringAnimation` by updating `toValue`, which is relevant to avoiding stutter when a press/release is interrupted. Source: [Pop README](https://github.com/facebookarchive/pop). - -## Strongest Patterns - -1. Press-down and release should be separate phases. Real implementations either make press-down immediate (`fluid-interfaces` Calculator, Telegram opacity) or use a faster press spring than release (`Prism`, `neumorphic-style`). A single release-style spring for both directions is likely to feel laggy or wobbly on press-down. - -2. Everyday iOS buttons use subtle scale. The strongest concrete scale cluster is `0.95...0.99` for standard SwiftUI button styles. `0.90` or lower appears in examples/gists or highly tactile controls, but not in the stronger iOS app/library references for ordinary buttons. - -3. Overshoot is usually implicit spring overshoot, not an explicit `1 -> 0.8 -> 1.2 -> 1` keyframe for normal buttons. Under-damped release springs (`dampingFraction`/damping ratio below `1`) can create small overshoot while still targeting identity. Explicit large scale-up belongs to playful/momentum/force interactions, not normal list/card/button taps. - -4. Typical press timing is fast: `response` around `0.10...0.24` or `duration` around `0.10...0.20s`. Apple's `interactiveSpring` default response is `0.15`, Prism uses `0.19`, NeumorphicStyle uses `0.24`, and sing-box uses an opacity-only `0.12s` ease-out. - -5. Typical release timing is slower and smoother: `response` around `0.30...0.40` for reusable button styles, or UIKit `duration` around `0.5s` for color-only Calculator-style release. Damping commonly sits below critical damping (`0.4...0.86`) when bounce is desired, but `1.0` is the no-oscillation baseline. - -6. Direct manipulation should be interruptible and retargetable. `UIViewPropertyAnimator.isInterruptible = true`, Wave's retargetable animations, Pop's running-animation `toValue` update, and Apple's spring replacement behavior all point to avoiding queued multi-stage animations that cannot absorb a quick second tap or drag-cancel. - -7. Opacity-only is a valid native-feeling answer for dense chrome. Telegram and sing-box both avoid scale in compact controls and use immediate/short opacity transitions. Scale should probably be reserved for larger, isolated, touch-forward controls in Fire, not applied uniformly to every tappable view. - -## Candidate Parameter Ranges For Fire - -These are inferred from the sources above; they are not yet a product-code decision. - -- Standard button/card tap: press target `0.95...0.97`; press spring `response: 0.12...0.18`, `dampingFraction: 0.75...1.0`; release spring `response: 0.28...0.36`, `dampingFraction: 0.70...0.85`. -- Compact icon/chip tap: press target `0.92...0.96` only if the element has enough visual mass; otherwise prefer opacity `0.45...0.65` with `0.12...0.20s` release. -- Playful or high-emphasis control: press target may go lower (`0.90...0.94`) and release damping may go lower (`0.45...0.65`), but explicit overshoot above `1.05` should be rare and tied to a deliberate feature identity. -- Avoid a visible `1.2` overshoot for ordinary buttons. The closest strong source for larger scale is `fluid-interfaces` Flashlight, but that is force-driven direct manipulation with haptics and maps force up to `1.84x`; it is not a normal tap bounce. diff --git a/docs/architecture/2026-08-22-ios-press-tap-motion-apple-research.md b/docs/architecture/2026-08-22-ios-press-tap-motion-apple-research.md deleted file mode 100644 index 61ddedd5..00000000 --- a/docs/architecture/2026-08-22-ios-press-tap-motion-apple-research.md +++ /dev/null @@ -1,128 +0,0 @@ -# iOS Press/Tap Motion: Apple-First Research - -Date: 2026-08-22 -Scope: Apple primary sources only. Third-party libraries and non-Apple commentary are intentionally excluded. -Purpose: guide Fire's iOS button/chip press feedback tuning without inventing undocumented Apple defaults. - -## Primary Sources - -- [Apple Human Interface Guidelines: Buttons](https://developer.apple.com/design/human-interface-guidelines/buttons) -- [Apple Human Interface Guidelines: Motion](https://developer.apple.com/design/human-interface-guidelines/motion) -- [Apple Human Interface Guidelines: Gestures](https://developer.apple.com/design/human-interface-guidelines/gestures) -- [Apple Human Interface Guidelines: Feedback](https://developer.apple.com/design/human-interface-guidelines/feedback) -- [Apple Human Interface Guidelines: Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility) -- [WWDC18: Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/) -- [UIKit: UIControl.State.highlighted](https://developer.apple.com/documentation/uikit/uicontrol/state-swift.struct/highlighted) -- [UIKit: UIControl.isHighlighted](https://developer.apple.com/documentation/uikit/uicontrol/ishighlighted) -- [UIKit: UIButton.configurationUpdateHandler](https://developer.apple.com/documentation/uikit/uibutton/configurationupdatehandler-swift.property) -- [SwiftUI: ButtonStyle](https://developer.apple.com/documentation/swiftui/buttonstyle) -- [SwiftUI: ButtonStyleConfiguration](https://developer.apple.com/documentation/swiftui/buttonstyleconfiguration) -- [UIKit: UIView.animate spring API](https://developer.apple.com/documentation/uikit/uiview/animate%28withduration%3Adelay%3Ausingspringwithdamping%3Ainitialspringvelocity%3Aoptions%3Aanimations%3Acompletion%3A%29) -- [UIKit: UIViewPropertyAnimator](https://developer.apple.com/documentation/uikit/uiviewpropertyanimator) -- [UIKit: UIView.AnimationOptions.allowUserInteraction](https://developer.apple.com/documentation/uikit/uiview/animationoptions/allowuserinteraction) -- [UIKit: UIFeedbackGenerator.prepare()](https://developer.apple.com/documentation/uikit/uifeedbackgenerator/prepare%28%29) -- [Apple HIG: Playing haptics](https://developer.apple.com/design/human-interface-guidelines/playing-haptics) - -## What Apple States Directly - -1. Custom buttons need an explicit pressed state. Apple says a custom button without a press state can feel unresponsive, and system buttons provide built-in interaction states. Source: [HIG Buttons](https://developer.apple.com/design/human-interface-guidelines/buttons). - -2. The pressed state should start on touch-down, not after activation. In WWDC18's tap example, Apple describes a button highlighting immediately on touch-down to show the system is reacting, while tap confirmation waits until touch-up. Source: [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/). - -3. A tap must remain cancelable before touch-up. WWDC18 describes extra tap-area margin, dragging outside to cancel, and dragging back in to re-highlight and allow confirmation. Source: [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/). - -4. UIKit already models this lifecycle through `highlighted`. `UIControl.State.highlighted` is entered when a touch enters the control bounds and cleared on touch-up or touch exit; `UIControl.isHighlighted` is automatically set and cleared in response to appropriate touch events. Sources: [UIControl.State.highlighted](https://developer.apple.com/documentation/uikit/uicontrol/state-swift.struct/highlighted), [UIControl.isHighlighted](https://developer.apple.com/documentation/uikit/uicontrol/ishighlighted). - -5. For configured UIKit buttons, Apple exposes `configurationUpdateHandler` specifically to update button configuration when button state changes. Source: [UIButton.configurationUpdateHandler](https://developer.apple.com/documentation/uikit/uibutton/configurationupdatehandler-swift.property). - -6. SwiftUI separates standard button interaction from custom interaction. `ButtonStyle` applies custom appearance while keeping the platform's standard button interaction behavior; `ButtonStyleConfiguration.isPressed` reports the current press state. `PrimitiveButtonStyle` is the path for custom interaction behavior. Sources: [SwiftUI ButtonStyle](https://developer.apple.com/documentation/swiftui/buttonstyle), [SwiftUI ButtonStyleConfiguration](https://developer.apple.com/documentation/swiftui/buttonstyleconfiguration). - -7. Gesture feedback should be immediate and continuous. Apple's gesture guidance says useful gestures provide immediate feedback, and WWDC18 says taps, presses, and every object interaction need to respond instantly. Sources: [HIG Gestures](https://developer.apple.com/design/human-interface-guidelines/gestures), [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/). - -8. Motion for feedback should be brief, precise, purposeful, and unobtrusive. Apple says feedback animation should be brief and precise, and generally discourages adding motion to frequent app interactions because standard components already provide subtle animation. Sources: [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion), [HIG Feedback](https://developer.apple.com/design/human-interface-guidelines/feedback). - -9. Apple favors redirectable/interruption-friendly interactions over fixed call-and-response animations. WWDC18 frames fluid interfaces as behavior that works in concert with the interaction rather than a static timed animation that takes control away until it finishes. `UIViewPropertyAnimator` supports starting, pausing, stopping, reversing, scrubbing, and continuing animations, and has an `isInterruptible` property. Sources: [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/), [UIViewPropertyAnimator](https://developer.apple.com/documentation/uikit/uiviewpropertyanimator). - -10. UIKit's spring API defines useful numeric semantics even though it does not publish standard button scale values. A damping ratio of `1` decelerates without oscillation; damping closer to `0` increases oscillation. Apple also says initial spring velocity should match the view's velocity before attachment, and `1` velocity means the full animation distance per second. Source: [UIView.animate spring API](https://developer.apple.com/documentation/uikit/uiview/animate%28withduration%3Adelay%3Ausingspringwithdamping%3Ainitialspringvelocity%3Aoptions%3Aanimations%3Acompletion%3A%29). - -11. Animations should not block interaction unless blocking is intentional. `UIView.AnimationOptions.allowUserInteraction` exists to allow views to receive interaction during an animation, and HIG Motion says people should be able to cancel motion and should not need to wait for repeated animations to finish. Sources: [UIView.AnimationOptions.allowUserInteraction](https://developer.apple.com/documentation/uikit/uiview/animationoptions/allowuserinteraction), [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion). - -12. Haptics can complement visual press feedback, but need to be coherent and low-latency. Apple says haptics should complement other feedback, match the intensity and sharpness of accompanying animation, and avoid overuse. `UIFeedbackGenerator.prepare()` places the generator in a prepared state for lower-latency feedback when called before the event. Sources: [HIG Playing haptics](https://developer.apple.com/design/human-interface-guidelines/playing-haptics), [UIFeedbackGenerator.prepare()](https://developer.apple.com/documentation/uikit/uifeedbackgenerator/prepare%28%29). - -13. Reduced Motion should tighten this behavior. Apple accessibility guidance says that when Reduce Motion is active, apps should reduce automatic and repetitive animations, including zooming/scaling, and specifically lists tightening animation springs to reduce bounce effects. Sources: [HIG Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility), [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion). - -## What Apple Does Not Publish - -Apple's public HIG, UIKit, and SwiftUI references do not publish a single numeric scale path for a standard iOS button press, such as `1.00 -> 0.95 -> 1.00` or `1.00 -> 0.90 -> 1.03 -> 1.00`. They expose state lifecycles, timing tools, spring semantics, and qualitative motion guidance instead. Sources reviewed: [HIG Buttons](https://developer.apple.com/design/human-interface-guidelines/buttons), [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion), [UIButton.configurationUpdateHandler](https://developer.apple.com/documentation/uikit/uibutton/configurationupdatehandler-swift.property), [SwiftUI ButtonStyle](https://developer.apple.com/documentation/swiftui/buttonstyle), [UIView.animate spring API](https://developer.apple.com/documentation/uikit/uiview/animate%28withduration%3Adelay%3Ausingspringwithdamping%3Ainitialspringvelocity%3Aoptions%3Aanimations%3Acompletion%3A%29). - -## Open-Source Reference Points - -These are not Apple sources; they are included as ecosystem calibration points because Fire also needs a pragmatic implementation choice. - -- [SquishButton](https://github.com/BalestraPatrick/SquishButton) is explicitly modeled after the Clips record button, not a generic app button. Its README exposes `scaling = 10` pixels and `animationDuration = 0.15`, which confirms that strong squash can be appropriate for a special-purpose record affordance but is not evidence for default list chips or toolbar icons. Source: [SquishButton README](https://github.com/BalestraPatrick/SquishButton). - -- [PMSuperButton](https://github.com/pmusolino/PMSuperButton) is a broad `UIButton` subclass with highlighted/selected animations, ripple effects, gradients, loaders, and Interface Builder customization. It is a useful catalog of button affordances, but it is not a narrow press-motion dependency. Source: [PMSuperButton README](https://github.com/pmusolino/PMSuperButton). - -- [DOFavoriteButton](https://github.com/okmr-d/DOFavoriteButton) is a celebratory state-change button, not a generic press feedback layer. Its README exposes a customizable `duration` with default `1.0`, which is appropriate for a favorite/star animation but too long for routine touch-down/touch-up feedback. Source: [DOFavoriteButton README](https://github.com/okmr-d/DOFavoriteButton). - -- Apple’s newer SwiftUI spring presets provide a more relevant baseline for everyday controls than most third-party button libraries. `interactiveSpring(response:dampingFraction:blendDuration:)` defaults to `0.15 / 0.86 / 0.25`, `snappy(duration:extraBounce:)` uses base bounce `0.15`, and `bouncy(duration:extraBounce:)` uses base bounce `0.3`. Sources: [interactiveSpring(response:dampingFraction:blendDuration:)](https://developer.apple.com/documentation/swiftui/animation/interactivespring%28response%3Adampingfraction%3Ablendduration%3A%29), [snappy(duration:extraBounce:)](https://developer.apple.com/documentation/swiftui/animation/snappy%28duration%3Aextrabounce%3A%29), [bouncy(duration:extraBounce:)](https://developer.apple.com/documentation/swiftui/animation/bouncy%28duration%3Aextrabounce%3A%29). - -## Dependency Fit For Fire - -Fire should not pull one of the above libraries in as the implementation path for tap feedback. - -1. Fire needs one shared motion model across UIKit `UIButton`, Texture `ASButtonNode`, and a small SwiftUI surface. The surveyed libraries are mainly `UIButton` subclasses or special-purpose controls, so adopting one would still leave Fire maintaining a second motion system. Sources: [PMSuperButton README](https://github.com/pmusolino/PMSuperButton), [SquishButton README](https://github.com/BalestraPatrick/SquishButton), [DOFavoriteButton README](https://github.com/okmr-d/DOFavoriteButton). - -2. Fire’s architecture already centralizes press motion in `FireMotionUIKit` and `FireMotionEffects`. A small local retune preserves the repository’s “one authoritative implementation path” rule better than introducing a dependency that only covers part of the UI surface. - -3. The best use of these libraries is as reference material: keep Fire’s local shared motion layer, but tune it toward Apple’s lighter interaction springs and away from exaggerated subclass-specific bounce. - -## Fire Design Implications - -1. Treat `highlighted` / `isPressed` as the authoritative press state. Fire's UIKit path should map touch-down/touch-enter to the pressed visual state, touch-exit/cancel to restoration, and touch-up-inside to activation plus release feedback. This follows Apple's control state model and WWDC tap lifecycle. Sources: [UIControl.State.highlighted](https://developer.apple.com/documentation/uikit/uicontrol/state-swift.struct/highlighted), [UIControl.isHighlighted](https://developer.apple.com/documentation/uikit/uicontrol/ishighlighted), [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/). - -2. Avoid a large default press range for common buttons and chips. A `0.80` press scale is a 20% linear shrink and a 36% area shrink, so it is visually dominant. Apple does not forbid this, but HIG Motion's guidance for frequent interactions points toward subtle, brief feedback rather than a large animation people must notice every time. Source: [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion). - -3. Prefer a single spring release to a manually chained bounce sequence for standard controls. Apple spring APIs already support overshoot through damping below `1`, and WWDC18 favors continuous dynamic behavior. A fixed `shrink -> overshoot -> settle` chain is easier to make visibly jerky if interrupted. Sources: [UIView.animate spring API](https://developer.apple.com/documentation/uikit/uiview/animate%28withduration%3Adelay%3Ausingspringwithdamping%3Ainitialspringvelocity%3Aoptions%3Aanimations%3Acompletion%3A%29), [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/), [UIViewPropertyAnimator](https://developer.apple.com/documentation/uikit/uiviewpropertyanimator). - -4. If Fire uses overshoot, make it purposeful and tiered. WWDC18 says bounciness should be purposeful and balanced with utility. That supports reserving stronger bounce for playful or high-salience affordances, while keeping dense list chips, reaction chips, and composer buttons restrained. Source: [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/). - -5. The pressed transition should not be instantaneous if it creates a visible snap. Apple requires immediate response, not necessarily zero-duration transform mutation. A very short touch-down animation can preserve responsiveness while avoiding the "jump" produced by setting transform directly. Sources: [HIG Gestures](https://developer.apple.com/design/human-interface-guidelines/gestures), [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/). - -6. Any Fire press animation should start from the current presentation state and remain interruptible. Users can press, drag out, drag back in, or tap repeatedly; Apple explicitly emphasizes redirection and cancelability. Sources: [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/), [UIViewPropertyAnimator](https://developer.apple.com/documentation/uikit/uiviewpropertyanimator), [UIView.AnimationOptions.allowUserInteraction](https://developer.apple.com/documentation/uikit/uiview/animationoptions/allowuserinteraction). - -7. Reduced Motion should remove or sharply reduce bounce, not merely shorten the same curve. Apple's accessibility guidance calls out zooming/scaling and bounce effects specifically. Sources: [HIG Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility), [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion). - -## Practical Tuning Guardrails - -These are Fire-local implications, not Apple-published defaults. - -- Common controls: use subtle scale deltas and no obvious overshoot by default. This aligns with Apple's guidance for frequent UI interactions to stay lightweight and unobtrusive. Source basis: [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion). - -- Prominent one-shot actions: a modest overshoot can be acceptable if it reinforces completion, but the damping should stay high enough that it does not oscillate. Source basis: [UIView.animate spring API](https://developer.apple.com/documentation/uikit/uiview/animate%28withduration%3Adelay%3Ausingspringwithdamping%3Ainitialspringvelocity%3Aoptions%3Aanimations%3Acompletion%3A%29), [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/). - -- Dense chips and reaction pills: prefer highlight/opacity/material response plus a very small scale change, because they are frequent and sit inside scrollable content. Source basis: [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion), [HIG Gestures](https://developer.apple.com/design/human-interface-guidelines/gestures). - -- Strong `1.00 -> 0.80 -> 1.20 -> 1.00` motion should be considered a special-effect tier, not the default iOS button press style for Fire. Source basis: [HIG Motion](https://developer.apple.com/design/human-interface-guidelines/motion), [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/), [HIG Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility). - -## Fire 2026-08-22 Tuning Choice - -The chosen Fire direction is: - -- animate into the pressed state quickly instead of jumping there instantly -- release with one short spring toward identity instead of a fixed manual `press -> overshoot -> settle` chain -- keep press scales restrained for frequent controls -- reserve stronger bounce for special-purpose affordances, not generic buttons/chips - -That leads to shared scales closer to `0.96 / 0.94 / 0.93` for `button / compact / chip`, with an interactive release spring tuned closer to Apple’s `interactiveSpring` baseline than to a highly bouncy custom sequence. - -## Verification Checklist For A Future Code Change - -- Touch-down produces visible feedback immediately. -- Touch-up-inside confirms the action and releases feedback. -- Touch-exit/cancel restores feedback without activating. -- Drag-out and drag-back-in re-enter the pressed state. -- Repeated taps do not stack animations or jump transforms. -- While a release animation is running, the control remains interactive unless intentionally disabled. -- Reduce Motion eliminates or tightens bounce and avoids repetitive scaling. -- Haptics, if used, are prepared before the triggering event and remain proportional to the visual motion. diff --git a/docs/architecture/2026-08-27-android-ios-ui-parity.md b/docs/architecture/2026-08-27-android-ios-ui-parity.md deleted file mode 100644 index d317c51c..00000000 --- a/docs/architecture/2026-08-27-android-ios-ui-parity.md +++ /dev/null @@ -1,28 +0,0 @@ -# Android ↔ iOS UI / interaction parity - -Date: 2026-08-29 -Status: Waves 0–4 landed on Android host UI; remaining polish listed below -Authority: iOS visual + interaction. Android maps the same product, it does not invent a second Material language. - -## Landed (2026-08-27 / 2026-08-29) - -- Shared Compose chrome: card rows, icon wells, appearance capsule, empty/error, press bounce, secondary scaffold (`apps/android-app/.../core/ui/compose/`). -- Secondary destinations hide the bottom tab bar (iOS secondary stack analogue). -- Profile tab rebuilt as iOS card hub: 我的动态 / 书签 / 历史 / 草稿 / 私信 / 勋章 / 反馈 / 邀请 / LDC / CDK / 设置. -- Public profile uses follow/私信 + 关注/粉丝 + 最近动态 instead of top-topic dump. -- Follow lists, activity timeline, badges + detail, invite links. -- Settings: capsule appearance, DoH child page, developer-tools export, logout, version footer. -- Notification copy aligned to iOS Chinese templates. -- Home scope chrome: leading category drawer, status capsules (分类 / 排序 / 标签 / 清除), child shortcut strip, topic rows with avatar + category/tag chips + metric weight. -- Topic detail: pinned title after header scrolls away; WeChat-style quick-reply bar replaces FAB. -- User card: compact detent, 13pt action row, native profile deep link. -- Search full-screen header with back; notifications/chat lose Material cards/FAB and use canvas list chrome. - -## Still open - -- Topic-row surge micro-animations and home long-press bookmark editor. -- Topic-detail post-row Texture-level spacing/boost capsule polish. -- Composer / bookmark-editor sheet restyle. -- Shake-to-feedback, OLED fourth appearance segment, widget visual parity. - -Login remains the earlier Compose unification surface. diff --git a/docs/architecture/2026-09-19-render-presentation-roadmap.md b/docs/architecture/2026-09-19-render-presentation-roadmap.md deleted file mode 100644 index ad0123ba..00000000 --- a/docs/architecture/2026-09-19-render-presentation-roadmap.md +++ /dev/null @@ -1,871 +0,0 @@ -# RenderPresentation 后续阶段完整规划 - -日期:2026-09-19 -状态:已实施 -前置:`docs/architecture/2026-09-19-render-presentation.md`(终态摘要) -范围:帖子 / Boost / 聊天 / 资料 bio 的展示数据所有权、UI plan 形状、UniFFI 出站、宿主消费、Handle - -本文是 Stage 1–4 的唯一权威规格,现已落地。当前行为以代码与 `2026-09-19-render-presentation.md` 为准。不要另开平行方案,不要为旧 FFI 形状保留兼容出口。 - ---- - -## 0. 文档怎么用 - -读完应能回答五件事: - -1. 值从哪里来、谁拥有、谁释放。 -2. 哪些状态允许存在,哪些组合根本不该构造。 -3. 哪一层稳定、哪一层只是内部实现。 -4. 解析 / 展示计算 / FFI 拷贝 / 宿主排版分别发生在哪里。 -5. 每个阶段做什么、不做什么、怎样才算完成。 - -设计判断遵循仓库内 `.agents/skills/rust-quality-coding`:先所有权和领域类型,再函数,最后才是 trait / Handle / 零拷贝。展示计算保持同步 CPU,放在 async fetch 之后的映射侧,不进网络 task。不为“将来可能替换 renderer”抽象 trait。 - ---- - -## 1. 已经完成的阶段(Stage 0–4) - -Stage 1–4 已按本文落地。当前出站与宿主边界见 `docs/architecture/2026-09-19-render-presentation.md`。下面 Stage 0 段落保留为当时切点的记录。 - -2026-09-19 已落地的边界: - -```text -cooked HTML - → fire-core::parse_cooked_html (内部 AST,不上 FFI) - → fire-rich-text::render_document (内部 IR) - → fire-rich-text::PresentedDocument (IR + UI plan 的名义所有者) - → RenderPresentation (plain_text / image_attachments / segments) - → RenderPresentationState (UniFFI Record) - → iOS / Android FireRenderPresentation (宿主映射) -``` - -已做到: - -- `TopicPostState` / `TopicPostBoostState` / `ChatMessageState` 不再带 `cooked` 或 `render_document`,只带 `presentation`。 -- 宿主不再把文档回传 Rust 做第二次 `collect_images` / `plain_text` / segment 拆分。 -- 聊天 REST 与 MessageBus 的消息/频道 envelope 由 Rust 解析并带上 presentation。 -- 删除了会把 `cooked` 抹成空串的反向 `From for TopicPost`。 -- `present_cooked_html` 只留给测试夹具。 - -未做到(本文要规划的): - -- segment 仍是迷你 `RenderDocument`,block 树仍过 FFI。 -- 宿主仍重建 `FireRichTextNode`,并二次拆 onebox / 图文。 -- `TopicPost` / `ChatMessage` 领域对象仍只持有 `cooked`;每次 FFI 映射都重新 html5ever。 -- `PresentedDocument` 出站时 `into_presentation()`,IR 立刻丢掉,Handle 没有可包的运行时对象。 -- checksum、raw、bio、bus 的 delete/reaction/tracking、双端渲染缓存键仍是宿主拼的。 - -Stage 0 修的是「往返」。后续修的是「同一份正文被复制成太多份 IR,而且每次出 FFI 都重算、整页重拷」。 - ---- - -## 2. 原则与硬约束 - -### 2.1 一条权威路径 - -每个功能只保留一条实现路径。缺口暴露为缺失,不从 `raw`、平台 HTML parser 或 SwiftUI/Compose 假正文补。iOS 帖子行继续走 native runtime cell,不重开 SwiftUI post-row fallback。 - -### 2.2 所有权先于拷贝 - -| 数据 | 最终所有者 | 谁只读 | 谁不得持有 | -|---|---|---|---| -| cooked HTML | 解析期 / 编辑期的领域记录 | 持久化层 | FFI 热路径、宿主 cell | -| `CookedHtmlDocument` | `parse_cooked_html` 栈上 | 单测 | FFI、宿主 | -| `RenderDocument` | `PresentedDocument` | 调试 / 将来按需派生 | `TopicPostState`、宿主 | -| UI plan | `PresentedDocument` | Handle 方法 | 不得再复制一份平行 plan | -| 原生节点 / Spannable / `NSAttributedString` | 宿主 | cell | Rust | - -`Clone` 必须能说出新副本由谁使用。默认同页 load more、MessageBus 刷新、点赞回写不得再克隆整棵展示树。 - -### 2.3 UniFFI 0.32 能做什么、不能做什么 - -- Object 已经是 `u64` handle。这是 Stage 3 的唯一出站机制。 -- Record / Enum / `String` / `Vec` 都走 `RustBuffer` 拷贝。 -- `ForeignBytes` / `&[u8]` 只覆盖 **foreign → Rust、同步、顶层参数**。不能把展示树零拷贝送回 Swift/Kotlin。 -- 禁止把 Handle 做成 `fn presentation(&self) -> RenderPresentationState` 然后继续在热路径调用。那只是换了个名字搬树。 - -### 2.4 稳定边界 vs 内部实现 - -稳定(跨 crate / 跨 FFI / 宿主必须遵守): - -- `PresentedDocument` 是唯一运行时所有者。 -- 宿主只消费 UI plan 或 Handle 方法,不解析 cooked。 -- `TopicTreeRow` 继续只描述树形,不夹带正文。 - -内部(可以改、宿主不得依赖): - -- `CookedHtmlDocument`、扁平 `RenderBlock` 树、`display_segments` 的现行拆法。 -- `FireRenderBlockNodeBuilder` / `FireRenderBlockBuilder` / `FireRichTextBlockBuilder`(Stage 1 后退场)。 - -### 2.5 并发 - -HTML 解析和 UI plan 生成是同步 CPU。发生在: - -1. 网络 JSON 收成领域对象之后; -2. 写入会话内存之前。 - -不要放进 `run_on_ffi_runtime` 的请求闭包里和 I/O 抢线程,也不要放到宿主主线程。同一 `cooked + base_url` 的结果用 `Arc` 共享,不在 FFI 线程重算。 - ---- - -## 3. 目标终态 - -```text -网络 JSON / MessageBus - → fire-core 解析 - → TopicPostRecord / ChatMessageRecord (可持久化:id、cooked、raw、元数据) - → present_cooked → Arc (只算一次) - → TopicPostRuntime / ChatMessageRuntime (记录 + Arc) - │ - ├─ 会话内存、load more、点赞回写:只动元数据,复用 Arc - │ - └─ UniFFI - TopicPostState.presentation: Option> - Handle 方法: - checksum() / plain_text() / is_empty() - image_attachments() (小 Record 列表) - segment_count() - segment(i) -> RenderUiSegmentState - 默认详情行按需取 segment;列表/搜索/引用只取 plain_text + checksum - │ - └─ 宿主 - 用 Handle 身份做缓存键 - segment → 原生节点 - 不再持有 FireRichTextNode 作为中间 IR(或只在单段映射时临时存在) -``` - -终态宿主看到的正文不是 HTML,不是 block 树,也不是迷你 `RenderDocument`。它看到的是: - -```text -RenderUiSegment - Rich { nodes: Vec } // 已按宿主可画的节点收口 - Image { ... } - Onebox { ... } -``` - -`RenderDocument` 留在 Handle 里面。没有显式调试需求,不提供 `document()`。 - ---- - -## 4. 当前清单 - -### 4.1 Rust 类型 - -| 类型 | 位置 | 当前角色 | 终态角色 | -|---|---|---|---| -| `CookedHtmlDocument` | `fire-models` | 解析 AST | 内部,不上 FFI | -| `RenderDocument` + `RenderBlock` | `fire-models` | 语义 IR;也被塞进 Rich segment 出站 | 仅 `PresentedDocument` 内部 | -| `RenderDisplaySegment::{Rich,Image}` | `fire-models` | 迷你文档 / 独立图 | 被 `RenderUiSegment` 取代 | -| `RenderPresentation` | `fire-models` | 出站 Record 的领域镜像 | 过渡;Handle 就位后不再整包出站 | -| `PresentedDocument` | `fire-rich-text` | 名义所有者,出站即拆开 | 运行时唯一所有者,`Arc` 化 | -| `TopicPost.cooked` | `fire-models` | 领域唯一正文 | 持久化/编辑字段;展示走 Arc | -| `TopicPostBoost.cooked` | `fire-models` | 再解析一次出 presentation | 解析后丢掉,只留 plan | -| `ChatMessage.cooked` | `fire-models` | 同上 | 同上 | -| `UserProfile.bio_cooked` | `fire-models` | 原样出 FFI | 出 `bio_plain_text` 或 Handle | -| `TopicPostState.presentation` | `fire-uniffi-topics` | 整包 `RenderPresentationState` | `Option>` | -| `TopicPostState.raw` | `fire-uniffi-topics` | 每帖默认出站 | 按需 API | -| `TopicDetailSourceSnapshot.loaded_posts` | `fire-models` / UniFFI | 全量帖子 + 全量 presentation | 运行时 Arc 复用;FFI 只出增量或 handle 列表 | -| `TopicTreeRow` | `fire-models` | 只有 id / 层级 | 保持,不要夹带正文 | - -### 4.2 当前热路径(必须改) - -Rust 出站: - -- `fire-uniffi-topics`:`topic_post_state_from_model` / `topic_post_boost_state_from_model` -- `fire-uniffi-chat`:`chat_message_state_from_model` / `ChatStateMapper` -- `fire-uniffi-types`:`presentation_state_from_cooked`(types crate 依赖 fire-core,分层反了) -- `fire-core`:`present_cooked_html`、`boost_display_text`(内部先 `render_cooked_html` 一次) -- `fire-uniffi-topics`:`topic_detail_source_snapshot_state_from_model` 把 **全部** `loaded_posts` 再映射一遍 -- `fire-uniffi`:`present_cooked_html` 测试入口 - -iOS: - -- `FireRenderPresentation` / `FireRenderBlockNodeBuilder` -- `FireTopicPresentation.renderContentFromPresentation` + `splitRichNodes` -- `FireTopicDetailStore` 的 `presentationChecksum` -- `FireChatRichText` / `FireChatMessageCell` -- `FireChatBusPayload.jsonObject`(delete / reaction / tracking) -- 资料:`plainTextFromHtml(bioCooked)`,`FireProfileViewController` 仍有 `NSAttributedString.DocumentType.html` - -Android: - -- `FireRenderPresentation` / `FireRenderBlockBuilder` -- `FireRichTextBlockBuilder`(生产 cell 已不走;夹具和遗留切分仍在) -- `TopicDetailViewModel.parsePostContent` 走 `content()`,`PostViewHolder` 走 `blocks()`,同一帖两条映射 -- `LruCache(64)`,键是 post id,不是内容身份 - -### 4.3 宿主仍在做的本该 Rust 做的事 - -- 从扁平 block 重建树(`FireRenderBlockNodeBuilder`)。 -- 从 node 树再拆 onebox(iOS `splitRichNodes`)。 -- 从 node 树再拆图文(Android `FireRichTextBlockBuilder`)。 -- 用 `plainText + segment 数量 + 图片 URL` 做 checksum,**不含富文本结构**,缓存会误命中。 -- iOS 对同一 presentation 建两遍 attributed string:整篇一份,每个 text segment 再一份。 - ---- - -## 5. 问题诊断 - -### 5.1 一份正文的副本 - -当前一篇帖子在内存里可以同时存在: - -1. `TopicPost.cooked` -2. 解析期 `CookedHtmlDocument`(栈上,可接受) -3. `RenderDocument`(plain_text + 图 + blocks) -4. `RenderPresentation` 再拷 plain_text / 图,外加每个 Rich segment 一份迷你文档 -5. `RenderPresentationState` FFI 再拷一遍 -6. `FireRichTextNode` 树 -7. `NSAttributedString` / Spannable - -Stage 0 删了「宿主 → Rust」的 5.5。5.4 到 5.6 还在。 - -### 5.2 每次出站都重算 - -`TopicPost` 不持有 `PresentedDocument`。下列每次都跑完整解析: - -- 详情首屏 -- load more(旧帖和新帖一起 remap) -- `fetch_post` / 回复历史 / 编辑回写 -- 聊天 REST 与 MessageBus -- Boost:`boost_display_text` 一次,`presentation_state_from_cooked` 再一次 - -`PresentedDocument::from_document` 算完立刻 `into_presentation()`,Arc 无从挂起。 - -### 5.3 展示计划不完整 - -`display_segments` 只保证「独立图片 vs 一段富文本」。Onebox、code、quote 仍埋在迷你文档里。于是: - -- iOS 必须再扫 node 才能抽出 onebox 卡 -- Android 必须再扫 node 才能切图文 -- 两端 `FireRichTextNode` 变成第三套 IR - -### 5.4 身份不稳定 - -`FireRenderPresentation.checksum` 忽略 segment 内容。两篇结构不同、纯文本和图片 URL 相同的帖子会撞键。iOS store 和 Android LruCache 因此不能当权威身份用。 - -### 5.5 分层反了 - -`fire-uniffi-types` 依赖 `fire-core` 只为了 `presentation_state_from_cooked`。types crate 应只有 Record 和纯 `From`,不该跑 html5ever。 - ---- - -## 6. 阶段总览 - -| 阶段 | 名称 | 解决什么 | 不解决什么 | 依赖 | -|---|---|---|---|---| -| 0 | 出站改为 Presentation Record | 往返 | 迷你文档、重算、Handle | 已完成 | -| 1 | UI plan 收口 | 迷你文档 + 宿主二次拆分 | 重算、Handle | 无 | -| 2 | 领域持有 `Arc` | 重算、Boost 双解析、types→core | Handle、按需 raw | 1 的类型,可与 1 后半并行 | -| 3 | `RenderDocumentHandle` | FFI 整包树 | bio/bus 边角 | 2 | -| 4 | 收口边角 | checksum、raw、bio、bus、缓存键 | 新的排版引擎 | 2,建议 3 之后 | - -顺序硬约束: - -- **先改 UI plan 形状,再做 Handle。** Handle 若仍返回现行 `RenderPresentationState`,热路径一份不省。 -- **先让领域持有 Arc,再把 Arc 抬成 Object。** 否则 Handle 每次构造都还要 parse。 -- Stage 1 可以单独合并。Stage 3 不能跳过 Stage 2。 - -```text -Stage 0 ──已完成──▶ Stage 1 形状 - │ - ▼ - Stage 2 所有权 / 只算一次 - │ - ▼ - Stage 3 Handle(u64 出站) - │ - ▼ - Stage 4 边角与分层打扫 -``` - ---- - -## 7. Stage 1 — 把 segment 收成真正的 UI plan - -### 7.1 目标 - -宿主不再看到 `RenderDocument`。FFI 上的一段正文是「可直接画的 segment 列表」。iOS 删除 `splitRichNodes` 的 onebox 二次拆分。Android 生产路径删除 `FireRichTextBlockBuilder`。`FireRenderBlockNodeBuilder` / `FireRenderBlockBuilder` 在本阶段结束时只服务测试夹具或删除。 - -### 7.2 目标类型 - -`fire-models` 新增(名字以落地时 crate 内最终名为准,语义不得变): - -```rust -pub enum RenderUiSegment { - Rich { nodes: Vec }, - Image(RenderImageAttachment), - Onebox(RenderOneboxCard), -} - -pub struct RenderOneboxCard { - pub url: Option, - pub title: Option, - pub description: Option, - pub source_name: Option, - pub icon_url: Option, - pub thumbnail_url: Option, - pub thumbnail_width: Option, - pub thumbnail_height: Option, -} - -/// 与当前 FireRichTextNode 一对一,供宿主机械映射。 -/// 不是扁平 RenderBlock,不带 id / parent_id / depth。 -pub enum RenderRichNode { - Text { content: String }, - Bold { children: Vec }, - Italic { children: Vec }, - Strikethrough { children: Vec }, - Code { code: String }, - CodeBlock { language: Option, code: String }, - Link { url: String, children: Vec }, - Mention { username: String }, - MentionGroup { name: String, url: String }, - Hashtag { text: String, url: String, kind: Option }, - Emoji { url: String, fallback_text: String, only_emoji: bool }, - Heading { level: u8, children: Vec }, - Blockquote { children: Vec }, - Quote { - author: Option, - post_number: Option, - topic_id: Option, - children: Vec, - }, - List { ordered: bool, items: Vec> }, - ListItem { children: Vec }, - Spoiler { children: Vec }, - Details { summary: Vec, children: Vec }, - Table { text: String }, - Video { url: String, title: Option }, - Divider, - LineBreak, - Paragraph { children: Vec }, -} -``` - -UniFFI 出站把 `RenderRichNode::List` 和 `RenderBlockKind::List` 命名为 `ListNode`。Kotlin 嵌套类不能叫 `List`,否则会盖住 `kotlin.collections.List`,生成绑定无法编译。 - -`RenderPresentation` 改为: - -```rust -pub struct RenderPresentation { - pub checksum: u64, - pub plain_text: String, - pub image_attachments: Vec, - pub segments: Vec, -} -``` - -`checksum` 在 `present_document` 时写入,覆盖 plain_text、每段 kind、富文本结构、图片 URL / 尺寸。宿主禁止再本地哈希。 - -### 7.3 为什么 Rich 仍是树,而不是 attributed run - -Quote、list、details、spoiler 需要嵌套。压成 `Vec` 会把这些结构抹平,宿主还得自己恢复,等于再造一套 IR。`RenderRichNode` 与现有 `FireRichTextNode` 同构,Stage 1 的宿主改动是机械映射,不是重写排版。 - -独立成段的只有宿主 **已经当成独立 cell** 的东西:图片、onebox。Code / quote / details 继续留在 Rich 段里,与当前 Texture / Android 行为一致。本阶段不把它们升成独立 cell,避免视觉回归。 - -### 7.4 `display_segments` 怎么改 - -现行 `append_display_segments` 把容器打散再 `wrap_rich_segment` 成迷你 `RenderDocument`。改为: - -1. 仍按现规则切开独立 `Image`。 -2. 遇到 `RenderBlockKind::Onebox` 输出 `RenderUiSegment::Onebox`,不再埋进 Rich。 -3. 连续的非图片、非 onebox 子树一次收成 `Vec`。 -4. 删除 `wrap_rich_segment` / `subtree_document` 对 `RenderDocument` 的再分配(id remap、再提 plain_text)。 - -`PresentedDocument` 继续同时持有内部 `RenderDocument`(给 Stage 3 Handle)和这份 UI plan。`present_document` 只生成 plan,不再 `clone` 一份与 document 重复的 attachments 到 plan 之外——plan 的 `image_attachments` 可以是对 document 附件的一次拥有转移或 `Arc<[T]>`。若 Stage 1 先继续 clone 附件列表,必须在注释里标明 Stage 2 改为共享。 - -### 7.5 FFI - -`RenderDisplaySegmentState` 换成 `RenderUiSegmentState`。`RenderDocumentState` 不再出现在 `TopicPostState` / `ChatMessageState` / `TopicPostBoostState` / `RenderPresentationState.segments` 上。 - -`RenderDocumentState` / `RenderBlockState` 若仍被 `parse_cooked_html` 测试或夹具使用,可以留在 types crate,但标注为内部/测试,生产热路径不得引用。 - -`present_cooked_html` 改为返回新 `RenderPresentationState`(含 checksum 与新 segment)。测试夹具跟着改。 - -### 7.6 宿主 - -iOS: - -- `FireRenderPresentation.richNodes` 映射 `RenderRichNode` → `FireRichTextNode`,不再经过 `FireRenderBlockNodeBuilder`。 -- `renderContentFromPresentation` 按 Rust segment 直接生成 `FireTopicPostRenderSegment`:`Rich → .text(attributed)`,`Image → .image`,`Onebox → .onebox`。 -- 删除 `splitRichNodes`。 -- 整篇 `attributedText` 若仍被搜索/引用需要,从 `plain_text` 或把 Rich 段 attributed 接起来;禁止再从「全树 nodes」和「分段 nodes」各建一套逻辑分叉。优先:引用/搜索只用 `plain_text`;cell 只用分段 attributed。 -- checksum 改为读 `presentation.checksum`。 - -Android: - -- `FireRenderPresentation.blocks` 直接消费 `RenderUiSegment`。 -- `PostViewHolder` 与 `ViewModel` 共用同一映射函数,禁止 `content()` 与 `blocks()` 两套。 -- 生产代码删除对 `FireRichTextBlockBuilder.build(nodes, attachments)` 的调用。夹具可暂留,阶段结束时标 deprecated。 - -### 7.7 文件面 - -Rust: - -- `crates/fire-models/src/rich_text.rs` -- `crates/fire-rich-text/src/ui_plan.rs`(`display_segments`) -- `crates/fire-rich-text/src/presentation.rs` -- `crates/fire-uniffi-types/src/records/render_block.rs` -- 全部构造 `RenderPresentationState` / `RenderDisplaySegmentState` 的测试 - -iOS: - -- `FireRenderPresentation.swift` -- `FireTopicPresentation.swift` -- `FireRenderBlockNodeBuilder.swift`(退场或降为测试) -- `FirePostCellLayout.swift`(Boost 仍走 richNodes) -- 单测:`FireTopicPresentationTests`、layout tests - -Android: - -- `FireRenderPresentation.kt` -- `FireRenderBlockBuilder.kt` / `FireRichTextBlockBuilder.kt` -- `PostViewHolder.kt` / `TopicDetailViewModel.kt` / `ChatChannelActivity.kt` -- `FireRichTextBlockBuilderTest.kt` - -### 7.8 验收 - -- 生产 FFI 热路径的 grep:`RenderDocumentState` 不得再出现在 `TopicPostState` / `ChatMessageState` / `TopicPostBoostState` / `RenderPresentationState`。 -- iOS 生产代码 grep:`splitRichNodes`、`FireRenderBlockNodeBuilder` 为零。 -- Android 生产 cell grep:`FireRichTextBlockBuilder` 为零。 -- 现有 rich-text 单测(quote / details / onebox / 图注过滤 / emoji fallback)全部改为断言 `RenderUiSegment`,语义不得回退。 -- 目视:详情长帖图文交错、onebox 卡、quote 折叠、Boost chip emoji 与 Stage 0 一致。 -- checksum 对「同文不同结构」必须变化。补单测。 - -### 7.9 本阶段明确不做 - -- 不引入 Handle。 -- 不把 `TopicPost` 改成持有 Arc(那是 Stage 2)。 -- 不改 MessageBus delete/reaction JSON。 -- 不在 Rust 里生成 `NSAttributedString` / Spannable。 - ---- - -## 8. Stage 2 — 领域持有 `Arc` - -### 8.1 目标 - -一份 `cooked + base_url` 在进程内只解析一次。load more、点赞、书签、MessageBus 元数据补丁、聊天列表 upsert 复用同一 `Arc`。FFI 映射不再调用 `present_cooked_html`。 - -### 8.2 类型怎么拆 - -`TopicPost` 目前既是网络解析结果,也是 serde 缓存形状,也是 FFI 映射源。不要把 `Arc` 塞进会整包 JSON 序列化的缓存记录。 - -推荐拆成: - -```rust -/// 可持久化 / 可 serde。不含运行时 IR。 -pub struct TopicPostRecord { - pub id: u64, - // ... 现有 TopicPost 字段,包括 cooked、raw ... -} - -/// 会话内存里的帖子。展示与元数据一起走。 -pub struct TopicPost { - pub record: TopicPostRecord, - pub presented: Option>, -} -``` - -若希望少改调用点,允许在现有 `TopicPost` 上加: - -```rust -#[serde(skip)] -pub presented: Option>, -``` - -但 `TopicDetailSourceSnapshot` 一旦 serde 进 SQLite / 文件,必须保证 skip 生效,冷启动从 `cooked` 再 present 一次。两种写法选一个,禁止并行两套「运行时帖子」。 - -`ChatMessage`、`TopicPostBoost` 同样处理。Boost 的 `display_text` 从 `presented.plain_text()` 做归因剥离,禁止再跑一遍 `render_cooked_html`。 - -### 8.3 何时 present - -唯一入口: - -```rust -fn attach_presentation(post: TopicPostRecord, base_url: &str) -> TopicPost -``` - -调用点: - -- `topic_payloads` 解析完 raw post -- `chat_payloads` 解析完 message -- 编辑 / 发帖回写拿到新 cooked 之后 -- 冷启动从缓存读出 record 之后 - -禁止调用点: - -- `topic_post_state_from_model` -- `ChatStateMapper` -- 宿主 `presentCookedHtml` - -`base_url` 来自 `FireCore` 会话,不写死 `"https://linux.do"`,除非测试夹具。 - -同一会话内用 `(post_id, cooked_fingerprint, base_url)` 做 memo。编辑后 cooked 变了才换 Arc。点赞 / 反应 / bookmark 只改 record 元数据,`presented` 指针不变。 - -### 8.4 load more 与快照 - -今天 `TopicLoadMoreOutcome.source_snapshot` 携带全部 `loaded_posts`。Stage 2 即使还整包出站,也不得对旧帖重 parse:旧帖带着原来的 Arc 走 `From`。 - -本阶段同时把核心快照改成「全量运行时 + 增量 FFI」的准备: - -- 内存:`loaded_posts: HashMap` 或保留 Vec 但按 id 复用 Arc。 -- FFI:可以仍先出全量 handle/record(Stage 3 再变瘦),但映射函数是 `clone Arc`,不是 `present_cooked_html`。 - -已有 `TopicDetailSourceAppend.appended_posts`。Stage 2 结束时,load more 的 **Rust 内部**必须能只 present 新增帖。FFI 是否改为只推 append 可以放到 Stage 3,与 Handle 一起做,避免改两次出站形状。 - -### 8.5 分层 - -`presentation_state_from_cooked` 从 `fire-uniffi-types` 删除。 - -```text -fire-models 记录 + UI plan 类型 -fire-rich-text document → PresentedDocument(不碰网络、不碰 UniFFI) -fire-core parse HTML + attach_presentation -fire-uniffi-types 只 From 等纯映射,不依赖 fire-core 做 present -fire-uniffi-topics 从 TopicPost.presented 升 FFI -``` - -`fire-uniffi-types` 对 `fire-core` 的依赖若只为 presentation,本阶段去掉。若还有 runtime / error 共享,把 present 辅助挪走,不要为了方便把解析留在 types。 - -### 8.6 `present_cooked_html` 的命运 - -- 测试夹具可以继续调用 fire-core / 顶层 UniFFI 函数。 -- 生产映射路径 grep 必须为零。 -- 文档写明:这是「只有一段 cooked、没有领域对象」的遗留入口,不是帖子主路径。 - -### 8.7 文件面 - -- `fire-models/src/topic_detail.rs`、`chat.rs` -- `fire-core/src/topic_payloads.rs`、`chat_payloads.rs`、`rich_text.rs`、`core/topics.rs` -- `fire-uniffi-topics/src/records.rs`、`lib.rs` -- `fire-uniffi-chat/src/records.rs`、`lib.rs` -- `fire-uniffi-types/src/records/render_block.rs`、`Cargo.toml` -- Boost:`boost_display_text` - -### 8.8 验收 - -- 同一 `TopicPost` 在「首屏映射 + load more 再映射」中,`Arc::ptr_eq` 为真(单测)。 -- 点赞回写后 `presented` 指针不变。 -- Boost 单测:一次 parse,`display_text` 与 presentation.plain_text 同源。 -- `fire-uniffi-types` 不再 `use fire_core::present_cooked_html`。 -- 基准(至少开发机日志):大帖详情 load more 不再出现与旧帖数量成正比的 html5ever 时间。允许用 tracing span `present_cooked` 计数断言:第二次 load more 的 present 次数 ≈ 新帖数。 - -### 8.9 本阶段明确不做 - -- 不把 `TopicPostState.presentation` 改成 Object(Stage 3)。 -- 可以仍整包 lift `RenderPresentationState`,因为 Arc 已算完,lift 只是拷 plan。这是可接受的过渡。 -- 不改资料 bio、不改 bus delete JSON。 - ---- - -## 9. Stage 3 — `RenderDocumentHandle` - -### 9.1 目标 - -热路径跨 FFI 只传 `u64`。宿主按 Handle 身份缓存原生排版。需要画某一段时再取该段 Record。列表、搜索、引用、checksum 比较不取 segment 树。 - -### 9.2 对象形状 - -```rust -#[derive(uniffi::Object)] -pub struct RenderDocumentHandle { - inner: Arc, -} - -#[uniffi::export] -impl RenderDocumentHandle { - pub fn checksum(&self) -> u64; - pub fn is_empty(&self) -> bool; - pub fn plain_text(&self) -> String; - pub fn image_attachments(&self) -> Vec; - pub fn segment_count(&self) -> u32; - pub fn segment(&self, index: u32) -> Option; - - /// 仅测试 / 调试。生产 cell / store 不得调用。 - pub fn debug_ui_plan(&self) -> RenderPresentationState; -} -``` - -`TopicPostState` / `TopicPostBoostState` / `ChatMessageState`: - -```rust -pub presentation: Option>, -``` - -没有 `cooked`,没有 `render_document`,没有内嵌 `RenderPresentationState`。 - -构造: - -```rust -impl RenderDocumentHandle { - pub fn from_presented(presented: Arc) -> Arc { - Arc::new(Self { inner: presented }) - } -} -``` - -同一 `Arc` 升一次 Handle 并在会话里复用。禁止每次 FFI 映射 `Arc::new(Handle { inner: presented.clone() })` 又包一层新 Object——否则宿主身份每次都变,缓存全废。做法:`PresentedDocument` 侧可持有弱引用或在会话表 `HashMap>`。更简单:Handle 就是 `#[uniffi::Object]` 包着的 `Arc`,映射时对已有 `Arc` 做 clone(clone 的是外层 Arc,handle id 不变)。因此 Stage 2 的运行时帖子应直接存 `Arc`,或存 `Arc` 并保证「一个 PresentedDocument 只对应一个 Handle」。推荐后者加一层 `HandleBox`: - -```rust -pub struct PresentedBody { - document: Arc, - handle: Arc, // 与 document 同一份 inner -} -``` - -创建一次,之后只 clone `PresentedBody`。 - -### 9.3 宿主怎么用 - -详情 cell configure: - -```text -let handle = post.presentation -if handle.checksum() == cached.checksum { reuse nodes } -else { - for i in 0..handle.segmentCount() { - map(handle.segment(i)) - } -} -``` - -搜索 / 引用 / 列表预览:只调 `plainText()`。 - -禁止: - -- `debug_ui_plan()` 出现在 `FireTopicPresentation` / `PostViewHolder` / `FireChatRichText` -- 把所有 segment 一次性取回再塞进自己的平行 cache,作为长期 IR(一次性取可以,但缓存键必须是 handle checksum / object identity) - -iOS `contentInputsByPostID` 的输入改为 `presentationChecksum: handle.checksum()`。Android `LruCache` 键改为 `checksum` 或 `(postId, checksum)`,避免编辑后命中旧 Spannable。 - -### 9.4 详情快照出站变瘦 - -与 Handle 同一阶段做: - -`TopicDetailSourceSnapshotState.loaded_posts` 仍可给宿主一张「id → 帖子元数据 + handle」表,这是投影需要的。但: - -- 不要把 `raw` 放进这张表。 -- load more FFI 改为「append 的 posts + 更新后的 cursor / ranges / tree」,不要把旧帖元数据再写一遍。宿主已有的 handle 继续持有。 -- `TopicTreePresentationState` 继续只有 `TopicTreeRow`(id 与层级)。 - -已有类型 `TopicDetailSourceAppend` 应对齐成 UniFFI Record,作为 `load_more` 的出站,而不是每次 `TopicLoadMoreOutcomeState` 复制整表。 - -### 9.5 raw 按需 - -新增或复用现有 `fetch_post`:编辑弹窗只在用户点编辑时要 `raw`。`TopicPostState.raw` 从默认详情快照删除。若 `fetch_post` 已返回完整 `TopicPostState`,编辑路径走它,并允许这一次带 `raw`。 - -### 9.6 UniFFI / 绑定 - -- 重新生成 Swift / Kotlin bindings。 -- Object 跨线程:Handle 必须 `Send + Sync`(`Arc` 已满足)。 -- 宿主不得对 Handle 做深比较;用 checksum 或引用身份。 -- 文档写明:Handle 生命周期由 Rust Arc 与 UniFFI 引用计数共同管理;宿主存 Handle 即延长 IR 寿命。详情页释放后,旧 cell 不得再调方法。 - -### 9.7 验收 - -- 生产 `TopicPostState` 无 `RenderPresentationState` 字段。 -- 大帖详情首屏 FFI 载荷不再含每帖完整 block 树;可用绑定生成物或集成测试断言 `segment()` 才触发该段 lift。 -- load more 不把旧帖的 segment 再 lift 一遍(tracing 或测试桩计数)。 -- iOS/Android 编辑:未点编辑时详情快照不含 raw;点编辑后能拿到 raw。 -- 点赞后 cell 不因新 Handle 身份重建正文(checksum 不变且 handle 身份不变)。 - -### 9.8 本阶段明确不做 - -- 不在 Handle 上暴露 `document()` / `blocks()`。 -- 不用 `ForeignBytes` 手写序列化格式。 -- 不把 pixel buffer / 图片解码塞进 Handle。 - ---- - -## 10. Stage 4 — 边角、身份、剩余混杂逻辑 - -Stage 2/3 做完后,这些才能收得干净。可拆成独立 PR,但必须落在同一规格下。 - -### 10.1 checksum 权威化 - -- 唯一写入点:`present_document`。 -- 算法固定:对 UI plan 做稳定序列化(长度前缀或明确分隔),再 hash(xxhash / siphash,选一个写死)。 -- 宿主、store、Android LruCache、聊天 `contentID` 全部读这个 `u64`。 -- 删除 `FireRenderPresentation.checksum` 的本地字符串拼接。 - -### 10.2 资料 bio - -`UserProfile.bio_cooked` 不再出给宿主当 HTML。 - -二选一,优先 A: - -- A. `bio_plain_text: Option`。资料卡只显示纯文本,不必上富文本。 -- B. 与帖子同一套 Handle。仅当产品要在资料页渲染 mention / emoji 时才用。 - -删除 iOS `NSAttributedString.DocumentType.html` 资料路径。`plainTextFromHtml` 对 bio 的调用改为读 Rust 字段。 - -### 10.3 聊天 MessageBus 剩余 JSON - -iOS 仍用 `FireChatBusPayload.jsonObject` 处理: - -- delete:`deleted_id` -- reaction:`chat_message_id` / `emoji` / `action` / `user` -- tracking:`channel_id` / `unread_count` / `mention_count` / `thread_id` -- new-messages 的 `type == "channel"` 过滤 - -这些与展示无关,但是协议解析。收口到 `fire-core` 的 typed bus payload: - -```rust -pub enum ChatBusEvent { - MessageUpsert { message: ChatMessage }, - MessageDeleted { id: u64 }, - Reaction { message_id: u64, emoji: String, action: ChatReactionAction, actor_id: Option }, - Tracking { channel_id: u64, unread: u32, mention: u32, thread_id: Option }, - ChannelUpsert { channel: ChatChannel }, - Ignored, -} -``` - -FFI:`chat_bus_event_from_payload(payload_json, fallback_channel_id, base_url) -> ChatBusEventState`。 - -iOS 删除 `jsonObject` 的生产调用。Android 列表侧现有的 `JSONObject` 轻量解析一并换掉,避免两端协议分叉。 - -### 10.4 双端缓存对齐 - -| 用途 | 键 | -|---|---| -| iOS topic render cache | `post_id + handle.checksum` | -| iOS chat NSCache | `message_id + checksum + is_deleted` | -| Android LruCache | 同上,禁止只按 `post_id` | -| 引用 / 搜索 | 只用 `plain_text`,不建 attributed | - -### 10.5 测试入口收敛 - -- `present_cooked_html`:仅测试 target 可见,或留在 UniFFI 但文档标 `testonly`。 -- `parse_cooked_html`:继续仅内部 / 单测。 -- 删除任何「平台传入 cooked 换 presentation」的生产调用点。 - -### 10.6 文档与仓库地图 - -本阶段结束时必须同步: - -- 本文状态改为 Implemented,逐阶段打勾 -- `2026-09-19-render-presentation.md` 改写为终态摘要,不再描述 Record 热路径 -- `fire-native-architecture.md` §3.6 / §4.6 / §7.5 -- `2026-06-05-rich-text-and-state-observer-design.md` 顶部备注 -- `2026-08-09-chat-tab-design.md` -- `docs/knowledge/api/03-topics.md`、用户资料相关 knowledge -- iOS / Android README 里仍写 `RenderPresentationState` 整包出站的句子 - -### 10.7 验收 - -- 宿主生产代码 grep:`presentCookedHtml`、`plainTextFromHtml` 用于 bio、`jsonObject(from: event)` 用于 chat bus,均为零。 -- `FireChatBusPayload` 若只剩空壳则删除。 -- checksum 单测覆盖结构变化。 -- 资料卡不再走 HTML 文档类型。 - ---- - -## 11. 跨阶段:crate、测试、验证 - -### 11.1 crate 责任(终态) - -```text -fire-models 领域记录、UI plan 类型、不跑 parser -fire-rich-text RenderDocument + PresentedDocument + checksum -fire-core HTML parse、attach_presentation、bus typed parse -fire-store 只存 record(cooked/raw/元数据),不存 IR -fire-uniffi-types FFI Record / Enum,纯 From -fire-uniffi-topics / chat / user Handle 提升、命令 -native hosts 原生节点、手势、图片管线 -``` - -### 11.2 测试策略 - -每个阶段都要有: - -1. `fire-rich-text` 语义金标(现有 quote / onebox / 图注 / emoji 测试改断言,不删场景)。 -2. FFI 形状测试:生产 Record 不含 `cooked`、不含迷你 `RenderDocument`(Stage 1+);Stage 3 起含 Handle。 -3. 所有权测试:Arc 指针在元数据补丁后保持不变(Stage 2+)。 -4. 宿主单测:夹具改为 `present_cooked_html` 或构造 `RenderUiSegment`,不再手搭 `RenderDocumentState`。 -5. 阶段结束前:相关 crate `cargo test --lib` 与 clippy `--no-deps -D warnings`。 - -没有浏览器可验原生详情。用现有 iOS/Android 单测 + 必要的真机/模拟器目视清单(长帖、onebox、Boost、聊天实时消息、编辑)。 - -### 11.3 验证清单(目视) - -- 详情:图文交错、onebox 卡、quote 折叠与展开、表格纯文本、视频占位、mention / hashtag 点击。 -- Boost overlay 与 chip 的 emoji。 -- 聊天 REST 历史 + MessageBus 新消息,正文与删除态。 -- 点赞 / 反应后正文不闪、不重排(Stage 2/3)。 -- 编辑保存后 checksum 变、正文更新。 -- 资料卡 bio 纯文本,无 HTML 标签泄漏。 - -### 11.4 文档纪律 - -实现某阶段时同步改本文对应章节的状态,并改「当前清单」表。禁止只在代码里演进、让本文停在 Stage 0 口吻。 - ---- - -## 12. 明确不做 - -- 不在 Rust 做 Core Text / Yoga / 完整排版。宿主继续拥有字体、颜色、手势、图片请求。 -- 不引入第二套 renderer,不用 WebView 画正文。 -- 不把 `ForeignBytes` 当出站方案。 -- 不为旧 `RenderPresentationState` 热路径留双栈。Stage 1 换 segment 形状就是切断。 -- 不把 `RenderDocumentState` 重新放回 `TopicPostState`「以备调试」。调试走 Handle 的 `debug_ui_plan` 或 Rust 日志。 -- 不为 parser / presenter 做 trait。没有第二实现。 -- 不把 chat 的 delete/reaction 继续留在宿主「因为很小」。Stage 4 一次收完,避免协议再分叉。 -- 不在 Stage 1 把 code/quote/details 改成独立 cell。那是产品改版,不是本规划。 - ---- - -## 13. 风险 - -| 风险 | 为什么会发生 | 处理 | -|---|---|---| -| `RenderRichNode` 与 `FireRichTextNode` 漏字段 | 两端 node 手写 | Stage 1 用对照表 + 穷尽 match;未知 kind 显式缺口,不吞 | -| onebox 提前成段导致位置错 | 现行拆分把 onebox 留在富文本流里 | 金标用真实 cooked 夹具比位置,不只比字段 | -| serde skip 丢 presented,冷启动全页卡顿 | 缓存只有 cooked | 冷启动 present 放后台映射线程;UI 先出树行,正文按 handle 就位填充 | -| Handle 每次 remap 新 Object | 宿主缓存全失效 | `PresentedBody` 固定一对 document/handle | -| 过早做 Stage 3 | 仍整包 lift plan | 代码审拒绝合并「Handle.getPresentation()」热路径 | -| 大文档与代码漂移 | 阶段多 | 每阶段改本文状态,否则不算完成 | - -没有「旧路径回退」。阶段中途发现语义回归,停在该阶段修权威路径。 - ---- - -## 14. 阶段验收总表 - -| 项 | Stage 1 | Stage 2 | Stage 3 | Stage 4 | -|---|---|---|---|---| -| 热路径无迷你 `RenderDocument` | 必须 | 保持 | 保持 | 保持 | -| 宿主无二次拆 onebox/图文 | 必须 | 保持 | 保持 | 保持 | -| 生产映射不再 parse cooked | | 必须 | 保持 | 保持 | -| `Arc` 在元数据补丁后稳定 | | 必须 | 必须(含 Handle 身份) | 保持 | -| 帖子出站是 Object handle | | | 必须 | 保持 | -| 默认快照无 raw | | 可选 | 必须 | 保持 | -| bio / bus JSON 离开宿主 | | | | 必须 | -| checksum 只来自 Rust | 写入字段 | 领域携带 | Handle 暴露 | 宿主删除本地哈希 | -| 文档与代码一致 | 改形状描述 | 改所有权描述 | 改 FFI 描述 | 本文标 Implemented | - ---- - -## 15. 建议的提交切片 - -不要把四个阶段做成一个 PR。建议: - -1. **Stage 1a**:`RenderUiSegment` / `RenderRichNode` + `display_segments` 改写 + Rust 单测。FFI 仍可暂时从新 plan 再填旧 `RenderDisplaySegment::Rich(document)`——**不推荐**。能直接切 FFI 就直接切。 -2. **Stage 1b**:UniFFI + iOS/Android 映射,删除宿主二次拆分。 -3. **Stage 2**:`attach_presentation`、Boost 单次 parse、去掉 types→core present。 -4. **Stage 3a**:Handle 类型 + 会话内 `PresentedBody`;`TopicPostState` 改字段。 -5. **Stage 3b**:load more 增量 FFI + raw 按需。 -6. **Stage 4**:bio、bus typed event、缓存键、文档终态。 - -1a 与 1b 若拆开,中间不得出现「Rust 已是新 plan、宿主仍走旧 segment」的双栈超过一个 PR 周期。 - ---- - -## 16. 与 Stage 0 文档的关系 - -- `docs/architecture/2026-09-19-render-presentation.md` 描述 **当前已落地** 的 Handle 出站。 -- 本文是 Stage 1–4 的规格与阶段记录;细节以代码和那篇终态摘要为准,避免两份当前边界。 - -`docs/architecture/fire-native-architecture.md` 的富文本管道图已改到 Handle。 diff --git a/docs/architecture/2026-09-19-render-presentation.md b/docs/architecture/2026-09-19-render-presentation.md index 41bdadef..4e4a4013 100644 --- a/docs/architecture/2026-09-19-render-presentation.md +++ b/docs/architecture/2026-09-19-render-presentation.md @@ -2,8 +2,7 @@ 日期:2026-09-19 状态:已实现(Stage 0–4) -范围:帖子 / Boost / 聊天 / 资料 bio 的展示数据在 Rust 算完;热路径出站是 `RenderDocumentHandle` -规格全文:`docs/architecture/2026-09-19-render-presentation-roadmap.md` +范围:帖子 / Boost / 聊天 / 资料 bio 的展示数据在 Rust 算完;热路径出站是 `RenderDocumentHandle` ## 问题 diff --git a/docs/architecture/2026-09-22-ios-topic-detail-session.md b/docs/architecture/2026-09-22-ios-topic-detail-session.md deleted file mode 100644 index 1a9895e9..00000000 --- a/docs/architecture/2026-09-22-ios-topic-detail-session.md +++ /dev/null @@ -1,1203 +0,0 @@ -# iOS 话题详情:Rust 会话唯一控制面 - -| 项 | 值 | -| --- | --- | -| 日期 | 2026-09-22 | -| 状态 | 已落地(Rust 会话 + iOS/Android 单源;旧分页 RPC 已删) | -| 范围 | 话题详情模块。Home / 搜索 / 通知 / 聊天不改架构 | -| 通道 | 只动 `fire-uniffi-topics` + `fire-core` 话题模块。不合并 session / chat / search / notification | -| 参考 | KycNative 模块内对象生命周期与 ABI 投影。不把 Fire 收成一个 `FaceVerifySession` 式应用对象 | - -## Feasibility Assessment - -可行,且应做。源游标、树、未读根自动延伸已经在 Rust: - -- `FireTopicDetailSourceRuntime` / 私有 `TopicDetailSourceSession`:`crates/fire-core/src/core/topics.rs` -- `FireCore::fetch_topic_detail_source_snapshot`、`fetch_topic_detail_page`、`append_topic_detail_source`、`load_more_topic_posts`、`extend_topic_source_to_unread_root_if_needed` -- 模型 `TopicDetailPage { source_snapshot, tree_presentation }`:`crates/fire-models/src/topic_detail.rs` -- FFI 仍是 RPC 目录:`FireTopicsHandle::{fetch_topic_detail_page, load_more_topic_posts, like_post, create_reply, ...}`(`crates/fire-uniffi-topics/src/lib.rs`) - -缺口是 iOS 第二控制面,不是缺协议。`FireTopicDetailStore` 持有 `topicDetails`、`topicSourceSnapshots`、`topicTreePresentations`、`topicPostLookups`、`topicSourceCursorsByTopic`、窗口 / 区间 / hydration task,并自己决定重试、预取、乐观回滚、MessageBus 刷新。这违反 `docs/architecture/fire-native-architecture.md` §1.1 与 §2.4。 - -不需要新网络栈。CF 挑战与 cookie self-healing 已在 `FireNetworkLayer`(`cloudflare_challenge_handler`、`cookie_self_healing_handler`,注册入口在 `FireSessionHandle`)。话题详情不再在 Swift 里解析 `FireUniFfiError` 决定重试。 - -Android 早期阶段不改调用点。`TopicRepository.fetchTopicDetailPage` / `loadMoreTopicPosts` 与 `FireSessionStore.fetchTopicDetailPage` 继续打旧 RPC。旧 RPC 只转发 `load_topic_detail_*`,不 `open` 会话,直到两端都迁完再删。 - -主要风险:iOS 消费面一次切走 `TopicDetailState` / `TopicPostState` / `postLookup`;LoginRequired 的 headless 重登今天只从话题 store 和首页 store 进入。见 Architectural Notes。 - -## Current Surface Inventory (method-level) - -### Rust 已有,会话应吃掉而不是重写 - -| 位置 | 符号 | 归宿 | -| --- | --- | --- | -| `topics.rs` | `TopicDetailSourceSession` 及 `source_snapshot` / `merge_posts` / `recompute_loaded_state` | 留在会话私有状态。不导出 | -| `topics.rs` | `fetch_topic_detail_source_snapshot` | 会话 `open` / `reload` 的内部步骤 | -| `topics.rs` | `fetch_topic_detail_page` | 同上,含 `extend_topic_source_to_unread_root_if_needed` | -| `topics.rs` | `load_more_topic_posts` / `append_topic_detail_source` | 会话 `load_more` 与可见区预取 | -| `topics.rs` | `build_topic_tree_presentation` | 私有。树不进 UI 快照的源字段 | -| `topics.rs` | `fetch_topic_posts` / `fetch_topic_ai_summary` | 会话内部补洞与摘要 | -| `interactions/` | `like_post` / `unlike_post` -> `Option`;`toggle_post_reaction`;`create_reply`;`create_boost`;`vote_poll` | 会话命令调用。返回值不穿过 FFI 给 Swift 改帖 | -| `messagebus.rs` | `subscribe_message_bus_channel` / `unsubscribe_message_bus_channel` | 会话在 open/close 自己订阅 | -| `presence.rs` | `bootstrap_topic_reply_presence` / `update_topic_reply_presence` / `topic_reply_presence_state` | 会话内部 | -| `state_observer.rs` | `notify_session` / `notify_topic_list` / `notify_notification_center` | 不扩展。话题详情用会话级 observer | -| `network.rs` | `StaleSessionResponse`(epoch 前进后丢弃响应);CF `retry_after_cloudflare_challenge` | 会话内重试一次 `force_load`。Swift 不再看见这个错误 | - -`TopicDetailSourceQuery` 仍带 `initial_batch_size`、`load_more_batch_size`、`max_auto_batches_per_gesture`、`max_auto_posts_per_gesture`。生产路径改为常量。`tests/network.rs` 用 1/3/10 等非生产批量,见测试节。 - -常量今天分裂两处,数值已经一致,收到会话旁边: - -| 策略 | Swift 现状 | Rust 现状 | -| --- | --- | --- | -| 首批 / 续批 | `topicDetailInitialBatchSize = 40`,`topicDetailLoadMoreBatchSize = 40` | `DEFAULT_TOPIC_INITIAL_BATCH_SIZE` / `DEFAULT_TOPIC_LOAD_MORE_BATCH_SIZE` | -| 自动连批 | Swift 写死 `maxAutoBatchesPerGesture: 3`,`maxAutoPostsPerGesture: 120` | 同名 default | -| 流内预取 | `topicPostPrefetchThreshold = 10`,`topicPostForwardExpansionSize = 60`,`topicPostPageSize = 30`,`topicPostHydrationIterationLimit = 8`,debounce 120ms | 无。在 Swift `handleVisiblePostNumbersChanged` / `expandRequestedRangeIfNeeded` | -| 列表尾预取 | `fireTopicDetailShouldLoadMore` 默认 `trailingThreshold = 5` | 无 | -| 回复上下文 | `replyContextPostBatchSize = 20` | 无 | -| MessageBus 刷新 | `scheduleTopicDetailRefresh` 睡 1.5s;滚动中延期 | 无 | -| presence 心跳 | 30s | `update_topic_reply_presence` 另有服务端节流 | - -### FFI 现状 - -`FireTopicsHandle` 是无生命周期的 RPC。话题详情相关:`fetch_topic_detail_source_snapshot`、`fetch_topic_detail_page`、`load_more_topic_posts`、`fetch_topic_posts`、`fetch_topic_ai_summary`、`create_reply`、`create_boost`、`delete_boost`、`fetch_post`、`fetch_post_replies`、`fetch_post_reply_ids`、`fetch_post_reply_history`、`update_post`、`delete_post`、`recover_post`、`flag_post`、`fetch_post_action_types`、`update_topic`、`report_topic_timings`、`like_post`、`unlike_post`、`toggle_post_reaction`、`fetch_reaction_users`、`accept_solution`、`unaccept_solution`、`vote_poll`、`unvote_poll`、`vote_topic`、`unvote_topic`、`fetch_topic_voters`。 - -记录在 `fire-uniffi-topics/src/records.rs`。`TopicPostState.presentation` 已是 `Option>`(`fire-uniffi-types/src/handle.rs`,`checksum()` / `plain_text()` / `segment(i)`)。单元格不得再拿 cooked HTML。 - -全局 `StateObserver`(`fire-uniffi/src/lib.rs`)只有 `on_session_snapshot`、`on_topic_list_snapshot`、`on_notification_center_snapshot`。`fetch_topic_list` 注释写明分页结果不能广播成权威全表。话题详情禁止塞进这个 observer。 - -### iOS store:逐方法归类 - -归类:`删` = 逻辑进 Rust,方法删除。`转` = 保留,函数体变成一行命令转发。`留` = 纯 UI,不进 Rust。store 最终只留「转」和快照持有。 - -`FireTopicDetailStore.swift` - -| 方法 | 类 | -| --- | --- | -| `checksum` | 删。服务端字段的 `layout_checksum` / `interaction_checksum` 由 Rust 算。Swift builder 仍把本地 chrome 折进 layout / in-place token,不把 token 设成 Rust checksum 本身 | -| `bumpTopicCollectionRevision` / `Chrome` / `Sidecar` / `Interaction` | 删。快照带单调 revision | -| `setLoadingTopic` / `setLoadingMoreTopicPosts` / `setLoadMoreTopicPostsError` / `setLoadingTopicAiSummary` | 删 | -| `setMutatingPost` / `setSubmittingReply` / `setLoadingPostReplyContext` / `setPostReplyContextError` | 删。进快照行标志或 composer 段 | -| `setTopicPresenceUsers` / `setPendingScrollTarget` / `updateTopicErrorMessage` / `updateTopicDetailNotice` | 删 | -| `applySession` | 转。只转发两种 readiness,见「三种会话过渡」。`canReadAuthenticatedApi == true` 时直接 return,epoch 变化不在这里清快照。完整登出才 `release` 全部 owner 并清空快照。短暂未登录只取消在途 HTTP | -| `cancelInFlightFetches` | 删。`close` 取消 actor 任务 | -| `handleMessageBusStopped` | 删。bus runtime 通知内部 listener | -| `reset` | 转。`registry.close_all()` | -| `clearTopicDetailAnchor` / `clearTransientAnchor` | 转。`clear_scroll_target` | -| `markScrollTargetSatisfied` | 转。`acknowledge_scroll_target` | -| `pendingScrollTarget` / `isScrollTargetExhausted` / `topicDetail` / `topicRenderState` / `topicPostLookup` / presence 与 AI summary / notice / revision / loading / `hasMoreTopicPosts` / `isSubmittingReply` / `isMutatingPost` 全部 getter | 删。VC 读 `snapshot(for:)` | -| `canStartNextTopicSourcePageLoad` | 删 | -| `mergeReplyContextTreeRows` | 删 | -| `formattedTopicIDs` | 删 | -| `renderStateCoversRowInputs` | 删 | -| `elapsedMilliseconds` | 留在 VC 诊断,从 store 挪走 | -| `snapshotByAppending` / `cookedByteCount` / `hydrateRequestedRange` | 删 | -| `nextDirectionalSearchRange` / `previousDirectionalSearchRange` / `nextForwardSearchRange` | 删。这是滚动锚点找流位置,不是正文搜索。调用点在 `+Load.swift` `nextRequestedRangeForUnresolvedTarget` | -| `performWithTimeout` 及文件末尾 request gate(`start` / `cancel` / `setWorkTask` / `setTimeoutTask` / `finish`) | 删。超时是会话常量 | - -`FireTopicDetailStore+Load.swift` - -| 方法 | 类 | -| --- | --- | -| `loadTopicDetail` | 转。`open` 或已打开时 `reload` | -| `fetchTopicDetailPagePayload` | 删。含 `performWithCloudflareRecovery`、`StaleSessionResponse` 循环、`attemptReadPathLoginRecovery`、批量参数 | -| `detailContainsPostNumber` | 删 | -| `rememberTopicRecoverySlug` / `bestKnownTopicRecoverySlug` / `topicCloudflareRecoveryURL` | 删。slug 作为 `open` 入参,供首包前的 CF URL;header 到达后以 header.slug 为准。URL 由网络层按现有 foreground 请求构造 | -| `synthesizedTopicDetail` / `prepareTopicDetailPagePayload` | 删。禁止再把 source+tree 合成 `TopicDetailState` | -| `applyTopicDetailPagePayload` | 删。今天第 318 行 `appViewModel.patchHomeTopicCounts(from:)` 改由快照上的窄 patch 触发 | -| `loadNextTopicSourcePage` / `enqueueNextTopicSourcePageLoad` | 删 | -| `loadMoreTopicPostsIfNeeded` | 转。只服务用户点「加载更多」/ 失败 footer 重试。阈值预取删除 | -| `handleVisiblePostNumbersChanged` | 转。`note_visible_posts` | -| `needsAnchoredReload` / `prepareTopicDetail` / `cacheTopicDetail` / `setTopicDetail` / `rebuildTopicDetail` | 删 | -| `buildTopicDetailRenderUpdate` / `applyTopicDetailRenderUpdate` / `scheduleTopicRenderCacheUpdate` / `applyTopicRenderCache` / `applyTopicDetail` | 删。渲染缓存改读 `RenderDocumentHandle` | -| `reloadTopicAiSummary` | 转。`reload_ai_summary` | -| `loadTopicAiSummaryIfNeeded` | 删。`summarizable` 后会话自己拉 | -| `prehydrateAnchoredContextBeforeDisplayIfNeeded` / `expandRequestedRangeIfNeeded` / `hydrateTopicPostsToTargetIfNeeded` / `advanceRequestedRangeTowardPendingScrollTargetIfNeeded` / `loadedPostNumbers` / `applyHydratedTopicPostsIfNeeded` / `hasMissingPostsInRequestedRange` / `refreshTopicWindowState` / `resolvedTopicWindowState` / `resolveRequestedRange` / `clampedRequestedRange` / `streamIndex` / `scrollTargetIsExhausted` / `nextRequestedRangeForUnresolvedTarget` / `initialRequestedRange` / `expandedRequestedRange` / `boundedRequestedRange` | 删 | - -`FireTopicDetailStore+Mutations.swift` - -| 方法 | 类 | -| --- | --- | -| `submitReply` / `createBoost` / `updatePost` / `deletePost` / `recoverPost` / `flagPost` / `votePoll` / `unvotePoll` | 转。不返回 `TopicPostState` 给调用方改树。`updatePost` 今天返回帖,改为 `async throws`,编辑器预填走 `prepare_edit` | -| `loadPostActionTypesIfNeeded` | 转。`ensure_flag_types`。目录进快照 `flag_types`,store 不再缓存 | -| `loadPostReplyContextIfNeeded` | 转。`load_reply_context` | -| `applyReplyContextRowsIfPossible` / `fetchReplyContextReplies` / `orderedUniquePostIDs` | 删 | -| `performPostManagementMutation` / `refreshTopicDetailAfterMutation` / `refreshTopicDetailPageFromNetwork` | 删 | -| `applyCreatedBoost` / `applyCreatedReply` | 删 | - -`FireTopicDetailStore+Presence.swift` - -| 方法 | 类 | -| --- | --- | -| `beginTopicDetailLifecycle` | 转。并入 `open` 的 owner token | -| `endTopicDetailLifecycle` | 转。`close`。不再因首页行可见而保留详情(见 Key Decisions) | -| `pruneInactiveTopicDetailState`(两个)/ `retainedTopicDetailIDs` / `evictTopicDetailState` | 删。refcount 替代 | -| `maintainTopicDetailSubscription` | 删。订阅频道与今天 iOS 一致:`/topic/{id}`、`/topic/{id}/reactions`、`/polls/{id}`、`/presence/discourse-presence/reply/{id}`(`FireSessionStore.subscribeTopic*`) | -| `handleMessageBusEvent` | 删。`FireAppViewModel.handleMessageBusEvent` 不再把 `.topicDetail` / `.topicReaction` / `.presence` 转给 topic store。聊天分支不动 | -| `setTopicDetailScrollInteractionActive` | 转。`note_scroll_interaction` | -| `beginTopicReplyPresence` / `endTopicReplyPresence` | 转。`begin_reply_typing` / `end_reply_typing` | -| `scheduleTopicDetailRefresh` / `refreshTopicDetailFromMessageBus` / `refreshTopicPresenceState` / `applyTopicPresenceState` / `activeAnchorPostNumber` | 删 | - -`FireTopicDetailStore+Reactions.swift` - -| 方法 | 类 | -| --- | --- | -| `setPostLiked` / `togglePostReaction` | 转 | -| `captureReactionSnapshot` / `restoreReactionSnapshot` / `applyOptimisticReactionChange` / `adjustCount` / `applyPostReactionUpdate` | 删 | - -### 留在 VC / cell 的 UI 状态(不进 store,不进 Rust) - -`expandedPostTextIDs`、`expandedReplyRootPostIDs`、`expandedReactionPickerPostIDs`、composer draft / `composerContext` / `quickReplyError`、`isTopicAiSummaryExpanded`、键盘、搜索高亮、滚动偏移、cell 本地 overflow(`docs/architecture/2026-09-19-ios-topic-detail-local-updates.md`)。三档 Texture 管道留在 Swift。Rust checksum 只覆盖服务端字段。builder 仍把展开、搜索高亮等本地 chrome 折进 layout / in-place token。 - -### UI 消费点(本设计要改输入,不改管道语义) - -| 文件 | 今天读什么 | 之后 | -| --- | --- | --- | -| `FireTopicDetailViewController` `buildCurrentFeedState` / `Chrome` / `Composer` / `Sidecar` / `Interaction` / `PageState` / `buildRuntimeConfiguration` | `TopicDetailState`、`postLookup`、store revision | 快照段 + VC 本地 chrome | -| `FireTopicDetailPageState.swift` | 同上 | 重写成快照视图,不再嵌 `TopicDetailState` | -| `FireTopicDetailFeedModels.swift` | `FireTopicDetailRuntimePostContext.post: TopicPostState` | 行 DTO | -| `FireTopicDetailRuntimeSnapshotBuilder` | detail + renderState + lookup | 快照行 + 本地展开集合 | -| `FireTopicDetailFeedUpdatePipeline` | `invalidationToken` / `postLayoutContentToken` / `postContentToken` | 三档规则不变。Rust checksum 只是 builder 的输入之一。禁止 `contentToken = layout_checksum` | -| `FireTopicDetailPaginationCoordinator` | `fireTopicDetailShouldLoadMore` 用过滤后的 item 下标,默认尾阈值 5 | 协调器只上报 `note_filtered_feed_tail(itemCount, visibleMaxItem)`。比较进 Rust。footer 重试仍 `load_more`。删掉 Swift 里的第二份阈值 | -| `FireTopicDetailVisibilityCoordinator` | 240ms 合并可见楼层号 | 留。只调 `note_visible_posts`。120ms 产品 debounce 进 Rust,240ms 仍是 UI 合并 | -| `Controller/` 下 toolbar / interaction / search / modal | 读 store 帖 | 读快照行。搜索只扫已加载行的 `plain_text()` | -| `FireTopicInteractionService` | 赞/表情/投票走 store;`voteTopic`、书签、通知级别、timings 直接打 session store 再 `refreshTopicDetailAfterMutation` | 话题详情屏幕上的写操作全部走 store 转发。`fetchReactionUsers` / `fetchTopicVoters` 仍是一次性拉取,不进帖树 | -| `FireAppViewModel.submitReply` / `updatePost` | 已转发 store | 保持转发,签名去掉返回帖 | -| `FireRootCoordinator` | 拥有唯一生产 store(约第 95 行) | 仍是唯一 store | - -额外 `FireTopicDetailStore(appViewModel:)` 构造(必须改成拿 root store,否则会再开一套会话): - -- `FireAppRouteDestinationView.swift` -- `FirePublicProfileView.swift` -- `FireFollowListViewController.swift` -- `FireProfileActivityTimelineView.swift` -- `FireProfileView.swift` -- 单测里的临时 store 改为注入 snapshot fixture,不拉网 - -### 首页行补丁(唯一允许碰首页的点) - -调用链今天是: - -1. `FireTopicDetailStore.applyTopicDetailPagePayload` 与 `+Mutations` 刷新成功后调 `FireAppViewModel.patchHomeTopicCounts(from: TopicDetailState)`(`FireAppViewModel.swift` 约 791 行) -2. `FireHomeFeedStore.patchTopicCounts` -> `patchedTopicRow(_:from:)`(`FireHomeFeedStore.swift` 98–209 行) - -公式:帖数 / 回复数 / 浏览 / `lastRead` / `highest` 覆盖;`lastRead == nil` 时保留原 `hasUnreadPosts`;`lastRead >= highest` 时未读与新帖数清零;否则保留原 `unreadPosts` / `newPosts` 且 `hasUnreadPosts = true`。没有从 stream 重算未读。 - -Rust 没有对应方法。`notify_topic_list` 推的是整表 `TopicListResponse`,不能用于单行。设计只加窄 patch,不改首页分页。 - -### Android(本阶段只保证能编过) - -`TopicDetailViewModel.loadTopicDetail` -> `fetchTopicDetailPagePayload` -> `TopicRepository.fetchTopicDetailPage` -> `FireSessionStore.fetchTopicDetailPage` -> `core.topics().fetchTopicDetailPage`。`loadMorePosts` 同理走 `loadMoreTopicPosts(cursor)`。这些签名在删除 PR 之前保持。 - -## Design - -### 决策 - -1. 一个话题一个 `TopicDetailSession`。`open` / 命令 / `close`。不是 `FireTopicsHandle` 上再堆 HTTP。 -2. Registry 挂在 `FireCore`,key = topic id。`open` 按 owner token 引用计数,同一 token 再 open 是替换 observer。`release(topic_id, owner_token)` 只卸该 owner。最后一人离开才拆会话。 -3. 命令进,不可变 `TopicDetailUiSnapshot` 出。后台刷新推同一类型。Swift 不保留第二份 source / tree / post 字典。 -4. UniFFI 只做 `into_core` / `from_core`、错误映射、panic 边界。业务分支不进 `fire-uniffi-topics`。 -5. 不新增「请宿主决定下一步」回调。平台能力继续用 session 通道已有的 CF / cookie hook。 -6. 不复制 Kyc:无逐帧同步 tick、无专用会话线程、不在 UI 线程等 HTTP。Kyc 的 `cfg(target_os)` 主要是 JNI、日志和 vendor 绑定,不是产品语义开关。话题详情不按 `target_os` 分产品行为。 -7. Actor 跑在现有 tokio(`run_on_ffi_runtime` 那套),每会话一个 task + `mpsc`。HTTP 在 actor 内 await。observer 在放下锁之后调用,`catch_unwind`,不 debounce 点赞。 -8. 新会话 API 不收批量参数。actor 用常量组 query。旧 RPC 在删除前仍把宿主 query 的批量原样交给同一个 `load_topic_detail_page`。 -9. 旧 RPC 在删除前只转发 `load_topic_detail_page` / `load_topic_detail_source_snapshot` / `load_more_topic_detail_posts`,不进 `Registry.open`。无 observer、无 MessageBus 订阅、无预取、无 owner。Android 行为不变。 -10. 首页只收窄计数 patch。不调用 `notify_topic_list`。 - -### 不复制的 Kyc 形状 - -要的:`FaceVerifySession` 的生命周期对象;`Ffi*::into_core` / `from_core`;`docs/ARCHITECTURE.md`「接口层只做 ABI」;壳(`FacePipelineController` / `FaceSessionHost`)投影 tick、不拥有 login/compare。话题详情里壳只投影快照、上报可见楼层与生命周期。 - -不要的:`process_frame` -> `FrameTick` 同步回路;`facelight-session` 专用线程;把平台绑定用的 `cfg(target_os)` 拿来切产品语义。Fire 这边不新增这种分叉。 - -### 模块 - -```text -fire-models/src/topic_detail_ui.rs UI 投影,无逻辑 -fire-core/src/core/topic_detail/ 会话、registry、命令 -fire-core/src/core/topic_detail/project/ source+tree -> UI 快照投影 -fire-uniffi-topics/src/session.rs Handle + observer 适配 -fire-uniffi-topics/src/records.rs from_core 记录 -``` - -`topics.rs` 里的 source session 原样搬进会话文件(或留在 `topics.rs` 作为 `pub(crate)`)。`FireCore.topic_detail_source` 从 `core/mod.rs` 移除,改成: - -```rust -topic_detail_sessions: Arc, -``` - -`FireCore::fetch_topic_detail_page` 等公开方法保留为兼容包装,内部调用 `load_topic_detail_page` / `load_more_topic_detail_posts`。不另写一套。 - -### 生命周期与调用 - -```text -VC appear - | - v -Store.open(id, owner, slug, target, bypass) 1 line - | - v -FireTopicsHandle.open_topic_detail - | - v -Registry.open(topic_id, owner, observer) - | - +-- same owner token --> replace that observer - | - +-- other owners exist --> fan-out current snapshot - | - +-- new session --> spawn actor on shared tokio - | - v - same path as fetch_topic_detail_page - source session + tree + unread-root seek - | - v - project TopicDetailUiSnapshot - | - v - observer.on_snapshot not on UI thread - | - v - Store.snapshots[id] = snap - | - v - VC: rows + local chrome - Texture 3-tier pipeline -``` - -`open` 立即返回 handle。第一帧可以是 `phase = loading`。缓存短路只属于 `open`,而且只在调用方没要求绕过缓存、并且已有 source 已经包含目标楼时:重推快照,不打网。这对应今天 `loadTopicDetail` 里 `!force` 且 source 已覆盖目标就 return(`+Load.swift` 33–41 行)。`bypass_cache == false` 才走这条。`force_load` 是另一位,只进服务端 query,不决定要不要打网。 - -```text -VC tap like / reply / load-more - | - v -Store command 1 line, no post merge - | - v -session mpsc - | - +-- optimistic write posts_by_id - +-- push snapshot (interaction or collection rev) - +-- HTTP via existing FireCore methods - | ok -> reconcile, push - | err -> rollback, push, surface error - v -observer - | - v -pipeline reads checksums, does not patch posts -``` - -```text -MessageBus poll loop, each message - | - +-- read live listener list not the list at start - | - +-- host UnboundedSender home / chat / notif - | - v -TopicDetailSession - TopicDetail | TopicReaction: - scrolling -> defer - else sleep 1.5s, reload track_visit=false - TopicDetail + detail_event_type polls: - same refresh path, no new kind - Presence: - typing users onto snapshot -``` - -`FireMessageBusRuntime` 只有一个在 `start_message_bus` 时放进 `MessageBusPollContext` 的 `event_sender`。内部 listener 必须在每条消息上从 runtime 现读,不能在 start 时拷走。`add_internal_listener` / `remove_internal_listener` 不替换 host sender。`stop_message_bus` 通知 listener;会话若仍有 owner,bus 再次 start 后重订阅。频道与 last id 保持 `FireSessionStore.subscribeTopicDetailChannel`:detail 用 header `message_bus_last_id`,reactions 为 nil,polls 为 0,scope transient。 - -没有 `MessageBusEventKind::Polls`。`/polls/{id}` 在 `messagebus.rs` 里是 `TopicDetail` 且 `detail_event_type == "polls"`。监听这个组合,或频道前缀 `/polls/`,不要新枚举。 - -```text -header counts changed - | - v -FireCore::patch_cached_home_topic_counts - read cached row if present - do not call notify_topic_list - | - v -snapshot.home_row_patch: Option<...> - | - v -FireHomeFeedStore.applyHomeRowCountPatch - assign fields only -``` - -未读决策在 Rust,照抄 `patchedTopicRow`,不从 stream 重算: - -```rust -pub enum TopicHomeUnreadDecision { - /// last_read is None. Do not compare post numbers in Swift. - /// If row.hasUnreadPosts: keep unreadPosts and newPosts. - /// If !row.hasUnreadPosts: zero both. Leave the flag as it is. - WhenLastReadMissing, - /// last_read >= highest. Zero both counts. hasUnreadPosts = false. - CaughtUp, - /// last_read < highest. Keep both counts. hasUnreadPosts = true. - StillUnread, -} -``` - -这是 `patchedTopicRow`(`FireHomeFeedStore.swift` 105–109 行)的原公式。`lastRead == nil` 时用行上已有的 `hasUnreadPosts`,为 false 则清零,不是「两个计数字段都不动」。`lastRead < highest` 的比较只在 Rust。patch 结构体没有 `like_count`:`patchedTopicRow` 不写 `likeCount`。 - -只在 header 的 `posts_count` / `reply_count` / `views` / `last_read_post_number` / `highest_post_number` 或上述未读结果会改变该行时设置 `home_row_patch`。只改赞的 generation 为 `None`,不写磁盘。 - -内存行:`FireHomeFeedStore.applyHomeRowCountPatch` 按三态赋值。话题不在 `topicEntities` 则 no-op。 - -磁盘(今天的 `patchTopicCounts` 不写磁盘,这是新增,范围写死):`FireCore::patch_cached_home_topic_counts` 的键是 `current_auth_scope_hash()` 加上 `topic_list_cache_scope_key(&self.current_home_topic_list_query())`。`HomeTopicListScope` 不是这个字符串。`FireStore` 增加 `topic_list_cache_list_pages(auth_scope_hash, scope_key) -> Vec<(u32, String)>`,只列这一对键下的页。命中后同时改两处,禁止调用 `topic_row_from_topic`(它把 `has_unread_posts` 写成 `unread_posts > 0`,和 `patchedTopicRow` 不一致): - -- `topics[]` 里匹配的 `TopicSummary`:`posts_count`、`reply_count`、`views`、`last_read_post_number`、`highest_post_number`、`unread_posts`、`new_posts`。`TopicSummary` 没有 `has_unread_posts`。 -- `rows[]` 里匹配的 `TopicRow`:嵌套 `topic` 的同一组计数字段,加上行自己的 `has_unread_posts`。`WhenLastReadMissing` 读的是这个 `TopicRow.has_unread_posts`,不是 summary。 - -写回用 `topic_list_cache_write`,键不变。不调用 `notify_topic_list`。不扫其它 scope。 - -PR-B 删除 `patchedTopicRow` 和 `patchTopicCounts`。`FireTopicListMessageBusRefreshTests` 改断言 `applyHomeRowCountPatch`。未读三态的单元测试放在 Rust,Swift 不再留第二份公式。 - -### Core 类型 - -```rust -// fire-core/src/core/topic_detail_session.rs - -pub const TOPIC_DETAIL_INITIAL_BATCH: u16 = 40; -pub const TOPIC_DETAIL_LOAD_MORE_BATCH: u16 = 40; -pub const TOPIC_DETAIL_MAX_AUTO_BATCHES: u8 = 3; -pub const TOPIC_DETAIL_MAX_AUTO_POSTS: u16 = 120; -pub const TOPIC_DETAIL_PREFETCH_THRESHOLD: u32 = 10; -pub const TOPIC_DETAIL_FORWARD_EXPANSION: u32 = 60; -pub const TOPIC_DETAIL_HYDRATION_PAGE: usize = 30; -pub const TOPIC_DETAIL_HYDRATION_ITERS: u8 = 8; -pub const TOPIC_DETAIL_VISIBLE_DEBOUNCE: Duration = Duration::from_millis(120); -pub const TOPIC_DETAIL_LIST_TAIL_THRESHOLD: u32 = 5; -pub const TOPIC_DETAIL_REPLY_CONTEXT_BATCH: usize = 20; -pub const TOPIC_DETAIL_REFRESH_DEBOUNCE: Duration = Duration::from_millis(1500); -pub const TOPIC_DETAIL_PRESENCE_HEARTBEAT: Duration = Duration::from_secs(30); -pub const TOPIC_DETAIL_REQUEST_TIMEOUT: Duration = Duration::from_secs(30); - -pub struct TopicDetailOpenRequest { - pub topic_id: u64, - pub owner_token: String, - pub slug_hint: Option, - pub target_post_number: Option, - /// Local cache bypass for `open` only. Not the server query bit. - pub bypass_cache: bool, - /// `TopicDetailSourceQuery.force_load`. Does not decide whether to skip HTTP. - pub force_load: bool, - pub track_visit: bool, - pub allow_suggested_unread_root: bool, -} - -pub trait TopicDetailObserver: Send + Sync { - fn on_snapshot(&self, snapshot: TopicDetailUiSnapshot); -} - -impl TopicDetailSessionRegistry { - pub fn open( - &self, - request: TopicDetailOpenRequest, - observer: Arc, - ) -> Arc; - /// Drops only this owner and its observer. Last owner unsubscribes, - /// cancels tasks, and removes the session. Same token re-open replaces - /// the observer; it does not append a second one. - pub fn release(&self, topic_id: u64, owner_token: &str); - pub fn close_all(&self); - /// Transient unauth. Cancels actor HTTP. Keeps owners and the last Ready snapshot. - pub fn cancel_inflight_http(&self); -} - -impl TopicDetailSession { - pub fn release_owner(&self, owner_token: &str); - /// Always HTTP. No cache short-circuit. `force_load` is only the server query bit. - pub fn reload( - &self, - target_post_number: Option, - force_load: bool, - track_visit: bool, - allow_suggested_unread_root: bool, - ); - pub fn load_more(&self); - pub fn note_visible_posts(&self, post_numbers: Vec); - pub fn note_filtered_feed_tail(&self, item_count: u32, visible_max_item: Option); - pub fn note_scroll_interaction(&self, active: bool); - pub fn acknowledge_scroll_target(&self, post_number: u32); - pub fn clear_scroll_target(&self); - pub fn begin_reply_typing(&self); - pub fn end_reply_typing(&self); - pub fn reload_ai_summary(&self, skip_age_check: bool); - pub fn load_reply_context(&self, post_id: u64); - pub async fn prepare_edit(&self, post_id: u64) -> Result; - pub async fn ensure_flag_types(&self) -> Result<(), FireCoreError>; - pub async fn submit_reply( - &self, - raw: String, - reply_to_post_number: Option, - scroll_to_created: bool, - ) -> Result<(), FireCoreError>; - pub async fn create_boost(&self, post_id: u64, raw: String) -> Result<(), FireCoreError>; - pub async fn delete_boost(&self, post_id: u64, boost_id: u64) -> Result<(), FireCoreError>; - pub async fn update_post( - &self, - post_id: u64, - raw: String, - edit_reason: Option, - ) -> Result<(), FireCoreError>; - pub async fn delete_post(&self, post_id: u64) -> Result<(), FireCoreError>; - pub async fn recover_post(&self, post_id: u64) -> Result<(), FireCoreError>; - pub async fn flag_post( - &self, - post_id: u64, - flag_type_id: u32, - message: Option, - ) -> Result<(), FireCoreError>; - pub async fn set_liked(&self, post_id: u64, liked: bool) -> Result<(), FireCoreError>; - pub async fn toggle_reaction( - &self, - post_id: u64, - reaction_id: String, - ) -> Result<(), FireCoreError>; - pub async fn vote_poll( - &self, - post_id: u64, - poll_name: String, - options: Vec, - ) -> Result<(), FireCoreError>; - pub async fn unvote_poll( - &self, - post_id: u64, - poll_name: String, - ) -> Result<(), FireCoreError>; - pub async fn vote_topic(&self, voted: bool) -> Result<(), FireCoreError>; - pub async fn accept_solution(&self, post_id: u64, accepted: bool) -> Result<(), FireCoreError>; - pub async fn create_bookmark( - &self, - bookmarkable_id: u64, - bookmarkable_type: String, - name: Option, - reminder_at: Option, - auto_delete_preference: Option, - ) -> Result<(), FireCoreError>; - pub async fn update_bookmark( - &self, - bookmark_id: u64, - name: Option, - reminder_at: Option, - auto_delete_preference: Option, - ) -> Result<(), FireCoreError>; - pub async fn delete_bookmark(&self, bookmark_id: u64) -> Result<(), FireCoreError>; - pub async fn set_notification_level(&self, level: i32) -> Result<(), FireCoreError>; - pub async fn update_topic( - &self, - title: String, - category_id: u64, - tags: Vec, - ) -> Result<(), FireCoreError>; - pub async fn report_timings(&self, topic_time_ms: u32, timings: Vec) -> Result; -} - -``` - -唯一的拉页实现(不是 `cfg(test)`,actor、兼容 RPC、测试共用): - -```rust -pub(crate) async fn load_topic_detail_source_snapshot( - core: &FireCore, - query: TopicDetailSourceQuery, -) -> Result; - -pub(crate) async fn load_topic_detail_page( - core: &FireCore, - query: TopicDetailSourceQuery, -) -> Result; - -pub(crate) async fn load_more_topic_detail_posts( - core: &FireCore, - query: LoadMoreTopicPostsQuery, -) -> Result; -``` - -`FireCore::fetch_topic_detail_source_snapshot` / `fetch_topic_detail_page` / `load_more_topic_posts` 只转发这三个函数。兼容路径无 observer、无 MessageBus 订阅、无预取任务、无 owner。它写入的 `TopicDetailSourceSession` 就是 `load_more` 用 `(topic_id, session_id)` 查找的那张表(今天的 `FireTopicDetailSourceRuntime.sessions_by_topic_id`)。query 上的 `initial_batch_size`、`load_more_batch_size`、`max_auto_*`、`force_load`、`track_visit`、`allow_suggested_unread_root`、`target_post_number` 原样生效。Android `TopicRepository` 仍传 40/40/3/120,运行时行为不变。actor 自己组 query:批量用会话常量,访问与未读根用 open/reload 契约,不读 Swift 传来的批量。 - -`prepare_edit` 是唯一允许的拉取:编辑器要预填 raw,raw 不是 cell 的 cooked HTML。读会话里已有 `TopicPost.raw`,没有再走现有 `fetch_post`。Swift 把字符串放进编辑草稿(本地 chrome),不写回行字典。 - -空正文拒绝在 Rust 再做一次(`FireCoreError`),Swift composer 仍可在点击前本地拦住。这是守卫,不是两套分页策略。 - -写命令 `async` 只为让 composer 拿到 `quickReplyError`。成功路径不返回帖。点赞在 HTTP 前推乐观快照。回复和 boost 不插占位行,见「回复插入与 boost」。`like` 无 body 时与今天一样:有 `PostReactionUpdate` 就覆盖,没有就在会话内再拉一页(`track_visit = false`),Swift 不参与。 - -`create_bookmark` 包装 `FireCore::create_bookmark`(`interactions.rs`),`bookmarkable_type` 为 `"Topic"` 或 `"Post"`,保留 `auto_delete_preference`。成功后把返回的 bookmark id 写到 header(话题)或行(帖)。话题书签抬 `chrome_revision`。帖书签改行上的 bookmark 字段,从而改变 `interaction_checksum`(`postContentToken` 收录 bookmark,`postLayoutContentToken` 不收录)。`update_bookmark` / `delete_bookmark` 同样包装现有函数。没有 `TopicBookmarkTarget`,也没有单独的 `clear_bookmark`。 - -`update_topic` 成功后更新 chrome 的 title / category / tags 并抬 `chrome_revision`。计数 patch 不带标题、分类、标签、摘要。Swift `FireAppViewModel.updateTopic` 在命令返回后仍调用现有 `refreshHomeFeedIfPossible(force: true)`。excerpt 在这次首页刷新返回前保持旧值,这是有意的。`delete_post` / `recover_post` / `flag_post` / `update_post` 的 Swift 转发在成功后仍调用现有 `refreshHomeFeedIfPossible(force: false)`,对齐 `performPostManagementMutation`。会话同时在 header 计数变化时发 home patch。 - -`bypass_cache` 与 `force_load` 分开,不从其中一个推断另一个。缓存短路只在 `open`,而且只在 `bypass_cache == false` 且已有 source 已包含目标楼时:重推快照,不打网。`reload` 永远打 HTTP。对账、MessageBus、书签、通知级别、帖子编辑器、改话题用的 reload 固定 `force_load = false`,`track_visit = false`,`allow_suggested_unread_root = false`。`reload_ai_summary` 不走这次 reload。Android 兼容 RPC 把 query 的 `force_load`、`track_visit`、`allow_suggested_unread_root` 原样传入 `load_topic_detail_page`,没有 `open` 的缓存短路。 - -调用点不再写 `loadTopicDetail(force:)`。三位是: - -| 调用 | bypass_cache | force_load | track_visit | -| --- | --- | --- | --- | -| 首次 `open`,调用方 force == false(`viewDidAppear` 那条 `loadTopicDetail`) | false | false(仅当这次真的打网) | true | -| 下拉刷新 `performRefresh` | true | true | true | -| 信息流错误重试 `onLoadTopicDetail`(`FireTopicDetailFeedCellFactory` 的重试按钮) | true | true | true | -| Android `TopicDetailViewModel.loadTopicDetail` → `open` | true | true | true | - -`allow_suggested_unread_root` 不在这张表里单独发明:iOS 仍是「无目标且没有 Ready 快照」。Android 保持今天的 `targetPostNumber == null && _detail.value == null`,不改。下拉刷新和错误重试的 `track_visit = true` 是有意的,和删掉的编辑器保存不同。这两处用同一个 owner 再 `open`,不是 `reload`,这样 `bypass_cache` 才存在。 - -`openAdvancedComposer` 与 `openQuoteComposer` 的 `onReplySubmitted` 不再 `loadTopicDetail`。`submit_reply` 已经用 `force_load = false`、`track_visit = false` 对账。引用回复传 `scroll_to_created = true`:会话把 `create_reply` 返回帖的 `post_number` 写成 `scroll_target`。这替换今天 `openQuoteComposer` 里跳到被引用帖 `post.postNumber` 的行为。高级回复传 `scroll_to_created = false`。 - -`report_timings` 不改变快照结构。失败吞掉并返回 `false`,对齐 `FireTopicInteractionService.reportTopicTimings`。 - -### 快照(UI 投影) - -`fire-models` 新文件。不含 `raw_stream_ids`、`TopicSourceCursor`、`loaded_ranges`、cooked `String`。 - -```rust -pub struct TopicDetailUiSnapshot { - pub topic_id: u64, - pub generation: u64, - pub phase: TopicDetailPhase, // Loading | Ready | Failed - pub load_error: Option, - pub notice: Option, - pub has_more: bool, - pub is_loading_more: bool, - pub load_more_error: Option, - pub scroll_target_post_number: Option, - pub collection_revision: u64, - pub chrome_revision: u64, - pub sidecar_revision: u64, - pub interaction_revision: u64, - pub chrome: TopicDetailChrome, - pub composer: TopicDetailComposerModel, - pub sidecar: TopicDetailSidecarModel, - pub rows: Vec, - pub focused_reply_context: Option, - pub flag_types: Vec, - pub home_row_patch: Option, -} - -pub struct TopicDetailUiRow { - pub post_id: u64, - pub post_number: u32, - pub root_post_number: u32, - pub parent_post_number: Option, - pub depth: u16, - pub has_children: bool, - pub is_last_sibling: bool, - pub descendant_count: u32, - pub author: TopicDetailAuthorDisplay, - pub presentation: AttachedPresentation, // FFI 层换成 RenderDocumentHandle - pub layout_checksum: u64, - pub interaction_checksum: u64, - pub created_at: Option, - pub reply_count: u32, - pub reply_to_username: Option, - pub like_count: u32, - pub reactions: Vec, - pub current_reaction_id: Option, - pub polls: Vec, - pub boosts: Vec, - pub accepted_answer: bool, - pub can_accept_answer: bool, - pub can_unaccept_answer: bool, - pub can_edit: bool, - pub can_delete: bool, - pub can_recover: bool, - pub can_boost: bool, - pub bookmarked: bool, - pub bookmark_id: Option, - pub hidden: bool, - pub is_mutating: bool, - pub is_loading_reply_context: bool, - pub is_original_post: bool, -} - -pub struct TopicDetailReactionChip { - pub id: String, - pub count: u32, - pub selected: bool, -} - -pub struct TopicHomeRowCountPatch { - pub topic_id: u64, - pub posts_count: u32, - pub reply_count: u32, - pub views: u32, - pub last_read_post_number: Option, - pub highest_post_number: u32, - pub unread: TopicHomeUnreadDecision, -} -``` - -没有 `like_count`。`patchedTopicRow` 不拷贝它。 - -### 嵌套显示结构 - -字段来自 `TopicPost`、`TopicPostAuthorMetadata`、`TopicPostBoost`、`Poll`、`TopicHeader`。boost 与正文用 `RenderDocumentHandle`,cooked 字符串不出 FFI。 - -`TopicDetailAuthorDisplay`:`username`,`name`,`avatar_template`,`user_id`,`user_title`,`primary_group_name`,`flair_url`,`flair_name`,`flair_bg_color`,`flair_color`,`flair_group_id`,`moderator`,`admin`,`group_moderator`,`user_status_emoji`,`user_status_description`。 - -`TopicDetailPollDisplay`:`id`,`name`,`kind`,`status`,`results`,`voters`,`user_votes`。选项:`id`,`html`,`plain_text`,`votes`。选项 html 是投票控件要画的,不是帖子 cooked。 - -`TopicDetailBoostDisplay`:`id`,`display_text`,`user`(`id`,`username`,`name`,`avatar_template`),`can_delete`,`can_flag`,`user_flag_status`,`available_flags`,`presentation: RenderDocumentHandle`。没有 `cooked`。 - -`TopicDetailChrome`:`title`,`slug`,`archetype`,`bookmarked`,`bookmark_id`,`bookmark_name`,`bookmark_reminder_at`,`notification_level`,`can_edit`,`category_id`,`tags`(`TopicTag` 的 name),`views`,`posts_count`,`reply_count`,`like_count`(话题赞,给统计行,不进首页 patch),`vote_count`,`user_voted`,`can_vote`,`has_accepted_answer`,`created_at`,`highest_post_number`,`last_read_post_number`。参与者:`user_id`,`username`,`name`。 - -`TopicDetailComposerModel`:`typing_users`(`id`,`username`,`avatar_template`),`is_submitting`。没有草稿、没有最短回复长度、没有 `canWrite`。 - -`TopicDetailSidecarModel`:`summarized_text`,`algorithm`,`outdated`,`can_regenerate`,`new_posts_since_summary`,`updated_at`,`is_loading`,`error`。没有 `isTopicAiSummaryExpanded`。 - -`TopicDetailReplyContext`:`root_post_id`,已并入主行的 `appended_post_ids`,`history_rows: Vec`。 - -行上另外要有:`updated_at`,`post_type`,`reply_to_user`(`username`,`name`,`avatar_template`),`bookmark_name`,`bookmark_reminder_at`。`can_boost` 已在行上。 - -VC 继续从 `SessionState` 读,不拷进话题快照,也不要在改 builder 时删掉: - -- `canWriteInteractions` = `FireAppViewModel.canStartAuthenticatedMutation` -- `baseURLString` = `session.bootstrap.baseUrl`,空则 `https://linux.do` -- `minimumReplyLength` = `FireTopicPresentation.minimumReplyLength`,私信用 `minPersonalMessagePostLength`,否则 `minPostLength` -- 是否私信线程用 chrome 的 `archetype`,经现有 `FireTopicPresentation.isPrivateMessageArchetype` - -### Checksum - -Rust 只哈希服务端字段。Swift builder 把本地 chrome 折进去。验收标准是今天的 `postLayoutContentToken`(`FireTopicDetailRuntimeSnapshotBuilder.swift` 418–430 行),字段为: - -- `post.id` -- `FirePostAuthorMetadataDisplay.contentToken` -- `renderContent?.signature.token ?? "pending"` -- `pollsContentToken` -- `FirePostBoostDisplay.contentToken`(id、用户、displayText、presentation plain text、canDelete、canFlag,不是条数) -- `String(!post.reactions.isEmpty)`(空与非空,不是完整反应列表) -- `String(replyShortcutCount != nil)` -- `String(isReplyThreadExpanded)` -- `String(isReactionPickerExpanded)` -- `String(textExpansionState.isExpanded)` -- `String(textExpansionState.isCollapsible)` - -`layout_checksum` 只覆盖其中的服务端部分:post id、作者 metadata、presentation checksum、poll token、boost token、`reactions.is_empty()`。回复快捷方式是否为 nil、回复树展开、表情条展开、正文展开,留在 Swift。 - -`interaction_checksum` 覆盖 `postContentToken` 里的服务端部分:楼层号、用户名、头像、created/updated、like count、reply count、完整反应列表(id、kind、count、can_undo)、current reaction id、accepted / can_edit / can_delete / can_recover / hidden、bookmark 三字段加 bookmarked、`is_mutating`、`is_loading_reply_context`。搜索高亮、`canWriteInteractions`、正文展开、表情条展开留在 Swift。 - -builder 组 token,而不是赋值: - -- layout token = `layout_checksum` + 上面四项本地 chrome(shortcut、回复树、表情条、正文展开) -- in-place token = `interaction_checksum` + layout token 里 Swift 已折入的本地项 + `isSearchHighlighted` + `canWriteInteractions` -- 摘要卡再把 `isTopicAiSummaryExpanded` 折进该卡的 layout token - -禁止 `contentToken = layout_checksum` 或 `inPlaceUpdateToken = interaction_checksum`。首枚反应让 `reactions.is_empty()` 翻转,layout token 变,走可见行 relayout。之后的续赞只变 `interaction_checksum`,走 in-place。正文展开不进 `FireTopicDetailFeedInvalidationToken`(今天也没有 `expandedPostTextIDs`),靠 `applyLocalInteractionSnapshot` 里 layout token 变化 relayout。搜索高亮留在 in-place token;`activeSearchPostID` 仍在 invalidation token 上。 - -`collection_revision`:插删行、分页、首屏替换、加载/错误/has_more 变化。`interaction_revision`:只改表情或 mutating,且 layout checksum 不变。`chrome_revision`:标题、话题书签、通知级别、投票数。`sidecar_revision`:AI 摘要与 notice。展开回复树不在 Rust revision 里,VC 把 `expandedReplyRootPostIDs` 放进自己的 invalidation token,继续走 collection diff。 - -行集合是已加载树的前序,含楼主。二级楼默认隐藏仍由 Swift `makeReplyDisplayPlan` 用 `expandedReplyRootPostIDs` 过滤。Rust 不接收展开集合。 - -`focused_reply_context` 在 `load_reply_context` 后填充:已并入主行的子楼 id,加历史行(今天的 `postReplyHistoryByPostID`)。`applyReplyContextRowsIfPossible` 的并树进会话,用现有 `TopicTreeRow` 规则,不在 Swift 改 parent/depth。 - -`load_error` 枚举:`Network`、`LoginRequired`、`Unrecoverable { message }`。VC 只展示,不 `switch` 后重试。 - -### 会话私有状态 - -```rust -struct SessionInner { - source: TopicDetailSourceSession, // 现有私有结构 - tree: TopicTreePresentation, - generation: u64, - scroll_target: Option, - scroll_target_exhausted: bool, - window: TopicWindow, // 现 FireTopicDetailWindowState 的语义 - scroll_active: bool, - deferred_refresh: DeferredRefresh, // None | Pending | Ready(snapshot) - owners: HashMap>, - optimistic: HashMap, // 回滚用,不对 Swift 暴露 -} -``` - -`note_visible_posts` 在 120ms debounce 后,坐标是楼层号,不是列表下标: - -- 可见楼层距已加载窗口边 ≤ `PREFETCH_THRESHOLD`(10)时,按 `FORWARD_EXPANSION`(60)与 `HYDRATION_PAGE`(30)补 `fetch_topic_posts`,最多 `HYDRATION_ITERS`(8)。等价 `expandRequestedRangeIfNeeded` + `hydrateTopicPostsToTargetIfNeeded`。 -- 有未完成 `scroll_target` 时沿用 `nextRequestedRangeForUnresolvedTarget` 的跳转,直到命中或 `scrollTargetIsExhausted`。窗口上限仍是今天的 `FireTopicDetailWindowState.maxWindowSize`(200),私有,不进 FFI。命中前快照带 `scroll_target_post_number`。VC `acknowledge_scroll_target` 后清空。 - -`note_filtered_feed_tail` 的坐标是 `makeReplyDisplayPlan` 隐藏二级回复之后的列表下标,不是快照全序行。谓词与 `fireTopicDetailShouldLoadMore` 相同:`item_count > 0`,`visible_max_item` 为 Some,且 `item_count - visible_max_item <= 5`,并且 `has_more`。满足则跑与 `load_more_topic_posts` 相同的连批停止条件。Swift 删掉 `fireTopicDetailShouldLoadMore`,避免两份阈值。协调器只上报两个整数。 - -`load_more` 是用户点 footer 的一拍,同一停止条件,不看尾阈值。 - -### 回复插入与 boost - -`submit_reply` 不在 HTTP 前插占位行。`create_reply` 返回 `TopicPost` 之后,按 `applyCreatedReply`(`+Mutations.swift` 537–581 行): - -- id 不在 `raw_stream_ids` 则 append -- 合并进 `posts_by_id` -- `posts_count = max(old + 1, stream_len)`,`reply_count = max(old + 1, posts_count.saturating_sub(1))` -- `highest_post_number = max(highest, post_number)`,`last_read = max(last_read.unwrap_or(0), post_number)` -- 若窗口 `requested_range.upper_bound >= 插入前的 stream_len`,把上界伸到新的 stream 末尾 -- 重建树,推快照。header 计数变了才带 `home_row_patch` -- 再 `reload(target: None, force_load: false, track_visit: false, allow_suggested_unread_root: false)` 对账。这一步必须打网,不能因为帖已经在 source 里就短路。 - -`create_boost` 成功后:该 id 不在列表则 append,`can_boost = false`。boost token 变,`layout_checksum` 变,抬 `collection_revision`(高度变,不是 in-place)。然后同一套 `track_visit = false` 的 reload。 - -### 恢复 - -- CF:请求继续走 foreground profile,现有 `retry_after_cloudflare_challenge`。会话不调用 Swift。 -- cookie:现有 `cookie_self_healing_handler`。 -- `StaleSessionResponse`:再打一次 HTTP,`force_load = true`,`track_visit` 保持这次加载的原值。这是服务端 query 位,不是缓存短路。仍失败才 `load_error`。 -- `LoginRequired`:不写 `FireAuthRecoveryHint`,不发明轮换原因。`FireAuthRecoveryHintReason` 仍只有 `TOnlyRotation` 与 `ForumSessionOnlyRotation`。`runAuthenticatedWritePreflight` 的 hint epoch 判断不动。 - -唤醒字段不进持久化信封。权威副本在 `FireSessionRuntimeState`,和 `auth_recovery_hint` 一样。`SessionSnapshot` 若为了 `SessionState::from_snapshot` 带上它,必须 `#[serde(skip)]`,而且 `update_session_persistence_revisions` 比较时忽略这一字段,不能单凭它增加 `snapshot_revision`。`export_session_json` / `PersistedSessionEnvelope` 因此写不进去。`restore_session_json` 在清 `auth_recovery_hint` 的同一处把 runtime 上的请求清掉(`persistence.rs` 第 39 行旁边)。 - -```rust -pub struct ReadPathLoginRequest { - pub generation: u64, - pub operation: String, -} - -// FireSessionRuntimeState -pub(crate) read_path_login_request: Option, - -// SessionSnapshot,只出现在 notify 推出去的副本上 -#[serde(skip)] -pub read_path_login_request: Option, -``` - -`request_read_path_login(operation) -> u64` 写 runtime 字段。已有未完成的 generation 时,后来的 LoginRequired 加入这一代,不换号。`notify_session` 把该字段拷到推送副本上。`DebouncedEmitter` 仍是 100ms 取最新快照,未完成的请求留在 runtime 上,所以窗口里后到的快照仍带着它。不增加 epoch。 - -`applySession` 看到新 generation 时,不调用 `runReadPathLoginRecovery`。那只是 cookie 重放,没有 single-flight,也没有 headless。要跑的是 `attemptReadPathLoginRecovery` 去掉 `LoginRequired` 类型守卫之后的函数体,operation 用 `ReadPathLoginRequest.operation`: - -1. `attemptHostCookieResyncRecovery(operation:)`。同一 epoch 已有任务则 join。 -2. 只有它返回 false,才 `attemptMidSessionHeadlessReauth(operation:)`。 - -首页 store 继续自己调用带守卫的 `attemptReadPathLoginRecovery`,不改。 - -返回后 `applySession` 调 `FireSessionHandle::complete_read_path_login(generation, succeeded)`。实现在 `FireCore` 里走 registry,叫醒这一代的全部 waiter。不新增话题 observer。`succeeded == true` 时每个 waiter `reload(force_load: true, track_visit: 这次加载的原值, allow_suggested_unread_root: false)` 一次。`reload` 必打网。`succeeded == false` 时这些快照停在 `LoginRequired`,不第二次。无关 epoch 变化不触发。 - -### 三种会话过渡 - -`FireTopicDetailStore.applySession` 保留,只转发 readiness。`FireAppViewModel.applySession` 继续调用它。 - -| 过渡 | 条件 | 行为 | -| --- | --- | --- | -| 完整登出 | `!hasLoginCookie && !hasCurrentUser` | 每个 handle `close`(只释放自己的 owner)。registry 无 owner 后拆会话。Swift 清空 `snapshots` | -| 短暂不可读 | `!canReadAuthenticatedApi` 且不是完整登出 | `cancel_inflight_http`。保留 owner 和最后一帧 Ready 快照。不推空快照 | -| 读路径恢复成功 | `complete_read_path_login(succeeded: true)` | `reload(force_load: true)`,`track_visit` 不变,必打网。先不推空快照。失败则停在 `LoginRequired` | - -`canReadAuthenticatedApi == true` 时 `applySession` 立即 return。cookie / CSRF 造成的 epoch 增加不走登出分支。 - -乐观更新:`set_liked` / `toggle_reaction` 在 actor 里克隆帖、改 count 与 current reaction、推 interaction 快照、置 `is_mutating`。失败恢复克隆。成功用 `PostReactionUpdate` 覆盖。与 `applyOptimisticReactionChange` 同一规则(heart id `"heart"`,再点同一 reaction 即取消)。 - -MessageBus:`TopicDetail` 与 `TopicReaction` 走 1.5s debounce 后 `reload(target: None, force_load: false, track_visit: false, allow_suggested_unread_root: false)`,必打网。`detail_event_type == "polls"` 走同一条,不新增 kind。滚动中:请求还没结束记 `Pending`;请求已结束则把快照放进 `Ready`,对齐 `deferredTopicDetailRefreshPayloads`。`note_scroll_interaction(false)` 若是 `Ready`,直接推这帧,不再请求;若是 `Pending`,再 reload。`presence` 读 `topic_reply_presence_state`,滤掉当前用户,写入 composer。Swift 不再滤。 - -AI 摘要:首包后若 `summarizable` 且无摘要,会话调用现有 `fetch_topic_ai_summary`。loading 不抬 `collection_revision`(今天 `setLoadingTopicAiSummary` 的注释:避免空 chrome 抖动)。失败只抬 sidecar。 - -### FFI - -```rust -// fire-uniffi-topics/src/session.rs - -#[uniffi::export(with_foreign)] -pub trait TopicDetailObserver: Send + Sync { - fn on_snapshot(&self, snapshot: TopicDetailUiSnapshotState); -} - -#[derive(uniffi::Object)] -pub struct TopicDetailSessionHandle { - inner: Arc, - topic_id: u64, - owner_token: String, -} - -#[uniffi::export] -impl FireTopicsHandle { - pub fn open_topic_detail( - &self, - request: TopicDetailOpenRequestState, - observer: Arc, - ) -> Result, FireUniFfiError>; -} - -#[uniffi::export] -impl TopicDetailSessionHandle { - /// Handle stores the owner token from open. `release` calls - /// registry.release(topic_id, owner_token) for that owner only. - /// Named `release` (not `close`) so Kotlin UniFFI does not collide with `AutoCloseable.close`. - pub fn release(&self); - /// Always HTTP. `force_load` is `TopicDetailSourceQuery.force_load`, not a cache bypass. - pub fn reload( - &self, - target_post_number: Option, - force_load: bool, - track_visit: bool, - allow_suggested_unread_root: bool, - ); - pub fn load_more(&self); - pub fn note_visible_posts(&self, post_numbers: Vec); - pub fn note_filtered_feed_tail(&self, item_count: u32, visible_max_item: Option); - pub fn note_scroll_interaction(&self, active: bool); - pub fn acknowledge_scroll_target(&self, post_number: u32); - pub fn clear_scroll_target(&self); - pub fn begin_reply_typing(&self); - pub fn end_reply_typing(&self); - pub fn reload_ai_summary(&self, skip_age_check: bool); - pub fn load_reply_context(&self, post_id: u64); - pub async fn prepare_edit(&self, post_id: u64) -> Result; - pub async fn submit_reply(&self, raw: String, reply_to_post_number: Option, scroll_to_created: bool) -> Result<(), FireUniFfiError>; - pub async fn create_boost(&self, post_id: u64, raw: String) -> Result<(), FireUniFfiError>; - pub async fn delete_boost(&self, post_id: u64, boost_id: u64) -> Result<(), FireUniFfiError>; - pub async fn update_post(&self, post_id: u64, raw: String, edit_reason: Option) -> Result<(), FireUniFfiError>; - pub async fn delete_post(&self, post_id: u64) -> Result<(), FireUniFfiError>; - pub async fn recover_post(&self, post_id: u64) -> Result<(), FireUniFfiError>; - pub async fn flag_post(&self, post_id: u64, flag_type_id: u32, message: Option) -> Result<(), FireUniFfiError>; - pub async fn ensure_flag_types(&self) -> Result<(), FireUniFfiError>; - pub async fn set_liked(&self, post_id: u64, liked: bool) -> Result<(), FireUniFfiError>; - pub async fn toggle_reaction(&self, post_id: u64, reaction_id: String) -> Result<(), FireUniFfiError>; - pub async fn vote_poll(&self, post_id: u64, poll_name: String, options: Vec) -> Result<(), FireUniFfiError>; - pub async fn unvote_poll(&self, post_id: u64, poll_name: String) -> Result<(), FireUniFfiError>; - pub async fn vote_topic(&self, voted: bool) -> Result<(), FireUniFfiError>; - pub async fn accept_solution(&self, post_id: u64, accepted: bool) -> Result<(), FireUniFfiError>; - pub async fn create_bookmark(&self, bookmarkable_id: u64, bookmarkable_type: String, name: Option, reminder_at: Option, auto_delete_preference: Option) -> Result<(), FireUniFfiError>; - pub async fn update_bookmark(&self, bookmark_id: u64, name: Option, reminder_at: Option, auto_delete_preference: Option) -> Result<(), FireUniFfiError>; - pub async fn delete_bookmark(&self, bookmark_id: u64) -> Result<(), FireUniFfiError>; - pub async fn set_notification_level(&self, level: i32) -> Result<(), FireUniFfiError>; - pub async fn update_topic(&self, title: String, category_id: u64, tags: Vec) -> Result<(), FireUniFfiError>; - pub async fn report_timings(&self, topic_time_ms: u32, timings: Vec) -> Result; -} -``` - -适配器: - -```rust -struct FfiTopicDetailObserver { - inner: Arc, -} - -impl fire_core::TopicDetailObserver for FfiTopicDetailObserver { - fn on_snapshot(&self, snapshot: fire_core::TopicDetailUiSnapshot) { - self.inner.on_snapshot(TopicDetailUiSnapshotState::from_core(snapshot)); - } -} -``` - -`from_core` 只做字段拷贝,并把 `AttachedPresentation` 交给已有 `intern_presented_handle`。禁止在这里决定预取、重试、未读。 - -兼容包装(删之前): - -```rust -impl FireTopicsHandle { - pub async fn fetch_topic_detail_page(...) -> Result { - // load_topic_detail_page(query.into())。batch、force、track_visit、 - // allow_suggested_unread_root 都保留。无 observer、无订阅、无预取、无 owner。 - } - pub async fn fetch_topic_detail_source_snapshot(...) -> Result { - // load_topic_detail_source_snapshot。同一张 session 表。 - } - pub async fn load_more_topic_posts(...) -> Result { - // load_more_topic_detail_posts。cursor.session_id 必须命中刚才写入的 source session。 - } -} -``` - -`fetch_topic_posts`、`like_post` 等非详情屏幕也会用的 RPC 保持原样,直到 Android 详情不再通过它们改本地帖。详情屏幕的 iOS 路径停止调用 `fetchTopicDetailPage` / `loadMoreTopicPosts`。 - -晚到快照:`generation` 单调。Swift 丢弃更旧的 generation。 - -### Swift 之后的 store 与 VC - -```swift -@MainActor -final class FireTopicDetailStore: ObservableObject { - @Published private(set) var snapshots: [UInt64: TopicDetailUiSnapshot] = [:] - - func open(topicId: UInt64, ownerToken: String, slug: String?, targetPostNumber: UInt32?, bypassCache: Bool, forceLoad: Bool, trackVisit: Bool, allowSuggestedUnreadRoot: Bool) - func close(topicId: UInt64, ownerToken: String) - func reload(topicId: UInt64, targetPostNumber: UInt32?, forceLoad: Bool, trackVisit: Bool, allowSuggestedUnreadRoot: Bool) - func loadMore(topicId: UInt64) - func noteVisiblePosts(topicId: UInt64, postNumbers: Set) - func noteFilteredFeedTail(topicId: UInt64, itemCount: Int, visibleMaxItem: Int?) - func applySession(_ session: SessionState) - func noteScrollInteraction(topicId: UInt64, active: Bool) - func acknowledgeScrollTarget(topicId: UInt64, postNumber: UInt32) - func clearScrollTarget(topicId: UInt64) - func beginReplyTyping(topicId: UInt64) - func endReplyTyping(topicId: UInt64) async - func reloadAiSummary(topicId: UInt64, skipAgeCheck: Bool) - func loadReplyContext(topicId: UInt64, postId: UInt64) - func prepareEdit(topicId: UInt64, postId: UInt64) async throws -> String - func submitReply(topicId: UInt64, raw: String, replyToPostNumber: UInt32?, scrollToCreated: Bool) async throws - func setPostLiked(topicId: UInt64, postId: UInt64, liked: Bool) async throws - func togglePostReaction(topicId: UInt64, postId: UInt64, reactionId: String) async throws - func votePoll(topicId: UInt64, postId: UInt64, pollName: String, options: [String]) async throws - func unvotePoll(topicId: UInt64, postId: UInt64, pollName: String) async throws - func voteTopic(topicId: UInt64, voted: Bool) async throws - func updatePost(topicId: UInt64, postId: UInt64, raw: String, editReason: String?) async throws - func deletePost(topicId: UInt64, postId: UInt64) async throws - func recoverPost(topicId: UInt64, postId: UInt64) async throws - func flagPost(topicId: UInt64, postId: UInt64, flagTypeId: UInt32, message: String?) async throws - func ensureFlagTypes(topicId: UInt64) async throws - func createBookmark(topicId: UInt64, bookmarkableId: UInt64, bookmarkableType: String, name: String?, reminderAt: String?, autoDeletePreference: Int32?) async throws - func updateBookmark(topicId: UInt64, bookmarkId: UInt64, name: String?, reminderAt: String?, autoDeletePreference: Int32?) async throws - func deleteBookmark(topicId: UInt64, bookmarkId: UInt64) async throws - func setNotificationLevel(topicId: UInt64, level: Int32) async throws - func updateTopic(topicId: UInt64, title: String, categoryId: UInt64, tags: [String]) async throws - func acceptSolution(topicId: UInt64, postId: UInt64, accepted: Bool) async throws - func reportTimings(topicId: UInt64, topicTimeMs: UInt32, timings: [UInt32: UInt32]) async -> Bool - func reset() - - func snapshot(for topicId: UInt64) -> TopicDetailUiSnapshot? { snapshots[topicId] } -} - -final class FireTopicDetailSnapshotSink: TopicDetailObserver, @unchecked Sendable { - func onSnapshot(snapshot: TopicDetailUiSnapshot) { - Task { @MainActor in store.apply(snapshot) } - } -} -``` - -`apply`:若 `generation` 不旧于已应用值,替换 `snapshots[id]`;若 `homeRowPatch != nil`,调 `FireAppViewModel.applyHomeRowCountPatch`。不合并行。 - -`FireSessionStore.openTopicDetail` / `cancelTopicDetailHttp` / `closeAllTopicDetailSessions` 标为 `nonisolated`:只碰 `core` UniFFI,供 `@MainActor` 的 `FireTopicDetailStore` 同步拿到 handle,不进 session actor 队列。 - -`FireHomeFeedStore.applyHomeRowCountPatch` 替换 `patchTopicCounts`。同一 PR 删除 `patchedTopicRow` 与 `patchTopicCounts`。`FireTopicDetailModalRouter.presentBookmarkEditor` 的话题详情 `onReload` 不再调用 `loadTopicDetail`;保存和删除改走 store 的 create / update / delete bookmark。`presentTopicBookmarkEditor` / `presentPostBookmarkEditor` 同样改。 - -VC `buildCurrentFeedState` 改为读 `snapshot.rows`、`phase`、`hasMore`、`collectionRevision`、`scrollTarget`。`buildCurrentInteractionState` 只保留三个 expanded 集合。`mutating` / reply-context loading 来自行字段。`canWriteInteractions`、`baseURLString`、`minimumReplyLength` 仍从 session / bootstrap 读。Combine 从多个 revision 字典改成 `$snapshots`,用 `FireTopicDetailRevisionFingerprint`(`Equatable`)按 `collection` / `chrome` / `sidecar` / `interaction` 去重。本地展开仍走 `applyLocalInteractionSnapshot`,主线程,不经 Rust。 - -`FireTopicDetailRuntimeConfiguration` 丢掉 `detail: TopicDetailState?` 与 `postLookup`。builder 用行 DTO,再把本地 chrome 折进 token。禁止把 `contentToken` 或 `inPlaceUpdateToken` 设成裸的 Rust checksum。管道 `apply` 的三档判断不改。 - -分页协调器:`fireTopicDetailShouldLoadMore` 删除。过滤后的 `itemCount` / `visibleMaxItem` 经 `noteFilteredFeedTail` 上报。footer 仍 `loadMore`。可见楼层号仍由 `FireTopicDetailVisibilityCoordinator.publishIfChanged` 上报。 - -### 错误与线程 - -| 错误 | 会话行为 | Swift 话题详情 | -| --- | --- | --- | -| Network | 快照 `Failed` + 文案 | 展示 | -| CF challenge | 网络层已弹 WebView 并重试 | 无感知 | -| cookie healing | 网络层已重试 | 无感知 | -| StaleSessionResponse | 内部 force 再读一次 | 无感知 | -| LoginRequired | 同一代请求。成功则 `force_load` reload 一次,`track_visit` 不变 | 只展示。`applySession` 先 `attemptHostCookieResyncRecovery`,失败再 `attemptMidSessionHeadlessReauth`。不调用 `runReadPathLoginRecovery` | -| Http 429 | 网络层已退避 | 最终失败才展示 | -| 写失败 | 回滚乐观快照,`Err` 给 composer | `quickReplyError` 本地 | - -禁止在主线程 `wait` UniFFI。`open` / `note_*` / `load_more` 是同步入队。写命令的 `async` 只 await 已在 runtime 上的 actor,Swift 侧在 `Task` 里调用。 - -## Phased Implementation - -每阶段结束工作区可编译。阶段内不要长期双源。iOS 在 Android ViewModel 迁移之前达到「store 只有快照 + VC 只有本地 chrome」。 - -### Phase 1 — Rust 会话 + 兼容投影 - -新文件: - -- `crates/fire-models/src/topic_detail_ui.rs` -- `crates/fire-core/src/core/topic_detail/`(会话、registry) -- `crates/fire-core/src/core/topic_detail/project/`(source+tree -> 快照投影) -- `crates/fire-uniffi-topics/src/session.rs` - -改: - -- `fire-models/src/lib.rs` 导出新类型 -- `fire-core/src/core/mod.rs`:`topic_detail_source` 换成 `topic_detail_sessions` -- `fire-core/src/core/topics.rs`:`fetch_topic_detail_page` / `load_more_topic_posts` / `fetch_topic_detail_source_snapshot` 只转发 `load_topic_detail_*`,不调用 `Registry.open`。无 observer、无 MessageBus 订阅、无预取、无 owner -- `fire-core/src/core/messagebus.rs`:内部 listener 列表,poll 分发处(现有 host sender 旁边)再送一份 -- `FireSessionRuntimeState` 持有 `ReadPathLoginRequest`。推送用的 `SessionSnapshot` 字段 `#[serde(skip)]`,不进 `snapshot_revision`。`restore_session_json` 清掉它。`SessionState::from_snapshot` 能看见推送副本。`FireSessionHandle::complete_read_path_login` 走 registry 叫醒 waiter -- `fire-core/src/core/mod.rs`:`request_read_path_login` / `complete_read_path_login`。不碰 `FireAuthRecoveryHint` -- `fire-store`:`topic_list_cache_list_pages` -- `fire-uniffi-topics/src/lib.rs`:`open_topic_detail`。旧 `fetch_topic_detail_source_snapshot` / `fetch_topic_detail_page` / `load_more_topic_posts` 把 query 原样委托给 `load_topic_detail_*`。不忽略 batch -- `fire-uniffi-topics/src/records.rs`:`TopicDetailUiSnapshotState::from_core` 与行记录。不写分支 - -iOS / Android 调用点不动。旧 RPC 仍返回原来的记录,并且仍遵守 query 的 batch、`force_load`、`track_visit`、`allow_suggested_unread_root`。 - -测试: - -- `topics.rs` 现有树 / 游标单测保持,改 `super` 路径即可 -- `tests/network.rs` 的自定义 batch(`initial_batch_size` 10、3、1,以及 cursor `batch_size == 10`)继续打 `FireCore::fetch_topic_detail_page` / `fetch_topic_detail_source_snapshot`,因为这两个方法就是 `load_topic_detail_*`。断言不变,包括 `fetch_topic_detail_page_auto_extends_to_first_unread_root`、`skips_unread_root_auto_extend_when_not_allowed`、全部 `fetch_topic_detail_source_snapshot_*` -- 新测:同一 owner 再 open 是替换不是第二个 observer;最后 `release` 取消订阅;`note_visible_posts` 在阈值内才 append;`note_filtered_feed_tail` 用过滤后的下标;`StaleSessionResponse` 只 force 一次且 `track_visit` 不变;乐观 like 失败回滚;滚动中已完成的 reload 在松手时直接推、不再请求;`WhenLastReadMissing` 在 `has_unread == false` 时清零;compat 调用不注册 observer、不订阅 MessageBus - -`cargo test -p fire-core -p fire-uniffi-topics` 与 Android 现有编译是本阶段门槛。 - -### Phase 2 — iOS 改吃快照(一个 PR,结束时编译) - -这是行为切换。不要先留 `topicDetails` 再合成快照。 - -顺序(同一 PR): - -1. 生成 UniFFI(现有 `apps/ios-app/scripts/sync_uniffi_bindings.sh`) -2. 改 `FireTopicDetailStore` 为上一节签名。删除 `+Load` 里的合并 / 窗口 / 重试。`+Mutations` / `+Reactions` / `+Presence` 只留转发 -3. `FireTopicDetailSnapshotSink` 放在 store 文件 -4. 改 `FireTopicDetailPageState`、`FeedModels`、`RuntimeSnapshotBuilder`、`SnapshotAssembler`、`ViewController` 的 `buildCurrent*` 与 revision sink -5. `PaginationCoordinator` 改为 `noteFilteredFeedTail`;`VisibilityCoordinator` 回调改 `noteVisiblePosts`。删除 `fireTopicDetailShouldLoadMore` -6. `FireTopicInteractionService` 的话题写操作改 store 转发。`voteTopic` 不再 `refreshTopicDetailAfterMutation` -7. `FireAppViewModel.submitReply` / `updatePost` 去掉返回帖。`updateTopic` 改为会话命令,成功后仍 `refreshHomeFeedIfPossible(force: true)`,不再 `refreshTopicDetailAfterMutation`。`patchHomeTopicCounts` 改为 `applyHomeRowCountPatch`,并删除 `patchedTopicRow`。`handleMessageBusEvent` 去掉话题分支。`applySession` 看到新 generation 时先 `attemptHostCookieResyncRecovery(operation:)`,返回 false 再 `attemptMidSessionHeadlessReauth(operation:)`,然后 `complete_read_path_login`。不调用 `runReadPathLoginRecovery`。话题 store 的 `applySession` 只转发登出 / 短暂不可读 -8. `presentBookmarkEditor`、`presentTopicBookmarkEditor`、`presentPostBookmarkEditor` 的 `onReload` 不再 `loadTopicDetail`。改调 create / update / delete bookmark。`presentPostEditor` 的 `onSaved`、`presentTopicEditor` 的 `onSaved`、`updateTopicNotificationLevel` 同样禁止 `loadTopicDetail(force: true)`,改为对应会话命令。对账是命令内部的 `reload(force_load: false, track_visit: false)`,必打网。去掉今天这第二发 `trackVisit: true` 是有意的。`recoveryOriginURL` 用 `open` 已经传入的 slug,不调用删掉的 `topicCloudflareRecoveryURL` -9. `performRefresh` 与 `onLoadTopicDetail`(`FireTopicDetailFeedCellFactory` 重试)改为 `open(bypass_cache: true, force_load: true, track_visit: true)`。这次记访问是有意的。`openAdvancedComposer` / `openQuoteComposer` 的 `onReplySubmitted` 不再 `loadTopicDetail`。引用回复 `submitReply(..., scrollToCreated: true)`,由会话把新帖楼层写成 `scroll_target` -10. 六个额外 store 构造改为使用 root store。含 `FireAppRoutePresentationTests` 里的临时 store -11. 详情路径停止调用 `FireSessionStore.fetchTopicDetailPage` / `loadMoreTopicPosts` - -门槛:见 PR-B 审查清单。话题 store 不再以 `TopicDetailState` 为成员。 - -### Phase 3 — Android ViewModel(独立 PR,方法级) - -`TopicDetailViewModel.kt`: - -| 方法 | 动作 | -| --- | --- | -| `prepareForTopicLoad` | 换 topic id 时 `close` 上一个 owner,再 `open` 下一个。清本地展开与渲染缓存 | -| `loadTopicDetail` | `open(bypass_cache: true, force_load: true, track_visit: true)`。`allow_suggested_unread_root` 仍是 `targetPostNumber == null && _detail.value == null`。不要把 `bypass_cache` 留成 false,否则第二次打开会跳过今天这发 HTTP | -| `fetchTopicDetailPagePayload` / `applyFetchedPayload` / `mergeLoadMore` / `applyReactionUpdate` / `applyPollUpdate` | 删 | -| `refreshCurrentTopic` | 删。通知级别、改话题、书签、删帖、恢复改走会话命令。命令内部 `track_visit = false`、`force = false` 对账。禁止留下对 `fetchTopicDetailPage` 的调用 | -| `replacePost` | 删。乐观写入在 actor 内 | -| `maintainTopicDetailMessageBus` / `scheduleTopicDetailRefresh` / `refreshTopicDetailFromMessageBus` / `releaseTopicDetailMessageBus` / `drainDeferredMessageBusRefreshIfNeeded` | 删 | -| `loadMorePosts` / `loadMorePostsPage` | `load_more` | -| `scrollToPostWhenLoaded` / `hasLoadedPostNumber` | 删。滚动目标交给会话的窗口算法(`maxWindowSize = 200`,`nextRequestedRangeForUnresolvedTarget`)。不要在 Kotlin 再写 20 页循环(`TARGET_HYDRATION_PAGE_LIMIT`) | -| `setTopicDetailScrollInteractionActive` | `note_scroll_interaction` | -| `reloadTopicAiSummary` / `loadTopicAiSummaryIfNeeded` | 命令 / 删 | -| `toggleHeart` / `toggleReaction` / `votePoll` / `unvotePoll` / `toggleTopicVote` / `deletePost` / `recoverPost` / `updatePost` / 书签 / `setTopicNotificationLevel` / `updateTopic` | 会话命令 | -| `expandReplyThread` | 留本地 | -| `projectRows` / `postRow` / `searchMatches` / `usesBoostBarrage` | 输入改快照行。`uniqueTreeRows`、`postsById`、`postsForDetail`、`initialScrollTargetPostNumber` 删 | -| `getRenderContent` / `preloadRenderContent` | 改 `RenderDocumentHandle` | -| `onCleared` | `close`(只释放本屏 owner) | - -`TopicRepository.fetchTopicDetailPage` / `loadMoreTopicPosts` 此 PR 不再被 ViewModel 调用,方法先留着,避免别的调用点断编译。`FireSessionStore.fetchTopicDetailPage` 同理。 - -### Phase 4 — 删除旧 RPC - -两端都不再调用之后: - -- 删 `FireTopicsHandle::fetch_topic_detail_source_snapshot`、`fetch_topic_detail_page`、`load_more_topic_posts` -- 删 FFI `TopicDetailSourceQueryState` 的 batch 字段,或整个 query 记录若无引用 -- 删 Android `TopicRepository.fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot` -- 删 Android `FireSessionStore.fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot` -- 删 iOS `FireSessionStore.fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot` -- 删 `FireCore` 上这三个公开包装。`load_topic_detail_page` 仍是 `pub(crate)`,给测试和 actor 用,不是第二套逻辑 -- 详情屏幕不再使用的 `TopicDetailState` 合成路径删除。其它屏幕若仍要单帖,继续用 `fetch_post` - -## Architectural Notes - -与 `fire-native-architecture.md` 的偏差要在实现时改文档,而不是改代码去迎合过期句子: - -- §1.3 把 `topic_detail_feed` 写成 `FireAppCore` 全局推送边界。落地是每会话 observer。不要给 `StateObserver` 加第四个方法。 -- §2.4 当前稳定边界仍是 session / topic list / notification center。本设计不改变这三条。 -- §2.5 `StaleSessionResponse`「平台无感知」今天并未做到:`FireTopicDetailStore.loadTopicDetail` 仍 `case StaleSessionResponse` 后 `force` 重试。会话补上这一跳。 -- §2.5 LoginRequired 写的是「展示失败,不自动 logout」。Headless 重登今天从话题 store 解析 `FireUniFfiError.LoginRequired` 进入。改成 `SessionSnapshot.read_path_login_request` 唤醒 `applySession`,话题详情不再解析错误。失败则快照停在 `LoginRequired`,不自动 logout。 - -三档更新必须保住(`2026-09-19-ios-topic-detail-local-updates.md`)。比较的是 Swift 组出来的 token,不是裸 Rust checksum: - -1. layout token 不变且 in-place token 变:复用 + `applyVisibleNodeUpdates`。续赞停在这档(`reactions.is_empty()` 仍为 true 方向上的非空,like 只进 `interaction_checksum`)。 -2. layout token 变且行可见:relayout。首枚反应翻转 `reactions.is_empty()`。正文展开、表情条、回复树展开、摘要展开由 Swift 折进 layout token,不要求 Rust checksum 变化。 -3. 行身份集合变化(分页、展开回复树):collection diff。展开回复树的身份变化来自 Swift 过滤,不是 Rust revision。`FireTopicDetailFeedInvalidationToken` 仍不含 `expandedPostTextIDs`。 - -`is_mutating` 只进表情 alpha,不禁用回复 / boost / overflow / 投票。chip 签名不含 mutating,避免打断 bounce。overflow 仍是 cell 本地,relayout 不得写回 `false`。 - -`FireTopicDetailWindowState`(`FireAppViewModelSupport.swift`)随窗口逻辑删除。`maxWindowSize = 200` 进会话私有窗口,不进 FFI。 - -Kyc `FaceSessionHost` 持有会话并在 `releaseSession` 拆掉。Fire 的对应物是 store 的 `close(ownerToken:)`,不是一个全局 `FireAppCore` 替身。`FireTopicsHandle` 继续从 `FireAppCore.topics()` 拿。 - -风险: - -- 离开详情即丢会话。今天 `endTopicDetailLifecycle` 在首页仍可见时保留详情。按屏幕 refcount 后,返回同一话题会重新 `open`。只有 `bypass_cache == false` 且 source 已含目标楼才不打网。最后 owner 的 `close` 会拆掉会话。这是有意行为变化,避免首页可见集变成第二套保留策略。 -- 多 store 若漏改,会各开一个 owner。`close` 只释放该 handle 记住的 owner,最后一个才拆会话。同一 token 再 open 是替换。Phase 2 仍把 `FireTopicDetailStore` 的公开 init 收成内部,只允许 root 构造。 -- 兼容 RPC 若忽略 batch,`tests/network.rs` 里 batch 为 1/3/10 的 source snapshot 用例会按 40 失败,Android 若将来传入非 40 也会变。所以 compat 保留 query 批量。actor 自己的打开路径才用常量。 -- 乐观表情与 MessageBus 刷新并发:actor 单写。刷新开始时若该帖 `is_mutating`,跳过覆盖该帖,等命令结束再对齐。 -- observer 若在 Swift 主线程同步做全量快照构建会死锁或卡滚动。sink 只赋值 `snapshots`,重的 `buildSnapshot` 仍走现有 `Task.detached`。 -- 首页 patch 在话题不在 `topicEntities` 时无效果。与今天相同。不要为此去拉首页。 - -## File Change Summary - -| 文件 | 阶段 | 动作 | -| --- | --- | --- | -| `crates/fire-models/src/topic_detail_ui.rs` | 1 | 新增快照与 home patch | -| `crates/fire-models/src/lib.rs` | 1 | 导出 | -| `crates/fire-core/src/core/topic_detail/` | 1 | 会话、registry、常量、命令 | -| `crates/fire-core/src/core/topic_detail/project/` | 1 | 私有 source+tree -> 快照;compat -> `TopicDetailPage` | -| `crates/fire-core/src/core/topics.rs` | 1 | source session 留私有;公开 fetch 变包装 | -| `FireSessionRuntimeState`、`SessionSnapshot`(`#[serde(skip)]`)、`SessionState` | 1 | `ReadPathLoginRequest` 不进信封、不抬 `snapshot_revision`。restore 时清掉。不改 `FireAuthRecoveryHint` | -| `crates/fire-core/src/core/mod.rs` | 1 | registry;`request_read_path_login` / `complete_read_path_login` | -| `crates/fire-store/src/lib.rs` | 1 | `topic_list_cache_list_pages` | -| `crates/fire-core/src/core/messagebus.rs` | 1 | 内部 listener | -| `crates/fire-uniffi-topics/src/session.rs` | 1 | Handle、observer 适配 | -| `crates/fire-uniffi-topics/src/lib.rs` | 1 | `open_topic_detail`。旧 RPC 只转发 `load_topic_detail_*`,不 `Registry.open` | -| `crates/fire-uniffi-topics/src/records.rs` | 1 | `from_core` 记录 | -| `crates/fire-core/tests/network.rs` | 1 | 仍走公开 `fetch_*`,确认委托后断言不变 | -| `apps/ios-app/App/ViewModels/FireAppViewModel.swift` | 2 | 去掉话题错误重试。`applySession` 走 cookie resync,失败再 headless。`updateTopic` 仍刷新首页 | -| `apps/ios-app/App/Stores/FireTopicDetailStore*.swift` | 2 | 快照持有 + 转发 | -| `apps/ios-app/App/TopicDetail/**` | 2 | 消费快照;管道留 | -| `apps/ios-app/App/Services/FireTopicInteractionService.swift` | 2 | 写操作转发 | -| `apps/ios-app/App/Stores/FireHomeFeedStore.swift` | 2 | `applyHomeRowCountPatch`。删除 `patchedTopicRow` / `patchTopicCounts` | -| `apps/ios-app/App/Core/FireRootCoordinator.swift` | 2 | 仍拥有唯一 store | -| 六个额外 store 构造点 | 2 | 改用 root store | -| `apps/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift` | 2 | 窗口断言删除或改读 Rust;UI 无关用例保留 | -| `apps/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift` | 2 | fixture 改快照行 | -| `docs/architecture/fire-native-architecture.md` §1.3 §2.4 §2.5 | 2 | 写成每会话 observer | -| `docs/architecture/2026-09-19-ios-topic-detail-local-updates.md` | 2 | 写明 Rust checksum 与 Swift 折入的本地 chrome | -| `TopicRepository.kt`、两端 `FireSessionStore` | 4 | 删除 `fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot` | -| `apps/android-app/.../TopicDetailViewModel.kt` | 3 | 方法表 | -| `FireTopicsHandle` 三个分页方法 | 4 | 删除。含 `fetch_topic_detail_source_snapshot` | - -## Key Decisions - -- 话题详情是 `fire-uniffi-topics` 上的一个对象,不是新的 UniFFI crate,也不是全应用一个 session。 -- 全局 `StateObserver` 不增加话题详情。 -- Swift store 不做页合并、不算区间、不解析 `FireUniFfiError` 重试。 -- 新会话的批量是常量 40/40/3/120。预取 10、前向 60、hydration 页 30、迭代 8、过滤后列表尾 5、回复上下文 20、可见 debounce 120ms、刷新 1.5s、presence 30s、请求超时 30s、窗口 200。旧 RPC 在 Phase 4 前仍尊重宿主 query 的批量。 -- 用户「加载更多」是 `load_more`。楼层预取是 `note_visible_posts`。列表尾预取是 `note_filtered_feed_tail`,用过滤后的 item 下标。 -- 点赞在 HTTP 前乐观更新。回复在 `create_reply` 返回后按 `applyCreatedReply` 插入并伸窗口,不插占位行。Swift 不改帖。 -- 展开、草稿、键盘、搜索高亮、滚动偏移、overflow 留在 VC / cell,并折进 Swift token。 -- 首页补丁是 `TopicHomeRowCountPatch`,无 `like_count`。未读三态对齐 `patchedTopicRow`,含 `lastRead == nil` 且 `hasUnreadPosts == false` 时清零。只在计数会变时发出。不广播 topic list。标题 / 分类 / 标签仍靠现有 `refreshHomeFeedIfPossible`。 -- 旧 RPC 只转发 `load_topic_detail_*`,不进 `Registry.open`。无 observer、无订阅、无预取、无 owner。Android 早期运行时行为不变。 -- `open` 的缓存短路和 query 的 `force_load` 是两位。`reload` 永远打网。对账用 `force_load = false`、`track_visit = false`。 -- `close` / `release(topic_id, owner_token)` 只释放该 owner。 -- 书签是 `create_bookmark` / `update_bookmark` / `delete_bookmark` 的薄包装,带 `bookmarkable_type` 与 `auto_delete_preference`。 -- 详情状态只由屏幕 owner 保持。首页可见不再充当隐式 owner。 -- 编辑 raw 用 `prepare_edit` 单次读取,不把 raw 放进每一行。 - -## Alternatives Considered - -- 继续在 `FireTopicsHandle` 上加参数,让 Swift 少传 batch。拒绝。控制流仍在 Swift,违反 §1.1。 -- 把话题快照塞进 `StateObserver`。拒绝。多话题会把全局 observer 变成第二总线,且与「分页不要广播全表」同一类问题。 -- 一个进程级 `TopicDetailController` 仿 `FaceVerifySession` 包掉整个 App。拒绝。用户约束:只学模块内 API,Fire 多通道保持。 -- 专用 `topic-detail` OS 线程 + 同步 `call`。拒绝。会把 UI 挂在 HTTP 上。Kyc 的帧回路不适用于帖子流。 -- Swift 暂留 `TopicDetailState` 由快照反推。拒绝。那是第二真相源。 -- 首页未读改由话题 stream 重算 `unreadPosts`。拒绝。今天的公式是清零或保留,重算会改产品语义,也超出首页范围。 -- `notify_topic_list` 推一页被改过的列表。拒绝。`fetch_topic_list` 已写明宿主自己应用分页,广播会把一页当成全表。 -- 展开回复树改成 Rust 命令。拒绝。该状态是本地 chrome,文档要求留在 Swift。 -- Phase 2 双写 `topicDetails` 与快照直到 Android 完成。拒绝。iOS 必须先到达单源,双写会把合并逻辑留下。 - -## PR Plan - -1. **PR-A Rust 会话与兼容 RPC。** Phase 1。iOS/Android 行为不变。审查点:actor 不阻塞;observer 不进 `StateObserver`;compat 无订阅、无预取、无 owner,且保留 batch / `force_load` / `track_visit` / `allow_suggested_unread_root`;`tests/network.rs` 自定义 batch 断言仍绿;`release` 只拆一个 owner。 -2. **PR-B iOS 单源。** Phase 2。一个 PR,中间可以不编译,不拆双源的中间步。审查不通过,如果下面任一条成立: - - `TopicDetailState` 仍是 store 成员 - - 详情路径仍 `switch` `FireUniFfiError` 来决定重试 - - `contentToken` 或 `inPlaceUpdateToken` 被赋成裸的 Rust checksum - - `FireAppViewModel.updateTopic` 仍调用 `refreshTopicDetailAfterMutation`,或丢掉 `refreshHomeFeedIfPossible(force: true)` - - `presentBookmarkEditor` / `presentTopicBookmarkEditor` / `presentPostBookmarkEditor` 的 `onReload`,或 `presentPostEditor` / `presentTopicEditor` 的 `onSaved`,或 `updateTopicNotificationLevel` 仍调用 `loadTopicDetail` - - `performRefresh`、`onLoadTopicDetail`、`openAdvancedComposer.onReplySubmitted`、`openQuoteComposer.onReplySubmitted` 仍调用 `loadTopicDetail(force:)`。前两个必须是 `bypass_cache = true`、`force_load = true`、`track_visit = true`。后两个不得再拉页;引用回复必须 `scroll_to_created` - - Android `open` 不是 `bypass_cache = true`、`force_load = true`、`track_visit = true`(`allow_suggested_unread_root` 除外,那条保持原公式)。这条在 PR-C 落地,PR-B 审查时对照契约表,避免 iOS 表和 Android 行各写一套 - - `patchedTopicRow` 还在 - - 详情路径仍调用 `fetchTopicDetailPage` / `loadMoreTopicPosts` -3. **PR-C Android ViewModel。** Phase 3。方法表含 `prepareForTopicLoad`、`scrollToPostWhenLoaded`、`refreshCurrentTopic`、`replacePost`。Repository 方法先留。PR 结束后 ViewModel 不得再调用 `fetchTopicDetailPage`。 -4. **PR-D 删除旧 RPC。** Phase 4。删三个分页 FFI,以及两端 `FireSessionStore` 和 `TopicRepository` 上的 `fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot`。单独审查,便于回滚。 - -文档更新放在 PR-B(iOS 行为已变)和 PR-D(RPC 消失)。不要在 PR-A 把架构文档改成「Swift 已不再合并」——那时 Swift 还在合并。 - -## Open Questions - -- `fetchReactionUsers` / `fetchTopicVoters` 是 sheet 列表,不是帖树。保持一次性 RPC。若产品要它们也进快照,另开任务。 -- 被动掉登录时 `applySession` 里已有的 `scheduleMidSessionReauthAfterPassiveDeauth` 保持原样。它看的是 readiness 从已登录变成未登录,和 `ReadPathLoginRequest` 不是一条路径。不要把二者合成一个 hint。 - -## Goals & Non-Goals - -目标: - -- Rust 是话题详情唯一数据源和唯一逻辑处理器。 -- Swift 只渲染 UI 快照,外加纯本地 chrome。 -- 一个会话对象,命令进、快照出,含后台刷新。 -- 源游标、stream、批量、未读自动延伸、乐观对账、预取、MessageBus 刷新策略全部私有。 -- iOS 先于 Android 到达该形状。每阶段可编译。旧 RPC 最后删除。 -- 三档就地更新行为保持。 -- 首页行计数仍然正确,且首页 store 不再做未读比较。 - -非目标: - -- 合并 UniFFI 通道,或做全应用单一 session。 -- 改首页、搜索、通知、聊天的架构。 -- 重做 Texture 管道、动画、overflow 的 cell 本地状态。 -- 把展开正文 / 回复树 / 表情条 / 草稿 / 键盘 / 搜索高亮放进 Rust。 -- 在话题详情增加新的平台决策回调。 -- 用 `FrameTick`、专用线程或同步 HTTP 阻塞 UI。 -- 从 stream 重算首页未读条数。 -- Phase 1–2 修改 Android ViewModel 行为。 diff --git a/docs/architecture/2026-09-23-page-and-rust-module-splits.md b/docs/architecture/2026-09-23-page-and-rust-module-splits.md deleted file mode 100644 index d3be5fd1..00000000 --- a/docs/architecture/2026-09-23-page-and-rust-module-splits.md +++ /dev/null @@ -1,50 +0,0 @@ -# 2026-09-23:页面组合拆分与 Rust 大文件切目录 - -| 项 | 值 | -| --- | --- | -| 日期 | 2026-09-23 | -| 状态 | 已落地(文件边界;Session 控制面升级仍按 TopicDetail 刀法预备,未迁行为) | -| 范围 | iOS 高流量页目录拆分 + fire-core / fire-models / fire-rich-text / fire-uniffi-session 模块切分 | -| 参考 | [2026-09-22-ios-topic-detail-session.md](2026-09-22-ios-topic-detail-session.md) | - -对照 TopicDetail 落地:先立 Host / Shell / Controller / Feed / State 目录,Swift store 暂不改行为。下一波 Session(`HomeFeedSession` / `ChatChannelSession` / `ComposerSession` / Notification runtime 收口)在边界稳定后再迁控制面。 - -## iOS 页面目录 - -| 面 | 新根 | 说明 | -| --- | --- | --- | -| Topic List Kit | `App/ListKit/TopicList/` | 从 Bookmarks 文件抽出共用 cell / metric / toast / palette | -| Composer | `App/Composer/` | Route/Validation/Markdown/Shell/Host + VC 扩展 | -| Home | `App/Home/` | Controller + Feed + Shell;scope/drawer 仍在 `Views/Home/` | -| Search | `App/Search/` | Controller + Feed + Header | -| Notifications | `App/Notifications/` | Inbox / History / Cells;presentation 仍在 `Views/Notifications/` | -| Chat Channel | `App/Chat/Channel/` | Load / Bus / Interactions / Table + message cell | -| Messages / Drafts / Profile cells | `Views/Messages/`、`Views/Drafts/`、`Views/Profile/Cells/` | 轻量拆;死 SwiftUI Profile/PublicProfile 已删 | - -## Rust 模块目录 - -| 原文件 | 现目录 | -| --- | --- | -| `fire-core/src/core/network.rs` | `core/network/{mod,constants,client,traced,execute,request,csrf,challenge,heal,auth_signals,headers,body,tests}.rs` | -| `fire-core/src/diagnostics.rs` | `diagnostics/{models,store,listener,logs,bundle,tests}.rs` | -| `fire-models/src/cookie.rs` | `cookie/{canonical,snapshot,sweep,tests}.rs` | -| `fire-core/src/topic_payloads.rs` | `topic_payloads/{list,post,detail,poll,deser}.rs` | -| `fire-rich-text/src/lib.rs` | `map.rs` / `onebox.rs` / `images.rs` / `plain_text.rs` / `tests.rs` | -| `fire-uniffi-session/src/records.rs` | `records/{cookie,session,bootstrap,login,challenge,refresh,handlers,doh}.rs` | -| `fire-uniffi-session/src/lib.rs` handle | `handle/{cookies,challenge,login,refresh,doh,scope}.rs` | -| `fire-core/src/core/interactions.rs` | `interactions/{bookmarks,posts,replies,polls,votes,reactions,boosts,timings,...}.rs` | -| `fire-core/src/core/session.rs` | `session/{classify,challenge,cookies,bootstrap,login}.rs` | -| `fire-core/src/core/chat.rs` | `chat/{channels,messages,reactions,pins,threads,search}.rs` | -| `fire-core/src/core/notifications.rs` | `notifications/{fetch,runtime,read}.rs` | -| `topic_detail_project.rs` | `topic_detail/project/{row,chrome,checksum}.rs` | -| `topics/source/load.rs` | `topics/source/load/{initial,page,load_more}.rs` | -| hydrate AI summary | `topics/source/summary.rs` | - -对外 crate 路径保持稳定(`mod` 目录替换单文件)。 - -## 下一波 Session(预备,未迁行为) - -- `HomeFeedSession`:吃掉 `FireHomeFeedStore` 的 scope / merge / MB debounce / unread patch -- `ChatChannelSession`:每频道 open/close,对齐 TopicDetail -- Notification runtime 收口:Swift 分页并回 `FireNotificationRuntime` -- `ComposerSession`:draft / validation / 三类 submit / upload resolve diff --git a/docs/architecture/2026-09-25-module-boundaries.md b/docs/architecture/2026-09-25-module-boundaries.md new file mode 100644 index 00000000..04eae72a --- /dev/null +++ b/docs/architecture/2026-09-25-module-boundaries.md @@ -0,0 +1,81 @@ +# 2026-09-25:模块边界(当前口径) + +| 项 | 值 | +| --- | --- | +| 日期 | 2026-09-25 | +| 状态 | 当前实现 | +| 范围 | iOS / Android / Rust 宿主与核心模块边界 | +| 参考 | [2026-09-19-ios-topic-detail-local-updates.md](2026-09-19-ios-topic-detail-local-updates.md)、[2026-09-19-render-presentation.md](2026-09-19-render-presentation.md) | + +本文件只描述**现在怎么切**。 + +## 拆法 + +```text +页面骨架 Activity / VC + └─ Fragment 一个 region 内独立刷新的块 + └─ View/方法 单个视觉单元,或单一职责函数 +``` + +- 一个文件只回答一个问题。 +- 深模块对外 interface 小,实现可以长;不要为了行数切开。 +- 禁止第二份 session 状态、第二条渲染 / 登录 / CF 路径。 +- 话题帖子行:iOS 留 Texture runtime cell;Android 留 `PostViewHolder` + `item_topic_post`。 +- UniFFI 签名、crate-root `pub use`、生成绑定不拆。 + +## Session 控制面 + +| 域 | iOS | Android | Rust | +| --- | --- | --- | --- | +| TopicDetail | `FireTopicDetailStore` 持 handle | `TopicDetailViewModel` 持 `TopicDetailSessionHandle`,只投 snapshot | `TopicDetailSession` actor | +| Home | `FireHomeFeedSession` + 薄 `FireHomeFeedStore` | `HomeViewModel` + Paging3 + Rust `currentHomeTopicListScope` | 列表 scope / patch,不造 HomeFeedSession | +| Notifications | `FireNotificationStore` 读 runtime 快照 | `NotificationsViewModel` 是 Paging 胶水 | `FireNotificationRuntime` | +| Chat 列表 | `FireChatListSession` | `ChatChannelsViewModel` | RPC + Bus | +| Chat 单频道 | `FireChatChannelSession` | `ChatChannelSession` | RPC + Bus;尚未下沉 actor | +| Composer | `FireComposerSession` | `ComposerViewModel` 已是提交门面 | 写路径走现有 RPC | + +平台态留下:WebView 登录、CF、cookie 提取、键盘、滚动、展开、图片选择器、输入草稿。 + +不要横切:`FireSessionStore`、`FireSpannableBuilder`、`HomeViewModel`、`NotificationsViewModel`、登录 / CF 协调器。 + +## iOS 页面目录 + +| 面 | 根 | +| --- | --- | +| Topic List Kit | `App/ListKit/TopicList/` | +| Composer | `App/Composer/` | +| Home | `App/Home/` | +| Search | `App/Search/` | +| Notifications | `App/Notifications/` | +| Chat Channel | `App/Chat/Channel/` | +| TopicDetail | `App/TopicDetail/`(Host / Feed / Modal / Runtime) | + +## Android 宿主 + +- TopicDetail:同一 `TopicDetailActivity` / `PostViewHolder`,弹层与 bind 族是同包 `internal` 扩展;adapter 一 type 一文件。 +- `TopicDetailViewModel` 是 snapshot 门面:展开走 `snapshotReplyRows`,投票 / 通知档走 handle,不再本地 merge。 +- Chat:`ChatChannelActivity` 只留键盘、滚动、图片 picker、输入;策略在 `ChatChannelSession`。 +- ComposerAssist 已按 mention / tag / recipient / draft / upload / markdown 分文件。 + +## Rust 模块目录 + +对外 crate 路径保持稳定(`mod` 目录替换单文件)。 + +| 域 | 现目录 | +| --- | --- | +| network | `fire-core/src/core/network/` | +| session / auth | `fire-core/src/core/session/`、`auth/` | +| chat | `fire-core/src/core/chat/` | +| notifications | `fire-core/src/core/notifications/` | +| interactions | `fire-core/src/core/interactions/` | +| topic detail | `fire-core` actor + `fire-models/src/topic_detail/` | +| payloads | `topic_payloads/`、`user_payloads/`、`chat_payloads/`、`cookies/` | +| parsing | `fire-core/src/core/parsing/` | +| rich text | `fire-rich-text/`、`fire-models/src/rich_text/` | +| UniFFI session | `fire-uniffi-session/src/{records,handle}/` | + +Home / Chat / Composer 若再下沉 Rust actor,按 TopicDetail 模板,不要平行第二份策略。 + +## 话题详情会话 + +`TopicDetailSession` 是唯一控制面。平台只持 handle、投 snapshot、保留本地 chrome(展开、搜索高亮、键盘、滚动)。不要再开第二套分页 merge / MessageBus 刷新。iOS 帖子行留 Texture runtime cell。Rust checksum 只覆盖服务端字段;本地 chrome 折进 layout / in-place token 的规则见 [2026-09-19-ios-topic-detail-local-updates.md](2026-09-19-ios-topic-detail-local-updates.md)。 diff --git a/docs/architecture/discourse-startup-implementation-plan.md b/docs/architecture/discourse-startup-implementation-plan.md deleted file mode 100644 index c04097ce..00000000 --- a/docs/architecture/discourse-startup-implementation-plan.md +++ /dev/null @@ -1,684 +0,0 @@ -# 重构 Fire 启动阶段:对齐 Discourse 启动实现规格 - -## Breaking Change Notice - -本文档为**破坏性重构**。所有启动阶段代码将完全重写以对齐 `docs/knowledge/discourse-startup-implementation-spec.md`。不保留任何兼容代码,不提供迁移路径。 - -1. iOS 端:删除 `FireStartupPreloadCoordinator`,重写 `FireAppViewModel.loadInitialState()`,新增 `FirePreheatGateViewController`、`FireAppStateRefresher`。 -2. Android 端:删除 `AuthViewModel.restoreSession()` 现有逻辑,重写 `OnboardingFragment` 启动流程,新增 `PreheatGateFragment`、`AppStateRefresher`。 -3. Rust 端:新增 `PreloadedDataService` 模块、`AppStateRefresher` 模块;重写启动时序编排。 - -## Feasibility Assessment - -Fully feasible。Rust 核心已有完整的 bootstrap 解析(`parsing.rs`)、session 管理(`core/session/`)、CSRF 刷新(`core/auth.rs`)、cookie 管理(`cookies.rs`)、MessageBus(`core/messagebus/`)、auth strike(`core/auth_strike.rs`)、probe(`core/auth.rs`)等能力。两端平台已有 WebView login coordinator 和 FFI 桥接。缺失部分是启动阶段编排(首页 HTML 请求与 UI 并行、PreheatGate 阻塞、AppStateRefresher 分批刷新)和 User 数据模型在 Rust 侧的完整定义。这些都是增量开发,无技术障碍。 - -## Current Surface Inventory - -### Rust(需变更) - -- `fire-core/src/core/mod.rs` — `FireCore` 主结构体,持有 session/network/diagnostics -- `fire-core/src/core/session/` — session 应用方法(merge/apply/sync/finalize;分 classify/challenge/cookies/bootstrap/login) -- `fire-core/src/core/auth.rs` — bootstrap 刷新、CSRF 刷新、probe、passive logout、strike -- `fire-core/src/core/network/` — 网络层 + 拦截器 -- `fire-core/src/parsing.rs` — HTML bootstrap 解析(parse_home_state) -- `fire-core/src/session_store.rs` — session 持久化 -- `fire-models/src/session.rs` — BootstrapArtifacts、LoginPhase、SessionSnapshot -- `fire-models/src/user.rs` — UserProfile(目前只有 profile/summary 模型,缺少启动期 currentUser 快照模型) -- `fire-uniffi-session/src/lib.rs` — session FFI handle - -### iOS(需变更) - -- `apps/ios-app/App/ViewModels/FireAppViewModel.swift`(~2664 行)— 中央 ViewModel,包含启动、登录、所有 API 调用 -- `apps/ios-app/App/Startup/FireStartupPreloadCoordinator.swift` — 当前启动预加载(将被删除) -- `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift`(~1314 行)— actor FFI 桥接 -- `apps/ios-app/App/Core/FireRootCoordinator.swift` — UIKit root/preheat/auth/main-tab gate -- `apps/ios-app/App/Core/FireMainTabBarController.swift` — UIKit authenticated tab shell -- `apps/ios-app/App/Views/Other/FireOnboardingView.swift` — SwiftUI 引导页(将被重写为 UIKit) - -### Android(需变更) - -- `apps/android-app/src/main/java/com/fire/app/ui/auth/OnboardingFragment.kt` — 启动鉴权 -- `apps/android-app/src/main/java/com/fire/app/ui/auth/AuthViewModel.kt` — session 恢复 -- `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` — FFI 桥接 -- `apps/android-app/src/main/java/com/fire/app/data/repository/SessionRepository.kt` — session 操作 - -## Design - -以 `docs/knowledge/discourse-startup-implementation-spec.md` 为唯一权威目标规格。所有实现细节严格对齐该文档,不论现有代码如何。 - -### Key Design Decisions - -1. **首页 HTML 请求归 Rust 所有,与 UI 并行发起** — 规格要求 `main()` 尾部 `unawaited(ensureLoaded())` 与 UI 渲染并行。Rust 新增 `PreloadedDataService`,在 `FireCore` 构造后立即发起 `GET https://linux.do` HTML 请求,平台在 `main()`/`Application.onCreate()` 触发。不用平台发起 HTTP。 - -2. **PreheatGate 阻塞 UI 渲染** — 规格要求 Widget 树中 PreheatGate 阻塞等待首页数据。iOS 新增 `FirePreheatGateViewController`,Android 新增 `PreheatGateFragment`。在首页数据加载完成前显示加载指示器;失败则显示错误页面(重试/退出登录/网络设置)。 - -3. **data-preloaded 作为登录态首要判断依据** — 规格明确 `currentUser` 的存在与否是启动期判断登录态的首要依据。不依赖额外的 `/session/current.json` 调用(除非无预加载 currentUser 但 CookieJar 有 _t)。 - -4. **AppStateRefresher 由 Rust 单点编排** — 规格要求 authState 变化后,第一批立即刷新核心数据,第二批延迟 1 秒刷新次要数据。当前实现以 Rust `AppStateRefresher` 为唯一编排器;平台只触发 `triggerAppStateRefresh(...)` 并消费批次 callback,不再各自维护平台版 refresher。首页当前 tab 的 `kind/category/tags` 选择状态也由 Rust runtime 持有,平台只同步 UI 选择。 - -5. **User 启动期缓存模型** — 规格要求启动时将 User 序列化缓存,下次启动先从缓存返回。Rust 侧新增 `CurrentUserCache`,持久化到 SQLite。 - -6. **会话代完全归 Rust** — 规格的 `AuthSession.advance()` 已在 Rust 中以 `epoch` 实现。平台不再自行维护代数,只从 Rust session snapshot 读取。 - -7. **删除 Flutter/Dart 特有概念** — 规格中 SharedPreferences、CookieJar(Dart 实现)、MigrationService 等 Flutter 概念不迁移。对应功能在 Rust 中已有(session.json 持久化、openwire CookieJar、session_store 迁移)。 - -### 新增类型定义 - -#### Rust: CurrentUserSnapshot(轻量启动期用户缓存) - -```rust -// fire-models/src/user.rs - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CurrentUserSnapshot { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, - pub animated_avatar: Option, - pub trust_level: u8, - pub status: Option, - pub flair_url: Option, - pub flair_name: Option, - pub flair_bg_color: Option, - pub flair_color: Option, - pub flair_group_id: Option, - pub gamification_score: Option, - pub unread_notifications: u32, - pub unread_high_priority_notifications: u32, - pub all_unread_notifications_count: u32, - pub seen_notification_id: u64, - pub notification_channel_position: i64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct UserStatus { - pub description: Option, - pub emoji: Option, -} -``` - -#### Rust: PreloadedDataService 输出 - -```rust -// fire-models/src/session.rs additions - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PreloadedDataResult { - pub current_user: Option, - pub site_settings: Option, - pub site: Option, - pub topic_tracking_state_meta: Option>, - pub topic_tracking_states: Option>, - pub custom_emoji: Option>, - pub topic_list: Option, - pub enabled_reaction_ids: Option>, - pub categories: Option>, - pub top_tags: Option>, - pub can_tag_topics: Option, -} -``` - -#### Rust: AppStateRefresherRequest - -```rust -// fire-models/src/session.rs additions - -#[derive(Debug, Clone)] -pub enum RefreshBatch { - Core, - Secondary, -} - -#[derive(Debug, Clone)] -pub struct AppStateRefreshEvent { - pub batch: RefreshBatch, - pub trigger: RefreshTrigger, -} - -#[derive(Debug, Clone)] -pub enum RefreshTrigger { - LoginCompleted, - LogoutCompleted, - SessionRestored, -} -``` - -#### FFI: StateObserver 回调增强 - -```rust -// fire-uniffi-types additions - -trait StateObserver: Send + Sync { - fn on_session_snapshot(&self, snapshot: SessionSnapshotState); - fn on_passive_logout(&self, trigger: PassiveLogoutTriggerState); - fn on_cf_clearance_expired(&self); - fn on_preloaded_data_ready(&self, result: PreloadedDataResultState); - fn on_app_state_refresh_needed(&self, event: AppStateRefreshEventState); -} -``` - -#### iOS: PreheatGate - -```swift -// apps/ios-app/App/Startup/FirePreheatGateViewController.swift - -final class FirePreheatGateViewController: UIViewController { - // 阻塞等待首页数据加载完成 - // 显示 UI: 加载指示器 / 错误页面 - // 成功后自动 transition 到 FireMainTabViewController - // 失败: 重试 / 退出登录 / 网络设置 -} -``` - -#### Android: PreheatGate - -```kotlin -// apps/android-app/.../ui/startup/PreheatGateFragment.kt - -class PreheatGateFragment : Fragment() { - // 阻塞等待首页数据加载完成 - // 显示 UI: ProgressBar / Error layout - // 成功后自动 navigate 到 HomeFragment - // 失败: 重试 / 退出登录 / 网络设置 -} -``` - -## Phased Implementation - -### Phase 1: Rust — 新增 PreloadedDataService 与 User 启动期模型 - -#### File: `crates/fire-models/src/user.rs` - -- 新增 `CurrentUserSnapshot` 结构体(规格 Section 9 所有字段) -- 新增 `UserStatus` 结构体(description + emoji) -- 新增 `AvatarUrlCalculator` 工具:`calculate_avatar_url(template, animated_avatar, base_url, size) -> String` - -#### File: `crates/fire-models/src/session.rs` - -- 新增 `PreloadedDataResult` 结构体 -- 新增 `AppStateRefreshEvent`、`RefreshBatch`、`RefreshTrigger` 枚举 -- 新增 `PreloadedDataState` 枚举:`NotStarted` | `Loading` | `Ready(PreloadedDataResult)` | `Failed(Error)` - -#### File: `crates/fire-models/src/lib.rs` - -- 注册新模块,确保编译通过 - -#### File: `crates/fire-core/src/preloaded_data.rs`(新文件) - -- `PreloadedDataService` 结构体: - - `ensure_loaded(&self) -> Result<()>`:发起 `GET https://linux.do` HTML 请求,调用 `parse_home_state()` + `hydrate_preloaded_fields()`,将结果存入内存 - - 防重入:`_loading` 标志 - - 成功后通过 `StateObserver.on_preloaded_data_ready()` 推送 -- `get_current_user_snapshot(&self) -> Option`:同步返回已加载的用户数据 -- `get_cached_user(&self) -> Option`:从 SQLite 缓存读取(启动早期) -- `cache_current_user(&self, user: &CurrentUserSnapshot)`:写入 SQLite 缓存 -- 解析逻辑复用现有 `parsing.rs` - -#### File: `crates/fire-core/src/core/mod.rs` - -- 新增 `preloaded_data: Arc>` 字段 -- 新增 `preloaded_data_service: Arc` 字段 -- 新增公开方法 `preloaded_data_service(&self) -> Arc` - -#### File: `crates/fire-store/src/lib.rs` - -- 新增 `current_user_cache` 表:key TEXT PRIMARY KEY, data TEXT, updated_at INTEGER -- 新增 `get_cached_user() -> Option` -- 新增 `set_cached_user(data: &str)` -- 新增 `clear_cached_user()` - -#### File: `crates/fire-core/src/lib.rs` - -- 注册 `preloaded_data` 模块 - -### Phase 2: Rust — AppStateRefresher 编排 - -#### File: `crates/fire-core/src/app_state_refresher.rs`(新文件) - -- `AppStateRefresher` 结构体,持有 `FireCore` 引用 -- `refresh_all(&self, trigger: RefreshTrigger)`: - - 第一批(立即执行): - - 强制刷新 bootstrap / categories / current user / topic tracking 基线 - - 使用 Rust 持有的 `current home topic-list scope` 请求当前首页列表 - - 向平台回调 `RefreshBatch::Core` - - 第二批(延迟 1 秒,避免并发过多触发风控): - - userSummary(`/u/{username}/summary.json`) - - recent notifications(`/notifications.json`) - - 浏览历史(`/read.json`) - - bookmarks(`/u/{username}/bookmarks.json`) - - 向平台回调 `RefreshBatch::Secondary` -- 去抖:2 秒内重复调用直接跳过 -- 通过 UniFFI `AppStateRefreshHandler` 通知平台各批次完成 - -#### File: `crates/fire-core/src/core/auth.rs` - -- 修改 `probe_session()` 返回值增加 `CurrentUserSnapshot` -- 修改 `refresh_bootstrap()` 解析完成后同时填充 `PreloadedDataService` 的内存状态和 User 缓存 -- 新增 `refresh_current_user_with_cooldown(&self) -> Result>`:2 分钟冷却 - -#### File: `crates/fire-core/src/core/session.rs` - -- 新增 `determine_login_state(&self) -> LoginStateDetermination` 方法,实现规格 Section 6 的完整判断路径: - ``` - 首页 HTML 解析完成 → data-preloaded 有 currentUser? - ├── 有 → 已登录,同步返回用户数据 - └── 无 → CookieJar 有 _t? - ├── 无 → 确认未登录 - └── 有 → probe_session() - ├── 有 current_user → 确认已登录 - ├── 无/404/401/403 → 确认失效 → 执行登出 - └── 网络异常 → 保守保留登录态 - ``` - -#### File: `crates/fire-core/src/core/mod.rs` - -- 新增 `app_state_refresher: Arc` 字段 -- 新增公开方法 `app_state_refresher(&self) -> Arc` -- 在 session state 变更时触发 `app_state_refresher.refresh_all()` - -#### File: `crates/fire-core/src/lib.rs` - -- 注册 `app_state_refresher` 模块 - -### Phase 3: Rust — FFI 暴露启动阶段 API - -#### File: `crates/fire-uniffi-session/src/lib.rs` - -新增 FFI 方法: - -- `fn ensure_preloaded_data_loaded(&self) -> Result<()>` — 触发首页 HTML 请求 -- `fn preloaded_data_state(&self) -> PreloadedDataStateState` — 返回当前状态 -- `fn current_user_snapshot(&self) -> Option` — 返回已加载用户 -- `fn cached_user(&self) -> Option` — 返回缓存用户 -- `fn determine_login_state(&self) -> LoginStateDeterminationState` — 登录态判断 -- `fn trigger_app_state_refresh(&self, trigger: RefreshTriggerState) -> Result<()>` — 手动触发刷新 - -#### File: `crates/fire-uniffi-types/src/records/` - -新增 FFI record 类型: - -- `CurrentUserSnapshotState` — 映射 `CurrentUserSnapshot` -- `PreloadedDataResultState` — 映射 `PreloadedDataResult` -- `PreloadedDataStateState` — 枚举:NotStarted / Loading / Ready / Failed -- `LoginStateDeterminationState` — 枚举:LoggedIn(CurrentUserSnapshotState) / NotLoggedIn / SessionExpired / NetworkErrorPreserveState -- `AppStateRefreshEventState` — 映射刷新事件 -- `RefreshTriggerState` — 枚举 -- `RefreshBatchState` — 枚举 - -#### File: `crates/fire-uniffi/src/lib.rs` - -- 确保 `FireAppCore` 暴露新增的 session 方法 - -### Phase 4: Rust — MessageBus 初始化对齐规格 - -#### File: `crates/fire-core/src/core/messagebus.rs` - -- 修改 `start_message_bus()` 接受 `topic_tracking_state_meta: HashMap` 参数 -- 启动时批量订阅频道:`/latest`、`/new`、`/unread`、`/topic_tracking_state` -- 额外订阅通知频道:`/notification/{userId}`、`/notification-alert/{userId}` -- 长轮询请求体格式对齐规格:`/latest=6855147&/new=104155&...` -- 请求头:`X-Shared-Session-Key`(独立域名时)、`X-SILENCE-LOGGER: true`、`Discourse-Background: true` -- 独立域名配置:当 `long_polling_base_url` 有值时,请求发往独立域名,禁用 Cookie,改用 `X-Shared-Session-Key` - -#### File: `crates/fire-uniffi-messagebus/src/lib.rs` - -- 修改 `start_message_bus()` 签名,接受 `topic_tracking_state_meta` 参数 - -### Phase 5: Rust — 启动时序编排 - -#### File: `crates/fire-core/src/core/mod.rs` - -新增 `initialize_startup_sequence(&self) -> Result<()>` 方法,实现规格的完整启动时序: - -``` -Phase A: main() 初始化 - 1. 创建 FireCore(已有的构造函数) - 2. 并行触发 PreloadedDataService.ensure_loaded()(unawaited) - 3. 返回,让平台开始 UI 渲染 - -Phase B: 平台 PreheatGate 调用 await_preloaded_data() - 1. 阻塞等待首页数据加载完成 - 2. 解析 data-preloaded → 判断登录态 - 3. 已登录 → 启动 CfClearanceRefresh(通知平台) - 4. 失败 → 返回错误,平台显示错误页面 - -Phase C: 主界面就绪后 - 1. 平台调用 initialize_post_ui() - 2. 已登录 → 启动 MessageBus(传入 topic_tracking_state_meta) - 3. 触发 AppStateRefresher.refresh_all(SessionRestored) -``` - -#### File: `crates/fire-uniffi-session/src/lib.rs` - -新增 FFI 方法: - -- `fn await_preloaded_data(&self) -> Result` — 阻塞等待首页数据 -- `fn initialize_post_ui(&self) -> Result<()>` — 主界面就绪后初始化 - -### Phase 6: iOS — 重写启动流程 - -#### 删除以下文件 - -- **File: `apps/ios-app/App/Startup/FireStartupPreloadCoordinator.swift`** — 删除,被 Rust PreloadedDataService 替代 - -#### File: `apps/ios-app/App/Startup/FirePreheatGateViewController.swift`(新文件) - -UIKit ViewController 实现 PreheatGate: - -```swift -final class FirePreheatGateViewController: UIViewController { - private let sessionStore: FireSessionStore - private let loadingView = UIActivityIndicatorView(style: .large) - private let errorView: FireStartupErrorView // 自定义错误视图 - - override func viewDidLoad() { - super.viewDidLoad() - setupUI() // 加载指示器居中 - awaitPreloadedData() - } - - private func awaitPreloadedData() { - Task { - do { - let result = try await sessionStore.awaitPreloadedData() - onPreloadedDataReady(result) - } catch { - showErrorPage(error) - } - } - } - - private func onPreloadedDataReady(_ result: PreloadedDataResultState) { - // 检查是否需要重新登录(数据迁移导致 Cookie 清空) - if result.requiresRelogin { - showReloginDialog() - return - } - // 成功 → transition 到主界面 - transitionToMainTab() - } - - private func showErrorPage(_ error: Error) { - // 显示错误页面:重试 / 退出登录 / 网络设置 - } -} -``` - -#### File: `apps/ios-app/App/Startup/FireStartupErrorView.swift`(新文件) - -自定义 UIKit 错误视图:图标 + 错误信息 + 三个按钮(重试/退出登录/网络设置) - -#### File: `apps/ios-app/App/Startup/FireAppStateRefresher.swift`(新文件) - -```swift -actor FireAppStateRefresher { - private let sessionStore: FireSessionStore - private var lastRefreshTime: Date = .distantPast - private let debounceInterval: TimeInterval = 2.0 - - func refreshAll(trigger: RefreshTriggerState) async { - // 去抖:2 秒内跳过 - guard Date().timeIntervalSince(lastRefreshTime) > debounceInterval else { return } - lastRefreshTime = Date() - - // 第一批(通过 Rust FFI 触发,Rust 内部执行) - // Rust 推送 on_app_state_refresh_needed(batch: .core) - - // 第二批(1 秒后) - // Rust 推送 on_app_state_refresh_needed(batch: .secondary) - } -} -``` - -#### File: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` - -**大幅重写**。删除现有 `loadInitialState()` 中所有手动编排逻辑,替换为: - -```swift -func loadInitialState() async { - // 1. 创建 FireSessionStore(Rust FireAppCore) - // 2. 触发 Rust ensurePreloadedDataLoaded()(异步,不阻塞) - // 3. 展示 FirePreheatGateViewController - // 4. PreheatGate 完成后: - // - 设置 StateObserver 监听 session 变化 - // - 调用 initializePostUi() - // - 根据 loginState 决定显示 Onboarding 还是 MainTab -} -``` - -删除所有直接 API 调用方法(topicList、search、notifications 等)。这些现在由 Stores 直接调用 Rust FFI。 - -#### File: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` - -新增方法(包装 Rust FFI): - -- `func ensurePreloadedDataLoaded() async throws` -- `func awaitPreloadedData() async throws -> PreloadedDataResultState` -- `func initializePostUi() async throws` -- `func currentUserDefaults() -> CurrentUserSnapshotState?` -- `func cachedUser() -> CurrentUserSnapshotState?` -- `func determineLoginState() async -> LoginStateDeterminationState` -- `func triggerAppStateRefresh(trigger: RefreshTriggerState) async throws` - -#### File: `apps/ios-app/App/Core/FireRootCoordinator.swift` - -当前 UIKit root gate: - -- 未初始化:显示 `FirePreheatGateWaitingViewController` / `FirePreheatGateViewController` -- 已初始化未登录:显示当前 onboarding host(后续迁 UIKit) -- 已初始化已登录:显示 `FireMainTabBarController`(UIKit `UITabBarController`) - -#### File: `apps/ios-app/App/Views/Other/FireOnboardingView.swift` - -重写为 UIKit:`FireOnboardingViewController`(如果 Phase 6 前尚未完成登录文档中要求的 UIKit 迁移)。 - -#### File: `apps/ios-app/App/Navigation/FireMessageBusCoordinator.swift` - -修改 `startMessageBus()` 调用,传入 `topicTrackingStateMeta`(从 preloaded data 获取)。 - -#### File: `apps/ios-app/App/Core/SessionState+Helpers.swift` - -新增 `fromPreloadedData()` 便利方法,从 `PreloadedDataResultState` 构建 UI 可用的 session state。 - -### Phase 7: Android — 重写启动流程 - -#### File: `apps/android-app/.../ui/startup/PreheatGateFragment.kt`(新文件) - -```kotlin -class PreheatGateFragment : Fragment() { - private lateinit var progressBar: ProgressBar - private lateinit var errorLayout: View - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - awaitPreloadedData() - } - - private fun awaitPreloadedData() { - viewLifecycleOwner.lifecycleScope.launch { - try { - val result = sessionStore.awaitPreloadedData() - onPreloadedDataReady(result) - } catch (e: Exception) { - showErrorPage(e) - } - } - } - - private fun onPreloadedDataReady(result: PreloadedDataResultState) { - if (result.requiresRelogin) { - showReloginDialog() - return - } - // navigate to home or onboarding - } - - private fun showErrorPage(error: Exception) { - // 重试 / 退出登录 / 网络设置 - } -} -``` - -#### File: `apps/android-app/.../ui/startup/PreheatGateLayout.kt`(新文件) - -自定义布局:ProgressBar 居中 + Error 状态布局 - -#### File: `apps/android-app/.../session/FireAppStateRefreshRepository.kt`(新文件) - -Android 不再实现平台版 `AppStateRefresher`。改为提供一个进程级 callback repository: - -- `PreheatGateFragment` / `LoginWebViewFragment` 用它作为 `triggerAppStateRefresh(..., handler)` 的 handler -- `HomeViewModel` 订阅该 repository,收到 `RefreshBatch::Core` 后刷新权威 snapshot、按需接通/关闭 MessageBus,并触发当前列表刷新 -- 首页 `kind/category/tags` 选择状态通过 `FireSessionStore.currentHomeTopicListScope()/setCurrentHomeTopicListScope(...)` 与 Rust runtime 同步,不再只存在于 ViewModel 本地 -- 平台不再保留去抖和批次编排逻辑 - -#### File: `apps/android-app/.../ui/auth/OnboardingFragment.kt` - -**大幅重写**。删除现有 `restoreSession()` 逻辑,替换为: - -```kotlin -override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - // 启动流程现在由 PreheatGateFragment 处理 - // Onboarding 只负责:未登录时显示登录入口 - observeLoginState() -} -``` - -#### File: `apps/android-app/.../ui/auth/AuthViewModel.kt` - -**大幅重写**。删除所有手动 session 恢复逻辑。ViewModel 只负责: - -- 观察来自 Rust 的 `LoginStateDeterminationState` -- 暴露 `loginState: StateFlow` -- 暴露 `cachedUser: StateFlow` - -#### File: `apps/android-app/.../session/FireSessionStore.kt` - -新增方法(包装 Rust FFI): - -- `suspend fun ensurePreloadedDataLoaded()` -- `suspend fun awaitPreloadedData(): PreloadedDataResultState` -- `suspend fun initializePostUi()` -- `fun currentUserDefaults(): CurrentUserSnapshotState?` -- `fun cachedUser(): CurrentUserSnapshotState?` -- `suspend fun determineLoginState(): LoginStateDeterminationState` -- `suspend fun triggerAppStateRefresh(trigger: RefreshTriggerState)` - -#### File: `apps/android-app/.../data/repository/SessionRepository.kt` - -**大幅简化**。删除所有手动编排逻辑,保留为轻量包装: - -```kotlin -class SessionRepository(private val sessionStore: FireSessionStore) { - suspend fun restoreSession() { - // 现在只是触发 Rust ensurePreloadedDataLoaded - // 实际恢复由 Rust PreloadedDataService + session.json 处理 - } -} -``` - -#### File: `apps/android-app/.../messagebus/FireMessageBusCoordinator.kt` - -修改 `startMessageBus()` 调用,传入 `topicTrackingStateMeta`。 - -#### File: `apps/android-app/src/main/res/navigation/fire_nav_graph.xml` - -修改导航图: - -- Start destination 改为 `preheatGateFragment` -- `preheatGateFragment` → 根据 login state → `homeFragment` 或 `onboardingFragment` -- 删除直接从 `onboardingFragment` 到 `homeFragment` 的 auth check 逻辑(auth check 现在在 PreheatGate 中) - -### Phase 8: 双端 — cf_clearance 自动续期对齐 - -#### File: `apps/ios-app/Sources/FireAppSession/FireCfClearanceRefreshService.swift` - -修改启动条件:只在登录态已由权威 startup/login 路径确认、且 session 具备 `currentUser + canReadAuthenticatedApi + cf_clearance + turnstileSitekey` 时启动。 - -#### Android - -Android 不保留后台 `cf_clearance` 自动续期 service。Cloudflare 续期继续保持为显式的 host-owned challenge WebView 完成路径;删除未接线、判定过时的 `FireCfClearanceService.kt`,避免形成第二套启动条件。 - -### Phase 9: 删除废弃代码 - -#### iOS 删除列表 - -| 文件 | 原因 | -|------|------| -| `App/Startup/FireStartupPreloadCoordinator.swift` | 被 Rust PreloadedDataService 替代 | - -#### Android 删除列表 - -| 文件 | 原因 | -|------|------| -| `apps/android-app/src/main/java/com/fire/app/session/FireCfClearanceService.kt` | 未接线的旧 helper,判定路径与权威 startup/login 状态机不一致 | -| `apps/android-app/src/main/java/com/fire/app/data/repository/SessionRepository.kt` | 仅剩未使用的遗留 session 包装层,不再承担任何 startup 或 topic-detail 运行时职责 | - -### Phase 10: 验证 - -- Rust: `cargo build --workspace` 编译通过 -- Rust: `cargo test --workspace` 全部通过 -- iOS: Xcode 编译通过,冷启动验证完整流程 -- Android: Gradle 编译通过,冷启动验证完整流程 -- 双端交叉验证启动时序对齐规格 Section 16 - -## Architectural Notes - -- **无兼容层**:所有变更均为破坏性重写。不保留旧代码路径,不添加 fallback。 -- **Rust 为唯一逻辑引擎**:启动时序编排、登录态判断、数据刷新全部在 Rust 中。平台只负责 UI 展示和用户交互。 -- **StateObserver 推送模型**:Rust 主动推送 state snapshot 和 refresh event,平台被动接收。平台不轮询 Rust。 -- **session.json + Keychain/Keystore 双层持久化**不变:Rust 持久化完整 session(含 bootstrap、cookies),平台安全存储 auth cookies。 -- **新增 crate 依赖**:`fire-core` 新增对 `fire-store` 的 user cache 表依赖(已有依赖)。 -- **MessageBus 启动时机变化**:从「login 完成即启动」改为「PreheatGate 完成 + 主界面就绪 + 已登录」才启动,对齐规格。 -- **AppStateRefresher 是 Rust 侧单例**:不是平台侧概念。平台只接收 refresh event 并更新 UI。 - -## File Change Summary - -### Rust - -- `crates/fire-models/src/user.rs` — 新增 CurrentUserSnapshot、UserStatus、AvatarUrlCalculator -- `crates/fire-models/src/session.rs` — 新增 PreloadedDataResult、AppStateRefreshEvent、RefreshBatch、RefreshTrigger、PreloadedDataState -- `crates/fire-models/src/lib.rs` — 注册新模块 -- `crates/fire-core/src/preloaded_data.rs` — 新文件:PreloadedDataService -- `crates/fire-core/src/app_state_refresher.rs` — 新文件:AppStateRefresher -- `crates/fire-core/src/core/mod.rs` — 新增 preloaded_data/app_state_refresher 字段和方法 -- `crates/fire-core/src/core/session.rs` — 新增 determine_login_state() -- `crates/fire-core/src/core/auth.rs` — 修改 probe_session() 返回值,新增 refresh_current_user_with_cooldown() -- `crates/fire-core/src/core/messagebus.rs` — 修改 start_message_bus() 接受 meta 参数,对齐规格轮询协议 -- `crates/fire-core/src/lib.rs` — 注册新模块 -- `crates/fire-store/src/lib.rs` — 新增 current_user_cache 表和 CRUD -- `crates/fire-store/src/migrations.rs` — 新增 migration -- `crates/fire-uniffi-session/src/lib.rs` — 新增 6 个 FFI 方法 -- `crates/fire-uniffi-messagebus/src/lib.rs` — 修改 start_message_bus() 签名 -- `crates/fire-uniffi-types/src/records/` — 新增 7 个 FFI record 类型 -- `crates/fire-uniffi/src/lib.rs` — 确保暴露新方法 - -### iOS - -- `apps/ios-app/App/Startup/FireStartupPreloadCoordinator.swift` — **删除** -- `apps/ios-app/App/Startup/FirePreheatGateViewController.swift` — **新文件**:PreheatGate -- `apps/ios-app/App/Startup/FireStartupErrorView.swift` — **新文件**:错误页面 -- `apps/ios-app/App/Startup/FireAppStateRefresher.swift` — **新文件**:刷新去抖 -- `apps/ios-app/App/ViewModels/FireAppViewModel.swift` — **大幅重写**:删除手动编排,改用 Rust 驱动 -- `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` — 新增 7 个 FFI 包装方法 -- `apps/ios-app/App/Core/FireRootCoordinator.swift` — UIKit PreheatGate → Onboarding/MainTab root owner -- `apps/ios-app/App/Core/FireMainTabBarController.swift` — UIKit authenticated tab shell -- `apps/ios-app/App/Views/Other/FireOnboardingView.swift` — 重写为 UIKit -- `apps/ios-app/App/Navigation/FireMessageBusCoordinator.swift` — 修改 MessageBus 启动参数 -- `apps/ios-app/App/Core/SessionState+Helpers.swift` — 新增 fromPreloadedData() -- `apps/ios-app/Sources/FireAppSession/FireCfClearanceRefreshService.swift` — 修改启动条件 - -### Android - -- `apps/android-app/.../ui/startup/PreheatGateFragment.kt` — **新文件**:PreheatGate -- `apps/android-app/.../ui/startup/PreheatGateLayout.kt` — **新文件**:启动布局 -- `apps/android-app/.../startup/AppStateRefresher.kt` — **新文件**:刷新去抖 -- `apps/android-app/.../ui/auth/OnboardingFragment.kt` — **大幅重写** -- `apps/android-app/.../ui/auth/AuthViewModel.kt` — **大幅重写** -- `apps/android-app/.../session/FireSessionStore.kt` — 新增 7 个 FFI 包装方法 -- `apps/android-app/.../data/repository/SessionRepository.kt` — **大幅简化** -- `apps/android-app/.../messagebus/FireMessageBusCoordinator.kt` — 修改 MessageBus 启动参数 -- `apps/android-app/.../session/FireCfClearanceService.kt` — 修改启动条件 -- `apps/android-app/src/main/res/navigation/fire_nav_graph.xml` — 修改 start destination diff --git a/docs/architecture/fire-native-architecture.md b/docs/architecture/fire-native-architecture.md index c3dc7a5b..7bd3ad3d 100644 --- a/docs/architecture/fire-native-architecture.md +++ b/docs/architecture/fire-native-architecture.md @@ -121,7 +121,7 @@ Rich text render instruction generation. #### fire-core -Core orchestration engine. Owns session state, networking, API orchestration, and delegates to subsystems. Large modules live as directories (`core/network/`, `core/session/`, `core/chat/`, `core/interactions/`, `core/notifications/`, `diagnostics/`, `topic_payloads/`); see [2026-09-23-page-and-rust-module-splits.md](2026-09-23-page-and-rust-module-splits.md). +Core orchestration engine. Owns session state, networking, API orchestration, and delegates to subsystems. Large modules live as directories (`core/network/`, `core/session/`, `core/chat/`, `core/interactions/`, `core/notifications/`, `diagnostics/`, `topic_payloads/`); see [2026-09-25-module-boundaries.md](2026-09-25-module-boundaries.md). - **Networking**: openwire client + optional DoH `DnsResolver` (user-configurable endpoint, default off) + transparent gzip/zlib/brotli/zstd response compression + request epoch guard + CSRF retry + auth signal/probe policy + Cloudflare challenge handler retry + logging - **Session management**: Cookie sync, Bootstrap parsing, login state machine @@ -252,7 +252,11 @@ apps/ios-app/ FireAppDelegate.swift # UIKit @main, process lifecycle, push registration FireSceneDelegate.swift # UIWindowScene owner FireRootCoordinator.swift # Root/auth/route coordinator (launch↔main two-state) + FireRootCoordinator+*.swift # Authentication, root presentation, routing, APM FireMainTabBarController.swift # Authenticated UIKit tab shell + FireMainNavigationController.swift # Shared tab/secondary navigation shell + FireMainCardAnimator.swift # Full-screen card transition animator + Components/ # Shared SwiftUI components, avatar, remote image pipeline Theme/ FireDesignTokens.swift # Cross-platform design constants @@ -293,11 +297,16 @@ apps/ios-app/ TopicDetail/ Controller/FireTopicDetailViewController.swift - Controller/FireTopicDetailInteractionCoordinator.swift + Controller/FireTopicDetailViewController+Reactions.swift + Controller/FireTopicDetailViewController+PostManagement.swift + Controller/FireTopicDetailViewController+TopicVoting.swift + Controller/FireTopicDetailViewController+PollVoting.swift Controller/FireTopicDetailSearchCoordinator.swift Controller/FireTopicSearchBar.swift Feed/FireTopicDetailFeedController.swift + Feed/FireTopicDetailFeedController+*.swift Feed/FireTopicDetailFeedCellFactory.swift + Feed/FireTopicDetailFeedCellFactory+*.swift Feed/FireTopicDetailRuntimeSnapshotBuilder.swift Support/FireTopicListMetricPresentation.swift # Texture post nodes remain under ListKit/TopicDetail/ @@ -366,7 +375,11 @@ apps/ios-app/ Image/ FireImageBridge.swift # Rust decoded pixels → CGImage → Texture / Nuke RichText/ - FireRichTextRenderer.swift # RenderBlock nodes → NSAttributedString + FireRichTextModels.swift + FireRichTextAttributedStringBuilder*.swift # Single node → NSAttributedString render chain + FireRichTextEmojiAttachment.swift + FireRichTextTextView.swift + FireRichTextView.swift # Transitional SwiftUI bridge Widgets/ FireAvatarView.swift FireActionButton.swift diff --git a/docs/architecture/login-cf-cookie-v0218-migration-plan.md b/docs/architecture/login-cf-cookie-v0218-migration-plan.md deleted file mode 100644 index 0e16683b..00000000 --- a/docs/architecture/login-cf-cookie-v0218-migration-plan.md +++ /dev/null @@ -1,734 +0,0 @@ -# Migrate Login, Cloudflare, and Cookies to the v0.2.18 Knowledge Contract - -## Breaking Change Notice - -This is a breaking apps/session refactor. Fire must stop treating the -Discourse Ember `/login` page as the password-login path and must expose richer -cookie/session records over UniFFI. Existing platform login controllers, cookie -replay assumptions, and low-confidence `name=value` cookie snapshots are not -sufficient for the v0.2.18-derived behavior now documented in `docs/knowledge/`. - -Consumer migration: - -1. Replace full-page WebView password-login callers with a native form plus - minimal WebView JS login dialog. -2. Replace `PlatformCookieState` usage with expanded canonical cookie records - that preserve host-only, Secure, HttpOnly, SameSite, Partitioned, expiry, - creation time, version, source, and trust. -3. Route WebView login `{phase,status,body}` through the shared Rust classifier. -4. Treat Rust canonical cookie/session state as authoritative; platform code - only reads/writes/deletes native WebView cookies. - -## Feasibility Assessment - -The migration is fully feasible. Fire already has iOS and Android WebView login -controllers, Cloudflare challenge handlers, platform cookie extraction hooks, -UniFFI session APIs, Rust auth epochs, bootstrap refresh, conservative logout -probes, Cloudflare `403`/`429` detection, and cookie replay/scoring foundations. -The missing pieces are the minimal WebView-owned login transaction, canonical -cookie version/freshness arbitration, cookie sweep/self-healing, and a -pre-dispatch CF freeze gate. Fully feasible. - -## Current Surface Inventory - -- `docs/knowledge/discourse-webview-login-guide.md` -- authoritative - stack-neutral password-login contract. -- `docs/knowledge/discourse-cloudflare-challenge-guide.md` -- authoritative - challenge detection, verification, and freeze contract. -- `docs/knowledge/discourse-cookie-session-state-guide.md` -- authoritative - canonical cookie, priming, sweep, and self-healing contract. -- `docs/knowledge/api/02-auth-and-session.md` -- auth/session endpoint - reference and login boundary summary. -- `docs/knowledge/api/01-global-conventions.md` -- shared cookie, CSRF, status, - and Cloudflare signal conventions. -- `apps/ios-app/App/Views/Other/FireLoginWebView.swift` -- current full - WebView login surface; replace normal password path. -- `apps/ios-app/App/ViewModels/FireAppViewModel.swift` -- current login - presentation and session application orchestration. -- `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- Swift actor - facade over session UniFFI APIs. -- `apps/ios-app/Sources/FireAppSession/FireWebViewLoginCoordinator.swift` -- - current WebKit cookie extraction and login finalization helper. -- `apps/ios-app/Sources/FireAppSession/FireWebViewBrowserProfile.swift` -- - shared WKWebView profile, UA, scripts, and login browser configuration. -- `apps/ios-app/Sources/FireAppSession/FireCloudflareChallengeCoordinator.swift` - -- current platform CF challenge handler. -- `apps/ios-app/Sources/FireAppSession/FireCfClearanceRefreshService.swift` -- - hidden clearance refresh and challenge-cookie coordination. -- `apps/android-app/src/main/java/com/fire/app/ui/auth/LoginWebViewFragment.kt` - -- current full WebView login fragment; replace normal password path. -- `apps/android-app/src/main/java/com/fire/app/session/FireLoginScripts.kt` -- - current `/login` probing scripts; replace with minimal login document builder. -- `apps/android-app/src/main/java/com/fire/app/session/FireWebViewLoginCoordinator.kt` - -- current WebView state capture and low-confidence cookie parsing. -- `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- - Android wrapper over session UniFFI APIs. -- `apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeActivity.kt` - -- current foreground CF challenge WebView. -- `apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt` - -- current blocking CF challenge callback. -- `apps/android-app/src/main/java/com/fire/app/ui/webview/FireWebViewSupport.kt` - -- shared Android WebView settings and UA handling. -- `crates/fire-models/src/cookie.rs` -- current cookie records; expand to - canonical cookie metadata and sweep records. -- `crates/fire-models/src/session.rs` -- current session state and login - phase records; add WebView login classifier records and CF request modes. -- `crates/fire-core/src/cookies.rs` -- current OpenWire cookie jar; replace - scoring/merge with canonical save/load/freshness/sweep planning. -- `crates/fire-core/src/core/session.rs` -- current - `finalize_login_from_webview`, platform cookie apply, and challenge completion. -- `crates/fire-core/src/core/network.rs` -- request execution, CSRF retry, - CF detection, and auth signal classification. -- `crates/fire-core/src/core/cf_challenge.rs` -- CF runtime state and - platform handler registry. -- `crates/fire-core/src/core/auth.rs` -- CSRF refresh, bootstrap refresh, - probes, and passive logout. -- `crates/fire-core/src/app_state_refresher.rs` -- login-ready and - post-login refresh batches. -- `crates/fire-uniffi-session/src/lib.rs` -- session FFI methods. -- `crates/fire-uniffi-session/src/records.rs` -- session/cookie FFI records. -- `crates/fire-store/src/cookie_replay.rs` -- transitional replay queue. -- `crates/fire-store/src/migrations.rs` -- storage migrations if canonical - cookies need persistence changes. - -## Design - -Fire implements the behavior documented in `docs/knowledge/` with the repository -ownership split: - -- Platform owns native login UI, minimal WebView login/challenge execution, - native cookie store reads/writes/deletes, user-agent repair, and secure - credential storage. -- Rust owns login result parsing, session state, canonical cookie arbitration, - sweep planning, self-healing, API orchestration, CF request blocking, auth - generation, and login-ready refresh. - -### Key Design Decisions - -1. **Use WebView-owned login requests** -- Password login opens a small WebView - document with base origin `https://linux.do/`; JS runs `/session/csrf`, - hCaptcha create, and `/session.json`. Rejected alternative: Rust/OpenWire - performs `/session/csrf` for login. Reason: login CSRF can be browser - fingerprint sensitive, and the knowledge contract requires WebView-owned - requests. - -2. **Delete the old Ember `/login` implementation plan** -- The older plan is - removed instead of marked superseded. Rejected alternative: keep it as - historical guidance. Reason: the repository no longer depends on reference - source files, so stale implementation docs must not compete with - `docs/knowledge/`. - -3. **Make `docs/knowledge/` the only protocol authority** -- Architecture plans - and implementation code cite stack-neutral knowledge docs, not reference - project paths. Rejected alternative: keep source-file references as comments. - Reason: the reference submodule is not an implementation dependency. - -4. **Parse `session.json` in Rust** -- iOS and Android send raw - `{phase,status,body}` to Rust and render the returned decision. Rejected - alternative: duplicate parsing in Swift and Kotlin. Reason: 2FA/error mapping - is backend protocol logic. - -5. **Finalize login in one Rust handoff** -- After JS success, platform extracts - live WebView cookies and calls a single async Rust finalizer. Rust advances - auth generation, applies trusted cookies, refreshes bootstrap with an 8 - second timeout, and always notifies login-ready. Rejected alternative: - platform-triggered refresh batches after finalization. Reason: split - finalization can permanently wedge UI when platform lifecycle objects - disappear. - -6. **Use Rust canonical cookies with platform action plans** -- Rust stores - metadata, version, trust, and winner decisions. Platforms execute exact native - cookie actions. Rejected alternative: implement independent sentinel logic in - Swift and Kotlin. Reason: cookie invariants must be identical across both - platforms. - -7. **Store host-only as metadata, not identity** -- Canonical key is - `(name, normalized_domain, path, partition_key)`. Rejected alternative: - include host-only in the key. Reason: platform WebView APIs often cannot - reliably expose host-only state, and keying by it recreates duplicate - variants. - -8. **Trusted writes bump versions; untrusted reads pass freshness** -- Network - `Set-Cookie`, WebView login success, and confirmed CF values are trusted. - Generic WebView bulk reads are untrusted. Rejected alternative: last writer - wins. Reason: old WebView variants can otherwise overwrite fresh - login/challenge values. - -9. **Freeze business requests during CF verification** -- Rust blocks ordinary - API, MessageBus, and timing requests while `cf_in_progress` is true, except - explicit internal `skip_cf_block` requests. Rejected alternative: allow more - requests to discover the same challenge. Reason: continued traffic with stale - clearance can create request floods and retry loops. - -### Concrete Type / Interface Definitions - -Rust login classifier records: - -```rust -pub enum WebViewLoginPhase { - Csrf, - Hcaptcha, - Session, - Exception, -} - -pub struct WebViewLoginJsResult { - pub phase: WebViewLoginPhase, - pub status: u16, - pub body: String, -} - -pub enum WebViewLoginDecision { - Success, - NeedSecondFactor(SecondFactorRequirement), - RetryCloudflare, - Failure(LoginFailureKind), -} - -pub struct SecondFactorRequirement { - pub totp_enabled: bool, - pub security_key_enabled: bool, - pub backup_enabled: bool, - pub message: Option, -} -``` - -Rust canonical cookie records: - -```rust -pub enum CookieSource { - Unknown, - NetworkSetCookie, - WebViewLogin, - WebViewChallenge, - WebViewBulkRead, - ManualRestore, -} - -pub enum CookieTrust { - Trusted, - Untrusted, -} - -pub enum CookieSameSite { - Unspecified, - Lax, - Strict, - None, -} - -pub struct CanonicalCookie { - pub name: String, - pub value: String, - pub domain: Option, - pub path: String, - pub host_only: bool, - pub secure: bool, - pub http_only: bool, - pub same_site: CookieSameSite, - pub partition_key: Option, - pub partitioned: bool, - pub expires_at_unix_ms: Option, - pub max_age_seconds: Option, - pub creation_time_unix_ms: i64, - pub last_access_time_unix_ms: i64, - pub version: u64, - pub source: CookieSource, - pub raw_set_cookie: Option, - pub origin_url: Option, -} -``` - -Rust/platform cookie action records: - -```rust -pub enum CookieSweepIntent { - EnsureUnique, - Delete, -} - -pub struct WebViewCookieInfo { - pub name: String, - pub value: String, - pub domain: Option, - pub path: Option, - pub host_only: Option, - pub secure: Option, - pub http_only: Option, - pub same_site: Option, - pub expires_at_unix_ms: Option, -} - -pub enum WebViewCookieAction { - SetRaw { url: String, set_cookie: String }, - DeleteExact { url: String, name: String, domain: Option, path: String }, - DeleteByName { url: String, name: String }, -} - -pub struct CookieSweepPlan { - pub name: String, - pub intent: CookieSweepIntent, - pub actions: Vec, - pub selected_winner: Option, -} - -pub enum CookieSelfHealingPhase { - Sweep, - NuclearReset, -} - -pub struct CookieSelfHealingRequest { - pub operation: String, - pub request_url: String, - pub target_url: String, - pub phase: CookieSelfHealingPhase, - pub attempt: u8, - pub cookie_names: Vec, - pub session_epoch: u64, -} - -pub struct CookieSelfHealingResult { - pub completed: bool, - pub session_epoch: u64, -} -``` - -Usage example: - -```rust -let decision = core.classify_webview_login_result(js_result)?; - -match decision { - WebViewLoginDecision::Success => { - let cookies = platform.extract_webview_cookie_info("https://linux.do/").await?; - core.finalize_webview_js_login(identifier, browser_ua, cookies).await?; - } - WebViewLoginDecision::NeedSecondFactor(requirement) => { - platform.show_totp_dialog(requirement).await?; - } - WebViewLoginDecision::RetryCloudflare => { - platform.verify_cloudflare_now().await?; - } - WebViewLoginDecision::Failure(kind) => return Err(kind.into()), -} -``` - -## Phased Implementation - -## Phase 1: Documentation Authority Reset - -**File: `docs/knowledge/discourse-webview-login-guide.md`** - -- Keep this as the authoritative password-login protocol. -- Include JS bridge names, endpoint order, request headers, hCaptcha fallback, - 2FA retry, CSRF CF retry, priming, and finalization. - -**File: `docs/knowledge/discourse-cloudflare-challenge-guide.md`** - -- Keep this as the authoritative challenge protocol. -- Include `403 || 429`, `cf-mitigated: challenge`, request modes, - `cf_in_progress`, manual verify, freshness filtering, and UA repair. - -**File: `docs/knowledge/discourse-cookie-session-state-guide.md`** - -- Keep this as the authoritative cookie/session invariant protocol. -- Include canonical fields, storage key, freshness, explicit delete, priming, - sentinel sweep, winner selection, nuclear reset, and self-healing. - -Rationale: implementation must be driven by framework-neutral knowledge docs, -not by a removed reference submodule or stale full-browser login plan. - -## Phase 2: Rust Login Protocol And Finalization - -**File: `crates/fire-models/src/session.rs`** - -- Add `WebViewLoginPhase`, `WebViewLoginJsResult`, `WebViewLoginDecision`, - `SecondFactorRequirement`, `LoginFailureKind`, and `CloudflareRequestMode`. -- Keep response-body fields raw so Rust can parse once and platforms can render - typed decisions. - -**File: `crates/fire-core/src/core/session.rs`** - -- Add `classify_webview_login_result(result) -> WebViewLoginDecision`. -- Implement reason mapping from - `docs/knowledge/discourse-webview-login-guide.md`. -- Add async `finalize_webview_js_login(...)`: - - advance auth generation first; - - apply WebView login cookies as trusted; - - persist username and browser UA hints; - - read `_t` from canonical cookies; - - run login-ready refresh with 8 second timeout; - - always notify session observers in finalization fallback. -- Keep `finalize_login_from_webview` only as a temporary compatibility wrapper - until both platforms migrate. - -**File: `crates/fire-core/src/app_state_refresher.rs`** - -- Add a login-finalization refresh entry that can run from Rust-owned state. -- Ensure delayed batches do not depend on platform view/fragment lifetimes. - -**File: `crates/fire-uniffi-session/src/lib.rs`** - -- Expose `classify_webview_login_result`. -- Expose async `finalize_webview_js_login`. - -**File: `crates/fire-uniffi-session/src/records.rs`** - -- Add FFI records for login JS result, login decision, second-factor - requirement, failure kind, and CF request mode. - -## Phase 3: Rust Canonical Cookie Engine - -**File: `crates/fire-models/src/cookie.rs`** - -- Add `CanonicalCookie`, `CookieSource`, `CookieTrust`, `CookieSameSite`, - `WebViewCookieInfo`, `WebViewCookieAction`, `CookieSweepPlan`, and - `NuclearResetPlan`. -- Implement storage key, freshness comparison, Set-Cookie reconstruction, and - host-only normalization. - -**File: `crates/fire-core/src/cookies.rs`** - -- Parse `Set-Cookie` into canonical cookies with Secure, HttpOnly, SameSite, - host-only, partition, expiry, creation time, and raw header. -- Save trusted writes with version bump on value change. -- Save untrusted writes only when fresher. -- Add `delete_by_name(uri, name)` that bypasses freshness. -- Build request cookie headers from canonical cookies with one critical winner. -- Preserve `_t` and `_forum_session` as host-only for `linux.do`. - -**File: `crates/fire-store/src/migrations.rs`** - -- Add canonical cookie persistence migration if cookies are not stored in the - existing session file. -- Preserve old replay data for transition. - -**File: `crates/fire-store/src/cookie_replay.rs`** - -- Keep as a compatibility source for WebView priming until canonical priming is - complete. -- Add removal notes for the later cleanup phase. - -## Phase 4: Cookie Sentinel, Priming, And Self-Healing - -**File: `crates/fire-core/src/cookies.rs`** - -- Add sweep plan generation for `EnsureUnique` and `Delete`. -- Implement winner rules from - `docs/knowledge/discourse-cookie-session-state-guide.md`. -- Add nuclear reset plan generation. -- Add priming payload generation for `https://linux.do/`. -- Add commit hooks for platform sweep results. - -**File: `crates/fire-core/src/core/network.rs`** - -- Add self-healing branch for `401`, `419`, and strong logged-out signals: - sweep + retry, then nuclear reset + retry once, with recursion guard. -- Keep conservative session probe for true logout after healing fails. - -**File: `crates/fire-core/src/core/cookie_healing.rs`** - -- Add the Rust-owned platform handler registry used by the network - self-healing branch. -- Keep platform cookie-store mutation behind an explicit handler so normal API - orchestration stays in Rust while native cookie stores remain platform-owned. - -**File: `crates/fire-uniffi-session/src/lib.rs`** - -- Expose `webview_priming_payload`. -- Expose `cookie_sweep_plan`, `cookie_nuclear_reset_plan`, and - `commit_cookie_sweep_result`. -- Expose `register_cookie_self_healing_handler` and - `unregister_cookie_self_healing_handler`. - -**File: `crates/fire-uniffi-session/src/records.rs`** - -- Add records for WebView cookie snapshots, raw set/delete actions, sweep - status, and nuclear reset result. -- Add `CookieSelfHealingPhaseState`, `CookieSelfHealingRequestState`, - `CookieSelfHealingResultState`, and the foreign `CookieSelfHealingHandler` - trait. - -Current branch status: - -- Rust canonical cookie records, freshness arbitration, explicit delete, - host-only normalization, request header generation, and network `Set-Cookie` - ingestion are implemented. -- Legacy `PlatformCookie` inputs are now bridged into canonical state with - source/trust distinctions so existing native call sites can migrate - incrementally. -- `webview_priming_payload` is exposed over UniFFI and returns raw - `Set-Cookie` actions reconstructed from canonical state. -- Sweep plan generation and nuclear reset plan generation are implemented and - exposed over UniFFI. -- iOS and Android now have stack-local minimal login HTML/JS builders and unit - tests for the WebView-owned CSRF, hCaptcha, and `/session.json` transaction. -- iOS and Android session facades now expose login classification, priming, - sweep, and nuclear-reset APIs; both WebView login coordinators can execute - Rust `SetRaw`, `DeleteExact`, and `DeleteByName` cookie actions against their - native WebView cookie stores. -- The primary iOS and Android password-login entries now use native credential - fields plus a minimal same-origin WebView document for hCaptcha and - `window.__fireLogin`; they no longer load the Discourse Ember `/login` page as - the normal password-login path. -- Login CSRF Cloudflare failures now trigger a one-shot platform foreground - verification path, apply returned challenge cookies to Rust, wait briefly for - platform cookie propagation, re-prime the same live login WebView, and re-run - `window.__fireLogin` with the original hCaptcha/second-factor arguments. -- Rust detects Cloudflare challenge responses on `403` or `429`, treats - `cf-mitigated: challenge` as sufficient even for non-HTML bodies, marks - verification as in-progress, blocks ordinary business requests before - dispatch, and allows only explicit `skip_cf_block` retries through the gate. -- Sweep commit hooks are now implemented: iOS and Android execute Rust - WebView cookie action plans, re-sample the platform cookie store, and commit - the post-sweep winner/delete result back into Rust canonical cookie state. -- Cookie self-healing retry orchestration is implemented in Rust network - execution. `401`, `419`, and strong `discourse-logged-out` responses trigger - sweep + retry twice, then nuclear reset + retry once, guarded by a request - marker to prevent recursive healing. -- iOS and Android register runtime cookie self-healing handlers. The handlers - call the existing platform WebView cookie sweep/nuclear-reset action - executor against the default browser cookie store and return the observed - session epoch to Rust. -- Platform cookie extraction now treats hidden `cf_clearance` SameSite metadata - as `SameSite=None` when native APIs omit it; raw network `Set-Cookie` - metadata still wins when present. -- Remaining follow-up hardening is higher-fidelity cookie-store observation and - platform metadata extraction where native APIs expose it. The current login, - CF, sweep, and self-healing paths no longer depend on the old Ember `/login` - flow. - -## Phase 5: Cloudflare Freeze Gate - -**File: `crates/fire-core/src/core/cf_challenge.rs`** - -- Expose observable `cf_in_progress`. -- Add request mode fields and manual-verify bypass flags. -- Track fresh `cf_clearance` value returned by platform verification. - -**File: `crates/fire-core/src/core/network.rs`** - -- Add pre-dispatch CF block: - - reject ordinary business requests while `cf_in_progress`; - - allow only `skip_cf_block` internal work; - - classify blocked requests separately from network failures. -- Detect CF on `403 || 429` plus Cloudflare-specific header/body signals. - -**File: `crates/fire-core/src/core/interactions.rs`** - -- Drop pending topic timings and suppress timing accumulation while - `cf_in_progress`. - -## Phase 6: iOS Native Path - -**File: `apps/ios-app/App/Views/Other/FireLoginWebView.swift`** - -- Replace the normal full-page password login with native form plus modal - minimal WebView login dialog. -- Load inline HTML with base URL `https://linux.do/`. -- Register bridge handlers `hcaptcha_pass`, `hcaptcha_error`, - `hcaptcha_expired`, and `login_result`. -- Keep the same live WKWebView for TOTP retry. - -**File: `apps/ios-app/Sources/FireAppSession/FireWebViewBrowserProfile.swift`** - -- Add a lean login-dialog WKWebView configuration. -- Omit Ember preloaded capture, credential autofill hooks, and fingerprint - interception from the minimal login dialog. -- Keep browser-compatible UA and required hCaptcha compatibility settings. - -**File: `apps/ios-app/Sources/FireAppSession/FireWebViewLoginCoordinator.swift`** - -- Add priming into a specific WKWebView from Rust priming payload. -- Add full cookie extraction with host-only and SameSite mapping where WebKit - exposes it. -- Add exact native set/delete action execution for Rust sweep plans. -- Register `WKHTTPCookieStoreObserver`, debounce external changes, and suppress - observer loops during internal writes. - -**File: `apps/ios-app/Sources/FireAppSession/FireCloudflareChallengeCoordinator.swift`** - -- Refactor full-screen challenge into contextual/manual verification behavior. -- Return fresh `cf_clearance`, related cookies, and browser UA to Rust. - -**File: `apps/ios-app/Sources/FireAppSession/FireCfClearanceRefreshService.swift`** - -- Invalidate priming before deleting old challenge cookies. -- Re-read Rust canonical state before every async cookie write batch. - -**File: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift`** - -- Bridge new login classifier, finalizer, priming, sweep, and CF APIs. - -**File: `apps/ios-app/App/ViewModels/FireAppViewModel.swift`** - -- Route login entry to the new native form + JS dialog. -- Remove primary-path `/login` readiness polling. -- Apply the Rust finalizer session snapshot as the single success handoff. - -## Phase 7: Android Native Path - -**File: `apps/android-app/src/main/java/com/fire/app/ui/auth/LoginWebViewFragment.kt`** - -- Replace the normal full-page password login with native form plus dialog - WebView. -- Use `loadDataWithBaseURL("https://linux.do/", ...)`. -- Register JS interfaces for hCaptcha and login result callbacks. -- Keep the same WebView instance for TOTP retry. - -**File: `apps/android-app/src/main/java/com/fire/app/session/FireLoginScripts.kt`** - -- Replace `/login` page probing scripts with a minimal login HTML/JS builder. -- Name the new function `window.__fireLogin`. -- Do not manually forge browser-owned headers. - -**File: `apps/android-app/src/main/java/com/fire/app/session/FireWebViewLoginCoordinator.kt`** - -- Add priming from Rust canonical payload into the target WebView. -- Extract full cookie info where WebView APIs expose it. -- Treat `CookieManager.getCookie()` as low-confidence fallback only. -- Force `_t` and `_forum_session` host-only metadata when Android fields are - ambiguous. -- Execute Rust sweep set/delete actions through CookieManager/native helpers. - -**File: `apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeActivity.kt`** - -- Mirror the CF verification contract from the knowledge guide. -- Return fresh `cf_clearance`, all related cookies, and browser UA. - -**File: `apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt`** - -- Pass request mode and manual-verify options through the platform handler. - -**File: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt`** - -- Bridge new login classifier, finalizer, priming, sweep, and CF APIs. - -**File: `apps/android-app/src/main/java/com/fire/app/ui/webview/FireWebViewSupport.kt`** - -- Keep browser-compatible settings for login/challenge WebViews. -- Ensure JS bridge exposure is limited to the minimal login dialog and trusted - challenge surfaces. - -## Phase 8: Tests And Verification - -**File: `crates/fire-core/tests/login_finalization.rs`** - -- Add classifier tests for success, 2FA, known failure reasons, non-JSON body, - and CSRF CF retry. -- Add finalizer tests proving timeout still notifies session-ready. - -**File: `crates/fire-core/tests/session_flow.rs`** - -- Add canonical cookie tests: - - trusted value bumps version; - - untrusted stale WebView read is ignored; - - explicit delete removes persistent `cf_clearance`; - - `_t` remains host-only; - - winner rule picks non-canonical WebView value when multiple variants exist. - -**File: `crates/fire-core/tests/network.rs`** - -- Add CF tests: - - `429` with `cf-mitigated: challenge` enters CF path; - - ordinary `429` does not; - - business request is blocked during `cf_in_progress`; - - `skip_cf_block` internal retry proceeds. - -**File: `apps/ios-app/Tests/Unit/FireSessionStoreTests.swift`** - -- Add tests for login result routing, priming calls, trusted cookie extraction, - and host-only mapping. - -**File: `apps/android-app/src/test/java/com/fire/app/session`** - -- Add tests for minimal login HTML construction, JS bridge result routing, - low-confidence fallback mapping, and host-only session forcing. - -Verification commands: - -```bash -cargo test --workspace -cd apps/android-app && ./gradlew testDebugUnitTest -cd apps/ios-app && xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -``` - -Current branch targeted verification: - -```bash -cargo test --manifest-path crates/fire-core/Cargo.toml self_heal -cargo test --manifest-path crates/fire-uniffi-session/Cargo.toml register_cookie_self_healing_handler -cd apps/android-app && ./gradlew compileDebugKotlin compileDebugUnitTestKotlin testDebugUnitTest --rerun-tasks -x syncFireUniffiDebugBindings --tests com.fire.app.session.FireWebViewCookieActionSupportTest --tests com.fire.app.session.FireLoginScriptsTest -cd apps/ios-app && xcodebuild test -quiet -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -only-testing:FireTests/FireWebViewCookieActionSupportTests -``` - -Note: a full Android `--rerun-tasks` native archive rebuild was attempted, but -the local machine ran out of disk space while writing `libfire_uniffi.a`. The -targeted Android command above still forced Kotlin recompilation and unit tests -against the existing generated UniFFI bindings. - -## Architectural Notes - -- Semver impact: UniFFI records and methods change; generated Swift/Kotlin - bindings must be regenerated in the same implementation branch. -- Object safety / trait coherence: platform cookie actions should use concrete - UniFFI records, not generic Rust traits across FFI. -- Side effects: login finalization advances auth generation before writing new - session state; stale request responses must not write cookies afterward. -- Not changed: Rust/OpenWire remains the HTTP client for normal authenticated - API traffic after login. -- Not changed: platform remains owner of WebView UI, WebView cookie store - mechanics, keychain/keystore, files, media, and notifications. -- New external dependencies: none required initially. -- Removed behavior: normal password login no longer depends on Discourse Ember - `/login`, navigation-to-root success detection, page-bootstrap readiness - polling, or fingerprint upload wait. -- Risk: Android WebView cookie metadata is incomplete on some versions. Treat - those snapshots as low confidence and use Rust canonical metadata when writing - winners. -- Risk: bootstrap refresh after login can hit CF. It must timeout and notify - login-ready instead of blocking UI forever. - -## File Change Summary - -- `docs/architecture/login-cf-cookie-v0218-migration-plan.md` -- rewritten to depend only on `docs/knowledge/`. -- `docs/knowledge/api-overview.md` -- link the login, CF, and cookie authority docs. -- `docs/knowledge/api/01-global-conventions.md` -- link detailed session guides and update CF handling summary. -- `docs/knowledge/api/02-auth-and-session.md` -- update login boundary to the minimal WebView JS flow. -- `docs/knowledge/api/14-misc-apis.md` -- update recommended login order. -- `docs/knowledge/discourse-cloudflare-challenge-guide.md` -- new stack-neutral CF challenge contract. -- `docs/knowledge/discourse-cookie-session-state-guide.md` -- stack-neutral canonical cookie/session contract, including platform SameSite metadata gaps. -- `docs/knowledge/discourse-webview-login-guide.md` -- expanded stack-neutral password-login contract. -- `apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeActivity.kt` -- implement CF verification result handoff. -- `apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt` -- bridge CF request mode/manual verify options. -- `apps/android-app/src/main/java/com/fire/app/session/FireCookieSelfHealingCoordinator.kt` -- bridge Rust cookie self-healing requests to Android WebView cookie actions. -- `apps/android-app/src/main/java/com/fire/app/session/FireLoginScripts.kt` -- build minimal login HTML/JS. -- `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- bridge new FFI login/cookie APIs. -- `apps/android-app/src/main/java/com/fire/app/session/FireWebViewLoginCoordinator.kt` -- implement priming, extraction, and sweep actions. -- `apps/android-app/src/main/java/com/fire/app/ui/auth/LoginWebViewFragment.kt` -- replace full browser login with native form + JS dialog. -- `apps/android-app/src/main/java/com/fire/app/ui/webview/FireWebViewSupport.kt` -- constrain WebView settings and JS bridge exposure. -- `apps/ios-app/App/ViewModels/FireAppViewModel.swift` -- route login and success handoff to the new single path. -- `apps/ios-app/App/Views/Other/FireLoginWebView.swift` -- replace full browser login with native form + JS dialog. -- `apps/ios-app/Sources/FireAppSession/FireCfClearanceRefreshService.swift` -- coordinate priming invalidation and CF refresh races. -- `apps/ios-app/Sources/FireAppSession/FireCloudflareChallengeCoordinator.swift` -- implement CF verification result handoff. -- `apps/ios-app/Sources/FireAppSession/FireCookieSelfHealingCoordinator.swift` -- bridge Rust cookie self-healing requests to WebKit cookie actions. -- `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- bridge new FFI login/cookie APIs. -- `apps/ios-app/Sources/FireAppSession/FireWebViewBrowserProfile.swift` -- add lean login-dialog WebView profile. -- `apps/ios-app/Sources/FireAppSession/FireWebViewLoginCoordinator.swift` -- implement priming, extraction, observer, and sweep actions. -- `crates/fire-core/src/app_state_refresher.rs` -- implement bounded login-ready finalization refresh. -- `crates/fire-core/src/cookies.rs` -- implement canonical cookie jar, freshness, sweep planning, priming, and self-healing helpers. -- `crates/fire-core/src/core/auth.rs` -- align probes/passive logout with cookie self-healing. -- `crates/fire-core/src/core/cf_challenge.rs` -- expose CF in-progress state and request modes. -- `crates/fire-core/src/core/cookie_healing.rs` -- register platform cookie self-healing handlers. -- `crates/fire-core/src/core/interactions.rs` -- drop/suppress timings during CF verification. -- `crates/fire-core/src/core/network.rs` -- implement CF pre-dispatch gate, detection, and healing retry guard. -- `crates/fire-core/src/core/session.rs` -- implement WebView login classifier and async finalizer. -- `crates/fire-core/tests/login_finalization.rs` -- add JS login classifier/finalizer tests. -- `crates/fire-core/tests/network.rs` -- add CF detection/freeze/self-healing tests. -- `crates/fire-core/tests/session_flow.rs` -- add canonical cookie versioning and host-only tests. -- `crates/fire-models/src/cookie.rs` -- add canonical cookie and sweep models. -- `crates/fire-models/src/session.rs` -- add WebView login and CF mode records. -- `crates/fire-store/src/cookie_replay.rs` -- keep transitional replay and document removal path. -- `crates/fire-store/src/migrations.rs` -- add canonical cookie persistence migration if needed. -- `crates/fire-uniffi-session/src/lib.rs` -- expose login, priming, sweep, finalizer, and CF APIs. -- `crates/fire-uniffi-session/src/records.rs` -- add expanded cookie and login records. diff --git a/docs/release/README.md b/docs/release/README.md index 01926d65..bbe9a468 100644 --- a/docs/release/README.md +++ b/docs/release/README.md @@ -155,18 +155,16 @@ shape and escape literal `|` characters in cell text. ## Manual Release Inputs -Real screenshots, preview videos, store records, legal review, device performance numbers, and accessibility audit results are not generated by these docs. Record final evidence in `release-gate-evidence.md`; keep P4 roadmap acceptance unchecked until every required gate has completed evidence and the shared P4 evidence suite passes. +Real screenshots, preview videos, store records, legal review, device performance numbers, and accessibility audit results are not generated by these docs. Record final evidence in `release-gate-evidence.md`. -Before marking P4 acceptance complete, run the full release-readiness wrapper: +Before shipping, run the full release-readiness wrapper: ```bash scripts/verify-release-readiness.sh ``` -It runs the shared P4 release evidence suite, roadmap plan contract, roadmap -architecture constraints, roadmap implementation evidence, and roadmap P4 -acceptance verifiers. It is expected to fail until all manual P4 evidence is -complete. +It runs the shared release evidence suite. It is expected to fail until all +manual release evidence is complete. The shared non-recursive P4 evidence suite can also be checked directly: @@ -192,8 +190,7 @@ evidence rows, duplicate performance/accessibility screen or audit coverage rows, invalid or future dates, placeholder metadata fields, dead local evidence paths, malformed evidence URLs, malformed URL hosts, placeholder URL hosts, extra Markdown table columns, missing Markdown table boundaries, and weak -accepted-waiver notes are rejected, and that checked P4 roadmap acceptance is -allowed only when the full fixture suite passes. +accepted-waiver notes are rejected. The final evidence register can also be checked directly: @@ -218,28 +215,7 @@ notes metadata still contain fake, mock, placeholder, dummy, synthetic, TODO/TBD calendar dates or future dates, or whose rows have missing or extra Markdown table columns. -The roadmap acceptance boxes can also be checked directly: - -```bash -scripts/verify-roadmap-p4-acceptance.sh -``` - -This verifier fails if the design document's P4 acceptance rows are renamed, -duplicated, or missing. If any P4 acceptance box is checked, it also requires -the shared non-recursive P4 evidence suite to pass: store marketing assets, -performance benchmarks, accessibility audit, internal testing evidence, privacy -review evidence, and release-gate evidence. - -The roadmap document set can be checked directly: - -```bash -scripts/verify-roadmap-plan-contract.sh -``` - -This verifier requires the one design spec and the four implementation plans to -stay present with the expected P1/P2/P3/P4 top-level task counts. - -The roadmap architecture constraints can also be checked directly: +Architecture constraints can also be checked directly: ```bash scripts/verify-roadmap-architecture-constraints.sh @@ -248,13 +224,3 @@ scripts/verify-roadmap-architecture-constraints.sh This verifier checks the platform/Rust ownership boundary, current minimum API targets, iOS topic-detail native runtime path, and reference/infrastructure repository boundaries. - -The checked P1-P3 roadmap acceptance claims can be checked directly: - -```bash -scripts/verify-roadmap-implementation-evidence.sh -``` - -This verifier checks concrete code paths, files, and scoped cleanup patterns -that support the completed P1-P3 acceptance rows. It is not a substitute for -the manual P4 release evidence verifiers. diff --git a/docs/superpowers/plans/2026-06-04-discourse-startup-alignment.md b/docs/superpowers/plans/2026-06-04-discourse-startup-alignment.md deleted file mode 100644 index 31a1fa1c..00000000 --- a/docs/superpowers/plans/2026-06-04-discourse-startup-alignment.md +++ /dev/null @@ -1,776 +0,0 @@ -# Discourse 启动阶段对齐实现计划 - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** 将 Fire 启动流程完全对齐 `docs/knowledge/discourse-startup-implementation-spec.md`,包括首页 HTML 并行请求、PreheatGate 阻塞、登录态判断路径、AppStateRefresher 分批刷新、MessageBus 初始化。 - -**Architecture:** Rust 统一拥有 `PreloadedDataService`(首页 HTML 请求与解析)、启动期登录态判定、`AppStateRefresher`(分批刷新编排)、MessageBus 启动参数准备。平台只保留 `PreheatGate` 和主界面切换等 UI 职责;平台不得再自行编排 session 恢复、bootstrap 刷新、首页 feed 预刷、MessageBus 提前启动等启动业务逻辑。 - -**Tech Stack:** Rust + UniFFI + tokio + openwire + SQLite / Swift + UIKit + Texture / Kotlin + androidx + RecyclerView + Paging3 - -**Design Doc:** `docs/architecture/discourse-startup-implementation-plan.md` - -## Audit Corrections (2026-06-05) - -本计划基于当前仓库审查结果进行修正。以下事项为**强约束**,后续执行不得回退: - -- `PreheatGate` 必须等待首页 HTML 请求进入**终态**(成功或失败)。不得把 `Loading` / in-flight 状态映射为 `Ready`。 -- 启动登录态判断必须以 Rust 权威异步路径为准:`currentUser` → 无 `_t` → `NotLoggedIn` → 有 `_t` 时 probe `/session/current.json`。平台不得自行省略 probe 分支。 -- `AppStateRefresher` 是 Rust 侧单例编排器;平台只负责触发和消费刷新事件,不得重新手写等价的刷新流程。 -- `MessageBus` 的 `topicTrackingStateMeta` 参数变更必须在 Rust FFI、iOS wrapper、Android wrapper、所有调用点一次性收口,不能只改 Rust。 -- 当前仓库已经存在部分实现,下面的 Task 4-13 都应视为**纠偏重构**,不是从零新增。任何与当前代码冲突的旧步骤,以本修正版为准。 -- 破坏性重构要求继续生效:删除或停用旧启动路径,不保留兼容层,不允许新旧编排并存。 - -## Implementation Status (2026-06-05) - -- 已落地:`PreloadedDataService` 终态等待 / single-flight / `Notify` 并发模型、`parse_preloaded_payload()` 规范化复用、启动 `_t -> /session/current.json` probe 判定、invalid probe 的 Rust 本地登出清理。 -- 已落地:`AppStateRefresher` 现在负责 Rust 侧 debounce、第一批 bootstrap 强制刷新、第二批 `user summary` / `bookmarks` / `read history` / `recent notifications` 刷新,并已有 integration test 覆盖立即执行、延迟执行、2 秒去抖。 -- 已落地:`topicTrackingStateMeta` 签名已贯通 Rust FFI、iOS wrapper、Android wrapper 与宿主调用点;`cargo build -p fire-core`、`cargo test -p fire-core --test startup_alignment --test app_state_refresher`、`./gradlew assembleDebug`、`xcodebuild ... build` 当前均通过。 -- 已落地:preloaded current-user cache 会随 bootstrap 更新同步,并在 `logout_local()` 时清空,避免同进程内登录态切换继续暴露旧 `currentUser`。 -- 已落地:iOS `loadInitialState()` 不再直接执行启动登录态判定 / 首页 feed 首刷 / MessageBus 启动;`FirePreheatGateViewController` 等待 preload 终态后,由 `completeStartupAfterPreheat()` 统一执行 post-preheat 登录态分流。 -- 已落地:Android Home 首屏不再额外调用 `refreshSession()` 作为冷启动恢复入口,`HomeViewModel` 直接从 `FireSessionStore` 读取权威 snapshot 并按需接通 topic-list MessageBus 监听。 -- 已落地:Rust `AppStateRefresher` 批次事件已经通过 UniFFI callback 暴露,iOS 现已使用统一 refresh callback 驱动 auth 后首页列表强刷与通知状态同步,不再由 `completeLogin()` 手写首页刷新 / MessageBus 启动决策。 -- 已落地:Android 现在也通过共享 `FireAppStateRefreshRepository` 消费 Rust refresh callback;`PreheatGateFragment` / `LoginWebViewFragment` 不再只 fire-and-forget,`HomeViewModel` 会在 `RefreshBatch::Core` 后刷新权威 snapshot、按需接通/关闭 MessageBus,并触发当前列表刷新。 -- 已落地:iOS `FireCfClearanceRefreshService` 现在显式依赖“登录态已确认” gate;Android 删除了未接线且判定过时的 `FireCfClearanceService.kt`,继续只保留显式 challenge WebView 的 host-owned 续期路径。 -- 已落地:Rust 现在持有 `current home topic-list scope`(kind/category/tags),双端首页筛选会同步这份权威 scope;`AppStateRefresher` 第一批刷新会据此真实请求当前 tab/topic list,而不是只让平台自己判断该刷哪一路。 -- 已落地:Android 未再保留无用的 `SessionRepository` 壳;startup 侧 direct `restoreSession()` grep 已清零,`refreshBootstrapIfNeeded()` 的剩余调用点都只在 login/profile 等非 startup 读写路径。 - -- 待继续审计:spec Section 14 中仓库尚未建模的 provider(如“我的话题”、外部 credit/cdk user-info)当前没有对应产品 surface,本轮未新增这些能力。 - ---- - -### Task 1: 新增 CurrentUserSnapshot 和 UserStatus 数据模型 - -**Files:** -- Modify: `crates/fire-models/src/user.rs` -- Test: `crates/fire-models/src/lib.rs`(在现有测试模块中添加) - -- [ ] **Step 1: 在 `user.rs` 末尾添加 CurrentUserSnapshot 和 UserStatus** - -```rust -// fire-models/src/user.rs — 在文件末尾追加 - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct UserStatus { - pub description: Option, - pub emoji: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct CurrentUserSnapshot { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, - pub animated_avatar: Option, - pub trust_level: u8, - #[serde(default)] - pub status: Option, - pub flair_url: Option, - pub flair_name: Option, - pub flair_bg_color: Option, - pub flair_color: Option, - pub flair_group_id: Option, - pub gamification_score: Option, - #[serde(default)] - pub unread_notifications: u32, - #[serde(default)] - pub unread_high_priority_notifications: u32, - #[serde(default)] - pub all_unread_notifications_count: u32, - #[serde(default)] - pub seen_notification_id: u64, - #[serde(default = "default_notification_channel_position")] - pub notification_channel_position: i64, - pub last_posted_at: Option, - pub last_seen_at: Option, - pub created_at: Option, - pub location: Option, - pub website: Option, - pub website_name: Option, - pub can_follow: Option, - pub is_followed: Option, - pub total_followers: Option, - pub total_following: Option, - pub can_send_private_messages: Option, - pub can_send_private_message_to_user: Option, - pub muted: Option, - pub ignored: Option, - pub can_mute_user: Option, - pub can_ignore_user: Option, - pub suspend_reason: Option, - pub suspended_till: Option, - pub silence_reason: Option, - pub silenced_till: Option, -} - -fn default_notification_channel_position() -> i64 { - -1 -} -``` - -- [ ] **Step 2: 在 `user.rs` 顶部确认已有 `use serde::{Deserialize, Serialize};`(已存在,无需改动)** - -- [ ] **Step 3: 在 `lib.rs` 测试模块中添加 CurrentUserSnapshot 测试** - -在 `crates/fire-models/src/lib.rs` 的 `mod tests` 块中,找到最后一个 `}` 前,追加: - -```rust - #[test] - fn current_user_snapshot_default_notification_channel_position() { - use super::CurrentUserSnapshot; - let snapshot = CurrentUserSnapshot::default(); - assert_eq!(snapshot.notification_channel_position, -1); - } -``` - -同时更新 `tests` 模块顶部的 `use super::{...}` 导入,加入 `CurrentUserSnapshot`。 - -- [ ] **Step 4: 运行测试验证** - -Run: `cargo test -p fire-models` -Expected: 所有测试 PASS - -- [ ] **Step 5: Commit** - -```bash -git add crates/fire-models/src/user.rs crates/fire-models/src/lib.rs -git commit -m "feat(models): add CurrentUserSnapshot and UserStatus for startup preloaded data" -``` - ---- - -### Task 2: 新增 PreloadedDataResult 和启动期枚举类型 - -**Files:** -- Modify: `crates/fire-models/src/session.rs` - -- [ ] **Step 1: 在 `session.rs` 文件末尾(`ProbeResult` 之后)追加新类型** - -```rust -// fire-models/src/session.rs — 在文件末尾追加 - -use std::collections::HashMap; - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct PreloadedDataResult { - pub current_user: Option, - pub site_settings: Option, - pub site: Option, - pub topic_tracking_state_meta: Option>, - pub topic_tracking_states: Option>, - pub custom_emoji: Option>, - pub topic_list: Option, - pub enabled_reaction_ids: Vec, - pub categories: Vec, - pub top_tags: Vec, - pub can_tag_topics: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PreloadedDataState { - NotStarted, - Loading, - Ready, - Failed, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RefreshTrigger { - LoginCompleted, - LogoutCompleted, - SessionRestored, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RefreshBatch { - Core, - Secondary, -} - -#[derive(Debug, Clone)] -pub struct AppStateRefreshEvent { - pub batch: RefreshBatch, - pub trigger: RefreshTrigger, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum LoginStateDetermination { - LoggedIn { username: String, user_id: u64 }, - NotLoggedIn, - SessionExpired, - NetworkErrorPreserveState, -} -``` - -注意:`session.rs` 顶部已有 `use serde::{Deserialize, Serialize};`。需要确认 `serde_json` 在 `Cargo.toml` 的依赖中。检查: - -Run: `grep -c 'serde_json' crates/fire-models/Cargo.toml` - -如果 `serde_json` 不在依赖中,需要在 `Cargo.toml` 的 `[dependencies]` 中添加 `serde_json = "1"`。 - -- [ ] **Step 2: 运行测试验证编译** - -Run: `cargo build -p fire-models` -Expected: 编译成功 - -- [ ] **Step 3: Commit** - -```bash -git add crates/fire-models/src/session.rs crates/fire-models/Cargo.toml -git commit -m "feat(models): add PreloadedDataResult, PreloadedDataState, AppStateRefreshEvent, LoginStateDetermination" -``` - ---- - -### Task 3: 新增 fire-store user_cache 表 - -**Files:** -- Modify: `crates/fire-store/src/migrations.rs` -- Modify: `crates/fire-store/src/lib.rs` - -- [ ] **Step 1: 阅读 `migrations.rs` 了解现有 migration 编号** - -Run: `grep -n 'fn migration_' crates/fire-store/src/migrations.rs | tail -5` - -假设最后一个 migration 是 `migration_3`,新 migration 编号为 4。 - -- [ ] **Step 2: 在 `migrations.rs` 追加新 migration** - -```rust -// 在文件末尾追加 - -pub(crate) fn migration_4(conn: &rusqlite::Connection) -> rusqlite::Result<()> { - conn.execute_batch( - "CREATE TABLE IF NOT EXISTS current_user_cache ( - cache_key TEXT PRIMARY KEY NOT NULL, - data TEXT NOT NULL, - updated_at INTEGER NOT NULL - );" - )?; - Ok(()) -} -``` - -- [ ] **Step 3: 在 `lib.rs` 的 migration 运行链中追加 `migration_4`** - -在 `lib.rs` 中找到 `migration_3` 被调用的位置,在其后追加 `migrations::migration_4(&conn)?;`。 - -- [ ] **Step 4: 在 `lib.rs` 的 `impl FireStore` 中追加 user cache 方法** - -```rust - pub fn get_cached_user(&self) -> Result> { - let mut stmt = self.conn.prepare( - "SELECT data FROM current_user_cache WHERE cache_key = 'primary' ORDER BY updated_at DESC LIMIT 1" - )?; - let mut rows = stmt.query([])?; - match rows.next()? { - Some(row) => Ok(Some(row.get(0)?)), - None => Ok(None), - } - } - - pub fn set_cached_user(&self, data: &str) -> Result<()> { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs() as i64; - self.conn.execute( - "INSERT OR REPLACE INTO current_user_cache (cache_key, data, updated_at) VALUES ('primary', ?1, ?2)", - rusqlite::params![data, now], - )?; - Ok(()) - } - - pub fn clear_cached_user(&self) -> Result<()> { - self.conn.execute("DELETE FROM current_user_cache", [])?; - Ok(()) - } -``` - -- [ ] **Step 5: 编译验证** - -Run: `cargo build -p fire-store` -Expected: 编译成功 - -- [ ] **Step 6: Commit** - -```bash -git add crates/fire-store/src/migrations.rs crates/fire-store/src/lib.rs -git commit -m "feat(store): add current_user_cache table and CRUD methods" -``` - ---- - -### Task 4: 重构 `PreloadedDataService`(替换当前有缺陷实现) - -**Files:** -- Modify: `crates/fire-core/src/preloaded_data.rs` -- Modify: `crates/fire-core/src/parsing.rs` -- Modify: `crates/fire-core/src/core/mod.rs` - -- [ ] **Step 1: 以当前实现为基线做纠偏,不再按“从零创建新模块”执行** - -当前仓库已经有 `preloaded_data.rs`、`parse_home_state()`、`preloaded_data_service()`。本任务目标是修正行为,不是重复搭壳。 - -- [ ] **Step 2: 明确两个 API 语义** - -要求 Rust 侧至少拆出两个语义清晰的入口: - -- `ensure_loaded()`:只负责触发 single-flight 首页请求;若已有请求进行中,不得把 in-flight 当作成功完成。 -- `await_loaded_result()`:等待首页请求进入终态,返回 `PreloadedDataResult` 或错误。 - -`PreheatGate` 和所有启动判定逻辑只能依赖第二个入口。 - -- [ ] **Step 3: 修正并发等待模型** - -当前问题是“已有并发加载时返回 `Loading`,上层又把它映射成 `Ready`”。修正版必须引入 `tokio::sync::Notify`、waiter 列表或等价机制,使并发调用者在已有 in-flight 请求时真正等待到终态。 - -必须满足: - -- main() / host 初始化触发的 preload 可以与 UI 并行。 -- `PreheatGate` 复用同一个请求。 -- 同时只有一个首页 HTML 请求在飞。 -- 失败后允许下一次显式重试重新发起。 - -- [ ] **Step 4: 统一复用 `parsing.rs` 的规范化解析能力** - -不得在 `PreloadedDataService` 再手写一个“一层 JSON decode”版本。真实 Discourse 页面里,`data-preloaded` 的 value 经常是字符串化 JSON;必须复用 `parse_preloaded_payload()` / `hydrate_preloaded_fields()` 已有的“外层 JSON + 内层字符串 JSON 解码”逻辑,确保以下字段真实可用: - -- `currentUser` -- `siteSettings` -- `site` -- `topicTrackingStateMeta` -- `topicTrackingStates` -- `customEmoji` -- `topicList` / `topic_list` / `latest` - -- [ ] **Step 5: 成功路径要原子收口** - -单次成功加载必须在同一条 Rust 权威路径里完成以下动作: - -- 更新 session cookies / bootstrap -- 写入 current user cache -- 保存 terminal `PreloadedDataResult` -- 唤醒所有等待者 - -失败路径也要保存 terminal error 并唤醒等待者,不能让平台侧靠超时或猜测恢复。 - -- [ ] **Step 6: 不新增旁路网络 API** - -优先复用 FireCore 现有的 traced request helpers(如 `build_home_request()` / `execute_request()` / `read_response_text()`)。不要为了实现 preload 再发明一套旁路 HTTP helper。 - -- [ ] **Step 7: 添加回归测试** - -至少覆盖: - -- 并发 `ensure_loaded + await_loaded_result` 只发一个请求 -- `data-preloaded` 内层字符串 JSON 可正确展开 -- in-flight 状态不会被上层视为 `Ready` -- 失败后允许 retry - -- [ ] **Step 8: 验证** - -Run: `cargo build -p fire-core` - -Run: `cargo test -p fire-core preloaded` - ---- - -### Task 5: 收口启动登录态判定为 Rust 权威入口 - -**Files:** -- Modify: `crates/fire-core/src/core/session.rs` -- Modify: `crates/fire-core/src/core/auth.rs` - -- [ ] **Step 1: 保留“本地快照判定”和“启动权威判定”两个层次,但只允许后者驱动 PreheatGate** - -推荐约束: - -- `determine_login_state()`:仅返回基于当前内存快照的本地判断,可用于 diagnostics / 非启动路径。 -- `determine_login_state_with_probe()`:启动权威路径,必须完整执行 spec Section 6/7。 - -`PreheatGate`、启动导航、cf_clearance 启动条件都只能使用权威异步判定。 - -- [ ] **Step 2: 强制对齐 spec 分支** - -权威异步判定必须严格执行: - -1. `data-preloaded.currentUser` 存在 → `LoggedIn` -2. 无 `currentUser` 且无 `_t` → `NotLoggedIn` -3. 无 `currentUser` 但有 `_t` → `GET /session/current.json` -4. probe 有 `current_user` → `LoggedIn` -5. probe 为无用户 / 404 / 401 / 403 → `SessionExpired` -6. probe 网络异常 → `NetworkErrorPreserveState` - -- [ ] **Step 3: 失效分支必须执行 Rust 侧清理** - -当 probe 明确返回失效时,Rust 权威路径要负责执行本地登出清理(保留 `cf_clearance`),而不是把“判定失效后是否 logout”下放给平台拼装。 - -- [ ] **Step 4: 增加针对 `_t` cookie 分支的测试** - -至少覆盖: - -- 预加载有 `currentUser` -- 无 cookie -- 有 `_t` 且 probe valid -- 有 `_t` 且 probe invalid -- 有 `_t` 且 probe network error - -- [ ] **Step 5: 验证** - -Run: `cargo build -p fire-core` - -Run: `cargo test -p fire-core determine_login_state` - ---- - -### Task 6: 补全 Rust 侧 `AppStateRefresher` - -**Files:** -- Modify: `crates/fire-core/src/app_state_refresher.rs` -- Modify: `crates/fire-core/src/core/mod.rs` -- Modify: `crates/fire-uniffi-session/src/lib.rs` - -- [ ] **Step 1: 将 `AppStateRefresher` 定义为 Rust 唯一编排器** - -平台可以有极薄的 wrapper / trigger,但不得再实现独立的数据刷新逻辑。所有 auth 相关 refresh 的调度、节流、批次切分都在 Rust 内完成。 - -- [ ] **Step 2: 第一批刷新必须不止 `refresh_bootstrap_if_needed()`** - -第一批至少要覆盖 spec Section 14 的核心数据: - -- current user(带 2 分钟冷却) -- categories -- topic tracking meta -- topic tracking states -- 当前首页 tab/topic list - -如果某个数据最终仍由平台 store 展示,Rust 应通过统一 refresh event / callback 触发平台调用现有 Rust fetch API,而不是让平台重新手写一套等价决策树。 - -- [ ] **Step 3: 第二批延迟 1 秒刷新** - -第二批至少覆盖: - -- user summary -- notifications list -- tags -- bookmarks -- 我的话题 / 浏览历史(若当前仓库已有) -- MessageBus 重新初始化 / 重连 - -- [ ] **Step 4: auth 事件必须统一接入** - -`LoginCompleted` / `LogoutCompleted` / `SessionRestored` 三个 trigger 都要走同一 Rust refresher。平台侧原有“登录后手动 refreshHomeFeed / 手动 startMessageBus / 手动 snapshot sync”路径必须删除或停用。 - -- [ ] **Step 5: debounce 和事件语义测试** - -至少覆盖: - -- 2 秒内重复调用被跳过 -- 第一批立即执行 -- 第二批延迟执行 -- 登录/登出/恢复三类 trigger 都能到达 Rust refresher - -- [ ] **Step 6: 验证** - -Run: `cargo build -p fire-core` - -Run: `cargo test -p fire-core app_state_refresher` - ---- - -### Task 7: 修正 FFI 启动面 - -**Files:** -- Modify: `crates/fire-uniffi-session/src/lib.rs` -- Modify: `crates/fire-uniffi-session/src/records.rs` -- Modify: `crates/fire-uniffi-messagebus/src/lib.rs` - -- [ ] **Step 1: 使用真实 records 文件位置** - -当前 session records 位于 `crates/fire-uniffi-session/src/records.rs`,不是 `fire-uniffi-types/src/records/`。后续执行按真实文件布局修改。 - -- [ ] **Step 2: 把 `await_preloaded_data` 改成终态语义** - -允许两种方案,任选其一,但必须避免当前错误: - -- 方案 A:`await_preloaded_data()` 直接返回 `PreloadedDataResultState` -- 方案 B:保留 `await_preloaded_data()` 作为终态等待 API,再新增 `preloaded_data_result()` 读取结果 - -无论选哪种,都必须满足: - -- 上层不会把 `Loading` 当 `Ready` -- `PreheatGate` 可以拿到成功结果或错误 -- 不再依赖无结构的 bare notification 判断结果 - -- [ ] **Step 3: 统一暴露启动权威判定和 refresher trigger** - -FFI 至少需要稳定暴露: - -- `ensure_preloaded_data_loaded()` -- 终态等待 preload 的 API -- `current_user_snapshot()` -- `cached_user()` -- `determine_login_state_with_probe()`(或等价 startup authority API) -- `trigger_app_state_refresh(trigger)` - -- [ ] **Step 4: 收口 MessageBus FFI 签名** - -`start_message_bus(...)` 的 `topicTrackingStateMeta` 参数变更必须在同一任务内完成: - -- Rust core -- `fire-uniffi-messagebus` -- iOS `FireSessionStore` -- Android `FireSessionStore` -- 所有启动 / coordinator 调用点 - -禁止出现“Rust 已改、host wrapper 未改”的中间状态。 - -- [ ] **Step 5: 验证** - -Run: `cargo build -p fire-uniffi-session` - -Run: `cargo build -p fire-uniffi-messagebus` - ---- - -### Task 8: MessageBus 启动对齐 spec - -**Files:** -- Modify: `crates/fire-core/src/core/messagebus.rs` -- Modify: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/messagebus/FireMessageBusCoordinator.kt` - -- [ ] **Step 1: 统一启动时机** - -MessageBus 只能在以下条件同时满足后启动: - -- PreheatGate 已完成 -- 启动登录态权威判定为 `LoggedIn` -- 主界面已就绪 - -PreheatGate 自身不启动 MessageBus。 - -- [ ] **Step 2: 明确 meta 来源** - -`topicTrackingStateMeta` 只能来自 Rust preload 结果 / bootstrap,不能让平台重新拼装默认值或静默省略。 - -- [ ] **Step 3: 保持协议对齐** - -继续确保: - -- 批量订阅 `/latest` `/new` `/unread` `/topic_tracking_state` -- 订阅 `/notification/{userId}` `/notification-alert/{userId}` -- 请求头包含 `X-SILENCE-LOGGER: true`、`Discourse-Background: true` -- 独立域名时禁用 Cookie,改用 `X-Shared-Session-Key` - -- [ ] **Step 4: 编译验证 host wrappers** - -必须显式验证 iOS 和 Android wrapper 已跟上 FFI 签名变更。 - -Run: `cd apps/android-app && ./gradlew assembleDebug` - -Run: `cd apps/ios-app && xcodebuild -project Fire.xcodeproj -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16' build` - ---- - -### Task 9: 基线编译与测试前置修正 - -**Files:** -- 无新增修改 - -- [ ] **Step 1: Rust workspace 编译必须保持通过** - -Run: `cargo build --workspace` - -- [ ] **Step 2: 处理 workspace test 基线问题** - -Run: `cargo test --workspace` - -截至 2026-06-05,已知基线问题为源码版 openwire workspace 的 websocket feature / trait 不匹配。Fire 现已改为从 crates.io 解析 openwire;如果要把本任务标记为“全量验证完成”,必须满足二选一: - -- 修复该基线问题 -- 明确得到 owner 决策,将其作为独立前置 blocker 记录并从本任务验收项中显式剥离 - -- [ ] **Step 3: Android host 编译必须恢复为绿色** - -截至 2026-06-05,已知当前阻塞是: - -- `apps/android-app/.../FireSessionStore.kt` 调用 `startMessageBus(...)` 时缺少 `topicTrackingStateMeta` 参数 - -本问题必须在 Task 7/8 中被消除。 - -- [ ] **Step 4: 若有验证修复,单独提交** - -```bash -git add -A -git commit -m "fix: restore startup alignment build and verification baseline" -``` - ---- - -### Task 10: iOS — 删除旧启动编排,收口到 PreheatGate 后单路径 - -**Files:** -- Delete: `apps/ios-app/App/Startup/FireStartupPreloadCoordinator.swift` -- Modify: `apps/ios-app/App/Startup/FirePreheatGateViewController.swift` -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` -- Modify: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- Modify: `apps/ios-app/App/Views/Other/FireTabRoot.swift` - -- [ ] **Step 1: `loadInitialState()` 只负责创建 `FireSessionStore` 和触发 preload** - -删除当前 `loadInitialState()` 中所有启动业务编排,包括但不限于: - -- `determineLoginState()` -- `restoreColdStartSession()` -- `refreshHomeFeedIfPossible(force: true)` -- `ensureMessageBusActiveIfPossible()` - -修正后,`loadInitialState()` 只做两件事: - -- 初始化 `FireSessionStore` -- 触发 Rust `ensure_preloaded_data_loaded()`(unawaited / single-flight) - -- [ ] **Step 2: `FirePreheatGateViewController` 必须等待终态结果** - -Gate 只能依赖 Rust 的终态等待 API,等待完成后再调用启动权威登录态判定。不得用“收到任意成功返回 / 任意 notification”就放行。 - -- [ ] **Step 3: Gate 结束后只走一个 post-preheat 路径** - -成功进入主流程后,iOS 只能通过一个统一入口完成: - -- restore / apply session snapshot -- 根据登录态切换 Home / Onboarding -- 触发 `triggerAppStateRefresh(.SessionRestored)`(若已登录) -- 在主界面 ready 后启动 MessageBus(传入 preload meta) - -禁止在 `FireTabRoot`、`FireOnboardingView`、已登录 tabs 内再复制一套 startup restore 逻辑。 - -- [ ] **Step 4: `FireSessionStore.startMessageBus(...)` 跟上 meta 签名** - -Swift wrapper 必须显式传 `topicTrackingStateMeta`;不能继续用旧二参调用。 - -- [ ] **Step 5: 删除遗留启动入口** - -清理或停用: - -- startup 期间的 `ensureMessageBusActiveIfPossible()` -- startup 期间的手动 home feed refresh -- 任何仅为兼容旧启动路径而保留的 notification / fallback - -- [ ] **Step 6: 验证** - -Run: `cd apps/ios-app && xcodebuild -project Fire.xcodeproj -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16' build` - ---- - -### Task 11: Android — 删除旧恢复链,收口到 `PreheatGateFragment` - -**Files:** -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/startup/PreheatGateFragment.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/auth/OnboardingFragment.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/auth/AuthViewModel.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/data/repository/SessionRepository.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/home/HomeFragment.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- Modify: `apps/android-app/src/main/res/navigation/fire_nav_graph.xml` - -- [ ] **Step 1: `PreheatGateFragment` 等待终态 preload,再走权威登录态判定** - -Gate 不得再使用同步 `determineLoginState()` 直接决定导航;必须调用 Rust 权威异步判定 API。 - -- [ ] **Step 2: 删除旧 startup restore 链** - -以下旧路径必须删除或停用: - -- `AuthViewModel.restoreSession()` -- `SessionRepository.restoreSession()` 作为启动入口 -- `OnboardingFragment` 的 restore button 启动逻辑 -- `HomeFragment` / `HomeViewModel.restoreSession()` 冷启动恢复逻辑 - -Home 页面应默认认为“进入此页面前 session 已经由 PreheatGate 判定完成”。 - -- [ ] **Step 3: 收口 post-preheat 导航** - -Android 启动只允许: - -- `preheatGateFragment -> homeFragment` -- `preheatGateFragment -> onboardingFragment` - -不得再由 `OnboardingFragment` 或 `HomeFragment` 重做 auth gate。 - -- [ ] **Step 4: `FireSessionStore.startMessageBus(...)` 跟上 meta 签名** - -Kotlin wrapper 和 `FireMessageBusCoordinator` 必须一起更新,消除当前 `assembleDebug` 的编译错误。 - -- [ ] **Step 5: 验证** - -Run: `cd apps/android-app && ./gradlew assembleDebug` - ---- - -### Task 12: 双端 `cf_clearance` 启动条件收口 - -**Files:** -- Modify: `apps/ios-app/Sources/FireAppSession/FireCfClearanceRefreshService.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireCfClearanceService.kt` - -- [ ] **Step 1: 启动条件统一以 Rust 已确认的 current user 为准** - -双端都应基于 Rust 已确认的 session/readiness/current user 信息决定是否启动自动续期,而不是各自做 ad hoc 判定。 - -- [ ] **Step 2: Gate 未完成前不启动** - -`cf_clearance` 自动续期必须发生在 preload 完成、登录态已确认之后,避免在 auth 未判定前干扰启动路径。 - -- [ ] **Step 3: 验证** - -冷启动分别验证: - -- 已登录且有 current user → 启动 -- 未登录 → 不启动 -- preload 失败 / network error → 不抢跑 - ---- - -### Task 13: 最终验收与清理 - -**Files:** -- 无新增修改 - -- [ ] **Step 1: 跑启动场景矩阵** - -至少覆盖: - -- 有缓存登录态且 preload 含 `currentUser` -- 有 `_t` 但 preload 无 `currentUser`,必须走 probe -- 无 cookie,直接进入未登录 -- preload 失败,PreheatGate 错误页可重试 - -- [ ] **Step 2: grep 清理遗留旧路径** - -重点检查以下模式不再作为启动入口存在: - -- `restoreSession()` 被 startup 直接调用 -- `refreshBootstrapIfNeeded()` 被 startup 手写调用 -- Preheat 完成前直接 `startMessageBus()` - -- [ ] **Step 3: 文档对齐** - -完成实现后,至少同步以下文档: - -- `docs/knowledge/discourse-startup-implementation-spec.md`(若实现反证了 spec,先停下确认,不得默改) -- `docs/architecture/discourse-startup-implementation-plan.md` -- 本执行计划文档 - -- [ ] **Step 4: 最终提交** - -```bash -git add -A -git commit -m "chore: complete discourse startup alignment cleanup and verification" -``` diff --git a/docs/superpowers/plans/2026-06-04-login-rust-core.md b/docs/superpowers/plans/2026-06-04-login-rust-core.md deleted file mode 100644 index b4f0056b..00000000 --- a/docs/superpowers/plans/2026-06-04-login-rust-core.md +++ /dev/null @@ -1,1197 +0,0 @@ -# Discourse WebView Login — Rust Core Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Implement the Rust-side login infrastructure: cookie scoring, low-confidence filtering, cookie replay queue, login finalization FFI, strike/probe conservative logout, and passive logout. - -**Architecture:** All session logic lives in `fire-core` with models in `fire-models`, persistence in `fire-store`, and FFI exposure in `fire-uniffi-session`. Platforms call `finalize_login_from_webview` instead of the current multi-step `syncLoginContext → refreshBootstrap → refreshCsrfToken` dance. - -**Tech Stack:** Rust, tokio, rusqlite, uniffi 0.31, existing openwire networking - -**Spec:** `docs/architecture/discourse-webview-login-implementation-plan.md` Sections 2.1–2.10 - ---- - -## File Structure - -| File | Responsibility | -|---|---| -| `fire-models/src/cookie.rs` | Cookie scoring, low-confidence detection, `same_site` field | -| `fire-models/src/session.rs` | `PassiveLogoutTrigger`, `ProbeResult`, `LoginFinalizationResult` models | -| `fire-store/src/migrations.rs` | `cookie_replay_queue` table migration | -| `fire-store/src/cookie_replay.rs` | Cookie replay queue read/write | -| `fire-store/src/lib.rs` | Wire up `cookie_replay` module | -| `fire-core/src/core/cookies.rs` | `score_platform_cookie()` function | -| `fire-core/src/core/session.rs` | `finalize_login_from_webview()` method | -| `fire-core/src/core/auth_strike.rs` | Strike system, signal classification, probe orchestration | -| `fire-core/src/core/auth.rs` | `probe_session()`, `passive_logout()` additions | -| `fire-core/src/core/network.rs` | Hook Set-Cookie into replay queue, integrate strike callbacks | -| `fire-core/src/core/mod.rs` | Register `auth_strike` module | -| `fire-core/tests/login_finalization.rs` | Integration tests for login finalization | -| `fire-core/tests/auth_strike.rs` | Integration tests for strike/probe system | -| `fire-uniffi-types/records/login_finalization.rs` | FFI records for new types | -| `fire-uniffi-session/src/lib.rs` | New FFI methods | - ---- - -### Task 1: Add `same_site` and `is_low_confidence` to PlatformCookie - -**Files:** -- Modify: `crates/fire-models/src/cookie.rs` -- Test: inline `#[cfg(test)]` in same file - -- [ ] **Step 1: Write failing test for `is_low_confidence`** - -Add to the `#[cfg(test)] mod tests` block in `cookie.rs`: - -```rust -#[test] -fn low_confidence_cookie_has_no_domain_and_no_path() { - let cookie = PlatformCookie { - name: "_t".into(), - value: "abc".into(), - domain: None, - path: None, - expires_at_unix_ms: None, - same_site: None, - }; - assert!(cookie.is_low_confidence()); - - let with_domain = PlatformCookie { - domain: Some(".linux.do".into()), - ..cookie.clone() - }; - assert!(!with_domain.is_low_confidence()); - - let with_path = PlatformCookie { - domain: None, - path: Some("/".into()), - ..cookie.clone() - }; - assert!(!with_path.is_low_confidence()); -} -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `cargo test -p fire-models -- low_confidence` -Expected: FAIL (field `same_site` does not exist, method `is_low_confidence` not found) - -- [ ] **Step 3: Add `same_site` field to `PlatformCookie` and implement `is_low_confidence`** - -In `PlatformCookie` struct, add field `pub same_site: Option`. - -Implement: -```rust -pub fn is_low_confidence(&self) -> bool { - self.domain.is_none() && self.path.is_none() -} -``` - -Update all `PlatformCookie` constructors in tests and production code to include `same_site: None`. - -- [ ] **Step 4: Run test to verify it passes** - -Run: `cargo test -p fire-models -- low_confidence` -Expected: PASS - -- [ ] **Step 5: Run full fire-models test suite** - -Run: `cargo test -p fire-models` -Expected: All pass - -- [ ] **Step 6: Commit** - -```bash -git add crates/fire-models/src/cookie.rs -git commit -m "feat(models): add same_site field and is_low_confidence to PlatformCookie" -``` - ---- - -### Task 2: Implement cookie scoring function - -**Files:** -- Modify: `crates/fire-models/src/cookie.rs` -- Test: inline `#[cfg(test)]` in same file - -- [ ] **Step 1: Write failing test for `score_platform_cookie`** - -```rust -#[test] -fn cookie_scoring_prefers_host_only_over_subdomain() { - let host = "linux.do"; - let host_only = PlatformCookie { - name: "_t".into(), - value: "abc".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - let subdomain = PlatformCookie { - name: "_t".into(), - value: "abc".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - let exact = PlatformCookie { - name: "_t".into(), - value: "abc".into(), - domain: Some("linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - assert!(score_platform_cookie(&host_only, host) > score_platform_cookie(&subdomain, host)); - assert!(score_platform_cookie(&exact, host) > score_platform_cookie(&subdomain, host)); - assert!(score_platform_cookie(&host_only, host) > score_platform_cookie(&exact, host)); -} - -#[test] -fn cookie_scoring_penalizes_empty_value() { - let host = "linux.do"; - let with_value = PlatformCookie { - name: "_t".into(), - value: "abc".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - let empty = PlatformCookie { - name: "_t".into(), - value: "".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - assert!(score_platform_cookie(&with_value, host) > score_platform_cookie(&empty, host)); -} -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `cargo test -p fire-models -- cookie_scoring` -Expected: FAIL (function not found) - -- [ ] **Step 3: Implement `score_platform_cookie`** - -```rust -pub fn score_platform_cookie(cookie: &PlatformCookie, host: &str) -> i64 { - let mut score: i64 = 0; - if !cookie.value.is_empty() { - score += 100_000; - } - if !cookie.is_expired_now() { - score += 50_000; - } - match &cookie.domain { - None => score += 40_000, - Some(d) if d == host => score += 30_000, - Some(d) if host.ends_with(&format!(".{}", d)) => score += 20_000, - _ => {} - } - score -} -``` - -- [ ] **Step 4: Run test to verify it passes** - -Run: `cargo test -p fire-models -- cookie_scoring` -Expected: PASS - -- [ ] **Step 5: Commit** - -```bash -git add crates/fire-models/src/cookie.rs -git commit -m "feat(models): add score_platform_cookie for boundary sync cookie selection" -``` - ---- - -### Task 3: Add `scored_apply_platform_cookies` to CookieSnapshot - -**Files:** -- Modify: `crates/fire-models/src/cookie.rs` -- Test: inline `#[cfg(test)]` - -- [ ] **Step 1: Write failing test** - -```rust -#[test] -fn scored_apply_selects_best_cookie_by_score() { - let host = "linux.do"; - let mut snapshot = CookieSnapshot::default(); - let weak_cookie = PlatformCookie { - name: "_t".into(), - value: "old".into(), - domain: Some(".linux.do".into()), - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - snapshot.merge_platform_cookies(&[weak_cookie]); - assert_eq!(snapshot.t_token.as_deref(), Some("old")); - - let strong_cookie = PlatformCookie { - name: "_t".into(), - value: "new".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }; - snapshot.scored_apply_platform_cookies(&[strong_cookie], host, true); - assert_eq!(snapshot.t_token.as_deref(), Some("new")); -} -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `cargo test -p fire-models -- scored_apply` -Expected: FAIL (method not found) - -- [ ] **Step 3: Implement `scored_apply_platform_cookies`** - -Add method to `CookieSnapshot`: -```rust -pub fn scored_apply_platform_cookies( - &mut self, - cookies: &[PlatformCookie], - host: &str, - allow_low_confidence_session_cookies: bool, -) { - let session_cookie_names = ["_t", "_forum_session"]; - let mut best_by_name: std::collections::HashMap = - std::collections::HashMap::new(); - - for cookie in cookies { - if !allow_low_confidence_session_cookies - && cookie.is_low_confidence() - && session_cookie_names.contains(&cookie.name.as_str()) - { - continue; - } - let score = score_platform_cookie(cookie, host); - let entry = best_by_name.get(&cookie.name); - if entry.is_none() || score > entry.unwrap().0 { - best_by_name.insert(cookie.name.clone(), (score, cookie)); - } - } - - let winners: Vec = best_by_name - .into_values() - .map(|(_, c)| c.clone()) - .collect(); - - self.apply_platform_cookies(&winners); -} -``` - -- [ ] **Step 4: Run test to verify it passes** - -Run: `cargo test -p fire-models -- scored_apply` -Expected: PASS - -- [ ] **Step 5: Run full fire-models suite** - -Run: `cargo test -p fire-models` -Expected: All pass - -- [ ] **Step 6: Commit** - -```bash -git add crates/fire-models/src/cookie.rs -git commit -m "feat(models): add scored_apply_platform_cookies with low-confidence filtering" -``` - ---- - -### Task 4: Add login finalization models to fire-models - -**Files:** -- Modify: `crates/fire-models/src/session.rs` -- Modify: `crates/fire-models/src/lib.rs` (if needed for re-exports) - -- [ ] **Step 1: Add `LoginFinalizationResult` and `PassiveLogoutTrigger` models** - -In `session.rs`, add: - -```rust -#[derive(Debug, Clone)] -pub struct LoginFinalizationResult { - pub success: bool, - pub t_token_verified: bool, - pub fingerprint_wait_needed: bool, -} - -#[derive(Debug, Clone)] -pub struct PassiveLogoutTrigger { - pub source: String, - pub signal_strength: SignalStrength, - pub cookie_diagnostic: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum SignalStrength { - Strong, - Weak, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum ProbeResult { - Valid { username: String }, - Invalid, - Inconclusive, -} -``` - -- [ ] **Step 2: Run cargo check** - -Run: `cargo check -p fire-models` -Expected: PASS (no compile errors) - -- [ ] **Step 3: Commit** - -```bash -git add crates/fire-models/src/session.rs -git commit -m "feat(models): add LoginFinalizationResult, PassiveLogoutTrigger, ProbeResult, SignalStrength" -``` - ---- - -### Task 5: Cookie replay queue in fire-store - -**Files:** -- Modify: `crates/fire-store/src/migrations.rs` -- Create: `crates/fire-store/src/cookie_replay.rs` -- Modify: `crates/fire-store/src/lib.rs` - -- [ ] **Step 1: Add migration for `cookie_replay_queue` table** - -In `migrations.rs`, add a new migration (v2): - -```rust -fn v2() -> Vec<&'static str> { - vec![ - "CREATE TABLE IF NOT EXISTS cookie_replay_queue ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - url TEXT NOT NULL, - raw_set_cookie TEXT NOT NULL, - cookie_name TEXT NOT NULL, - domain TEXT NOT NULL, - inserted_at INTEGER NOT NULL - )", - "CREATE UNIQUE INDEX IF NOT EXISTS idx_cookie_replay_dedup - ON cookie_replay_queue (cookie_name, domain)", - ] -} -``` - -Wire into the migration runner: if current version < 2, run v2(). - -- [ ] **Step 2: Implement `cookie_replay.rs`** - -```rust -use rusqlite::{params, Connection}; - -pub struct CookieReplayEntry { - pub url: String, - pub raw_set_cookie: String, - pub cookie_name: String, - pub domain: String, - pub inserted_at: u64, -} - -pub fn enqueue_set_cookie( - conn: &Connection, - url: &str, - raw_set_cookie: &str, - cookie_name: &str, - domain: &str, - inserted_at: u64, -) -> rusqlite::Result<()> { - conn.execute( - "INSERT OR REPLACE INTO cookie_replay_queue (url, raw_set_cookie, cookie_name, domain, inserted_at) - VALUES (?1, ?2, ?3, ?4, ?5)", - params![url, raw_set_cookie, cookie_name, domain, inserted_at as i64], - )?; - Ok(()) -} - -pub fn drain_replay_queue(conn: &Connection) -> rusqlite::Result> { - let mut stmt = conn.prepare( - "SELECT url, raw_set_cookie, cookie_name, domain, inserted_at FROM cookie_replay_queue ORDER BY inserted_at ASC" - )?; - let entries = stmt.query_map([], |row| { - Ok(CookieReplayEntry { - url: row.get(0)?, - raw_set_cookie: row.get(1)?, - cookie_name: row.get(2)?, - domain: row.get(3)?, - inserted_at: row.get::<_, i64>(4)? as u64, - }) - })?.collect::, _>>()?; - Ok(entries) -} - -pub fn clear_replay_queue(conn: &Connection) -> rusqlite::Result<()> { - conn.execute("DELETE FROM cookie_replay_queue", [])?; - Ok(()) -} -``` - -- [ ] **Step 3: Wire up module in `lib.rs`** - -Add `pub mod cookie_replay;` to `fire-store/src/lib.rs`. - -- [ ] **Step 4: Run cargo check** - -Run: `cargo check -p fire-store` -Expected: PASS - -- [ ] **Step 5: Commit** - -```bash -git add crates/fire-store/src/migrations.rs crates/fire-store/src/cookie_replay.rs crates/fire-store/src/lib.rs -git commit -m "feat(store): add cookie_replay_queue table and CRUD operations" -``` - ---- - -### Task 6: Hook Set-Cookie into replay queue in fire-core network layer - -**Files:** -- Modify: `crates/fire-core/src/core/network.rs` -- Modify: `crates/fire-core/src/core/mod.rs` - -- [ ] **Step 1: Add replay queue enqueue to response processing** - -In the `FireCommonHeaderInterceptor` or the response processing path, after parsing `Set-Cookie` headers from the response, call `enqueue_set_cookie` for each header. - -Add a helper function: - -```rust -fn enqueue_set_cookie_headers( - store: &FireStore, - url: &str, - headers: &http::HeaderMap, -) { - let now = current_unix_ms(); - for value in headers.get_all("set-cookie") { - if let Ok(raw) = value.to_str() { - if let Some((name, domain)) = parse_cookie_name_and_domain(raw) { - let _ = store.cookie_replay_enqueue(url, raw, &name, &domain, now); - } - } - } -} - -fn parse_cookie_name_and_domain(raw: &str) -> Option<(String, String)> { - let parts: Vec<&str> = raw.split(';').collect(); - let first = parts.first()?; - let name = first.split('=').next()?.trim().to_string(); - let domain = parts.iter() - .find(|p| p.trim().starts_with("domain=")) - .map(|p| p.trim().strip_prefix("domain=").unwrap_or("").trim().trim_start_matches('.').to_string()) - .unwrap_or_default(); - Some((name, domain)) -} -``` - -Wire `enqueue_set_cookie_headers` into `execute_request` response processing, after cookie application. - -- [ ] **Step 2: Run cargo check** - -Run: `cargo check -p fire-core` -Expected: PASS - -- [ ] **Step 3: Commit** - -```bash -git add crates/fire-core/src/core/network.rs crates/fire-core/src/core/mod.rs -git commit -m "feat(core): hook Set-Cookie headers into replay queue" -``` - ---- - -### Task 7: Implement `finalize_login_from_webview` in fire-core - -**Files:** -- Modify: `crates/fire-core/src/core/session.rs` -- Test: `crates/fire-core/tests/login_finalization.rs` - -- [ ] **Step 1: Write integration test** - -Create `crates/fire-core/tests/login_finalization.rs`: - -```rust -mod common; - -use fire_core::FireCore; -use fire_models::{PlatformCookie, LoginFinalizationResult}; - -#[tokio::test] -async fn finalize_login_applies_scored_cookies_and_advances_epoch() { - let server = common::TestServer::spawn(vec![ - common::raw_text_response(200, common::sample_home_html()), - ]); - let dir = common::temp_workspace_dir("finalize_login"); - let core = FireCore::new( - "https://linux.do".into(), - Some(dir.to_string_lossy().into()), - ).await.unwrap(); - - let cookies = vec![PlatformCookie { - name: "_t".into(), - value: "test_token".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }, PlatformCookie { - name: "_forum_session".into(), - value: "test_session".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }]; - - let result = core.finalize_login_from_webview( - "testuser".into(), - Some("csrf_token_123".into()), - None, - None, - cookies, - true, - ).await.unwrap(); - - assert!(result.success); - let snapshot = core.snapshot(); - assert!(snapshot.cookies.has_login_session()); - assert_eq!(snapshot.bootstrap.current_username.as_deref(), Some("testuser")); -} - -#[tokio::test] -async fn finalize_login_verifies_t_token_consistency() { - let dir = common::temp_workspace_dir("finalize_t_check"); - let core = FireCore::new( - "https://linux.do".into(), - Some(dir.to_string_lossy().into()), - ).await.unwrap(); - - let cookies = vec![PlatformCookie { - name: "_t".into(), - value: "webview_token".into(), - domain: None, - path: Some("/".into()), - expires_at_unix_ms: None, - same_site: None, - }]; - - let result = core.finalize_login_from_webview( - "testuser".into(), - None, - None, - None, - cookies, - true, - ).await.unwrap(); - - assert!(result.t_token_verified); -} -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `cargo test -p fire-core -- finalize_login` -Expected: FAIL (method not found) - -- [ ] **Step 3: Implement `finalize_login_from_webview`** - -In `session.rs`, add: - -```rust -pub async fn finalize_login_from_webview( - &self, - username: String, - csrf_token: Option, - raw_preloaded_html: Option, - browser_user_agent: Option, - cookies: Vec, - allow_low_confidence_session_cookies: bool, -) -> Result { - let base_url = self.base_url(); - let host = url::Url::parse(&base_url) - .ok() - .and_then(|u| u.host_str().map(|h| h.to_string())) - .unwrap_or_default(); - - let webview_t_token = cookies.iter() - .find(|c| c.name == "_t") - .map(|c| c.value.clone()); - - { - let mut state = self.state.write().await; - state.cookies.scored_apply_platform_cookies( - &cookies, - &host, - allow_low_confidence_session_cookies, - ); - } - - let jar_t_after = { - let state = self.state.read().await; - state.cookies.t_token.clone() - }; - - let t_token_verified = match (&webview_t_token, &jar_t_after) { - (Some(wv), Some(jar)) => wv == jar, - (None, _) => true, - (_, None) => false, - }; - - { - let mut state = self.state.write().await; - state.bootstrap.current_username = if !username.is_empty() { - Some(username) - } else { - None - }; - if let Some(ref csrf) = csrf_token { - state.cookies.csrf_token = Some(csrf.clone()); - } - if let Some(ref ua) = browser_user_agent { - state.browser_user_agent = Some(ua.clone()); - } - self.mutate_runtime_session_tracking_auth_change(&mut state, "PlatformSync"); - } - - self.update_session_advancing_epoch_if_auth_changed("PlatformSync"); - - let fingerprint_wait_needed = true; - - if let Some(html) = raw_preloaded_html { - self.apply_home_html(&html).await; - } - - let snapshot = self.snapshot(); - let success = snapshot.cookies.has_login_session(); - - Ok(LoginFinalizationResult { - success, - t_token_verified, - fingerprint_wait_needed, - }) -} -``` - -- [ ] **Step 4: Run test to verify it passes** - -Run: `cargo test -p fire-core -- finalize_login` -Expected: PASS - -- [ ] **Step 5: Commit** - -```bash -git add crates/fire-core/src/core/session.rs crates/fire-core/tests/login_finalization.rs -git commit -m "feat(core): implement finalize_login_from_webview with cookie scoring and t verification" -``` - ---- - -### Task 8: Implement strike system - -**Files:** -- Create: `crates/fire-core/src/core/auth_strike.rs` -- Modify: `crates/fire-core/src/core/mod.rs` -- Test: inline `#[cfg(test)]` in `auth_strike.rs` - -- [ ] **Step 1: Write failing test** - -```rust -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn strong_signal_triggers_probe_immediately() { - let mut state = AuthStrikeState::default(); - let decision = state.receive_auth_signal(SignalStrength::Strong); - assert!(matches!(decision, StrikeDecision::ProbeNeeded)); - } - - #[test] - fn weak_signal_needs_two_strikes() { - let mut state = AuthStrikeState::default(); - let decision = state.receive_auth_signal(SignalStrength::Weak); - assert!(matches!(decision, StrikeDecision::Accumulated { .. })); - let decision = state.receive_auth_signal(SignalStrength::Weak); - assert!(matches!(decision, StrikeDecision::ProbeNeeded)); - } - - #[test] - fn strikes_reset_after_45s_gap() { - let mut state = AuthStrikeState::default(); - state.receive_auth_signal(SignalStrength::Weak); - state.last_strike_at = Some(Instant::now() - Duration::from_secs(60)); - let decision = state.receive_auth_signal(SignalStrength::Weak); - if let StrikeDecision::Accumulated { strikes } = decision { - assert_eq!(strikes, 1); - } else { - panic!("Expected Accumulated"); - } - } - - #[test] - fn inconclusive_cooldown_ignores_weak_signals() { - let mut state = AuthStrikeState::default(); - state.inconclusive_until = Some(Instant::now() + Duration::from_secs(30)); - let decision = state.receive_auth_signal(SignalStrength::Weak); - assert!(matches!(decision, StrikeDecision::Ignore)); - } -} -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `cargo test -p fire-core -- auth_strike` -Expected: FAIL (module not found) - -- [ ] **Step 3: Implement `AuthStrikeState`** - -Create `auth_strike.rs`: - -```rust -use fire_models::session::SignalStrength; -use std::time::{Duration, Instant}; - -#[derive(Debug, Clone, PartialEq)] -pub enum StrikeDecision { - Ignore, - Accumulated { strikes: u8 }, - ProbeNeeded, -} - -#[derive(Debug)] -pub struct AuthStrikeState { - pub strike_count: u8, - pub last_strike_at: Option, - pub last_signal_strength: Option, - pub inconclusive_until: Option, - pub passive_logout_count_24h: u8, - pub passive_logout_window_start: Option, - pub probe_in_progress: bool, - pub logging_out: bool, -} - -const STRIKE_WINDOW: Duration = Duration::from_secs(45); -const INCONCLUSIVE_COOLDOWN: Duration = Duration::from_secs(30); -const PASSIVE_LOGOUT_WINDOW: Duration = Duration::from_secs(24 * 60 * 60); -const PASSIVE_LOGOUT_SUGGEST_CLEAR_THRESHOLD: u8 = 3; - -impl Default for AuthStrikeState { - fn default() -> Self { - Self { - strike_count: 0, - last_strike_at: None, - last_signal_strength: None, - inconclusive_until: None, - passive_logout_count_24h: 0, - passive_logout_window_start: None, - probe_in_progress: false, - logging_out: false, - } - } -} - -impl AuthStrikeState { - pub fn receive_auth_signal(&mut self, strength: SignalStrength) -> StrikeDecision { - if self.logging_out { - return StrikeDecision::Ignore; - } - if self.probe_in_progress { - return StrikeDecision::Ignore; - } - if let Some(until) = self.inconclusive_until { - if Instant::now() < until && strength == SignalStrength::Weak { - return StrikeDecision::Ignore; - } - } - - if let Some(last) = self.last_strike_at { - if Instant::now().duration_since(last) > STRIKE_WINDOW { - self.strike_count = 0; - } - } - - self.strike_count += 1; - self.last_strike_at = Some(Instant::now()); - self.last_signal_strength = Some(strength.clone()); - - let threshold = match strength { - SignalStrength::Strong => 1, - SignalStrength::Weak => 2, - }; - - if self.strike_count >= threshold { - StrikeDecision::ProbeNeeded - } else { - StrikeDecision::Accumulated { strikes: self.strike_count } - } - } - - pub fn reset_strikes(&mut self) { - self.strike_count = 0; - self.last_strike_at = None; - self.last_signal_strength = None; - self.inconclusive_until = None; - } - - pub fn enter_inconclusive_cooldown(&mut self) { - self.inconclusive_until = Some(Instant::now() + INCONCLUSIVE_COOLDOWN); - } - - pub fn should_suggest_data_clear(&self) -> bool { - self.passive_logout_count_24h >= PASSIVE_LOGOUT_SUGGEST_CLEAR_THRESHOLD - } - - pub fn record_passive_logout(&mut self) { - let now = Instant::now(); - if let Some(start) = self.passive_logout_window_start { - if now.duration_since(start) > PASSIVE_LOGOUT_WINDOW { - self.passive_logout_count_24h = 0; - self.passive_logout_window_start = Some(now); - } - } else { - self.passive_logout_window_start = Some(now); - } - self.passive_logout_count_24h += 1; - self.logging_out = true; - } -} -``` - -Register module in `mod.rs`: `pub mod auth_strike;` - -- [ ] **Step 4: Run test to verify it passes** - -Run: `cargo test -p fire-core -- auth_strike` -Expected: PASS - -- [ ] **Step 5: Commit** - -```bash -git add crates/fire-core/src/core/auth_strike.rs crates/fire-core/src/core/mod.rs -git commit -m "feat(core): implement AuthStrikeState with signal classification and cooldowns" -``` - ---- - -### Task 9: Implement `probe_session` and `passive_logout` in fire-core - -**Files:** -- Modify: `crates/fire-core/src/core/auth.rs` -- Test: `crates/fire-core/tests/auth_strike.rs` - -- [ ] **Step 1: Write integration test** - -```rust -#[tokio::test] -async fn probe_session_returns_valid_when_user_exists() { - let server = common::TestServer::spawn(vec![ - common::raw_text_response(200, r#"{"current_user":{"username":"testuser"}}"#), - ]); - let dir = common::temp_workspace_dir("probe_valid"); - let core = FireCore::new(server.base_url(), Some(dir.to_string_lossy().into())).await.unwrap(); - - let result = core.probe_session().await.unwrap(); - assert!(matches!(result, ProbeResult::Valid { .. })); -} - -#[tokio::test] -async fn probe_session_returns_invalid_on_404() { - let server = common::TestServer::spawn(vec![ - common::raw_text_response(404, "not found"), - ]); - let dir = common::temp_workspace_dir("probe_invalid"); - let core = FireCore::new(server.base_url(), Some(dir.to_string_lossy().into())).await.unwrap(); - - let result = core.probe_session().await.unwrap(); - assert!(matches!(result, ProbeResult::Invalid)); -} -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `cargo test -p fire-core -- probe_session` -Expected: FAIL (method not found) - -- [ ] **Step 3: Implement `probe_session` and `passive_logout`** - -In `auth.rs`: - -```rust -pub async fn probe_session(&self) -> Result { - let request = self.build_json_get_request( - "probe_session", - "/session/current.json", - None, - None, - ).await?; - let traced = self.create_traced_request(request); - let response = self.execute_request(traced).await?; - - let status = response.status(); - if status.as_u16() == 404 { - return Ok(ProbeResult::Invalid); - } - - let body = self.read_response_text("probe_session", response).await?; - let json: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); - - if let Some(user) = json.get("current_user") { - let username = user.get("username") - .and_then(|u| u.as_str()) - .unwrap_or("") - .to_string(); - if !username.is_empty() { - return Ok(ProbeResult::Valid { username }); - } - } - - if status.is_success() { - Ok(ProbeResult::Invalid) - } else if status.as_u16() == 401 || status.as_u16() == 403 { - Ok(ProbeResult::Invalid) - } else { - Ok(ProbeResult::Inconclusive) - } -} - -pub async fn passive_logout(&self, trigger: PassiveLogoutTrigger) -> Result<(), FireCoreError> { - self.advance_epoch("passive_logout"); - { - let mut state = self.state.write().await; - state.auth_strike.record_passive_logout(); - } - self.logout_local(true).await; - Ok(()) -} -``` - -- [ ] **Step 4: Run test to verify it passes** - -Run: `cargo test -p fire-core -- probe_session` -Expected: PASS - -- [ ] **Step 5: Commit** - -```bash -git add crates/fire-core/src/core/auth.rs crates/fire-core/tests/auth_strike.rs -git commit -m "feat(core): implement probe_session and passive_logout" -``` - ---- - -### Task 10: Integrate strike system into network response processing - -**Files:** -- Modify: `crates/fire-core/src/core/network.rs` -- Test: extend `crates/fire-core/tests/auth_strike.rs` - -- [ ] **Step 1: Write integration test** - -```rust -#[tokio::test] -async fn discourse_logged_out_strong_signal_triggers_probe() { - let home_html = common::sample_home_html(); - let server = common::TestServer::spawn_scripted(vec![ - common::TestServerStep::immediate(common::raw_text_response(200, &home_html)), - common::TestServerStep::immediate( - "HTTP/1.1 403 OK\r\ncontent-type: application/json\r\ndiscourse-logged-out: true\r\n\r\n[\"BAD CSRF\"]" - ), - common::TestServerStep::immediate(common::raw_text_response(200, r#"{"current_user":{"username":"testuser"}}"#)), - ]); - let dir = common::temp_workspace_dir("strike_integration"); - let core = FireCore::new(server.base_url(), Some(dir.to_string_lossy().into())).await.unwrap(); - - // Bootstrap - core.refresh_bootstrap().await.unwrap(); - - // Simulate receiving discourse-logged-out header during an API call - let state = core.state.read().await; - let initial_epoch = state.epoch; - drop(state); - - // After strike + probe, session should be verified or cleaned up - // (detailed verification depends on the actual request flow) -} -``` - -- [ ] **Step 2: Integrate strike system into `execute_api_request_with_csrf_retry`** - -In `network.rs`, modify `execute_api_request_with_csrf_retry` to: - -1. After detecting `discourse-logged-out` header or `not_logged_in` error type, classify signal strength -2. Call `auth_strike.receive_auth_signal(strength)` -3. If `ProbeNeeded`, run `probe_session()` -4. If probe confirms `Invalid`, run `passive_logout()` - -This requires holding a mutable reference to `AuthStrikeState` inside `FireSessionRuntimeState`. - -- [ ] **Step 3: Run cargo check and tests** - -Run: `cargo test -p fire-core` -Expected: All pass - -- [ ] **Step 4: Commit** - -```bash -git add crates/fire-core/src/core/network.rs crates/fire-core/tests/auth_strike.rs -git commit -m "feat(core): integrate strike system into API request response processing" -``` - ---- - -### Task 11: Expose new FFI methods in fire-uniffi-session - -**Files:** -- Create: `crates/fire-uniffi-types/records/login_finalization.rs` -- Modify: `crates/fire-uniffi-types/src/lib.rs` -- Modify: `crates/fire-uniffi-session/src/lib.rs` - -- [ ] **Step 1: Create FFI record types** - -In `fire-uniffi-types/records/login_finalization.rs`: - -```rust -#[derive(uniffi::Record, Debug, Clone)] -pub struct LoginFinalizationResultState { - pub success: bool, - pub t_token_verified: bool, - pub fingerprint_wait_needed: bool, -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct PassiveLogoutTriggerState { - pub source: String, - pub signal_strength: String, - pub cookie_diagnostic: String, -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct CookieReplayEntryState { - pub url: String, - pub raw_set_cookie: String, - pub cookie_name: String, - pub domain: String, - pub inserted_at: u64, -} -``` - -Add `From` impls mapping from `fire-models` types. - -- [ ] **Step 2: Add FFI methods to `FireSessionHandle`** - -```rust -fn finalize_login_from_webview( - &self, - username: String, - csrf_token: Option, - raw_preloaded_html: Option, - browser_user_agent: Option, - cookies: Vec, - allow_low_confidence_session_cookies: bool, -) -> Result { - run_fallible(self.shared.clone(), || { - let rt = ffi_runtime(); - rt.block_on(self.shared.core.finalize_login_from_webview( - username, - csrf_token, - raw_preloaded_html, - browser_user_agent, - cookies.into_iter().map(Into::into).collect(), - allow_low_confidence_session_cookies, - )) - }).map(Into::into) -} - -fn cookie_replay_queue(&self) -> Result> { - // delegate to fire-store -} - -fn clear_cookie_replay_queue(&self) -> Result<()> { - // delegate to fire-store -} - -fn probe_session(&self) -> Result { - // "valid:username", "invalid", "inconclusive" -} - -fn record_fingerprint_done(&self) { - // no-op for now, future hook point -} - -fn save_credential(&self, username: String, password: String) -> Result<()> { - // delegate to encrypted store -} - -fn load_credential(&self) -> Result> { - // returns JSON {"username":"...","password":"..."} or None -} - -fn clear_credential(&self) -> Result<()> { - // clear stored credential -} -``` - -- [ ] **Step 3: Run cargo check** - -Run: `cargo check -p fire-uniffi-session` -Expected: PASS - -- [ ] **Step 4: Run full Rust test suite** - -Run: `cargo test -p fire-models -p fire-core -p fire-uniffi --all-targets` -Expected: All pass - -- [ ] **Step 5: Commit** - -```bash -git add crates/fire-uniffi-types/ crates/fire-uniffi-session/ -git commit -m "feat(uniffi): expose finalize_login_from_webview, cookie_replay_queue, probe_session FFI methods" -``` - ---- - -### Task 12: Update CI test configuration - -**Files:** -- Modify: `.github/workflows/ci.yml` - -- [ ] **Step 1: Add `fire-store` to CI test targets** - -Update the `rust-host-test` job's test command from: - -``` -cargo test -p fire-models -p fire-core -p fire-uniffi --all-targets -``` - -to: - -``` -cargo test -p fire-models -p fire-store -p fire-core -p fire-uniffi --all-targets -``` - -- [ ] **Step 2: Commit** - -```bash -git add .github/workflows/ci.yml -git commit -m "ci: add fire-store to Rust test targets" -``` diff --git a/docs/superpowers/plans/2026-06-06-auth-cf-runtime-alignment.md b/docs/superpowers/plans/2026-06-06-auth-cf-runtime-alignment.md deleted file mode 100644 index f887821d..00000000 --- a/docs/superpowers/plans/2026-06-06-auth-cf-runtime-alignment.md +++ /dev/null @@ -1,542 +0,0 @@ -# Auth / Cloudflare Runtime Alignment Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** 将 Fire 下一阶段双端运行时的登录态、后台踢出登录、Cloudflare challenge、自动续期和 WebView 手动验证收口到一条 Rust/openwire 权威网络链路,对齐 FluxDO v0.2.15 的 Dio/OkHttp 风格拦截器分层和保守 auth signal/probe 策略。 - -**Architecture:** Rust Core 拥有 session state、CookieJar、CSRF、auth signal classification、probe、passive logout、Cloudflare 分类、请求重试和 openwire interceptor 编排。iOS / Android 只拥有 WebView 登录、Cloudflare challenge 完成、平台 cookie 提取、可见 UI 和错误展示。平台不得自行把普通 403、CSRF、Cloudflare、`discourse-logged-out` 推断成登出。 - -**Tech Stack:** Rust + openwire + UniFFI + tokio / Swift + WebKit / Kotlin + Android WebView + androidx - -**Design Inputs:** -- `docs/knowledge/api-overview.md` -- `docs/knowledge/api/01-global-conventions.md` -- `docs/knowledge/api/02-auth-and-session.md` -- `docs/architecture/fire-native-architecture.md` -- FluxDO v0.2.15 reference: `references/fluxdo/lib/services/network/discourse_dio.dart` -- FluxDO v0.2.15 reference: `references/fluxdo/lib/services/discourse/_auth.dart` -- FluxDO v0.2.15 reference: `references/fluxdo/lib/services/network/cookie/app_cookie_manager.dart` -- FluxDO v0.2.15 reference: `references/fluxdo/lib/services/network/interceptors/cf_challenge_interceptor.dart` -- FluxDO v0.2.15 reference: `references/fluxdo/lib/services/cf_challenge_service.dart` -- FluxDO v0.2.15 reference: `references/fluxdo/lib/services/network/cookie/boundary_sync_service.dart` -- FluxDO v0.2.15 reference: `references/fluxdo/lib/services/network/interceptors/redirect_interceptor.dart` - ---- - -## Audit Corrections (2026-06-06) - -本计划基于当前 Fire 和 FluxDO v0.2.15 源码审查结果,以下事项为**强约束**: - -- FluxDO v0.2.15 已经不是“任意 `discourse-logged-out` 即登出”的旧策略;它统一通过 auth signal、strike、`GET /session/current.json` probe 二次验证,避免 cookie 传输瞬时问题和 token rotation 窗口误判。Fire 下一阶段应对齐这条模型。 -- Auth signal 强弱必须分开:`not_logged_in` / `401|403 + discourse-logged-out` 是强信号,1 次触发 probe;`2xx/3xx + discourse-logged-out` 是 mixed/弱信号,2 次累积后触发 probe。 -- Probe 结果必须三态化:valid 保持登录并重置 strike;invalid 执行被动登出;inconclusive 先进入冷却期,若当前 strike 已累计到 FluxDO v0.2.15 的升级阈值(2 次)才升级为被动登出。 -- `BAD CSRF` 只属于 CSRF 分支:清空 CSRF token,刷新 `/session/csrf`,重试原请求一次。不得触发登录弹窗、不得清登录态。 -- `invalid_access` / 普通 `403` 是权限失败,不是后台踢出登录。 -- 成功 `2xx` `/session/csrf` 即使带 `discourse-logged-out` 或清 cookie,也不立即登出;它是 mixed/弱 auth signal。会话 cookie 删除需要被拦截,最终是否登出由 probe 机制决定。 -- Cloudflare challenge 判定必须同时依赖 Cloudflare 响应头和 HTML/body 特征,避免把帖子内容或 Discourse 自身 403 误判为 CF。 -- WebView cookie 只在边界同步:登录完成、Cloudflare 验证完成、明确的 host cookie repair。不得常态轮询 WebView cookie 来覆盖 Rust session。 -- Redirect 已完成差异审计:openwire 内置 follow-up 已覆盖 Fire 当前所需行为,不需要在 Fire 侧复制 FluxDO 的 `RedirectInterceptor`。若未来需要改变 redirect request 的 `Cookie` header 处理,应优先在 openwire 加可配置策略,而不是在 Fire app 层手写二次请求。 -- 登录页下方用于测试的“恢复已有会话”入口必须删除,启动登录态恢复只由 PreheatGate / Rust startup authority 处理。 - -## Implementation Status (2026-06-06) - -- 已落地:Android onboarding 删除隐藏的 `restore_session_button`、`onboarding_restore_session`、旧 `bootstrapping_layout`、旧 `error_banner`、只服务这些死 UI 的 `AuthViewModel`、`bg_error_banner`、未使用的 `action_onboarding_to_home` 和残留 `action_restore_session` 字符串。 -- 已核对:iOS onboarding/login 没有生产级“恢复已有会话”入口;Developer Tools 的“恢复会话”只会重新执行 `loadInitialState()` 诊断路径。 -- 已存在:Rust `is_cloudflare_challenge_response()` 已按 `403/429 + server=cloudflare + text/html + cf-mitigated/body` 分类 CF。 -- 已存在:Rust `execute_api_request_with_csrf_retry()` 已做缺失 CSRF 预刷新和 `BAD CSRF` 一次重试。 -- 已存在:Rust `response_login_invalidation_error()` 已把 `not_logged_in` 与普通 `invalid_access` 分开,且不会因成功 CSRF 响应直接登出。 -- 已存在:Rust `AuthStrikeState`、`probe_session()`、`determine_login_state_with_probe()` 提供后台踢出登录判定雏形;需要按 FluxDO v0.2.15 明确三态 probe、mixed signal cookie deletion block 和 inconclusive escalation 语义。 -- 已存在:iOS `FireCfClearanceRefreshService` 有登录态确认 gate 后的隐藏 Turnstile runtime;Android 尚无等价服务。 -- 已存在:iOS `performWithCloudflareRecovery` / `performWriteWithCloudflareRetry` 目前只是直跑闭包,不会自动弹恢复 WebView;后续需要改名或接入新的 auth runtime handler,避免保留误导性命名。 - -## Follow-Up Scope (2026-06-17) - -本轮修复优先处理会造成用户卡死或登录态被错误清理的硬失败路径,已对齐 FluxDO 的核心边界:CF challenge 不进入 self-heal/logout,BAD-CSRF 优先刷新重试,CF 完成后重试请求重建 profile header,后台/静默请求命中 CF 时不再直接返回 incomplete/cancelled。 - -仍需单独规划的体验与调度增强: - -- FluxDO 式非阻塞验证入口:后台/静默请求触发 CF 时,先展示可升级的 floating pill / 小窗入口,而不是立即打开全屏 challenge UI。用户点击或超时后再提升为前台验证。当前 Fire 的最小修复是复用同一个全屏 WebView/Activity 来打通验证闭环。 -- 全局 RequestScheduler / sliding-window limit:在 `cf_verifying`、短时间高并发 403/429、以及普通 rate-limit 场景下,于请求发出前冻结或排队非 `skip_cf_block` 业务请求,避免并发请求风暴反复撞 CF。当前 Fire 只有 Rust CF runtime `in_progress` 门控和 cooldown,还没有 FluxDO 那层统一调度与滑动窗口限流。 - ---- - -## Runtime Signal Matrix - -| 场景 | 信号 | 强度 | Rust 处理 | 平台处理 | -|---|---|---:|---|---| -| 本地无 `_t` / 无认证 cookie | `CookieSnapshot.can_authenticate_requests() == false` | terminal local | `NotLoggedIn`,不发认证写请求 | 显示登录入口 | -| 启动有 cookie 但无 current user | `/session/current.json` probe valid | terminal valid | 写入 current user,进入 logged-in | 进入主界面 | -| 启动 probe 404 / 无 `current_user` | `/session/current.json` invalid | terminal invalid | passive logout,保留 `cf_clearance` | 回 onboarding | -| 启动 probe 网络失败 / CF | inconclusive | none | 保留本地状态,暴露错误/诊断 | 不自动清登录态 | -| 后台踢出登录 | `401/403` JSON `error_type=not_logged_in` | strong | auth strike -> probe;probe invalid 或 inconclusive escalated 才 passive logout | 只消费最终 session state | -| 普通无权限 | `403` JSON `error_type=invalid_access` | none | 返回 `HttpStatus` / forbidden | 显示权限错误 | -| Discourse header | `401/403 + discourse-logged-out` | strong | 1 次触发 probe;不直接清 session cookie | 不自动弹登录 | -| Mixed logged-out signal | `2xx/3xx + discourse-logged-out` | weak | 记录 strike,拦截会话 cookie 删除,达到阈值后 probe | 平台不可见 | -| CSRF 坏 token | body `["BAD CSRF"]` | csrf only | 清 token -> 刷新 -> 重试一次 | 平台不可见 | -| CSRF 成功但带 logged-out | `2xx /session/csrf` + mixed signal | weak | 接受 CSRF token,拦截 cookie 删除,走弱 auth signal | 平台不可见 | -| Cloudflare challenge | `403/429` + CF headers + HTML/body marker | cf only | 触发 CF resolution path;不登出 | WebView 完成挑战并回灌 cookie | -| rate limit | `429` without CF challenge | rate only | backoff / classify rate limit | 显示稍后重试 | - -## Target Interceptor Shape - -FluxDO 的 Dio 链路是: - -```text -SessionGuard -> RequestScheduler -> CookieManager -> retry/header/csrf - -> Redirect -> Error -> CfChallenge -> NetworkLog -``` - -Fire 的 openwire 目标链路应收口为: - -```text -RequestEpochGuard - -> FireCommonHeaderInterceptor - -> FireCookieJar / Set-Cookie ingress - -> FireCsrfInterceptor - -> FireRetry / RateLimit - -> FireAuthSignalInterceptor - -> FireCloudflareInterceptor - -> Trace / Log -``` - -Redirect 不进入 Fire 侧 interceptor 链路。审计结果:openwire 的 `FollowUpPolicyService` 已提供默认 10 跳上限、HTTPS -> HTTP 降级保护、`301/302/303` method rewrite、`307/308` method/body preservation、跨 origin `Cookie` / `Authorization` 移除、以及每跳按目标 URL 重新走 `CookieJar` 的能力。Fire 当前不手动塞显式 `Cookie` header,因此不需要 FluxDO 式手动 redirect interceptor。 - -唯一保留边界:如果未来某个调用方显式写入 `Cookie` header,same-origin redirect 会保留该显式 header;这不是 Fire 当前路径。需要严格“每跳都清 Cookie header”时,应改 openwire redirect request policy。 - ---- - -## File Structure - -| File | Responsibility | -|---|---| -| `crates/fire-models/src/session.rs` | Auth signal、CF challenge request/result、runtime event models | -| `crates/fire-models/src/cookie.rs` | Platform cookie scoring、low-confidence filtering、critical cookie helpers | -| `crates/fire-core/src/core/network.rs` | HTTP status classification、CSRF retry、CF classification、auth-signal hook | -| `crates/fire-core/src/core/auth.rs` | probe、passive logout、auth strike outcome policy | -| `crates/fire-core/src/core/auth_strike.rs` | Strong/weak signal accumulation and cooldown | -| `crates/fire-core/src/core/cf_challenge.rs` | NEW: challenge resolution orchestration and retry gate | -| `crates/fire-core/src/core/session.rs` | WebView login finalization and boundary cookie application | -| `crates/fire-uniffi-session/src/records.rs` | FFI records for auth runtime events and challenge outcomes | -| `crates/fire-uniffi-session/src/lib.rs` | Register auth runtime handler and expose boundary sync methods | -| `apps/ios-app/Sources/FireAppSession/FireCfClearanceRefreshService.swift` | iOS hidden Turnstile refresh runtime | -| `apps/ios-app/Sources/FireAppSession/FireWebViewLoginCoordinator.swift` | iOS login boundary sync | -| `apps/ios-app/App/ViewModels/FireAppViewModel.swift` | iOS auth runtime host handler and UI routing | -| `apps/android-app/src/main/java/com/fire/app/session/FireWebViewLoginCoordinator.kt` | Android login boundary sync | -| `apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt` | NEW: Android manual CF WebView coordinator | -| `apps/android-app/src/main/java/com/fire/app/session/FireCfClearanceRefreshService.kt` | NEW: Android hidden Turnstile refresh runtime | -| `apps/android-app/src/main/java/com/fire/app/core/error/FireErrorHandling.kt` | Android error display, no local logout inference | -| `docs/knowledge/api/01-global-conventions.md` | Keep interceptor docs aligned after implementation | -| `docs/knowledge/api/02-auth-and-session.md` | Keep auth/session docs aligned after implementation | -| `docs/architecture/fire-native-architecture.md` | Keep Rust/platform ownership split aligned | - ---- - -### Task 1: Rust — Align auth runtime signals with FluxDO v0.2.15 - -**Files:** -- Modify: `crates/fire-models/src/session.rs` -- Modify: `crates/fire-core/src/core/network.rs` -- Modify: `crates/fire-core/src/core/auth.rs` -- Test: `crates/fire-core/tests/network.rs` -- Test: `crates/fire-core/tests/auth_strike.rs` - -- [ ] **Step 1: Add explicit auth signal model** - -Add `AuthRuntimeSignal` / `AuthRuntimeSignalStrength` / `AuthRuntimeSignalSource` models covering: - -```text -NotLoggedInBody -DiscourseLoggedOutHeader -MixedLoggedOutHeader -AuthCookieDeletion -MixedSignalCookieDeletionBlocked -InvalidAccessForbidden -BadCsrf -CloudflareChallenge -RateLimit -ProbeValid -ProbeInvalid -ProbeInconclusive -ProbeInconclusiveEscalated -``` - -Only confirmed probe outcomes may mutate login state: `ProbeValid` preserves session and resets strikes; `ProbeInvalid` logs out; `ProbeInconclusive` cools down unless strike count has reached the v0.2.15 escalation threshold. - -- [ ] **Step 2: Extract response classification** - -Move `not_logged_in_message`, `response_login_invalidation_signal`, `is_bad_csrf_body`, and `is_cloudflare_challenge_response` into a classifier function that returns both `FireCoreError` and diagnostic `AuthRuntimeSignal`. - -The classifier must map: - -- `not_logged_in` body -> strong auth signal. -- `401/403 + discourse-logged-out` -> strong auth signal. -- `2xx/3xx + discourse-logged-out` -> weak/mixed auth signal. -- `invalid_access` -> forbidden, no auth signal. -- `BAD CSRF` -> csrf signal, no auth signal. -- Cloudflare HTML -> cf signal, no auth signal. - -- [ ] **Step 3: Lock in forbidden-vs-login tests** - -Add or update tests proving: - -- `403 invalid_access` returns `HttpStatus` and preserves `_t`, `_forum_session`, CSRF. -- `401/403 not_logged_in` triggers strike/probe. -- `2xx /session/csrf` with `discourse-logged-out` still stores CSRF, blocks destructive session-cookie deletion, and records only a weak auth signal. -- `BAD CSRF` does not call auth strike. -- CF challenge does not call auth strike and does not clear session. -- `401/403 + discourse-logged-out` is strong and probes after one strike. -- two weak mixed signals probe after the second strike. - -- [ ] **Step 4: Align inconclusive probe policy** - -Match FluxDO v0.2.15: - -- First inconclusive probe enters a 30-second weak-signal cooldown. -- Weak auth signals are suppressed during cooldown. -- If the probe was triggered with strike count >= 2 and remains inconclusive, escalate to passive logout with a distinct `probe_escalated` diagnostic reason. -- Startup login-state probe remains more conservative: network exceptions preserve local state. - -- [ ] **Step 5: Update docs** - -Sync `docs/knowledge/api/01-global-conventions.md` and `docs/knowledge/api/02-auth-and-session.md` so the table matches actual classifier behavior. - ---- - -### Task 2: Rust — Keep session generation and stale response handling authoritative - -**Files:** -- Modify: `crates/fire-core/src/core/network.rs` -- Modify: `crates/fire-core/src/core/mod.rs` -- Modify: `crates/fire-core/src/cookies.rs` -- Test: `crates/fire-core/tests/network.rs` - -- [ ] **Step 1: Re-audit request epoch behavior** - -Confirm every API request stores `FireRequestEpoch` before execution and every body read checks stale response context. - -- [ ] **Step 2: Align auth cookie ingress with epoch** - -Ensure `Set-Cookie` updates from stale responses never overwrite current session cookies. Keep FluxDO's `SessionGuardInterceptor` behavior mapped to Rust epoch rather than platform cancellation. - -- [ ] **Step 3: Block mixed-signal session-cookie deletion** - -Mirror FluxDO v0.2.15 `AppCookieManager`: if a `2xx/3xx` response carries `discourse-logged-out` and a session-cookie delete (`_t` / `_forum_session`) but the body is not `not_logged_in`, ignore the destructive cookie delete and let auth signal/probe decide the final session state. - -- [ ] **Step 4: Add stale and mixed Set-Cookie tests** - -Simulate a request whose response arrives after session epoch advances. Assert stale cookie changes are ignored and diagnostics record cancellation. - -Also simulate `200 /session/csrf` with `discourse-logged-out` and session-cookie deletion headers. Assert CSRF is stored, `_t` / `_forum_session` remain, and a weak/mixed auth signal is recorded. - ---- - -### Task 3: Rust + Platforms — Enforce boundary-only cookie sync - -**Files:** -- Modify: `crates/fire-models/src/cookie.rs` -- Modify: `crates/fire-core/src/core/session.rs` -- Modify: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- Test: `crates/fire-core/tests/login_finalization.rs` - -- [ ] **Step 1: Default production login finalization to high-confidence cookies** - -Audit current iOS/Android calls that pass `allowLowConfidenceSessionCookies: true`. Move production login completion toward FluxDO's default: reject low-confidence session cookies unless device-specific evidence proves the platform cannot provide domain/path/flags. - -- [ ] **Step 2: Keep WebView sync entry points finite** - -Allowed platform-to-Rust cookie sync events: - -```text -finalize_login_from_webview -complete_cloudflare_challenge -host_cookie_repair_once_per_epoch -explicit developer diagnostics action -``` - -No screen may call cookie sync as a generic render/update side effect. - -- [ ] **Step 3: Add duplicate cookie scoring tests** - -Assert host-only `_t` beats `.linux.do` domain `_t`, non-empty beats empty, unexpired beats expired, and `cf_clearance` can be preserved across logout. - ---- - -### Task 4: Rust — Finish CSRF as an interceptor-level behavior - -**Files:** -- Modify: `crates/fire-core/src/core/network.rs` -- Modify: `crates/fire-core/src/core/auth.rs` -- Test: `crates/fire-core/tests/network.rs` -- Test: `crates/fire-core/tests/interactions.rs` - -- [ ] **Step 1: Keep CSRF preflight in Rust** - -All POST/PUT/DELETE/PATCH paths must use `execute_api_request_with_csrf_retry()` or an equivalent Rust-owned wrapper. Platform code must not decide when to call `/session/csrf`. - -- [ ] **Step 2: Preserve Discourse web-client semantics** - -When a write request somehow reaches build time without a CSRF token, continue sending `X-CSRF-Token: undefined` so the server can return `BAD CSRF` and Rust can retry once. - -- [ ] **Step 3: Verify queued refresh behavior** - -Keep single-flight `/session/csrf`; queued callers must skip refresh if auth cookies disappeared while waiting. - ---- - -### Task 5: Rust + UniFFI — Add Cloudflare challenge resolution contract - -**Files:** -- Create: `crates/fire-core/src/core/cf_challenge.rs` -- Modify: `crates/fire-core/src/core/mod.rs` -- Modify: `crates/fire-core/src/core/network.rs` -- Modify: `crates/fire-models/src/session.rs` -- Modify: `crates/fire-uniffi-session/src/records.rs` -- Modify: `crates/fire-uniffi-session/src/lib.rs` -- Test: `crates/fire-core/tests/network.rs` - -- [ ] **Step 1: Add challenge models** - -Define: - -```text -CloudflareChallengeRequest { - operation, - request_url, - origin_url, - is_foreground, - session_epoch, -} - -CloudflareChallengeResult { - completed, - user_cancelled, - cookies, - browser_user_agent, -} -``` - -- [ ] **Step 2: Register a platform challenge handler** - -Expose a UniFFI registration point on the session/core handle. Rust may request challenge completion, but platform owns the WebView UI. - -- [ ] **Step 3: Retry original operation once** - -When the platform returns a completed result with a new `cf_clearance`, Rust applies cookies through scored boundary sync and retries the original request exactly once with stale cookie headers removed. - -- [ ] **Step 4: Preserve failure semantics** - -If the handler is unavailable, user cancels, or no new `cf_clearance` is observed, return `FireCoreError::CloudflareChallenge`. Do not log out, do not open login, do not clear `_t`. - -- [ ] **Step 5: Add cooldown** - -Mirror FluxDO's cooldown intent: repeated failed challenge completions enter a short cooldown so multiple blocked requests do not fan out into multiple WebViews. - ---- - -### Task 6: iOS — Wire platform-owned manual challenge and keep auto refresh gated - -**Files:** -- Modify: `apps/ios-app/Sources/FireAppSession/FireCfClearanceRefreshService.swift` -- Modify: `apps/ios-app/Sources/FireAppSession/FireWebViewLoginCoordinator.swift` -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` -- Modify: `apps/ios-app/App/Views/Other/FireLoginWebView.swift` -- Test: `apps/ios-app/Tests/Unit/FireSessionStoreTests.swift` -- Test: `apps/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift` - -- [ ] **Step 1: Implement `FireCloudflareChallengeCoordinator`** - -Use the shared auth-browser profile. Load `originURL` when provided so topic/list context is preserved; otherwise load `/challenge` on the LinuxDo base URL. - -- [ ] **Step 2: Detect successful challenge** - -Use the existing iOS cookie snapshot helper pattern: - -- Record baseline `cf_clearance`. -- Wait for a new `cf_clearance`. -- Confirm the page no longer contains active challenge markers. -- Return only the relevant platform cookies to Rust. - -- [ ] **Step 3: Keep hidden refresh runtime behind gates** - -`FireCfClearanceRefreshService.shouldAutoRefresh()` must remain gated by: - -```text -scene active -login state confirmed -current user present -authenticated API readable -existing cf_clearance present -turnstile sitekey present -``` - -- [ ] **Step 4: Remove misleading no-op naming** - -Rename or replace `performWithCloudflareRecovery` / `performWriteWithCloudflareRetry` after the Rust contract exists. Until then, do not reintroduce auto-present recovery behavior under those names. - ---- - -### Task 7: Android — Add parity manual challenge and hidden refresh runtime - -**Files:** -- Create: `apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/session/FireCfClearanceRefreshService.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/auth/LoginWebViewFragment.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/webview/FireWebViewSupport.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/core/error/FireErrorHandling.kt` -- Test: Android unit / instrumentation tests where available - -- [ ] **Step 1: Reuse browser-like WebView configuration** - -Manual CF WebView must share login WebView UA, cookie manager, JS settings, popup routing, safe browsing, and dark/light behavior. - -- [ ] **Step 2: Implement foreground challenge UI** - -Foreground user actions may present a visible challenge screen. Background/silent work must also be able to complete CF verification instead of returning `CloudflareChallenge` immediately. The current minimum path may reuse the full-screen challenge Activity; a later UX pass should add a FluxDO-style floating pill / small-window entry that can be promoted to full-screen verification. - -- [ ] **Step 3: Implement hidden `cf_clearance` refresh** - -Mirror the iOS runtime and FluxDO service: - -- Load Turnstile HTML in an offscreen WebView only after login is confirmed. -- Intercept `/cdn-cgi/challenge-platform/.../rc/...`. -- Replay the rc call through native networking. -- Sync only `cf_clearance` back to Rust. - -- [ ] **Step 4: Do not add an Android startup recovery shortcut** - -Onboarding remains a single login entry. Startup session restoration stays in `PreheatGateFragment` and Rust `determineLoginStateWithProbe()`. - ---- - -### Task 8: Double-end error presentation policy - -**Files:** -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/core/error/FireErrorHandling.kt` -- Modify: affected stores/view models that currently special-case auth errors - -- [ ] **Step 1: LoginRequired presentation** - -`LoginRequired` should be displayed as a request failure unless Rust session state has actually transitioned to logged out. Platform must not present login just because one request returned `LoginRequired`. - -- [ ] **Step 2: Cloudflare presentation** - -Foreground operations may route to manual challenge. Passive/background operations that hit CF should be able to trigger verification instead of failing silently; the current bridge may use the same host-owned challenge UI, while the follow-up UX target is a non-blocking floating pill / small-window entry that can be promoted by user action or timeout. - -Current implementation note: Rust now carries Cloudflare presentation context on -the traced request. The full notification history fetch is explicitly -foreground-capable, while recent notification cache refreshes remain -background. This keeps notification-tab user gestures aligned with home/topic -detail/search reads without letting silent notification work steal focus. - -- [ ] **Step 3: Add global request scheduler and sliding-window limit** - -Introduce a RequestScheduler-style gate before business requests are sent. When manual CF verification is active, block or queue non-`skip_cf_block` requests; when repeated 403/429 responses arrive in a short window, apply cooldown/backoff before more requests are dispatched. This is separate from the existing Rust CF challenge `in_progress` gate, which only protects the active resolution window and does not provide FluxDO-style global request scheduling. - -- [ ] **Step 4: State-driven navigation** - -Navigation to onboarding/login must be driven by authoritative session snapshot state, not by a local platform classifier. - ---- - -### Task 9: Redirect delta audit against openwire - -**Files:** -- Inspect: upstream `openwire` sources for the crates.io version in use -- No Fire-side redirect interceptor required -- Potential openwire change only if future callers need stricter explicit-`Cookie` redirect handling -- Test: openwire redirect tests - -- [x] **Step 1: Audit current openwire redirect behavior** - -Verified: - -- Default max redirect count is 10. -- HTTPS -> HTTP downgrade is rejected unless explicitly allowed. -- `301/302/303` switch non-GET/HEAD requests to GET and drop body framing headers. -- `307/308` preserve method/body and require replayable body. -- Cross-origin redirect removes `Cookie` and `Authorization`. -- Normal Fire requests do not carry an explicit `Cookie` header before openwire's CookieJar injection, so redirect follow-ups recompute cookies for the redirected URL. -- Response `Set-Cookie` is persisted against the response request URL before following the next location; Fire's `FireSessionCookieJar` additionally rejects non same-site ingress. - -- [x] **Step 2: Compare FluxDO behavior** - -FluxDO disables Dio auto redirect and manually reissues redirect requests after clearing `Cookie` / `cookie` headers so its CookieManager recomputes cookies. Openwire already follows the same practical behavior for Fire's normal CookieJar-owned requests, with stronger built-in redirect guardrails. Fire should not copy FluxDO's manual redirect interceptor. - -- [x] **Step 3: Decide ownership** - -Decision: no Fire-specific redirect implementation in this auth/CF runtime plan. - -If future product code explicitly sets `Cookie` headers and needs FluxDO's stricter per-hop clearing even for same-origin redirects, fix it in openwire by adding a redirect request policy knob and tests. Do not implement redirect recursion in a Fire application interceptor. - ---- - -### Task 10: Remove legacy recovery surfaces and stale docs - -**Files:** -- Already modified: `apps/android-app/src/main/res/layout/fragment_onboarding.xml` -- Already modified: `apps/android-app/src/main/java/com/fire/app/ui/auth/OnboardingFragment.kt` -- Already modified: `apps/android-app/src/main/res/navigation/fire_nav_graph.xml` -- Already modified: `apps/android-app/src/main/res/values/strings.xml` -- Already modified: `apps/android-app/src/main/java/com/fire/app/ui/auth/AuthViewModel.kt` -- Already modified: `apps/android-app/src/main/res/drawable/bg_error_banner.xml` -- Modify after runtime implementation: `apps/ios-app/README.md` -- Modify after runtime implementation: `docs/architecture/fire-native-architecture.md` -- Modify after runtime implementation: `docs/knowledge/api/01-global-conventions.md` -- Modify after runtime implementation: `docs/knowledge/api/02-auth-and-session.md` - -- [x] **Step 1: Remove Android login-below restore entry** - -Delete `restore_session_button`, `onboarding_restore_session`, unused onboarding-to-home action, and the same stale onboarding branch's hidden loading/error UI. - -- [x] **Step 2: Re-audit iOS login/onboarding** - -Confirm there is no equivalent login-below restore entry. Developer tools may keep a diagnostic “恢复会话” action if it only re-runs startup loading and is clearly not a production login shortcut. - -- [x] **Step 3: Clean stale recovery docs** - -After Tasks 5-8 land, remove any doc text claiming the app auto-opens login or recovery WebView for ordinary request errors. - ---- - -### Task 11: Verification Matrix - -**Rust commands:** - -```bash -cargo test -p fire-models -cargo test -p fire-core --test network --test auth_strike --test login_finalization -cargo test -p fire-uniffi-session -cargo test -p openwire --features websocket --lib policy:: -``` - -**Android commands:** - -```bash -export ANDROID_HOME=/Users/zhangfan/Library/Android/sdk -export ANDROID_SDK_ROOT=/Users/zhangfan/Library/Android/sdk -./gradlew :app:assembleDebug -``` - -**iOS commands:** - -```bash -cd apps/ios-app -xcodegen generate -xcodebuild -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16' build -``` - -**Manual scenarios:** - -- [ ] Cold start with no cookies: PreheatGate -> onboarding; no restore-account action visible. -- [ ] Cold start with valid `_t`: Rust probe valid -> home; MessageBus starts after first home refresh. -- [ ] Cold start with expired `_t`: probe invalid -> passive logout preserving `cf_clearance`. -- [ ] `/session/csrf` returns `2xx` with `discourse-logged-out`: CSRF stored, no login popup. -- [ ] `403 invalid_access`: no logout, no challenge UI. -- [ ] `403 not_logged_in` + probe valid: request fails, session preserved. -- [ ] `403 not_logged_in` + probe invalid: passive logout, onboarding after snapshot changes. -- [ ] `403 CF HTML`: manual challenge, new `cf_clearance`, original request retries once. -- [ ] Silent/background `403 CF HTML`: verification path is available and does not return incomplete/cancelled solely because the triggering request is background; future UX should prefer floating pill / small-window promotion over immediate full-screen UI. -- [x] Redirect across same origin: openwire audit confirms normal Fire CookieJar-owned requests recompute cookies for each follow-up URL. -- [x] Redirect across origin: openwire audit confirms cross-origin redirect removes `Cookie` / `Authorization`, and Fire cookie ingress remains same-site scoped. diff --git a/docs/superpowers/plans/2026-06-06-topic-detail-api-consolidation.md b/docs/superpowers/plans/2026-06-06-topic-detail-api-consolidation.md deleted file mode 100644 index 13d7873a..00000000 --- a/docs/superpowers/plans/2026-06-06-topic-detail-api-consolidation.md +++ /dev/null @@ -1,883 +0,0 @@ -# Topic Detail API Consolidation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** 将 Fire 贴文详情收口到“原始网络数据源分页”和“树状业务呈现”严格分离的 Rust 权威模型:底层分页必须按 `post_stream.stream` 的原始顺序和树化前的最后 `postId` 批量拉取,树状 thread 呈现作为上层业务处理保留并继续成为 Fire 双端特色。 - -**Architecture:** Rust Core 同时拥有两层职责,但必须显式分层。第一层是 raw source:负责 `/t/{id}.json`、`/t/{id}/posts.json?post_ids[]=...`、原始 `post_stream.stream`、source cursor、deep-link anchor 和批量拉取。第二层是 presentation:在已加载 raw posts 基础上生成树状 timeline rows、depth、parent、root grouping 和 UI 所需摘要。iOS / Android 只拥有路由、滚动、可见性上报、原生渲染、平台挑战 WebView 和少量 targeted hydration;平台不得以树状 row 或 root reply 反向驱动网络分页。 - -**Tech Stack:** Rust + openwire + UniFFI + tokio / Swift + UIKit + Texture / Kotlin + RecyclerView + androidx - -**Design Inputs:** -- `docs/knowledge/api-overview.md` -- `docs/knowledge/api/03-topics.md` -- `docs/knowledge/api/10-presence-and-categories.md` -- `docs/knowledge/api/12-messagebus.md` -- `docs/architecture/fire-native-architecture.md` -- `crates/fire-models/src/topic_detail.rs` -- `crates/fire-core/src/core/topics.rs` -- `crates/fire-core/src/core/topic_feed.rs` -- `crates/fire-core/src/core/interactions.rs` -- `crates/fire-core/src/core/presence.rs` -- `crates/fire-uniffi-topics/src/lib.rs` -- `crates/fire-uniffi-topics/src/records.rs` -- `apps/ios-app/App/Stores/FireTopicDetailStore.swift` -- `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- `apps/android-app/src/main/java/com/fire/app/data/repository/TopicRepository.kt` -- `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt` -- `references/fluxdo/lib/services/discourse/_topics.dart` -- `references/fluxdo/lib/providers/topic_detail/_loading_methods.dart` -- `references/fluxdo/lib/providers/topic_detail/_filter_methods.dart` -- `references/fluxdo/lib/providers/topic_detail/_post_updates.dart` -- `references/fluxdo/lib/providers/message_bus/topic_channel_provider.dart` - ---- - -## Audit Corrections (2026-06-06) - -本计划基于当前 Fire 与 FluxDO 源码审查结果,以下事项为**强约束**: - -- `docs/knowledge/api-overview.md` 仍把贴文详情概括成 `GET /t/{topicId}.json` + `GET /t/{topicId}/posts.json`,这只能表达底层端点,不再等于 Fire 当前权威读模型。 -- Fire 当前双端主详情页的真实入口已经是 Rust `fetch_topic_screen()` + `fetch_topic_response_page()`,而不是平台直接拼 `/t/{id}/{postNumber}.json` 或 `getPostsByNumber(...)` 窗口。 -- FluxDO 对 Fire 的参考价值主要是端点清单、筛选参数、MessageBus 事件类型、Presence/timings/AI summary 等侧边能力,不是其 host-managed 详情窗口架构本身。 -- Fire 当前 Rust 主路径确实在用 top-level root id 驱动主分页:`fetch_topic_screen()` 先抽 `root_stream_ids`,后续 `load_root_branch_into_session(root_post_id, ...)` 再用 `fetch_post_reply_ids(root_post.id)` 和 descendant `post_ids[]` 拉数据。这条路径把业务树结构反向拿来驱动底层网络分页,不符合本计划目标。 -- 正确的底层分页边界应该来自树化前的原始 `post_stream.stream`。无论最终 UI 是否展示为树状 thread,网络层都必须依据原始流中的最后已加载 `postId` / `stream offset` 继续批量拉取下一段 raw posts。 -- 一次用户触发的“加载更多”不必严格等于一次网络批量请求。如果某一批 raw posts 只给现有 root 补充 descendants、没有给树状视图带来新的 root-level 可见进展,那么同一次用户动作内应自动继续拉下一批,直到出现新的 root post、source exhaust、达到自动批量上限或发生错误。 -- `TopicDetailFeedSnapshot` / processed feed 路径在 Rust 仍存在,但 iOS/Android 主详情页都不依赖它;本计划要求删除这条并行读链路,而不是继续以 retained 或 inactive 名义保留。 -- `fetch_topic_detail()` / `fetch_topic_detail_initial()` 仍通过 UniFFI 暴露,但当前 iOS/Android 主详情页没有依赖它们作为 authoritative surface;本计划要求把它们收口为内部底层接口或直接删除外部暴露,不允许继续维持“看起来也能当主接口”的兼容面。 -- `forceLoad` 查询参数已经存在于 Fire 当前 `TopicDetailQuery` / `TopicScreenQuery` 实现中;如果它仍有运行时意义,就必须补文档并进入契约说明;如果没有意义,后续必须删除,而不是继续保持隐式行为。 -- 回复上下文 API 与主阅读面 API 必须分层:`fetch_topic_posts`、`fetch_post_reply_ids`、`fetch_post_reply_history`、`fetch_post_replies` 只用于 targeted context,不参与主详情页分页。 -- MessageBus 在 API 层的职责是 topic/reaction/poll/presence 事件和失效信号,不是让 host 回退到逐帖 `fetch post` patch 模式重新拼读模型。 -- Presence、topic timings、AI summary 都是主详情页成功渲染之后的 sidecar capability,不应被塞进 `TopicScreen` 主载荷里。 - -## Target Contract - -### Raw Source Contract - -```text -TopicDetailSourceQuery { - topic_id, - target_post_number?, - track_visit, - force_load, - initial_batch_size -} - - -> TopicDetailSourceSnapshot { - header, - body, - raw_stream_ids, - loaded_posts, - source_cursor?, - focused_post_number? - } - -TopicSourceCursor { - topic_id, - last_loaded_post_id, - next_stream_offset, - batch_size -} - -LoadMoreTopicPostsQuery { cursor } - -> TopicDetailSourceAppend { - appended_posts, - next_source_cursor? - } -``` - -### Tree Presentation Contract - -```text -fetch_topic_detail_page(TopicDetailSourceQuery) - -> TopicDetailPage { - source_snapshot, - tree_presentation - } - -TopicTreePresentation { - original_post_id, - original_post_number, - reply_rows, - total_loaded_post_count, - visible_root_post_numbers, - gained_new_root_progress -} - -TopicTreeRow { - post_id, - post_number, - root_post_number, - parent_post_number?, - depth, - sibling_index, - is_last_sibling, - descendant_count -} -``` - -树状 depth、parent、root grouping、thread 展示都属于这一层。它可以继续作为 Fire 双端特色存在,但不得反向决定下一次网络分页边界。完整 `TopicPost` 只通过 source snapshot 传输,tree presentation 只携带 post id / number 和展示元数据。 - -### Targeted Context Contract - -这些 API 只允许服务局部上下文,不得再被提升为主详情页分页入口: - -- `fetch_topic_posts(topic_id, post_ids[])` -- `fetch_post_by_number(topic_id, post_number)` -- `fetch_post_reply_ids(post_id)` -- `fetch_post_reply_history(post_id)` - -### Sidecar Contract - -- `report_topic_timings(input)` -- `bootstrap_topic_reply_presence(topic_id, owner_token)` -- `update_topic_reply_presence(topic_id, active)` -- `fetch_topic_ai_summary(topic_id, skip_age_check)` -- MessageBus `/topic/{topicId}`、`/topic/{topicId}/reactions`、poll channel、`/presence/discourse-presence/reply/{topicId}` - -## Proposed Data Structures - -### Rust Internal Runtime - -这些结构只存在于 Rust Core 内部,不直接穿过 UniFFI: - -```rust -struct TopicDetailSourceSession { - topic_id: u64, - session_id: u64, - session_epoch: u64, - header: TopicHeader, - body_post_id: u64, - body_post_number: u32, - focused_post_number: Option, - raw_stream_ids: Vec, - posts_by_id: HashMap, - post_id_by_number: HashMap, - loaded_ranges: Vec, - next_stream_offset: usize, - last_loaded_post_id: Option, - source_exhausted: bool, -} - -struct TopicLoadedRange { - start_offset: usize, - end_offset_exclusive: usize, - first_post_id: u64, - last_post_id: u64, -} - -struct TopicLoadMorePolicy { - batch_size: u16, - max_auto_batches_per_gesture: u8, - max_auto_posts_per_gesture: u16, - require_new_root_progress: bool, -} -``` - -字段约束: - -- `raw_stream_ids` 是网络 source 真相,直接来自底层 detail `post_stream.stream` -- `posts_by_id` / `post_id_by_number` 只表示“已经拉到手的 raw posts”,不编码树结构 -- `loaded_ranges` 反映 raw stream 哪些 offset 已被装载,便于去重和调试 -- `next_stream_offset` / `last_loaded_post_id` 是唯一分页边界 -- `source_exhausted` 只由 `next_stream_offset >= raw_stream_ids.len()` 得出 -- 树状 root、depth、parent、descendant_count 不进入 source session - -### UniFFI / Shared Records - -这些结构是平台可见的稳定契约: - -```rust -pub struct TopicDetailSourceQuery { - pub topic_id: u64, - pub target_post_number: Option, - pub track_visit: bool, - pub force_load: bool, - pub initial_batch_size: u16, - pub load_more_batch_size: u16, - pub max_auto_batches_per_gesture: u8, - pub max_auto_posts_per_gesture: u16, -} - -pub struct TopicDetailSourceSnapshot { - pub header: TopicHeader, - pub body: TopicBody, - pub raw_stream_ids: Vec, - pub loaded_posts: Vec, - pub loaded_ranges: Vec, - pub source_cursor: Option, - pub source_exhausted: bool, - pub focused_post_number: Option, -} - -pub struct TopicSourceCursor { - pub topic_id: u64, - pub session_id: u64, - pub next_stream_offset: u32, - pub last_loaded_post_id: Option, - pub batch_size: u16, -} - -pub struct TopicDetailSourceAppend { - pub appended_posts: Vec, - pub loaded_ranges: Vec, - pub source_cursor: Option, - pub source_exhausted: bool, -} - -pub struct TopicTreePresentation { - pub original_post_id: u64, - pub original_post_number: u32, - pub reply_rows: Vec, - pub total_loaded_post_count: u32, - pub visible_root_post_numbers: Vec, - pub gained_new_root_progress: bool, -} - -pub struct TopicTreeRow { - pub post_id: u64, - pub post_number: u32, - pub root_post_number: u32, - pub parent_post_number: Option, - pub depth: u16, - pub sibling_index: u16, - pub is_last_sibling: bool, - pub descendant_count: u32, -} - -pub enum TopicLoadMoreStopReason { - GainedVisibleRootProgress, - SourceExhausted, - MaxAutoBatchesReached, - MaxAutoPostsReached, - RequestFailed, -} - -pub struct TopicLoadMoreOutcome { - pub source_snapshot: TopicDetailSourceSnapshot, - pub tree_presentation: TopicTreePresentation, - pub chained_batches: u8, - pub chained_posts: u16, - pub stop_reason: TopicLoadMoreStopReason, -} -``` - -字段约束: - -- `TopicDetailSourceSnapshot` 是 raw-source 状态快照,不包含预先树化的 rows -- `TopicTreePresentation` 是 source snapshot 的派生结果,可重复构建;跨 UniFFI 只返回 slim row 元数据,不重复携带 `TopicPost` -- `gained_new_root_progress` 只用于判定本次用户手势是否继续自动拉下一批,不代表 `hasMore` -- `TopicLoadMoreOutcome` 把“source 是否到底”和“本次是否带来新的 root 进展”显式分开 - -### Platform Page State - -iOS store / Android ViewModel 应持有的状态建议统一为: - -```text -TopicDetailPageState - sourceSnapshot: TopicDetailSourceSnapshot - treePresentation: TopicTreePresentation - loadMoreState: - isLoading - stopReason? - chainedBatches - chainedPosts - anchorState: - targetPostNumber? - pendingScrollPostNumber? - sidecars: - aiSummary? - presenceUsers[] - timingState -``` - -平台约束: - -- 平台只缓存 `sourceSnapshot` 和 `treePresentation` -- 平台不持有独立的 root-page cursor、branch cursor、root reply ids 分页状态 -- 平台可做 render diff、scroll anchor、visible-post timing,但不决定下一批网络拉什么 -- iOS / Android 的树状显示差异只能体现在 presentation consume 层,不能倒灌 source 层 - -## Structure Migration Map - -### Public Contract Mapping - -| Current type / field | Current meaning | New home | Action | -|---|---|---|---| -| `TopicScreenQuery` | 主详情读取 + root-page 分页入口 | `TopicDetailSourceQuery` | Rename + semantic rewrite | -| `TopicScreen.header` | 主题元数据 | `TopicDetailSourceSnapshot.header` | Move | -| `TopicScreen.body` | 主贴 | `TopicDetailSourceSnapshot.body` | Move | -| `TopicScreen.response.rows` | 已树化的回复行 | `TopicTreePresentation.reply_rows` | Move to presentation layer | -| `TopicScreen.response.focused_post_number` | deep-link 命中信息 | `TopicDetailSourceSnapshot.focused_post_number` | Move | -| `TopicResponseCursor.next_root_offset` | root 分页偏移 | none | Delete | -| `TopicResponseCursor.next_branch_offset` | branch 分页偏移 | none | Delete | -| `TopicResponseCursor.page_size` | root page size | `TopicSourceCursor.batch_size` | Replace semantics | -| `TopicResponseCursor.row_page_size` | 行数预算 | none | Delete | -| `TopicResponsePageQuery` | 基于 root/branch 的下一页请求 | `LoadMoreTopicPostsQuery` | Replace | -| `TopicResponsePage.rows` | 本次树化行增量 | `TopicLoadMoreOutcome.tree_presentation.reply_rows` | Replace | -| `TopicResponsePage.next_cursor` | root/branch next cursor | `TopicDetailSourceAppend.source_cursor` | Replace | -| `TopicResponsePage.total_root_count` | root 总数 | none | Delete unless future diagnostics explicitly require | -| `TopicResponsePage.loaded_root_count` | 已加载 root 数 | none | Delete | -| `TopicResponsePage.total_response_count` | 回复总数 | `TopicDetailSourceSnapshot.raw_stream_ids.len() - 1` or `header.reply_count` | Derive, do not carry dedicated field | -| `TopicResponseRow.root_post_number` | 树展示根节点 | `TopicTreeRow.root_post_number` | Keep in presentation only | -| `TopicResponseRow.parent_post_number` | 树展示父节点 | `TopicTreeRow.parent_post_number` | Keep in presentation only | -| `TopicResponseRow.depth` | 树展示深度 | `TopicTreeRow.depth` | Keep in presentation only | -| `TopicResponseRow.descendant_count` | 树展示摘要 | `TopicTreeRow.descendant_count` | Keep in presentation only | - -### Rust Internal Mapping - -| Current runtime structure | Problem | New structure | Action | -|---|---|---|---| -| `FireTopicResponseRuntime` | 名称和职责绑定 root-response 分页 | `FireTopicDetailSourceRuntime` | Rename + rewrite | -| `TopicResponseSession` | 把 source、root、branch、presentation 混在一起 | `TopicDetailSourceSession` | Replace | -| `TopicBranchIndex` | 为 root-driven 分页服务 | none | Delete | -| `TopicResponseNode` | 为 branch tree index 服务 | none as stored runtime; compute transiently in presentation build | Delete persistent runtime form | -| `BranchLoadRequest` | root-level batch planning | none | Delete | -| `TopicResponsePageLoadRequest` | root/branch page load input | `TopicSourceBatchLoadRequest` if needed internally | Replace | -| `branch_reply_ids_by_root_id` | root->descendant source cache | none | Delete | -| `branch_by_root_id` | root->presentation cache | none persistent; recompute presentation from loaded raw posts | Delete | - -### Platform State Mapping - -| Current platform state | New state | Action | -|---|---|---| -| iOS `topicScreens[topicId]` | `sourceSnapshots[topicId]` + `treePresentations[topicId]` | Split | -| iOS `topicResponseRowsByTopic` | `treePresentations[topicId].replyRows` | Replace | -| iOS `topicResponseCursorsByTopic` | `sourceCursorsByTopic` | Replace | -| Android `screen` | `sourceSnapshot` + `treePresentation` | Split | -| Android `responseRows` | `treePresentation.replyRows` | Replace | -| Android `cursor` | `sourceCursor` | Replace | - -## Explicit Cleanup / Delete List - -以下内容不是“可以考虑清理”,而是本计划实现过程中要明确删除的对象。 - -### Rust Models / FFI - -- `TopicScreenQuery` -- `TopicScreen` -- `TopicResponseCursor` -- `TopicResponsePageQuery` -- `TopicResponsePage` -- `TopicResponseRow` -- `TopicScreenQueryState` -- `TopicScreenState` -- `TopicResponseCursorState` -- `TopicResponsePageQueryState` -- `TopicResponsePageState` -- `TopicResponseRowState` -- `TopicDetailFeedQueryState` -- `TopicDetailFeedSnapshotState` -- `TopicDetailFeedItemState` -- `TopicDetailCursorState` -- `TopicDetailLoadedRangeState` 中仅为旧 feed cursor 服务的字段定义,如果与新 source range 设计不兼容则重做 - -### Rust Core Root-Driven Pagination Logic - -- `TopicResponseSession` -- `TopicBranchIndex` -- `TopicResponseNode` -- `BranchLoadRequest` -- `TopicResponsePageLoadRequest` -- `roots_needed_for_response_page(...)` -- `assemble_topic_response_page(...)` -- `build_branch_index(...)` -- `append_children_preorder(...)` -- `root_stream_ids_from_top_level_posts(...)` -- `root_stream_ids_including_focus_root(...)` -- `initial_topic_response_page_size(...)` -- `load_root_branch_into_session(...)` -- `fetch_topic_response_page(...)` 现有 root/branch 语义实现 -- 所有 `branch_reply_ids_by_root_id` / `branch_by_root_id` / `root_stream_ids` 持久状态 - -### Platform Convenience Surfaces - -- iOS `FireSessionStore.fetchTopicDetail(query:)` 作为主详情入口的使用 -- iOS `FireSessionStore.fetchTopicDetailInitial(query:)` -- iOS `FireSessionStore.fetchTopicDetail(topicID:trackVisit:)` -- iOS `FireSessionStore.loadTopicDetailFeed(...)` -- iOS `FireSessionStore.refreshTopicDetailFeed(...)` -- iOS `FireSessionStore.cachedTopicDetailFeed(...)` -- Android `FireSessionStore.fetchTopicDetail(...)` -- Android `FireSessionStore.fetchTopicDetailInitial(...)` -- Android / iOS 任何仍把 `TopicScreen` / `TopicResponsePage` 当主详情权威契约的 wrapper - -### Platform State / Logic To Remove - -- iOS `topicResponseRowsByTopic` -- iOS `topicResponseCursorsByTopic` -- iOS 任何以 response row / root row 判断下一次要拉哪批网络数据的逻辑 -- Android `responseRows` 作为 source state 的职责 -- Android `cursor` 中任何 root/branch 语义 -- 双端任何基于 root-level row 可见性决定底层 source batch 边界的逻辑 - -### Optional Deletion If No Independent Product Need Remains - -这些调用若只剩兼容用途,应在同一轮实现里删除,而不是继续以 fallback 名义保留: - -- `fetch_post_replies(...)` -- reply-context 中任何 “reply-id tree 失败后退回 `/replies.json`” 的逻辑 - -### Explicit Non-Goals For This Rollout - -- 不恢复 FluxDO 风格的 host-managed `getPostsByNumber(...)` 页面窗口逻辑。 -- 不再让 root reply ids、tree rows、root page 概念驱动底层网络分页。 -- 删除 processed feed snapshot 及其平台暴露,不保留 inactive / retained / migration 名义的并行读链路。 -- 删除平台层 stringly `filter` / `username_filters` / `filter_top_level_replies` 详情页窗口逻辑,不保留兼容入口。 -- 不为了筛选模式再引入一套与主详情不同的主读取模型;若未来需要筛选详情页,应新增 typed Rust `TopicScreenFilter` 合约。 - ---- - -### Task 1: Docs — Rewrite topic detail API docs to match the current runtime - -**Files:** -- Modify: `docs/knowledge/api-overview.md` -- Modify: `docs/knowledge/api/03-topics.md` -- Modify: `docs/knowledge/api/10-presence-and-categories.md` -- Modify: `docs/knowledge/api/12-messagebus.md` -- Modify: `docs/architecture/fire-native-architecture.md` -- Modify: `apps/ios-app/README.md` -- Modify: `apps/android-app/README.md` - -- [ ] **Step 1: 修正 topic detail 文档入口** - -把 `api-overview` 中“话题详情”从旧摘要: - -```text -GET /t/{topicId}.json -GET /t/{topicId}/posts.json -POST /topics/timings -GET /presence/get -POST /presence/update -``` - -改成分层描述: - -```text -Primary source: raw stream + source cursor + batched post_ids loading -Presentation: tree rows built from loaded raw posts -Sidecar: timings / presence / AI summary / MessageBus -``` - -- [ ] **Step 2: 在 `03-topics.md` 明确 primary vs low-level** - -保留底层端点章节,但新增一节 “Fire authoritative topic-detail contract”,明确: - -- `GET /t/{id}.json` 只是底层原始 detail 端点 -- `post_stream.stream` 是底层分页真相来源 -- `GET /t/{topicId}/posts.json` 主路径只按 raw stream slice + `post_ids[]` 批量拉取 -- 树状 rows 是对 loaded raw posts 的业务加工结果 -- `post_number` 深链只影响初始 anchor,不再定义主分页模型 - -- [ ] **Step 3: 补齐 Fire-specific query knobs** - -当前运行时存在但文档未写清的契约必须显式记录: - -- `initial_batch_size` -- `last_loaded_post_id` -- `next_stream_offset` -- `target_post_number` -- `forceLoad` 的现状、适用场景和后续去留决策 - -- [ ] **Step 4: 把 Presence / timings / MessageBus 从“主详情载荷”中剥离** - -在 `10-presence-and-categories.md` 和 `12-messagebus.md` 明确: - -- Presence 是 sidecar,不参与主详情页首屏数据 shape -- timings 是后台静默写路径 -- MessageBus topic/reaction/poll/presence 是失效与事件信号,不是主详情读模型 - -- [ ] **Step 5: 统一 README 描述** - -iOS / Android README 都要保持同一结论: - -- authoritative source path = initial detail + batched `post_ids[]` append -- authoritative presentation path = tree rows built from loaded raw posts -- targeted context path = reply ids/history/posts -- AI summary / presence / timings 为独立 sidecar - ---- - -### Task 2: Rust + UniFFI — Replace root-based cursor pagination with raw source pagination - -**Files:** -- Modify: `crates/fire-models/src/topic_detail.rs` -- Modify: `crates/fire-uniffi-topics/src/lib.rs` -- Modify: `crates/fire-uniffi-topics/src/records.rs` -- Modify: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` - -- [ ] **Step 1: 在 model / UniFFI 引入 source 与 presentation 的分层结构** - -新增或重构为两层契约: - -- `TopicDetailSourceQuery` -- `TopicDetailSourceSnapshot` -- `TopicLoadedRangeState` -- `TopicSourceCursor` -- `LoadMoreTopicPostsQuery` -- `TopicDetailSourceAppend` -- `TopicDetailPage` -- `TopicTreePresentation` -- `TopicTreeRow` -- `TopicLoadMoreStopReason` -- `TopicLoadMoreOutcome` - -`TopicDetailQuery` 若继续存在,只允许作为底层 raw endpoint contract,不再承担主详情页分页语义。 - -- [ ] **Step 2: 删除平台 session store 上的误导性 convenience surface** - -当前以下方法虽然存在,但并非主详情页真实入口: - -- iOS `fetchTopicDetail(topicID:trackVisit:)` -- iOS `loadTopicDetailFeed(...)` / `refreshTopicDetailFeed(...)` / `cachedTopicDetailFeed(...)` -- Android `fetchTopicDetail(...)` / `fetchTopicDetailInitial(...)` - -本阶段要求: -- 迁移任何剩余调用方后,直接移除平台侧 public wrapper -- 不允许通过重命名、注释或 legacy 标签继续把 dead surface 留在公开 API 上 - -- [ ] **Step 3: 删除 `TopicResponseCursor` / root-page 语义的 FFI 与平台暴露** - -以下语义不再作为主详情公开契约存在: - -- `next_root_offset` -- `next_branch_offset` -- `root_page_size` -- `row_page_size` -- 任何以 root page 为网络分页单位的 cursor - -如果删除过程中发现隐藏 consumer: -- 先迁移 consumer 到 raw source cursor + tree presentation -- 同一任务内完成删除 -- 不允许以 migration surface、internal fallback、retained path 的名义继续保留 - -- [ ] **Step 4: 对照 `Explicit Cleanup / Delete List` 勾销 public dead surface** - -本步骤结束前必须明确核对: - -- Rust Models / FFI 下的 dead types 是否已删 -- Platform Convenience Surfaces 下的 wrappers 是否已删 -- 旧 root-page cursor 语义是否已从 public API 消失 - -未删除项必须记录具体 blocker 和所属文件,不允许默认保留。 - -- [ ] **Step 5: 重新生成并校验绑定** - -如果 FFI surface 发生变更: - -Run: `apps/ios-app/scripts/sync_uniffi_bindings.sh` - -Expected: Swift/Kotlin 绑定与 Rust surface 一致 - ---- - -### Task 3: Rust — Separate raw-source batching from tree assembly - -**Files:** -- Modify: `crates/fire-core/src/core/topics.rs` -- Test: `crates/fire-core/tests/network.rs` -- Test: `crates/fire-core/src/core/topics.rs` unit tests - -- [ ] **Step 1: 删除 root-driven 主分页** - -当前以下主分页行为需要移除: - -- 从 `filter_top_level_replies=true` 提取 `root_stream_ids` -- 用 `roots_needed_for_response_page(...)` 决定下一次网络拉取 -- 对每个 root 调 `fetch_post_reply_ids(root_post.id)` 再按 branch 补 descendant ids - -这些都属于“业务树结构反向驱动网络 source”的错误方向。 - -- [ ] **Step 2: 删除 root/branch runtime 持久状态** - -本步骤要求一起删除: - -- `root_stream_ids` -- `branch_reply_ids_by_root_id` -- `branch_by_root_id` -- `TopicBranchIndex` -- `TopicResponseNode` - -若 presentation build 仍需要短暂树索引,只允许在单次构建过程中临时创建,不得常驻 source runtime。 - -- [ ] **Step 3: 以 raw stream 建立 source session** - -新的 source session 至少要持有: - -- `raw_stream_ids`,直接来自 detail `post_stream.stream` -- `loaded_posts_by_id` -- `loaded_stream_offsets` 或等价 loaded range -- `last_loaded_post_id` -- `next_stream_offset` -- deep-link anchor metadata - -主分页必须只从 `raw_stream_ids` 的下一个 offset 继续切 batch,并通过 `fetch_topic_posts(post_ids[])` 拉取。 - -- [ ] **Step 4: 初始加载与 deep link 仍可保留 targeted anchor,但不改变主分页模型** - -要求: - -- 初始详情仍可通过 `/t/{id}.json` 或 `/t/{id}/{postNumber}.json` 获取 anchor 附近首包 -- deep link 可额外确保目标 post 所在局部窗口被 hydration -- 但首包之后的继续加载,一律回到 `raw_stream_ids` 线性 batch append -- 不允许因为 deep link target 落在某个 root branch,就把后续分页切换成按 root 拉 - -- [ ] **Step 5: 将单次用户 load more 定义成“可见进展驱动”的自动批量循环** - -对用户来说,一次上拉加载应该尽量带来可见进展。推荐规则: - -```text -user load more - -> load source batch #1 - -> rebuild tree presentation - -> if no new visible root-level progress and source not exhausted: - auto load source batch #2 - -> repeat until: - new root-level progress - or source exhausted - or max_auto_batches reached - or max_auto_posts reached - or request fails -``` - -其中: - -- `source exhausted` 只由 raw stream cursor 判定 -- `new root-level progress` 只决定这次用户动作是否继续自动拉下一批,不决定底层 `hasMore` -- 自动批量循环属于 Rust source/presentation orchestration,不下放平台各自发明 - -- [ ] **Step 6: 将树状 thread 变成 source 之上的纯业务装配** - -保留 Fire 的树状特色,但它只能消费 loaded raw posts: - -- 根据 `reply_to_post_number` / post order 构建 tree rows -- 生成 `depth` / `parent_post_number` / root grouping -- 允许 partial-load 下存在未闭合 thread -- 不允许 tree row / root row 反向决定下一次 source batch - -- [ ] **Step 7: 强化 tree assembly 健壮性** - -补测试覆盖: - -- duplicate post ids -- reply-to-self -- missing parent -- reply cycle -- orphan descendants -- partial descendant hydration - -要求 tree assembly 在这些异常数据下仍能产出稳定 preorder rows,而不是把错误兜回平台。 - -- [ ] **Step 8: 锁定 source cursor 失效、自动批量和去重语义** - -补测试覆盖: - -- session epoch 改变后旧 cursor 失效 -- topic id / session id 不匹配时返回 `InvalidTopicResponseCursor` -- source batch append 按 `raw_stream_ids` 顺序推进,不产生重复 raw posts -- tree rebuild 后不产生重复 rows -- `fetch_topic_posts` 写回 active source session cache 后,后续 targeted hydration 复用缓存而不重复请求 -- 单次用户 load more 在第一批未产生新 root-level progress 时,会自动继续下一批 -- 自动批量在出现新 root-level progress、source exhaust、达到批量/帖子预算或错误时停止 - -- [ ] **Step 9: 对照 `Explicit Cleanup / Delete List` 勾销 root-driven core logic** - -本步骤结束前必须明确核对: - -- Rust Core Root-Driven Pagination Logic 下的函数和结构是否已删 -- old `fetch_topic_response_page(...)` implementation 是否已替换 -- root-driven source cache 是否已消失 - -未删除项必须附带明确新职责说明,不能因为“可能还有用”保留。 - -- [ ] **Step 10: 补齐 source vs presentation 契约文档注释** - -在 Rust 侧明确: - -- `next_stream_offset` / `last_loaded_post_id` 属于底层 source cursor -- tree rows / depth / root grouping 属于 presentation 结果 -- source batch size 控制本次拉取的 raw posts 数,不等于 UI row 数 -- 单次用户 load more 可串联多个 source batches,以换取一次手势的可见树状进展 - ---- - -### Task 4: Platforms — Keep iOS / Android as pure consumers of screen + targeted context - -**Files:** -- Modify: `apps/ios-app/App/Stores/FireTopicDetailStore.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/data/repository/TopicRepository.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt` -- Test: `apps/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift` - -- [ ] **Step 1: 固定主读取与刷新入口** - -双端主详情页必须只通过以下路径读取与刷新: - -- initial load -> detail source snapshot -- mutation refresh -> source snapshot refresh -- MessageBus refresh -> source snapshot refresh -- load more -> source cursor batch append -- render -> tree presentation rebuild -- one gesture may chain multiple source batches before completing - -平台最终状态应明确拆成: - -- source snapshot state -- tree presentation state -- load-more state -- anchor / scroll state -- sidecar state - -- [ ] **Step 2: 禁止主详情页回退到 host-managed 窗口** - -不得引入或恢复: - -- `getPostsByNumber(...)` 风格的前后窗口分页 -- 用 `TopicDetail.post_stream.stream` 在 host 侧自己切片当主分页 -- 用 `GET /t/{id}/{postNumber}.json` 做主深链分页 -- 用 tree row / root row 位置反向决定 source batch 边界 -- 把“单批未出现新 root”错误地当成“已经到底”或“这次加载无效” - -- [ ] **Step 3: targeted hydration 只服务上下文** - -以下 API 只允许用于局部上下文: - -- `fetchTopicPosts(post_ids)` -> anchor hydration / targeted merge -- `fetchPostReplyIds` + batched `fetchTopicPosts` -> reply context tree -- `fetchPostReplyHistory` -> parent chain context - -不得把这些 targeted API 重新升格成主详情页读模型。`fetchPostReplies` 若仅剩 fallback 价值,应一并删除。 - -- [ ] **Step 4: 删除平台旧状态字段与旧依赖面** - -本步骤要求明确替换或删除: - -- iOS `topicResponseRowsByTopic` -- iOS `topicResponseCursorsByTopic` -- iOS 对 old `TopicScreen.response` 的 source-state 依赖 -- Android `responseRows` 承担 source-state 的职责 -- Android `cursor` 中 old root/branch 语义 -- 双端任何用 root row / response row 反推 source batch 的逻辑 - -- [ ] **Step 5: 保持滚动期 MessageBus 刷新延后语义** - -继续维持当前正确策略: - -- 滚动期不立即 whole-screen apply -- 停止滚动后只应用最新一份 deferred screen -- identical refreshed screen / rows 直接丢弃 - -这条规则在 iOS / Android 两端都必须保留,避免实时刷新打断滚动路径。 - ---- - -### Task 5: Sidecars — Formalize AI summary, Presence, timings, and reply context as orthogonal capabilities - -**Files:** -- Modify: `crates/fire-core/src/core/interactions.rs` -- Modify: `crates/fire-core/src/core/presence.rs` -- Modify: `apps/ios-app/App/Stores/FireTopicDetailStore.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt` -- Modify: `references/fluxdo/lib/services/discourse/_presence.dart` (reference-only audit notes if needed in docs) - -- [ ] **Step 1: AI summary 保持非阻塞 sidecar** - -规范双端行为: - -- 仅在 header 暴露 `summarizable` / `hasCachedSummary` / `hasSummary` 时异步加载 -- summary 失败不打断主详情页 -- summary 重试只作用于 summary 卡片,不触发 whole-screen reload - -- [ ] **Step 2: Presence 保持 bootstrap + heartbeat 模型** - -规范 Rust / host 边界: - -- bootstrap presence 从 Rust 发起 `GET /presence/get` -- update presence 从 Rust 发起 `/presence/update` -- topic detail 页面只消费 presence state,不自己组织 channel/body - -- [ ] **Step 3: timings 维持后台静默写语义** - -补充并验证以下契约: - -- host 只上报可见 post timings -- Rust 负责 form body 组织和 `429` cooldown -- `429` 视为软失败,不影响主详情页会话状态 - -- [ ] **Step 4: reply context 收口到 reply-id tree 权威路径** - -双端统一为: - -```text -fetch_post_reply_ids - -> batched fetch_topic_posts - -> fetch_post_reply_history -``` - -不要让某一端回退到“先 `/replies.json` 再猜结构”的旧路径。若 `fetch_post_replies` 在当前产品面已无独立职责,应直接删除该调用链和 FFI 暴露。 - ---- - -### Task 6: Phase 2 follow-up — Add typed filtered topic-detail contract on top of the same raw source pipeline - -**Files:** -- Future Modify: `crates/fire-models/src/topic_detail.rs` -- Future Modify: `crates/fire-core/src/core/topics.rs` -- Future Modify: `crates/fire-uniffi-topics/src/records.rs` -- Future Modify: iOS / Android topic detail stores once product confirms filtered surface requirements - -- [ ] **Step 1: 先冻结当前范围** - -本期不把 FluxDO 的以下页面侧过滤逻辑直接搬到原生主详情页: - -- `filter=summary` -- `username_filters=...` -- `filter_top_level_replies=true` + host 自补主贴 - -- [ ] **Step 2: 若未来需要筛选详情页,新增 typed Rust filter** - -推荐新增: - -```text -TopicScreenFilter { - All, - Summary, - AuthorOnly { username }, - TopLevelOnly -} -``` - -由 Rust 统一决定底层调用 `/t/{id}.json` 的哪些 query params、如何生成 tree presentation、是否需要单独补主贴、以及如何在不破坏 raw source pipeline 的前提下投影出筛选后的视图。 - -- [ ] **Step 3: 平台不得直接消费 stringly raw filter contract** - -未来即使要支持筛选,也只能消费 typed screen/filter contract,不能恢复: - -- host 侧 string `filter` -- host 侧 string `username_filters` -- host 侧直接用 raw `TopicDetail.post_stream` 维护过滤窗口 - ---- - -### Task 7: Verification Matrix - -- [ ] `docs/knowledge/api-overview.md` 不再把 topic detail 简化成旧 raw endpoint 流程,且相对链接路径正确。 -- [ ] `docs/knowledge/api/03-topics.md` 明确 raw source contract 与 tree presentation contract 的边界。 -- [ ] iOS 主详情页 initial load / refresh / load more 只走 raw source snapshot + source cursor batch append,再树状化渲染。 -- [ ] Android 主详情页 initial load / refresh / load more 只走 raw source snapshot + source cursor batch append,再树状化渲染。 -- [ ] deep link 到嵌套回复时,首包会正确包含目标 anchor,但后续 load more 仍回到原始 stream 批量拉取,而不是切成 root-driven 分页。 -- [ ] source batch append 多页推进按 `post_stream.stream` 原始顺序工作,不依赖 top-level root ids。 -- [ ] old source cursor 在 session epoch 改变后失效,不会污染新详情会话。 -- [ ] 单次用户 load more 若首批仅补充现有 root 的子回复、未带来新的 root-level 可见进展,会自动继续下一批,而不是要求用户再次上拉。 -- [ ] 单次用户 load more 在 source exhaust、出现新的 root-level 可见进展、达到自动批量预算或错误时结束。 -- [ ] MessageBus 刷新在滚动中延后,停止滚动后只应用最新 screen,重复 payload 被丢弃。 -- [ ] Presence bootstrap 与 update 不参与主详情页首屏载荷,且当前用户会被从可见 typing/presence 用户中过滤。 -- [ ] `/topics/timings` 的 `429` 被视为软失败和 cooldown,不会触发登出或全页错误。 -- [ ] AI summary 缺失或失败不会阻断主详情页,只影响 summary 自身 UI。 -- [ ] reply context 统一走 `reply-ids + posts + reply-history`,不再保留 `/replies.json` fallback。 -- [ ] tree presentation 在 source batch append 后仍能稳定保持 Fire 的嵌套 thread 特色,不退化成纯平铺列表。 -- [ ] 平台层没有新的 `getPostsByNumber(...)` 风格主详情页分页逻辑进入代码库。 -- [ ] Rust 主路径没有新的 root-driven source pagination 逻辑进入代码库。 -- [ ] processed feed FFI、平台 convenience wrappers、以及仅为兼容存在的 topic-detail dead surface 已删除,不再以 retained / inactive / migration 名义存在。 -- [ ] 在 typed filtered topic-detail contract 落地前,平台不会新增任何 stringly filter fallback surface。 diff --git a/docs/superpowers/plans/2026-06-07-topic-detail-main-thread-and-ui-split-plan.md b/docs/superpowers/plans/2026-06-07-topic-detail-main-thread-and-ui-split-plan.md deleted file mode 100644 index f95a2a12..00000000 --- a/docs/superpowers/plans/2026-06-07-topic-detail-main-thread-and-ui-split-plan.md +++ /dev/null @@ -1,527 +0,0 @@ -# Topic Detail Main-Thread and UI Split Optimization Plan - -> 日期: 2026-06-07 -> 状态: Implemented -> 范围: iOS topic detail 主线程卡顿、poll option 同步解析、topic tree FFI 载荷瘦身、Android 冷启动 UI 线程初始化、详情页状态拆分 - -## Goal - -解决 review 指出的四类性能风险,并把详情页从“单个大状态刷新整页”推进到“按职责拆分状态域、各自刷新”的结构: - -- iOS 不在 `@MainActor` 上比较完整 `TopicDetailState` -- iOS cell / layout key 路径不再同步 HTML 解析 poll option 标题 -- 双端 topic detail 不再把完整 post 在 FFI 边界来回传递多次 -- Android 首次 `FireSessionStore` / `FireAppCore` 初始化不阻塞 UI 线程 -- iOS 详情页拆成 feed、chrome、composer、sidecar、interaction 几个刷新域,避免输入框、toolbar、sidecar 状态触发整页 feed diff - -核心原则:不是简单把所有逻辑塞进后台线程,而是先减少主路径要做的工作,再把仍然昂贵、纯计算的派生步骤放到后台。主线程只保留状态发布、UIKit / Texture apply、导航和用户交互收口。 - -## Implementation Status - -2026-06-07 已落地 review 指出的四个高风险点、baseline instrumentation 和 iOS 状态域拆分: - -- iOS `FireTopicDetailStore` 不再在 `@MainActor` 上用合成 `Equatable` 比较完整 `TopicDetailState`,改为维护 feed/chrome content tokens,主线程只比较轻量 token 后再决定是否发布详情状态。 -- Rust / UniFFI 新增 `TopicDetailPage` / `TopicDetailPageState` combined result;topic detail initial / refresh 通过一次 FFI 返回 source snapshot + tree presentation。 -- `TopicTreePresentationState` / `TopicTreeRowState` 已瘦身为 post id / post number / depth / parent / root 等元数据;完整 `TopicPostState` 只保留在 `sourceSnapshot.body.post` 与 `sourceSnapshot.loadedPosts`。 -- poll option 新增 Rust 侧 `plain_text` / UniFFI `plainText`;iOS 和 Android poll row 直接消费纯文本标题,不再在 cell configure / layout key 路径同步解析 HTML。 -- Android `FireSessionStoreRepository.get(context)` 改为 suspend IO 初始化路径,启动、列表、详情、搜索、书签、通知、私信、登录、composer 等 UI call site 均在 coroutine 中获取 session store。 -- iOS `FireTopicDetailPageState` 已拆成 `FireTopicDetailFeedState`、`FireTopicDetailChromeState`、`FireTopicDetailComposerState`、`FireTopicDetailSidecarState`、`FireTopicDetailInteractionState` 和 route state。 -- Store revision 已拆成 collection/chrome/sidecar/interaction;AI summary 只 bump sidecar,mutation/reply-context loading 只 bump interaction,topic bookmark/notification 这类 chrome token 变化不再 bump feed collection revision。 -- `FireTopicDetailSnapshotInput` 已独立出来,feed item construction 通过 detached task 后台构建,MainActor 只丢弃过期 generation 并执行 Texture / collection apply。 -- Phase 0 instrumentation 已加入 Rust source/tree timing,iOS FFI/render/main-apply/snapshot timing,Android startup timing。大帖、poll topic 和冷启动的具体数值采集属于运行期观测动作,代码路径已提供字段。 - -## Direct Answers - -### 主线程上的内容是否可以迁移到异步线程 - -可以,但要分层迁移: - -- 必须留在主线程 / MainActor: - - `@Published` 状态写入 - - UIKit / Texture node apply - - navigation item、toolbar、quick reply bar 更新 - - visible cell in-place 更新 - - 生命周期和手势事件收口 -- 应迁移到后台或 Rust: - - `TopicDetailState` 变更判断与 signature 生成 - - tree presentation 构建与 row metadata 生成 - - rich text render cache / attributed string 预计算 - - poll option HTML -> plain text - - snapshot item list 的纯数据构建 - - Android `FireSessionStore` / `FireAppCore` 首次构造 - -注意:单纯把 `topicDetails[topicId] != detail` 放到 `Task.detached` 不是最优解。它仍然需要复制完整 FFI 大对象,也会制造取消和乱序 apply 问题。更优方案是让 Rust 或后台构建阶段产出轻量 revision / signature,MainActor 只比较 token。 - -### UI 展示部分是否可以拆分 - -可以,而且当前代码已经有可利用的边界: - -- `FireTopicDetailFeedController` -- `FireTopicDetailPaginationCoordinator` -- `FireTopicDetailVisibilityCoordinator` -- `FireTopicDetailToolbarCoordinator` -- `FireTopicQuickReplyBarNode` -- `FireTopicDetailModalRouter` - -当前问题不是完全没有拆组件,而是状态刷新仍然集中在 `FireTopicDetailStore` 和 `FireTopicDetailViewController.buildAndApplySnapshot()`。下一步应拆状态域,而不是重写 UI 层: - -- feed state: 原帖、回复、layout、render cache、pagination -- chrome state: toolbar、bookmark、notification、topic vote、share URL -- composer state: draft、target、validation、submitting -- sidecar state: AI summary、presence、timings -- interaction state: mutating post IDs、expanded text IDs、reply thread expansion - -## Pre-Fix Evidence - -### iOS deep compare on MainActor - -`apps/ios-app/App/Stores/FireTopicDetailStore.swift` 是 `@MainActor` store。当前 `setTopicDetail` 用完整对象比较: - -```swift -let changed = topicDetails[topicId] != detail -``` - -`TopicDetailState` 包含 `postStream.posts`,每个 `TopicPostState` 又包含 `cooked` 和 `renderDocument`。大帖刷新、MessageBus refresh、返回相同数据或差异靠后时,这个比较会在主线程走深比较。 - -### iOS render cache 已部分后台化,但 poll title 修复前仍在 cell/layout 路径 - -`FireTopicDetailStore.scheduleTopicRenderCacheUpdate` / `buildTopicDetailRenderUpdate` 已用 `Task.detached` 构建 `FireTopicPresentation.detailRenderCache(...)`,这是正确方向。 - -修复前 `FirePostPollRenderModel.models(from:)` 会在 poll option cache miss 时从 option HTML 同步派生标题,调用点覆盖 cell configure、layout precompute 和 layout key 构建。修复后 poll option 标题由 Rust 在共享 rich-text plain-text 路径产出,iOS / Android 都只消费 `plainText`,平台侧不再保留正文或 poll 标题的 HTML 解析 fallback。 - -### FFI tree payload 当前重复带完整 post - -修复前 source snapshot: - -```rust -TopicDetailSourceSnapshotState { - body: TopicBodyState, - loaded_posts: Vec, - ... -} -``` - -修复前 tree query 又把完整 post 传回 Rust: - -```rust -TopicTreePresentationQueryState { - body_post: TopicPostState, - raw_stream_ids: Vec, - loaded_posts: Vec, - focused_post_number: Option, -} -``` - -修复前 tree result 再把完整 post 带回平台: - -```rust -TopicTreeRowState { - post: TopicPostState, - ... -} -``` - -因为 `TopicPostState` 包含 `cooked` 和 `render_document`,这会造成大帖 FFI 重复序列化和重复传输。 - -### Android first store creation is synchronous at the UI call site - -`PreheatGateFragment.awaitPreloadedData()` 在启动页面先执行: - -```kotlin -val store = FireSessionStoreRepository.get(requireContext()) -``` - -随后才进入 coroutine。`FireSessionStoreRepository.get()` 会同步构造 `FireSessionStore`,而 `FireSessionStore.init` 里创建 `FireAppCore`、注册 observer、解析 session path。这些 IO / Rust 初始化工作应从 UI 线程移走。 - -### iOS page state already has coarse revision but not enough state-domain isolation - -`FireTopicDetailViewController` 已订阅: - -- `topicCollectionRevisions` -> `buildAndApplySnapshot()` -- `topicChromeRevisions` -> `buildAndApplyChromeState()` - -但 controller-local 事件仍有过度刷新: - -- quick reply draft 每次变化会调用 `buildAndApplySnapshot()` -- composer target / validation / submitting 和 feed snapshot 混在 `FireTopicDetailPageState` -- `FireTopicDetailSnapshotAssembler` 标注 `@MainActor`,纯 snapshot item list 构建无法后台化 - -## Non-Goals - -- 不重引入 SwiftUI post row fallback。 -- 不把 topic detail 主阅读面改成 host-managed window / `getPostsByNumber(...)`。 -- 不增加 parallel rendering path。 -- 不用 tree row / root row 反向决定网络分页边界。 -- 不把 AI summary、presence、timings 塞进主详情载荷。 - -## Target Architecture - -### Rust / UniFFI - -新增或调整为一个 combined + slim contract: - -```text -fetch_topic_detail_page(query) - -> TopicDetailPageState { - source_snapshot, - tree_presentation - } - -load_more_topic_posts(cursor) - -> TopicLoadMoreOutcomeState { - source_snapshot, - tree_presentation, - chained_batches, - chained_posts, - stop_reason - } - -TopicTreePresentationState { - original_post_id, - reply_rows: Vec, - total_loaded_post_count, - visible_root_post_numbers, - gained_new_root_progress -} - -TopicTreeRowMetaState { - post_id, - post_number, - root_post_number, - parent_post_number, - depth, - preorder_index, - has_children, - descendant_count, - sibling_index, - is_last_sibling -} -``` - -Full post payload only appears in `source_snapshot.body.post` and `source_snapshot.loaded_posts`. Tree presentation references posts by id / post number only. - -### iOS Store / Controller - -Split state and refresh domains: - -```text -FireTopicDetailStore - source state: - sourceSnapshots - treePresentations - postLookups - detailTokens - feed state: - renderCaches - renderStates - windowStates - collectionRevisions - chrome state: - toolbar / bookmark / notification revisions - sidecar state: - aiSummary - presence - timings - interaction state: - mutatingPostIDs - loadingReplyContextIDs -``` - -Controller should apply: - -- feed updates only when feed token changes -- chrome updates only when toolbar token changes -- quick reply bar updates only when composer token changes -- visible post node updates only when in-place interaction token changes - -### Android Startup - -Change first initialization to a suspend IO path: - -```kotlin -suspend fun FireSessionStoreRepository.get(context): FireSessionStore = - withContext(Dispatchers.IO) { getOrCreateBlocking(context.applicationContext) } -``` - -`PreheatGateFragment` should enter `lifecycleScope.launch` before calling `get(...)`. Other UI call sites should also use the suspend path or receive an already initialized store. - -## Implementation Plan - -### Phase 0: Baseline instrumentation - -Files: - -- Modify: `apps/ios-app/App/Stores/FireTopicDetailStore.swift` -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/startup/PreheatGateFragment.kt` -- Optional Modify: `crates/fire-core/src/core/topics.rs` - -Steps: - -- [x] Add lightweight signposts / log fields for topic detail apply: - - source fetch duration - - tree presentation duration - - render cache duration - - MainActor apply duration - - collection snapshot item count - - loaded post count and cooked byte count -- [x] Add startup timing around Android `FireSessionStoreRepository.get(...)`. -- [x] Capture fields are instrumented for runtime QA before/after sampling on: - - large topic initial load - - MessageBus refresh with identical payload - - poll-bearing topic scroll - - Android cold start / deep link first entry - -Acceptance: - -- Logs identify whether time is spent in fetch, FFI conversion, render cache, snapshot build, or UI apply. -- No behavior changes yet. - -### Phase 1: Fix P1 iOS deep compare - -Files: - -- Modify: `apps/ios-app/App/Stores/FireTopicDetailStore.swift` -- Modify: `apps/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift` -- Test: `apps/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift` - -Steps: - -- [x] Introduce `FireTopicDetailFeedContentToken` and `FireTopicDetailChromeContentToken`. -- [x] Token fields should cover visible detail semantics without embedding full cooked/render tree: - - topic id - - message bus last id - - header counters and flags - - bookmark / notification fields - - `postStream.stream` checksum - - per post id, post number, updated_at, like count, reaction signature, poll signature, cooked length + stable checksum - - details permission / participant signature -- [x] Keep feed/chrome content tokens by topic ID. -- [x] Replace `topicDetails[topicId] != detail` with token comparison. -- [x] Build token before `MainActor` apply where possible. If token must be computed in Swift, compute in the existing detached render-cache task or a dedicated detached task and apply only latest generation. -- [x] Keep full `TopicDetailState` assignment only when token changed. -- [x] Preserve `bumpRevision` behavior exactly. -- [x] Add tests: - - identical large detail does not publish / bump collection revision - - changed late post does publish - - changed bookmark / notification chrome field updates correct revision - - token collision-sensitive fields are included - -Acceptance: - -- No full `TopicDetailState` equality check remains on `@MainActor`. -- Identical refresh does O(1) main-thread comparison. -- Store tests cover no-op and changed refresh. - -### Phase 2: Collapse and slim topic tree FFI - -Files: - -- Modify: `crates/fire-models/src/topic_detail.rs` -- Modify: `crates/fire-core/src/core/topics.rs` -- Modify: `crates/fire-uniffi-topics/src/lib.rs` -- Modify: `crates/fire-uniffi-topics/src/records.rs` -- Modify: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- Modify: `apps/ios-app/App/Stores/FireTopicDetailStore.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/data/repository/TopicRepository.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt` -- Test: `crates/fire-core/tests/network.rs` -- Test: `apps/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift` -- Test: `apps/android-app/src/test/.../TopicDetailPostRowsTest.kt` or equivalent - -Steps: - -- [x] Add `TopicTreeRowMeta` / `TopicTreeRowMetaState` without full `TopicPost`. -- [x] Add `TopicDetailPage` / `TopicDetailPageState` combined result: - - `source_snapshot` - - `tree_presentation` -- [x] Add Rust core method that builds source snapshot and tree presentation in one call from the same internal source session. -- [x] Keep `load_more_topic_posts` combined, but make returned `tree_presentation.reply_rows` slim. -- [x] Remove platform path that sends `bodyPost` and `loadedPosts` back to Rust just to build the tree. -- [x] iOS rebuild: - - keep `sourceSnapshots[topicId]` - - keep `treePresentations[topicId]` - - derive `postLookup` from `sourceSnapshot.body.post + sourceSnapshot.loadedPosts` - - synthesize `TopicDetailState` from source + slim tree metadata only when compatibility with existing UI code still needs it -- [x] Android rebuild: - - `PostRow` uses row metadata + post lookup - - `_detail.postStream.posts` comes from source posts only - - mutation patch updates source posts and post lookup, not duplicated tree row post copies -- [x] Delete or deprecate old `buildTopicTreePresentation(query: TopicTreePresentationQueryState)` platform wrapper after all call sites move. - -Acceptance: - -- Main detail flow crosses FFI once for source + tree on initial refresh. -- Tree row FFI no longer carries `TopicPostState`. -- `TopicPostState.renderDocument` is serialized once per loaded post per response, not again through tree rows. -- Both platforms render the same row order/depth as before. - -### Phase 3: Move poll option title parsing out of iOS cell/layout path - -Files: - -- Modify: `crates/fire-models/src/topic_detail.rs` -- Modify: `crates/fire-uniffi-topics/src/records.rs` -- Modify: `apps/ios-app/App/ListKit/TopicDetail/FirePostPollRenderer.swift` -- Modify: `apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt` if Android consumes option title directly -- Test: `cargo test -p fire-models -p fire-uniffi-topics` -- Test: iOS unit test for poll model title - -Steps: - -- [x] Add `plain_text` or `title` to `PollOption` / `PollOptionState`. -- [x] Populate it in Rust using the existing shared plain-text rich text path. -- [x] Update iOS `FirePostPollRenderModel.models(from:)` to use `option.plainText` and fallback to `option.id`. -- [x] Remove `FirePostPollPlainTextCache` and `optionTitle(fromHTML:)` from the cell path. -- [x] Ensure `FireTopicDetailFeedController.makeLayoutKey` uses already materialized poll signatures only. -- [x] Audit iOS topic-detail poll title call sites and confirm none are reachable from cell configure or layout key cache miss. - -Acceptance: - -- No synchronous HTML parsing can be triggered by poll model construction. -- Poll-bearing rows can configure and compute layout keys without synchronous HTML parsing. - -### Phase 4: Move Android core initialization off UI thread - -Files: - -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStoreRepository.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/startup/PreheatGateFragment.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/MainActivity.kt` -- Modify: other `FireSessionStoreRepository.get(...)` UI call sites found by `rg` -- Test: Android unit tests if repository behavior is testable - -Steps: - -- [x] Replace sync public `get(context)` with a suspend `get(context)` or add a clearly named `getOrCreate(context)` suspend method. -- [x] Keep a private blocking `getOrCreateBlocking(applicationContext)` behind `withContext(Dispatchers.IO)`. -- [x] Preserve singleton locking and Cloudflare challenge handler registration. -- [x] Update `PreheatGateFragment.awaitPreloadedData()`: - - enter `lifecycleScope.launch` first - - call repository from IO - - then call `prepareStartupSession`, `awaitPreloadedData`, and login probe -- [x] Update other UI call sites so none construct `FireSessionStore` before entering a coroutine / IO context. -- [x] Do not use `runBlocking` on UI thread. - -Acceptance: - -- First `FireAppCore` construction cannot happen on the Android main thread. -- Cold start / deep link first entry keeps the UI responsive while preheat runs. - -### Phase 5: Split iOS topic detail state refresh domains - -Files: - -- Modify: `apps/ios-app/App/TopicDetail/State/FireTopicDetailPageState.swift` -- Modify: `apps/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift` -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift` -- Modify: `apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift` -- Modify: `apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedUpdatePipeline.swift` -- Modify: `apps/ios-app/App/Stores/FireTopicDetailStore.swift` -- Test: `apps/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift` - -Steps: - -- [x] Split `FireTopicDetailPageState` into: - - `FireTopicDetailFeedState` - - `FireTopicDetailChromeState` - - `FireTopicDetailComposerState` - - `FireTopicDetailSidecarState` - - `FireTopicDetailInteractionState` -- [x] Split invalidation tokens: - - feed token: post/tree/render/layout/pagination only - - chrome token: title/share/bookmark/notification/topic vote only - - composer token: draft/target/validation/submitting only - - sidecar token: AI summary/presence/timing display only - - visible-node token: mutating/reaction/loading reply context/expanded text only -- [x] Change quick reply draft updates to apply only composer state: - - no feed snapshot rebuild on every keystroke - - no collection diff on validation-only changes -- [x] Change toolbar-only changes to call only `toolbarCoordinator.apply(...)`. -- [x] Change AI summary reload failure/loading to update only the summary item if present, not rebuild unrelated post items. -- [x] Extract a pure `FireTopicDetailSnapshotInput: Sendable` for feed item construction. -- [x] Move pure feed item list construction off `@MainActor` when inputs are ready and attach action callbacks only at apply time. -- [x] Keep Texture / collection update application on MainActor. -- [x] Add tests asserting: - - composer draft token change does not change feed invalidation token - - chrome token change does not change feed items - - expanded text affects only the relevant post item content token - - mutation state can use visible in-place update path - -Acceptance: - -- Typing in quick reply does not call `feedUpdatePipeline.apply(...)`. -- Toolbar changes do not diff post rows. -- Feed snapshot build becomes pure and eligible for background execution. -- UI behavior remains unchanged. - -### Phase 6: Verification and regression gates - -Rust: - -```bash -cargo fmt --all --check -cargo test -p fire-models -p fire-core -p fire-uniffi-topics --all-targets -``` - -iOS: - -```bash -xcodegen generate --spec apps/ios-app/project.yml -FIRE_SKIP_UNIFFI_BINDGEN=1 xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme 'Fire Local' -destination 'platform=iOS Simulator,id=' test -``` - -Android: - -```bash -export JAVA_HOME=$(/usr/libexec/java_home -v 17) -export ANDROID_HOME=/Users/zhangfan/Library/Android/sdk -export ANDROID_SDK_ROOT=/Users/zhangfan/Library/Android/sdk -cd apps/android-app -./gradlew testDebugUnitTest assembleDebug -``` - -Runtime checks: - -- iOS large topic initial load: no visible main-thread freeze during identical refresh. -- iOS poll-bearing topic scroll: no synchronous HTML parsing from cell/layout stack. -- iOS quick reply typing: no feed collection diff. -- iOS MessageBus identical refresh during/after scroll: no full detail deep compare. -- Android cold start: first `FireSessionStore` construction happens on IO dispatcher. - -Validated on this branch: - -- `cargo fmt --all --check` -- `cargo test -p fire-models -p fire-core -p fire-uniffi-topics --all-targets` -- `xcodegen generate --spec apps/ios-app/project.yml` -- `FIRE_SKIP_UNIFFI_BINDGEN=1 xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme 'Fire Local' -destination 'platform=iOS Simulator,id=5318776E-FF02-4468-8549-DFF919ED16E0' test` -- `cd apps/android-app && ./gradlew testDebugUnitTest assembleDebug` - -Note: the iPhone 16 / iOS 18.0 simulator path failed because CoreSimulator could not clone the device and left it stuck in creation state; the same iOS test lane passed on an existing iPhone 15 Pro / iOS 17.5 simulator. - -## Suggested Commit Split - -1. `perf(topics): collapse topic detail page ffi payloads` -2. `perf(ios): reduce topic detail main thread refresh work` -3. `perf(android): initialize fire session store off main thread` -4. `docs: document topic detail performance boundaries` - -## Risk Notes - -- Token comparison must include every visible field that can affect UI. Missing fields would create stale UI. -- Slim tree rows require careful post lookup rebuild on both platforms. Mutation updates must patch source posts, not stale row copies. -- Moving snapshot build off-main requires separating pure data from UIKit objects and callbacks. -- Android repository API changes may affect multiple call sites; update all `FireSessionStoreRepository.get(...)` consumers in one commit. -- UniFFI model changes require regenerating bindings and then regenerating the iOS Xcode project if source lists change. - -## Documentation Follow-Up - -After implementation, update: - -- `docs/knowledge/api/03-topics.md`: already describes the raw source + tree presentation boundary; no HTTP protocol change was needed. -- `docs/architecture/2026-06-05-rich-text-and-state-observer-design.md`: updated with poll option plain text and topic detail render-boundary notes. -- `docs/superpowers/plans/2026-06-06-topic-detail-api-consolidation.md`: updated so the source/presentation contract reflects combined page fetch and slim tree rows. - -Documentation should be synchronized after code lands, not before, because code remains the source of truth. diff --git a/docs/superpowers/plans/2026-06-08-p1-foundation.md b/docs/superpowers/plans/2026-06-08-p1-foundation.md deleted file mode 100644 index 6a618988..00000000 --- a/docs/superpowers/plans/2026-06-08-p1-foundation.md +++ /dev/null @@ -1,972 +0,0 @@ -# P1 基础夯实 Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** 消除视觉不一致、补齐 Accessibility、统一架构模式、Android 核心页面补全 - -**Architecture:** iOS 侧已聚焦 FireTheme Token 统一、通用分页 Store 提取、FireAppViewModel 拆分;Android 侧已补全草稿列表、FCM 本地通知接入、阅读历史、通知历史和话题阅读计时。两端共享上下文菜单、空状态组件、Shimmer 动画等模式。 - -**Tech Stack:** SwiftUI / UIKit (iOS), Kotlin + ViewBinding + Paging 3 (Android), Rust UniFFI (shared core) - ---- - -## File Structure - -### iOS Changes - -| Action | Path | Responsibility | -|--------|------|----------------| -| Modify | `App/Core/FireTheme.swift` | 新增 corner radius / surface token | -| Modify | `App/Core/FireComponents.swift` | 统一空状态、新增 Shimmer | -| Create | `App/Core/FireShimmerModifier.swift` | Shimmer 动画修饰器 | -| Create | `App/Core/FireContextMenus.swift` | 可复用上下文菜单构建器 | -| Create | `App/Stores/FirePaginatedStore.swift` | 通用分页 Store 基类 | -| Modify | `App/Stores/FireHomeFeedStore.swift` | 适配新 Token | -| Modify | `App/Stores/FireNotificationStore.swift` | 提取通用模式 | -| Modify | `App/Stores/FireSearchStore.swift` | 继承 FirePaginatedStore | -| Modify | `App/ViewModels/FireAppViewModel.swift` | 拆分服务层和门面扩展 | -| Create | `App/ViewModels/FireAppViewModelSupport.swift` | 支撑类型、错误、状态观察协调器、搜索 scope | -| Create | `App/ViewModels/FireAppViewModel+Diagnostics.swift` | 诊断、日志、网络 trace、APM facade | -| Create | `App/ViewModels/FireAppViewModel+Profile.swift` | 个人资料、关注、邀请、徽章、LDC/CDK facade | -| Create | `App/ViewModels/FireAppViewModel+RecoveryURLs.swift` | Cloudflare 恢复 URL 构建 | -| Create | `App/Services/FireTopicInteractionService.swift` | 话题交互服务 | -| Create | `App/Services/FireNotificationService.swift` | 通知服务 | -| Create | `App/Services/FireSearchService.swift` | 搜索服务 | -| Modify | `App/Views/*.swift` | Token 替换、Accessibility 标注、上下文菜单 | - -### Android Changes - -| Action | Path | Responsibility | -|--------|------|----------------| -| Create | `ui/drafts/DraftsFragment.kt` | 草稿列表页 | -| Create | `ui/drafts/DraftsViewModel.kt` | 草稿 ViewModel | -| Create | `ui/drafts/DraftsAdapter.kt` | 草稿列表适配器 | -| Create | `ui/readhistory/ReadHistoryFragment.kt` | 阅读历史页 | -| Create | `ui/readhistory/ReadHistoryViewModel.kt` | 阅读历史 ViewModel | -| Create | `ui/notifications/NotificationHistoryFragment.kt` | 通知历史全屏页 | -| Create | `push/FireFirebaseMessagingService.kt` | FCM 推送服务 | -| Create | `core/theme/FireShimmerLayout.kt` | Shimmer 动画布局 | -| Modify | `build.gradle.kts` | 添加 Firebase 依赖 | -| Modify | `res/navigation/fire_nav_graph.xml` | 新增导航目标 | - ---- - -## Task 1: iOS FireTheme Token 统一 - -**Files:** -- Modify: `apps/ios-app/App/Core/FireTheme.swift` -- Modify: `apps/ios-app/App/Core/FireComponents.swift` -- Modify: `apps/ios-app/App/Views/Composer/FireComposerView.swift` -- Modify: `apps/ios-app/App/Views/Other/FireOnboardingView.swift` -- Modify: `apps/ios-app/App/Views/Search/FireSearchView.swift` - -- [x] **Step 1: 新增 corner radius Token 和 surface Token** - -`FireTheme` now defines: - -```swift -extension FireTheme { - static let cornerRadius: CGFloat = 20 - static let mediumCornerRadius: CGFloat = 14 - static let smallCornerRadius: CGFloat = 10 - static let chipCornerRadius: CGFloat = 100 - static let panelShadowRadius: CGFloat = 16 - static let panelShadowY: CGFloat = 8 -} -``` - -It also exposes semantic `canvas`, `surface`, and `surfaceSecondary` colors for SwiftUI surfaces. - -- [x] **Step 2: 全局搜索并替换硬编码圆角值** - -搜索模式及替换目标: - -| 搜索 | 替换为 | -|------|--------| -| `cornerRadius: 16` (非 FireTheme 引用) | `cornerRadius: FireTheme.cornerRadius` | -| `cornerRadius: 18` | `cornerRadius: FireTheme.cornerRadius` | -| `cornerRadius: 12` | `cornerRadius: FireTheme.mediumCornerRadius` | -| `cornerRadius: 10` | `cornerRadius: FireTheme.smallCornerRadius` | - -涉及文件(需逐一检查确认): -- `App/Core/FireComponents.swift` -- `App/Views/FireComposerView.swift` -- `App/Views/FireOnboardingView.swift` -- `App/Views/FireSearchView.swift` -- `App/Views/FireTopicRow.swift` - -Verified scoped search over `FireTheme.swift`, `FireComponents.swift`, `FireComposerView.swift`, `FireOnboardingView.swift`, `FireSearchView.swift`, and `FireTopicRow.swift` no longer finds the listed hardcoded radius patterns. - -- [x] **Step 3: 替换背景色硬编码** - -| 搜索模式 | 替换为 | -|----------|--------| -| `Color(.systemGroupedBackground)` | `FireTheme.canvasMid` | -| `Color(.secondarySystemBackground)` | `FireTheme.surface` | -| `Color.black.opacity(0.06)` | `FireTheme.divider` | -| `Color.black.opacity(0.` 任何描边 | `FireTheme.divider` | - -`FireComposerView` now uses `FireTheme.canvas` for the page background and `FireTheme.surface` for composer panels. The scoped search no longer finds `Color(.systemGroupedBackground)` or `Color(.secondarySystemBackground)` in the planned files. - -- [x] **Step 4: 构建验证** - -Run: `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -Result: build succeeded. Existing warnings remain from `UITextItemInteraction`, no-op `await`, Swift 6 capture diagnostics, and related pre-existing code. - -- [x] **Step 5: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md \ - apps/ios-app/App/Core/FireTheme.swift \ - apps/ios-app/App/Core/FireComponents.swift \ - apps/ios-app/App/Views/Composer/FireComposerView.swift \ - apps/ios-app/App/Views/Other/FireOnboardingView.swift \ - apps/ios-app/App/Views/Search/FireSearchView.swift -git commit -m "refactor(ios): unify corner radius and background tokens across FireTheme" -``` - ---- - -## Task 2: iOS Feed Kind Selector 统一 - -**Files:** -- Modify: `apps/ios-app/App/Views/FireFilteredTopicListView.swift` -- Reference: `apps/ios-app/App/Core/FireComponents.swift` (contains `FireFeedKindSelector`) - -- [x] **Step 1: 定位 FireFilteredTopicListView 中的简易筛选器** - -读取 `FireFilteredTopicListView.swift`,找到使用 `Capsule().fill()` 的筛选器代码段。 - -- [x] **Step 2: 替换为 FireFeedKindSelector** - -将内联的 Capsule 筛选器替换为 `FireFeedKindSelector`(使用 `matchedGeometryEffect` 的版本),确保与首页视觉完全一致。 - -实际集成参数: -- `selectedKind: TopicListKindState` -- `namespace: Namespace.ID` -- `onSelect: (TopicListKindState) -> Void` - -- [x] **Step 3: 构建验证** - -Verified: -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -- [x] **Step 4: Commit** - -```bash -git add apps/ios-app/App/Views/FireFilteredTopicListView.swift -git commit -m "refactor(ios): unify feed kind selector between home and filtered views" -``` - ---- - -## Task 3: iOS Feed Kind 标题语言统一 - -**Files:** -- Modify: `apps/ios-app/App/Core/SessionState+Helpers.swift`(或 TopicListKindState extension 所在文件) - -- [x] **Step 1: 定位 TopicListKindState.title 定义** - -搜索 `TopicListKindState` 的 `title` computed property。当前返回英文如 "Latest", "New"。 - -- [x] **Step 2: 统一为中文标题** - -```swift -var title: String { - switch self { - case .latest: return "最新" - case .new: return "最新发布" - case .unread: return "未读" - case .unseen: return "未看" - case .hot: return "热门" - case .top: return "精华" - case .privateMessagesInbox: return "收件箱" - case .privateMessagesSent: return "已发送" - } -} -``` - -- [x] **Step 3: 构建验证** - -Verified: -- `cd apps/ios-app && xcodebuild test -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -only-testing:FireTests/FireEntityStateTests` -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -- [x] **Step 4: Commit** - -```bash -git add -u -git commit -m "fix(ios): unify feed kind titles to Chinese" -``` - ---- - -## Task 4: iOS Accessibility 标注 — 话题行和首页 - -**Files:** -- Modify: `apps/ios-app/App/Views/FireTopicRow.swift` -- Modify: `apps/ios-app/App/Views/FireHomeView.swift` - -- [x] **Step 1: FireTopicRow Accessibility** - -为 `FireTopicRow` 添加 accessibility 标注: - -```swift -.accessibilityElement(children: .combine) -.accessibilityLabel("\(topic.title), \(topic.categoryName ?? ""), \(topic.replyCount) 回复, \(topic.views) 浏览") -.accessibilityHint("双击查看话题详情") -``` - -- [x] **Step 2: FireHomeView 按钮标注** - -为图标按钮添加 `accessibilityLabel`: - -```swift -// 搜索按钮 -.accessibilityLabel("搜索") - -// 创建话题按钮 -.accessibilityLabel("创建新话题") -``` - -- [x] **Step 3: Skeleton 视图隐藏** - -所有骨架屏视图添加 `.accessibilityHidden(true)`。 - -- [x] **Step 4: 构建验证** - -Verified: -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -- [x] **Step 5: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md apps/ios-app/App/Core/FireComponents.swift apps/ios-app/App/ListKit/Home/FireHomeCollectionView.swift apps/ios-app/App/Views/Home/FireTopicRow.swift apps/ios-app/App/Views/Home/FireHomeView.swift -git commit -m "a11y(ios): add accessibility labels to topic rows and home buttons" -``` - ---- - -## Task 5: iOS Accessibility 标注 — 编辑器、搜索、通知、其他 - -**Files:** -- Modify: `apps/ios-app/App/Views/Composer/FireComposerView.swift` -- Modify: `apps/ios-app/App/Views/Messages/FireRecipientTokenField.swift` -- Modify: `apps/ios-app/App/Views/Search/FireSearchView.swift` -- Modify: `apps/ios-app/App/Views/Notifications/FireNotificationsView.swift` -- Modify: `apps/ios-app/App/Views/Notifications/FireNotificationHistoryView.swift` -- Modify: `apps/ios-app/App/Views/Bookmarks/FireBookmarksView.swift` -- Modify: `apps/ios-app/App/Views/Other/FireDraftsView.swift` -- Modify: `apps/ios-app/App/Views/Other/FireOnboardingView.swift` -- Modify: `apps/ios-app/App/Views/Profile/FireProfileView.swift` -- Modify: `apps/ios-app/App/Views/Profile/FireProfileActivityRow.swift` -- Modify: `apps/ios-app/App/Views/Profile/FireProfileHeaderComponents.swift` - -- [x] **Step 1: FireComposerView 工具栏按钮标注** - -为编辑器工具栏按钮添加 accessibility 标注: - -```swift -// 上传图片按钮 -.accessibilityLabel("上传图片") -// 预览按钮 -.accessibilityLabel("切换预览") -// 发送按钮 -.accessibilityLabel("发送") -// 草稿保存状态 -.accessibilityLabel("草稿已自动保存") -``` - -- [x] **Step 2: FireSearchView 标注** - -```swift -// 搜索结果行 -.accessibilityElement(children: .combine) -.accessibilityLabel("搜索结果: \(result.title)") -// 筛选器按钮 -.accessibilityLabel("筛选: \(scope.title)") -``` - -- [x] **Step 3: FireNotificationsView 标注** - -```swift -// 通知行 -.accessibilityElement(children: .combine) -.accessibilityLabel("\(notification.description), \(timeAgo)") -// 标记已读按钮 -.accessibilityLabel("标记为已读") -``` - -- [x] **Step 4: 其余视图批量标注** - -对 `FireBookmarksView`, `FireDraftsView`, `FireOnboardingView`, `FireProfileView` 的交互元素添加 `.accessibilityLabel()`。 - -- [x] **Step 5: 构建验证** - -Verified: -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -- [x] **Step 6: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md apps/ios-app/App/Views/Composer/FireComposerView.swift apps/ios-app/App/Views/Messages/FireRecipientTokenField.swift apps/ios-app/App/Views/Search/FireSearchView.swift apps/ios-app/App/Views/Notifications/FireNotificationsView.swift apps/ios-app/App/Views/Notifications/FireNotificationHistoryView.swift apps/ios-app/App/Views/Bookmarks/FireBookmarksView.swift apps/ios-app/App/Views/Other/FireDraftsView.swift apps/ios-app/App/Views/Other/FireOnboardingView.swift apps/ios-app/App/Views/Profile/FireProfileView.swift apps/ios-app/App/Views/Profile/FireProfileActivityRow.swift apps/ios-app/App/Views/Profile/FireProfileHeaderComponents.swift -git commit -m "a11y(ios): label composer search notifications and profile views" -``` - ---- - -## Task 6: iOS 暗黑模式修复 - -**Files:** -- Modify: `apps/ios-app/App/Views/Composer/FireComposerView.swift` -- Modify: `apps/ios-app/App/Core/FireTheme.swift` -- Modify: `apps/ios-app/App/Core/FireComponents.swift` - -- [x] **Step 1: 修复 Composer 中的硬编码黑色** - -搜索 `Color.black.opacity(` 并替换: - -```swift -// 替换前: -Color.black.opacity(0.06) - -// 替换后: -FireTheme.divider -``` - -```swift -// 替换前(描边): -.stroke(Color.black.opacity(0.08), lineWidth: 1) - -// 替换后: -.stroke(FireTheme.divider, lineWidth: 1) -``` - -- [x] **Step 2: 全项目扫描其他 Color.black/Color.white 硬编码** - -Run: `rg "Color\.black\.opacity|Color\.white\.opacity" apps/ios-app/App/Views/ apps/ios-app/App/Core/` -逐一评估并替换为 FireTheme 语义色。 - -Result: -- Composer editor border now uses `FireTheme.divider`. -- `FireCard` shadows now use adaptive `FireTheme.panelShadow` / `FireTheme.contrastPanelShadow`. -- Remaining scan hits are profile avatar white rings in `FireProfileView` and `FirePublicProfileView`; these are intentional image-overlay highlights, not semantic dividers/backgrounds. - -- [x] **Step 3: 暗黑模式验证** - -Verified: -- `rg "Color\.black\.opacity|Color\.white\.opacity" apps/ios-app/App/Views/ apps/ios-app/App/Core/` -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -- [x] **Step 4: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md apps/ios-app/App/Views/Composer/FireComposerView.swift apps/ios-app/App/Core/FireTheme.swift apps/ios-app/App/Core/FireComponents.swift -git commit -m "fix(ios): replace hardcoded composer colors with theme tokens" -``` - ---- - -## Task 7: iOS 通用分页 Store 提取 - -**Files:** -- Create: `apps/ios-app/App/Stores/FirePaginatedStore.swift` -- Modify: `apps/ios-app/App/Stores/FireSearchStore.swift` -- Modify: `apps/ios-app/App/Stores/FireNotificationStore.swift` -- Modify: `apps/ios-app/Fire.xcodeproj/project.pbxproj` -- Modify: `apps/ios-app/README.md` - -- [x] **Step 1: 创建 FirePaginatedStore 基类** - -`FirePaginatedStore` now owns shared paginated list state: -- `items`, `isLoading`, `isLoadingMore`, `hasLoadedOnce` -- blocking/non-blocking errors -- next cursor tracking -- cancellable fire-and-forget `load` / `loadMore` -- awaited `loadAsync` / `loadMoreAsync` -- overridable `fetchPage`, `mergeItems`, and recoverable-error hook - -- [x] **Step 2: 迁移 FireSearchStore** - -`FireSearchStore` now inherits `FirePaginatedStore` while preserving its existing public API (`result`, `currentPage`, `isSearching`, `isAppending`, `errorMessage`, `submit(reset:)`). Search keeps the aggregate `SearchResultState` model and uses page numbers as the base cursor instead of introducing a fake item wrapper. - -- [x] **Step 3: 迁移 FireNotificationStore 全量通知分页** - -`FireNotificationStore` now delegates full-history pagination to a private `FirePaginatedStore` subclass and bridges `objectWillChange` back to the outer store. Recent notifications, unread count, read mutations, and MessageBus refresh remain explicit in `FireNotificationStore`. - -- [x] **Step 4: 构建验证** - -Verified: -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -- [x] **Step 5: 运行搜索相关测试** - -Verified: -- `cd apps/ios-app && xcodebuild test -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -only-testing:FireTests/FireSearchStoreTests` - -- [x] **Step 6: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md apps/ios-app/README.md apps/ios-app/App/Stores/FirePaginatedStore.swift apps/ios-app/App/Stores/FireSearchStore.swift apps/ios-app/App/Stores/FireNotificationStore.swift apps/ios-app/Fire.xcodeproj/project.pbxproj -git commit -m "refactor(ios): extract generic FirePaginatedStore base class" -``` - ---- - -## Task 8: iOS 空状态组件复用 + Shimmer 动画 - -**Files:** -- Modify: `apps/ios-app/App/Core/FireComponents.swift` -- Create: `apps/ios-app/App/Core/FireShimmerModifier.swift` -- Modify: `apps/ios-app/App/ListKit/Home/FireHomeCollectionView.swift` -- Modify: `apps/ios-app/App/Views/Home/FireFilteredTopicListView.swift` -- Modify: `apps/ios-app/App/Views/Notifications/FireNotificationsView.swift` -- Modify: `apps/ios-app/App/Views/Notifications/FireNotificationHistoryView.swift` -- Modify: `apps/ios-app/Fire.xcodeproj/project.pbxproj` - -- [x] **Step 1: 创建 Shimmer 修饰器** - -`FireShimmerModifier` now provides `View.fireShimmer()` with FireTheme colors, geometry-relative animation, hit-testing disabled, clipping, and reduce-motion support. - -- [x] **Step 2: 确认 FireEmptyFeedState 已存在** - -`FireEmptyFeedState` now supports reusable icon, optional title, message, and optional action button parameters while preserving the existing message/action initializer shape. - -- [x] **Step 3: 在视图列表中应用 Shimmer 和空状态** - -Applied `.fireShimmer()` to the existing SwiftUI skeletons: -- `FireTopicSkeletonList` -- `FireHomeCollectionView.loadingRow` -- `FireFilteredTopicListView.loadingSection` -- `FireNotificationsView.loadingSkeleton` - -Reused `FireEmptyFeedState` in: -- `FireFilteredTopicListView.emptySection` -- `FireNotificationsView.emptyState` -- `FireNotificationHistoryView.emptyState` - -Checked search, bookmarks, drafts, private messages, and read history; they did not have `.redacted(reason: .placeholder)` skeletons to replace. - -- [x] **Step 4: 构建验证** - -Verified: -- `rg -n "redacted\\(reason: \\.placeholder\\)|fireShimmer\\(|FireEmptyFeedState\\(" apps/ios-app/App -g '*.swift'` -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -- [x] **Step 5: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md apps/ios-app/App/Core/FireShimmerModifier.swift apps/ios-app/App/Core/FireComponents.swift apps/ios-app/App/ListKit/Home/FireHomeCollectionView.swift apps/ios-app/App/Views/Home/FireFilteredTopicListView.swift apps/ios-app/App/Views/Notifications/FireNotificationsView.swift apps/ios-app/App/Views/Notifications/FireNotificationHistoryView.swift apps/ios-app/Fire.xcodeproj/project.pbxproj -git commit -m "feat(ios): add shimmer animation and reuse empty states" -``` - ---- - -## Task 9: iOS 上下文菜单 - -**Files:** -- Create: `apps/ios-app/App/Core/FireContextMenus.swift` -- Modify: `apps/ios-app/App/ListKit/Home/FireHomeCollectionView.swift` -- Modify: `apps/ios-app/App/Views/Home/FireHomeView.swift` -- Modify: `apps/ios-app/App/Views/Home/FireFilteredTopicListView.swift` -- Modify: `apps/ios-app/App/Views/Search/FireSearchView.swift` -- Modify: `apps/ios-app/App/Views/Bookmarks/FireBookmarksView.swift` -- Modify: `apps/ios-app/App/Views/Other/FireReadHistoryView.swift` -- Modify: `apps/ios-app/App/Views/FireNotificationsView.swift` -- Modify: `apps/ios-app/App/Views/Notifications/FireNotificationHistoryView.swift` -- Modify: `apps/ios-app/Fire.xcodeproj/project.pbxproj` - -- [x] **Step 1: 创建上下文菜单构建器** - -`FireContextMenus.swift` now provides: -- `FireTopicContextMenu` for open, bookmark editor, share, copy link, and mute actions. -- `FireNotificationContextMenu` for open, mark-read, copy content, share link, and copy link actions. -- small URL/context helpers for topic share URLs, notification share URLs, and bookmark editor contexts. - -- [x] **Step 2: 话题行添加上下文菜单** - -`FireTopicRow` remains presentation-only. Owning views attach menus with local closures so routing, bookmark sheets, mutation services, and refresh behavior stay with the surface that owns them: -- Home collection rows -- Filtered category/tag topic lists -- Search topic results -- Bookmarks -- Read history - -Bookmark actions reuse `FireBookmarkEditorSheet`; muting uses `FireTopicInteractionService.setTopicNotificationLevel(.muted)`. There is no topic-list mark-read API, so no synthetic fallback action was added. - -- [x] **Step 3: 通知行添加上下文菜单** - -Recent and full notification history now share `FireNotificationRow`, which wraps `FireNotificationRowContent` with tap handling, accessibility labels, and context-menu actions. Mark-read uses `FireNotificationStore.markRead(id:)`; open uses the existing route presentation path. - -- [x] **Step 4: 构建验证** - -Verified: -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF' -quiet` - -- [x] **Step 5: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md apps/ios-app/App/Core/FireContextMenus.swift apps/ios-app/App/ListKit/Home/FireHomeCollectionView.swift apps/ios-app/App/Views/Home/FireHomeView.swift apps/ios-app/App/Views/Home/FireFilteredTopicListView.swift apps/ios-app/App/Views/Search/FireSearchView.swift apps/ios-app/App/Views/Bookmarks/FireBookmarksView.swift apps/ios-app/App/Views/Other/FireReadHistoryView.swift apps/ios-app/App/Views/Notifications/FireNotificationsView.swift apps/ios-app/App/Views/Notifications/FireNotificationHistoryView.swift apps/ios-app/Fire.xcodeproj/project.pbxproj -git commit -m "feat(ios): add context menus to topic rows and notifications" -``` - ---- - -## Task 10: iOS FireAppViewModel 拆分 — 话题交互服务 - -**Files:** -- Create: `apps/ios-app/App/Services/FireTopicInteractionService.swift` -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` - -- [x] **Step 1: 创建 FireTopicInteractionService** - -从 `FireAppViewModel` 中提取以下方法到 `FireTopicInteractionService`: - -```swift -import Foundation - -@MainActor -final class FireTopicInteractionService { - private let appViewModel: FireAppViewModel - - init(appViewModel: FireAppViewModel) { - self.appViewModel = appViewModel - } - - // 从 FireAppViewModel 搬入: - // - toggleLike(postId:) - // - toggleReaction(postId:reaction:) - // - createBookmark(postId:name:reminderAt:) - // - deleteBookmark(bookmarkId:) - // - toggleTopicVote(topicId:) - // - votePoll(pollName:optionId:postId:) - // - unvotePoll(pollName:optionId:postId:) - // - flagPost(postId:reasonId:) - // - reportPostTimings(topicId:timings:) -} -``` - -- [x] **Step 2: FireAppViewModel 持有 service 实例** - -在 `FireAppViewModel` 中添加: - -```swift -let topicInteraction: FireTopicInteractionService -``` - -在 `init` 中初始化。所有调用 `toggleLike` 等方法的视图改为通过 `appViewModel.topicInteraction.toggleLike(...)`。 - -- [x] **Step 3: 构建验证** - -Run: `cd apps/ios-app && xcodebuild build -scheme FireApp -destination 'platform=iOS Simulator,name=iPhone 16' -quiet 2>&1 | tail -5` -Expected: `** BUILD SUCCEEDED **` - -- [x] **Step 4: 运行相关测试** - -Run: `cd apps/ios-app && xcodebuild test -scheme FireApp -destination 'platform=iOS Simulator,name=iPhone 16' 2>&1 | grep -E '(Test Suite|Executed|FAILED)'` -Expected: All tests pass, 0 failures - -- [x] **Step 5: Commit** - -```bash -git add apps/ios-app/App/Services/FireTopicInteractionService.swift apps/ios-app/App/ViewModels/FireAppViewModel.swift -git commit -m "refactor(ios): extract FireTopicInteractionService from FireAppViewModel" -``` - ---- - -## Task 11: iOS FireAppViewModel 拆分 — 通知服务 - -**Files:** -- Create: `apps/ios-app/App/Services/FireNotificationService.swift` -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` - -- [x] **Step 1: 创建 FireNotificationService** - -从 `FireAppViewModel` 中提取: - -```swift -@MainActor -final class FireNotificationService { - private let appViewModel: FireAppViewModel - - init(appViewModel: FireAppViewModel) { - self.appViewModel = appViewModel - } - - // 从 FireAppViewModel 搬入: - // - fetchRecentNotifications() - // - fetchFullNotifications(offset:) - // - markNotificationRead(notificationId:) - // - markAllNotificationsRead() -} -``` - -- [x] **Step 2: FireAppViewModel 持有 service 实例** - -```swift -let notificationService: FireNotificationService -``` - -- [x] **Step 3: 构建并测试** - -Run: `cd apps/ios-app && xcodebuild build -scheme FireApp -destination 'platform=iOS Simulator,name=iPhone 16' -quiet 2>&1 | tail -5` -Expected: `** BUILD SUCCEEDED **` - -- [x] **Step 4: Commit** - -```bash -git add apps/ios-app/App/Services/FireNotificationService.swift apps/ios-app/App/ViewModels/FireAppViewModel.swift -git commit -m "refactor(ios): extract FireNotificationService from FireAppViewModel" -``` - ---- - -## Task 12: iOS FireAppViewModel 拆分 — 搜索服务 - -**Files:** -- Create: `apps/ios-app/App/Services/FireSearchService.swift` -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` - -- [x] **Step 1: 创建 FireSearchService** - -```swift -@MainActor -final class FireSearchService { - private let appViewModel: FireAppViewModel - - init(appViewModel: FireAppViewModel) { - self.appViewModel = appViewModel - } - - // 从 FireAppViewModel 搬入: - // - search(query:scope:page:) - // - searchTags(query:) - // - searchUsers(query:) -} -``` - -- [x] **Step 2: FireAppViewModel 持有 service 实例** - -```swift -let searchService: FireSearchService -``` - -- [x] **Step 3: 构建并测试** - -Run: `cd apps/ios-app && xcodebuild build -scheme FireApp -destination 'platform=iOS Simulator,name=iPhone 16' -quiet 2>&1 | tail -5` -Expected: `** BUILD SUCCEEDED **` - -- [x] **Step 4: Commit** - -```bash -git add apps/ios-app/App/Services/FireSearchService.swift apps/ios-app/App/ViewModels/FireAppViewModel.swift -git commit -m "refactor(ios): extract FireSearchService from FireAppViewModel" -``` - ---- - -### Follow-up: iOS FireAppViewModel 拆分 — 门面扩展收敛 - -**Files:** -- Create: `apps/ios-app/App/ViewModels/FireAppViewModelSupport.swift` -- Create: `apps/ios-app/App/ViewModels/FireAppViewModel+Diagnostics.swift` -- Create: `apps/ios-app/App/ViewModels/FireAppViewModel+Profile.swift` -- Create: `apps/ios-app/App/ViewModels/FireAppViewModel+RecoveryURLs.swift` -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` -- Modify: `apps/ios-app/Fire.xcodeproj/project.pbxproj` - -- [x] **Step 1: Move support types out of the main view model file** - -`FireAppViewModelSupport.swift` now owns login/diagnostics error types, auth presentation state, Cloudflare cookie snapshot diagnostics, app-state/state-observer coordinators, topic-detail request/window structs, and search scope helpers. - -- [x] **Step 2: Move diagnostics facade methods** - -`FireAppViewModel+Diagnostics.swift` owns log listing/reading, network trace access, diagnostic session ID, support bundle export, APM summary/export, log flushing, and diagnostics scene-phase handling. - -- [x] **Step 3: Move profile and LDC/CDK facade methods** - -`FireAppViewModel+Profile.swift` owns user profile/summary/actions/bookmarks/follows/invites/badges and LDC/CDK authorization, approval, callback, user-info, and logout pass-through methods. - -- [x] **Step 4: Move Cloudflare recovery URL builders** - -`FireAppViewModel+RecoveryURLs.swift` owns site-root, topic-list, topic-detail, filter, tag, and query-item URL normalization helpers used by the platform WebView recovery path. - -- [x] **Step 5: Build and line-count verification** - -Verified: -- `wc -l apps/ios-app/App/ViewModels/FireAppViewModel.swift` -> `1431` -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3' -derivedDataPath /tmp/fire-ios-vm-split-build CODE_SIGNING_ALLOWED=NO -quiet` passed - -The split is behavior-preserving: stateful login/session/message-bus orchestration remains in `FireAppViewModel.swift`; native topic-detail rows remain on the UIKit/Texture runtime cell path. - ---- - -## Task 13: Android — 草稿列表页 - -**Files:** -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/data/paging/DraftsPagingSource.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/drafts/DraftsFragment.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/drafts/DraftsViewModel.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/drafts/DraftsAdapter.kt` -- Create: `apps/android-app/src/main/res/layout/fragment_drafts.xml` -- Create: `apps/android-app/src/main/res/layout/item_draft.xml` -- Modify: `apps/android-app/src/main/res/navigation/fire_nav_graph.xml` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/profile/ProfileFragment.kt` -- Modify: `apps/android-app/src/main/res/layout/fragment_profile.xml` -- Modify: `apps/android-app/src/main/res/values/strings.xml` - -- [x] **Step 1: Expose draft listing in Android session store** - -`FireSessionStore.fetchDrafts(offset, limit)` now wraps `core.notifications().fetchDrafts(...)` on `Dispatchers.IO`, matching the existing `fetchDraft`, `saveDraft`, and `deleteDraft` UniFFI boundary. - -- [x] **Step 2: Add Paging-backed draft data flow** - -`DraftsPagingSource` requests drafts by offset and limit, returns `DraftState` rows directly from UniFFI, and advances `nextKey` only when `DraftListResponseState.hasMore` is true. `DraftsViewModel` owns the `Pager`, caches it in `viewModelScope`, and reports delete errors through `FireErrorReporter`. - -- [x] **Step 3: Add drafts list UI** - -`DraftsFragment` follows the existing Android list-page shape: `SwipeRefreshLayout`, `RecyclerView`, initial loading indicator, empty/error text, and lifecycle-aware Paging collection. `DraftsAdapter` renders title, excerpt, type/date/user metadata, and a delete button for each draft. - -- [x] **Step 4: Resume and delete behavior** - -Draft taps use the authoritative composer paths: -- `new_topic` opens `TopicComposerSheet`, which restores the fixed `new_topic` draft key. -- `new_private_message` opens `PrivateMessageComposerSheet`, which restores the fixed `new_private_message` draft key. -- Reply drafts open `ReplyComposerSheet` with the parsed `topic_` or `topic__post_` target, preferring explicit `replyToPostNumber` payload data when present. -- Unknown draft keys show `feed_drafts_resume_unavailable` instead of adding a fallback editor path. - -Delete confirms with an `AlertDialog`, calls `sessionStore.deleteDraft(draft.draftKey, draft.sequence)`, then refreshes the Paging adapter. - -- [x] **Step 5: Add profile navigation entry** - -`fire_nav_graph.xml` now includes `draftsFragment` and `ProfileFragment` navigates through generated Safe Args. The profile action row was updated to three equal actions: Bookmarks, Drafts, and Private Messages. - -- [x] **Step 6: Build verification** - -Run: `cd apps/android-app && ./gradlew assembleDebug` - -Result: `BUILD SUCCESSFUL` - -- [x] **Step 7: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md \ - apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt \ - apps/android-app/src/main/java/com/fire/app/data/paging/DraftsPagingSource.kt \ - apps/android-app/src/main/java/com/fire/app/ui/drafts/DraftsViewModel.kt \ - apps/android-app/src/main/java/com/fire/app/ui/drafts/DraftsAdapter.kt \ - apps/android-app/src/main/java/com/fire/app/ui/drafts/DraftsFragment.kt \ - apps/android-app/src/main/java/com/fire/app/ui/profile/ProfileFragment.kt \ - apps/android-app/src/main/res/layout/fragment_drafts.xml \ - apps/android-app/src/main/res/layout/item_draft.xml \ - apps/android-app/src/main/res/layout/fragment_profile.xml \ - apps/android-app/src/main/res/navigation/fire_nav_graph.xml \ - apps/android-app/src/main/res/values/strings.xml -git commit -m "feat(android): add drafts list screen" -``` - ---- - -## Task 14: Android — 推送通知(FCM) - -**Files:** -- Modify: `apps/android-app/build.gradle.kts` -- Create: `apps/android-app/src/main/java/com/fire/app/push/FireFirebaseMessagingService.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/push/FirePushNotification.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/push/FirePushNotificationDispatcher.kt` -- Modify: `apps/android-app/src/main/AndroidManifest.xml` -- Local/CI config: `apps/android-app/google-services.json` (ignored production project config) - -- [x] **Step 1: 添加 Firebase 依赖** - -`build.gradle.kts` now declares the Google Services plugin and Firebase -Messaging dependencies: - -```kotlin -id("com.google.gms.google-services") version "4.4.2" apply false - -implementation(platform("com.google.firebase:firebase-bom:33.15.0")) -implementation("com.google.firebase:firebase-messaging-ktx") -``` - -The Google Services plugin is applied only when a real -`apps/android-app/google-services.json` exists, so source builds remain -repeatable without checking private Firebase project configuration into git. -`apps/android-app/.gitignore` excludes that file. - -- [x] **Step 2: 创建 FCM Service** - -`FireFirebaseMessagingService` receives token refreshes and FCM messages. Token -refreshes are logged to Rust diagnostics, but not registered directly from -Android because there is no shared Rust/core token-registration API yet. Message -handling parses common Discourse/LinuxDo payload fields through -`FirePushPayloadParser`, displays a local notification through -`FirePushNotificationDispatcher`, and refreshes Rust notification state -opportunistically without making notification display depend on network success. - -- [x] **Step 3: 注册 Service 和通知 Channel** - -`AndroidManifest.xml` registers the non-exported Firebase messaging service: - -```xml - - - - - -``` - -`FireApplication.onCreate()` creates the `fire_notifications` channel through -`FirePushNotificationDispatcher`, separate from the existing bookmark reminder -channel. - -- [x] **Step 4: 构建验证** - -Run: -- `cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.push.FirePushPayloadParserTest` -- `cd apps/android-app && ./gradlew assembleDebug` - -Result: passed. - -- [x] **Step 5: Commit** - -Included in this commit. - -```bash -git add apps/android-app/.gitignore apps/android-app/build.gradle.kts apps/android-app/src/main/java/com/fire/app/push/ apps/android-app/src/test/java/com/fire/app/push/ apps/android-app/src/main/AndroidManifest.xml apps/android-app/src/main/java/com/fire/app/FireApplication.kt apps/android-app/src/main/res/values/strings.xml apps/android-app/README.md docs/superpowers/plans/2026-06-08-p1-foundation.md -git commit -m "feat(android): add Firebase Cloud Messaging push notification support" -``` - ---- - -## Task 15: Android — 阅读历史页 - -**Files:** -- Create: `apps/android-app/src/main/java/com/fire/app/data/paging/ReadHistoryPagingSource.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/readhistory/ReadHistoryFragment.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/readhistory/ReadHistoryViewModel.kt` -- Create: `apps/android-app/src/main/res/layout/fragment_read_history.xml` -- Modify: `apps/android-app/src/main/res/navigation/fire_nav_graph.xml` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/profile/ProfileFragment.kt` -- Modify: `apps/android-app/src/main/res/layout/fragment_profile.xml` -- Modify: `apps/android-app/src/main/res/values/strings.xml` - -- [x] **Step 1: Add Paging-backed read history data flow** - -`ReadHistoryPagingSource` calls `FireSessionStore.fetchReadHistory(page)` and returns `TopicRowState` rows directly from `TopicListState`, using `nextPage` as the authoritative continuation. `ReadHistoryViewModel` owns the `Pager` and caches it in `viewModelScope`. - -- [x] **Step 2: Add read history screen** - -`ReadHistoryFragment` reuses `TopicListAdapter`, `TopicDetailActivity`, `SwipeRefreshLayout`, and the existing loading/empty/error list-state pattern. Topic taps open the topic detail at `lastReadPostNumber` when available. - -- [x] **Step 3: Add profile navigation entry** - -`fire_nav_graph.xml` now includes `readHistoryFragment` and the generated `actionProfileToReadHistory()` Safe Args action. The own-profile action row now exposes Bookmarks, Drafts, Messages, and History. - -- [x] **Step 4: Build verification** - -Run: `cd apps/android-app && ./gradlew assembleDebug` - -Result: `BUILD SUCCESSFUL` - -- [x] **Step 5: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md \ - apps/android-app/src/main/java/com/fire/app/data/paging/ReadHistoryPagingSource.kt \ - apps/android-app/src/main/java/com/fire/app/ui/readhistory/ReadHistoryViewModel.kt \ - apps/android-app/src/main/java/com/fire/app/ui/readhistory/ReadHistoryFragment.kt \ - apps/android-app/src/main/java/com/fire/app/ui/profile/ProfileFragment.kt \ - apps/android-app/src/main/res/layout/fragment_read_history.xml \ - apps/android-app/src/main/res/layout/fragment_profile.xml \ - apps/android-app/src/main/res/navigation/fire_nav_graph.xml \ - apps/android-app/src/main/res/values/strings.xml -git commit -m "feat(android): add read history screen with pagination" -``` - ---- - -## Task 16: Android — 通知历史全屏页 - -**Files:** -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationListAdapter.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationHistoryAdapter.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationHistoryFragment.kt` -- Create: `apps/android-app/src/main/res/layout/fragment_notification_history.xml` -- Create: `apps/android-app/src/main/res/layout/item_notification_history_header.xml` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationsFragment.kt` -- Modify: `apps/android-app/src/main/res/layout/fragment_notifications.xml` -- Modify: `apps/android-app/src/main/res/navigation/fire_nav_graph.xml` -- Modify: `apps/android-app/src/main/res/values/strings.xml` - -- [x] **Step 1: Create grouped notification history screen** - -`NotificationHistoryFragment` reuses `NotificationsViewModel` and the existing `NotificationPagingSource` through `notificationPagingFlow()`. It maps notification rows into a history row model and uses Paging `insertSeparators` for Today / Yesterday / Earlier section headers. - -- [x] **Step 2: Reuse notification row rendering** - -`NotificationListAdapter` now exposes a reusable `NotificationViewHolder`, and `NotificationHistoryAdapter` wraps it for notification rows while rendering section headers from `item_notification_history_header.xml`. - -- [x] **Step 3: Add layout and navigation** - -`fragment_notification_history.xml` provides a full-screen `SwipeRefreshLayout` + `RecyclerView` list with loading and empty/error states. `NotificationsFragment` now has a `View All` text button that navigates to `notificationHistoryFragment`; the history screen can still navigate profile-targeted notifications to `profileFragment`. - -- [x] **Step 4: Build verification** - -Run: `cd apps/android-app && ./gradlew assembleDebug` - -Result: `BUILD SUCCESSFUL` - -- [x] **Step 5: Commit** - -```bash -git add docs/superpowers/plans/2026-06-08-p1-foundation.md \ - apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationListAdapter.kt \ - apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationHistoryAdapter.kt \ - apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationHistoryFragment.kt \ - apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationsFragment.kt \ - apps/android-app/src/main/res/layout/fragment_notifications.xml \ - apps/android-app/src/main/res/layout/fragment_notification_history.xml \ - apps/android-app/src/main/res/layout/item_notification_history_header.xml \ - apps/android-app/src/main/res/navigation/fire_nav_graph.xml \ - apps/android-app/src/main/res/values/strings.xml -git commit -m "feat(android): add full-page notification history with grouped sections" -``` - ---- - -## Task 17: Android — 话题阅读计时 - -**Files:** -- Create: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicTimingTracker.kt` -- Create: `apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicTimingTrackerTest.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/FireApplication.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt` - -- [x] **Step 1: 创建 TopicTimingTracker** - -Implemented `TopicTimingTracker` with one-second ticks, 60-second flushes, idle pause handling, per-post timing caps, rejected-report backoff, scene active/inactive control, and deterministic clock/dispatcher injection for JVM tests. - -- [x] **Step 2: 集成到 TopicDetailActivity / FireSessionStore** - -`TopicDetailActivity` now owns native visible-row collection from the `RecyclerView` lifecycle and reports through `FireSessionStore.reportTopicTimings(...)` into the Rust UniFFI `/topics/timings` API. `TopicDetailViewModel` is now provider-backed so its existing `onCleared()` cleanup reliably releases topic MessageBus subscriptions. - -- [x] **Step 3: 构建验证** - -Verified: -- `cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.ui.topicdetail.TopicTimingTrackerTest` -- `cd apps/android-app && ./gradlew assembleDebug` - -- [x] **Step 4: Commit** - -```bash -git add apps/android-app/src/main/java/com/fire/app/FireApplication.kt apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicTimingTracker.kt apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicTimingTrackerTest.kt docs/superpowers/plans/2026-06-08-p1-foundation.md -git commit -m "feat(android): add topic timing tracker for read time reporting" -``` diff --git a/docs/superpowers/plans/2026-06-08-p2-feature-completion.md b/docs/superpowers/plans/2026-06-08-p2-feature-completion.md deleted file mode 100644 index e5c7f535..00000000 --- a/docs/superpowers/plans/2026-06-08-p2-feature-completion.md +++ /dev/null @@ -1,811 +0,0 @@ -# P2 功能补全 Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** 补齐 API 表面中的未实现功能,LDC/CDK OAuth 优先实现 - -**Architecture:** LDC/CDK OAuth 从 Rust core 新模块开始,通过 UniFFI 暴露给 iOS/Android 原生 UI。编辑器增强、回复树展示、话题搜索等功能在现有 Rust 模型基础上扩展原生 UI 层。 - -**Tech Stack:** Rust (fire-core, fire-models, fire-uniffi) / SwiftUI (iOS) / Kotlin + ViewBinding (Android) - ---- - -## File Structure - -### Rust Changes - -| Action | Path | Responsibility | -|--------|------|----------------| -| Create | `crates/fire-models/src/ldc.rs` | LDC/CDK 模型类型 | -| Create | `crates/fire-core/src/core/ldc.rs` | LDC OAuth + API 实现 | -| Create | `crates/fire-core/src/core/cdk.rs` | CDK OAuth + API 实现 | -| Create | `crates/fire-core/src/ldc_payloads.rs` | LDC/CDK JSON 解析 | -| Modify | `crates/fire-models/src/lib.rs` | 注册 ldc 模块 | -| Modify | `crates/fire-core/src/core/mod.rs` | 注册 ldc/cdk 模块 | -| Modify | `crates/fire-uniffi/src/lib.rs` | 暴露 LDC/CDK handle | - -### iOS Changes - -| Action | Path | Responsibility | -|--------|------|----------------| -| Create | `App/Views/Profile/FireLDCView.swift` | LDC 信用主页 | -| Create | `App/Views/Profile/FireCDKView.swift` | CDK 连接页 | -| Create | `App/Views/FireConnectStatsView.swift` | Connect 统计页 | -| Modify | `App/TopicDetail/` | 原生 runtime 话题详情回复树展示 | -| Modify | `App/Views/Composer/FireComposerView.swift` | 集成 Markdown 工具栏和引用插入 | -| Modify | `App/Views/Composer/FirePostEditorView.swift` | 升级为 FireComposerTextView | -| Modify | `App/TopicDetail/` 相关文件 | 话题通知级别 UI、话题内搜索 | - -### Android Changes - -| Action | Path | Responsibility | -|--------|------|----------------| -| Create | `ui/ldc/LDCFragment.kt` | LDC 信用主页 | -| Create | `ui/ldc/LDCViewModel.kt` | LDC ViewModel | -| Create | `ui/ldc/CDKFragment.kt` | CDK 连接页 | -| Modify | `ui/topicdetail/TopicDetailViewModel.kt` | 回复树 row projection | -| Modify | `ui/topicdetail/TopicDetailActivity.kt` | 话题详情回复树展示 | -| Create | `ui/composer/MarkdownToolbarView.kt` | Markdown 工具栏 | -| Modify | `ui/composer/ReplyComposerSheet.kt` | 集成工具栏 | - ---- - -## Task 1: LDC/CDK — Rust 模型层 - -**Files:** -- Create: `crates/fire-models/src/ldc.rs` -- Modify: `crates/fire-models/src/lib.rs` - -- [x] **Step 1: 创建 LDC/CDK 模型类型** - -Implemented in `crates/fire-models/src/ldc.rs`. - -Implementation note: the original schematic fields were replaced with the observed protocol contract from `docs/knowledge/api/13-ldc-cdk-oauth.md` and `references/fluxdo/lib/models/`. - -- `LdcUserInfo` mirrors `GET https://credit.linux.do/api/v1/oauth/user-info`: `nickname`, `trust_level`, `avatar_url`, receive/payment/transfer/community totals, balances, quota, pay flags, pay level, daily limit, and optional gamification score. -- `CdkUserInfo` mirrors `GET https://cdk.linux.do/api/v1/oauth/user-info`: `nickname`, `trust_level`, `avatar_url`, and `score`; it intentionally does not reuse LDC balance/payment fields. -- `LdcAuthorizationUrl`, `CdkAuthorizationUrl`, `LdcApprovalStatus`, `LdcPayment`, `LdcPaymentList`, `ConnectTrustLevelProgress`, and `TrustLevelRequirement` are present for the next core and UI tasks. -- `LdcApprovalStatus::Approved` carries both `code` and `state`, matching the OAuth approval redirect. -- Serialization tests cover the documented LDC and CDK `user-info` shapes. - -- [x] **Step 2: 注册模块** - -在 `crates/fire-models/src/lib.rs` 中添加: - -```rust -mod ldc; -pub use ldc::*; -``` - -- [x] **Step 3: 构建验证** - -Run: `cd rust && cargo check -p fire-models 2>&1 | tail -5` -Expected: `Finished` without errors - -- [x] **Step 4: Commit** - -```bash -git add crates/fire-models/src/ldc.rs crates/fire-models/src/lib.rs -git commit -m "feat(models): add LDC Credit and CDK OAuth model types" -``` - ---- - -## Task 2: LDC/CDK — Rust Core 实现 - -**Files:** -- Create: `crates/fire-core/src/core/ldc.rs` -- Create: `crates/fire-core/src/core/cdk.rs` -- Create: `crates/fire-core/src/ldc_payloads.rs` -- Modify: `crates/fire-core/src/core/mod.rs` -- Modify: `crates/fire-core/src/core/network.rs` -- Modify: `crates/fire-core/src/lib.rs` -- Modify: `crates/fire-core/Cargo.toml` -- Modify: `crates/fire-models/src/ldc.rs` - -- [x] **Step 1: 实现 LDC OAuth 流程** - -Implemented in `crates/fire-core/src/core/ldc.rs`. - -Implementation note: the stale schematic endpoints were replaced with the observed contract in `docs/knowledge/api/13-ldc-cdk-oauth.md`. - -- `ldc_authorization_url()` calls `GET https://credit.linux.do/api/v1/oauth/login`. -- `ldc_approval_link()` loads the returned authorization URL as HTML and parses `a[href*="/oauth2/approve/"]`. -- `ldc_approve()` calls `https://connect.linux.do/oauth2/approve/...` with redirects disabled and parses `code` + `state` from `Location`. -- `ldc_callback(code, state)` posts `application/x-www-form-urlencoded` to `https://credit.linux.do/api/v1/oauth/callback`. -- `ldc_user_info()` calls `GET https://credit.linux.do/api/v1/oauth/user-info`. -- `ldc_logout()` calls `GET https://credit.linux.do/api/v1/oauth/logout`. -- `ldc_reward()` implements the documented Basic-auth JSON reward API at `https://credit.linux.do/epay/pay/distribute`. -- No LDC payment-history endpoint was added because it is not present in the current knowledge doc. - -- [x] **Step 2: 实现 CDK OAuth 流程** - -Implemented in `crates/fire-core/src/core/cdk.rs`. - -- CDK uses the same OAuth flow helpers as LDC against `https://cdk.linux.do/api/v1/oauth/*`. -- CDK user-info is parsed into `CdkUserInfo` with `score`; it does not reuse LDC balance/payment fields. - -- [x] **Step 3: 实现 JSON/HTML 解析** - -Implemented in `crates/fire-core/src/ldc_payloads.rs`. - -- Parsers return `serde_json::Error`, matching existing `fire-core` payload modules. -- Unit tests cover LDC user-info, CDK user-info, authorization URL state extraction, approval HTML link extraction, and reward success/failure response shapes. - -- [x] **Step 4: 注册模块** - -`crates/fire-core/src/core/mod.rs` registers `mod ldc;` and `mod cdk;`. `crates/fire-core/src/lib.rs` registers `mod ldc_payloads;`. - -- [x] **Step 5: 构建验证** - -Run: `cd rust && cargo check -p fire-core` -Result: passed. - -- [x] **Step 6: 运行测试** - -Run: `cd rust && cargo test -p fire-core` -Result: passed. - -- [x] **Step 7: Commit** - -```bash -git add crates/fire-core/Cargo.toml Cargo.lock crates/fire-core/src/core/ldc.rs crates/fire-core/src/core/cdk.rs crates/fire-core/src/ldc_payloads.rs crates/fire-core/src/core/mod.rs crates/fire-core/src/core/network.rs crates/fire-core/src/lib.rs crates/fire-models/src/ldc.rs docs/superpowers/plans/2026-06-08-p2-feature-completion.md -git commit -m "feat(core): implement LDC Credit and CDK OAuth flows" -``` - ---- - -## Task 3: LDC/CDK — UniFFI 桥接 - -**Files:** -- Create: `crates/fire-uniffi-ldc/` (新 crate) -- Modify: `Cargo.toml` -- Modify: `crates/fire-uniffi/Cargo.toml` -- Modify: `crates/fire-uniffi/src/lib.rs` -- Modify: `apps/ios-app/project.yml` - -- [x] **Step 1: 创建 fire-uniffi-ldc crate** - -Implemented in `crates/fire-uniffi-ldc/` following the existing handle crate pattern. - -- `crates/fire-uniffi-ldc/Cargo.toml` -- `crates/fire-uniffi-ldc/src/lib.rs` -- `crates/fire-uniffi-ldc/src/records.rs` - -Implementation notes: - -- `FireLdcHandle` stores `Arc` and uses `run_on_ffi_runtime`, matching the existing `fire-uniffi-search`/`fire-uniffi-user` pattern. -- One handle exposes both service flows because LDC and CDK share the same OAuth approval mechanics. -- LDC methods: `ldc_authorization_url`, `ldc_approval_link`, `ldc_approve`, `ldc_callback`, `ldc_user_info`, `ldc_logout`, and `ldc_reward`. -- CDK methods: `cdk_authorization_url`, `cdk_approval_link`, `cdk_approve`, `cdk_callback`, `cdk_user_info`, and `cdk_logout`. -- `LdcApprovalStatusState` is a record with a simple `LdcApprovalStatusKindState` plus optional `code`/`state`, which keeps payload-carrying OAuth approval data easy for Swift/Kotlin to consume. -- LDC/CDK state records live in the feature crate instead of `fire-uniffi-types`, because they are not shared by other handles. -- `ldc_reward` takes client credentials per call and does not persist them in Rust; platform keychain/keystore ownership remains unchanged. - -- [x] **Step 2: 在 FireAppCore 中暴露 handle** - -`crates/fire-uniffi/src/lib.rs` adds an `ldc` handle field, initializes it from the shared core, and exposes `FireAppCore::ldc()`. - -`Cargo.toml` registers `fire-uniffi-ldc` as a workspace member and `crates/fire-uniffi/Cargo.toml` depends on it. - -`apps/ios-app/project.yml` lists `Generated/FireUniFfi/fire_uniffi_ldc.swift` as a UniFFI prebuild output. Android bindgen copies generated namespaces wholesale, so no Android source-list change is needed. - -- [x] **Step 3: 构建验证** - -Run: `cargo fmt --all --check` -Result: passed. - -Run: `cargo check -p fire-uniffi-ldc` -Result: passed. - -Run: `cargo test -p fire-uniffi-ldc` -Result: passed. - -Run: `cargo check -p fire-uniffi` -Result: passed after clearing stale package build artifacts with `cargo clean -p fire-models -p fire-core -p fire-uniffi -p fire-uniffi-ldc`. - -Run: temporary UniFFI bindgen for Swift and Kotlin against `target/debug/libfire_uniffi.dylib` -Result: generated `fire_uniffi_ldc.swift`, `uniffi/fire_uniffi_ldc/fire_uniffi_ldc.kt`, and `FireAppCore.ldc()`. - -- [x] **Step 4: Commit** - -```bash -git add Cargo.toml Cargo.lock crates/fire-uniffi-ldc/ crates/fire-uniffi/Cargo.toml crates/fire-uniffi/src/lib.rs apps/ios-app/project.yml docs/superpowers/plans/2026-06-08-p2-feature-completion.md -git commit -m "feat(uniffi): add LDC and CDK OAuth bridge" -``` - ---- - -## Task 4: LDC/CDK — iOS UI - -**Files:** -- Create: `apps/ios-app/App/Views/Profile/FireLDCView.swift` -- Create: `apps/ios-app/App/Views/Profile/FireCDKView.swift` -- Modify: `apps/ios-app/App/Views/Profile/FireProfileView.swift` (添加入口) -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` (透传 LDC/CDK calls) -- Modify: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` (唯一 Rust bridge) -- Modify: `apps/ios-app/Fire.xcodeproj/project.pbxproj` (注册新 Swift sources) - -- [x] **Step 1: 创建 LDC 信用视图** - -`FireLDCView` lives in the existing profile SwiftUI surface and uses the shared `FireTheme`, `FireMetricTile`, `FireKeyValueRow`, and `FireErrorBanner` components. It loads `ldcUserInfo()` through `FireAppViewModel`, showing available/community balances, receive/payment/transfer/community totals, quota, pay score/level, pay-key/admin flags, daily limit, and optional gamification score. - -No LDC payment-history list is present yet because neither `docs/knowledge/api/13-ldc-cdk-oauth.md` nor the read-only FluxDo reference exposes a payment-history endpoint. The implemented UI displays the documented `user-info` balance/aggregate fields rather than adding an undocumented secondary API path. - -- [x] **Step 2: 创建 CDK 连接视图** - -`FireCDKView` mirrors the LDC authorization surface while using `CdkUserInfoState`: identity, trust level, and CDK score. CDK intentionally does not reuse LDC balance/payment fields. - -- [x] **Step 3: 在 Profile 中添加入口** - -`FireProfileView` adds two profile shortcuts: -- `LDC 信用` (`creditcard.fill`) pushes `FireLDCView(viewModel:)`. -- `CDK 连接` (`key.fill`) pushes `FireCDKView(viewModel:)`. - -- [x] **Step 4: 接入授权/登出流程** - -The iOS session facade now exposes the full UniFFI LDC/CDK handle surface: -- authorization URL fetch -- approval-page link extraction -- approve redirect -- callback POST -- user-info refresh -- logout - -The views run the approval/callback sequence from explicit user actions and never own cookies, WebView login, or credential persistence; those remain platform-owned browser/session concerns and Rust-owned API orchestration as required by the architecture split. - -- [x] **Step 5: 构建验证** - -Run: `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet` -Expected: `** BUILD SUCCEEDED **` - -- [x] **Step 6: Commit** - -```bash -git add apps/ios-app/App/Views/Profile/FireLDCView.swift apps/ios-app/App/Views/Profile/FireCDKView.swift apps/ios-app/App/Views/Profile/FireProfileView.swift apps/ios-app/App/ViewModels/FireAppViewModel.swift apps/ios-app/Sources/FireAppSession/FireSessionStore.swift apps/ios-app/Fire.xcodeproj/project.pbxproj -git commit -m "feat(ios): add LDC Credit and CDK connection views" -``` - ---- - -## Task 5: LDC/CDK — Android UI - -**Files:** -- Create: `apps/android-app/src/main/java/com/fire/app/ui/ldc/LDCFragment.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/ldc/CDKFragment.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/ldc/LdcCdkFragment.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/ldc/LdcCdkViewModel.kt` -- Create: `apps/android-app/src/main/res/layout/fragment_ldc.xml` -- Modify: `apps/android-app/src/main/res/navigation/fire_nav_graph.xml` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/profile/ProfileFragment.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt` -- Modify: `apps/android-app/src/main/res/layout/fragment_profile.xml` -- Modify: `apps/android-app/src/main/res/values/strings.xml` - -- [x] **Step 1: 创建 LDC/CDK ViewModel 和 Fragment** - -遵循 Android MVVM 模式(参考 `HomeViewModel` + `HomeFragment`): -- `LdcCdkViewModel`: `StateFlow`, user-info state, authorization state, `loadUserInfo()`, `prepareAuthorization()`, `completeAuthorization()`, `logout()` -- `LDCFragment`: LDC 余额/信用指标展示 + 授权/登出操作 + 空状态/加载状态 -- `CDKFragment`: CDK 连接账号/积分展示 + 授权/登出操作 + 空状态/加载状态 - -- [x] **Step 2: 布局和导航** - -`fragment_ldc.xml` uses one fixed ViewBinding layout for both services: overview metrics, optional LDC detail rows, explicit refresh, authorization URL/link rows with copy actions, approve/callback completion, and logout. - -Navigation graph adds `ldcFragment` and `cdkFragment`. The current-user profile action strip adds `LDC` and `CDK` entries using a horizontal scroll container so the existing Bookmarks/Drafts/Messages/Read History actions stay reachable on narrow screens. - -`FireSessionStore.kt` wraps the generated `core.ldc()` methods and remains Android's only Rust bridge for these screens. Cookie stores, WebView login, and platform browser context remain outside the new UI. - -- [x] **Step 3: 构建验证** - -Run: `cd apps/android-app && ./gradlew assembleDebug` -Result: `BUILD SUCCESSFUL` - -- [x] **Step 4: Commit** - -```bash -git add apps/android-app/src/main/java/com/fire/app/ui/ldc/ apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt apps/android-app/src/main/java/com/fire/app/ui/profile/ProfileFragment.kt apps/android-app/src/main/res/drawable/bg_ldc_*.xml apps/android-app/src/main/res/layout/fragment_ldc.xml apps/android-app/src/main/res/layout/fragment_profile.xml apps/android-app/src/main/res/navigation/fire_nav_graph.xml apps/android-app/src/main/res/values/strings.xml -git commit -m "feat(android): add LDC Credit and CDK connection screens" -``` - ---- - -## Task 6: 回复树展示 — iOS - -**Files:** -- Modify: `apps/ios-app/App/TopicDetail/Support/FireTopicDetailSharedModels.swift` -- Modify: `apps/ios-app/App/TopicDetail/State/FireTopicDetailPageState.swift` -- Modify: `apps/ios-app/App/TopicDetail/State/FireTopicDetailPageSnapshot.swift` -- Modify: `apps/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift` -- Modify: `apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift` -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift` -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift` -- Modify: `apps/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift` - -- [x] **Step 1: 收口为回复树展示** - -Implemented as the topic-detail native runtime presentation on the authoritative reply-tree reading surface. - -- The existing Texture `ASCollectionNode` feed and `FirePostCellNode` path remain authoritative for original post and reply rows. -- Topic detail renders every loaded Rust tree row in order, preserves Rust-provided depth, and keeps scroll lookup available for loaded nested replies. -- No toolbar entry or controller-local state remains for alternate display projections. - -- [x] **Step 2: 移除视图切换入口** - -`FireTopicDetailToolbarCoordinator` does not expose an alternate display menu. Rust source snapshots, raw-stream pagination, render documents, and native cell layout stay on one authoritative reply-tree path. - -Unit coverage in `FireTopicDetailRuntimeTests` asserts loaded nested replies are visible by default with native runtime cell context. - -- [x] **Step 3: 构建验证** - -Run: `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet` -Result: `** BUILD SUCCEEDED **` - -Run: `cd apps/ios-app && xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -only-testing:FireTests/FireTopicDetailRuntimeTests -quiet` -Result: passed. - -- [x] **Step 4: Commit** - -```bash -git add apps/ios-app/App/TopicDetail/ apps/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift apps/ios-app/README.md docs/superpowers/plans/2026-06-08-p2-feature-completion.md -git commit -m "refactor(ios): keep topic detail on reply tree presentation" -``` - ---- - -## Task 7: 回复树展示 — Android - -**Files:** -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt` -- Modify: `apps/android-app/src/main/res/values/strings.xml` -- Modify: `apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicDetailPostRowsTest.kt` - -- [x] **Step 1: 收口 row projection** - -Implemented on the existing authoritative topic-detail list path. Android -preserves the current Rust tree row order, depth, parent post number, and child -markers. - -- [x] **Step 2: TopicDetailActivity 使用单一路径** - -The toolbar does not expose an alternate display dialog. Topic detail uses the same -`ConcatAdapter` / `PostListAdapter`, the same Rust source snapshot, and the same -Rust tree presentation rows for the reply-shaped reading surface. - -- [x] **Step 3: 构建验证** - -Run: - -```bash -cd apps/android-app -./gradlew testDebugUnitTest --tests com.fire.app.ui.topicdetail.TopicDetailPostRowsTest -./gradlew assembleDebug -``` - -Result: both commands completed with `BUILD SUCCESSFUL`. - -- [x] **Step 4: Commit** - -The Android topic-detail cleanup is committed with the cross-platform reply-tree presentation path. - -```bash -git add docs/superpowers/plans/2026-06-08-p2-feature-completion.md apps/android-app/README.md apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt apps/android-app/src/main/res/values/strings.xml apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicDetailPostRowsTest.kt -git commit -m "refactor(android): keep topic detail on reply tree presentation" -``` - ---- - -## Task 8: 编辑器增强 — Markdown 工具栏 - -**Files:** -- Modify: `apps/ios-app/App/Views/Composer/FireComposerView.swift` -- Modify: `apps/ios-app/App/Views/Composer/FirePostEditorView.swift` -- Modify: `apps/ios-app/Tests/Unit/FireComposerValidationTests.swift` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/composer/MarkdownToolbarView.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerAssist.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/composer/ReplyComposerSheet.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/composer/TopicComposerSheet.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/composer/PrivateMessageComposerSheet.kt` -- Modify: Android composer sheet layouts/resources/tests - -- [x] **Step 1: iOS Markdown 工具栏组件** - -Implemented in the already-compiled composer source to avoid mixing this task -with the unrelated dirty `Fire.xcodeproj/project.pbxproj` state. The reusable -`FireMarkdownToolbar` and `FireMarkdownInsertion` model support bold, italic, -strikethrough, inline code, code block, quote, unordered list, ordered list, -link, and image marker actions. - -- [x] **Step 2: 集成到 FireComposerView / FirePostEditorView** - -`FireComposerView` and `FirePostEditorView` now share the `FireComposerTextView` -selection-binding path. Formatting wraps selected text, inserts paired markers -at the cursor when there is no selection, and keeps focus/selection in the text -view. This also completes the planned PostEditorView text editor upgrade without -introducing a second edit path. - -- [x] **Step 3: Android Markdown 工具栏** - -`MarkdownToolbarView.kt` provides the horizontal formatting toolbar and binds to -the target body `EditText`. `ComposerAssist.kt` owns the pure -`MarkdownInsertion` helper plus the `EditText` adapter. The toolbar is integrated -into `ReplyComposerSheet`, `TopicComposerSheet`, and -`PrivateMessageComposerSheet`, and is hidden with the editor while preview mode -is active. - -- [x] **Step 4: 构建验证(两端)** - -Focused tests already passed: - -```bash -cd apps/ios-app -xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -only-testing:FireTests/FireComposerValidationTests -quiet - -cd apps/android-app -./gradlew testDebugUnitTest --tests com.fire.app.ui.composer.MarkdownInsertionTest -``` - -Final build commands: - -```bash -cd apps/ios-app -xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet - -cd apps/android-app -./gradlew assembleDebug -``` - -Result: focused tests and both final build commands completed successfully. - -- [x] **Step 5: Commit** - -Included in commit `02f0a0e`. - -```bash -git add docs/superpowers/plans/2026-06-08-p2-feature-completion.md apps/ios-app/README.md apps/ios-app/App/Views/Composer/FireComposerView.swift apps/ios-app/App/Views/Composer/FirePostEditorView.swift apps/ios-app/Tests/Unit/FireComposerValidationTests.swift apps/android-app/README.md apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerAssist.kt apps/android-app/src/main/java/com/fire/app/ui/composer/MarkdownToolbarView.kt apps/android-app/src/main/java/com/fire/app/ui/composer/ReplyComposerSheet.kt apps/android-app/src/main/java/com/fire/app/ui/composer/TopicComposerSheet.kt apps/android-app/src/main/java/com/fire/app/ui/composer/PrivateMessageComposerSheet.kt apps/android-app/src/main/res/layout/sheet_reply_composer.xml apps/android-app/src/main/res/layout/sheet_topic_composer.xml apps/android-app/src/main/res/layout/sheet_private_message_composer.xml apps/android-app/src/main/res/values/strings.xml apps/android-app/src/test/java/com/fire/app/ui/composer/MarkdownInsertionTest.kt -git commit -m "feat(composer): add Markdown formatting toolbar for iOS and Android" -``` - ---- - -## Task 9: 编辑器增强 — 引用插入 - -**Files:** -- Modify: `apps/ios-app/App/Views/Composer/FireComposerView.swift` -- Modify: `apps/ios-app/App/TopicDetail/` (post action callbacks) -- Modify: Android 对应文件 - -- [x] **Step 1: iOS 引用插入实现** - -iOS topic-detail native post cells now expose 「引用回复」 from the existing -post operation menu. The action builds Discourse quote Markdown through -`FireQuoteMarkdown`, using Rust-provided `post.renderDocument?.plainText` -rather than parsing `post.cooked` on the platform. Empty render text surfaces a -notice instead of inventing a fallback body. - -Selecting quote opens the full-screen advanced reply composer with: - -- `replyToPostNumber` / `replyToUsername` set to the quoted post -- `[quote="username, post:{number}, topic:{id}"]\n{plain_text}\n[/quote]\n\n` - inserted as `initialBody` -- cursor positioned after the quote block -- restored drafts preserved by prepending the quote once if a matching draft - already exists - -- [x] **Step 2: Android 引用插入** - -Android post rows now show a Quote action beside Reply. `QuoteMarkdown` builds -the same Discourse `[quote]` block from `post.renderDocument?.plainText`, and -`ReplyComposerSheet` accepts an `initialBody` argument. Existing restored draft -content is kept and the quote is inserted once at the beginning. - -- [x] **Step 3: 构建验证** - -Focused verification passed: - -```bash -cd apps/android-app -./gradlew testDebugUnitTest --tests com.fire.app.ui.composer.MarkdownInsertionTest -./gradlew assembleDebug - -cd apps/ios-app -xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -only-testing:FireTests/FireComposerValidationTests -quiet -xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet -``` - -iOS still emits the existing deprecation / Swift 6 migration warnings noted in -earlier tasks, but the build and focused test target pass. - -- [x] **Step 4: Commit** - -Committed as `d0528bd feat(composer): add quote insertion from topic detail posts`. - -```bash -git add -u -git commit -m "feat(composer): add quote insertion from topic detail posts" -``` - ---- - -## Task 10: 编辑器增强 — PostEditorView 升级 - -**Files:** -- Modify: `apps/ios-app/App/Views/Composer/FirePostEditorView.swift` - -- [x] **Step 1: 替换基础 TextEditor** - -Completed as part of Task 8 to keep Markdown formatting on one authoritative -iOS text editing path. `FirePostEditorView` now uses `FireComposerTextView` with -selection binding and `FireMarkdownToolbar`. - -Post edit remains intentionally narrower than full composer flows: it does not -add draft autosave, preview mode, or image upload in this task because the -existing post-edit API requires server-provided raw text and a direct save -mutation path. - -- [x] **Step 2: 构建验证** - -Run: - -```bash -cd apps/ios-app -xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -only-testing:FireTests/FireComposerValidationTests -quiet -xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet -``` - -Result: both commands completed successfully. - -- [x] **Step 3: Commit** - -Included in `feat(composer): add Markdown formatting toolbar for iOS and Android`. - ---- - -## Task 11: 话题通知级别控制 - -**Files:** -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift` -- Modify: `apps/ios-app/App/TopicDetail/Support/FireTopicDetailSharedModels.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListAdapter.kt` -- Modify: `apps/android-app/src/main/res/layout/item_topic_header.xml` -- Modify: `apps/android-app/src/main/res/values/strings.xml` -- Create: `apps/android-app/src/main/res/drawable/ic_notifications_active.xml` -- Create: `apps/android-app/src/main/res/drawable/ic_notifications_off.xml` -- Reference: `docs/knowledge/api/03-topics.md` (topic notification level API) - -- [x] **Step 1: iOS 通知级别按钮** - -`FireTopicDetailToolbarCoordinator` now owns a dedicated bell item in the topic -detail navigation toolbar. The item is hidden for private-message threads, -disabled when write interactions are unavailable, and opens a `UIMenu` titled -「通知设置」 with the four Discourse levels: 静音、常规、跟踪、关注. - -The icon reflects the Rust-provided current notification level: - -- muted: `bell.slash.fill` -- regular: `bell` -- tracking / watching: `bell.fill` - -The old notification section was removed from the ellipsis menu so the toolbar -bell is the one authoritative control. - -- [x] **Step 2: Android 通知级别按钮** - -`TopicDetailActivity` now adds a toolbar bell menu item that is hidden for -private-message threads, updates its title and icon from -`detail.details.notificationLevel`, and opens the notification-level chooser. -The previous header-row notification button was removed from -`PostListAdapter` / `item_topic_header.xml` so Android also has one -authoritative toolbar control. - -- [x] **Step 3: 构建验证** - -Run: - -```bash -cd apps/android-app -./gradlew assembleDebug - -cd apps/ios-app -xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet -``` - -Result: both commands completed successfully. iOS still emits the existing -deprecation / Swift 6 migration warnings noted in earlier tasks. - -- [x] **Step 4: Commit** - -Included in `feat(topic-detail): add topic notification level control to toolbar`. - -```bash -git add -u -git commit -m "feat(topic-detail): add topic notification level control to toolbar" -``` - ---- - -## Task 12: Reaction 选择器增强 - -**Files:** -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift` -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift` -- Modify: `apps/ios-app/App/TopicDetail/Support/FireTopicDetailModalViews.swift` -- Modify: `apps/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift` -- Modify: `apps/ios-app/Sources/FireAppSession/FireSessionStore.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/ReactionPresentation.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt` -- Reference: `docs/knowledge/api/04-posts.md` (reaction APIs) - -- [x] **Step 1: 获取可用 Reaction 列表** - -iOS and Android now build reaction picker options from the Rust-owned bootstrap -`enabledReactionIds` list, with `heart` retained in the picker and the current -reaction preserved if it is not present in bootstrap. iOS exposes the picker -from the native post operation menu; Android upgrades the existing React action -dialog. - -- [x] **Step 2: 搜索表情** - -Both picker implementations support search over reaction id, localized label, -and emoji symbol. - -- [x] **Step 3: Reaction 用户列表** - -iOS adds a Rust-backed reaction-user sheet via -`FireSessionStore.fetchReactionUsers(postID:)`. Android keeps the existing -summary-level reaction-user lookup and adds long-press lookup from a specific -picker row. - -- [x] **Step 4: 构建验证** - -Run: - -```bash -cd apps/android-app -./gradlew testDebugUnitTest --tests com.fire.app.ui.topicdetail.ReactionPresentationTest -./gradlew assembleDebug - -cd apps/ios-app -xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -only-testing:FireTests/FireTopicPresentationTests -quiet -xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet -``` - -Result: all commands completed successfully. iOS still emits the existing -deprecation / Swift 6 migration warnings noted in earlier tasks. - -- [x] **Step 5: Commit** - -Included in `feat(reactions): enhance reaction picker with full list, search, and user list`. - -```bash -git add -u -git commit -m "feat(reactions): enhance reaction picker with full list, search, and user list" -``` - ---- - -## Task 13: 书签提醒 UI - -**Files:** -- Modify: `apps/ios-app/App/Views/Bookmarks/FireBookmarkEditorSheet.swift` -- Modify: iOS bookmark context call sites -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/BookmarkReminderScheduler.kt` -- Reference: `docs/knowledge/api/10-presence-and-categories.md` (bookmark reminders) - -- [x] **Step 1: iOS 书签编辑器添加提醒选择器** - -`FireBookmarkEditorSheet` already owns the native `Toggle` + `DatePicker` -reminder UI. This task kept that authoritative shared sheet, ensured past saved -reminders do not initialize outside the DatePicker range, and continued passing -ISO UTC `reminder_at` through the existing Rust bookmark APIs. - -- [x] **Step 2: 提醒触发时展示本地通知** - -Added host-owned local reminder scheduling to the shared iOS bookmark editor. -Successful saves schedule or cancel `UNUserNotificationCenter` requests keyed by -bookmarkable type/id; deletes cancel the matching local reminder. Notification -payloads reuse the typed route keys so taps route back to the bookmarked topic -or post. - -- [x] **Step 3: Android 对称实现** - -Android topic-detail bookmark editing now uses a native reminder toggle plus -`DatePickerDialog` / `TimePickerDialog`, sends ISO UTC `reminder_at` to Rust, -and schedules host-owned local notifications through `AlarmManager` only after -the Rust bookmark mutation succeeds. Reminder notifications deep-link back to -the topic detail screen, and Android 13+ notification permission is requested -when needed. - -- [x] **Step 4: 构建验证** - -Run: - -```bash -cd apps/android-app -./gradlew testDebugUnitTest --tests com.fire.app.ui.topicdetail.BookmarkReminderSchedulerTest -./gradlew assembleDebug - -cd apps/ios-app -xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet -``` - -Result: all commands completed successfully. iOS still emits the existing -deprecation / Swift 6 migration warnings noted in earlier tasks. - -- [x] **Step 5: Commit** - -Included in `feat(bookmarks): add reminder date picker and local notifications for bookmark reminders`. - -```bash -git add -u -git commit -m "feat(bookmarks): add reminder date picker and local notifications for bookmark reminders" -``` - ---- - -## Task 14: 话题内搜索 - -**Files:** -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift` -- Modify: `apps/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift` -- Modify: `apps/ios-app/App/TopicDetail/Nodes/FireTopicDetailRootNode.swift` -- Modify: `apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift` -- Modify: `apps/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift` -- Modify: `apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift` -- Modify: `apps/ios-app/App/ListKit/TopicDetail/FirePostCellLayout.swift` -- Modify: `apps/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift` -- Create: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicSearchOverlay.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListAdapter.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt` - -- [x] **Step 1: iOS 话题搜索 UI** - -Implemented on the existing UIKit/Texture topic-detail runtime path, not as a -new SwiftUI post-row or SwiftUI search component. `FireTopicDetailToolbarCoordinator` -adds a toolbar `magnifyingglass` button, and `FireTopicDetailViewController` -owns a small UIKit `FireTopicSearchBar` subview above the `ASCollectionNode`. -`FireTopicDetailRootNode` tracks the top chrome inset so the search bar does not -cover feed content. - -- [x] **Step 2: 搜索逻辑** - -Both platforms search only loaded `TopicPostState.renderDocument.plainText`. -The helper returns de-duplicated matches sorted by post number, ignores posts -without Rust render documents, highlights the active matched post, and supports -previous/next wraparound navigation. Navigation reuses the authoritative -topic-detail floor scroll path instead of adding a server-side search API or a -parallel post projection. - -- [x] **Step 3: Android 话题搜索** - -`TopicSearchOverlay` is a native ViewBinding-backed toolbar overlay under the -Material toolbar. `TopicDetailActivity` owns query/result state and scrolls via -the existing `scrollToPostNumber` helper. `PostListAdapter`, `HeaderAdapter`, -and `PostViewHolder` render the current active-match highlight across the -original post and reply rows. - -- [x] **Step 4: 构建验证** - -Run: -- `cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.ui.topicdetail.TopicDetailPostRowsTest` -- `cd apps/android-app && ./gradlew assembleDebug` -- `cd apps/ios-app && xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -only-testing:FireTests/FireTopicPresentationTests/testTopicSearchMatchesLoadedRenderPlainTextInPostOrder -quiet` -- `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -quiet` - -Result: passed, with existing iOS deprecation / Swift 6 migration warnings. - -- [x] **Step 5: Commit** - -Included in commit `2725b39`. - -```bash -git add apps/ios-app/App/TopicDetail/ apps/ios-app/App/ListKit/TopicDetail/ apps/ios-app/Tests/Unit/FireTopicPresentationTests.swift apps/ios-app/Tests/Unit/FirePostCellLayoutCalculatorTests.swift apps/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift apps/android-app/src/main/java/com/fire/app/ui/topicdetail/ apps/android-app/src/main/res/layout/activity_topic_detail.xml apps/android-app/src/main/res/values/ids.xml apps/android-app/src/main/res/values/strings.xml apps/android-app/src/test/java/com/fire/app/ui/topicdetail/TopicDetailPostRowsTest.kt docs/superpowers/plans/2026-06-08-p2-feature-completion.md apps/ios-app/README.md apps/android-app/README.md -git commit -m "feat(topic-detail): add in-topic text search with highlight navigation" -``` diff --git a/docs/superpowers/plans/2026-06-08-p3-native-differentiation.md b/docs/superpowers/plans/2026-06-08-p3-native-differentiation.md deleted file mode 100644 index 927c667a..00000000 --- a/docs/superpowers/plans/2026-06-08-p3-native-differentiation.md +++ /dev/null @@ -1,747 +0,0 @@ -# Native Differentiation Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Ship platform-differentiating features — home screen widgets, offline caching, haptic feedback, shimmer loading, Siri Shortcuts, and Material You — that make Fire feel like a first-party native app on both iOS and Android. - -**Architecture:** Rust owns the offline cache layer via `fire-store` SQLite tables with read-through semantics on network failure; platform stores consume cached payloads transparently. Widgets read from App Group shared containers (iOS) or native widget state mirrored by platform stores (Android), both populated from Rust-backed app loads through the UniFFI bridge. All UI components follow existing `FireTheme` / `FireColors` conventions and are added to the existing component libraries (`FireComponents.swift`, `FireColors.kt`). - -**Tech Stack:** Rust + UniFFI + rusqlite / SwiftUI + WidgetKit + AppIntents / Android Views + AppWidgetProvider + RemoteViews + Material You / Kotlin Coroutines + Paging 3 - -## Feasibility Assessment - -Fully feasible. The Rust `fire-store` crate already has a SQLite migration system with 3 migrations (`current_user_cache`, `topic_posts`, `topic_response_rows`, `cookie_replay_queue`) and supports `auth_scope_hash`-scoped reads/writes. The iOS app has a well-structured `FireTheme` enum with adaptive colors and corner-radius tokens. The Android app uses `FireColors.kt` backed by XML color resources with a clean resolver pattern. Both platforms already have PagingSource / Store patterns that can be augmented with offline fallback without architectural changes. No external dependencies are introduced that don't already exist in the respective ecosystems. - -## Current Surface Inventory - -- `crates/fire-store/src/lib.rs` — `FireStore` struct with `open()`, `open_in_memory()`, cookie replay, user cache methods -- `crates/fire-store/src/migrations.rs` — Schema migrations v1–v3 -- `crates/fire-core/src/core/topics.rs` — `FireCore::fetch_topic_list()` and topic detail source runtime -- `crates/fire-core/src/core/notifications.rs` — Notification fetching and state management -- `apps/ios-app/App/Core/FireTheme.swift` — `FireTheme` enum with adaptive colors, corner radius constants -- `apps/ios-app/App/Core/FireComponents.swift` — 954-line reusable component library -- `apps/ios-app/App/Stores/FireHomeFeedStore.swift` — Home feed state management with `topicLoadErrorMessage` -- `apps/ios-app/App/Stores/FireNotificationStore.swift` — Notification state with error tracking -- `apps/ios-app/App/ViewModels/FireAppViewModel.swift` — Central coordinator (2313 lines) -- `apps/ios-app/App/Views/Home/FireHomeView.swift` — Home view with `.alert()` usage at line 156 -- `apps/android-app/src/main/java/com/fire/app/core/theme/FireColors.kt` — Color resolver with `resolveColor()` -- `apps/android-app/src/main/java/com/fire/app/data/paging/TopicListPagingSource.kt` — Paging 3 source for topics -- `apps/android-app/src/main/java/com/fire/app/data/paging/NotificationPagingSource.kt` — Paging 3 source for notifications -- `apps/android-app/src/main/res/values/colors.xml` — Currently only launcher colors - -## Design - -### Key Design Decisions - -1. **Offline cache lives in Rust `fire-store`, not in platform code.** Both platforms already depend on the UniFFI bridge for data. Adding cache tables to the same SQLite database that `fire-store` already manages keeps cache invalidation, scoping, and migration in one place. The alternative — platform-side Room / CoreData caches — would duplicate serialization logic and break the "Rust owns data" boundary. - -2. **Widgets read from shared containers, not live FFI calls.** iOS WidgetKit extensions run in a separate process with strict memory limits. Writing topic summaries to an App Group `UserDefaults` from the main app process gives the widget a cheap synchronous read path. The alternative — calling UniFFI from the widget extension — would require bundling the Rust dylib into the extension and exceed memory budgets. - -3. **Shimmer uses one shared platform path.** iOS keeps the existing `FireShimmerModifier` as the single SwiftUI animation implementation and applies it through shared skeleton row components; current first-page loading screens no longer fall back to blocking spinners where row-shaped skeletons are available. On Android, a custom `ShimmerLayout` wraps existing `RecyclerView` item layouts without changing their structure. - -4. **Haptic feedback uses the existing `FireMotion` layer.** Remaining SwiftUI transitional surfaces use Fire's UIKit-backed haptic modifiers so the app stays iOS 16-compatible, while UIKit/Texture surfaces call the same small `FireMotionHaptics` bridge at confirmed interaction points. Decorative motion remains Reduce Motion-aware through `FireMotionTokens` and `fireRespectingReduceMotion`. - -5. **Material You uses `DynamicColors` from the Material component library.** Android already depends on `com.google.android.material`. Dynamic Color support is a one-time theme configuration, not a new dependency. The `FireColors.kt` resolver pattern is extended with a `dynamicColorsEnabled` check that falls back to static colors on API < 31. - -6. **Toast component replaces non-critical `.alert()` calls.** Notice-only iOS `.alert("提示", ...)` call sites are non-modal toasts. Critical confirmations, blocking load failures, and error-detail modals remain as alerts or inline error states. - -### New Types - -```rust -// fire-store: new cache tables (Migration 4) -pub struct TopicListCacheEntry { - pub scope_key: String, // "{kind}:{category_id}:{tag}" - pub page: u32, - pub payload_json: String, - pub fetched_at_ms: i64, -} - -pub struct NotificationListCacheEntry { - pub scope_key: String, // "recent" | "full:{offset}" - pub payload_json: String, - pub fetched_at_ms: i64, -} -``` - -```swift -// iOS: shared widget data -struct FireWidgetTopicEntry: Codable, Identifiable { - var id: UInt64 - var title: String - var categorySlug: String - var categoryColor: String - var replyCount: Int - var lastPostedAt: Date -} - -struct FireWidgetData: Codable { - var unreadCount: Int - var recentTopics: [FireWidgetTopicEntry] - var updatedAt: Date -} -``` - -```swift -enum FireToastStyle { - case success, error, info, warning -} - -struct FireToast: Identifiable, Equatable { - let id: UUID - let message: String - let style: FireToastStyle -} - -struct FireToastView: View { - let toast: FireToast -} -``` - -## Phased Implementation - -### Task 1: Toast/Snackbar Component (iOS + Android) - -**Files:** -- Modify: `apps/ios-app/App/Core/FireComponents.swift` -- Create: `apps/android-app/src/main/java/com/fire/app/core/ui/FireToast.kt` -- Modify: `apps/ios-app/App/Views/Home/FireHomeView.swift` -- Modify: `apps/ios-app/App/Views/Home/FireFilteredTopicListView.swift` -- Modify: `apps/ios-app/App/Views/Bookmarks/FireBookmarksView.swift` -- Modify: `apps/ios-app/App/Views/Search/FireSearchView.swift` -- Modify: `apps/ios-app/App/Views/Other/FireDraftsView.swift` -- Modify: `apps/ios-app/App/Views/Other/FireReadHistoryView.swift` -- Modify: `apps/ios-app/App/Views/Messages/FirePrivateMessagesView.swift` -- Modify: `apps/ios-app/App/Views/Profile/FirePublicProfileView.swift` -- Modify: Android composer sheets and topic-detail interaction feedback surfaces - -- [x] **Step 1: Add `FireToastStyle`, `FireToast`, `FireToastView`, and `fireToast(_:)` in `apps/ios-app/App/Core/FireComponents.swift`** - - Implemented in the existing compiled component library instead of creating `FireToast.swift` to avoid unrelated `Fire.xcodeproj` metadata churn while the project file has local dirty changes. The modifier owns an identity-aware auto-dismiss task so an old timer cannot dismiss a newer toast. - -- [x] **Step 2: Create `FireToast` Android component in `apps/android-app/src/main/java/com/fire/app/core/ui/FireToast.kt`** - - Implemented as a Material `Snackbar` wrapper with `SUCCESS`, `ERROR`, `INFO`, and `WARNING` styles backed by the existing Fire color resources plus a string-resource overload. - -- [x] **Step 3: Replace non-critical iOS notice alerts with `fireToast`** - - Converted notice-only `.alert("提示", ...)` feedback in Home, filtered topic lists, Bookmarks, Search, Drafts, Read History, Private Messages, and public-profile private-message submission. Critical confirmations and blocking error states remain modal or inline. - -- [x] **Step 4: Add Android Snackbar calls in composer and topic-detail feedback flows** - - Converted composer sheet errors/draft restore/login/category warnings plus topic-detail action errors, bookmark save/delete, quote-empty, and reaction picker/user feedback at the UI boundary. ViewModels remain business-state owners and do not own Android views. - -- [x] **Step 5: Verify** - - - `cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.ui.composer.MarkdownInsertionTest` — passed - - `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3.1' -quiet` — passed; existing unrelated warnings remain - -**Commit message:** `feat(toast): add FireToast component, replace non-critical alerts on iOS and Android` - ---- - -### Task 2: iOS Widget — Data Sharing Layer - -**Files:** -- Create: `apps/ios-app/App/Shared/FireWidgetData.swift` -- Create: `apps/ios-app/App/Shared/FireWidgetSnapshotWriter.swift` -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` -- Modify: `apps/ios-app/App/Stores/FireHomeFeedStore.swift` -- Modify: `apps/ios-app/App/Stores/FireNotificationStore.swift` -- Modify: `apps/ios-app/Fire.entitlements` -- Create: `apps/ios-app/FireWidget.entitlements` - -- [x] **Step 1: Create shared widget snapshot types** - - `FireWidgetData` and `FireWidgetTopicEntry` live in `App/Shared/FireWidgetData.swift` and are compiled into both the app target and `FireWidgetExtension`. The snapshot is encoded to App Group `UserDefaults` under `group.com.fire.app` with key `fire_widget_data`. - -- [x] **Step 2: Add App Group entitlement** - - Both `Fire.entitlements` and `FireWidget.entitlements` include `com.apple.security.application-groups = group.com.fire.app`. - -- [x] **Step 3: Add `updateWidgetData()` through an app-only writer** - - `FireWidgetSnapshotWriter` stays in the app target only. It converts current Rust-backed `FireTopicRowPresentation` rows plus notification count into widget-safe snapshot data, limits topic entries to five, clears snapshots while unauthenticated, and calls `WidgetCenter.shared.reloadAllTimelines()`. - -- [x] **Step 4: Refresh snapshots from authoritative stores** - - `FireHomeFeedStore` updates widget snapshots after topic-list state changes, including empty first pages. `FireNotificationStore` updates snapshots after notification state changes. Logout and unauthenticated session paths clear shared widget data through `FireAppViewModel.updateWidgetData()`. - -- [x] **Step 5: Verify** - - - `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3' -derivedDataPath /tmp/fire-ios-widget-build2 CODE_SIGNING_ALLOWED=NO -quiet` — passed - - `plutil -p /tmp/fire-ios-widget-build2/Build/Products/Debug-iphonesimulator/Fire.app/PlugIns/FireWidgetExtension.appex/Info.plist` — confirmed `NSExtensionPointIdentifier = com.apple.widgetkit-extension` - -**Commit message:** `feat(widget-data): add shared App Group data layer for iOS home screen widgets` - ---- - -### Task 3: iOS Widget — Small Widget - -**Files:** -- Create: `apps/ios-app/App/Widgets/FireWidgetEntry.swift` -- Create: `apps/ios-app/App/Widgets/FireWidgetViews.swift` -- Create: `apps/ios-app/App/Widgets/FireWidgetBundle.swift` -- Create: `apps/ios-app/App/Widgets/FireSmallWidget.swift` -- Create: `apps/ios-app/Configs/FireWidget-Info.plist` -- Modify: `apps/ios-app/Fire.xcodeproj/project.pbxproj` -- Modify: `apps/ios-app/project.yml` - -- [x] **Step 1: Create `FireWidgetExtension` target** - - The Xcode project and `project.yml` define a `FireWidgetExtension` app-extension target with iOS 16 deployment, App Group entitlement, and an explicit `Configs/FireWidget-Info.plist` containing the WidgetKit `NSExtension` dictionary. The app target embeds the extension in `PlugIns`. - -- [x] **Step 2: Create timeline entry/provider types** - - `FireWidgetEntry.swift` defines `FireWidgetEntry` and `FireWidgetProvider`. Timelines read only `FireWidgetData.load()` from the App Group shared container and refresh after 30 minutes; the extension never calls UniFFI or Rust. - -- [x] **Step 3: Create small widget** - - `FireSmallWidget.swift` displays the Fire brand, unread count, and latest topic summary. It supports `.systemSmall` and deep-links to `fire://notifications`. - -- [x] **Step 4: Add widget deep link handling in the app** - - `FireRouteParser`, `FireNavigationState`, `FireTabRoot`, and `FireHomeView` route `fire://notifications`, `fire://topic/`, and related topic/profile routes through the existing native topic-detail and tab-navigation paths. - -- [x] **Step 5: Verify** - - - `xcodebuild build -scheme Fire ... CODE_SIGNING_ALLOWED=NO -quiet` — passed - - Built extension plist contains `NSExtensionPointIdentifier = com.apple.widgetkit-extension` and bundle ID `com.fire.app.ios.local.debug.widget` - -**Commit message:** `feat(widget-small): add iOS small home screen widget with unread count and latest topic` - ---- - -### Task 4: iOS Widget — Medium Widget - -**Files:** -- Create: `apps/ios-app/App/Widgets/FireMediumWidget.swift` -- Modify: `apps/ios-app/App/Widgets/FireWidgetBundle.swift` -- Modify: `apps/ios-app/App/Widgets/FireWidgetViews.swift` - -- [x] **Step 1: Create `FireMediumWidget.swift`** - - `FireMediumWidget` supports `.systemMedium`, displays unread status and up to three topic rows, and links each row to `fire://topic/`. - -- [x] **Step 2: Add shared widget color/view helpers** - - `FireWidgetViews.swift` contains shared color parsing, category swatch rendering, empty-state rendering, and compact topic-row rendering used by all widget sizes. - -- [x] **Step 3: Register `FireMediumWidget` in `FireWidgetBundle`** - - `FireWidgetBundle` registers `FireSmallWidget`, `FireMediumWidget`, and `FireLargeWidget`. - -- [x] **Step 4: Verify** - - - `xcodebuild build -scheme Fire ... CODE_SIGNING_ALLOWED=NO -quiet` — passed - -**Commit message:** `feat(widget-medium): add iOS medium home screen widget with trending topics` - ---- - -### Task 5: iOS Widget — Large Widget - -**Files:** -- Create: `apps/ios-app/App/Widgets/FireLargeWidget.swift` -- Modify: `apps/ios-app/App/Widgets/FireWidgetBundle.swift` - -- [x] **Step 1: Create `FireLargeWidget.swift`** - - `FireLargeWidget` supports `.systemLarge`, renders unread summary plus up to five topic rows, and uses the same App Group snapshot as the small/medium widgets. - -- [x] **Step 2: Register `FireLargeWidget` in `FireWidgetBundle`** - - `FireWidgetBundle` includes all three widgets in one WidgetKit extension entry point. - -- [x] **Step 3: Verify** - - - `xcodebuild build -scheme Fire ... CODE_SIGNING_ALLOWED=NO -quiet` — passed - -**Commit message:** `feat(widget-large): add iOS large home screen widget with timeline layout` - ---- - -### Task 6: Android Widget — Native RemoteViews Implementation - -**Files:** -- Create: `apps/android-app/src/main/java/com/fire/app/widget/FireUnreadWidgetProvider.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/widget/FireTopicListWidgetProvider.kt` -- Create: `apps/android-app/src/main/java/com/fire/app/widget/FireWidgetData.kt` -- Create: `apps/android-app/src/main/res/drawable/bg_widget_panel.xml` -- Create: `apps/android-app/src/main/res/layout/widget_unread.xml` -- Create: `apps/android-app/src/main/res/layout/widget_topic_list.xml` -- Create: `apps/android-app/src/main/res/xml/fire_unread_widget_info.xml` -- Create: `apps/android-app/src/main/res/xml/fire_topic_list_widget_info.xml` -- Modify: `apps/android-app/src/main/AndroidManifest.xml` -- Modify: `apps/android-app/src/main/java/com/fire/app/MainActivity.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/data/paging/TopicListPagingSource.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationsViewModel.kt` -- Modify: `apps/android-app/src/main/res/values/strings.xml` - -- [x] **Step 1: Use platform AppWidgetProvider/RemoteViews rather than adding Glance** - -The Android host is View/XML-based and does not have a Compose compiler setup. The widget implementation therefore uses `AppWidgetProvider` plus `RemoteViews`, preserving the existing Android stack and avoiding a widget-only Compose/Glance dependency. - -- [x] **Step 2: Create `FireWidgetData.kt` with shared state management** - -`FireWidgetData` persists a compact snapshot in `SharedPreferences` under `fire_widget_prefs`: unread count, current username, up to five topic summaries, and the last update timestamp. Topic summaries are mirrored from `TopicRowState` values returned by Rust-backed paging loads; notification counters are mirrored from `NotificationCenterState`. Widgets never call UniFFI directly. - -- [x] **Step 3: Create `FireUnreadWidgetProvider` small unread-count widget** - -The small widget renders `widget_unread.xml`, pluralizes the unread notification count, shows an empty state when count is zero, and opens `fire://notifications` through `MainActivity`. - -- [x] **Step 4: Create unread widget metadata and layout resources** - -Added `widget_unread.xml`, `fire_unread_widget_info.xml`, shared `bg_widget_panel.xml`, and localized string/plural resources. - -- [x] **Step 5: Create `FireTopicListWidgetProvider` medium topic-list widget** - -The medium widget renders `widget_topic_list.xml`, shows the signed-in username or default title, displays up to three recent topic rows with category/reply/like/timestamp metadata, opens the app from the root, and deep-links rows into `TopicDetailActivity`. - -- [x] **Step 6: Create topic-list widget metadata and layout resources** - -Added `widget_topic_list.xml`, `fire_topic_list_widget_info.xml`, and topic metadata string resources. - -- [x] **Step 7: Register widget providers and notification deep link in `AndroidManifest.xml`** - -Registered `FireUnreadWidgetProvider` and `FireTopicListWidgetProvider` with `APPWIDGET_UPDATE` receivers. Added a `fire://notifications` `MainActivity` intent filter next to the existing profile deep link. - -- [x] **Step 8: Update widget data from app state changes** - -`TopicListPagingSource` now passes first-page topic rows to `HomeViewModel`, which mirrors them into `FireWidgetData` after every page-zero load, including an empty successful result. `NotificationsViewModel` mirrors unread counters after notification center refresh. Both paths use `FireApplication.getInstance()` to avoid introducing platform-side data ownership. - -- [x] **Step 9: Verify Android build/test** - -`cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.ui.composer.MarkdownInsertionTest` — passed. - -**Commit message:** `feat(widget-android): add native app widgets` - ---- - -### Task 7: Haptic Feedback Full Coverage (iOS) - -**Files:** -- Modify: `apps/ios-app/App/FireMotion/FireMotionEffects.swift` -- Modify: `apps/ios-app/App/Views/Other/FireTabRoot.swift` -- Modify: `apps/ios-app/App/ListKit/FireDiffableListController.swift` -- Modify: `apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift` -- Modify: `apps/ios-app/App/Views/Composer/FireComposerView.swift` -- Modify: `apps/ios-app/App/Views/Composer/FirePostEditorView.swift` -- Modify: `apps/ios-app/App/Views/Bookmarks/FireBookmarkEditorSheet.swift` - -- [x] **Step 1: Extend the existing `FireMotion` haptic layer** - - Added declarative SwiftUI helpers for error, selection, and impact feedback, plus a small `FireMotionHaptics` UIKit bridge for Texture/UIKit event handlers. No separate `FireHaptics.swift` was introduced, preserving one authoritative motion/haptics path. - -- [x] **Step 2: Add haptics to like toggle, reaction toggle, bookmark toggle** - - Topic-detail native cells now fire medium impact for heart/like, selection feedback for custom reactions, and light impact for bookmark actions from both action sheet and context menu paths. Existing SwiftUI like/bookmark/follow effects continue to use `FireMotion` modifiers. - -- [x] **Step 3: Add haptics to pull-to-refresh completion** - - `FireDiffableListController` fires a light impact when the shared UIKit refresh control completes, covering Home and other collection-hosted refresh surfaces through the authoritative list controller. - -- [x] **Step 4: Add haptics to send success/failure in composer** - - Existing composer, post editor, and bookmark editor success pulses remain on `fireSuccessFeedback`; validation and server failures now pulse `fireErrorFeedback`. - -- [x] **Step 5: Add haptics to tab switch, context menu, and swipe reply** - - `FireTabRoot` emits selection feedback on tab changes, topic-detail menu presentation emits medium impact, and swipe-to-reply emits medium impact when the gesture crosses the reply threshold. - -- [x] **Step 6: Verify** - - - `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3.1' -quiet` — passed; existing unrelated warnings remain - -**Commit message:** `feat(haptics): add accessibility-gated haptic feedback to all interaction points` - ---- - -### Task 8: Offline Cache Layer (Rust) - -**Files:** -- Modify: `crates/fire-store/src/migrations.rs` (add migration 4) -- Modify: `crates/fire-store/src/lib.rs` (add cache read/write methods) -- Modify: `crates/fire-models/src/topic.rs` and `crates/fire-models/src/notification.rs` (surface cached response metadata) -- Modify: `crates/fire-core/src/core/topics.rs` (add cache integration to fetch) -- Modify: `crates/fire-core/src/core/notifications.rs` (add cache integration) -- Modify: `crates/fire-core/src/core/session.rs` (clear scoped caches on logout) -- Modify: `crates/fire-uniffi-types/src/records/topic_list.rs` and `crates/fire-uniffi-notifications/src/records.rs` (carry cached metadata across UniFFI) - -- [x] **Step 1: Add Migration 4 for topic list and notification cache tables in `migrations.rs`** - - Added `topic_list_cache` keyed by `(auth_scope_hash, scope_key, page)` and `notification_list_cache` keyed by `(auth_scope_hash, scope_key)`, with update-time indexes for future pruning. - -- [x] **Step 2: Add `topic_list_cache_write` and `topic_list_cache_read` methods to `FireStore` in `lib.rs`** - - Added scoped topic-list write/read methods plus unit coverage for auth scope, scope key, and page isolation. - -- [x] **Step 3: Add `notification_list_cache_write` and `notification_list_cache_read` methods to `FireStore`** - - Added notification list write/read methods and shared `clear_list_caches(auth_scope_hash)` for logout invalidation. - -- [x] **Step 4: Add cache write after successful topic list fetch in `topics.rs`** - - `fetch_topic_list` serializes the parsed `TopicListResponse` after successful network parse and stores it under the current Rust-owned auth scope hash. Cache write failures are logged and non-fatal. - -- [x] **Step 5: Add read-through cache fallback on network error in `topics.rs`** - - `fetch_topic_list` falls back only for `FireCoreError::Network`; HTTP, Cloudflare, login, stale-session, and parse errors stay authoritative. Cached responses return with `TopicListResponse.is_cached = true`, and UniFFI exposes `TopicListState.is_cached`. - -- [x] **Step 6: Add same cache write/fallback for notifications in `notifications.rs`** - - Recent and full notification pages use scoped cache keys that include kind, limit, and offset. Cached responses set `NotificationListResponse.is_cached = true`, update the Rust notification runtime, and UniFFI exposes `NotificationListState.is_cached`, `NotificationCenterState.recent_is_cached`, and `NotificationCenterState.full_is_cached`. - -- [x] **Step 7: Add cache invalidation on logout in `session.rs`** - - `logout_local()` clears topic and notification list caches for the current auth scope before mutating session cookies, then clears runtime notification/topic presence state as before. - -- [x] **Step 8: Verify with `cargo test -p fire-store` and `cargo test -p fire-core`** - - - `cargo test -p fire-store` — passed - - `cargo test -p fire-core fetch_topic_list_returns_cached_page_on_network_error` — passed - - `cargo test -p fire-core fetch_recent_notifications_returns_cached_page_on_network_error` — passed - - `cargo test -p fire-core` — passed - - `cargo build -p fire-uniffi` — passed - -**Commit message:** `feat(offline-cache): add Rust-side topic list and notification cache with read-through fallback` - ---- - -### Task 9: Offline Cache Layer (iOS) - -**Files:** -- Modify: `apps/ios-app/App/Core/FireComponents.swift` -- Modify: `apps/ios-app/App/Stores/FireHomeFeedStore.swift` -- Modify: `apps/ios-app/App/Stores/FireNotificationStore.swift` -- Modify: `apps/ios-app/App/Stores/FirePaginatedStore.swift` -- Modify: `apps/ios-app/App/Views/Home/FireHomeView.swift` -- Modify: `apps/ios-app/App/Views/Notifications/FireNotificationsView.swift` -- Modify: `apps/ios-app/App/Views/Notifications/FireNotificationHistoryView.swift` - -- [x] **Step 1: Add shared `FireOfflineBanner` to `FireComponents.swift`** - - Added a compact warning-colored banner using the existing `FireTheme` tokens and SF Symbol `wifi.slash`. The banner lives with the shared SwiftUI components instead of adding a one-off file. - -- [x] **Step 2: Add `isOffline` state to `FireHomeFeedStore`** - - `FireHomeFeedStore` now updates `isOffline` from `TopicListState.isCached` and clears it on explicit feed scope changes. The platform store still uses the normal topic-list fetch path; Rust owns the read-through cache behavior. - -- [x] **Step 3: Carry cached page metadata through `FirePaginatedStore`** - - `PageResult` now includes `isCached` with a default of `false`, so pagination stores can expose cache state without changing unrelated callers. - -- [x] **Step 4: Add offline state to `FireNotificationStore`** - - Recent notifications use `NotificationListState.isCached` / `NotificationCenterState.recentIsCached`; full notification history uses the paginated store and `NotificationListState.isCached` / `NotificationCenterState.fullIsCached`. - -- [x] **Step 5: Add banners to home and notification views** - - `FireHomeView`, `FireNotificationsView`, and `FireNotificationHistoryView` render `FireOfflineBanner` above their existing list content when the corresponding store state reports cached data. - -- [x] **Step 6: Verify iOS build** - - - `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3.1' -quiet` — passed - -**Commit message:** `feat(offline-ios): add offline banner and cache-aware state to iOS home and notification views` - ---- - -### Task 10: Offline Cache Layer (Android) - -**Files:** -- Modify: `apps/android-app/src/main/java/com/fire/app/data/paging/TopicListPagingSource.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/data/paging/NotificationPagingSource.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/home/HomeFragment.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationsViewModel.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationsFragment.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationHistoryFragment.kt` -- Create: `apps/android-app/src/main/res/layout/view_offline_banner.xml` -- Create: `apps/android-app/src/main/res/drawable/bg_offline_banner.xml` -- Create: `apps/android-app/src/main/res/drawable/ic_wifi_off.xml` -- Modify: `apps/android-app/src/main/res/layout/fragment_home.xml` -- Modify: `apps/android-app/src/main/res/layout/fragment_notifications.xml` -- Modify: `apps/android-app/src/main/res/layout/fragment_notification_history.xml` -- Modify: `apps/android-app/src/main/res/values/strings.xml` - -- [x] **Step 1: Keep Android on the normal Rust fetch path** - - No Android `fetchCachedTopicList()` or `fetchCachedNotifications()` path was added. `TopicListPagingSource` and `NotificationPagingSource` call the same repository methods as before; Rust decides whether a network failure can read through to cache. - -- [x] **Step 2: Report cached page metadata from PagingSources** - - Both paging sources now accept an `onPageLoaded` callback and pass through `response.isCached`. Existing callers that do not show offline state use the default no-op callback. - -- [x] **Step 3: Add offline state to Android view models** - - `HomeViewModel` exposes `isOffline` and resets it on feed/filter refresh. `NotificationsViewModel` exposes recent, full-history, and combined offline flows using `NotificationListState.isCached` and `NotificationCenterState.recentIsCached` / `fullIsCached`. - -- [x] **Step 4: Add XML banner resources** - - Added `view_offline_banner.xml`, `bg_offline_banner.xml`, `ic_wifi_off.xml`, and `offline_cache_banner`. The banner uses existing `fire_warning` and `fire_chip_warning_background` colors. - -- [x] **Step 5: Add banner visibility to home and notification fragments** - - `HomeFragment`, `NotificationsFragment`, and `NotificationHistoryFragment` include the shared banner layout and bind visibility to the view model flows. Explicit swipe/manual refresh clears the banner before requesting fresh data. - -- [x] **Step 6: Verify Android build** - - - `cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.ui.composer.MarkdownInsertionTest` — passed - -**Commit message:** `feat(offline-android): add cache-aware offline banners` - ---- - -### Task 11: Shimmer Loading Animation (iOS) - -**Files:** -- Modify: `apps/ios-app/App/Core/FireShimmerModifier.swift` -- Modify: `apps/ios-app/App/Core/FireComponents.swift` -- Modify: list views with first-page blocking loading states - -- [x] **Step 1: Reuse the shared `FireShimmerModifier.swift` shimmer path** - - The branch already had a tracked `FireShimmerModifier` from the iOS native rebuild work. Task 11 keeps that as the single animation implementation instead of adding a parallel `FireShimmer.swift` path. The modifier overlays an animated sweep on existing skeleton shapes and respects `accessibilityReduceMotion`. - -- [x] **Step 2: Find all `.redacted(reason: .placeholder)` usages** - - Verified with `rg "redacted\\(reason: \\.placeholder\\)" apps/ios-app/App`: there are no current SwiftUI redacted placeholders. The earlier pseudo-code was stale relative to the native rebuild branch. - -- [x] **Step 3: Keep home loading on the native ListKit skeleton path** - - Home is owned by `FireHomeCollectionView`, not redacted SwiftUI rows. Its existing `loadingRow` already uses `.fireShimmer()` and keeps topic rows on the native collection runtime path. - -- [x] **Step 4: Replace blocking first-load spinners in notification, search, bookmarks, and secondary list views** - - Added shared `FireTopicSkeletonRow`, configurable `FireTopicSkeletonList`, `FireNotificationSkeletonRow`, and `FireNotificationSkeletonList` in `FireComponents.swift`. Recent notifications now reuse the notification skeleton list; full notification history, search execution, bookmarks, read history, drafts, and private messages use shimmer skeletons for initial page loading while keeping pagination footers as compact `ProgressView`s. - -- [x] **Step 5: Verify iOS build** - - `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3.1' -quiet` passed. Existing unrelated warnings remain around deprecated text interactions, `await` without async operations, and Swift 6 capture diagnostics. - -**Commit message:** `feat(shimmer-ios): replace redacted placeholders with animated shimmer loading views` - ---- - -### Task 12: Shimmer Loading Animation (Android) - -**Files:** -- Create: `apps/android-app/src/main/java/com/fire/app/core/ui/ShimmerLayout.kt` -- Create: `apps/android-app/src/main/res/layout/item_topic_shimmer.xml` -- Modify: `apps/android-app/src/main/res/layout/fragment_home.xml` -- Modify: `apps/android-app/src/main/res/values/fire_colors.xml` -- Modify: `apps/android-app/src/main/res/values-night/fire_colors.xml` - -- [x] **Step 1: Create `ShimmerLayout.kt`** - - Added a reusable `FrameLayout` overlay that draws an animated linear-gradient sweep in `dispatchDraw`, cancels on detach, and respects the system animator-disabled setting through `ValueAnimator.areAnimatorsEnabled()`. - -- [x] **Step 2: Create `item_topic_shimmer.xml`** - - Added a wrapper layout around the existing `item_topic_row_skeleton`, preserving the current skeleton row shape while adding the shimmer treatment. - -- [x] **Step 3: Add shimmer loading state to Home** - - `fragment_home.xml` now uses six `item_topic_shimmer` includes in the existing `loading_skeleton_view`. `HomeFragment` load-state ownership remains unchanged. - -- [x] **Step 4: Verify** - - - `cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.ui.composer.MarkdownInsertionTest` — passed - -**Commit message:** `feat(shimmer-android): add shimmer loading animation for RecyclerView items` - ---- - -### Task 13: iOS Siri Shortcuts - -**Files:** -- Create: `apps/ios-app/App/Intents/FireShortcuts.swift` -- Create: `apps/ios-app/App/Intents/FireViewUnreadIntent.swift` -- Create: `apps/ios-app/App/Intents/FireSearchTopicsIntent.swift` -- Create: `apps/ios-app/App/Intents/FireViewProfileIntent.swift` -- Modify: `apps/ios-app/App/Navigation/FireNavigationState.swift` -- Modify: `apps/ios-app/App/Routing/FireAppRoute.swift` -- Modify: `apps/ios-app/App/Routing/FireRouteParser.swift` -- Modify: `apps/ios-app/App/Views/Other/FireTabRoot.swift` -- Modify: `apps/ios-app/App/Views/Home/FireHomeView.swift` - -- [x] **Step 1: Create `FireViewUnreadIntent` using AppIntents framework** - - `FireViewUnreadIntent` uses `openAppWhenRun = true` and sets `FireNavigationState.shared.pendingRoute = .notifications` from `perform()`. It intentionally does not use `OpenURLIntent`, which is iOS 18-only while Fire targets iOS 16. - -- [x] **Step 2: Create `FireSearchTopicsIntent`** - - `FireSearchTopicsIntent` defines an optional `@Parameter(title: "Search Query") var query: String?` without an unsupported inline default, then sets `.search(query:)` on `FireNavigationState.shared`. - -- [x] **Step 3: Create `FireViewProfileIntent`** - - `FireViewProfileIntent` opens the app and sets `.profileTab` on `FireNavigationState.shared`. - -- [x] **Step 4: Create `FireShortcuts` to group intents** - - `FireShortcuts` registers unread, search, and profile App Shortcuts with system images `bell.badge`, `magnifyingglass`, and `person.circle`. - -- [x] **Step 5: Add deep link and shortcut route handling** - - `FireAppRoute` now models `.notifications`, `.profileTab`, and `.search(query:)`. `FireRouteParser` parses `fire://notifications`, `fire://profile`, and `fire://search?query=...`; `FireTabRoot` selects the notifications/profile tabs or forwards search to `FireHomeView`, and `FireSearchStore.prepareSearch(query:)` preloads the query. - -- [x] **Step 6: Verify** - - - `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3' -derivedDataPath /tmp/fire-ios-widget-build2 CODE_SIGNING_ALLOWED=NO -quiet` — passed - - `cd apps/ios-app && xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3' -derivedDataPath /tmp/fire-ios-widget-build2 CODE_SIGNING_ALLOWED=NO -only-testing:FireTests/FireRouteParserTests -quiet` — passed, 23 route parser tests - -**Commit message:** `feat(shortcuts): add Siri Shortcuts for unread, search, and profile navigation` - ---- - -### Task 14: Android Material You - -**Files:** -- Modify: `apps/android-app/src/main/java/com/fire/app/core/theme/FireColors.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/FireApplication.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/MainActivity.kt` -- Modify: `apps/android-app/src/main/AndroidManifest.xml` -- Modify: `apps/android-app/src/main/res/values/themes.xml` -- Create: `apps/android-app/src/main/res/values-night/themes.xml` - -- [x] **Step 1: Add Material You dynamic color support to `FireColors.kt`** - - `FireColors.accent()` and `accentSoft()` now resolve Material theme attributes when dynamic color is available on Android 12+ and fall back to the Fire palette otherwise. Other semantic/text/surface methods remain fixed Fire palette values so XML-heavy branded surfaces keep their existing contrast and identity. - -- [x] **Step 2: Apply Dynamic Colors in `FireApplication.kt`** - - Startup applies `DynamicColors.applyToActivitiesIfAvailable(this)`, records whether dynamic colors are active, and exposes a wrapped themed context for app-context color resolution. - -- [x] **Step 3: Enable edge-to-edge rendering in `MainActivity.kt`** - - `MainActivity` calls `enableEdgeToEdge()` before `super.onCreate`, while preserving the existing root inset listener that pads content around system bars. - -- [x] **Step 4: Add Predictive Back Gesture support** - - `AndroidManifest.xml` sets `android:enableOnBackInvokedCallback="true"` on the application tag. - -- [x] **Step 5: Add Material3 light/night theme attrs** - - `values/themes.xml` now declares Fire fallback Material3 color attributes and system-bar colors. `values-night/themes.xml` mirrors those attrs with dark-mode system-bar icon flags. - -- [x] **Step 6: Verify** - - - `cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.ui.composer.MarkdownInsertionTest` — passed - -**Commit message:** `feat(material-you): add Dynamic Color, edge-to-edge, and predictive back gesture` - ---- - -### Task 15: Dark Mode Fine-tuning - -**Files:** -- Modify: `apps/ios-app/App/Core/FireTheme.swift` -- Modify: `apps/ios-app/App/Views/Other/FireTabRoot.swift` -- Modify: `apps/ios-app/App/Views/Profile/FireProfileView.swift` -- Modify: `apps/android-app/src/main/java/com/fire/app/core/theme/FireColors.kt` -- Modify: `apps/android-app/src/main/java/com/fire/app/FireApplication.kt` -- Modify: `apps/android-app/src/main/res/values-night/fire_colors.xml` - -- [x] **Step 1: Add OLED pure black option to `FireAppearancePreference`** - - `FireAppearancePreference` now includes `.oled`, displays `纯黑`, and resolves to `.dark` color scheme so the app stays in dark-mode system chrome while Fire surfaces can choose OLED overrides. - -- [x] **Step 2: Keep OLED overrides in the authoritative `FireTheme.swift` path** - - The implementation avoids a separate Xcode project-file change by extending `FireTheme.adaptive()` with an optional `oled` color and a shared `appearancePreferenceStorageKey`. Canvas, surface, panel, chrome, and tab-bar colors now substitute pure-black / near-black OLED values when the stored preference is `oled`. - -- [x] **Step 3: Make OLED surfaces recompute from the stored preference** - - OLED-sensitive colors are computed properties instead of static `let` constants, so switching between dark and pure black re-evaluates the current preference. - -- [x] **Step 4: Add OLED toggle to profile settings** - - `FireProfileView` already renders `FireAppearancePreference.allCases` in the settings segmented picker, so adding the enum case surfaces the pure-black option automatically. `FireTabRoot` and settings now share `FireTheme.appearancePreferenceStorageKey`. - -- [x] **Step 5: Add Android OLED mode hook in `FireColors.kt`** - - `FireColors` now loads a persisted `fire.appearance/oled_mode` flag at app startup and returns `#000000`, `#0A0A0B`, and `#111113` from `backgroundCanvas()`, `backgroundSurface()`, and `backgroundElevated()` when enabled. Android has no existing appearance settings UI, so this task keeps the mode hook centralized instead of adding a partial settings architecture. - -- [x] **Step 6: Run contrast ratio checks** - - Contrast checks passed for representative iOS and Android dark/OLED text-on-surface pairs. Android night `fire_text_tertiary` was adjusted from `#6B7280` to `#7B8491` so tertiary text reaches 4.83:1 on dark canvas and 5.55:1 on OLED black. - -- [x] **Step 7: Verify builds** - - - `cd apps/android-app && ./gradlew testDebugUnitTest --tests com.fire.app.ui.composer.MarkdownInsertionTest` — passed - - `cd apps/ios-app && xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,id=D733CCB1-7B2A-49B5-B3F8-36CB6D0CB2BF,OS=18.3.1' -quiet` — passed - -**Commit message:** `feat(dark-mode): add OLED pure black option and contrast ratio validation` - -## Architectural Notes - -- **Rust ownership boundary:** Offline cache tables live in `fire-store` and are written/read only by `fire-core`. Platforms never touch SQLite directly — they receive cached or fresh data through the same UniFFI call path. This preserves the "Rust owns data" boundary. -- **No new external dependencies:** Android widgets use platform `AppWidgetProvider`/`RemoteViews`; Material Dynamic Colors are part of the Material library already used. WidgetKit and AppIntents are used through APIs compatible with Fire's iOS 16 deployment target. No third-party packages are added. -- **Backward compatibility:** Material You falls back to static Fire colors on API < 31. Siri Shortcuts remain on the iOS 16-compatible AppIntents path. Android widgets use the app's existing minSdk-compatible widget APIs, with newer launcher sizing hints ignored on older launchers. -- **Widget memory:** iOS widget timelines are capped at 30-minute refresh intervals and read from lightweight UserDefaults data — no Rust FFI calls in the widget extension process. -- **Motion accessibility:** Decorative motion is gated or degraded through `FireMotionTokens` / `fireRespectingReduceMotion`. Haptics use the small `FireMotionHaptics` UIKit bridge from both transitional SwiftUI surfaces and Texture/UIKit cells. -- **Cache staleness:** Cache entries have no TTL — they are invalidated on logout and overwritten on every successful fetch. This is intentional: stale data is better than no data for offline mode, and the next successful fetch always replaces it. -- **OLED mode scope:** OLED mode only affects dark-theme canvas/surface colors. Text, accent, and semantic colors remain unchanged to maintain contrast ratios. - -## File Change Summary - -- `apps/ios-app/App/Core/FireComponents.swift` — Toast component, auto-dismiss modifier, and style variants -- `apps/android-app/src/main/java/com/fire/app/core/ui/FireToast.kt` — Snackbar-based Android toast -- `apps/ios-app/App/Views/Home/FireHomeView.swift` — Replace notice alert with toast -- `apps/ios-app/App/Views/Home/FireFilteredTopicListView.swift` — Replace notice alert with toast -- `apps/ios-app/App/Views/Bookmarks/FireBookmarksView.swift` — Replace alert with toast -- `apps/ios-app/App/Views/Search/FireSearchView.swift` — Replace notice alert with toast -- `apps/ios-app/App/Views/Other/FireDraftsView.swift` — Replace alert with toast -- `apps/ios-app/App/Views/Other/FireReadHistoryView.swift` — Replace notice alert with toast -- `apps/ios-app/App/Views/Messages/FirePrivateMessagesView.swift` — Replace alert with toast -- `apps/ios-app/App/Views/Profile/FirePublicProfileView.swift` — Replace composer notice alert with toast -- `apps/ios-app/App/Shared/FireWidgetData.swift` — Shared data model for widget communication -- `apps/ios-app/App/Shared/FireWidgetSnapshotWriter.swift` — App-only widget snapshot writer and timeline reload hook -- `apps/ios-app/App/Widgets/FireWidgetEntry.swift` — Timeline entry and provider types -- `apps/ios-app/App/Widgets/FireWidgetBundle.swift` — Widget extension entry point -- `apps/ios-app/App/Widgets/FireWidgetViews.swift` — Shared WidgetKit view helpers -- `apps/ios-app/App/Widgets/FireSmallWidget.swift` — Small unread count widget -- `apps/ios-app/App/Widgets/FireMediumWidget.swift` — Medium trending topics widget -- `apps/ios-app/App/Widgets/FireLargeWidget.swift` — Large timeline widget -- `apps/ios-app/App/ViewModels/FireAppViewModel.swift` — Widget data update, deep link handler -- `apps/android-app/src/main/java/com/fire/app/widget/FireWidgetData.kt` — Android widget shared state -- `apps/android-app/src/main/java/com/fire/app/widget/FireUnreadWidgetProvider.kt` — Unread count `RemoteViews` widget -- `apps/android-app/src/main/java/com/fire/app/widget/FireTopicListWidgetProvider.kt` — Topic list `RemoteViews` widget -- `apps/android-app/src/main/res/layout/widget_unread.xml` — Unread-count widget layout -- `apps/android-app/src/main/res/layout/widget_topic_list.xml` — Topic-list widget layout -- `apps/android-app/src/main/res/drawable/bg_widget_panel.xml` — Shared widget panel background -- `apps/android-app/src/main/res/xml/fire_unread_widget_info.xml` — Widget metadata -- `apps/android-app/src/main/res/xml/fire_topic_list_widget_info.xml` — Widget metadata -- `apps/android-app/src/main/AndroidManifest.xml` — Android widget receivers and notification deep link -- `apps/android-app/src/main/java/com/fire/app/MainActivity.kt` — Widget notification deep-link handling -- `apps/android-app/src/main/java/com/fire/app/data/paging/TopicListPagingSource.kt` — First-page topic rows for widget updates -- `apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt` — Topic-list widget snapshot updates -- `apps/android-app/src/main/java/com/fire/app/ui/notifications/NotificationsViewModel.kt` — Unread widget snapshot updates -- `apps/ios-app/App/FireMotion/FireMotionEffects.swift` — Shared SwiftUI feedback modifiers and UIKit haptic bridge -- `apps/ios-app/App/Views/Other/FireTabRoot.swift` — Add haptics to tab switch -- `apps/ios-app/App/ListKit/FireDiffableListController.swift` — Add haptic to pull-to-refresh completion -- `apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift` — Add haptics to native Texture post interactions -- `crates/fire-store/src/migrations.rs` — Migration 4 for topic/notification cache -- `crates/fire-store/src/lib.rs` — Cache read/write methods -- `crates/fire-core/src/core/topics.rs` — Read-through cache on fetch -- `crates/fire-core/src/core/notifications.rs` — Read-through cache on fetch -- `apps/ios-app/App/Core/FireOfflineBanner.swift` — Offline mode banner component -- `apps/ios-app/App/Stores/FireHomeFeedStore.swift` — Offline state tracking -- `apps/ios-app/App/Stores/FireNotificationStore.swift` — Offline state tracking -- `apps/android-app/src/main/java/com/fire/app/data/paging/TopicListPagingSource.kt` — Cache fallback -- `apps/android-app/src/main/java/com/fire/app/data/paging/NotificationPagingSource.kt` — Cache fallback -- `apps/android-app/src/main/java/com/fire/app/core/ui/FireOfflineBanner.kt` — Offline banner view -- `apps/android-app/src/main/java/com/fire/app/core/ui/ShimmerLayout.kt` — Shimmer animation layout -- `apps/android-app/src/main/res/layout/item_topic_shimmer.xml` — Shimmer item layout -- `apps/ios-app/App/Core/FireShimmerModifier.swift` — SwiftUI shimmer animation modifier -- `apps/ios-app/App/Core/FireComponents.swift` — Shared SwiftUI skeleton row components -- `apps/ios-app/App/Intents/FireShortcuts.swift` — App Shortcuts provider -- `apps/ios-app/App/Intents/FireViewUnreadIntent.swift` — View unread intent -- `apps/ios-app/App/Intents/FireSearchTopicsIntent.swift` — Search intent -- `apps/ios-app/App/Intents/FireViewProfileIntent.swift` — View profile intent -- `apps/android-app/src/main/java/com/fire/app/core/theme/FireColors.kt` — Dynamic Color accent resolution -- `apps/android-app/src/main/java/com/fire/app/FireApplication.kt` — Dynamic Color initialization -- `apps/android-app/src/main/java/com/fire/app/MainActivity.kt` — Edge-to-edge -- `apps/ios-app/App/Core/FireOledTheme.swift` — OLED pure black color overrides -- `apps/ios-app/App/Core/FireTheme.swift` — OLED mode integration diff --git a/docs/superpowers/plans/2026-06-08-p4-release-preparation.md b/docs/superpowers/plans/2026-06-08-p4-release-preparation.md deleted file mode 100644 index be556545..00000000 --- a/docs/superpowers/plans/2026-06-08-p4-release-preparation.md +++ /dev/null @@ -1,279 +0,0 @@ -# Prepare Fire Release Materials - -> **For agentic workers:** Use this plan as the P4 release-preparation source of truth. Checkbox state tracks repository artifacts only; store-console actions, real screenshots/videos, legal review, device benchmarks, and accessibility audits remain manual gates. - -## Feasibility Assessment - -P4 is process-heavy and does not require changes to the Rust/native architecture. The repository can hold listing drafts, privacy/data-safety drafts, benchmark scripts, accessibility checklists, license inventories, and marketing asset folders now. Final App Store / Play Store readiness still requires human store access and real-device validation. Feasible with caveats: repository scaffolding is complete, but release acceptance remains blocked on manual evidence. - -## Current Surface Inventory - -- `docs/release/` -- release copy, compliance drafts, testing guides, benchmark definitions, accessibility checklist, release-gate evidence register, and license inventory. -- `apps/ios-app/marketing/` -- App Store screenshot and preview-video folder structure. -- `apps/android-app/marketing/` -- Play Store screenshot and feature-graphic folder structure. -- `scripts/ios/archive_release.sh` -- existing iOS archive/upload path used by the TestFlight guide. -- `scripts/ios/verify_xcode26_toolchain.sh` -- existing App Store Connect toolchain guard used before iOS uploads. -- `scripts/collect-licenses.sh` -- generated third-party dependency inventory. -- `scripts/verify-marketing-assets.sh` -- store marketing asset verifier for final screenshots, optional App Preview file placement, and Play feature-graphic dimensions. -- `scripts/verify-performance-benchmarks.sh` -- release benchmark evidence verifier for physical-device iOS and Android result rows. -- `scripts/verify-accessibility-audit.sh` -- release accessibility evidence verifier for physical-device iOS and Android screen/audit rows. -- `scripts/verify-internal-testing-evidence.sh` -- internal testing evidence verifier for store records, uploaded builds, tester invites, and feedback triage. -- `scripts/verify-privacy-review-evidence.sh` -- maintainer/legal privacy review evidence verifier. -- `scripts/verify-p4-release-evidence-suite.sh` -- shared non-recursive P4 evidence verifier for store media, performance, accessibility, internal testing, privacy review, and release-gate evidence. -- `scripts/verify-release-readiness.sh` -- composite P4 release-readiness verifier that runs the shared P4 evidence suite and roadmap guards. -- `scripts/verify-release-gates.sh` -- release-gate evidence verifier for the exact required manual gate set. -- `scripts/verify-roadmap-plan-contract.sh` -- roadmap document contract verifier for the one-spec/four-plan task counts. -- `scripts/verify-roadmap-architecture-constraints.sh` -- roadmap architecture/platform-boundary verifier for minimum APIs, native runtime paths, and reference boundaries. -- `scripts/verify-roadmap-implementation-evidence.sh` -- checked P1-P3 roadmap implementation evidence verifier. -- `scripts/verify-roadmap-p4-acceptance.sh` -- roadmap P4 acceptance verifier that keeps checked boxes tied to the shared P4 evidence suite. -- `scripts/test-release-verifiers.sh` -- temporary-fixture regression tests for release-readiness wrapper wiring, release evidence parsers, fake-evidence markers, marketing asset validation, and checked P4 acceptance guards. -- `scripts/benchmark-*.sh` -- benchmark workflows for cold start, scroll fluency, topic load, and memory. -- `apps/android-app/src/main/AndroidManifest.xml` -- Android backup is release-disabled with `allowBackup="false"`. -- `apps/android-app/src/main/res/xml/backup_rules.xml` -- all-exclude Android Auto Backup rules. -- `apps/android-app/src/main/res/xml/data_extraction_rules.xml` -- all-exclude Android cloud-backup and device-transfer rules. -- `apps/ios-app/Configs/PrivacyInfo.xcprivacy` -- app privacy manifest with required-reason API declarations. -- `apps/ios-app/Configs/FireWidget/PrivacyInfo.xcprivacy` -- widget extension privacy manifest with required-reason API declarations. -- `apps/ios-app/Sources/FireAppSession/APM/FireAPMManager.swift` -- local PLCrashReporter / MetricKit diagnostic behavior. -- `apps/ios-app/App/DeveloperTools/FirePushDiagnosticsView.swift` -- APNs token is local-only at this stage. -- `apps/android-app/src/main/java/com/fire/app/push/FireFirebaseMessagingService.kt` -- FCM token registration API is not available; payloads are local notification input. -- `crates/fire-core/tests/session_flow.rs` -- verifies that redacted session export strips auth cookies while preserving bootstrap context. - -## Design - -### Key Design Decisions - -1. **Version release source material, not fake final media.** The repo now includes marketing directories and `.gitkeep` placeholders, but no fabricated screenshots, preview videos, or feature graphics. Real assets must come from release-candidate builds. -2. **Keep privacy drafts conservative.** Privacy documents state local diagnostics, widget snapshots, offline cache, local push token handling, Android backup exclusion, privacy-manifest coverage, and redacted-export behavior without overclaiming legal review. -3. **Make benchmark scripts honest about prerequisites.** Android scripts use `adb` when available; iOS scripts print required Instruments/xctrace workflows because reliable iOS FPS/memory/topic measurements require device tooling. -4. **Generate license inventory from current declarations.** `scripts/collect-licenses.sh` uses `cargo metadata --locked` for Rust crate license fields and resolves Android `releaseRuntimeClasspath` with Gradle before reading Maven POM license metadata. Full legal review and Swift package license-text review remain required. -5. **Separate repository completion from release acceptance.** P4 acceptance boxes in the roadmap remain unchecked until real store/test/performance/accessibility evidence exists. -6. **Keep manual gate evidence centralized.** `docs/release/release-gate-evidence.md` is the register for screenshots, store records, legal signoff, release-build benchmarks, accessibility audit runs, and any accepted waivers. It does not satisfy those gates by itself. -7. **Make the final release gate fail closed.** `scripts/verify-release-gates.sh` checks the evidence register and fails until the exact required gate rows are present once, with no unknown rows, and every row has an accepted/completed status, owner, evidence link, and real calendar date. `Accepted` release-gate waivers must include explicit approval/waiver context plus a reason in notes, such as `Approved by ...; reason: ...`. Evidence links must be well-formed HTTP(S) URLs with fully qualified hostnames or safe repo-relative paths to non-empty local files, not directories, and malformed URLs, malformed URL hosts, single-label URL hosts, or placeholder URL hosts are rejected. Manual evidence verifiers reject completed or accepted rows that still contain fake/mock/placeholder-style markers in completion metadata such as owner, reviewer, tester, device, result, evidence link, or notes, and reject missing or extra Markdown table columns; literal pipe characters must be escaped in cells. Current failure is expected because manual gates are still open. -8. **Make store-media structure checkable before evidence closure.** `scripts/verify-marketing-assets.sh` validates that required screenshot buckets contain real PNG/JPEG files with readable dimensions, final asset filenames do not carry fake/mock/placeholder-style markers, screenshots are at least 320px on each side, PNG screenshots are not single-color placeholders, screenshot buckets do not contain nested directories or alternate asset paths, the optional App Preview path is unambiguous and contains MP4 `ftyp` content when present, and the Play feature graphic is PNG content with exact `1024x500` dimensions and non-flat pixels. The script is expected to fail until final release-candidate media exists. -9. **Make benchmark evidence complete by metric and platform.** `scripts/verify-performance-benchmarks.sh` checks `performance-benchmarks.md` for exactly one iOS row and exactly one Android release-build physical-device row for every target metric, requires metric-bound numeric result units, rejects ambiguous multi-value memory results unless the peak value is labeled, treats the highest labeled peak memory value as authoritative, and fails until threshold failures are fixed or explicitly accepted with approval/waiver context plus a reason in notes. -10. **Make accessibility evidence complete by screen and audit area.** `scripts/verify-accessibility-audit.sh` checks `accessibility-audit-checklist.md` for exactly one iOS row and exactly one Android physical-device row covering every listed screen and audit category, and fails until blocking failures are fixed or explicitly accepted with explicit approval/waiver context plus a reason in notes. -11. **Make testing-track evidence explicit.** `docs/release/internal-testing-evidence.md` records App Store Connect / Play Console records, release-candidate uploads, tester invites, and feedback triage. `scripts/verify-internal-testing-evidence.sh` fails until all required platform rows are complete and non-duplicated, requires evidence links to be fully qualified HTTP(S) URLs or existing local files, requires build numbers, commit SHAs, invite dates, and numeric blocker counts, and requires accepted rows to include explicit approval/waiver context plus a reason in notes. -12. **Make privacy review evidence explicit.** `docs/release/privacy-review-evidence.md` records maintainer/legal review of the privacy policy, store answers, backup behavior, diagnostic redaction, privacy manifests, license inventory, and final publication approval. `scripts/verify-privacy-review-evidence.sh` fails until all required review rows are complete and non-duplicated, requires evidence links to be fully qualified HTTP(S) URLs or existing local files, requires final publication approval wording, and requires accepted rows to include explicit approval/waiver context plus a reason in notes. -13. **Make final readiness one command.** `scripts/verify-release-readiness.sh` runs the shared P4 release evidence suite, roadmap plan contract, roadmap architecture constraints, roadmap implementation evidence, and roadmap P4 acceptance verifiers together. It does not replace any underlying gate; it fails until every lower-level verifier passes. -14. **Keep the roadmap document contract checkable.** `scripts/verify-roadmap-plan-contract.sh` verifies the one design spec and four implementation plans stay present with P1/P2/P3/P4 top-level task counts of 17/14/15/6. -15. **Keep architecture constraints evidence-bound.** `scripts/verify-roadmap-architecture-constraints.sh` checks the platform/Rust ownership split, minimum API targets, iOS topic-detail native runtime path, and reference/infrastructure repository boundaries. -16. **Keep checked implementation acceptance evidence-bound.** `scripts/verify-roadmap-implementation-evidence.sh` checks concrete code files, symbols, scoped cleanup patterns, and size limits that support the checked P1-P3 acceptance rows. -17. **Keep roadmap P4 acceptance evidence-bound.** `scripts/verify-roadmap-p4-acceptance.sh` checks the exact P4 acceptance rows in the design document and fails if any box is checked before the shared P4 evidence suite passes. - -## Phased Implementation - -### Task 1: Store Listing Drafts And Marketing Structure - -**Files:** -- `docs/release/app-store-description.md` -- `docs/release/play-store-description.md` -- `apps/ios-app/marketing/README.md` -- `apps/ios-app/marketing/screenshots/iPhone6.5/.gitkeep` -- `apps/ios-app/marketing/screenshots/iPhone5.5/.gitkeep` -- `apps/ios-app/marketing/screenshots/iPad12.9/.gitkeep` -- `apps/ios-app/marketing/screenshots/iPad11/.gitkeep` -- `apps/ios-app/marketing/preview-video/.gitkeep` -- `apps/android-app/marketing/README.md` -- `apps/android-app/marketing/screenshots/phone/.gitkeep` -- `apps/android-app/marketing/screenshots/tablet7/.gitkeep` -- `apps/android-app/marketing/screenshots/tablet10/.gitkeep` -- `scripts/verify-marketing-assets.sh` - -- [x] Create App Store and Play Store listing drafts. -- [x] Create iOS and Android marketing asset folder structures. -- [x] Document that real release-candidate media is still required. -- [x] Add a store marketing asset verifier that fails until final assets exist. -- [ ] Capture and validate final App Store screenshots. -- [ ] Capture or decide not to ship an App Preview video. -- [ ] Capture and validate final Play Store screenshots. -- [ ] Create and approve the Play Store 1024x500 feature graphic. - -### Task 2: Privacy, Data Safety, And Licenses - -**Files:** -- `docs/release/privacy-policy.md` -- `docs/release/app-store-data-collection.md` -- `docs/release/play-store-data-safety.md` -- `docs/release/third-party-licenses.md` -- `docs/release/privacy-review-evidence.md` -- `scripts/collect-licenses.sh` -- `scripts/verify-privacy-review-evidence.sh` -- `apps/android-app/src/main/AndroidManifest.xml` -- `apps/android-app/src/main/res/xml/backup_rules.xml` -- `apps/android-app/src/main/res/xml/data_extraction_rules.xml` -- `apps/ios-app/Configs/PrivacyInfo.xcprivacy` -- `apps/ios-app/Configs/FireWidget/PrivacyInfo.xcprivacy` -- `apps/ios-app/project.yml` -- `crates/fire-core/src/core/persistence.rs` -- `crates/fire-core/src/session_store.rs` -- `crates/fire-core/tests/session_flow.rs` - -- [x] Create privacy policy draft aligned with current code facts. -- [x] Create App Store privacy questionnaire draft. -- [x] Create Play Store Data Safety draft. -- [x] Add license collection script. -- [x] Generate current third-party dependency inventory. -- [x] Generate Rust crate license names from `cargo metadata --locked`. -- [x] Verify Android transitive license metadata with Gradle tooling. -- [x] Add a maintainer/legal privacy review evidence log and verifier. -- [ ] Complete maintainer/legal privacy review. -- [x] Decide Android `allowBackup` release behavior and update docs/store answers. -- [x] Add iOS app and widget privacy manifests with required-reason API declarations. -- [x] Fix redacted session export before any public diagnostic workflow claims redaction. - -### Task 3: Internal Testing Guides And Readiness Guards - -**Files:** -- `docs/release/testflight-setup.md` -- `docs/release/play-store-testing-setup.md` -- `docs/release/internal-testing-evidence.md` -- `docs/release/test-feedback-template.md` -- `docs/release/release-gate-evidence.md` -- `scripts/verify-internal-testing-evidence.sh` -- `scripts/verify-release-gates.sh` -- `scripts/verify-release-readiness.sh` -- `scripts/verify-p4-release-evidence-suite.sh` -- `scripts/verify-roadmap-plan-contract.sh` -- `scripts/verify-roadmap-architecture-constraints.sh` -- `scripts/verify-roadmap-implementation-evidence.sh` -- `scripts/verify-roadmap-p4-acceptance.sh` -- `scripts/test-release-verifiers.sh` - -- [x] Document TestFlight build/upload flow using existing iOS release scripts. -- [x] Document Play Store internal/closed/open testing setup. -- [x] Add a tester feedback template. -- [x] Add a release-gate evidence register for manual P4 gates. -- [x] Add a verifier that fails until manual gate evidence is complete. -- [x] Add an internal testing evidence log and verifier for store/test-track gates. -- [x] Add a composite release-readiness verifier that runs every P4 guard. -- [x] Add a roadmap plan contract verifier for the one-spec/four-plan task counts. -- [x] Add a roadmap architecture constraints verifier for platform/Rust ownership, minimum APIs, topic-detail native runtime paths, and reference boundaries. -- [x] Add a roadmap implementation evidence verifier for checked P1-P3 acceptance rows. -- [x] Add a roadmap P4 acceptance verifier that blocks premature checkbox closure. -- [ ] Create App Store Connect app record. -- [ ] Create Play Console app record. -- [ ] Upload release-candidate builds to internal testing tracks. -- [ ] Invite testers and collect feedback. - -### Task 4: Performance Regression Gates - -**Files:** -- `docs/release/performance-benchmarks.md` -- `scripts/benchmark-cold-start.sh` -- `scripts/benchmark-scroll-fps.sh` -- `scripts/benchmark-topic-load.sh` -- `scripts/benchmark-memory-peak.sh` -- `scripts/verify-performance-benchmarks.sh` - -- [x] Define release benchmark targets and failure thresholds. -- [x] Add Android `adb` benchmark workflows. -- [x] Add iOS measurement workflows for Instruments/xctrace. -- [x] Add a performance benchmark evidence verifier that fails until final physical-device results exist. -- [ ] Record release-build iOS measurements on a physical device. -- [ ] Record release-build Android measurements on a physical device. -- [ ] Resolve or explicitly accept any threshold failures. - -### Task 5: Accessibility Audit - -**Files:** -- `docs/release/accessibility-audit-checklist.md` -- `scripts/verify-accessibility-audit.sh` - -- [x] Add a cross-platform accessibility audit checklist. -- [x] Add an accessibility audit evidence verifier that fails until final physical-device results exist. -- [ ] Run VoiceOver full-flow audit. -- [ ] Run TalkBack full-flow audit. -- [ ] Run Dynamic Type / font-scale audit. -- [ ] Run Reduce Motion and haptic audit. -- [ ] Run high-contrast and color-blindness checks. -- [ ] Record results and fix blocking failures. - -### Task 6: Final P4 Evidence Closure - -**Files:** -- `docs/release/release-gate-evidence.md` -- `docs/superpowers/specs/2026-06-08-fire-v2-roadmap-design.md` -- `scripts/verify-release-readiness.sh` - -- [ ] Populate every manual release-gate evidence row with owner, evidence link, date, and `Complete` or accepted-waiver status. -- [ ] Run `scripts/verify-release-readiness.sh` and confirm all lower-level release guards pass. -- [ ] Check the P4 roadmap acceptance boxes only after release readiness passes. - -## Architectural Notes - -- No Rust/native architecture changes are part of P4 release-prep scaffolding. -- The platform/Rust ownership split remains unchanged. -- `references/fluxdo/` and `third_party/` are not edited by this plan. -- Generated release media is intentionally absent until captured from real release-candidate builds. -- Privacy and data-safety drafts are conservative working documents, not final legal text. -- `docs/release/release-gate-evidence.md` tracks manual gate proof, but rows start as `Not started` and must be updated by the humans or release engineers who perform those actions. -- `scripts/verify-marketing-assets.sh` is expected to fail while marketing folders contain only `.gitkeep` placeholders, while PNG assets are flat single-color placeholders, while final asset filenames still contain fake/mock/placeholder-style markers, while screenshot folders contain nested directories or alternate asset paths, or while screenshot/feature-graphic dimensions do not match the release constraints; it is a precondition for store-media evidence closure, not a replacement for human asset review. -- `scripts/verify-performance-benchmarks.sh` is expected to fail while benchmark results are absent; it is a precondition for performance evidence closure, not a substitute for release-build physical-device measurement. -- `scripts/verify-accessibility-audit.sh` is expected to fail while accessibility results are absent; it is a precondition for accessibility evidence closure, not a substitute for a release-candidate assistive-technology audit. -- `scripts/verify-internal-testing-evidence.sh` is expected to fail while store records, uploaded builds, tester invites, or feedback triage rows are absent; it is a precondition for internal-testing evidence closure, not a substitute for store-console access. -- `scripts/verify-privacy-review-evidence.sh` is expected to fail while maintainer/legal review evidence is absent; it is a precondition for privacy evidence closure, not a substitute for legal approval. -- `scripts/verify-release-readiness.sh` is expected to fail while any lower-level P4 verifier fails; it is the final repo-owned readiness command before changing roadmap P4 acceptance. -- `scripts/verify-p4-release-evidence-suite.sh` is expected to fail while any store-media, performance, accessibility, internal-testing, privacy-review, or release-gate evidence verifier fails; it is shared by release readiness and checked roadmap P4 acceptance. -- `scripts/verify-release-gates.sh` is expected to fail until the manual P4 evidence rows are populated, and it also fails if required gate rows are renamed, duplicated, missing, or unknown; this is a release guard, not a development-test failure. -- Manual evidence verifiers are expected to fail if completed or accepted evidence rows still contain fake, mock, placeholder, dummy, synthetic, TODO/TBD, `example.com`, `not-real`, or `not real` markers in owner, reviewer, tester, device, result, evidence-link, or notes metadata, if evidence links are dead local paths, local directories, malformed URLs, malformed URL hosts, single-label URL hosts, or placeholder URL hosts, if dates are impossible calendar dates or future dates, if rows have missing or extra Markdown table columns, if required manual evidence rows, platform/metric benchmark rows, or platform/screen and platform/audit accessibility rows are duplicated, if performance results lack metric-bound numeric units, leave multi-value memory results ambiguous, or hide a threshold miss behind a lower non-peak memory value, or if accepted waiver notes lack explicit approval/waiver context plus a reason, risk, exception, or no-ship decision. -- `scripts/verify-roadmap-plan-contract.sh` is expected to pass while the roadmap document set keeps one spec, four implementation plans, and the agreed 17/14/15/6 top-level task split. -- `scripts/verify-roadmap-architecture-constraints.sh` is expected to pass while the platform/Rust ownership split, minimum API targets, iOS topic-detail native runtime path, and reference/infrastructure boundaries stay intact. -- `scripts/verify-roadmap-implementation-evidence.sh` is expected to pass while checked P1-P3 acceptance code paths remain present; it does not prove P4 release readiness. -- `scripts/verify-roadmap-p4-acceptance.sh` is expected to pass while P4 roadmap acceptance remains unchecked, and to fail if any acceptance box is checked before the shared P4 evidence suite passes. -- `scripts/test-release-verifiers.sh` is expected to pass without real manual evidence because it uses isolated temporary fixtures to regression-test the release verifiers themselves, including release-readiness wrapper wiring, fake-evidence marker rejection, malformed store-media failures, flat PNG placeholder rejection, non-measurement performance results, target misses marked `Pass`, ambiguous or misleading multi-value memory results, duplicate manual evidence rows, duplicate performance/accessibility screen or audit coverage rows, invalid or future dates, placeholder metadata fields, dead local evidence paths, malformed evidence URLs, malformed URL hosts, single-label URL hosts, placeholder URL hosts, extra Markdown table columns, missing Markdown table boundaries, weak accepted-waiver notes, and weak internal-testing/privacy metadata. -- Roadmap P4 acceptance remains unchecked until manual evidence exists. - -## File Change Summary - -- `docs/release/README.md` -- release materials index and manual-gate note. -- `docs/release/accessibility-audit-checklist.md` -- cross-platform accessibility release checklist. -- `docs/release/app-store-data-collection.md` -- App Store privacy questionnaire draft. -- `docs/release/app-store-description.md` -- App Store listing draft. -- `docs/release/internal-testing-evidence.md` -- store records, release-candidate uploads, tester invites, and feedback-triage evidence log. -- `docs/release/performance-benchmarks.md` -- benchmark targets and results log. -- `docs/release/play-store-data-safety.md` -- Play Store data-safety draft. -- `docs/release/play-store-description.md` -- Play Store listing draft. -- `docs/release/play-store-testing-setup.md` -- Play Store testing guide. -- `docs/release/privacy-policy.md` -- privacy policy draft aligned to current code. -- `docs/release/privacy-review-evidence.md` -- maintainer/legal privacy review evidence log. -- `docs/release/release-gate-evidence.md` -- manual P4 gate evidence register. -- `docs/release/test-feedback-template.md` -- beta feedback template. -- `docs/release/testflight-setup.md` -- TestFlight setup guide. -- `docs/release/third-party-licenses.md` -- generated dependency inventory. -- `apps/android-app/marketing/README.md` -- Play Store asset requirements. -- `apps/android-app/marketing/screenshots/phone/.gitkeep` -- phone screenshot folder placeholder. -- `apps/android-app/marketing/screenshots/tablet7/.gitkeep` -- 7" tablet screenshot folder placeholder. -- `apps/android-app/marketing/screenshots/tablet10/.gitkeep` -- 10" tablet screenshot folder placeholder. -- `apps/android-app/src/main/AndroidManifest.xml` -- disables Android backup for release. -- `apps/android-app/src/main/res/xml/backup_rules.xml` -- excludes all app data from legacy Auto Backup. -- `apps/android-app/src/main/res/xml/data_extraction_rules.xml` -- excludes all app data from Android cloud backup and device transfer. -- `apps/ios-app/Configs/FireWidget/PrivacyInfo.xcprivacy` -- widget privacy manifest with UserDefaults required-reason declarations. -- `apps/ios-app/Configs/PrivacyInfo.xcprivacy` -- app privacy manifest with required-reason declarations. -- `apps/ios-app/project.yml` -- wires privacy manifests into the app and widget resource phases. -- `apps/ios-app/marketing/README.md` -- App Store asset requirements. -- `apps/ios-app/marketing/preview-video/.gitkeep` -- App Preview folder placeholder. -- `apps/ios-app/marketing/screenshots/iPad11/.gitkeep` -- iPad 11" screenshot folder placeholder. -- `apps/ios-app/marketing/screenshots/iPad12.9/.gitkeep` -- iPad 12.9" screenshot folder placeholder. -- `apps/ios-app/marketing/screenshots/iPhone5.5/.gitkeep` -- iPhone 5.5" screenshot folder placeholder. -- `apps/ios-app/marketing/screenshots/iPhone6.5/.gitkeep` -- iPhone 6.5" screenshot folder placeholder. -- `scripts/benchmark-cold-start.sh` -- cold-start benchmark workflow. -- `scripts/benchmark-memory-peak.sh` -- memory benchmark workflow. -- `scripts/benchmark-scroll-fps.sh` -- scroll fluency benchmark workflow. -- `scripts/benchmark-topic-load.sh` -- topic detail load benchmark workflow. -- `scripts/collect-licenses.sh` -- dependency license inventory generator. -- `scripts/verify-accessibility-audit.sh` -- verifies release accessibility result rows across iOS and Android screens and audit categories. -- `scripts/verify-internal-testing-evidence.sh` -- verifies internal testing evidence rows across iOS and Android store/test-track gates. -- `scripts/verify-marketing-assets.sh` -- validates final store screenshot files, optional App Preview placement, and Play feature-graphic dimensions. -- `scripts/verify-performance-benchmarks.sh` -- verifies release benchmark result rows across iOS and Android target metrics. -- `scripts/verify-privacy-review-evidence.sh` -- verifies maintainer/legal privacy review evidence rows. -- `scripts/verify-release-readiness.sh` -- runs all P4 release-readiness verifiers as one final command. -- `scripts/verify-p4-release-evidence-suite.sh` -- runs the non-recursive lower-level P4 evidence suite used by readiness and checked acceptance guards. -- `scripts/verify-release-gates.sh` -- verifies exact manual P4 gate rows and required completion metadata. -- `scripts/verify-roadmap-plan-contract.sh` -- verifies the roadmap spec/plan set and expected top-level task counts. -- `scripts/verify-roadmap-architecture-constraints.sh` -- verifies minimum API targets, platform/Rust ownership boundaries, the iOS topic-detail native runtime path, and reference/infrastructure repository boundaries. -- `scripts/verify-roadmap-implementation-evidence.sh` -- verifies checked P1-P3 acceptance code evidence remains present. -- `scripts/verify-roadmap-p4-acceptance.sh` -- verifies exact roadmap P4 acceptance rows and requires the shared P4 evidence suite before checked acceptance. -- `scripts/test-release-verifiers.sh` -- regression-tests release verifier failure modes with temporary fixtures, including release-readiness wrapper wiring, fake evidence, and malformed store-media cases. -- `crates/fire-core/src/core/persistence.rs` -- writes redacted session exports through the redacted envelope. -- `crates/fire-core/src/session_store.rs` -- creates versioned redacted envelopes with auth cookies stripped. -- `crates/fire-core/tests/session_flow.rs` -- covers redacted JSON and file persistence restore behavior. diff --git a/docs/superpowers/plans/2026-06-13-ios16-uikit-root-contract.md b/docs/superpowers/plans/2026-06-13-ios16-uikit-root-contract.md deleted file mode 100644 index 730a8447..00000000 --- a/docs/superpowers/plans/2026-06-13-ios16-uikit-root-contract.md +++ /dev/null @@ -1,110 +0,0 @@ -# iOS 16 UIKit Root Contract - -**Status:** Started -**Goal:** Move Fire's production iOS surface to iOS 16-compatible UIKit/Texture -runtime ownership while keeping Rust as the only product logic engine. - -## Scope - -This plan starts the larger SwiftUI retirement effort with a narrow first PR: - -- Lower the iOS app, widget extension, tests, and UniFFI cross-build defaults to - iOS 16. -- Remove iOS 17-only SwiftUI APIs from shared host code that still compiles in - production targets. -- Update architecture guardrails so future work cannot drift back to an iOS 17 - or SwiftUI-root assumption. -- Document the migration order for the larger UIKit root and screen work. - -It intentionally does not rewrite every SwiftUI screen in the first PR. The -current repository still has transitional SwiftUI production views, and deleting -them safely depends on replacing the app root/navigation shell first. - -## Architecture Contract - -- UIKit + Texture is the production iOS runtime. -- iOS 16 is the minimum supported app, widget, and test deployment target. -- SwiftUI is allowed only for WidgetKit, Developer Tools, and explicitly tracked - transitional bridges during migration. -- AppKit support must reuse the same Rust snapshot and command contracts as - UIKit; it must not add a parallel product-logic path. -- Rust continues to own session, API orchestration, pagination/cache semantics, - rich-text semantics, MessageBus, networking, and logging. - -## Workstreams - -### 1. Root Shell - -Replace the SwiftUI `FireTabRoot` ownership boundary with: - -- `FireSceneDelegate` -- `FireRootCoordinator` -- `FireMainTabBarController` -- one `UINavigationController` per production tab -- UIKit-owned auth/preheat/login presentations - -This workstream must land before broad screen migration, because route handling, -deep links, notification taps, APM route labels, and auth-state transitions all -currently converge in the SwiftUI root. - -Topic route presentation now uses the selected tab's UIKit navigation stack -instead of a root-level full-screen modal navigation controller. The legacy -`FirePresentedTopicRouteHost`, modal topic navigation factory, and presented -route navigation controller were removed. `FireMainNavigationController` is the -single tab navigation owner; it centralizes root navigation-bar visibility and -owns the full-screen `UIPercentDrivenInteractiveTransition` pop gesture. - -### 2. UIKit List Runtime - -Promote the current `FireDiffableListController` from a SwiftUI -`UIViewControllerRepresentable` bridge into the primary UIKit list runtime. -Migrate high-traffic list surfaces first: - -- Home (landed: tab root now uses `FireHomeViewController`; the topic list, filters, pagination, offline banner, and topic menus run on `FireListViewController`; the former SwiftUI production page and `FireHomeCollectionView` bridge were removed; category/tag sheets and bookmark editing remain tracked transitional SwiftUI presentations) -- Notifications (landed: tab root now uses `FireNotificationsViewController`; full history uses `FireNotificationHistoryViewController`; both run on `FireListViewController` and the SwiftUI production pages were removed) -- Search (landed: `FireSearchViewController` on `FireListViewController`; the SwiftUI production page and SwiftUI result rows were removed; bookmark editor remains a tracked transitional SwiftUI presentation) -- Messages (landed: `FirePrivateMessagesViewController` on `FireListViewController`; new private messages now open `FireComposerViewController`; Profile keeps only a thin SwiftUI-to-UIKit host until Profile itself migrates) -- Bookmarks (landed: `FireBookmarksViewController` on `FireListViewController`; Profile keeps only a thin SwiftUI-to-UIKit host until Profile itself migrates) -- Read history (landed: `FireReadHistoryViewController` on `FireListViewController`; Profile keeps only a thin SwiftUI-to-UIKit host until Profile itself migrates) -- Drafts (landed: `FireDraftsViewController` on `FireListViewController`; draft continuation now opens `FireComposerViewController`; Profile keeps only a thin SwiftUI-to-UIKit host until Profile itself migrates) - -Each migrated screen should delete its previous production SwiftUI page instead -of leaving a fallback. - -### 3. Auth and Composer - -- Login WebView (landed: `FireLoginWebViewController` now owns the UIKit - `WKWebView`, navigation chrome, readiness state, credential capture, and - completion action; the former SwiftUI auth screen and `UIViewRepresentable` - login bridge were removed) -- Cloudflare foreground challenge (landed: `FireCloudflareChallengeViewController` - remains the platform-owned UIKit WebView challenge path) -- Onboarding (landed: `FireOnboardingViewController` is the unauthenticated - UIKit root; Developer Tools remains a tracked SwiftUI exception) -- Composer (landed: `FireComposerViewController` owns native text input, - markdown toolbar actions, category/tag/recipient/mention search, draft - recovery/autosave, platform photo picking, image upload insertion, and - create-topic/reply/private-message submission. Home, Messages, Drafts, Topic - detail, and Public Profile now open the UIKit runtime; the old SwiftUI - `FireComposerView` page has been deleted; Public Profile still uses a - temporary SwiftUI-to-UIKit host until Profile itself migrates.) - -### 4. Profile and Secondary Surfaces - -Migrate profile, badges, LDC/CDK, invite links, categories, and other secondary -production views after the root/list runtime is stable. Developer Tools can -remain SwiftUI until the production path is complete. - -## Verification - -- `scripts/verify-roadmap-architecture-constraints.sh` -- `rg 'deploymentTarget: "17\.0"|IPHONEOS_DEPLOYMENT_TARGET.*17\.0' apps/ios-app` -- `rg 'sensoryFeedback|\.onChange\(of:.*\) \{ _,' apps/ios-app/App -g '*.swift'` -- iOS build with `CODE_SIGNING_ALLOWED=NO` - -## Follow-Up PRs - -1. `codex/ios-uikit-root-shell` -2. `codex/ios-uikit-list-runtime` -3. `codex/ios-uikit-auth-composer` -4. `codex/ios-uikit-profile-secondary` diff --git a/docs/superpowers/plans/2026-06-16-native-login-page-redesign.md b/docs/superpowers/plans/2026-06-16-native-login-page-redesign.md deleted file mode 100644 index 69a15482..00000000 --- a/docs/superpowers/plans/2026-06-16-native-login-page-redesign.md +++ /dev/null @@ -1,1880 +0,0 @@ -# Native Login Page Redesign Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Replace the monolithic `FireLoginWebViewController` with a pure-native `FireLoginViewController` ( UIKit programmatic ) + a separate `FireCaptchaLoginDialogController` for hCaptcha, fixing the login flow ordering so verification only happens after the user enters credentials and taps login. - -**Architecture:** Two-VC split aligned with fluxdo's `LoginPage` + `WebViewLoginDialog`. `FireLoginViewController` owns the native form, presents the captcha dialog, and coordinates the flow. `FireAppViewModel` exposes async capabilities (CF clearance, cookie priming, classify, finalize) but does NOT present UI. The captcha dialog keeps its WKWebView alive until `completeJsLogin` extracts cookies. - -**Tech Stack:** UIKit (programmatic), WKWebView, Rust/UniFFI boundary (unchanged), Texture (not used for login). - -**Spec:** `docs/superpowers/specs/2026-06-16-native-login-page-redesign-design.md` - ---- - -## File Structure - -| File | Responsibility | -|------|----------------| -| `apps/ios-app/App/Views/Other/FireLoginViewController.swift` | Pure-native login page: logo, credential inputs, remember-password checkbox, login button, forgot-password link, "other login methods" button. Presents captcha dialog + handles results. | -| `apps/ios-app/App/Views/Other/FireCaptchaLoginDialogController.swift` | Form-sheet dialog containing WKWebView for hCaptcha + `__fireLogin` execution. Exposes live `webView` for cookie extraction. Supports `retryWithSecondFactor`. | -| `apps/ios-app/App/ViewModels/FireAppViewModel.swift` | Modified: `openLogin()` simplified, new `ensureCloudflareClearance()` / `loginCoordinatorForDialog()` / `probeLoginSyncReadiness(from:)`, `completeMinimalLogin` gains `rememberCredential` param. | -| `apps/ios-app/App/Core/FireRootCoordinator.swift` | Modified: present `FireLoginViewController` instead of `FireLoginWebViewController`. | -| `apps/ios-app/App/Views/Other/FireLoginWebView.swift` | **Deleted.** | - -**Preserved (no changes):** -- `FireWebViewBrowserProfile.swift` — `minimalLoginHTML`, `__fireLogin`, `makeMinimalLoginConfiguration` -- `FireWebViewLoginCoordinator.swift` — `completeJsLogin(from:)`, `primeCookies(into:)` -- `FireSessionStore.swift` — `finalizeLoginFromWebView`, `classifyWebviewLoginResult`, `saveLoginCredential` -- `FireAuthCookieKeychainStore.swift` — `FireSavedCredential` -- `FireCloudflareChallengeCoordinator` — `completeManualVerification` -- All Rust/UniFFI boundary code - ---- - -## Phase 1: Native Login Page + Login Flow (Complete Deliverable) - -### Task 1: Create FireCaptchaLoginDialogController - -**Files:** -- Create: `apps/ios-app/App/Views/Other/FireCaptchaLoginDialogController.swift` - -**Context:** This dialog is a `.pageSheet` modal containing a WKWebView. It loads `FireLoginScripts.minimalLoginHTML` to render the hCaptcha widget. When hCaptcha passes, JS auto-calls `window.__fireLogin(id, pwd, token)` which does `fetch /session/csrf → POST /hcaptcha/create → POST /session.json`. Results come back via `webkit.messageHandlers.login_result`. The WKWebView must stay alive for cookie extraction by `completeJsLogin(from:)`. - -The dialog reuses `FireWebViewBrowserProfile.makeMinimalLoginConfiguration` and `FireLoginScripts.fireLoginInvocation` from the existing codebase. - -- [ ] **Step 1: Create the dialog VC skeleton** - -Create `apps/ios-app/App/Views/Other/FireCaptchaLoginDialogController.swift`: - -```swift -import UIKit -import WebKit - -/// Result delivered to the presenting VC when the login JS completes. -enum FireCaptchaDialogResult { - case success - case needSecondFactor(SecondFactorRequirementState) - case retryCloudflare - case failure(LoginFailureState) -} - -/// Form-sheet dialog that renders hCaptcha in a WKWebView and executes -/// `window.__fireLogin`. The WKWebView stays alive until the presenter -/// extracts cookies via `completeJsLogin(from:)`. -/// -/// On success the presenter MUST call `completeMinimalLogin(from: dialog.webView, ...)` -/// before dismissing this dialog — otherwise the live WebView is destroyed -/// and cookies cannot be extracted. -final class FireCaptchaLoginDialogController: UIViewController { - - // MARK: - Public Properties - - /// The live WKWebView. Presenters read cookies from this after `.success`. - private(set) var webView: WKWebView! - - // MARK: - Private Properties - - private let identifier: String - private let password: String - private let loginCoordinator: FireWebViewLoginCoordinator - private let onResult: (FireCaptchaDialogResult) -> Void - private let onCancel: () -> Void - - private var lastLoginHcaptchaToken: String? - private var lastLoginSecondFactorToken: String? - private var hasReportedResult = false - private var titleLabel: UILabel! - private var closeButton: UIButton! - private var statusLabel: UILabel! - private var activityIndicator: UIActivityIndicatorView! - - /// Set by the presenting VC before presenting. Called when JS posts - /// a login_result message to classify the raw phase/status/body. - var classifyResult: ((WebViewLoginPhaseState, UInt16, String) -> Void)? - - // MARK: - Init - - init( - identifier: String, - password: String, - loginCoordinator: FireWebViewLoginCoordinator, - onResult: @escaping (FireCaptchaDialogResult) -> Void, - onCancel: @escaping () -> Void - ) { - self.identifier = identifier - self.password = password - self.loginCoordinator = loginCoordinator - self.onResult = onResult - self.onCancel = onCancel - super.init(nibName: nil, bundle: nil) - modalPresentationStyle = .pageSheet - if let sheet = sheetPresentationController { - sheet.detents = [.medium(), .large()] - sheet.prefersGrabberVisible = true - sheet.prefersScrollingExpandsWhenScrolledToEdge = false - } - } - - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError() } - - // MARK: - Lifecycle - - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = .systemBackground - setupNavigationBar() - setupWebView() - setupStatusLabel() - loadMinimalLoginPage() - } - - // MARK: - Setup - - private func setupNavigationBar() { - let navBar = UINavigationBar() - navBar.translatesAutoresizingMaskIntoConstraints = false - let navItem = UINavigationItem(title: "安全验证") - let closeAction = UIAction(title: "关闭", image: UIImage(systemName: "xmark")) { [weak self] _ in - self?.handleCancel() - } - navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, primaryAction: closeAction) - navBar.items = [navItem] - view.addSubview(navBar) - - NSLayoutConstraint.activate([ - navBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - navBar.leadingAnchor.constraint(equalTo: view.leadingAnchor), - navBar.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) - } - - private func setupWebView() { - let configuration = FireWebViewBrowserProfile.makeMinimalLoginConfiguration( - messageHandler: FireCaptchaScriptMessageProxy(delegate: self) - ) - webView = WKWebView(frame: .zero, configuration: configuration) - webView.translatesAutoresizingMaskIntoConstraints = false - webView.scrollView.isScrollEnabled = false - view.addSubview(webView) - - NSLayoutConstraint.activate([ - webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 56), - webView.leadingAnchor.constraint(equalTo: view.leadingAnchor), - webView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) - } - - private func setupStatusLabel() { - statusLabel = UILabel() - statusLabel.translatesAutoresizingMaskIntoConstraints = false - statusLabel.font = .systemFont(ofSize: 14) - statusLabel.textColor = .secondaryLabel - statusLabel.textAlignment = .center - statusLabel.numberOfLines = 0 - statusLabel.text = "正在加载验证…" - view.addSubview(statusLabel) - - activityIndicator = UIActivityIndicatorView(style: .medium) - activityIndicator.translatesAutoresizingMaskIntoConstraints = false - activityIndicator.startAnimating() - view.addSubview(activityIndicator) - - NSLayoutConstraint.activate([ - statusLabel.topAnchor.constraint(equalTo: webView.bottomAnchor, constant: 12), - statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), - statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), - statusLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16), - activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor), - activityIndicator.centerYAnchor.constraint(equalTo: webView.centerYAnchor), - ]) - } - - // MARK: - Load - - private func loadMinimalLoginPage() { - // Prime cookies into the WebView store before loading HTML - // Uses loginCoordinator.primeCookies which reads canonical cookies from Rust - Task { - do { - try await loginCoordinator.primeCookies( - into: webView, - targetURL: URL(string: "https://linux.do/") - ) - } catch { - // Non-fatal: CF retry path re-primes later - } - await MainActor.run { - let html = FireLoginScripts.minimalLoginHTML( - hcaptchaSiteKey: FireLoginScripts.linuxDoHcaptchaSiteKey, - hcaptchaCreateEndpoint: "/captcha/hcaptcha/create.json" - ) - self.webView.loadHTMLString(html, baseURL: URL(string: "https://linux.do/")) - } - } - } - - // MARK: - Public Retry - - /// Retry login with a 2FA TOTP code. Uses the same live WebView — the - /// `h_captcha_temp_id` cookie is still valid for the short retry window. - func retryWithSecondFactor(_ token: String) { - hasReportedResult = false - lastLoginHcaptchaToken = nil - lastLoginSecondFactorToken = token - statusLabel.text = "正在验证…" - activityIndicator.startAnimating() - let invocation = FireLoginScripts.fireLoginInvocation( - identifier: identifier, - password: password, - hcaptchaToken: nil, - secondFactorToken: token - ) - webView.evaluateJavaScript(invocation) { [weak self] _, error in - if let error { - self?.reportResult(.failure(LoginFailureState( - kind: .unknown, - message: error.localizedDescription, - sentToEmail: nil, - currentEmail: nil - ))) - } - } - } - - // MARK: - Private - - private func runLogin(hcaptchaToken: String) { - lastLoginHcaptchaToken = hcaptchaToken - lastLoginSecondFactorToken = nil - statusLabel.text = "正在登录…" - activityIndicator.startAnimating() - let invocation = FireLoginScripts.fireLoginInvocation( - identifier: identifier, - password: password, - hcaptchaToken: hcaptchaToken, - secondFactorToken: nil - ) - webView.evaluateJavaScript(invocation) { [weak self] _, error in - if let error { - self?.reportResult(.failure(LoginFailureState( - kind: .unknown, - message: error.localizedDescription, - sentToEmail: nil, - currentEmail: nil - ))) - } - } - } - - private func reportResult(_ result: FireCaptchaDialogResult) { - guard !hasReportedResult else { return } - hasReportedResult = true - activityIndicator.stopAnimating() - switch result { - case .success: - statusLabel.text = "验证成功" - case .needSecondFactor: - statusLabel.text = "" - case .retryCloudflare: - statusLabel.text = "正在恢复网络…" - case .failure(let failure): - statusLabel.text = failure.message ?? "登录失败" - statusLabel.textColor = .systemRed - // Allow retry: reset hCaptcha - hasReportedResult = false - } - onResult(result) - } - - private func handleCancel() { - onCancel() - dismiss(animated: true) - } - - // MARK: - Deinit - - deinit { - webView?.stopLoading() - } -} - -// MARK: - Script Message Handling - -private final class FireCaptchaScriptMessageProxy: NSObject, WKScriptMessageHandler { - weak var delegate: FireCaptchaLoginDialogController? - - init(delegate: FireCaptchaLoginDialogController) { - self.delegate = delegate - } - - func userContentController( - _ userContentController: WKUserContentController, - didReceive message: WKScriptMessage - ) { - guard let delegate else { return } - switch message.name { - case FireLoginScripts.hcaptchaPassMessageName: - // JS posts the token as a plain string: postNative('hcaptcha_pass', token) - if let token = message.body as? String { - delegate.runLoginInternal(hcaptchaToken: token) - } - case FireLoginScripts.hcaptchaErrorMessageName: - // JS posts error as string - let msg = (message.body as? String) ?? "人机验证失败" - delegate.showHcaptchaError(msg) - case FireLoginScripts.hcaptchaExpiredMessageName: - delegate.showHcaptchaError("人机验证已过期,请重试") - case FireLoginScripts.loginResultMessageName: - if let body = message.body as? [String: Any] { - delegate.handleLoginResultJs(body) - } - default: - break - } - } -} - -// MARK: - Internal methods for message proxy access -// -// These methods are called by FireCaptchaScriptMessageProxy. They must be -// on the main class (not an extension) because they access private state. - -extension FireCaptchaLoginDialogController { - func runLoginInternal(hcaptchaToken: String) { - runLogin(hcaptchaToken: hcaptchaToken) - } - - func showHcaptchaError(_ message: String) { - DispatchQueue.main.async { [weak self] in - self?.statusLabel.text = message - self?.statusLabel.textColor = .systemRed - } - } - - func handleLoginResultJs(_ body: [String: Any]) { - // Parse JS result body into phase/status/body for classification - // phase is a string from JS: "csrf" | "hcaptcha" | "session" | "exception" - let phaseStr = (body["phase"] as? String) ?? "exception" - let phase: WebViewLoginPhaseState - switch phaseStr { - case "csrf": phase = .csrf - case "hcaptcha": phase = .hcaptcha - case "session": phase = .session - default: phase = .exception - } - let status = UInt16((body["status"] as? Int) ?? 0) - let bodyStr = (body["body"] as? String) ?? "" - classifyResult?(phase, status, bodyStr) - } -} -``` - -Note: The dialog receives a `FireWebViewLoginCoordinator` instance for cookie priming. The coordinator's `primeCookies(into:targetURL:)` method reads canonical cookies from Rust and executes them against the WebView's `httpCookieStore`. The WKWebView must stay alive for cookie extraction by `completeJsLogin(from:)`. - -- [ ] **Step 2: Verify it compiles** - -Run: `xcodegen generate --spec apps/ios-app/project.yml && xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire -destination 'generic/platform=iOS Simulator' build 2>&1 | tail -20` - -Expected: Build errors only from the new file (referencing types that don't exist yet or priming API mismatch). Fix any type mismatches against the actual `FireWebViewBrowserProfile` / `FireWebViewLoginCoordinator` APIs. - -- [ ] **Step 3: Regenerate Xcode project and commit** - -```bash -xcodegen generate --spec apps/ios-app/project.yml -git add apps/ios-app/App/Views/Other/FireCaptchaLoginDialogController.swift apps/ios-app/Fire.xcodeproj/project.pbxproj -git commit -m "feat(login): add FireCaptchaLoginDialogController for hCaptcha + login request" -``` - ---- - -### Task 2: Add ViewModel Async Capabilities - -**Files:** -- Modify: `apps/ios-app/App/ViewModels/FireAppViewModel.swift` - -**Context:** The ViewModel currently has `prepareMinimalAuthWebView(_:)` (line 427-474) which does CF check + prime + load at page open. We need to split this into discrete async capabilities that the VC calls on-demand. We also need to add `rememberCredential` to `completeMinimalLogin`. - -The existing `completeLoginCloudflareChallenge(sessionStore:)` (line 359-381) and `recoverLoginCloudflareChallenge(in:)` (line 348-357) already contain CF logic we can reuse. - -- [ ] **Step 1: Add `ensureCloudflareClearance()` async method** - -In `FireAppViewModel.swift`, add a new method near the existing CF methods (after line 381): - -```swift -/// Checks cf_clearance and runs CF challenge if missing. -/// Returns true on success, false on failure or user cancellation. -func ensureCloudflareClearance() async -> Bool { - do { - let sessionStore = try await sessionStoreValue() - if try await sessionStore.snapshot().readiness.hasCloudflareClearance { - return true - } - - try await completeLoginCloudflareChallenge(sessionStore: sessionStore) - try await Task.sleep(for: .milliseconds(1_500)) - return try await sessionStore.snapshot().readiness.hasCloudflareClearance - } catch { - errorMessage = error.localizedDescription - return false - } -} -``` - -- [ ] **Step 2: Add `loginCoordinatorForDialog()` accessor** - -The captcha dialog needs a `FireWebViewLoginCoordinator` instance for cookie priming. Add a simple accessor: - -Add after `ensureCloudflareClearance()`: - -```swift -/// Returns the login coordinator for the captcha dialog to use for priming. -func loginCoordinatorForDialog() async throws -> FireWebViewLoginCoordinator { - try await loginCoordinatorValue() -} - -/// Probes whether a full WebView fallback page has enough captured data -/// for the existing completeLogin(from:) finalizer. -func probeLoginSyncReadiness(from webView: WKWebView) async throws -> FireLoginSyncReadiness { - let loginCoordinator = try await loginCoordinatorValue() - return try await loginCoordinator.probeLoginSyncReadiness(from: webView) -} -``` - -- [ ] **Step 3: Add `rememberCredential` parameter to `completeMinimalLogin`** - -Modify `completeMinimalLogin` at line 293-339. Change the signature and the save logic: - -```swift -func completeMinimalLogin( - from webView: WKWebView, - identifier: String, - password: String, - rememberCredential: Bool -) { - guard !isSyncingLoginSession else { - return - } - - isSyncingLoginSession = true - Task { - defer { isSyncingLoginSession = false } - - do { - try await FireAPMManager.shared.withSpan(.authLoginSync) { - let loginCoordinator = try await loginCoordinatorValue() - let sessionStore = try await sessionStoreValue() - errorMessage = nil - await applySession( - try await loginCoordinator.completeJsLogin( - from: webView, - identifier: identifier - ), - activateMessageBus: false - ) - if rememberCredential { - try await sessionStore.saveLoginCredential( - username: identifier, - password: password - ) - savedLoginCredential = try await sessionStore.loadSavedCredential() - } else { - // User unchecked "remember password" — clear old saved credentials - // so the next login page open does not auto-fill. - try await sessionStore.clearSavedCredential() - savedLoginCredential = nil - } - FireCfClearanceRefreshService.shared.setLoginStateConfirmed(true) - try await sessionStore.triggerAppStateRefresh( - .loginCompleted, - handler: appStateRefreshCoordinator - ) - setAuthPresentationState(nil) - canSyncLoginSession = false - cachedLoginSyncReadiness = nil - } - } catch { - if await handleRecoverableSessionErrorIfNeeded(error) { - return - } - errorMessage = error.localizedDescription - } - } -} -``` - -Key change: `saveLoginCredential` is now inside `if rememberCredential { }`, and when unchecked `clearSavedCredential()` is called to remove any previously saved credentials. Product semantic: unchecking "remember password" means the next login page open will not auto-fill. - -- [ ] **Step 4: Add `classifyLoginResult` helper for dialog** - -Add a method that the VC can call to classify a raw login_result JS body. Keep this helper returning the shared `WebViewLoginDecisionState`; the UIKit-only `FireCaptchaDialogResult` mapping stays inside `FireLoginViewController`, so `FireAppViewModel` does not depend on UI types. The `WebViewLoginJsResultState` takes a `WebViewLoginPhaseState` enum (`.csrf`/`.hcaptcha`/`.session`/`.exception`), a `UInt16` status, and a `String` body: - -```swift -/// Classifies a raw login_result JS body into the shared WebView decision. -func classifyLoginResult( - phase: WebViewLoginPhaseState, - status: UInt16, - body: String -) async throws -> WebViewLoginDecisionState { - let result = WebViewLoginJsResultState( - phase: phase, - status: status, - body: body - ) - return try await classifyWebViewLoginResult(result) -} -``` - -- [ ] **Step 5: Simplify `openLogin()`** - -Modify `openLogin()` at line 229-255 to remove the WebView preload. Keep only state + credential load: - -```swift -func openLogin() { - guard authPresentationState == nil else { return } - authPresentationState = .login - Task { - do { - let sessionStore = try await sessionStoreValue() - savedLoginCredential = try await sessionStore.loadSavedCredential() - _ = try await loginCoordinatorValue() - } catch { - errorMessage = error.localizedDescription - } - } -} -``` - -- [ ] **Step 6: Verify it compiles** - -Run: `xcodegen generate --spec apps/ios-app/project.yml && xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire -destination 'generic/platform=iOS Simulator' build 2>&1 | tail -20` - -Expected: Build may still fail because `FireLoginWebViewController` references the old `completeMinimalLogin(from:identifier:password:)` signature. That's OK — Task 4 will delete that file. - -- [ ] **Step 7: Commit** - -```bash -git add apps/ios-app/App/ViewModels/FireAppViewModel.swift -git commit -m "feat(login): add async login capabilities to ViewModel - -- ensureCloudflareClearance() for on-demand CF check -- loginCoordinatorForDialog() exposes the authoritative login coordinator -- probeLoginSyncReadiness(from:) supports full WebView fallback finalization -- completeMinimalLogin gains rememberCredential param -- classifyLoginResult() returns shared WebViewLoginDecisionState -- openLogin() simplified, no WebView preload" -``` - ---- - -### Task 3: Create FireLoginViewController - -**Files:** -- Create: `apps/ios-app/App/Views/Other/FireLoginViewController.swift` - -**Context:** This is the pure-native login page. Layout: logo (top), credential inputs, remember-password checkbox, login button, forgot-password link, "other login methods" button. The VC owns the login flow orchestration: calls ViewModel async capabilities, presents the captcha dialog, handles results. - -- [ ] **Step 1: Create the login VC with layout** - -Create `apps/ios-app/App/Views/Other/FireLoginViewController.swift`: - -```swift -import UIKit -import WebKit -import Combine - -/// Pure-native login page. No WebView in this VC. -/// Presents `FireCaptchaLoginDialogController` for hCaptcha + login request. -final class FireLoginViewController: UIViewController { - - // MARK: - Dependencies - - private let viewModel: FireAppViewModel - private var cancellables = Set() - - // MARK: - UI Elements - - private let scrollView = UIScrollView() - private let contentView = UIView() - private let logoImageView = UIImageView() - private let titleLabel = UILabel() - private let subtitleLabel = UILabel() - private let identifierField = UITextField() - private let passwordField = UITextField() - private let rememberSwitch = UISwitch() - private let rememberLabel = UILabel() - private let loginButton = UIButton(type: .system) - private let forgotPasswordButton = UIButton(type: .system) - private let dividerLabel = UILabel() - private let otherMethodsButton = UIButton(type: .system) - private let errorBannerLabel = UILabel() - private let activityIndicator = UIActivityIndicatorView(style: .large) - - // MARK: - Login Flow State - - private var captchaDialog: FireCaptchaLoginDialogController? - private var cfRetryUsed = false - private var pendingIdentifier: String = "" - private var pendingPassword: String = "" - private var pendingRememberCredential: Bool = false - private var hasShownSecondFactor = false - - // MARK: - Init - - init(viewModel: FireAppViewModel) { - self.viewModel = viewModel - super.init(nibName: nil, bundle: nil) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError() } - - // MARK: - Lifecycle - - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = .systemBackground - setupNavigation() - setupScrollView() - setupLogo() - setupCredentialFields() - setupRememberPassword() - setupLoginButton() - setupForgotPassword() - setupOtherMethods() - setupErrorBanner() - setupActivityIndicator() - observeViewModelState() - } - - // MARK: - ViewModel State - - private func observeViewModelState() { - observeSavedCredential() - observeLoginErrorsAndSyncingState() - } - - /// Auto-fills credentials whenever they load (openLogin loads them asynchronously). - private func observeSavedCredential() { - viewModel.$savedLoginCredential - .receive(on: RunLoop.main) - .sink { [weak self] credential in - guard let credential else { return } - self?.identifierField.text = credential.username - self?.passwordField.text = credential.password - self?.rememberSwitch.isOn = true - self?.updateLoginButtonState() - } - .store(in: &cancellables) - } - - /// Existing ViewModel finalization APIs are fire-and-forget. Observe their - /// published state so the native controller can clear loading UI and surface - /// finalization failures instead of leaving the sheet spinning. - private func observeLoginErrorsAndSyncingState() { - viewModel.$errorMessage - .receive(on: RunLoop.main) - .compactMap { $0 } - .filter { !$0.isEmpty } - .sink { [weak self] message in - guard let self, self.captchaDialog != nil else { return } - self.setLoginLoading(false) - self.dismissCaptchaDialog() - self.showErrorBanner(message) - } - .store(in: &cancellables) - - viewModel.$isSyncingLoginSession - .receive(on: RunLoop.main) - .sink { [weak self] isSyncing in - guard let self, !isSyncing, self.viewModel.authPresentationState != nil else { return } - self.setLoginLoading(false) - } - .store(in: &cancellables) - } - - // MARK: - Setup - - private func setupNavigation() { - title = "登录 LinuxDo" - } - - private func setupScrollView() { - scrollView.translatesAutoresizingMaskIntoConstraints = false - scrollView.keyboardDismissMode = .interactive - view.addSubview(scrollView) - - contentView.translatesAutoresizingMaskIntoConstraints = false - scrollView.addSubview(contentView) - - NSLayoutConstraint.activate([ - scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), - scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), - - contentView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor), - contentView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor), - contentView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor), - contentView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor), - contentView.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor), - ]) - } - - private func setupLogo() { - logoImageView.translatesAutoresizingMaskIntoConstraints = false - logoImageView.image = UIImage(systemName: "flame.fill") - logoImageView.tintColor = .systemOrange - logoImageView.contentMode = .scaleAspectFit - - titleLabel.translatesAutoresizingMaskIntoConstraints = false - titleLabel.text = "Fire" - titleLabel.font = .systemFont(ofSize: 32, weight: .bold) - titleLabel.textAlignment = .center - - subtitleLabel.translatesAutoresizingMaskIntoConstraints = false - subtitleLabel.text = "LinuxDo 社区客户端" - subtitleLabel.font = .systemFont(ofSize: 15) - subtitleLabel.textColor = .secondaryLabel - subtitleLabel.textAlignment = .center - - contentView.addSubview(logoImageView) - contentView.addSubview(titleLabel) - contentView.addSubview(subtitleLabel) - - NSLayoutConstraint.activate([ - logoImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 48), - logoImageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - logoImageView.widthAnchor.constraint(equalToConstant: 72), - logoImageView.heightAnchor.constraint(equalToConstant: 72), - - titleLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 16), - titleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - - subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4), - subtitleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - ]) - } - - private func setupCredentialFields() { - identifierField.translatesAutoresizingMaskIntoConstraints = false - identifierField.placeholder = "用户名或邮箱" - identifierField.borderStyle = .roundedRect - identifierField.autocapitalizationType = .none - identifierField.autocorrectionType = .no - identifierField.textContentType = .username - identifierField.returnKeyType = .next - identifierField.addTarget(self, action: #selector(textFieldsChanged), for: .editingChanged) - - passwordField.translatesAutoresizingMaskIntoConstraints = false - passwordField.placeholder = "密码" - passwordField.borderStyle = .roundedRect - passwordField.isSecureTextEntry = true - passwordField.textContentType = .password - passwordField.returnKeyType = .go - passwordField.addTarget(self, action: #selector(textFieldsChanged), for: .editingChanged) - - contentView.addSubview(identifierField) - contentView.addSubview(passwordField) - - NSLayoutConstraint.activate([ - identifierField.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 32), - identifierField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24), - identifierField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24), - identifierField.heightAnchor.constraint(equalToConstant: 48), - - passwordField.topAnchor.constraint(equalTo: identifierField.bottomAnchor, constant: 12), - passwordField.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - passwordField.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - passwordField.heightAnchor.constraint(equalToConstant: 48), - ]) - } - - private func setupRememberPassword() { - rememberSwitch.translatesAutoresizingMaskIntoConstraints = false - rememberSwitch.onTintColor = .systemOrange - rememberSwitch.addTarget(self, action: #selector(rememberChanged), for: .valueChanged) - - rememberLabel.translatesAutoresizingMaskIntoConstraints = false - rememberLabel.text = "记住账号密码" - rememberLabel.font = .systemFont(ofSize: 15) - rememberLabel.textColor = .secondaryLabel - rememberLabel.isUserInteractionEnabled = true - let tap = UITapGestureRecognizer(target: self, action: #selector(rememberLabelTapped)) - rememberLabel.addGestureRecognizer(tap) - - contentView.addSubview(rememberSwitch) - contentView.addSubview(rememberLabel) - - NSLayoutConstraint.activate([ - rememberSwitch.topAnchor.constraint(equalTo: passwordField.bottomAnchor, constant: 12), - rememberSwitch.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - - rememberLabel.centerYAnchor.constraint(equalTo: rememberSwitch.centerYAnchor), - rememberLabel.leadingAnchor.constraint(equalTo: rememberSwitch.trailingAnchor, constant: 8), - ]) - } - - private func setupLoginButton() { - loginButton.translatesAutoresizingMaskIntoConstraints = false - var config = UIButton.Configuration.filled() - config.title = "登录" - config.cornerStyle = .medium - loginButton.configuration = config - loginButton.addTarget(self, action: #selector(loginTapped), for: .touchUpInside) - loginButton.isEnabled = false - - contentView.addSubview(loginButton) - - NSLayoutConstraint.activate([ - loginButton.topAnchor.constraint(equalTo: rememberSwitch.bottomAnchor, constant: 20), - loginButton.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - loginButton.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - loginButton.heightAnchor.constraint(equalToConstant: 50), - ]) - } - - private func setupForgotPassword() { - forgotPasswordButton.translatesAutoresizingMaskIntoConstraints = false - forgotPasswordButton.setTitle("忘记密码?", for: .normal) - forgotPasswordButton.titleLabel?.font = .systemFont(ofSize: 14) - forgotPasswordButton.setTitleColor(.secondaryLabel, for: .normal) - forgotPasswordButton.addTarget(self, action: #selector(forgotPasswordTapped), for: .touchUpInside) - - contentView.addSubview(forgotPasswordButton) - - NSLayoutConstraint.activate([ - forgotPasswordButton.topAnchor.constraint(equalTo: loginButton.bottomAnchor, constant: 12), - forgotPasswordButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - ]) - } - - private func setupOtherMethods() { - dividerLabel.translatesAutoresizingMaskIntoConstraints = false - dividerLabel.text = "── 其他方式 ──" - dividerLabel.font = .systemFont(ofSize: 13) - dividerLabel.textColor = .tertiaryLabel - dividerLabel.textAlignment = .center - - otherMethodsButton.translatesAutoresizingMaskIntoConstraints = false - var config = UIButton.Configuration.bordered() - config.title = "其他方式登录 (OAuth / Passkey)" - config.image = UIImage(systemName: "globe") - config.imagePadding = 8 - config.cornerStyle = .medium - otherMethodsButton.configuration = config - otherMethodsButton.addTarget(self, action: #selector(otherMethodsTapped), for: .touchUpInside) - - contentView.addSubview(dividerLabel) - contentView.addSubview(otherMethodsButton) - - NSLayoutConstraint.activate([ - dividerLabel.topAnchor.constraint(equalTo: forgotPasswordButton.bottomAnchor, constant: 20), - dividerLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - - otherMethodsButton.topAnchor.constraint(equalTo: dividerLabel.bottomAnchor, constant: 12), - otherMethodsButton.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - otherMethodsButton.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - otherMethodsButton.heightAnchor.constraint(equalToConstant: 44), - otherMethodsButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -32), - ]) - } - - private func setupErrorBanner() { - errorBannerLabel.translatesAutoresizingMaskIntoConstraints = false - errorBannerLabel.font = .systemFont(ofSize: 14) - errorBannerLabel.textColor = .systemRed - errorBannerLabel.textAlignment = .center - errorBannerLabel.numberOfLines = 0 - errorBannerLabel.isHidden = true - - contentView.addSubview(errorBannerLabel) - - NSLayoutConstraint.activate([ - errorBannerLabel.topAnchor.constraint(equalTo: otherMethodsButton.bottomAnchor, constant: 12), - errorBannerLabel.leadingAnchor.constraint(equalTo: identifierField.leadingAnchor), - errorBannerLabel.trailingAnchor.constraint(equalTo: identifierField.trailingAnchor), - errorBannerLabel.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -16), - ]) - } - - private func setupActivityIndicator() { - activityIndicator.translatesAutoresizingMaskIntoConstraints = false - activityIndicator.hidesWhenStopped = true - view.addSubview(activityIndicator) - - NSLayoutConstraint.activate([ - activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor), - activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor), - ]) - } - - // MARK: - Credential Auto-fill - - private func applySavedCredentialIfNeeded() { - Task { @MainActor in - let credential = viewModel.savedLoginCredential - guard let credential else { return } - identifierField.text = credential.username - passwordField.text = credential.password - rememberSwitch.isOn = true - updateLoginButtonState() - } - } - - // MARK: - Actions - - @objc private func textFieldsChanged() { - updateLoginButtonState() - hideErrorBanner() - } - - @objc private func rememberChanged() { - // Toggle handled by UISwitch - } - - @objc private func rememberLabelTapped() { - rememberSwitch.setOn(!rememberSwitch.isOn, animated: true) - } - - @objc private func loginTapped() { - guard let identifier = identifierField.text?.trimmingCharacters(in: .whitespacesAndNewlines), - let password = passwordField.text, - !identifier.isEmpty, !password.isEmpty else { return } - - pendingIdentifier = identifier - pendingPassword = password - pendingRememberCredential = rememberSwitch.isOn - hideErrorBanner() - setLoginLoading(true) - - Task { await performLogin() } - } - - @objc private func forgotPasswordTapped() { - // Phase 2: present FireWebViewBrowserViewController with /password-reset - showComingSoon() - } - - @objc private func otherMethodsTapped() { - // Phase 2: present FireWebViewBrowserViewController with /login - showComingSoon() - } - - // MARK: - Login Flow - - private func performLogin() async { - // Step 1: Ensure Cloudflare clearance - let cfOK = await viewModel.ensureCloudflareClearance() - guard cfOK else { - await MainActor.run { - setLoginLoading(false) - showErrorBanner("网络验证失败,请重试") - } - return - } - - // Step 2: Get login coordinator for the dialog - let loginCoordinator: FireWebViewLoginCoordinator - do { - loginCoordinator = try await viewModel.loginCoordinatorForDialog() - } catch { - await MainActor.run { - setLoginLoading(false) - showErrorBanner("网络准备失败,请重试") - } - return - } - - // Step 3: Present captcha dialog - await MainActor.run { - presentCaptchaDialog(loginCoordinator: loginCoordinator) - } - } - - @MainActor - private func presentCaptchaDialog(loginCoordinator: FireWebViewLoginCoordinator) { - let dialog = FireCaptchaLoginDialogController( - identifier: pendingIdentifier, - password: pendingPassword, - loginCoordinator: loginCoordinator, - onResult: { [weak self] result in - self?.handleDialogResult(result) - }, - onCancel: { [weak self] in - self?.setLoginLoading(false) - self?.captchaDialog = nil - } - ) - - // Wire up the classifier closure - dialog.classifyResult = { [weak self] phase, status, body in - guard let self else { return } - Task { - do { - let decision = try await self.viewModel.classifyLoginResult( - phase: phase, - status: status, - body: body - ) - await MainActor.run { - dialog.dispatchResult(self.dialogResult(from: decision)) - } - } catch { - await MainActor.run { - dialog.dispatchResult(.failure(LoginFailureState( - kind: .unknown, - message: error.localizedDescription, - sentToEmail: nil, - currentEmail: nil - ))) - } - } - } - } - - captchaDialog = dialog - present(dialog, animated: true) - } - - private func dialogResult(from decision: WebViewLoginDecisionState) -> FireCaptchaDialogResult { - switch decision { - case .success: - return .success - case .needSecondFactor(let requirement): - return .needSecondFactor(requirement) - case .retryCloudflare: - return .retryCloudflare - case .failure(let failure): - return .failure(failure) - } - } - - private func handleDialogResult(_ result: FireCaptchaDialogResult) { - switch result { - case .success: - completeLoginFromDialog() - - case .needSecondFactor(let requirement): - if !hasShownSecondFactor || requirement.message != nil { - showSecondFactorPrompt(requirement: requirement) - } - - case .retryCloudflare: - recoverCloudflare() - - case .failure(let failure): - DispatchQueue.main.async { [weak self] in - self?.setLoginLoading(false) - self?.dismissCaptchaDialog() - self?.showErrorBanner(failure.message ?? "登录失败") - if failure.kind == .invalidCredentials { - self?.passwordField.text = nil - self?.updateLoginButtonState() - } - } - } - } - - private func completeLoginFromDialog() { - guard let dialog = captchaDialog else { return } - let webView = dialog.webView - let identifier = pendingIdentifier - let password = pendingPassword - let remember = pendingRememberCredential - - Task { @MainActor in - viewModel.completeMinimalLogin( - from: webView, - identifier: identifier, - password: password, - rememberCredential: remember - ) - // Success sets authPresentationState(nil) → coordinator dismisses everything. - // Errors are surfaced by observeLoginErrorsAndSyncingState(). - } - } - - private func showSecondFactorPrompt(requirement: SecondFactorRequirementState) { - DispatchQueue.main.async { [weak self] in - guard let self else { return } - self.hasShownSecondFactor = true - - let alert = UIAlertController( - title: "两步验证", - message: requirement.message ?? "请输入验证器中的 6 位代码", - preferredStyle: .alert - ) - alert.addTextField { field in - field.placeholder = "6 位验证码" - field.keyboardType = .numberPad - field.textContentType = .oneTimeCode - } - alert.addAction(UIAlertAction(title: "确定", style: .default) { [weak self] _ in - guard let code = alert.textFields?.first?.text?.trimmingCharacters(in: .whitespacesAndNewlines), - !code.isEmpty else { return } - self?.captchaDialog?.retryWithSecondFactor(code) - }) - alert.addAction(UIAlertAction(title: "取消", style: .cancel) { [weak self] _ in - self?.setLoginLoading(false) - self?.dismissCaptchaDialog() - }) - self.present(alert, animated: true) - } - } - - private func recoverCloudflare() { - guard !cfRetryUsed else { - DispatchQueue.main.async { [weak self] in - self?.setLoginLoading(false) - self?.dismissCaptchaDialog() - self?.showErrorBanner("网络验证失败,请稍后重试") - } - return - } - cfRetryUsed = true - - Task { - // Use existing recoverLoginCloudflareChallenge logic via ViewModel - await MainActor.run { - // ViewModel.recoverLoginCloudflareChallenge re-primes and retries - // The dialog's WebView will re-run __fireLogin after CF recovery - // This needs the dialog to stay alive and re-prime - // For now, dismiss and re-present after CF recovery - // TODO: implement CF retry within the same dialog - } - } - } - - // MARK: - Helpers - - private func updateLoginButtonState() { - let hasId = !(identifierField.text?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true) - let hasPwd = !(passwordField.text?.isEmpty ?? true) - loginButton.isEnabled = hasId && hasPwd - } - - private func setLoginLoading(_ loading: Bool) { - if loading { - activityIndicator.startAnimating() - loginButton.isEnabled = false - view.isUserInteractionEnabled = false - } else { - activityIndicator.stopAnimating() - updateLoginButtonState() - view.isUserInteractionEnabled = true - } - } - - private func showErrorBanner(_ message: String) { - errorBannerLabel.text = message - errorBannerLabel.isHidden = false - } - - private func hideErrorBanner() { - errorBannerLabel.isHidden = true - } - - private func dismissCaptchaDialog() { - captchaDialog?.dismiss(animated: true) { [weak self] in - self?.captchaDialog = nil - } - } - - private func showComingSoon() { - let alert = UIAlertController(title: "即将支持", message: "此功能将在后续版本中推出,敬请期待。", preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "好的", style: .default)) - present(alert, animated: true) - } -} -``` - -Note: The `dispatchResult` method on `FireCaptchaLoginDialogController` needs to be added — it's the bridge between the `classifyResult` closure and `reportResult`. Add it to the dialog: - -In `FireCaptchaLoginDialogController.swift`, add: -```swift -/// Called by the presenting VC after classifying the JS result. -func dispatchResult(_ result: FireCaptchaDialogResult) { - reportResult(result) -} -``` - -- [ ] **Step 2: Add `dispatchResult` to dialog** - -Add to `FireCaptchaLoginDialogController`: -```swift -func dispatchResult(_ result: FireCaptchaDialogResult) { - reportResult(result) -} -``` - -- [ ] **Step 3: Verify it compiles** - -Run: `xcodegen generate --spec apps/ios-app/project.yml && xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire -destination 'generic/platform=iOS Simulator' build 2>&1 | tail -20` - -Expected: Build should succeed except for `FireRootCoordinator` still referencing old VC and `FireLoginWebView.swift` referencing old `completeMinimalLogin` signature. - -- [ ] **Step 4: Commit** - -```bash -git add apps/ios-app/App/Views/Other/FireLoginViewController.swift apps/ios-app/App/Views/Other/FireCaptchaLoginDialogController.swift -git commit -m "feat(login): add FireLoginViewController with native form layout" -``` - ---- - -### Task 4: Switch Root Coordinator + Delete Old VC - -**Files:** -- Modify: `apps/ios-app/App/Core/FireRootCoordinator.swift` -- Delete: `apps/ios-app/App/Views/Other/FireLoginWebView.swift` - -**Context:** The coordinator currently creates `FireLoginWebViewController` inside `syncAuthPresentation(_:)`. This task is the build cutover that removes the old VC after the ViewModel signature changes. Task 5 must follow before the branch is considered mergeable/releasable, because same-dialog CF retry is part of the complete native login behavior. - -- [ ] **Step 1: Replace VC construction in coordinator** - -In `FireRootCoordinator.swift`, find the `syncAuthPresentation` method (around line 357-368). Replace the construction of `FireLoginWebViewController` with `FireLoginViewController`: - -```swift -let controller = FireLoginViewController(viewModel: viewModel) -let navigationController = UINavigationController(rootViewController: controller) -navigationController.modalPresentationStyle = .fullScreen -presentationAnchor()?.present(navigationController, animated: true) -authController = navigationController -``` - -Find the exact old code that constructs `FireLoginWebViewController` and replace it. The old code likely looks like: -```swift -let controller = FireLoginWebViewController( - viewModel: viewModel, - presentationState: state -) -``` - -- [ ] **Step 2: Delete old login VC** - -```bash -git rm apps/ios-app/App/Views/Other/FireLoginWebView.swift -``` - -- [ ] **Step 3: Verify build** - -Run: `xcodegen generate --spec apps/ios-app/project.yml && xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire -destination 'generic/platform=iOS Simulator' build 2>&1 | tail -30` - -Expected: Build succeeds. If there are references to `FireLoginWebViewController` elsewhere, find and update them. - -- [ ] **Step 4: Commit** - -```bash -git add -A apps/ios-app/ -git commit -m "feat(login): switch to FireLoginViewController, delete FireLoginWebView - -- Root coordinator presents FireLoginViewController -- FireLoginWebView.swift removed (816 lines → 0) -- Login flow: native form → on-demand CF → captcha dialog → finalize" -``` - -Gate: do not merge or ship at this point. Continue immediately with Task 5 so `.retryCloudflare` reuses the same live dialog/WebView instead of failing back to a stale outer login flow. - ---- - -### Task 5: Fix CF Retry Within Dialog - -**Files:** -- Modify: `apps/ios-app/App/Views/Other/FireLoginViewController.swift` - -**Context:** The `recoverCloudflare()` method in Task 3 has a TODO for CF retry within the same dialog. The knowledge base (`discourse-webview-login-guide.md:252-264`) specifies: CF verification → wait for cookie propagation → extract cookies → write to Rust trusted → re-prime the same live WebView → re-run `__fireLogin` with the same arguments that failed during the csrf phase. - -- [ ] **Step 1: Implement CF retry within dialog** - -Replace the `recoverCloudflare()` method in `FireLoginViewController`: - -```swift - private func recoverCloudflare() { - guard !cfRetryUsed else { - DispatchQueue.main.async { [weak self] in - self?.setLoginLoading(false) - self?.dismissCaptchaDialog() - self?.showErrorBanner("网络验证失败,请稍后重试") - } - return - } - cfRetryUsed = true - - Task { - // Use existing recoverLoginCloudflareChallenge(in:) which always - // forces CF challenge + 1.5s propagation wait + re-prime. - // This is NOT the same as ensureCloudflareClearance() which - // short-circuits when session readiness already has CF clearance — but .retryCloudflare - // means the current clearance was rejected by /session/csrf. - guard let dialog = self.captchaDialog else { return } - do { - try await viewModel.recoverLoginCloudflareChallenge(in: dialog.webView) - } catch { - await MainActor.run { - self.setLoginLoading(false) - self.dismissCaptchaDialog() - self.showErrorBanner("网络验证失败,请重试") - } - return - } - - // Re-run __fireLogin with the same arguments that failed during csrf. - await MainActor.run { - dialog.retryAfterCloudflareRecovery() - } - } - } -``` - -- [ ] **Step 2: Add `retryAfterCloudflareRecovery` to dialog** - -In `FireCaptchaLoginDialogController.swift`, add: - -```swift -/// Re-primes and re-runs __fireLogin after CF recovery. -/// Reuses the same arguments because csrf phase fails before hCaptcha create/session submit. -func retryAfterCloudflareRecovery() { - guard lastLoginHcaptchaToken != nil || lastLoginSecondFactorToken != nil else { - statusLabel.text = "请重新尝试登录" - statusLabel.textColor = .secondaryLabel - hasReportedResult = false - return - } - hasReportedResult = false - statusLabel.text = "正在重试登录…" - statusLabel.textColor = .secondaryLabel - activityIndicator.startAnimating() - let invocation = FireLoginScripts.fireLoginInvocation( - identifier: identifier, - password: password, - hcaptchaToken: lastLoginHcaptchaToken, - secondFactorToken: lastLoginSecondFactorToken - ) - webView.evaluateJavaScript(invocation) { [weak self] _, error in - if let error { - self?.reportResult(.failure(LoginFailureState( - kind: .unknown, - message: error.localizedDescription, - sentToEmail: nil, - currentEmail: nil - ))) - } - } -} -``` - -- [ ] **Step 3: Verify build** - -Run: `xcodegen generate --spec apps/ios-app/project.yml && xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire -destination 'generic/platform=iOS Simulator' build 2>&1 | tail -20` - -Expected: Build succeeds. - -- [ ] **Step 4: Commit** - -```bash -git add apps/ios-app/App/Views/Other/FireLoginViewController.swift apps/ios-app/App/Views/Other/FireCaptchaLoginDialogController.swift -git commit -m "feat(login): implement CF retry within captcha dialog - -Re-prime live WebView and reuse the failed csrf attempt args after CF recovery -per discourse-webview-login-guide.md:252-264." -``` - ---- - -## Phase 2: Full WebView Fallback (Social Login + Forgot Password) - -### Task 6: Create FireWebViewBrowserViewController - -**Files:** -- Create: `apps/ios-app/App/Views/Other/FireWebViewBrowserViewController.swift` - -**Context:** A simple full-screen WKWebView browser VC for loading `linux.do/login` or `linux.do/password-reset`. It uses the shared browser profile so preloaded bootstrap capture and fingerprint scripts stay installed. It monitors auth cookies, probes full login sync readiness, and only then triggers the existing `completeLogin(from:)` finalizer. - -- [ ] **Step 1: Create the browser VC** - -Create `apps/ios-app/App/Views/Other/FireWebViewBrowserViewController.swift`: - -```swift -import Combine -import UIKit -import WebKit - -/// Full-screen WebView browser for login fallback paths (OAuth, Passkey, -/// forgot password). Loads linux.do pages and detects login success via -/// cookie monitoring. -final class FireWebViewBrowserViewController: UIViewController { - - // MARK: - Properties - - private let initialURL: URL - private let viewModel: FireAppViewModel - private var webView: WKWebView! - private var navigationBar: UINavigationBar! - private var progressView: UIProgressView! - private var hasFinalizedLogin = false - private var cookiePollTimer: Timer? - private let scriptMessageProxy = FireBrowserScriptMessageProxy() - private var cancellables = Set() - - // MARK: - Init - - init(url: URL, viewModel: FireAppViewModel) { - self.initialURL = url - self.viewModel = viewModel - super.init(nibName: nil, bundle: nil) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError() } - - // MARK: - Lifecycle - - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = .systemBackground - setupNavigationBar() - setupWebView() - setupProgressView() - observeViewModelErrors() - loadURL() - startCookiePolling() - } - - deinit { - cookiePollTimer?.invalidate() - webView?.removeObserver(self, forKeyPath: "estimatedProgress") - [ - FireLoginScripts.loginCredentialsMessageName, - FireLoginScripts.fingerprintDoneMessageName, - ].forEach { name in - webView?.configuration.userContentController.removeScriptMessageHandler(forName: name) - } - webView?.stopLoading() - } - - // MARK: - Setup - - private func setupNavigationBar() { - navigationBar = UINavigationBar() - navigationBar.translatesAutoresizingMaskIntoConstraints = false - let navItem = UINavigationItem(title: initialURL.host ?? "") - navItem.leftBarButtonItem = UIBarButtonItem( - barButtonSystemItem: .close, - primaryAction: UIAction { [weak self] _ in - self?.dismiss(animated: true) - } - ) - navItem.rightBarButtonItem = UIBarButtonItem( - barButtonSystemItem: .refresh, - primaryAction: UIAction { [weak self] _ in - self?.webView?.reload() - } - ) - navigationBar.items = [navItem] - view.addSubview(navigationBar) - - NSLayoutConstraint.activate([ - navigationBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - navigationBar.leadingAnchor.constraint(equalTo: view.leadingAnchor), - navigationBar.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) - } - - private func setupWebView() { - scriptMessageProxy.onMessage = { [weak self] message in - self?.handleScriptMessage(message) - } - let configuration = FireWebViewBrowserProfile.makeLoginConfiguration( - credential: viewModel.savedLoginCredential, - messageHandler: scriptMessageProxy - ) - webView = WKWebView(frame: .zero, configuration: configuration) - webView.translatesAutoresizingMaskIntoConstraints = false - FireWebViewBrowserProfile.configure( - webView, - preferredUserAgent: viewModel.session.browserUserAgent - ) - webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) - view.addSubview(webView) - - NSLayoutConstraint.activate([ - webView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor), - webView.leadingAnchor.constraint(equalTo: view.leadingAnchor), - webView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - webView.bottomAnchor.constraint(equalTo: view.bottomAnchor), - ]) - } - - private func observeViewModelErrors() { - viewModel.$errorMessage - .receive(on: RunLoop.main) - .compactMap { $0 } - .filter { !$0.isEmpty } - .sink { [weak self] message in - guard let self, self.hasFinalizedLogin else { return } - self.hasFinalizedLogin = false - self.startCookiePolling() - self.showErrorAlert(message) - } - .store(in: &cancellables) - } - - private func setupProgressView() { - progressView = UIProgressView(progressViewStyle: .bar) - progressView.translatesAutoresizingMaskIntoConstraints = false - progressView.tintColor = .systemOrange - view.addSubview(progressView) - - NSLayoutConstraint.activate([ - progressView.topAnchor.constraint(equalTo: webView.topAnchor), - progressView.leadingAnchor.constraint(equalTo: view.leadingAnchor), - progressView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) - } - - private func loadURL() { - // Prime cookies from Rust before loading. The WebView configuration - // already installed preloadedDataCapture, credential autofill, and - // fingerprint intercept scripts through makeLoginConfiguration. - Task { - do { - let loginCoordinator = try await viewModel.loginCoordinatorForDialog() - try await loginCoordinator.primeCookies( - into: webView, - targetURL: URL(string: "https://linux.do/") - ) - } catch { - // Non-fatal: continue without priming - } - await MainActor.run { - self.webView.load(URLRequest(url: self.initialURL)) - } - } - } - - private func startCookiePolling() { - // Poll for _t cookie (auth token) every 2 seconds - cookiePollTimer?.invalidate() - cookiePollTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in - self?.checkForAuthToken() - } - } - - private func checkForAuthToken() { - webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { [weak self] cookies in - Task { @MainActor in - guard let self, !self.hasFinalizedLogin else { return } - let hasAuth = cookies.contains { $0.name == "_t" && !$0.value.isEmpty } - guard hasAuth else { return } - - do { - let readiness = try await self.viewModel.probeLoginSyncReadiness(from: self.webView) - guard readiness.isReady else { return } - } catch { - return - } - - self.hasFinalizedLogin = true - self.cookiePollTimer?.invalidate() - // Use completeLogin(from:) for full WebView path — it reads - // username/csrf from page meta/preloaded data, not from params. - self.viewModel.completeLogin(from: self.webView) - } - } - } - - private func handleScriptMessage(_ message: WKScriptMessage) { - switch message.name { - case FireLoginScripts.fingerprintDoneMessageName: - viewModel.recordLoginFingerprintDone() - case FireLoginScripts.loginCredentialsMessageName: - // The native login form owns credential persistence. For fallback - // pages this message is only used to keep preloaded capture active. - break - default: - break - } - } - - private func showErrorAlert(_ message: String) { - let alert = UIAlertController(title: "登录同步失败", message: message, preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "重试", style: .default)) - present(alert, animated: true) - } - - // MARK: - KVO - - override func observeValue( - forKeyPath keyPath: String?, - of object: Any?, - change: [NSKeyValueChangeKey: Any]?, - context: UnsafeMutableRawPointer? - ) { - if keyPath == "estimatedProgress" { - DispatchQueue.main.async { [weak self] in - guard let self else { return } - self.progressView.progress = Float(self.webView.estimatedProgress) - self.progressView.isHidden = self.webView.estimatedProgress >= 1.0 - } - } - } -} - -private final class FireBrowserScriptMessageProxy: NSObject, WKScriptMessageHandler { - var onMessage: ((WKScriptMessage) -> Void)? - - func userContentController( - _ userContentController: WKUserContentController, - didReceive message: WKScriptMessage - ) { - onMessage?(message) - } -} -``` - -Note: Cookie monitoring uses a 2-second polling timer against `WKWebsiteDataStore.default().httpCookieStore.getAllCookies`. `_t` only indicates an auth cookie exists; finalization must also wait for `probeLoginSyncReadiness(from:)` because the Rust finalizer requires auth cookies plus captured username/bootstrap data from the preloaded scripts. Use `completeLogin(from:)` for this full WebView path; do not call `completeMinimalLogin` with empty credentials. - -- [ ] **Step 2: Wire up forgot-password and other-methods buttons** - -In `FireLoginViewController.swift`, replace the `showComingSoon()` calls: - -```swift -@objc private func forgotPasswordTapped() { - let url = URL(string: "https://linux.do/password-reset")! - presentWebViewBrowser(url: url) -} - -@objc private func otherMethodsTapped() { - let url = URL(string: "https://linux.do/login")! - presentWebViewBrowser(url: url) -} - -private func presentWebViewBrowser(url: URL) { - let browser = FireWebViewBrowserViewController(url: url, viewModel: viewModel) - browser.modalPresentationStyle = .fullScreen - present(browser, animated: true) -} - -private func showComingSoon() { - // Remove this method — no longer needed -} -``` - -Remove the `showComingSoon()` method body and the two call sites that used it. - -- [ ] **Step 3: Verify build** - -Run: `xcodegen generate --spec apps/ios-app/project.yml && xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire -destination 'generic/platform=iOS Simulator' build 2>&1 | tail -20` - -Expected: Build succeeds. - -- [ ] **Step 4: Commit** - -```bash -git add apps/ios-app/App/Views/Other/FireWebViewBrowserViewController.swift apps/ios-app/App/Views/Other/FireLoginViewController.swift -git commit -m "feat(login): add WebView browser fallback for OAuth/forgot-password" -``` - ---- - -## Phase 3: Error Handling Polish - -### Task 7: Inline Error Banner Component - -**Files:** -- Modify: `apps/ios-app/App/Views/Other/FireLoginViewController.swift` - -**Context:** Currently errors are shown via a simple hidden label. Improve to a proper auto-dismissing banner with animation. Also handle repeated `needSecondFactor` messages in the 2FA alert. - -- [ ] **Step 1: Replace error label with animated banner** - -Replace `errorBannerLabel` with a container view that slides in/out: - -```swift -private let errorBannerContainer = UIView() -private let errorBannerImageView = UIImageView() -private let errorBannerLabel = UILabel() - -private func setupErrorBanner() { - errorBannerContainer.translatesAutoresizingMaskIntoConstraints = false - errorBannerContainer.backgroundColor = UIColor.systemRed.withAlphaComponent(0.1) - errorBannerContainer.layer.cornerRadius = 8 - errorBannerContainer.isHidden = true - errorBannerContainer.alpha = 0 - - errorBannerImageView.translatesAutoresizingMaskIntoConstraints = false - errorBannerImageView.image = UIImage(systemName: "exclamationmark.triangle.fill") - errorBannerImageView.tintColor = .systemRed - - errorBannerLabel.translatesAutoresizingMaskIntoConstraints = false - errorBannerLabel.font = .systemFont(ofSize: 14) - errorBannerLabel.textColor = .systemRed - errorBannerLabel.numberOfLines = 0 - - errorBannerContainer.addSubview(errorBannerImageView) - errorBannerContainer.addSubview(errorBannerLabel) - view.addSubview(errorBannerContainer) - - NSLayoutConstraint.activate([ - errorBannerContainer.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8), - errorBannerContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), - errorBannerContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), - - errorBannerImageView.topAnchor.constraint(equalTo: errorBannerContainer.topAnchor, constant: 12), - errorBannerImageView.leadingAnchor.constraint(equalTo: errorBannerContainer.leadingAnchor, constant: 12), - errorBannerImageView.widthAnchor.constraint(equalToConstant: 20), - errorBannerImageView.heightAnchor.constraint(equalToConstant: 20), - errorBannerImageView.bottomAnchor.constraint(lessThanOrEqualTo: errorBannerContainer.bottomAnchor, constant: -12), - - errorBannerLabel.topAnchor.constraint(equalTo: errorBannerContainer.topAnchor, constant: 12), - errorBannerLabel.leadingAnchor.constraint(equalTo: errorBannerImageView.trailingAnchor, constant: 8), - errorBannerLabel.trailingAnchor.constraint(equalTo: errorBannerContainer.trailingAnchor, constant: -12), - errorBannerLabel.bottomAnchor.constraint(equalTo: errorBannerContainer.bottomAnchor, constant: -12), - ]) -} - -private func showErrorBanner(_ message: String) { - errorBannerLabel.text = message - errorBannerContainer.isHidden = false - UIView.animate(withDuration: 0.25) { - self.errorBannerContainer.alpha = 1 - } - // Auto-dismiss after 4 seconds - DispatchQueue.main.asyncAfter(deadline: .now() + 4) { [weak self] in - self?.hideErrorBanner() - } -} - -private func hideErrorBanner() { - guard !errorBannerContainer.isHidden else { return } - UIView.animate(withDuration: 0.25, animations: { - self.errorBannerContainer.alpha = 0 - }) { _ in - self.errorBannerContainer.isHidden = true - } -} -``` - -- [ ] **Step 2: Handle repeated needSecondFactor with error message** - -Update `showSecondFactorPrompt` to show the server message as the alert body when retrying: - -```swift -private func showSecondFactorPrompt(requirement: SecondFactorRequirementState) { - DispatchQueue.main.async { [weak self] in - guard let self else { return } - let isFirstAttempt = !self.hasShownSecondFactor - self.hasShownSecondFactor = true - - let title = isFirstAttempt ? "两步验证" : "验证码错误" - let message = requirement.message ?? "请输入验证器中的 6 位代码" - - let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) - alert.addTextField { field in - field.placeholder = "6 位验证码" - field.keyboardType = .numberPad - field.textContentType = .oneTimeCode - } - alert.addAction(UIAlertAction(title: "确定", style: .default) { [weak self] _ in - guard let code = alert.textFields?.first?.text?.trimmingCharacters(in: .whitespacesAndNewlines), - !code.isEmpty else { return } - self?.captchaDialog?.retryWithSecondFactor(code) - }) - alert.addAction(UIAlertAction(title: "取消", style: .cancel) { [weak self] _ in - self?.setLoginLoading(false) - self?.dismissCaptchaDialog() - }) - self.present(alert, animated: true) - } -} -``` - -- [ ] **Step 3: Verify build** - -Run: `xcodegen generate --spec apps/ios-app/project.yml && xcodebuild -project apps/ios-app/Fire.xcodeproj -scheme Fire -destination 'generic/platform=iOS Simulator' build 2>&1 | tail -20` - -Expected: Build succeeds. - -- [ ] **Step 4: Commit** - -```bash -git add apps/ios-app/App/Views/Other/FireLoginViewController.swift -git commit -m "polish(login): animated error banner + 2FA retry messaging" -``` - ---- - -## Post-Implementation Verification - -### Task 8: Manual Flow Verification - -- [ ] **Step 1: Verify cold-start login flow** - -1. Clear app data / sign out -2. Launch app → should land on onboarding -3. Tap "登录 LinuxDo" -4. Verify: login page shows logo, inputs, remember checkbox, login button, forgot password, other methods — **no hCaptcha visible, no network activity** -5. Type credentials, tap login -6. Verify: CF challenge appears if needed, then captcha dialog appears with hCaptcha -7. Complete hCaptcha → verify login succeeds → app enters main interface - -- [ ] **Step 2: Verify remember-password** - -1. Log out -2. Open login page → verify saved credentials auto-filled, checkbox on -3. Uncheck "记住密码", log in -4. Log out again -5. Open login → verify fields are **empty** (old saved credentials were cleared) - -- [ ] **Step 3: Verify 2FA flow** - -1. Log in with a 2FA-enabled account -2. Verify 2FA prompt appears after hCaptcha -3. Enter wrong code → verify "验证码错误" message with server error -4. Enter correct code → verify login succeeds - -- [ ] **Step 4: Verify WebView fallback** - -1. Tap "忘记密码?" → verify WebView loads `/password-reset` -2. Close, tap "其他方式登录" → verify WebView loads `/login` - -- [ ] **Step 5: Verify error states** - -1. Enter wrong password → verify inline error banner (not UIAlertController) -2. Verify banner auto-dismisses after 4 seconds - -- [ ] **Step 6: Commit final state** - -```bash -git add -A -git commit -m "feat(login): native login page redesign complete - -- FireLoginViewController: pure-native UIKit login page -- FireCaptchaLoginDialogController: hCaptcha + login request dialog -- Login flow: credentials first → CF on-demand → hCaptcha → finalize -- Remember-password checkbox threaded to save API -- WebView fallback for OAuth/forgot-password -- Animated error banner" -``` - ---- - -## Spec Coverage Checklist - -| Spec Requirement | Task | -|-----------------|------| -| Native UIKit login page (logo, inputs, checkbox, buttons) | Task 3 | -| hCaptcha dialog VC with live WebView | Task 1 | -| CF on-demand trigger (not page-open) | Task 2, Task 3 | -| `rememberCredential` param threaded to finalize | Task 2 | -| VC owns dialog present/dismiss, ViewModel async capabilities | Task 2, Task 3 | -| Live WebView handoff for cookie extraction | Task 1, Task 3 | -| Delete FireLoginWebView.swift | Task 4 | -| Forgot password → WebView /password-reset | Task 6 | -| Other login methods → WebView /login | Task 6 | -| Error states per WebViewLoginDecisionState | Task 3, Task 7 | -| 2FA retry in same live WebView | Task 1, Task 3 | -| CF retry within dialog (reuse failed csrf attempt args) | Task 5 | -| Animated inline error banner | Task 7 | diff --git a/docs/superpowers/plans/2026-06-16-topic-push-and-tab-scroll-to-top.md b/docs/superpowers/plans/2026-06-16-topic-push-and-tab-scroll-to-top.md deleted file mode 100644 index cf8425e1..00000000 --- a/docs/superpowers/plans/2026-06-16-topic-push-and-tab-scroll-to-top.md +++ /dev/null @@ -1,92 +0,0 @@ -# Secondary Stack and Full-Screen Pop Implementation Record - -**Status:** Updated 2026-07-24 — all product secondary pages use an app-root -full-screen stack that covers the tab shell (Android multi-Activity analogue). - -## Current Behavior - -- Topic route requests still enter through `FireNavigationState.presentedTopicRoute`. -- Arbitrary secondary view controllers enter through - `FireRootCoordinator.presentSecondary(_:)`. -- Typed secondary routes (topic / profile / badge) also enter through - `FireRootCoordinator.presentSecondaryRoute(_:)` / - `FireAppRouteControllerFactory.presentSecondaryRoute`. -- `FireRootCoordinator` owns one **app-root secondary `FireMainNavigationController`** - presented full-screen above `FireMainTabBarController`. -- The tab shell (including `UITabBar`) is **not** mutated: there is no - `hidesBottomBarWhenPushed` for secondary product pages. The secondary page simply - covers the tab bar the same way a second Android Activity covers the first. -- If a secondary stack is already presented, additional secondary opens **push** - onto that stack. -- Nested topic links reuse - `FireAppRouteControllerFactory.makeTopicRoutePresenter` with a provider that - returns the secondary navigation controller (or `appRoot` which single-flights - through `presentedTopicRoute` and then pushes onto the same stack). -- Logout / switch to onboarding dismisses the secondary stack without leaving a - stale presented host. - -### Surfaces that open on the secondary stack - -| Entry | How | -|---|---| -| Topic detail (home / notifications / deep link) | `presentTopicRoute` → secondary stack | -| Search | `FireRootCoordinator.presentSecondary(FireSearchViewController)` | -| Profile content (bookmarks, history, drafts, messages, badges, follow lists) | Profile `pushFullScreen` → `presentSecondary` | -| Settings / LDC / CDK / invites | Profile `pushFullScreen` / hosting → `presentSecondary` | -| Notification history | `presentSecondary` | -| Public profile / badge routes | `presentSecondaryRoute` | -| Nested drill-down already on secondary | local `navigationController.push` | - -Tab roots stay tab-owned: home feed, notifications list, profile root. - -## Full-Screen Interactive Pop / Dismiss - -`FireMainNavigationController` owns the WeChat-style full-screen back gesture: - -- The system edge-only `interactivePopGestureRecognizer` is disabled. -- A full-screen `UIPanGestureRecognizer` is attached to the navigation - controller's root view. -- A pan can begin when either: - - the stack has more than one controller (in-stack pop), or - - `allowsInteractiveDismissWhenAtRoot` is true and this controller is presented - (interactive dismiss of the whole secondary stack, revealing the untouched tab shell). -- Progress is driven by `UIPercentDrivenInteractiveTransition`. -- In-stack pop uses a card animator plus a **navigation-bar snapshot** so chrome - rides with the outgoing page instead of flipping to the destination bar early. -- Present / dismiss of the secondary stack use the same card push/pop motion - (slide from right / slide out to right with light parallax on the under page). -- Root secondary pages without their own left bar item get an explicit back control - that dismisses the stack. -- The gesture finishes when either progress reaches `0.34` or rightward velocity - reaches `720 pt/s`; otherwise it cancels. - -`FireTopicDetailViewController` already supports the presented-root path: - -- Root of a presented secondary stack shows an explicit back control that dismisses. -- Its legacy edge-only non-interactive gesture stays disabled under - `FireMainNavigationController` so there is one authoritative back gesture. - -## Deliberately Separate Work - -Tab re-tap scroll-to-top is not part of this implementation. Modal tools -(composer, category/tag pickers, sheets) remain `present`ed modals and are not -secondary stack pages. - -## Primary Files - -| File | Current responsibility | -|---|---| -| `apps/ios-app/App/Core/FireRootCoordinator.swift` | Presents / pushes the app-root secondary stack; dismisses it on logout. | -| `apps/ios-app/App/Core/FireMainTabBarController.swift` | Tab shell + `FireMainNavigationController` (full-screen pop, interactive root dismiss, card transitions, nav-bar snapshot). | -| `apps/ios-app/App/Routing/FireAppRouteControllerFactory.swift` | Builds route VCs, nested presenters, `presentSecondaryRoute`. | -| `apps/ios-app/App/Routing/FireAppRoute.swift` | `presentsAsSecondaryPage` classification. | -| `apps/ios-app/App/Views/Profile/FireProfileViewController.swift` | Profile secondary entries via `presentSecondary`. | -| `apps/ios-app/App/Views/Home/FireHomeView.swift` | Search + secondary route opens via root stack. | -| `apps/ios-app/Tests/Unit/FireAppRouteTests.swift` | Route classification + pop / dismiss gate tests. | - -## Verification - -```bash -xcodebuild test -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' -only-testing:FireTests/FireAppRouteTests CODE_SIGNING_ALLOWED=NO -xcodebuild build -scheme Fire -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.3.1' CODE_SIGNING_ALLOWED=NO -``` diff --git a/docs/superpowers/plans/2026-07-31-android-compose-ui-unification.md b/docs/superpowers/plans/2026-07-31-android-compose-ui-unification.md deleted file mode 100644 index 42291c12..00000000 --- a/docs/superpowers/plans/2026-07-31-android-compose-ui-unification.md +++ /dev/null @@ -1,374 +0,0 @@ -# Android Compose UI Unification Implementation Plan - -> **For agentic workers:** Implement task-by-task. Checkboxes track progress. -> **Spec (authoritative product model):** `docs/superpowers/specs/2026-07-31-android-compose-ui-unification-design.md` - -**Goal:** Android login matches iOS **visual + interaction**: single onboarding surface with `validating` / `credential` / `loggingIn`, Compose theme tokens from `FireTheme.swift`, captcha/OAuth as Web surface (not form host), flame launcher icon. - -**Architecture:** Fragment hosts Compose (`ComposeView`). `OnboardingFragment` + `OnboardingViewModel` own the product login UI. `LoginWebViewFragment` (or DialogFragment) is a **Web-only** surface for hCaptcha / OAuth / passkey / CF. Session code under `session/` is reused; only missing host stores (`FireLastLoginMethod`) are added. - -**Tech Stack:** Kotlin 2.2.0 + `org.jetbrains.kotlin.plugin.compose`, Compose BOM (pin latest stable at implement time; doc example `2025.06.00`), Material3, Fragment, Navigation Component (graph IDs stable), WebView via `AndroidView`. - ---- - -## Global Constraints - -- Paths are repo-root relative under `apps/android-app/`. -- **Do not** ship “welcome button → second page with form + browser” as the final UX. That is the *current* Android model to replace. -- **Do not** put credential fields inside the primary WebView host in the end state. -- **Do not** change Rust / UniFFI login protocol for this workstream. -- **Do not** delete `FireColors.kt` / `fire_colors.xml` while other pages use them. -- **Do not** modify iOS. -- Appearance: `system` | `light` | `dark` only (no OLED). -- Login primary copy: **Chinese**, aligned with iOS (`用户名或邮箱`, `密码`, `登录`, `登录中…`, …). -- Material icons: use `Icons.Filled.Visibility` / `VisibilityOff` (or drawables). **Never** `Icons.Default.Eye` (does not exist). -- Business logic stays on main thread boundaries consistent with existing Fragment coroutines (`lifecycleScope`). -- Prefer `StateFlow` / `mutableStateOf` for Compose updates; do not rely on `ComposeView.invalidate()`. - ---- - -## File Structure - -| File | Role | -|------|------| -| `src/main/java/com/fire/app/core/theme/compose/FireAppearancePreference.kt` | system/light/dark + prefs | -| `src/main/java/com/fire/app/core/theme/compose/FireColorTokens.kt` | light/dark color constants from iOS | -| `src/main/java/com/fire/app/core/theme/compose/FireColorScheme.kt` | Material3 scheme + extended tokens | -| `src/main/java/com/fire/app/core/theme/compose/FireShapes.kt` | radii / sizes | -| `src/main/java/com/fire/app/core/theme/compose/FireTypography.kt` | type scale | -| `src/main/java/com/fire/app/core/theme/compose/FireDimens.kt` | spacing | -| `src/main/java/com/fire/app/core/theme/compose/FireTheme.kt` | `FireTheme { }` entry + `fireExtended` | -| `src/main/java/com/fire/app/session/FireLastLoginStore.kt` | last login method persistence | -| `src/main/java/com/fire/app/ui/auth/FireExternalLoginMethod.kt` | provider enum | -| `src/main/java/com/fire/app/ui/auth/FireLastLoginMethod.kt` | last-method enum (or co-locate with store) | -| `src/main/java/com/fire/app/ui/auth/OnboardingViewModel.kt` | phase + form + orchestration | -| `src/main/java/com/fire/app/ui/auth/compose/OnboardingScreen.kt` | full page composition | -| `src/main/java/com/fire/app/ui/auth/compose/ValidatingContent.kt` | validating phase UI | -| `src/main/java/com/fire/app/ui/auth/compose/CredentialForm.kt` | fields + options + login button | -| `src/main/java/com/fire/app/ui/auth/compose/ExternalLoginRow.kt` | 6 providers | -| `src/main/java/com/fire/app/ui/auth/compose/LoginWebChrome.kt` | chrome for **Web surface only** | -| `src/main/res/drawable/ic_login_{google,github,x,discord,apple,passkey}.xml` | brand icons | -| Modify: `build.gradle.kts` | Compose plugin + deps | -| Modify: `OnboardingFragment.kt` | ComposeView host | -| Modify: `LoginWebViewFragment.kt` | Web-only; accept mode/args; remove form UI | -| Modify: `strings.xml` | Chinese login strings | -| Modify: `ic_launcher_foreground.xml`, `colors.xml` | flame icon | - ---- - -## Phase 1: Compose Dependencies + Theme Foundation - -### Task 1: Enable Compose in Gradle - -**Files:** `apps/android-app/build.gradle.kts` - -- [x] Add plugin `id("org.jetbrains.kotlin.plugin.compose") version "2.2.0"` next to Kotlin Android plugin. -- [x] `buildFeatures { compose = true }` (keep `viewBinding = true`). -- [x] Dependencies (BOM version: use latest stable at implement time): - -```kotlin -val composeBom = platform("androidx.compose:compose-bom:2025.06.00") -implementation(composeBom) -implementation("androidx.compose.ui:ui") -implementation("androidx.compose.ui:ui-tooling-preview") -implementation("androidx.compose.material3:material3") -implementation("androidx.compose.material:material-icons-extended") // if using Visibility icons -implementation("androidx.activity:activity-compose:1.10.1") -implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7") -implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7") -debugImplementation("androidx.compose.ui:ui-tooling") -``` - -- [x] `cd apps/android-app && ./gradlew assembleDebug` → SUCCESS -- [x] Commit: `build(android): enable Jetpack Compose for login unification` - -### Task 2: FireAppearancePreference + tests - -**Files:** - -- Create `.../core/theme/compose/FireAppearancePreference.kt` -- Create `.../src/test/java/com/fire/app/core/theme/compose/FireAppearancePreferenceTest.kt` - -API: - -```kotlin -enum class FireAppearancePreference(val storageKey: String) { - System("system"), Light("light"), Dark("dark"); - companion object { - const val STORAGE_KEY = "fire.appearancePreference" - fun load(context: Context, prefsName: String = "fire.appearance"): FireAppearancePreference - fun save(context: Context, preference: FireAppearancePreference, prefsName: String = "fire.appearance") - } -} -``` - -- [x] Unit tests: default system; round-trip light/dark; garbage → system -- [x] Add Robolectric only if project does not already have a preferred Android unit-test stack; otherwise use existing patterns -- [x] Commit: `feat(android): add FireAppearancePreference for Compose theme` - -### Task 3: Color tokens from iOS - -**Files:** `FireColorTokens.kt` - -- [x] Port light/dark tokens from `apps/ios-app/App/Core/FireTheme.swift` using `round(c*255)`. -- [x] Dark ink/subtle/tertiary: `Color.White.copy(alpha = …)`, not opaque hex. -- [x] Include: accent*, canvas*, surface*, chrome*, iconWell, softSurface, track, ink*, divider, chromeBorder, semantic success/warning/error/info, skeleton*, tagChip* (as needed for login + future pages). -- [x] Commit: `feat(android): map FireTheme.swift colors to Compose tokens` - -### Task 4: ColorScheme + shapes + typography + FireTheme - -**Files:** `FireColorScheme.kt`, `FireShapes.kt`, `FireTypography.kt`, `FireDimens.kt`, `FireTheme.kt` - -- [x] `data class FireExtendedColors(...)` + `CompositionLocalProvider` -- [x] `val MaterialTheme.fireExtended` accessor -- [x] `FireTheme(preference, content)` resolves system dark via `isSystemInDarkTheme()` -- [x] Shapes: 14 / 12 / 10 / 8 / pill; page inset 16; section 16 -- [x] `@Preview` light + dark smoke composable optional -- [x] `assembleDebug` SUCCESS -- [x] Commit: `feat(android): add FireTheme Compose entry and extended tokens` - ---- - -## Phase 2: Login Assets + Last-Login Store - -### Task 5: Provider icons - -**Files:** `src/main/res/drawable/ic_login_*.xml` (6) - -- [x] Source from iOS `LoginProvider*.imageset` (preserve multicolor where needed; use PNG density buckets if vector loses color) -- [x] Naming: `ic_login_google`, `ic_login_github`, `ic_login_x`, `ic_login_discord`, `ic_login_apple`, `ic_login_passkey` -- [x] Commit: `feat(android): add login provider brand icons` - -### Task 6: Enums + last-login store - -**Files:** - -- `FireExternalLoginMethod.kt` — align discourse keys with iOS (`google_oauth2`, `github`, `twitter`, `discord`, `apple`, passkey `null`) -- `FireLastLoginMethod.kt` — password + six external -- `FireLastLoginStore.kt` — load/save via SharedPreferences or EncryptedSharedPreferences; key stable - -- [x] Mapping helpers: external ↔ last-login (password has no external icon) -- [x] Unit tests for round-trip -- [x] Commit: `feat(android): add last-login method store and provider enums` - -### Task 7: Chinese string resources - -**Files:** `src/main/res/values/strings.xml` - -- [x] Align primary login strings with iOS (see design table) -- [x] Keep technical error strings; convert user-facing login chrome to Chinese -- [x] Add a11y: show/hide password, provider content descriptions (`使用 Google 登录`, …) -- [x] Commit: `i18n(android): Chinese login copy parity with iOS` - ---- - -## Phase 3: Onboarding Compose UI (no network yet) - -### Task 8: CredentialForm + ExternalLoginRow - -**Files:** `compose/CredentialForm.kt`, `compose/ExternalLoginRow.kt` - -**CredentialForm** must include: - -- Identifier / password 48dp, 10dp corners, secondary fill + 1px separator-like border -- Eye toggle; remember row; forgot password link -- Login button 50dp accent; loading state; last-login accent border when method == password -- Callbacks only — no session calls inside the composable - -**ExternalLoginRow:** - -- “其他方式” divider label -- 6 equal chips, 52dp, 14dp radius, 24dp icons -- Highlight border when `highlighted == method` - -- [x] Compile + optional screenshot preview -- [x] Commit: `feat(android): Compose credential form and external login row` - -### Task 9: ValidatingContent + OnboardingScreen - -**Files:** `compose/ValidatingContent.kt`, `compose/OnboardingScreen.kt` - -Layout rules (from iOS): - -- Full-bleed `canvasMid` -- Horizontal inset 24dp -- Brand: flame (`ic_fire_flame` exists) + “Fire” + subtitle -- Error banner above phase content -- Phase switch: Validating | Credential (form+external) | LoggingIn (form with loading OR validating-style host message — match iOS: loggingIn uses form loading + host message) -- Optical vertical center of brand+phase block - -API sketch: - -```kotlin -@Composable -fun OnboardingScreen( - state: OnboardingUiState, - onIdentifierChange: (String) -> Unit, - onPasswordChange: (String) -> Unit, - onTogglePasswordVisibility: () -> Unit, - onToggleRemember: () -> Unit, - onLogin: () -> Unit, - onForgotPassword: () -> Unit, - onExternal: (FireExternalLoginMethod) -> Unit, - onDismissError: () -> Unit, - onCancelAutoLogin: () -> Unit, - modifier: Modifier = Modifier, -) -``` - -- [x] Commit: `feat(android): Compose OnboardingScreen with phase container` - -### Task 10: OnboardingViewModel (UI state only first) - -**Files:** `OnboardingViewModel.kt` - -- [x] Expose `StateFlow` -- [x] Form field updates + `isLoginEnabled` -- [x] Prefill from `FireCredentialStore` without wiping edits -- [x] Load `FireLastLoginStore` -- [x] Phase transitions stubbed: cold start starts `Validating` then → `Credential` after short prepare; signed-out entry → `Credential` immediately -- [x] Commit: `feat(android): OnboardingViewModel for login phase state` - -### Task 11: Wire OnboardingFragment to Compose - -**Files:** `OnboardingFragment.kt` - -- [x] Replace XML inflate with `ComposeView` + `FireTheme` + `OnboardingScreen` -- [x] Obtain ViewModel via `viewModels()` / factory with Application context -- [x] Remove dependency on `fragment_onboarding.xml` for runtime (layout file may remain unused until cleanup task) -- [x] Manual: launch app logged-out → see iOS-like form (login button not fully wired yet OK) -- [x] Commit: `refactor(android): host onboarding UI in ComposeView` - ---- - -## Phase 4: Real Login Wiring + Web Surface Shrink - -### Task 12: Redefine LoginWebViewFragment as Web surface - -**Files:** `LoginWebViewFragment.kt`, optionally `LoginCaptchaDialogFragment.kt`, nav args if needed - -**Keep methods (logic):** configure WebView, JS interface, hCaptcha callbacks, minimal login script invoke, CF retry, OAuth poll, completeLogin, 2FA dialog, cookie priming. - -**Remove from this UI:** identifier/password EditTexts, remember UI, primary “type password here” product chrome. - -**Entry contract** (args or shared ViewModel event): - -| Mode | Behavior | -|------|----------| -| `password_captcha` | Load minimal login page; run captcha; invoke `__fireLogin` with identifier/password from caller | -| `oauth` | Load `/login` or `/auth/{provider}`; poll readiness; completeLogin | -| `passkey` | Load login; click passkey control via existing script patterns | - -- [x] Store `retainedWebView`; destroy in `onDestroyView` -- [x] Chrome composable optional: close + progress only -- [x] Commit: `refactor(android): LoginWebViewFragment is captcha/OAuth web surface` - -### Task 13: Connect ViewModel → Web surface → completeLogin - -**Files:** `OnboardingViewModel.kt`, `OnboardingFragment.kt`, navigation glue - -Password path (mirror iOS): - -1. User taps **登录** → phase `LoggingIn`, message 正在准备验证… -2. Present captcha Web surface with pending identifier/password/remember -3. On hCaptcha pass → JS login → capture cookies → `FireWebViewLoginCoordinator.completeLogin` -4. Save credential if remember; save `FireLastLoginMethod.Password` -5. Navigate home when session can read authenticated API -6. On failure → phase `Credential`, show error banner, **keep typed fields** - -External path: - -1. Tap provider → Web surface mode oauth/passkey -2. On success → save last method → home - -Forgot password: open `https://linux.do/password-reset` external or in-app Custom Tab / Web surface. - -- [x] E2E password login on device -- [x] E2E at least one OAuth provider if credentials available -- [x] Commit: `feat(android): wire Compose onboarding to session login flow` - -### Task 14: Startup validating + password auto-login - -**Files:** `OnboardingViewModel.kt`, `FireAutoLoginPlanner.kt`, `PreheatGateFragment.kt` - -- [x] Cold start: show validating (“正在校验登录态…”) -- [x] If session already authenticated → host navigates home (existing shell behavior) -- [x] Else if last method is password + saved credential → auto-login (captcha sheet) with cancel -- [x] Else → credential phase -- [x] Session-expired: headless-pool external only (Google → OAuth surface + auto-start); never password auto-login -- [x] Signed-out: credential only (no auto-login) -- [x] Preheat `NotLoggedIn` → `coldStart` (not `signedOut`); explicit logout must pass `signedOut` -- [x] Commit: `feat(android): onboarding validating phase and password auto-login` - -### Task 14b: Review remediation (login parity) - -- [x] OAuth/Passkey `FireExternalLoginScripts.autoStart` on `/login` -- [x] Password captcha as light `CaptchaLoginDialogFragment` sheet; failures return to onboarding banner -- [x] `remember=false` clears stored credentials on success -- [x] Cancel auto-login copy: “已取消自动登录” (not “账号密码已失效”) -- [x] Visual: system orange CTA medium corner, system blue forgot, `- 其他方式 -`, safeDrawing, LoggingIn host chrome -- [x] Unit tests: `FireAutoLoginPlannerTest`, `FireExternalLoginScriptsTest` - ---- - -## Phase 5: App Icon + Final Verification - -### Task 15: Launcher flame icon - -**Files:** `ic_launcher_foreground.xml`, `colors.xml`, possibly mipmap PNGs - -- [x] Export from iOS `AppIcon-1024.png` (vector or PNG). Hand-drawn path is last resort. -- [x] Adaptive safe zone; compare side-by-side with iOS -- [x] Commit: `feat(android): unify launcher icon with iOS flame` - -### Task 16: Verification checklist - -- [x] `./gradlew assembleDebug` -- [x] Unit tests for appearance + last-login -- [x] Light + dark onboarding matches iOS checklist in design spec -- [ ] Password login E2E -- [x] External provider chips visible; last-login highlight works -- [ ] Keyboard does not cover fields permanently -- [x] Error banner + failed login retains fields -- [x] CF challenge path still recoverable -- [x] 2FA still works -- [x] Other tabs (Home/TopicDetail/…) unaffected -- [x] No primary UX dependency on English “Sync Login” - ---- - -## Explicit Non-Goals / Deferred - -| Item | When | -|------|------| -| Headless OAuth engine parity with iOS `FireHeadlessExternalLoginEngine` | Follow-up if password auto-login + manual OAuth chips ship first | -| OLED appearance | Later; map to dark if needed | -| Full app Compose migration | Separate workstreams per surface | -| Delete XML theme | After last XML screen migrates | -| iOS changes | Never in this branch | - ---- - -## Task → Spec Traceability - -| Spec requirement | Tasks | -|------------------|-------| -| Compose theme from iOS | 1–4 | -| Single-page onboarding IA | 8–11, 13 | -| Captcha/OAuth not form host | 12–13 | -| External providers + icons | 5–6, 8 | -| Last-login highlight | 6, 8, 13 | -| Chinese copy | 7 | -| Auto-login / validating | 14 | -| Flame icon | 15 | - ---- - -## Implementation Notes for Agents - -1. Read live iOS files listed in the design spec **before** coding UI numbers. -2. Read full `LoginWebViewFragment.kt` before shrinking it; preserve CF/OAuth edge cases. -3. Prefer small commits per task above. -4. If blocked on DialogFragment vs full-screen Web for captcha, default to **DialogFragment/bottom sheet for password captcha** and full-screen for OAuth redirects. -5. If Compose BOM version conflicts with AGP 8.11.x, pin BOM to a version known-good for that AGP; do not downgrade Kotlin below 2.2.0 without explicit approval. -6. Update this plan’s checkboxes as work completes; keep design doc as product truth if plan drifts. diff --git a/docs/superpowers/specs/2026-06-08-fire-v2-roadmap-design.md b/docs/superpowers/specs/2026-06-08-fire-v2-roadmap-design.md deleted file mode 100644 index 2f7a986e..00000000 --- a/docs/superpowers/specs/2026-06-08-fire-v2-roadmap-design.md +++ /dev/null @@ -1,533 +0,0 @@ -# Fire v2.0 大版本规划:交互体验与功能设计文档 - -> 路线方案:基础夯实 → 功能扩展 → 原生差异化 → 发布准备 -> 目标周期:16+ 周 | 交付策略:阶段化交付,每阶段有独立可验证成果 -> 核心定位:在功能对等基础上,通过原生独有体验实现差异化 -> 文档契约:1 个设计文档 + 4 个实施计划,共 52 个顶层任务(P1 17 / P2 14 / P3 15 / P4 6),由 `scripts/verify-roadmap-plan-contract.sh` 校验。架构/平台边界约束由 `scripts/verify-roadmap-architecture-constraints.sh` 校验。已勾选的 P1-P3 验收代码证据由 `scripts/verify-roadmap-implementation-evidence.sh` 校验。 - ---- - -## 一、现状评估 - -### 1.1 Rust Core — 功能完整 - -`fire-core` 已覆盖 LinuxDo 主要 API 表面。Session 生命周期(含 epoch 防重放、auth strike、CF challenge)完整;Topics/Posts/Users/Search/Notifications/MessageBus/Presence/Interactions/Creation/Chat 全部实现。LDC/CDK 已落在 `fire-models::ldc`、`fire-core::core::{ldc, cdk}` 与 `fire-uniffi-ldc`,`FireAppCore` 通过 UniFFI 向平台暴露 9 个子 handle(含 `ldc` 与 `chat`)。 - -**当前边界:** LDC 用户信息、余额/累计支付字段、OAuth 授权、登出与奖励分发已实现;独立支付历史 endpoint 在现有知识库中未被观测到,因此不作为已实现能力声明。 - -### 1.2 iOS — 功能丰富,体验有打磨空间 - -| 模块 | 完成度 | 关键差距 | -|------|--------|----------| -| 首页/话题列表 | ★★★★☆ | Feed kind 中英文标题不一致;`FireFeedKindSelector` 与 `FilteredTopicListView` 使用不同的视觉风格 | -| 话题详情 | ★★★★★ | AsyncDisplayKit/Texture 原生运行时路径成熟;回复树展示、话题内搜索、通知级别控制已实现 | -| 通知 | ★★★★☆ | 缺上下文菜单;`notificationAlert` 事件处理为 no-op | -| 搜索 | ★★★★☆ | 缺搜索结果上下文菜单 | -| 编辑器 | ★★★★☆ | Markdown 工具栏、引用插入、共享 `FireComposerTextView` 已实现;独立链接预览卡片仍未作为确认交付项 | -| 私信 | ★★★★☆ | 功能完整 | -| 个人资料 | ★★★★☆ | 缺关注列表入口的发现引导 | -| 书签/草稿 | ★★★★☆ | 功能完整 | -| 开发者工具 | ★★★★★ | APM、网络追踪、日志、诊断导出齐全 | -| 无障碍 | ★★☆☆☆ | UIKit 路径标注完善;SwiftUI 视图几乎无 `.accessibilityLabel` | -| 暗黑模式 | ★★★★☆ | 主题系统成熟;部分硬编码颜色未走 Token | -| 国际化 | ★☆☆☆☆ | 全量中文字符串硬编码,无 NSLocalizedString | -| 视觉一致性 | ★★★☆☆ | 圆角(10/12/14/16/18/20 混用)、背景色系统(至少 4 种写法)、空状态组件已建但未复用 | - -**架构问题:** -- `FireAppViewModel.swift` 已通过服务/扩展拆分降至 1431 行;session、MessageBus、登录恢复等状态编排仍保留在主门面 -- 通用分页/加载/错误模式已抽到 `FirePaginatedStore`,后续可继续迁移低风险列表 -- 多个列表视图未使用 `ListKit` 抽象(通知、私信、阅读历史、草稿、搜索) - -### 1.3 Android — 核心对齐,辅助页面已补齐 - -| 模块 | 完成度 | 关键差距 | -|------|--------|----------| -| 首页/话题列表 | ★★★★☆ | 功能与 iOS 对齐 | -| 话题详情 | ★★★★★ | 回复树展示、话题内搜索、通知级别、Reaction 增强、书签提醒均在 View/XML 原生路径实现 | -| 通知 | ★★★★☆ | 通知列表和通知历史页可用;FCM 仅处理本地 token/message 事件,后端 token 注册 API 尚不可用 | -| 搜索 | ★★★★☆ | 功能完整 | -| 编辑器 | ★★★★★ | Markdown 工具栏、引用插入、预览路径可用 | -| 私信 | ★★★★☆ | 功能完整 | -| 个人资料 | ★★★☆☆ | 缺关注列表、徽章详情、活动时间线 | -| 书签 | ★★★★☆ | 功能完整 | -| 草稿列表 | ★★★★☆ | `DraftsFragment` + Paging 数据流可用 | -| 阅读历史 | ★★★★☆ | `ReadHistoryFragment` + Paging 数据流可用 | -| 推送通知(FCM) | ★★★☆☆ | `FireFirebaseMessagingService`、通知 channel、payload 解析与本地通知可用;token 注册需等待后端/API | -| 开发者工具 | 未实现 | APM、诊断等无对应页面 | -| 无障碍 | ★★☆☆☆ | 基础 content descriptions,覆盖不全 | - ---- - -## 二、P1 基础夯实(4-5 周) - -> 目标:消除视觉不一致、补齐 Accessibility、统一架构模式、Android 核心页面补全 - -### 2.1 视觉 Token 统一(iOS + Android,1 周) - -**圆角 Token 规范化:** - -当前混用 10/12/14/16/18/20 六种圆角。收敛为 4 个 Token: - -| Token | 值 | 用途 | -|-------|----|------| -| `FireTheme.cornerRadius` | 14 | 大卡片、面板、Sheet(收紧,避免过度圆润) | -| `FireTheme.mediumCornerRadius` | 12 | 行级组件、状态芯片、分类标签 | -| `FireTheme.smallCornerRadius` | 10 | 输入框、搜索栏、小按钮 | -| `FireTheme.pillRadius` | .infinity | 胶囊形标签、信任等级药丸 | - -全局替换硬编码值为 Token 引用。 - -**背景色 Token 统一:** - -将 `Color(.systemGroupedBackground)`、`Color(.secondarySystemBackground)`、`FireSceneBackground`、`.scrollContentBackground(.hidden)` 统一收敛到 `FireTheme` 的 3 个语义色: - -| Token | 语义 | 适配值 | -|-------|------|--------| -| `FireTheme.canvas` | 页面最底层 | 自动适配 light/dark | -| `FireTheme.surface` | 卡片/面板层 | 自动适配 light/dark | -| `FireTheme.surfaceSecondary` | 分组/凹陷区 | 自动适配 light/dark | - -**Feed Kind Selector 统一:** - -将 `FireFilteredTopicListView` 中的简易 `Capsule().fill()` 替换为 `FireFeedKindSelector`(使用 `matchedGeometryEffect`),确保同一交互在首页和筛选页视觉一致。 - -**Feed Kind 标题语言统一:** - -当前 `TopicListKindState.title` 返回英文("Latest", "New"),而 `privateMessagesInbox` 返回中文。统一为中文标题,为后续国际化铺路。 - -### 2.2 无障碍标注补全(iOS,1 周) - -**SwiftUI 视图批量标注:** - -对以下视图添加 `.accessibilityLabel()` / `.accessibilityHint()`: -- `FireTopicRow` — 读取话题标题、回复数、查看数、分类 -- `FireComposerView` — 编辑区、工具栏按钮(上传/预览) -- `FireSearchView` — 搜索字段、结果行、筛选器 -- `FireHomeView` — 创建按钮、搜索按钮 -- `FireBookmarksView` — 书签行、删除操作 -- `FireDraftsViewController` — 草稿行、继续编辑、删除 -- `FireOnboardingView` — 登录按钮、品牌区域 -- `FireNotificationsViewController` / `FireNotificationHistoryViewController` — 通知行、标记已读 -- `FireProfileView` — 各统计项、操作按钮 - -**加载骨架屏标注:** -- 所有 skeleton/placeholder 视图标记 `.accessibilityHidden(true)` -- 使用 `.accessibilityAnnouncement` 在加载完成时播报 - -**按钮标签:** -- 所有仅图标按钮添加 `accessibilityLabel` -- 添加 `accessibilitySortPriority` 确保关键元素优先朗读 - -### 2.3 暗黑模式修复(iOS,3 天) - -- 替换 `FireComposerView` 中的 `Color.black.opacity(0.06)` 为自适应 `FireTheme.divider` -- 替换 `FireComposerView` 中的 `Color.black.opacity()` 描边为 `FireTheme.border` -- 检查所有 `Color.black`/`Color.white` 硬编码用法,替换为语义色 - -### 2.4 架构统一 — 通用分页 Store 提取(iOS + Android,1 周) - -**iOS:提取 `FirePaginatedStore`** - -当前 8 个 ViewModel 独立实现 `hasLoadedOnce`、`isLoading`、`isLoadingMore`、`errorMessage`、分页加载逻辑。提取为: - -``` -FirePaginatedStore - @Published items: [Item] - @Published isLoading: Bool - @Published isLoadingMore: Bool - @Published hasLoadedOnce: Bool - @Published blockingError: String? - @Published nonBlockingError: String? - - func load(forceRefresh: Bool) - func loadMore() - func reset() -``` - -受益的 ViewModel: -- `FireFilteredTopicListViewModel` -- `FirePrivateMessagesViewModel` -- `FireBookmarksViewModel` -- `FireReadHistoryViewModel` -- `FireDraftsViewModel` -- `FireNotificationStore`(recent + full 合并) -- `FireSearchStore` - -**Android:同等地提取 `PaginatedViewModel` 基类。** - -### 2.5 空状态组件复用(iOS + Android,3 天) - -`FireEmptyFeedState` 已存在于 `FireComponents.swift` 但从未被使用。各视图自建空状态。 - -统一方案: -- 所有列表视图使用 `FireEmptyFeedState`(或其 Android 等价物) -- 支持 3 种状态:空数据、加载失败、无搜索结果 -- 配合 Shimmer 动画替换静态 `.redacted(reason: .placeholder)` - -### 2.6 上下文菜单(iOS + Android,3 天) - -为以下元素添加长按上下文菜单: - -| 元素 | 菜单项 | -|------|--------| -| 话题行(首页/搜索/书签) | 收藏、分享、在新窗口打开、静音/关注 | -| 通知行 | 标记已读、跳转到话题、跳转到用户 | -| 搜索结果行 | 收藏、分享 | - -### 2.7 Android 缺失页面补全(Android,已完成) - -**草稿列表页:** -- `DraftsFragment` + `DraftsViewModel` 已接入 -- Paging 加载、继续编辑(跳转到对应编辑器)、删除错误上报可用 -- Rust 核心 `fetchDrafts()` / `deleteDraft()` 已通过 Android session store 暴露 - -**推送通知(FCM):** -- Firebase Cloud Messaging 依赖和 Manifest service 已接入 -- `FireFirebaseMessagingService` 处理 token refresh 与消息 payload -- 通知 Channel 和本地通知展示已配置 -- 后端 token 注册 API 尚不可用,当前只记录 token refresh 诊断并处理本地通知 - -**通知历史全屏页:** -- `NotificationHistoryFragment` + `NotificationsViewModel` 已接入 -- 支持按今天/昨天/更早分组显示、分页加载和跳转 - -**阅读历史页:** -- `ReadHistoryFragment` + `ReadHistoryViewModel` 已接入 -- 调用 Rust 核心 `fetchReadHistory()` 分页加载 - -**话题阅读计时:** -- Android `TopicTimingTracker` 已集成到话题详情生命周期 -- 通过 Rust 核心报告阅读时间 - -### 2.8 `FireAppViewModel` 拆分启动(iOS,已完成) - -`FireAppViewModel.swift` 当前 1431 行,满足 `<1500` 验收线。P1 已提取最独立的服务与 facade 扩展: - -1. **`FireTopicInteractionService`** — 收藏、Reaction、投票、标记等话题内交互 -2. **`FireNotificationService`** — 通知获取、标记已读、计数 -3. **`FireSearchService`** — 搜索执行、结果管理 -4. **`FireAppViewModelSupport.swift`** — 支撑错误、认证展示状态、Cloudflare cookie snapshot、状态观察协调器和搜索 scope -5. **`FireAppViewModel+Diagnostics.swift`** — 日志、网络 trace、APM 与支持包导出 facade -6. **`FireAppViewModel+Profile.swift`** — 个人资料、关注、邀请、徽章、LDC/CDK facade -7. **`FireAppViewModel+RecoveryURLs.swift`** — Cloudflare 恢复 WebView URL 构建 - -`FireAppViewModel` 保留 session 管理、MessageBus 协调、登录/Cloudflare 恢复、路由等状态性核心职责。 - ---- - -## 三、P2 功能补全(5-6 周) - -> 目标:补齐 API 表面曾缺失的功能,LDC/CDK OAuth 优先 - -### 3.1 LDC Credit / CDK OAuth(全栈,已完成) - -**Rust 层:** - -`fire-core` 已新增 `src/core/ldc.rs` 和 `src/core/cdk.rs`: - -- LDC OAuth 授权 URL 生成 → 加载审批页 → 用户确认 → 回调换取 Token → 获取用户信息(余额、累计支付字段) -- CDK OAuth 对称流程(不同 user-info 结构) -- Connect 审批页 HTML 解析(授权确认链接提取) -- LDC 奖励/分发 API(Basic auth) - -`fire-models` 新增对应模型类型,`fire-uniffi-ldc` 暴露一个共享 OAuth 机制的 LDC/CDK handle。当前实现覆盖 LDC `user-info` 中的余额/累计支付字段与 CDK `score`,不声明独立 LDC 支付历史列表,因为当前知识库未观测到对应 endpoint。 - -**iOS 层:** - -- 个人资料页新增「LDC 信用」入口 → 授权绑定、余额/累计支付字段和状态查看 -- 「CDK 连接」入口 → 授权绑定、查看状态 -- Connect 审批页由平台 WebView/原生跳转承载,Rust 只负责授权链接提取与回调编排 - -**Android 层:** - -- `LDCFragment` / `CDKFragment` 对称实现 iOS 的 LDC/CDK UI - -### 3.2 回复树展示(iOS + Android,已完成) - -Rust 模型层提供 `TopicTreeRow` / `TopicTreePresentation`。原生 UI 层已收口为 Fire 的回复形阅读体验: - -**话题详情页固定使用回复树展示:** -- iOS / Android 均消费 Rust tree presentation 的顺序、depth、parent 元数据 -- 不保留线性/平铺展示选择入口 -- 不维护平台侧第二套 row projection 或数据源 - -### 3.3 编辑器增强(iOS + Android,已完成) - -**Markdown 工具栏:** -- 在键盘上方添加格式化快捷栏:粗体、斜体、删除线、代码、代码块、引用、有序/无序列表、链接、图片 -- 点击按钮在光标位置插入对应 Markdown 标记 - -**引用插入:** -- 话题详情中选中帖子内容 → 「引用回复」→ 自动在编辑器中插入 `[quote]` 块 - -**链接预览:** -- 未作为已验收交付项;当前编辑器预览渲染 Markdown 内容和图片占位,不声明外链 metadata 预览卡片 - -**PostEditorView 升级:** -- `FirePostEditorView` 已从基础 `TextEditor` 升级为 `FireComposerTextView`,与主编辑器保持一致 - -### 3.4 话题通知级别控制(iOS + Android,已完成) - -Rust 已有 `setTopicNotificationLevel` API,原生层已接入: - -- 话题详情工具栏新增「通知」按钮 -- 弹出选择:静音(muted)/常规(regular)/跟踪(tracking)/关注(watching) -- 状态反映在工具栏图标上 - -### 3.5 表情/Reaction 选择器增强(iOS + Android,已完成) - -- 扩展现有 Reaction 选择器,展示可用 Reaction 列表(Rust 已有 `fetchAvailableReactions` API) -- 支持搜索表情 -- 展示 Reaction 用户列表 - -### 3.6 书签提醒 UI(iOS + Android,已完成) - -Rust 已有 bookmark reminder API,原生层已接入: - -- 书签编辑器中的「提醒」日期选择器 -- 提醒触发时的本地通知 -- 提醒管理视图(列出所有待处理提醒) - -### 3.7 话题内搜索(iOS + Android,已完成) - -- 话题详情页工具栏新增搜索按钮 -- 搜索面板输入关键词 -- 搜索已加载 `renderDocument.plainText`,高亮当前匹配帖子并跳转 -- 支持上/下一个匹配导航 - ---- - -## 四、P3 原生差异化(5-6 周) - -> 目标:在坚实的功能基础上,叠加原生端独有的体验优势 - -### 4.1 iOS Widget(已完成) - -**今日热门 Widget(小/中/大):** -- Small:未读数 + 最新话题标题 -- Medium:2-3 条热门话题 -- Large:5 条热门话题 + 分类标签 - -**未读数 Widget:** -- Small 圆形/矩形显示未读通知数 -- 点击跳转到通知页 - -**技术方案:** -- WidgetKit + SwiftUI -- 通过 App Group 共享数据 -- App 主进程从 Rust-backed 首页/通知状态写入共享 UserDefaults;Widget 扩展只读取 App Group 快照,不调用 UniFFI - -### 4.2 Android Widget(已完成) - -**RemoteViews Widget:** -- 未读通知数 -- 热门话题列表 -- 使用 `AppWidgetProvider` + `RemoteViews`,避免在 View/XML 宿主中引入 Compose/Glance - -### 4.3 Haptic 反馈全面覆盖(iOS,已完成) - -基于既有 `FireMotion` 层扩展到: - -| 交互 | 反馈 | -|------|------| -| 点赞/取消点赞 | `.selectionChanged` | -| Reaction 切换 | `.selectionChanged` | -| 收藏/取消收藏 | `.selectionChanged` | -| 下拉刷新完成 | `.success` | -| 发送成功 | `.success` | -| 发送失败 | `.error` | -| Tab 切换 | `.selectionChanged`(轻) | -| 上下文菜单弹出 | `.selectionChanged` | -| 长按操作 | `.mediumImpact` | - -### 4.4 Toast/Snackbar 组件(iOS + Android,已完成) - -替代非关键反馈使用的 `.alert()`(阻塞交互): - -- 编辑器自动保存确认 -- 草稿已保存 -- 操作成功(收藏、Reaction) -- 网络恢复提示 - -非模态、自动消失、不阻断用户操作流。 - -### 4.5 离线缓存层(iOS + Android,已完成) - -**目标:** 网络不可用时显示上次成功加载的数据而非空白错误页。 - -**策略:** -- Rust `fire-store` SQLite read-through cache 已覆盖话题列表和通知列表 -- 成功加载后写缓存;网络错误时优先返回缓存页并带出 cached metadata -- iOS/Android 首页和通知页展示离线提示条 -- 写操作未队列化;当前仍走在线写入路径,避免引入未验证的重试语义 - -### 4.6 Shimmer 加载动画(iOS + Android,已完成) - -替换静态 `.redacted(reason: .placeholder)`: - -- 渐变光效从左到右扫过 -- 颜色适配 light/dark 模式 -- 可配置动画速度 -- 应用于所有列表骨架屏 - -### 4.7 iOS Siri 快捷指令(已完成) - -- 「查看未读」— 跳转到通知页 -- 「搜索话题」— 打开搜索页并传入查询 -- 「查看个人资料」— 跳转到个人资料 -- 通过 `AppIntents` 框架实现 - -### 4.8 Android Material You 适配(已完成) - -- Dynamic Color 主题 -- 随系统壁纸变化的应用色调 -- 边缘到边缘渲染 -- Predictive Back Gesture 支持 - -### 4.9 深色模式精细调校(iOS + Android,已完成) - -在现有主题系统基础上: -- OLED 纯黑选项(iOS/Android) -- 跟随系统/手动切换保持不变 -- 确保所有自定义组件在深色模式下对比度合格 - ---- - -## 五、P4 发布准备(2-3 周) - -### 5.1 App Store / Play Store 素材 - -- 应用截图(6.5" / 5.5" iPhone,7" / 10" iPad,多种 Android 尺寸) -- 应用预览视频 -- 应用描述(中英文) -- 关键词优化 - -当前已建素材目录、store listing draft 和 `scripts/verify-marketing-assets.sh`;最终 release-candidate 截图、视频取舍和 Play feature graphic 仍需人工产出/审批并记录证据。 - -### 5.2 合规与政策 - -- 隐私政策文档(数据收集声明) -- App Store 数据收集问卷 -- Google Play 数据安全声明 -- 第三方库许可证归集 - -当前已有隐私/数据安全草稿、iOS app/widget privacy manifest、第三方许可证归集脚本、Android transitive license metadata 校验、`docs/release/privacy-review-evidence.md` 和 `scripts/verify-privacy-review-evidence.sh`;最终 maintainer/legal review 仍未完成。 - -### 5.3 TestFlight / 内部测试轨道 - -- TestFlight 外部测试组设置 -- Google Play 内部测试轨道 -- 分发邀请 -- 反馈收集机制 - -当前已有 TestFlight/Play testing 流程文档、反馈模板、`docs/release/internal-testing-evidence.md` 和 `scripts/verify-internal-testing-evidence.sh`;App Store Connect / Play Console 记录、RC 上传、tester 邀请和反馈收集仍是手动 gate。 - -### 5.4 性能回归测试 - -- 首页滚动流畅度(60fps 基线) -- 话题详情首屏加载时间(< 2s 目标) -- 内存峰值监控 -- 冷启动时间(< 3s 目标) - -当前已有 iOS `xctrace` 与 Android `adb` benchmark workflow 和 `scripts/verify-performance-benchmarks.sh`;release-build 物理设备数据尚未采集。 - -### 5.5 无障碍审核 - -- VoiceOver / TalkBack 全流程测试 -- 动态字体测试 -- Reduce Motion 测试 -- 高对比度模式测试 - -当前已有跨平台 accessibility audit checklist 和 `scripts/verify-accessibility-audit.sh`;VoiceOver、TalkBack、Dynamic Type/font-scale、Reduce Motion/haptic、高对比度/色盲检查仍需人工执行并记录结果。 - ---- - -## 六、功能优先级矩阵 - -| 功能 | 阶段 | 影响 | 复杂度 | 平台 | -|------|------|------|--------|------| -| 圆角/颜色 Token 统一 | P1 | 高 | 低 | iOS+Android | -| 通用分页 Store 提取 | P1 | 高 | 中 | iOS+Android | -| Accessibility 标注 | P1 | 高 | 中 | iOS | -| 暗黑模式修复 | P1 | 中 | 低 | iOS | -| 空状态复用 + Shimmer | P1 | 中 | 低 | iOS+Android | -| 上下文菜单 | P1 | 中 | 低 | iOS+Android | -| Android 草稿列表 | P1 | 高 | 中 | Android | -| Android 推送(FCM) | P1 | 高 | 中 | Android | -| Android 通知历史/阅读历史 | P1 | 中 | 中 | Android | -| `FireAppViewModel` 拆分 | P1 | 高 | 中 | iOS | -| LDC/CDK OAuth | P2 | 高 | 高 | 全栈 | -| 回复树展示 | P2 | 中 | 中 | iOS+Android | -| 编辑器增强 | P2 | 高 | 中 | iOS+Android | -| 话题通知级别 | P2 | 中 | 低 | iOS+Android | -| Reaction 增强 | P2 | 中 | 低 | iOS+Android | -| 书签提醒 | P2 | 低 | 低 | iOS+Android | -| 话题内搜索 | P2 | 中 | 中 | iOS+Android | -| iOS Widget | P3 | 高 | 中 | iOS | -| Android Widget | P3 | 中 | 中 | Android | -| Haptic 全面覆盖 | P3 | 中 | 低 | iOS | -| Toast/Snackbar | P3 | 中 | 低 | iOS+Android | -| 离线缓存 | P3 | 高 | 高 | iOS+Android | -| Siri 快捷指令 | P3 | 低 | 中 | iOS | -| Material You | P3 | 中 | 中 | Android | -| 深色模式精调 | P3 | 中 | 低 | iOS+Android | - ---- - -## 七、风险与缓解 - -| 风险 | 概率 | 影响 | 缓解措施 | -|------|------|------|----------| -| LDC/CDK OAuth 协议变更 | 中 | 高 | 实现前先抓包验证当前协议;保持与 `docs/knowledge/api/13-ldc-cdk-oauth.md` 同步 | -| Android FCM 集成需要后端配合 | 中 | 中 | 提前确认 push endpoint 是否就绪;如未就绪可降级为本地定时轮询 | -| `FireAppViewModel` 拆分引入回归 | 中 | 中 | 拆分前后运行全量单元测试;每次拆一个模块 | -| 离线缓存层增加存储复杂度 | 低 | 中 | 使用 Rust `fire-store` 已有 SQLite 基础;限制缓存大小和过期策略 | -| Widget 数据同步延迟 | 低 | 低 | 使用 App Group + 共享 UserDefaults,数据延迟控制在 15 分钟内 | - ---- - -## 八、阶段验收标准 - -### P1 验收 -- [x] 所有已审计硬编码圆角值替换为 Token -- [x] 已审计列表视图使用 `FireEmptyFeedState` / 对等空状态路径 -- [x] P1 覆盖范围内 SwiftUI 交互元素有 `.accessibilityLabel` -- [x] 暗黑模式下已审计视觉异常修复 -- [x] `FirePaginatedStore` 覆盖搜索、通知、首页等核心分页路径 -- [x] Android 草稿列表页可用 -- [x] Android FCM service 接收 token refresh/message payload 并展示本地通知;后端 token 注册 API 尚不可用 -- [x] `FireAppViewModel.swift` 行数 < 1500(当前 1431) - -### P2 验收 -- [x] LDC 授权、余额/累计支付字段和用户信息可在 App 内查看;独立支付历史列表未作为已实现 endpoint 声明 -- [x] CDK 授权绑定流程完成 -- [x] 话题详情固定展示回复树结构 -- [x] 编辑器有 Markdown 工具栏和引用插入 -- [x] 话题通知级别可设置 -- [x] 话题内可搜索高亮 - -### P3 验收 -- [x] iOS Widget 至少 2 种尺寸可用 -- [x] Android Widget 可用 -- [x] P3 覆盖范围内的关键 iOS 交互操作有 Haptic 反馈 -- [x] Toast 组件替代非关键 `.alert()` -- [x] 离线模式下首页/通知列表页可展示 Rust read-through cache 数据 - -### P4 验收 -- [ ] App Store / Play Store 素材齐全 -- [ ] TestFlight / 内部测试轨道可分发 -- [ ] 首页滚动 60fps 无掉帧 -- [ ] 话题详情首屏 < 2s -- [ ] VoiceOver / TalkBack 全流程可操作 - -P4 repository scaffolding 已完成,并已有 store media / internal testing / privacy review / performance / accessibility / release gate / roadmap plan contract / roadmap architecture constraints / roadmap implementation evidence / roadmap acceptance 校验脚本以及 `scripts/verify-release-readiness.sh` 总入口;最终验收仍依赖手动 store media、store records/test tracks/tester invites、maintainer/legal review、release-build 物理设备 benchmark,以及 VoiceOver/TalkBack/Dynamic Type/Reduce Motion/high-contrast audit 结果。 - -Store-media 校验要求最终素材文件名不能残留 fake/mock/placeholder 类标记,截图尺寸可解析且每边至少 320px,PNG 截图和 Play feature graphic 不能是单色占位图,截图目录只能包含常规图片文件,不能有嵌套目录或替代素材路径。App Preview 若存在必须是 `preview-video/app-preview.mp4` 常规文件并包含 MP4 `ftyp` 内容;Play feature graphic 必须是精确 `1024x500` PNG。 - -手动证据校验会拒绝 Complete/Accepted 行中残留 fake/mock/placeholder/dummy/synthetic/TODO/TBD/`example.com`/`not-real`/`not real` 标记。Evidence link 必须是 fully qualified HTTP(S) URL 或指向非空文件的安全 repo-relative path,且不能使用 dead local path、local directory、malformed URL、malformed URL host、single-label URL host、localhost/`.local`/`.test`/`.invalid` 这类占位 URL host。Date 必须是真实 `YYYY-MM-DD` 日历日期且不能是未来日期,表格行必须保持 exact Markdown column shape,并转义 cell 内的 literal `|`。 - -Performance result 必须包含与指标绑定的带单位数值;多内存值必须使用 `peak` 标注峰值,否则视为歧义结果,阈值比较使用最高的已标注 peak 值。Performance 每个平台/指标只能有一行,accessibility 每个平台/screen 或平台/audit category 只能有一行;manual release gate、internal testing、privacy review 证据行也不能重复。所有 `Accepted` waiver 必须在 notes 中包含明确 approval/waiver 语义和 reason/risk/exception/no-ship 说明,避免用伪造、占位或含糊证据关闭 P4。 - -`scripts/verify-p4-release-evidence-suite.sh` 提供 release readiness 和 checked P4 acceptance 共享的非递归 P4 证据套件;`scripts/test-release-verifiers.sh` 使用临时 fixtures 回归验证 release-readiness wrapper 与这些 release verifier 的 pass/fail 行为,包括 fake evidence、malformed store media、flat PNG placeholder、unexpected screenshot/preview entries、dead local evidence path、malformed evidence URL、malformed URL host、single-label URL host、placeholder URL host、invalid or future date、placeholder metadata field、missing/extra Markdown table column、non-measurement performance result、target misses marked `Pass`、ambiguous or misleading multi-value memory result、duplicate evidence rows 和 weak accepted-waiver notes,不替代真实人工证据。 - -`scripts/verify-roadmap-architecture-constraints.sh` 校验架构/平台边界、最低 API、iOS topic-detail native runtime path 和 reference/infrastructure 边界;`scripts/verify-roadmap-implementation-evidence.sh` 校验已勾选的 P1-P3 代码证据;`scripts/verify-roadmap-p4-acceptance.sh` 要求上方 P4 验收项保持精确命名,并在任何验收框被勾选时要求 shared P4 evidence suite 先通过。 diff --git a/docs/superpowers/specs/2026-06-16-native-login-page-redesign-design.md b/docs/superpowers/specs/2026-06-16-native-login-page-redesign-design.md deleted file mode 100644 index edbd87b1..00000000 --- a/docs/superpowers/specs/2026-06-16-native-login-page-redesign-design.md +++ /dev/null @@ -1,382 +0,0 @@ -# Native Login Page Redesign - -**Date:** 2026-06-16 -**Status:** Draft (pending user spec review, revision 2) -**Related:** `references/fluxdo/` login flow, `docs/knowledge/` login protocol - -## Problem Statement - -当前 Fire iOS 的登录流程存在时序错误和架构问题: - -1. **时序错误**:用户打开登录页后立即触发 Cloudflare challenge + 加载 hCaptcha widget,此时用户尚未输入账号密码。正确流程应是用户先输入凭据、点击登录后再触发验证。 -2. **架构耦合**:`FireLoginWebView.swift`(816 行)将原生表单 UI、WebView 配置、hCaptcha 渲染、登录请求、CF 协调全部塞在一个 UIViewController 中,职责混乱。 -3. **交互体验差**:社交登录(Google/Apple/浏览器)没有入口;没有"记住密码"勾选;错误用 UIAlertController 弹窗打断体验。 - -fluxdo 参考实现(`references/fluxdo/lib/pages/login_page.dart` + `lib/widgets/auth/webview_login_dialog.dart`)已经解决了这些问题:原生表单收集凭据,点登录后按需弹 mini WebView dialog 做 hCaptcha + 请求。 - -## Design Decisions - -| 决策 | 选择 | 理由 | -|------|------|------| -| 技术栈 | UIKit (programmatic) | 与现有 iOS 代码一致,不引入 SwiftUI 桥接成本 | -| WebView 交互模式 | Dialog/Sheet 弹出 | 对齐 fluxdo,点登录后才弹出,不占用登录页空间 | -| CF 验证时机 | 点登录后按需触发 | 不再页面打开就验证,减少无意义网络请求 | -| 记住密码 | 复用现有 Keychain 方案 + checkbox 贯穿 API | `FireSavedCredential` + `FireAuthCookieKeychainStore` 已完备;`rememberCredential` 参数一路传到 finalization | -| 社交登录入口 | 一个"其他方式登录"按钮 + 忘记密码链接 | 对齐 fluxdo:单按钮打开完整 WebView 加载 `/login`;忘记密码走 `/password-reset` | -| 登录成功 dismiss | dismiss 整个 modal | 单次 dismiss 回到主界面 | -| ViewModel 职责边界 | ViewModel 只暴露 async 能力,VC 负责 present dialog | 对齐 fluxdo 页面层拉起 dialog 的模式,贴合现有 Fire 边界 | - -## Architecture - -### 组件拆分 - -``` -FireRootCoordinator - └─ present FireLoginViewController (full-screen modal) - │ 纯原生 UIKit VC,不含 WebView - │ 负责:UI 展示、present/dismiss dialog、present 完整 WebView 兜底 - │ - ├─ 用户点"登录" → - │ FireLoginViewController.performLogin(identifier, password, rememberCredential) - │ │ - │ ├─ [VC 层] await viewModel.ensureCloudflareClearance() - │ │ (ViewModel async 能力:检查/触发 CF,返回成功/失败) - │ │ - │ ├─ [VC 层] await viewModel.primeCookiesForLogin() - │ │ (ViewModel async 能力:读取 canonical cookies 返回给 VC) - │ │ - │ ├─ [VC 层] present FireCaptchaLoginDialogController (form sheet) - │ │ │ 含 WKWebView - │ │ │ - 渲染 hCaptcha widget - │ │ │ - 用户通过 hCaptcha → JS __fireLogin(id,pwd,token) - │ │ │ - 结果通过 closure onResult 回调 - │ │ │ - WKWebView 在 dialog 存活期间保持 alive - │ │ │ - │ │ └─ onResult(dialog) → VC 处理: - │ │ ├─ success: await viewModel.completeMinimalLogin( - │ │ │ from: dialog.webView, ← LIVE WebView 传入 - │ │ │ identifier:, password:, - │ │ │ rememberCredential: ← 贯穿勾选状态 - │ │ │ ) → dismiss dialog → dismiss 登录 modal - │ │ │ - │ │ ├─ needSecondFactor(requirement): - │ │ │ 登录页弹 native 2FA 输入框 - │ │ │ → dialog.retryWithSecondFactor(code) - │ │ │ (同一存活 WebView 重试) - │ │ │ - │ │ ├─ retryCloudflare: - │ │ │ await viewModel.recoverCloudflareAndRetry() - │ │ │ → 重新 prime + dialog 重新执行 __fireLogin - │ │ │ (限一次,cfRetryUsed) - │ │ │ - │ │ └─ failure(kind): 登录页显示错误 - │ │ - │ └─ [失败/取消] 恢复登录页初始状态 - │ - ├─ "其他方式登录" 按钮 → - │ present FireWebViewBrowserViewController (full WebView, linux.do/login) - │ - ├─ "忘记密码?" 链接 → - │ present FireWebViewBrowserViewController (full WebView, linux.do/password-reset) - │ - └─ 登录成功 → - dismiss 整个 modal -``` - -### 职责边界(ViewModel vs VC) - -对齐 fluxdo 的分工(页面层 `_handleSubmit` 拉起 dialog,service 只做解析/收口): - -| 职责 | 归属 | 说明 | -|------|------|------| -| UI 展示与用户交互 | `FireLoginViewController` | 原生表单、error banner、社交入口 | -| present/dismiss dialog | `FireLoginViewController` | VC 直接 present,不走 ViewModel | -| present/dismiss 完整 WebView | `FireLoginViewController` | "其他方式登录" / "忘记密码" | -| 2FA 输入框展示 | `FireLoginViewController` | native UIAlertController/自定义弹窗 | -| 检查/触发 CF challenge | `FireAppViewModel` (async) | `ensureCloudflareClearance()` → `Bool`/`Error` | -| 读取 canonical cookies | `FireAppViewModel` (async) | `primeCookiesForLogin()` → cookie payload | -| 分类登录结果 | `FireAppViewModel` (async) | `classifyWebViewLoginResult()` → `WebViewLoginDecisionState` | -| Cookie 捕获 + finalize | `FireAppViewModel` (async) | `completeMinimalLogin(from:webView:...)` 需要 live WKWebView | -| CF 重试恢复 | `FireAppViewModel` (async) | `recoverCloudflareAndRetry()` | -| 保存/加载凭据 | `FireAppViewModel` (async) | `saveLoginCredential`/`loadSavedCredential` | - -### 原生登录页布局 (FireLoginViewController) - -``` -┌─────────────────────────────┐ -│ │ -│ [Fire Logo] │ 品牌图标,垂直偏上 -│ "Fire × LinuxDo" │ 副标题 -│ │ -│ ┌───────────────────────┐ │ -│ │ 用户名或邮箱 │ │ UITextField, .username -│ └───────────────────────┘ │ -│ ┌───────────────────────┐ │ -│ │ 密码 │ │ UITextField, isSecureTextEntry, .password -│ └───────────────────────┘ │ -│ │ -│ [✓] 记住账号密码 │ UIButton checkbox -│ │ -│ ┌───────────────────────┐ │ -│ │ 登 录 │ │ 主按钮,双字段非空时 enable -│ └───────────────────────┘ │ -│ │ -│ 忘记密码? │ 文字链接,→ WebView /password-reset -│ │ -│ ─────── 或 ──────── │ 分割线 -│ │ -│ ┌───────────────────────┐ │ -│ │ 其他方式登录 │ │ OutlinedButton → WebView /login -│ │ (OAuth / Passkey) │ │ (对齐 fluxdo 单按钮设计) -│ └───────────────────────┘ │ -│ │ -└─────────────────────────────┘ -``` - -**关于 Google/Apple 独立图标:** fluxdo 使用一个统一的"其他方式登录"按钮而非三个独立图标。linux.do 的 OAuth/Passkey 全部在 Discourse `/login` 页面由服务端处理,原生无法区分。我们采纳 fluxdo 的设计——一个按钮打开完整 WebView。如果后续需要 Google/Apple 原生 OAuth(需要服务端 OAuth client ID 配合),再单独拆分。 - -**数据绑定:** -- 复用 `viewModel.$savedLoginCredential` → 有保存的凭据时自动填充,默认勾选"记住密码" -- 登录按钮 `isEnabled` 绑定两个字段都非空 -- 错误展示用内联 error banner(不用 UIAlertController) - -### hCaptcha Dialog (FireCaptchaLoginDialogController) - -``` -┌─────────────────────────────┐ -│ 安全验证 [×] │ 标题栏 -├─────────────────────────────┤ -│ [状态文字 / 错误信息] │ 顶部状态区(文案如「请完成下方验证」) -│ [spinner,加载时显示] │ -├─────────────────────────────┤ -│ │ -│ [ hCaptcha Widget ] │ WKWebView 渲染(状态区下方) -│ │ -└─────────────────────────────┘ -``` - -**生命周期:** -``` -init(identifier, password, primingCookies, onResult, onCancel) - ├─ viewDidLoad: 配置 WKWebView → primeCookies → loadHTMLString(minimalLoginHTML) - ├─ hCaptcha 通过: 自动调用 __fireLogin(id, pwd, token) - │ → JS: fetch /session/csrf → POST /hcaptcha/create → POST /session.json - ├─ login_result messageHandler: onResult(result) - └─ 用户关闭: onCancel() - -retryWithSecondFactor(token) - └─ 同一存活 WebView 内重跑 __fireLogin(hcaptchaToken=nil, secondFactorToken=token) - -// 关键:dialog 的 WKWebView 在成功收口前不可销毁 -var webView: WKWebView { get } // 暴露给 VC 传给 completeMinimalLogin -``` - -**Live WebView 交接约束:** - -成功路径必须保持 dialog 内的 WKWebView 存活,直到 cookie 提取完成: - -``` -dialog onResult(.success) - → VC 调用 viewModel.completeMinimalLogin(from: dialog.webView, ...) - → loginCoordinator.completeJsLogin(from: webView) // 从 LIVE WebView 抽 cookie - → cookies = relevantCookies(from: webView) // 提取 _t, _forum_session 等 - → finalizeLoginFromWebView(captured) // Rust 收口 - → 成功后才 dismiss dialog(此时 WebView 可安全销毁) -``` - -知识库 `docs/knowledge/discourse-webview-login-guide.md:286` 明确要求:disposal 前必须从 live WebView 提取 `_t`、`_forum_session`、`cf_clearance`、`_cfuvid` 等 cookies。`FireWebViewLoginCoordinator.completeJsLogin(from:)` (`:372`) 直接从传入的 WKWebView 读取 `navigator.userAgent` 和 cookies。因此 dialog 不可在 `onResult` 回调中自动 dismiss,必须由 VC 在 finalize 完成后主动 dismiss。 - -### 登录时序(修正后) - -``` -[1] 点"登录 LinuxDo" → openLogin() → present FireLoginViewController - (无网络请求,无 WebView) - -[2] 登录页加载 → 自动填充 saved credential(纯本地) - -[3] 用户填写凭据,点"登录" - └─ FireLoginViewController.performLogin(identifier, password, rememberCredential) - ├─ [3a] await viewModel.ensureCloudflareClearance() - │ ├─ true → 进入 [3b] - │ └─ false/error → 登录页 error banner,终止 - ├─ [3b] let cookies = await viewModel.primeCookiesForLogin() - ├─ [3c] VC present FireCaptchaLoginDialogController(id, pwd, cookies) - │ └─ hCaptcha → __fireLogin → session.json → onResult - └─ [3d] VC 处理结果 (基于 WebViewLoginDecisionState) - ├─ .success → await completeMinimalLogin(from: dialog.webView, ...) - │ → dismiss dialog → dismiss 登录 modal - ├─ .needSecondFactor(req) → VC 弹 2FA → dialog.retryWithSecondFactor(code) - │ (重试后再次 onResult,可能仍是 needSecondFactor——见错误处理) - ├─ .retryCloudflare → await recoverCloudflareAndRetry() (一次) - │ → 重新 prime + dialog 重跑 __fireLogin - └─ .failure(kind) → dismiss dialog → 登录页 error banner -``` - -### 记住密码 API 贯穿 - -`rememberCredential` 参数从 UI checkbox 一路传到 finalization: - -``` -FireLoginViewController - ├─ performLogin(identifier, password, rememberCredential: Bool) - └─ onResult(.success) → - viewModel.completeMinimalLogin( - from: dialog.webView, - identifier: identifier, - password: password, - rememberCredential: rememberCredential ← 新增参数 - ) - └─ completeMinimalLogin 内部: - if rememberCredential { - try await sessionStore.saveLoginCredential(username:, password:) - } else { - // 未勾选时不保存新凭据 - // 如果 Keychain 中已有旧凭据,保留旧值不清除(不意外删除用户数据) - } -``` - -当前 `completeMinimalLogin` (`FireAppViewModel.swift:318`) 无条件调用 `saveLoginCredential`,需要改为根据 `rememberCredential` 条件执行。 - -### 社交登录与忘记密码(完整 WebView 兜底) - -对齐 fluxdo 的两个 WebView 入口: - -1. **"其他方式登录"按钮** → present `FireWebViewBrowserViewController`,加载 `https://linux.do/login`。Discourse 服务端处理 OAuth/Passkey/注册。 -2. **"忘记密码?"链接** → present `FireWebViewBrowserViewController`,加载 `https://linux.do/password-reset`。 - -登录成功检测(对齐 fluxdo `WebViewLoginPage`): -- 监听 WKWebView cookie store 变化 -- 检测 `_t` cookie(有效 auth token)→ 触发 finalize -- 或注入 JS 检查 `meta[name="current-username"]` -- 成功后 dismiss WebView → dismiss 登录页 → finalize 路径 - -### Cookie 流转(含 Live WebView 交接) - -``` -Keychain/Session → ViewModel.primeCookiesForLogin() → cookie payload - ↓ - VC 传入 dialog init → primeCookies into Dialog's WKWebView - ↓ - hCaptcha + session.json - ↓ - dialog onResult → VC - ↓ - VC: viewModel.completeMinimalLogin(from: dialog.webView, ...) - ↓ LIVE WKWebView 传入 - completeJsLogin(from: webView) - → relevantCookies(from: webView) ← 从 live WebView 提取 - → finalizeLoginFromWebView → Rust session - ↓ - saveLoginCredential (如果 rememberCredential == true) - ↓ - VC dismiss dialog (WebView 可安全销毁) - → VC dismiss 登录 modal -``` - -## Error Handling - -错误处理基于 Rust 的 `WebViewLoginDecisionState`(`crates/fire-core/src/core/session.rs:91-122`),不自行发明状态: - -| WebViewLoginDecisionState | 触发条件 | 展示位置 | UI 行为 | -|--------------------------|---------|---------|---------| -| `.success` | session.json 200 | — | completeMinimalLogin → dismiss all | -| `.needSecondFactor(requirement)` | reason=`second_factor` 或 `invalid_second_factor` | VC 弹 native 2FA 输入框 | 输入验证码 → `dialog.retryWithSecondFactor(code)` | -| `.retryCloudflare` | phase `csrf` 返回 CF challenge 响应(非 BAD CSRF 笼统判定) | — | 自动 `recoverCloudflareAndRetry()` 一次 | -| `.failure(kind)` | `invalid_credentials` / `not_activated` / `not_approved` / `expired` / unknown | 登录页内联 error banner | 根据 kind 显示不同文案 | - -**2FA 错误处理(重要):** Rust 把 `invalid_second_factor` 和 `second_factor` 都映射成 `.needSecondFactor`(`session.rs:96`),不产生独立的 `.failure`。2FA 验证码错误时,用户会收到**重复的** `.needSecondFactor(requirement)`,其中 `requirement.message` 包含服务端错误信息。UI 策略: -- 第一次 `.needSecondFactor` → 弹 2FA 输入框 -- 重试后再次 `.needSecondFactor` 且 `message` 非空 → 在 2FA 输入框下方显示 `message` 作为错误提示,清空验证码,允许重试 -- `requirement.backup_enabled` / `security_key_enabled` 为 true 但用户无此能力 → 显示"备用码/安全密钥请通过其他方式登录"提示,引导走完整 WebView(对齐 fluxdo `two_factor_dialog.dart:94-106` 的 fallback 逻辑) - -**CF retry 触发条件(精确):** 仅当 phase `csrf`(`/session/csrf` 请求)返回 Cloudflare challenge 响应时才触发 `.retryCloudflare`。知识库 `discourse-webview-login-guide.md:252-264` 定义了完整步骤:CF 验证 → 等 cookie 传播 → 提取 `cf_clearance` + `_cfuvid` → 写入 Rust trusted → 重新 prime 同一 live WebView → 重跑 `__fireLogin`(hCaptcha token 可复用,因为 csrf 阶段在 hCaptcha create 之前失败)。不是所有 BAD CSRF 都等于 CF retry。 - -**hCaptcha widget 错误:** hCaptcha 失败/过期由 widget 自身处理(auto reset),通过 `hcaptcha_error` / `hcaptcha_expired` messageHandler 通知 dialog 底部状态区显示提示。这不经过 Rust 分类。 - -**网络超时:** JS fetch 层超时由 dialog 自行处理,不产生 `WebViewLoginDecisionState`。dialog 底部状态区显示"网络超时,请重试"。 - -**Dialog dismiss 边界:** -- 登录成功 → **finalize 完成后** dismiss dialog → dismiss 整个 modal(不可提前 dismiss dialog,否则 live WebView 销毁导致 cookie 提取失败) -- 登录失败 → dismiss dialog → 登录页恢复按钮 + error banner -- 用户点 [×] 关闭 dialog → onCancel → 取消 loading,登录页恢复初始状态 -- CF 验证期间用户可取消,回到登录页 - -**已有防护保留:** -- `cfRetryUsed`(CF 重试一次)防止无限重试 -- `classifyWebViewLoginResult`(Rust 分类)不变 -- `completeJsLogin` cookie 捕获不变(需要 live WKWebView) -- `finalizeLoginFromWebView` Rust finalize 不变 - -## Implementation Phases - -### Phase 1:原生登录页 UI + 登录流程接通(可验证交付点) - -新建 `FireLoginViewController.swift`(纯原生 UI)和 `FireCaptchaLoginDialogController.swift`(hCaptcha dialog)。`FireRootCoordinator` 切换到新 VC。登录按钮接通完整流程(CF 检查 → present dialog → 结果处理 → finalize)。旧 `FireLoginWebView.swift` 删除。 - -**为什么 UI 和流程必须一起交付:** 如果只替换 UI 但不接通登录流程,用户会从当前可用的登录入口退化成无法登录。此阶段必须是一个完整的、可验证的交付点。 - -| 文件 | 操作 | -|------|------| -| 新建 `FireLoginViewController.swift` | Logo + 输入框 + 记住密码 + 登录按钮 + 忘记密码链接 + "其他方式登录"按钮 | -| 新建 `FireCaptchaLoginDialogController.swift` | hCaptcha WebView + `__fireLogin` + 结果回调 + live WebView 暴露 | -| 修改 `FireAppViewModel.swift` | `openLogin()` 简化移除预加载;新增 `ensureCloudflareClearance()` / `primeCookiesForLogin()`;`completeMinimalLogin` 增加 `rememberCredential` 参数 | -| 修改 `FireRootCoordinator.swift` | present `FireLoginViewController` 替代旧 VC | -| 删除 `FireLoginWebView.swift` | 旧 VC 移除 | - -**验收标准:** 用户可以打开登录页 → 输入账号密码 → 通过 hCaptcha → 成功登录进入主界面。CF 按需触发。记住密码勾选生效。2FA 可用。 - -### Phase 2:完整 WebView 兜底(社交登录 + 忘记密码) - -"其他方式登录"按钮和"忘记密码"链接接通完整 WebView VC。 - -| 文件 | 操作 | -|------|------| -| 新建/复用 `FireWebViewBrowserViewController.swift` | 完整 WebView,支持加载指定 URL + 登录成功检测 | -| 修改 `FireLoginViewController.swift` | 按钮点击 → present browser VC | - -### Phase 3:错误处理打磨 - -内联 error banner 替代 UIAlertController,2FA 弹窗优化(重复 needSecondFactor 的 message 展示),dialog 底部状态区错误完善。 - -| 文件 | 操作 | -|------|------| -| 修改 `FireLoginViewController.swift` | 内联 error banner 组件 | -| 修改 `FireCaptchaLoginDialogController.swift` | 顶部状态区错误展示 + 重试提示 | - -## File Change Summary - -| 文件路径 | 操作 | 阶段 | -|---------|------|------| -| `apps/ios-app/App/Views/Other/FireLoginViewController.swift` | 新建 | P1, P3 (error banner) | -| `apps/ios-app/App/Views/Other/FireCaptchaLoginDialogController.swift` | 新建 | P1, P3 | -| `apps/ios-app/App/Views/Other/FireWebViewBrowserViewController.swift` | 新建/复用 | P2 | -| `apps/ios-app/App/Views/Other/FireLoginWebView.swift` | 删除 | P1 | -| `apps/ios-app/App/ViewModels/FireAppViewModel.swift` | 修改 | P1 | -| `apps/ios-app/App/Core/FireRootCoordinator.swift` | 修改 | P1 | - -## Preserved Boundaries (不变) - -以下逻辑完全保留不动,确保 Rust 侧和 finalize 链路稳定: - -- UniFFI boundary:`finalizeLoginFromWebView`、`classifyWebviewLoginResult` -- Cookie 捕获:`FireWebViewLoginCoordinator.completeJsLogin`(需要 live WKWebView) -- Keychain 凭据存储:`FireSavedCredential`、`FireAuthCookieKeychainStore` -- Minimal login HTML/JS:`FireLoginScripts.minimalLoginHTML`、`__fireLogin` -- CF challenge coordinator:`FireCloudflareChallengeCoordinator` -- Session store:`FireSessionStore` -- Rust 登录决策状态机:`WebViewLoginDecision`(success / needSecondFactor / retryCloudflare / failure) - -## Reference - -- fluxdo 登录页:`references/fluxdo/lib/pages/login_page.dart:138-213` -- fluxdo hCaptcha dialog:`references/fluxdo/lib/widgets/auth/webview_login_dialog.dart` -- fluxdo 原生表单:`references/fluxdo/lib/widgets/auth/login_form.dart` -- fluxdo WebView 兜底:`references/fluxdo/lib/pages/webview_login_page.dart` -- fluxdo 忘记密码:`references/fluxdo/lib/pages/login_page.dart:396` -- fluxdo 其他方式登录:`references/fluxdo/lib/pages/login_page.dart:416` -- Fire 当前登录 VC(待替换):`apps/ios-app/App/Views/Other/FireLoginWebView.swift` -- Fire minimal login 脚本:`apps/ios-app/Sources/FireAppSession/FireWebViewBrowserProfile.swift:193-408` -- Fire 登录协调器:`apps/ios-app/Sources/FireAppSession/FireWebViewLoginCoordinator.swift:372` -- Fire completeMinimalLogin(需加 rememberCredential):`apps/ios-app/App/ViewModels/FireAppViewModel.swift:293` -- Rust 登录决策状态机:`crates/fire-core/src/core/session.rs:91-122` -- 登录知识库(cookie 交接、CF retry、2FA):`docs/knowledge/discourse-webview-login-guide.md:240-299` diff --git a/docs/superpowers/specs/2026-07-31-android-compose-ui-unification-design.md b/docs/superpowers/specs/2026-07-31-android-compose-ui-unification-design.md deleted file mode 100644 index 6ab24fb6..00000000 --- a/docs/superpowers/specs/2026-07-31-android-compose-ui-unification-design.md +++ /dev/null @@ -1,408 +0,0 @@ -# Android Compose UI Unification — Login Parity, Theme Foundation, App Icon - -**Date:** 2026-07-31 -**Status:** Spec (revised after code review against live iOS/Android login) -**Related (authoritative sources):** - -| Platform | Paths | -|----------|--------| -| iOS visual / interaction | `apps/ios-app/App/Core/FireTheme.swift`, `App/Views/Other/FireOnboardingView.swift`, `App/Startup/FireOnboardingCredentialFormView.swift`, `App/Startup/FireOnboardingValidatingView.swift`, `App/Startup/FireExternalLoginMethod.swift`, `App/Views/Other/FireCaptchaLoginDialogController.swift`, `App/Startup/FireAutoLoginPlanner.swift`, `App/Startup/FireHeadlessExternalLoginEngine.swift` | -| Android current host | `apps/android-app/src/main/java/com/fire/app/ui/auth/OnboardingFragment.kt`, `LoginWebViewFragment.kt`, `core/theme/FireColors.kt`, `session/*` | -| Protocol knowledge | `docs/knowledge/discourse-official-login-flow.md`, `docs/knowledge/discourse-webview-login-guide.md` | - -## Problem Statement - -Fire Android 与 iOS 的登录体验差距不是“皮肤色差”,而是**产品交互模型不同**: - -1. **iOS(目标基准)** — 单页 onboarding: - - 三阶段状态机:`validating` → `credential` → `loggingIn` - - 同一屏:品牌头 + error banner + 凭据表单 + 外部登录行 - - hCaptcha / 2FA 在 **sheet 弹层**(`FireCaptchaLoginDialogController`),不是主表单宿主 - - 支持自动登录、上次登录方式高亮、记住密码、键盘避让、开发者工具入口 -2. **Android(现状)** — 两段式 WebView 中心: - - `OnboardingFragment`:仅品牌 +「登录」按钮,跳转下一页 - - `LoginWebViewFragment`:chrome 栏 + 表单 + 全屏 WebView 内联 captcha - - 无三阶段机、无外部登录图标行、无上次登录高亮、无 auto-login、文案多为英文 -3. **主题 / 图标** — Android `FireColors.kt` 简陋;launcher 为占位三条横线,iOS 为完整火焰图标。 - -目标:Android 登录的**视觉 + 交互路径**对齐 iOS,达到可上架的生产级一致性。Compose 是实现手段;iOS 是产品与视觉权威。 - -## Review Findings (why the prior draft was incomplete) - -| Issue | Prior draft | Required correction | -|-------|-------------|---------------------| -| Interaction model | 保留「欢迎页 → LoginWebView 表单+WebView」 | **单页 onboarding 承载表单**;WebView 仅作 captcha/OAuth/CF 辅助 surface | -| Phase machine | Design 写了 `Validating/Credential/LoggingIn`,plan Task 8 却只做欢迎按钮 | Design 与 plan **统一为三阶段单页** | -| Captcha UX | “Android 更 WebView-centric,保持内联” | 对齐 iOS:**弹层 / DialogFragment sheet**,主屏保持 native 表单 | -| External providers | Design 有,plan 未接到 onboarding 主路径 | 主屏 `ExternalLoginRow` 必做;OAuth 经 WebView sheet 启动 | -| Last-login / auto-login | 未规划 Android 缺的 store API | 新增 `FireLastLoginMethod` + 持久化;auto-login 作为同批或紧随 parity 任务 | -| Copy language | 混用 `Sync Login` 等英文 | 登录主路径文案 **中文对齐 iOS**(用户名或邮箱 / 密码 / 登录 / 登录中…) | -| Paths | 部分写成 `android-app/...` | 一律 `apps/android-app/...` | -| Material icons | plan 使用不存在的 `Icons.Default.Eye` | 使用 `Icons.Filled.Visibility` / `VisibilityOff`(或 material-icons-extended) | -| ViewModel | Design 有 `OnboardingViewModel`,plan 无独立任务 | plan 必须有 ViewModel(或等价 state owner)任务 | -| OLED | 刻意三档 | 保持 system/light/dark;文档注明 iOS 另有 OLED,Android 首期不引入 | -| Scope creep risk | 2100 行 plan 把 `LoginWebViewFragment` 整页换成 form+WebView | 拆成:主屏 Compose parity + WebView surface 职责收缩 | - -## Design Decisions - -| # | Decision | Choice | Rejected | Why | -|---|----------|--------|----------|-----| -| 1 | Parity meaning | Visual + interaction path parity with iOS | Code-share / rewrite iOS | iOS stack is mature; Android adopts Compose | -| 2 | Login IA | **Single onboarding screen** owns form + phases | Two-step welcome → browser form | Matches `FireOnboardingView` | -| 3 | WebView role | Captcha / OAuth / CF challenge surface only | Form host with chrome + sync | Matches captcha sheet + external browser roles on iOS | -| 4 | UI framework | Jetpack Compose inside Fragment hosts | Full Activity rewrite / Nav graph rewrite | Incremental; keeps `fire_nav_graph.xml` stable during phase 1 | -| 5 | Theme baseline | Map `FireTheme.swift` tokens 1:1 | Invent Android-only palette | One brand language | -| 6 | Appearance | `system` / `light` / `dark` | Include OLED now | Avoid iOS OLED migration baggage; leave hook for later | -| 7 | Business logic | Reuse `session/*` + UniFFI; extend only missing host stores | Rewrite login in Rust for this task | Cookie / CF / JS login already work on Android | -| 8 | Navigation | Keep graph IDs; change destinations’ **content** | New Compose Navigation root | Lower risk; can collapse graph later | -| 9 | Icon | iOS `AppIcon-1024.png` → adaptive foreground | Keep three-bar placeholder | Production brand | - -## Scope - -### In Scope (this workstream) - -1. Compose deps + `core/theme/compose/*` token system aligned to iOS -2. Login **interaction + visual parity**: - - `OnboardingFragment` → Compose single-page onboarding (phases + brand + form + external row + error + keyboard) - - Captcha/OAuth/CF via DialogFragment or full-screen secondary fragment **without** embedding the credential form - - Provider brand icons + `FireExternalLoginMethod` - - `FireLastLoginMethod` persistence + UI highlight - - Chinese string parity for login chrome -3. App launcher icon unification (flame) -4. Unit tests for appearance preference + last-login store - -### Explicitly Out of Scope (follow-ups) - -- Migrating Home / TopicDetail / Notifications to Compose -- Profile / Settings Compose parity (landed 2026-08-27; remaining list/chrome pages still follow-up) -- Deleting `FireColors.kt` / `fire_colors.xml` while other pages still use them -- Full iOS auto-login sophistication (headless external engine) if blocked — **minimum**: password auto-login when saved credential exists; headless OAuth can be phase-extend -- iOS code changes -- OLED appearance mode -- Rewriting Rust login protocol - -## Target Architecture - -### Interaction map (must match iOS) - -``` -Cold start / session expired - │ - ▼ -┌───────────────────────────────────────────┐ -│ OnboardingFragment (Compose) │ -│ brand header (flame / Fire / subtitle) │ -│ error banner │ -│ phase container: │ -│ • Validating (spinner + message) │ -│ • Credential (form + external row) │ -│ • LoggingIn (loading on form/host) │ -└───────────────┬───────────────────────────┘ - │ password login - ▼ - CaptchaSheet / LoginWebSurface - (WebView: hCaptcha + __fireLogin JS) - │ success cookies - ▼ - completeLogin → home - -External provider / passkey - │ - ▼ - LoginWebSurface (OAuth or passkey click) - │ - ▼ - completeLogin → home -``` - -**Do not** keep the current product path “tap 登录 → second page that is half form half browser chrome” as the end state. Intermediate migration may temporarily route, but acceptance is single-page parity. - -### Package layout - -``` -apps/android-app/src/main/java/com/fire/app/ -├── core/theme/compose/ -│ ├── FireAppearancePreference.kt -│ ├── FireColorTokens.kt -│ ├── FireColorScheme.kt -│ ├── FireShapes.kt -│ ├── FireTypography.kt -│ ├── FireDimens.kt -│ └── FireTheme.kt -├── session/ -│ ├── FireCredentialStore.kt (existing) -│ ├── FireLastLoginStore.kt (new — method enum + prefs/encrypted store) -│ └── … coordinators unchanged -└── ui/auth/ - ├── OnboardingFragment.kt (ComposeView host) - ├── OnboardingViewModel.kt (phase + form state + login orchestration) - ├── LoginWebViewFragment.kt (Web surface host; form UI removed) - ├── LoginCaptchaDialogFragment.kt (optional DialogFragment alternative) - └── compose/ - ├── OnboardingScreen.kt - ├── ValidatingContent.kt - ├── CredentialForm.kt - ├── ExternalLoginRow.kt - └── LoginWebChrome.kt (only for Web surface, not main form) -``` - -Paths in all tables below use repo-root relative `apps/android-app/...`. - -### Fragment ↔ Compose host pattern - -```kotlin -// OnboardingFragment — host only -override fun onCreateView(...): View = - ComposeView(requireContext()).apply { - setViewCompositionStrategy(DisposeOnViewTreeLifecycleDestroyed) - setContent { - FireTheme { - val vm: OnboardingViewModel = viewModel() - OnboardingScreen( - state = vm.uiState.collectAsStateWithLifecycle().value, - actions = vm, - ) - } - } - } -``` - -WebView surfaces use `AndroidView` factory; retain a single `WebView` instance on the Fragment/Dialog for cookie/JS continuity. Destroy on `onDestroyView`. - -### Theme tokens - -Source of truth: `apps/ios-app/App/Core/FireTheme.swift`. - -Conversion rule: for opaque `UIColor(red:g:b:a:1)`, -`hex_channel = round(channel * 255)`. - -Verified samples (must match implementation): - -| Token | Light | Dark | -|-------|-------|------| -| accent | `#E8632E` (0.91, 0.39, 0.18) | `#FA7A3D` (0.98, 0.48, 0.24) | -| canvasMid | `#F2F0EB` (0.95, 0.94, 0.92) | `#000000` | -| surface | `#FFFFFF` | `#1C1C1E` | -| surfaceSecondary | `#F2F0ED` (0.95, 0.94, 0.93) | `#2C2C2E` | -| ink | `#1C1C1F` (0.11, 0.11, 0.12) | white @ 0.96 alpha | -| subtleInk | `#66666E` (0.40, 0.40, 0.43) | white @ 0.55 alpha | - -Dark ink **must** use alpha white, not opaque `#FFFFFF`. - -Shapes (from iOS `FireTheme` extensions): corner 14 / 12 / 10 / 8; chip pill 100; page inset 16; section spacing 16. - -`FireTheme { }` reads `FireAppearancePreference` and applies `MaterialTheme` + `CompositionLocal` for extended tokens (`fireExtended.accent`, `canvasMid`, …). - -### Visual / interaction parity checklist (login) - -Must match iOS `FireOnboardingView` + `FireOnboardingCredentialFormView`: - -| Element | Spec | -|---------|------| -| Canvas | Full-bleed `canvasMid`; no top app bar on onboarding | -| Brand | Flame 44–56dp, title **Fire** bold title1-scale, subtitle **LinuxDo 原生客户端** secondary | -| Content layout | Brand + form as one vertical block, optically centered (~centerY − 24dp equivalent), horizontal inset 24dp | -| Error banner | Dismissible; shows host error strings; aborts logging-in phase | -| Identifier field | 48dp, 10dp radius, placeholder **用户名或邮箱**, no autocap | -| Password field | 48dp, 10dp radius, eye toggle (show/hide), go/ime → login | -| Options row | **记住密码** checkbox (circle / checkmark.circle style) + **忘记密码?** systemBlue link | -| Login button | 50dp, accent fill, white label **登录**; disabled when empty; loading **登录中…** + spinner | -| Last-login | Password method: accent border on login button; external method: accent border on that provider chip; hint text **上次使用:…** | -| External row | Label **其他方式**; 6 chips: Google / GitHub / X / Discord / Apple / Passkey; 52dp height, 14dp radius, 24dp brand icons, alwaysOriginal | -| Validating | Spinner + **正在校验登录态…**; optional cancel during auto-login | -| Keyboard | IME padding / scroll; tap outside dismisses | -| Captcha | Sheet/dialog WebView; white captcha chrome preferred; password fields **not** remounted under WebView | -| Success | Navigate home only after `canReadAuthenticatedApi` / existing Android completeLogin path | - -### State model - -```kotlin -enum class OnboardingPhase { Validating, Credential, LoggingIn } - -enum class FireLastLoginMethod { - Password, Google, GitHub, X, Discord, Apple, Passkey -} - -enum class FireExternalLoginMethod( - val displayName: String, - val discourseProviderName: String?, // null = passkey -) { - Google("Google", "google_oauth2"), - GitHub("GitHub", "github"), - X("X", "twitter"), - Discord("Discord", "discord"), - Apple("Apple", "apple"), - Passkey("Passkey", null); -} - -data class OnboardingUiState( - val phase: OnboardingPhase = OnboardingPhase.Validating, - val errorMessage: String? = null, - val identifier: String = "", - val password: String = "", - val isPasswordVisible: Boolean = false, - val rememberPassword: Boolean = false, - val lastLoginMethod: FireLastLoginMethod? = null, - val isLoginEnabled: Boolean = false, - // entry: coldStart | sessionExpired | signedOut (mirror iOS FireOnboardingEntry) - val entry: OnboardingEntry = OnboardingEntry.ColdStart, -) -``` - -`OnboardingViewModel` responsibilities: - -- Drive phase transitions (mirror iOS publisher logic at host level, not pixel-perfect Combine) -- Prefill from `FireCredentialStore`; never wipe in-progress edits on nil credential -- Password login: enter `LoggingIn` → present captcha surface with identifier/password → on success save credential (if remember) + last method + `completeLogin` -- External login: present Web surface with auto-start provider / passkey script -- Startup: validating → optional auto-login (password if saved) → credential -- Signed-out entry: skip validating auto-login; show credential immediately - -### Web surface (ex–LoginWebViewFragment) - -**Keep** all proven machinery: - -- `configureLoginWebView`, JS bridge, `FireLoginScripts`, OAuth polling -- Cloudflare challenge coordination / retry -- Second-factor handling -- `FireWebViewLoginCoordinator.completeLogin` / cookie capture - -**Remove from this surface as product UI:** - -- Credential form fields and “Sync Login” as the primary CTA for typing passwords - (password entry lives on onboarding) - -**Chrome for Web surface** may retain close + progress + optional title for OAuth debugging; it is not the brand login page. - -Navigation options (pick one in implementation; default recommended): - -1. **Recommended:** `LoginCaptchaDialogFragment` / bottom sheet for password captcha; full-screen `LoginWebViewFragment` only for OAuth that needs multi-hop redirects -2. Alternative: single `LoginWebViewFragment` with args `mode=captcha|oauth|passkey` and no form - -### Strings (Chinese parity) - -Add/replace login-facing strings so primary UI matches iOS: - -| Key (suggested) | Value | -|-----------------|--------| -| `login_identifier_hint` | 用户名或邮箱 | -| `login_password_hint` | 密码 | -| `login_action` | 登录 | -| `login_in_progress` | 登录中… | -| `login_remember_password` | 记住密码 | -| `login_forgot_password` | 忘记密码? | -| `login_other_methods` | 其他方式 | -| `login_last_used` | 上次使用:%1$s | -| `onboarding_checking_login_state` | 正在校验登录态… | -| `onboarding_subtitle` | LinuxDo 原生客户端 (exists) | - -Deprecate user-facing **Sync Login** as the main password CTA. - -### App icon - -1. Source: `apps/ios-app/App/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png` -2. Adaptive foreground: vector preferred; else density mipmaps; safe zone 72/108 -3. Background: sample from iOS source; update `launcher_background` -4. Visual QA against iOS home screen - -Provider icons: from iOS `LoginProvider*.imageset` → `res/drawable/ic_login_*.xml` (or PNG if multicolor). - -## Implementation Phases - -### Phase 0 — Spec lock (this doc) - -- [x] Align design to iOS single-page model -- [x] Correct file paths and out-of-scope boundaries -- [ ] User confirms captcha presentation (dialog vs full-screen fragment) if needed - -### Phase 1 — Compose + theme foundation - -- Enable Compose compiler plugin + BOM in `apps/android-app/build.gradle.kts` -- Add `core/theme/compose/*` -- Preview light/dark `FireTheme` -- Unit tests for `FireAppearancePreference` - -### Phase 2 — Login stores + assets - -- `FireLastLoginMethod` + store -- Provider drawables + `FireExternalLoginMethod` -- Chinese string resources - -### Phase 3 — Onboarding Compose UI + ViewModel - -- `OnboardingScreen` / `ValidatingContent` / `CredentialForm` / `ExternalLoginRow` -- Wire `OnboardingFragment` → ComposeView -- Keyboard + error banner + last-login chrome -- Phase transitions without captcha first (mock/no-op) for UI QA - -### Phase 4 — Wire real login + shrink Web surface - -- Present captcha/OAuth Web surface from ViewModel actions -- Move password JS login invocation off form-host fragment -- Preserve CF / 2FA / cookie completeLogin -- Auto-login password path when credential saved -- E2E: password, OAuth, passkey (if device supports), 2FA - -### Phase 5 — App icon + verification - -- Replace launcher foreground -- Full checklist below - -## Risks and Mitigations - -| Risk | Mitigation | -|------|------------| -| WebView recreation loses cookies mid-login | Retain WebView on Fragment/Dialog field; prime cookies before load | -| Compose state not updating from WebView callbacks | Use `mutableStateOf` / `StateFlow` on main; never `ComposeView.invalidate()` as primary | -| Two theme systems | Token values match iOS; login uses Compose theme only | -| OAuth redirect needs full browser chrome | Full-screen Web surface mode; form stays on onboarding | -| Auto-login / headless OAuth gap vs iOS | Ship password auto-login first; document OAuth headless as follow-up if cost high | -| Material icon missing glyphs | Use Visibility icons or drawable resources; no nonexistent `Eye` | -| Navigation graph thrash | Keep IDs; only change destination view implementations | - -## Acceptance Criteria - -- [ ] Visual side-by-side with iOS login (light + dark): layout, type hierarchy, accent, field chrome -- [ ] Single primary login surface; no “welcome-only” dead-end page in final UX -- [ ] Password login completes via captcha sheet/surface and lands home -- [ ] External provider chips present and launch correct Discourse auth path -- [ ] Remember password + last-login highlight work across process death -- [ ] System dark mode tokens match table above -- [ ] Launcher icon is flame-aligned with iOS -- [ ] Home / TopicDetail / other XML pages still compile and run -- [ ] `./gradlew assembleDebug` and relevant unit tests pass - -## File Change Summary - -### New - -- `apps/android-app/src/main/java/com/fire/app/core/theme/compose/*` (theme package) -- `apps/android-app/src/main/java/com/fire/app/ui/auth/OnboardingViewModel.kt` -- `apps/android-app/src/main/java/com/fire/app/ui/auth/compose/*.kt` -- `apps/android-app/src/main/java/com/fire/app/session/FireLastLoginStore.kt` (name flexible) -- `apps/android-app/src/main/res/drawable/ic_login_*.xml` -- Tests under `apps/android-app/src/test/java/com/fire/app/...` - -### Modified - -- `apps/android-app/build.gradle.kts` -- `apps/android-app/src/main/java/com/fire/app/ui/auth/OnboardingFragment.kt` -- `apps/android-app/src/main/java/com/fire/app/ui/auth/LoginWebViewFragment.kt` (role shrink) -- `apps/android-app/src/main/res/values/strings.xml` (+ night colors only if needed) -- `apps/android-app/src/main/res/drawable/ic_launcher_foreground.xml` -- `apps/android-app/src/main/res/values/colors.xml` (`launcher_background`) -- Possibly `fire_nav_graph.xml` **only** if args/modes are required (prefer no structural change) - -### Unchanged - -- iOS tree -- Rust / UniFFI login protocol -- Non-auth feature Fragments -- `FireColors.kt` until later migrations - -## Relationship to Implementation Plan - -Executable task breakdown: -`docs/superpowers/plans/2026-07-31-android-compose-ui-unification.md` - -That plan **must** follow this interaction model. Any task that reintroduces form-on-WebView as the primary UX is out of date. diff --git a/scripts/test-release-verifiers.sh b/scripts/test-release-verifiers.sh index d2d60a89..f40a926e 100755 --- a/scripts/test-release-verifiers.sh +++ b/scripts/test-release-verifiers.sh @@ -726,10 +726,6 @@ write_release_gate(fixture / "release-gates-missing-trailing-pipe.md", missing_t write_release_gate(fixture / "release-gates-not-real.md", marker="not-real") write_release_gate(fixture / "release-gates-not-real-space.md", marker="not real") -roadmap = fixture / "checked-roadmap.md" -text = Path("docs/superpowers/specs/2026-06-08-fire-v2-roadmap-design.md").read_text() -text = text.replace("- [ ] App Store / Play Store 素材齐全", "- [x] App Store / Play Store 素材齐全", 1) -roadmap.write_text(text) PY fixture="$tmp_dir/fixture" @@ -1172,27 +1168,6 @@ expect_fail_contains "accessibility rejects weak accepted waiver notes" \ "accepted accessibility waivers require approver and reason in notes" \ scripts/verify-accessibility-audit.sh "$fixture/accessibility-accepted-weak.md" -expect_pass "roadmap P4 acceptance allows checked roadmap with complete fixture evidence" \ - "${suite_env[@]}" \ - scripts/verify-roadmap-p4-acceptance.sh \ - "$fixture/checked-roadmap.md" \ - "$fixture/release-gates.md" - -expect_fail_contains "roadmap P4 acceptance rejects checked roadmap with missing lower-level evidence" \ - "P4 release evidence suite is incomplete" \ - env \ - "FIRE_MARKETING_ASSETS_ROOT=$fixture/marketing" \ - "FIRE_PERFORMANCE_BENCHMARK_FILE=$fixture/performance-missing.md" \ - "FIRE_ACCESSIBILITY_AUDIT_FILE=$fixture/accessibility.md" \ - "FIRE_INTERNAL_TESTING_EVIDENCE_FILE=$fixture/internal.md" \ - "FIRE_PRIVACY_REVIEW_EVIDENCE_FILE=$fixture/privacy.md" \ - scripts/verify-roadmap-p4-acceptance.sh \ - "$fixture/checked-roadmap.md" \ - "$fixture/release-gates.md" - -expect_pass "roadmap P4 acceptance allows unchecked production roadmap" \ - scripts/verify-roadmap-p4-acceptance.sh - if [[ "$failure_count" -gt 0 ]]; then printf 'Release verifier regression tests failed: %d failure(s)\n' "$failure_count" >&2 exit 1 diff --git a/scripts/verify-release-readiness.sh b/scripts/verify-release-readiness.sh index 7c798cf4..98e2e23d 100755 --- a/scripts/verify-release-readiness.sh +++ b/scripts/verify-release-readiness.sh @@ -6,10 +6,6 @@ cd "$ROOT_DIR" checks=( "P4 release evidence suite|scripts/verify-p4-release-evidence-suite.sh" - "Roadmap plan contract|scripts/verify-roadmap-plan-contract.sh" - "Roadmap architecture constraints|scripts/verify-roadmap-architecture-constraints.sh" - "Roadmap implementation evidence|scripts/verify-roadmap-implementation-evidence.sh" - "Roadmap P4 acceptance|scripts/verify-roadmap-p4-acceptance.sh" ) failure_count=0 diff --git a/scripts/verify-roadmap-implementation-evidence.sh b/scripts/verify-roadmap-implementation-evidence.sh deleted file mode 100755 index 3aca8425..00000000 --- a/scripts/verify-roadmap-implementation-evidence.sh +++ /dev/null @@ -1,149 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -failure_count=0 -checked_count=0 - -fail() { - failure_count=$((failure_count + 1)) - printf 'FAIL: %s\n' "$*" >&2 -} - -pass() { - checked_count=$((checked_count + 1)) - printf 'PASS: %s\n' "$*" -} - -require_file() { - local label="$1" - local file="$2" - - if [[ -f "$file" ]]; then - pass "$label: found $file" - else - fail "$label: missing required file $file" - fi -} - -require_pattern() { - local label="$1" - local file="$2" - local pattern="$3" - - if [[ ! -f "$file" ]]; then - fail "$label: missing required file $file" - return - fi - - if rg -q "$pattern" "$file"; then - pass "$label: pattern found in $file" - else - fail "$label: pattern not found in $file: $pattern" - fi -} - -require_no_pattern() { - local label="$1" - local file_glob="$2" - local pattern="$3" - - if rg -q "$pattern" $file_glob; then - fail "$label: forbidden pattern found: $pattern" - rg -n "$pattern" $file_glob >&2 || true - else - pass "$label: forbidden pattern absent" - fi -} - -require_line_count_below() { - local label="$1" - local file="$2" - local maximum="$3" - local line_count - - if [[ ! -f "$file" ]]; then - fail "$label: missing required file $file" - return - fi - - line_count="$(wc -l < "$file" | tr -d '[:space:]')" - if [[ "$line_count" =~ ^[0-9]+$ ]] && (( line_count < maximum )); then - pass "$label: $file has $line_count line(s), below $maximum" - else - fail "$label: $file has $line_count line(s), expected below $maximum" - fi -} - -echo "==> P1 implementation evidence" -require_pattern "P1 theme radius tokens" "apps/ios-app/App/Core/FireTheme.swift" "static let cornerRadius: CGFloat = 20" -require_pattern "P1 theme medium radius token" "apps/ios-app/App/Core/FireTheme.swift" "static let mediumCornerRadius: CGFloat = 14" -require_pattern "P1 theme small radius token" "apps/ios-app/App/Core/FireTheme.swift" "static let smallCornerRadius: CGFloat = 10" -require_pattern "P1 theme canvas token" "apps/ios-app/App/Core/FireTheme.swift" "static var canvas: Color" -require_pattern "P1 theme surface token" "apps/ios-app/App/Core/FireTheme.swift" "static var surface: Color" -require_no_pattern "P1 scoped hardcoded radius cleanup" "apps/ios-app/App/Core/FireComponents.swift apps/ios-app/App/Views/Composer/FireComposerView.swift apps/ios-app/App/Views/Other/FireOnboardingView.swift apps/ios-app/App/Views/Search/FireSearchView.swift apps/ios-app/App/Views/Home/FireTopicRow.swift apps/ios-app/App/Views/Home/FireFilteredTopicListView.swift" "cornerRadius:\\s*(10|12|16|18)\\b|\\.cornerRadius\\((10|12|16|18)\\b" -require_no_pattern "P1 scoped dark-mode hardcoding cleanup" "apps/ios-app/App/Views/Composer/FireComposerView.swift apps/ios-app/App/Views/Other/FireOnboardingView.swift apps/ios-app/App/Views/Search/FireSearchView.swift apps/ios-app/App/Core/FireComponents.swift" "Color\\.black\\.opacity|Color\\.black|Color\\.white|Color\\(\\.systemGroupedBackground\\)|Color\\(\\.secondarySystemBackground\\)" -require_pattern "P1 reusable empty state component" "apps/ios-app/App/Core/FireComponents.swift" "struct FireEmptyFeedState" -require_pattern "P1 filtered list empty state usage" "apps/ios-app/App/Views/Home/FireFilteredTopicListView.swift" "FireEmptyFeedState\\(" -require_pattern "P1 notification empty state usage" "apps/ios-app/App/Views/Notifications/FireNotificationsViewController.swift" "title: \"暂无通知\"" -require_pattern "P1 shimmer path" "apps/ios-app/App/Core/FireShimmerModifier.swift" "func fireShimmer\\(\\)" -require_pattern "P1 topic row accessibility label" "apps/ios-app/App/Views/Home/FireTopicRow.swift" "\\.accessibilityLabel\\(" -require_pattern "P1 home create accessibility label" "apps/ios-app/App/Views/Home/FireHomeView.swift" "accessibilityLabel[[:space:]]*=[[:space:]]*\"创建新话题\"|\\.accessibilityLabel\\(\"创建新话题\"\\)" -require_pattern "P1 home search accessibility label" "apps/ios-app/App/Views/Home/FireHomeView.swift" "accessibilityLabel[[:space:]]*=[[:space:]]*\"搜索\"|\\.accessibilityLabel\\(\"搜索\"\\)" -require_pattern "P1 paginated store base" "apps/ios-app/App/Stores/FirePaginatedStore.swift" "class FirePaginatedStore: ObservableObject" -require_pattern "P1 search store pagination" "apps/ios-app/App/Stores/FireSearchStore.swift" "FirePaginatedStore" -require_pattern "P1 notification store pagination" "apps/ios-app/App/Stores/FireNotificationStore.swift" "FirePaginatedStore" -require_file "P1 Android drafts fragment" "apps/android-app/src/main/java/com/fire/app/ui/drafts/DraftsFragment.kt" -require_pattern "P1 Android drafts session bridge" "apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt" "fetchDrafts\\(" -require_file "P1 Android FCM service" "apps/android-app/src/main/java/com/fire/app/push/FireFirebaseMessagingService.kt" -require_pattern "P1 Android FCM token handling" "apps/android-app/src/main/java/com/fire/app/push/FireFirebaseMessagingService.kt" "override fun onNewToken" -require_pattern "P1 Android FCM message handling" "apps/android-app/src/main/java/com/fire/app/push/FireFirebaseMessagingService.kt" "override fun onMessageReceived" -require_pattern "P1 Android push local notification dispatcher" "apps/android-app/src/main/java/com/fire/app/push/FirePushNotificationDispatcher.kt" "NotificationManagerCompat\\.from\\(context\\)\\.notify" -require_line_count_below "P1 FireAppViewModel size" "apps/ios-app/App/ViewModels/FireAppViewModel.swift" 1500 - -echo -echo "==> P2 implementation evidence" -require_file "P2 Rust LDC core" "crates/fire-core/src/core/ldc.rs" -require_file "P2 Rust CDK core" "crates/fire-core/src/core/cdk.rs" -require_pattern "P2 UniFFI LDC authorization" "crates/fire-uniffi-ldc/src/lib.rs" "ldc_authorization_url" -require_pattern "P2 UniFFI CDK authorization" "crates/fire-uniffi-ldc/src/lib.rs" "cdk_authorization_url" -require_file "P2 iOS LDC view" "apps/ios-app/App/Views/Profile/FireLDCView.swift" -require_file "P2 iOS CDK view" "apps/ios-app/App/Views/Profile/FireCDKView.swift" -require_file "P2 Android LDC fragment" "apps/android-app/src/main/java/com/fire/app/ui/ldc/LDCFragment.kt" -require_file "P2 Android CDK fragment" "apps/android-app/src/main/java/com/fire/app/ui/ldc/CDKFragment.kt" -require_pattern "P2 Rust topic thread model" "crates/fire-models/src/topic_detail.rs" "pub struct TopicThread" -require_pattern "P2 Android topic tree projection" "apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt" "TopicDetailPostRows\\.projectRows" -require_pattern "P2 iOS topic search controller" "apps/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift" "FireTopicSearchBar" -require_pattern "P2 Android topic search overlay" "apps/android-app/src/main/res/layout/activity_topic_detail.xml" "TopicSearchOverlay" -require_pattern "P2 iOS Markdown toolbar" "apps/ios-app/App/Views/Composer/FireComposerView.swift" "struct FireMarkdownToolbar" -require_pattern "P2 Android Markdown toolbar" "apps/android-app/src/main/java/com/fire/app/ui/composer/MarkdownToolbarView.kt" "class MarkdownToolbarView" -require_pattern "P2 iOS quote insertion" "apps/ios-app/App/Views/Composer/FireComposerView.swift" "enum FireQuoteMarkdown" -require_pattern "P2 Android quote insertion test" "apps/android-app/src/test/java/com/fire/app/ui/composer/MarkdownInsertionTest.kt" "quoteMarkdown_buildsDiscourseQuoteBlockFromPlainText" -require_pattern "P2 iOS topic notification level" "apps/ios-app/Sources/FireAppSession/FireSessionStore.swift" "setTopicNotificationLevel" -require_pattern "P2 Android topic notification level" "apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt" "setTopicNotificationLevel" - -echo -echo "==> P3 implementation evidence" -require_pattern "P3 iOS widget bundle" "apps/ios-app/App/Widgets/FireWidgetBundle.swift" "FireMediumWidget\\(\\)" -require_pattern "P3 iOS large widget" "apps/ios-app/App/Widgets/FireWidgetBundle.swift" "FireLargeWidget\\(\\)" -require_pattern "P3 Android unread widget" "apps/android-app/src/main/java/com/fire/app/widget/FireUnreadWidgetProvider.kt" "AppWidgetProvider" -require_pattern "P3 Android topic-list widget" "apps/android-app/src/main/java/com/fire/app/widget/FireTopicListWidgetProvider.kt" "AppWidgetProvider" -require_pattern "P3 Android widgets registered" "apps/android-app/src/main/AndroidManifest.xml" "FireTopicListWidgetProvider" -require_pattern "P3 iOS haptics layer" "apps/ios-app/App/FireMotion/FireMotionEffects.swift" "enum FireMotionHaptics" -require_pattern "P3 iOS post-row haptics" "apps/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift" "FireMotionHaptics" -require_pattern "P3 iOS toast component" "apps/ios-app/App/Core/FireComponents.swift" "struct FireToast" -require_pattern "P3 Android toast component" "apps/android-app/src/main/java/com/fire/app/core/ui/FireToast.kt" "object FireToast" -require_pattern "P3 Rust topic cache write" "crates/fire-store/src/lib.rs" "topic_list_cache_write" -require_pattern "P3 Rust notification cache write" "crates/fire-store/src/lib.rs" "notification_list_cache_write" -require_pattern "P3 Rust topic cache read-through" "crates/fire-core/src/core/topics.rs" "topic_list_cache_read" -require_pattern "P3 Rust notification cache read-through" "crates/fire-core/src/core/notifications.rs" "notification_list_cache_read" -require_pattern "P3 iOS home offline state" "apps/ios-app/App/Stores/FireHomeFeedStore.swift" "isOffline = response\\.isCached" -require_pattern "P3 iOS notification offline state" "apps/ios-app/App/Stores/FireNotificationStore.swift" "isOffline = result\\.isCached" -require_pattern "P3 Android home offline state" "apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt" "_isOffline\\.value = isCached" -require_pattern "P3 Android offline banner" "apps/android-app/src/main/res/layout/view_offline_banner.xml" "offline_cache_banner" - -if [[ "$failure_count" -gt 0 ]]; then - printf 'Roadmap implementation evidence verification failed: %d failure(s), %d check(s) passed\n' "$failure_count" "$checked_count" >&2 - exit 1 -fi - -printf 'Roadmap implementation evidence verification passed: %d check(s).\n' "$checked_count" diff --git a/scripts/verify-roadmap-p4-acceptance.sh b/scripts/verify-roadmap-p4-acceptance.sh deleted file mode 100755 index dc1ad6f9..00000000 --- a/scripts/verify-roadmap-p4-acceptance.sh +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -roadmap_file="${1:-docs/superpowers/specs/2026-06-08-fire-v2-roadmap-design.md}" -release_gate_file="${2:-docs/release/release-gate-evidence.md}" -p4_release_evidence_suite="scripts/verify-p4-release-evidence-suite.sh" - -if [[ ! -f "$roadmap_file" ]]; then - echo "roadmap design file not found: $roadmap_file" >&2 - exit 2 -fi - -if [[ ! -f "$release_gate_file" ]]; then - echo "release gate evidence file not found: $release_gate_file" >&2 - exit 2 -fi - -parse_output="$( - awk ' - BEGIN { - add_required("App Store / Play Store 素材齐全") - add_required("TestFlight / 内部测试轨道可分发") - add_required("首页滚动 60fps 无掉帧") - add_required("话题详情首屏 < 2s") - add_required("VoiceOver / TalkBack 全流程可操作") - - row_count = 0 - checked_count = 0 - failure_count = 0 - in_p4_acceptance = 0 - } - - function add_required(item) { - required[item] = 1 - required_names[++required_count] = item - } - - function trim(value) { - gsub(/^[[:space:]]+|[[:space:]]+$/, "", value) - return value - } - - function fail(item, message) { - failure_count += 1 - printf("FAIL: %s: %s\n", item, message) > "/dev/stderr" - } - - /^### P4 验收[[:space:]]*$/ { - in_p4_acceptance = 1 - next - } - - in_p4_acceptance && /^### / { - in_p4_acceptance = 0 - next - } - - in_p4_acceptance && /^- \[[ xX]\][[:space:]]+/ { - item = $0 - is_checked = item ~ /^- \[[xX]\][[:space:]]+/ - sub(/^- \[[ xX]\][[:space:]]+/, "", item) - item = trim(item) - - row_count += 1 - - if (seen_all[item] > 0) { - fail(item, "duplicate P4 acceptance row") - } - seen_all[item] += 1 - - if (!(item in required)) { - fail(item, "unknown P4 acceptance row; use the exact required roadmap wording") - } else { - seen[item] = 1 - } - - if (is_checked) { - checked_count += 1 - } - } - - END { - for (required_index = 1; required_index <= required_count; required_index += 1) { - item = required_names[required_index] - if (!(item in seen)) { - fail(item, "missing required P4 acceptance row") - } - } - - if (row_count == 0) { - fail("P4 验收", "no P4 acceptance rows found") - } - - if (failure_count > 0) { - printf("Roadmap P4 acceptance verification failed: %d row(s), %d failure(s)\n", row_count, failure_count) > "/dev/stderr" - exit 1 - } - - printf("row_count=%d\n", row_count) - printf("checked_count=%d\n", checked_count) - } - ' "$roadmap_file" -)" - -row_count="$(printf '%s\n' "$parse_output" | awk -F= '/^row_count=/ { print $2; exit }')" -checked_count="$(printf '%s\n' "$parse_output" | awk -F= '/^checked_count=/ { print $2; exit }')" - -if [[ -z "$row_count" || -z "$checked_count" ]]; then - echo "roadmap P4 acceptance parser did not report row counts" >&2 - exit 1 -fi - -if [[ "$checked_count" -gt 0 ]]; then - if [[ ! -x "$p4_release_evidence_suite" ]]; then - printf 'FAIL: P4 release evidence suite is missing or not executable: %s\n' "$p4_release_evidence_suite" >&2 - exit 2 - fi - - if ! suite_output="$( - FIRE_RELEASE_GATE_EVIDENCE_FILE="$release_gate_file" \ - "$p4_release_evidence_suite" 2>&1 - )"; then - printf '%s\n' "$suite_output" >&2 - printf 'FAIL: roadmap P4 acceptance has %d checked item(s), but P4 release evidence suite is incomplete.\n' "$checked_count" >&2 - exit 1 - fi -fi - -printf 'Roadmap P4 acceptance verification passed: %d row(s), %d checked.\n' "$row_count" "$checked_count" diff --git a/scripts/verify-roadmap-plan-contract.sh b/scripts/verify-roadmap-plan-contract.sh deleted file mode 100755 index 35377276..00000000 --- a/scripts/verify-roadmap-plan-contract.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -spec_file="docs/superpowers/specs/2026-06-08-fire-v2-roadmap-design.md" - -plans=( - "P1|docs/superpowers/plans/2026-06-08-p1-foundation.md|17" - "P2|docs/superpowers/plans/2026-06-08-p2-feature-completion.md|14" - "P3|docs/superpowers/plans/2026-06-08-p3-native-differentiation.md|15" - "P4|docs/superpowers/plans/2026-06-08-p4-release-preparation.md|6" -) - -failure_count=0 -total_expected=0 -total_actual=0 - -fail() { - failure_count=$((failure_count + 1)) - printf 'FAIL: %s\n' "$*" >&2 -} - -if [[ ! -f "$spec_file" ]]; then - fail "roadmap design spec is missing: $spec_file" -else - printf 'INFO: roadmap design spec found: %s\n' "$spec_file" -fi - -for entry in "${plans[@]}"; do - IFS='|' read -r label plan_file expected_count <<< "$entry" - total_expected=$((total_expected + expected_count)) - - if [[ ! -f "$plan_file" ]]; then - fail "$label plan is missing: $plan_file" - continue - fi - - actual_count="$(awk '/^## Task [0-9]+:/ || /^### Task [0-9]+:/ { count += 1 } END { print count + 0 }' "$plan_file")" - total_actual=$((total_actual + actual_count)) - - while IFS= read -r malformed_heading; do - fail "$label plan has non-contract task heading: $malformed_heading" - done < <(awk '$0 ~ /^## Task / || $0 ~ /^### Task / { if ($0 !~ /^## Task [0-9]+:/ && $0 !~ /^### Task [0-9]+:/) print FNR ":" $0 }' "$plan_file") - - if [[ "$actual_count" -ne "$expected_count" ]]; then - fail "$label plan expected $expected_count top-level task(s), found $actual_count in $plan_file" - else - printf 'INFO: %s plan task count OK: %d\n' "$label" "$actual_count" - fi -done - -if [[ "$total_actual" -ne "$total_expected" ]]; then - fail "roadmap plan total expected $total_expected top-level task(s), found $total_actual" -else - printf 'INFO: roadmap plan total OK: %d task(s)\n' "$total_actual" -fi - -if [[ "$failure_count" -gt 0 ]]; then - printf 'Roadmap plan contract verification failed: %d failure(s)\n' "$failure_count" >&2 - exit 1 -fi - -printf 'Roadmap plan contract verification passed: 1 spec, %d plan(s), %d task(s).\n' "${#plans[@]}" "$total_actual"