Layer › Copy CSS

Photoshop's Layer › Copy CSS puts CSS for the selected layers on the
clipboard. The new engine command layer.copyCSS writes each layer as a
class named after it (characters CSS doesn't allow become _): a type
layer's font size, family, colour, line height and alignment, a solid
fill or shape's background colour, or an image named after the layer;
then its opacity under 100 %, its absolute position and size (none for
type) and its z-index from the bottom, in Photoshop's format and order.
The Layer menu item copies the result to the clipboard.

Fixes #9372

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Hector VillarrealandClaude Opus 5.5 committed 2026-11-07 23:23:58 -06:00
1 parent aae9b7ea61
commit 4cd60bc06b
8 files changed
+295 -1

No files matched your search

+2
View File
@@ -98,6 +98,7 @@ pub mod history_select_cmds;
pub mod history_source_cmds;
pub mod image_cmds;
pub mod layer_copy_cmds;
pub mod layer_css_cmds;
pub mod layer_label_cmds;
pub mod layer_list_cmds;
pub mod layer_mask_props_cmds;
@@ -1389,6 +1390,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::adjust_cmds::specs());
v.extend(crate::layer_menu_cmds::specs());
v.extend(crate::layer_label_cmds::specs());
v.extend(crate::layer_css_cmds::specs());
v.extend(crate::layer_xmp_cmds::specs());
v.extend(crate::mode_cmds::specs());
v.extend(crate::multichannel_cmds::specs());
+163
View File
@@ -0,0 +1,163 @@
//! Layer › Copy CSS (#9372): CSS for the selected layers, written as Photoshop writes it. The
//! command returns the text; the shell puts it on the clipboard.
//!
//! Each layer is a class named after it (characters CSS doesn't allow in a name become `_`):
//! a type layer gives its font, colour, line height and alignment, a solid shape or fill layer
//! its colour, any other layer an image named after it; then the opacity when it isn't 100 %,
//! the absolute position (and size, except for type), and its place in the stack as `z-index`,
//! counted from the bottom layer as 1.
use photocraft_doc::{Document, Fill, Layer, LayerContent, LayerId, text::TextAlign};
use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
pub const ID: &str = "layer.copyCSS";
fn bad(message: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: ID.into(), msg: message.into() }
}
fn enabled(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selected_layers().is_empty() { Err("no layer selected".into()) } else { Ok(()) }
}
/// A number as Photoshop writes it in CSS: at most three decimals, no trailing zeros.
pub fn number(v: f64) -> String {
let v = if v.is_finite() { (v * 1000.0).round() / 1000.0 } else { 0.0 };
let s = format!("{v:.3}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s == "-0" { "0".into() } else { s.to_string() }
}
/// The class name for a layer: its name with every character CSS doesn't allow in a name as `_`.
pub fn class_name(name: &str) -> String {
let s: String = name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
if s.is_empty() { "layer".into() } else { s }
}
fn rgb(c: &photocraft_color::Color) -> String {
let [r, g, b] = c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
format!("rgb({r}, {g}, {b})")
}
/// The rule for one layer, `z` its place in the stack from the bottom (1-based); `None` for a
/// layer CSS can't describe (groups, adjustments) or one with nothing to place.
pub fn rule(doc: &Document, z: usize, l: &Layer) -> Option<String> {
let px_per_pt = f64::from(doc.resolution_dpi.max(1.0)) / 72.0;
let mut props: Vec<(&str, String)> = Vec::new();
let mut sized = true;
let mut bounds = photocraft_doc::comps::position_bounds(l);
match &l.content {
LayerContent::Group(_) | LayerContent::Adjustment(_) => return None,
LayerContent::Text(t) => {
let style = t.runs.first().map(|r| &r.style);
let size_pt = style.map_or(t.size_pt, |s| s.size_pt);
let family = style.map(|s| s.font_family.as_str()).filter(|f| !f.is_empty()).unwrap_or(&t.font_family);
let color = style.map_or(t.color, |s| s.color);
let paragraph = t.paragraphs.first().map(|p| p.style.clone()).unwrap_or_default();
// Auto leading is the paragraph's multiple of the size (1.2 by default).
let line_height = match style.and_then(|s| s.leading_pt) {
Some(leading) if size_pt > 0.0 => f64::from(leading / size_pt),
_ => f64::from(paragraph.auto_leading),
};
let align = match paragraph.align {
TextAlign::Left => "left",
TextAlign::Center => "center",
TextAlign::Right => "right",
_ => "justify",
};
props.push(("font-size", format!("{}px", number(f64::from(size_pt) * px_per_pt))));
props.push(("font-family", format!("\"{}\"", family.replace('"', "'"))));
props.push(("color", rgb(&color)));
props.push(("line-height", number(line_height)));
props.push(("text-align", align.into()));
// Point text has no box of its own: only its position.
sized = false;
}
LayerContent::Shape(sh) => match &sh.fill {
Some(Fill::Solid(c)) => props.push(("background-color", rgb(c))),
_ => props.push(("background-image", format!("url(\"{}.png\")", l.name))),
},
LayerContent::Fill(f) => {
// A fill layer without a shape covers the canvas.
if bounds.is_empty() {
bounds = doc.bounds();
}
match f {
Fill::Solid(c) => props.push(("background-color", rgb(c))),
_ => props.push(("background-image", format!("url(\"{}.png\")", l.name))),
}
}
_ => props.push(("background-image", format!("url(\"{}.png\")", l.name))),
}
if bounds.is_empty() {
return None;
}
if l.opacity < 1.0 {
props.push(("opacity", number(f64::from(l.opacity.max(0.0)))));
}
props.push(("position", "absolute".into()));
props.push(("left", format!("{}px", number(f64::from(bounds.x0)))));
props.push(("top", format!("{}px", number(f64::from(bounds.y0)))));
if sized {
props.push(("width", format!("{}px", number(f64::from(bounds.width())))));
props.push(("height", format!("{}px", number(f64::from(bounds.height())))));
}
props.push(("z-index", z.to_string()));
let mut out = format!(".{} {{\n", class_name(&l.name));
for (k, v) in props {
out.push_str(&format!(" {k}: {v};\n"));
}
out.push_str("}\n");
Some(out)
}
fn copy_css(s: &mut Session, p: &Value) -> Result<Value> {
let p = p.as_object().ok_or_else(|| bad("expected an object"))?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let ids = match p.get("layer") {
None | Some(Value::Null) => st.selected_layers(),
Some(v) => vec![LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?)],
};
if ids.is_empty() {
return Err(bad("no layer selected"));
}
let walk = st.doc.walk();
for id in &ids {
if !walk.iter().any(|(_, _, l)| l.id == *id) {
return Err(EngineError::NoLayer(*id));
}
}
// In Layers panel order, top first.
let rules: Vec<(u64, String)> = walk
.iter()
.enumerate()
.rev()
.filter(|(_, (_, _, l))| ids.contains(&l.id))
.filter_map(|(i, (_, _, l))| rule(&st.doc, i + 1, l).map(|r| (l.id.0, r)))
.collect();
if rules.is_empty() {
return Err(EngineError::Other("Copy CSS needs a pixel, type, shape or fill layer with content".into()));
}
let css = rules.iter().map(|(_, r)| r.as_str()).collect::<Vec<_>>().join("\n");
Ok(json!({"css": css, "layers": rules.iter().map(|(id, _)| id).collect::<Vec<_>>()}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec {
id: ID,
label: "Copy CSS",
menu: &["Layer"],
shortcut: None,
params: r#"{"layer":id?} (no layer: the selected layers) → {"css": text, "layers": [id…]}; the app puts the text on the clipboard"#,
enabled,
run: copy_css,
journal: false,
}]
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,94 @@
use super::*;
use photocraft_doc::Layer;
use photocraft_geom::Rect;
/// A 400 × 300 document at 72 ppi with a 200 × 140 pixel layer at (100, 80) named `name`.
fn session(name: &str) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
s.execute("layer.new.layer", json!({"name": name})).unwrap();
s.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 80, 300, 220), &[0.16, 0.35, 0.78, 1.0]);
Ok(())
})
.unwrap();
s
}
/// Photoshop 2025 copies this for a 200 × 140 pixel layer at (100, 80), second from the bottom.
#[test]
fn a_pixel_layer_copies_as_photoshop_writes_it() {
let mut s = session("Box");
let r = s.execute(ID, json!({})).unwrap();
assert_eq!(
r["css"],
json!(
".Box {\n background-image: url(\"Box.png\");\n position: absolute;\n left: 100px;\n top: 80px;\n width: 200px;\n height: 140px;\n z-index: 2;\n}\n"
)
);
// Photoshop: a name with spaces keeps them in the image name and turns them to `_` in the
// class; an opacity under 100 % follows the background.
let mut s = session("My Box 2");
s.edit("opacity", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().opacity = 128.0 / 255.0;
Ok(())
})
.unwrap();
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(".My_Box_2 {\n background-image: url(\"My Box 2.png\");\n opacity: 0.502;\n position: absolute;\n"), "{css}");
}
#[test]
fn fill_and_type_layers_describe_their_colour_and_font() {
let doc = session("Box").active().unwrap().doc.clone();
// Photoshop: a solid colour gives `background-color` (a fill layer without a shape covers the
// canvas).
let fill = Layer::new("Card", LayerContent::Fill(Fill::Solid(photocraft_color::Color::rgb(1.0, 120.0 / 255.0, 30.0 / 255.0))));
assert_eq!(
rule(&doc, 4, &fill).unwrap(),
".Card {\n background-color: rgb(255, 120, 30);\n position: absolute;\n left: 0px;\n top: 0px;\n width: 400px;\n height: 300px;\n z-index: 4;\n}\n"
);
// A type layer: size, family, colour, auto leading and alignment, then only its position
// (Photoshop writes no size for point text). Its position is where its pixels are.
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
cache.fill_rect(Rect::new(49, 28, 120, 52), &[0.0, 0.0, 0.0, 1.0]);
let text = photocraft_doc::TextLayer {
font_family: "Inter".into(),
size_pt: 24.0,
color: photocraft_color::Color::rgb(0.0, 0.0, 0.0),
cache: Some(cache),
..Default::default()
};
let title = Layer::new("Title", LayerContent::Text(text));
let css = rule(&doc, 3, &title).unwrap_or_default();
assert_eq!(
css,
".Title {\n font-size: 24px;\n font-family: \"Inter\";\n color: rgb(0, 0, 0);\n line-height: 1.2;\n text-align: left;\n position: absolute;\n left: 49px;\n top: 28px;\n z-index: 3;\n}\n"
);
// Groups and adjustments have no CSS.
let group = Layer::group("Group 1", Vec::new());
assert!(rule(&doc, 5, &group).is_none());
}
#[test]
fn numbers_and_names_are_written_as_photoshop_does() {
assert_eq!(number(48.9374), "48.937");
assert_eq!(number(27.6), "27.6");
assert_eq!(number(100.0), "100");
assert_eq!(number(-0.0001), "0");
assert_eq!(number(f64::NAN), "0");
assert_eq!(class_name("My Box 2"), "My_Box_2");
assert_eq!(class_name(""), "layer");
}
#[test]
fn bad_params_and_layers_without_css_are_errors() {
let mut s = session("Box");
assert!(s.execute(ID, json!({"layer": "x"})).is_err());
assert!(s.execute(ID, json!({"layer": 999_999})).is_err());
assert!(s.execute(ID, json!([])).is_err());
s.execute("layer.new.group", json!({})).unwrap();
assert!(s.execute(ID, json!({})).is_err(), "a group alone has no CSS");
let mut empty = Session::new();
assert!(empty.execute(ID, json!({})).is_err(), "no document");
}
+1
View File
@@ -110,6 +110,7 @@ pub use cmd::history_select_cmds;
pub use cmd::history_source_cmds;
pub use cmd::image_cmds;
pub use cmd::layer_copy_cmds;
pub use cmd::layer_css_cmds;
pub use cmd::layer_label_cmds;
pub use cmd::layer_list_cmds;
pub use cmd::layer_mask_props_cmds;
+1
View File
@@ -258,6 +258,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["Layer", "New"], "---", None, "---"),
(&["Layer", "New"], "Layer via Copy", Some("Cmd+J"), "layer.new.layerViaCopy"),
(&["Layer", "New"], "Layer via Cut", Some("Cmd+Shift+J"), "layer.new.layerViaCut"),
(&["Layer"], "Copy CSS", None, "layer.copyCSS"),
(&["Layer"], "Duplicate Layer…", None, "layer.duplicate"),
(&["Layer", "Delete"], "Layer", None, "layer.delete"),
(&["Layer", "Delete"], "Hidden Layers", None, "layer.delete.hiddenLayers"),
+8
View File
@@ -86,6 +86,14 @@ fn invoke_early_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str,
if id == "help.checkForUpdates" {
return Some(crate::updates_ui::check(app, ctx, params.clone()));
}
// Layer › Copy CSS: the engine writes the CSS, the clipboard is the shell's (#9372).
if id == photocraft_engine::layer_css_cmds::ID {
return Some(app.run(id, params.clone()).inspect(|r| {
if let Some(css) = r.get("css").and_then(Value::as_str) {
ctx.copy_text(css.to_string());
}
}));
}
if id == "ui.symmetryTransform" {
return Some(crate::symmetry_ui::begin(app).map(|_| Value::Null));
}
+1 -1
View File
@@ -7,7 +7,7 @@ use crate::menu_catalog::CATALOG;
use crate::menus::is_live;
/// Minimum number of live catalog items. Raise it when parity grows; never lower it.
pub const FLOOR: usize = 661;
pub const FLOOR: usize = 662;
/// One top-level menu's coverage.
#[derive(Clone, Debug, serde::Serialize)]
+25
View File
@@ -550,3 +550,28 @@ fn proof_setup_presets_and_checkmarks() {
let params = crate::filter_dialog::parse_spec(spec.params);
assert!(matches!(&params[0].kind, crate::filter_dialog::Kind::Choice { options, .. } if options[0] == "srgb" && !options.iter().any(|v| v.contains('/'))));
}
/// Layer › Copy CSS puts the layer's CSS on the clipboard, as Photoshop's does (#9372).
#[test]
fn copy_css_puts_the_layers_css_on_the_clipboard() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.session.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
app.session.execute("layer.new.layer", json!({"name": "Box"})).unwrap();
app.session
.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(100, 80, 300, 220), &[0.2, 0.4, 0.8, 1.0]);
Ok(())
})
.unwrap();
app.sync_views();
assert!(crate::menus::menu_items(&app).iter().any(|i| i.id == "layer.copyCSS" && i.path == ["Layer"]), "Layer › Copy CSS");
let ctx = egui::Context::default();
let mut result = None;
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
result = Some(invoke(&mut app, ui.ctx(), "layer.copyCSS", json!({})));
});
out.textures_delta.clear();
let css = result.unwrap().unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(".Box {\n background-image: url(\"Box.png\");\n"), "{css}");
assert_eq!(out.platform_output.commands, [egui::OutputCommand::CopyText(css)]);
}