feat(app-iced): M114 账户页三轨登录(微软正版 / 第三方皮肤站 / 本地档案)

- 账户页:当前账户卡 + 全部账户列表 + 空态三入口 + 皮肤区;五项动作(添加/切换/删除/重新登录/校验)
- 三轨添加流程:设备码(用户码+链接+倒计时+过期重试+取消)、授权码(浏览器+可复制链接+取消)、
  本地档案(名字校验)、第三方站(服务地址 + 服务发现校验 + 密码登录,密码掩码且用完即弃)
- 导航:账户为一等页,入口是轨底头像位(未登录=描边剪影 / 已登录=首字母块+名字;窄高收成图标条)
- 凭据红线:DTO 侧形状脱敏 + 状态层二次脱敏 + 密码掩码;Inject-JWT 测试断言视图模型干净(已做变异取证)
- presenter:authlib 登录/服务发现/皮肤抓取(复用下载引擎的 HTTP 客户端,无新增依赖)、
  皮肤原图经 DTO 到 UI 裁剪成头像(既有 image 依赖,未改 Cargo.toml)
- i18n:新增 account 域 51 条中英文案(离线档案口径全量写入),金表同步
This commit is contained in:
AskaEth committed 2026-11-05 05:08:35 +08:00
1 parent e7b04c4afe
commit 1ff00bbe50
43 files changed
+4343 -117

No files matched your search

