feat: add production UI gallery and inspector system
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-07-18 12:05:26 -04:00
1 parent cf6eaba534
commit 53dc1e44d8
95 files changed
+11003 -1652

No files matched your search

@@ -0,0 +1,328 @@
//! Penpot 420×350 material color popup with live preview and reversible dismissal.
mod popup;
use egui;
use super::typography::TypeRole;
pub(super) const POPUP_SIZE: egui::Vec2 = egui::vec2(420.0, 350.0);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PickerMode {
Wheel,
Sliders,
Presets,
}
#[derive(Debug, Clone)]
pub(super) struct PickerSession {
original: [f32; 4],
current: [f32; 4],
mode: PickerMode,
hex: String,
opened_at: f64,
owner_rect: egui::Rect,
original_intensity: Option<f32>,
current_intensity: Option<f32>,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ColorPickerResponse {
pub changed: bool,
pub applied: bool,
pub cancelled: bool,
}
pub fn color_control(
ui: &mut egui::Ui,
salt: impl std::hash::Hash,
label: &str,
rgba: &mut [f32; 4],
) -> ColorPickerResponse {
color_control_impl(ui, salt, label, rgba, None)
}
pub fn color_control_with_intensity(
ui: &mut egui::Ui,
salt: impl std::hash::Hash,
label: &str,
rgba: &mut [f32; 4],
intensity: &mut f32,
) -> ColorPickerResponse {
color_control_impl(ui, salt, label, rgba, Some(intensity))
}
fn color_control_impl(
ui: &mut egui::Ui,
salt: impl std::hash::Hash,
label: &str,
rgba: &mut [f32; 4],
intensity: Option<&mut f32>,
) -> ColorPickerResponse {
let palette = super::palette(ui);
let id = ui.make_persistent_id(("penpot_color_picker", salt));
let width = ui.available_width().max(1.0);
let (rect, response) = ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::click());
let swatch_width = 44.0_f32.min(width);
let swatch_rect = egui::Rect::from_min_size(rect.min, egui::vec2(swatch_width, 22.0));
let gap = if width > swatch_width + 6.0 { 6.0 } else { 0.0 };
let hex_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(swatch_width + gap, 0.0),
egui::vec2((width - swatch_width - gap).max(0.0), 22.0),
);
popup::checker(ui.painter(), swatch_rect, palette.control, palette.elevated);
let inner_swatch = swatch_rect.shrink(1.0);
let rgb_rect = egui::Rect::from_min_max(
inner_swatch.min,
egui::pos2(inner_swatch.center().x, inner_swatch.max.y),
);
let alpha_rect = egui::Rect::from_min_max(
egui::pos2(inner_swatch.center().x, inner_swatch.min.y),
inner_swatch.max,
);
ui.painter().rect_filled(
rgb_rect,
3.0,
egui::Color32::from_rgb(byte(rgba[0]), byte(rgba[1]), byte(rgba[2])),
);
ui.painter().rect_filled(alpha_rect, 3.0, color32(*rgba));
ui.painter().rect_stroke(
swatch_rect,
4.0,
egui::Stroke::new(1.0_f32, palette.border_strong),
egui::StrokeKind::Inside,
);
if hex_rect.width() > 0.0 {
ui.painter().rect(
hex_rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
ui.painter().text(
hex_rect.left_center() + egui::vec2(9.0, 0.0),
egui::Align2::LEFT_CENTER,
hex(*rgba),
TypeRole::Body.font(),
palette.text_primary,
);
}
if response.clicked() {
let opened_at = ui.input(|input| input.time);
ui.ctx().data_mut(|data| {
data.insert_temp(
id,
PickerSession {
original: *rgba,
current: *rgba,
mode: PickerMode::Wheel,
hex: hex(*rgba),
opened_at,
owner_rect: ui.clip_rect(),
original_intensity: intensity.as_deref().copied(),
current_intensity: intensity.as_deref().copied(),
},
);
});
}
let before = *rgba;
let mut result = ColorPickerResponse::default();
let Some(mut session) = ui.ctx().data_mut(|data| data.get_temp::<PickerSession>(id)) else {
return result;
};
let screen_rect = ui.ctx().content_rect();
let popup_rect = centered_popup_rect(session.owner_rect, screen_rect);
let scrim = egui::Area::new(id.with("modal_scrim"))
.order(egui::Order::Foreground)
.fixed_pos(session.owner_rect.min)
.show(ui.ctx(), |ui| {
let (rect, response) =
ui.allocate_exact_size(session.owner_rect.size(), egui::Sense::click());
ui.painter()
.rect_filled(rect, 0.0, egui::Color32::from_black_alpha(132));
response
})
.inner;
let popup_response = egui::Area::new(id.with("popup"))
.order(egui::Order::Foreground)
.fixed_pos(popup_rect.min)
.show(ui.ctx(), |ui| {
ui.set_min_size(POPUP_SIZE);
ui.set_max_size(POPUP_SIZE);
popup::show(ui, label, &mut session, &mut result)
})
.response;
let escape = ui.input(|input| input.key_pressed(egui::Key::Escape));
let outside_click = scrim.clicked()
|| ui.input(|input| {
input.pointer.any_pressed()
&& input.time > session.opened_at
&& input
.pointer
.interact_pos()
.is_some_and(|position| !popup_response.rect.contains(position))
});
if escape || outside_click {
result.cancelled = true;
}
if result.cancelled {
*rgba = session.original;
if let (Some(target), Some(original)) = (intensity, session.original_intensity) {
*target = original;
}
ui.ctx().data_mut(|data| data.remove::<PickerSession>(id));
} else {
*rgba = session.current;
if let (Some(target), Some(current)) = (intensity, session.current_intensity) {
*target = current;
}
if result.applied {
ui.ctx().data_mut(|data| data.remove::<PickerSession>(id));
} else {
ui.ctx().data_mut(|data| data.insert_temp(id, session));
}
}
result.changed = *rgba != before;
result
}
fn centered_popup_rect(owner: egui::Rect, screen: egui::Rect) -> egui::Rect {
const SCREEN_MARGIN: f32 = 12.0;
let desired = owner.center() - POPUP_SIZE * 0.5;
let minimum = screen.min + egui::vec2(SCREEN_MARGIN, SCREEN_MARGIN);
let maximum = screen.max - POPUP_SIZE - egui::vec2(SCREEN_MARGIN, SCREEN_MARGIN);
let x = if maximum.x >= minimum.x {
desired.x.clamp(minimum.x, maximum.x)
} else {
screen.center().x - POPUP_SIZE.x * 0.5
};
let y = if maximum.y >= minimum.y {
desired.y.clamp(minimum.y, maximum.y)
} else {
screen.center().y - POPUP_SIZE.y * 0.5
};
egui::Rect::from_min_size(egui::pos2(x, y), POPUP_SIZE)
}
pub(super) fn set_current(session: &mut PickerSession, value: [f32; 4]) {
session.current = value.map(|component| component.clamp(0.0, 1.0));
session.hex = hex(session.current);
}
pub(super) fn color32(value: [f32; 4]) -> egui::Color32 {
egui::Color32::from_rgba_unmultiplied(
byte(value[0]),
byte(value[1]),
byte(value[2]),
byte(value[3]),
)
}
pub(super) fn rgba(value: egui::Color32) -> [f32; 4] {
[
value.r() as f32 / 255.0,
value.g() as f32 / 255.0,
value.b() as f32 / 255.0,
value.a() as f32 / 255.0,
]
}
pub(super) fn byte(value: f32) -> u8 {
(value.clamp(0.0, 1.0) * 255.0).round() as u8
}
pub(super) fn hex(value: [f32; 4]) -> String {
if byte(value[3]) == 255 {
format!(
"#{:02X}{:02X}{:02X}",
byte(value[0]),
byte(value[1]),
byte(value[2])
)
} else {
format!(
"#{:02X}{:02X}{:02X}{:02X}",
byte(value[0]),
byte(value[1]),
byte(value[2]),
byte(value[3])
)
}
}
pub(super) fn parse_hex(value: &str) -> Option<[f32; 4]> {
let value = value.trim().trim_start_matches('#');
if !matches!(value.len(), 6 | 8) {
return None;
}
let rgb = u32::from_str_radix(&value[..6], 16).ok()?;
let alpha = if value.len() == 8 {
u8::from_str_radix(&value[6..], 16).ok()?
} else {
255
};
Some([
((rgb >> 16) & 0xFF) as f32 / 255.0,
((rgb >> 8) & 0xFF) as f32 / 255.0,
(rgb & 0xFF) as f32 / 255.0,
alpha as f32 / 255.0,
])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn popup_centers_on_inspector_owner_and_stays_on_screen() {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
let inspector =
egui::Rect::from_min_size(egui::pos2(800.0, 40.0), egui::vec2(640.0, 820.0));
let popup = centered_popup_rect(inspector, screen);
assert_eq!(popup.size(), POPUP_SIZE);
assert_eq!(popup.center(), inspector.center());
let edge = centered_popup_rect(
egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(200.0, 200.0)),
screen,
);
assert!(edge.left() >= 12.0);
assert!(edge.top() >= 12.0);
}
#[test]
fn penpot_hex_round_trip_preserves_rgba() {
let value = [0.2, 0.4, 0.6, 0.8];
let parsed = parse_hex(&hex(value)).expect("valid generated hex");
for (left, right) in value.into_iter().zip(parsed) {
assert!((left - right).abs() <= 1.0 / 255.0);
}
}
#[test]
fn cancel_restores_opening_value_and_apply_keeps_live_preview() {
let original = [0.1, 0.2, 0.3, 1.0];
let mut session = PickerSession {
original,
current: [0.8, 0.7, 0.6, 0.5],
mode: PickerMode::Wheel,
hex: String::new(),
opened_at: 0.0,
owner_rect: egui::Rect::ZERO,
original_intensity: None,
current_intensity: None,
};
let applied = session.current;
set_current(&mut session, applied);
assert_eq!(session.original, original);
assert_eq!(session.current, applied);
}
}
@@ -0,0 +1,765 @@
//! Fixed-coordinate renderer for the exported Penpot color overlay.
mod sliders;
use egui::{self, ecolor::Hsva};
use egui_phosphor_icons::{icons, Icon};
use super::{
byte, color32, parse_hex, rgba, set_current, ColorPickerResponse, PickerMode, PickerSession,
POPUP_SIZE,
};
use crate::design_system::typography::TypeRole;
const RECENTS: [egui::Color32; 8] = colors([
0xE7D4B4, 0x53D3E6, 0xCA6CE0, 0xF06B75, 0x55C58A, 0xF3C85B, 0x6F88EF, 0xF3F5F7,
]);
const PRESETS: [egui::Color32; 24] = colors([
0xE7D4B4, 0xF2EEE8, 0xD5B59C, 0xA8795B, 0x734C3C, 0x3B2D29, 0xE45D68, 0xF09A55, 0xE9D05B,
0x79C267, 0x45B7A6, 0x4FA9D8, 0x5A78DE, 0x8E68D8, 0xC26BC7, 0xE68DB5, 0xF5F7FA, 0xC4CCD5,
0x8995A3, 0x56616E, 0x303842, 0x1D242C, 0x101419, 0x07090C,
]);
const PLANNED_EYEDROPPER: &str = "Planned — screen sampling pending";
const fn colors<const N: usize>(values: [u32; N]) -> [egui::Color32; N] {
let mut result = [egui::Color32::BLACK; N];
let mut index = 0;
while index < N {
let value = values[index];
result[index] = egui::Color32::from_rgb(
((value >> 16) & 0xFF) as u8,
((value >> 8) & 0xFF) as u8,
(value & 0xFF) as u8,
);
index += 1;
}
result
}
struct Geometry;
impl Geometry {
const HEADER_HEIGHT: f32 = 38.0;
const CONTENT: egui::Rect =
egui::Rect::from_min_max(egui::pos2(12.0, 74.0), egui::pos2(408.0, 276.0));
const WHEEL_EDITOR: egui::Rect =
egui::Rect::from_min_max(egui::pos2(12.0, 74.0), egui::pos2(190.0, 276.0));
const VALUES: egui::Rect =
egui::Rect::from_min_max(egui::pos2(198.0, 82.0), egui::pos2(396.0, 268.0));
const RECENTS: egui::Rect =
egui::Rect::from_min_max(egui::pos2(12.0, 282.0), egui::pos2(408.0, 310.0));
const FOOTER: egui::Rect =
egui::Rect::from_min_max(egui::pos2(12.0, 316.0), egui::pos2(408.0, 342.0));
fn rect(root: egui::Rect, local: egui::Rect) -> egui::Rect {
local.translate(root.min.to_vec2())
}
fn at(root: egui::Rect, x: f32, y: f32, width: f32, height: f32) -> egui::Rect {
egui::Rect::from_min_size(root.min + egui::vec2(x, y), egui::vec2(width, height))
}
}
pub(super) fn show(
ui: &mut egui::Ui,
label: &str,
session: &mut PickerSession,
result: &mut ColorPickerResponse,
) -> egui::Response {
let palette = crate::design_system::palette(ui);
let (root, response) = ui.allocate_exact_size(POPUP_SIZE, egui::Sense::hover());
ui.painter().rect(
root,
7.0,
palette.panel,
egui::Stroke::new(1.0_f32, palette.border_strong),
egui::StrokeKind::Inside,
);
ui.painter().line_segment(
[
root.min + egui::vec2(0.0, Geometry::HEADER_HEIGHT),
root.min + egui::vec2(root.width(), Geometry::HEADER_HEIGHT),
],
egui::Stroke::new(1.0_f32, palette.border),
);
header(ui, root, label, session, result);
mode_tabs(ui, root, session);
intensity_control(ui, root, session);
match session.mode {
PickerMode::Wheel => wheel_mode(ui, root, session),
PickerMode::Sliders => sliders::show(ui, root, session),
PickerMode::Presets => presets_mode(ui, root, session),
}
recent_row(ui, root, session);
footer(ui, root, result);
response
}
fn intensity_control(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let Some(intensity) = session.current_intensity.as_mut() else {
return;
};
let palette = crate::design_system::palette(ui);
text(
ui,
root.min + egui::vec2(272.0, 55.0),
egui::Align2::LEFT_CENTER,
"Intensity",
TypeRole::Small.font(),
palette.text_muted,
);
ui.put(
Geometry::at(root, 326.0, 43.0, 82.0, 24.0),
egui::DragValue::new(intensity)
.range(0.0..=50_000.0)
.speed(10.0),
)
.on_hover_text("Emissive luminance multiplier in nits");
}
fn header(
ui: &mut egui::Ui,
root: egui::Rect,
label: &str,
session: &PickerSession,
result: &mut ColorPickerResponse,
) {
let palette = crate::design_system::palette(ui);
text(
ui,
root.min + egui::vec2(12.0, 19.0),
egui::Align2::LEFT_CENTER,
label,
TypeRole::Section.font(),
palette.text_primary,
);
text(
ui,
root.min + egui::vec2(84.0, 19.0),
egui::Align2::LEFT_CENTER,
"sRGB · RGBA",
TypeRole::Small.font(),
palette.text_muted,
);
paint_swatch(
ui,
Geometry::at(root, 348.0, 7.0, 26.0, 24.0),
color32(session.current),
egui::Sense::hover(),
"Current color",
);
if icon_button(
ui,
Geometry::at(root, 384.0, 7.0, 24.0, 24.0),
icons::X,
"Cancel color changes",
true,
)
.clicked()
{
result.cancelled = true;
}
}
fn mode_tabs(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::design_system::palette(ui);
for (index, (mode, icon, label, width)) in [
(PickerMode::Wheel, icons::CIRCLE, "Wheel", 76.0),
(PickerMode::Sliders, icons::SLIDERS, "Sliders", 76.0),
(PickerMode::Presets, icons::SQUARES_FOUR, "Presets", 78.0),
]
.into_iter()
.enumerate()
{
let x = [12.0, 92.0, 172.0][index];
let rect = Geometry::at(root, x, 42.0, width, 26.0);
let selected = session.mode == mode;
let response = ui.put(
rect,
egui::Button::new(crate::design_system::controls::icon_label(
icon,
label,
TypeRole::Body,
12.0,
if selected {
palette.text_primary
} else {
palette.text_secondary
},
))
.fill(if selected {
palette.accent_dark
} else {
palette.control
})
.stroke(egui::Stroke::new(
1.0_f32,
if selected {
palette.accent
} else {
palette.border
},
))
.corner_radius(4.0),
);
if selected {
ui.painter().rect_filled(
egui::Rect::from_center_size(
egui::pos2(rect.center().x, rect.bottom() - 1.0),
egui::vec2(60.0, 2.0),
),
1.0,
palette.accent,
);
}
if response.clicked() {
session.mode = mode;
}
}
}
fn wheel_mode(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::design_system::palette(ui);
let ring = Geometry::at(root, 29.0, 88.0, 144.0, 144.0);
let sv = Geometry::at(root, 65.0, 124.0, 72.0, 72.0);
let editor = Geometry::rect(root, Geometry::WHEEL_EDITOR);
let response = ui.interact(
editor,
ui.make_persistent_id("penpot_color_wheel"),
egui::Sense::click_and_drag(),
);
let mut hsva = Hsva::from_rgba_unmultiplied(
session.current[0],
session.current[1],
session.current[2],
session.current[3],
);
paint_hue_wheel(ui.painter(), ring, hsva.h, palette.text_primary);
paint_sv(
ui.painter(),
sv,
hsva.h,
hsva.s,
hsva.v,
palette.text_primary,
);
if response.clicked() || response.dragged() {
if let Some(position) = response.interact_pointer_pos() {
let delta = position - ring.center();
if sv.contains(position) {
hsva.s = ((position.x - sv.left()) / sv.width()).clamp(0.0, 1.0);
hsva.v = (1.0 - (position.y - sv.top()) / sv.height()).clamp(0.0, 1.0);
} else if (52.0..=76.0).contains(&delta.length()) {
hsva.h = (delta.angle() / std::f32::consts::TAU + 0.25).rem_euclid(1.0);
}
let [r, g, b] = hsva.to_rgb();
set_current(session, [r, g, b, hsva.a]);
}
}
text(
ui,
root.min + egui::vec2(101.0, 252.0),
egui::Align2::CENTER_CENTER,
"Drag ring or field",
TypeRole::Small.font(),
palette.text_muted,
);
values(ui, root, session);
}
fn values(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::design_system::palette(ui);
let _values_bounds = Geometry::rect(root, Geometry::VALUES);
caption(ui, root, 198.0, 82.0, "CURRENT");
caption(ui, root, 302.0, 82.0, "PREVIOUS");
paint_swatch(
ui,
Geometry::at(root, 198.0, 96.0, 94.0, 30.0),
color32(session.current),
egui::Sense::hover(),
"Current live value",
);
paint_swatch(
ui,
Geometry::at(root, 302.0, 96.0, 94.0, 30.0),
color32(session.original),
egui::Sense::hover(),
"Value when the picker opened",
);
caption(ui, root, 198.0, 132.0, "HEX");
let hex_field = Geometry::at(root, 198.0, 144.0, 166.0, 24.0);
field_background(ui, hex_field);
let edit_rect = egui::Rect::from_min_max(
hex_field.min,
egui::pos2(hex_field.right() - 24.0, hex_field.bottom()),
);
let edit = ui.put(
edit_rect.shrink2(egui::vec2(5.0, 2.0)),
egui::TextEdit::singleline(&mut session.hex)
.font(TypeRole::Body.font())
.frame(egui::Frame::NONE),
);
if edit.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)) {
if let Some(value) = parse_hex(&session.hex) {
set_current(session, value);
}
}
if bare_icon(
ui,
egui::Rect::from_min_size(
egui::pos2(hex_field.right() - 24.0, hex_field.top()),
egui::vec2(24.0, 24.0),
),
icons::COPY,
"Copy HEX",
palette.text_secondary,
)
.clicked()
{
ui.ctx().copy_text(session.hex.clone());
}
let eyedropper = Geometry::at(root, 370.0, 144.0, 26.0, 24.0);
field_background(ui, eyedropper);
bare_icon(
ui,
eyedropper,
icons::EYEDROPPER,
PLANNED_EYEDROPPER,
palette.text_muted,
);
caption(ui, root, 198.0, 174.0, "RGBA");
let mut bytes = session.current.map(byte);
let before_bytes = bytes;
for (index, prefix) in ["R ", "G ", "B ", "A "].into_iter().enumerate() {
let rect = Geometry::at(root, 198.0 + index as f32 * 49.0, 186.0, 45.0, 24.0);
ui.put(
rect,
egui::DragValue::new(&mut bytes[index])
.range(0..=255)
.prefix(prefix),
);
}
if bytes != before_bytes {
set_current(session, bytes.map(|component| component as f32 / 255.0));
}
caption(ui, root, 198.0, 216.0, "HSV");
let mut hsva = Hsva::from_rgba_unmultiplied(
session.current[0],
session.current[1],
session.current[2],
session.current[3],
);
let mut hsv = [hsva.h * 360.0, hsva.s * 100.0, hsva.v * 100.0];
let before_hsv = hsv;
for (index, suffix) in ["°", "%", "%"].into_iter().enumerate() {
let rect = Geometry::at(root, 198.0 + index as f32 * 66.0, 228.0, 61.0, 24.0);
ui.put(
rect,
egui::DragValue::new(&mut hsv[index])
.range(if index == 0 { 0.0..=360.0 } else { 0.0..=100.0 })
.suffix(suffix)
.max_decimals(0),
);
}
if hsv != before_hsv {
hsva.h = hsv[0] / 360.0;
hsva.s = hsv[1] / 100.0;
hsva.v = hsv[2] / 100.0;
let [r, g, b] = hsva.to_rgb();
set_current(session, [r, g, b, hsva.a]);
}
caption(ui, root, 198.0, 258.0, "ALPHA");
alpha_control(ui, Geometry::at(root, 240.0, 256.0, 156.0, 14.0), session);
}
fn presets_mode(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::design_system::palette(ui);
let content = Geometry::rect(root, Geometry::CONTENT);
ui.painter().rect_filled(content, 4.0, palette.recessed);
caption(ui, root, 24.0, 86.0, "MATERIAL PALETTE");
for (index, color) in PRESETS.into_iter().enumerate() {
let column = index % 8;
let row = index / 8;
let rect = Geometry::at(
root,
24.0 + column as f32 * 47.0,
104.0 + row as f32 * 52.0,
34.0,
34.0,
);
if paint_swatch(ui, rect, color, egui::Sense::click(), "Use preset color").clicked() {
set_current(session, rgba(color));
}
}
}
fn recent_row(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::design_system::palette(ui);
let row = Geometry::rect(root, Geometry::RECENTS);
ui.painter().rect_filled(row, 4.0, palette.section);
text(
ui,
root.min + egui::vec2(20.0, 296.0),
egui::Align2::LEFT_CENTER,
"RECENT",
TypeRole::Caption.font(),
palette.text_muted,
);
for (index, color) in RECENTS.into_iter().enumerate() {
let rect = Geometry::at(root, 74.0 + index as f32 * 36.0, 286.0, 28.0, 20.0);
if paint_swatch(ui, rect, color, egui::Sense::click(), "Use recent color").clicked() {
set_current(session, rgba(color));
}
}
}
fn footer(ui: &mut egui::Ui, root: egui::Rect, result: &mut ColorPickerResponse) {
let palette = crate::design_system::palette(ui);
let footer = Geometry::rect(root, Geometry::FOOTER);
text(
ui,
footer.left_center(),
egui::Align2::LEFT_CENTER,
"Enter apply · Esc cancel",
TypeRole::Small.font(),
palette.text_muted,
);
if labeled_button(
ui,
Geometry::at(root, 254.0, 316.0, 72.0, 26.0),
icons::X,
"Cancel",
false,
)
.clicked()
{
result.cancelled = true;
}
if labeled_button(
ui,
Geometry::at(root, 334.0, 316.0, 74.0, 26.0),
icons::CHECK,
"Apply",
true,
)
.clicked()
{
result.applied = true;
}
}
fn alpha_control(ui: &mut egui::Ui, rect: egui::Rect, session: &mut PickerSession) {
let palette = crate::design_system::palette(ui);
checker(ui.painter(), rect, palette.control, palette.elevated);
let response = ui.interact(
rect.expand2(egui::vec2(0.0, 4.0)),
ui.make_persistent_id("penpot_color_alpha"),
egui::Sense::click_and_drag(),
);
if response.clicked() || response.dragged() {
if let Some(position) = response.interact_pointer_pos() {
let mut value = session.current;
value[3] = ((position.x - rect.left()) / rect.width()).clamp(0.0, 1.0);
set_current(session, value);
}
}
let x = egui::lerp(rect.left()..=rect.right(), session.current[3]);
ui.painter().rect_filled(
egui::Rect::from_min_max(rect.min, egui::pos2(x, rect.bottom())),
2.0,
palette.accent.gamma_multiply(0.65),
);
ui.painter().rect_filled(
egui::Rect::from_center_size(egui::pos2(x, rect.center().y), egui::vec2(10.0, 18.0)),
3.0,
palette.text_primary,
);
}
fn paint_hue_wheel(
painter: &egui::Painter,
rect: egui::Rect,
selected_hue: f32,
marker_color: egui::Color32,
) {
let center = rect.center();
let outer = 72.0;
let inner = 54.0;
let mut mesh = egui::Mesh::default();
const SEGMENTS: usize = 72;
for segment in 0..SEGMENTS {
let h0 = segment as f32 / SEGMENTS as f32;
let h1 = (segment + 1) as f32 / SEGMENTS as f32;
let a0 = (h0 - 0.25) * std::f32::consts::TAU;
let a1 = (h1 - 0.25) * std::f32::consts::TAU;
let start = mesh.vertices.len() as u32;
let c0 = egui::Color32::from(Hsva::new(h0, 1.0, 1.0, 1.0));
let c1 = egui::Color32::from(Hsva::new(h1, 1.0, 1.0, 1.0));
for (radius, angle, color) in [
(inner, a0, c0),
(outer, a0, c0),
(outer, a1, c1),
(inner, a1, c1),
] {
mesh.colored_vertex(
center + egui::vec2(angle.cos(), angle.sin()) * radius,
color,
);
}
mesh.add_triangle(start, start + 1, start + 2);
mesh.add_triangle(start, start + 2, start + 3);
}
painter.add(mesh);
let angle = (selected_hue - 0.25) * std::f32::consts::TAU;
let marker = center + egui::vec2(angle.cos(), angle.sin()) * 63.0;
painter.circle_stroke(marker, 5.0, egui::Stroke::new(2.0_f32, marker_color));
}
fn paint_sv(
painter: &egui::Painter,
rect: egui::Rect,
hue: f32,
saturation: f32,
value: f32,
marker_color: egui::Color32,
) {
let mut mesh = egui::Mesh::default();
for (position, color) in [
(rect.left_top(), egui::Color32::WHITE),
(
rect.right_top(),
egui::Color32::from(Hsva::new(hue, 1.0, 1.0, 1.0)),
),
(rect.right_bottom(), egui::Color32::BLACK),
(rect.left_bottom(), egui::Color32::BLACK),
] {
mesh.colored_vertex(position, color);
}
mesh.add_triangle(0, 1, 2);
mesh.add_triangle(0, 2, 3);
painter.add(mesh);
let marker = egui::pos2(
egui::lerp(rect.x_range(), saturation),
egui::lerp(rect.y_range(), 1.0 - value),
);
painter.circle_stroke(marker, 5.0, egui::Stroke::new(2.0_f32, marker_color));
}
pub(super) fn checker(
painter: &egui::Painter,
rect: egui::Rect,
dark: egui::Color32,
light: egui::Color32,
) {
let size = 6.0;
let columns = (rect.width() / size).ceil() as usize;
let rows = (rect.height() / size).ceil() as usize;
for row in 0..rows {
for column in 0..columns {
let cell = egui::Rect::from_min_size(
rect.min + egui::vec2(column as f32 * size, row as f32 * size),
egui::vec2(size, size),
)
.intersect(rect);
painter.rect_filled(
cell,
0.0,
if (row + column) % 2 == 0 { dark } else { light },
);
}
}
}
fn paint_swatch(
ui: &mut egui::Ui,
rect: egui::Rect,
color: egui::Color32,
sense: egui::Sense,
tooltip: &str,
) -> egui::Response {
let palette = crate::design_system::palette(ui);
checker(ui.painter(), rect, palette.control, palette.elevated);
ui.painter().rect_filled(rect.shrink(1.0), 3.0, color);
ui.painter().rect_stroke(
rect,
3.0,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
ui.interact(
rect,
ui.make_persistent_id(("color_swatch", rect.min.x.to_bits(), rect.min.y.to_bits())),
sense,
)
.on_hover_text(tooltip)
}
fn icon_button(
ui: &mut egui::Ui,
rect: egui::Rect,
icon: Icon,
tooltip: &str,
enabled: bool,
) -> egui::Response {
let palette = crate::design_system::palette(ui);
ui.put(
rect,
egui::Button::new(egui::RichText::new(icon.as_str()).font(egui::FontId::new(
13.0,
egui::FontFamily::Name("phosphor-regular".into()),
)))
.fill(palette.control)
.stroke(egui::Stroke::new(1.0_f32, palette.border))
.corner_radius(4.0)
.sense(if enabled {
egui::Sense::click()
} else {
egui::Sense::hover()
}),
)
.on_hover_text(tooltip)
}
fn bare_icon(
ui: &mut egui::Ui,
rect: egui::Rect,
icon: Icon,
tooltip: &str,
color: egui::Color32,
) -> egui::Response {
let response = ui.interact(
rect,
ui.make_persistent_id(("color_icon", tooltip)),
if tooltip == PLANNED_EYEDROPPER {
egui::Sense::hover()
} else {
egui::Sense::click()
},
);
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
color,
);
response.on_hover_text(tooltip)
}
fn labeled_button(
ui: &mut egui::Ui,
rect: egui::Rect,
icon: Icon,
label: &str,
accent: bool,
) -> egui::Response {
let palette = crate::design_system::palette(ui);
ui.push_id(("color_picker_footer_action", label), |ui| {
ui.put(
rect,
egui::Button::new(crate::design_system::controls::icon_label(
icon,
label,
TypeRole::Control,
12.0,
palette.text_primary,
))
.fill(if accent {
palette.accent
} else {
palette.control
})
.stroke(egui::Stroke::new(
1.0_f32,
if accent {
palette.accent
} else {
palette.border
},
))
.corner_radius(4.0),
)
})
.inner
}
fn field_background(ui: &egui::Ui, rect: egui::Rect) {
let palette = crate::design_system::palette(ui);
ui.painter().rect(
rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
}
fn caption(ui: &egui::Ui, root: egui::Rect, x: f32, y: f32, value: &str) {
let palette = crate::design_system::palette(ui);
text(
ui,
root.min + egui::vec2(x, y),
egui::Align2::LEFT_TOP,
value,
TypeRole::Caption.font(),
palette.text_muted,
);
}
fn text(
ui: &egui::Ui,
position: egui::Pos2,
align: egui::Align2,
value: &str,
font: egui::FontId,
color: egui::Color32,
) {
ui.painter().text(position, align, value, font, color);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exported_popup_regions_match_penpot_geometry() {
assert_eq!(POPUP_SIZE, egui::vec2(420.0, 350.0));
assert_eq!(Geometry::HEADER_HEIGHT, 38.0);
assert_eq!(Geometry::CONTENT.size(), egui::vec2(396.0, 202.0));
assert_eq!(Geometry::WHEEL_EDITOR.size(), egui::vec2(178.0, 202.0));
assert_eq!(Geometry::VALUES.size(), egui::vec2(198.0, 186.0));
assert_eq!(Geometry::RECENTS.size(), egui::vec2(396.0, 28.0));
assert_eq!(Geometry::FOOTER.size(), egui::vec2(396.0, 26.0));
}
#[test]
fn exported_value_and_action_fields_retain_exact_sizes() {
let root = egui::Rect::from_min_size(egui::Pos2::ZERO, POPUP_SIZE);
assert_eq!(
Geometry::at(root, 198.0, 144.0, 166.0, 24.0).size(),
egui::vec2(166.0, 24.0)
);
assert_eq!(
Geometry::at(root, 370.0, 144.0, 26.0, 24.0).size(),
egui::vec2(26.0, 24.0)
);
assert_eq!(
Geometry::at(root, 240.0, 256.0, 156.0, 14.0).size(),
egui::vec2(156.0, 14.0)
);
assert_eq!(
Geometry::at(root, 334.0, 316.0, 74.0, 26.0).size(),
egui::vec2(74.0, 26.0)
);
}
#[test]
fn disabled_eyedropper_has_no_state_or_action_contract() {
assert_eq!(PLANNED_EYEDROPPER, "Planned — screen sampling pending");
}
}
@@ -0,0 +1,167 @@
//! Fixed Penpot geometry for the color picker's RGBA and HSV channel modes.
use egui::{self, ecolor::Hsva};
use super::super::{byte, set_current, PickerSession};
use super::{caption, text, Geometry};
use crate::design_system::typography::TypeRole;
/// Each 186 px channel group owns a 178 px row: a single-letter channel label,
/// a 104 px track, and a 44 px value field.
struct SliderGeometry;
impl SliderGeometry {
const RGBA_X: f32 = 12.0;
const HSV_X: f32 = 206.0;
const TITLE_Y: f32 = 74.0;
const FIRST_ROW_Y: f32 = 90.0;
const ROW_STRIDE: f32 = 30.0;
const LABEL_WIDTH: f32 = 18.0;
const TRACK_X: f32 = 24.0;
const TRACK_WIDTH: f32 = 104.0;
const VALUE_X: f32 = 134.0;
const VALUE_WIDTH: f32 = 44.0;
const ROW_HEIGHT: f32 = 24.0;
}
pub(super) fn show(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
let palette = crate::design_system::palette(ui);
let content = Geometry::rect(root, Geometry::CONTENT);
ui.painter().rect_filled(content, 4.0, palette.recessed);
caption(
ui,
root,
SliderGeometry::RGBA_X,
SliderGeometry::TITLE_Y,
"RGBA CHANNELS",
);
caption(
ui,
root,
SliderGeometry::HSV_X,
SliderGeometry::TITLE_Y,
"HSV CHANNELS",
);
let mut bytes = session.current.map(|component| f32::from(byte(component)));
let before_bytes = bytes;
for (index, label) in ["R", "G", "B", "A"].into_iter().enumerate() {
slider_channel(
ui,
root,
SliderGeometry::RGBA_X,
index,
label,
&mut bytes[index],
0.0..=255.0,
"",
);
}
if bytes != before_bytes {
set_current(session, bytes.map(|component| component / 255.0));
}
let mut hsva = Hsva::from_rgba_unmultiplied(
session.current[0],
session.current[1],
session.current[2],
session.current[3],
);
let mut values = [
hsva.h * 360.0,
hsva.s * 100.0,
hsva.v * 100.0,
hsva.a * 100.0,
];
let before = values;
for (index, label) in ["H", "S", "V", "A"].into_iter().enumerate() {
let range = if index == 0 { 0.0..=360.0 } else { 0.0..=100.0 };
slider_channel(
ui,
root,
SliderGeometry::HSV_X,
index,
label,
&mut values[index],
range,
if index == 0 { "°" } else { "%" },
);
}
if values != before {
hsva.h = values[0] / 360.0;
hsva.s = values[1] / 100.0;
hsva.v = values[2] / 100.0;
hsva.a = values[3] / 100.0;
let [r, g, b] = hsva.to_rgb();
set_current(session, [r, g, b, hsva.a]);
}
}
#[allow(clippy::too_many_arguments)]
fn slider_channel(
ui: &mut egui::Ui,
root: egui::Rect,
group_x: f32,
index: usize,
label: &str,
value: &mut f32,
range: std::ops::RangeInclusive<f32>,
suffix: &str,
) {
let palette = crate::design_system::palette(ui);
let y = SliderGeometry::FIRST_ROW_Y + index as f32 * SliderGeometry::ROW_STRIDE;
let label_rect = Geometry::at(
root,
group_x,
y,
SliderGeometry::LABEL_WIDTH,
SliderGeometry::ROW_HEIGHT,
);
text(
ui,
label_rect.left_center(),
egui::Align2::LEFT_CENTER,
label,
TypeRole::Body.font(),
palette.text_secondary,
);
ui.put(
Geometry::at(
root,
group_x + SliderGeometry::TRACK_X,
y,
SliderGeometry::TRACK_WIDTH,
SliderGeometry::ROW_HEIGHT,
),
egui::Slider::new(value, range.clone()).show_value(false),
);
ui.put(
Geometry::at(
root,
group_x + SliderGeometry::VALUE_X,
y,
SliderGeometry::VALUE_WIDTH,
SliderGeometry::ROW_HEIGHT,
),
egui::DragValue::new(value)
.range(range)
.suffix(suffix)
.max_decimals(0),
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sliders_mode_matches_the_two_exported_channel_groups() {
assert_eq!(SliderGeometry::HSV_X - SliderGeometry::RGBA_X, 194.0);
assert_eq!(SliderGeometry::TRACK_WIDTH, 104.0);
assert_eq!(SliderGeometry::VALUE_WIDTH, 44.0);
assert_eq!(SliderGeometry::VALUE_X + SliderGeometry::VALUE_WIDTH, 178.0);
assert_eq!(SliderGeometry::ROW_STRIDE, 30.0);
assert_eq!(SliderGeometry::ROW_HEIGHT, 24.0);
}
}
@@ -0,0 +1,381 @@
//! Reusable Penpot-styled editor controls with no world or asset-store access.
use egui;
use egui_phosphor_icons::{icons, Icon};
use std::ops::RangeInclusive;
use super::palette;
use super::typography::TypeRole;
// Penpot's scalar component keeps a six-pixel leading inset inside its value-group frame. The
// exported child geometry is authoritative here; the group's transparent parent frame is six
// pixels narrower than its visible children and must not be mistaken for the control width.
const SCALAR_TRACK_X: f32 = 6.0;
const SCALAR_NUMBER_GAP: f32 = 6.0;
const SCALAR_TRACK_INTERACTION_HEIGHT: f32 = 10.0;
const SCALAR_NUMBER_WIDTH: f32 = 33.0;
const SCALAR_THUMB_RADIUS: f32 = 4.0;
pub fn section_frame(ui: &egui::Ui) -> egui::Frame {
let palette = palette(ui);
egui::Frame::new()
.fill(palette.section)
.stroke(egui::Stroke::new(1.0_f32, palette.border))
.corner_radius(egui::CornerRadius::same(5))
}
pub fn section_header(ui: &mut egui::Ui, title: &str, open: &mut bool) -> egui::Response {
section_header_with_summary(ui, title, None, open)
}
pub fn section_header_with_summary(
ui: &mut egui::Ui,
title: &str,
summary: Option<&str>,
open: &mut bool,
) -> egui::Response {
let palette = palette(ui);
let (rect, response) = ui.allocate_exact_size(
egui::vec2(
ui.available_width().max(1.0),
super::INPUT_SECTION_HEADER_HEIGHT,
),
egui::Sense::click(),
);
ui.painter().rect_filled(rect, 4.0, palette.elevated);
ui.painter().text(
rect.left_center() + egui::vec2(12.0, 0.0),
egui::Align2::CENTER_CENTER,
if *open {
icons::CARET_DOWN.as_str()
} else {
icons::CARET_RIGHT.as_str()
},
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.text_secondary,
);
ui.painter().text(
rect.left_center() + egui::vec2(26.0, 0.0),
egui::Align2::LEFT_CENTER,
title,
TypeRole::Section.font(),
palette.text_primary,
);
if let Some(summary) = summary {
ui.painter().text(
rect.right_center() - egui::vec2(12.0, 0.0),
egui::Align2::RIGHT_CENTER,
summary,
TypeRole::Small.font(),
palette.text_muted,
);
}
if response.clicked() {
*open = !*open;
}
response
}
/// Compose a Phosphor glyph and Source Sans label without asking either font to render the
/// other's codepoints. This is the canonical path for icon-plus-text controls in a design-system
/// scope.
pub fn icon_label(
icon: Icon,
label: &str,
role: TypeRole,
icon_size: f32,
color: egui::Color32,
) -> egui::WidgetText {
let mut job = egui::text::LayoutJob::default();
job.append(
icon.as_str(),
0.0,
egui::TextFormat {
font_id: egui::FontId::new(icon_size, egui::FontFamily::Name("phosphor-bold".into())),
color,
..Default::default()
},
);
if !label.is_empty() {
job.append(
label,
6.0,
egui::TextFormat {
font_id: role.font(),
color,
..Default::default()
},
);
}
job.into()
}
pub fn icon_button(ui: &mut egui::Ui, icon: Icon, tooltip: &str, enabled: bool) -> egui::Response {
let palette = palette(ui);
let response = ui.add_enabled(
enabled,
egui::Button::new(
egui::RichText::new(icon.as_str())
.font(egui::FontId::new(
14.0,
egui::FontFamily::Name("phosphor-bold".into()),
))
.color(palette.text_secondary),
)
.min_size(egui::vec2(24.0, 24.0))
.fill(palette.control)
.stroke(egui::Stroke::new(1.0_f32, palette.border))
.corner_radius(egui::CornerRadius::same(4)),
);
response.on_hover_text(tooltip)
}
pub fn status(ui: &mut egui::Ui, icon: Icon, color: egui::Color32, label: &str, tooltip: &str) {
let palette = palette(ui);
let mut job = egui::text::LayoutJob::default();
job.append(
icon.as_str(),
0.0,
egui::TextFormat {
font_id: egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-bold".into())),
color,
..Default::default()
},
);
job.append(
label,
5.0,
egui::TextFormat {
font_id: TypeRole::Small.font(),
color: palette.text_secondary,
..Default::default()
},
);
let response = ui.add(egui::Label::new(job).sense(egui::Sense::hover()));
response.on_hover_text(tooltip);
}
pub fn switch(ui: &mut egui::Ui, value: &mut bool) -> egui::Response {
let palette = palette(ui);
let (rect, mut response) = ui.allocate_exact_size(egui::vec2(31.0, 16.0), egui::Sense::click());
if response.clicked() {
*value = !*value;
response.mark_changed();
}
let fill = if *value {
palette.accent_dark
} else {
palette.control
};
let stroke = if *value {
palette.accent
} else {
palette.border_strong
};
ui.painter().rect(
rect,
8.0,
fill,
egui::Stroke::new(1.0_f32, stroke),
egui::StrokeKind::Inside,
);
let x = if *value {
rect.right() - 8.0
} else {
rect.left() + 8.0
};
ui.painter()
.circle_filled(egui::pos2(x, rect.center().y), 5.0, palette.text_primary);
response
}
/// Fixed 128×24 two-option control used by the Penpot material Surface section.
///
/// Returning the selected side keeps the control independent from material state and prevents
/// stock `selectable_label` padding from changing its geometry.
pub fn two_option_segmented(
ui: &mut egui::Ui,
left_label: &str,
right_label: &str,
right_selected: bool,
) -> Option<bool> {
const WIDTH: f32 = 128.0;
const HEIGHT: f32 = 24.0;
const OPTION_WIDTH: f32 = WIDTH * 0.5;
let palette = palette(ui);
let (rect, _) = ui.allocate_exact_size(egui::vec2(WIDTH, HEIGHT), egui::Sense::hover());
ui.painter().rect(
rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
let left = egui::Rect::from_min_size(rect.min, egui::vec2(OPTION_WIDTH, HEIGHT));
let right = egui::Rect::from_min_size(
rect.min + egui::vec2(OPTION_WIDTH, 0.0),
egui::vec2(OPTION_WIDTH, HEIGHT),
);
let mut selection = None;
for (option_rect, label, selected, value) in [
(left, left_label, !right_selected, false),
(right, right_label, right_selected, true),
] {
let response = ui.interact(
option_rect,
ui.make_persistent_id(("two_option_segment", label)),
egui::Sense::click(),
);
let fill = if selected {
palette.accent_dark
} else if response.hovered() {
palette.elevated
} else {
palette.control
};
ui.painter().rect_filled(option_rect.shrink(1.0), 3.0, fill);
if selected {
ui.painter().rect_stroke(
option_rect,
3.0,
egui::Stroke::new(1.0_f32, palette.accent),
egui::StrokeKind::Inside,
);
}
ui.painter().text(
option_rect.center(),
egui::Align2::CENTER_CENTER,
label,
TypeRole::Control.font(),
if selected {
palette.text_primary
} else {
palette.text_secondary
},
);
if response.clicked() && right_selected != value {
selection = Some(value);
}
}
selection
}
/// Exact Penpot scalar editor used by material inputs.
///
/// The track and numeric field are painted as independent controls so egui's stock slider
/// padding cannot move the thumb into the value field at the reference width.
pub fn scalar_control(
ui: &mut egui::Ui,
salt: impl std::hash::Hash,
value: &mut f32,
range: RangeInclusive<f32>,
max_decimals: usize,
) -> egui::Response {
let palette = palette(ui);
let before = *value;
// The final Penpot component deliberately stretches only the track at the compact
// breakpoint: 93.8 px at the 569 px reference and 160.3 px at the 369 px reference.
// The numeric field remains a stable 33 px in both modes, after a six-pixel leading inset
// and a six-pixel track-to-number gap.
let width = ui.available_width().max(1.0);
let (rect, base_response) =
ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::hover());
let number_width = SCALAR_NUMBER_WIDTH.min(width);
let number_x = (width - number_width).max(0.0);
let track_width = (number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP).max(1.0);
let slider_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(SCALAR_TRACK_X, 6.0),
egui::vec2(track_width, SCALAR_TRACK_INTERACTION_HEIGHT),
);
let track_rect =
egui::Rect::from_center_size(slider_rect.center(), egui::vec2(track_width, 3.0));
let slider_response = ui.interact(
slider_rect,
ui.make_persistent_id(("penpot_scalar", salt)),
egui::Sense::click_and_drag(),
);
if slider_response.clicked() || slider_response.dragged() {
if let Some(pointer) = slider_response.interact_pointer_pos() {
let start = *range.start();
let end = *range.end();
let normalized = ((pointer.x - track_rect.left()) / track_rect.width()).clamp(0.0, 1.0);
*value = egui::lerp(start..=end, normalized);
}
}
let start = *range.start();
let end = *range.end();
let normalized = if end > start {
((*value - start) / (end - start)).clamp(0.0, 1.0)
} else {
0.0
};
ui.painter().rect_filled(track_rect, 2.0, palette.border);
let fill = egui::Rect::from_min_max(
track_rect.left_top(),
egui::pos2(
egui::lerp(track_rect.x_range(), normalized),
track_rect.bottom(),
),
);
ui.painter().rect_filled(fill, 2.0, palette.accent);
let thumb_center = egui::pos2(
egui::lerp(track_rect.x_range(), normalized),
track_rect.center().y,
);
ui.painter().circle(
thumb_center,
SCALAR_THUMB_RADIUS,
palette.text_primary,
egui::Stroke::new(1.0_f32, palette.accent),
);
let number_rect = egui::Rect::from_min_size(
rect.min + egui::vec2(number_x, 0.0),
egui::vec2(number_width, 22.0),
);
let number_response = ui.put(
number_rect,
egui::DragValue::new(value)
.speed(0.01)
.range(range)
.max_decimals(max_decimals),
);
let mut response = base_response.union(slider_response).union(number_response);
if *value != before {
response.mark_changed();
}
response
}
#[cfg(test)]
mod scalar_tests {
use super::*;
#[test]
fn penpot_scalar_geometry_matches_the_current_export() {
let wide_width = 138.8;
let wide_number_x = wide_width - SCALAR_NUMBER_WIDTH;
let wide_track = wide_number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP;
assert!((wide_track - 93.8).abs() < 0.001);
let compact_width = 205.3;
let compact_number_x = compact_width - SCALAR_NUMBER_WIDTH;
let compact_track = compact_number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP;
assert!((compact_track - 160.3).abs() < 0.001);
assert_eq!(SCALAR_TRACK_INTERACTION_HEIGHT, 10.0);
assert_eq!(SCALAR_THUMB_RADIUS, 4.0);
}
}
#[cfg(test)]
mod segmented_tests {
#[test]
fn penpot_segmented_control_has_two_fixed_halves() {
const WIDTH: f32 = 128.0;
const OPTION_WIDTH: f32 = WIDTH * 0.5;
assert_eq!(OPTION_WIDTH, 64.0);
assert_eq!(OPTION_WIDTH * 2.0, WIDTH);
}
}
+153
View File
@@ -0,0 +1,153 @@
//! Penpot-led editor design-system primitives.
//!
//! The first consumer is the Material Slot panel. These semantic tokens and controls are kept
//! independent from material/world state so later editor panels can migrate without copying style.
pub mod color_picker;
pub mod controls;
pub mod property_grid;
pub mod typography;
use egui::{self, Color32, CornerRadius, Stroke};
use crate::theme::EditorVisualPalette;
pub const REFERENCE_WIDTH: f32 = 620.0;
pub const INSPECTOR_MIN_WIDTH: f32 = 420.0;
pub const OUTER_PADDING: f32 = 12.0;
pub const SECTION_GAP: f32 = 8.0;
pub const MATERIALS_HEADING_HEIGHT: f32 = 32.0;
pub const HEADER_HEIGHT: f32 = 82.0;
pub const COLLAPSED_HEADER_HEIGHT: f32 = 52.0;
pub const MATERIAL_PREVIEW_SIZE: f32 = 64.0;
pub const MATERIAL_IDENTITY_WIDTH: f32 = 229.5;
pub const SURFACE_SECTION_HEIGHT: f32 = 46.0;
pub const COMPACT_SURFACE_SECTION_HEIGHT: f32 = 46.0;
pub const INPUT_SECTION_HEADER_HEIGHT: f32 = 24.0;
pub const PARAMETER_ROW_HEIGHT: f32 = 32.0;
pub const COMPACT_PARAMETER_ROW_HEIGHT: f32 = 58.0;
pub const UV_SECTION_HEIGHT: f32 = 54.0;
pub const COMPACT_UV_SECTION_HEIGHT: f32 = 94.0;
pub const ADVANCED_COLLAPSED_HEIGHT: f32 = 30.0;
pub const ADVANCED_EXPANDED_HEIGHT: f32 = 178.0;
pub const CONTROL_HEIGHT: f32 = 24.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DesignPalette {
pub accent: Color32,
pub accent_dark: Color32,
pub panel: Color32,
pub section: Color32,
pub recessed: Color32,
pub control: Color32,
pub elevated: Color32,
pub row_even: Color32,
pub row_odd: Color32,
pub checker: Color32,
pub border: Color32,
pub border_strong: Color32,
pub text_primary: Color32,
pub text_secondary: Color32,
pub text_muted: Color32,
pub healthy: Color32,
pub warning: Color32,
pub error: Color32,
}
impl From<EditorVisualPalette> for DesignPalette {
fn from(value: EditorVisualPalette) -> Self {
Self {
accent: value.selection,
accent_dark: value.selection_bg,
panel: value.panel,
section: value.widget,
recessed: value.panel_dark,
control: value.widget,
elevated: value.elevated,
row_even: value.panel,
row_odd: value.widget,
checker: value.elevated,
border: value.border,
border_strong: value.border_strong,
text_primary: value.text,
text_secondary: value.text_dim,
text_muted: value.text_muted,
healthy: value.success,
warning: value.warning,
error: value.error,
}
}
}
pub fn palette(ui: &egui::Ui) -> DesignPalette {
crate::theme::editor_palette(ui.ctx()).into()
}
/// Applies the Penpot material-panel visual language locally without restyling the whole editor.
pub fn scope<R>(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
let palette = palette(ui);
ui.scope(|ui| {
let style = ui.style_mut();
style.spacing.item_spacing = egui::vec2(8.0, 4.0);
style.spacing.button_padding = egui::vec2(8.0, 3.0);
style.spacing.interact_size = egui::vec2(31.0, CONTROL_HEIGHT);
style.visuals.widgets.noninteractive.bg_fill = palette.section;
style.visuals.widgets.noninteractive.bg_stroke = Stroke::new(1.0_f32, palette.border);
style.visuals.widgets.noninteractive.fg_stroke =
Stroke::new(1.0_f32, palette.text_secondary);
style.visuals.widgets.inactive.bg_fill = palette.control;
style.visuals.widgets.inactive.weak_bg_fill = palette.control;
style.visuals.widgets.inactive.bg_stroke = Stroke::new(1.0_f32, palette.border);
style.visuals.widgets.inactive.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
style.visuals.widgets.hovered.bg_fill = palette.elevated;
style.visuals.widgets.hovered.weak_bg_fill = palette.elevated;
style.visuals.widgets.hovered.bg_stroke = Stroke::new(1.0_f32, palette.border_strong);
style.visuals.widgets.hovered.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
style.visuals.widgets.active.bg_fill = palette.accent_dark;
style.visuals.widgets.active.weak_bg_fill = palette.accent_dark;
style.visuals.widgets.active.bg_stroke = Stroke::new(1.0_f32, palette.accent);
style.visuals.widgets.active.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
style.visuals.selection.bg_fill = palette.accent_dark;
style.visuals.selection.stroke = Stroke::new(1.0_f32, palette.accent);
style.visuals.window_fill = palette.panel;
style.visuals.window_stroke = Stroke::new(1.0_f32, palette.border_strong);
style.visuals.window_corner_radius = CornerRadius::same(7);
style.visuals.menu_corner_radius = CornerRadius::same(5);
style.visuals.override_text_color = Some(palette.text_primary);
typography::install_local_text_styles(style);
add_contents(ui)
})
.inner
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_geometry_tokens_are_exact() {
assert_eq!(REFERENCE_WIDTH, 620.0);
assert_eq!(MATERIALS_HEADING_HEIGHT, 32.0);
assert_eq!(HEADER_HEIGHT, 82.0);
assert_eq!(COLLAPSED_HEADER_HEIGHT, 52.0);
assert_eq!(MATERIAL_PREVIEW_SIZE, 64.0);
assert_eq!(MATERIAL_IDENTITY_WIDTH, 229.5);
assert_eq!(SURFACE_SECTION_HEIGHT, 46.0);
assert_eq!(COMPACT_SURFACE_SECTION_HEIGHT, 46.0);
assert_eq!(INPUT_SECTION_HEADER_HEIGHT, 24.0);
assert_eq!(PARAMETER_ROW_HEIGHT, 32.0);
assert_eq!(COMPACT_PARAMETER_ROW_HEIGHT, 58.0);
assert_eq!(UV_SECTION_HEIGHT, 54.0);
assert_eq!(COMPACT_UV_SECTION_HEIGHT, 94.0);
assert_eq!(ADVANCED_COLLAPSED_HEIGHT, 30.0);
assert_eq!(ADVANCED_EXPANDED_HEIGHT, 178.0);
}
#[test]
fn material_design_palette_uses_blacksite_semantics() {
let palette = DesignPalette::from(crate::theme::BLACKSITE_PALETTE);
assert_eq!(palette.accent, crate::theme::SELECTION);
assert_eq!(palette.panel, crate::theme::PANEL_BG);
assert_eq!(palette.text_primary, crate::theme::TEXT);
}
}
@@ -0,0 +1,294 @@
//! Testable geometry for dense Penpot material property rows.
use super::{COMPACT_PARAMETER_ROW_HEIGHT, PARAMETER_ROW_HEIGHT};
use egui;
/// Minimum live section width that can safely retain the exported wide-row geometry.
///
/// The Penpot reference section itself is 569 px wide. In the native Inspector, dock chrome,
/// component-card borders, and the floating scrollbar consume up to ten pixels before the
/// material parameter body is allocated. Treat that 559 px contained canvas as wide so a 640 px
/// Inspector renders the authoritative wide reference instead of incorrectly switching to the
/// 420 px two-line rows.
pub const WIDE_SECTION_WIDTH: f32 = 559.0;
pub const RESPONSIVE_BREAKPOINT: f32 = WIDE_SECTION_WIDTH;
/// The actor component chrome can consume up to twelve pixels of the exported 372 px compact
/// canvas. At 360 px the complete texture row still fits: 12 px inset + 336 px group + 12 px inset.
const COMPACT_INLINE_ACTION_FIT_WIDTH: f32 = 357.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PropertyGridGeometry {
pub stacked: bool,
pub row_height: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PropertyRowRects {
pub row: egui::Rect,
pub label: egui::Rect,
pub value: egui::Rect,
pub color_value: egui::Rect,
pub channel: egui::Rect,
pub texture_group: egui::Rect,
pub texture_field: egui::Rect,
pub locate: egui::Rect,
pub clear: egui::Rect,
pub inline_texture_actions: bool,
}
impl PropertyGridGeometry {
pub fn for_width(section_width: f32) -> Self {
if section_width + f32::EPSILON >= RESPONSIVE_BREAKPOINT {
Self {
stacked: false,
row_height: PARAMETER_ROW_HEIGHT,
}
} else {
Self {
stacked: true,
row_height: COMPACT_PARAMETER_ROW_HEIGHT,
}
}
}
pub fn row_rects(self, row: egui::Rect) -> PropertyRowRects {
let inset = 12.0_f32.min(row.width() * 0.5);
let inner_width = (row.width() - inset * 2.0).max(1.0);
if !self.stacked {
let texture_group_width = (inner_width - 286.5).max(60.0);
let texture_field_width = (texture_group_width - 60.0).max(1.0);
let texture_group = egui::Rect::from_min_size(
row.min + egui::vec2(298.5, 5.0),
egui::vec2(texture_group_width, 22.0),
);
return PropertyRowRects {
row,
label: egui::Rect::from_min_size(
row.min + egui::vec2(12.0, 5.0),
egui::vec2(82.0, 22.0),
),
value: egui::Rect::from_min_size(
row.min + egui::vec2(103.35, 5.0),
egui::vec2(138.8, 22.0),
),
color_value: egui::Rect::from_min_size(
row.min + egui::vec2(107.95, 5.0),
egui::vec2(182.55, 22.0),
),
channel: egui::Rect::from_min_size(
row.min + egui::vec2(242.5, 5.0),
egui::vec2(48.0, 22.0),
),
texture_group,
texture_field: egui::Rect::from_min_size(
texture_group.min,
egui::vec2(texture_field_width, 22.0),
),
locate: egui::Rect::from_min_size(
texture_group.min + egui::vec2(texture_field_width + 6.0, 0.0),
egui::vec2(24.0, 22.0),
),
clear: egui::Rect::from_min_size(
texture_group.min + egui::vec2(texture_field_width + 36.0, 0.0),
egui::vec2(24.0, 22.0),
),
inline_texture_actions: true,
};
}
let channel_width = 48.0_f32.min(inner_width);
let channel_x = inset + inner_width - channel_width;
let value_x = (inset + 91.35).min(channel_x);
// The scalar's visible children finish 0.35 px before the channel. Penpot's transparent
// parent frame is six pixels narrower and is not the actual clipping boundary.
let value_width = (channel_x - value_x - 0.35).max(1.0);
let color_value_x = (inset + 95.95).min(channel_x);
let color_value_width = (inset + inner_width - color_value_x).max(1.0);
let texture_group = egui::Rect::from_min_size(
row.min + egui::vec2(inset, 31.0),
egui::vec2(inner_width, 22.0),
);
let inline_texture_actions = row.width() + f32::EPSILON >= COMPACT_INLINE_ACTION_FIT_WIDTH;
let texture_field_width = if inline_texture_actions {
(inner_width - 60.0).max(1.0)
} else {
(inner_width - 30.0).max(1.0)
};
let overflow_or_locate_x = texture_field_width + 6.0;
PropertyRowRects {
row,
label: egui::Rect::from_min_size(
row.min + egui::vec2(inset, 5.0),
egui::vec2(78.0_f32.min(inner_width), 22.0),
),
value: egui::Rect::from_min_size(
row.min + egui::vec2(value_x, 5.0),
egui::vec2(value_width, 22.0),
),
color_value: egui::Rect::from_min_size(
row.min + egui::vec2(color_value_x, 5.0),
egui::vec2(color_value_width, 22.0),
),
channel: egui::Rect::from_min_size(
row.min + egui::vec2(channel_x, 5.0),
egui::vec2(channel_width, 22.0),
),
texture_group,
texture_field: egui::Rect::from_min_size(
texture_group.min,
egui::vec2(texture_field_width, 22.0),
),
locate: egui::Rect::from_min_size(
texture_group.min + egui::vec2(overflow_or_locate_x, 0.0),
egui::vec2(24.0, 22.0),
),
clear: egui::Rect::from_min_size(
texture_group.min
+ egui::vec2(
if inline_texture_actions {
texture_field_width + 36.0
} else {
inner_width
},
0.0,
),
egui::vec2(if inline_texture_actions { 24.0 } else { 0.0 }, 22.0),
),
inline_texture_actions,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_exact_reference_geometry_matches_columns() {
let geometry = PropertyGridGeometry::for_width(569.0);
assert!(!geometry.stacked);
assert_eq!(geometry.row_height, 32.0);
}
#[test]
fn native_wide_containment_threshold_keeps_reference_rows() {
let geometry = PropertyGridGeometry::for_width(559.0);
assert!(!geometry.stacked);
assert_eq!(geometry.row_height, 32.0);
}
#[test]
fn below_native_wide_containment_threshold_reflows_without_compression() {
let geometry = PropertyGridGeometry::for_width(558.0);
assert!(geometry.stacked);
assert_eq!(geometry.row_height, 58.0);
}
#[test]
fn row_rects_match_exported_wide_geometry() {
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(569.0, 32.0));
let rects = PropertyGridGeometry::for_width(569.0).row_rects(row);
assert_eq!(rects.label.min, egui::pos2(12.0, 5.0));
assert_eq!(rects.value.min, egui::pos2(103.35, 5.0));
assert!((rects.value.width() - 138.8).abs() < 0.001);
assert_eq!(rects.value.height(), 22.0);
assert_eq!(rects.color_value.min, egui::pos2(107.95, 5.0));
assert!((rects.color_value.width() - 182.55).abs() < 0.001);
assert_eq!(
rects.channel,
egui::Rect::from_min_size(egui::pos2(242.5, 5.0), egui::vec2(48.0, 22.0))
);
assert_eq!(
rects.texture_group,
egui::Rect::from_min_size(egui::pos2(298.5, 5.0), egui::vec2(258.5, 22.0))
);
assert_eq!(rects.texture_field.size(), egui::vec2(198.5, 22.0));
assert_eq!(rects.locate.min, egui::pos2(503.0, 5.0));
assert_eq!(rects.clear.min, egui::pos2(533.0, 5.0));
assert!(rects.inline_texture_actions);
}
#[test]
fn row_rects_match_exported_compact_geometry() {
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(369.0, 58.0));
let rects = PropertyGridGeometry::for_width(369.0).row_rects(row);
assert_eq!(rects.label.min, egui::pos2(12.0, 5.0));
assert_eq!(rects.value.min, egui::pos2(103.35, 5.0));
assert!((rects.value.width() - 205.3).abs() < 0.001);
assert_eq!(rects.color_value.min, egui::pos2(107.95, 5.0));
assert!((rects.color_value.width() - 249.05).abs() < 0.001);
assert_eq!(
rects.channel,
egui::Rect::from_min_size(egui::pos2(309.0, 5.0), egui::vec2(48.0, 22.0))
);
assert_eq!(
rects.texture_group,
egui::Rect::from_min_size(egui::pos2(12.0, 31.0), egui::vec2(345.0, 22.0))
);
assert_eq!(rects.texture_field.size(), egui::vec2(285.0, 22.0));
assert_eq!(rects.locate.min, egui::pos2(303.0, 31.0));
assert_eq!(rects.clear.min, egui::pos2(333.0, 31.0));
assert!(rects.inline_texture_actions);
}
#[test]
fn transient_row_rects_are_finite_and_contained() {
for width in [356.0, 300.0, 240.0] {
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 58.0));
let rects = PropertyGridGeometry::for_width(width).row_rects(row);
for rect in [
rects.label,
rects.value,
rects.color_value,
rects.channel,
rects.texture_group,
rects.texture_field,
rects.locate,
rects.clear,
] {
assert!(rect.is_finite());
assert!(row.contains_rect(rect));
}
assert!(!rects.inline_texture_actions);
}
}
#[test]
fn inspector_chrome_reduced_floor_keeps_compact_texture_actions() {
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(363.0, 58.0));
let rects = PropertyGridGeometry::for_width(363.0).row_rects(row);
assert!(rects.inline_texture_actions);
assert_eq!(rects.texture_group.min, egui::pos2(12.0, 31.0));
assert_eq!(rects.texture_group.max, egui::pos2(351.0, 53.0));
assert!(row.contains_rect(rects.locate));
assert!(row.contains_rect(rects.clear));
}
#[test]
fn penpot_wide_growth_only_expands_texture_field() {
let reference_row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(569.0, 32.0));
let wide_row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(669.0, 32.0));
let reference = PropertyGridGeometry::for_width(569.0).row_rects(reference_row);
let wide = PropertyGridGeometry::for_width(669.0).row_rects(wide_row);
assert_eq!(wide.label, reference.label);
assert_eq!(wide.value, reference.value);
assert_eq!(wide.color_value, reference.color_value);
assert_eq!(wide.channel, reference.channel);
assert_eq!(
wide.texture_field.width(),
reference.texture_field.width() + 100.0
);
}
#[test]
fn penpot_very_narrow_first_line_never_exceeds_inner_width() {
let geometry = PropertyGridGeometry::for_width(300.0);
assert!(geometry.stacked);
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 58.0));
let rects = geometry.row_rects(row);
assert!(row.contains_rect(rects.label));
assert!(row.contains_rect(rects.value));
assert!(row.contains_rect(rects.channel));
assert_eq!(rects.texture_group.width(), 276.0);
}
}
@@ -0,0 +1,94 @@
//! Source Sans typography roles used by the Penpot-led editor visual system.
use egui::{self, FontFamily, FontId, RichText, Style, TextStyle};
use crate::fonts::{SOURCE_SANS_BOLD, SOURCE_SANS_REGULAR};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TypeRole {
Caption,
Eyebrow,
Small,
Body,
Control,
Section,
AssetLabel,
AssetTitle,
Title,
}
impl TypeRole {
pub const fn size(self) -> f32 {
match self {
Self::Caption | Self::Eyebrow => 9.0,
Self::Small => 10.0,
Self::Body => 11.0,
Self::Control | Self::AssetLabel => 10.0,
Self::Section => 11.0,
Self::AssetTitle => 13.0,
Self::Title => 14.0,
}
}
pub const fn bold(self) -> bool {
matches!(
self,
Self::Eyebrow | Self::Section | Self::AssetLabel | Self::AssetTitle | Self::Title
)
}
pub fn font(self) -> FontId {
let family = if self.bold() {
SOURCE_SANS_BOLD
} else {
SOURCE_SANS_REGULAR
};
FontId::new(self.size(), FontFamily::Name(family.into()))
}
pub fn text(self, value: impl Into<String>) -> RichText {
RichText::new(value).font(self.font())
}
}
pub fn install_local_text_styles(style: &mut Style) {
style
.text_styles
.insert(TextStyle::Body, TypeRole::Body.font());
style
.text_styles
.insert(TextStyle::Button, TypeRole::Control.font());
style
.text_styles
.insert(TextStyle::Small, TypeRole::Small.font());
style
.text_styles
.insert(TextStyle::Heading, TypeRole::Title.font());
style.text_styles.insert(
TextStyle::Monospace,
FontId::new(11.0, egui::FontFamily::Monospace),
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_type_scale_and_weights_are_stable() {
assert_eq!(TypeRole::Caption.size(), 9.0);
assert_eq!(TypeRole::Eyebrow.size(), 9.0);
assert_eq!(TypeRole::Small.size(), 10.0);
assert_eq!(TypeRole::Body.size(), 11.0);
assert_eq!(TypeRole::Control.size(), 10.0);
assert_eq!(TypeRole::Section.size(), 11.0);
assert_eq!(TypeRole::AssetLabel.size(), 10.0);
assert_eq!(TypeRole::AssetTitle.size(), 13.0);
assert_eq!(TypeRole::Title.size(), 14.0);
assert!(!TypeRole::Body.bold());
assert!(TypeRole::Eyebrow.bold());
assert!(TypeRole::Section.bold());
assert!(TypeRole::AssetLabel.bold());
assert!(TypeRole::AssetTitle.bold());
}
}
+54
View File
@@ -0,0 +1,54 @@
//! Source Sans Pro and Phosphor font registration for every Blacksite egui host.
use std::sync::Arc;
pub const SOURCE_SANS_REGULAR: &str = "blacksite-source-sans-regular";
pub const SOURCE_SANS_BOLD: &str = "blacksite-source-sans-bold";
pub fn font_definitions() -> egui::FontDefinitions {
let mut fonts = egui::FontDefinitions::default();
egui_phosphor_icons::add_fonts(&mut fonts);
fonts.font_data.insert(
SOURCE_SANS_REGULAR.to_owned(),
Arc::new(egui::FontData::from_static(include_bytes!(
"../assets/fonts/source-sans/SourceSansPro-Regular.ttf"
))),
);
fonts.font_data.insert(
SOURCE_SANS_BOLD.to_owned(),
Arc::new(egui::FontData::from_static(include_bytes!(
"../assets/fonts/source-sans/SourceSansPro-Bold.ttf"
))),
);
fonts
.families
.entry(egui::FontFamily::Proportional)
.or_default()
.insert(0, SOURCE_SANS_REGULAR.to_owned());
fonts.families.insert(
egui::FontFamily::Name(SOURCE_SANS_REGULAR.into()),
vec![SOURCE_SANS_REGULAR.to_owned()],
);
fonts.families.insert(
egui::FontFamily::Name(SOURCE_SANS_BOLD.into()),
vec![SOURCE_SANS_BOLD.to_owned(), SOURCE_SANS_REGULAR.to_owned()],
);
let fallbacks = fonts
.families
.get(&egui::FontFamily::Proportional)
.cloned()
.unwrap_or_default();
for (family, font_names) in &mut fonts.families {
let egui::FontFamily::Name(name) = family else {
continue;
};
if name.starts_with("phosphor-") {
for fallback in &fallbacks {
if !font_names.contains(fallback) {
font_names.push(fallback.clone());
}
}
}
}
fonts
}
+262
View File
@@ -0,0 +1,262 @@
//! Action-returning Inspector component-card chrome shared by production and gallery fixtures.
use egui;
use egui_phosphor_icons::{icons, Icon};
use crate::design_system;
use crate::design_system::typography::TypeRole;
use crate::theme::{BORDER, ERROR, SELECTION, SUCCESS, TEXT, TEXT_DIM, TEXT_MUTED, WIDGET_BG};
pub const COMPONENT_HEADER_HEIGHT: f32 = 50.0;
const COMPONENT_RAIL_X: f32 = 7.0;
const COMPONENT_CARET_CENTER_X: f32 = 26.0;
const COMPONENT_ICON_CENTER_X: f32 = 51.0;
const COMPONENT_IDENTITY_X: f32 = 69.0;
const COMPONENT_ACTIONS_WIDTH: f32 = 104.0;
#[derive(Debug, Clone, Copy)]
pub struct ComponentCardOptions {
pub type_name: &'static str,
pub title: &'static str,
pub icon: Icon,
pub active_toggle: bool,
pub removable: bool,
pub reorderable: bool,
pub resettable: bool,
pub copyable: bool,
pub summary: &'static str,
pub body_margin: i8,
}
impl ComponentCardOptions {
pub const fn removable(type_name: &'static str, title: &'static str, icon: Icon) -> Self {
Self {
type_name,
title,
icon,
active_toggle: true,
removable: true,
reorderable: true,
resettable: true,
copyable: true,
summary: "Authoring component",
body_margin: 12,
}
}
pub const fn fixed(type_name: &'static str, title: &'static str, icon: Icon) -> Self {
Self {
type_name,
title,
icon,
active_toggle: false,
removable: false,
reorderable: false,
resettable: true,
copyable: false,
summary: "Authoring component",
body_margin: 12,
}
}
}
#[derive(Debug, Clone)]
pub struct ComponentCardViewModel {
pub options: ComponentCardOptions,
pub active: bool,
pub collapsed: bool,
pub pasteable: bool,
pub can_move_up: bool,
pub can_move_down: bool,
}
#[derive(Debug, Clone, Default)]
pub struct ComponentCardAction {
pub type_name: &'static str,
pub collapsed: Option<bool>,
pub active: Option<bool>,
pub reset: bool,
pub copy: bool,
pub paste: bool,
pub move_up: bool,
pub move_down: bool,
pub remove: bool,
}
pub fn component_card(
ui: &mut egui::Ui,
view: &ComponentCardViewModel,
add_contents: impl FnOnce(&mut egui::Ui),
) -> ComponentCardAction {
let mut action = ComponentCardAction {
type_name: view.options.type_name,
..Default::default()
};
design_system::scope(ui, |ui| {
egui::Frame::new()
.fill(WIDGET_BG)
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.corner_radius(egui::CornerRadius::same(5))
.show(ui, |ui| {
let width = ui.available_width().max(1.0);
let (header, response) = ui.allocate_exact_size(
egui::vec2(width, COMPONENT_HEADER_HEIGHT),
egui::Sense::click(),
);
ui.painter().rect_filled(
egui::Rect::from_min_size(
header.min + egui::vec2(COMPONENT_RAIL_X, 7.0),
egui::vec2(3.0, 36.0),
),
2.0,
SELECTION,
);
let caret_rect = egui::Rect::from_center_size(
egui::pos2(header.left() + COMPONENT_CARET_CENTER_X, header.center().y),
egui::vec2(20.0, 28.0),
);
if ui
.put(
caret_rect,
egui::Button::new(icon_text(
if view.collapsed {
icons::CARET_RIGHT
} else {
icons::CARET_DOWN
},
12.0,
))
.frame(false),
)
.clicked()
{
action.collapsed = Some(!view.collapsed);
}
ui.painter().text(
egui::pos2(header.left() + COMPONENT_ICON_CENTER_X, header.center().y),
egui::Align2::CENTER_CENTER,
view.options.icon.as_str(),
egui::FontId::new(18.0, egui::FontFamily::Name("phosphor-bold".into())),
TEXT_DIM,
);
ui.painter().text(
egui::pos2(header.left() + COMPONENT_IDENTITY_X, header.top() + 18.0),
egui::Align2::LEFT_CENTER,
view.options.title,
TypeRole::Title.font(),
TEXT,
);
ui.painter().text(
egui::pos2(header.left() + COMPONENT_IDENTITY_X, header.top() + 34.0),
egui::Align2::LEFT_CENTER,
view.options.summary,
TypeRole::Small.font(),
TEXT_MUTED,
);
let actions_rect = egui::Rect::from_min_size(
egui::pos2(
header.right() - COMPONENT_ACTIONS_WIDTH - 8.0,
header.top() + 11.0,
),
egui::vec2(COMPONENT_ACTIONS_WIDTH, 28.0),
);
ui.scope_builder(egui::UiBuilder::new().max_rect(actions_rect), |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
actions_menu(ui, view, &mut action);
let color = if view.active { SUCCESS } else { TEXT_MUTED };
let status_rect = ui
.allocate_exact_size(egui::vec2(8.0, 14.0), egui::Sense::hover())
.0;
ui.painter().circle_filled(status_rect.center(), 4.0, color);
ui.label(
TypeRole::Small
.text(if view.active { "Active" } else { "Off" })
.color(TEXT_DIM),
);
});
});
if response.clicked()
&& ui
.input(|input| input.pointer.interact_pos())
.is_some_and(|point| {
!caret_rect.contains(point) && !actions_rect.contains(point)
})
{
action.collapsed = Some(!view.collapsed);
}
if !view.collapsed {
egui::Frame::new()
.inner_margin(egui::Margin {
left: view.options.body_margin,
right: view.options.body_margin,
top: 10,
bottom: view.options.body_margin,
})
.show(ui, add_contents);
}
});
});
ui.add_space(6.0);
action
}
fn actions_menu(
ui: &mut egui::Ui,
view: &ComponentCardViewModel,
action: &mut ComponentCardAction,
) {
ui.menu_button(
icon_text(icons::DOTS_THREE_VERTICAL, 16.0).color(TEXT_DIM),
|ui| {
ui.set_min_width(160.0);
action.reset |= action_button(ui, view.options.resettable, "Reset");
action.copy |= action_button(ui, view.options.copyable, "Copy Values");
action.paste |= action_button(ui, view.pasteable, "Paste Values");
ui.separator();
action.move_up |= action_button(ui, view.can_move_up, "Move Up");
action.move_down |= action_button(ui, view.can_move_down, "Move Down");
ui.separator();
ui.add_enabled(false, egui::Button::new("Open Documentation"));
if ui
.add_enabled(
view.options.removable,
egui::Button::new(egui::RichText::new("Remove").color(ERROR)),
)
.clicked()
{
action.remove = true;
ui.close();
}
},
);
}
fn action_button(ui: &mut egui::Ui, enabled: bool, label: &str) -> bool {
let clicked = ui.add_enabled(enabled, egui::Button::new(label)).clicked();
if clicked {
ui.close();
}
clicked
}
fn icon_text(icon: Icon, size: f32) -> egui::RichText {
egui::RichText::new(icon.as_str()).font(egui::FontId::new(
size,
egui::FontFamily::Name("phosphor-bold".into()),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_component_header_geometry_is_exact() {
assert_eq!(COMPONENT_HEADER_HEIGHT, 50.0);
assert_eq!(COMPONENT_RAIL_X, 7.0);
assert_eq!(COMPONENT_CARET_CENTER_X, 26.0);
assert_eq!(COMPONENT_ICON_CENTER_X, 51.0);
assert_eq!(COMPONENT_IDENTITY_X, 69.0);
assert_eq!(COMPONENT_ACTIONS_WIDTH, 104.0);
}
}
+12
View File
@@ -0,0 +1,12 @@
//! Production egui presentation shared by the Blacksite editor and lightweight UI gallery.
//!
//! This crate owns rendering, deterministic geometry, and action-returning view contracts. It does
//! not own a Bevy world, project state, authored-document publication, scene mutations, or content
//! processing.
pub mod design_system;
pub mod fonts;
pub mod inspector;
pub mod materials;
pub mod renderer;
pub mod theme;
@@ -0,0 +1,286 @@
//! Non-interactive Penpot v2.3.1 renderer-control preview.
use egui;
use egui_phosphor_icons::icons;
use crate::design_system::typography::TypeRole;
use crate::design_system::{self, ADVANCED_COLLAPSED_HEIGHT, ADVANCED_EXPANDED_HEIGHT};
const PLANNED_TOOLTIP: &str = "Planned — renderer support pending";
pub(super) fn unsupported_advanced_preview(ui: &mut egui::Ui) {
let open_id = ui.make_persistent_id("material_unsupported_advanced_open");
let reveal_id = open_id.with("reveal_complete_body");
let mut open = ui
.ctx()
.data_mut(|data| data.get_persisted::<bool>(open_id))
.unwrap_or(false);
let width = ui.available_width().max(1.0);
let mode = super::layout::ResponsiveMaterialLayout::for_width(width);
let height = if open {
if mode == super::layout::ResponsiveMaterialLayout::Transient {
254.0
} else {
ADVANCED_EXPANDED_HEIGHT
}
} else {
ADVANCED_COLLAPSED_HEIGHT
};
let palette = design_system::palette(ui);
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
ui.painter().rect(
rect,
5.0,
palette.panel,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
let header = egui::Rect::from_min_size(rect.min, egui::vec2(rect.width(), 30.0));
ui.painter().rect_filled(header, 4.0, palette.panel);
let header_response = ui.interact(header, open_id.with("header"), egui::Sense::click());
if header_response.clicked() {
open = !open;
ui.ctx().data_mut(|data| data.insert_temp(reveal_id, open));
}
header_response.on_hover_text(if open {
"Collapse Advanced preview"
} else {
"Expand Advanced preview"
});
ui.painter().text(
header.left_center() + egui::vec2(12.0, 0.0),
egui::Align2::LEFT_CENTER,
if open {
icons::CARET_DOWN.as_str()
} else {
icons::CARET_RIGHT.as_str()
},
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.text_secondary,
);
ui.painter().text(
header.left_center() + egui::vec2(26.0, 0.0),
egui::Align2::LEFT_CENTER,
"Advanced",
TypeRole::Section.font(),
palette.text_secondary,
);
if !open && rect.width() >= 300.0 {
ui.painter().hline(
(header.left() + 82.0)..=(header.right() - 158.0),
header.center().y,
egui::Stroke::new(1.0_f32, palette.border),
);
ui.painter().text(
header.right_center() - egui::vec2(12.0, 0.0),
egui::Align2::RIGHT_CENTER,
PLANNED_TOOLTIP,
TypeRole::Small.font(),
palette.text_muted,
);
}
if open {
match mode {
super::layout::ResponsiveMaterialLayout::Reference => reference_controls(ui, rect),
super::layout::ResponsiveMaterialLayout::Compact => {
compact_reference_controls(ui, rect)
}
super::layout::ResponsiveMaterialLayout::Transient => compact_controls(ui, rect),
}
}
let reveal_complete_body = ui
.ctx()
.data_mut(|data| data.get_temp::<bool>(reveal_id))
.unwrap_or(false);
if open && reveal_complete_body && rect.height() > ADVANCED_COLLAPSED_HEIGHT {
ui.scroll_to_rect(rect, Some(egui::Align::BOTTOM));
ui.ctx().data_mut(|data| data.remove::<bool>(reveal_id));
}
ui.ctx()
.data_mut(|data| data.insert_persisted(open_id, open));
}
fn reference_controls(ui: &mut egui::Ui, rect: egui::Rect) {
disabled_field(ui, rect, 28.0, 42.0, "Culling", "Back");
disabled_field(ui, rect, 28.0, 76.0, "Render Queue", "From Shader");
disabled_toggle(ui, rect, 328.0, 42.0, "Depth Write", true);
disabled_toggle(ui, rect, 328.0, 76.0, "Receive Shadows", true);
planned_note(ui, rect, 28.0, 124.0);
}
fn compact_reference_controls(ui: &mut egui::Ui, rect: egui::Rect) {
disabled_field_at(ui, rect, 20.0, 90.0, 90.0, 42.0, "Culling", "Back");
disabled_field_at(
ui,
rect,
20.0,
90.0,
90.0,
76.0,
"Render Queue",
"From Shader",
);
disabled_toggle_at(
ui,
rect,
196.0,
rect.width() - 38.0,
42.0,
"Depth Write",
true,
);
disabled_toggle_at(
ui,
rect,
196.0,
rect.width() - 38.0,
76.0,
"Receive Shadows",
true,
);
planned_note(ui, rect, 20.0, 124.0);
}
fn compact_controls(ui: &mut egui::Ui, rect: egui::Rect) {
disabled_field(ui, rect, 20.0, 42.0, "Culling", "Back");
disabled_field(ui, rect, 20.0, 78.0, "Render Queue", "From Shader");
disabled_toggle(ui, rect, 20.0, 124.0, "Depth Write", true);
disabled_toggle(ui, rect, 20.0, 160.0, "Receive Shadows", true);
planned_note(ui, rect, 20.0, 210.0);
}
fn disabled_field(ui: &mut egui::Ui, rect: egui::Rect, x: f32, y: f32, label: &str, value: &str) {
disabled_field_at(ui, rect, x, x + 106.0, 150.0, y, label, value);
}
#[expect(
clippy::too_many_arguments,
reason = "explicit Penpot preview geometry"
)]
fn disabled_field_at(
ui: &mut egui::Ui,
rect: egui::Rect,
label_x: f32,
field_x: f32,
field_width: f32,
y: f32,
label: &str,
value: &str,
) {
let palette = design_system::palette(ui);
ui.painter().text(
rect.min + egui::vec2(label_x, y),
egui::Align2::LEFT_CENTER,
label,
TypeRole::Body.font(),
palette.text_muted,
);
let field = egui::Rect::from_min_size(
egui::pos2(rect.left() + field_x, rect.top() + y - 7.0),
egui::vec2(field_width.min(rect.width() - field_x - 8.0).max(1.0), 24.0),
);
paint_disabled_field(ui, field, value);
}
fn disabled_toggle(
ui: &mut egui::Ui,
rect: egui::Rect,
x: f32,
y: f32,
label: &str,
enabled: bool,
) {
disabled_toggle_at(ui, rect, x, x + 106.0, y, label, enabled);
}
fn disabled_toggle_at(
ui: &mut egui::Ui,
rect: egui::Rect,
label_x: f32,
toggle_x: f32,
y: f32,
label: &str,
enabled: bool,
) {
let palette = design_system::palette(ui);
ui.painter().text(
rect.min + egui::vec2(label_x, y),
egui::Align2::LEFT_CENTER,
label,
TypeRole::Body.font(),
palette.text_muted,
);
let toggle = egui::Rect::from_min_size(
egui::pos2(rect.left() + toggle_x, rect.top() + y - 8.0),
egui::vec2(30.0, 16.0),
);
ui.painter().rect(
toggle,
8.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
let thumb_x = if enabled {
toggle.right() - 8.0
} else {
toggle.left() + 8.0
};
ui.painter().circle_filled(
egui::pos2(thumb_x, toggle.center().y),
5.0,
palette.text_muted,
);
ui.interact(
toggle,
ui.make_persistent_id(("advanced_toggle", label)),
egui::Sense::hover(),
)
.on_hover_text(PLANNED_TOOLTIP);
}
fn paint_disabled_field(ui: &mut egui::Ui, rect: egui::Rect, value: &str) {
let palette = design_system::palette(ui);
ui.painter().rect(
rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
ui.painter().text(
rect.left_center() + egui::vec2(10.0, 0.0),
egui::Align2::LEFT_CENTER,
value,
TypeRole::Body.font(),
palette.text_muted,
);
ui.interact(
rect,
ui.make_persistent_id(("advanced_field", value)),
egui::Sense::hover(),
)
.on_hover_text(PLANNED_TOOLTIP);
}
fn planned_note(ui: &egui::Ui, rect: egui::Rect, x: f32, y: f32) {
let palette = design_system::palette(ui);
ui.painter().text(
rect.min + egui::vec2(x, y),
egui::Align2::LEFT_CENTER,
PLANNED_TOOLTIP,
TypeRole::Small.font(),
palette.text_muted,
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_advanced_preview_matches_v231_heights() {
assert_eq!(ADVANCED_COLLAPSED_HEIGHT, 30.0);
assert_eq!(ADVANCED_EXPANDED_HEIGHT, 178.0);
}
}
+724
View File
@@ -0,0 +1,724 @@
use super::texture_inputs::{
ensure_material_texture_binding, material_property_texture_binding,
material_texture_channel_ui, texture_binding_ui, texture_channel_label,
upsert_material_texture_binding,
};
use super::uv_transform::{material_vec2_value, set_material_vec2_value, uv_transform_section};
use super::*;
use crate::design_system;
use crate::design_system::color_picker::{color_control, color_control_with_intensity};
use crate::design_system::controls::{
scalar_control, section_header, section_header_with_summary, switch,
};
use crate::design_system::property_grid::PropertyGridGeometry;
use crate::design_system::typography::TypeRole;
use material_schema::MaterialShaderKind;
pub fn material_input_schema_editor(
ui: &mut egui::Ui,
schema: &MaterialInputSchema,
inputs: &mut MaterialInputSet,
texture_assets: &[MaterialTextureCandidate],
drop_candidate: Option<&MaterialTextureCandidate>,
) -> MaterialInputEditorResponse {
material_input_schema_editor_with_inheritance(
ui,
schema,
inputs,
None,
texture_assets,
drop_candidate,
)
}
pub fn material_input_schema_editor_with_inheritance(
ui: &mut egui::Ui,
schema: &MaterialInputSchema,
inputs: &mut MaterialInputSet,
inherited: Option<&MaterialInputSet>,
texture_assets: &[MaterialTextureCandidate],
drop_candidate: Option<&MaterialTextureCandidate>,
) -> MaterialInputEditorResponse {
let mut response = MaterialInputEditorResponse::default();
let has_standard_packed_inputs = ["occlusion", "roughness", "metallic"]
.iter()
.all(|name| schema.inputs.iter().any(|input| input.name == *name));
let mut groups = schema.groups.clone();
if groups.is_empty() {
groups.push(material_schema::MaterialInputGroupDesc {
id: String::new(),
display_name: "Properties".into(),
order: 0,
advanced: false,
});
}
groups.sort_by_key(|group| group.order);
for group in groups {
let mut properties = schema
.inputs
.iter()
.filter(|property| {
property.group == group.id
&& matches!(
property.presentation,
material_schema::MaterialInputPresentation::Row
)
})
.collect::<Vec<_>>();
let companions = schema
.inputs
.iter()
.filter(|property| property.group == group.id)
.filter_map(|property| match &property.presentation {
material_schema::MaterialInputPresentation::Companion { owner } => {
Some((owner.as_str(), property))
}
material_schema::MaterialInputPresentation::Row => None,
})
.collect::<Vec<_>>();
properties.sort_by_key(|property| property.order);
if properties.is_empty() {
continue;
}
if group.id == "uv_transform" {
material_uv_transform_ui(ui, inputs, inherited);
// The design-system scope contributes four pixels between vertical items; add the
// remaining four to reach the authored eight-pixel section gap.
ui.add_space(4.0);
continue;
}
let open_id = ui.make_persistent_id(("material_input_group_open", &group.id));
let mut open = ui
.ctx()
.data_mut(|data| data.get_persisted::<bool>(open_id))
.unwrap_or(!group.advanced);
let context = MaterialInputGroupContext {
properties: &properties,
companions: &companions,
texture_assets,
drop_candidate,
};
let rows = material_input_group_ui(ui, context, &mut open, inputs, |ui, open| {
if group.id == "surface_inputs" {
let summary = format!("{} bindings", properties.len());
section_header_with_summary(ui, "Inputs", Some(&summary), open);
} else {
section_header(ui, &group.display_name, open);
}
});
response.accepted_drop |= rows.accepted_drop;
response.locate = response.locate.take().or(rows.locate);
response.browse_library |= rows.browse_library;
ui.ctx()
.data_mut(|data| data.insert_persisted(open_id, open));
ui.add_space(4.0);
}
if has_standard_packed_inputs {
super::advanced_preview::unsupported_advanced_preview(ui);
}
response
}
#[derive(Clone, Copy)]
struct MaterialInputGroupContext<'schema, 'view> {
properties: &'view [&'schema MaterialInputDesc],
companions: &'view [(&'schema str, &'schema MaterialInputDesc)],
texture_assets: &'view [MaterialTextureCandidate],
drop_candidate: Option<&'view MaterialTextureCandidate>,
}
fn material_input_group_ui(
ui: &mut egui::Ui,
context: MaterialInputGroupContext<'_, '_>,
open: &mut bool,
inputs: &mut MaterialInputSet,
header_ui: impl FnOnce(&mut egui::Ui, &mut bool),
) -> MaterialInputEditorResponse {
let width = ui.available_width().max(1.0);
let geometry = PropertyGridGeometry::for_width(width);
let body_open = *open;
let height = material_input_group_height(width, body_open, context.properties.len());
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
let palette = design_system::palette(ui);
ui.painter().rect(
rect,
5.0,
palette.section,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
// The parent owns the complete section rect. Child controls may manage local layout state,
// but they cannot alter where the next material section begins.
let mut section = ui.new_child(egui::UiBuilder::new().max_rect(rect));
section.set_clip_rect(rect.intersect(ui.clip_rect()));
let header_rect = egui::Rect::from_min_size(
rect.min,
egui::vec2(width, design_system::INPUT_SECTION_HEADER_HEIGHT),
);
let mut header = section.new_child(egui::UiBuilder::new().max_rect(header_rect));
header.set_clip_rect(header_rect.intersect(section.clip_rect()));
header_ui(&mut header, open);
if body_open {
let rows_rect =
egui::Rect::from_min_max(egui::pos2(rect.left(), header_rect.bottom()), rect.max);
material_input_rows(&mut section, rows_rect, geometry, context, inputs)
} else {
MaterialInputEditorResponse::default()
}
}
fn material_input_group_height(width: f32, open: bool, rows: usize) -> f32 {
let body = if open {
PropertyGridGeometry::for_width(width).row_height * rows as f32
} else {
0.0
};
design_system::INPUT_SECTION_HEADER_HEIGHT + body
}
fn material_uv_transform_ui(
ui: &mut egui::Ui,
inputs: &mut MaterialInputSet,
inherited: Option<&MaterialInputSet>,
) {
let mut offset = material_vec2_value(inputs, "uv_offset", Vec2::ZERO);
let mut tiling = material_vec2_value(inputs, "uv_tiling", Vec2::ONE);
let reset_offset = inherited.map_or(Vec2::ZERO, |inputs| {
material_vec2_value(inputs, "uv_offset", Vec2::ZERO)
});
let reset_tiling = inherited.map_or(Vec2::ONE, |inputs| {
material_vec2_value(inputs, "uv_tiling", Vec2::ONE)
});
let original = (offset, tiling);
uv_transform_section(ui, &mut offset, &mut tiling, reset_offset, reset_tiling);
if (offset, tiling) != original {
set_material_vec2_value(inputs, "uv_offset", offset);
set_material_vec2_value(inputs, "uv_tiling", tiling);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PackedMapMode {
Arm,
Separate,
}
pub fn packed_map_mode(inputs: &MaterialInputSet) -> PackedMapMode {
let channels = [
("occlusion", TextureChannel::R),
("roughness", TextureChannel::G),
("metallic", TextureChannel::B),
];
if channels.iter().all(|(name, channel)| {
inputs
.texture(name)
.is_some_and(|binding| binding.channel == *channel)
}) {
PackedMapMode::Arm
} else {
PackedMapMode::Separate
}
}
pub fn apply_arm_texture_preset(inputs: &mut MaterialInputSet) {
let shared_texture = ["occlusion", "roughness", "metallic"]
.iter()
.find_map(|name| {
inputs
.texture(name)
.and_then(|binding| binding.texture.clone())
});
for (name, channel) in [
("occlusion", TextureChannel::R),
("roughness", TextureChannel::G),
("metallic", TextureChannel::B),
] {
let binding = ensure_material_texture_binding(&mut inputs.textures, name);
binding.channel = channel;
if let Some(texture) = shared_texture.clone() {
binding.texture = Some(texture);
}
}
}
pub fn apply_separate_texture_preset(inputs: &mut MaterialInputSet) {
for name in ["occlusion", "roughness", "metallic"] {
ensure_material_texture_binding(&mut inputs.textures, name).channel = TextureChannel::R;
}
}
fn material_input_rows(
ui: &mut egui::Ui,
rows_rect: egui::Rect,
geometry: PropertyGridGeometry,
context: MaterialInputGroupContext<'_, '_>,
inputs: &mut MaterialInputSet,
) -> MaterialInputEditorResponse {
let palette = design_system::palette(ui);
let mut response = MaterialInputEditorResponse::default();
for (row, property) in context.properties.iter().enumerate() {
let companion = context
.companions
.iter()
.find_map(|(owner, companion)| (*owner == property.name).then_some(*companion));
ui.push_id(("material_input_row", &property.name), |ui| {
let row_rect = egui::Rect::from_min_size(
rows_rect.min + egui::vec2(0.0, row as f32 * geometry.row_height),
egui::vec2(rows_rect.width(), geometry.row_height),
);
ui.painter().rect_filled(
row_rect,
0.0,
if row.is_multiple_of(2) {
palette.row_even
} else {
palette.row_odd
},
);
let rects = geometry.row_rects(row_rect);
rect_ui(ui, rects.label, |ui| material_input_label(ui, property));
let is_color = matches!(property.property_type, ShaderPropertyType::Color);
rect_ui(
ui,
if is_color {
rects.color_value
} else {
rects.value
},
|ui| material_input_value_ui(ui, property, companion, inputs),
);
if !is_color {
rect_ui(ui, rects.channel, |ui| {
material_input_channel_ui(ui, property, inputs)
});
}
if material_input_uses_texture(property) {
let texture = rect_ui(ui, rects.texture_group, |ui| {
material_input_texture_ui(
ui,
property,
inputs,
context.texture_assets,
context.drop_candidate,
rects.inline_texture_actions,
)
});
response.accepted_drop |= texture.accepted_drop;
response.locate = response.locate.take().or(texture.locate);
response.browse_library |= texture.browse_library;
}
});
}
response
}
fn rect_ui<R>(
ui: &mut egui::Ui,
rect: egui::Rect,
add_contents: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
add_contents(ui)
})
.inner
}
pub(super) fn material_input_label(ui: &mut egui::Ui, property: &MaterialInputDesc) {
let palette = design_system::palette(ui);
ui.add(
egui::Label::new(
TypeRole::Body
.text(&property.display_name)
.color(palette.text_secondary),
)
.truncate(),
)
.on_hover_text(&property.tooltip);
}
pub(super) fn material_input_uses_texture(property: &MaterialInputDesc) -> bool {
property.texture.is_some() || matches!(property.property_type, ShaderPropertyType::Texture)
}
pub(super) fn material_input_value_ui(
ui: &mut egui::Ui,
property: &MaterialInputDesc,
companion: Option<&MaterialInputDesc>,
inputs: &mut MaterialInputSet,
) {
let MaterialInputSet { values, .. } = inputs;
ui.horizontal(|ui| {
if matches!(property.property_type, ShaderPropertyType::Texture) {
ui.label(egui::RichText::new("Texture").small().color(TEXT_DIM));
} else {
let default = property
.default_value
.clone()
.unwrap_or_else(|| default_value_for_shader_property(&property.property_type));
let mut value = values
.iter()
.find(|value| value.name == property.name)
.map(|parameter| parameter.value.clone())
.unwrap_or(default);
if !parameter_value_matches_property(&value, &property.property_type) {
value = default_value_for_shader_property(&property.property_type);
}
let original = value.clone();
if matches!(property.property_type, ShaderPropertyType::Color)
&& companion.is_some_and(|input| input.name == "emissive_intensity")
{
let companion = companion.expect("checked companion");
let companion_default = companion
.default_value
.clone()
.unwrap_or(MaterialParameterValue::Float(0.0));
let mut companion_value = values
.iter()
.find(|value| value.name == companion.name)
.map(|parameter| parameter.value.clone())
.unwrap_or(companion_default);
if !parameter_value_matches_property(&companion_value, &companion.property_type) {
companion_value = default_value_for_shader_property(&companion.property_type);
}
let original_companion = companion_value.clone();
if let (
MaterialParameterValue::Color(color),
MaterialParameterValue::Float(intensity),
) = (&mut value, &mut companion_value)
{
let mut rgba = [color.r, color.g, color.b, color.a];
let picker = color_control_with_intensity(
ui,
"material_emissive_color",
&property.display_name,
&mut rgba,
intensity,
);
if picker.changed {
*color = ColorDesc {
r: rgba[0],
g: rgba[1],
b: rgba[2],
a: rgba[3],
};
}
}
if value != original {
upsert_material_parameter(values, &property.name, value);
}
if companion_value != original_companion {
upsert_material_parameter(values, &companion.name, companion_value);
}
} else {
material_parameter_control_ui(
ui,
&property.display_name,
&property.property_type,
&mut value,
);
if value != original {
upsert_material_parameter(values, &property.name, value);
}
}
}
});
}
fn upsert_material_parameter(
values: &mut Vec<MaterialParameter>,
name: &str,
value: MaterialParameterValue,
) {
if let Some(parameter) = values.iter_mut().find(|parameter| parameter.name == name) {
parameter.value = value;
} else {
values.push(MaterialParameter {
name: name.to_string(),
value,
});
}
}
fn material_input_channel_ui(
ui: &mut egui::Ui,
property: &MaterialInputDesc,
inputs: &mut MaterialInputSet,
) {
let palette = design_system::palette(ui);
if property
.texture
.as_ref()
.is_some_and(|texture| texture.allow_channel_override)
{
let original = material_property_texture_binding(&inputs.textures, property);
let mut binding = original.clone();
material_texture_channel_ui(ui, property, &mut binding);
if binding != original {
upsert_material_texture_binding(&mut inputs.textures, binding);
}
} else {
let channel = property.texture.as_ref().map(|texture| {
if matches!(texture.semantic, material_schema::TextureSemantic::Color) {
"RGB"
} else {
texture_channel_label(texture.default_channel)
}
});
if let Some(channel) = channel {
readonly_channel(ui, channel);
} else {
ui.label(TypeRole::Body.text("—").color(palette.text_muted));
}
}
}
pub(super) fn material_input_texture_ui(
ui: &mut egui::Ui,
property: &MaterialInputDesc,
inputs: &mut MaterialInputSet,
texture_assets: &[MaterialTextureCandidate],
drop_candidate: Option<&MaterialTextureCandidate>,
inline_actions: bool,
) -> TextureSlotResponse {
if !material_input_uses_texture(property) {
return TextureSlotResponse::default();
}
let original = material_property_texture_binding(&inputs.textures, property);
let mut binding = original.clone();
let response = texture_binding_ui(
ui,
&mut binding,
texture_assets,
drop_candidate,
inline_actions,
);
if binding != original {
upsert_material_texture_binding(&mut inputs.textures, binding);
}
response
}
pub(super) fn material_parameter_control_ui(
ui: &mut egui::Ui,
label: &str,
property_type: &ShaderPropertyType,
value: &mut MaterialParameterValue,
) {
if !parameter_value_matches_property(value, property_type) {
*value = default_value_for_shader_property(property_type);
}
match value {
MaterialParameterValue::Bool(value) => {
switch(ui, value);
}
MaterialParameterValue::Float(value) => {
let (min, max) = match property_type {
ShaderPropertyType::Float { min, max } => (*min, *max),
_ => (None, None),
};
match (min, max) {
(Some(min), Some(max)) => {
scalar_control(ui, label, value, min..=max, usize::from(max <= 1_000.0) * 2);
}
_ => {
ui.add(egui::DragValue::new(value).speed(0.01));
}
}
}
MaterialParameterValue::Vec2(value) => {
ui.add(egui::DragValue::new(&mut value.x).speed(0.01).prefix("X "));
ui.add(egui::DragValue::new(&mut value.y).speed(0.01).prefix("Y "));
}
MaterialParameterValue::Vec3(value) => {
ui.add(egui::DragValue::new(&mut value.x).speed(0.01).prefix("X "));
ui.add(egui::DragValue::new(&mut value.y).speed(0.01).prefix("Y "));
ui.add(egui::DragValue::new(&mut value.z).speed(0.01).prefix("Z "));
}
MaterialParameterValue::Color(value) => {
let mut rgba = [value.r, value.g, value.b, value.a];
let response = color_control(ui, "material_color", label, &mut rgba);
if response.changed {
*value = ColorDesc {
r: rgba[0],
g: rgba[1],
b: rgba[2],
a: rgba[3],
};
}
}
MaterialParameterValue::Enum(value) => {
let options = match property_type {
ShaderPropertyType::Enum { options } => options.as_slice(),
_ => &[],
};
egui::ComboBox::from_id_salt(("material_enum", value.as_str()))
.selected_text(value.as_str())
.show_ui(ui, |ui| {
for option in options {
ui.selectable_value(value, option.clone(), option);
}
});
}
}
}
fn readonly_channel(ui: &mut egui::Ui, channel: &str) {
let palette = design_system::palette(ui);
let (rect, response) = ui.allocate_exact_size(egui::vec2(48.0, 22.0), egui::Sense::hover());
ui.painter().rect(
rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
ui.painter().text(
rect.left_center() + egui::vec2(9.0, 0.0),
egui::Align2::LEFT_CENTER,
channel,
TypeRole::Body.font(),
palette.text_secondary,
);
ui.painter().text(
rect.right_center() - egui::vec2(8.0, 0.0),
egui::Align2::CENTER_CENTER,
egui_phosphor_icons::icons::CARET_DOWN.as_str(),
egui::FontId::new(9.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.text_muted,
);
response.on_hover_text("Channel is fixed by this material input");
}
pub fn default_value_for_shader_property(
property_type: &ShaderPropertyType,
) -> MaterialParameterValue {
match property_type {
ShaderPropertyType::Bool => MaterialParameterValue::Bool(false),
ShaderPropertyType::Float { .. } => MaterialParameterValue::Float(0.0),
ShaderPropertyType::Vec2 => MaterialParameterValue::Vec2(Vec2::ZERO),
ShaderPropertyType::Vec3 => MaterialParameterValue::Vec3(Vec3::ZERO),
ShaderPropertyType::Color => MaterialParameterValue::Color(ColorDesc::default()),
ShaderPropertyType::Enum { options } => {
MaterialParameterValue::Enum(options.first().cloned().unwrap_or_default())
}
ShaderPropertyType::Texture => MaterialParameterValue::Float(0.0),
}
}
pub fn parameter_value_matches_property(
value: &MaterialParameterValue,
property_type: &ShaderPropertyType,
) -> bool {
matches!(
(value, property_type),
(MaterialParameterValue::Bool(_), ShaderPropertyType::Bool)
| (
MaterialParameterValue::Float(_),
ShaderPropertyType::Float { .. }
)
| (MaterialParameterValue::Vec2(_), ShaderPropertyType::Vec2)
| (MaterialParameterValue::Vec3(_), ShaderPropertyType::Vec3)
| (MaterialParameterValue::Color(_), ShaderPropertyType::Color)
| (
MaterialParameterValue::Enum(_),
ShaderPropertyType::Enum { .. }
)
)
}
pub fn compact_text_edit(ui: &mut egui::Ui, label: &str, value: &mut String) {
ui.horizontal(|ui| {
ui.add_sized([92.0, 20.0], egui::Label::new(label));
ui.add_sized(
[fit_width(ui, 100.0, f32::INFINITY), 22.0],
egui::TextEdit::singleline(value),
);
});
}
pub fn shader_kind_picker(ui: &mut egui::Ui, kind: &mut MaterialShaderKind) {
ui.horizontal(|ui| {
ui.add_sized([92.0, 20.0], egui::Label::new("Shader"));
shader_kind_combo(ui, kind, "asset_material_shader_kind");
});
}
pub fn shader_kind_combo(
ui: &mut egui::Ui,
kind: &mut MaterialShaderKind,
salt: impl std::hash::Hash,
) {
egui::ComboBox::from_id_salt(salt)
.selected_text(match kind {
MaterialShaderKind::StandardLit => "Standard Lit",
MaterialShaderKind::Unlit => "Unlit",
MaterialShaderKind::Custom => "Custom Surface",
})
.width(150.0_f32.min(ui.available_width().max(1.0)))
.show_ui(ui, |ui| {
ui.selectable_value(kind, MaterialShaderKind::StandardLit, "Standard Lit");
ui.selectable_value(kind, MaterialShaderKind::Unlit, "Unlit");
ui.selectable_value(kind, MaterialShaderKind::Custom, "Custom Surface");
});
}
pub fn optional_path_edit(ui: &mut egui::Ui, label: &str, value: &mut Option<String>) {
ui.horizontal(|ui| {
ui.add_sized([92.0, 20.0], egui::Label::new(label));
let mut text = value.clone().unwrap_or_default();
if ui
.add_sized(
[fit_width(ui, 80.0, f32::INFINITY), 22.0],
egui::TextEdit::singleline(&mut text),
)
.changed()
{
*value = if text.trim().is_empty() {
None
} else {
Some(text)
};
}
if ui.button("Clear").clicked() {
*value = None;
}
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn input_group_parent_owns_exact_reference_and_compact_heights() {
assert_eq!(material_input_group_height(569.0, true, 6), 216.0);
assert_eq!(material_input_group_height(369.0, true, 6), 372.0);
assert_eq!(material_input_group_height(569.0, false, 6), 24.0);
}
#[test]
fn rendering_missing_standard_defaults_does_not_author_or_dirty_inputs() {
let context = egui::Context::default();
context.set_fonts(crate::fonts::font_definitions());
let mut inputs = MaterialInputSet::default();
let original = inputs.clone();
let schema = material_schema::standard_lit_input_schema();
let _ = context.run_ui(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(700.0, 900.0),
)),
..Default::default()
},
|ui| {
material_input_schema_editor(ui, &schema, &mut inputs, &[], None);
},
);
assert_eq!(inputs, original);
}
}
+344
View File
@@ -0,0 +1,344 @@
//! Numeric Penpot v2.3.1 material-panel geometry shared by rendering and tests.
use egui;
use crate::design_system::{
ADVANCED_COLLAPSED_HEIGHT, ADVANCED_EXPANDED_HEIGHT, COLLAPSED_HEADER_HEIGHT, HEADER_HEIGHT,
INPUT_SECTION_HEADER_HEIGHT, MATERIAL_IDENTITY_WIDTH, MATERIAL_PREVIEW_SIZE, OUTER_PADDING,
PARAMETER_ROW_HEIGHT, SECTION_GAP, SURFACE_SECTION_HEIGHT, UV_SECTION_HEIGHT,
};
/// Smallest canvas that can still contain the exported compact Surface controls.
///
/// The Penpot board owns a 372 px parameter section. In the actor Inspector, component-card
/// chrome can temporarily reduce that canvas by a few pixels even while the Inspector itself is
/// at its supported 420 px floor. The fixed compact controls only require 362 px, so keep the
/// intended two-line layout until that real containment limit and reserve `Transient` for actual
/// sub-minimum docking frames.
pub(super) const COMPACT_SECTION_WIDTH: f32 = 357.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ResponsiveMaterialLayout {
Reference,
Compact,
Transient,
}
impl ResponsiveMaterialLayout {
pub(super) fn for_width(width: f32) -> Self {
if width + f32::EPSILON >= crate::design_system::property_grid::WIDE_SECTION_WIDTH {
Self::Reference
} else if width + f32::EPSILON >= COMPACT_SECTION_WIDTH {
Self::Compact
} else {
Self::Transient
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct SurfaceSectionGeometry {
pub height: f32,
pub title: egui::Rect,
pub blend: egui::Rect,
pub packed: egui::Rect,
pub double_sided: egui::Rect,
}
impl SurfaceSectionGeometry {
pub(super) fn for_rect(rect: egui::Rect) -> Self {
let local = |x: f32, y: f32, width: f32, height: f32| {
let x = x.clamp(0.0, rect.width());
let y = y.clamp(0.0, rect.height());
egui::Rect::from_min_size(
rect.min + egui::vec2(x, y),
egui::vec2(
width.max(0.0).min(rect.width() - x),
height.max(0.0).min(rect.height() - y),
),
)
};
match ResponsiveMaterialLayout::for_width(rect.width()) {
ResponsiveMaterialLayout::Reference => Self {
height: SURFACE_SECTION_HEIGHT,
title: local(10.0, 10.0, 48.0, 26.0),
blend: local(66.0, 10.0, 250.0, 26.0),
packed: local(324.0, 11.0, 128.0, 24.0),
double_sided: local(460.0, 12.0, 99.0, 22.0),
},
ResponsiveMaterialLayout::Compact => Self {
height: crate::design_system::COMPACT_SURFACE_SECTION_HEIGHT,
title: local(10.0, 10.0, 48.0, 26.0),
blend: local(66.0, 10.0, 50.0, 26.0),
packed: local(124.0, 11.0, 128.0, 24.0),
double_sided: local(260.0, 12.0, 99.0, 22.0),
},
ResponsiveMaterialLayout::Transient => Self {
height: 100.0,
title: local(10.0, 10.0, 48.0, 26.0),
blend: local(66.0, 10.0, (rect.width() - 76.0).clamp(1.0, 250.0), 26.0),
packed: local(10.0, 42.0, (rect.width() - 20.0).clamp(0.0, 128.0), 24.0),
double_sided: local(146.0, 43.0, (rect.width() - 156.0).clamp(0.0, 99.0), 22.0),
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct UvGroupGeometry {
pub label: egui::Rect,
pub x: egui::Rect,
pub y: egui::Rect,
pub reset: Option<egui::Rect>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct UvSectionGeometry {
pub height: f32,
pub title: egui::Rect,
pub offset: UvGroupGeometry,
pub tiling: UvGroupGeometry,
}
impl UvSectionGeometry {
pub(super) fn for_rect(rect: egui::Rect) -> Self {
let mode = ResponsiveMaterialLayout::for_width(rect.width());
let title = egui::Rect::from_min_size(
rect.min + egui::vec2(12.0, 7.0),
egui::vec2(20.0_f32.min(rect.width()), 14.0_f32.min(rect.height())),
);
if mode == ResponsiveMaterialLayout::Transient {
let group_width = (rect.width() - 20.0).max(1.0);
return Self {
height: 100.0,
title,
offset: uv_group(rect.min + egui::vec2(42.0, 7.0), group_width),
tiling: uv_group(rect.min + egui::vec2(42.0, 47.0), group_width),
};
}
if mode == ResponsiveMaterialLayout::Reference {
Self {
height: UV_SECTION_HEIGHT,
title,
offset: uv_group(rect.min + egui::vec2(104.667, 7.0), 165.0),
tiling: uv_group(rect.min + egui::vec2(332.333, 7.0), 164.0),
}
} else {
Self {
height: crate::design_system::COMPACT_UV_SECTION_HEIGHT,
title,
offset: uv_group(rect.min + egui::vec2(118.0, 7.0), 165.0),
tiling: uv_group(rect.min + egui::vec2(118.5, 47.0), 164.0),
}
}
}
}
fn uv_group(origin: egui::Pos2, group_width: f32) -> UvGroupGeometry {
let local = |x: f32, y: f32, control_width: f32, height: f32| {
let x = x.clamp(0.0, group_width.max(0.0));
egui::Rect::from_min_size(
origin + egui::vec2(x, y),
egui::vec2(control_width.max(0.0).min(group_width - x), height),
)
};
let reset = (group_width >= 164.0).then(|| local(group_width - 24.0, 8.0, 24.0, 24.0));
UvGroupGeometry {
label: local(0.0, 10.0, 25.0, 20.0),
x: local(30.0, 8.0, 50.0, 24.0),
y: local(86.0, 8.0, 50.0, 24.0),
reset,
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct MaterialPanelGeometry {
pub header: f32,
pub collapsed_header: f32,
pub asset_zone: f32,
pub surface: f32,
pub input_header: f32,
pub input_row: f32,
pub uv: f32,
pub advanced_collapsed: f32,
pub advanced_expanded: f32,
pub preview: f32,
pub identity: f32,
pub outer_padding: f32,
pub section_gap: f32,
}
impl MaterialPanelGeometry {
pub(super) const REFERENCE: Self = Self {
header: HEADER_HEIGHT,
collapsed_header: COLLAPSED_HEADER_HEIGHT,
asset_zone: HEADER_HEIGHT,
surface: SURFACE_SECTION_HEIGHT,
input_header: INPUT_SECTION_HEADER_HEIGHT,
input_row: PARAMETER_ROW_HEIGHT,
uv: UV_SECTION_HEIGHT,
advanced_collapsed: ADVANCED_COLLAPSED_HEIGHT,
advanced_expanded: ADVANCED_EXPANDED_HEIGHT,
preview: MATERIAL_PREVIEW_SIZE,
identity: MATERIAL_IDENTITY_WIDTH,
outer_padding: OUTER_PADDING,
section_gap: SECTION_GAP,
};
#[cfg(test)]
pub(super) const fn slot_width(inspector_width: f32) -> f32 {
inspector_width - OUTER_PADDING * 2.0
}
#[cfg(test)]
pub(super) const fn parameter_width(slot_width: f32) -> f32 {
slot_width - 27.0
}
#[cfg(test)]
pub(super) const fn inputs_height(compact: bool, primary_rows: usize) -> f32 {
INPUT_SECTION_HEADER_HEIGHT
+ primary_rows as f32
* if compact {
crate::design_system::COMPACT_PARAMETER_ROW_HEIGHT
} else {
PARAMETER_ROW_HEIGHT
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn final_penpot_reference_geometry_is_exact() {
let geometry = MaterialPanelGeometry::REFERENCE;
assert_eq!(geometry.header, 82.0);
assert_eq!(geometry.collapsed_header, 52.0);
assert_eq!(geometry.asset_zone, 82.0);
assert_eq!(geometry.surface, 46.0);
assert_eq!(geometry.input_header, 24.0);
assert_eq!(geometry.input_row, 32.0);
assert_eq!(geometry.uv, 54.0);
assert_eq!(geometry.advanced_collapsed, 30.0);
assert_eq!(geometry.advanced_expanded, 178.0);
assert_eq!(geometry.preview, 64.0);
assert_eq!(geometry.identity, 229.5);
assert_eq!(620.0 - OUTER_PADDING * 2.0, 596.0);
assert_eq!(420.0 - OUTER_PADDING * 2.0, 396.0);
assert_eq!(MaterialPanelGeometry::slot_width(620.0), 596.0);
assert_eq!(MaterialPanelGeometry::slot_width(420.0), 396.0);
assert_eq!(MaterialPanelGeometry::parameter_width(596.0), 569.0);
assert_eq!(MaterialPanelGeometry::parameter_width(396.0), 369.0);
assert_eq!(MaterialPanelGeometry::inputs_height(false, 6), 216.0);
assert_eq!(MaterialPanelGeometry::inputs_height(true, 6), 372.0);
}
#[test]
fn surface_geometry_matches_both_exported_references() {
let wide = SurfaceSectionGeometry::for_rect(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(569.0, 46.0),
));
assert_eq!(
wide.title,
egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(48.0, 26.0))
);
assert_eq!(
wide.blend,
egui::Rect::from_min_size(egui::pos2(66.0, 10.0), egui::vec2(250.0, 26.0))
);
assert_eq!(
wide.packed,
egui::Rect::from_min_size(egui::pos2(324.0, 11.0), egui::vec2(128.0, 24.0))
);
assert_eq!(
wide.double_sided,
egui::Rect::from_min_size(egui::pos2(460.0, 12.0), egui::vec2(99.0, 22.0))
);
let narrow = SurfaceSectionGeometry::for_rect(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(369.0, 46.0),
));
assert_eq!(
narrow.blend,
egui::Rect::from_min_size(egui::pos2(66.0, 10.0), egui::vec2(50.0, 26.0))
);
assert_eq!(
narrow.packed,
egui::Rect::from_min_size(egui::pos2(124.0, 11.0), egui::vec2(128.0, 24.0))
);
assert_eq!(
narrow.double_sided,
egui::Rect::from_min_size(egui::pos2(260.0, 12.0), egui::vec2(99.0, 22.0))
);
}
#[test]
fn uv_geometry_centers_title_and_keeps_independent_resets() {
for (width, height) in [(569.0, 54.0), (369.0, 94.0)] {
let section = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height));
let geometry = UvSectionGeometry::for_rect(section);
assert_eq!(geometry.title.min, egui::pos2(12.0, 7.0));
assert_eq!(geometry.title.height(), 14.0);
assert_eq!(geometry.offset.x.size(), egui::vec2(50.0, 24.0));
assert_eq!(geometry.offset.y.size(), egui::vec2(50.0, 24.0));
assert!(geometry.offset.reset.is_some());
assert!(geometry.tiling.reset.is_some());
for rect in [
geometry.title,
geometry.offset.label,
geometry.offset.x,
geometry.offset.y,
geometry.offset.reset.expect("reference reset"),
geometry.tiling.label,
geometry.tiling.x,
geometry.tiling.y,
geometry.tiling.reset.expect("reference reset"),
] {
assert!(section.contains_rect(rect));
assert!(rect.is_finite());
}
}
}
#[test]
fn transient_geometry_stays_finite_and_bounded() {
let section = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 100.0));
let surface = SurfaceSectionGeometry::for_rect(section);
let uv = UvSectionGeometry::for_rect(section);
for rect in [
surface.title,
surface.blend,
surface.packed,
surface.double_sided,
] {
assert!(rect.is_finite());
assert!(section.contains_rect(rect));
}
for rect in [
uv.title,
uv.offset.label,
uv.offset.x,
uv.offset.y,
uv.tiling.label,
uv.tiling.x,
uv.tiling.y,
] {
assert!(rect.is_finite());
assert!(section.contains_rect(rect));
}
}
#[test]
fn inspector_chrome_reduced_floor_keeps_the_penpot_compact_surface() {
let section = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(363.0, 46.0));
let surface = SurfaceSectionGeometry::for_rect(section);
assert_eq!(surface.height, 46.0);
assert_eq!(surface.packed.min, egui::pos2(124.0, 11.0));
assert_eq!(surface.packed.max, egui::pos2(252.0, 35.0));
assert_eq!(surface.double_sided.min, egui::pos2(260.0, 12.0));
}
}
+96
View File
@@ -0,0 +1,96 @@
//! Material-slot and schema-driven parameter widgets shared by production and the gallery.
use bevy_math::{Vec2, Vec3};
use egui;
use egui_phosphor_icons::Icon;
use material_schema::{
ColorDesc, EditorAssetRef, MaterialInputDesc, MaterialInputSchema, MaterialInputSet,
MaterialParameter, MaterialParameterValue, MaterialTextureBinding, ShaderPropertyType,
TextureChannel,
};
use crate::theme::TEXT_DIM;
mod advanced_preview;
mod inputs;
mod layout;
mod panel;
mod pickers;
mod surface;
mod texture_inputs;
mod uv_transform;
pub use inputs::{
apply_arm_texture_preset, apply_separate_texture_preset, compact_text_edit,
default_value_for_shader_property, material_input_schema_editor,
material_input_schema_editor_with_inheritance, optional_path_edit, packed_map_mode,
parameter_value_matches_property, shader_kind_combo, shader_kind_picker, PackedMapMode,
};
pub use panel::{
material_slot_panel, materials_section, MaterialHealth, MaterialLayerBadge,
MaterialPickerCandidate, MaterialSlotAction, MaterialSlotPanelAction,
MaterialSlotPanelResponse, MaterialSlotPanelViewModel, MaterialsSectionViewModel,
};
pub use surface::material_surface_options_ui;
pub use texture_inputs::ensure_material_texture_binding;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MaterialLocateTarget {
File(String),
SubAsset {
parent_path: String,
sub_asset_id: String,
label: String,
source_path: Option<String>,
},
}
#[derive(Clone, Debug)]
pub struct MaterialTextureCandidate {
pub label: String,
pub detail: String,
pub reference: EditorAssetRef,
pub locate: MaterialLocateTarget,
pub thumbnail: MaterialThumbnailPresentation,
}
#[derive(Default)]
pub struct MaterialInputEditorResponse {
pub accepted_drop: bool,
pub locate: Option<MaterialLocateTarget>,
pub browse_library: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MaterialThumbnailPresentation {
Ready(egui::TextureId),
Pending,
Failed,
Empty,
}
#[derive(Clone, Copy)]
enum TextureSlotSelection<'a> {
Reference(Option<&'a EditorAssetRef>),
}
#[derive(Default)]
struct TextureSlotResponse {
selected: Option<MaterialTextureCandidate>,
locate: Option<MaterialLocateTarget>,
clear: bool,
accepted_drop: bool,
browse_library: bool,
}
fn fit_width(ui: &egui::Ui, min: f32, max: f32) -> f32 {
let available = ui.available_width().max(1.0);
available.min(max).max(min.min(available))
}
fn icon_text(icon: Icon, size: f32) -> egui::RichText {
egui::RichText::new(icon.as_str()).font(egui::FontId::new(
size,
egui::FontFamily::Name("phosphor-bold".into()),
))
}
+773
View File
@@ -0,0 +1,773 @@
//! Action-returning Penpot material-slot shell shared by primitive and mesh inspectors.
use egui;
use egui_phosphor_icons::icons;
use material_schema::{EditorAssetRef, MaterialShaderKind};
use super::layout::MaterialPanelGeometry;
use super::MaterialThumbnailPresentation;
use crate::design_system::controls::status;
use crate::design_system::typography::TypeRole;
use crate::design_system::{self, DesignPalette, HEADER_HEIGHT};
mod header_actions;
use header_actions::{expanded_status_actions, overflow_menu, SLOT_STATUS_ACTION_WIDTH};
// `Frame` reserves one pixel for the slot stroke before handing its child Ui to us. These local
// origins compensate for that inset so the painted rail/caret/preview retain the exported board
// coordinates relative to the outer slot rectangle.
const SLOT_ACCENT_X: f32 = 7.0;
const SLOT_CARET_CENTER_X: f32 = 22.0;
const SLOT_PREVIEW_X: f32 = 34.0;
const SHADER_CONTROL_WIDTH: f32 = 220.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MaterialLayerBadge {
ModelSource,
ModelDefault,
ProjectDefault,
DefaultGrid,
}
impl MaterialLayerBadge {
pub const fn label(self) -> &'static str {
match self {
Self::ModelSource => "Model Source",
Self::ModelDefault => "Model Default",
Self::ProjectDefault => "Project Default",
Self::DefaultGrid => "Default Grid",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MaterialHealth {
Healthy,
Dirty,
Processing,
Broken,
ReadOnly,
}
impl MaterialHealth {
fn presentation(self, palette: DesignPalette) -> (egui::Color32, &'static str, &'static str) {
match self {
Self::Healthy => (
palette.text_secondary,
"Compiled",
"Material is resolved and up to date",
),
Self::Dirty => (
palette.warning,
"Unsaved",
"Material has unsaved in-memory changes",
),
Self::Processing => (
palette.accent,
"Processing",
"Derived material data is processing",
),
Self::Broken => (
palette.error,
"Failed",
"Material reference or processing failed",
),
Self::ReadOnly => (
palette.text_muted,
"Read only",
"This material cannot be edited in place",
),
}
}
fn icon(self) -> egui_phosphor_icons::Icon {
match self {
Self::Healthy => icons::CHECK_CIRCLE,
Self::Dirty => icons::PENCIL_SIMPLE,
Self::Processing => icons::CIRCLE_NOTCH,
Self::Broken => icons::WARNING_CIRCLE,
Self::ReadOnly => icons::LOCK_SIMPLE,
}
}
}
#[derive(Debug, Clone)]
pub struct MaterialPickerCandidate {
pub reference: EditorAssetRef,
pub label: String,
pub detail: String,
pub thumbnail: MaterialThumbnailPresentation,
}
#[derive(Debug, Clone)]
pub struct MaterialSlotPanelViewModel {
pub slot_id: String,
pub label: String,
pub path: Option<String>,
pub shader: String,
pub shader_kind: Option<MaterialShaderKind>,
pub can_edit_shader: bool,
pub thumbnail: MaterialThumbnailPresentation,
pub inherited: Option<MaterialLayerBadge>,
pub health: MaterialHealth,
pub assigned: Option<EditorAssetRef>,
pub effective: Option<EditorAssetRef>,
pub candidates: Vec<MaterialPickerCandidate>,
pub drop_candidate: Option<MaterialPickerCandidate>,
pub invalid_drop_reason: Option<String>,
pub can_locate: bool,
pub can_clear: bool,
pub can_extract: bool,
pub can_create_instance: bool,
/// Initial disclosure used only until this slot has persisted UI state.
pub parameters_initially_open: bool,
/// Renderer arrays keep the full asset/action header visible when only parameters collapse.
pub expanded_header_when_parameters_closed: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum MaterialSlotAction {
Assign {
reference: EditorAssetRef,
from_drop: bool,
},
BrowseLibrary,
Locate,
Clear,
ExtractEditable,
CreateInstance,
SetShader(MaterialShaderKind),
}
#[derive(Debug, Clone, PartialEq)]
pub struct MaterialSlotPanelAction {
pub slot_id: String,
pub action: MaterialSlotAction,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MaterialsSectionViewModel {
pub slot_ids: Vec<String>,
}
pub struct MaterialSlotPanelResponse {
pub actions: Vec<MaterialSlotPanelAction>,
}
pub fn materials_section<R>(
ui: &mut egui::Ui,
_view: &MaterialsSectionViewModel,
add_slots: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
let start = ui.next_widget_position();
let expanded = actor_materials_rect(ui.max_rect(), start.y);
let mut child = ui.new_child(
egui::UiBuilder::new()
.max_rect(expanded)
.layout(egui::Layout::top_down(egui::Align::Min)),
);
child.set_clip_rect(ui.clip_rect());
let result = design_system::scope(&mut child, |ui| {
let palette = design_system::palette(ui);
ui.allocate_ui_with_layout(
egui::vec2(
ui.available_width().max(1.0),
design_system::MATERIALS_HEADING_HEIGHT,
),
egui::Layout::left_to_right(egui::Align::Center),
|ui| {
ui.label(
TypeRole::Title
.text("Materials")
.color(palette.text_primary),
);
},
);
// The top-down layout already contributes the design system's four-pixel item gap after
// the 32 px heading. Add only the remaining four pixels so the slot begins at the Penpot
// board's authored eight-pixel offset instead of drifting four pixels lower.
ui.add_space(4.0);
add_slots(ui)
});
// `min_rect` is not a safe content-height signal for a child hosted by a ScrollArea: nested
// frames may temporarily inherit the parent's virtual extent even though their layout cursor
// has only advanced through finite authored rows. Advancing from that rect creates a phantom
// tail after multi-slot renderers and lets the Inspector scrollbar enter an empty region.
// The cursor is the authoritative end of this top-down section.
let used_bottom = materials_used_bottom(child.next_widget_position().y, start.y);
ui.advance_cursor_after_rect(egui::Rect::from_min_max(
egui::pos2(ui.max_rect().left(), start.y),
egui::pos2(ui.max_rect().right(), used_bottom),
));
result
}
fn actor_materials_rect(body: egui::Rect, start_y: f32) -> egui::Rect {
// A ScrollArea content Ui has an effectively unbounded max-rect in its scrolling direction.
// Carrying that bottom edge into the child gives the Materials section a phantom multi-screen
// height even though its painted contents are finite. Seed only the exported width here; egui
// grows the zero-height child as headings and slots are actually allocated.
egui::Rect::from_min_size(
egui::pos2(body.left(), start_y),
egui::vec2(body.width(), 0.0),
)
}
fn materials_used_bottom(cursor_y: f32, start_y: f32) -> f32 {
if cursor_y.is_finite() {
cursor_y.max(start_y)
} else {
start_y
}
}
pub fn material_slot_panel(
ui: &mut egui::Ui,
id: impl std::hash::Hash,
view: &MaterialSlotPanelViewModel,
content_ui: impl FnOnce(&mut egui::Ui),
diagnostics_ui: impl FnOnce(&mut egui::Ui),
) -> MaterialSlotPanelResponse {
design_system::scope(ui, |ui| {
let palette = design_system::palette(ui);
let id = ui.make_persistent_id(id);
let open_id = id.with("parameters_open");
let mut parameters_open = ui
.ctx()
.data_mut(|data| data.get_persisted::<bool>(open_id))
.unwrap_or(view.parameters_initially_open);
let mut slot_actions = Vec::new();
egui::Frame::new()
.fill(palette.recessed)
.stroke(egui::Stroke::new(1.0_f32, palette.border_strong))
.corner_radius(egui::CornerRadius::same(8))
.show(ui, |ui| {
slot_header(
ui,
id,
view,
&mut parameters_open,
&mut slot_actions,
diagnostics_ui,
);
if parameters_open {
parameter_body(ui, content_ui);
}
ui.ctx()
.data_mut(|data| data.insert_persisted(open_id, parameters_open));
});
MaterialSlotPanelResponse {
actions: slot_actions
.into_iter()
.map(|action| MaterialSlotPanelAction {
slot_id: view.slot_id.clone(),
action,
})
.collect(),
}
})
}
fn slot_header(
ui: &mut egui::Ui,
id: egui::Id,
view: &MaterialSlotPanelViewModel,
open: &mut bool,
actions: &mut Vec<MaterialSlotAction>,
diagnostics_ui: impl FnOnce(&mut egui::Ui),
) {
let palette = design_system::palette(ui);
let expanded_header = *open || view.expanded_header_when_parameters_closed;
let height = if expanded_header {
HEADER_HEIGHT
} else {
MaterialPanelGeometry::REFERENCE.collapsed_header
};
let width = ui.available_width().max(1.0);
let (rect, response) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::click());
ui.painter().rect_filled(rect, 7.0, palette.recessed);
ui.painter().rect_filled(
egui::Rect::from_min_size(
rect.min + egui::vec2(SLOT_ACCENT_X, 8.0),
egui::vec2(3.0, height - 16.0),
),
2.0,
palette.accent,
);
let caret_rect = egui::Rect::from_center_size(
egui::pos2(rect.left() + SLOT_CARET_CENTER_X, rect.center().y),
egui::vec2(18.0, 28.0),
);
let caret_icon = if *open {
icons::CARET_DOWN
} else {
icons::CARET_RIGHT
};
let caret = ui.put(
caret_rect,
egui::Button::new(
egui::RichText::new(caret_icon.as_str()).font(egui::FontId::new(
12.0,
egui::FontFamily::Name("phosphor-bold".into()),
)),
)
.frame(false),
);
if caret.clicked() {
*open = !*open;
}
let preview_size = if expanded_header { 64.0 } else { 32.0 };
let preview_rect = egui::Rect::from_min_size(
egui::pos2(
rect.left() + SLOT_PREVIEW_X,
rect.center().y - preview_size * 0.5,
),
egui::vec2(preview_size, preview_size),
);
let preview = material_thumbnail_at(ui, view, preview_rect);
let action_width = SLOT_STATUS_ACTION_WIDTH;
let identity_left = preview_rect.right() + 6.0;
let actions_left = rect.right() - action_width - 8.0;
let identity_right = (identity_left + design_system::MATERIAL_IDENTITY_WIDTH)
.min(actions_left)
.max(identity_left + 1.0);
let identity_rect = egui::Rect::from_min_max(
egui::pos2(
identity_left,
rect.top() + if expanded_header { 8.0 } else { 7.0 },
),
egui::pos2(
identity_right,
rect.bottom() - if expanded_header { 8.0 } else { 7.0 },
),
);
let identity = ui
.scope_builder(egui::UiBuilder::new().max_rect(identity_rect), |ui| {
ui.set_clip_rect(identity_rect.intersect(ui.clip_rect()));
if expanded_header {
material_identity(ui, view, actions)
} else {
compact_material_identity(ui, view)
}
})
.inner;
let actions_rect = egui::Rect::from_min_size(
egui::pos2(
actions_left,
rect.top() + if expanded_header { 9.0 } else { 7.0 },
),
egui::vec2(
action_width,
if expanded_header { 64.0 } else { height - 14.0 },
),
);
if expanded_header {
expanded_status_actions(ui, actions_rect, view, actions, diagnostics_ui, palette);
} else {
ui.scope_builder(egui::UiBuilder::new().max_rect(actions_rect), |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
overflow_menu(ui, view, actions, diagnostics_ui);
let (color, label, tooltip) = view.health.presentation(palette);
ui.horizontal(|ui| status(ui, view.health.icon(), color, label, tooltip));
});
});
}
if response.clicked() {
if let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) {
if !caret_rect.contains(pointer)
&& !preview_rect.contains(pointer)
&& !identity_rect.contains(pointer)
&& !actions_rect.contains(pointer)
{
*open = !*open;
}
}
}
super::pickers::material_picker_popup(
ui,
id.with("material_picker"),
&preview.union(identity),
view,
actions,
);
if response.hovered()
&& view.drop_candidate.is_some()
&& ui.input(|input| input.pointer.any_released())
{
if let Some(candidate) = view.drop_candidate.as_ref() {
actions.push(MaterialSlotAction::Assign {
reference: candidate.reference.clone(),
from_drop: true,
});
}
}
if response.hovered() {
if let Some(reason) = view.invalid_drop_reason.as_deref() {
response.on_hover_text(reason);
}
}
}
fn compact_material_identity(
ui: &mut egui::Ui,
view: &MaterialSlotPanelViewModel,
) -> egui::Response {
let palette = design_system::palette(ui);
let name = ui
.add(
egui::Label::new(
TypeRole::AssetTitle
.text(&view.label)
.color(palette.text_primary),
)
.truncate()
.sense(egui::Sense::click()),
)
.on_hover_text(&view.label);
let detail_text = view
.inherited
.map(MaterialLayerBadge::label)
.unwrap_or(view.shader.as_str());
let detail = ui
.add(
egui::Label::new(TypeRole::Small.text(detail_text).color(palette.text_muted))
.truncate()
.sense(egui::Sense::click()),
)
.on_hover_text(detail_text);
name.union(detail)
}
fn parameter_body(ui: &mut egui::Ui, content_ui: impl FnOnce(&mut egui::Ui)) {
let palette = design_system::palette(ui);
egui::Frame::new()
.fill(palette.recessed)
.inner_margin(egui::Margin {
// The parent slot stroke already contributes one pixel on each side. Reclaim it here
// so the parameter sections are the authored 569/369 px instead of 567/367 px.
left: 18,
right: 7,
// Own the exported PARAMETERS origin here so every primitive/static/skinned caller
// receives the same position independent of its surrounding component chrome.
top: 21,
bottom: 8,
})
.show(ui, |ui| {
let mut measure = egui::text::LayoutJob::default();
measure.append(
"PARAMETERS",
0.0,
egui::TextFormat {
font_id: TypeRole::Eyebrow.font(),
extra_letter_spacing: 0.6,
color: egui::Color32::TRANSPARENT,
..Default::default()
},
);
// Penpot positions the 9 px eyebrow two raster pixels above egui's default label
// baseline. Keep the label's normal allocation so section flow remains unchanged,
// then paint the visible glyphs at the authored baseline.
let response = ui.label(measure);
let mut visible = egui::text::LayoutJob::default();
visible.append(
"PARAMETERS",
0.0,
egui::TextFormat {
font_id: TypeRole::Eyebrow.font(),
extra_letter_spacing: 0.6,
color: palette.accent,
..Default::default()
},
);
let galley = ui.painter().layout_job(visible);
ui.painter().galley(
response.rect.min - egui::vec2(0.0, 5.0),
galley,
palette.accent,
);
let spine_x = ui.min_rect().left() - 11.0;
let spine_top = ui.cursor().top();
content_ui(ui);
let spine_bottom = ui.min_rect().bottom().max(spine_top);
ui.painter().vline(
spine_x,
spine_top..=spine_bottom,
egui::Stroke::new(1.0_f32, palette.accent_dark),
);
});
}
fn material_identity(
ui: &mut egui::Ui,
view: &MaterialSlotPanelViewModel,
actions: &mut Vec<MaterialSlotAction>,
) -> egui::Response {
let palette = design_system::palette(ui);
let name = ui
.add(
egui::Label::new(
TypeRole::AssetTitle
.text(&view.label)
.color(palette.text_primary),
)
.truncate()
.sense(egui::Sense::click()),
)
.on_hover_text(&view.label);
let unassigned = view.assigned.is_none() && view.effective.is_none();
let path = view.path.as_deref().unwrap_or(if unassigned {
"Drop a material here or choose from the browser"
} else {
"Engine built-in material"
});
let identity = view.inherited.map_or_else(
|| path.to_string(),
|layer| format!("{path} · {}", layer.label()),
);
let detail = ui
.add(
egui::Label::new(TypeRole::Small.text(&identity).color(palette.text_muted))
.truncate()
.sense(egui::Sense::click()),
)
.on_hover_text(&identity);
if view.can_edit_shader {
if let Some(mut kind) = view.shader_kind {
egui::ComboBox::from_id_salt("material_identity_shader_kind")
.selected_text(&view.shader)
.width(SHADER_CONTROL_WIDTH.min(ui.available_width().max(1.0)))
.show_ui(ui, |ui| {
ui.selectable_value(&mut kind, MaterialShaderKind::StandardLit, "Standard Lit");
ui.selectable_value(&mut kind, MaterialShaderKind::Unlit, "Unlit");
ui.selectable_value(&mut kind, MaterialShaderKind::Custom, "Custom Surface");
});
if Some(kind) != view.shader_kind {
actions.push(MaterialSlotAction::SetShader(kind));
}
}
} else if !view.shader.is_empty() {
ui.add_sized(
[
SHADER_CONTROL_WIDTH.min(ui.available_width().max(1.0)),
22.0,
],
egui::Label::new(
TypeRole::Body
.text(&view.shader)
.color(palette.text_secondary),
),
);
}
name.union(detail)
}
fn material_thumbnail_at(
ui: &mut egui::Ui,
view: &MaterialSlotPanelViewModel,
rect: egui::Rect,
) -> egui::Response {
let palette = design_system::palette(ui);
let response = ui.interact(
rect,
ui.make_persistent_id(("material_preview", &view.slot_id)),
egui::Sense::click(),
);
let size = rect.width();
let cell = size / 4.0;
for row in 0..4 {
for column in 0..4 {
ui.painter().rect_filled(
egui::Rect::from_min_size(
rect.min + egui::vec2(column as f32 * cell, row as f32 * cell),
egui::vec2(cell, cell),
)
.intersect(rect),
0.0,
if (row + column) % 2 == 0 {
palette.checker
} else {
palette.recessed
},
);
}
}
match view.thumbnail {
MaterialThumbnailPresentation::Ready(texture) => {
ui.painter().image(
texture,
rect.shrink(2.0),
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
}
MaterialThumbnailPresentation::Pending => {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icons::CIRCLE_NOTCH.as_str(),
egui::FontId::new(22.0, egui::FontFamily::Name("phosphor-regular".into())),
palette.text_secondary,
);
}
MaterialThumbnailPresentation::Failed => {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icons::WARNING.as_str(),
egui::FontId::new(22.0, egui::FontFamily::Name("phosphor-regular".into())),
palette.error,
);
}
MaterialThumbnailPresentation::Empty => {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icons::PALETTE.as_str(),
egui::FontId::new(22.0, egui::FontFamily::Name("phosphor-regular".into())),
palette.text_muted,
);
}
}
ui.painter().rect_stroke(
rect,
4.0,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
response.on_hover_text(format!("Open {} material picker", view.label))
}
#[cfg(test)]
mod tests {
use super::*;
fn view() -> MaterialSlotPanelViewModel {
MaterialSlotPanelViewModel {
slot_id: "slot:test".into(),
label: "M_Wood_Planks".into(),
path: Some("materials/wood/M_Wood_Planks.mat".into()),
shader: "Standard Lit".into(),
shader_kind: Some(MaterialShaderKind::StandardLit),
can_edit_shader: true,
thumbnail: MaterialThumbnailPresentation::Pending,
inherited: None,
health: MaterialHealth::Healthy,
assigned: None,
effective: None,
candidates: Vec::new(),
drop_candidate: None,
invalid_drop_reason: None,
can_locate: true,
can_clear: true,
can_extract: false,
can_create_instance: true,
parameters_initially_open: true,
expanded_header_when_parameters_closed: false,
}
}
#[test]
fn slot_header_insets_match_the_current_penpot_export() {
const OUTER_FRAME_STROKE_INSET: f32 = 1.0;
assert_eq!(SLOT_ACCENT_X + OUTER_FRAME_STROKE_INSET, 8.0);
assert_eq!(SLOT_CARET_CENTER_X + OUTER_FRAME_STROKE_INSET, 23.0);
assert_eq!(SLOT_PREVIEW_X + OUTER_FRAME_STROKE_INSET, 35.0);
assert_eq!(SLOT_PREVIEW_X - (SLOT_CARET_CENTER_X + 6.0), 6.0);
assert_eq!(SLOT_STATUS_ACTION_WIDTH, 140.0);
assert_eq!(SHADER_CONTROL_WIDTH, 220.0);
}
#[test]
fn actor_component_body_preserves_penpot_slot_widths() {
let wide_body = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(596.0, 700.0));
let compact_body = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(396.0, 700.0));
let wide = actor_materials_rect(wide_body, 32.0);
let compact = actor_materials_rect(compact_body, 32.0);
assert_eq!(wide.width(), 596.0);
assert_eq!(compact.width(), 396.0);
assert_eq!(wide.left(), 0.0);
assert_eq!(compact.left(), 0.0);
assert_eq!(wide.top(), 32.0);
assert_eq!(compact.top(), 32.0);
assert_eq!(wide.height(), 0.0);
assert_eq!(compact.height(), 0.0);
}
#[test]
fn materials_height_uses_the_finite_layout_cursor_not_a_virtual_scroll_extent() {
assert_eq!(materials_used_bottom(948.0, 320.0), 948.0);
assert_eq!(materials_used_bottom(240.0, 320.0), 320.0);
assert_eq!(materials_used_bottom(f32::INFINITY, 320.0), 320.0);
}
#[test]
fn penpot_direct_assignment_has_no_redundant_explicit_badge() {
assert!(view().inherited.is_none());
}
#[test]
fn penpot_assignment_action_carries_exact_stable_reference() {
let reference = EditorAssetRef::new("asset-id", "material:source", "M_Wood");
let action = MaterialSlotPanelAction {
slot_id: "slot:test".into(),
action: MaterialSlotAction::Assign {
reference: reference.clone(),
from_drop: false,
},
};
assert_eq!(
action,
MaterialSlotPanelAction {
slot_id: "slot:test".into(),
action: MaterialSlotAction::Assign {
reference,
from_drop: false,
},
}
);
}
#[test]
fn penpot_supported_material_states_share_one_view_model() {
for health in [
MaterialHealth::Healthy,
MaterialHealth::Dirty,
MaterialHealth::Processing,
MaterialHealth::Broken,
MaterialHealth::ReadOnly,
] {
let mut view = view();
view.health = health;
let palette = DesignPalette::from(crate::theme::BLACKSITE_PALETTE);
assert!(!view.health.presentation(palette).1.is_empty());
}
}
#[test]
fn penpot_material_statuses_use_semantic_phosphor_icons() {
assert_eq!(
MaterialHealth::Healthy.icon().as_str(),
icons::CHECK_CIRCLE.as_str()
);
assert_eq!(
MaterialHealth::Dirty.icon().as_str(),
icons::PENCIL_SIMPLE.as_str()
);
assert_eq!(
MaterialHealth::Processing.icon().as_str(),
icons::CIRCLE_NOTCH.as_str()
);
assert_eq!(
MaterialHealth::Broken.icon().as_str(),
icons::WARNING_CIRCLE.as_str()
);
assert_eq!(
MaterialHealth::ReadOnly.icon().as_str(),
icons::LOCK_SIMPLE.as_str()
);
}
}
@@ -0,0 +1,238 @@
//! Exact Penpot status/action geometry for an expanded material-slot header.
use egui;
use egui_phosphor_icons::icons;
use super::{MaterialSlotAction, MaterialSlotPanelViewModel};
use crate::design_system::controls::{icon_button, icon_label, status};
use crate::design_system::typography::TypeRole;
use crate::design_system::{self, DesignPalette};
pub(super) const SLOT_STATUS_ACTION_WIDTH: f32 = 140.0;
#[derive(Debug, Clone, Copy, PartialEq)]
struct ExpandedHeaderActionGeometry {
status: egui::Rect,
menu: egui::Rect,
browse: egui::Rect,
locate: egui::Rect,
clear: egui::Rect,
}
fn geometry(rect: egui::Rect) -> ExpandedHeaderActionGeometry {
let status_row = egui::Rect::from_min_size(
rect.min + egui::vec2(0.0, 5.333),
egui::vec2(SLOT_STATUS_ACTION_WIDTH, 24.0),
);
let menu = egui::Rect::from_min_size(
status_row.min + egui::vec2(116.0, 0.0),
egui::vec2(24.0, 24.0),
);
let action_row = rect.min + egui::vec2(0.0, 34.667);
ExpandedHeaderActionGeometry {
status: egui::Rect::from_min_max(
status_row.min,
egui::pos2(menu.left() - 5.0, status_row.bottom()),
),
menu,
browse: egui::Rect::from_min_size(
action_row + egui::vec2(56.0, 0.0),
egui::vec2(24.0, 24.0),
),
locate: egui::Rect::from_min_size(
action_row + egui::vec2(86.0, 0.0),
egui::vec2(24.0, 24.0),
),
clear: egui::Rect::from_min_size(
action_row + egui::vec2(116.0, 0.0),
egui::vec2(24.0, 24.0),
),
}
}
pub(super) fn expanded_status_actions(
ui: &mut egui::Ui,
rect: egui::Rect,
view: &MaterialSlotPanelViewModel,
actions: &mut Vec<MaterialSlotAction>,
diagnostics_ui: impl FnOnce(&mut egui::Ui),
palette: DesignPalette,
) {
if view.assigned.is_none() && view.effective.is_none() {
let button_rect = egui::Rect::from_min_size(
rect.right_bottom() - egui::vec2(116.0, 28.0),
egui::vec2(116.0, 28.0),
);
if rect_scope(ui, button_rect, |ui| {
ui.add(
egui::Button::new(icon_label(
icons::FOLDER_OPEN,
"Choose material",
TypeRole::Control,
13.0,
palette.text_primary,
))
.min_size(button_rect.size()),
)
.clicked()
}) {
actions.push(MaterialSlotAction::BrowseLibrary);
}
return;
}
let geometry = geometry(rect);
rect_scope(ui, geometry.status, |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let (color, label, tooltip) = view.health.presentation(palette);
status(ui, view.health.icon(), color, label, tooltip);
});
});
rect_scope(ui, geometry.menu, |ui| {
overflow_menu(ui, view, actions, diagnostics_ui);
});
for (button_rect, action, enabled, icon, tooltip) in [
(
geometry.browse,
MaterialSlotAction::BrowseLibrary,
true,
icons::FOLDER_OPEN,
"Browse project materials",
),
(
geometry.locate,
MaterialSlotAction::Locate,
view.can_locate,
icons::CROSSHAIR,
"Locate in Content Browser",
),
(
geometry.clear,
MaterialSlotAction::Clear,
view.can_clear,
icons::X,
"Clear actor assignment",
),
] {
if !enabled {
continue;
}
let clicked = rect_scope(ui, button_rect, |ui| {
icon_button(ui, icon, tooltip, true).clicked()
});
if clicked {
actions.push(action);
}
}
}
pub(super) fn overflow_menu(
ui: &mut egui::Ui,
view: &MaterialSlotPanelViewModel,
actions: &mut Vec<MaterialSlotAction>,
diagnostics_ui: impl FnOnce(&mut egui::Ui),
) {
let palette = design_system::palette(ui);
ui.menu_button(
egui::RichText::new(icons::DOTS_THREE.as_str()).font(egui::FontId::new(
16.0,
egui::FontFamily::Name("phosphor-bold".into()),
)),
|ui| {
if view.can_locate && menu_action(ui, icons::CROSSHAIR, "Locate", palette.text_primary)
{
actions.push(MaterialSlotAction::Locate);
ui.close();
}
if menu_action(
ui,
icons::FOLDER_OPEN,
"Browse Asset Library",
palette.text_primary,
) {
actions.push(MaterialSlotAction::BrowseLibrary);
ui.close();
}
if view.can_clear && menu_action(ui, icons::X, "Clear material", palette.text_primary) {
actions.push(MaterialSlotAction::Clear);
ui.close();
}
if view.can_create_instance
&& menu_action(
ui,
icons::COPY,
"Create Instance and Assign",
palette.text_primary,
)
{
actions.push(MaterialSlotAction::CreateInstance);
ui.close();
}
if view.can_extract
&& menu_action(ui, icons::EXPORT, "Extract Editable…", palette.text_primary)
{
actions.push(MaterialSlotAction::ExtractEditable);
ui.close();
}
ui.separator();
ui.label(TypeRole::Section.text("Source & Diagnostics"));
diagnostics_ui(ui);
},
)
.response
.on_hover_text("Material actions and diagnostics");
}
fn menu_action(
ui: &mut egui::Ui,
icon: egui_phosphor_icons::Icon,
label: &str,
color: egui::Color32,
) -> bool {
ui.add(egui::Button::new(icon_label(
icon,
label,
TypeRole::Control,
14.0,
color,
)))
.clicked()
}
fn rect_scope<R>(
ui: &mut egui::Ui,
rect: egui::Rect,
add_contents: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
add_contents(ui)
})
.inner
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expanded_status_and_actions_match_the_penpot_header_geometry() {
let rect = egui::Rect::from_min_size(egui::pos2(448.0, 9.0), egui::vec2(140.0, 64.0));
let geometry = geometry(rect);
assert_eq!(geometry.menu.min, egui::pos2(564.0, 14.333));
assert_eq!(geometry.browse.min, egui::pos2(504.0, 43.667));
assert_eq!(geometry.locate.min, egui::pos2(534.0, 43.667));
assert_eq!(geometry.clear.min, egui::pos2(564.0, 43.667));
assert_eq!(geometry.menu.size(), egui::vec2(24.0, 24.0));
assert_eq!(geometry.clear.size(), egui::vec2(24.0, 24.0));
for child in [
geometry.status,
geometry.menu,
geometry.browse,
geometry.locate,
geometry.clear,
] {
assert!(rect.contains_rect(child));
}
}
}
+420
View File
@@ -0,0 +1,420 @@
//! Penpot-styled material and texture asset pickers.
use egui;
use egui_phosphor_icons::icons;
use material_schema::EditorAssetRef;
use super::panel::{MaterialPickerCandidate, MaterialSlotAction, MaterialSlotPanelViewModel};
use super::{MaterialTextureCandidate, MaterialThumbnailPresentation, TextureSlotResponse};
use crate::design_system;
use crate::design_system::controls::icon_label;
use crate::design_system::typography::TypeRole;
const MATERIAL_PICKER_WIDTH: f32 = 244.0;
const TEXTURE_PICKER_WIDTH: f32 = 420.0;
const PICKER_ROW_HEIGHT: f32 = 44.0;
const PICKER_THUMBNAIL: f32 = 36.0;
pub(super) fn material_picker_popup(
_ui: &mut egui::Ui,
id: egui::Id,
anchor: &egui::Response,
view: &MaterialSlotPanelViewModel,
actions: &mut Vec<MaterialSlotAction>,
) {
egui::Popup::menu(anchor)
.id(id)
.width(MATERIAL_PICKER_WIDTH)
.show(|ui| {
ui.label(
TypeRole::Section
.text("Material Assets")
.color(design_system::palette(ui).text_primary),
);
if let Some(current) = view.effective.as_ref() {
if let Some(candidate) = find_material_candidate(&view.candidates, current) {
material_menu_row(ui, candidate, true, actions);
} else {
unresolved_material_menu_row(ui, current);
}
}
let recent_keys = recent_keys(ui, "material_picker_recents");
let recent = candidates_for_recent_keys(&view.candidates, &recent_keys);
for candidate in recent.into_iter().take(4) {
let selected = view
.effective
.as_ref()
.is_some_and(|current| same_reference(current, &candidate.reference));
if !selected {
material_menu_row(ui, candidate, false, actions);
}
}
picker_footer(ui, view.assigned.is_some(), actions);
});
}
pub(super) fn texture_picker_popup(
_ui: &mut egui::Ui,
id: egui::Id,
anchor: &egui::Response,
candidates: &[MaterialTextureCandidate],
selected: Option<&MaterialTextureCandidate>,
response: &mut TextureSlotResponse,
) {
egui::Popup::menu(anchor)
.id(id)
.width(TEXTURE_PICKER_WIDTH)
.show(|ui| {
picker_heading(
ui,
"Select Texture",
"Project textures and imported subassets",
);
if let Some(current) = selected {
picker_section_label(ui, "CURRENT");
texture_candidate_row(ui, current, true, response);
}
let recent_keys = recent_keys(ui, "texture_picker_recents");
let recent = candidates_for_recent_texture_keys(candidates, &recent_keys);
if !recent.is_empty() {
picker_section_label(ui, "RECENT");
for candidate in recent.into_iter().take(4) {
texture_candidate_row(ui, candidate, false, response);
}
}
picker_section_label(ui, "PROJECT TEXTURES");
egui::ScrollArea::vertical()
.id_salt(id.with("project_textures"))
.max_height(240.0)
.auto_shrink([false, true])
.show(ui, |ui| {
if candidates.is_empty() {
empty_picker_row(ui, "No project textures");
}
for candidate in candidates {
let selected = selected.is_some_and(|current| {
same_reference(&current.reference, &candidate.reference)
});
texture_candidate_row(ui, candidate, selected, response);
}
});
let palette = design_system::palette(ui);
ui.separator();
if ui
.add(egui::Button::new(icon_label(
icons::FOLDER_OPEN,
"Browse Asset Library",
TypeRole::Control,
14.0,
palette.text_primary,
)))
.clicked()
{
response.browse_library = true;
ui.close();
}
if selected.is_some()
&& ui
.add(egui::Button::new(icon_label(
icons::X,
"Clear Texture",
TypeRole::Control,
14.0,
palette.text_primary,
)))
.clicked()
{
response.clear = true;
ui.close();
}
});
}
fn picker_heading(ui: &mut egui::Ui, title: &str, subtitle: &str) {
let palette = design_system::palette(ui);
ui.label(TypeRole::Title.text(title).color(palette.text_primary));
ui.label(TypeRole::Small.text(subtitle).color(palette.text_muted));
ui.separator();
}
fn picker_section_label(ui: &mut egui::Ui, label: &str) {
let palette = design_system::palette(ui);
ui.add_space(4.0);
ui.label(TypeRole::Caption.text(label).color(palette.text_muted));
}
fn material_menu_row(
ui: &mut egui::Ui,
candidate: &MaterialPickerCandidate,
selected: bool,
actions: &mut Vec<MaterialSlotAction>,
) {
let response = picker_asset_row(
ui,
&candidate.label,
&candidate.detail,
candidate.thumbnail,
selected,
);
if response.clicked() {
remember_recent(ui, "material_picker_recents", &candidate.reference);
actions.push(MaterialSlotAction::Assign {
reference: candidate.reference.clone(),
from_drop: false,
});
ui.close();
}
}
fn texture_candidate_row(
ui: &mut egui::Ui,
candidate: &MaterialTextureCandidate,
selected: bool,
response: &mut TextureSlotResponse,
) {
let row = picker_asset_row(
ui,
&candidate.label,
&candidate.detail,
candidate.thumbnail,
selected,
);
if row.clicked() {
remember_recent(ui, "texture_picker_recents", &candidate.reference);
response.selected = Some(candidate.clone());
ui.close();
}
}
fn picker_asset_row(
ui: &mut egui::Ui,
label: &str,
detail: &str,
thumbnail: MaterialThumbnailPresentation,
selected: bool,
) -> egui::Response {
let palette = design_system::palette(ui);
let (rect, response) = ui.allocate_exact_size(
egui::vec2(ui.available_width().max(1.0), PICKER_ROW_HEIGHT),
egui::Sense::click(),
);
let fill = if selected {
palette.accent_dark
} else if response.hovered() {
palette.elevated
} else {
palette.recessed
};
ui.painter().rect(
rect,
5.0,
fill,
egui::Stroke::new(
1.0_f32,
if selected {
palette.accent
} else {
palette.border
},
),
egui::StrokeKind::Inside,
);
let thumb = egui::Rect::from_min_size(
rect.left_top() + egui::vec2(4.0, 4.0),
egui::vec2(PICKER_THUMBNAIL, PICKER_THUMBNAIL),
);
paint_thumbnail(ui, thumb, thumbnail);
let text_rect = egui::Rect::from_min_max(
egui::pos2(thumb.right() + 8.0, rect.top() + 5.0),
egui::pos2(rect.right() - 8.0, rect.bottom() - 5.0),
);
let mut child = ui.new_child(
egui::UiBuilder::new()
.max_rect(text_rect)
.layout(egui::Layout::top_down(egui::Align::Min)),
);
child.set_clip_rect(rect.intersect(ui.clip_rect()));
child
.add(egui::Label::new(TypeRole::Body.text(label).color(palette.text_primary)).truncate())
.on_hover_text(label);
child
.add(egui::Label::new(TypeRole::Small.text(detail).color(palette.text_muted)).truncate())
.on_hover_text(detail);
response
}
fn paint_thumbnail(ui: &egui::Ui, rect: egui::Rect, thumbnail: MaterialThumbnailPresentation) {
let palette = design_system::palette(ui);
ui.painter().rect_filled(rect, 4.0, palette.control);
match thumbnail {
MaterialThumbnailPresentation::Ready(texture) => {
ui.painter().image(
texture,
rect,
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
}
MaterialThumbnailPresentation::Pending => {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icons::CIRCLE_NOTCH.as_str(),
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.text_muted,
);
}
MaterialThumbnailPresentation::Failed => {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icons::WARNING.as_str(),
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.error,
);
}
MaterialThumbnailPresentation::Empty => {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icons::PALETTE.as_str(),
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.text_muted,
);
}
}
ui.painter().rect_stroke(
rect,
4.0,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
}
fn picker_footer(ui: &mut egui::Ui, can_clear: bool, actions: &mut Vec<MaterialSlotAction>) {
let palette = design_system::palette(ui);
ui.separator();
if ui
.add(egui::Button::new(icon_label(
icons::FOLDER_OPEN,
"Browse Asset Library",
TypeRole::Control,
14.0,
palette.text_primary,
)))
.clicked()
{
actions.push(MaterialSlotAction::BrowseLibrary);
ui.close();
}
if can_clear
&& ui
.add(egui::Button::new(icon_label(
icons::X,
"Clear Material",
TypeRole::Control,
14.0,
palette.text_primary,
)))
.clicked()
{
actions.push(MaterialSlotAction::Clear);
ui.close();
}
}
fn unresolved_material_menu_row(ui: &mut egui::Ui, current: &EditorAssetRef) {
let palette = design_system::palette(ui);
ui.add_sized(
[ui.available_width().max(1.0), 28.0],
egui::Button::new(TypeRole::Body.text(&current.label).color(palette.error)).selected(true),
)
.on_hover_text("The currently assigned material could not be resolved");
}
fn empty_picker_row(ui: &mut egui::Ui, message: &str) {
let palette = design_system::palette(ui);
ui.add_sized(
[ui.available_width().max(1.0), 32.0],
egui::Label::new(TypeRole::Body.text(message).color(palette.text_muted)),
);
}
fn same_reference(left: &EditorAssetRef, right: &EditorAssetRef) -> bool {
left.asset_id == right.asset_id && left.sub_asset_id == right.sub_asset_id
}
fn find_material_candidate<'a>(
candidates: &'a [MaterialPickerCandidate],
reference: &EditorAssetRef,
) -> Option<&'a MaterialPickerCandidate> {
candidates
.iter()
.find(|candidate| same_reference(&candidate.reference, reference))
}
fn recent_keys(ui: &egui::Ui, salt: &'static str) -> Vec<(String, String)> {
let id = ui.make_persistent_id(salt);
ui.ctx()
.data_mut(|data| data.get_persisted::<Vec<(String, String)>>(id))
.unwrap_or_default()
}
fn remember_recent(ui: &egui::Ui, salt: &'static str, reference: &EditorAssetRef) {
let id = ui.make_persistent_id(salt);
let mut keys = recent_keys(ui, salt);
let key = (reference.asset_id.clone(), reference.sub_asset_id.clone());
keys.retain(|current| current != &key);
keys.insert(0, key);
keys.truncate(8);
ui.ctx().data_mut(|data| data.insert_persisted(id, keys));
}
fn candidates_for_recent_keys<'a>(
candidates: &'a [MaterialPickerCandidate],
keys: &[(String, String)],
) -> Vec<&'a MaterialPickerCandidate> {
keys.iter()
.filter_map(|(asset_id, sub_asset_id)| {
candidates.iter().find(|candidate| {
candidate.reference.asset_id == *asset_id
&& candidate.reference.sub_asset_id == *sub_asset_id
})
})
.collect()
}
fn candidates_for_recent_texture_keys<'a>(
candidates: &'a [MaterialTextureCandidate],
keys: &[(String, String)],
) -> Vec<&'a MaterialTextureCandidate> {
keys.iter()
.filter_map(|(asset_id, sub_asset_id)| {
candidates.iter().find(|candidate| {
candidate.reference.asset_id == *asset_id
&& candidate.reference.sub_asset_id == *sub_asset_id
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn penpot_picker_reference_comparison_uses_stable_identity_not_label() {
let left = EditorAssetRef::new("asset", "material:source", "Left");
let right = EditorAssetRef::new("asset", "material:source", "Renamed");
assert!(same_reference(&left, &right));
}
#[test]
fn penpot_picker_geometry_matches_penpot_assets() {
assert_eq!(MATERIAL_PICKER_WIDTH, 244.0);
assert_eq!(TEXTURE_PICKER_WIDTH, 420.0);
assert_eq!(PICKER_ROW_HEIGHT, 44.0);
assert_eq!(PICKER_THUMBNAIL, 36.0);
}
}
+120
View File
@@ -0,0 +1,120 @@
//! Penpot Surface section backed by shared material document values.
use egui;
use material_schema::{MaterialAlphaMode, MaterialInputSet, MaterialRenderState};
use super::inputs::{
apply_arm_texture_preset, apply_separate_texture_preset, packed_map_mode, PackedMapMode,
};
use super::layout::{ResponsiveMaterialLayout, SurfaceSectionGeometry};
use crate::design_system;
pub fn material_surface_options_ui(
ui: &mut egui::Ui,
state: &mut MaterialRenderState,
packed_inputs: Option<&mut MaterialInputSet>,
) {
let palette = design_system::palette(ui);
let width = ui.available_width().max(1.0);
let height = match ResponsiveMaterialLayout::for_width(width) {
ResponsiveMaterialLayout::Reference => design_system::SURFACE_SECTION_HEIGHT,
ResponsiveMaterialLayout::Compact => design_system::COMPACT_SURFACE_SECTION_HEIGHT,
ResponsiveMaterialLayout::Transient => 100.0,
};
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
ui.painter().rect(
rect,
5.0,
palette.panel,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
let geometry = SurfaceSectionGeometry::for_rect(rect);
ui.painter().text(
geometry.title.left_center(),
egui::Align2::LEFT_CENTER,
"Surface",
design_system::typography::TypeRole::Section.font(),
palette.text_primary,
);
clipped_rect_ui(ui, geometry.blend, |ui| surface_blend_controls(ui, state));
if let Some(inputs) = packed_inputs {
clipped_rect_ui(ui, geometry.packed, |ui| packed_mode_controls(ui, inputs));
}
ui.painter().text(
geometry.double_sided.left_center() + egui::vec2(7.0, 0.0),
egui::Align2::LEFT_CENTER,
"Double Sided",
design_system::typography::TypeRole::Body.font(),
palette.text_secondary,
);
let switch_rect = egui::Rect::from_min_size(
geometry.double_sided.min + egui::vec2(76.0, 3.0),
egui::vec2(31.0, 16.0),
);
clipped_rect_ui(ui, switch_rect, |ui| {
design_system::controls::switch(ui, &mut state.double_sided)
.on_hover_text("Render both sides of the surface");
});
// Explicitly placed blend/packing/switch children do not own vertical flow. Reassert the
// Surface rectangle after they render so the following authored section gap starts at the
// true 46/100 px boundary.
ui.advance_cursor_after_rect(rect);
}
fn packed_mode_controls(ui: &mut egui::Ui, inputs: &mut MaterialInputSet) {
let arm = packed_map_mode(inputs) == PackedMapMode::Arm;
match design_system::controls::two_option_segmented(ui, "Separate", "ORM", arm) {
Some(false) => apply_separate_texture_preset(inputs),
Some(true) => apply_arm_texture_preset(inputs),
None => {}
}
}
fn surface_blend_controls(ui: &mut egui::Ui, state: &mut MaterialRenderState) {
let width = ui.available_width().max(1.0);
let show_cutoff = state.alpha_mode == MaterialAlphaMode::Cutout;
let combo_width = if show_cutoff {
(width - 58.0).max(1.0)
} else {
width
};
let combo_rect = egui::Rect::from_min_size(ui.min_rect().min, egui::vec2(combo_width, 24.0));
clipped_rect_ui(ui, combo_rect, |ui| {
egui::ComboBox::from_id_salt("material_alpha_mode")
.selected_text(match state.alpha_mode {
MaterialAlphaMode::Opaque => "Opaque",
MaterialAlphaMode::Cutout => "Cutout",
})
.width(combo_width)
.show_ui(ui, |ui| {
ui.selectable_value(&mut state.alpha_mode, MaterialAlphaMode::Opaque, "Opaque");
ui.selectable_value(&mut state.alpha_mode, MaterialAlphaMode::Cutout, "Cutout");
});
});
if show_cutoff {
let cutoff_rect = egui::Rect::from_min_size(
ui.min_rect().min + egui::vec2(combo_width + 4.0, 1.0),
egui::vec2(54.0_f32.min(width - combo_width - 4.0), 22.0),
);
ui.put(
cutoff_rect,
egui::DragValue::new(&mut state.alpha_cutoff)
.range(0.0..=1.0)
.speed(0.01),
)
.on_hover_text("Alpha cutoff");
}
}
fn clipped_rect_ui<R>(
ui: &mut egui::Ui,
rect: egui::Rect,
add_contents: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
add_contents(ui)
})
.inner
}
@@ -0,0 +1,413 @@
//! Texture/channel controls shared by Material and Material Instance input tables.
use super::*;
use crate::design_system;
use crate::design_system::typography::TypeRole;
use egui_phosphor_icons::icons;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TextureFieldAdornment {
TypedThumbnail,
BrokenReference,
Empty,
}
fn texture_field_adornment(
presentation: Option<MaterialThumbnailPresentation>,
current_present: bool,
) -> TextureFieldAdornment {
if presentation.is_some() {
TextureFieldAdornment::TypedThumbnail
} else if current_present {
TextureFieldAdornment::BrokenReference
} else {
TextureFieldAdornment::Empty
}
}
pub(super) fn material_property_texture_binding(
textures: &[MaterialTextureBinding],
property: &MaterialInputDesc,
) -> MaterialTextureBinding {
textures
.iter()
.find(|texture| texture.name == property.name)
.cloned()
.unwrap_or_else(|| MaterialTextureBinding {
name: property.name.clone(),
texture: None,
channel: property
.texture
.as_ref()
.map_or(TextureChannel::Rgba, |desc| desc.default_channel),
})
}
pub(super) fn upsert_material_texture_binding(
textures: &mut Vec<MaterialTextureBinding>,
binding: MaterialTextureBinding,
) {
if let Some(existing) = textures
.iter_mut()
.find(|texture| texture.name == binding.name)
{
*existing = binding;
} else {
textures.push(binding);
}
}
pub(super) fn material_texture_channel_ui(
ui: &mut egui::Ui,
property: &MaterialInputDesc,
binding: &mut MaterialTextureBinding,
) {
let allow_override = property
.texture
.as_ref()
.is_some_and(|texture| texture.allow_channel_override);
if !allow_override {
return;
}
egui::ComboBox::from_id_salt(("texture_channel", &property.name))
.selected_text(texture_channel_label(binding.channel))
.width(48.0)
.show_ui(ui, |ui| {
for channel in [
TextureChannel::R,
TextureChannel::G,
TextureChannel::B,
TextureChannel::A,
] {
ui.selectable_value(
&mut binding.channel,
channel,
texture_channel_label(channel),
);
}
});
}
pub(super) fn texture_channel_label(channel: TextureChannel) -> &'static str {
match channel {
TextureChannel::R => "R",
TextureChannel::G => "G",
TextureChannel::B => "B",
TextureChannel::A => "A",
TextureChannel::Rgb => "RGB",
TextureChannel::Rgba => "RGBA",
}
}
pub fn ensure_material_texture_binding<'a>(
textures: &'a mut Vec<MaterialTextureBinding>,
name: &str,
) -> &'a mut MaterialTextureBinding {
let index = textures
.iter()
.position(|texture| texture.name == name)
.unwrap_or_else(|| {
textures.push(MaterialTextureBinding {
name: name.to_string(),
texture: None,
channel: TextureChannel::Rgba,
});
textures.len() - 1
});
&mut textures[index]
}
pub(super) fn texture_binding_ui(
ui: &mut egui::Ui,
binding: &mut MaterialTextureBinding,
texture_assets: &[MaterialTextureCandidate],
drop_candidate: Option<&MaterialTextureCandidate>,
inline_actions: bool,
) -> TextureSlotResponse {
let response = texture_slot_ui(
ui,
format!("binding_{}", binding.name),
TextureSlotSelection::Reference(binding.texture.as_ref()),
"(none)",
texture_assets,
drop_candidate,
inline_actions,
);
if response.clear {
binding.texture = None;
} else if let Some(candidate) = response.selected.as_ref() {
binding.texture = Some(candidate.reference.clone());
}
response
}
pub(super) fn texture_slot_ui(
ui: &mut egui::Ui,
slot_id: impl std::hash::Hash,
current: TextureSlotSelection<'_>,
empty_label: &str,
candidates: &[MaterialTextureCandidate],
drop_candidate: Option<&MaterialTextureCandidate>,
inline_actions: bool,
) -> TextureSlotResponse {
let palette = design_system::palette(ui);
let mut result = TextureSlotResponse::default();
ui.push_id(slot_id, |ui| {
let width = ui.available_width().max(1.0);
let (outer, _) = ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::hover());
let group = outer;
let field_width = if inline_actions {
(group.width() - 60.0).max(1.0)
} else {
(group.width() - 30.0).max(1.0)
};
let field_rect = egui::Rect::from_min_size(group.min, egui::vec2(field_width, 22.0));
let locate_rect = egui::Rect::from_min_size(
group.min + egui::vec2(field_width + 6.0, 0.0),
egui::vec2(24.0, 22.0),
);
let clear_rect = inline_actions.then(|| {
egui::Rect::from_min_size(
group.min + egui::vec2(field_width + 36.0, 0.0),
egui::vec2(24.0, 22.0),
)
});
let selected_candidate = candidates.iter().find(|candidate| match current {
TextureSlotSelection::Reference(reference) => reference.is_some_and(|reference| {
reference.asset_id == candidate.reference.asset_id
&& reference.sub_asset_id == candidate.reference.sub_asset_id
}),
});
let current_present = match current {
TextureSlotSelection::Reference(reference) => reference.is_some(),
};
let display_label = selected_candidate
.map(|candidate| candidate.label.as_str())
.or_else(|| match current {
TextureSlotSelection::Reference(reference) => {
reference.map(|reference| reference.label.as_str())
}
})
.unwrap_or(empty_label);
let presentation = selected_candidate.map(|candidate| candidate.thumbnail);
let adornment = texture_field_adornment(presentation, current_present);
let label_color = if current_present {
palette.text_primary
} else {
palette.text_muted
};
ui.painter().rect(
field_rect,
4.0,
palette.control,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
let field = ui.interact(
field_rect,
ui.make_persistent_id("texture_field"),
egui::Sense::click(),
);
let image_rect = egui::Rect::from_center_size(
egui::pos2(field_rect.left() + 14.0, field_rect.center().y),
egui::vec2(16.0, 16.0),
);
match selected_candidate.map(|candidate| candidate.thumbnail) {
Some(MaterialThumbnailPresentation::Ready(texture)) => {
ui.painter().image(
texture,
image_rect,
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
}
Some(MaterialThumbnailPresentation::Pending) => {
paint_field_icon(ui, image_rect, icons::CIRCLE_NOTCH, palette.text_muted);
}
Some(MaterialThumbnailPresentation::Failed) => {
paint_field_icon(ui, image_rect, icons::WARNING, palette.error);
}
Some(MaterialThumbnailPresentation::Empty) => {
paint_field_icon(ui, image_rect, icons::IMAGE, palette.text_muted);
}
None => paint_field_icon(
ui,
image_rect,
if adornment == TextureFieldAdornment::BrokenReference {
icons::WARNING
} else {
icons::IMAGE
},
if adornment == TextureFieldAdornment::BrokenReference {
palette.error
} else {
palette.text_muted
},
),
}
let text_rect = egui::Rect::from_min_max(
egui::pos2(field_rect.left() + 27.0, field_rect.top()),
egui::pos2(field_rect.right() - 6.0, field_rect.bottom()),
);
// `Label::truncate` centers its galley when forced into the full fixed field rectangle.
// Paint the truncated galley at the Penpot text origin instead: the typed thumbnail and
// the asset name then form one stable left-aligned identity regardless of field width.
let galley =
egui::WidgetText::from(TypeRole::AssetLabel.text(display_label).color(label_color))
.into_galley(
ui,
Some(egui::TextWrapMode::Truncate),
text_rect.width(),
egui::FontSelection::Default,
);
let text_pos = egui::pos2(
text_rect.left(),
text_rect.center().y - galley.size().y * 0.5,
);
let text_painter = ui
.painter()
.with_clip_rect(text_rect.intersect(ui.clip_rect()));
text_painter.galley(text_pos, galley, label_color);
field.clone().on_hover_text(display_label);
let drop_hovered = drop_candidate.is_some() && field.hovered();
if drop_hovered {
ui.painter().rect_stroke(
field_rect,
4.0,
egui::Stroke::new(2.0_f32, palette.accent),
egui::StrokeKind::Inside,
);
}
super::pickers::texture_picker_popup(
ui,
field.id.with("texture_picker"),
&field,
candidates,
selected_candidate,
&mut result,
);
if let Some(clear_rect) = clear_rect {
let locate = ui.put(
locate_rect,
egui::Button::new(icon_text(icons::CROSSHAIR, 14.0))
.min_size(locate_rect.size())
.fill(palette.control)
.stroke(egui::Stroke::new(1.0_f32, palette.border)),
);
if selected_candidate.is_some() && locate.clicked() {
result.locate = selected_candidate.map(|candidate| candidate.locate.clone());
}
locate.on_hover_text(if selected_candidate.is_some() {
"Locate texture in Content Browser"
} else {
"No texture to locate"
});
let clear = ui.put(
clear_rect,
egui::Button::new(icon_text(icons::X, 14.0))
.min_size(clear_rect.size())
.fill(palette.control)
.stroke(egui::Stroke::new(1.0_f32, palette.border)),
);
if current_present && clear.clicked() {
result.clear = true;
}
clear.on_hover_text(if current_present {
"Clear texture"
} else {
"No texture to clear"
});
} else {
transient_texture_actions(
ui,
locate_rect,
selected_candidate,
current_present,
&mut result,
);
}
if drop_hovered && ui.input(|input| input.pointer.any_released()) {
if let Some(candidate) = drop_candidate {
result.selected = Some(candidate.clone());
result.accepted_drop = true;
}
}
});
result
}
fn transient_texture_actions(
ui: &mut egui::Ui,
rect: egui::Rect,
selected_candidate: Option<&MaterialTextureCandidate>,
current_present: bool,
result: &mut TextureSlotResponse,
) {
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
ui.menu_button(icon_text(icons::DOTS_THREE, 14.0), |ui| {
if ui
.add_enabled(selected_candidate.is_some(), egui::Button::new("Locate"))
.clicked()
{
result.locate = selected_candidate.map(|candidate| candidate.locate.clone());
ui.close();
}
if ui
.add_enabled(current_present, egui::Button::new("Clear"))
.clicked()
{
result.clear = true;
ui.close();
}
})
.response
.on_hover_text("Texture actions");
});
}
fn paint_field_icon(
ui: &egui::Ui,
rect: egui::Rect,
icon: egui_phosphor_icons::Icon,
color: egui::Color32,
) {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icon.as_str(),
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-bold".into())),
color,
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ready_texture_uses_its_thumbnail_without_a_redundant_asset_glyph() {
assert_eq!(
texture_field_adornment(
Some(MaterialThumbnailPresentation::Ready(
egui::TextureId::Managed(7)
)),
true,
),
TextureFieldAdornment::TypedThumbnail
);
}
#[test]
fn unresolved_and_empty_texture_fields_keep_distinct_fallbacks() {
assert_eq!(
texture_field_adornment(None, true),
TextureFieldAdornment::BrokenReference
);
assert_eq!(
texture_field_adornment(None, false),
TextureFieldAdornment::Empty
);
}
}
@@ -0,0 +1,131 @@
//! Shared material UV-transform authoring used by Materials and Material Instances.
use bevy_math::Vec2;
use egui;
use egui_phosphor_icons::icons;
use material_schema::{MaterialInputSet, MaterialParameter, MaterialParameterValue};
use crate::design_system;
use crate::design_system::typography::TypeRole;
pub(super) fn uv_transform_section(
ui: &mut egui::Ui,
offset: &mut Vec2,
tiling: &mut Vec2,
reset_offset: Vec2,
reset_tiling: Vec2,
) {
let palette = design_system::palette(ui);
let width = ui.available_width().max(1.0);
let height = match super::layout::ResponsiveMaterialLayout::for_width(width) {
super::layout::ResponsiveMaterialLayout::Reference => {
crate::design_system::UV_SECTION_HEIGHT
}
super::layout::ResponsiveMaterialLayout::Compact => {
crate::design_system::COMPACT_UV_SECTION_HEIGHT
}
super::layout::ResponsiveMaterialLayout::Transient => 100.0,
};
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
ui.painter().rect(
rect,
5.0,
palette.panel,
egui::Stroke::new(1.0_f32, palette.border),
egui::StrokeKind::Inside,
);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect));
child.set_clip_rect(rect.intersect(ui.clip_rect()));
let geometry = super::layout::UvSectionGeometry::for_rect(rect);
child.painter().text(
geometry.title.left_center(),
egui::Align2::LEFT_CENTER,
"UV",
TypeRole::Section.font(),
palette.text_primary,
);
vec2_group(
&mut child,
geometry.offset,
"Offset",
offset,
reset_offset,
"Reset UV offset",
);
vec2_group(
&mut child,
geometry.tiling,
"Tiling",
tiling,
reset_tiling,
"Reset UV tiling",
);
}
fn vec2_group(
ui: &mut egui::Ui,
geometry: super::layout::UvGroupGeometry,
label: &str,
value: &mut Vec2,
reset: Vec2,
tooltip: &str,
) {
let palette = design_system::palette(ui);
ui.painter().text(
geometry.label.left_center(),
egui::Align2::LEFT_CENTER,
label,
TypeRole::Small.font(),
palette.text_muted,
);
ui.put(
geometry.x,
egui::DragValue::new(&mut value.x).speed(0.01).prefix("X "),
);
ui.put(
geometry.y,
egui::DragValue::new(&mut value.y).speed(0.01).prefix("Y "),
);
if let Some(reset_rect) = geometry.reset {
let enabled = *value != reset;
let response = ui.put(
reset_rect,
egui::Button::new(
egui::RichText::new(icons::ARROW_COUNTER_CLOCKWISE.as_str()).font(
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
),
),
);
if enabled && response.clicked() {
*value = reset;
}
response.on_hover_text(tooltip);
}
}
pub(super) fn material_vec2_value(inputs: &MaterialInputSet, name: &str, default: Vec2) -> Vec2 {
inputs
.values
.iter()
.find(|parameter| parameter.name == name)
.and_then(|parameter| match parameter.value {
MaterialParameterValue::Vec2(value) => Some(value),
_ => None,
})
.unwrap_or(default)
}
pub(super) fn set_material_vec2_value(inputs: &mut MaterialInputSet, name: &str, value: Vec2) {
if let Some(parameter) = inputs
.values
.iter_mut()
.find(|parameter| parameter.name == name)
{
parameter.value = MaterialParameterValue::Vec2(value);
} else {
inputs.values.push(MaterialParameter {
name: name.into(),
value: MaterialParameterValue::Vec2(value),
});
}
}
+412
View File
@@ -0,0 +1,412 @@
//! Static/skinned renderer-array presentation shared by production and the UI gallery.
use egui;
use egui_phosphor_icons::icons;
use crate::design_system;
use crate::design_system::typography::TypeRole;
use crate::theme::{BORDER, PANEL_BG_DARK, WIDGET_BG};
pub const RENDERER_ARRAY_HEADER_HEIGHT: f32 = 40.0;
pub const EXPANDED_RENDERER_HEADER_HEIGHT: f32 = 84.0;
pub const COLLAPSED_RENDERER_HEADER_HEIGHT: f32 = 60.0;
pub const RENDERER_PROPERTIES_HEADER_HEIGHT: f32 = 38.0;
pub const MATERIAL_SLOTS_HEADER_HEIGHT: f32 = 50.0;
#[derive(Clone, Copy)]
pub struct RendererPanelHeaderViewModel<'a> {
pub index: usize,
pub label: &'a str,
pub path: &'a str,
pub slot_count: usize,
pub texture_id: Option<egui::TextureId>,
}
pub fn renderer_array_header(ui: &mut egui::Ui, count: usize) -> bool {
let palette = design_system::palette(ui);
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_width().max(1.0), RENDERER_ARRAY_HEADER_HEIGHT),
egui::Sense::hover(),
);
ui.painter().rect_filled(rect, 4.0, palette.elevated);
ui.painter().text(
rect.left_center() + egui::vec2(12.0, 0.0),
egui::Align2::LEFT_CENTER,
icons::SQUARES_FOUR.as_str(),
egui::FontId::new(16.0, egui::FontFamily::Name("phosphor-regular".into())),
palette.text_secondary,
);
ui.painter().text(
rect.left_center() + egui::vec2(32.0, 0.0),
egui::Align2::LEFT_CENTER,
"Mesh renderers",
TypeRole::Section.font(),
palette.text_primary,
);
let badge = egui::Rect::from_center_size(
rect.left_center() + egui::vec2(124.0, 0.0),
egui::vec2(20.0, 20.0),
);
ui.painter()
.circle_filled(badge.center(), 10.0, palette.accent.linear_multiply(0.22));
ui.painter().text(
badge.center(),
egui::Align2::CENTER_CENTER,
format!("{count}"),
TypeRole::Small.font(),
palette.accent,
);
ui.painter().text(
rect.left_center() + egui::vec2(144.0, 0.0),
egui::Align2::LEFT_CENTER,
"Each renderer owns the slots exposed by its mesh",
TypeRole::Caption.font(),
palette.text_muted,
);
let add_rect = egui::Rect::from_min_size(
egui::pos2(rect.right() - 116.0, rect.top() + 7.0),
egui::vec2(104.0, 26.0),
);
ui.put(
add_rect,
egui::Button::new(design_system::controls::icon_label(
icons::PLUS,
"Add renderer",
TypeRole::Body,
12.0,
palette.text_primary,
)),
)
.clicked()
}
pub fn renderer_panel(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui)) {
egui::Frame::new()
.fill(WIDGET_BG.linear_multiply(0.82))
.stroke(egui::Stroke::new(1.0_f32, BORDER))
.corner_radius(egui::CornerRadius::same(5))
.show(ui, |ui| {
ui.set_max_width(ui.available_width());
add_contents(ui);
});
ui.add_space(10.0);
}
pub fn renderer_panel_header(
ui: &mut egui::Ui,
model: RendererPanelHeaderViewModel<'_>,
open: &mut bool,
add_actions: impl FnOnce(&mut egui::Ui),
) {
let palette = design_system::palette(ui);
let height = if *open {
EXPANDED_RENDERER_HEADER_HEIGHT
} else {
COLLAPSED_RENDERER_HEADER_HEIGHT
};
let (rect, header_response) = ui.allocate_exact_size(
egui::vec2(ui.available_width().max(1.0), height),
egui::Sense::click(),
);
ui.painter().rect_filled(
egui::Rect::from_min_size(
rect.min + egui::vec2(6.0, 8.0),
egui::vec2(3.0, height - 16.0),
),
2.0,
palette.accent,
);
ui.painter().text(
rect.left_center() + egui::vec2(24.0, 0.0),
egui::Align2::CENTER_CENTER,
if *open {
icons::CARET_DOWN.as_str()
} else {
icons::CARET_RIGHT.as_str()
},
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
palette.text_secondary,
);
let preview_size = if *open { 58.0 } else { 40.0 };
let preview = egui::Rect::from_center_size(
egui::pos2(rect.left() + 68.0, rect.center().y),
egui::vec2(preview_size, preview_size),
);
ui.painter().rect(
preview,
4.0,
PANEL_BG_DARK,
egui::Stroke::new(1.0_f32, BORDER),
egui::StrokeKind::Inside,
);
if let Some(texture_id) = model.texture_id {
ui.painter().image(
texture_id,
preview.shrink(3.0),
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
} else {
ui.painter().text(
preview.center(),
egui::Align2::CENTER_CENTER,
icons::CUBE.as_str(),
egui::FontId::new(20.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.text_secondary,
);
}
let label = if model.label.trim().is_empty() {
"Mesh renderer"
} else {
model.label.trim()
};
let identity_x = rect.left() + 105.0;
if *open {
ui.painter().text(
egui::pos2(identity_x, rect.top() + 28.0),
egui::Align2::LEFT_CENTER,
format!("RENDERER {}", model.index),
TypeRole::Eyebrow.font(),
palette.accent,
);
}
ui.painter().text(
egui::pos2(
identity_x,
if *open {
rect.top() + 45.0
} else {
rect.center().y - 7.0
},
),
egui::Align2::LEFT_CENTER,
label,
TypeRole::AssetTitle.font(),
palette.text_primary,
);
ui.painter().text(
egui::pos2(
identity_x,
if *open {
rect.top() + 62.0
} else {
rect.center().y + 9.0
},
),
egui::Align2::LEFT_CENTER,
if *open {
model.path.to_owned()
} else {
format!(
"Renderer {} · {} material slot{}",
model.index,
model.slot_count,
if model.slot_count == 1 { "" } else { "s" }
)
},
TypeRole::Small.font(),
palette.text_muted,
);
let slot_badge = egui::Rect::from_min_size(
egui::pos2(
rect.right() - if *open { 60.0 } else { 78.0 },
rect.top() + if *open { 12.0 } else { 8.0 },
),
egui::vec2(40.0, 20.0),
);
ui.painter()
.rect_filled(slot_badge, 10.0, palette.accent.linear_multiply(0.22));
ui.painter().text(
slot_badge.center(),
egui::Align2::CENTER_CENTER,
format!(
"{} slot{}",
model.slot_count,
if model.slot_count == 1 { "" } else { "s" }
),
TypeRole::Eyebrow.font(),
palette.accent,
);
let action_rect = if *open {
ui.painter().circle_filled(
egui::pos2(rect.right() - 10.0, rect.top() + 22.0),
4.0,
palette.healthy,
);
let action_rect = egui::Rect::from_min_size(
egui::pos2(rect.right() - 132.0, rect.bottom() - 38.0),
egui::vec2(122.0, 28.0),
);
ui.scope_builder(egui::UiBuilder::new().max_rect(action_rect), |ui| {
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
add_actions,
);
});
action_rect
} else {
let action_rect = egui::Rect::from_center_size(
egui::pos2(rect.right() - 20.0, rect.center().y),
egui::vec2(28.0, 28.0),
);
ui.scope_builder(egui::UiBuilder::new().max_rect(action_rect), |ui| {
design_system::controls::icon_button(
ui,
icons::DOTS_THREE_VERTICAL,
"Renderer actions",
true,
);
});
action_rect
};
if header_response.clicked()
&& ui
.input(|input| input.pointer.interact_pos())
.is_some_and(|pointer| !preview.contains(pointer) && !action_rect.contains(pointer))
{
*open = !*open;
}
}
pub fn renderer_material_slots_header(ui: &mut egui::Ui, count: usize) {
let palette = design_system::palette(ui);
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_width().max(1.0), MATERIAL_SLOTS_HEADER_HEIGHT),
egui::Sense::hover(),
);
ui.painter().rect_filled(rect, 0.0, palette.elevated);
ui.painter().text(
rect.left_center() + egui::vec2(15.0, 0.0),
egui::Align2::CENTER_CENTER,
icons::CARET_DOWN.as_str(),
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.text_secondary,
);
ui.painter().text(
rect.left_center() + egui::vec2(35.0, 0.0),
egui::Align2::CENTER_CENTER,
icons::PALETTE.as_str(),
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.accent,
);
ui.painter().text(
rect.left_center() + egui::vec2(49.0, 0.0),
egui::Align2::LEFT_CENTER,
"Material slots",
TypeRole::Section.font(),
palette.text_primary,
);
ui.painter().text(
rect.left_center() + egui::vec2(122.0, 0.0),
egui::Align2::LEFT_CENTER,
format!("{count} exposed by mesh"),
TypeRole::Caption.font(),
palette.text_muted,
);
ui.painter().line_segment(
[
egui::pos2(rect.left() + 201.0, rect.center().y),
egui::pos2(rect.right() - 93.0, rect.center().y),
],
egui::Stroke::new(1.0_f32, palette.border),
);
ui.painter().text(
rect.right_center() - egui::vec2(76.0, 0.0),
egui::Align2::CENTER_CENTER,
icons::LINK.as_str(),
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.text_muted,
);
ui.painter().text(
rect.right_center() - egui::vec2(10.0, 0.0),
egui::Align2::RIGHT_CENTER,
"Index mapped",
TypeRole::Eyebrow.font(),
palette.text_muted,
);
}
pub fn renderer_properties_header(ui: &mut egui::Ui) {
let palette = design_system::palette(ui);
let (rect, _) = ui.allocate_exact_size(
egui::vec2(
ui.available_width().max(1.0),
RENDERER_PROPERTIES_HEADER_HEIGHT,
),
egui::Sense::hover(),
);
ui.painter().text(
rect.left_center() + egui::vec2(4.0, 0.0),
egui::Align2::CENTER_CENTER,
icons::SLIDERS_HORIZONTAL.as_str(),
egui::FontId::new(13.0, egui::FontFamily::Name("phosphor-bold".into())),
palette.accent,
);
ui.painter().text(
rect.left_center() + egui::vec2(20.0, 0.0),
egui::Align2::LEFT_CENTER,
"Renderer properties",
TypeRole::AssetLabel.font(),
palette.accent,
);
ui.painter().text(
rect.right_center(),
egui::Align2::RIGHT_CENTER,
"Mesh + render flags",
TypeRole::Caption.font(),
palette.text_muted,
);
}
pub fn renderer_material_slot_row<R>(
ui: &mut egui::Ui,
index: usize,
add_contents: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
let palette = design_system::palette(ui);
let row = ui.horizontal_top(|ui| {
let (index_rect, _) = ui.allocate_exact_size(egui::vec2(39.0, 60.0), egui::Sense::hover());
ui.painter().text(
index_rect.center_top() + egui::vec2(0.0, 8.0),
egui::Align2::CENTER_CENTER,
"SLOT",
TypeRole::Caption.font(),
palette.text_muted,
);
ui.painter().text(
index_rect.center_top() + egui::vec2(0.0, 18.0),
egui::Align2::CENTER_CENTER,
index.to_string(),
TypeRole::Body.font(),
palette.text_muted,
);
ui.vertical(|ui| {
ui.set_width(ui.available_width().max(1.0));
add_contents(ui)
})
.inner
});
let rail_x = row.response.rect.left() + 23.0;
ui.painter().line_segment(
[
egui::pos2(rail_x, row.response.rect.top() + 35.0),
egui::pos2(rail_x, row.response.rect.bottom() - 8.0),
],
egui::Stroke::new(1.0_f32, palette.border_strong),
);
row.inner
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn renderer_headers_match_current_penpot_heights() {
assert_eq!(RENDERER_ARRAY_HEADER_HEIGHT, 40.0);
assert_eq!(EXPANDED_RENDERER_HEADER_HEIGHT, 84.0);
assert_eq!(COLLAPSED_RENDERER_HEADER_HEIGHT, 60.0);
assert_eq!(RENDERER_PROPERTIES_HEADER_HEIGHT, 38.0);
assert_eq!(MATERIAL_SLOTS_HEADER_HEIGHT, 50.0);
}
}
+156
View File
@@ -0,0 +1,156 @@
//! Semantic Blacksite editor palette shared by production and the UI gallery.
use egui::{self, Color32, CornerRadius, FontId, Id, Stroke, Visuals};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EditorVisualPalette {
pub canvas: Color32,
pub panel: Color32,
pub panel_dark: Color32,
pub widget: Color32,
pub elevated: Color32,
pub accent: Color32,
pub accent_hover: Color32,
pub selection: Color32,
pub selection_secondary: Color32,
pub selection_bg: Color32,
pub selection_bg_muted: Color32,
pub text: Color32,
pub text_selected: Color32,
pub text_dim: Color32,
pub text_muted: Color32,
pub border: Color32,
pub border_strong: Color32,
pub success: Color32,
pub warning: Color32,
pub error: Color32,
}
pub const CANVAS_BG: Color32 = Color32::from_rgb(7, 8, 10);
pub const PANEL_BG: Color32 = Color32::from_rgb(13, 15, 18);
pub const PANEL_BG_DARK: Color32 = Color32::from_rgb(9, 11, 13);
pub const WIDGET_BG: Color32 = Color32::from_rgb(21, 24, 28);
pub const ELEVATED_BG: Color32 = Color32::from_rgb(31, 35, 40);
pub const ACCENT: Color32 = Color32::from_rgb(229, 164, 51);
pub const ACCENT_HOVER: Color32 = Color32::from_rgb(249, 193, 79);
pub const SELECTION: Color32 = Color32::from_rgb(65, 198, 207);
pub const SELECTION_SECONDARY: Color32 = Color32::from_rgb(84, 139, 155);
pub const SELECTION_BG: Color32 = Color32::from_rgb(22, 72, 78);
pub const SELECTION_BG_MUTED: Color32 = Color32::from_rgb(23, 48, 54);
pub const TEXT: Color32 = Color32::from_rgb(220, 225, 229);
pub const TEXT_SELECTED: Color32 = Color32::from_rgb(250, 251, 252);
pub const TEXT_DIM: Color32 = Color32::from_rgb(155, 163, 171);
pub const TEXT_MUTED: Color32 = Color32::from_rgb(96, 105, 114);
pub const BORDER: Color32 = Color32::from_rgb(38, 43, 49);
pub const BORDER_STRONG: Color32 = Color32::from_rgb(64, 71, 79);
pub const SUCCESS: Color32 = Color32::from_rgb(84, 190, 127);
pub const WARNING: Color32 = Color32::from_rgb(235, 180, 72);
pub const ERROR: Color32 = Color32::from_rgb(226, 94, 94);
pub const BLACKSITE_PALETTE: EditorVisualPalette = EditorVisualPalette {
canvas: CANVAS_BG,
panel: PANEL_BG,
panel_dark: PANEL_BG_DARK,
widget: WIDGET_BG,
elevated: ELEVATED_BG,
accent: ACCENT,
accent_hover: ACCENT_HOVER,
selection: SELECTION,
selection_secondary: SELECTION_SECONDARY,
selection_bg: SELECTION_BG,
selection_bg_muted: SELECTION_BG_MUTED,
text: TEXT,
text_selected: TEXT_SELECTED,
text_dim: TEXT_DIM,
text_muted: TEXT_MUTED,
border: BORDER,
border_strong: BORDER_STRONG,
success: SUCCESS,
warning: WARNING,
error: ERROR,
};
const EDITOR_PALETTE_ID: &str = "blacksite.editor.visual_palette";
pub fn editor_palette(ctx: &egui::Context) -> EditorVisualPalette {
ctx.data_mut(|data| {
data.get_temp::<EditorVisualPalette>(Id::new(EDITOR_PALETTE_ID))
.unwrap_or(BLACKSITE_PALETTE)
})
}
pub fn apply_editor_theme(ctx: &egui::Context) {
apply_editor_theme_with_palette(ctx, editor_palette(ctx));
}
pub fn apply_editor_theme_with_palette(ctx: &egui::Context, palette: EditorVisualPalette) {
ctx.data_mut(|data| data.insert_temp(Id::new(EDITOR_PALETTE_ID), palette));
let mut visuals = Visuals::dark();
visuals.panel_fill = palette.panel;
visuals.window_fill = palette.widget;
visuals.extreme_bg_color = palette.canvas;
visuals.faint_bg_color = palette.panel_dark;
visuals.code_bg_color = palette.panel_dark;
visuals.text_edit_bg_color = Some(palette.canvas);
visuals.weak_text_color = Some(palette.text_muted);
visuals.widgets.noninteractive.bg_fill = palette.panel;
visuals.widgets.noninteractive.bg_stroke = Stroke::new(1.0_f32, palette.border);
visuals.widgets.noninteractive.fg_stroke = Stroke::new(1.0_f32, palette.text_dim);
visuals.widgets.inactive.bg_fill = palette.widget;
visuals.widgets.inactive.weak_bg_fill = palette.widget;
visuals.widgets.inactive.bg_stroke = Stroke::new(1.0_f32, palette.border);
visuals.widgets.inactive.fg_stroke = Stroke::new(1.0_f32, palette.text);
visuals.widgets.hovered.bg_fill = palette.elevated;
visuals.widgets.hovered.weak_bg_fill = palette.elevated;
visuals.widgets.hovered.bg_stroke = Stroke::new(1.0_f32, palette.border_strong);
visuals.widgets.hovered.fg_stroke = Stroke::new(1.0_f32, palette.text_selected);
visuals.widgets.active.bg_fill = palette.elevated;
visuals.widgets.active.weak_bg_fill = palette.elevated;
visuals.widgets.active.bg_stroke = Stroke::new(1.0_f32, palette.accent);
visuals.widgets.active.fg_stroke = Stroke::new(1.0_f32, palette.text_selected);
visuals.widgets.open = visuals.widgets.hovered;
visuals.selection.bg_fill = palette.selection_bg;
visuals.selection.stroke = Stroke::new(1.0_f32, palette.selection);
visuals.hyperlink_color = palette.selection;
visuals.warn_fg_color = palette.warning;
visuals.error_fg_color = palette.error;
visuals.window_stroke = Stroke::new(1.0_f32, palette.border);
visuals.window_corner_radius = CornerRadius::same(4);
visuals.menu_corner_radius = CornerRadius::same(3);
visuals.button_frame = true;
visuals.collapsing_header_frame = false;
visuals.indent_has_left_vline = true;
visuals.striped = true;
visuals.slider_trailing_fill = true;
visuals.interact_cursor = Some(egui::CursorIcon::PointingHand);
let mut style = (*ctx.global_style()).clone();
style.visuals = visuals;
style.spacing.item_spacing = egui::vec2(8.0, 7.0);
style.spacing.button_padding = egui::vec2(10.0, 5.0);
style.spacing.interact_size = egui::vec2(40.0, 28.0);
style.spacing.window_margin = egui::Margin::same(10);
style.spacing.menu_margin = egui::Margin::same(8);
style.spacing.indent = 17.0;
style.interaction.tooltip_delay = 0.32;
style.interaction.tooltip_grace_time = 0.18;
style.animation_time = 0.12;
style.compact_menu_style = true;
style.text_styles.insert(
egui::TextStyle::Body,
FontId::new(14.0, egui::FontFamily::Proportional),
);
style.text_styles.insert(
egui::TextStyle::Button,
FontId::new(13.0, egui::FontFamily::Proportional),
);
style.text_styles.insert(
egui::TextStyle::Heading,
FontId::new(16.0, egui::FontFamily::Proportional),
);
style.text_styles.insert(
egui::TextStyle::Small,
FontId::new(12.0, egui::FontFamily::Proportional),
);
ctx.set_global_style(style);
}