Skip to main content

aureole_core/
responsive.rs

1//! 按窗口大小切换样式:尺寸档([`window_size_class`])、断点([`is_window_at_least`])、按档取值([`responsive`])。
2//!
3//! 每个窗口(和每个测试工具)有一份自己的窗口大小信号,挂在窗口的作用域上([`reactive::provide_context`]);
4//! 窗口里的绑定在哪个窗口里执行,就读哪个窗口的大小,多窗口互不影响。尺寸档、断点都是派生值:
5//! 拖动改变窗口大小时它们每帧重算一次(比较一个数),只有跨过分档宽度时值才变,读它的绑定才重新执行。
6
7use std::cell::{Cell, RefCell};
8use std::rc::{Rc, Weak};
9
10use reactive::{Memo, Scope, Signal, memo, signal};
11
12use crate::geometry::Rect;
13use crate::host::{WindowId, current_window_id};
14
15/// 窗口宽度的档位,见 [`window_size_class`]。可以比较大小:`Compact < Regular < Wide`
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub enum SizeClass {
18    /// 窄:默认宽度小于 640
19    Compact,
20    /// 中等:默认 640 到 1024
21    #[default]
22    Regular,
23    /// 宽:默认 1024 及以上
24    Wide,
25}
26
27impl SizeClass {
28    /// 按分档宽度([`set_size_class_widths`])给出 `width` 属于哪一档。在绑定里调用时,改分档宽度也会让它重新执行;
29    /// 量到的容器宽度([`crate::Element::report_bounds`])也可以这样分档
30    pub fn from_width(width: f32) -> Self {
31        let [regular, wide] = thresholds().get();
32        if width >= wide {
33            Self::Wide
34        } else if width >= regular {
35            Self::Regular
36        } else {
37            Self::Compact
38        }
39    }
40
41    /// 是否是窄档
42    pub fn is_compact(self) -> bool {
43        self == Self::Compact
44    }
45
46    /// 是否是宽档
47    pub fn is_wide(self) -> bool {
48        self == Self::Wide
49    }
50
51    /// 按档位取一个值:`class.pick(12.0, 16.0, 24.0)`
52    pub fn pick<T>(self, compact: T, regular: T, wide: T) -> T {
53        match self {
54            Self::Compact => compact,
55            Self::Regular => regular,
56            Self::Wide => wide,
57        }
58    }
59}
60
61thread_local! {
62    /// 分档宽度 [中等, 宽],全应用一份
63    static THRESHOLDS: Cell<Option<Signal<[f32; 2]>>> = const { Cell::new(None) };
64    /// 所有窗口(和测试工具)的大小,找不到所在窗口时按当前窗口或最后一个查
65    static REGISTRY: RefCell<Vec<(Option<WindowId>, Weak<Inner>)>> = const { RefCell::new(Vec::new()) };
66}
67
68fn thresholds() -> Signal<[f32; 2]> {
69    THRESHOLDS.with(|cell| {
70        cell.get().unwrap_or_else(|| {
71            let s = reactive::detached(|| signal([640.0, 1024.0]));
72            cell.set(Some(s));
73            s
74        })
75    })
76}
77
78/// 改尺寸档的分界:宽度不小于 `regular` 是中等档,不小于 `wide` 是宽档(默认 640、1024)。
79/// 全应用一份;所有窗口里读 [`window_size_class`] 的绑定跟着更新
80pub fn set_size_class_widths(regular: f32, wide: f32) {
81    thresholds().set_if_changed([regular, wide.max(regular)]);
82}
83
84/// 当前窗口宽度的档位(响应式)。窗口大小每帧都可能变,但只有跨过分档宽度时值才变,
85/// 读它的绑定只在这时重新执行:
86///
87/// ```no_run
88/// # use aureole::prelude::*;
89/// use aureole::{SizeClass, window_size_class};
90/// column()
91///     .direction(move || if window_size_class() >= SizeClass::Regular { Direction::Row } else { Direction::Column })
92///     .gap(move || window_size_class().pick(12.0, 16.0, 24.0));
93/// ```
94///
95/// "当前窗口"是调用它的代码所在的窗口:元素的绑定属于挂载它的窗口(测试工具里是 `Harness`
96/// 的虚拟窗口),在哪个窗口里重新执行都一样。要在绑定里调用;在构建视图的函数体里直接调用只读一次,不会跟着变
97pub fn window_size_class() -> SizeClass {
98    metrics().map_or_else(SizeClass::default, |m| m.class.get())
99}
100
101/// 当前窗口内容区的大小,逻辑像素(响应式,每次变化都通知;只关心档位时用 [`window_size_class`] 或 [`is_window_at_least`])
102pub fn window_size() -> [f32; 2] {
103    metrics().map_or([0.0; 2], |m| m.size.get())
104}
105
106/// 当前窗口宽度是否不小于 `width`(响应式):只在跨过这个宽度时通知。同一个窗口里同一个宽度共用一个派生值
107///
108/// ```no_run
109/// # use aureole::prelude::*;
110/// use aureole::is_window_at_least;
111/// row().child_when(move || is_window_at_least(900.0), || text("宽窗口才显示的侧栏"));
112/// ```
113pub fn is_window_at_least(width: f32) -> bool {
114    let Some(m) = metrics() else { return false };
115    let bits = width.to_bits();
116    let existing = m.breakpoints.borrow().iter().find(|(w, _)| *w == bits).map(|(_, memo)| *memo);
117    let memo = existing.unwrap_or_else(|| {
118        let size = m.size;
119        // 建在窗口的作用域里:不随调用它的绑定重新执行而释放
120        let memo = m.scope.run(|| memo(move || size.get()[0] >= width));
121        m.breakpoints.borrow_mut().push((bits, memo));
122        memo
123    });
124    memo.get()
125}
126
127/// 按当前窗口的档位取值,直接传给属性:`.gap(responsive(12.0, 16.0, 24.0))`、
128/// `.direction(responsive(Direction::Column, Direction::Row, Direction::Row))`。只在跨过分档宽度时重新取值
129pub fn responsive<T: Clone + 'static>(compact: T, regular: T, wide: T) -> impl Fn() -> T + 'static {
130    move || window_size_class().pick(compact.clone(), regular.clone(), wide.clone())
131}
132
133/// 隐藏了的标题栏占了多少([`title_bar_info`])。都是窗口内容区里的逻辑像素
134#[derive(Clone, Copy, Debug, Default, PartialEq)]
135pub struct TitleBarInfo {
136    /// 标题栏这一条有多高:自己画标题栏时用它当高度。系统的标题栏(内容不在标题栏下面)、全屏时是 0
137    pub height: f32,
138    /// 系统窗口按钮(macOS 的红绿灯)的范围。要应用自己画按钮的平台(Windows、Linux)、全屏时是 `None`
139    pub controls: Option<Rect>,
140    /// 标题栏的内容要从左边让开多少,才不和系统窗口按钮叠在一起
141    pub inset_left: f32,
142    /// 标题栏的内容要从右边让开多少,才不和系统窗口按钮叠在一起
143    pub inset_right: f32,
144}
145
146/// 当前窗口隐藏了的标题栏(`TitleBar::Hidden`)占了多少:高度、系统窗口按钮在哪、标题栏的内容要让开多少(响应式)。
147/// 窗口缩放、进出全屏、挪了按钮时变,绑定跟着更新,所以可以直接绑到布局上:
148///
149/// ```no_run
150/// # use aureole::prelude::*;
151/// use aureole::title_bar_info;
152/// row()
153///     .window_drag_area(true)
154///     .height(move || px(title_bar_info().height))
155///     .child(text("我的应用").margin_left(move || px(title_bar_info().inset_left)));
156/// ```
157///
158/// "当前窗口"的意思同 [`window_size`]。测试工具里是 [`TitleBarInfo::default`],用 `Harness::set_title_bar_info` 模拟
159pub fn title_bar_info() -> TitleBarInfo {
160    metrics().map_or_else(TitleBarInfo::default, |m| m.title_bar.get())
161}
162
163/// 一个窗口(或测试工具)的大小和由它派生的档位、隐藏了的标题栏的度量
164pub(crate) struct Inner {
165    size: Signal<[f32; 2]>,
166    class: Memo<SizeClass>,
167    title_bar: Signal<TitleBarInfo>,
168    breakpoints: RefCell<Vec<(u32, Memo<bool>)>>,
169    scope: Scope,
170    /// 作用域释放后不能再读里面的信号
171    alive: Cell<bool>,
172}
173
174/// 窗口大小的句柄,元素树里留一份(每帧把新大小写进去),作用域上提供一份(绑定里查)
175#[derive(Clone)]
176pub(crate) struct WindowMetrics(Rc<Inner>);
177
178impl WindowMetrics {
179    /// 在当前作用域(窗口或测试工具的)里建好,提供给里面的代码,并登记(找不到所在窗口时用)
180    pub fn attach(size: [f32; 2], window: Option<WindowId>) -> Self {
181        let scope = Scope::current().unwrap_or_default();
182        let size = signal(size);
183        let class = memo(move || SizeClass::from_width(size.get()[0]));
184        let title_bar = signal(TitleBarInfo::default());
185        let inner = Rc::new(Inner { size, class, title_bar, breakpoints: RefCell::new(Vec::new()), scope, alive: Cell::new(true) });
186        let metrics = Self(inner);
187        reactive::provide_context(metrics.clone());
188        let weak = Rc::downgrade(&metrics.0);
189        REGISTRY.with(|r| {
190            let mut r = r.borrow_mut();
191            r.retain(|(_, w)| w.upgrade().is_some_and(|i| i.alive.get()));
192            r.push((window, weak.clone()));
193        });
194        reactive::on_cleanup(move || {
195            if let Some(inner) = weak.upgrade() {
196                inner.alive.set(false);
197            }
198        });
199        metrics
200    }
201
202    /// 窗口大小变了(每帧开始时,不借用元素树时调用)
203    pub fn set_size(&self, size: [f32; 2]) {
204        if self.0.alive.get() {
205            self.0.size.set_if_changed(size);
206        }
207    }
208
209    /// 隐藏了的标题栏的度量变了(不借用元素树时调用)
210    pub fn set_title_bar(&self, info: TitleBarInfo) {
211        if self.0.alive.get() {
212            self.0.title_bar.set_if_changed(info);
213        }
214    }
215}
216
217/// 调用方所在窗口的大小:先沿作用域找,找不到(不在任何窗口的作用域里)时用当前窗口,再不行用最后建的那个
218fn metrics() -> Option<Rc<Inner>> {
219    if let Some(m) = reactive::context::<WindowMetrics>() {
220        return m.0.alive.get().then_some(m.0);
221    }
222    let current = current_window_id();
223    REGISTRY.with(|r| {
224        let r = r.borrow();
225        let live = |(_, w): &(Option<WindowId>, Weak<Inner>)| w.upgrade().filter(|i| i.alive.get());
226        r.iter().rev().find(|(h, _)| current.is_some() && *h == current).and_then(live).or_else(|| r.iter().rev().find_map(live))
227    })
228}