+3
View File
@@ -80,6 +80,8 @@ pub(super) fn route_of(nav: NavItem) -> Route {
NavItem::Logs => Route::Logs,
NavItem::Settings => Route::Settings,
NavItem::Ai => Route::Agent,
// 轨底头像位(M114):账户是一级页,但**不在主序列**里
NavItem::Account => Route::Accounts,
}
}
@@ -94,5 +96,6 @@ pub(super) fn nav_item_of(route: &Route) -> NavItem {
Route::Logs => NavItem::Logs,
Route::Settings => NavItem::Settings,
Route::Agent => NavItem::Ai,
Route::Accounts => NavItem::Account,
}
}
+26 -1
View File
@@ -150,6 +150,12 @@ pub struct App {
/// 而检索条件与结果(会跨页存活、要被事件写)在 `AppState::content`。放进 `view` 模型也
/// 不行——`refresh_view` 每次都用快照重建模型,选择会被冲回默认值。
pub(super) content: pages::content::PageState,
/// 账户页的**表单状态**(三条轨道的输入串;密码只活在这一次请求里)。
pub(super) account_form: pages::account::Form,
/// 账户页视图模型(与 `view` 同一条「状态变了才重建」的门控)。
pub(super) account: pages::account::Page,
/// 皮肤/头像解码缓存(M114:同一张皮肤只解一次)。
pub(super) avatars: pages::account::avatar::Cache,
}
impl App {
@@ -251,6 +257,15 @@ impl App {
download_draft: pages::InstallDraft::default(),
install_cancelled_seen: 0,
content: pages::content::PageState::default(),
account_form: pages::account::Form::new(),
account: pages::account::Page::build(
&AppState::new(),
&pages::account::Form::new(),
&mut pages::account::avatar::Cache::default(),
unlucky_i18n::Lang::En,
width,
),
avatars: pages::account::avatar::Cache::default(),
};
// 配色来源档可能已经指向一张背景图:那时 `Ui` 必须由解析出的方案构造,而不是 baseline。
app.rebuild_ui();
@@ -333,7 +348,7 @@ impl App {
// 草稿同理(M105):它也是页面自己持有的输入,重建模型时带回去,
// 否则每来一条事件(连安装进度都算)用户填的加载器就被抹回「原版」。
let draft = self.download_draft.clone();
// 右栗占掉的宽度先扣掉:面板展开时页面按更窄的宽度排版(「收缩而不是溢出」,M104)
// 右栏占掉的宽度先扣掉:面板展开时页面按更窄的宽度排版(「收缩而不是溢出」,M104)
let width = self.agent.content_width(self.width);
// M106:语言形参跟着 `LangState` 走(`draft` 那一位是 M105 的安装草稿)。
self.view = super::view::model(
@@ -345,6 +360,16 @@ impl App {
self.lang(),
&self.content,
);
// 账户页(M114):与 `view` 同一次门控重建;皮肤解码走缓存,所以重复重建不重解图。
// 语言同样跟着 M106 的 `LangState` 走(M114 早期钉死 `Lang::En` 的写法已删)。
let lang = self.lang();
self.account = pages::account::Page::build(
&self.state,
&self.account_form,
&mut self.avatars,
lang,
width,
);
self.view_dirty = false;
self.refreshes += 1;
}
+10
View File
@@ -42,6 +42,7 @@ use super::message::{route_of, Message};
use super::state::{App, IDLE_TICK, TICK, TICK_MS, WATCH_WINDOW};
use super::CAPTURE_AT_FRAME;
mod account;
mod agent;
mod content;
mod download;
@@ -185,6 +186,7 @@ impl App {
// M109:直达内容库时补一次检索(与页面内切换同一个入口)
self.ensure_content_loaded();
}
account::force_account_state(self);
self.auto_select();
self.view_dirty = true;
@@ -245,6 +247,12 @@ impl App {
self.state
.toasts
.expire(u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX));
// 设备码/授权码的倒计时(M114):等待态每秒都要重画一次,否则「剩 900s」永远不动,
// 用户会以为卡死了——这正是任务里「不得只转圈」的那一条。
if self.state.device_login.phase == unlucky_presenter::dto::DeviceLoginPhase::Waiting {
self.view_dirty = true;
}
// `ticks` 的单位是**33 ms 的一拍**,不是「advance 被调了几次」:空闲心跳一次跨 1 s,
// 要记 30 拍,这样 `theme::config_poll_due`(30 拍 ≈ 1 秒)在两种时钟下语义一致。
let ticks = elapsed.as_millis().div_euclid(u128::from(TICK_MS));
@@ -389,6 +397,8 @@ fn env_start_route() -> Option<Route> {
"agent" => Some(Route::Agent),
// M109:内容库(截图矩阵要能直达;页面内的四条侧栏不在路由里)
"content" => Some(Route::Content),
// M114:账户页的 D30 矩阵要能直达(`cli.rs` 不在本 mission 的 scope)
"accounts" => Some(Route::Accounts),
_ => None,
}
}
+156
View File
@@ -0,0 +1,156 @@
//! 账户页消息的落点(M114):页面只发意图,这里翻成 `AppCommand` 或本地的表单状态写入。
//!
//! 三条纪律(与 `update.rs` 同源):
//!
//! 1. **不做乐观回显**:切账户/删账户/登录都只派命令,等 `AccountsChanged` /
//! `DeviceLoginChanged` / `AuthlibLoginChanged` 回来才改列表;
//! 2. **密码只走一次**:`Submit` 把 `AuthlibRequest` 交给后端后立刻清掉表单里的密码
//! (成功失败都清——重试用新输入,不在内存里多留一份凭据);
//! 3. **表单态是纯 UI 状态**:输入框改动只写 `App::account_form` + 置脏,不派命令。
use unlucky_presenter::dto::{AppCommand, AuthlibRequest};
use crate::pages::account::{Message as Account, Panel, Track};
use super::super::state::App;
impl App {
/// 账户页消息。
pub(super) fn on_account(&mut self, message: Account) {
match message {
Account::Open(track) => {
self.account_form.open(track);
// 微软面板一打开就把「设备码」这条路准备好:用户点开就该看到码或选择按钮,
// 而不是再点一次「登录」(面板里的两条流按钮仍然可选)
if track == Track::Microsoft && self.state.device_login.phase.visible() {
self.account_form.panel = Panel::Microsoft;
}
self.view_dirty = true;
}
Account::Close => {
self.account_form.close();
// 关面板同时收掉登录任务(避免关掉面板后后台还在轮询、也不会凭空多一个账户)
if self.state.device_login.phase.busy() || self.state.authlib_login.phase.busy() {
self.dispatch(AppCommand::CancelDeviceLogin);
}
self.view_dirty = true;
}
Account::Server(value) => {
self.account_form.server = value;
self.view_dirty = true;
}
Account::Login(value) => {
self.account_form.login = value;
self.view_dirty = true;
}
Account::Password(value) => {
self.account_form.password = value;
self.view_dirty = true;
}
Account::OfflineName(value) => {
self.account_form.offline_name = value;
self.view_dirty = true;
}
Account::Probe => {
let server = self.account_form.server.clone();
if !server.trim().is_empty() {
self.dispatch(AppCommand::ProbeAuthlibServer(server));
}
}
Account::Submit => match self.account_form.panel {
Panel::Offline => {
let name = self.account_form.offline_name.trim().to_string();
if !name.is_empty() {
self.account_form.offline_name.clear();
self.dispatch(AppCommand::AddOfflineAccount(name));
}
}
Panel::Authlib => {
let ready = self.account_form.authlib_ready();
if ready {
let request = AuthlibRequest::new(
self.account_form.server.clone(),
self.account_form.login.clone(),
std::mem::take(&mut self.account_form.password),
);
self.dispatch(AppCommand::AddAuthlibAccount(request));
}
}
Panel::Microsoft => self.on_account(Account::StartBrowser),
Panel::None => {}
},
Account::StartDevice => self.dispatch(AppCommand::StartDeviceLogin),
Account::StartBrowser => self.dispatch(AppCommand::StartBrowserLogin),
Account::Cancel => {
self.account_form.close();
self.dispatch(AppCommand::CancelDeviceLogin);
}
Account::Copy(text) => {
// 剪贴板只放用户码/链接这类**公开**内容(凭据永不经过这条路径)
let _: iced::Task<crate::app::Message> = iced::clipboard::write(text);
}
Account::Switch(id) => self.dispatch(AppCommand::SwitchAccount(id)),
Account::Remove(id) => self.dispatch(AppCommand::RemoveAccount(id)),
Account::Relogin => {
// 「重新登录」按微软轨的默认流走(授权码 + 系统浏览器)
self.account_form.panel = Panel::Microsoft;
self.dispatch(AppCommand::StartBrowserLogin);
}
}
self.refresh_view();
}
}
/// 取证开关 `ULL_ACCOUNT_STATE` 的落地:把「很难自然等到」的状态钉死一次。
///
/// 为什么需要:设备码过期要等 15 分钟、第三方站表单要手点两下,截图通道等不到。这里只在
/// **截图模式**下生效(`--screenshot`),交互模式一律不读——与 `ULL_START_ROUTE` 同一口径。
pub(super) fn force_account_state(app: &mut App) {
if !app.has_screenshot() {
return;
}
let Ok(state) = std::env::var("ULL_ACCOUNT_STATE") else {
return;
};
match state.trim().to_lowercase().as_str() {
// 设备码已过期:起点往前挪一小时(倒计时自己算出来就是 0)
"expired" => {
app.state.device_login_started =
Some(std::time::Instant::now() - std::time::Duration::from_secs(3_600));
}
// 第三方站表单:直接把面板打开并预填地址(截图要看到输入框与校验按钮)
"authlib" | "authlib-form" => {
app.account_form.panel = crate::pages::account::Panel::Authlib;
if app.account_form.server.trim().is_empty() {
app.account_form.server = "https://littleskin.cn/api/yggdrasil/".to_string();
}
app.account_form.login = "steve@example.com".to_string();
app.account_form.password = "not-a-real-password".to_string();
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use crate::pages::account::{Message as Account, Panel, Track};
/// 表单态是纯 UI 状态:打开/关闭面板不派命令,但会把面板切对。
///
/// 抓得住:`Open` 忘了写 `panel`(点了轨道卡什么都不出现)、`close()` 不清密码。
/// 抓不住:真实 dispatch 的副作用(那要真后端)。
#[test]
fn the_form_state_follows_the_page_messages() {
use crate::pages::account::Form;
let mut form = Form::new();
assert_eq!(form.panel, Panel::None);
form.open(Track::Authlib);
assert_eq!(form.panel, Panel::Authlib);
form.password = "hunter2".to_string();
form.close();
assert_eq!(form.panel, Panel::None);
assert!(form.password.is_empty(), "关闭面板必须把一次性密码清掉");
let _ = Account::Open(Track::Offline);
}
}
@@ -88,6 +88,8 @@ impl App {
self.view_dirty = true;
self.refresh_view();
}
// M114:账户页(三轨登录 / 列表动作 / 表单输入)
pages::Message::Account(message) => self.on_account(message),
// 还没接后端的占位动作:只打日志(哪几个、为什么,见 pages 模块文档的偏离登记)
pages::Message::Action(action) => {
eprintln!("[page] 占位动作 {action:?} pressed(没有对应 AppCommand)");
+31 -1
View File
@@ -19,6 +19,7 @@ use super::state::{log_first_frame, App};
use super::APP_TITLE;
mod logs;
mod rail;
use logs::logs_model;
@@ -55,10 +56,12 @@ impl App {
// 右栗(M104):拆出档返回 `None`(会话已在独立页里);拖拽期间另有铺满窗口的取指针层。
let overlay = agent::drag_overlay(&self.agent).map(|element| element.map(Message::Agent));
let account = self.rail_account();
match pages::Screen::of(self.state.route()) {
Some(_) => shell::view_with_background(
&self.ui,
nav_item_of(self.state.route()),
&account,
APP_TITLE,
background,
// M101 r2:设置页的只读状态(外观运行期状态 + 各组自己的状态)一次递进去。
@@ -79,10 +82,37 @@ impl App {
self.options.force_state,
self.lang(),
),
// `Route::Agent`:独立页与右栗共用同一个 `conversation::view`(`agent::page` 内部调的它)。
// 账户页(M114):它不走 `pages::Screen` 那四页的 `Model`,自己一棵树
// (模型在 `App::account`,由 `refresh_view` 按同一条门控重建;宽度用 M104 的
// 中栏可用宽,与其它页同源)。
None if self.state.route() == &Route::Accounts => shell::view_with_background(
&self.ui,
NavItem::Account,
&account,
APP_TITLE,
background,
pages::account::view(
&self.ui,
pages::layout::frame_metrics(
pages::layout::PaneKit::Single,
self.account.width,
),
&self.account,
self.lang(),
)
.map(Message::Page),
agent::docked(&self.ui, &self.agent, self.width)
.map(|element| element.map(Message::Agent)),
overlay,
self.options.force_state,
// M106:导航轨标签按当前界面语言取词。
self.lang(),
),
// `Route::Agent`:独立页与右栏共用同一个 `conversation::view`(`agent::page` 内部调的它)。
None => shell::view_with_background(
&self.ui,
NavItem::Ai,
&account,
APP_TITLE,
background,
agent::page(&self.ui, &self.agent, self.width).map(Message::Agent),
+35
View File
@@ -0,0 +1,35 @@
//! 导航轨底部**账户头像位**的状态换算(M114)。
//!
//! 为什么单独一个文件:`app/view.rs` 贴着 400 行硬线,而这块逻辑与页面树无关——
//! 它只回答「轨底那个头像位现在该显示成未登录,还是某个账户」。
use crate::shell;
use super::super::state::App;
/// 导航轨收成「图标条」的窗口高度(M114)。
///
/// 判据不是「项数」而是**真实可用高度**:四项 + 底部头像位在 48 标题栏之上还要放得下
/// 4 × 52 + 4 × 4 + 52 ≈ 300;留出一屏正文的最小高度(424 行宽 + 页头 + 边距),
/// 低于 720 就把标签收掉,只留图标与头像位(头像位**永远可见**,任务要求)。
const RAIL_COMPACT_HEIGHT: f32 = 720.0;
impl App {
/// 导航轨底部头像位的状态(M114):未登录 / 已登录两态要一眼能分。
pub(super) fn rail_account(&self) -> shell::RailAccount {
let compact = self.height < RAIL_COMPACT_HEIGHT;
match self.state.active_account() {
Some(account) => {
shell::RailAccount::signed_in(account.monogram(), account.name.clone())
.compact(compact)
}
// M106:未登录标签跟着**生效语言**走(早期钉死 `Lang::En` 的写法已删)。
None => shell::RailAccount::signed_out(
self.lang()
.catalog()
.text(unlucky_i18n::Key::AccountRailSignedOut),
)
.compact(compact),
}
}
}
+11 -6
View File
@@ -15,12 +15,8 @@
//!
//! ## 三处口径说明
//!
//! 1. **状态差异落在指示线/描边/标签上,容器底色不叠状态层**——这是 A1 文本字段的口径
//! (`HoverActiveIndicatorColor` / `FocusActiveIndicatorColor` 等 token),与按钮家族
//! 「叠一个 8%/10% 的状态层」不同。press 在 A1 里**没有**独立 token,本实现按 hover 处理(登记 D11)。
//! 2. 标签是「**常浮起**」的两段式:有标签就固定占上面那 16px(`BodySmall`),不做上浮动画
//! (M3 的动画由 motion mission 统一接,登记 D12)。
//! 3. 缺省宽度 `Length::Fill`:文本框在页面里按列宽伸展,最小宽 280 无法在 iced 表达(G21)。
//! 1. **状态差异落在指示线/描边/标签上,容器底色不叠状态层**(A1 的口径,与按钮家族的 8%/10% 状态层不同);press 无独立 token,按 hover 处理(D11)。
//! 2. 标签是「**常浮起**」的两段式(占上面 16px,不做上浮动画,登记 D12);缺省宽度 `Fill`(最小宽 280 无法在 iced 表达,G21)。
use iced::widget::text::LineHeight;
use iced::widget::{column, container, row, text, text_input};
@@ -73,6 +69,7 @@ pub struct Field<'a> {
error: bool,
state: Option<Interaction>,
width: Length,
secure: bool,
}
impl<'a> Field<'a> {
@@ -89,6 +86,7 @@ impl<'a> Field<'a> {
error: false,
state: None,
width: Length::Fill,
secure: false,
}
}
@@ -145,6 +143,12 @@ impl<'a> Field<'a> {
self.width = width;
self
}
/// 密码式输入(M114):上屏是掩码(明文上屏=UI 侧凭据泄漏)。
pub fn secure(mut self, secure: bool) -> Self {
self.secure = secure;
self
}
}
/// 一个字段在某一态下的全套颜色(9.4 / 9.7 / 9.8 的落点)。
@@ -269,6 +273,7 @@ pub fn text_field<'a, M: Clone + 'a>(
} else {
Some(on_input)
})
.secure(field.secure)
.size(input_style.size_px)
.line_height(LineHeight::Absolute(Pixels(input_style.line_height_px)))
.font(ui.font_of(input_style))
+2 -1
View File
@@ -234,6 +234,7 @@ mod tests {
fn sub_24_boxes_go_through_view_at() {
const VIEW: &[(&str, usize)] = &[
("shell/nav.rs", 1),
("shell/nav/account.rs", 1), // M114:轨底头像位
("components/inputs/field.rs", 2),
("components/inputs/menu.rs", 2),
("components/inputs/search.rs", 2),
@@ -267,7 +268,7 @@ mod tests {
}
}
assert!(bad.is_empty(), "图标入口用法违规:\n{}", bad.join("\n"));
assert_eq!(views, 13, "全仓 `icons::view` 调用点总数变了");
assert_eq!(views, 14, "`icons::view` 调用点总数变了");
fn sites(list: &[(&str, usize)], rel: &str) -> usize {
list.iter().find(|(p, _)| *p == rel).map_or(0, |(_, n)| *n)
+149
View File
@@ -0,0 +1,149 @@
//! 账户页(M114):**三轨**登录(微软正版 / 第三方皮肤站 / 本地档案)+ 账户列表 + 皮肤区。
//!
//! ## 这一页回答什么
//!
//! 用户的原话是「用户管理页面还没做吗?包括不限于正版登录 离线登录 第三方皮肤站登录」。
//! Slint 版曾有这个页面(`DevDocs/ops/screens-m43/account-data.png`),换 iced 时没搬过来,
//! 于是 iced 版**一个账户入口都没有**——本页就是把它补回来,并按 M114 的口径做成三轨。
//!
//! ## 四条红线(都在本页的断言里)
//!
//! | 红线 | 落点 |
//! |---|---|
//! | 页面不得出现任何 token / refresh_token | 上屏文案只来自 [`model`] 的公开字段;`tests` 里有「把 JWT 塞进事件、断言模型干净」的用例 |
//! | 离线档案的说明必须带「仅本地/隔离网络测试用,无法连接启用正版验证的服务器」 | `Key::AccountTrackOfflineBody` / `Key::AccountOfflineWarning` 两处都写全 |
//! | 设备码不得只转圈 | [`login`]:用户码 + 链接 + 倒计时 + 「已过期,重试」 |
//! | 没有皮肤不给假皮肤 | 头像位 = 首字母块(`profile_id` 稳定取色);第三方轨才可能出真图 |
//!
//! ## 模块
//!
//! | 文件 | 职责 |
//! |---|---|
//! | [`model`] | 状态 → 视图模型(列表行 / 当前账户 / 三条轨道的面板态) |
//! | [`avatar`] | 首字母块 + 皮肤图(解码/裁剪缓存;失败一律退回首字母块,**绝不白块**) |
//! | [`widgets`] | 本页的小件(头像块 / 章节标题 / 徽标),样式全部走令牌 |
//! | [`rows`] | 当前账户卡片 + 账户列表行 |
//! | [`forms`] | 三条轨道的入口卡 + 本地档案/第三方站表单 |
//! | [`login`] | 微软登录面板(设备码倒计时 / 浏览器授权 / 失败态) |
//! | `tests` | 视图模型的判据(凭据红线、空态、倒计时、皮肤回落) |
pub mod avatar;
pub mod forms;
pub mod login;
pub mod model;
pub mod panels;
pub mod rows;
pub mod widgets;
#[cfg(test)]
mod tests;
pub use model::{Form, Page, Panel, Track};
use iced::widget::{column, scrollable};
use iced::{Element, Length};
use unlucky_design::spacing::Space;
use unlucky_i18n::{Key, Lang};
use crate::app::components::buttons::{self, Button};
use crate::pages::frame::{self, Header};
use crate::pages::layout::FrameMetrics;
use crate::theme::Ui;
use super::Message as PageMessage;
/// 账户页的页面消息(app 层把它翻成 `AppCommand` / 状态写入)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Message {
/// 打开某条轨道的表单
Open(Track),
/// 关掉表单/登录面板
Close,
/// 第三方站地址输入
Server(String),
/// 登录名输入
Login(String),
/// 密码输入(只存在内存里,随请求交给 host,用完即弃)
Password(String),
/// 本地档案名输入
OfflineName(String),
/// 校验服务器地址(服务发现)
Probe,
/// 表单提交(本地档案 → 建档案;第三方站 → 登录)
Submit,
/// 微软:设备码流
StartDevice,
/// 微软:授权码流(拉起系统浏览器)
StartBrowser,
/// 取消/关掉登录面板
Cancel,
/// 复制一段文本(用户码 / 链接)
Copy(String),
/// 切换当前启动账户
Switch(String),
/// 删除账户
Remove(String),
/// 重新登录(微软轨 → 授权码流)
Relogin,
}
impl Message {
/// 包成页面的消息(本模块内部与 app 层都用它,保证只有一处包装点)。
pub fn into_page(self) -> PageMessage {
PageMessage::Account(self)
}
}
/// 整页。
pub fn view<'a>(
ui: &'a Ui,
metrics: FrameMetrics,
page: &'a Page,
lang: Lang,
) -> Element<'a, PageMessage> {
let text = lang.catalog();
let subtitle = text.text(Key::AccountSubtitle);
let add = text.text(Key::AccountEmptyAction);
let header = Header::new(text.text(Key::AccountTitle))
.subtitle(subtitle)
.action(buttons::tonal(
ui,
Button::new(add, Message::Open(Track::Microsoft).into_page()),
));
let top = if page.rows.is_empty() {
forms::empty(ui, text, lang)
} else {
column![
rows::active_card(ui, page, text, lang),
rows::list(ui, page, text, lang),
]
.spacing(ui.space(Space::X6))
.into()
};
// 三条轨道入口 + 表单/登录面板:面板存在时**只画面板**,且**置顶**——
// 否则在 1180×760 下设备码的「复制用户码 / 取消」会掉到折线以下(D30 复审实测)。
let flows = match page.panel {
Panel::None => forms::tracks(ui, text, lang),
_ => forms::panel(ui, page, text, lang),
};
let mut content = column![].spacing(ui.space(Space::X6)).width(Length::Fill);
content = if page.panel == Panel::None {
content.push(top).push(flows)
} else {
content.push(flows).push(top)
};
frame::page(
ui,
metrics,
header,
scrollable(content)
.style(frame::scroll_style(ui))
.width(Length::Fill)
.height(Length::Fill),
)
}
+205
View File
@@ -0,0 +1,205 @@
//! 头像位与皮肤区:**首字母块**(无皮肤时)与**真图**(第三方轨抓到皮肤时)。
//!
//! ## 为什么头像可以「真有图」
//!
//! presenter 只把皮肤的 **PNG 原图**送到 UI(它不引入图片解码依赖),裁剪/缩放全部在这里做:
//! Minecraft 皮肤的头部在 `(8,8)` 的 8×8 方块(64×64 皮肤),帽子层在 `(40,8)`,
//! 两层贴起来再放大到 64×64 就是一张真正的头像。**解码失败一律退回首字母块**——
//! 头像位不允许出现白块(M114 明文要求)。
//!
//! ## 依赖口径
//!
//! 用的是 `crates/app-iced/Cargo.toml` **既有**的 `image`(png feature,M93 背景图那一条),
//! 本 mission 没有改任何依赖表。
use std::collections::BTreeMap;
use iced::widget::image;
use unlucky_presenter::dto::SkinImage;
/// 头像边长(像素):列表行 40、当前账户卡片 56 共用同一张 64 的图(缩下来仍然清晰)。
const HEAD_PX: u32 = 64;
/// 皮肤原图的头部坐标(64×64 皮肤的标准布局)。
const FACE: (u32, u32) = (8, 8);
/// 帽子/头发层的坐标(叠在脸上一层)。
const HAT: (u32, u32) = (40, 8);
/// 头部方块边长(8×8)。
const FACE_EDGE: u32 = 8;
/// 一个账户的解码结果(失败就是两个 `None`,UI 画首字母块)。
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Avatar {
/// 裁好的头像(64×64 RGBA)
pub head: Option<image::Handle>,
/// 皮肤原图(皮肤预览区用)
pub skin: Option<image::Handle>,
}
/// 解码缓存:同一个账户的同一张皮肤只解码一次。
///
/// 键 = 账户 id,值 = (皮肤来源串, 解码结果)。来源串变了(重新登录换了皮肤)就重解。
#[derive(Debug, Default)]
pub struct Cache {
entries: BTreeMap<String, (String, Avatar)>,
}
impl Cache {
/// 取某个账户的头像(必要时解码)。
pub fn resolve(&mut self, id: &str, skin: Option<&SkinImage>) -> Avatar {
let source = skin.map(|skin| skin.source.clone()).unwrap_or_default();
let empty = skin.is_none_or(SkinImage::is_empty);
if empty {
// 没有皮肤 = 没有图(离线轨永远走这条;**不给假皮肤**)
self.entries.remove(id);
return Avatar::default();
}
if let Some((cached_source, avatar)) = self.entries.get(id) {
if cached_source == &source {
return avatar.clone();
}
}
let decoded = skin.map(decode).unwrap_or_default();
self.entries
.insert(id.to_string(), (source, decoded.clone()));
decoded
}
/// 当前缓存条目数(单测与诊断用)。
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
/// 缓存是否为空。
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
/// PNG 皮肤 → 头像(裁 + 叠帽子层 + 放大)。
fn decode(skin: &SkinImage) -> Avatar {
let Some(decoded) = decode_png(&skin.png) else {
return Avatar::default();
};
let (width, height) = (decoded.width(), decoded.height());
// 旧版皮肤是 64×32:没有帽子层,只有脸
if width < FACE.0 + FACE_EDGE || height < FACE.1 + FACE_EDGE {
return Avatar::default();
}
let mut face =
::image::imageops::crop_imm(&decoded, FACE.0, FACE.1, FACE_EDGE, FACE_EDGE).to_image();
if width >= HAT.0 + FACE_EDGE && height >= HAT.1 + FACE_EDGE {
let hat =
::image::imageops::crop_imm(&decoded, HAT.0, HAT.1, FACE_EDGE, FACE_EDGE).to_image();
::image::imageops::overlay(&mut face, &hat, 0, 0);
}
let scaled = ::image::imageops::resize(
&face,
HEAD_PX,
HEAD_PX,
::image::imageops::FilterType::Nearest,
);
Avatar {
head: Some(image::Handle::from_rgba(
HEAD_PX,
HEAD_PX,
scaled.into_raw(),
)),
// 皮肤预览用**原图**(64×64):tower 口径是「原图直接展示,不为好看伪造皮肤」
skin: Some(image::Handle::from_bytes(skin.png.clone())),
}
}
/// 解 PNG(尺寸上限与背景图那条守门同源:皮肤不该有超大图)。
fn decode_png(bytes: &[u8]) -> Option<::image::RgbaImage> {
const MAX_EDGE: u32 = 512;
let reader = ::image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.ok()?;
let (width, height) = reader.into_dimensions().ok()?;
if width == 0 || height == 0 || width > MAX_EDGE || height > MAX_EDGE {
return None;
}
let reader = ::image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.ok()?;
Some(reader.decode().ok()?.to_rgba8())
}
#[cfg(test)]
mod tests {
use super::*;
use ::image::ImageEncoder;
use ::image::{Rgba, RgbaImage};
fn png_of(image: &RgbaImage) -> Vec<u8> {
let mut bytes = Vec::new();
let encoder = ::image::codecs::png::PngEncoder::new(&mut bytes);
encoder
.write_image(
image.as_raw(),
image.width(),
image.height(),
::image::ExtendedColorType::Rgba8,
)
.expect("编码 PNG");
bytes
}
/// 造一张 64×64 的皮肤:脸是红色,帽子层是半透明蓝。
fn skin_bytes() -> Vec<u8> {
let mut skin = RgbaImage::from_pixel(64, 64, Rgba([0, 0, 0, 0]));
for x in 8..16 {
for y in 8..16 {
skin.put_pixel(x, y, Rgba([200, 10, 10, 255]));
}
}
for x in 40..48 {
for y in 8..16 {
skin.put_pixel(x, y, Rgba([10, 10, 200, 120]));
}
}
png_of(&skin)
}
#[test]
fn a_real_skin_becomes_a_head_with_the_hat_layer() {
let avatar = decode(&SkinImage {
png: skin_bytes(),
source: "test".to_string(),
});
assert!(avatar.head.is_some(), "64×64 皮肤必须裁出头像");
assert!(avatar.skin.is_some(), "皮肤预览要有原图");
}
#[test]
fn a_broken_payload_falls_back_instead_of_panicking() {
let avatar = decode(&SkinImage {
png: b"not a png".to_vec(),
source: "test".to_string(),
});
assert!(avatar.head.is_none(), "解不开就退回首字母块");
assert!(avatar.skin.is_none());
}
#[test]
fn the_cache_keeps_one_entry_per_account_and_drops_it_without_a_skin() {
let mut cache = Cache::default();
let skin = SkinImage {
png: skin_bytes(),
source: "a".to_string(),
};
let first = cache.resolve("account:a", Some(&skin));
assert!(first.head.is_some());
assert_eq!(cache.len(), 1);
// 同一来源:命中缓存
let again = cache.resolve("account:a", Some(&skin));
assert!(again.head.is_some());
// 没有皮肤:条目被删掉(不留「上次的图」冒充真皮肤)
let none = cache.resolve("account:a", None);
assert!(none.head.is_none());
assert!(cache.is_empty());
}
}
+328
View File
@@ -0,0 +1,328 @@
//! 三条轨道的入口卡与两张表单(本地档案 / 第三方皮肤站)。
//!
//! ## 为什么是「三条轨道」而不是「一个添加按钮 + 一个类型下拉」
//!
//! 三条轨道的**字段完全不同**(微软没有密码输入框、本地档案没有服务器、第三方站两样都有),
//! 而且失败原因也不同(403 / 白名单未批 / 服务器不可达)。把它们压进一个表单只会让每种情况
//! 都要解释自己不属于另外两种——所以入口就是三张卡,各自展开自己的面板。
use iced::widget::{column, container, row};
use iced::{Alignment, Element, Length};
use unlucky_design::color::Role;
use unlucky_design::spacing::Space;
use unlucky_design::typography::TypeRole;
use unlucky_i18n::{Catalog, Key, Lang};
use crate::app::components::buttons::{self, Button};
use crate::app::components::feedback::empty_state::{empty_state, EmptyState};
use crate::app::components::inputs::{text_field, Field, FieldVariant};
use crate::pages::frame;
use crate::theme::Ui;
use crate::pages::account::model::{AuthlibPanel, Page, Track};
use crate::pages::Message as PageMessage;
use super::{login, widgets, Message as Account};
/// 空态:不是一张白页——标题 + 说明 + **三条轨道的直达入口**。
pub fn empty<'a>(ui: &'a Ui, catalog: Catalog, lang: Lang) -> Element<'a, PageMessage> {
let mut actions = row![]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center);
for track in Track::ALL {
// 三个按钮各用**轨道的名字**做标签(三条都叫「登录」的话,用户分不清点哪个)
actions = actions.push(buttons::tonal(
ui,
Button::new(
catalog.text(track.title_key()),
Account::Open(track).into_page(),
),
));
}
let state = empty_state(
ui,
EmptyState::new(
unlucky_design::icons::IconKind::User,
catalog.text(Key::AccountEmptyTitle),
catalog.text(Key::AccountEmptyBody),
),
);
let _ = lang;
column![
container(state).height(Length::Fixed(ui.space(Space::X8) * 8.0)),
container(actions)
.width(Length::Fill)
.align_x(Alignment::Center)
.center_x(Length::Fill),
]
.spacing(ui.space(Space::X4))
.width(Length::Fill)
.into()
}
/// 三条轨道的入口卡(面板没打开时画这一排)。
pub fn tracks<'a>(ui: &'a Ui, catalog: Catalog, lang: Lang) -> Element<'a, PageMessage> {
let _ = lang;
let mut row = iced::widget::Row::new().spacing(ui.space(Space::X4));
for track in Track::ALL {
row = row.push(track_card(ui, track, catalog));
}
row.width(Length::Fill).into()
}
fn track_card<'a>(ui: &'a Ui, track: Track, catalog: Catalog) -> Element<'a, PageMessage> {
let body = column![
frame::text_role(
ui,
TypeRole::TitleSmall,
true,
catalog.text(track.title_key()),
ui.color(Role::OnSurface),
),
frame::text_role(
ui,
TypeRole::BodySmall,
false,
catalog.text(track.body_key()),
ui.color(Role::OnSurfaceVariant),
),
buttons::outlined(
ui,
Button::new(
catalog.text(track.action_key()),
Account::Open(track).into_page(),
),
),
]
.spacing(ui.space(Space::X3));
container(frame::card(ui, body))
.width(Length::FillPortion(1))
.into()
}
/// 当前打开的面板。
pub fn panel<'a>(
ui: &'a Ui,
page: &'a Page,
catalog: Catalog,
lang: Lang,
) -> Element<'a, PageMessage> {
let _ = lang;
match page.panel {
crate::pages::account::model::Panel::None => tracks(ui, catalog, Lang::En),
crate::pages::account::model::Panel::Microsoft => login::panel(ui, &page.device, catalog),
crate::pages::account::model::Panel::Authlib => authlib_form(ui, page, catalog),
crate::pages::account::model::Panel::Offline => offline_form(ui, page, catalog),
}
}
/// 本地档案表单(**说明里带「仅本地/隔离网络测试用」这条限定**)。
fn offline_form<'a>(ui: &'a Ui, page: &'a Page, catalog: Catalog) -> Element<'a, PageMessage> {
let ready = page.form.offline_ready();
let submit = if ready {
buttons::filled(
ui,
Button::new(
catalog.text(Key::AccountOfflineSubmit),
Account::Submit.into_page(),
),
)
} else {
buttons::filled(
ui,
Button::disabled(catalog.text(Key::AccountOfflineSubmit)),
)
};
let body = column![
widgets::section(
ui,
catalog.text(Key::AccountTrackOfflineTitle),
Some(catalog.text(Key::AccountTrackOfflineBody)),
),
warning(ui, catalog.text(Key::AccountOfflineWarning)),
text_field(
ui,
Field::new(&page.form.offline_name)
.variant(FieldVariant::Outlined)
.label(catalog.text(Key::AccountOfflineNameLabel))
.placeholder(catalog.text(Key::AccountOfflineNameHint))
.supporting(catalog.text(Key::AccountOfflineNameHint)),
|value| Account::OfflineName(value).into_page(),
),
row![
submit,
buttons::text(
ui,
Button::new(
catalog.text(Key::AccountDialogClose),
Account::Close.into_page()
)
),
]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center),
]
.spacing(ui.space(Space::X3));
frame::card(ui, body)
}
/// 第三方站表单:地址(可单独校验)+ 登录名 + 密码 + 登录。
fn authlib_form<'a>(ui: &'a Ui, page: &'a Page, catalog: Catalog) -> Element<'a, PageMessage> {
let busy = page.authlib.busy();
let ready = page.form.authlib_ready() && !busy;
let submit = if ready {
buttons::filled(
ui,
Button::new(
catalog.text(Key::AccountAuthlibSubmit),
Account::Submit.into_page(),
),
)
} else {
buttons::filled(
ui,
Button::disabled(catalog.text(Key::AccountAuthlibSubmit)),
)
};
let mut body = column![
widgets::section(
ui,
catalog.text(Key::AccountTrackAuthlibTitle),
Some(catalog.text(Key::AccountTrackAuthlibBody)),
),
text_field(
ui,
Field::new(&page.form.server)
.variant(FieldVariant::Outlined)
.label(catalog.text(Key::AccountServerLabel))
.placeholder(catalog.text(Key::AccountServerHint))
.supporting(if page.checked_server.is_empty() {
catalog.text(Key::AccountServerHint)
} else {
page.checked_server.as_str()
}),
|value| Account::Server(value).into_page(),
),
text_field(
ui,
Field::new(&page.form.login)
.variant(FieldVariant::Outlined)
.label(catalog.text(Key::AccountLoginNameLabel))
.placeholder(""),
|value| Account::Login(value).into_page(),
),
text_field(
ui,
Field::new(&page.form.password)
.variant(FieldVariant::Outlined)
.label(catalog.text(Key::AccountPasswordLabel))
.supporting(catalog.text(Key::AccountPasswordHint))
// 密码**掩码**显示:明文只在内存里,不上屏
.secure(true),
|value| Account::Password(value).into_page(),
),
status_line(ui, page, catalog),
row![
buttons::outlined(
ui,
Button::new(
catalog.text(Key::AccountServerProbe),
Account::Probe.into_page()
)
),
submit,
buttons::text(
ui,
Button::new(
catalog.text(Key::AccountDialogClose),
Account::Close.into_page()
)
),
]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center),
]
.spacing(ui.space(Space::X3));
if !ready && !busy {
body = body.push(frame::text_role(
ui,
TypeRole::BodySmall,
false,
catalog.text(Key::AccountAuthlibIdleHint),
ui.color(Role::OnSurfaceVariant),
));
}
frame::card(ui, body)
}
/// 第三方轨的状态行(校验通过 / 进行中 / 失败原文)。
///
/// 进行中与通过都走 **i18n**:presenter 给的 `message` 是后端诊断串(中文),
/// 直接上屏会让英文界面里混一段中文;失败态才用它(那是要人读的错误原因)。
fn status_line<'a>(ui: &'a Ui, page: &'a Page, catalog: Catalog) -> Element<'a, PageMessage> {
match &page.authlib {
AuthlibPanel::Idle => frame::text_role(
ui,
TypeRole::BodySmall,
false,
"",
ui.color(Role::OnSurfaceVariant),
),
AuthlibPanel::Running { .. } => frame::text_role(
ui,
TypeRole::LabelMedium,
false,
catalog.text(Key::AccountServerChecking),
ui.color(Role::OnSurfaceVariant),
),
AuthlibPanel::Ready { server_name, .. } => frame::text_role_owned(
ui,
TypeRole::LabelMedium,
true,
catalog.render(Key::AccountServerOk, &[("server", server_name.as_str())]),
ui.color(Role::Primary),
),
AuthlibPanel::Failed { message } => frame::text_role(
ui,
TypeRole::LabelMedium,
false,
message,
ui.color(Role::Error),
),
AuthlibPanel::Succeeded { name } => frame::text_role(
ui,
TypeRole::LabelMedium,
true,
name,
ui.color(Role::Primary),
),
}
}
/// 「仅本地/隔离网络测试用」这条限定:**带色块**,不是一句灰字(用户要点得明白)。
fn warning<'a>(ui: &'a Ui, text: &'a str) -> Element<'a, PageMessage> {
container(frame::text_role(
ui,
TypeRole::BodySmall,
false,
text,
ui.color(Role::OnErrorContainer),
))
.width(Length::Fill)
.padding(ui.space(Space::X2))
.style(move |_theme| container::Style {
background: Some(iced::Background::Color(ui.color(Role::ErrorContainer))),
border: iced::Border {
radius: ui.radius_dp(unlucky_design::shape::ShapeScale::Small),
..iced::Border::default()
},
..container::Style::default()
})
.into()
}
+349
View File
@@ -0,0 +1,349 @@
//! 微软登录面板:设备码(用户码 + 链接 + **倒计时** + 过期重试)与授权码(浏览器 + 可复制链接 + 取消)。
//!
//! ## 为什么不是「一个转圈」
//!
//! 设备码流的等待期可以长到 15 分钟。只画转圈的话,用户既不知道要做什么、也不知道还剩多久,
//! 更不知道已经过期了——M114 把这三件事都做成可见状态:用户码(可复制)、链接(可复制/打开)、
//! 倒计时(`{secs}s left`)与过期后的「已过期,重试」。授权码流同理,另外必须能**取消**。
use iced::widget::{column, container, row};
use iced::{Alignment, Background, Border, Element, Length};
use unlucky_design::color::Role;
use unlucky_design::shape::ShapeScale;
use unlucky_design::spacing::Space;
use unlucky_design::typography::TypeRole;
use unlucky_i18n::{Catalog, Key};
use crate::app::components::buttons::{self, Button};
use crate::pages::frame;
use crate::theme::Ui;
use crate::pages::account::model::DevicePanel;
use crate::pages::Message as PageMessage;
use super::Message as Account;
/// 微软登录面板。
pub fn panel<'a>(
ui: &'a Ui,
device: &'a DevicePanel,
catalog: Catalog,
) -> Element<'a, PageMessage> {
match device {
DevicePanel::Hidden => idle(ui, catalog),
DevicePanel::Requesting { message } => notice(ui, message, catalog),
DevicePanel::Code {
code,
link,
remaining,
expired,
..
} => device_code(ui, code, link, *remaining, *expired, catalog),
DevicePanel::Browser {
link,
remaining,
expired,
..
} => browser(ui, link, *remaining, *expired, catalog),
DevicePanel::Failed { message } => failed(ui, message, catalog),
DevicePanel::Succeeded { name } => succeeded(ui, name, catalog),
}
}
/// 空闲:给出两条流的入口(GUI 默认授权码流,设备码是备选)。
fn idle<'a>(ui: &'a Ui, catalog: Catalog) -> Element<'a, PageMessage> {
let body = column![row![
buttons::filled(
ui,
Button::new(
catalog.text(Key::AccountDeviceBrowser),
Account::StartBrowser.into_page(),
)
),
buttons::outlined(
ui,
Button::new(
catalog.text(Key::AccountDeviceUseCode),
Account::StartDevice.into_page(),
)
),
buttons::text(
ui,
Button::new(
catalog.text(Key::AccountDeviceCancel),
Account::Close.into_page()
)
),
]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center),]
.spacing(ui.space(Space::X3));
frame::card(ui, body)
}
/// 「正在申请/正在校验」:一句状态 + 取消。
fn notice<'a>(ui: &'a Ui, message: &'a str, catalog: Catalog) -> Element<'a, PageMessage> {
let body = column![
frame::text_role(
ui,
TypeRole::BodyMedium,
false,
message,
ui.color(Role::OnSurfaceVariant),
),
row![buttons::text(
ui,
Button::new(
catalog.text(Key::AccountDeviceCancel),
Account::Cancel.into_page()
)
)]
.align_y(Alignment::Center),
]
.spacing(ui.space(Space::X3));
frame::card(ui, body)
}
/// 设备码等待态:**码 + 链接 + 倒计时**。
fn device_code<'a>(
ui: &'a Ui,
code: &'a str,
link: &'a str,
remaining: Option<u64>,
expired: bool,
catalog: Catalog,
) -> Element<'a, PageMessage> {
let mut actions = row![
buttons::tonal(
ui,
Button::new(
catalog.text(Key::AccountDeviceCodeCopy),
Account::Copy(code.to_string()).into_page(),
)
),
buttons::outlined(
ui,
Button::new(
catalog.text(Key::AccountDeviceLinkCopy),
Account::Copy(link.to_string()).into_page(),
)
),
]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center);
if expired {
actions = actions.push(buttons::filled(
ui,
Button::new(
catalog.text(Key::AccountDeviceRetry),
Account::StartDevice.into_page(),
),
));
}
actions = actions.push(buttons::text(
ui,
Button::new(
catalog.text(Key::AccountDeviceCancel),
Account::Cancel.into_page(),
),
));
let countdown = countdown_line(ui, remaining, expired, catalog);
let body = column![
frame::text_role(
ui,
TypeRole::LabelMedium,
false,
catalog.text(Key::AccountDeviceCodeLabel),
ui.color(Role::OnSurfaceVariant),
),
frame::text_role(
ui,
TypeRole::HeadlineSmall,
true,
code,
ui.color(Role::OnSurface),
),
frame::text_role(
ui,
TypeRole::BodySmall,
false,
link,
ui.color(Role::OnSurfaceVariant),
),
countdown,
frame::text_role(
ui,
TypeRole::BodySmall,
false,
catalog.text(Key::AccountDeviceHint),
ui.color(Role::OnSurfaceVariant),
),
actions,
]
.spacing(ui.space(Space::X3));
frame::card(ui, body)
}
/// 授权码等待态:浏览器已拉起,链接可复制;过期可重试。
fn browser<'a>(
ui: &'a Ui,
link: &'a str,
remaining: Option<u64>,
expired: bool,
catalog: Catalog,
) -> Element<'a, PageMessage> {
let mut actions = row![buttons::outlined(
ui,
Button::new(
catalog.text(Key::AccountDeviceLinkCopy),
Account::Copy(link.to_string()).into_page(),
)
)]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center);
if expired {
actions = actions.push(buttons::filled(
ui,
Button::new(
catalog.text(Key::AccountDeviceRetry),
Account::StartBrowser.into_page(),
),
));
}
actions = actions.push(buttons::text(
ui,
Button::new(
catalog.text(Key::AccountDeviceCancel),
Account::Cancel.into_page(),
),
));
let body = column![
frame::text_role(
ui,
TypeRole::BodyMedium,
false,
catalog.text(Key::AccountDeviceBrowserHint),
ui.color(Role::OnSurface),
),
frame::text_role(
ui,
TypeRole::BodySmall,
false,
link,
ui.color(Role::OnSurfaceVariant),
),
countdown_line(ui, remaining, expired, catalog),
actions,
]
.spacing(ui.space(Space::X3));
frame::card(ui, body)
}
/// 倒计时 / 过期提示(**这一行是「不得只转圈」的落点**)。
fn countdown_line<'a>(
ui: &'a Ui,
remaining: Option<u64>,
expired: bool,
catalog: Catalog,
) -> Element<'a, PageMessage> {
if expired {
return frame::text_role(
ui,
TypeRole::LabelMedium,
true,
catalog.text(Key::AccountDeviceExpired),
ui.color(Role::Error),
);
}
let text = remaining.map_or_else(String::new, |secs| {
catalog.render(Key::AccountDeviceCountdown, &[("secs", &secs.to_string())])
});
frame::text_role_owned(
ui,
TypeRole::LabelMedium,
false,
text,
ui.color(Role::OnSurfaceVariant),
)
}
/// 失败态(`ErrorContainer` 面板:不是一句灰字)。
fn failed<'a>(ui: &'a Ui, message: &'a str, catalog: Catalog) -> Element<'a, PageMessage> {
let body = column![
frame::text_role(
ui,
TypeRole::TitleSmall,
true,
catalog.text(Key::AccountLoginFailed),
ui.color(Role::OnErrorContainer),
),
frame::text_role(
ui,
TypeRole::BodyMedium,
false,
message,
ui.color(Role::OnErrorContainer),
),
row![
buttons::tonal(
ui,
Button::new(
catalog.text(Key::AccountDeviceRetry),
Account::StartDevice.into_page(),
)
),
buttons::text(
ui,
Button::new(
catalog.text(Key::AccountDialogClose),
Account::Close.into_page()
)
),
]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center),
]
.spacing(ui.space(Space::X3));
container(body)
.width(Length::Fill)
.padding(ui.metrics().card_padding)
.style(move |_theme| container::Style {
background: Some(Background::Color(ui.color(Role::ErrorContainer))),
border: Border {
radius: ui.radius_dp(ShapeScale::Medium),
..Border::default()
},
..container::Style::default()
})
.into()
}
/// 成功态。
fn succeeded<'a>(ui: &'a Ui, name: &'a str, catalog: Catalog) -> Element<'a, PageMessage> {
let text = format!("{} · {name}", catalog.text(Key::AccountActiveChip));
let body = column![
frame::text_role_owned(
ui,
TypeRole::BodyMedium,
true,
text,
ui.color(Role::OnSurface),
),
row![buttons::text(
ui,
Button::new(
catalog.text(Key::AccountDialogClose),
Account::Close.into_page()
)
)]
.align_y(Alignment::Center),
]
.spacing(ui.space(Space::X3));
frame::card(ui, body)
}
+278
View File
@@ -0,0 +1,278 @@
//! 状态 → 账户页视图模型(页面层不认识 presenter 的其它类型,只认这里)。
//!
//! 三条轨道在 UI 上只有三种「面板」:微软登录面板 / 第三方站表单 / 本地档案表单。
//! 表单里那些**输入串**是纯 UI 状态,归 [`Form`](app 层持有);从 presenter 来的只有
//! 账户列表、登录进度与倒计时。
use iced::widget::image;
use unlucky_i18n::{Key, Lang};
use unlucky_presenter::dto::{AccountKind, AccountView};
use unlucky_presenter::state::AppState;
use super::avatar::{Avatar, Cache};
use super::panels::{authlib_panel, device_panel};
pub use super::panels::{AuthlibPanel, DevicePanel};
/// 三条轨道。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Track {
/// 微软正版(设备码 / 授权码两条流)
Microsoft,
/// 第三方皮肤站(authlib-injector)
Authlib,
/// 本地档案(离线)
Offline,
}
impl Track {
/// 卡片标题的 key。
#[must_use]
pub const fn title_key(self) -> Key {
match self {
Self::Microsoft => Key::AccountTrackMicrosoftTitle,
Self::Authlib => Key::AccountTrackAuthlibTitle,
Self::Offline => Key::AccountTrackOfflineTitle,
}
}
/// 卡片说明的 key。
#[must_use]
pub const fn body_key(self) -> Key {
match self {
Self::Microsoft => Key::AccountTrackMicrosoftBody,
Self::Authlib => Key::AccountTrackAuthlibBody,
Self::Offline => Key::AccountTrackOfflineBody,
}
}
/// 卡片主按钮的 key(微软/第三方是「登录」,本地是「创建档案」)。
#[must_use]
pub const fn action_key(self) -> Key {
match self {
Self::Microsoft => Key::AccountTrackOpen,
Self::Authlib => Key::AccountTrackOpen,
Self::Offline => Key::AccountTrackCreate,
}
}
/// 三条轨道(卡片顺序)。
pub const ALL: [Track; 3] = [Track::Microsoft, Track::Authlib, Track::Offline];
}
/// 当前打开的面板。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Panel {
/// 只画三条轨道入口
#[default]
None,
/// 微软登录面板
Microsoft,
/// 第三方站表单
Authlib,
/// 本地档案表单
Offline,
}
/// 表单的**纯 UI 状态**(app 层持有,随消息改动)。
///
/// 密码只存在这里和「一次 `AppCommand::AddAuthlibAccount` 的载荷」里:不进日志、不进快照、
/// 不进任何回程 DTO(M114 凭据红线)。
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Form {
/// 当前面板
pub panel: Panel,
/// 第三方站地址
pub server: String,
/// 登录名
pub login: String,
/// 密码(一次性的请求值)
pub password: String,
/// 本地档案名
pub offline_name: String,
}
impl Form {
/// 空表单(只画三条轨道)。
pub fn new() -> Self {
Self::default()
}
/// 打开某条轨道的面板(已开着同一个就用原值,避免输入被清掉)。
pub fn open(&mut self, track: Track) {
self.panel = match track {
Track::Microsoft => Panel::Microsoft,
Track::Authlib => Panel::Authlib,
Track::Offline => Panel::Offline,
};
}
/// 关掉面板(**密码一起清掉**:留着没有意义,只是多留一份凭据在内存里)。
pub fn close(&mut self) {
self.password.clear();
self.panel = Panel::None;
}
/// 提交之后清掉一次性凭据(成功与否都清:重试用新输入)。
pub fn clear_secret(&mut self) {
self.password.clear();
}
/// 本地档案名是否已填(`trim` 后非空才算)。
#[must_use]
pub fn offline_ready(&self) -> bool {
!self.offline_name.trim().is_empty()
}
/// 第三方站表单是否已填(三项都非空;地址的语法问题由 host 的规范化兜)。
#[must_use]
pub fn authlib_ready(&self) -> bool {
!self.server.trim().is_empty() && !self.login.trim().is_empty() && !self.password.is_empty()
}
}
/// 列表行 / 当前账户卡片用的数据。
#[derive(Debug, Clone, PartialEq)]
pub struct Row {
/// 稳定 id(切/删/重登都按它派命令)
pub id: String,
/// 展示名
pub name: String,
/// 首字母块的字
pub monogram: String,
/// 首字母块色号(0..6,`profile_id` 稳定推导)
pub tone: u8,
/// 轨道
pub kind: AccountKind,
/// 轨道文案(i18n)
pub kind_label: String,
/// 「添加于 {date}」
pub added: String,
/// 副行:服务器 / 登录名(没有就空)
pub detail: String,
/// 是否是当前启动账户
pub active: bool,
/// 裁好的头像(`None` = 画首字母块)
pub head: Option<image::Handle>,
/// 皮肤原图(皮肤预览区)
pub skin: Option<image::Handle>,
}
/// 整页视图模型。
#[derive(Debug, Clone, PartialEq)]
pub struct Page {
/// 账户行
pub rows: Vec<Row>,
/// 当前启动账户在 `rows` 里的下标
pub active: Option<usize>,
/// 打开的面板
pub panel: Panel,
/// 表单值(渲染要读)
pub form: Form,
/// 微软登录面板
pub device: DevicePanel,
/// 第三方轨面板
pub authlib: AuthlibPanel,
/// 校验通过的服务器名(表单上显示)
pub checked_server: String,
/// 版面宽度(**中栏可用宽**,M104 的 `AgentUi::content_width`;账户页自己的
/// `layout::frame_metrics` 拿它算列宽,与其它页同源)
pub width: f32,
}
impl Page {
/// 从状态与表单构造(`avatars` 是解码缓存,见 [`Cache]`;`width` 是中栏可用宽)。
pub fn build(
state: &AppState,
form: &Form,
avatars: &mut Cache,
lang: Lang,
width: f32,
) -> Self {
let rows: Vec<Row> = state
.accounts
.iter()
.map(|account| row_of(account, avatars, lang))
.collect();
let active = rows.iter().position(|row| row.active);
let device = device_panel(&state.device_login, state.device_code_remaining());
// 登录在进行(或刚失败/刚成功)时,面板**必须**是微软那条轨:否则用户点了登录、
// 后台已经在等设备码,页面上却只剩三张入口卡——那正是「只转圈」的另一种坏法。
let panel = if matches!(device, DevicePanel::Hidden) {
form.panel
} else {
Panel::Microsoft
};
let (authlib, checked_server) = authlib_panel(&state.authlib_login);
// 「校验通过」的服务器名只在该面板打开且地址一致时显示(换了地址就不再是它)
let checked_server = if form.server.trim().is_empty()
|| state.authlib_login.server.trim().is_empty()
|| form.server.trim() != state.authlib_login.server.trim()
{
String::new()
} else {
checked_server
};
Page {
rows,
active,
panel,
form: form.clone(),
device,
authlib,
checked_server,
width,
}
}
/// 当前账户行。
#[must_use]
pub fn active_row(&self) -> Option<&Row> {
self.active.and_then(|index| self.rows.get(index))
}
/// 有没有账户(空态判据)。
#[must_use]
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
/// 皮肤预览区要画的那张图(当前账户有皮肤才画)。
#[must_use]
pub fn active_skin(&self) -> Option<&image::Handle> {
self.active_row().and_then(|row| row.skin.as_ref())
}
}
/// 单行。
fn row_of(account: &AccountView, avatars: &mut Cache, lang: Lang) -> Row {
let text = lang.catalog();
let avatar: Avatar = avatars.resolve(&account.id, account.skin.as_ref());
let kind_label = match account.kind {
AccountKind::Microsoft => text.text(Key::AccountKindMicrosoft),
AccountKind::Authlib => text.text(Key::AccountKindAuthlib),
AccountKind::Offline => text.text(Key::AccountKindOffline),
};
let detail = if !account.server_url.is_empty() {
text.render(
Key::AccountServer,
&[("server", account.server_url.as_str())],
)
} else {
account.login_name.clone()
};
Row {
id: account.id.clone(),
name: account.name.clone(),
monogram: account.monogram(),
tone: account.monogram_tone(),
kind: account.kind,
kind_label: kind_label.to_string(),
added: text.render(Key::AccountAddedOn, &[("date", account.created.as_str())]),
detail,
active: account.active,
head: avatar.head,
skin: avatar.skin,
}
}
+158
View File
@@ -0,0 +1,158 @@
//! 两条登录流的面板态(微软设备码/授权码 + 第三方站校验/登录)。
//!
//! 从 `model.rs` 拆出来守 400 行硬线:这些类型是「UI 要画什么」的枚举,
//! 判定逻辑(倒计时 → 已过期、服务发现 → 可用)也在这里,页面与表单只消费结果。
use unlucky_presenter::dto::{DeviceLoginPhase, DeviceLoginView};
/// 微软登录面板要画什么(每态都不同,**不允许只有一个转圈**)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DevicePanel {
/// 没有登录在跑
Hidden,
/// 正在申请设备码
Requesting {
/// 状态文案(presenter 给的,已脱敏)
message: String,
},
/// 设备码等待用户操作
Code {
/// 用户码
code: String,
/// 验证链接
link: String,
/// 剩余秒数
remaining: Option<u64>,
/// 是否已过期
expired: bool,
/// 状态文案
message: String,
},
/// 授权码流:等浏览器回调
Browser {
/// 授权链接(可复制)
link: String,
/// 剩余秒数
remaining: Option<u64>,
/// 是否已过期
expired: bool,
/// 状态文案
message: String,
},
/// 失败(原文已脱敏)
Failed {
/// 失败原因
message: String,
},
/// 成功
Succeeded {
/// 账户名
name: String,
},
}
/// 第三方轨面板的可见状态。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthlibPanel {
/// 没在跑
Idle,
/// 正在校验/登录
Running {
/// 状态文案
message: String,
},
/// 地址校验通过(服务发现拿到服务器名)
Ready {
/// 服务器名
server_name: String,
/// 状态文案
message: String,
},
/// 失败(原文已脱敏)
Failed {
/// 失败原因
message: String,
},
/// 成功
Succeeded {
/// 账户名
name: String,
},
}
/// 微软登录状态 → 面板态(倒计时与「已过期」都在这里定性,UI 只画)。
pub(super) fn device_panel(view: &DeviceLoginView, remaining: Option<u64>) -> DevicePanel {
let expired = remaining == Some(0);
match view.phase {
DeviceLoginPhase::Idle => DevicePanel::Hidden,
DeviceLoginPhase::Requesting => DevicePanel::Requesting {
message: view.message.clone(),
},
DeviceLoginPhase::Waiting => {
if view.user_code.trim().is_empty() {
DevicePanel::Browser {
link: view.verification_uri.clone(),
remaining,
expired,
message: view.message.clone(),
}
} else {
DevicePanel::Code {
code: view.user_code.clone(),
link: view.qr_link.clone(),
remaining,
expired,
message: view.message.clone(),
}
}
}
DeviceLoginPhase::Failed => DevicePanel::Failed {
message: view.message.clone(),
},
DeviceLoginPhase::Succeeded => DevicePanel::Succeeded {
name: view.account_name.clone(),
},
}
}
/// 第三方轨状态 → 面板态(顺带取出「校验通过的服务器名」)。
pub(super) fn authlib_panel(
view: &unlucky_presenter::dto::AuthlibLoginView,
) -> (AuthlibPanel, String) {
match view.phase {
DeviceLoginPhase::Idle => (AuthlibPanel::Idle, String::new()),
DeviceLoginPhase::Requesting => (
AuthlibPanel::Running {
message: view.message.clone(),
},
String::new(),
),
DeviceLoginPhase::Waiting => (
AuthlibPanel::Ready {
server_name: view.server_name.clone(),
message: view.message.clone(),
},
view.server_name.clone(),
),
DeviceLoginPhase::Succeeded => (
AuthlibPanel::Succeeded {
name: view.account_name.clone(),
},
view.server_name.clone(),
),
DeviceLoginPhase::Failed => (
AuthlibPanel::Failed {
message: view.message.clone(),
},
String::new(),
),
}
}
impl AuthlibPanel {
/// 是否正在跑(此时表单字段禁用,避免改了一半的地址被提交)。
#[must_use]
pub fn busy(&self) -> bool {
matches!(self, Self::Running { .. })
}
}
+233
View File
@@ -0,0 +1,233 @@
//! 账户列表:当前账户卡片 + 全部账户行 + 皮肤预览区。
use iced::widget::{column, container, image, row, space};
use iced::{Alignment, ContentFit, Element, Length};
use unlucky_design::color::Role;
use unlucky_design::spacing::Space;
use unlucky_design::typography::TypeRole;
use unlucky_i18n::{Catalog, Key, Lang};
use crate::app::components::buttons::{self, Button};
use crate::pages::frame;
use crate::theme::Ui;
use crate::pages::account::{model::Page as Model, widgets};
use crate::pages::Message as PageMessage;
use super::Message as Account;
/// 当前账户卡片(含皮肤预览区)。
pub fn active_card<'a>(
ui: &'a Ui,
page: &'a Model,
catalog: Catalog,
lang: Lang,
) -> Element<'a, PageMessage> {
let Some(current) = page.active_row() else {
return container(space::vertical()).into();
};
let _ = lang;
let mut actions = row![]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center);
actions = actions.push(buttons::text(
ui,
Button::new(
catalog.text(Key::AccountRelogin),
Account::Relogin.into_page(),
),
));
actions = actions.push(buttons::text(
ui,
Button::new(
catalog.text(Key::AccountRemove),
Account::Remove(current.id.clone()).into_page(),
),
));
let mut name_line = row![
frame::text_role(
ui,
TypeRole::TitleMedium,
true,
&current.name,
ui.color(Role::OnSurface),
),
widgets::badge(ui, &current.kind_label, false),
]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center);
if current.active {
name_line = name_line.push(widgets::badge(
ui,
catalog.text(Key::AccountActiveChip),
true,
));
}
let identity = column![
name_line,
frame::text_role(
ui,
TypeRole::BodySmall,
false,
&current.added,
ui.color(Role::OnSurfaceVariant),
),
]
.spacing(ui.space(Space::X1));
let left = row![
widgets::avatar(ui, current, widgets::AVATAR_ACTIVE),
container(identity).width(Length::Fill),
actions,
]
.spacing(ui.space(Space::X4))
.align_y(Alignment::Center);
let mut body = column![
widgets::section(ui, catalog.text(Key::AccountCurrentTitle), None),
left,
]
.spacing(ui.space(Space::X4));
if let Some(skin) = page.active_skin() {
body = body.push(skin_preview(ui, skin.clone(), catalog));
}
frame::card(ui, body)
}
/// 皮肤预览区:**原图直出**(64×64),旁边一句话说清「皮肤从哪来」。
fn skin_preview<'a>(
ui: &'a Ui,
skin: iced::widget::image::Handle,
catalog: Catalog,
) -> Element<'a, PageMessage> {
let size = ui.space(Space::X8) * 2.0;
row![
container(
image(skin)
.width(Length::Fixed(size))
.height(Length::Fixed(size))
.content_fit(ContentFit::Contain),
)
.width(Length::Fixed(size))
.height(Length::Fixed(size)),
column![
frame::text_role(
ui,
TypeRole::LabelMedium,
true,
catalog.text(Key::AccountSkinTitle),
ui.color(Role::OnSurface),
),
frame::text_role(
ui,
TypeRole::BodySmall,
false,
catalog.text(Key::AccountSkinHint),
ui.color(Role::OnSurfaceVariant),
),
]
.spacing(ui.space(Space::X1)),
]
.spacing(ui.space(Space::X4))
.align_y(Alignment::Center)
.into()
}
/// 「全部账户」列表。
pub fn list<'a>(
ui: &'a Ui,
page: &'a Model,
catalog: Catalog,
lang: Lang,
) -> Element<'a, PageMessage> {
let _ = lang;
let mut items = column![widgets::section(
ui,
catalog.text(Key::AccountListTitle),
None
)]
.spacing(ui.space(Space::X3));
for row in &page.rows {
items = items.push(item(ui, row, catalog));
}
frame::card(ui, items)
}
/// 一行账户。
fn item<'a>(
ui: &'a Ui,
row: &'a crate::pages::account::model::Row,
catalog: Catalog,
) -> Element<'a, PageMessage> {
let mut detail = column![
frame::text_role(
ui,
TypeRole::LabelMedium,
false,
&row.name,
ui.color(Role::OnSurface),
),
frame::text_role(
ui,
TypeRole::BodySmall,
false,
&row.added,
ui.color(Role::OnSurfaceVariant),
),
]
.spacing(ui.space(Space::X1));
if !row.detail.is_empty() {
detail = detail.push(frame::text_role(
ui,
TypeRole::BodySmall,
false,
&row.detail,
ui.color(Role::OnSurfaceVariant),
));
}
let mut trailing = row![widgets::badge(ui, &row.kind_label, false),]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center);
if row.active {
trailing = trailing.push(widgets::badge(
ui,
catalog.text(Key::AccountActiveChip),
true,
));
} else {
trailing = trailing.push(buttons::text(
ui,
Button::new(
catalog.text(Key::AccountSwitch),
Account::Switch(row.id.clone()).into_page(),
),
));
}
trailing = trailing.push(buttons::text(
ui,
Button::new(
catalog.text(Key::AccountRemove),
Account::Remove(row.id.clone()).into_page(),
),
));
row![
widgets::avatar(ui, row, widgets::AVATAR_LIST),
container(detail).width(Length::Fill),
trailing,
]
.spacing(ui.space(Space::X3))
.align_y(Alignment::Center)
.padding(iced::Padding::from([0.0, ui.space(Space::X2)]))
.into()
}
+322
View File
@@ -0,0 +1,322 @@
//! 账户页视图模型的判据(M114 的核心断言都在这里)。
//!
//! | 用例 | 抓得住什么 |
//! |---|---|
//! | `a_jwt_injected_into_events_never_reaches_the_page` | **凭据红线**:DTO → 状态 → 视图模型这一路漏了脱敏 |
//! | `an_empty_account_list_offers_all_three_tracks` | 空态变成白页(没有入口) |
//! | `the_device_code_panel_shows_a_countdown_and_expires` | 设备码「只转圈」(倒计时/过期不可见) |
//! | `a_third_party_account_falls_back_to_the_monogram` | 没有皮肤却画白块 / 拿假皮肤充数 |
//! | `the_offline_track_keeps_the_agreed_wording` | 离线档案的说明被改写成「兼容旧启动器」那套 |
use unlucky_i18n::{Key, Lang};
use unlucky_presenter::dto::{
AccountKind, AccountView, AppEvent, AuthlibLoginView, CoreEvent, DeviceLoginPhase,
DeviceLoginView, SkinImage,
};
use unlucky_presenter::state::AppState;
use super::avatar::Cache;
use super::model::{AuthlibPanel, DevicePanel, Form, Page, Panel, Track};
fn account(name: &str, kind: AccountKind, active: bool) -> AccountView {
AccountView {
id: format!("account:{name}"),
name: name.to_string(),
kind,
profile_id: "0f8f1d3c4b5a69788796a5b4c3d2e1f0".to_string(),
login_name: String::new(),
created: "2026-10-31 20:12".to_string(),
active,
server_url: String::new(),
skin: None,
}
}
fn build(state: &AppState, form: &Form) -> Page {
Page::build(state, form, &mut Cache::default(), Lang::ZhCn, 1180.0)
}
/// 把视图模型里**所有会上屏的文本**拼起来(凭据红线就是在这坨里查)。
fn visible_text(page: &Page) -> String {
let mut out = String::new();
for row in &page.rows {
out.push_str(&row.name);
out.push_str(&row.monogram);
out.push_str(&row.kind_label);
out.push_str(&row.added);
out.push_str(&row.detail);
}
out.push_str(&page.form.server);
out.push_str(&page.form.login);
out.push_str(&page.form.offline_name);
out.push_str(&page.checked_server);
match &page.device {
DevicePanel::Hidden => {}
DevicePanel::Requesting { message } => out.push_str(message),
DevicePanel::Code {
code,
link,
message,
..
} => {
out.push_str(code);
out.push_str(link);
out.push_str(message);
}
DevicePanel::Browser { link, message, .. } => {
out.push_str(link);
out.push_str(message);
}
DevicePanel::Failed { message } => out.push_str(message),
DevicePanel::Succeeded { name } => out.push_str(name),
}
match &page.authlib {
AuthlibPanel::Idle => {}
AuthlibPanel::Running { message } => out.push_str(message),
AuthlibPanel::Ready {
server_name,
message,
} => {
out.push_str(server_name);
out.push_str(message);
}
AuthlibPanel::Failed { message } => out.push_str(message),
AuthlibPanel::Succeeded { name } => out.push_str(name),
}
out
}
const JWT: &str =
"eyJhbGciOiJSUzI1NiIsIng1dCI6IkFCQyJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlLXZhbHVl";
/// **凭据红线(审核项)**:把 JWT 形状串注入事件 → 视图模型里不许出现。
///
/// 抓得住:presenter 状态层的脱敏被删(`AppState::apply_device_login` / `apply_authlib_login`),
/// 或页面把 DTO 的错误原文直接搬上屏。
/// 抓不住:某个将来新增的**独立**字段绕过 `message` 通道(那需要另加断言)。
#[test]
fn a_jwt_injected_into_events_never_reaches_the_page() {
let mut state = AppState::new();
state.accounts = vec![account("Steve", AccountKind::Microsoft, true)];
// **绕过构造器**直接摆一个带 JWT 的 DTO:模拟「将来某个新构造器忘了脱敏」/「后端把原文塞进来」。
// 用 `DeviceLoginView::failed(..)` 构造是测不到状态层脱敏的(构造器自己就脱过了)。
state.apply(AppEvent::Core(CoreEvent::DeviceLoginChanged(
DeviceLoginView {
phase: DeviceLoginPhase::Failed,
message: format!("微软返回错误:accessToken={JWT} refresh_token={JWT}"),
..DeviceLoginView::new()
},
)));
state.apply(AppEvent::Core(CoreEvent::AuthlibLoginChanged(
AuthlibLoginView {
phase: DeviceLoginPhase::Failed,
server: "https://littleskin.cn/api/yggdrasil/".to_string(),
server_name: String::new(),
message: format!("服务器回包异常 {JWT}"),
account_name: String::new(),
},
)));
let page = build(&state, &Form::new());
let text = visible_text(&page);
assert!(!text.contains("eyJ"), "视图模型里出现了 JWT:{text}");
assert!(!text.to_lowercase().contains("refreshtoken"), "{text}");
assert!(
text.contains("⟪redacted⟫"),
"错误文案要被标成已脱敏:{text}"
);
}
/// 空态:**三条轨道都有入口**,不是一张白页。
#[test]
fn an_empty_account_list_offers_all_three_tracks() {
let state = AppState::new();
let page = build(&state, &Form::new());
assert!(page.is_empty());
assert_eq!(page.panel, Panel::None);
assert!(page.active_row().is_none());
assert_eq!(Track::ALL.len(), 3);
// 三条轨道的文案 key 各不相同(不是三张一样的卡)
let mut keys: Vec<&str> = Track::ALL
.iter()
.map(|track| track.title_key().name())
.collect();
keys.sort_unstable();
keys.dedup();
assert_eq!(keys.len(), 3);
}
/// 设备码:**倒计时可见**,过期后是「已过期」而不是继续转圈。
#[test]
fn the_device_code_panel_shows_a_countdown_and_expires() {
let mut state = AppState::new();
state.apply(AppEvent::Core(CoreEvent::DeviceLoginChanged(
DeviceLoginView::waiting("ABCD-EFGH", "https://www.microsoft.com/link", 900, ""),
)));
let page = build(&state, &Form::new());
match &page.device {
DevicePanel::Code {
code,
remaining,
expired,
..
} => {
assert_eq!(code, "ABCD-EFGH");
assert!(remaining.is_some_and(|secs| secs > 0));
assert!(!expired);
}
other => panic!("等待态应该是设备码面板,实际 {other:?}"),
}
// 起点往前挪 20 分钟 ⇒ 过期
state.device_login_started =
Some(std::time::Instant::now() - std::time::Duration::from_secs(1_200));
let page = build(&state, &Form::new());
match &page.device {
DevicePanel::Code {
remaining, expired, ..
} => {
assert_eq!(*remaining, Some(0));
assert!(*expired, "过期必须被标出来(面板要画「已过期,重试」)");
}
other => panic!("过期态仍是设备码面板,实际 {other:?}"),
}
// 授权码流也走同一条倒计时(没有用户码时是 Browser 面板)
state.apply(AppEvent::Core(CoreEvent::DeviceLoginChanged(
DeviceLoginView::browser_waiting("https://login.microsoftonline.com/x", 300, None),
)));
let page = build(&state, &Form::new());
assert!(matches!(page.device, DevicePanel::Browser { .. }));
}
/// 没有皮肤 = 首字母块(不是白块、不是假皮肤);坏图也必须回落。
#[test]
fn a_third_party_account_falls_back_to_the_monogram() {
let mut state = AppState::new();
state.accounts = vec![
account("Alex", AccountKind::Authlib, true),
account("Steve", AccountKind::Microsoft, false),
];
let page = build(&state, &Form::new());
assert!(
page.rows.iter().all(|row| row.head.is_none()),
"没有皮肤就不许有图"
);
assert!(page.rows.iter().all(|row| !row.monogram.is_empty()));
assert!(page.active_skin().is_none(), "皮肤预览区没有图就不画");
// 塞一张坏图:解码失败 → 仍然回落到首字母块(不 panic、不白块)
state.accounts[0].skin = Some(SkinImage {
png: b"not a png".to_vec(),
source: "test".to_string(),
});
let page = build(&state, &Form::new());
assert!(page.rows[0].head.is_none());
// 离线档案永远没有皮肤:即使被塞了假数据,UI 侧也只认 DTO 的 `kind`
state.accounts[1].skin = None;
state.accounts[1].kind = AccountKind::Offline;
let page = build(&state, &Form::new());
assert!(page.rows[1].head.is_none());
}
/// 离线档案的说明**必须**带「无法连接启用正版验证的服务器」这条限定(中英都要)。
#[test]
fn the_offline_track_keeps_the_agreed_wording() {
for lang in Lang::ALL {
let catalog = lang.catalog();
for key in [Key::AccountTrackOfflineBody, Key::AccountOfflineWarning] {
let text = catalog.text(key);
assert!(
text.contains("cannot join servers that require a genuine Minecraft account")
|| text.contains("无法连接启用正版验证的服务器"),
"{} 的 {key:?} 丢了「仅本地/隔离网络测试用」口径:{text}",
lang.tag()
);
assert!(
!text.contains("migration") && !text.contains("迁移"),
"不许改写成「兼容旧启动器迁移」:{text}"
);
}
}
}
/// 三条轨道在列表里**文案互不相同**(每一行都贴自己的轨道徽标)。
#[test]
fn every_track_has_its_own_badge() {
let mut state = AppState::new();
state.accounts = vec![
account("a", AccountKind::Microsoft, true),
account("b", AccountKind::Authlib, false),
account("c", AccountKind::Offline, false),
];
let page = build(&state, &Form::new());
let labels: Vec<&str> = page
.rows
.iter()
.map(|row| row.kind_label.as_str())
.collect();
assert_eq!(labels.len(), 3);
assert_ne!(labels[0], labels[1]);
assert_ne!(labels[1], labels[2]);
assert!(
labels.iter().all(|label| !label.is_empty()),
"轨道徽标不能空"
);
}
/// 表单状态:三条轨道各开各的,密码关面板即清。
#[test]
fn the_form_tracks_are_independent() {
let mut form = Form::new();
form.open(Track::Offline);
assert_eq!(form.panel, Panel::Offline);
assert!(!form.offline_ready(), "空名字不能提交");
form.offline_name = "Alex".to_string();
assert!(form.offline_ready());
form.open(Track::Authlib);
assert_eq!(form.panel, Panel::Authlib);
assert!(!form.authlib_ready(), "地址/登录名/密码缺一不可");
form.server = "https://littleskin.cn/api/yggdrasil/".to_string();
form.login = "alex".to_string();
form.password = "hunter2".to_string();
assert!(form.authlib_ready());
form.clear_secret();
assert!(form.password.is_empty());
assert!(!form.authlib_ready());
}
/// 登录阶段的可判据性:Requesting / Waiting / Failed 各自映射到不同面板。
#[test]
fn login_phases_map_to_distinct_panels() {
let mut state = AppState::new();
state.apply(AppEvent::Core(CoreEvent::DeviceLoginChanged(
DeviceLoginView {
phase: DeviceLoginPhase::Requesting,
message: "正在向微软申请设备码…".to_string(),
..DeviceLoginView::new()
},
)));
assert!(matches!(
build(&state, &Form::new()).device,
DevicePanel::Requesting { .. }
));
state.apply(AppEvent::Core(CoreEvent::DeviceLoginChanged(
DeviceLoginView::failed("HTTP 403"),
)));
assert!(matches!(
build(&state, &Form::new()).device,
DevicePanel::Failed { .. }
));
state.apply(AppEvent::Core(CoreEvent::DeviceLoginChanged(
DeviceLoginView::new(),
)));
assert!(matches!(
build(&state, &Form::new()).device,
DevicePanel::Hidden
));
}
@@ -0,0 +1,189 @@
//! 本页小件:头像块(首字母块 / 真图)、章节标题、轨道徽标。
//!
//! ## 令牌纪律
//!
//! 本文件**零**色值 / 字号 / 半径字面量:颜色一律 [`Ui::color`],尺寸走 `Space` /
//! `LayoutMetrics` / `ui.style(..)`。首字母块的「色号」也只是**挑哪一个角色**,
//! 不是一个具体颜色——深浅两套主题各自成立。
use iced::widget::text::LineHeight;
use iced::widget::{container, image, row, text};
use iced::{Alignment, Background, Border, ContentFit, Element, Length, Pixels};
use unlucky_design::color::Role;
use unlucky_design::shape::ShapeScale;
use unlucky_design::spacing::Space;
use unlucky_design::typography::TypeRole;
use crate::pages::frame;
use crate::theme::Ui;
use super::super::Message;
use super::model::Row;
/// 头像块的可选尺寸(列表 40 / 当前账户 56)。
pub const AVATAR_LIST: f32 = 40.0;
/// 当前账户卡片上的头像边长。
pub const AVATAR_ACTIVE: f32 = 56.0;
/// 色号 → (底色, 字色) 角色对。
///
/// 只有「挑角色」这一步是硬的:六个色号对应六个容器角色,深浅主题各有一套值,
/// 所以同一个账户在两种主题下都成立,也不会撞出低对比。
fn tone(ui: &Ui, tone: u8) -> (iced::Color, iced::Color) {
match tone % 6 {
0 => (
ui.color(Role::PrimaryContainer),
ui.color(Role::OnPrimaryContainer),
),
1 => (
ui.color(Role::SecondaryContainer),
ui.color(Role::OnSecondaryContainer),
),
2 => (
ui.color(Role::TertiaryContainer),
ui.color(Role::OnTertiaryContainer),
),
3 => (
ui.color(Role::SurfaceContainerHighest),
ui.color(Role::OnSurface),
),
4 => (ui.color(Role::PrimaryFixed), ui.color(Role::OnPrimaryFixed)),
_ => (
ui.color(Role::SurfaceVariant),
ui.color(Role::OnSurfaceVariant),
),
}
}
/// 头像块:有真图就画图(圆角裁切),没有就画**首字母块**。
///
/// 三条铁律:① 图解码失败一定回到首字母块(不白块);② 首字母块的字来自 `AccountView::monogram`,
/// 永不空串;③ 两者尺寸完全一致,切换时不跳版。
pub fn avatar<'a>(ui: &'a Ui, row: &Row, size: f32) -> Element<'a, Message> {
if let Some(handle) = &row.head {
return container(
image(handle.clone())
.width(Length::Fixed(size))
.height(Length::Fixed(size))
.content_fit(ContentFit::Cover),
)
.width(Length::Fixed(size))
.height(Length::Fixed(size))
.style(move |_theme| container::Style {
border: Border {
radius: ui.radius(ShapeScale::Full, size),
..Border::default()
},
..container::Style::default()
})
.into();
}
monogram(ui, &row.monogram, row.tone, size)
}
/// 首字母块(没有皮肤时的头像位)。
pub fn monogram<'a>(ui: &'a Ui, letter: &str, tone_index: u8, size: f32) -> Element<'a, Message> {
let (background, foreground) = tone(ui, tone_index);
let style = ui.emphasized(TypeRole::TitleMedium);
container(
text(letter.to_string())
.size(style.size_px)
.line_height(LineHeight::Absolute(Pixels(style.line_height_px)))
.font(ui.font_of(style))
.color(foreground),
)
.width(Length::Fixed(size))
.height(Length::Fixed(size))
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.style(move |_theme| container::Style {
background: Some(Background::Color(background)),
border: Border {
radius: ui.radius(ShapeScale::Full, size),
..Border::default()
},
..container::Style::default()
})
.into()
}
/// 章节标题(`TitleMedium` + 可选副文案)。
pub fn section<'a>(ui: &'a Ui, title: &'a str, support: Option<&'a str>) -> Element<'a, Message> {
let mut column = iced::widget::column![frame::text_role(
ui,
TypeRole::TitleMedium,
true,
title,
ui.color(Role::OnSurface),
)]
.spacing(ui.space(Space::X1));
if let Some(support) = support {
column = column.push(frame::text_role(
ui,
TypeRole::BodySmall,
false,
support,
ui.color(Role::OnSurfaceVariant),
));
}
column.into()
}
/// 轨道徽标(小药丸:`LabelMedium` + `SecondaryContainer`)。
pub fn badge<'a>(ui: &'a Ui, label: &'a str, active: bool) -> Element<'a, Message> {
let (background, foreground) = if active {
(
ui.color(Role::SecondaryContainer),
ui.color(Role::OnSecondaryContainer),
)
} else {
(
ui.color(Role::SurfaceContainerHighest),
ui.color(Role::OnSurfaceVariant),
)
};
let style = ui.style(TypeRole::LabelMedium);
container(
text(label.to_string())
.size(style.size_px)
.line_height(LineHeight::Absolute(Pixels(style.line_height_px)))
.font(ui.font_of(style))
.color(foreground),
)
.padding(iced::Padding::from([0.0, ui.space(Space::X2)]))
.height(ui.metrics().control_height - ui.space(Space::X2) * 2.0)
.align_y(Alignment::Center)
.style(move |_theme| container::Style {
background: Some(Background::Color(background)),
border: Border {
radius: ui.radius(ShapeScale::Full, ui.metrics().control_height),
..Border::default()
},
..container::Style::default()
})
.into()
}
/// 一条「标签 + 值」的元信息行(列表行副文案之外的结构化信息)。
pub fn meta_line<'a>(ui: &'a Ui, label: &'a str, value: &'a str) -> Element<'a, Message> {
row![
frame::text_role(
ui,
TypeRole::LabelSmall,
false,
label,
ui.color(Role::OnSurfaceVariant),
),
frame::text_role(
ui,
TypeRole::LabelMedium,
false,
value,
ui.color(Role::OnSurface)
),
]
.spacing(ui.space(Space::X2))
.align_y(Alignment::Center)
.into()
}
+4
View File
@@ -91,6 +91,10 @@ pub enum Message {
/// 加一条内容库消息只动 `pages/content/message.rs`,不动本枚举的正文,也不动
/// `app/update/page_messages.rs` 那条不许 `_ =>` 的 match。
Content(content::Message),
/// 账户页消息(**M114**:三轨登录 / 列表动作 / 表单输入;app 层翻成 `AppCommand`)。
///
/// 与 `Settings` 同一种做法:账户页自己的消息枚举在 `pages/account.rs`,这里只加一支入口。
Account(crate::pages::account::Message),
}
/// 页面动作清单(骨架期够用就行;接线时按业务语义重命名/扩充)。
+1
View File
@@ -109,6 +109,7 @@ pub mod harness;
pub mod layout;
pub mod model;
pub mod account;
pub mod content;
mod download;
mod instances;
+3
View File
@@ -69,6 +69,9 @@ impl Screen {
Route::Content => Screen::Content,
Route::Logs => Screen::Logs,
Route::Settings => Screen::Settings,
// 账户页(M114)不是本枚举四页之一:它由 `pages::account` 自己的树画
// (路由在 `app/view.rs` 里先被拦下),harness 的单页矩阵也不含它。
Route::Accounts => return None,
Route::Agent => return None,
})
}
+29 -10
View File
@@ -21,13 +21,14 @@ mod nav;
/// 用 `#[path]` 挂到外壳的命名空间。
///
/// 为什么是 `#[path]` 而不是在 `pages/mod.rs` 加一行 `mod agent;`:`pages/mod.rs` 是四条页面线
/// 共用的声明文件(本 mission 的 scope 没给它),而右栗是**外壳的一部分**(它挂在任何页面右边)。
/// 共用的声明文件(M104 的 scope 没给它),而右栏是**外壳的一部分**(它挂在任何页面右边)。
/// 先例是 `app/mod.rs` 挂 `../components/mod.rs`。物理路径只有一份,逻辑名字有两个用途:
/// 宿主(右栗)归外壳,视图(会话组件)归页面目录。
/// 宿主(右栏)归外壳,视图(会话组件)归页面目录。
#[path = "../pages/agent/mod.rs"]
pub(crate) mod agent;
pub use nav::NavItem;
// M114:轨底账户头像位的状态也归外壳(`NavItem` + `RailAccount` 一起导出)。
pub use nav::{NavItem, RailAccount};
use iced::widget::text::LineHeight;
use iced::widget::{button, column, container, mouse_area, row, space, stack, text};
@@ -47,17 +48,34 @@ use crate::cli::ForcedState;
use crate::icons;
use crate::theme::Ui;
/// 整棵树(**内容槽位版**):外壳画标题栏 / 缩放热区 / 导航轨 / 右栗,中间那块交给调用方。
/// 整棵树(**内容槽位版**):外壳画标题栏 / 缩放热区 / 导航轨 / 右栏,中间那块交给调用方。
///
/// 产品页的唯一入口(M90 r2 / P1-1;M104 起多两样东西:右侧助手栏与拖拽取指针层;
/// M114 起导航轨还会画轨底的账户头像位)。
///
/// 分工写死:
///
/// - 本模块负责:标题栏(拖动面 = **整条 48px 栏里从窗口左缘到第一个 caption** 的 `mouse_area`,
/// 没有单独的 8px 热区;三个 caption 键各 46×48)、东/南两条缩放热区(各 `Space::X1` = 4px)、
/// 导航轨、右栏、根容器底色;
/// - 调用方负责:`content`(页面内容区)。它拿到的可用宽度是 `窗口宽 − rail 88 − 右栏`,
/// 而页面自己的 `layout::frame_metrics` 仍以**中栏可用宽**为输入(M104 的 `content_width`)。
///
/// 面板 α(D36 / M93)不从这里传:它是**表面色**的属性,唯一施加点是 `Ui::layer`
/// (`crate::theme`)。外壳的根容器 / 标题栏 / 导航轨都走 `ui.layer(..)`,因此自动同源。
///
/// 产品页入口:**内容槽位 + 背景层 + 右栏 + 拖拽层 + 轨底账户头像位**。
///
/// `background` 由 `pages::appearance::layer` 产出(已与 `Message::Page` 映射过);垫在 `stack!`
/// 最底层,于是「面板 α < 1」时能真的看见它——这就是 D34 在像素上的落点。
// 9 个形参:M104 的 `right`/`overlay` 之后 M106 又加了 `lang`(导航轨标签要按语言取词)。
// 拆成结构体要动 `app/view.rs` 的两处调用点,而那正是 M104/M105 反复设锚点的地方——
// 等 M105 那轮 rebase(`draft` 与 `lang` 两个形参都要留)时一并结构体化,先就地 `allow`。
// 10 个形参:M104 的 `right`/`overlay`、M106 的 `lang`(导航轨标签按语言取词)、
// M114 的 `account`(轨底账户头像位状态)。拆成结构体要动 `app/view.rs` / `account_page.rs`
// 的调用点,而那正是 M104/M105/M109 反复设锚点的地方——先就地 `allow`,等下次合流再结构体化。
#[allow(clippy::too_many_arguments)]
pub fn view_with_background<'a>(
ui: &'a Ui,
selected: NavItem,
account: &nav::RailAccount,
app_title: &'a str,
background: Option<Element<'a, Message>>,
content: Element<'a, Message>,
@@ -66,10 +84,11 @@ pub fn view_with_background<'a>(
forced: Option<ForcedState>,
lang: Lang,
) -> Element<'a, Message> {
// 右栗(M104)是 `row` 的**第三个兄弟**而不是叠层:它是布局宽度的一部分,压在上面会让
// 中栗以为自己还有那么宽(那就是任务里禁止的「溢出」)。它的宽度由 `agent::docked` 自己声明。
// 右栏(M104)是 `row` 的**第三个兄弟**而不是叠层:它是布局宽度的一部分,压在上面会让
// 中栏以为自己还有那么宽(那就是任务里禁止的「溢出」)。它的宽度由 `agent::docked` 自己声明。
// M106:导航轨标签按当前界面语言取词(`lang` 一路从 `App::lang()` 递进来)。
let mut work = row![nav::rail(ui, selected, forced, lang), content]
// M114:`account` 只影响轨底那一格,`right`/`overlay` 的语义一字未动。
let mut work = row![nav::rail(ui, selected, account, forced, lang), content]
.width(Length::Fill)
.height(Length::Fill);
if let Some(right) = right {
+51 -19
View File
@@ -23,6 +23,12 @@ use unlucky_design::spacing::{LayoutMetrics, Space};
use unlucky_design::typography::TypeRole;
use unlucky_i18n::{Key, Lang};
mod account;
pub use account::RailAccount;
use account::account_item;
use crate::app::Message;
use crate::cli::ForcedState;
use crate::icons;
@@ -42,10 +48,12 @@ pub enum NavItem {
Settings,
/// AI 助手。
Ai,
/// 账户页(**不进主序列**:入口是轨底的头像位,见 [`RailAccount`])。
Account,
}
impl NavItem {
/// 全部占位项(顺序 = 导航栏自上而下)。
/// 全部**主序列**项(顺序 = 导航栏自上而下)。账户不在其中:它固定贴在轨底。
pub const ALL: [NavItem; 5] = [
NavItem::Instances,
NavItem::Download,
@@ -62,6 +70,8 @@ impl NavItem {
NavItem::Logs => Key::NavLogs,
NavItem::Settings => Key::NavSettings,
NavItem::Ai => Key::NavAi,
// M114:轨底头像位的可访问名(不在主序列里,但 `router` 的 `nav()` 会问到它)。
NavItem::Account => Key::AccountTitle,
}
}
@@ -81,6 +91,7 @@ impl NavItem {
NavItem::Logs => IconKind::Logs,
NavItem::Settings => IconKind::Settings,
NavItem::Ai => IconKind::Ai,
NavItem::Account => IconKind::User,
}
}
}
@@ -89,27 +100,41 @@ impl NavItem {
pub(super) fn rail<'a>(
ui: &'a Ui,
selected: NavItem,
account: &RailAccount,
forced: Option<ForcedState>,
lang: Lang,
) -> Element<'a, Message> {
let metrics = ui.metrics();
let indicator = indicator_size(metrics);
let compact = account.compact;
let items = NavItem::ALL
.iter()
.map(|item| rail_item(ui, *item, *item == selected, indicator, forced, lang))
// `ALL` 本来就不含 `Account`(它固定在轨底),filter 只是把这条意图写明。
.filter(|item| **item != NavItem::Account)
.map(|item| rail_item(ui, *item, *item == selected, indicator, compact, forced, lang))
.collect::<Vec<_>>();
// 轨顶留白走 container padding,而不是「先塞一个 spacer 元素」:后者会被 column 的
// spacing(4)再加一档,实测变 28(视觉复审 P3-5)。
//
// 轨底色与其它面板同源(M93):`ui.layer` 已含面板 α,导航轨是面板层的一部分。
container(column(items).spacing(metrics.nav_item_gap))
.width(nav_rail_width(metrics))
.height(Length::Fill)
.padding(Padding::from([ui.space(Space::X6), 0.0]))
.style(move |_theme| filled(ui.layer(MaterialLayer::Canvas)))
.into()
//
// 账户头像位**固定贴在轨底**(M114):主序列四项在上,中间一段 Fill 把头像顶到底部——
// 于是「账户」不是第 6 个导航项,轨的长度也不会随页数增长。
container(
column![
column(items).spacing(metrics.nav_item_gap),
iced::widget::space::vertical(),
account_item(ui, selected, account, indicator, forced),
]
.height(Length::Fill),
)
.width(nav_rail_width(metrics))
.height(Length::Fill)
.padding(Padding::from([ui.space(Space::X6), 0.0]))
.style(move |_theme| filled(ui.layer(MaterialLayer::Canvas)))
.into()
}
fn rail_item<'a>(
@@ -117,6 +142,7 @@ fn rail_item<'a>(
item: NavItem,
selected: bool,
indicator: (f32, f32),
compact: bool,
forced: Option<ForcedState>,
lang: Lang,
) -> Element<'a, Message> {
@@ -152,26 +178,32 @@ fn rail_item<'a>(
});
let item_height = nav_item_height(ui, indicator_height);
let height = if compact {
indicator_height
} else {
item_height
};
// 列必须显式占满轨宽,否则它会 shrink 到 56,`align_x(Center)` 就变成空操作,
// 药丸会贴左缘(x=0..55 而不是 16..71)——r1 实测踩到的第二个坑。
let stack = column![
pill,
label(
let mut stack = column![pill]
.width(nav_rail_width(ui.metrics()))
.align_x(Alignment::Center)
.height(height);
if !compact {
// M114 的「窄高收成图标条」+ M106 的「按语言取词」并存。
stack = stack.push(label(
ui,
TypeRole::LabelMedium,
false,
item.label(lang),
label_color
),
]
.spacing(ui.space(Space::X1))
.width(nav_rail_width(ui.metrics()))
.align_x(Alignment::Center)
.height(item_height);
label_color,
));
}
stack = stack.spacing(ui.space(Space::X1));
button(stack)
.width(nav_rail_width(ui.metrics()))
.height(item_height)
.height(height)
.padding(0)
.style(move |_theme: &IcedTheme, status| {
let background = match overridden(forced, status) {
+220
View File
@@ -0,0 +1,220 @@
//! 导航轨**底部账户头像位**(M114):状态结构体 + 那个按钮。
//!
//! 为什么单独一个文件:`shell/nav.rs` 贴着 400 行硬线,而这块是 M114 新增的一整块
//! (未登录/已登录两态、窄高收成图标条的判据、点击跳账户页)。
use iced::widget::{button, column, container, text};
use iced::{Alignment, Background, Border, Element, Length, Shadow, Theme as IcedTheme};
use unlucky_design::color::{Role, StateLayer};
use unlucky_design::icons::IconKind;
use unlucky_design::shape::ShapeScale;
use unlucky_design::spacing::Space;
use unlucky_design::typography::TypeRole;
use crate::app::Message;
use crate::cli::ForcedState;
use crate::icons;
use crate::shell::overridden;
use crate::theme::Ui;
use super::{nav_item_height, nav_rail_width, NavItem};
/// 导航轨底部的**账户头像位**状态(M114)。
///
/// 为什么单独传而不是塞进 `NavItem`:它不是主序列里的第 6 项(那会让轨道越堆越长),
/// 而是固定在**底部**的一个头像位;未登录/已登录两态要在**形状上**就不同(描边剪影 vs 首字母块)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RailAccount {
/// 是否已登录(至少有一个账户)
pub signed_in: bool,
/// 首字母块的字(已登录时有意义)
pub initial: String,
/// 账户名(已登录时作为标签;未登录时是 i18n 的「未登录」)
pub label: String,
/// 窄高度/窄宽下的图标条形态(隐藏文字标签,只留头像位)
pub compact: bool,
}
impl RailAccount {
/// 未登录态。
pub fn signed_out(label: impl Into<String>) -> Self {
Self {
signed_in: false,
initial: String::new(),
label: label.into(),
compact: false,
}
}
/// 已登录态。
pub fn signed_in(initial: impl Into<String>, label: impl Into<String>) -> Self {
Self {
signed_in: true,
initial: initial.into(),
label: label.into(),
compact: false,
}
}
/// 图标条形态(导航项太多/太窄时收起文字标签)。
#[must_use]
pub fn compact(mut self, compact: bool) -> Self {
self.compact = compact;
self
}
}
/// 轨底的账户头像位:未登录 = 描边剪影,已登录 = 首字母块(两态在**形状**上就不同)。
pub(super) fn account_item<'a>(
ui: &'a Ui,
selected: NavItem,
account: &RailAccount,
indicator: (f32, f32),
forced: Option<ForcedState>,
) -> Element<'a, Message> {
let (indicator_width, indicator_height) = indicator;
let active = selected == NavItem::Account;
let label_color = if active {
ui.color(Role::Secondary)
} else {
ui.color(Role::OnSurfaceVariant)
};
let avatar: Element<'a, Message> = if account.signed_in {
let style = ui.emphasized(TypeRole::TitleMedium);
container(
text(account.initial.clone())
.size(style.size_px)
.line_height(iced::widget::text::LineHeight::Absolute(iced::Pixels(
style.line_height_px,
)))
.font(ui.font_of(style))
.color(ui.color(Role::OnSecondaryContainer)),
)
.width(Length::Fixed(avatar_size(ui, indicator_width)))
.height(Length::Fixed(avatar_size(ui, indicator_width)))
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.style(move |_theme| container::Style {
background: Some(Background::Color(ui.color(Role::SecondaryContainer))),
border: Border {
radius: ui.radius(ShapeScale::Full, avatar_size(ui, indicator_width)),
..Border::default()
},
..container::Style::default()
})
.into()
} else {
container(icons::view::<Message>(
IconKind::User,
ui.color(Role::OnSurfaceVariant),
))
.width(Length::Fixed(avatar_size(ui, indicator_width)))
.height(Length::Fixed(avatar_size(ui, indicator_width)))
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.style(move |_theme| container::Style {
border: Border {
color: ui.color(Role::Outline),
width: 1.0,
radius: ui.radius(ShapeScale::Full, avatar_size(ui, indicator_width)),
},
..container::Style::default()
})
.into()
};
let height = nav_item_height(ui, indicator_height);
let mut stack = column![avatar]
.spacing(ui.space(Space::X1))
.width(nav_rail_width(ui.metrics()))
.align_x(Alignment::Center);
if !account.compact {
// 用**拥有的**字符串画标签:`RailAccount` 是调用方临时算出来的状态,
// 借它的 `&str` 会让整棵树跟着那个临时值一起活(E0515)。
let style = ui.style(TypeRole::LabelSmall);
stack = stack.push(
text(account.label.clone())
.size(style.size_px)
.line_height(iced::widget::text::LineHeight::Absolute(iced::Pixels(
style.line_height_px,
)))
.font(ui.font_of(style))
.color(label_color),
);
}
button(stack)
.width(nav_rail_width(ui.metrics()))
.height(height)
.padding(0)
.style(move |_theme: &IcedTheme, status| button::Style {
background: match overridden(forced, status) {
button::Status::Hovered if !active => Some(Background::Color(ui.state_over(
StateLayer::Hover,
Role::OnSurface,
Role::Surface,
))),
button::Status::Pressed if !active => Some(Background::Color(ui.state_over(
StateLayer::Pressed,
Role::OnSurface,
Role::Surface,
))),
_ => None,
},
text_color: label_color,
border: Border::default(),
shadow: Shadow::default(),
snap: true,
})
.on_press(Message::Select(NavItem::Account))
.into()
}
/// 头像位边长 = 指示器宽 − 16,但不超过 48(12b 里没有这个控件,按令牌栅格取整)。
fn avatar_size(ui: &Ui, indicator_width: f32) -> f32 {
(indicator_width - Space::X4.dp()).min(ui.space(Space::X8) + Space::X2.dp())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_two_states_are_distinguishable() {
let out = RailAccount::signed_out("Not signed in");
assert!(!out.signed_in);
let on = RailAccount::signed_in("S", "Steve");
assert!(on.signed_in);
assert_eq!(on.initial, "S");
let compacted = on.clone().compact(true);
assert!(compacted.compact, "compact(true) 必须收成图标条");
}
#[test]
fn the_avatar_slot_fits_the_rail() {
use unlucky_design::color::SchemeFlavor;
use unlucky_design::typography::Platform;
use crate::theme::Families;
let ui = Ui::with_platform(
SchemeFlavor::Light,
Platform::Windows,
Families {
text: "Segoe UI",
display: "Segoe UI",
mono: "Consolas",
},
);
let width = super::super::indicator_size(ui.metrics()).0;
let size = avatar_size(&ui, width);
assert!(size > 0.0);
assert!(
size <= nav_rail_width(ui.metrics()),
"头像位不能比导航轨还宽({size} > {})",
nav_rail_width(ui.metrics())
);
}
}