Skip to content

Focus rings for feathers widgets and core widget examples. #20047

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

viridia
Copy link
Contributor

@viridia viridia commented Jul 8, 2025

Objective

Add focus rings for:

  • Core widget examples
  • Feathers widgets

Part of #19236

Screenshot 2025-07-08 at 4 23 25 PM

@alice-i-cecile

@alice-i-cecile alice-i-cecile added A-UI Graphical user interfaces, styles, layouts, and widgets S-Needs-Review Needs reviewer attention (from anyone!) to move forward A-Art Art, UX or graphic design M-Needs-Release-Note Work that should be called out in the blog due to impact labels Jul 8, 2025
@alice-i-cecile alice-i-cecile added this to the 0.17 milestone Jul 8, 2025
@alice-i-cecile alice-i-cecile added the C-Feature A new feature, making something new possible label Jul 8, 2025
@viridia
Copy link
Contributor Author

viridia commented Jul 8, 2025

BTW, you know what would be awesome? If outlines had a z-index offset :)

@ickshonpe
Copy link
Contributor

BTW, you know what would be awesome? If outlines had a z-index offset :)

I think using the outlines API probably just isn't a good fit for this. We could add another component or add a system to directly extract the focus rings for rendering. That would allow for arbitrary z-ordering.

Copy link
Contributor

@ickshonpe ickshonpe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could use an extraction system instead and draw the focus ring directly for the current InputFocus. Made a quick prototype:

pub fn extract_focus_ring(
    mut commands: Commands,
    mut extracted_uinodes: ResMut<ExtractedUiNodes>,
    focus: Extract<Res<InputFocus>>,
    theme: Extract<Option<Res<UiTheme>>>,
    uinode_query: Extract<
        Query<
            (
                &Node,
                &ComputedNode,
                &InheritedVisibility,
                &UiGlobalTransform,
                Option<&CalculatedClip>,
                &ComputedNodeTarget,
            ),
            With<TabIndex>,
        >,
    >,
    camera_map: Extract<UiCameraMap>,
) {
    let mut camera_mapper = camera_map.get_mapper();

    let Some(focused_entity) = focus.0 else {
        return;
    };
    let Ok((node, computed_node, inherited_visibility, transform, maybe_clip, target)) =
        uinode_query.get(focused_entity)
    else {
        return;
    };

    if !inherited_visibility.get() || node.display == Display::None {
        return;
    }

    let ring_color = theme
        .as_ref()
        .map(|theme| theme.color(bevy_feathers::tokens::FOCUS_RING))
        .unwrap_or(bevy_color::palettes::tailwind::BLUE_700.into());

    let Some(extracted_camera_entity) = camera_mapper.map(target) else {
        return;
    };

    let ring_width = 2. * target.scale_factor();
    let outer_distance = 2. * ring_width;
    let ring_size = computed_node.size() + outer_distance;
    let compute_radius = |node_corner_radius| {
        if 0. < node_corner_radius {
            node_corner_radius + outer_distance
        } else {
            0.
        }
    };

    let ring_radius = ResolvedBorderRadius {
        top_left: compute_radius(computed_node.border_radius.top_left),
        top_right: compute_radius(computed_node.border_radius.top_right),
        bottom_right: compute_radius(computed_node.border_radius.bottom_right),
        bottom_left: compute_radius(computed_node.border_radius.bottom_left),
    };

    extracted_uinodes.uinodes.push(ExtractedUiNode {
        z_order: computed_node.stack_index as f32 + stack_z_offsets::FOCUS_RING,
        render_entity: commands.spawn(TemporaryRenderEntity).id(),
        color: ring_color.into(),
        rect: Rect {
            max: ring_size,
            ..Default::default()
        },
        image: AssetId::default(),
        clip: maybe_clip.map(|clip| clip.clip),
        extracted_camera_entity,
        item: ExtractedUiItem::Node {
            transform: transform.into(),
            atlas_scaling: None,
            flip_x: false,
            flip_y: false,
            border: BorderRect::all(ring_width),
            border_radius: ring_radius,
            node_type: NodeType::Border(shader_flags::BORDER_ALL),
        },
        main_entity: focused_entity.into(),
    });
}

branch is here: https://github.com/ickshonpe/bevy/tree/focus_ring_extraction

