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