Merge pull request #2152 from Carbocode/fix/inside-stroke-padding

M2: align padding areas with inside strokes and add central drag grips
This commit is contained in:
BFlat authored and GitHub committed 2026-11-18 14:02:54 +07:00
commit 4f7ea53391
5 files changed
+461 -54

No files matched your search

+111 -49
View File
@@ -338,6 +338,42 @@ struct Zones {
tracks: Vec<[Pos2; 2]>,
}
/// Screen-space grip targets. Opposite grips stay at least 20 pixels apart, moving outward from
/// their midpoint only when needed: tiny frames and zoomed-out content must not merge them into
/// one indistinguishable target. Bands keep their actual padding geometry.
fn padding_handles(bands: &[(usize, Rect, f64)]) -> Vec<(usize, Rect, f64)> {
bands
.iter()
.map(|&(side, band, value)| {
let mut center = band.center();
if let Some((_, opposite, _)) = bands.iter().find(|(s, _, _)| *s == (side + 2) % 4) {
let (axis, other) = if side.is_multiple_of(2) { (&mut center.y, opposite.center().y) } else { (&mut center.x, opposite.center().x) };
if (*axis - other).abs() < 20.0 {
*axis = (*axis + other) / 2.0 + if matches!(side, 0 | 3) { -10.0 } else { 10.0 };
}
}
let rect = Rect::from_center_size(center, if side.is_multiple_of(2) { vec2(20.0, 12.0) } else { vec2(12.0, 20.0) });
(side, rect, value)
})
.collect()
}
/// Resolve overlapping targets by distance to the visible grip, shared by hover and press.
/// Iteration order alone can let an earlier target steal clicks on a later grip's painted bar.
fn padding_at(handles: &[(usize, Rect, f64)], pos: Pos2) -> Option<(usize, Rect, f64)> {
handles
.iter()
.filter(|(_, rect, _)| rect.contains(pos))
.min_by(|(_, a, _), (_, b, _)| a.center().distance_sq(pos).total_cmp(&b.center().distance_sq(pos)))
.copied()
}
/// Alt links opposing sides, Alt+Shift all four. Shift alone retains the existing axis gesture.
/// Painting and editing share this rule so the highlighted sides are exactly those that change.
fn padding_affects(side: usize, candidate: usize, modifiers: egui::Modifiers) -> bool {
candidate == side || (modifiers.alt && modifiers.shift) || ((modifiers.alt || modifiers.shift) && candidate == (side + 2) % 4)
}
fn al_zones(app: &FigApp) -> Option<Zones> {
let ds = app.session.ds().ok()?;
if ds.selection.len() != 1 || ds.text_edit.is_some() || ds.vector_edit.is_some() {
@@ -357,13 +393,17 @@ fn al_zones(app: &FigApp) -> Option<Zones> {
app.to_screen(p.x, p.y)
};
let band = |x0: f64, y0: f64, x1: f64, y1: f64| Rect::from_two_pos(to(x0, y0), to(x1, y1));
let [pt, pr, pb, pl] = al.padding;
let [pt, pr, pb, pl] = al.padding.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 });
let (it, ir, ib, il) = figcraft_layout::insets(n, al);
let (fw, fh) = (n.width, n.height);
// Padding starts at the inside edge of an included stroke, as the layout's content does.
// The bands exclude the stroke itself so their labels and drags still edit only padding.
let (left, top, right, bottom) = (il - pl, it - pt, fw - ir + pr, fh - ib + pb);
let bands = vec![
(0, band(0.0, 0.0, fw, pt.max(4.0)), pt),
(1, band(fw - pr.max(4.0), 0.0, fw, fh), pr),
(2, band(0.0, fh - pb.max(4.0), fw, fh), pb),
(3, band(0.0, 0.0, pl.max(4.0), fh), pl),
(0, band(left, top, right, top + pt.max(4.0)), pt),
(1, band(right - pr.max(4.0), top, right, bottom), pr),
(2, band(left, bottom - pb.max(4.0), right, bottom), pb),
(3, band(left, top, left + pl.max(4.0), bottom), pl),
];
// An auto gap shows (and is dragged from) the distance the layout gives it; the drag makes it a
// fixed gap again, as typing one does.
@@ -376,8 +416,8 @@ fn al_zones(app: &FigApp) -> Option<Zones> {
let mut tracks = Vec::new();
if let Some(g) = figcraft_layout::grid_geometry(doc, id) {
// Grid: bands between columns (column gap) and between rows (row gap), and the tracks.
let (top, bottom) = (g.rows.first().map(|r| r.0).unwrap_or(pt), g.rows.last().map(|r| r.1).unwrap_or(fh - pb));
let (left, right) = (g.columns.first().map(|c| c.0).unwrap_or(pl), g.columns.last().map(|c| c.1).unwrap_or(fw - pr));
let (top, bottom) = (g.rows.first().map(|r| r.0).unwrap_or(it), g.rows.last().map(|r| r.1).unwrap_or(fh - ib));
let (left, right) = (g.columns.first().map(|c| c.0).unwrap_or(il), g.columns.last().map(|c| c.1).unwrap_or(fw - ir));
for pair in g.columns.windows(2) {
if let [a, b] = pair {
gaps.push(main(band(a.1, top, b.0, bottom), false, al.gap));
@@ -403,7 +443,7 @@ fn al_zones(app: &FigApp) -> Option<Zones> {
let flip = |r: figcraft_geom::Rect| if vertical { figcraft_geom::Rect::new(r.y0, r.x0, r.y1, r.x1) } else { r };
let fband = |x0: f64, y0: f64, x1: f64, y1: f64| if vertical { band(y0, x0, y1, x1) } else { band(x0, y0, x1, y1) };
// Main-axis length and padding, cross-axis length and padding.
let (mw, mp0, mp1, cw, cp0, cp1) = if vertical { (fh, pt, pb, fw, pl, pr) } else { (fw, pl, pr, fh, pt, pb) };
let (mw, mp0, mp1, cw, cp0, cp1) = if vertical { (fh, it, ib, fw, il, ir) } else { (fw, il, ir, fh, it, ib) };
let boxes: Vec<figcraft_geom::Rect> = figcraft_layout::flow_children(doc, id)
.into_iter()
.filter_map(|c| doc.node(c))
@@ -514,26 +554,38 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) {
draw_crop(app, painter, id, &img, r);
return;
}
let hover = painter.ctx().input(|i| i.pointer.hover_pos());
let (hover, modifiers) = painter.ctx().input(|i| (i.pointer.hover_pos(), i.modifiers));
let tool_move = app.session.tool.tool == figcraft_engine::ToolId::Move && !app.session.tool.busy();
let dragging: Option<Drag> = painter.ctx().data(|d| d.get_temp(drag_id()));
if !tool_move && dragging.is_none() {
return;
}
let Some(z) = al_zones(app) else { return };
let tokens = crate::theme::Tokens::get(painter.ctx());
let handles = padding_handles(&z.bands);
let active_side = match &dragging {
Some(Drag::Padding { side, .. }) => Some(*side),
_ => None,
_ => hover.and_then(|pos| padding_at(&handles, pos).map(|(side, _, _)| side)),
};
for seg in &z.tracks {
painter.add(Shape::dashed_line(seg, Stroke::new(1.0, PINK.gamma_multiply(0.6)), 3.0, 3.0));
}
for (side, r, v) in &z.bands {
let hot = hover.is_some_and(|h| r.contains(h)) || active_side == Some(*side);
for ((side, r, v), (_, handle, _)) in z.bands.iter().zip(&handles) {
let linked = active_side.is_some_and(|active| padding_affects(active, *side, modifiers));
let hot = hover.is_some_and(|h| r.contains(h)) || linked;
if hot {
painter.rect_filled(*r, CornerRadius::ZERO, PINK.gamma_multiply(0.25));
pink_label(painter, crate::canvas::fmt(*v), r.center());
let offset = if side.is_multiple_of(2) { vec2(28.0, 0.0) } else { vec2(0.0, -20.0) };
pink_label(painter, crate::canvas::fmt(*v), handle.center() + offset);
}
let grip = Rect::from_center_size(handle.center(), if side.is_multiple_of(2) { vec2(16.0, 4.0) } else { vec2(4.0, 16.0) });
painter.rect_filled(grip, CornerRadius::same(2), if linked { tokens.padding_grip } else { tokens.padding_grip.gamma_multiply(0.6) });
painter.rect_stroke(
grip,
CornerRadius::same(2),
Stroke::new(if linked { 1.5 } else { 1.0 }, tokens.padding_grip_border),
StrokeKind::Outside,
);
}
let drag_key = match &dragging {
Some(Drag::Gap { key, .. }) => Some(*key),
@@ -552,14 +604,21 @@ pub fn draw(app: &mut FigApp, painter: &egui::Painter) {
let _ = Align2::CENTER_CENTER;
}
/// Pointer handling; returns true when a handle owns the pointer this frame.
pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
let (pressed, down, released, shift) = ctx.input(|i| {
/// A handle may own only the cursor while ordinary canvas hover and secondary clicks continue.
pub enum Input {
Ignored,
Hover(egui::CursorIcon),
Captured,
}
/// Consume active handle gestures, but report padding hover separately from captured input.
pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> Input {
let (pressed, down, released, modifiers) = ctx.input(|i| {
(
i.pointer.button_pressed(egui::PointerButton::Primary),
i.pointer.primary_down(),
i.pointer.button_released(egui::PointerButton::Primary),
i.modifiers.shift,
i.modifiers,
)
});
let dragging: Option<Drag> = ctx.data(|d| d.get_temp(drag_id()));
@@ -567,17 +626,17 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
// Escape or Undo closed the gesture under the held button: the drag is over.
if !gesture_open(app) {
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
return true;
return Input::Captured;
}
if down {
apply(app, &drag, pos, shift);
apply(app, &drag, pos, modifiers);
ctx.set_cursor_icon(egui::CursorIcon::Grabbing);
}
if released || !down {
let _ = app.session.commit_interaction();
ctx.data_mut(|d| d.remove::<Drag>(drag_id()));
}
return true;
return Input::Captured;
}
// Hover cursors / press to start.
if let Some((id, fills, index, g)) = gradient_target(app) {
@@ -594,16 +653,16 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
let _ = app.session.begin_interaction("Edit gradient");
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gradient { id, fills, index, which }));
}
return true;
return Input::Captured;
}
}
// Stops: select and slide them; a click elsewhere on the line adds one there.
let (Some(a), Some(b)) = (pts[0], pts[1]) else { return false };
let (Some(a), Some(b)) = (pts[0], pts[1]) else { return Input::Ignored };
let stop_hit = g.stops.iter().position(|st| (a + (b - a) * st.position - pos).length() <= 8.0);
let t = line_param(a, b, pos);
let on_line = t.is_some_and(|(_, d)| d <= 5.0);
if stop_hit.is_none() && !on_line {
return false;
return Input::Ignored;
}
ctx.set_cursor_icon(if stop_hit.is_some() { egui::CursorIcon::Grab } else { egui::CursorIcon::Copy });
if pressed {
@@ -624,7 +683,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
ctx.data_mut(|d| d.insert_temp(crate::colorpicker::stop_id(), stop));
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gradient { id, fills, index, which: 3 + stop }));
}
return true;
return Input::Captured;
}
if let Some((id, index, e)) = blur_target(app, ctx) {
let hit = blur_points(app, id, &e).and_then(|pts| pts.iter().position(|p| (*p - pos).length() <= 8.0));
@@ -634,15 +693,15 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
let _ = app.session.begin_interaction("Edit progressive blur");
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Blur { id, index, which }));
}
return true;
return Input::Captured;
}
}
if let Some((id, fills, index, _, rect)) = crop_target(app) {
// Crop mode: the layer's own resize handles crop it (the pointer events carry Cmd/Ctrl).
if app.ui.crop.is_some() && on_resize_handle(app, pos) {
return false;
return Input::Ignored;
}
let Some(c) = crop_corners(app, id, rect) else { return false };
let Some(c) = crop_corners(app, id, rect) else { return Input::Ignored };
let start = screen_to_unit(app, id, pos).unwrap_or((0.0, 0.0));
let corner = c.iter().position(|p| (*p - pos).length() <= 8.0);
let inside = start.0 >= rect.0.min(rect.2) && start.0 <= rect.0.max(rect.2) && start.1 >= rect.1.min(rect.3) && start.1 <= rect.1.max(rect.3);
@@ -654,7 +713,7 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
if pressed {
app.ui.crop = None;
}
return false;
return Input::Ignored;
}
};
ctx.set_cursor_icon(if which == 4 {
@@ -668,22 +727,21 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
let _ = app.session.begin_interaction("Crop image");
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Crop { id, fills, index, which, start, rect }));
}
return true;
return Input::Captured;
}
if app.session.tool.tool != figcraft_engine::ToolId::Move || app.session.tool.busy() {
return false;
return Input::Ignored;
}
let Some(Zones { id, bands, gaps, .. }) = al_zones(app) else { return false };
for (side, r, v) in bands {
if r.contains(pos) {
ctx.set_cursor_icon(if side % 2 == 0 { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal });
if pressed {
let _ = app.session.begin_interaction("Padding");
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Padding { id, side, start: pos, value: v }));
return true;
}
return false;
let Some(Zones { id, bands, gaps, .. }) = al_zones(app) else { return Input::Ignored };
if let Some((side, _, value)) = padding_at(&padding_handles(&bands), pos) {
let cursor = if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal };
ctx.set_cursor_icon(cursor);
if pressed {
let _ = app.session.begin_interaction("Padding");
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Padding { id, side, start: pos, value }));
return Input::Captured;
}
return Input::Hover(cursor);
}
for g in gaps {
if g.rect.contains(pos) {
@@ -691,15 +749,15 @@ pub fn input(app: &mut FigApp, ctx: &egui::Context, pos: Pos2) -> bool {
if pressed {
let _ = app.session.begin_interaction("Gap");
ctx.data_mut(|d| d.insert_temp(drag_id(), Drag::Gap { id, start: pos, value: g.value, vertical: g.vertical, key: g.key }));
return true;
return Input::Captured;
}
return false;
return Input::Ignored;
}
}
false
Input::Ignored
}
fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, modifiers: egui::Modifiers) {
let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0).max(1e-6);
match drag {
Drag::Gradient { id, fills, index, which } => {
@@ -748,10 +806,12 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
_ => pos.x - start.x,
}) / zoom;
let v = (value + d).round().max(0.0);
let key = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"].get(*side).copied().unwrap_or("paddingTop");
// Shift drags both sides of the axis together.
let props =
if shift { if side % 2 == 0 { json!({"paddingVertical": v}) } else { json!({"paddingHorizontal": v}) } } else { json!({ key: v }) };
let props: serde_json::Map<String, serde_json::Value> = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"]
.iter()
.enumerate()
.filter(|(candidate, _)| padding_affects(*side, *candidate, modifiers))
.map(|(_, key)| ((*key).to_owned(), json!(v)))
.collect();
let _ = app.session.execute("node.set", &json!({"ids": [id], "props": props}));
}
Drag::Crop { id, fills, index, which, start, rect } => {
@@ -767,7 +827,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
let (cx, cy) = corners.get(*which).copied().unwrap_or((x1, y1));
let (ow, oh) = (cx - ax, cy - ay);
let (mut nw, mut nh) = (u.0 - ax, u.1 - ay);
if !shift {
if !modifiers.shift {
// Node aspect matters: the unit box is not square in pixels.
let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return };
let k = ((nw * n.width).abs() / (ow * n.width).abs().max(1e-9)).max((nh * n.height).abs() / (oh * n.height).abs().max(1e-9));
@@ -806,4 +866,6 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
#[cfg(test)]
mod character_fill_tests;
#[cfg(test)]
mod padding_tests;
#[cfg(test)]
mod region_tests;
@@ -0,0 +1,305 @@
//! Padding bands follow the content box, including the frame's inside stroke.
use egui::{Event, Rect, vec2};
use figcraft_doc::NodeId;
use figcraft_engine::{Session, params::id_of};
use serde_json::json;
use super::{Drag, al_zones, drag_id};
use crate::layers_drag_tests::Ui;
fn scene() -> (Ui, NodeId) {
let mut s = Session::new();
let f = id_of(
&s.execute(
"frame.create",
&json!({"x": 100, "y": 100, "width": 300, "height": 200,
"props": {"layout": "horizontal", "gap": 10, "padding": [10, 20, 30, 40], "stroke": "#000000", "strokeWeight": 4, "strokeAlign": "inside"}
}),
)
.unwrap()["id"],
)
.unwrap();
s.execute("select.set", &json!({"ids": [f]})).unwrap();
(Ui::new(s), f)
}
/// The four visible grips in paint order, without relying on the hit-test geometry.
fn painted_grips(output: &egui::FullOutput) -> Vec<Rect> {
crate::live_tests::flat(&output.shapes)
.iter()
.filter_map(|shape| match shape {
egui::Shape::Rect(r)
if r.fill == super::PINK.gamma_multiply(0.6)
&& ((r.rect.width() == 16.0 && r.rect.height() == 4.0) || (r.rect.width() == 4.0 && r.rect.height() == 16.0)) =>
{
Some(r.rect)
}
_ => None,
})
.collect()
}
/// Even collapsed content boxes and reduced zoom leave each painted grip independently usable.
#[test]
fn tiny_frames_keep_every_painted_padding_grip_reachable() {
for (width, height, zoom, stroke) in [
(300.0, 4.0, 1.0, 0.0),
(300.0, 6.0, 1.0, 0.0),
(300.0, 10.0, 1.0, 0.0),
(300.0, 20.0, 0.25, 0.0),
(300.0, 20.0, 1.0, 8.0),
(4.0, 200.0, 1.0, 0.0),
(4.0, 4.0, 0.25, 0.0),
] {
for side in 0_usize..4 {
let (mut u, f) = scene();
u.app.run("node.set", json!({"ids": [f], "props": {"width": width, "height": height, "padding": 0, "strokeWeight": stroke}}));
u.app.session.ds_mut().unwrap().view.zoom = zoom;
let grips = painted_grips(&u.frame_output(vec![Event::PointerGone]));
assert_eq!(grips.len(), 4);
let center = grips[side].center();
let output = u.frame_output(vec![Event::PointerMoved(center)]);
assert_eq!(
output.platform_output.cursor_icon,
if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }
);
u.button(center, true);
assert!(
matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { side: active, .. }) if active == side),
"{width}x{height}, zoom {zoom}, stroke {stroke}, side {side}"
);
let to = center + [vec2(0.0, 2.0), vec2(-2.0, 0.0), vec2(0.0, -2.0), vec2(2.0, 0.0)][side] * zoom as f32;
u.frame(vec![Event::PointerMoved(to)]);
u.button(to, false);
let mut expected = [0.0; 4];
expected[side] = 2.0;
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, expected);
u.app.run("edit.undo", json!({}));
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [0.0; 4]);
}
}
}
/// A painted side grip wins over a neighbouring grip's enlarged, overlapping hit target.
#[test]
fn overlapping_padding_targets_use_the_nearest_grip_for_hover_and_press() {
let (mut u, f) = scene();
u.app.run("node.set", json!({"ids": [f], "props": {"width": 4, "height": 4, "padding": 0, "strokeWeight": 0}}));
let grips = painted_grips(&u.frame_output(vec![Event::PointerGone]));
assert_eq!(grips.len(), 4);
// On the upper part of the right bar, also inside the top grip's larger hit target.
let point = egui::pos2(grips[1].center().x - 1.0, grips[0].center().y + 5.0);
assert!(grips[1].contains(point));
let handles = super::padding_handles(&al_zones(&u.app).unwrap().bands);
assert_eq!(handles.iter().filter(|(_, r, _)| r.contains(point)).count(), 2);
let output = u.frame_output(vec![Event::PointerMoved(point)]);
assert_eq!(output.platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal);
let shapes = crate::live_tests::flat(&output.shapes);
assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == grips[1] && r.fill == super::PINK)));
assert!(!shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == grips[0] && r.fill == super::PINK)));
u.button(point, true);
assert!(matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { side: 1, .. })));
u.button(point, false);
}
#[test]
fn padding_bands_follow_uniform_and_individual_inside_strokes() {
let (mut u, f) = scene();
for (props, stroke) in [
(json!({"strokeWeight": 4}), [4.0; 4]),
(json!({"strokeWeight": 24}), [24.0; 4]),
(json!({"strokeSides": [8, 12, 16, 24]}), [8.0, 12.0, 16.0, 24.0]),
(json!({"strokesIncluded": false}), [0.0; 4]),
(json!({"strokesIncluded": true, "strokeAlign": "center"}), [0.0; 4]),
(json!({"strokeAlign": "outside"}), [0.0; 4]),
] {
u.app.run("node.set", json!({"ids": [f], "props": props}));
let [t, r, b, l] = stroke;
let expected = [
(l, t, 300.0 - r, t + 10.0),
(300.0 - r - 20.0, t, 300.0 - r, 200.0 - b),
(l, 200.0 - b - 30.0, 300.0 - r, 200.0 - b),
(l, t, l + 40.0, 200.0 - b),
];
let zones = al_zones(&u.app).unwrap();
for ((side, band, value), (x0, y0, x1, y1)) in zones.bands.iter().zip(expected) {
let expected = Rect::from_two_pos(u.app.to_screen(100.0 + x0, 100.0 + y0), u.app.to_screen(100.0 + x1, 100.0 + y1));
assert_eq!(*band, expected, "side {side}, stroke {stroke:?}");
assert_eq!(*value, [10.0, 20.0, 30.0, 40.0][*side]);
}
}
}
#[test]
fn gap_bands_span_the_content_box_inside_stroke_and_padding() {
let (mut u, f) = scene();
for _ in 0..2 {
u.app.run("shape.rectangle", json!({"parent": f, "width": 40, "height": 20}));
}
u.app.run("select.set", json!({"ids": [f]}));
for (mode, expected) in [("horizontal", (184.0, 114.0, 194.0, 266.0)), ("vertical", (144.0, 134.0, 376.0, 144.0))] {
u.app.run("node.set", json!({"ids": [f], "props": {"layout": mode}}));
let zones = al_zones(&u.app).unwrap();
assert_eq!(zones.gaps.len(), 1);
let (x0, y0, x1, y1) = expected;
assert_eq!(zones.gaps[0].rect, Rect::from_two_pos(u.app.to_screen(x0, y0), u.app.to_screen(x1, y1)));
}
}
#[test]
fn padding_drag_starts_only_on_the_central_handle_and_undoes_in_one_step() {
let (mut u, f) = scene();
u.app.run("node.set", json!({"ids": [f], "props": {"strokeWeight": 24}}));
u.frame(vec![]);
let top = al_zones(&u.app).unwrap().bands[0].1;
// The band away from its handle remains available to ordinary canvas tools.
let away = top.center() + vec2(50.0, 0.0);
u.button(away, true);
assert!(!matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { .. })));
u.button(away, false);
u.app.run("select.set", json!({"ids": [f]}));
u.frame(vec![]);
let center = al_zones(&u.app).unwrap().bands[0].1.center();
let zoom = u.app.session.ds().unwrap().view.zoom as f32;
u.button(center, true);
assert!(matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { side: 0, .. })));
let to = center + vec2(0.0, 6.0 * zoom);
u.frame(vec![Event::PointerMoved(to)]);
u.button(to, false);
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [16.0, 20.0, 30.0, 40.0]);
u.app.run("edit.undo", json!({}));
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [10.0, 20.0, 30.0, 40.0]);
}
#[test]
fn every_padding_grip_has_a_resize_cursor_and_links_the_requested_sides() {
for modifiers in
[egui::Modifiers::NONE, egui::Modifiers::ALT, egui::Modifiers::SHIFT, egui::Modifiers { alt: true, shift: true, ..Default::default() }]
{
for side in 0..4 {
let (mut u, f) = scene();
let center = al_zones(&u.app).unwrap().bands[side].1.center();
let output = u.frame_with(vec![Event::PointerMoved(center)], modifiers);
let cursor = if side.is_multiple_of(2) { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal };
assert_eq!(output.platform_output.cursor_icon, cursor, "padding side {side}");
u.button(center, true);
assert!(matches!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Padding { side: active, .. }) if active == side));
let zoom = u.app.session.ds().unwrap().view.zoom as f32;
let delta = [vec2(0.0, 6.0), vec2(-6.0, 0.0), vec2(0.0, -6.0), vec2(6.0, 0.0)][side] * zoom;
let to = center + delta;
u.frame_with(vec![Event::PointerMoved(to)], modifiers);
u.button(to, false);
let mut expected = [10.0, 20.0, 30.0, 40.0];
let value = expected[side] + 6.0;
if modifiers.alt && modifiers.shift {
expected = [value; 4];
} else {
expected[side] = value;
if modifiers.alt || modifiers.shift {
expected[(side + 2) % 4] = value;
}
}
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, expected);
u.app.run("edit.undo", json!({}));
assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().padding, [10.0, 20.0, 30.0, 40.0]);
}
}
}
#[test]
fn modifier_keys_highlight_linked_padding_bands_before_and_during_a_drag() {
let (mut u, _) = scene();
let zones = al_zones(&u.app).unwrap();
let center = zones.bands[0].1.center();
u.frame(vec![Event::PointerMoved(center)]);
// Pressing modifiers without moving the pointer previews the other affected sides.
for (modifiers, active) in [
(egui::Modifiers::NONE, [true, false, false, false]),
(egui::Modifiers::ALT, [true, false, true, false]),
(egui::Modifiers { alt: true, shift: true, ..Default::default() }, [true; 4]),
(egui::Modifiers::NONE, [true, false, false, false]),
] {
let output = u.frame_with(vec![], modifiers);
let shapes = crate::live_tests::flat(&output.shapes);
for ((side, rect, _), active) in zones.bands.iter().zip(active) {
let lit = shapes.iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.rect == *rect && r.fill == super::PINK.gamma_multiply(0.25)));
assert_eq!(lit, active, "side {side}, modifiers {modifiers:?}");
}
}
u.button(center, true);
let modifiers = egui::Modifiers { alt: true, shift: true, ..Default::default() };
let output = u.frame_with(vec![], modifiers);
let zones = al_zones(&u.app).unwrap();
let shapes = crate::live_tests::flat(&output.shapes);
for (_, rect, _) in &zones.bands {
assert!(shapes.iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.rect == *rect && r.fill == super::PINK.gamma_multiply(0.25))));
}
u.button(center, false);
}
/// Hover over a grip must still update the layer under the pointer without editing the document.
#[test]
fn padding_grip_hover_preserves_canvas_hover_and_resize_cursor() {
let (mut u, f) = scene();
let other = id_of(&u.app.session.execute("shape.rectangle", &json!({"x": 500, "y": 100, "width": 40, "height": 40})).unwrap()["id"]).unwrap();
u.app.run("select.set", json!({"ids": [f]}));
let over_other = u.app.to_screen(520.0, 120.0);
u.frame(vec![Event::PointerMoved(over_other)]);
assert_eq!(u.app.session.ds().unwrap().hover, Some(other));
let history = u.app.session.undo_depth();
let grip = al_zones(&u.app).unwrap().bands[0].1.center();
let output = u.frame_output(vec![Event::PointerMoved(grip)]);
assert_eq!(u.app.session.ds().unwrap().hover, Some(f), "the previous layer must not stay hovered");
assert_eq!(output.platform_output.cursor_icon, egui::CursorIcon::ResizeVertical);
assert_eq!(u.app.session.undo_depth(), history);
assert!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())).is_none());
}
/// Right-click on any padding grip opens the ordinary canvas menu without starting a drag.
#[test]
fn padding_grips_preserve_secondary_click_context_menus() {
for side in 0..4 {
let (mut u, f) = scene();
let center = al_zones(&u.app).unwrap().bands[side].1.center();
let history = u.app.session.undo_depth();
u.frame(vec![Event::PointerMoved(center)]);
for pressed in [true, false] {
u.frame(vec![Event::PointerButton { pos: center, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }]);
}
let (_, targets) = u.app.ui.context_menu.as_ref().expect("right-click on the grip opens the menu");
assert!(targets.contains(&f));
assert!(u.ctx.data(|d| d.get_temp::<Drag>(drag_id())).is_none());
assert_eq!(u.app.session.undo_depth(), history);
}
}
/// Custom light/dark palettes must control both grip states and their outlines.
#[test]
fn padding_grips_use_the_theme_fill_and_outline() {
for mut tokens in [crate::theme::Tokens::light(), crate::theme::Tokens::dark()] {
let (mut u, _) = scene();
let grips = painted_grips(&u.frame_output(vec![Event::PointerGone]));
assert_eq!(grips.len(), 4);
tokens.padding_grip = if tokens.dark { egui::Color32::from_rgb(20, 40, 60) } else { egui::Color32::from_rgb(120, 40, 60) };
tokens.padding_grip_border = egui::Color32::from_rgb(210, 180, 150);
for active in [false, true] {
let events = if active { vec![Event::PointerMoved(grips[0].center())] } else { vec![Event::PointerGone] };
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, u.screen)), events, ..Default::default() };
let mut output = u.ctx.clone().run_ui(raw, |ui| {
crate::theme::apply(ui.ctx(), tokens);
super::draw(&mut u.app, ui.painter());
});
output.textures_delta.clear();
let shapes = crate::live_tests::flat(&output.shapes);
for (side, grip) in grips.iter().enumerate() {
let linked = active && side == 0;
let fill = if linked { tokens.padding_grip } else { tokens.padding_grip.gamma_multiply(0.6) };
assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == *grip && r.fill == fill)));
let width = if linked { 1.5 } else { 1.0 };
assert!(shapes.iter().any(|shape| matches!(shape, egui::Shape::Rect(r) if r.rect == *grip && r.stroke.color == tokens.padding_grip_border && r.stroke.width == width)));
}
}
}
}
+16 -4
View File
@@ -283,9 +283,15 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo
if !app.canvas.dragging && resp.hovered() && crate::guides::input(app, &ctx, pos) {
return false;
}
if !app.canvas.dragging && resp.hovered() && crate::handles::input(app, &ctx, pos) {
return false;
}
let handle_cursor = if !app.canvas.dragging && resp.hovered() {
match crate::handles::input(app, &ctx, pos) {
crate::handles::Input::Captured => return false,
crate::handles::Input::Hover(cursor) => Some(cursor),
crate::handles::Input::Ignored => None,
}
} else {
None
};
if resp.secondary_clicked() {
open_context_menu(app, pos, mods.command);
return true;
@@ -382,7 +388,13 @@ pub(super) fn input(app: &mut FigApp, ui: &mut Ui, resp: &egui::Response) -> boo
send(app, PointerKind::Up, release_pos.unwrap_or(pos), &mods);
}
}
true
// Padding hover changes the cursor without skipping the normal hover and context-menu paths.
if let Some(cursor) = handle_cursor {
ctx.set_cursor_icon(cursor);
false
} else {
true
}
}
/// Pointer event `kind` at screen point `pos`, to the tools.
+8
View File
@@ -42,6 +42,10 @@ pub struct Tokens {
pub success: Color32,
pub warning: Color32,
pub guide: Color32,
/// Auto layout padding grips on the canvas.
pub padding_grip: Color32,
/// Contrasting edge around padding grips, including their dimmed state.
pub padding_grip_border: Color32,
pub tab_bar: Color32,
pub tab_active: Color32,
pub shadow: Color32,
@@ -133,6 +137,8 @@ impl Tokens {
success: DEV_READY,
warning: Color32::from_rgb(0xFF, 0xCD, 0x29),
guide: Color32::from_rgb(0xF2, 0x48, 0x22),
padding_grip: Color32::from_rgb(0xF2, 0x48, 0x8C),
padding_grip_border: Color32::WHITE,
tab_bar: Color32::from_rgb(0xE8, 0xE8, 0xE8),
tab_active: Color32::from_rgb(0xFF, 0xFF, 0xFF),
shadow: Color32::from_black_alpha(40),
@@ -176,6 +182,8 @@ impl Tokens {
success: DEV_READY,
warning: Color32::from_rgb(0xFF, 0xCD, 0x29),
guide: Color32::from_rgb(0xF2, 0x48, 0x22),
padding_grip: Color32::from_rgb(0xF2, 0x48, 0x8C),
padding_grip_border: Color32::WHITE,
tab_bar: Color32::from_rgb(0x1E, 0x1E, 0x1E),
tab_active: Color32::from_rgb(0x2C, 0x2C, 0x2C),
shadow: Color32::from_black_alpha(90),
+21 -1
View File
@@ -1,6 +1,6 @@
# Auto layout and constraints parity
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-09 · **Change:** patch (grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** patch (padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7)
Auto layout is the most used layout feature in Figma and the one where small differences (a
hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%,
@@ -27,6 +27,20 @@ outside the new frame’s layout flow and adding an unnecessary level to the lay
the selected container makes later changes to a child’s size reflow its siblings directly.
Selecting several groups still wraps that selection in a shared auto layout frame.
## Canvas padding grips
Padding bands begin at the inner edge of an included inside stroke. Each band's central grip
starts a padding drag; the rest of the band still highlights on hover and remains available to
ordinary canvas tools. The grip shows vertical resize arrows on the top and bottom, horizontal
arrows on the sides. Alt synchronises the opposite side to the dragged value, and Alt+Shift
synchronises all four. Shift alone retains the existing opposite-side gesture. Affected bands
and grips highlight immediately when modifiers change, both before and during a drag. One undo
restores every affected side. On very small frames or at reduced zoom, opposite grips move
outward to stay at least 20 screen pixels apart; the padding bands keep their geometry.
Overlapping hit targets select the nearest visible grip for both hover and drag. Hover keeps
the resize cursor while updating the hovered layer, and a secondary click opens the normal
canvas context menu. Only the primary press and active drag capture pointer input.
## Rules from the documentation
Status: **pass** (a case in the suite holds), **fixed** (the suite found a divergence, now fixed),
@@ -52,6 +66,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver
| Padding per side (uniform, vertical/horizontal, individual) | pass | `padding_and_stroke_rules` |
| A frame is never smaller than its padding (plus an included inside stroke), even when Fixed, hugging or given a smaller max | **fixed** | was free to shrink below its padding |
| Strokes included: only the frame's own **inside** stroke takes up space; center and outside strokes never do | **fixed** | every stroke alignment counted before; per-side inside weights count per side (silent on individual weights) |
| Canvas padding and gap bands follow the included inside stroke | **fixed** | Padding bands begin at the stroke's inner edge; flow gap bands span the available content box. Only the central grip starts a padding drag; hovering the band still highlights it. Geometry and pointer interactions are covered by `canvas::handles::padding_tests`. |
| New auto layout includes inside strokes by default | **fixed** | the default was excluded |
| Strokes included / excluded setting in the Design panel | **added** | `strokesIncluded` existed as a prop only |
| Gap: fixed distance; negative gaps overlap | pass | `gap_rules` |
@@ -101,7 +116,12 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver
| Date | Change | Summary |
|---|---|---|
| 2026-11-13 | patch | M2, #2152: Padding grip fills and outlines come from dedicated theme tokens, preserving linked-state emphasis and border widths. A rendering regression checks custom light and dark palettes. |
| 2026-11-13 | patch | M2, #2152: Padding grips preserve canvas hover and secondary-click context menus while retaining their resize cursor. Only primary presses and active handle drags capture input. Regressions reproduce both stale layer hover and blocked right-click menus. |
| 2026-11-11 | patch | M2.1: grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) (this replaces the 2026-10-11 rule from the documentation). Layout behaviour suite: three cases flipped, three added |
| 2026-11-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. |
| 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. |
| 2026-11-09 | patch | M2: Canvas padding bands follow the inner edge of included inside strokes, including per-side weights; gap bands use the same content insets. Geometry regression tests cover stroke growth, exclusion and center/outside alignment. Dimensions and padding values are unchanged. |
| 2026-11-05 | patch | M2, #1823: Suggest auto layout is no longer Add auto layout under another name: `layout.suggest` splits a frame's layers into rows (Vertical) or else columns (Horizontal) by the gaps between their boxes, wraps each band of several layers in a new frame without fill or clipping that hugs it, and repeats inside it (16 levels, 1,000 layers per frame at most). The frame keeps its size; gap and padding come from the bands, so layers keep their boxes where the gaps are even and the bands start at the same offset; instances and layers inside them are refused; uneven gaps (smallest used), bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes come back as `warnings`. A band frame hugs only when its own split succeeds: a band whose layers overlap along both axes gets no auto layout and stays Fixed, so it cannot reflow those children. `direction` sets the top level only; one undo step; `layout.add` is unchanged. Tests in `layout_suggest_tests.rs` |
| 2026-11-02 | patch | M2: a Cmd/Ctrl-click on a padding field (the horizontal or vertical pair, or a side with Individual padding open) makes the value typed go to all four sides in one undo step (Guide to auto layout, Keyboard shortcut guide); a plain click still edits that axis or side alone. The modifier was ignored before. Test: `padding_individual_tests` |
| 2026-11-03 | patch | M2, #1825: baseline alignment of a layer without text (an icon next to a text) puts its bottom on the line's baseline, as the help center's figure shows ("the bottoms of the icon and the word home are aligned on the red line"); it kept to the top of the line. A layer reaching below the text's baseline moves the text down, and a line with no text lines the layers' bottoms up (the documentation is silent; CSS baseline alignment does the same). Tests: `alignment_rules` (three cases), engine `baseline_alignment_puts_an_icons_bottom_on_the_text_baseline`. Numbers unchanged. |