M13.7: Essential Graphics scripting hooks, Font and uniform Scale controls, Open in Essential Graphics

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-03 07:23:22 -04:00
co-authored by Claude Opus 5.5
parent 5aae82b05c
commit 558de71720
8 changed files with 462 additions and 26 deletions
+129 -16
View File
@@ -88,6 +88,14 @@ fn add_property(s: &mut Session, p: &Value) -> Result<Value> {
let group = p.get("group").and_then(Value::as_u64);
let index = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
let rename = str_p(p, "name").map(str::to_string);
// `as`: show the property as another control (Source Text as `font`, Scale as `scale`).
let as_type = match str_p(p, "as") {
None => None,
Some(a) => {
let t = ControlType::parse(a).ok_or_else(|| bad(C, format!("as: font|scale|text|color|slider|checkbox|point|angle|dropdown, not `{a}`")))?;
Some(t)
}
};
let mut added = vec![];
for (cid, lid, uid) in &targets {
let l = s.project.comp(*cid).and_then(|c| c.layer(*lid)).ok_or(EngineError::NoComp)?;
@@ -95,20 +103,32 @@ fn add_property(s: &mut Session, p: &Value) -> Result<Value> {
if control_type(pr).is_none() {
return Err(bad(C, format!("`{}` can't be added to Essential Graphics (unsupported property type)", pr.name)));
}
if s.project.comp(*cid).and_then(|c| c.essential.as_ref()).is_some_and(|e| e.control_for(*lid, *uid).is_some()) {
// The natural control needs no `as`.
let as_type = as_type.filter(|t| control_type(pr) != Some(*t));
if let Some(t) = as_type
&& !essential::can_show_as(pr, t)
{
return Err(bad(C, format!("`{}` can't be shown as a {} control", pr.name, t.label())));
}
if s.project.comp(*cid).and_then(|c| c.essential.as_ref()).is_some_and(|e| e.control_for_as(*lid, *uid, as_type).is_some()) {
continue;
}
added.push((*cid, *lid, *uid, rename.clone().unwrap_or_else(|| pr.name.clone())));
let name = rename.clone().unwrap_or_else(|| match as_type {
Some(ControlType::Font) => format!("{} Font", l.name),
_ => pr.name.clone(),
});
added.push((*cid, *lid, *uid, name, as_type));
}
let ids = s.edit("Add Property to Essential Graphics", None, |proj, st| {
if let Some((cid, ..)) = added.first() {
st.essential_primary.get_or_insert(*cid);
}
let mut ids = vec![];
for (k, (cid, lid, uid, name)) in added.iter().enumerate() {
for (k, (cid, lid, uid, name, as_type)) in added.iter().enumerate() {
let id = proj.alloc();
let eg = eg_of(proj, *cid)?;
insert(eg, EgControl { id, name: name.clone(), kind: EgKind::Property { layer: *lid, prop: *uid } }, group, index.map(|i| i + k), C)?;
let ctl = EgControl { id, name: name.clone(), kind: EgKind::Property { layer: *lid, prop: *uid }, as_type: *as_type };
insert(eg, ctl, group, index.map(|i| i + k), C)?;
ids.push(id);
}
Ok(ids)
@@ -120,6 +140,39 @@ fn control_type(pr: &effectcraft_project::Property) -> Option<ControlType> {
essential::control_type(pr)
}
/// A Font control's value for `prop.set`: `cur` (a Source Text value) with the font family,
/// style and size from `v` (`{font?, style?, size?}` or a family name). `None` when `cur` is
/// not text.
pub fn font_value(cur: &KV, v: &Value) -> Option<Value> {
let KV::Text(doc) = cur else { return None };
let mut d = (**doc).clone();
match v {
Value::String(f) => d.font = f.clone(),
Value::Object(o) => {
if let Some(f) = o.get("font").and_then(Value::as_str) {
d.font = f.to_string();
}
if let Some(st) = o.get("style").and_then(Value::as_str) {
d.style = st.to_string();
}
if let Some(z) = o.get("size").and_then(Value::as_f64) {
d.size = z.max(0.1);
}
}
_ => return None,
}
serde_json::to_value(&d).ok()
}
/// A control's value for agents: Font controls show `{font, style, size}`, the rest the
/// property's value.
fn value_json(ty: Option<ControlType>, v: &KV) -> Value {
match (ty, v) {
(Some(ControlType::Font), KV::Text(d)) => json!({"font": d.font, "style": d.style, "size": d.size}),
_ => v.to_json(),
}
}
/// Media Replacement for a footage layer.
fn add_media(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.addMedia";
@@ -137,7 +190,7 @@ fn add_media(s: &mut Session, p: &Value) -> Result<Value> {
if eg.flat().iter().any(|c| matches!(c.kind, EgKind::Media { layer } if layer == lid)) {
return Err(bad(C, "this layer already has a Media Replacement control"));
}
insert(eg, EgControl { id, name, kind: EgKind::Media { layer: lid } }, group, None, C)?;
insert(eg, EgControl { id, name, kind: EgKind::Media { layer: lid }, as_type: None }, group, None, C)?;
Ok(id)
})?;
Ok(json!({"control": id}))
@@ -150,7 +203,7 @@ fn add_group(s: &mut Session, p: &Value) -> Result<Value> {
let id = s.edit("Add Essential Graphics Group", None, |proj, st| {
st.essential_primary.get_or_insert(cid);
let id = proj.alloc();
insert(eg_of(proj, cid)?, EgControl { id, name, kind: EgKind::Group { children: vec![] } }, None, index, "essential.addGroup")?;
insert(eg_of(proj, cid)?, EgControl { id, name, kind: EgKind::Group { children: vec![] }, as_type: None }, None, index, "essential.addGroup")?;
Ok(id)
})?;
Ok(json!({"control": id}))
@@ -163,7 +216,13 @@ fn add_comment(s: &mut Session, p: &Value) -> Result<Value> {
let id = s.edit("Add Essential Graphics Comment", None, |proj, st| {
st.essential_primary.get_or_insert(cid);
let id = proj.alloc();
insert(eg_of(proj, cid)?, EgControl { id, name: "Comment".into(), kind: EgKind::Comment { text } }, group, None, "essential.addComment")?;
insert(
eg_of(proj, cid)?,
EgControl { id, name: "Comment".into(), kind: EgKind::Comment { text }, as_type: None },
group,
None,
"essential.addComment",
)?;
Ok(id)
})?;
Ok(json!({"control": id}))
@@ -262,6 +321,35 @@ fn edit_dropdown(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"prop": uid, "items": items}))
}
/// Composition ▸ Open in Essential Graphics.
fn open_in_eg(s: &mut Session, p: &Value) -> Result<Value> {
let cid = comp_id(s, p)?;
s.state.essential_primary = Some(cid);
s.bump();
s.events.push(crate::Event::Frontend { command: "window.panel".into(), params: json!({"panel": "essentialGraphics"}) });
let name = s.project.item(cid).map(|i| i.name.clone()).unwrap_or_default();
Ok(json!({"comp": cid.0, "name": name}))
}
/// Whether a property can be exposed (`property.canAddToMotionGraphicsTemplate`).
fn can_add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.canAdd";
let (cid, lid, uid) = super::prop::prop_ref(s, p, C)?;
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
let pr = l.props.find(uid).ok_or_else(|| bad(C, "no such property"))?;
let as_type = str_p(p, "as").and_then(ControlType::parse);
let ty = match as_type {
Some(t) if essential::can_show_as(pr, t) => Some(t),
Some(t) => return Ok(json!({"ok": false, "reason": format!("`{}` can't be shown as a {} control", pr.name, t.label())})),
None => control_type(pr),
};
let in_eg = super::match_path_of(&l.props, uid).is_some_and(|m| m.starts_with(essential::GROUP));
Ok(match ty {
Some(t) if !in_eg => json!({"ok": true, "type": t}),
_ => json!({"ok": false, "reason": format!("`{}` can't be added to Essential Graphics (unsupported property type)", pr.name)}),
})
}
fn solo_supported(s: &mut Session, p: &Value) -> Result<Value> {
let on = b_p(p, "on").unwrap_or(!s.state.essential_solo);
s.state.essential_solo = on;
@@ -299,8 +387,8 @@ fn control_json(project: &Project, cid: ItemId, c: &EgControl) -> Value {
"id": c.id, "name": c.name, "kind": "property", "layer": layer.0, "prop": prop,
"layerName": src.map(|(l, _)| l.name.clone()),
"path": src.and_then(|(l, _)| super::match_path_of(&l.props, *prop)),
"type": src.and_then(|(_, pr)| essential::control_type(pr)),
"value": src.map(|(_, pr)| pr.value_at(Tick::ZERO).to_json()),
"type": src.and_then(|(_, pr)| essential::effective_type(c, pr)),
"value": src.map(|(_, pr)| value_json(essential::effective_type(c, pr), &pr.value_at(Tick::ZERO))),
"missing": src.is_none(),
})
}
@@ -384,8 +472,8 @@ fn instance_json(s: &mut Session, p: &Value) -> Result<Value> {
"control": c.id, "name": c.name, "kind": kind,
"uid": pr.as_ref().map(|x| x.uid),
"path": pr.as_ref().and_then(|x| super::match_path_of(&l.props, x.uid)),
"value": pr.as_ref().map(|x| x.value_at(l.layer_time(t)).to_json()),
"type": pr.as_ref().and_then(essential::control_type).or((kind == "media").then_some(ControlType::Media)),
"value": pr.as_ref().map(|x| value_json(essential::effective_type(c, x), &x.value_at(l.layer_time(t)))),
"type": pr.as_ref().and_then(|x| essential::effective_type(c, x)).or((kind == "media").then_some(ControlType::Media)),
"overridden": pr.as_ref().is_some_and(|x| over.contains(&x.uid)),
}));
}
@@ -395,7 +483,7 @@ fn instance_json(s: &mut Session, p: &Value) -> Result<Value> {
/// Set an instance's value for a control (`value`, or `item` for Media Replacement).
fn set_override(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.set";
let (cid, lid, _) = instance(s, p, C)?;
let (cid, lid, src) = instance(s, p, C)?;
let control = control_p(p, C)?;
let uid = master_uid(s, cid, lid, control).ok_or_else(|| bad(C, format!("no control {control} on this instance")))?;
if let Some(item) = p.get("item") {
@@ -414,7 +502,13 @@ fn set_override(s: &mut Session, p: &Value) -> Result<Value> {
})?;
return Ok(json!({"control": control, "item": item.0}));
}
let mut q = json!({"comp": cid.0, "layer": lid.0, "prop": uid, "value": p.get("value").cloned().ok_or_else(|| bad(C, "missing `value` (or `item`)"))?});
let mut value = p.get("value").cloned().ok_or_else(|| bad(C, "missing `value` (or `item`)"))?;
let as_type = s.project.comp(src).and_then(|c| c.essential.as_ref()).and_then(|e| e.find(control)).and_then(|c| c.as_type);
if as_type == Some(ControlType::Font) {
let cur = s.project.comp(cid).and_then(|c| c.layer(lid)).and_then(|l| l.props.find(uid)).map(|pr| pr.value.clone()).unwrap_or(KV::Scalar(0.0));
value = font_value(&cur, &value).ok_or_else(|| bad(C, "a Font control takes {font?, style?, size?} or a font family name"))?;
}
let mut q = json!({"comp": cid.0, "layer": lid.0, "prop": uid, "value": value});
if let Some(m) = p.get("merge") {
q["merge"] = m.clone();
}
@@ -477,12 +571,21 @@ fn push_to_comp(s: &mut Session, p: &Value) -> Result<Value> {
let mut writes = vec![];
for (control, uid) in &ts {
let (Some(ctl), Some(pr)) = (eg.find(*control), l.props.find(*uid)) else { continue };
writes.push((ctl.kind.clone(), pr.clone()));
writes.push((ctl.kind.clone(), pr.clone(), ctl.as_type));
}
s.edit("Push Override Values to Source", None, |proj, _| {
let sc = proj.comp_mut(src).ok_or(EngineError::NoComp)?;
for (kind, pr) in &writes {
for (kind, pr, as_type) in &writes {
match kind {
// A Font control writes only the font (the source keeps its text and keys).
EgKind::Property { layer, prop } if *as_type == Some(ControlType::Font) => {
if let Some(target) = sc.layer_mut(*layer).and_then(|l| l.props.find_mut(*prop)) {
essential::merge_font(&mut target.value, &pr.value);
for k in &mut target.keys {
essential::merge_font(&mut k.value, &pr.value);
}
}
}
EgKind::Property { layer, prop } => {
let Some(inner) = sc.layer_mut(*layer) else { continue };
// Instance keys are in the precomp layer's time (= the source comp's time);
@@ -740,7 +843,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Property to Essential Graphics",
["Animation"],
None,
"{comp?, layer?, path?|prop?: uid (default: the selected properties), name?, group?: control id, index?}",
"{comp?, layer?, path?|prop?: uid (default: the selected properties), name?, group?: control id, index?, as?: font (Source Text font family/style/size) | scale (uniform Scale)}",
has_selected_props,
add_property
),
@@ -774,6 +877,16 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("essential.revert", "Revert", [], None, "{layer, control? (default: all overridden)}", has_instance, revert),
cmd!("effect.editDropdown", "Edit Dropdown Menu", [], None, "{layer, path?|prop?, items: [string]}", has_comp, edit_dropdown),
query!("essential.list", "Essential Graphics controls", "{comp?, supported?: bool}", list),
query!("essential.canAdd", "Can Add Property to Essential Graphics", "{layer, path|prop, as?} → {ok, type?, reason?}", can_add),
cmd!(
"comp.openInEssentialGraphics",
"Open in Essential Graphics",
["Composition"],
None,
"{comp?} → makes it the Essential Graphics panel's Primary composition and shows the panel",
has_comp,
open_in_eg
),
query!("essential.instance", "Essential Properties of a precomp layer", "{layer}", instance_json),
query!("essential.templateInfo", "Read a template's manifest", "{path}", template_info),
]
+2
View File
@@ -780,6 +780,8 @@ mod tests_effects;
#[cfg(test)]
mod tests_essential;
#[cfg(test)]
mod tests_essential_more;
#[cfg(test)]
mod tests_face;
#[cfg(test)]
mod tests_fidelity;
+1
View File
@@ -666,6 +666,7 @@ Composition
Pre-render... | render.preRender
Save Current Preview... | render.saveCurrentPreview
---
Open in Essential Graphics | comp.openInEssentialGraphics
Responsive Design — Time
Create Intro | comp.responsiveTime {"op":"intro"}
Create Outro | comp.responsiveTime {"op":"outro"}
+94
View File
@@ -0,0 +1,94 @@
//! Essential Graphics Font and uniform Scale controls, Composition ▸ Open in Essential Graphics.
use effectcraft_keyframe::Value as KV;
use effectcraft_project::essential::{self, ControlType};
use serde_json::json;
use crate::{Event, Session};
#[test]
fn font_and_scale_controls_override_per_instance() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Title", "width": 64, "height": 64, "frameRate": 30, "duration": 1})).unwrap();
let title = s.active_comp_id().unwrap();
let text = s.execute("layer.newText", json!({"text": "Hello"})).unwrap()["layer"].as_u64().unwrap();
// Source Text: as text and as font; Scale as one slider.
let t = s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText"})).unwrap()["controls"][0].as_u64().unwrap();
let f = s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font"})).unwrap()["controls"][0].as_u64().unwrap();
let sc = s.execute("essential.addProperty", json!({"layer": text, "path": "transform/scale", "as": "scale"})).unwrap()["controls"][0].as_u64().unwrap();
// Adding the same font control again is a no-op; opacity can't be a font.
assert!(
s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font"})).unwrap()["controls"].as_array().unwrap().is_empty()
);
assert!(s.execute("essential.addProperty", json!({"layer": text, "path": "transform/opacity", "as": "font"})).is_err());
assert_eq!(s.execute("essential.canAdd", json!({"layer": text, "path": "transform/opacity", "as": "font"})).unwrap()["ok"], false);
assert_eq!(s.execute("essential.canAdd", json!({"layer": text, "path": "transform/scale", "as": "scale"})).unwrap()["type"], "scale");
let l = s.execute("essential.list", json!({})).unwrap();
let types: Vec<&str> = l["controls"].as_array().unwrap().iter().map(|c| c["type"].as_str().unwrap()).collect();
assert_eq!(types, ["text", "font", "scale"]);
assert!(l["controls"][1]["value"]["size"].as_f64().unwrap() > 0.0);
let eg = s.project.comp(title).unwrap().essential.clone().unwrap();
assert_eq!(eg.find(f).unwrap().as_type, Some(ControlType::Font));
// Survives save / load (serde).
let j = serde_json::to_value(&eg).unwrap();
assert_eq!(serde_json::from_value::<essential::EssentialGraphics>(j).unwrap(), eg);
// An instance: change the text, then the font and the scale.
s.execute("comp.new", json!({"name": "Main", "width": 64, "height": 64, "frameRate": 30, "duration": 1})).unwrap();
let inst = s.execute("layer.addItem", json!({"item": title.0})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.select", json!({"layers": [inst]})).unwrap();
s.execute("essential.set", json!({"layer": inst, "control": t, "value": "Bye"})).unwrap();
s.execute("essential.set", json!({"layer": inst, "control": f, "value": {"font": "Serif Test", "size": 40}})).unwrap();
s.execute("essential.set", json!({"layer": inst, "control": sc, "value": 50})).unwrap();
let i = s.execute("essential.instance", json!({"layer": inst})).unwrap();
assert_eq!(i["controls"][1]["value"]["font"], "Serif Test");
assert_eq!(i["controls"][1]["value"]["size"], 40.0);
assert_eq!(i["controls"][1]["overridden"], true);
assert_eq!(i["controls"][2]["type"], "scale");
assert_eq!(i["controls"][2]["value"][0], 50.0);
assert_eq!(i["controls"][2]["value"][1], 50.0);
// What the instance renders: the overridden text with the overridden font, scaled.
let layer = s.active_comp().unwrap().layer(effectcraft_project::LayerId(inst)).unwrap().clone();
let over: Vec<essential::Override> = {
let g = essential::group(&layer).unwrap();
let mut v = vec![];
g.walk("", &mut |_, p| {
if let Some(c) = essential::control_of(&p.match_id) {
v.push(essential::Override { control: c, value: p.value.clone() });
}
});
v
};
let p = essential::with_overrides(&s.project, title, &over).unwrap();
let src = p.comp(title).unwrap().layer(effectcraft_project::LayerId(text)).unwrap();
match src.props.prop("text/sourceText").map(|x| &x.value) {
Some(KV::Text(d)) => assert_eq!((d.text.as_str(), d.font.as_str(), d.size), ("Bye", "Serif Test", 40.0)),
o => panic!("{o:?}"),
}
// Push to Comp with only the font: the source keeps its own text.
s.execute("essential.revert", json!({"layer": inst, "control": t})).unwrap();
s.execute("essential.pushToComp", json!({"layer": inst, "control": f})).unwrap();
let srcl = s.project.comp(title).unwrap().layer(effectcraft_project::LayerId(text)).unwrap();
match srcl.props.prop("text/sourceText").map(|x| &x.value) {
Some(KV::Text(d)) => assert_eq!((d.text.as_str(), d.font.as_str()), ("Hello", "Serif Test")),
o => panic!("{o:?}"),
}
}
#[test]
fn open_in_essential_graphics_sets_the_primary_comp() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "A", "width": 32, "height": 32, "duration": 1})).unwrap();
let a = s.active_comp_id().unwrap();
s.execute("comp.new", json!({"name": "B", "width": 32, "height": 32, "duration": 1})).unwrap();
s.drain_events();
let r = s.execute("comp.openInEssentialGraphics", json!({"comp": a.0})).unwrap();
assert_eq!(r["name"], "A");
assert_eq!(s.state.essential_primary, Some(a));
assert!(
s.drain_events()
.iter()
.any(|e| matches!(e, Event::Frontend { command, params } if command == "window.panel" && params["panel"] == "essentialGraphics"))
);
assert_eq!(s.execute("essential.list", json!({})).unwrap()["name"], "A");
}