Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_feathers/src/font_styles.rs
6849 views
1
//! A framework for inheritable font styles.
2
use bevy_app::{Propagate, PropagateOver};
3
use bevy_asset::{AssetServer, Handle};
4
use bevy_ecs::{
5
component::Component,
6
lifecycle::Insert,
7
observer::On,
8
reflect::ReflectComponent,
9
system::{Commands, Query, Res},
10
};
11
use bevy_reflect::{prelude::ReflectDefault, Reflect};
12
use bevy_text::{Font, TextFont};
13
14
use crate::{handle_or_path::HandleOrPath, theme::ThemedText};
15
16
/// A component which, when inserted on an entity, will load the given font and propagate it
17
/// downward to any child text entity that has the [`ThemedText`] marker.
18
#[derive(Component, Default, Clone, Debug, Reflect)]
19
#[reflect(Component, Default)]
20
#[require(ThemedText, PropagateOver::<TextFont>::default())]
21
pub struct InheritableFont {
22
/// The font handle or path.
23
pub font: HandleOrPath<Font>,
24
/// The desired font size.
25
pub font_size: f32,
26
}
27
28
impl InheritableFont {
29
/// Create a new `InheritableFont` from a handle.
30
pub fn from_handle(handle: Handle<Font>) -> Self {
31
Self {
32
font: HandleOrPath::Handle(handle),
33
font_size: 16.0,
34
}
35
}
36
37
/// Create a new `InheritableFont` from a path.
38
pub fn from_path(path: &str) -> Self {
39
Self {
40
font: HandleOrPath::Path(path.to_string()),
41
font_size: 16.0,
42
}
43
}
44
}
45
46
/// An observer which looks for changes to the [`InheritableFont`] component on an entity, and
47
/// propagates downward the font to all participating text entities.
48
pub(crate) fn on_changed_font(
49
insert: On<Insert, InheritableFont>,
50
font_style: Query<&InheritableFont>,
51
assets: Res<AssetServer>,
52
mut commands: Commands,
53
) {
54
if let Ok(style) = font_style.get(insert.entity)
55
&& let Some(font) = match style.font {
56
HandleOrPath::Handle(ref h) => Some(h.clone()),
57
HandleOrPath::Path(ref p) => Some(assets.load::<Font>(p)),
58
}
59
{
60
commands.entity(insert.entity).insert(Propagate(TextFont {
61
font,
62
font_size: style.font_size,
63
..Default::default()
64
}));
65
}
66
}
67
68