diff --git a/CHANGELOG-PUBLIC.md b/CHANGELOG-PUBLIC.md index a1570c4..fb1c05d 100644 --- a/CHANGELOG-PUBLIC.md +++ b/CHANGELOG-PUBLIC.md @@ -2,6 +2,28 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. +## 0.5.0 — 2026-11-20 + +### Added + +- Star your favourite screenshots. Hover a screenshot and press the star; it fills in and stays visible. Use the All | Favourites switch at the top of the Screenshots page to see only your favourites. +- Screenshots are now named after the page or app you captured, with the date and time, for example `GitHub - capkit - Google Chrome, Nov 20, 11:52 AM`. Older captures that were all called "CapKit" now show a readable date instead. +- Recordings show a thumbnail of their first frame instead of a black box. +- Copy and favourite buttons have a soft click sound and a gentle press effect. The copy icon turns into a check the moment you press it. Settings switches get the same sound and press effect. +- A new left-hand menu groups your work: Screenshots and Screen record at the top, Showcase under Studio, and Settings at the bottom. A soft highlight glides to whatever you point at. + +### Improved + +- A fresh glass look across the dashboard: frosted buttons and cards that follow your accent colour in light and dark, Geist and Geist Mono as the fonts everywhere, and one consistent set of icons. +- The custom accent colour can be changed by clicking the swatch, and the CapKit logo and tagline are back on the dashboard. +- Screenshot, recording and note cards are the same size, fill each row evenly and no longer leave an odd gap on the right. Screenshot cards no longer repeat the date twice. +- Notes (now called Page notes) show the title and the website on one line, with a shorter preview. +- Settings content now fades softly under the tabs as you scroll instead of overlapping them. +- The page no longer jumps sideways when you switch between tabs of different length. +- "Record" is now called "Screen record". The minimize, maximize and close buttons are visible in light mode. +- Refresh on the Screenshots page now visibly spins, and the file count is no longer stuck at 200 (up to 1000 are shown). +- Your save folder is now `PicturesCapKit`. If you used the old Snaphub or ShotHub folder, CapKit renames it for you and keeps your files. + ## 0.4.0 — 2026-11-20 ### Added @@ -15,6 +37,8 @@ User-facing changes only, grouped by date under Added / Improved / Fixed. ### Improved +- The dashboard has a calmer look: one accent-tinted palette in light and dark, glass behind the window on Windows 11, consistent page headers, and quieter motion. Settings sections open from anywhere on their row, show their current value while closed, and animate smoothly. + - Press 1–9 and 0 to pick a tool in the capture toolbar, and V for Select. Each button shows its number in the corner, like C, S and A. - Copy, Save and Copy & Save (C, S, A) now deliver your note when the capture has pins, so the separate note buttons are gone. - Click a note pin with the Select tool to edit its comment, and drag the pin to move its comment with it. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 38fa9ee..3ee4893 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@snaphub/desktop", - "version": "0.4.0", + "version": "0.5.0", "private": true, "type": "module", "scripts": { @@ -17,8 +17,8 @@ }, "dependencies": { "@fontsource-variable/caveat": "5.2.8", - "@fontsource-variable/jetbrains-mono": "5.2.8", - "@fontsource-variable/plus-jakarta-sans": "5.2.8", + "@fontsource-variable/geist": "5.3.0", + "@fontsource-variable/geist-mono": "5.3.0", "@hugeicons/core-free-icons": "4.2.3", "@hugeicons/react": "1.1.9", "@snaphub/devtools-protocol": "workspace:*", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 4256306..83af404 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -616,7 +616,7 @@ dependencies = [ [[package]] name = "capkit-desktop" -version = "0.4.0" +version = "0.5.0" dependencies = [ "ab_glyph", "arboard", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 717fa14..941f63b 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "capkit-desktop" -version = "0.4.0" +version = "0.5.0" description = "CapKit lightweight desktop toolkit to capture, record, and showcase" authors = ["CapKit"] edition = "2024" @@ -50,7 +50,7 @@ windows = { version = "0.62.2", features = [ "Media_Ocr", # Package identity and the MSIX startup task (Store build only). "ApplicationModel", "ApplicationModel_Activation", - "Win32_Foundation", "Win32_System_Com", "Win32_UI_Accessibility", + "Win32_Foundation", "Win32_System_Com", "Win32_System_LibraryLoader", "Win32_UI_Accessibility", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", # Recording: a Windows Graphics Capture frame pool onto our own D3D11 device. "Graphics_Capture", "Graphics_DirectX_Direct3D11", diff --git a/apps/desktop/src-tauri/capabilities/dashboard.json b/apps/desktop/src-tauri/capabilities/dashboard.json new file mode 100644 index 0000000..7f4a9d1 --- /dev/null +++ b/apps/desktop/src-tauri/capabilities/dashboard.json @@ -0,0 +1,12 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "dashboard-window", + "description": "Lets the dashboard follow its light/dark toggle and drive its own title bar buttons.", + "windows": ["dashboard"], + "permissions": [ + "core:window:allow-set-theme", + "core:window:allow-minimize", + "core:window:allow-toggle-maximize", + "core:window:allow-is-maximized" + ] +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index eca8cdc..db0a6d3 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -245,6 +245,44 @@ fn launched_in_background() -> bool { }) } +/// Whether the dashboard's blurred backdrop exists on this OS (Windows 11, build +/// 22000 or later). Elsewhere the page keeps an opaque background, because a +/// transparent window without a backdrop would show the desktop through it. +#[tauri::command] +fn dashboard_supports_glass() -> bool { + #[cfg(target_os = "windows")] + { + #[repr(C)] + struct OsVersionInfo { + size: u32, + major: u32, + minor: u32, + build: u32, + platform: u32, + service_pack: [u16; 128], + } + #[link(name = "ntdll")] + unsafe extern "system" { + fn RtlGetVersion(info: *mut OsVersionInfo) -> i32; + } + let mut info = OsVersionInfo { + size: std::mem::size_of::() as u32, + major: 0, + minor: 0, + build: 0, + platform: 0, + service_pack: [0; 128], + }; + // SAFETY: `info` is a correctly sized, writable OSVERSIONINFOW and `size` is set. + let status = unsafe { RtlGetVersion(&mut info) }; + status == 0 && info.build >= 22000 + } + #[cfg(not(target_os = "windows"))] + { + false + } +} + #[tauri::command] fn dashboard_ready( app: AppHandle, @@ -2886,6 +2924,7 @@ pub fn run() { begin_capture, show_capture_surface, dashboard_ready, + dashboard_supports_glass, open_in_showcase, take_pending_showcase, on_screen_session, @@ -2992,6 +3031,15 @@ pub fn run() { .set_notes_images_directory(notes.images_directory()); app.manage(notes); + // Frosted glass behind the dashboard. The page asks `dashboard_supports_glass` + // and stays opaque where the blur is unavailable. + #[cfg(target_os = "windows")] + if let Some(window) = app.get_webview_window("dashboard") + && let Ok(hwnd) = window.hwnd() + { + platform::windows_glass::apply_blur(hwnd.0); + } + if launched_in_background() && let Some(window) = app.get_webview_window("dashboard") { diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rs index f390792..0d7be50 100644 --- a/apps/desktop/src-tauri/src/platform/mod.rs +++ b/apps/desktop/src-tauri/src/platform/mod.rs @@ -13,6 +13,10 @@ pub(crate) mod plugin_startup; #[cfg(target_os = "windows")] pub(crate) mod windows_display; #[cfg(target_os = "windows")] +pub(crate) mod windows_foreground; +#[cfg(target_os = "windows")] +pub(crate) mod windows_glass; +#[cfg(target_os = "windows")] pub(crate) mod windows_ocr; #[cfg(target_os = "windows")] pub(crate) mod windows_recorder; diff --git a/apps/desktop/src-tauri/src/platform/windows_foreground.rs b/apps/desktop/src-tauri/src/platform/windows_foreground.rs new file mode 100644 index 0000000..5066345 --- /dev/null +++ b/apps/desktop/src-tauri/src/platform/windows_foreground.rs @@ -0,0 +1,21 @@ +//! Names a capture after what is on screen. + +use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowTextW}; + +/// Title of the window that has focus, which for a browser is the page title and +/// for other apps the document and app name. `None` when nothing has focus or the +/// window has no title. +pub(crate) fn foreground_window_title() -> Option { + // SAFETY: both calls only read window state; the buffer outlives the call and its + // length is passed, so Windows cannot write past it. + unsafe { + let window = GetForegroundWindow(); + if window.is_invalid() { + return None; + } + let mut buffer = [0_u16; 256]; + let length = usize::try_from(GetWindowTextW(window, &mut buffer)).ok()?; + let title = String::from_utf16_lossy(buffer.get(..length)?); + (!title.trim().is_empty()).then_some(title) + } +} diff --git a/apps/desktop/src-tauri/src/platform/windows_glass.rs b/apps/desktop/src-tauri/src/platform/windows_glass.rs new file mode 100644 index 0000000..0dda90f --- /dev/null +++ b/apps/desktop/src-tauri/src/platform/windows_glass.rs @@ -0,0 +1,81 @@ +//! Frosted glass behind the dashboard window. +//! +//! The window is transparent; this asks the compositor to blur whatever sits +//! behind it, and the page paints translucent, accent-tinted surfaces on top. +//! Blurring is done by Windows, so it costs this process nothing per frame. +//! +//! It uses the accent policy (`SetWindowCompositionAttribute`) rather than the +//! documented system backdrop (Mica, or `DWMSBT_TRANSIENTWINDOW` acrylic): those +//! drop to a flat colour whenever the window loses focus, and the dashboard is +//! unfocused whenever the user is capturing. The accent policy keeps blurring +//! regardless, on Windows 10 as well as 11. + +use std::ffi::c_void; + +use windows::{ + Win32::{ + Foundation::HWND, + System::LibraryLoader::{GetModuleHandleW, GetProcAddress}, + }, + core::{BOOL, s, w}, +}; + +/// `WCA_ACCENT_POLICY`. +const ACCENT_POLICY: u32 = 19; +/// `ACCENT_ENABLE_ACRYLICBLURBEHIND`: blur plus the acrylic noise layer. +const ACCENT_ACRYLIC: u32 = 4; +/// `0xAABBGGRR`, nearly clear. The real tint is painted by the page, so a +/// change of accent or theme is a repaint rather than another call here. +const NEARLY_CLEAR_TINT: u32 = 0x10_10_10_10; + +#[repr(C)] +struct AccentPolicy { + state: u32, + flags: u32, + gradient: u32, + animation: u32, +} + +#[repr(C)] +struct CompositionData { + attribute: u32, + data: *mut c_void, + size: usize, +} + +type SetWindowCompositionAttribute = unsafe extern "system" fn(HWND, *mut CompositionData) -> BOOL; + +/// Blurs the desktop behind `hwnd`. Returns whether the blur took; when it did +/// not, the page keeps its opaque background. +pub(crate) fn apply_blur(hwnd: *mut c_void) -> bool { + let hwnd = HWND(hwnd); + // SAFETY: `user32.dll` is always loaded in a GUI process. The export is + // undocumented, so it is looked up rather than linked, and the transmute + // matches its long-stable signature + // `BOOL SetWindowCompositionAttribute(HWND, WINDOWCOMPOSITIONATTRIBDATA*)`. + // `policy` and `data` outlive the call. + unsafe { + let Ok(user32) = GetModuleHandleW(w!("user32.dll")) else { + return false; + }; + let Some(proc) = GetProcAddress(user32, s!("SetWindowCompositionAttribute")) else { + return false; + }; + let set = std::mem::transmute::< + unsafe extern "system" fn() -> isize, + SetWindowCompositionAttribute, + >(proc); + let mut policy = AccentPolicy { + state: ACCENT_ACRYLIC, + flags: 0, + gradient: NEARLY_CLEAR_TINT, + animation: 0, + }; + let mut data = CompositionData { + attribute: ACCENT_POLICY, + data: (&raw mut policy).cast::(), + size: std::mem::size_of::(), + }; + set(hwnd, &mut data).as_bool() + } +} diff --git a/apps/desktop/src-tauri/src/services/capture.rs b/apps/desktop/src-tauri/src/services/capture.rs index 8ce1863..18ec1e2 100644 --- a/apps/desktop/src-tauri/src/services/capture.rs +++ b/apps/desktop/src-tauri/src/services/capture.rs @@ -106,6 +106,8 @@ pub struct CaptureService { manual_scrolling: Mutex>, save_directory: Mutex, save_output_lock: Mutex<()>, + /// What was on screen when the capture started, used to name the saved file. + source_label: Mutex>, #[cfg(test)] render_count: AtomicUsize, #[cfg(test)] @@ -153,6 +155,7 @@ impl CaptureService { manual_scrolling: Mutex::new(HashMap::new()), save_directory: Mutex::new(save_directory), save_output_lock: Mutex::new(()), + source_label: Mutex::new(None), #[cfg(test)] render_count: AtomicUsize::new(0), #[cfg(test)] @@ -224,6 +227,7 @@ impl CaptureService { )); } + self.remember_source_label(); self.targets.begin_session()?; #[cfg(debug_assertions)] let capture_started = Instant::now(); @@ -289,6 +293,7 @@ impl CaptureService { "Screen capture permission is not available".into(), )); } + self.remember_source_label(); let captured = self.capture.capture_display_at_point(cursor)?; match action { CompletionAction::Copy => { @@ -609,6 +614,14 @@ impl CaptureService { } } + /// Records the focused window's title before the capture overlay takes focus. + fn remember_source_label(&self) { + #[cfg(target_os = "windows")] + if let Ok(mut label) = self.source_label.lock() { + *label = crate::platform::windows_foreground::foreground_window_title(); + } + } + fn save_new_image(&self, image: &RgbaImage) -> Result { let _guard = self .save_output_lock @@ -894,7 +907,7 @@ impl CaptureService { }) .collect::>(); files.sort_by_key(|item| Reverse(item.2)); - files.truncate(200); + files.truncate(1000); let thumbnails = session_directory().join("library-thumbnails"); fs::create_dir_all(&thumbnails).map_err(SnaphubError::export)?; @@ -966,7 +979,16 @@ impl CaptureService { fn next_save_path(&self) -> Result { let directory = self.save_directory()?; fs::create_dir_all(&directory).map_err(SnaphubError::export)?; - let stem = format!("CapKit_{}", Local::now().format("%Y-%m-%d_%H-%M-%S-%3f")); + let label = self + .source_label + .lock() + .ok() + .and_then(|label| label.as_deref().and_then(file_name_label)) + .unwrap_or_else(|| "CapKit".into()); + let stem = format!( + "{label}_{}_CapKit", + Local::now().format("%Y-%m-%d_%H-%M-%S-%3f") + ); for suffix in 0..10_000_u32 { let file_name = if suffix == 0 { format!("{stem}.png") @@ -1471,6 +1493,26 @@ fn parse_color(value: &str, opacity: f32) -> Rgba { Rgba([red, green, blue, (opacity.clamp(0.0, 1.0) * 255.0) as u8]) } +/// Turns a window title into a safe file-name prefix, or `None` when nothing is left. +fn file_name_label(title: &str) -> Option { + let cleaned: String = title + .chars() + .map(|character| { + if character.is_control() || "<>:\"/\\|?*".contains(character) { + ' ' + } else { + character + } + }) + .collect(); + let collapsed = cleaned.split_whitespace().collect::>().join(" "); + let shortened: String = collapsed.chars().take(60).collect(); + let trimmed = shortened.trim_matches(|character: char| { + character == '.' || character == '_' || character.is_whitespace() + }); + (!trimmed.is_empty()).then(|| trimmed.to_owned()) +} + fn default_save_directory() -> PathBuf { dirs::picture_dir() .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))) @@ -1508,6 +1550,12 @@ fn legacy_storage_preferences_path() -> PathBuf { fn load_save_directory() -> PathBuf { let current_path = storage_preferences_path(); + if let Some(directory) = read_save_directory(¤t_path) + && let Some(migrated) = migrate_legacy_default_directory(&directory) + { + let _ = persist_save_directory(&migrated); + return migrated; + } let previous_path = previous_snaphub_storage_preferences_path(); let legacy_path = legacy_storage_preferences_path(); for path in [¤t_path, &previous_path, &legacy_path] { @@ -1520,8 +1568,7 @@ fn load_save_directory() -> PathBuf { continue; }; if path != ¤t_path { - if directory == previous_default_save_directory() { - let migrated = default_save_directory(); + if let Some(migrated) = migrate_legacy_default_directory(&directory) { let _ = persist_save_directory(&migrated); return migrated; } @@ -1696,10 +1743,35 @@ mod storage_preferences_tests { } } -fn previous_default_save_directory() -> PathBuf { - dirs::picture_dir() - .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))) - .join("Snaphub") +/// Renames an untouched Snaphub/ShotHub default folder to `CapKit`, so existing +/// captures come along. Returns `None` for any other folder, or when `CapKit` +/// already exists and renaming would merge two libraries. +fn migrate_legacy_default_directory(directory: &Path) -> Option { + let target = default_save_directory(); + let pictures = target.parent()?; + let is_legacy_default = directory.parent() == Some(pictures) + && directory.file_name().is_some_and(|name| { + let name = name.to_string_lossy(); + name.eq_ignore_ascii_case("Snaphub") || name.eq_ignore_ascii_case("ShotHub") + }); + if !is_legacy_default { + return None; + } + if !directory.exists() { + return Some(target); + } + if target.exists() { + return None; + } + fs::rename(directory, &target).ok().map(|()| target) +} + +fn read_save_directory(path: &Path) -> Option { + fs::read_to_string(path) + .ok() + .and_then(|raw| serde_json::from_str::(&raw).ok()) + .map(|preferences| preferences.save_directory) + .filter(|directory| directory.is_absolute()) } fn save_atomic(image: &RgbaImage, destination: &Path) -> Result<(), SnaphubError> { @@ -2021,6 +2093,27 @@ mod tests { }) } + #[test] + fn file_name_label_keeps_readable_titles_and_strips_unsafe_characters() { + assert_eq!( + file_name_label("GitHub: capkit/issues? - Google Chrome").as_deref(), + Some("GitHub capkit issues - Google Chrome") + ); + assert_eq!(file_name_label(" ... "), None); + assert_eq!( + file_name_label(&"a".repeat(200)).map(|name| name.len()), + Some(60) + ); + } + + #[test] + fn legacy_default_folder_is_left_alone_when_it_is_not_a_default_name() { + assert_eq!( + migrate_legacy_default_directory(Path::new("D:/Work/Shots")), + None + ); + } + #[test] fn default_save_directory_uses_capkit_folder() { assert_eq!( diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 24a515f..eb3fca9 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "CapKit", - "version": "0.4.0", + "version": "0.5.0", "identifier": "com.snaphub.desktop", "build": { "beforeDevCommand": "pnpm dev", @@ -21,8 +21,8 @@ "minWidth": 900, "minHeight": 640, "center": true, - "decorations": true, - "transparent": false, + "decorations": false, + "transparent": true, "resizable": true, "skipTaskbar": false, "focus": true diff --git a/apps/desktop/src/components/OnScreenOverlay.tsx b/apps/desktop/src/components/OnScreenOverlay.tsx index 2171f9c..0a8c214 100644 --- a/apps/desktop/src/components/OnScreenOverlay.tsx +++ b/apps/desktop/src/components/OnScreenOverlay.tsx @@ -1303,7 +1303,7 @@ function PointerLayer({ function OnScreenSvgObject({ object }: { object: OnScreenObject }): React.JSX.Element | null { if (object.kind === "blur") return null; if (object.kind === "text") { - return {object.text}; + return {object.text}; } if (object.kind === "pencil") { return ; diff --git a/apps/desktop/src/components/dashboard/BrowserExtensionSettings.test.tsx b/apps/desktop/src/components/dashboard/BrowserExtensionSettings.test.tsx index f4e0323..0d4196a 100644 --- a/apps/desktop/src/components/dashboard/BrowserExtensionSettings.test.tsx +++ b/apps/desktop/src/components/dashboard/BrowserExtensionSettings.test.tsx @@ -97,8 +97,8 @@ describe("BrowserExtensionSettings", () => { }); render(); - expect(await screen.findByText("Connected · Chrome 130")).toBeVisible(); - expect(screen.getByText("Connected · Aside 2.1")).toBeVisible(); + expect(await screen.findByText("Connected to Chrome 130")).toBeVisible(); + expect(screen.getByText("Connected to Aside 2.1")).toBeVisible(); }); it("shows the switch description and copies the load-unpacked steps", async () => { @@ -123,7 +123,7 @@ describe("BrowserExtensionSettings", () => { tauri.forgetBrowser.mockResolvedValue(listening); render(); - expect(await screen.findByText(/Connected · chrome-extension/)).toBeVisible(); + expect(await screen.findByText(/Connected, chrome-extension/)).toBeVisible(); fireEvent.click(screen.getByRole("button", { name: "Forget Chrome" })); expect(tauri.forgetBrowser).not.toHaveBeenCalled(); expect(screen.getByText("Forget Chrome? It will need a new code.")).toBeVisible(); diff --git a/apps/desktop/src/components/dashboard/BrowserExtensionSettings.tsx b/apps/desktop/src/components/dashboard/BrowserExtensionSettings.tsx index ef85e77..780dad0 100644 --- a/apps/desktop/src/components/dashboard/BrowserExtensionSettings.tsx +++ b/apps/desktop/src/components/dashboard/BrowserExtensionSettings.tsx @@ -10,9 +10,10 @@ import { type BrowserLinkStatus, type PairingCode, } from "../../lib/tauri"; - -const buttonClass = - "shrink-0 rounded-md border border-stone-300 bg-stone-50 px-3 py-1.5 text-[12px] font-semibold text-stone-700 outline-none transition hover:border-stone-500 focus-visible:ring-2 focus-visible:ring-[var(--snaphub-accent)] disabled:cursor-not-allowed disabled:opacity-60 dark:border-white/10 dark:bg-[#333431] dark:text-stone-300 dark:hover:border-white/20"; +import { Copy, Tick as Check } from "../icons"; +import { Button } from "../ui/Button"; +import { SettingRow } from "../ui/SettingRow"; +import { Switch } from "../ui/Switch"; /** Whole seconds left until `expiresAt`, never below zero. */ export function secondsUntil(expiresAt: string, now: number): number { @@ -26,7 +27,7 @@ function describeState(status: BrowserLinkStatus): string[] { if (!status.enabled) return ["Off. Nothing is listening."]; if (status.state === "error") return [status.error ?? "Could not start the browser link."]; if (status.connected.length > 0) { - return status.connected.map((browser) => `Connected · ${browser.name} ${browser.version}`); + return status.connected.map((browser) => `Connected to ${browser.name} ${browser.version}`); } return [status.port === null ? "Starting…" : "Waiting for the extension"]; } @@ -145,76 +146,66 @@ export function BrowserExtensionSettings(): React.JSX.Element { return (
- + + void toggle(next)} /> + {status === null ? null : ( -
- {describeState(status).map((line) =>

{line}

)} +
+ {describeState(status).map((line) => ( +

+

+ ))}
)} {enabled && status?.state === "listening" ? ( -
+
{pairing === null || codeExpired || locked ? (
-

+

{locked ? "Too many wrong codes. Generate a new code." : codeExpired ? "Code expired" : "Pair a browser by entering a one-time code in the extension."}

- +
) : (
-

Enter this code in the extension popup

-

{`${pairing.code.slice(0, 3)} ${pairing.code.slice(3)}`}

-

Expires in {formatCountdown(remaining)}

+

Enter this code in the extension popup

+

{`${pairing.code.slice(0, 3)} ${pairing.code.slice(3)}`}

+

Expires in {formatCountdown(remaining)}

- +
)}
) : null} {status !== null && status.paired.length > 0 ? ( -
    +
      {status.paired.map((entry) => { const isConnected = status.connected.some((browser) => browser.name === entry.browser.name); return (
    • -

      {entry.browser.name} {entry.browser.version}

      -

      {isConnected ? "Connected" : "Not connected"} · {entry.origin}

      +

      {entry.browser.name} {entry.browser.version}

      +

      {isConnected ? "Connected" : "Not connected"}, {entry.origin}

      {confirmingForget === entry.origin ? (
      -

      Forget {entry.browser.name}? It will need a new code.

      - - +

      Forget {entry.browser.name}? It will need a new code.

      + +
      ) : ( - + )}
    • ); @@ -222,15 +213,21 @@ export function BrowserExtensionSettings(): React.JSX.Element {
    ) : null} -
    +
    -

    Get the extension

    -

    {EXTENSION_STEPS}

    +

    Get the extension

    +

    {EXTENSION_STEPS}

    - +
    - {message === null ? null :

    {message}

    } + {message === null ? null :

    {message}

    }
    ); } diff --git a/apps/desktop/src/components/dashboard/CapKitLogo.tsx b/apps/desktop/src/components/dashboard/CapKitLogo.tsx new file mode 100644 index 0000000..de4d9e9 --- /dev/null +++ b/apps/desktop/src/components/dashboard/CapKitLogo.tsx @@ -0,0 +1,28 @@ +/** + * The CapKit app mark, identical to `src-tauri/icons/icon.svg`. Brand art keeps + * its own fixed colours, so it ignores the theme tokens and reads the same in + * light and dark. + */ +export function CapKitLogo({ size = 28 }: { size?: number }): React.JSX.Element { + return ( + + ); +} diff --git a/apps/desktop/src/components/dashboard/DashboardPanel.test.tsx b/apps/desktop/src/components/dashboard/DashboardPanel.test.tsx index 6907ccd..13e2331 100644 --- a/apps/desktop/src/components/dashboard/DashboardPanel.test.tsx +++ b/apps/desktop/src/components/dashboard/DashboardPanel.test.tsx @@ -17,14 +17,14 @@ describe("DashboardPanel", () => { it("shows the app version and commit in the sidebar", async () => { render(); - expect(await screen.findByText(/v0\.2\.0 ·/)).toBeVisible(); + expect(await screen.findByText("v0.2.0")).toBeVisible(); }); it("opens on the screenshots dashboard", async () => { render(); expect(await screen.findByRole("heading", { name: "Screenshots" })).toBeVisible(); - expect(screen.getByText("Only images explicitly saved by Capkit appear here. Clipboard-only captures stay private and unindexed.")).toBeVisible(); + expect(screen.getByRole("heading", { level: 1, name: "Screenshots" })).toBeVisible(); expect(screen.getByRole("navigation", { name: "Capkit sections" })).toBeVisible(); }); @@ -32,12 +32,12 @@ describe("DashboardPanel", () => { render(); expect(screen.queryByRole("button", { name: "Open Cloud" })).toBeNull(); - expect(screen.getByRole("button", { name: "Open Record" })).toBeVisible(); + expect(screen.getByRole("button", { name: "Open Screen record" })).toBeVisible(); // Studio is reached from a recording, so it is no longer a section. expect(screen.queryByRole("button", { name: "Open Studio" })).toBeNull(); }); - it("orders the sidebar Screenshots, Showcase, Record, then Settings", () => { + it("groups the sidebar: Screenshots and Screen record, then Studio, then Settings", () => { render(); const nav = screen.getByRole("navigation", { name: "Capkit sections" }); @@ -46,14 +46,14 @@ describe("DashboardPanel", () => { within(nav) .getAllByRole("button") .map((button) => button.getAttribute("aria-label")), - ).toEqual(["Open Screenshots", "Open Showcase", "Open Record", "Open Settings"]); + ).toEqual(["Open Screenshots", "Open Screen record", "Open Showcase", "Open Settings"]); }); - it("opens the recorder from Record", async () => { + it("opens the recorder from Screen record", async () => { render(); - fireEvent.click(screen.getByRole("button", { name: "Open Record" })); - expect(await screen.findByRole("heading", { name: "Capture your screen." })).toBeVisible(); + fireEvent.click(screen.getByRole("button", { name: "Open Screen record" })); + expect(await screen.findByRole("heading", { name: "Screen record" })).toBeVisible(); expect(screen.getByRole("button", { name: "Start recording" })).toBeVisible(); expect(screen.queryByRole("heading", { name: "Screenshots" })).not.toBeInTheDocument(); }); @@ -72,7 +72,7 @@ describe("DashboardPanel", () => { render(); openSettings(); selectTab("Screenshots"); - openSection("Colors & default size"); + openSection("Colors and size"); expect(screen.getByText("5 / 5 selected")).toBeVisible(); expect(screen.getByRole("button", { name: "Add #39ff88" })).toBeDisabled(); @@ -82,20 +82,17 @@ describe("DashboardPanel", () => { render(); openSettings(); - fireEvent.click(screen.getByRole("button", { name: "Use dark mode" })); + fireEvent.click(screen.getByRole("button", { name: "Switch to dark mode" })); expect(document.documentElement).toHaveClass("dark"); - expect(screen.getByRole("button", { name: "Use dark mode" })).toHaveAttribute( - "aria-pressed", - "true", - ); + expect(screen.getByRole("button", { name: "Switch to light mode" })).toBeVisible(); }); it("shows a color marker for every default-color option", () => { render(); openSettings(); selectTab("Screenshots"); - openSection("Colors & default size"); + openSection("Colors and size"); fireEvent.click(screen.getByRole("button", { name: "Default annotation color" })); @@ -104,27 +101,39 @@ describe("DashboardPanel", () => { expect(within(colorList).getByRole("option", { name: "#D9FF43" })).toBeVisible(); }); - it("provides a reset action for every settings section", () => { + it("offers a section reset only once a section differs from its default", () => { render(); openSettings(); - // Every section now sits behind a tab, so the resets are counted the way - // they are met: one tab at a time, with each section opened. - let resets = 0; - for (const tab of Object.keys(sectionTitles) as (keyof typeof sectionTitles)[]) { - selectTab(tab); - for (const section of sectionTitles[tab]) openSection(section); - resets += screen.getAllByRole("button", { name: "Reset this section" }).length; - } + // At defaults only the two folder cards can be reset (their default is native). + expect(screen.getAllByRole("button", { name: "Reset this section" })).toHaveLength(2); - expect(resets).toBe(12); + openSection("Accent and glass"); + expect(within(sectionOf("Accent and glass")).queryByRole("button", { name: "Reset this section" })).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Use #39ff88 as theme accent" })); + fireEvent.click(within(sectionOf("Accent and glass")).getByRole("button", { name: "Reset this section" })); + expect(within(sectionOf("Accent and glass")).queryByRole("button", { name: "Reset this section" })).toBeNull(); + }); + + it("drives the page glass from the Glass strength slider and resets it with the section", () => { + render(); + openSettings(); + openSection("Accent and glass"); + + const slider = screen.getByRole("slider", { name: "Glass strength" }); + expect(slider).toHaveValue("50"); + fireEvent.change(slider, { target: { value: "80" } }); + expect(document.documentElement.style.getPropertyValue("--glass-strength")).toBe("0.8"); + + fireEvent.click(within(sectionOf("Accent and glass")).getByRole("button", { name: "Reset this section" })); + expect(screen.getByRole("slider", { name: "Glass strength" })).toHaveValue("50"); }); it("provides inline resets for overlay tint and individual shortcuts", () => { render(); openSettings(); selectTab("Screenshots"); - openSection("Detection & overlay"); + openSection("Detection and overlay"); expect(screen.getByRole("button", { name: "Reset overlay tint" })).toBeDisabled(); @@ -203,11 +212,11 @@ describe("DashboardPanel", () => { render(); openSettings(); selectTab("Screenshots"); - openSection("Default capture method"); + openSection("Scrolling capture"); - expect(screen.getByRole("radio", { name: "Use Automatic scrolling capture" })).toHaveAttribute("aria-checked", "true"); - fireEvent.click(screen.getByRole("radio", { name: "Use Always ask scrolling capture" })); - expect(screen.getByRole("radio", { name: "Use Always ask scrolling capture" })).toHaveAttribute("aria-checked", "true"); + expect(screen.getByRole("radio", { name: "Automatic" })).toHaveAttribute("aria-checked", "true"); + fireEvent.click(screen.getByRole("radio", { name: "Ask every time" })); + expect(screen.getByRole("radio", { name: "Ask every time" })).toHaveAttribute("aria-checked", "true"); }); it("leaves shortcut recording mode when its inline reset is pressed", () => { @@ -219,7 +228,7 @@ describe("DashboardPanel", () => { const resetShortcut = screen.getByRole("button", { name: "Reset Start capture shortcut" }); fireEvent.click(configureShortcut); - expect(configureShortcut).toHaveTextContent("Press shortcut…"); + expect(configureShortcut).toHaveTextContent("Press keys…"); expect(resetShortcut).toBeEnabled(); fireEvent.click(resetShortcut); @@ -233,10 +242,14 @@ describe("DashboardPanel", () => { selectTab("Shortcuts"); const configureShortcut = screen.getByRole("button", { name: "Configure Start capture" }); - const shortcutsHeading = screen.getByRole("heading", { name: "Shortcuts" }); + const shortcutsHeading = screen.getByRole("heading", { name: /^Global shortcuts/ }); const shortcutsSection = shortcutsHeading.closest("section"); if (shortcutsSection === null) throw new Error("Shortcuts heading must be inside a section"); + // The section reset only appears once a shortcut differs from its default. + fireEvent.click(configureShortcut); + fireEvent.keyDown(window, { key: "k", ctrlKey: true }); + expect(configureShortcut).toHaveTextContent("Ctrl+K"); fireEvent.click(configureShortcut); fireEvent.click(within(shortcutsSection).getByRole("button", { name: "Reset this section" })); @@ -285,7 +298,7 @@ describe("DashboardPanel", () => { fireEvent.click(configure); fireEvent.keyDown(window, { key: "a", ctrlKey: true }); - expect(configure).toHaveTextContent("Press shortcut…"); + expect(configure).toHaveTextContent("Press keys…"); expect(configure).toHaveAttribute("aria-pressed", "true"); }); @@ -339,11 +352,13 @@ describe("DashboardPanel", () => { for (const tab of Object.keys(sectionTitles) as (keyof typeof sectionTitles)[]) { selectTab(tab); - expect(sectionHeadings()).toEqual(sectionTitles[tab]); + // Open at startup is a single control, so it is a row, not an expandable card. + const expected = tab === "General" ? ["Open at startup", ...sectionTitles[tab]] : sectionTitles[tab]; + expect(sectionHeadings()).toEqual(expected); } selectTab("Screenshots"); - openSection("Detection & overlay"); + openSection("Detection and overlay"); expect(screen.queryByRole("switch", { name: "Open at startup" })).toBeNull(); }); @@ -363,10 +378,10 @@ describe("DashboardPanel", () => { // Opening a second section leaves the first one open. selectTab("Screenshots"); - openSection("Colors & default size"); - expect(sectionHeader("Choose what stays within reach")).toHaveAttribute("aria-expanded", "true"); - expect(sectionHeader("Colors & default size")).toHaveAttribute("aria-expanded", "true"); - expect(sectionHeader("Detection & overlay")).toHaveAttribute("aria-expanded", "false"); + openSection("Colors and size"); + expect(sectionHeader("Capture toolbar")).toHaveAttribute("aria-expanded", "true"); + expect(sectionHeader("Colors and size")).toHaveAttribute("aria-expanded", "true"); + expect(sectionHeader("Detection and overlay")).toHaveAttribute("aria-expanded", "false"); }); it("cancels shortcut recording when the section holding it collapses", () => { @@ -376,12 +391,12 @@ describe("DashboardPanel", () => { const configure = screen.getByRole("button", { name: "Configure Start capture" }); fireEvent.click(configure); - expect(configure).toHaveTextContent("Press shortcut…"); + expect(configure).toHaveTextContent("Press keys…"); - fireEvent.click(sectionHeader("Shortcuts")); - expect(sectionHeader("Shortcuts")).toHaveAttribute("aria-expanded", "false"); + fireEvent.click(sectionHeader("Global shortcuts")); + expect(sectionHeader("Global shortcuts")).toHaveAttribute("aria-expanded", "false"); - fireEvent.click(sectionHeader("Shortcuts")); + fireEvent.click(sectionHeader("Global shortcuts")); expect(screen.getByRole("button", { name: "Configure Start capture" })).toHaveAttribute( "aria-pressed", "false", @@ -391,16 +406,16 @@ describe("DashboardPanel", () => { /** Section titles per tab, in the order each tab shows them. */ const sectionTitles = { - General: ["Open at startup", "Keep CapKit current", "Theme accent", "Saved captures", "Saved recordings"], + General: ["Updates", "Accent and glass", "Screenshot folder", "Recording folder"], Screenshots: [ - "Choose what stays within reach", - "Colors & default size", - "Detection & overlay", + "Capture toolbar", + "Colors and size", + "Detection and overlay", "Capture cursor", - "Default capture method", + "Scrolling capture", ], - "Screen Draw": ["On-screen toolbar"], - Shortcuts: ["Shortcuts"], + "Screen Draw": ["Screen Draw"], + Shortcuts: ["Global shortcuts"], } as const; function openSettings(): void { @@ -415,12 +430,12 @@ function selectTab(label: string): void { function sectionHeadings(): readonly (string | null)[] { return within(screen.getByRole("tabpanel")) .getAllByRole("heading", { level: 2 }) - .map((heading) => heading.textContent); + .map((heading) => heading.querySelector("button > span")?.textContent ?? heading.textContent); } /** The disclosure control of the section carrying this heading. */ function sectionHeader(title: string): HTMLElement { - const heading = screen.getByRole("heading", { name: title }); + const heading = screen.getByRole("heading", { name: new RegExp(`^${title}`) }); const section = heading.closest("section"); if (section === null) throw new Error(`The ${title} heading must be inside a section`); const header = section.querySelector("button[aria-expanded]"); @@ -428,6 +443,12 @@ function sectionHeader(title: string): HTMLElement { return header; } +function sectionOf(title: string): HTMLElement { + const section = screen.getByRole("heading", { name: new RegExp(`^${title}`) }).closest("section"); + if (section === null) throw new Error(`The ${title} heading must be inside a section`); + return section; +} + function openSection(title: string): void { const header = sectionHeader(title); if (header.getAttribute("aria-expanded") === "false") fireEvent.click(header); diff --git a/apps/desktop/src/components/dashboard/DashboardPanel.tsx b/apps/desktop/src/components/dashboard/DashboardPanel.tsx index d799d3b..921da8d 100644 --- a/apps/desktop/src/components/dashboard/DashboardPanel.tsx +++ b/apps/desktop/src/components/dashboard/DashboardPanel.tsx @@ -1,8 +1,11 @@ import { getVersion } from "@tauri-apps/api/app"; import { invoke, isTauri } from "@tauri-apps/api/core"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { useSnaphubSettings } from "../../domain/settings"; -import { getBrowserLinkStatus, listSavedCaptures, setBrowserLinkAccent, listenForBrowserLinkStatus, listenForShowcaseRequest, takePendingShowcase, updateGlobalShortcuts } from "../../lib/tauri"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import { CapKitLogo } from "./CapKitLogo"; +import { DashboardTitleBar } from "./DashboardTitleBar"; +import { dashboardSupportsGlass, getBrowserLinkStatus, listSavedCaptures, setBrowserLinkAccent, listenForBrowserLinkStatus, listenForShowcaseRequest, takePendingShowcase, updateGlobalShortcuts } from "../../lib/tauri"; import { NotesView } from "./NotesView"; import { SettingsView } from "./SettingsView"; import { UpdateNotice } from "./UpdateNotice"; @@ -14,26 +17,42 @@ import { findSavedCapture, type SavedCapture } from "../../domain/capture"; import { Image, Moon, - NotePin, Presentation, Record, - Scan as ScanLine, Settings, + StickyNote, Sun, } from "../icons"; type DashboardTab = "screenshots" | "notes" | "showcase" | "record" | "settings"; -const navigation = [ - { id: "screenshots", label: "Screenshots", icon: Image }, - { id: "notes", label: "Notes", icon: NotePin }, - { id: "showcase", label: "Showcase", icon: Presentation }, - { id: "record", label: "Record", icon: Record }, - { id: "settings", label: "Settings", icon: Settings }, -] as const satisfies readonly { id: DashboardTab; label: string; icon: typeof Settings }[]; +type NavigationItem = { id: DashboardTab; label: string; icon: typeof Settings }; +type NavigationGroup = { heading?: string; hasDivider?: boolean; items: readonly NavigationItem[] }; + +/** Capture things first, then the studio that edits them, then settings apart at the end. */ +const navigationGroups: readonly NavigationGroup[] = [ + { + items: [ + { id: "screenshots", label: "Screenshots", icon: Image }, + { id: "record", label: "Screen record", icon: Record }, + { id: "notes", label: "Page notes", icon: StickyNote }, + ], + }, + { heading: "Studio", items: [{ id: "showcase", label: "Showcase", icon: Presentation }] }, + { hasDivider: true, items: [{ id: "settings", label: "Settings", icon: Settings }] }, +]; + +function navPillStyle(position: { top: number; height: number } | undefined): React.CSSProperties { + return position === undefined + ? { height: 0 } + : { height: `${String(position.height)}px`, transform: `translateY(${String(position.top)}px)` }; +} export function DashboardPanel(): React.JSX.Element { const [activeTab, setActiveTab] = useState("screenshots"); + const [hoveredTab, setHoveredTab] = useState(null); + const [navPositions, setNavPositions] = useState>>({}); + const navButtons = useRef(new Map()); const [showcaseCapture, setShowcaseCapture] = useState(null); const [isShowcaseStylePending, setIsShowcaseStylePending] = useState(false); const [version, setVersion] = useState(null); @@ -130,95 +149,169 @@ export function DashboardPanel(): React.JSX.Element { settings.shortcuts.onScreenToggle, ]); + // Glass needs the Windows compositor blur; elsewhere the page keeps its opaque base colour. + useEffect(() => { + document.body.classList.add("dashboard-surface"); + let cancelled = false; + void dashboardSupportsGlass() + .then((supported) => { + if (!cancelled) document.documentElement.classList.toggle("glass", supported); + }) + .catch(() => undefined); + return (): void => { + cancelled = true; + document.body.classList.remove("dashboard-surface"); + document.documentElement.classList.remove("glass"); + }; + }, []); + + // Keeps the native theme in step (webview colour scheme, system menus). + useEffect(() => { + if (!isTauri()) return; + void getCurrentWindow().setTheme(settings.appearance).catch((error: unknown) => { + console.error("CK-WINDOW-THEME-001", error); + }); + }, [settings.appearance]); + + /** Snaps the page for one frame so the theme swap never smears through transitions. */ + function changeAppearance(appearance: "light" | "dark"): void { + const root = document.documentElement; + root.classList.add("dark-dashboard-swap"); + updateSettings({ ...settings, appearance }); + window.requestAnimationFrame(() => { + window.requestAnimationFrame(() => root.classList.remove("dark-dashboard-swap")); + }); + } + + const visibleGroups = navigationGroups + .map((group) => ({ ...group, items: group.items.filter((item) => item.id !== "notes" || developerTools) })) + .filter((group) => group.items.length > 0); + useLayoutEffect(() => { + const next: Partial> = {}; + for (const [id, button] of navButtons.current) next[id] = { top: button.offsetTop, height: button.offsetHeight }; + setNavPositions(next); + }, [developerTools]); + + const nextAppearance = settings.appearance === "dark" ? "light" : "dark"; + const ThemeIcon = settings.appearance === "dark" ? Sun : Moon; + return ( -
    -