It doesn't support support the sub-focus for the checkbox but marker components could be added to signal a descendant should be outlined instead.

offset: Val::Px(2.0),
});
} else {
commands.entity(button).remove::<Outline>();
Copy link
Contributor

@ickshonpe ickshonpe Jul 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another alternative would be to have a separate entity, something like:

        (
            FocusRingNode,
            Node {
                position_type: PositionType::Absolute,
                left: Val::Px(0.),
                right: Val::Px(0.),
                top: Val::Px(0.),
                bottom: Val::Px(0.),
                ..Default::default()
            },
            Outline {
                color: theme.color(tokens::FOCUS_RING),
                width: Val::Px(2.0),
                offset: Val::Px(2.0),
            },
        )

And then when input focus changes, reparent the FocusRingNode to the new entity. There would also need to be a system that synchronised the border radii. Then you can set an arbitrary zindex on the ring node, and there would be no need to remove the outline from the previous entity.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'd like to put this issue aside for now.

Using outlines does cause a minor cosmetic problem when using segmented buttons (the adjacent button renders on top of the outline). However, most users will never see this, as focus outlines are disabled until you actually use tab navigation. Other than that minor glitch, outlines work pretty well.

A different approach is to temporarily modify the z-index of the focused button.

In any case, I only mentioned this as speculation; I didn't actually expect to get a solution :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like reusing Outline for this: it causes z-ordering issues, and because it's used for other things, you have to be careful of bugs around restoring the outline when removing focus.

I think that a separate entity with a dedicated component is going to be a much better foundation.

Copy link
Contributor Author

@viridia viridia Jul 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If that's the case, then what are outlines for?

Note that I didn't implement focus rings for core widgets, because of exactly this: core widgets aren't supposed to make assumptions about what styling decisions the client is going to make, whether or not they want to use outlines for focus or some other purpose. The place where I used outlines is (a) in examples, and (b) in the feathers widgets -- both of which presumably "own" their styling.

Sure, we can make something that spawns an absolutely-positioned child entity that inflates the parent's box and draws a border, copying over the border radius (although it will get tricky because we want to increase the radius value by the offset).

But my question then is, why did we add the outlines feature at all? I mean, you could make the argument that anyone who uses outlines for any reason is denying someone else the use of outline for some other reason.

I should note that outlines on the web have exactly this same problem, but I don't think that lets us off the hook; rather I think it means that we're copying the web's mistakes.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But my question then is, why did we add the outlines feature at all?

That's a very good point.

What if we rename the outline component to less of an attractive nuisance: something like FocusOutline? Then, point to Border in the docs for other uses.

We can then change the implementation to use multiple entities and have better z-layering in follow-up.

Copy link
Contributor

@ickshonpe ickshonpe Jul 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, we can make something that spawns an absolutely-positioned child entity that inflates the parent's box and draws a border, copying over the border radius (although it will get tricky because we want to increase the radius value by the offset).

There's no need to recalculate the border-radius when using outlines for this. It just needs to match the border-radius of the parent. The system for updating the FocusRingNode's border-radius would be very simple, just query for its parent's border-radius and copy it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need to solve the "restore previous outline when unfocused" problem right now. We can solve this later when we implement a more robust way of doing focus rings.

My reasoning is this: the use of outlines to implement focus rings is limited to the following cases:

  • examples (specifically core_widgets and input_focus examples).
  • feathers

Neither of these cases permits conflicting uses of outlines, but for different reasons. In the case of examples, the user can't re-use the components. In the case of feathers, we can simply declare by fiat that we "own" the outline (this is the benefit of having an opinionated widget collection).

If someone comes along later and says, "no I really want to use a feathers button but I want my own outlines for some different purpose" we can solve it then.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ickshonpe @alice-i-cecile So I went ahead and implemented the "focus outline as child entity" solution...and it doesn't solve the problem! Well, it doesn't solve the Z-ordering problem.

Using a local ZIndex doesn't do anything: it only affects order relative to siblings, and since the focus outline entity is a child, it doesn't have any siblings.

Using GlobalZIndex is problematic for different reasons: since there's no way for me to know the z-index of the parent, I have to pick some hard-coded value for the z-index for all outlines. I could pick some huge number and make the outlines always be on top, but what if I don't want the outline on top? Like, what if I want a tooltip or other kind of overlay to be above the focus outlines?

What we need is a RelativeGlobalZIndex!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting a GlobalZIndex doesn't seem great.
Maybe if it just walks up the tree raising the local ZIndex of all the focused elements ancestors as well? There could be some component that automatically moves not only the local node but also its ancestors to the top of the local draw order.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think for now let's just punt and solve it later. I worry about trying to shave too many yaks in one PR.

offset: Val::Px(2.0),
});
} else {
commands.entity(button).remove::<Outline>();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like reusing Outline for this: it causes z-ordering issues, and because it's used for other things, you have to be careful of bugs around restoring the outline when removing focus.

I think that a separate entity with a dedicated component is going to be a much better foundation.

@alice-i-cecile alice-i-cecile added S-Needs-SME Decision or review from an SME is required S-Needs-Design This issue requires design work to think about how it would best be accomplished and removed S-Needs-Review Needs reviewer attention (from anyone!) to move forward S-Needs-SME Decision or review from an SME is required labels Jul 10, 2025
@viridia viridia mentioned this pull request Jul 12, 2025
@alice-i-cecile alice-i-cecile self-requested a review July 13, 2025 17:30
@alice-i-cecile alice-i-cecile added S-Needs-Review Needs reviewer attention (from anyone!) to move forward and removed S-Needs-Design This issue requires design work to think about how it would best be accomplished labels Jul 13, 2025
@alice-i-cecile alice-i-cecile added the X-Controversial There is active debate or serious implications around merging this PR label Jul 21, 2025
@alice-i-cecile alice-i-cecile removed this from the 0.17 milestone Jul 21, 2025
@viridia
Copy link
Contributor Author

viridia commented Aug 9, 2025

@alice-i-cecile @ickshonpe I've completely re-written this PR from scratch. Please re-review.

@NthTensor NthTensor self-requested a review August 10, 2025 15:49
Copy link
Contributor

@ickshonpe ickshonpe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Get a stack overflow when I tried to run the feathers example with the latest version. The trivial example I used for some basic testing worked fine though.

I still think that adding nodes to the tree to display the focus rings is the wrong approach. They only need to be drawn, they don't need to be part of the layout. Then there's no need for any synchronisation, there aren't any conflicts with measure funcs, and the extraction function can automatically choose the right z-depth.

/// you wisth to display a focus outline.
#[derive(Component, Default, Clone, Reflect)]
#[reflect(Component, Clone, Default)]
pub struct VisibleFocusAnchor;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name "Anchor" is usually used to refer to anchor points, maybe something else would be clearer. VisibleFocusOutline?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanted a name that suggests this is not an outline, but rather an attachment point for an outline.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe -Mount or -Base?

I'd prefer an alternative if there's a good one but it's not super important and I'm fine with using -Anchor if you aren't happy with anything else. It's just that everywhere else an "anchor" means an attachment at a specific geometric point, instead of fit around this node like it does here.

*radii,
))
.id();
commands.entity(parent).add_child(outline);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nodes with a measure func like Text entities don't like having children, if a text node is given a focus outline like this it will probably collapse to zero size.

@ickshonpe
Copy link
Contributor

ickshonpe commented Aug 11, 2025

I don't mean to sound like I hate this that much. I think it's fine for now, we can merge it and move on.
I think I've worked out some very simple workarounds for the measure func and draw ordering problems that I could implement as follow up PRs.

@viridia
Copy link
Contributor Author

viridia commented Aug 11, 2025

I don't mean to sound like I hate this that much. I think it's fine for now, we can merge it and move on. I think I've worked out some very simple workarounds for the measure func and draw ordering problems that I could implement as follow up PRs.

Well, one option for the short term is to go back to using outlines instead of child entities. The same general system function will work either way, we don't have to change the API. It doesn't solve the Z-index problem, but if it's temporary I don't care.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-Art Art, UX or graphic design A-UI Graphical user interfaces, styles, layouts, and widgets C-Feature A new feature, making something new possible M-Needs-Release-Note Work that should be called out in the blog due to impact S-Needs-Review Needs reviewer attention (from anyone!) to move forward X-Controversial There is active debate or serious implications around merging this PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants