use gpui_kit::{
Along as _, Axis, Entity, IntoElement, Pixels, SharedString, Styled as _, Window, canvas,
};
const STEP: f32 = 0.5;
pub const UNMEASURED: f32 = 0.;
pub fn unmeasured(cx: &mut impl gpui_kit::AppContext) -> Entity<f32> {
cx.new(|_| UNMEASURED)
}
pub fn changed(held: f32, measured: f32) -> bool {
(held - measured).abs() > STEP
}
pub fn width(into: Entity<f32>) -> impl IntoElement {
dimension(into, Axis::Horizontal)
}
pub fn height(into: Entity<f32>) -> impl IntoElement {
dimension(into, Axis::Vertical)
}
pub fn text_width(window: &Window, text: &str, family: SharedString, size: Pixels) -> Pixels {
let mut style = window.text_style();
style.font_family = family;
style.font_size = size.into();
let line: SharedString = text.to_owned().into();
let run = style.to_run(line.len());
window
.text_system()
.shape_line(line, size, &[run], None)
.width
}
fn dimension(into: Entity<f32>, axis: Axis) -> impl IntoElement {
canvas(
move |bounds, _, cx| {
let measured = f32::from(bounds.size.along(axis));
into.update(cx, |width, cx| {
if changed(*width, measured) {
*width = measured;
cx.notify();
}
});
},
|_, (), _, _| {},
)
.absolute()
.size_full()
}
#[cfg(test)]
mod tests {
use super::changed;
#[test]
fn only_a_real_change_of_width_costs_a_frame() {
assert!(changed(0., 420.), "the first measurement");
assert!(changed(420., 300.));
assert!(!changed(420., 420.));
assert!(!changed(420., 420.4), "rounding is not a change");
}
}