Scripts: layer collections go stale after Revert, addDocument keeps the built-in layout

- A layer's, group's or compound path's layers, pageItems, groupItems,
  compoundPathItems and pathItems read before File > Revert now throw instead
  of listing the loaded document's art under the same id.
- addDocument with a saved preset of the built-in preset's name lays out
  several artboards as the built-in preset does, with presetSettings over it.
- Layer.zOrderPosition reads the kept list of sibling layers.
- PathItems.parent is described as any container, and the docs say when
  PathPoint.remove() keeps the direct selection.
This commit is contained in:
dotCooCoo committed 2026-12-01 13:43:56 -08:00
1 parent d52d8ff354
commit fe36fe67d0
5 files changed
+93 -41

No files matched your search

+18 -14
View File
@@ -53,8 +53,8 @@
//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
//! error. A run that fails leaves the tool as it was.
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
//! in the object.
//! - `controlBounds` is the visible bounds, widened to take in the direction points of the paths
//! those bounds take in.
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
//! in view-number order, and none without one. View objects keep their window's identity when
//! windows are renumbered. The screen mode is the app's:
@@ -569,6 +569,15 @@ fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [f64; 5] {
[float(h.run), float(st.uid), high, low, float(st.reverts)]
}
/// The handle of a collection that lists the art of the layer, group or compound path `id` in the
/// document `uid`, with the document's revert count as [`node_handle`] gives it, so that a
/// collection read before File > Revert is stale.
fn scoped_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
let [high, low] = id_parts(id);
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
[float(h.run), float(uid), high, low, float(reverts)]
}
fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> {
let &[run, uid, high, low, reverts] = handle else { return None };
let doc = find_doc(h, run, uid)?;
@@ -1596,21 +1605,16 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
let full = first.clone().with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
let shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim()));
if shadowed {
// `file.new` would find the saved preset of that name first, so the name is left out
// and the built-in preset's settings, with `presetSettings` over them, go as params.
shadowed_by = Some(first.clone());
// `file.new` would find the saved preset of that name first: the built-in preset's
// settings go as params instead, under the ones `presetSettings` gives.
if let Value::Object(base) = first.to_json() {
for (k, v) in base.into_iter().filter(|(k, _)| !matches!(k.as_str(), "name" | "size" | "orientation" | "profile")) {
p.entry(k).or_insert(v);
}
}
} else {
p.insert("preset".into(), json!(first.name));
if let Value::Object(settings) = full.to_json() {
for key in BUILT_IN_SETTINGS {
if let Some(v) = settings.get(*key) {
p.insert((*key).into(), v.clone());
}
}
if let Value::Object(settings) = full.to_json() {
for key in BUILT_IN_SETTINGS {
if let Some(v) = settings.get(*key) {
p.insert((*key).into(), v.clone());
}
}
}
+15 -16
View File
@@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_
use super::{
Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard,
arg, boolean, class_text, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of,
item_ref, later, method, named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, returns, text, typed,
typename, whole, with_doc,
arg, boolean, class_text, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref,
later, method, named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, returns, text, typed, typename, whole,
with_doc,
};
use crate::script::{Host, Link};
use crate::{DocState, Document, NodeId, NodeKind};
@@ -294,9 +294,9 @@ fn layer_typename(h: &Host, a: &[Data]) -> Answer {
fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
let at = with_doc(h, doc, |_, st| {
let list = layer_list(&st.doc, st.doc.parent_of(id));
list.iter().position(|l| *l == id).map(|i| list.len() - i)
});
let list = layer_ids(h, st, st.doc.parent_of(id))?;
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
})?;
at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into()))
}
@@ -476,9 +476,9 @@ fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) };
match handle.as_slice() {
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
[run, uid, high, low] => {
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
[_, _, _, _, _] => {
// A collection read before its document was reverted is stale, as its layer is.
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
let (doc, id) = held_layer(h, doc, id)?;
Ok((doc, Some(id)))
}
@@ -530,8 +530,7 @@ fn layer_ids(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<N
fn layers_of(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
let [high, low] = id_parts(id);
Ok(host_ref("Layers", &[float(h.run), float(doc.uid), high, low]))
Ok(host_ref("Layers", &super::scoped_handle(h, doc.uid, id)))
}
fn layers_length(h: &Host, a: &[Data]) -> Answer {
@@ -622,9 +621,9 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) };
match handle.as_slice() {
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
[run, uid, high, low] => {
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
[_, _, _, _, _] => {
// A collection read before its document was reverted is stale, as its container is.
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let holds = with_doc(h, doc, |_, st| {
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
});
@@ -684,12 +683,12 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> R
/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle
/// names the container.
pub(super) fn is_scoped(a: &[Data]) -> bool {
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 4)
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5)
}
fn collection(h: &Host, kind: Kind, container: Option<NodeId>, uid: u64) -> Data {
match container {
Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1]]),
Some(c) => host_ref(kind.class(), &super::scoped_handle(h, uid, c)),
None => host_ref(kind.class(), &[float(h.run), float(uid)]),
}
}
+5 -6
View File
@@ -475,8 +475,7 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
/// The `pathItems` of the layer or group `id` in the document `uid`.
pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data {
let [high, low] = id_parts(id);
host_ref("PathItems", &[float(h.run), float(uid), high, low])
host_ref("PathItems", &super::scoped_handle(h, uid, id))
}
/// The document of a `PathItems` object, and the layer, group or compound path it lists the paths
@@ -485,9 +484,9 @@ fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option<
let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) };
match handle.as_slice() {
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)),
[run, uid, high, low] => {
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
[_, _, _, _, _] => {
// A collection read before its document was reverted is stale, as its container is.
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let holds = with_doc(h, doc, |_, st| {
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
});
@@ -2083,7 +2082,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
named(vec![
("typename", get(l, items_typename), typed("string")),
("length", get(l, items_length), typed("number")),
("parent", get(l, items_parent), typed("Document")),
("parent", get(l, items_parent), typed("*")),
("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])),
("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])),
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
+44 -1
View File
@@ -1642,11 +1642,25 @@ fn add_document_starts_from_the_built_in_preset_when_a_saved_one_has_its_name()
#[test]
fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() {
let mut s = Session::new();
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap();
s.execute(
"file.newPresets.save",
&json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb", "artboardLayout": "row"}),
)
.unwrap();
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]);
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);");
assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset");
// Several artboards are laid out as the built-in preset lays them out when no saved preset
// has its name, and the title is kept.
let three = "var p = new DocumentPreset(); p.numArtboards = 3; p.title = 'Three';\
p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; p.artboardSpacing = undefined; var d = app.documents.addDocument('Print', p);\
var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); vc.log([d.name, r]);";
let out = log(&mut s, three);
let unshadowed = log(&mut Session::new(), three);
assert_eq!(out[0][0], json!("Three"));
assert_eq!(out[0][1].as_array().map(Vec::len), Some(3), "{out:?}");
assert_eq!(out, unshadowed, "the saved preset changes nothing");
}
#[test]
@@ -1967,6 +1981,23 @@ fn wrappers_go_stale_after_revert() {
}
}
/// A layer's collections read before File › Revert do not list the loaded document's art, even
/// where the loaded layer has the same id.
#[test]
fn a_layers_collections_read_before_a_revert_are_stale() {
let (mut s, ..) = doc();
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-lists");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
for list in ["pathItems", "pageItems", "groupItems", "compoundPathItems", "layers"] {
let source = format!(
"var d = app.activeDocument, c = d.layers[0].{list}; vc.log(c.length >= 0); d.pageItems[0].name = 'changed'; vc.run('file.revert');\
try {{ c.length; vc.log('ran'); }} catch (e) {{ vc.log('stale'); }} vc.log(d.layers[0].{list}.length >= 0);"
);
assert_eq!(log(&mut s, &source), vec![json!(true), json!("stale"), json!(true)], "{list}");
}
}
#[test]
fn remove_all_refuses_locked_art_before_deleting_anything() {
let (mut s, a, b) = doc();
@@ -2872,6 +2903,18 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() {
assert!(failure(&mut s, src).contains("only paths"), "{src}");
}
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
// Caught inside the run, the refused move leaves the object where it was and the compound
// path's members as they were.
for (make, to) in
[("d.groupItems.add()", "C"), ("d.groupItems.add()", "C.pathItems[0], ElementPlacement.PLACEBEFORE"), ("d.compoundPathItems.add()", "C")]
{
let src = format!(
"var d = app.activeDocument, C = d.compoundPathItems.getByName('C'), o = {make};\
try {{ o.move({to}); vc.log('moved'); }} catch (e) {{ vc.log(String(e).indexOf('only paths') >= 0); }}\
vc.log(o.parent.typename); vc.log(C.pathItems.length); vc.log(C.pathItems[0].parent.typename);"
);
assert_eq!(log(&mut s, &src), [json!(true), json!("Layer"), json!(2), json!("CompoundPathItem")], "{src}");
}
assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false"));
}
+11 -4
View File
@@ -3095,7 +3095,9 @@ through `$`:
tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers
panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was
deleted, that a named engine kept from an earlier run, or whose document was reverted with `file.revert`, throws
`Stale page item`. Layer objects also become stale after their document is reverted. `remove()` on an object that
`Stale page item`. Layer objects also become stale after their document is reverted, and so do the `layers`,
`pageItems`, `groupItems`, `compoundPathItems` and `pathItems` of a layer, group or compound path read before the
revert; the document's own collections stay usable. `remove()` on an object that
is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()`
when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on
a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard`
@@ -3318,9 +3320,14 @@ through `$`:
a path aligned to the pixel grid, or in an object that is, is written at each change, so its points
read as the grid snaps them.
Setting `closed` to true on a path with no points throws `Cannot close a path that has no points`.
Writing changes that added, removed or replaced points deselects the path's direct-selected anchors, even when the
path ends with as many points as before; changes that only move points or handles, change a point's type or set
`closed` keep them selected.
Writing changes that added or replaced points, or that removed points along with other such changes, deselects the
path's direct-selected anchors, even when the path ends with as many points as before. `PathPoint.remove()` on its
own keeps the rest of the direct selection: selected anchors after the removed point are renumbered and stay
selected, except that a selected segment that starts or ends at the removed point is deselected, and so is its other
anchor unless another selected segment still uses it. When every anchor left is selected and no segment is, the
path is selected as a whole. On a path aligned to the pixel grid, or in an object that is, which is written at each
change, the removal can clear the direct selection. Changes that
only move points or handles, change a point's type or set `closed` keep them selected.
`pathPoints`
(https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and
`removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`,