feat: 新增独立管理窗口

This commit is contained in:
JSR
2026-07-10 22:26:07 +08:00
parent 795bae1f03
commit 7971c6adbc
13 changed files with 343 additions and 163 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"identifier": "default", "identifier": "default",
"description": "Default capabilities for SecScore application", "description": "Default capabilities for SecScore application",
"windows": ["main"], "windows": ["main", "management"],
"permissions": [ "permissions": [
"core:default", "core:default",
"core:window:default", "core:window:default",
+1 -1
View File
@@ -1 +1 @@
{"default":{"identifier":"default","description":"Default capabilities for SecScore application","local":true,"windows":["main"],"permissions":["core:default","core:window:default","core:window:allow-show","core:window:allow-hide","core:window:allow-close","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-start-dragging","core:webview:default","core:app:default","core:tray:default","core:tray:allow-new","core:tray:allow-set-icon","core:tray:allow-set-menu","core:menu:default","shell:allow-open"]}} {"default":{"identifier":"default","description":"Default capabilities for SecScore application","local":true,"windows":["main","management"],"permissions":["core:default","core:window:default","core:window:allow-show","core:window:allow-hide","core:window:allow-close","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-start-dragging","core:webview:default","core:app:default","core:tray:default","core:tray:allow-new","core:tray:allow-set-icon","core:tray:allow-set-menu","core:menu:default","shell:allow-open"]}}
+103 -35
View File
@@ -68,14 +68,23 @@ if ($urlProtocol -and $command) {{
let (registered, details) = match output { let (registered, details) = match output {
Ok(o) => { Ok(o) => {
let stdout = String::from_utf8_lossy(&o.stdout).to_string(); let stdout = String::from_utf8_lossy(&o.stdout).to_string();
eprintln!("[URL Protocol] Windows PowerShell check output: {}", stdout.trim()); eprintln!(
"[URL Protocol] Windows PowerShell check output: {}",
stdout.trim()
);
if stdout.contains("REGISTERED") { if stdout.contains("REGISTERED") {
(true, "URL protocol fully registered in Windows Registry".to_string()) (
true,
"URL protocol fully registered in Windows Registry".to_string(),
)
} else if stdout.contains("PARTIAL") { } else if stdout.contains("PARTIAL") {
(false, format!("Partial registration: {}", stdout.trim())) (false, format!("Partial registration: {}", stdout.trim()))
} else { } else {
(false, "Registry key HKCU\\Software\\Classes\\secscore not found".to_string()) (
false,
"Registry key HKCU\\Software\\Classes\\secscore not found".to_string(),
)
} }
} }
Err(e) => { Err(e) => {
@@ -84,7 +93,10 @@ if ($urlProtocol -and $command) {{
} }
}; };
eprintln!("[URL Protocol] Windows check result: registered={}, {}", registered, details); eprintln!(
"[URL Protocol] Windows check result: registered={}, {}",
registered, details
);
Ok(IpcResponse::success(UrlProtocolStatus { Ok(IpcResponse::success(UrlProtocolStatus {
registered, registered,
@@ -113,7 +125,8 @@ if ($urlProtocol -and $command) {{
let stdout = String::from_utf8_lossy(&o.stdout); let stdout = String::from_utf8_lossy(&o.stdout);
if stdout.contains("secscore") { if stdout.contains("secscore") {
registered = true; registered = true;
details = "secscore:// registered via Launch Services (app bundle)".to_string(); details =
"secscore:// registered via Launch Services (app bundle)".to_string();
} else { } else {
details = "secscore:// not found in Launch Services dump".to_string(); details = "secscore:// not found in Launch Services dump".to_string();
} }
@@ -135,7 +148,10 @@ if ($urlProtocol -and $command) {{
} }
} }
eprintln!("[URL Protocol] macOS check result: registered={}, {}", registered, details); eprintln!(
"[URL Protocol] macOS check result: registered={}, {}",
registered, details
);
Ok(IpcResponse::success(UrlProtocolStatus { Ok(IpcResponse::success(UrlProtocolStatus {
registered, registered,
@@ -165,7 +181,8 @@ if ($urlProtocol -and $command) {{
let handler = String::from_utf8_lossy(&o.stdout).trim().to_string(); let handler = String::from_utf8_lossy(&o.stdout).trim().to_string();
if handler == "secscore.desktop" { if handler == "secscore.desktop" {
registered = true; registered = true;
details = "secscore.desktop is default URL scheme handler".to_string(); details = "secscore.desktop is default URL scheme handler"
.to_string();
} else { } else {
registered = true; registered = true;
details = format!( details = format!(
@@ -176,11 +193,15 @@ if ($urlProtocol -and $command) {{
} }
_ => { _ => {
registered = true; registered = true;
details = "Desktop file exists with MimeType (xdg-settings query failed)".to_string(); details =
"Desktop file exists with MimeType (xdg-settings query failed)"
.to_string();
} }
} }
} else { } else {
details = "Desktop file exists but missing x-scheme-handler/secscore MimeType".to_string(); details =
"Desktop file exists but missing x-scheme-handler/secscore MimeType"
.to_string();
} }
} }
Err(e) => { Err(e) => {
@@ -191,7 +212,10 @@ if ($urlProtocol -and $command) {{
details = "secscore.desktop not found in ~/.local/share/applications".to_string(); details = "secscore.desktop not found in ~/.local/share/applications".to_string();
} }
eprintln!("[URL Protocol] Linux check result: registered={}, {}", registered, details); eprintln!(
"[URL Protocol] Linux check result: registered={}, {}",
registered, details
);
Ok(IpcResponse::success(UrlProtocolStatus { Ok(IpcResponse::success(UrlProtocolStatus {
registered, registered,
@@ -244,7 +268,10 @@ if (-not (Test-Path 'HKCU:\Software\Classes\{protocol}')) {{
Ok(o) => { Ok(o) => {
let stdout = String::from_utf8_lossy(&o.stdout); let stdout = String::from_utf8_lossy(&o.stdout);
let ok = o.status.success() && stdout.contains("SUCCESS"); let ok = o.status.success() && stdout.contains("SUCCESS");
eprintln!("[URL Protocol] Windows PowerShell unregister result: {}", ok); eprintln!(
"[URL Protocol] Windows PowerShell unregister result: {}",
ok
);
ok ok
} }
Err(e) => { Err(e) => {
@@ -271,7 +298,10 @@ if (-not (Test-Path 'HKCU:\Software\Classes\{protocol}')) {{
match output { match output {
Ok(o) => { Ok(o) => {
eprintln!("[URL Protocol] macOS lsregister -u result: {}", o.status.success()); eprintln!(
"[URL Protocol] macOS lsregister -u result: {}",
o.status.success()
);
} }
Err(e) => { Err(e) => {
eprintln!("[URL Protocol] macOS lsregister -u error: {}", e); eprintln!("[URL Protocol] macOS lsregister -u error: {}", e);
@@ -310,7 +340,10 @@ if (-not (Test-Path 'HKCU:\Software\Classes\{protocol}')) {{
if desktop_path.exists() { if desktop_path.exists() {
match fs::remove_file(&desktop_path) { match fs::remove_file(&desktop_path) {
Ok(_) => { Ok(_) => {
eprintln!("[URL Protocol] Linux desktop file removed: {:?}", desktop_path); eprintln!(
"[URL Protocol] Linux desktop file removed: {:?}",
desktop_path
);
let apps_dir = home.join(".local/share/applications"); let apps_dir = home.join(".local/share/applications");
let _ = std::process::Command::new("update-desktop-database") let _ = std::process::Command::new("update-desktop-database")
.arg(apps_dir.to_string_lossy().to_string()) .arg(apps_dir.to_string_lossy().to_string())
@@ -397,7 +430,9 @@ pub async fn request_elevation(
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOW; use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOW;
let verb: Vec<u16> = OsStr::new("runas\0").encode_wide().collect(); let verb: Vec<u16> = OsStr::new("runas\0").encode_wide().collect();
let file: Vec<u16> = OsStr::new(&format!("{}\0", exe_str)).encode_wide().collect(); let file: Vec<u16> = OsStr::new(&format!("{}\0", exe_str))
.encode_wide()
.collect();
let params: Vec<u16> = OsStr::new("\0").encode_wide().collect(); let params: Vec<u16> = OsStr::new("\0").encode_wide().collect();
let result = unsafe { let result = unsafe {
@@ -442,7 +477,10 @@ pub async fn request_elevation(
app.exit(0); app.exit(0);
Ok(IpcResponse::success(())) Ok(IpcResponse::success(()))
} }
Ok(s) => Err(format!("Elevation cancelled or failed (exit code: {:?})", s.code())), Ok(s) => Err(format!(
"Elevation cancelled or failed (exit code: {:?})",
s.code()
)),
Err(e) => Err(format!("Failed to request elevation: {}", e)), Err(e) => Err(format!("Failed to request elevation: {}", e)),
} }
} }
@@ -453,16 +491,17 @@ pub async fn request_elevation(
std::env::current_exe().map_err(|e| format!("Failed to get exe path: {}", e))?; std::env::current_exe().map_err(|e| format!("Failed to get exe path: {}", e))?;
let exe_str = exe_path.to_string_lossy().to_string(); let exe_str = exe_path.to_string_lossy().to_string();
let status = std::process::Command::new("pkexec") let status = std::process::Command::new("pkexec").arg(&exe_str).status();
.arg(&exe_str)
.status();
match status { match status {
Ok(s) if s.success() => { Ok(s) if s.success() => {
app.exit(0); app.exit(0);
Ok(IpcResponse::success(())) Ok(IpcResponse::success(()))
} }
Ok(s) => Err(format!("Elevation cancelled or failed (exit code: {:?})", s.code())), Ok(s) => Err(format!(
"Elevation cancelled or failed (exit code: {:?})",
s.code()
)),
Err(e) => Err(format!("Failed to request elevation: {}", e)), Err(e) => Err(format!("Failed to request elevation: {}", e)),
} }
} }
@@ -480,7 +519,10 @@ pub async fn register_url_protocol(
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<IpcResponse<RegisterUrlProtocolResult>, String> { ) -> Result<IpcResponse<RegisterUrlProtocolResult>, String> {
let protocol = "secscore"; let protocol = "secscore";
eprintln!("[URL Protocol] Starting registration for protocol: {}", protocol); eprintln!(
"[URL Protocol] Starting registration for protocol: {}",
protocol
);
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {
@@ -525,7 +567,12 @@ try {{
let stdout = String::from_utf8_lossy(&o.stdout); let stdout = String::from_utf8_lossy(&o.stdout);
let stderr = String::from_utf8_lossy(&o.stderr); let stderr = String::from_utf8_lossy(&o.stderr);
let success = o.status.success() && stdout.contains("SUCCESS"); let success = o.status.success() && stdout.contains("SUCCESS");
eprintln!("[URL Protocol] Windows PowerShell result: success={}, stdout={}, stderr={}", success, stdout.trim(), stderr.trim()); eprintln!(
"[URL Protocol] Windows PowerShell result: success={}, stdout={}, stderr={}",
success,
stdout.trim(),
stderr.trim()
);
if success { if success {
let query_cmd = format!( let query_cmd = format!(
r#"reg query "HKCU\Software\Classes\{}\shell\open\command" /ve"#, r#"reg query "HKCU\Software\Classes\{}\shell\open\command" /ve"#,
@@ -540,7 +587,10 @@ try {{
} }
} }
eprintln!("[URL Protocol] Windows registration verification: {}", registered); eprintln!(
"[URL Protocol] Windows registration verification: {}",
registered
);
let _ = app; let _ = app;
return Ok(IpcResponse::success(RegisterUrlProtocolResult { return Ok(IpcResponse::success(RegisterUrlProtocolResult {
@@ -560,7 +610,10 @@ try {{
let mut registered = false; let mut registered = false;
if let Some(bundle_path) = app_bundle { if let Some(bundle_path) = app_bundle {
eprintln!("[URL Protocol] macOS: Found app bundle at {:?}", bundle_path); eprintln!(
"[URL Protocol] macOS: Found app bundle at {:?}",
bundle_path
);
let output = Command::new( let output = Command::new(
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister", "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
) )
@@ -573,7 +626,10 @@ try {{
registered = true; registered = true;
} }
Ok(o) => { Ok(o) => {
eprintln!("[URL Protocol] macOS: lsregister -f failed (exit: {:?}), trying -R -f", o.status.code()); eprintln!(
"[URL Protocol] macOS: lsregister -f failed (exit: {:?}), trying -R -f",
o.status.code()
);
let _ = Command::new("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister") let _ = Command::new("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister")
.args(["-R", "-f", &bundle_path.to_string_lossy()]) .args(["-R", "-f", &bundle_path.to_string_lossy()])
.output(); .output();
@@ -660,7 +716,10 @@ MimeType=x-scheme-handler/secscore;
match fs::write(&desktop_path, &desktop_content) { match fs::write(&desktop_path, &desktop_content) {
Ok(_) => { Ok(_) => {
eprintln!("[URL Protocol] Linux: Desktop file written to {:?}", desktop_path); eprintln!(
"[URL Protocol] Linux: Desktop file written to {:?}",
desktop_path
);
} }
Err(e) => { Err(e) => {
eprintln!("[URL Protocol] Linux: Desktop file write error: {}", e); eprintln!("[URL Protocol] Linux: Desktop file write error: {}", e);
@@ -674,7 +733,10 @@ MimeType=x-scheme-handler/secscore;
let update_result = std::process::Command::new("update-desktop-database") let update_result = std::process::Command::new("update-desktop-database")
.arg(apps_dir.to_string_lossy().to_string()) .arg(apps_dir.to_string_lossy().to_string())
.status(); .status();
eprintln!("[URL Protocol] Linux: update-desktop-database result: {:?}", update_result); eprintln!(
"[URL Protocol] Linux: update-desktop-database result: {:?}",
update_result
);
let xdg_set_result = std::process::Command::new("xdg-settings") let xdg_set_result = std::process::Command::new("xdg-settings")
.args([ .args([
@@ -684,22 +746,28 @@ MimeType=x-scheme-handler/secscore;
"secscore.desktop", "secscore.desktop",
]) ])
.status(); .status();
eprintln!("[URL Protocol] Linux: xdg-settings set result: {:?}", xdg_set_result); eprintln!(
"[URL Protocol] Linux: xdg-settings set result: {:?}",
xdg_set_result
);
let xdg_mime_result = std::process::Command::new("xdg-mime") let xdg_mime_result = std::process::Command::new("xdg-mime")
.args([ .args(["default", "secscore.desktop", "x-scheme-handler/secscore"])
"default",
"secscore.desktop",
"x-scheme-handler/secscore",
])
.status(); .status();
eprintln!("[URL Protocol] Linux: xdg-mime default result: {:?}", xdg_mime_result); eprintln!(
"[URL Protocol] Linux: xdg-mime default result: {:?}",
xdg_mime_result
);
let verify_exists = desktop_path.exists(); let verify_exists = desktop_path.exists();
let verify_content = fs::read_to_string(&desktop_path).unwrap_or_default(); let verify_content = fs::read_to_string(&desktop_path).unwrap_or_default();
let actually_registered = verify_exists && verify_content.contains("x-scheme-handler/secscore"); let actually_registered =
verify_exists && verify_content.contains("x-scheme-handler/secscore");
eprintln!("[URL Protocol] Linux registration verification: {}", actually_registered); eprintln!(
"[URL Protocol] Linux registration verification: {}",
actually_registered
);
let _ = app; let _ = app;
return Ok(IpcResponse::success(RegisterUrlProtocolResult { return Ok(IpcResponse::success(RegisterUrlProtocolResult {
+23 -21
View File
@@ -417,10 +417,7 @@ fn generate_code_challenge(verifier: &str) -> String {
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
hasher.update(verifier.as_bytes()); hasher.update(verifier.as_bytes());
let result = hasher.finalize(); let result = hasher.finalize();
base64::Engine::encode( base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, &result)
&base64::engine::general_purpose::URL_SAFE_NO_PAD,
&result,
)
} }
#[tauri::command] #[tauri::command]
@@ -472,7 +469,9 @@ pub async fn oauth_exchange_code(
); );
let device_uuid = get_or_create_device_uuid(); let device_uuid = get_or_create_device_uuid();
let ip_address = get_local_ip().await.unwrap_or_else(|_| "127.0.0.1".to_string()); let ip_address = get_local_ip()
.await
.unwrap_or_else(|_| "127.0.0.1".to_string());
let state_guard = state.read(); let state_guard = state.read();
let client = &state_guard.http_client; let client = &state_guard.http_client;
@@ -522,7 +521,10 @@ pub async fn oauth_exchange_code(
} }
} }
println!("[OAuth] Token 处理完成,access_token 长度: {}", token_response.access_token.len()); println!(
"[OAuth] Token 处理完成,access_token 长度: {}",
token_response.access_token.len()
);
Ok(IpcResponse::success(token_response)) Ok(IpcResponse::success(token_response))
} }
@@ -761,7 +763,9 @@ pub async fn oauth_report_online(
state: State<'_, Arc<RwLock<AppState>>>, state: State<'_, Arc<RwLock<AppState>>>,
) -> Result<IpcResponse<OnlineStatusResponse>, String> { ) -> Result<IpcResponse<OnlineStatusResponse>, String> {
let device_uuid = get_or_create_device_uuid(); let device_uuid = get_or_create_device_uuid();
let ip_address = get_local_ip().await.unwrap_or_else(|_| "127.0.0.1".to_string()); let ip_address = get_local_ip()
.await
.unwrap_or_else(|_| "127.0.0.1".to_string());
println!( println!(
"[OAuth] 上报在线状态 - platform_id: {}, device_uuid: {}, device_type: {}", "[OAuth] 上报在线状态 - platform_id: {}, device_uuid: {}, device_type: {}",
@@ -844,11 +848,10 @@ pub async fn oauth_save_login_state(state_data: OAuthState) -> Result<IpcRespons
println!("[OAuth] 保存登录状态 - user_id: {}", state_data.user_id); println!("[OAuth] 保存登录状态 - user_id: {}", state_data.user_id);
let file_path = get_oauth_state_file_path(); let file_path = get_oauth_state_file_path();
let json = serde_json::to_string_pretty(&state_data) let json =
.map_err(|e| format!("序列化失败: {}", e))?; serde_json::to_string_pretty(&state_data).map_err(|e| format!("序列化失败: {}", e))?;
std::fs::write(&file_path, json) std::fs::write(&file_path, json).map_err(|e| format!("写入文件失败: {}", e))?;
.map_err(|e| format!("写入文件失败: {}", e))?;
println!("[OAuth] 登录状态已保存到: {:?}", file_path); println!("[OAuth] 登录状态已保存到: {:?}", file_path);
Ok(IpcResponse::success(())) Ok(IpcResponse::success(()))
@@ -863,11 +866,10 @@ pub async fn oauth_load_login_state() -> Result<IpcResponse<Option<OAuthState>>,
return Ok(IpcResponse::success(None)); return Ok(IpcResponse::success(None));
} }
let json = std::fs::read_to_string(&file_path) let json = std::fs::read_to_string(&file_path).map_err(|e| format!("读取文件失败: {}", e))?;
.map_err(|e| format!("读取文件失败: {}", e))?;
let state: OAuthState = serde_json::from_str(&json) let state: OAuthState =
.map_err(|e| format!("解析 JSON 失败: {}", e))?; serde_json::from_str(&json).map_err(|e| format!("解析 JSON 失败: {}", e))?;
println!("[OAuth] 登录状态已加载 - user_id: {}", state.user_id); println!("[OAuth] 登录状态已加载 - user_id: {}", state.user_id);
Ok(IpcResponse::success(Some(state))) Ok(IpcResponse::success(Some(state)))
@@ -878,8 +880,7 @@ pub async fn oauth_clear_login_state() -> Result<IpcResponse<()>, String> {
let file_path = get_oauth_state_file_path(); let file_path = get_oauth_state_file_path();
if file_path.exists() { if file_path.exists() {
std::fs::remove_file(&file_path) std::fs::remove_file(&file_path).map_err(|e| format!("删除文件失败: {}", e))?;
.map_err(|e| format!("删除文件失败: {}", e))?;
println!("[OAuth] 登录状态已清除"); println!("[OAuth] 登录状态已清除");
} }
@@ -895,7 +896,9 @@ pub async fn oauth_refresh_access_token(
println!("[OAuth] 刷新 access_token"); println!("[OAuth] 刷新 access_token");
let device_uuid = get_or_create_device_uuid(); let device_uuid = get_or_create_device_uuid();
let ip_address = get_local_ip().await.unwrap_or_else(|_| "127.0.0.1".to_string()); let ip_address = get_local_ip()
.await
.unwrap_or_else(|_| "127.0.0.1".to_string());
let state_guard = state.read(); let state_guard = state.read();
let client = &state_guard.http_client; let client = &state_guard.http_client;
@@ -928,8 +931,8 @@ pub async fn oauth_refresh_access_token(
return Ok(IpcResponse::error(&response_text)); return Ok(IpcResponse::error(&response_text));
} }
let mut token_response: OAuthTokenResponse = serde_json::from_str(&response_text) let mut token_response: OAuthTokenResponse =
.map_err(|e| format!("解析响应失败: {}", e))?; serde_json::from_str(&response_text).map_err(|e| format!("解析响应失败: {}", e))?;
// 处理 access_token 格式: JWT|refresh_token // 处理 access_token 格式: JWT|refresh_token
if token_response.access_token.contains('|') { if token_response.access_token.contains('|') {
@@ -941,4 +944,3 @@ pub async fn oauth_refresh_access_token(
Ok(IpcResponse::success(token_response)) Ok(IpcResponse::success(token_response))
} }
+14 -4
View File
@@ -19,7 +19,9 @@ fn check_admin_permission(state: &Arc<RwLock<AppState>>, sender_id: Option<u32>)
} }
#[tauri::command] #[tauri::command]
pub fn plugin_get_all(state: State<'_, Arc<RwLock<AppState>>>) -> Result<IpcResponse<Vec<Plugin>>, String> { pub fn plugin_get_all(
state: State<'_, Arc<RwLock<AppState>>>,
) -> Result<IpcResponse<Vec<Plugin>>, String> {
let state_guard = state.read(); let state_guard = state.read();
let plugins = state_guard.plugins.read(); let plugins = state_guard.plugins.read();
let all_plugins = (*plugins).get_all_plugins().to_vec(); let all_plugins = (*plugins).get_all_plugins().to_vec();
@@ -41,7 +43,9 @@ pub fn plugin_get(
} }
#[tauri::command] #[tauri::command]
pub fn plugin_get_stats(state: State<'_, Arc<RwLock<AppState>>>) -> Result<IpcResponse<PluginStats>, String> { pub fn plugin_get_stats(
state: State<'_, Arc<RwLock<AppState>>>,
) -> Result<IpcResponse<PluginStats>, String> {
let state_guard = state.read(); let state_guard = state.read();
let plugins = state_guard.plugins.read(); let plugins = state_guard.plugins.read();
let stats = plugins.get_plugin_stats(); let stats = plugins.get_plugin_stats();
@@ -147,10 +151,16 @@ impl From<Plugin> for PluginListItem {
} }
#[tauri::command] #[tauri::command]
pub fn plugin_get_list(state: State<'_, Arc<RwLock<AppState>>>) -> Result<IpcResponse<Vec<PluginListItem>>, String> { pub fn plugin_get_list(
state: State<'_, Arc<RwLock<AppState>>>,
) -> Result<IpcResponse<Vec<PluginListItem>>, String> {
let state_guard = state.read(); let state_guard = state.read();
let plugins = state_guard.plugins.read(); let plugins = state_guard.plugins.read();
let list: Vec<PluginListItem> = (*plugins).get_all_plugins().iter().map(|p| (*p).clone().into()).collect(); let list: Vec<PluginListItem> = (*plugins)
.get_all_plugins()
.iter()
.map(|p| (*p).clone().into())
.collect();
Ok(IpcResponse::success(list)) Ok(IpcResponse::success(list))
} }
+87 -40
View File
@@ -1,23 +1,23 @@
use parking_lot::RwLock; use parking_lot::RwLock;
use std::sync::Arc; use std::sync::Arc;
use tauri::AppHandle; use tauri::{AppHandle, WebviewWindow};
#[cfg(desktop)] #[cfg(desktop)]
use tauri::Manager; use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};
use crate::state::AppState; use crate::state::AppState;
#[tauri::command] #[tauri::command]
pub async fn window_minimize( pub async fn window_minimize(
app: AppHandle, window: WebviewWindow,
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<(), String> { ) -> Result<(), String> {
#[cfg(not(desktop))] #[cfg(not(desktop))]
{ {
let _ = app; let _ = window;
} }
#[cfg(desktop)] #[cfg(desktop)]
if let Some(window) = app.get_webview_window("main") { {
window.minimize().map_err(|e| e.to_string())?; window.minimize().map_err(|e| e.to_string())?;
} }
Ok(()) Ok(())
@@ -25,83 +25,79 @@ pub async fn window_minimize(
#[tauri::command] #[tauri::command]
pub async fn window_maximize( pub async fn window_maximize(
app: AppHandle, window: WebviewWindow,
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<bool, String> { ) -> Result<bool, String> {
#[cfg(not(desktop))] #[cfg(not(desktop))]
{ {
let _ = app; let _ = window;
return Ok(false); return Ok(false);
} }
#[cfg(desktop)] #[cfg(desktop)]
{ {
if let Some(window) = app.get_webview_window("main") { let is_maximized = window.is_maximized().map_err(|e| e.to_string())?;
let is_maximized = window.is_maximized().map_err(|e| e.to_string())?;
if is_maximized { if is_maximized {
window.unmaximize().map_err(|e| e.to_string())?; window.unmaximize().map_err(|e| e.to_string())?;
Ok(false) Ok(false)
} else {
window.maximize().map_err(|e| e.to_string())?;
Ok(true)
}
} else { } else {
Err("Window not found".to_string()) window.maximize().map_err(|e| e.to_string())?;
Ok(true)
} }
} }
} }
#[tauri::command] #[tauri::command]
pub async fn window_close( pub async fn window_close(
app: AppHandle, window: WebviewWindow,
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<(), String> { ) -> Result<(), String> {
#[cfg(not(desktop))] #[cfg(not(desktop))]
{ {
let _ = app; let _ = window;
} }
#[cfg(desktop)] #[cfg(desktop)]
if let Some(window) = app.get_webview_window("main") { {
window.hide().map_err(|e| e.to_string())?; if window.label() == "main" {
window.hide().map_err(|e| e.to_string())?;
} else {
window.close().map_err(|e| e.to_string())?;
}
} }
Ok(()) Ok(())
} }
#[tauri::command] #[tauri::command]
pub async fn window_is_maximized( pub async fn window_is_maximized(
app: AppHandle, window: WebviewWindow,
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<bool, String> { ) -> Result<bool, String> {
#[cfg(not(desktop))] #[cfg(not(desktop))]
{ {
let _ = app; let _ = window;
return Ok(false); return Ok(false);
} }
#[cfg(desktop)] #[cfg(desktop)]
{ {
if let Some(window) = app.get_webview_window("main") { window.is_maximized().map_err(|e| e.to_string())
window.is_maximized().map_err(|e| e.to_string())
} else {
Ok(false)
}
} }
} }
#[tauri::command] #[tauri::command]
pub async fn toggle_devtools( pub async fn toggle_devtools(
app: AppHandle, window: WebviewWindow,
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<(), String> { ) -> Result<(), String> {
#[cfg(not(desktop))] #[cfg(not(desktop))]
{ {
let _ = app; let _ = window;
} }
#[cfg(all(debug_assertions, desktop))] #[cfg(all(debug_assertions, desktop))]
if let Some(window) = app.get_webview_window("main") { {
if window.is_devtools_open() { if window.is_devtools_open() {
window.close_devtools(); window.close_devtools();
} else { } else {
@@ -115,16 +111,16 @@ pub async fn toggle_devtools(
pub async fn window_resize( pub async fn window_resize(
width: u32, width: u32,
height: u32, height: u32,
app: AppHandle, window: WebviewWindow,
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<(), String> { ) -> Result<(), String> {
#[cfg(not(desktop))] #[cfg(not(desktop))]
{ {
let _ = (width, height, app); let _ = (width, height, window);
} }
#[cfg(desktop)] #[cfg(desktop)]
if let Some(window) = app.get_webview_window("main") { {
window window
.set_size(tauri::Size::Logical(tauri::LogicalSize { .set_size(tauri::Size::Logical(tauri::LogicalSize {
width: width as f64, width: width as f64,
@@ -138,16 +134,16 @@ pub async fn window_resize(
#[tauri::command] #[tauri::command]
pub async fn window_set_resizable( pub async fn window_set_resizable(
resizable: bool, resizable: bool,
app: AppHandle, window: WebviewWindow,
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<(), String> { ) -> Result<(), String> {
#[cfg(not(desktop))] #[cfg(not(desktop))]
{ {
let _ = (resizable, app); let _ = (resizable, window);
} }
#[cfg(desktop)] #[cfg(desktop)]
if let Some(window) = app.get_webview_window("main") { {
window.set_resizable(resizable).map_err(|e| e.to_string())?; window.set_resizable(resizable).map_err(|e| e.to_string())?;
} }
Ok(()) Ok(())
@@ -155,17 +151,68 @@ pub async fn window_set_resizable(
#[tauri::command] #[tauri::command]
pub async fn window_start_dragging( pub async fn window_start_dragging(
app: AppHandle, window: WebviewWindow,
_state: tauri::State<'_, Arc<RwLock<AppState>>>, _state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<(), String> { ) -> Result<(), String> {
#[cfg(not(desktop))] #[cfg(not(desktop))]
{ {
let _ = app; let _ = window;
} }
#[cfg(desktop)] #[cfg(desktop)]
if let Some(window) = app.get_webview_window("main") { {
window.start_dragging().map_err(|e| e.to_string())?; window.start_dragging().map_err(|e| e.to_string())?;
} }
Ok(()) Ok(())
} }
pub fn show_management_window(app: &AppHandle) -> Result<(), String> {
#[cfg(not(desktop))]
{
let _ = app;
return Ok(());
}
#[cfg(desktop)]
{
if let Some(window) = app.get_webview_window("management") {
window.show().map_err(|e| e.to_string())?;
window.set_focus().map_err(|e| e.to_string())?;
return Ok(());
}
let window = WebviewWindowBuilder::new(
app,
"management",
WebviewUrl::App("index.html?window=management#/students".into()),
)
.title("SecScore 管理")
.inner_size(1180.0, 680.0)
.min_inner_size(360.0, 640.0)
.resizable(true)
.decorations(true)
.transparent(true)
.hidden_title(true)
.title_bar_style(tauri::TitleBarStyle::Overlay)
.traffic_light_position(tauri::LogicalPosition::new(16.0, 22.0))
.center()
.build()
.map_err(|e| e.to_string())?;
#[cfg(target_os = "macos")]
{
let _ = window.set_shadow(true);
}
window.set_focus().map_err(|e| e.to_string())?;
Ok(())
}
}
#[tauri::command]
pub async fn window_open_management(
app: AppHandle,
_state: tauri::State<'_, Arc<RwLock<AppState>>>,
) -> Result<(), String> {
show_management_window(&app)
}
+6 -2
View File
@@ -128,6 +128,7 @@ pub fn run() {
window_maximize, window_maximize,
window_close, window_close,
window_is_maximized, window_is_maximized,
window_open_management,
toggle_devtools, toggle_devtools,
window_resize, window_resize,
window_set_resizable, window_set_resizable,
@@ -377,10 +378,11 @@ fn setup_database(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
#[cfg(desktop)] #[cfg(desktop)]
fn setup_tray(app: &mut App) -> Result<(), Box<dyn std::error::Error>> { fn setup_tray(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
let show_item = MenuItem::with_id(app, "show", "显示窗口", true, None::<&str>)?; let show_item = MenuItem::with_id(app, "show", "显示窗口", true, None::<&str>)?;
let management_item = MenuItem::with_id(app, "management", "打开管理页", true, None::<&str>)?;
let hide_item = MenuItem::with_id(app, "hide", "隐藏窗口", true, None::<&str>)?; let hide_item = MenuItem::with_id(app, "hide", "隐藏窗口", true, None::<&str>)?;
let quit_item = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?; let quit_item = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show_item, &hide_item, &quit_item])?; let menu = Menu::with_items(app, &[&show_item, &management_item, &hide_item, &quit_item])?;
let _tray = TrayIconBuilder::new() let _tray = TrayIconBuilder::new()
.icon(Image::from_bytes(include_bytes!("../icons/icon.png"))?) .icon(Image::from_bytes(include_bytes!("../icons/icon.png"))?)
@@ -398,6 +400,9 @@ fn setup_tray(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
let _ = window.hide(); let _ = window.hide();
} }
} }
"management" => {
let _ = show_management_window(app);
}
"quit" => { "quit" => {
app.exit(0); app.exit(0);
} }
@@ -457,4 +462,3 @@ fn setup_window_events(app: &mut App) -> Result<(), Box<dyn std::error::Error>>
fn setup_window_events(_app: &mut App) -> Result<(), Box<dyn std::error::Error>> { fn setup_window_events(_app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
Ok(()) Ok(())
} }
+3 -1
View File
@@ -986,7 +986,9 @@ fn normalize_optional_string(value: Option<String>) -> Option<String> {
}) })
} }
fn parse_reward_exchange_action_value(raw_value: Option<&str>) -> Option<RewardExchangeActionValue> { fn parse_reward_exchange_action_value(
raw_value: Option<&str>,
) -> Option<RewardExchangeActionValue> {
let raw_value = raw_value.map(str::trim)?; let raw_value = raw_value.map(str::trim)?;
if raw_value.is_empty() { if raw_value.is_empty() {
return None; return None;
+27 -9
View File
@@ -118,7 +118,8 @@ impl PluginService {
let plugins_dir = Self::get_plugins_dir(app_handle); let plugins_dir = Self::get_plugins_dir(app_handle);
if !plugins_dir.exists() { if !plugins_dir.exists() {
fs::create_dir_all(&plugins_dir).map_err(|e| format!("Failed to create plugins directory: {}", e))?; fs::create_dir_all(&plugins_dir)
.map_err(|e| format!("Failed to create plugins directory: {}", e))?;
} }
self.plugins.clear(); self.plugins.clear();
@@ -132,7 +133,9 @@ impl PluginService {
return Ok(()); return Ok(());
} }
for entry in fs::read_dir(dir).map_err(|e| format!("Failed to read plugins directory: {}", e))? { for entry in
fs::read_dir(dir).map_err(|e| format!("Failed to read plugins directory: {}", e))?
{
let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?; let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?;
let path = entry.path(); let path = entry.path();
@@ -149,7 +152,11 @@ impl PluginService {
); );
continue; continue;
} }
if self.plugins.iter().any(|existing| existing.id == manifest.id) { if self
.plugins
.iter()
.any(|existing| existing.id == manifest.id)
{
eprintln!( eprintln!(
"Skip duplicated plugin id {} at {}", "Skip duplicated plugin id {} at {}",
manifest.id, manifest.id,
@@ -190,7 +197,9 @@ impl PluginService {
.chars() .chars()
.all(|ch| ch.is_ascii_alphanumeric() || ch == '.' || ch == '_' || ch == '-') .all(|ch| ch.is_ascii_alphanumeric() || ch == '.' || ch == '_' || ch == '-')
{ {
return Err("Plugin id can only contain letters, numbers, dot, underscore, hyphen".to_string()); return Err(
"Plugin id can only contain letters, numbers, dot, underscore, hyphen".to_string(),
);
} }
if name.is_empty() { if name.is_empty() {
return Err("Plugin name cannot be empty".to_string()); return Err("Plugin name cannot be empty".to_string());
@@ -257,14 +266,17 @@ impl PluginService {
fn persist_manifest_enabled(manifest_path: &Path, enabled: bool) -> Result<(), String> { fn persist_manifest_enabled(manifest_path: &Path, enabled: bool) -> Result<(), String> {
let mut manifest = Self::load_plugin_manifest_from_file(manifest_path)?; let mut manifest = Self::load_plugin_manifest_from_file(manifest_path)?;
manifest.enabled = enabled; manifest.enabled = enabled;
let serialized = let serialized = serde_json::to_string_pretty(&manifest)
serde_json::to_string_pretty(&manifest).map_err(|e| format!("Failed to serialize manifest.json: {}", e))?; .map_err(|e| format!("Failed to serialize manifest.json: {}", e))?;
fs::write(manifest_path, format!("{}\n", serialized)) fs::write(manifest_path, format!("{}\n", serialized))
.map_err(|e| format!("Failed to write manifest.json: {}", e))?; .map_err(|e| format!("Failed to write manifest.json: {}", e))?;
Ok(()) Ok(())
} }
fn resolve_plugin_relative_path(plugin_dir: &Path, relative_path: &str) -> Result<PathBuf, String> { fn resolve_plugin_relative_path(
plugin_dir: &Path,
relative_path: &str,
) -> Result<PathBuf, String> {
let relative_path = relative_path.trim(); let relative_path = relative_path.trim();
if relative_path.is_empty() { if relative_path.is_empty() {
return Err("Plugin entry file path cannot be empty".to_string()); return Err("Plugin entry file path cannot be empty".to_string());
@@ -309,7 +321,11 @@ impl PluginService {
plugin_dir: PathBuf, plugin_dir: PathBuf,
) -> Result<Plugin, String> { ) -> Result<Plugin, String> {
Self::validate_manifest(&manifest)?; Self::validate_manifest(&manifest)?;
if self.plugins.iter().any(|existing| existing.id == manifest.id) { if self
.plugins
.iter()
.any(|existing| existing.id == manifest.id)
{
return Err("Plugin already installed".to_string()); return Err("Plugin already installed".to_string());
} }
if !plugin_dir.exists() || !plugin_dir.is_dir() { if !plugin_dir.exists() || !plugin_dir.is_dir() {
@@ -322,7 +338,9 @@ impl PluginService {
let source_manifest = Self::load_plugin_manifest(&plugin_dir)?; let source_manifest = Self::load_plugin_manifest(&plugin_dir)?;
Self::validate_manifest(&source_manifest)?; Self::validate_manifest(&source_manifest)?;
if source_manifest.id != manifest.id { if source_manifest.id != manifest.id {
return Err("Manifest mismatch: plugin id in folder does not match selected plugin".to_string()); return Err(
"Manifest mismatch: plugin id in folder does not match selected plugin".to_string(),
);
} }
let plugins_dir = Self::get_plugins_dir(app_handle); let plugins_dir = Self::get_plugins_dir(app_handle);
+50 -28
View File
@@ -44,6 +44,7 @@ const DEFAULT_MOBILE_BOTTOM_PRIMARY_KEYS: MobileNavKey[] = DEFAULT_MOBILE_BOTTOM
0, 0,
4 4
) )
const MANAGEMENT_DEFAULT_ROUTE = "/students"
const applyGlobalFontFamily = (fontValue?: string) => { const applyGlobalFontFamily = (fontValue?: string) => {
const fontFamily = resolveStoredFontFamily(fontValue) const fontFamily = resolveStoredFontFamily(fontValue)
document.documentElement.style.setProperty("--ss-font-family", fontFamily) document.documentElement.style.setProperty("--ss-font-family", fontFamily)
@@ -61,7 +62,11 @@ function MainContent(): React.JSX.Element {
typeof navigator !== "undefined" && typeof navigator !== "undefined" &&
/mac/i.test(navigator.userAgent) && /mac/i.test(navigator.userAgent) &&
!/iphone|ipad|ipod|android/i.test(navigator.userAgent) !/iphone|ipad|ipod|android/i.test(navigator.userAgent)
const [immersiveMode, setImmersiveMode] = useState(false) const isManagementWindow = useMemo(() => {
const params = new URLSearchParams(window.location.search)
return params.get("window") === "management"
}, [])
const [immersiveMode] = useState(!isManagementWindow)
const normalizeStoredBottomKeys = (raw: unknown): MobileNavKey[] => { const normalizeStoredBottomKeys = (raw: unknown): MobileNavKey[] => {
if (Array.isArray(raw)) { if (Array.isArray(raw)) {
@@ -82,11 +87,16 @@ function MainContent(): React.JSX.Element {
const currentPath = location.pathname === "/" ? "/home" : location.pathname const currentPath = location.pathname === "/" ? "/home" : location.pathname
const targetPath = route === "/" ? "/home" : route const targetPath = route === "/" ? "/home" : route
if (immersiveMode && !targetPath.startsWith("/home")) { if (!isManagementWindow && !targetPath.startsWith("/home")) {
navigate("/", { replace: true }) navigate("/", { replace: true })
return return
} }
if (isManagementWindow && targetPath.startsWith("/home")) {
navigate(MANAGEMENT_DEFAULT_ROUTE, { replace: true })
return
}
if (currentPath !== targetPath) { if (currentPath !== targetPath) {
navigate(route) navigate(route)
} }
@@ -104,7 +114,7 @@ function MainContent(): React.JSX.Element {
disposed = true disposed = true
if (unlisten) unlisten() if (unlisten) unlisten()
} }
}, [navigate, location.pathname, immersiveMode]) }, [navigate, location.pathname, isManagementWindow])
const [wizardVisible, setWizardVisible] = useState(false) const [wizardVisible, setWizardVisible] = useState(false)
const [permission, setPermission] = useState<"admin" | "points" | "view">("view") const [permission, setPermission] = useState<"admin" | "points" | "view">("view")
@@ -154,7 +164,7 @@ function MainContent(): React.JSX.Element {
const activeMenu = useMemo(() => { const activeMenu = useMemo(() => {
const p = location.pathname const p = location.pathname
if (p === "/" || p.startsWith("/home")) return "home" if (p === "/" || p.startsWith("/home")) return isManagementWindow ? "students" : "home"
if (p.startsWith("/students")) return "students" if (p.startsWith("/students")) return "students"
if (p.startsWith("/score")) return "score" if (p.startsWith("/score")) return "score"
if (p.startsWith("/boards")) return "boards" if (p.startsWith("/boards")) return "boards"
@@ -165,8 +175,8 @@ function MainContent(): React.JSX.Element {
if (p.startsWith("/reward-settings")) return "reward-settings" if (p.startsWith("/reward-settings")) return "reward-settings"
if (p.startsWith("/plugins")) return "plugins" if (p.startsWith("/plugins")) return "plugins"
if (p.startsWith("/settings")) return "settings" if (p.startsWith("/settings")) return "settings"
return "home" return isManagementWindow ? "students" : "home"
}, [location.pathname]) }, [location.pathname, isManagementWindow])
useEffect(() => { useEffect(() => {
const runtime = pluginRuntimeRef.current const runtime = pluginRuntimeRef.current
@@ -602,7 +612,8 @@ function MainContent(): React.JSX.Element {
const key = String(v) const key = String(v)
setMoreNavVisible(false) setMoreNavVisible(false)
setEditingNav(false) setEditingNav(false)
if (immersiveMode && key !== "home") return if (!isManagementWindow && key !== "home") return
if (isManagementWindow && key === "home") return
if (key === "home") navigate("/") if (key === "home") navigate("/")
if (key === "students") navigate("/students") if (key === "students") navigate("/students")
if (key === "score") navigate("/score") if (key === "score") navigate("/score")
@@ -626,29 +637,32 @@ function MainContent(): React.JSX.Element {
} }
useEffect(() => { useEffect(() => {
if (!immersiveMode) return if (
if (location.pathname !== "/" && !location.pathname.startsWith("/home")) { !isManagementWindow &&
location.pathname !== "/" &&
!location.pathname.startsWith("/home")
) {
navigate("/", { replace: true }) navigate("/", { replace: true })
return
} }
}, [immersiveMode, location.pathname, navigate]) if (
isManagementWindow &&
(location.pathname === "/" || location.pathname.startsWith("/home"))
) {
navigate(MANAGEMENT_DEFAULT_ROUTE, { replace: true })
}
}, [isManagementWindow, location.pathname, navigate])
const toggleImmersiveMode = () => { const openManagementWindow = useCallback(async () => {
setImmersiveMode((prev) => { const api = (window as any).api
const next = !prev if (!api?.openManagementWindow) return
if (next) { await api.openManagementWindow()
setFloatingSidebarExpanded(false) }, [])
if (location.pathname !== "/" && !location.pathname.startsWith("/home")) {
navigate("/", { replace: true })
}
}
return next
})
}
const isDark = currentTheme?.mode === "dark" const isDark = currentTheme?.mode === "dark"
const brandColor = currentTheme?.config?.tdesign?.brandColor || "#0052D9" const brandColor = currentTheme?.config?.tdesign?.brandColor || "#0052D9"
const isMobileDevice = isIosDevice || isAndroidDevice const isMobileDevice = isIosDevice || isAndroidDevice
const showMobileBottomNav = isPortraitMode && !immersiveMode const showMobileBottomNav = isPortraitMode && isManagementWindow
const mobileBottomNavIconMap: Record<MobileNavKey, React.ReactNode> = { const mobileBottomNavIconMap: Record<MobileNavKey, React.ReactNode> = {
home: <HomeOutlined style={{ fontSize: "18px" }} />, home: <HomeOutlined style={{ fontSize: "18px" }} />,
students: <UserOutlined style={{ fontSize: "18px" }} />, students: <UserOutlined style={{ fontSize: "18px" }} />,
@@ -664,8 +678,13 @@ function MainContent(): React.JSX.Element {
} }
const mobileNavAvailableItems = useMemo( const mobileNavAvailableItems = useMemo(
() => MOBILE_NAV_ITEMS.filter((item) => !(item.adminOnly && permission !== "admin")), () =>
[permission] MOBILE_NAV_ITEMS.filter(
(item) =>
(isManagementWindow ? item.key !== "home" : item.key === "home") &&
!(item.adminOnly && permission !== "admin")
),
[isManagementWindow, permission]
) )
const mobileBottomSelectedKeys = useMemo(() => { const mobileBottomSelectedKeys = useMemo(() => {
const availableKeySet = new Set(mobileNavAvailableItems.map((item) => item.key)) const availableKeySet = new Set(mobileNavAvailableItems.map((item) => item.key))
@@ -768,7 +787,7 @@ function MainContent(): React.JSX.Element {
<Layout <Layout
style={{ height: "100%", flexDirection: "row", overflow: "hidden", position: "relative" }} style={{ height: "100%", flexDirection: "row", overflow: "hidden", position: "relative" }}
> >
{!isPortraitMode && ( {!isPortraitMode && isManagementWindow && (
<div <div
className={`ss-immersive-sidebar ${immersiveMode ? "is-hidden" : "is-visible"}`} className={`ss-immersive-sidebar ${immersiveMode ? "is-hidden" : "is-visible"}`}
style={ style={
@@ -785,6 +804,7 @@ function MainContent(): React.JSX.Element {
floatingExpand={isPortraitMode} floatingExpand={isPortraitMode}
floatingExpanded={floatingSidebarExpanded} floatingExpanded={floatingSidebarExpanded}
onFloatingExpandedChange={setFloatingSidebarExpanded} onFloatingExpandedChange={setFloatingSidebarExpanded}
showHome={false}
/> />
</div> </div>
)} )}
@@ -804,8 +824,10 @@ function MainContent(): React.JSX.Element {
onToggleSidebar={toggleSidebar} onToggleSidebar={toggleSidebar}
immersiveMode={immersiveMode} immersiveMode={immersiveMode}
isHomePage={activeMenu === "home"} isHomePage={activeMenu === "home"}
onToggleImmersiveMode={toggleImmersiveMode} onOpenManagementWindow={openManagementWindow}
showSidebarToggle={!isPortraitMode} showSidebarToggle={!isPortraitMode && isManagementWindow}
showHomeRoute={!isManagementWindow}
fallbackRoute={isManagementWindow ? MANAGEMENT_DEFAULT_ROUTE : "/"}
bottomInset={showMobileBottomNav ? 84 : 0} bottomInset={showMobileBottomNav ? 84 : 0}
/> />
{showMobileBottomNav && ( {showMobileBottomNav && (
+24 -20
View File
@@ -3,9 +3,8 @@ import { Layout, Space, Button, Tag, Spin, Avatar, Popover, Progress } from "ant
import { import {
MenuFoldOutlined, MenuFoldOutlined,
MenuUnfoldOutlined, MenuUnfoldOutlined,
FullscreenOutlined,
FullscreenExitOutlined,
LeftOutlined, LeftOutlined,
SettingOutlined,
} from "@ant-design/icons" } from "@ant-design/icons"
import { Routes, Route, Navigate, useLocation, useNavigate } from "react-router-dom" import { Routes, Route, Navigate, useLocation, useNavigate } from "react-router-dom"
import { useTranslation } from "react-i18next" import { useTranslation } from "react-i18next"
@@ -71,8 +70,10 @@ interface ContentAreaProps {
onToggleSidebar: () => void onToggleSidebar: () => void
immersiveMode: boolean immersiveMode: boolean
isHomePage: boolean isHomePage: boolean
onToggleImmersiveMode: () => void onOpenManagementWindow?: () => Promise<void> | void
showSidebarToggle?: boolean showSidebarToggle?: boolean
showHomeRoute?: boolean
fallbackRoute?: string
bottomInset?: number bottomInset?: number
} }
@@ -99,8 +100,10 @@ export function ContentArea({
onToggleSidebar, onToggleSidebar,
immersiveMode, immersiveMode,
isHomePage, isHomePage,
onToggleImmersiveMode, onOpenManagementWindow,
showSidebarToggle = true, showSidebarToggle = true,
showHomeRoute = true,
fallbackRoute = "/",
bottomInset = 0, bottomInset = 0,
}: ContentAreaProps): React.JSX.Element { }: ContentAreaProps): React.JSX.Element {
const { t } = useTranslation() const { t } = useTranslation()
@@ -118,7 +121,7 @@ export function ContentArea({
const isBoardPage = normalizedPath.startsWith("/boards") const isBoardPage = normalizedPath.startsWith("/boards")
const isMobileHeaderMode = isPortraitMode && isMobileDevice && !immersiveMode const isMobileHeaderMode = isPortraitMode && isMobileDevice && !immersiveMode
const isPrimaryMobilePage = const isPrimaryMobilePage =
normalizedPath.startsWith("/home") || normalizedPath.startsWith("/settings") (showHomeRoute && normalizedPath.startsWith("/home")) || normalizedPath.startsWith("/settings")
const showMobileBack = isMobileHeaderMode && !isPrimaryMobilePage const showMobileBack = isMobileHeaderMode && !isPrimaryMobilePage
const mobilePageTitle = (() => { const mobilePageTitle = (() => {
if (normalizedPath.startsWith("/home")) return t("sidebar.home") if (normalizedPath.startsWith("/home")) return t("sidebar.home")
@@ -549,10 +552,9 @@ export function ContentArea({
{(immersiveMode || (isHomePage && !isMobileDevice)) && ( {(immersiveMode || (isHomePage && !isMobileDevice)) && (
<Button <Button
size="small" size="small"
type={immersiveMode ? "primary" : "default"} icon={<SettingOutlined />}
icon={immersiveMode ? <FullscreenExitOutlined /> : <FullscreenOutlined />} onClick={onOpenManagementWindow}
onClick={onToggleImmersiveMode} title="管理"
title={immersiveMode ? "退出沉浸模式" : "进入沉浸模式"}
/> />
)} )}
<Popover <Popover
@@ -651,16 +653,18 @@ export function ContentArea({
className={`ss-route-page${shouldAnimateSubPage ? " is-subpage-enter" : ""}${isBoardPage ? " is-board-page" : ""}`} className={`ss-route-page${shouldAnimateSubPage ? " is-subpage-enter" : ""}${isBoardPage ? " is-board-page" : ""}`}
> >
<Routes> <Routes>
<Route {showHomeRoute && (
path="/" <Route
element={ path="/"
<Home element={
canEdit={permission === "admin" || permission === "points"} <Home
isPortraitMode={isPortraitMode} canEdit={permission === "admin" || permission === "points"}
immersiveMode={immersiveMode} isPortraitMode={isPortraitMode}
/> immersiveMode={immersiveMode}
} />
/> }
/>
)}
<Route <Route
path="/students" path="/students"
element={<StudentManager canEdit={permission === "admin"} />} element={<StudentManager canEdit={permission === "admin"} />}
@@ -685,7 +689,7 @@ export function ContentArea({
/> />
<Route path="/plugins" element={<PluginManager canEdit={permission === "admin"} />} /> <Route path="/plugins" element={<PluginManager canEdit={permission === "admin"} />} />
<Route path="/settings" element={<Settings permission={permission} />} /> <Route path="/settings" element={<Settings permission={permission} />} />
<Route path="*" element={<Navigate to="/" replace />} /> <Route path="*" element={<Navigate to={fallbackRoute} replace />} />
</Routes> </Routes>
</div> </div>
</Suspense> </Suspense>
+3 -1
View File
@@ -27,6 +27,7 @@ interface SidebarProps {
floatingExpand: boolean floatingExpand: boolean
floatingExpanded: boolean floatingExpanded: boolean
onFloatingExpandedChange: (expanded: boolean) => void onFloatingExpandedChange: (expanded: boolean) => void
showHome?: boolean
} }
interface DbStatus { interface DbStatus {
@@ -43,6 +44,7 @@ export function Sidebar({
floatingExpand, floatingExpand,
floatingExpanded, floatingExpanded,
onFloatingExpandedChange, onFloatingExpandedChange,
showHome = true,
}: SidebarProps): React.JSX.Element { }: SidebarProps): React.JSX.Element {
const { t } = useTranslation() const { t } = useTranslation()
const [dbStatus, setDbStatus] = useState<DbStatus>({ type: "sqlite", connected: true }) const [dbStatus, setDbStatus] = useState<DbStatus>({ type: "sqlite", connected: true })
@@ -209,7 +211,7 @@ export function Sidebar({
label: t("sidebar.settings"), label: t("sidebar.settings"),
disabled: permission !== "admin", disabled: permission !== "admin",
}, },
] ].filter((item) => showHome || item.key !== "home")
const showFloatingPanel = floatingExpand && collapsed && floatingExpanded const showFloatingPanel = floatingExpand && collapsed && floatingExpanded
+1
View File
@@ -638,6 +638,7 @@ const api = {
windowMaximize: (): Promise<boolean> => invoke("window_maximize"), windowMaximize: (): Promise<boolean> => invoke("window_maximize"),
windowClose: (): Promise<void> => invoke("window_close"), windowClose: (): Promise<void> => invoke("window_close"),
windowIsMaximized: (): Promise<boolean> => invoke("window_is_maximized"), windowIsMaximized: (): Promise<boolean> => invoke("window_is_maximized"),
openManagementWindow: (): Promise<void> => invoke("window_open_management"),
startDraggingWindow: (): Promise<void> => invoke("window_start_dragging"), startDraggingWindow: (): Promise<void> => invoke("window_start_dragging"),
toggleDevTools: (): Promise<void> => invoke("toggle_devtools"), toggleDevTools: (): Promise<void> => invoke("toggle_devtools"),
windowResize: (width: number, height: number): Promise<void> => windowResize: (width: number, height: number): Promise<void> =>