fix(window): align macOS traffic light controls

This commit is contained in:
zipg authored and GitHub committed 2026-07-13 00:04:27 +08:00
1 parent 4b44ccf86e
commit 823b4297d8
7 files changed
+238 -6

No files matched your search

@@ -1,13 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, onMounted, onBeforeUnmount, h, nextTick, watch } from "vue"; import { computed, ref, onMounted, onBeforeUnmount, h, nextTick, watch } from "vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import { invoke } from "@tauri-apps/api/core";
import { DatabaseZap, FilePlus2, Loader2, Moon, Sun, SunMoon, History, Bot, ArrowLeftRight, FileCode, BookMarked, GitCompareArrows, TableProperties, Settings, CloudDownload, Package, FileDown, FolderTree } from "@lucide/vue"; import { DatabaseZap, FilePlus2, Loader2, Moon, Sun, SunMoon, History, Bot, ArrowLeftRight, FileCode, BookMarked, GitCompareArrows, TableProperties, Settings, CloudDownload, Package, FileDown, FolderTree } from "@lucide/vue";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import LightDropdown from "@/components/ui/LightDropdown.vue"; import LightDropdown from "@/components/ui/LightDropdown.vue";
import WindowControls from "@/components/layout/WindowControls.vue"; import WindowControls from "@/components/layout/WindowControls.vue";
import ExportProgressPopover from "@/components/export/ExportProgressPopover.vue"; import ExportProgressPopover from "@/components/export/ExportProgressPopover.vue";
import { shouldReserveMacTrafficLightInset, useWindowControls } from "@/composables/useWindowControls"; import { MAC_TRAFFIC_LIGHT_X, macTrafficLightInsetPaddingForScale, shouldReserveMacTrafficLightInset, useWindowControls } from "@/composables/useWindowControls";
import { useToast } from "@/composables/useToast"; import { useToast } from "@/composables/useToast";
import { useSettingsStore } from "@/stores/settingsStore"; import { useSettingsStore } from "@/stores/settingsStore";
import { isSystemAppThemeMode, type AppThemeMode } from "@/lib/app/appTheme"; import { isSystemAppThemeMode, type AppThemeMode } from "@/lib/app/appTheme";
@@ -95,7 +96,9 @@ function onToolbarDblClick(e: MouseEvent) {
} }
const toolbarEl = ref<HTMLElement>(); const toolbarEl = ref<HTMLElement>();
const newConnectionLabelEl = ref<HTMLElement>();
const toolbarCollapsed = ref(false); const toolbarCollapsed = ref(false);
const shouldReserveTrafficLightInset = computed(() => shouldReserveMacTrafficLightInset(isMac, isFullscreen.value, isDesktop));
function checkToolbarWidth() { function checkToolbarWidth() {
const el = toolbarEl.value; const el = toolbarEl.value;
@@ -110,8 +113,18 @@ function checkToolbarWidth() {
const rightWrapper = ref<HTMLElement>(); const rightWrapper = ref<HTMLElement>();
const rightOverflowCount = ref(0); const rightOverflowCount = ref(0);
let toolbarLayoutRaf = 0; let toolbarLayoutRaf = 0;
let trafficLightSyncRaf = 0;
let settlingRightOverflow = false; let settlingRightOverflow = false;
let pendingRightOverflowSettle = false; let pendingRightOverflowSettle = false;
const measuredTrafficLightInset = ref<number | null>(null);
type MacosTrafficLightLayout = {
x: number;
y: number;
center_y: number;
previous_center_y: number;
reserved_inset: number;
};
/** Ordered list of right-side item keys that can overflow into "More". /** Ordered list of right-side item keys that can overflow into "More".
* Items earlier in the list overflow first when space shrinks. */ * Items earlier in the list overflow first when space shrinks. */
@@ -274,15 +287,53 @@ function scheduleToolbarLayout() {
toolbarLayoutRaf = requestAnimationFrame(() => { toolbarLayoutRaf = requestAnimationFrame(() => {
toolbarLayoutRaf = 0; toolbarLayoutRaf = 0;
checkToolbarWidth(); checkToolbarWidth();
scheduleTrafficLightSync();
void settleRightOverflow(); void settleRightOverflow();
}); });
} }
function scheduleTrafficLightSync() {
if (!shouldReserveTrafficLightInset.value) return;
if (trafficLightSyncRaf) cancelAnimationFrame(trafficLightSyncRaf);
trafficLightSyncRaf = requestAnimationFrame(() => {
trafficLightSyncRaf = 0;
void syncTrafficLightsToToolbar();
});
}
async function syncTrafficLightsToToolbar() {
if (!shouldReserveTrafficLightInset.value) return;
const toolbarRect = toolbarEl.value?.getBoundingClientRect();
const targetEl = newConnectionLabelEl.value;
const targetRect = targetEl?.getBoundingClientRect();
if (!toolbarRect || !targetRect) return;
const targetCenterY = targetRect.top - toolbarRect.top + targetRect.height / 2;
try {
const layout = await invoke<MacosTrafficLightLayout>("set_macos_traffic_light_position", {
x: MAC_TRAFFIC_LIGHT_X,
y: targetCenterY,
scale: settingsStore.editorSettings.uiScale,
});
measuredTrafficLightInset.value = Math.ceil(layout.reserved_inset / settingsStore.editorSettings.uiScale);
} catch (error) {
console.warn("[DBX] Failed to sync macOS traffic light position", { targetCenterY, error });
}
}
function handleWindowResize() { function handleWindowResize() {
scheduleToolbarLayout(); scheduleToolbarLayout();
} }
watch(collapsibleRightItemDefs, () => scheduleToolbarLayout(), { flush: "post" }); watch(collapsibleRightItemDefs, () => scheduleToolbarLayout(), { flush: "post" });
watch(
() => settingsStore.editorSettings.uiScale,
() => {
measuredTrafficLightInset.value = null;
scheduleToolbarLayout();
window.setTimeout(scheduleTrafficLightSync, 120);
},
);
watch(shouldReserveTrafficLightInset, () => scheduleToolbarLayout());
// ──────────── Resize observer ──────────── // ──────────── Resize observer ────────────
@@ -298,6 +349,7 @@ onMounted(() => {
onBeforeUnmount(() => { onBeforeUnmount(() => {
if (toolbarLayoutRaf) cancelAnimationFrame(toolbarLayoutRaf); if (toolbarLayoutRaf) cancelAnimationFrame(toolbarLayoutRaf);
if (trafficLightSyncRaf) cancelAnimationFrame(trafficLightSyncRaf);
resizeObserver?.disconnect(); resizeObserver?.disconnect();
window.removeEventListener("resize", handleWindowResize); window.removeEventListener("resize", handleWindowResize);
}); });
@@ -417,13 +469,21 @@ function isRightItemVisible(key: string) {
const toolbarTextButtonClass = "h-8 px-2 text-xs gap-1 leading-none"; const toolbarTextButtonClass = "h-8 px-2 text-xs gap-1 leading-none";
const toolbarTextLabelClass = "inline-flex translate-y-px items-center leading-none"; const toolbarTextLabelClass = "inline-flex translate-y-px items-center leading-none";
const toolbarDropdownTriggerClass = `inline-flex h-8 items-center gap-1 rounded-[6px] px-2 text-xs font-medium leading-none hover:bg-muted hover:text-foreground dark:hover:bg-muted/50 transition-colors [&>span:first-child]:translate-y-px`; const toolbarDropdownTriggerClass = `inline-flex h-8 items-center gap-1 rounded-[6px] px-2 text-xs font-medium leading-none hover:bg-muted hover:text-foreground dark:hover:bg-muted/50 transition-colors [&>span:first-child]:translate-y-px`;
const toolbarStyle = computed(() => {
if (!shouldReserveTrafficLightInset.value) return undefined;
return {
paddingLeft: `${measuredTrafficLightInset.value ?? parseInt(macTrafficLightInsetPaddingForScale(settingsStore.editorSettings.uiScale), 10)}px`,
};
});
</script> </script>
<template> <template>
<div ref="toolbarEl" class="app-toolbar h-10 flex items-center gap-1 px-2 border-b bg-muted/30 shrink-0 overflow-hidden" :class="{ 'pl-17.5': shouldReserveMacTrafficLightInset(isMac, isFullscreen, isDesktop) }" data-tauri-drag-region @dblclick="onToolbarDblClick"> <div ref="toolbarEl" class="app-toolbar h-10 flex items-center gap-1 px-2 border-b bg-muted/30 shrink-0 overflow-hidden" :style="toolbarStyle" data-tauri-drag-region @dblclick="onToolbarDblClick">
<Button variant="ghost" size="sm" :class="toolbarTextButtonClass" @click="emit('new-connection')"> <Button variant="ghost" size="sm" :class="toolbarTextButtonClass" @click="emit('new-connection')">
<DatabaseZap class="h-3.5 w-3.5" /> <span class="inline-flex items-center gap-1">
<span :class="toolbarTextLabelClass">{{ t("toolbar.newConnection") }}</span> <DatabaseZap class="h-3.5 w-3.5" />
<span ref="newConnectionLabelEl" :class="toolbarTextLabelClass">{{ t("toolbar.newConnection") }}</span>
</span>
</Button> </Button>
<Button variant="ghost" size="sm" :class="toolbarTextButtonClass" @click="emit('new-query')" :disabled="!hasConnections"> <Button variant="ghost" size="sm" :class="toolbarTextButtonClass" @click="emit('new-query')" :disabled="!hasConnections">
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { shouldDrawDesktopWindowFrame, shouldReserveMacTrafficLightInset, shouldShowWindowControls } from "@/composables/useWindowControls"; import { macTrafficLightInsetPaddingForScale, macTrafficLightPositionForScale, shouldDrawDesktopWindowFrame, shouldReserveMacTrafficLightInset, shouldShowWindowControls } from "@/composables/useWindowControls";
describe("window controls", () => { describe("window controls", () => {
it("shows custom controls for non-macOS desktop windows", () => { it("shows custom controls for non-macOS desktop windows", () => {
@@ -26,4 +26,17 @@ describe("window controls", () => {
expect(shouldReserveMacTrafficLightInset(false, false, true)).toBe(false); expect(shouldReserveMacTrafficLightInset(false, false, true)).toBe(false);
expect(shouldReserveMacTrafficLightInset(true, false, false)).toBe(false); expect(shouldReserveMacTrafficLightInset(true, false, false)).toBe(false);
}); });
it("keeps the macOS traffic light reserve visually stable across UI scales", () => {
expect(macTrafficLightInsetPaddingForScale(1)).toBe("70px");
expect(macTrafficLightInsetPaddingForScale(0.9)).toBe("78px");
expect(macTrafficLightInsetPaddingForScale(1.25)).toBe("56px");
});
it("adjusts macOS traffic lights vertically with the UI scale", () => {
expect(macTrafficLightPositionForScale(1)).toEqual({ x: 16, y: 18 });
expect(macTrafficLightPositionForScale(0.9)).toEqual({ x: 16, y: 16 });
expect(macTrafficLightPositionForScale(1.1)).toEqual({ x: 16, y: 20 });
expect(macTrafficLightPositionForScale(1.25)).toEqual({ x: 16, y: 23 });
});
}); });
@@ -3,6 +3,30 @@ import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { isMacOS } from "@/lib/backend/platform"; import { isMacOS } from "@/lib/backend/platform";
import * as api from "@/lib/backend/api"; import * as api from "@/lib/backend/api";
const MIN_UI_SCALE = 0.75;
const MAX_UI_SCALE = 2;
export const MAC_TRAFFIC_LIGHT_X = 16;
export const MAC_TRAFFIC_LIGHT_BASE_Y = 18;
const MAC_TRAFFIC_LIGHT_SCALE_DELTA_Y = 20;
const MAC_TRAFFIC_LIGHT_RESERVED_INSET = 70;
function normalizeTrafficLightUiScale(scale: number): number {
return Number.isFinite(scale) ? Math.min(MAX_UI_SCALE, Math.max(MIN_UI_SCALE, scale)) : 1;
}
export function macTrafficLightPositionForScale(scale: number): { x: number; y: number } {
const normalizedScale = normalizeTrafficLightUiScale(scale);
return {
x: MAC_TRAFFIC_LIGHT_X,
y: Math.round(MAC_TRAFFIC_LIGHT_BASE_Y + (normalizedScale - 1) * MAC_TRAFFIC_LIGHT_SCALE_DELTA_Y),
};
}
export function macTrafficLightInsetPaddingForScale(scale: number): string {
const normalizedScale = normalizeTrafficLightUiScale(scale);
return `${Math.ceil(MAC_TRAFFIC_LIGHT_RESERVED_INSET / normalizedScale)}px`;
}
export function shouldReserveMacTrafficLightInset(isMac: boolean, isFullscreen: boolean, isDesktop = true): boolean { export function shouldReserveMacTrafficLightInset(isMac: boolean, isFullscreen: boolean, isDesktop = true): boolean {
return isDesktop && isMac && !isFullscreen; return isDesktop && isMac && !isFullscreen;
} }
+1 -1
View File
@@ -64,7 +64,7 @@ tauri-plugin-clipboard-manager = "2.3.2"
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
objc2 = { version = "0.6.4", default-features = false, features = ["std"] } objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSApplication", "NSImage"] } objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSApplication", "NSButton", "NSControl", "NSImage", "NSResponder", "NSView", "NSWindow"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["NSData"] } objc2-foundation = { version = "0.3.2", default-features = false, features = ["NSData"] }
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
+1
View File
@@ -45,5 +45,6 @@ pub mod text_export;
pub mod transfer; pub mod transfer;
pub mod tunnel_profiles; pub mod tunnel_profiles;
pub mod update; pub mod update;
pub mod window_controls;
pub mod xlsx_export; pub mod xlsx_export;
pub mod zookeeper_cmd; pub mod zookeeper_cmd;
+133
View File
@@ -0,0 +1,133 @@
#[cfg(target_os = "macos")]
async fn set_macos_traffic_light_position_inner(
window: tauri::Window,
target_x: f64,
target_center_y: f64,
ui_scale: f64,
) -> Result<MacosTrafficLightLayout, String> {
let ns_window = window.ns_window().map_err(|err| err.to_string())? as usize;
let (tx, rx) = tokio::sync::oneshot::channel();
window
.run_on_main_thread(move || unsafe {
use objc2_app_kit::{NSWindow, NSWindowButton};
let ns_window = &*(ns_window as *mut NSWindow);
let Some(close) = ns_window.standardWindowButton(NSWindowButton::CloseButton) else {
let _ = tx.send(None);
return;
};
let Some(miniaturize) = ns_window.standardWindowButton(NSWindowButton::MiniaturizeButton) else {
let _ = tx.send(None);
return;
};
let zoom = ns_window.standardWindowButton(NSWindowButton::ZoomButton);
let Some(title_bar_container_view) = close.superview().and_then(|view| view.superview()) else {
let _ = tx.send(None);
return;
};
let close_rect = close.frame();
let window_height = ns_window.frame().size.height;
let target_window_center_y = target_center_y * ui_scale;
let target_y = (target_window_center_y - close_rect.size.height / 2.0).max(0.0);
let title_bar_frame_height = close_rect.size.height + target_y;
let mut title_bar_rect = title_bar_container_view.frame();
title_bar_rect.size.height = title_bar_frame_height;
title_bar_rect.origin.y = window_height - title_bar_frame_height;
title_bar_container_view.setFrame(title_bar_rect);
let close_rect = close.frame();
let current_window_rect =
close.superview().map(|view| view.convertRect_toView(close_rect, None)).unwrap_or(close_rect);
let current_center_y =
window_height - (current_window_rect.origin.y + current_window_rect.size.height / 2.0);
let center_delta_y = target_window_center_y - current_center_y;
let space_between = miniaturize.frame().origin.x - close_rect.origin.x;
let mut buttons = vec![close, miniaturize];
if let Some(zoom) = zoom {
buttons.push(zoom);
}
for (index, button) in buttons.into_iter().enumerate() {
let mut rect = button.frame();
rect.origin.x = target_x + (index as f64 * space_between);
rect.origin.y -= center_delta_y;
button.setFrameOrigin(rect.origin);
}
let Some(close) = ns_window.standardWindowButton(NSWindowButton::CloseButton) else {
let _ = tx.send(None);
return;
};
let zoom = ns_window.standardWindowButton(NSWindowButton::ZoomButton);
let close_rect = close.frame();
let close_window_rect =
close.superview().map(|view| view.convertRect_toView(close_rect, None)).unwrap_or(close_rect);
let reserved_button_rect = zoom
.as_ref()
.and_then(|button| button.superview().map(|view| view.convertRect_toView(button.frame(), None)))
.unwrap_or(close_window_rect);
let button_center_y = window_height - (close_window_rect.origin.y + close_window_rect.size.height / 2.0);
let _ = tx.send(Some(MacosTrafficLightLayout {
x: close_window_rect.origin.x,
y: target_y,
center_y: button_center_y,
previous_center_y: current_center_y,
reserved_inset: reserved_button_rect.origin.x + reserved_button_rect.size.width + 8.0,
}));
})
.map_err(|err| err.to_string())?;
rx.await.map_err(|err| err.to_string())?.ok_or_else(|| "Unable to locate macOS traffic light buttons".to_string())
}
#[cfg(not(target_os = "macos"))]
async fn set_macos_traffic_light_position_inner(
_window: tauri::Window,
x: f64,
target_center_y: f64,
ui_scale: f64,
) -> Result<MacosTrafficLightLayout, String> {
let center_y = target_center_y * ui_scale;
Ok(MacosTrafficLightLayout { x, y: center_y, center_y, previous_center_y: center_y, reserved_inset: 0.0 })
}
fn validate_macos_traffic_light_position(x: f64, y: f64, scale: f64) -> Result<(), String> {
if !x.is_finite() || !y.is_finite() || !scale.is_finite() || scale <= 0.0 {
return Err("Invalid traffic light position".to_string());
}
Ok(())
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct MacosTrafficLightLayout {
x: f64,
y: f64,
center_y: f64,
previous_center_y: f64,
reserved_inset: f64,
}
#[tauri::command]
pub async fn set_macos_traffic_light_position(
window: tauri::Window,
x: f64,
y: f64,
scale: f64,
) -> Result<MacosTrafficLightLayout, String> {
validate_macos_traffic_light_position(x, y, scale)?;
// Await AppKit work asynchronously so the main thread can execute the scheduled closure.
set_macos_traffic_light_position_inner(window, x, y, scale).await
}
#[cfg(test)]
mod tests {
use super::validate_macos_traffic_light_position;
#[test]
fn validates_macos_traffic_light_position_inputs() {
assert!(validate_macos_traffic_light_position(16.0, 18.0, 1.0).is_ok());
assert!(validate_macos_traffic_light_position(f64::NAN, 18.0, 1.0).is_err());
assert!(validate_macos_traffic_light_position(16.0, f64::INFINITY, 1.0).is_err());
assert!(validate_macos_traffic_light_position(16.0, 18.0, 0.0).is_err());
}
}
+1
View File
@@ -878,6 +878,7 @@ pub fn run() {
commands::app_settings::save_desktop_settings, commands::app_settings::save_desktop_settings,
commands::app_settings::complete_app_close, commands::app_settings::complete_app_close,
commands::app_settings::request_app_close_from_window_controls, commands::app_settings::request_app_close_from_window_controls,
commands::window_controls::set_macos_traffic_light_position,
commands::app_settings::set_driver_store_dir, commands::app_settings::set_driver_store_dir,
commands::app_settings::set_plugin_store_dir, commands::app_settings::set_plugin_store_dir,
commands::app_settings::set_agent_store_dir, commands::app_settings::set_agent_store_dir,