百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
Q

quill

> 编程语言
开源

一个用于 Bevy 的反应式 UI 框架

198 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

一个用于 Bevy 的反应式 UI 框架

Quill

Quill is a UI framework for the Bevy game engine. It's meant to provide a simple API for constructing reactive user interfaces, similar to frameworks like React and Solid, but built on a foundation of Bevy ECS state management.

Quill is an experimental library which borrows ideas from a number of popular UI frameworks, including React.js, Solid.js, Dioxus, and Xilem. However, the way these ideas are implemented is quite different, owing to the need to build on the foundations of Bevy ECS.

Quill is relatively unopinionated about styling, layout or ECS hierarchies - you can use it to build a traditional 2D game UI, gizmo-like overlays in 3D, or reactive scenes. However, Quill comes with a separate crate, bevy_quill_obsidian which provides a set of opininated widgets for building game editors.

Getting started

:warning: Quill currently requires the unstable Rust feature impl_trait_in_assoc_type. This requirement will go away once the feature has been stabilized, which is scheduled to happen sometime before the end of 2024.

:warning: Quill is currently in early development, and is likely to change as it evolves.

For now, you can run the examples. The "complex" example shows off multiple features of the library:

bash
cargo run --example complex

Aspirations / guiding principles:

  • Allows easy composition and re-use of hierarchical widgets.
  • Built on top of existing Bevy UI components.
  • No special syntax required, it's just Rust.
  • Allows reactive hooks such as use_resource() that hook into Bevy's change detection framework.
  • State management built on top of Bevy ECS, rather than maintaining its own separate UI "world".
  • Any data type (String, int, color, etc.) can be displayed in the UI so long as it implements the View trait.
  • Efficient rendering approach with minimal memory allocations. Uses a hybrid approach that borrows from both React and Solid to handle incremental modifications of the UI node graph.
  • Supports dynamic styling and animation effects.

A Basic Example

To create a basic widget, start by creating a struct which implements the ViewTemplate trait. This trait has one method, create(), which takes a context (Cx) and returns a View.

rust
/// A view template
struct MyWidget;

impl ViewTempate for MyWidget {
    type View = impl View;

    fn create(cx: &mut Cx) -> Self::View {
        // Access data in a resource
        let counter = cx.use_resource::();
        Element::::new().children((
            format!("The count is: {}", counter.count),
        ))
    }
}

To actually display this widget, you'll need to set up a few things:

  • Add QuillPlugin in your app's plugins.
  • Initialize the Counter resource.
  • Spawn a view root.

The view root is an ECS entity which represents the root of the UI hierarchy. Note that there are actually two hierarchies, the "view hierarchy" which is the tree of templates and reactive objects, and the "display hierarchy", which are the actual Bevy entities that get rendered on the screen. You only need to worry about the former, since the display hierarchy is automatically constructed.

To spawn a root for the MyWidget template, use Bevy commands in a setup system:

rust
commands.spawn(MyWidget.to_root());

View Structure and Lifecycle

Quill manages views and templates on three different levels:

  • View templates are application-level components that "react" when their dependencies change. If you have every used React.js, a ViewTemplate is the equivalent of a React Component.
  • Views are lower-level constructs that generate the basic ECS building blocks of a UI, such as entities and components. Views understand incremental updates: how to patch an ECS hierarchy to make modifications without re-constructing the whole tree.
  • Display nodes are the actual renderable ECS entities created by the views.

Every ViewTemplate has a method called create which is called when the template is first spawned, and which is called again each time the display needs to update. It's important to understand how create() is called, as this is the key to working with Quill:

  • create() is typically called many times, which means that any code inside of create needs to be written in a way that is repeatable. Fortunately, the Cx object has lots of methods to help with this: for example, if you want to write some code that only runs once, or only runs under certain situations, you can call cx.create_effect().
  • create() is reactive, meaning that it will be run again whenever one of its dependencies change. For example, when you access a Bevy resource or component, it automatically adds that resource or component to a tracking list. If some other function later modifies that resource or component, it will trigger a reaction, which will cause create to run again.

It's important to write the create() method in a way that doesn't leak memory or resources. For example, it would be a mistake to write a create() method that calls material_assets.add() directly, since this would add a new material every update, returning a new handle. Instead, you can wrap the material initialization in a call to cx.create_memo(), which will allow you to preserve the material handle between invocations.

As a general rule, you should write your templates in a "mostly functional" style, minimizing side effects. When you do need side effects, there are special methods available like .insert() or .create_mutable() to help you out.

The return value from create is an object that implements the View trait. Views have a more complicated lifecycle that involves methods such as build(), rebuild() and raze(), but most of the time you won't need to worry about these.

Elements

Typically you won't need to write your own implementations of View, as these have already been provided. The most important of these is the Element type, which creates a single display node entity. Elements have three aspects:

  • A bundle type: the type of bundle that will be inserted into the entity upon creation.
  • Zero or more children.
  • Zero or more "effects".

