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

+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,
})
}