Struct Image

Source
pub struct Image { /* private fields */ }
Available on crate feature yew only.
Expand description

Image Component

A highly optimized and feature-rich Image component for Yew applications, supporting lazy loading, blur placeholders, fallback handling, and multiple responsive layouts.

§Properties

The component uses the ImageProps struct for its properties. Key properties include:

  • src: The main image source URL (&'static str). Required.
  • alt: Alternative text for accessibility (&'static str). Default: "".
  • layout: The image layout strategy (Layout). Default: Layout::Auto.
  • width: The width of the image (&'static str). Required for certain layouts.
  • height: The height of the image (&'static str). Required for certain layouts.
  • sizes: Defines responsive image sizes (&'static str). Default: "".
  • quality: Image quality (custom property) (&'static str). Optional.
  • placeholder: Placeholder strategy before the image loads (e.g., "blur") (&'static str). Default: "".
  • blur_data_url: Base64-encoded low-res placeholder image (&'static str). Used when placeholder is "blur".
  • fallback_src: Fallback image URL if the main src fails to load (&'static str). Optional.
  • priority: Whether to load the image eagerly instead of lazily (bool). Default: false.
  • object_fit: CSS object-fit value (ObjectFit). Default: ObjectFit::Contain.
  • object_position: Object positioning inside the container (Position). Default: Position::Center.
  • style: Additional inline CSS styles (&'static str). Default: "".
  • class: Additional CSS classes (&'static str). Default: "".
  • decoding: Decoding strategy (Decoding). Default: Decoding::Auto.
  • on_load: Callback invoked when the image successfully loads (Callback<()>). Default: no-op.
  • on_error: Callback invoked if loading or fallback loading fails (Callback<String>). Default: no-op.
  • node_ref: Node reference for the underlying img element (NodeRef).
  • ARIA attributes: Full ARIA support for better accessibility (aria_label, aria_hidden, etc.).

§Features

  • Lazy Loading with IntersectionObserver: Image is loaded only when scrolled into view, boosting performance and saving bandwidth.

  • Fallback Handling: Automatically tries a fallback_src if the primary src fails, ensuring robustness.

  • Blur Placeholder: Supports blurred low-resolution placeholders for smoother image transitions.

  • Multiple Layouts: Supports various layouts like Fill, Responsive, Intrinsic, Fixed, Auto, Stretch, and ScaleDown.

  • Accessibility: Built-in support for ARIA attributes to make images fully accessible.

§Layout Modes

  • Layout::Fill: Image stretches to fill its container absolutely.
  • Layout::Responsive: Maintains aspect ratio and scales responsively.
  • Layout::Intrinsic: Renders using natural image dimensions.
  • Layout::Fixed: Renders at a fixed size.
  • Layout::Auto: Default natural behavior without forcing constraints.
  • Layout::Stretch: Fills the parent container’s width and height.
  • Layout::ScaleDown: Scales image down to fit the container without stretching.

§Examples

§Basic Usage

use yew::prelude::*;
use image_rs::yew::Image;
use image_rs::Layout;

#[function_component(App)]
pub fn app() -> Html {
    html! {
        <Image
            src="/images/photo.jpg"
            alt="A beautiful view"
            width="800"
            height="600"
            layout={Layout::Responsive}
        />
    }
}

§Blur Placeholder

use yew::prelude::*;
use image_rs::yew::Image;
use image_rs::Layout;

#[function_component(App)]
pub fn app() -> Html {
    html! {
        <Image
            src="/images/photo.jpg"
            alt="Blur example"
            width="800"
            height="600"
            layout={Layout::Intrinsic}
            placeholder="blur"
            blur_data_url="data:image/jpeg;base64,..."
        />
    }
}

§Fallback Image

use yew::prelude::*;
use image_rs::yew::Image;
use image_rs::Layout;

#[function_component(App)]
pub fn app() -> Html {
    html! {
        <Image
            src="/images/main.jpg"
            fallback_src="/images/fallback.jpg"
            alt="With fallback"
            width="800"
            height="600"
            layout={Layout::Fixed}
        />
    }
}

§Behavior

  • The image starts loading lazily once it enters the viewport (10% visible threshold).
  • If loading fails, a network fetch checks the fallback image.
  • Blur placeholder is rendered with a heavy blur(20px) effect until the full image loads.
  • Depending on the Layout, the container styling adjusts automatically.

§Notes

  • width and height are required for Responsive, Intrinsic, and Fixed layouts.
  • Layout::Fill ignores width and height, stretching to fit the parent container.
  • Accessibility attributes like aria-label and aria-hidden are passed directly to the <img> element.
  • Priority images (priority = true) are loaded eagerly instead of lazily.

§Errors

  • If both src and fallback_src fail, the on_error callback is triggered with an error message.
  • JSON parsing from a fallback response is attempted but not mandatory for image loading success.

§Optimization Techniques

  • IntersectionObserver is used for intelligent lazy loading.
  • Caching via RequestCache::Reload ensures fallback images are always fetched fresh if needed.
  • Async/await approach for fetch operations provides non-blocking fallback handling.

§See Also

Trait Implementations§

Source§

impl BaseComponent for Image
where Self: 'static,

Source§

type Message = ()

The Component’s Message.
Source§

type Properties = ImageProps

The Component’s Properties.
Source§

fn create(ctx: &Context<Self>) -> Self

Creates a component.
Source§

fn update(&mut self, _ctx: &Context<Self>, _msg: Self::Message) -> bool

Updates component’s internal state.
Source§

fn changed( &mut self, _ctx: &Context<Self>, _old_props: &Self::Properties, ) -> bool

React to changes of component properties.
Source§

fn view(&self, ctx: &Context<Self>) -> HtmlResult

Returns a component layout to be rendered.
Source§

fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool)

Notified after a layout is rendered.
Source§

fn destroy(&mut self, _ctx: &Context<Self>)

Notified before a component is destroyed.
Source§

fn prepare_state(&self) -> Option<String>

Prepares the server-side state.
Source§

impl Debug for Image

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FunctionProvider for Image

Source§

type Properties = ImageProps

Properties for the Function Component.
Source§

fn run(ctx: &mut HookContext, props: &Self::Properties) -> HtmlResult

Render the component. This function returns the Html to be rendered for the component. Read more

Auto Trait Implementations§

§

impl !Freeze for Image

§

impl !RefUnwindSafe for Image

§

impl !Send for Image

§

impl !Sync for Image

§

impl Unpin for Image

§

impl !UnwindSafe for Image

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<E, T, Request, Encoding> FromReq<Patch<Encoding>, Request, E> for T
where Request: Req<E> + Send + 'static, Encoding: Decodes<T>, E: FromServerFnError,

Source§

async fn from_req(req: Request) -> Result<T, E>

Attempts to deserialize the arguments from a request.
Source§

impl<E, T, Request, Encoding> FromReq<Post<Encoding>, Request, E> for T
where Request: Req<E> + Send + 'static, Encoding: Decodes<T>, E: FromServerFnError,

Source§

async fn from_req(req: Request) -> Result<T, E>

Attempts to deserialize the arguments from a request.
Source§

impl<E, T, Request, Encoding> FromReq<Put<Encoding>, Request, E> for T
where Request: Req<E> + Send + 'static, Encoding: Decodes<T>, E: FromServerFnError,

Source§

async fn from_req(req: Request) -> Result<T, E>

Attempts to deserialize the arguments from a request.
Source§

impl<E, Encoding, Response, T> FromRes<Patch<Encoding>, Response, E> for T
where Response: ClientRes<E> + Send, Encoding: Decodes<T>, E: FromServerFnError,

Source§

async fn from_res(res: Response) -> Result<T, E>

Attempts to deserialize the outputs from a response.
Source§

impl<E, Encoding, Response, T> FromRes<Post<Encoding>, Response, E> for T
where Response: ClientRes<E> + Send, Encoding: Decodes<T>, E: FromServerFnError,

Source§

async fn from_res(res: Response) -> Result<T, E>

Attempts to deserialize the outputs from a response.
Source§

impl<E, Encoding, Response, T> FromRes<Put<Encoding>, Response, E> for T
where Response: ClientRes<E> + Send, Encoding: Decodes<T>, E: FromServerFnError,

Source§

async fn from_res(res: Response) -> Result<T, E>

Attempts to deserialize the outputs from a response.
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoPropValue<Option<T>> for T

Source§

fn into_prop_value(self) -> Option<T>

Convert self to a value of a Properties struct.
Source§

impl<T> IntoPropValue<T> for T

Source§

fn into_prop_value(self) -> T

Convert self to a value of a Properties struct.
Source§

impl<E, T, Encoding, Request> IntoReq<Patch<Encoding>, Request, E> for T
where Request: ClientReq<E>, Encoding: Encodes<T>, E: FromServerFnError,

Source§

fn into_req(self, path: &str, accepts: &str) -> Result<Request, E>

Attempts to serialize the arguments into an HTTP request.
Source§

impl<E, T, Encoding, Request> IntoReq<Post<Encoding>, Request, E> for T
where Request: ClientReq<E>, Encoding: Encodes<T>, E: FromServerFnError,

Source§

fn into_req(self, path: &str, accepts: &str) -> Result<Request, E>

Attempts to serialize the arguments into an HTTP request.
Source§

impl<E, T, Encoding, Request> IntoReq<Put<Encoding>, Request, E> for T
where Request: ClientReq<E>, Encoding: Encodes<T>, E: FromServerFnError,

Source§

fn into_req(self, path: &str, accepts: &str) -> Result<Request, E>

Attempts to serialize the arguments into an HTTP request.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> SerializableKey for T

Source§

fn ser_key(&self) -> String

Serializes the key to a unique string. Read more
Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T> StorageAccess<T> for T

Source§

fn as_borrowed(&self) -> &T

Borrows the value.
Source§

fn into_taken(self) -> T

Takes the value.
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<Token, Builder, How> AllPropsFor<Builder, How> for Token
where Builder: Buildable<Token>, <Builder as Buildable<Token>>::WrappedToken: HasAllProps<<Builder as Buildable<Token>>::Output, How>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> HasAllProps<(), T> for T