The children of an element are also views, defined using View objects. These are constructed by the parent and inserted as children of the display node using the standard Bevy parent/child relations.

"Effects" are anything that add or modify an entity's ECS components, such as:

  • Adding bevy_mod_picking event handlers.
  • Adding custom materials.
  • Adding animations.
  • Adding ARIA nodes for accessibility.
  • Applying styles.

Children and effects are added using a builder pattern, as in the following example:

rust
Element::::new()
    .style(style_panel)
    .children((
        "Hello, ",
        "world!",
    ))

The children() method accepts either a single view or a tuple of views. In this case, we're passing plain text strings. Because the View trait has an implementation for &str, these strings can be displayed as views, and will construct the appropriate bevy_ui Text nodes.

Note that ViewTemplates also implement View, so you can freely mix both templates and views when defining children.

In the above example, the .style() method adds a "style effect" - an effect which initializes the style components of the entity.

The .style() method is an example of a static effect, an effect which is only applied once when the element is first created. There are also dynamic effects which can be applied multiple times. Dynamic effects typically take a list of dependencies, and only re-run the effect when the dependencies change. For example, here's a style effect which displays a "focus rectangle" around a checkbox, but only when the "focus" flag (as determined by the accessiibility Focus resource) is set to true:

rust
.style_dyn(
    // This closure only runs when 'focused' changes.
    |focused, sb| {
        if focused {
            sb.outline_color(colors::FOCUS)
                .outline_offset(1.0)
                .width(2.0);
        } else {
            sb.outline_color(Option::::None);
        }
    },
    focused,
)

Another frequently-used effect is .insert() and it's dynamic counterpart, .insert_dyn(), which inserts an ECS component. There's also a variation, .insert_if() which inserts a component when the condition is true, and removes it when it's false - handy for marker components like Disabled.

The .insert() method is frequently used for inserting bevy_mod_picking event handlers.

More Examples

Conditional rendering with Cond

The Cond (short for "conditional") view takes a conditional expression, and two child views, one which is built when the condition is true, the other when the condition is false.

rust
/// Widget that displays whether the count is even or odd.
struct EvenOrOdd;

impl ViewTempate for EvenOrOdd {
    type View = impl View;

    fn create(cx: &mut Cx) -> Self::View {
        let counter = cx.use_resource::();
        Element::new().children((
            "The count is: ",
            Cond::new(counter.count & 1 == 0, "even", "odd"),
        ))
    }
}

Note: It's perfectly OK to use a regular if statement or match for conditional views, however there is a limitation, which is that the result type has to be the same for all branches. Cond doesn't have this limitation, the true and false branches can be different types. Internally, Cond tears down the previous branch and initializes the new branch whenever the condition variable changes.

Often the "false" branch of a Cond will be the empty view, (), which renders nothing and creates no entities.

Conditional rendering with Switch

You can select from multiple views using Switch. This works great with Bevy game states!

rust
let state = *cx.use_resource::>().get();

Switch::new(state)
    .case(EditorState::Realm, EditModeRealmControls)
    .case(EditorState::Terrain, EditModeTerrainControls)
    .case(EditorState::Scenery, EditModeSceneryControls)
    .case(EditorState::Meta, EditModeMetadataControls)
    .case(EditorState::Play, EditModePlayControls)

Rendering multiple items with For

For::each() takes a list of items, and a callback which builds a View for each item:

rust
struct EventLog;

impl ViewTempate for EventLog {
    type View = impl View;

    fn create(cx: &mut Cx) -> Self::View {
      let log = cx.use_resource::();
      Element::new()
          .children(For::each(&log.0, |item| {
              Element::new()
                  .styled(STYLE_LOG_ENTRY.clone())
                  .children((item.to_owned(), "00:00:00"))
          }).with_fallback("No items")),
    }
}

During updates, the For view compares the list of items with the previous list and computes a diff. Only items which have actually changed (insertions, deletions and mutations) are rebuilt. There are three different variations of the For construct, which differ in how they handle comparisons between items:

  • For::each() requires that the array elements implement PartialEq.
  • For::each_cmp() takes an additional comparator argument which is used to compare the items.
  • For::index() doesn't compare items, but instead uses the array index as a key. This version is less efficient, since an item insertion or deletion will require re-building all of the child views.

Returning multiple nodes

Normally a ViewTemplate returns a single View. If you want to return multiple views, use a tuple:

rust
(
    "Hello, ",
    "World!"
)

This works because tuples of views are also views.

Despawning

To despawn a Quill view hierarchy, simply call .despawn() on the root entity. Do not call .despawn_recursive() as this will panic. The reason is because the Quill view hierarchy is more complex than just simple parent/child relationships, and relies on Bevy component hooks to do it's interna

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rust

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言