A disabled component that shows data paints its enabled look faded

Component::DISABLED picks how a disabled instance looks: the style's Disabled
state (DisabledLook::States, the default for chrome controls) or its enabled
look at Opacity::DISABLED (DisabledLook::Faded). Step 13 fades the surface,
part layers, paint, faces and paint_over of a faded component; its children
and step 14 paint outside the fade and show their own disabled look. egui
fades a shape as it is added, so a settled region replays the faded paint.

Tile, RowThumb, Swatch, PointPicker, Navigator, PreviewPane, ColorStrip,
ColorArea, PaintChip, PagePicture, PagePictures, ReadingView and DrawPad
declare Faded. The tile's disabled veil and the Disabled entries of the tile
and swatch looks go. Opacity::DISABLED is 0.5, the old disabled fade and the
old knob's disabled share.
This commit is contained in:
aiongg
2026-11-12 14:32:44 +00:00
parent 9a6580c7c5
commit 84639de189
28 changed files with 258 additions and 60 deletions
+2 -1
View File
@@ -5,7 +5,7 @@ use crate::AreaMode;
use craft_behavior::{Metrics, Mixed, Sense};
use craft_theme::ModelValues;
use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PaintUi, Props as _, Role, WordSetCx as _,
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, MeasureCx, PaintUi, Props as _, Role, WordSetCx as _,
};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::Label;
@@ -100,6 +100,7 @@ impl<'a> ColorArea<'a> {
impl Component for ColorArea<'_> {
const SINGLE_VALUE: bool = true;
const ROLE: Role = Role::GROUP;
const DISABLED: DisabledLook = DisabledLook::Faded;
const PARTS: bool = false;
const STOPS: bool = false;
const OVERLAYS: bool = false;
+3 -2
View File
@@ -12,8 +12,8 @@ use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey};
use craft_theme::Srgba;
use craft_ui::choice::{ChoiceWords, Segmented, Swatch};
use craft_ui::contract::{
Access, Activation, Bind, Common, Component, Cx, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, WordSetCx as _,
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _,
PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, WordSetCx as _,
};
use craft_ui::primitives::textures::CachedTexture;
use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth};
@@ -354,6 +354,7 @@ fn value_text(words: &PaintWords, paint: &Paint) -> String {
impl Component for PaintChip<'_> {
const ROLE: Role = Role::COLOR_WELL;
const DISABLED: DisabledLook = DisabledLook::Faded;
type Style = PaintChipStyle;
type Output = PaintChipOutput;
+3 -1
View File
@@ -6,7 +6,8 @@ use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps, step_u
use craft_behavior::{Axis, Metrics, NavMove, PartKey, Sense, ValueDrag};
use craft_theme::ModelValues;
use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, Numeric, PaintUi, PartsCx, Props as _, Role,
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Numeric, PaintUi, PartsCx, Props as _,
Role,
};
use craft_ui::primitives::{PaintShape, StrokeWidth};
use craft_ui::runtime::env::Label;
@@ -127,6 +128,7 @@ impl<'a> ColorStrip<'a> {
impl Component for ColorStrip<'_> {
const SINGLE_VALUE: bool = true;
const ROLE: Role = Role::SLIDER;
const DISABLED: DisabledLook = DisabledLook::Faded;
const OVERLAYS: bool = false;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
type Style = ColorStripStyle;
+3 -1
View File
@@ -10,7 +10,8 @@ use craft_behavior::IconId;
use craft_behavior::{Input, Metrics, PartKey, Sense};
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
CommandSet, Common, Component, Cx, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Props as _, Role, Show as _, ShowContainer as _, clicked,
CommandSet, Common, Component, Cx, DisabledLook, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Props as _, Role, Show as _, ShowContainer as _,
clicked,
};
use craft_ui::dialog::Dialog;
use craft_ui::layout_components::Row;
@@ -212,6 +213,7 @@ impl<'a> PagePicture<'a> {
impl Component for PagePicture<'_> {
const ROLE: Role = Role::IMAGE;
const DISABLED: DisabledLook = DisabledLook::Faded;
const KEYS: KeyUse = KeyUse::of(Input::Pointer);
type Style = PagePictureStyle;
type Output = PagePictureOutput;
+3 -2
View File
@@ -7,8 +7,8 @@
use craft_behavior::{IconId, Metrics, NavMove, PartKey, PressPhase, Sense};
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Access, Animate as _, Common, Component, Cx, Focus as _, Input, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _,
Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, clicked, spec,
Access, Animate as _, Common, Component, Cx, DisabledLook, Focus as _, Input, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _,
Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, clicked, spec,
};
use craft_ui::layout_components::Row;
use craft_ui::primitives::textures::{Priority, TextureStoreOptions, ThumbPaint, ThumbRequest, ThumbnailOptions, Thumbnails, texture_side};
@@ -279,6 +279,7 @@ impl<'a> ReadingView<'a> {
impl Component for ReadingView<'_> {
const ROLE: Role = Role::DOCUMENT;
const DISABLED: DisabledLook = DisabledLook::Faded;
const OVERLAYS: bool = false;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::InlineArrows).with_activate(ActivateKeys::Space).with_moves();
type Style = ReadingViewStyle;
+2 -1
View File
@@ -7,7 +7,7 @@ use crate::ui::access::{AccessDescriber, describe};
use craft_behavior::{Input, Metrics, PixelSize, Sense};
use craft_ui::canvas::DetailPlan;
use craft_ui::canvas::PixelRect;
use craft_ui::contract::{Access, Common, Component, Cx, MeasureCx, NoValue, Outcome, PaintUi, Role};
use craft_ui::contract::{Access, Common, Component, Cx, DisabledLook, MeasureCx, NoValue, Outcome, PaintUi, Role};
use craft_ui::primitives::textures::{
Priority, TextureState, TextureStoreOptions, ThumbPaint, ThumbRequest, ThumbnailOptions, Thumbnails, texture_side,
};
@@ -144,6 +144,7 @@ impl<'a> PagePictures<'a> {
impl Component for PagePictures<'_> {
const ROLE: Role = Role::GROUP;
const DISABLED: DisabledLook = DisabledLook::Faded;
const ALT_ROLES: &'static [Role] = &[Role::None];
const PARTS: bool = false;
const STOPS: bool = false;
+3 -2
View File
@@ -10,8 +10,8 @@ use craft_theme::variant::Tone;
use craft_ui::buttons::Button;
use craft_ui::choice::Segmented;
use craft_ui::contract::{
Bind, BindMut, Common, Component, Cx, Edit as _, Entry, Focus as _, MeasureCx, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _,
ShowContainer as _, clicked,
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, Entry, Focus as _, MeasureCx, PaintUi, PartsCx, Pointer as _, Props as _, Role,
Show as _, ShowContainer as _, clicked,
};
use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft_ui::display::{Picture, PictureSize, Text};
@@ -234,6 +234,7 @@ impl<'a> DrawPad<'a> {
impl Component for DrawPad<'_> {
const ROLE: Role = Role::IMAGE;
const DISABLED: DisabledLook = DisabledLook::Faded;
const OVERLAYS: bool = false;
const SINGLE_VALUE: bool = true;
/// The pad is drawn with the pointer: it takes no activation key, and Undo removes the last stroke.
+3 -2
View File
@@ -215,8 +215,9 @@ impl Easing {
pub struct Opacity;
impl Opacity {
/// Multiplier for disabled controls.
pub const DISABLED: f32 = 0.4;
/// How much of its look a disabled thing keeps: the opacity of a faded component (`DisabledLook::Faded`) and the
/// share a disabled knob's fill moves toward the disabled fill.
pub const DISABLED: f32 = 0.5;
/// Alpha of a window or layer while it moves over a drop target, so what lies under it shows through.
pub const MOVING: f32 = 0.75;
/// Alpha of a mark the app derived, drawn beside the user's own marks of the same kind so those stand out.
@@ -7,8 +7,8 @@ use crate::canvas::zoom_motion::{self, Steer};
use crate::canvas::{CanvasWords, NavigationOptions, PageKey, ViewCommands, WheelAction, WheelNavigation};
use crate::canvas_data::ProxyColor;
use crate::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi,
PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
};
use crate::primitives::textures::CachedTexture;
use crate::primitives::{ContentPainterCx, PaintShape};
@@ -289,6 +289,7 @@ fn take_navigation(cx: &mut Cx<'_, Navigator<'_>>, next: &mut CanvasView, runnin
impl Component for Navigator<'_> {
const ROLE: Role = Role::GROUP;
const DISABLED: DisabledLook = DisabledLook::Faded;
const OVERLAYS: bool = false;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
const BINDS_VIEW: bool = true;
@@ -126,7 +126,7 @@ impl BodyHooks<'_> {
if !overflow {
continue;
}
let enabled = cx.core.resolved.enabled;
let enabled = cx.core.looks_enabled();
let state = crate::contract::steps::part_state(
cx.core.results.get(&(bar.key, Some(crate::contract::cx::THUMB))).unwrap_or(&crate::primitives::PartResult::IDLE),
enabled,
@@ -160,6 +160,11 @@ pub struct CxCore<'a> {
pub(crate) texts: Option<(PartKey, Box<dyn TextResult>)>,
/// The selection parts step 7 declared, which `PaintUi::selectable_text` shows.
pub(crate) selections: Vec<craft_behavior::PartRef>,
/// Not enabled, with `DisabledLook::Faded`: the component and its faces paint their enabled look, which step 13
/// fades.
pub(crate) faded: bool,
/// The opacity of the component's `Ui` before step 13 faded it, which its children paint at.
pub(crate) unfaded: Option<f32>,
/// Where the text part reserved the surface in the painter, so the field's surface paints beneath its text.
pub(crate) surface_slot: Option<egui::layers::ShapeIdx>,
/// The editor part as step 8b set it up.
+12 -2
View File
@@ -25,6 +25,12 @@ pub trait Styled {
}
impl CxCore<'_> {
/// Whether the component paints its enabled look: it is enabled, or it is `faded` and the fade alone shows that it
/// is not.
pub(crate) fn looks_enabled(&self) -> bool {
self.resolved.enabled || self.faded
}
fn assert_stated(&self) {
debug_assert!(self.stated, "the state set is written at step 12; it is not readable in `update` or `overlay`");
}
@@ -69,8 +75,10 @@ impl CxCore<'_> {
}
}
let pressed = result.pressed();
let state = if !self.resolved.enabled || result.inactive {
let state = if !self.looks_enabled() || result.inactive {
craft_theme::State::Disabled
} else if !self.resolved.enabled {
craft_theme::State::Rest
} else if pressed {
craft_theme::State::Pressed
} else if hovered {
@@ -94,8 +102,10 @@ impl Styled for CxCore<'_> {
self.assert_stated();
let hovered = self.response.hovered() && !self.results.values().any(|result| result.hovered);
let pressed = self.press.phase.is_press();
let state = if !self.resolved.enabled {
let state = if !self.looks_enabled() {
craft_theme::State::Disabled
} else if !self.resolved.enabled {
craft_theme::State::Rest
} else if pressed {
craft_theme::State::Pressed
} else if hovered {
@@ -697,7 +697,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
if content > f64::from(rect.height()) {
let span = ScrollSpan::new(0.0..content, self.offset..self.offset + f64::from(rect.height()));
let result = cx.core.results.get(&(SCROLL, Some(crate::contract::cx::THUMB))).cloned().unwrap_or(crate::primitives::PartResult::IDLE);
let state = crate::contract::steps::part_state(&result, cx.core.resolved.enabled, None);
let state = crate::contract::steps::part_state(&result, cx.core.looks_enabled(), None);
ui.painter().extend(ScrollBar::shapes(&look, track, Axis::Y, rtl, &span, &state, ui.ctx().pixels_per_point()));
}
}
+15
View File
@@ -289,6 +289,19 @@ pub const MAX_EXTENT: f32 = 32_768.0;
/// a dialog.
pub trait Pattern {}
/// How a component that is not enabled looks (`Component::DISABLED`). Either way it takes no input, its access node
/// is disabled and the children it shows inherit the disabled state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DisabledLook {
/// The style's Disabled state: `text.disabled` ink, the theme's disabled fills. Controls whose look is chrome
/// (buttons, fields, sliders) take it.
States,
/// The component paints its enabled look at `Opacity::DISABLED`: its surface, its paint, its faces and
/// `paint_over`, not its focus ring. A component that shows data (a picture, a colour, a plot) takes it, so the
/// data dims with the rest. The children it shows are not inside the fade; each shows its own disabled look.
Faded,
}
/// The core trait: every UI type is a `Component`.
pub trait Component: Meta + Sized {
/// The AccessKit role.
@@ -331,6 +344,8 @@ pub trait Component: Meta + Sized {
/// canvas view), not a value the user edits. The wheel moves a view without focus, as it scrolls a scroll
/// region; a bound value control takes it only while focused or armed.
const BINDS_VIEW: bool = false;
/// How a disabled instance looks: token states (the default), or its enabled look faded.
const DISABLED: DisabledLook = DisabledLook::States;
/// The style type.
type Style: ComponentStyle;
+20 -3
View File
@@ -47,6 +47,8 @@ pub struct PaintUi<'a> {
pub(crate) size: ControlSize,
/// The selection parts step 7 declared.
pub(crate) selections: &'a [PartRef],
/// The opacity before step 13 faded the component (`DisabledLook::Faded`): its children paint at it.
pub(crate) unfaded: Option<f32>,
/// The children's `Ui`, built on the first child under `sub(id, "children")`.
pub(crate) kids: Option<Ui>,
}
@@ -188,9 +190,15 @@ impl PaintUi<'_> {
fn child_with<C: Show>(&mut self, id: Id, rect: Rect, child: C, tip: Option<TipFn<'_>>, inside: Option<Arc<InsideLabel>>) -> C::Output {
let scope = sub(self.id, "children");
let parent = &mut *self.ui;
let unfaded = self.unfaded;
let kids = self.kids.get_or_insert_with(|| {
let builder = egui::UiBuilder::new().layout(child::pinned_layout()).scope_id(scope).max_rect(self.rect);
alloc::child(parent, access::with_parent(builder, self.id))
let mut kids = alloc::child(parent, access::with_parent(builder, self.id));
// A child shows its own disabled look, outside its owner's fade.
if let Some(opacity) = unfaded {
kids.set_opacity(opacity);
}
kids
});
let ctx = kids.ctx().clone();
let env = super::cx::child_env(&Env::of(kids), &super::cx::Under { enabled: self.enabled, size: self.size, inside });
@@ -222,8 +230,17 @@ impl PaintUi<'_> {
return;
};
let focus = self.active.filter(|(active, _)| *active == part).map(|(_, visible)| visible);
let source =
FaceSource { id: self.id, result, focus, response: self.response, ink, muted: self.muted, flags: self.flags, enabled: self.enabled };
let source = FaceSource {
id: self.id,
result,
focus,
response: self.response,
ink,
muted: self.muted,
flags: self.flags,
enabled: self.enabled,
faded: self.unfaded.is_some(),
};
let record = run::paint_face(self.ui, self.env, &source, part, face);
let mut own = self.record.borrow_mut();
if let Some(baseline) = record.baseline {
+14 -1
View File
@@ -371,6 +371,8 @@ fn blank_core<'a>(
gestures: Default::default(),
texts: None,
selections: Vec::new(),
faded: false,
unfaded: None,
surface_slot: None,
editor: None,
editor_inputs: Vec::new(),
@@ -399,6 +401,8 @@ pub(crate) struct TypeFacts {
pub canvas_control: bool,
pub labelled_after: bool,
pub binds_view: bool,
/// `DISABLED` is `Faded`.
pub faded: bool,
/// The style key's type, which `Auto` ids are counted per.
pub style_key: TypeId,
}
@@ -416,6 +420,7 @@ impl TypeFacts {
canvas_control: C::CANVAS_CONTROL,
labelled_after: C::LABELLED_AFTER,
binds_view: C::BINDS_VIEW,
faded: C::DISABLED == super::DisabledLook::Faded,
style_key: TypeId::of::<C::StyleKey>(),
}
}
@@ -561,6 +566,7 @@ pub(super) fn paint_ui<'a>(ui: &'a mut Ui, env: &'a Env, core: &'a CxCore<'_>, s
enabled: core.resolved.enabled,
size: core.resolved.size,
selections: &core.selections,
unfaded: core.unfaded,
kids: None,
}
}
@@ -1020,6 +1026,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option<ShowAt>, h
p.trace.mark(Step::Paint);
let mut values = AppValues::default();
e.content_env(&mut values);
let unfaded = steps::fade(ui, e.core());
steps::paint_surface(ui, env, e.core_ref(), style);
steps::paint_part_layers(ui, env, e.core_ref());
// Paint and content stay inside the rect (grown by the type's declared outset), however small the room is.
@@ -1027,6 +1034,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option<ShowAt>, h
let inside = e.core_ref().rect.expand(e.paint_outset(&env.tokens)).intersect(outer_clip);
ui.set_clip_rect(inside);
e.paint(ui, env);
ui.set_opacity(unfaded);
ui.set_clip_rect(outer_clip);
steps::paint_focus(ui, e.core_ref(), style);
ui.set_clip_rect(inside);
@@ -1056,7 +1064,9 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option<ShowAt>, h
ui.set_clip_rect(outer_clip);
sensing::place_over_widgets(ui, id, member, decls);
ui.set_clip_rect(inside);
steps::fade(ui, e.core());
e.paint_over(ui, env);
ui.set_opacity(unfaded);
ui.set_clip_rect(outer_clip);
// 15 settle
p.trace.mark(Step::Settle);
@@ -1272,7 +1282,8 @@ pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option<T
log::debug!("{} measured the size {size:?} and shows nothing", facts.name);
}
}
let core = blank_core(env.view(), &resolved, &mut stage, ctx.clone(), env.ink, steps::inert_response(ui, id), step1.command.clone());
let mut core = blank_core(env.view(), &resolved, &mut stage, ctx.clone(), env.ink, steps::inert_response(ui, id), step1.command.clone());
core.faded = facts.faded && !resolved.enabled;
// 6 to 16, in the host's `Ui`, once per call of the host.
let mut host = t.host(HostCx { ui: &*ui, env, id, label: &step1.label, size });
let parent = ui.scope_id();
@@ -1392,4 +1403,6 @@ pub(crate) struct FaceSource<'a> {
pub flags: crate::style::Flags,
/// Whether the host is enabled: a face of a disabled host paints with the Disabled state.
pub enabled: bool,
/// The host is faded (`DisabledLook::Faded`): its faces paint their enabled look inside its fade.
pub faded: bool,
}
+9 -3
View File
@@ -598,9 +598,10 @@ pub(crate) fn paint_face<C: Show>(ui: &mut Ui, env: &Env, source: &super::FaceSo
stage.face = true;
let rect = source.result.rect;
let flow = Flow::new(rect, env.direction.is_rtl());
let part_state = steps::part_state(source.result, step1.enabled && source.enabled, source.focus);
let part_state = steps::part_state(source.result, source.faded || (step1.enabled && source.enabled), source.focus);
let mut core = blank_core(env.view(), &resolved, &mut stage, ctx.clone(), env.ink, source.response.clone(), None);
core.face_mode = true;
core.faded = source.faded;
core.rect = rect;
core.content_rect = flow.inset(StyleView::metrics(&*style).padding);
core.flow = flow;
@@ -633,6 +634,7 @@ pub(crate) fn paint_face<C: Show>(ui: &mut Ui, env: &Env, source: &super::FaceSo
enabled: step1.enabled && source.enabled,
size: step1.size,
selections: &[],
unfaded: None,
kids: None,
};
face.paint(&mut pui, &cx);
@@ -738,7 +740,8 @@ pub(crate) fn member_show<C: Show>(
let rtl = env.direction.is_rtl();
let resolved = steps::resolved(id, &step1, &common);
let enabled = node.enabled && step1.enabled;
let hovered = sensed.response.hovered();
let faded = !enabled && C::DISABLED == crate::contract::DisabledLook::Faded;
let hovered = sensed.response.hovered() && !faded;
let result = crate::primitives::PartResult {
rect: row,
press: sensed.press,
@@ -749,11 +752,12 @@ pub(crate) fn member_show<C: Show>(
inactive: false,
held: false,
};
let part_state = steps::part_state(&result, enabled, None);
let part_state = steps::part_state(&result, enabled || faded, None);
// A peek that opens no lifetime stage and is dropped without a write-back, as a face's.
let mut stage = MemoryStage::open_peek(&ctx, id);
stage.face = true;
let mut core = blank_core(env.view(), &resolved, &mut stage, ctx.clone(), env.ink, sensed.response, step1.command.clone());
core.faded = faded;
let flow = Flow::new(row, rtl);
core.rect = row;
core.content_rect = flow.inset(StyleView::metrics(&*style).padding);
@@ -772,10 +776,12 @@ pub(crate) fn member_show<C: Show>(
cx.core.stated = true;
cx.core.ink = steps::surface_ink(StyleView::surface(&*style), &state, env.ink);
item.update(&mut cx);
let unfaded = steps::fade(ui, &mut cx.core);
steps::paint_surface(ui, env, &cx.core, &*style);
steps::paint_part_layers(ui, env, &cx.core);
item.paint(&mut super::paint_ui(ui, env, &cx.core, &*style), &cx);
item.paint_over(&mut super::paint_ui(ui, env, &cx.core, &*style), &cx);
ui.set_opacity(unfaded);
let mut access = Access::default();
item.access(&mut access, &cx);
let member_node = report_member(&cx.core, &access, node, C::ROLE);
+1 -1
View File
@@ -30,7 +30,7 @@ pub(super) use id::measuring;
pub(crate) use id::{draft, id, keeping_ids};
pub(crate) use label::scrub_by_label;
pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_cx};
pub(crate) use paint::{paint_focus, paint_part_layers, paint_surface, surface_ink};
pub(crate) use paint::{fade, paint_focus, paint_part_layers, paint_surface, surface_ink};
pub(crate) use parts::{PartsStep, check_parts, declares_none};
pub(crate) use place::place;
pub(crate) use report::{ReportIn, report, report_inert, report_parts, validity_of};
@@ -12,6 +12,18 @@ pub(crate) fn surface_ink(look: Option<&crate::style::SurfaceLook>, state: &Stat
look.and_then(|look| look.kind_in(state)).map_or(inherited, |kind| kind.ink())
}
/// Step 13 for a component that is `faded` (`DisabledLook::Faded`, not enabled): multiplies `ui`'s opacity by
/// `Opacity::DISABLED` until the caller sets it back. Returns the opacity before, which the focus ring, step 14 and the
/// children `PaintUi` shows paint at. egui fades a shape as it is added, so a run record keeps the faded shapes.
pub(crate) fn fade(ui: &mut Ui, core: &mut CxCore<'_>) -> f32 {
let before = core.unfaded.unwrap_or_else(|| ui.opacity());
if core.faded {
ui.set_opacity(before * craft_theme::Opacity::DISABLED);
core.unfaded = Some(before);
}
before
}
/// Step 13, paint, the pipeline's part before `C::paint`: the root surface and the state fill.
pub(crate) fn paint_surface(ui: &Ui, env: &Env, core: &CxCore<'_>, style: &dyn StyleView) {
let Some(look) = style.surface() else { return };
@@ -76,7 +76,8 @@ pub(crate) fn state(p: &mut dyn ErasedPass<'_>, style: &dyn StyleView, open: boo
flags |= Flags::INVALID;
}
core.sync_focus();
let (hovered, pressed) = (core.response.hovered(), core.press.phase.is_press());
// A faded component shows no hover or press: its rest look is its disabled look.
let (hovered, pressed) = if core.faded { (false, false) } else { (core.response.hovered(), core.press.phase.is_press()) };
let (focused, visible) = (core.focus.focused, core.focus.visible);
if focused {
flags |= Flags::FOCUSED;
@@ -84,8 +85,10 @@ pub(crate) fn state(p: &mut dyn ErasedPass<'_>, style: &dyn StyleView, open: boo
if visible {
flags |= Flags::FOCUS_VISIBLE;
}
let state = if !core.resolved.enabled {
let state = if !core.looks_enabled() {
State::Disabled
} else if !core.resolved.enabled {
State::Rest
} else if pressed || flags.contains(Flags::OPEN) {
State::Pressed
} else if hovered {
@@ -3,8 +3,8 @@
use crate::buttons::IconButton;
use crate::contract::{
Bind, Common, Component, Cx, Focus as _, Input, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _,
ShowContainer as _,
Bind, Common, Component, Cx, DisabledLook, Focus as _, Input, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role,
Show as _, ShowContainer as _,
};
use crate::display::{Progress, Text};
use crate::layout_components::Row;
@@ -375,6 +375,7 @@ impl PreviewPane<'_> {
impl Component for PreviewPane<'_> {
const ROLE: Role = Role::GROUP;
const DISABLED: DisabledLook = DisabledLook::Faded;
const OVERLAYS: bool = false;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
type Style = PreviewPaneStyle;
+5 -5
View File
@@ -4,8 +4,8 @@
use super::radio::RadioKind;
use super::words::ChoiceWords;
use crate::contract::{
Access, Activation, Common, Component, Cx, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, Pointer as _, Props as _, Role, Styled as _,
WordSetCx as _,
Access, Activation, Common, Component, Cx, DisabledLook, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, Pointer as _, Props as _, Role,
Styled as _, WordSetCx as _,
};
use crate::primitives::{Checker, ContentPainterCx, Draw, PaintShape, StrokeWidth, glyph};
use crate::runtime::requests::ColorRequest;
@@ -199,6 +199,7 @@ impl<T: Value + 'static> Component for Swatch<T> {
const PARTS: bool = false;
const OVERLAYS: bool = false;
const ALT_ROLES: &'static [Role] = &[Role::RADIO_BUTTON, Role::LIST_BOX_OPTION];
const DISABLED: DisabledLook = DisabledLook::Faded;
type Style = SwatchStyle;
type Output = SwatchOutput;
@@ -208,14 +209,13 @@ impl<T: Value + 'static> Component for Swatch<T> {
let clear = cx.color(Rgba::TRANSPARENT);
let rest = cx.color(colors.line.control_edge);
let accent = cx.color(colors.accent.solid);
let disabled = cx.color(colors.text.disabled);
SwatchStyle {
metrics: Metrics::new(),
focus: cx.focus_look(),
side: if key.cell && !key.well { metrics.cell } else { metrics.side },
radius: if key.cell && !key.well { CornerRadius::ZERO } else { metrics.radius },
edge: Stateful::new(rest).off(States::new(rest, rest, rest, disabled)),
ring: Stateful::new(clear).on(States::new(accent, accent, accent, disabled)),
edge: Stateful::new(rest),
ring: Stateful::new(clear).on(States::new(accent, accent, accent, accent)),
mark: cx.color(colors.text.normal),
mixed_fill: cx.color(colors.surface.sunken),
mixed_mark: cx.color(colors.text.muted),
+2 -1
View File
@@ -2,7 +2,7 @@
#[cfg(doc)]
use super::ListRow;
use crate::contract::{Common, Component, Cx, PaintUi, Role};
use crate::contract::{Common, Component, Cx, DisabledLook, PaintUi, Role};
use crate::list::words::ListWords;
use crate::primitives::ContentPainterCx;
use crate::runtime::env::Label;
@@ -142,6 +142,7 @@ impl Component for RowThumb<'_> {
const PARTS: bool = false;
const STOPS: bool = false;
const OVERLAYS: bool = false;
const DISABLED: DisabledLook = DisabledLook::Faded;
type Style = RowThumbStyle;
type Output = Response;
+6 -22
View File
@@ -12,8 +12,8 @@ use super::{BadgeKind, BadgeSlot, BadgeVisibility, CaptionPlace, TileBadge, Tile
use crate::buttons::IconButton;
use crate::choice::{Checkbox, ChoiceWords, Rating};
use crate::contract::{
Access, Bind, Common, Component, Cx, Focus as _, ItemOutput, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role,
Styled as _, WordSetCx as _,
Access, Bind, Common, Component, Cx, DisabledLook, Focus as _, ItemOutput, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _,
Props as _, Role, Styled as _, WordSetCx as _,
};
use crate::display::Badge;
use crate::list::{RowThumb, ThumbAspect, ThumbPaint, ToggleState};
@@ -24,7 +24,7 @@ use crate::style::{ComponentStyle, Corners, DataColor, Flags, IconLook, StyleCol
use craft_behavior::{AccessAction, AccessData, Flow, IconId, Insets, Metrics, Mixed, NavShape, PartKey, PressPhase, Proposal, Roving, Sense};
use craft_keymap::Mods;
use craft_theme::variant::{Emphasis, Tone};
use craft_theme::{Opacity, Rgba, Srgba, Stateful, States, TypeRole, Variant, over};
use craft_theme::{Rgba, Srgba, Stateful, States, TypeRole, Variant, over};
use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2};
/// Stars a rating has.
@@ -228,7 +228,6 @@ pub struct TileStyle {
pill_icon: IconLook,
placeholder: StyleColor,
dim: StyleColor,
veil: Stateful<StyleColor>,
/// The fill under the badge bar and the check box, over the picture.
plate: StyleColor,
pill: StyleColor,
@@ -596,6 +595,7 @@ fn badge_rects(flow: Flow, widths: &[f32], height: f32, sizes: &Sizes, plate: Op
impl Component for Tile<'_> {
const ROLE: Role = Role::LIST_ITEM;
const OVERLAYS: bool = false;
const DISABLED: DisabledLook = DisabledLook::Faded;
type Style = TileStyle;
type Output = TileOutput;
@@ -631,21 +631,11 @@ impl Component for Tile<'_> {
let surface = SurfaceLook::new(fill).radius(radius).border(edge, tokens.stroke.thick);
let surface = if key.card { surface.kind(SurfaceKind::Raised) } else { surface };
let on_selected = c(text.on_selected);
let ink = |base: StyleColor| {
Stateful::new(base).off(States::new(base, base, base, c(text.disabled))).on(States::new(
on_selected,
on_selected,
on_selected,
on_selected,
))
};
let ink = |base: StyleColor| Stateful::new(base).on(States::new(on_selected, on_selected, on_selected, on_selected));
let fixed = |color: Rgba| Stateful::new(c(color));
let pill = cx.with_variant(pill_variant(Tone::Neutral)).variant_look();
let plate = c(colors.surface.scrim);
let on_bar = |ink: StyleColor, side: f32| IconLook::new(side, Stateful::new(ink)).on(Stateful::new(plate));
// A disabled tile's picture moves toward the disabled fill as a disabled surface's fill does.
let disabled = c(colors.state.disabled_fill.faded(Opacity::DISABLED));
let veil = Stateful::new(c(clear)).off(States::new(c(clear), c(clear), c(clear), disabled));
TileStyle {
surface,
metrics: Metrics::new().padding(Insets::new(sizes.inset, sizes.inset, sizes.inset, sizes.inset)).gap(sizes.tight),
@@ -662,15 +652,10 @@ impl Component for Tile<'_> {
stars: on_bar(c(text.on_strong), tokens.size.icon.glyph_sm),
picked: on_bar(cx.tone(Tone::Good), sizes.glyph),
rejected: on_bar(cx.tone(Tone::Bad), sizes.glyph),
face: IconLook::new(
sizes.face,
Stateful::new(c(text.muted)).off(States::new(c(text.muted), c(text.muted), c(text.muted), c(text.disabled))),
)
.on(fixed(colors.surface.sunken)),
face: IconLook::new(sizes.face, fixed(text.muted)).on(fixed(colors.surface.sunken)),
pill_icon: IconLook::new(sizes.glyph, pill.text.clone()).on(pill.fill.clone()),
placeholder: c(colors.surface.sunken),
dim: c(colors.surface.scrim.faded(DIM_VEIL)),
veil,
plate,
pill: pill.fill.off.rest,
band: c(colors.status.bad.solid),
@@ -820,7 +805,6 @@ impl Component for Tile<'_> {
if self.dimmed || self.rejected || self.hidden {
draw.fill(&PaintShape::Rect(picture, flat), style.dim);
}
draw.fill(&PaintShape::Rect(picture, flat), cx.resolve(&style.veil));
self.paint_range_and_scrub(&draw, cx, picture);
}
self.paint_band(ui, cx, &placed);
@@ -4,8 +4,8 @@
//! `NumberField`s the caller shows beside it, bound to the same value.
use crate::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Numeric, PaintUi, PartsCx, Pointer as _,
Props as _, Role, WordSetCx as _,
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Numeric, PaintUi, PartsCx,
Pointer as _, Props as _, Role, WordSetCx as _,
};
use crate::primitives::{ContentPainterCx, PaintShape};
use crate::runtime::access::Name;
@@ -333,6 +333,7 @@ impl Component for PointPicker<'_> {
const ROLE: Role = Role::GROUP;
const OVERLAYS: bool = false;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
const DISABLED: DisabledLook = DisabledLook::Faded;
type Style = PointPickerStyle;
type Output = EditResponse<[Mixed<f64>; 2]>;
+116
View File
@@ -0,0 +1,116 @@
//! `DisabledLook::Faded`: a disabled component that shows data paints its enabled look at `Opacity::DISABLED`, its
//! faces and the faded children it shows each faded once; a settled region holding one replays the faded paint.
use craft_theme::variant::Tone;
use craft_theme::{Opacity, Srgba};
use craft_ui::buttons::Button;
use craft_ui::contract::{Lazy, Props as _, Show as _};
use craft_ui::list::ThumbAspect;
use craft_ui::runtime::env::Label;
use craft_ui::testing::layout::in_region;
use craft_ui::testing::{Frames, trial};
use craft_ui::tile_grid::{BadgeKind, BadgeSlot, Tile, TileBadge};
use egui::epaint::ColorMode;
use egui::{Color32, Rect, Shape, Ui, pos2};
use std::cell::Cell;
const REGION: Rect = Rect { min: pos2(10.0, 10.0), max: pos2(210.0, 310.0) };
/// A tile with a picture (its `RowThumb` child), a text badge (a face), the stars (a face), a colour dot and a caption.
fn tile(ui: &mut Ui, enabled: bool) {
in_region(ui, REGION, |ui| {
Tile::new("IMG_0002.jpg")
.thumb(ThumbAspect::SQUARE, |cx, rect| {
cx.painter.rect_filled(rect, 0.0, Color32::from_rgb(0x30, 0x90, 0xd0));
})
.badge(TileBadge::new(BadgeSlot::EndTop, BadgeKind::Text(Label::from("1/3")), Tone::Neutral, None))
.rating(3)
.label_color(Srgba::rgb(0.86, 0.31, 0.24))
.enabled(enabled)
.show(ui);
});
}
/// The strongest alpha among the colours `shape` paints with, or `None` for a shape that paints none.
fn alpha(shape: &Shape) -> Option<u8> {
let solid = |mode: &ColorMode| match mode {
ColorMode::Solid(color) => color.a(),
ColorMode::UV(_) => 0,
};
let alphas: Vec<u8> = match shape {
Shape::Rect(rect) => vec![rect.fill.a(), rect.stroke.color.a()],
Shape::Circle(circle) => vec![circle.fill.a(), circle.stroke.color.a()],
Shape::Ellipse(ellipse) => vec![ellipse.fill.a(), ellipse.stroke.color.a()],
Shape::Path(path) => vec![path.fill.a(), solid(&path.stroke.color)],
Shape::LineSegment { stroke, .. } => vec![stroke.color.a()],
Shape::Mesh(mesh) => mesh.vertices.iter().map(|vertex| vertex.color.a()).collect(),
Shape::Text(text) => text.galley.rows.iter().flat_map(|row| row.row.visuals.mesh.vertices.iter().map(|vertex| vertex.color.a())).collect(),
_ => Vec::new(),
};
alphas.into_iter().max().filter(|a| *a > 0)
}
fn alphas(shapes: &[Shape]) -> Vec<Option<u8>> {
shapes.iter().map(alpha).collect()
}
/// The shapes of a frame once the scene shows the same thing two frames running.
fn settled_shapes(frames: &mut Frames, mut scene: impl FnMut(&mut Ui)) -> Vec<Shape> {
frames.idle(4, &mut scene);
frames.frame_shapes(&mut scene)
}
/// Every shape a disabled tile paints is `Opacity::DISABLED` as opaque as the same shape enabled: its own paint, its
/// faces and its picture, which the `RowThumb` child fades itself. Nothing is faded twice, and the text keeps its
/// enabled colours. A disabled button keeps its token look and paints nothing faded.
#[trial]
fn a_disabled_faded_component_paints_its_enabled_look_faded_once() {
let enabled = settled_shapes(&mut Frames::new(), |ui| tile(ui, true));
let disabled = settled_shapes(&mut Frames::new(), |ui| tile(ui, false));
assert_eq!(enabled.len(), disabled.len(), "a disabled tile paints the shapes it paints enabled");
let mut faded = 0;
for (at, (on, off)) in alphas(&enabled).into_iter().zip(alphas(&disabled)).enumerate() {
let Some(on) = on else { continue };
let off = f32::from(off.unwrap_or(0));
let expected = f32::from(on) * Opacity::DISABLED;
assert!((off - expected).abs() <= 1.5, "shape {at}: alpha {off} disabled, {on} enabled: {:?}", disabled[at]);
faded += 1;
}
assert!(faded > 5, "the picture, the badge, the stars, the dot and the caption each paint: {faded}");
let fallbacks = |shapes: &[Shape]| -> Vec<Color32> {
shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text.fallback_color.to_opaque()) } else { None }).collect()
};
assert_eq!(fallbacks(&enabled), fallbacks(&disabled), "the disabled tile's text keeps its enabled ink");
let button = settled_shapes(&mut Frames::new(), |ui| {
in_region(ui, REGION, |ui| {
Button::new("Apply").enabled(false).show(ui);
});
});
assert!(
button.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).all(|text| text.opacity_factor == 1.0),
"a disabled button is not faded"
);
}
/// A settled region holding a disabled faded tile runs nothing, and replays the faded paint of the frame that ran.
#[trial]
fn a_settled_region_replays_a_faded_component_without_running_it() {
let runs = Cell::new(0);
let scene = |ui: &mut Ui| {
Lazy::new("faded", 0.0).settles(true).show(ui, |ui| {
runs.set(runs.get() + 1);
tile(ui, false);
});
};
let ran = settled_shapes(&mut Frames::new(), |ui| tile(ui, false));
let mut frames = Frames::new();
frames.frame(vec![], scene);
assert!(runs.get() > 0, "the first frame runs the region");
frames.idle(30, scene);
for frame in 0..4 {
runs.set(0);
let shapes = frames.frame_shapes(scene);
assert_eq!(runs.get(), 0, "settled frame {frame} ran the region");
assert_eq!(alphas(&shapes), alphas(&ran), "settled frame {frame} paints the faded shapes a run paints");
}
}
+1
View File
@@ -8,6 +8,7 @@ mod bars;
pub(crate) mod body;
mod commands;
mod contract;
mod disabled_fade;
mod field_text_centred;
mod keys;
mod label;
+2
View File
@@ -428,6 +428,8 @@ Semantic tokens fall in eight groups: surface, text, line, accent, status, state
Accent fills that carry text use the strong pair: the accent moved in lightness only as far as white text needs.
A disabled component looks one of two ways (`Component::DISABLED`). A control whose look is chrome (a button, a field, a slider) takes its style's Disabled state: `text.disabled` ink and the disabled fills. A component that shows data (a picture, a colour, a plot, a tile) declares `DisabledLook::Faded`: step 13 paints its enabled look, faces included, at `Opacity::DISABLED`, so its data dims with the rest. The children it shows stay outside its fade and show their own disabled look.
### 5.2 Typography
App text maps to the nearest named role. A real new need gets a new role. No role serves a single use.