mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 10:48:15 +01:00
Merge branch 'merge-fw/lint' into merge-fw/main
This commit is contained in:
commit
caa0e85b8e
32 files changed
+290
-174
No files matched your search
@@ -59,6 +59,7 @@ impl ServerLimits {
|
||||
/// How [`serve_with`] runs a server: its [`ServerLimits`], the clock its authentication deadline is
|
||||
/// read against, and a signal for each ended connection. A [`ServerLimits`] converts into the
|
||||
/// options with the real clock and no signal.
|
||||
#[non_exhaustive]
|
||||
pub struct ServeOptions {
|
||||
/// The caps on lines and the time a connection has to authenticate.
|
||||
pub limits: ServerLimits,
|
||||
@@ -69,6 +70,18 @@ pub struct ServeOptions {
|
||||
pub ended: Option<Sender<()>>,
|
||||
}
|
||||
|
||||
impl ServeOptions {
|
||||
/// Sets the clock the authentication deadline is read against.
|
||||
pub fn clock(self, clock: DeadlineClock) -> Self {
|
||||
Self { clock, ..self }
|
||||
}
|
||||
|
||||
/// Sets the sender that gets `()` each time a connection has ended.
|
||||
pub fn ended(self, ended: Sender<()>) -> Self {
|
||||
Self { ended: Some(ended), ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ServeOptions {
|
||||
fn default() -> Self {
|
||||
ServerLimits::default().into()
|
||||
|
||||
@@ -12,10 +12,9 @@ fn a_failed_accept_waits_before_the_next() {
|
||||
let failed = || Err(std::io::Error::other("no file descriptors left"));
|
||||
let waits = Cell::new(0);
|
||||
let incoming = [failed(), Ok(1), failed(), failed(), Ok(2)].into_iter().map(|result| {
|
||||
result.map(|connection| {
|
||||
let preceding_failures = if connection == 1 { 1 } else { 3 };
|
||||
result.inspect(|connection| {
|
||||
let preceding_failures = if *connection == 1 { 1 } else { 3 };
|
||||
assert_eq!(waits.get(), preceding_failures, "every failure waits before the next accept");
|
||||
connection
|
||||
})
|
||||
});
|
||||
let connections: Vec<_> = accepted(incoming, || waits.set(waits.get() + 1)).collect();
|
||||
|
||||
@@ -146,7 +146,7 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
|
||||
let _ = read.send(());
|
||||
now
|
||||
});
|
||||
let options = ServeOptions { limits: ServerLimits::default().auth_deadline(Duration::from_secs(10)), clock, ended: Some(ended) };
|
||||
let options = ServeOptions::from(ServerLimits::default().auth_deadline(Duration::from_secs(10))).clock(clock).ended(ended);
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(HANG)).expect("timeout");
|
||||
@@ -199,8 +199,7 @@ fn a_reset_connection_counts_as_closed() {
|
||||
fn serve_counting_ends() -> (Receiver<ControlRequest>, server::Listening, Receiver<()>) {
|
||||
let (ended, connection_ended) = channel();
|
||||
let start = motion::now();
|
||||
let options =
|
||||
ServeOptions { limits: ServerLimits::default().auth_deadline(Duration::from_secs(60)), clock: Arc::new(move || start), ended: Some(ended) };
|
||||
let options = ServeOptions::from(ServerLimits::default().auth_deadline(Duration::from_secs(60))).clock(Arc::new(move || start)).ended(ended);
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
(rx, server, connection_ended)
|
||||
}
|
||||
|
||||
@@ -147,29 +147,32 @@ impl<'a> ThemeColorMenu<'a> {
|
||||
let standard: Vec<_> = STANDARD_COLORS.iter().map(|(color, name)| (Label::from(*name), MenuColor::from(*color).swatch())).collect();
|
||||
let stack = Stack::new().id(cx.id.with("theme-color-menu")).gap(Gap::None).least_width(LeastWidth::Popup);
|
||||
let mut shown = stack.show(ui, |ui, _| {
|
||||
let mut pick = None;
|
||||
let mut eyedropper = None;
|
||||
Text::new(words.theme.clone()).role(TypeRole::BodyStrong).show(ui);
|
||||
let table = SwatchTable::new(words.theme_table.fill(&[("label", label.as_str())]), &theme)
|
||||
.per_row(slots.len())
|
||||
.selection(Bind::given(Selection::default()))
|
||||
.tips(true)
|
||||
.spacing(SwatchSpacing::Spaced)
|
||||
.show_all(ui);
|
||||
if let Some(at) = table.selected {
|
||||
pick = picks.get(at).cloned();
|
||||
}
|
||||
ui.add_space(Gap::Tight.points(ui));
|
||||
Text::new(words.standard.clone()).role(TypeRole::BodyStrong).show(ui);
|
||||
let table = SwatchTable::new(words.standard_table.fill(&[("label", label.as_str())]), &standard)
|
||||
.per_row(STANDARD_COLORS.len())
|
||||
.selection(Bind::given(Selection::default()))
|
||||
.tips(true)
|
||||
.spacing(SwatchSpacing::Spaced)
|
||||
.show_all(ui);
|
||||
if let Some((color, _)) = table.selected.and_then(|at| STANDARD_COLORS.get(at)) {
|
||||
pick = Some(MenuColor::from(*color).pick());
|
||||
}
|
||||
// The two swatch sections stand a tight gap apart; each heading sits on its table.
|
||||
let tables = Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
let themed = Stack::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
Text::new(words.theme.clone()).role(TypeRole::BodyStrong).show(ui);
|
||||
let table = SwatchTable::new(words.theme_table.fill(&[("label", label.as_str())]), &theme)
|
||||
.per_row(slots.len())
|
||||
.selection(Bind::given(Selection::default()))
|
||||
.tips(true)
|
||||
.spacing(SwatchSpacing::Spaced)
|
||||
.show_all(ui);
|
||||
table.selected.and_then(|at| picks.get(at).cloned())
|
||||
});
|
||||
let standard = Stack::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
Text::new(words.standard.clone()).role(TypeRole::BodyStrong).show(ui);
|
||||
let table = SwatchTable::new(words.standard_table.fill(&[("label", label.as_str())]), &standard)
|
||||
.per_row(STANDARD_COLORS.len())
|
||||
.selection(Bind::given(Selection::default()))
|
||||
.tips(true)
|
||||
.spacing(SwatchSpacing::Spaced)
|
||||
.show_all(ui);
|
||||
table.selected.and_then(|at| STANDARD_COLORS.get(at)).map(|(color, _)| MenuColor::from(*color).pick())
|
||||
});
|
||||
standard.inner.flatten().or(themed.inner.flatten())
|
||||
});
|
||||
let mut pick = tables.inner.flatten();
|
||||
Divider::horizontal().show(ui);
|
||||
if let Some(none) = &self.none
|
||||
&& MenuItem::new(none.clone()).show(ui).ran
|
||||
@@ -240,7 +243,8 @@ impl Outcome for ThemeColorMenuOutput {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPick {
|
||||
/// A style-alias scheme slot and the chosen tint or shade transforms.
|
||||
/// A style-alias scheme slot and the chosen tint or shade transforms; [`ColorPick::scheme`] builds one.
|
||||
#[non_exhaustive]
|
||||
Scheme {
|
||||
/// The scheme slot's style alias.
|
||||
slot: SchemeSlot,
|
||||
@@ -252,3 +256,10 @@ pub enum ColorPick {
|
||||
/// No colour.
|
||||
None,
|
||||
}
|
||||
|
||||
impl ColorPick {
|
||||
/// A scheme slot with the chosen variant's transforms; empty `mods` is the base colour.
|
||||
pub fn scheme(slot: SchemeSlot, mods: Vec<ColorTransform>) -> Self {
|
||||
Self::Scheme { slot, mods }
|
||||
}
|
||||
}
|
||||
@@ -135,29 +135,35 @@ impl CaptureSource for Late {
|
||||
|
||||
const PICKED: Srgba = Srgba { r: 0.25, g: 0.5, b: 0.75, a: 1.0 };
|
||||
|
||||
#[trial]
|
||||
fn a_pick_dropper_picks_once_and_ends_on_escape_a_secondary_press_or_a_press_off_the_document() {
|
||||
let make = |mode| {
|
||||
let reads = Rc::new(Cell::new(0));
|
||||
let sampled = Rc::clone(&reads);
|
||||
let dropper = DropperTool::new(move |at| {
|
||||
sampled.set(sampled.get() + 1);
|
||||
(at[0] >= 0.0 && at[1] >= 0.0 && at[0] < f64::from(SIZE[0]) && at[1] < f64::from(SIZE[1])).then_some(PICKED)
|
||||
})
|
||||
.mode(mode);
|
||||
let rerun = Rc::new(Cell::new(false));
|
||||
let discard = Rc::clone(&rerun);
|
||||
let mut tool = ToolFixture::with_view("Dropper", dropper, sampler_view, move |ui, _| {
|
||||
if frame::discardable(ui.ctx()) && discard.replace(false) {
|
||||
frame::discard_pass(ui.ctx(), "rerun a dropper pass");
|
||||
}
|
||||
});
|
||||
tool.fixture().room(vec2(800.0, 600.0)).settle();
|
||||
(tool, rerun, reads)
|
||||
};
|
||||
let inside = |tool: &ToolFixture<DropperTool<'static>>| tool.canvas().rect.min + vec2(100.5, 50.5);
|
||||
/// A dropper in `mode` over the sampled document, the flag that discards its next pass, and its count of samples read.
|
||||
fn dropper_rig(mode: DropperMode) -> (ToolFixture<DropperTool<'static>>, Rc<Cell<bool>>, Rc<Cell<usize>>) {
|
||||
let reads = Rc::new(Cell::new(0));
|
||||
let sampled = Rc::clone(&reads);
|
||||
let dropper = DropperTool::new(move |at| {
|
||||
sampled.set(sampled.get() + 1);
|
||||
(at[0] >= 0.0 && at[1] >= 0.0 && at[0] < f64::from(SIZE[0]) && at[1] < f64::from(SIZE[1])).then_some(PICKED)
|
||||
})
|
||||
.mode(mode);
|
||||
let rerun = Rc::new(Cell::new(false));
|
||||
let discard = Rc::clone(&rerun);
|
||||
let mut tool = ToolFixture::with_view("Dropper", dropper, sampler_view, move |ui, _| {
|
||||
if frame::discardable(ui.ctx()) && discard.replace(false) {
|
||||
frame::discard_pass(ui.ctx(), "rerun a dropper pass");
|
||||
}
|
||||
});
|
||||
tool.fixture().room(vec2(800.0, 600.0)).settle();
|
||||
(tool, rerun, reads)
|
||||
}
|
||||
|
||||
let (mut tool, rerun, reads) = make(DropperMode::Pick);
|
||||
/// A point inside the sampled document.
|
||||
fn inside(tool: &ToolFixture<DropperTool<'static>>) -> Pos2 {
|
||||
tool.canvas().rect.min + vec2(100.5, 50.5)
|
||||
}
|
||||
|
||||
/// A pick dropper's hover: its loupe stays while the pointer rests and through a rerun, leaves with the pointer, and
|
||||
/// neither samples again nor picks.
|
||||
fn a_pick_droppers_hover_keeps_its_loupe_and_never_picks() {
|
||||
let (mut tool, rerun, reads) = dropper_rig(DropperMode::Pick);
|
||||
let at = inside(&tool);
|
||||
let without_loupe = tool.fixture().texts().to_vec();
|
||||
tool.move_to(at);
|
||||
@@ -184,6 +190,34 @@ fn a_pick_dropper_picks_once_and_ends_on_escape_a_secondary_press_or_a_press_off
|
||||
let mut dropper = tool.tool_mut();
|
||||
assert!(dropper.take_at().is_none() && !dropper.ended(), "hover never picks or disarms");
|
||||
}
|
||||
}
|
||||
|
||||
/// A sample dropper samples on press, through a drag and once on release, stays armed, and a cancel never ends it.
|
||||
fn a_sample_dropper_samples_while_pressed_and_stays_armed() {
|
||||
let (mut tool, rerun, reads) = dropper_rig(DropperMode::Sample);
|
||||
let at = inside(&tool);
|
||||
tool.press_at(at);
|
||||
assert_eq!(tool.tool_mut().take(), Some(PICKED), "sample mode samples on press");
|
||||
tool.move_to(at + vec2(60.0, 20.0));
|
||||
assert_eq!(tool.tool_mut().take(), Some(PICKED), "sample mode samples during a drag");
|
||||
let before_release = reads.get();
|
||||
rerun.set(true);
|
||||
tool.release_at(at + vec2(60.0, 20.0));
|
||||
assert_eq!(reads.get(), before_release + 1, "a second pass in one frame does not repeat the release sample");
|
||||
assert_eq!(tool.tool_mut().take(), Some(PICKED));
|
||||
assert!(!tool.tool().ended(), "sample mode stays armed after release");
|
||||
tool.escape();
|
||||
{
|
||||
let mut dropper = tool.tool_mut();
|
||||
assert!(dropper.cancelled() && !dropper.ended(), "sample cancellation never becomes a pick ending");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_pick_dropper_picks_once_and_ends_on_escape_a_secondary_press_or_a_press_off_the_document() {
|
||||
let make = dropper_rig;
|
||||
a_pick_droppers_hover_keeps_its_loupe_and_never_picks();
|
||||
a_sample_dropper_samples_while_pressed_and_stays_armed();
|
||||
|
||||
let (mut tool, rerun, reads) = make(DropperMode::Pick);
|
||||
let at = inside(&tool);
|
||||
@@ -262,24 +296,6 @@ fn a_pick_dropper_picks_once_and_ends_on_escape_a_secondary_press_or_a_press_off
|
||||
let mut dropper = tool.tool_mut();
|
||||
assert!(dropper.ended() && dropper.take().is_some(), "a later click still picks after a discarded pass");
|
||||
}
|
||||
|
||||
let (mut tool, rerun, reads) = make(DropperMode::Sample);
|
||||
let at = inside(&tool);
|
||||
tool.press_at(at);
|
||||
assert_eq!(tool.tool_mut().take(), Some(PICKED), "sample mode samples on press");
|
||||
tool.move_to(at + vec2(60.0, 20.0));
|
||||
assert_eq!(tool.tool_mut().take(), Some(PICKED), "sample mode samples during a drag");
|
||||
let before_release = reads.get();
|
||||
rerun.set(true);
|
||||
tool.release_at(at + vec2(60.0, 20.0));
|
||||
assert_eq!(reads.get(), before_release + 1, "a second pass in one frame does not repeat the release sample");
|
||||
assert_eq!(tool.tool_mut().take(), Some(PICKED));
|
||||
assert!(!tool.tool().ended(), "sample mode stays armed after release");
|
||||
tool.escape();
|
||||
{
|
||||
let mut dropper = tool.tool_mut();
|
||||
assert!(dropper.cancelled() && !dropper.ended(), "sample cancellation never becomes a pick ending");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
|
||||
@@ -9,7 +9,7 @@ use craft_drawingml::color::{ColorScheme, Rgba, SchemeSlot, variants_of};
|
||||
use craft_drawingml::theme::Theme;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::SplitButton;
|
||||
use craft_ui::contract::{Props as _, Show as _};
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::runtime::requests::{EyedropperRequest, HostAnswer};
|
||||
use craft_ui::testing::{Fixture, Target, trial};
|
||||
@@ -149,7 +149,7 @@ fn a_cell_reports_its_slot_with_the_style_alias_and_its_variants_mods() {
|
||||
trial.rerun.set(true);
|
||||
trial.fixture.click(cell);
|
||||
trial.fixture.settle();
|
||||
assert_eq!(trial.picks.borrow().as_slice(), &[ColorPick::Scheme { slot: alias, mods }], "the cell reports its slot and row once");
|
||||
assert_eq!(trial.picks.borrow().as_slice(), &[ColorPick::scheme(alias, mods)], "the cell reports its slot and row once");
|
||||
assert_eq!(trial.fixture.tree().expanded_of(arrow.node), Some(false), "a cell pick closes the menu");
|
||||
}
|
||||
}
|
||||
@@ -841,7 +841,8 @@ impl ContentAwareFillWorkspace {
|
||||
/// passes) only the canvas's own state is dropped.
|
||||
fn cancel_gesture(&mut self, ctx: Option<&Context>, reason: CancelReason) {
|
||||
if let (Some(ctx), Some(id)) = (ctx, self.canvas_id) {
|
||||
match self.tool {
|
||||
// These tools request no URLs, so the cancel response has nothing to open.
|
||||
let _ = match self.tool {
|
||||
FillTool::Hand => ToolHost::new().cancel(ctx, id, &mut self.hand, reason),
|
||||
FillTool::Zoom => ToolHost::new().cancel(ctx, id, &mut self.zoom, reason),
|
||||
FillTool::SamplingBrush | FillTool::Lasso => {
|
||||
|
||||
@@ -698,7 +698,8 @@ impl Edit {
|
||||
let cursor = self.cursor_options;
|
||||
let LiquifyView { canvas, canvas_id, .. } = state;
|
||||
if let (Some(ctx), Some(id)) = (ctx, *canvas_id) {
|
||||
match self.settings.tool {
|
||||
// These tools request no URLs, so the cancel response has nothing to open.
|
||||
let _ = match self.settings.tool {
|
||||
LiquifyTool::Hand => ToolHost::new().cancel(ctx, id, &mut canvas.hand, reason),
|
||||
LiquifyTool::Zoom => ToolHost::new().cancel(ctx, id, &mut canvas.zoom, reason),
|
||||
_ => ToolHost::new().cancel(ctx, id, &mut canvas.tool(&mut self.settings, &cursor), reason),
|
||||
|
||||
@@ -419,16 +419,17 @@ impl RawDevelopWorkspace {
|
||||
fn end_gesture(&mut self, ctx: &Context, reason: CancelReason) {
|
||||
let Some(canvas) = self.canvas else { return };
|
||||
let size = [self.size.width, self.size.height];
|
||||
// These tools request no URLs, so the cancel response has nothing to open.
|
||||
match self.tool {
|
||||
RawTool::Hand => {}
|
||||
RawTool::Zoom => {
|
||||
if let Some(zoom) = self.zoom_tool.as_mut() {
|
||||
ToolHost::new().cancel(ctx, canvas, zoom, reason);
|
||||
let _ = ToolHost::new().cancel(ctx, canvas, zoom, reason);
|
||||
}
|
||||
}
|
||||
RawTool::Sampler => {
|
||||
let mut pass = self.sampler_tool.pass(&self.samplers, size);
|
||||
ToolHost::new().cancel(ctx, canvas, &mut pass, reason);
|
||||
let _ = ToolHost::new().cancel(ctx, canvas, &mut pass, reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,12 +639,13 @@ impl VanishingPointWorkspace {
|
||||
/// Cancels the gesture the strip's tool holds with `reason`: the editor puts back what the press found (the
|
||||
/// Hand's and Zoom's drags go through the host).
|
||||
fn cancel_gesture(&mut self, ctx: &egui::Context, state: &VanishingView, reason: CancelReason, out: &mut Vec<VanishingPointEvent>) {
|
||||
// The Hand and Zoom request no URLs, so the cancel response has nothing to open.
|
||||
match (self.strip, state.canvas) {
|
||||
(VanishingPointStripTool::Hand, Some(canvas)) => {
|
||||
ToolHost::new().cancel(ctx, canvas, &mut self.hand, reason);
|
||||
let _ = ToolHost::new().cancel(ctx, canvas, &mut self.hand, reason);
|
||||
}
|
||||
(VanishingPointStripTool::Zoom, Some(canvas)) => {
|
||||
ToolHost::new().cancel(ctx, canvas, &mut self.zoom, reason);
|
||||
let _ = ToolHost::new().cancel(ctx, canvas, &mut self.zoom, reason);
|
||||
}
|
||||
_ => self.editor.cancel(&mut self.session, reason),
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Stories of the in-ribbon gallery.
|
||||
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::contract::{Show as _, clicked};
|
||||
use craft_ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft_ui::primitives::textures::Revision;
|
||||
use craft_ui::primitives::{FakeThumbSource, ThumbnailOptions, Thumbnails};
|
||||
@@ -31,7 +31,7 @@ fn gallery_more_body(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Gallery::new("Styles", &items, Some(¤t))
|
||||
.tiles(6, 3)
|
||||
.more(GalleryMore::Body(&mut |ui, cx| {
|
||||
if Button::new("Apply style").show(ui).clicked() {
|
||||
if clicked(&Button::new("Apply style").show(ui)) {
|
||||
cx.request_close();
|
||||
}
|
||||
}))
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::rc::Rc;
|
||||
use craft_behavior::IconId;
|
||||
use craft_menu::ribbon::{BackLook, BackstageCommands, BackstageEntry, BackstageEvent, BackstageView};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, Props as _, Role, Show as _};
|
||||
use craft_ui::contract::{Bind, Role, Show as _};
|
||||
use craft_ui::runtime::commands::CommandSet as _;
|
||||
use craft_ui::runtime::egui::access::NodeKey;
|
||||
use craft_ui::runtime::env::WindowKey;
|
||||
|
||||
@@ -566,7 +566,7 @@ fn a_tab_keeps_its_own_group_row_scroll_offset_when_it_is_picked_again() {
|
||||
let discard = rerun.clone();
|
||||
let forward_name = Rc::new(RefCell::new(Label::Empty));
|
||||
let name = forward_name.clone();
|
||||
let id = Id::new("ribbon.scroll_trial");
|
||||
let id = Id::unique("ribbon.scroll_trial");
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
if discard.take() {
|
||||
ui.ctx().request_discard("the ribbon input frame runs twice");
|
||||
|
||||
@@ -11,7 +11,7 @@ use craft_ui::display::Badge;
|
||||
use craft_ui::primitives::{HAlign, IconSpec, PaintShape, StrokeWidth, SubmitKey, TextRun, Wrap};
|
||||
use craft_ui::runtime::env::{EnvView, Label};
|
||||
use craft_ui::runtime::focus::{self, FocusTarget};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, Ink, StyleColor, StyleCx, TypeRole, UiTokens};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, Flags, Ink, State, StateMix, StateSet, Stateful, StyleColor, StyleCx, TypeRole, UiTokens};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::{Color32, CornerRadius, Pos2, Rect, Vec2, vec2};
|
||||
|
||||
@@ -40,9 +40,8 @@ pub(crate) struct CommentRowStyle {
|
||||
/// The author's face on an inline card, and its initials.
|
||||
face: StyleColor,
|
||||
face_ink: StyleColor,
|
||||
/// The soft fill, selected fill and corners of an inline card's surface.
|
||||
tile: StyleColor,
|
||||
tile_selected: StyleColor,
|
||||
/// The fill of an inline card's surface, the selection fill while selected, and its corners.
|
||||
tile: Stateful<StyleColor>,
|
||||
corners: CornerRadius,
|
||||
/// The line that joins a card's avatars.
|
||||
thread_line: StyleColor,
|
||||
@@ -931,8 +930,7 @@ impl Component for CommentRow<'_> {
|
||||
avatar_ink: cx.color(color.text.normal),
|
||||
face: cx.color(color.accent.strong),
|
||||
face_ink: cx.color(color.text.on_strong),
|
||||
tile: cx.color(color.surface.chrome),
|
||||
tile_selected: cx.color(color.state.selected),
|
||||
tile: Stateful::new(cx.color(color.surface.chrome)).when(Flags::SELECTED, cx.color(color.state.selected)),
|
||||
corners: UiTokens::corner(cx.tokens.shape.radius.surface),
|
||||
thread_line: cx.color(color.line.divider),
|
||||
kind_icon: cx.tokens.size.icon.sm,
|
||||
@@ -1000,7 +998,9 @@ impl Component for CommentRow<'_> {
|
||||
// fill, outlined in the accent.
|
||||
if self.actions == CardActions::Inline && self.thread.is_some() {
|
||||
let surface = PaintShape::Rect(Rect::from_min_max(rect.min, Pos2::new(rect.max.x, rect.max.y - st.gap)), st.corners);
|
||||
ui.draw().fill(&surface, if self.selected { st.tile_selected } else { st.tile });
|
||||
let mut flags = Flags::empty();
|
||||
flags.set(Flags::SELECTED, self.selected);
|
||||
ui.draw().fill(&surface, StateSet::new(State::Rest, flags, StateMix::default()).resolve(&st.tile));
|
||||
if self.selected {
|
||||
ui.draw().stroke(&surface, StrokeWidth::Medium, st.bar);
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ const LINE: usize = 4;
|
||||
|
||||
impl Host {
|
||||
fn rows(&self) -> Vec<Range<usize>> {
|
||||
let Some(columns) = self.columns else { return vec![0..self.text.chars().count()] };
|
||||
let Some(columns) = self.columns else { return std::iter::once(0..self.text.chars().count()).collect() };
|
||||
let chars: Vec<char> = self.text.chars().collect();
|
||||
let mut rows = Vec::new();
|
||||
let mut start = 0;
|
||||
|
||||
@@ -139,7 +139,7 @@ fn mark_segments(shapes: &[Shape], ink: Color32) -> Vec<[Pos2; 2]> {
|
||||
segments.extend(path.points.windows(2).map(|pair| [pair[0], pair[1]]));
|
||||
}
|
||||
Shape::Mesh(mesh) => {
|
||||
for triangle in mesh.indices.chunks_exact(3) {
|
||||
for triangle in mesh.indices.as_chunks::<3>().0 {
|
||||
for (a, b) in [(0, 1), (1, 2), (2, 0)] {
|
||||
let (a, b) = (mesh.vertices[triangle[a] as usize], mesh.vertices[triangle[b] as usize]);
|
||||
if a.color == ink && b.color == ink {
|
||||
|
||||
@@ -890,7 +890,7 @@ pub trait ShowContainer: Container + sealed::ShowContainer {
|
||||
};
|
||||
let mut ui = Ui::new(
|
||||
ctx.clone(),
|
||||
egui::Id::unique("craft_ui::container_measure"),
|
||||
crate::runtime::egui::memory::unique("craft_ui::container_measure"),
|
||||
egui::UiBuilder::new().max_rect(Rect::from_min_size(Pos2::ZERO, room)).invisible(),
|
||||
);
|
||||
crate::runtime::env::Env::run_in(&mut ui, env.clone(), |ui| run::measure_container(self, ui, proposal, &mut body))
|
||||
|
||||
@@ -91,17 +91,21 @@ pub(crate) mod trials {
|
||||
use crate::style::Ink;
|
||||
use crate::testing::{Frames, trial};
|
||||
use craft_theme::{Contrast, Mode, variant::Tone};
|
||||
use egui::{Color32, Pos2, Shape, Stroke, vec2};
|
||||
use egui::{Color32, Pos2, Shape, Stroke, Vec2, vec2};
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[trial]
|
||||
fn a_wave_stays_on_its_segment_and_straight_is_one_segment() {
|
||||
let mut frames = Frames::new();
|
||||
let width = 2.0;
|
||||
for delta in [vec2(1.0, 0.0), vec2(5.0, 3.0), vec2(20.0, -12.0)] {
|
||||
// Any ink: the shape of the mark does not depend on it.
|
||||
let ink = Color32::from_rgb(200, 40, 40);
|
||||
// Segments shorter than a stroke width, of one peak, and of several, level, rising and falling.
|
||||
for (angle, length) in [(0.0_f32, 1.0_f32), (0.54, 5.8), (-0.54, 23.3)] {
|
||||
let delta = Vec2::angled(angle) * length;
|
||||
let a = egui::pos2(40.0, 50.0);
|
||||
let b = a + delta;
|
||||
let shapes = frames.frame_shapes(|ui| paint_flag_mark(ui.painter(), a, b, FlagMark::Wave, Color32::RED, width));
|
||||
let shapes = frames.frame_shapes(|ui| paint_flag_mark(ui.painter(), a, b, FlagMark::Wave, ink, width));
|
||||
let [Shape::Path(path)] = shapes.as_slice() else { panic!("a wave is an open path") };
|
||||
let along = delta.normalized();
|
||||
let normal = vec2(-along.y, along.x);
|
||||
@@ -119,7 +123,7 @@ pub(crate) mod trials {
|
||||
assert!((pair[0] - a).dot(normal) * (pair[1] - a).dot(normal) < 0.0, "successive peaks cross the baseline");
|
||||
assert!(((pair[1] - pair[0]).dot(along) - 2.0 * width).abs() < 1e-4);
|
||||
}
|
||||
let shapes = frames.frame_shapes(|ui| paint_flag_mark(ui.painter(), a, b, FlagMark::Straight, Color32::RED, width));
|
||||
let shapes = frames.frame_shapes(|ui| paint_flag_mark(ui.painter(), a, b, FlagMark::Straight, ink, width));
|
||||
assert!(matches!(shapes.as_slice(), [Shape::LineSegment { points, .. }] if points[0] == a && points[1] == b));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,6 +387,15 @@ pub(crate) fn offers_context_menu(ctx: &Context, id: Id) -> bool {
|
||||
with_emitted(ctx, |emitted| emitted.context.contains(&id))
|
||||
}
|
||||
|
||||
/// The move an AccessKit increment (forward) or decrement (back) asks of a numeric part; `None` for any other action.
|
||||
pub(crate) fn step_move(action: accesskit::Action) -> Option<craft_behavior::NavMove> {
|
||||
match action {
|
||||
accesskit::Action::Increment => Some(craft_behavior::NavMove::Forward),
|
||||
accesskit::Action::Decrement => Some(craft_behavior::NavMove::Back),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns AccessKit output on, so every viewport's pass settles an update ([`settle_output`]) that automation reads
|
||||
/// ([`kept_tree`]).
|
||||
pub(crate) fn keep_trees(ctx: &Context) {
|
||||
|
||||
@@ -277,11 +277,9 @@ impl Intents {
|
||||
fn move_of(intent: &Intent, numeric_parts: &[PartRef]) -> Option<(NavMove, MoveMods)> {
|
||||
match intent {
|
||||
Intent::Move(mv, mods) => Some((*mv, *mods)),
|
||||
Intent::Access(request) if request.target.is_some_and(|part| numeric_parts.contains(&part)) => match request.action {
|
||||
accesskit::Action::Increment => Some((NavMove::Forward, MoveMods::PLAIN)),
|
||||
accesskit::Action::Decrement => Some((NavMove::Back, MoveMods::PLAIN)),
|
||||
_ => None,
|
||||
},
|
||||
Intent::Access(request) if request.target.is_some_and(|part| numeric_parts.contains(&part)) => {
|
||||
crate::runtime::egui::access::step_move(request.action).map(|mv| (mv, MoveMods::PLAIN))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,8 +269,11 @@ fn an_app_icons_parts_paint_in_document_order_and_on_and_off_parts_only_in_their
|
||||
let uploads = RefCell::new(Vec::new());
|
||||
let mut paint = |name: &'static str, mode| icon_quads(&mut frames, &tokens, ink, name, mode, &uploads);
|
||||
let enabled = paint(ORDERED_NAME, DataMode::Full);
|
||||
// design: allow[raw-colour/const](a white tint preserves the fixed square's colour)
|
||||
assert_eq!(enabled.iter().map(|(_, tint)| *tint).collect::<Vec<_>>(), [ink, Color32::WHITE, ink]);
|
||||
let tints = enabled.iter().map(|(_, tint)| *tint).collect::<Vec<_>>();
|
||||
assert_eq!(tints.len(), 3, "the ordered icon paints three runs, got {tints:?}");
|
||||
let [first, fixed, last] = tints[..] else { return };
|
||||
assert_eq!([first, last], [ink, ink], "the ink runs take the ink");
|
||||
assert!(keeps_colours(fixed, ink), "the fixed run's tint keeps the colours it is drawn in: {fixed:?}");
|
||||
let disabled = paint(ORDERED_NAME, DataMode::Dimmed);
|
||||
assert_eq!(disabled.len(), 1);
|
||||
assert!(enabled.iter().all(|(texture, _)| *texture != disabled[0].0));
|
||||
@@ -302,7 +305,8 @@ fn an_app_icons_parts_paint_in_document_order_and_on_and_off_parts_only_in_their
|
||||
assert!(features.is_some(), "the feature icon must register");
|
||||
let Some(features) = features else { return };
|
||||
let silhouette = features.layer(24.0, 1.0, Layer::Silhouette);
|
||||
assert_eq!(features.layer(24.0, 1.0, Layer::Run { run: 0, class: Class::Ink }), silhouette, "every feature survives splitting");
|
||||
let run = features.layer(24.0, 1.0, Layer::Run { run: 0, class: Class::Ink });
|
||||
assert_eq!(run, silhouette, "every feature survives splitting");
|
||||
assert!(texel(&silhouette, 1, 3).a() > texel(&silhouette, 0, 3).a(), "round caps extend the segment");
|
||||
assert!(texel(&silhouette, 7, 1).a() > texel(&silhouette, 6, 0).a(), "round joins trim the outer corner");
|
||||
assert!(texel(&silhouette, 15, 3).a() > texel(&silhouette, 18, 3).a(), "dashes leave gaps");
|
||||
@@ -364,11 +368,20 @@ fn encoded_app_icons_paint_through_draw_and_invalid_siblings_stay_out_of_the_ind
|
||||
let encoded = icon(name);
|
||||
assert!(encoded.is_some(), "a valid encoded sibling must register");
|
||||
let Some(encoded) = encoded else { return };
|
||||
assert!(encoded.layer(24.0, 1.0, Layer::Silhouette).pixels.iter().any(|pixel| pixel.a() > 0));
|
||||
let silhouette = encoded.layer(24.0, 1.0, Layer::Silhouette);
|
||||
assert!(silhouette.pixels.iter().any(|pixel| pixel.a() > 0));
|
||||
}
|
||||
assert_eq!(mask(UTF16_NAME), mask(LATIN1_NAME), "encodings preserve the same geometry");
|
||||
}
|
||||
|
||||
/// Whether `tint` leaves every colour it multiplies as it is (`ink` and a red, a green and a blue), as a fixed part's
|
||||
/// tint must for the part to keep the colours it is drawn in.
|
||||
fn keeps_colours(tint: Color32, ink: Color32) -> bool {
|
||||
[ink, Color32::from_rgb(208, 32, 32), Color32::from_rgb(10, 200, 30), Color32::from_rgb(30, 60, 220)]
|
||||
.into_iter()
|
||||
.all(|drawn| tint * drawn == drawn)
|
||||
}
|
||||
|
||||
/// The textured quads `name` paints in `mode` under `ink`, first to last; the images they upload go to `uploads`.
|
||||
fn icon_quads(
|
||||
frames: &mut Frames,
|
||||
|
||||
@@ -163,7 +163,9 @@ pub struct CommandPalette<'a> {
|
||||
entries: &'a [HelpEntry],
|
||||
index: &'a SearchIndex,
|
||||
open: Bind<'a, bool>,
|
||||
/// The optional query and selection shared with the host.
|
||||
/// The query and selection shared with the host: the bound state is the palette's query and selection authority,
|
||||
/// read and written each pass. Without this binding, the palette keeps its own state.
|
||||
#[prop]
|
||||
state: Option<Bind<'a, PaletteState>>,
|
||||
/// The pick counts that rank the results, 0 for a command never picked.
|
||||
#[prop]
|
||||
@@ -214,13 +216,6 @@ impl<'a> CommandPalette<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses the bound state as the palette's query and selection authority, read and written each pass.
|
||||
/// Without this binding, the palette keeps its own state.
|
||||
pub fn state(mut self, state: Bind<'a, PaletteState>) -> Self {
|
||||
self.state = Some(state);
|
||||
self
|
||||
}
|
||||
|
||||
/// Puts `command` first in `recents`, once, keeping the newest `RECENT_KEPT`.
|
||||
pub fn remember(recents: &mut Vec<CommandRef>, command: CommandRef) {
|
||||
recents.retain(|held| *held != command);
|
||||
|
||||
@@ -11,7 +11,7 @@ use super::canvas_shell::slots as keys;
|
||||
use super::options_place::{FloatingBar, OptionsBarDrag, OptionsBarPlace, PlaceTarget};
|
||||
use super::regions::{Claim, SlotSize, layout};
|
||||
use super::reveal::{Aim, Reveal, Tracking};
|
||||
use super::screen_mode::{ScreenMode, ScreenModeCommands, ScreenModeFollow, ScreenModeSet};
|
||||
use super::screen_mode::{FollowBy, ScreenMode, ScreenModeCommands, ScreenModeFollow, ScreenModeSet};
|
||||
use super::title_bar::PageBand;
|
||||
use super::words::ShellWords;
|
||||
use crate::contract::overlay::{PopupRegion, Resize};
|
||||
@@ -620,6 +620,8 @@ pub struct AppShell<'a, S> {
|
||||
body: Option<SlotBody<'a, S>>,
|
||||
/// The full-window page and its command scope, set while it shows.
|
||||
page: Option<(CommandScope, VersionFn<'a, S>, SlotBody<'a, S>)>,
|
||||
/// The shown page's kind; a page below the title keeps its title slot and skips the page band.
|
||||
#[prop]
|
||||
page_kind: PageKind,
|
||||
}
|
||||
|
||||
@@ -765,12 +767,6 @@ impl<'a, S> AppShell<'a, S> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the shown page's kind; a page below the title keeps its title slot and skips the page band.
|
||||
pub fn page_kind(mut self, kind: PageKind) -> Self {
|
||||
self.page_kind = kind;
|
||||
self
|
||||
}
|
||||
|
||||
/// A slot at the reading end, inside the ones added before it.
|
||||
pub fn end(self, slot: Slot, version: impl Fn(&S) -> Option<u64> + 'a, add: impl FnMut(&mut Ui, &mut BodyCx<'_>, &mut S) + 'a) -> Self {
|
||||
self.place(PaneEdge::End, slot, version, add)
|
||||
@@ -860,7 +856,8 @@ impl<'a, S> AppShell<'a, S> {
|
||||
|
||||
let name: Arc<str> = words.screen_mode.as_str().into();
|
||||
let held_mode = page.as_ref().filter(|_| page_kind == PageKind::Presentation).map(|_| ScreenMode::FullScreen);
|
||||
let (mode, changed) = kept.screen.follow(&ctx, cx, screen_mode.reborrow(), Arc::clone(&name), !embedded, mode_set, held_mode);
|
||||
let by = FollowBy { os: !embedded, set: mode_set, held: held_mode };
|
||||
let (mode, changed) = kept.screen.follow(&ctx, cx, screen_mode.reborrow(), Arc::clone(&name), by);
|
||||
if changed {
|
||||
kept.reveal.clear();
|
||||
}
|
||||
|
||||
@@ -156,6 +156,17 @@ impl ScreenModeCommands {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pass of [`ScreenModeFollow::follow`] goes by besides the binding.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct FollowBy {
|
||||
/// Whether the shell brings its window to the mode (not an embedded shell).
|
||||
pub(super) os: bool,
|
||||
/// The modes the cycle commands step through.
|
||||
pub(super) set: ScreenModeSet,
|
||||
/// The mode a page holds the window in while it shows, without writing the binding.
|
||||
pub(super) held: Option<ScreenMode>,
|
||||
}
|
||||
|
||||
/// The shell's record of how its window follows the screen mode, kept between passes.
|
||||
///
|
||||
/// A hold brings the window to its target without writing the bound mode, so hiding a presentation restores the
|
||||
@@ -176,7 +187,7 @@ pub(super) struct ScreenModeFollow {
|
||||
|
||||
impl ScreenModeFollow {
|
||||
/// Reads `bind` and drains only the commands delivered to this pass; a second pass does not replay them.
|
||||
/// With `os`, brings the window to `held` or the bound mode; an embedded shell only changes its own region.
|
||||
/// With `by.os`, brings the window to `by.held` or the bound mode; an embedded shell only changes its own region.
|
||||
/// A hold never writes the binding; an OS exit keeps its target at Standard until `held` is None. Writes a changed bound mode
|
||||
/// under `name`. Returns that bound mode and whether the window target differs from the last applied target.
|
||||
pub(super) fn follow(
|
||||
@@ -185,10 +196,9 @@ impl ScreenModeFollow {
|
||||
cx: &mut BodyCx<'_>,
|
||||
mut bind: BindMut<'_, ScreenMode>,
|
||||
name: Arc<str>,
|
||||
os: bool,
|
||||
set: ScreenModeSet,
|
||||
held: Option<ScreenMode>,
|
||||
by: FollowBy,
|
||||
) -> (ScreenMode, bool) {
|
||||
let FollowBy { os, set, held } = by;
|
||||
let before = match bind.read(cx) {
|
||||
Some(Mixed::Same(held)) => held,
|
||||
_ => ScreenMode::default(),
|
||||
|
||||
@@ -117,18 +117,21 @@ impl Outcome for BarOutput {
|
||||
/// The bar is a plain container; its members are the host's. A host memoizes them with a `MemoView` inside the body
|
||||
/// closure, over props that hold what the members read (`BarItem`, `StatusMessage`, `StatusProgress` and the other
|
||||
/// member types derive `MemoProps`), and sends the members' events through an `Outbox`.
|
||||
#[derive(crate::contract::Component)]
|
||||
#[derive(crate::contract::Component, crate::contract::Props)]
|
||||
#[component(container)]
|
||||
pub struct Bar<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
#[container]
|
||||
// The bar writes its container props itself (`surface` keeps the over-picture scrim): no builder is forwarded.
|
||||
#[container()]
|
||||
props: ContainerProps,
|
||||
kind: BarKind,
|
||||
/// The surface and member placement of the bar.
|
||||
#[style_key]
|
||||
look: BarLook,
|
||||
chrome_surface: SurfaceKind,
|
||||
/// Whether empty bar space owns background presses through drag and release.
|
||||
#[prop]
|
||||
background_press: BarBackgroundPress,
|
||||
commit_cancel: Option<(Label, Label)>,
|
||||
committed: bool,
|
||||
@@ -137,15 +140,11 @@ pub struct Bar<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Bar<'a> {
|
||||
/// Chooses whether empty bar space owns background presses through drag and release.
|
||||
pub fn background_press(mut self, policy: BarBackgroundPress) -> Self {
|
||||
self.background_press = policy;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a chrome or over-picture surface with the same member arrangement.
|
||||
pub fn look(mut self, look: BarLook) -> Self {
|
||||
self.look = look;
|
||||
/// Stands the bar over a picture ([`BarLook::OverPicture`]): a pill scrim with ghost members in place of the
|
||||
/// chrome surface, with the same member arrangement.
|
||||
#[must_use]
|
||||
pub fn over_picture(mut self) -> Self {
|
||||
self.look = BarLook::OverPicture;
|
||||
self.apply_surface();
|
||||
self
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
//! Stories of the bars.
|
||||
|
||||
use super::{
|
||||
Bar, BarBackgroundPress, BarHome, BarItem, BarItems, BarKind, BarLook, BarTool, ItemDisplay, StatusItem, StatusMessage, StatusProgress,
|
||||
StatusReadout, StatusValues,
|
||||
Bar, BarBackgroundPress, BarHome, BarItem, BarItems, BarKind, BarTool, ItemDisplay, StatusItem, StatusMessage, StatusProgress, StatusReadout,
|
||||
StatusValues,
|
||||
};
|
||||
use crate::buttons::{Button, Link};
|
||||
use crate::choice::{Checkbox, Segmented};
|
||||
use crate::contract::{Bind, Entry, Props as _};
|
||||
use crate::contract::{Bind, Entry, Props as _, clicked};
|
||||
use crate::contract::{Show as _, ShowContainer as _};
|
||||
use crate::display::{Divider, Picture, PictureSize, Shade, Text};
|
||||
use crate::form::Field;
|
||||
use crate::layout_components::Row;
|
||||
use crate::layout_components::{Row, Stack};
|
||||
use crate::list::{ThumbAspect, ThumbSize};
|
||||
use crate::menu::{Menu, MenuItem};
|
||||
use crate::pickers::Select;
|
||||
@@ -58,13 +58,19 @@ fn over_picture(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
.extent(PictureSize::Thumb(ThumbSize::Large))
|
||||
.show(ui)
|
||||
.rect;
|
||||
let mut overlay = ui.new_child(egui::UiBuilder::new().max_rect(stage));
|
||||
Bar::new("Picture tools", BarKind::Tool)
|
||||
.look(BarLook::OverPicture)
|
||||
.show(&mut overlay, |ui, _| {
|
||||
BarItems::new(items()).show(ui);
|
||||
})
|
||||
.into()
|
||||
// The bar stands at the top of the stage, over the picture.
|
||||
let shown = Stack::new().show_at(ui, stage, |ui, _| {
|
||||
Bar::new("Picture tools", BarKind::Tool)
|
||||
.over_picture()
|
||||
.show(ui, |ui, _| {
|
||||
BarItems::new(items()).show(ui);
|
||||
})
|
||||
.output
|
||||
});
|
||||
match shown.inner {
|
||||
Some(bar) => bar.into(),
|
||||
None => shown.output.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty bar space owns the press while the member still activates; the stage remains a separate target.
|
||||
@@ -76,21 +82,28 @@ fn bar_background_press(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
.extent(PictureSize::Thumb(ThumbSize::Large))
|
||||
.show(ui)
|
||||
.rect;
|
||||
if Button::new("Stage").show_at(ui, stage).clicked() {
|
||||
if clicked(&Button::new("Stage").show_at(ui, stage)) {
|
||||
stage_clicks += 1;
|
||||
}
|
||||
let mut overlay = ui.new_child(egui::UiBuilder::new().max_rect(stage));
|
||||
let shown = Bar::new("Absorbing bar", BarKind::Tool).look(BarLook::OverPicture).background_press(BarBackgroundPress::Absorb).show(
|
||||
&mut overlay,
|
||||
|ui, _| {
|
||||
if Button::new("Member").show(ui).clicked() {
|
||||
member_clicks += 1;
|
||||
}
|
||||
},
|
||||
);
|
||||
// The bar stands at the top of the stage, over the stage's button.
|
||||
let shown = Stack::new().show_at(ui, stage, |ui, _| {
|
||||
Bar::new("Absorbing bar", BarKind::Tool)
|
||||
.over_picture()
|
||||
.background_press(BarBackgroundPress::Absorb)
|
||||
.show(ui, |ui, _| {
|
||||
if clicked(&Button::new("Member").show(ui)) {
|
||||
member_clicks += 1;
|
||||
}
|
||||
})
|
||||
.output
|
||||
});
|
||||
*data.value("stage clicks", 0usize) = stage_clicks;
|
||||
*data.value("member clicks", 0usize) = member_clicks;
|
||||
StoryOutput::from(shown).readout(format!("Stage activations: {stage_clicks}; member activations: {member_clicks}"))
|
||||
let output = match shown.inner {
|
||||
Some(bar) => StoryOutput::from(bar),
|
||||
None => StoryOutput::from(shown.output),
|
||||
};
|
||||
output.readout(format!("Stage activations: {stage_clicks}; member activations: {member_clicks}"))
|
||||
}
|
||||
|
||||
/// A bar made to wrap: its members continue on a new line in a narrow stage instead of scrolling.
|
||||
|
||||
@@ -233,7 +233,8 @@ impl Component for Picture<'_> {
|
||||
return;
|
||||
}
|
||||
// A centred picture's rect is its room; it draws at its aspect in the room's middle.
|
||||
let rect = if self.extent == PictureSize::FitCentred { fit_rect(cx.content_rect, Vec2::new(self.width(1.0), 1.0)) } else { cx.content_rect };
|
||||
let aspect = Vec2::new(self.width(cx.style.height), cx.style.height);
|
||||
let rect = if self.extent == PictureSize::FitCentred { fit_rect(cx.content_rect, aspect) } else { cx.content_rect };
|
||||
match &self.source {
|
||||
Source::Image { key, image } => {
|
||||
let texture = store(&cx.ctx).get_or_put(&cx.ctx, (cx.resolved.id, *key), self.revision, *image);
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::contract::Show as _;
|
||||
use crate::list::{ThumbAspect, ThumbSize};
|
||||
use crate::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::{Color32, ColorImage, Ui, vec2};
|
||||
use egui::{Color32, ColorImage, Ui, Vec2, vec2};
|
||||
|
||||
/// A diagonal gradient, so a fitted or stretched picture shows.
|
||||
fn gradient() -> ColorImage {
|
||||
@@ -113,23 +113,26 @@ fn picture_fill(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Picture::painter("Preview", ThumbAspect::new(4, 1), |cx, rect| cx.checker(rect)).extent(PictureSize::Fill).show(ui).into()
|
||||
}
|
||||
|
||||
/// The short, wide room the fitted portrait previews stand in.
|
||||
const FIT_ROOM: Vec2 = vec2(300.0, 120.0);
|
||||
|
||||
/// A portrait preview remains inside a short, wide room at its own aspect, aligned at its start.
|
||||
#[story(Picture<'static>, covers = [], drive = Drive::Never)]
|
||||
fn picture_fit(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
ui.allocate_ui(vec2(300.0, 120.0), |ui| {
|
||||
crate::testing::memory::scoped(ui, |ui| {
|
||||
ui.set_max_size(FIT_ROOM);
|
||||
Picture::painter("Fitted preview", ThumbAspect::new(3, 4), |cx, rect| cx.checker(rect)).extent(PictureSize::Fit).show(ui)
|
||||
})
|
||||
.inner
|
||||
.into()
|
||||
}
|
||||
|
||||
/// A portrait preview in the middle of a short, wide room at its own aspect: a slide a window centres in its body.
|
||||
#[story(Picture<'static>, covers = [], drive = Drive::Never)]
|
||||
fn picture_fit_centred(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
ui.allocate_ui(vec2(300.0, 120.0), |ui| {
|
||||
crate::testing::memory::scoped(ui, |ui| {
|
||||
ui.set_max_size(FIT_ROOM);
|
||||
Picture::painter("Centred preview", ThumbAspect::new(3, 4), |cx, rect| cx.checker(rect)).extent(PictureSize::FitCentred).show(ui)
|
||||
})
|
||||
.inner
|
||||
.into()
|
||||
}
|
||||
|
||||
|
||||
@@ -94,12 +94,21 @@ pub enum ColumnRule {
|
||||
/// Exactly this many columns share the width; zero asks for one.
|
||||
Exactly(usize),
|
||||
/// Centre the largest pictures that fit the view; fixed headers and tails that exceed it scroll normally.
|
||||
/// [`ColumnRule::fit_to_view`] makes one.
|
||||
#[non_exhaustive]
|
||||
FitToView {
|
||||
/// The most columns allowed.
|
||||
most_columns: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl ColumnRule {
|
||||
/// The rule that centres the largest pictures that fit the view, in at most `most_columns` columns.
|
||||
pub const fn fit_to_view(most_columns: usize) -> Self {
|
||||
ColumnRule::FitToView { most_columns }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the grid reports besides the collection's events.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use craft_behavior::IconId;
|
||||
use craft_behavior::kurbo::Size;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::bars::{Bar, BarKind, BarLook, BreadcrumbBar, StatusItem, StatusMessage, StatusProgress, StatusReadout, StatusValues, path_crumbs};
|
||||
use craft_ui::bars::{Bar, BarKind, BreadcrumbBar, StatusItem, StatusMessage, StatusProgress, StatusReadout, StatusValues, path_crumbs};
|
||||
use craft_ui::buttons::{Button, IconButton, Link};
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
@@ -40,7 +40,7 @@ fn an_over_picture_bar_and_a_painted_hint_share_their_surface() {
|
||||
Bar::new("Chrome tools", BarKind::Tool).show(ui, |ui, _| {
|
||||
Button::new("Chrome action").show(ui);
|
||||
});
|
||||
let bar = Bar::new("Picture tools", BarKind::Tool).look(BarLook::OverPicture).show(ui, |ui, _| {
|
||||
let bar = Bar::new("Picture tools", BarKind::Tool).over_picture().show(ui, |ui, _| {
|
||||
Button::new("Picture action").show(ui);
|
||||
});
|
||||
let env = Env::of(ui);
|
||||
@@ -71,7 +71,7 @@ fn an_over_picture_bars_members_read_on_its_scrim() {
|
||||
use craft_ui::testing::style::tokens;
|
||||
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
Bar::new("Picture tools", BarKind::Tool).look(BarLook::OverPicture).show(ui, |ui, _| {
|
||||
Bar::new("Picture tools", BarKind::Tool).over_picture().show(ui, |ui, _| {
|
||||
IconButton::new(IconId::new("chevron_left")).label("Previous").show(ui);
|
||||
ToggleButton::new("Pen", Bind::given(false)).icon(IconId::new("pencil")).icon_only().show(ui);
|
||||
ToggleButton::new("Black", Bind::given(false)).show(ui);
|
||||
|
||||
@@ -963,10 +963,18 @@ fn a_side_menus_row_shows_the_standard_icon() {
|
||||
}
|
||||
|
||||
/// An icon-only button in a side menu (WordCraft's Back arrow on the File rail) reads in the menu's ink, as a `Button`
|
||||
/// row's icon does, not in the dark ghost ink that vanished on the brand surface; elsewhere it keeps its own ink.
|
||||
/// row's icon does, not in the dark ghost ink that vanished on the brand surface; elsewhere it keeps its own ink. A side
|
||||
/// menu reads in the ink of the surface it stands on: on a chrome rail (DeckCraft's File rail) that ink still reads
|
||||
/// as text on the chrome.
|
||||
#[trial]
|
||||
fn a_side_menus_icon_button_reads_in_the_menus_ink() {
|
||||
let rest = |side: bool, icon_only: bool| {
|
||||
use craft_theme::{Contrast, Mode, Rgba, contrast_ratio, text_contrast_min};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::style::SurfaceKind;
|
||||
use craft_ui::testing::style::tokens;
|
||||
|
||||
// The button's rest icon ink in `mode`, inside a side menu when `side`, the menu standing on `surface` when given.
|
||||
let rest = |surface: Option<SurfaceKind>, side: bool, icon_only: bool, mode: Mode| {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let show = |ui: &mut Ui| {
|
||||
if icon_only {
|
||||
@@ -975,25 +983,40 @@ fn a_side_menus_icon_button_reads_in_the_menus_ink() {
|
||||
let _ = Button::new("Print").icon(IconId::new("print")).variant(Variant::GHOST).show(ui);
|
||||
}
|
||||
};
|
||||
let stand = |ui: &mut Ui| match surface {
|
||||
Some(kind) => {
|
||||
let _ = Stack::new().surface(kind).show(ui, |ui, _| show(ui));
|
||||
}
|
||||
None => show(ui),
|
||||
};
|
||||
if side {
|
||||
with_env(
|
||||
ui,
|
||||
|overrides| {
|
||||
overrides.values.set(ControlPlace::SideMenu);
|
||||
},
|
||||
show,
|
||||
stand,
|
||||
);
|
||||
} else {
|
||||
show(ui);
|
||||
stand(ui);
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.theme(mode, Contrast::Standard).settle();
|
||||
let kind = if icon_only { std::any::type_name::<IconButton<'static>>() } else { std::any::type_name::<Button<'static>>() };
|
||||
let style = fixture.styles_of(kind).into_iter().next().expect("the button resolved its style");
|
||||
style.looks.icons.first().expect("the button has an icon look").color.off.rest.egui()
|
||||
};
|
||||
assert_eq!(rest(true, true), rest(true, false), "the icon button takes the ink of the menu's rows");
|
||||
assert_ne!(rest(true, true), rest(false, true), "outside a side menu it keeps its own ink");
|
||||
let brand = Some(SurfaceKind::Brand);
|
||||
assert_eq!(rest(brand, true, true, Mode::Light), rest(brand, true, false, Mode::Light), "the icon button takes the ink of the menu's rows");
|
||||
assert_ne!(rest(brand, true, true, Mode::Light), rest(None, false, true, Mode::Light), "outside a side menu it keeps its own ink");
|
||||
|
||||
let chrome = Some(SurfaceKind::Chrome);
|
||||
for mode in [Mode::Light, Mode::Dark] {
|
||||
let ink = rest(chrome, true, true, mode);
|
||||
assert_eq!(ink, rest(chrome, true, false, mode), "on a chrome rail the icon button takes the ink of the menu's rows in {mode:?}");
|
||||
let ratio = contrast_ratio(Rgba(ink.to_array()), tokens(mode, Contrast::Standard).color.surface.chrome);
|
||||
assert!(ratio >= text_contrast_min(Contrast::Standard), "a side menu on chrome reads at {ratio:.2} in {mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The command the arrow trial's split button is bound to.
|
||||
|
||||
@@ -365,7 +365,7 @@ fn fit_to_view_tiles_stay_in_view_and_fewer_tiles_are_larger() {
|
||||
.rows_stamp(1)
|
||||
.groups(&groups)
|
||||
.tail(&tails)
|
||||
.column_rule(ColumnRule::FitToView { most_columns: most.get() })
|
||||
.column_rule(ColumnRule::fit_to_view(most.get()))
|
||||
.selection(Bind::bound(&mut *picks.borrow_mut()))
|
||||
.show_items(ui, &source, &mut |key, cx| {
|
||||
held.borrow_mut().tiles.insert(*key, cx.rect);
|
||||
|
||||
Reference in new issue
Block a user