Scripts: layers and groups give their own text frames

Layer.textFrames and GroupItem.textFrames threw "not available yet".
They now give a TextFrames collection with the members of the
document's: length, [i], index, getByName, add, pointText, areaText,
pathText and removeAll. It lists the type directly in the layer or
group, topmost first, as the layer's other collections do, and new type
goes on top of the layer's or group's contents whatever the current
layer. A hidden or locked layer or group throws and changes nothing.

text.create takes a parent: a shown, unlocked layer or group that the
new type goes on top of, whatever the drawing mode. Area type and type
on a path are moved there with node.move in the same step.

Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo
2026-11-24 17:55:12 -08:00
parent d7dd4464d9
commit 2356ffe747
7 changed files with 229 additions and 39 deletions
+38 -3
View File
@@ -155,7 +155,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
@@ -885,7 +885,38 @@ fn path_create(s: &mut Session, p: &Value) -> Result<Value> {
add_look(s, "Pen", path_kind(path, None), look, None)
}
/// The shown, unlocked layer or group `text.create`'s `parent` names, if it names one.
fn text_parent(s: &Session, p: &Value) -> Result<Option<NodeId>> {
const C: &str = "text.create";
let Some(parent) = object_param(p, "parent", C)? else { return Ok(None) };
let d = &s.doc()?.doc;
let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) };
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() {
return Err(bad(C, format!("{} is not a layer or group", parent.0)));
}
if !d.is_editable(parent) {
return Err(bad(C, "the layer or group is hidden or locked"));
}
Ok(Some(parent))
}
/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected.
fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result<Value> {
let id = s.edit("Type", |d, sel| {
let id = d.alloc_id();
let mut n = Node::new(id, kind);
NewArt::plain(Appearance::default()).apply(d, &mut n);
super::object::align_new_object(d, &mut n);
n.bbox_angle = bbox_angle;
d.insert(Some(parent), usize::MAX, n)?;
sel.set([id]);
Ok(id)
})?;
Ok(json!({ "id": id.0 }))
}
fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
let parent = text_parent(s, p)?;
let x = f64_req(p, "x", "text.create")?;
let y = f64_req(p, "y", "text.create")?;
super::paint::check_keep_model(p, "text.create")?;
@@ -922,8 +953,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
// Lays the text out (and sizes an Auto Size frame).
super::typecmd::refresh_bounds(&mut t);
}
let made =
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?;
let made = match parent {
Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?,
None => {
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?
}
};
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
let made = super::typecmd::with_bounds(s, id, made);
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
+24 -5
View File
@@ -12,8 +12,8 @@
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's
//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the
//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's
//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
//! hold every group or compound path at any depth, in the order of the document's `pageItems`.
//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes
//! a sublayer on top of that layer's contents. The new layer becomes the current one.
@@ -65,6 +65,8 @@ enum Kind {
Group,
/// Compound paths (`CompoundPathItem`).
Compound,
/// Type (`TextFrame`), whose collection's other members are in `text.rs`.
Text,
}
impl Kind {
@@ -73,6 +75,7 @@ impl Kind {
Kind::Any => "PageItems",
Kind::Group => "GroupItems",
Kind::Compound => "CompoundPathItems",
Kind::Text => "TextFrames",
}
}
@@ -81,6 +84,7 @@ impl Kind {
Kind::Any => typename(n).is_some(),
Kind::Group => typename(n) == Some("GroupItem"),
Kind::Compound => typename(n) == Some("CompoundPathItem"),
Kind::Text => typename(n) == Some("TextFrame"),
}
}
}
@@ -845,6 +849,20 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Compound)
}
fn held_text(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Text)
}
/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists.
pub(super) fn text_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
art_scope(h, d, Kind::Text.class())
}
/// The type objects directly in `container`, topmost first.
pub(super) fn text_list(h: &Host, st: &DocState, container: NodeId) -> Result<Rc<Vec<NodeId>>> {
art_list(h, st, Kind::Text, Some(container))
}
// ---- GroupItem and CompoundPathItem ----
fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result<Item> {
@@ -897,8 +915,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> {
("pageItems", get(l, held_page_items)),
("groupItems", get(l, held_groups)),
("compoundPathItems", get(l, held_compounds)),
("textFrames", get(l, held_text)),
]);
m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
m
}
"CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]),
@@ -1320,6 +1339,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("pageItems", get(l, held_page_items)),
("groupItems", get(l, held_groups)),
("compoundPathItems", get(l, held_compounds)),
("textFrames", get(l, held_text)),
("zOrderPosition", get(l, layer_z_position)),
("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)),
("isIsolated", get(l, layer_is_isolated)),
@@ -1328,8 +1348,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("zOrder", method(l, layer_z_order)),
]);
layer.extend(
["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"]
.map(|m| later(l, "Layer", m)),
["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)),
);
vec![
class("Layer", None, layer, None),
+70 -26
View File
@@ -1,4 +1,4 @@
//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its
//! Type in the script object model: the `textFrames` of a document, a layer and a group, each `TextFrame`, the `TextRange` of its
//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and
//! `paragraphAttributes`, and `app.textFonts`, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/>,
@@ -7,6 +7,9 @@
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/> describe them.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`,
//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden
//! or locked layer or group throws.
//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so
//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves
//! out to the whole character. One item of `characters` is one code point.
@@ -1231,32 +1234,46 @@ fn frame_ids(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
ids
}
/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists.
fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option<NodeId>), HostError> {
super::layers::text_scope(h, arg(a, 0))
}
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "TextFrames")
Ok(frames_scope(h, a)?.0)
}
/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those
/// directly in a layer or group, topmost first.
fn listed(h: &Host, st: &DocState, container: Option<NodeId>) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
match container {
None => Ok(frame_ids(h, st)),
Some(c) => super::layers::text_list(h, st, c),
}
}
fn frames_length(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64)))
let (doc, c) = frames_scope(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64)))
}
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
let (doc, c) = frames_scope(h, a)?;
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
}
fn frames_at(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
}
fn frames_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st);
let ids = listed(h, st, c)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -1284,29 +1301,40 @@ fn vertical_of(d: &Data) -> std::result::Result<bool, HostError> {
}
}
/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`.
fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer {
/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on
/// top of the contents of `container` when there is one.
fn point_text(h: &Host, (doc, container): (Doc, Option<NodeId>), anchor: Option<[f64; 2]>, vertical: bool) -> Answer {
let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?;
let (_, r) =
on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?;
let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical});
if let Some(c) = container {
check_open(h, doc, c)?;
if let Some(o) = params.as_object_mut() {
o.insert("parent".into(), json!(c.0));
}
}
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &params))?;
new_ref(h, doc, result_id(&r))
}
/// The error for a layer or group that takes no new type.
const SHUT_CONTAINER: &str = "the layer or group is hidden or locked";
/// `add()`: empty point type at the origin.
fn frames_add(h: &Host, a: &[Data]) -> Answer {
point_text(h, frames_doc(h, a)?, None, false)
point_text(h, frames_scope(h, a)?, None, false)
}
/// `pointText(anchor, orientation?)`.
fn frames_point_text(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let scope = frames_scope(h, a)?;
let anchor = point(arg(a, 1), "anchor")?;
point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?)
point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?)
}
/// Turns the path `d` names into area type or type on a path with `text.createInPath`.
/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves
/// it on top of the contents of the collection's layer or group when there is one.
fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, container) = frames_scope(h, a)?;
if handle_of(arg(a, 1), "PathItem").is_none() {
return Err(HostError::Type("textPath must be a PathItem".into()));
}
@@ -1321,8 +1349,23 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
let vertical = vertical_of(arg(a, orientation))?;
let mode = if on_path { "onPath" } else { "area" };
let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical});
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
new_ref(h, doc, result_id(&r))
let Some(c) = container else {
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
return new_ref(h, doc, result_id(&r));
};
check_open(h, doc, c)?;
let id = super::atomically(h, |h| {
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
let id = result_id(&r).ok_or_else(|| HostError::Error("the command made no object".into()))?;
super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?;
Ok(id)
})?;
new_ref(h, doc, Some(id))
}
/// Refuses a hidden or locked layer or group as the place for new type.
fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> {
if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) }
}
/// `areaText(textPath, orientation?, baseFrame?, postFix?)`.
@@ -1335,15 +1378,16 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
in_path(h, a, true, &[2, 3, 5, 6])
}
/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first.
/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or
/// locked one stops it first.
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let (ids, refused) = with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st);
let ids = listed(h, st, c)?;
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
(ids, refused)
});
Ok::<_, HostError>((ids, refused))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
+87
View File
@@ -582,6 +582,93 @@ fn type_made_with_a_large_id_is_the_new_type() {
assert_eq!(plain(&s, NodeId(big)), "");
}
/// A script that builds a layer `base` holding type `back`, a group `g` (type `g-text` and a
/// group `gg` holding type `gg-text`) and type `front`, a sublayer `sub` of it holding type
/// `sub-text`, and a layer `other` holding type `other-text`, which it leaves current.
const NESTED_TYPE: &str = "var d = app.activeDocument, L0 = d.layers[0]; L0.name = 'base';\
function put(c, name, y) { var t = c.textFrames.pointText([20, y]); t.contents = name; t.name = name; return t; }\
put(L0, 'back', 20); var g = L0.groupItems.add(); g.name = 'g'; put(g, 'g-text', 40);\
var gg = g.groupItems.add(); gg.name = 'gg'; put(gg, 'gg-text', 60); put(L0, 'front', 80);\
var sub = L0.layers.add(); sub.name = 'sub'; put(sub, 'sub-text', 100);\
var L1 = d.layers.add(); L1.name = 'other'; put(L1, 'other-text', 120); d.activeLayer = L1;\
function names(c) { var a = []; for (var i = 0; i < c.length; i++) a.push(c[i].name); return a.join(','); }";
#[test]
fn a_layers_and_a_groups_text_frames_list_only_their_own_type() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let out = log(
&mut s,
&format!(
"{NESTED_TYPE} vc.log([names(L0.textFrames), names(g.textFrames), names(sub.textFrames), names(L1.textFrames)]);\
vc.log([L0.textFrames.typename, L0.textFrames.parent.name, g.textFrames.parent.typename, g.textFrames.parent.name]);\
vc.log([L0.textFrames.getByName('front').name, L0.textFrames.index(1).name, L0.textFrames[2] === undefined]);\
vc.log(d.textFrames.length);"
),
);
assert_eq!(out[0], json!(["front,back", "g-text", "sub-text", "other-text"]));
assert_eq!(out[1], json!(["TextFrames", "base", "GroupItem", "g"]));
assert_eq!(out[2], json!(["front", "back", true]));
assert_eq!(out[3], json!(6));
// Type inside the layer's group or sublayer is not the layer's own.
let e = failure(&mut s, &format!("{NESTED_TYPE} L0.textFrames.getByName('gg-text');"));
assert!(e.contains("Not found"), "{e}");
}
#[test]
fn text_frames_of_a_layer_or_group_put_new_type_in_it() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 50})).unwrap();
let before = undo_steps(&s);
// The rectangle is in the first layer, which becomes `base`; `other` is current while the
// collections of `base` and `g` add type.
let out = log(
&mut s,
&format!(
"var rect = app.activeDocument.pageItems[0]; {NESTED_TYPE}\
var t = L0.textFrames.add(); t.name = 'added';\
vc.log([t.layer.name, L0.pageItems[0].name, t.kind, d.activeLayer.name]);\
var gt = g.textFrames.add(); gt.name = 'g-added'; vc.log([gt.parent.name, g.pageItems[0].name]);\
var at = g.textFrames.areaText(rect); at.name = 'area'; vc.log([at.parent.name, g.pageItems[0].name, at.kind]);\
g.textFrames.removeAll(); vc.log([names(g.pageItems), names(L0.textFrames)]);"
),
);
assert_eq!(out[0], json!(["base", "added", "TextType.POINTTEXT", "other"]));
assert_eq!(out[1], json!(["g", "g-added"]));
assert_eq!(out[2], json!(["g", "area", "TextType.AREATEXT"]));
// removeAll takes the group's own type and leaves the type inside its group.
assert_eq!(out[3], json!(["gg", "added,front,back"]));
assert_eq!(undo_steps(&s), before + 1);
// A locked layer and a hidden group take no new type, and the run changes nothing.
let before = undo_steps(&s);
let e = failure(&mut s, &format!("{NESTED_TYPE} L0.locked = true; L0.textFrames.add();"));
assert!(e.contains("hidden or locked"), "{e}");
let e = failure(&mut s, &format!("{NESTED_TYPE} g.hidden = true; g.textFrames.pointText([5, 5]);"));
assert!(e.contains("hidden or locked"), "{e}");
assert_eq!(undo_steps(&s), before);
}
#[test]
fn text_create_puts_type_in_the_layer_or_group_it_names() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let group = s.execute("object.newGroup", &json!({})).unwrap()["id"].as_u64().unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
// A new layer is current, and a locked one takes no type.
let locked = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().map(NodeId).unwrap();
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
let before = undo_steps(&s);
for bad in [json!("1"), json!(rect), json!(9999), json!(locked.0)] {
assert!(s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": bad})).is_err(), "{bad}");
}
assert_eq!(undo_steps(&s), before);
let id = s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": group})).unwrap()["id"].as_u64().unwrap();
let d = &s.active().unwrap().doc;
assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(group)));
assert_eq!(undo_steps(&s), before + 1);
}
#[test]
fn text_members_refuse_objects_of_other_classes() {
let (mut s, _) = doc_with("abc");
@@ -109,7 +109,7 @@ const INSIDE: &[(&str, &str)] = &[
dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \
locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \
preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \
textFrames= typename visible visible= zOrder zOrderPosition",
typename visible visible= zOrder zOrderPosition",
),
("Layers.", "prototype"),
("Layers.prototype.", "add constructor getByName index length parent removeAll typename"),
@@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[
(
"GroupItem.prototype.",
"clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \
rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=",
rasterItems rasterItems= symbolItems symbolItems= textFrames",
),
("GroupItems.", "prototype"),
("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll typename"),
+7 -2
View File
@@ -620,7 +620,7 @@ change nothing; an omitted or null `id` keeps the default. Commands that need an
`path` keys of `appearance.transfer`, `appearance.copyFrom`, `layer.move`, the `livePaint.*` commands and
`text.createInPath`) refuse a value that is not a non-negative integer with "`id` must be a whole number", naming the
key, and report a key left out or null as missing. The optional `group` of `livePaint.fill` and `parent` of
`node.move` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when
`node.move` and `text.create` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when
`group` is left out or null, and reports a missing group only when both are left out. A command that needs a number
(`x` of `shape.rectangle`, `pos` of `guide.add`, `index`, `x` and `y` of the `object.mesh.*` and
`object.envelope.setMeshPoint` point commands, and the others like them) refuses a value that is not a number with
@@ -2772,7 +2772,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot
with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn
a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation`
value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not
available yet. A `TextFrame`
available yet. A `Layer` and a `GroupItem` have `textFrames` with the same members. VectorCraft's own rules for
them: they list the type objects directly in the layer or group, topmost first, and their `add()`, `pointText`,
`areaText` and `pathText` put the new type on top of the layer's or group's contents, whatever the current layer.
Point type goes there with `text.create`'s `parent`, which takes a shown, unlocked layer or group and ignores the
drawing mode, and area type and type on a path go there with `node.move`, in the same undo step. A hidden or
locked layer or group throws an error and changes nothing. A `TextFrame`
(https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`,
`AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`,
`createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to
+1 -1
View File
@@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Paths and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
- Scripts: `document.textFrames`, and the `textFrames` of a layer or group, which list the type directly in it and put new type on top of its contents (VectorCraft's own rule), make point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/, with https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ for the layer's and group's `textFrames`, describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.