Path: blob/main/crates/bevy_feathers/src/font_styles.rs
6849 views
//! A framework for inheritable font styles.1use bevy_app::{Propagate, PropagateOver};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, theme::ThemedText};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`] marker.17#[derive(Component, Default, Clone, Debug, Reflect)]18#[reflect(Component, Default)]19#[require(ThemedText, PropagateOver::<TextFont>::default())]20pub struct InheritableFont {21/// The font handle or path.22pub font: HandleOrPath<Font>,23/// The desired font size.24pub font_size: f32,25}2627impl InheritableFont {28/// Create a new `InheritableFont` from a handle.29pub fn from_handle(handle: Handle<Font>) -> Self {30Self {31font: HandleOrPath::Handle(handle),32font_size: 16.0,33}34}3536/// Create a new `InheritableFont` from a path.37pub fn from_path(path: &str) -> Self {38Self {39font: HandleOrPath::Path(path.to_string()),40font_size: 16.0,41}42}43}4445/// An observer which looks for changes to the [`InheritableFont`] component on an entity, and46/// propagates downward the font to all participating text entities.47pub(crate) fn on_changed_font(48insert: On<Insert, InheritableFont>,49font_style: Query<&InheritableFont>,50assets: Res<AssetServer>,51mut commands: Commands,52) {53if let Ok(style) = font_style.get(insert.entity)54&& let Some(font) = match style.font {55HandleOrPath::Handle(ref h) => Some(h.clone()),56HandleOrPath::Path(ref p) => Some(assets.load::<Font>(p)),57}58{59commands.entity(insert.entity).insert(Propagate(TextFont {60font,61font_size: style.font_size,62..Default::default()63}));64}65}666768