From 62f1abe5bd34b43942543d6802ab36ec324a8f93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:58:46 -0800 Subject: [PATCH] Scripts: collection reads look up names such as -1 and 1.5 The indexer hands a key that is the text of a number to the collection as a number, so pageItems["-1"] and documents["1.5"] read as positions and gave undefined, and "-1" in pageItems was false, even when getByName("-1") found the object. pageItems and documents now take only array indices as positions and look up any other number by its text as a name, giving undefined when nothing has it. index(key) still takes a number as a position. --- crates/engine/src/script/dom.rs | 70 ++++++++++++++++++++------- crates/engine/src/tests/script_dom.rs | 30 ++++++++++++ docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 4 files changed, 87 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 46ca2824d4..c61dc66b7e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -840,11 +840,19 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer { Ok(host_ref("Application", &[])) } -/// `documents[i]`, and `documents["name"]` as `getByName` reads it. +/// `documents[i]`, and `documents["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no document has it. fn docs_at(h: &Host, a: &[Data]) -> Answer { let s = h.session.borrow(); let at = match arg(a, 1) { - Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), + Data::Number(n) => match position(*n) { + Some(i) => s.documents().get(i), + None => { + let name = vectorcraft_js::number_to_string(*n); + s.documents().iter().find(|d| d.title() == name) + } + }, Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) { None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), found => found, @@ -864,10 +872,11 @@ fn docs_by_name(h: &Host, a: &[Data]) -> Answer { fn docs_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => docs_by_name(h, a), - Data::Number(_) => match docs_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let s = h.session.borrow(); + let st = position(*n).and_then(|i| s.documents().get(i)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + Ok(doc_ref(h, st.uid)) + } _ => Err(HostError::Type("give a name or an index".into())), } } @@ -1453,27 +1462,49 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } -/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. +/// The position an indexer key names when it is an array index, 0 to 2^32 - 2. +fn position(n: f64) -> Option { + whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) +} + +/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no object has it. fn items_at(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - if let Data::String(_) = arg(a, 1) { - return match items_by_name(h, a) { + match arg(a, 1) { + Data::String(_) => match items_by_name(h, a) { Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), r => r, - }; + }, + Data::Number(n) => match position(*n) { + Some(i) => Ok(item_at(h, doc, i)), + None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }, + }, + _ => Ok(Data::Undefined), } - let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +/// The object at position `i` of `pageItems`, or `undefined` past the end. +fn item_at(h: &Host, doc: Doc, i: usize) -> Data { + with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))) } fn items_by_name(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + items_named(h, doc, name) +} + +/// The first object of `pageItems` named `name`, or `Not found`. +fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { let ids = page_items(h, st); 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())); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -1481,10 +1512,13 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer { fn items_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), - Data::Number(_) => match items_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let doc = items_doc(h, a)?; + match position(*n).map(|i| item_at(h, doc, i)) { + None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())), + Some(d) => Ok(d), + } + } _ => Err(HostError::Type("give a name or an index".into())), } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c1aa77e6a6..a8a0615354 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1753,6 +1753,36 @@ fn a_collection_read_with_a_name_gives_the_named_object() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); } +/// A collection read with a name that is the text of a number but not an array index, such as `-1` +/// or `1.5`, gives the object of that name, and `undefined` when nothing has it; array indices stay +/// positions, and `index` still takes a number as a position. +#[test] +fn a_collection_read_with_a_number_name_that_is_not_an_index_gives_the_named_object() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "NaN"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = [];\ + vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p.NaN === p.getByName('NaN'), 'NaN' in p]);\ + vc.log([p['1.5'] === undefined, '1.5' in p, p[0].name, p['1'].name]);\ + try { p.index(-1); } catch (e) { m.push(e.message); }\ + var t = new DocumentPreset(); t.title = '1.5'; var d = app.documents.addDocument('Print', t);\ + var ds = app.documents; vc.log([ds['1.5'] === d, '1.5' in ds, ds[1.5] === d, ds['-1'] === undefined, '-1' in ds]);\ + try { ds.index(1.5); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!( + out, + vec![ + json!([true, true, true, true, true]), + json!([true, false, "NaN", "-1"]), + json!([true, true, true, true, false]), + json!(["Not found", "Not found"]), + ] + ); +} + /// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or /// locked layer throw and the run changes nothing, while its name and note still change; an object /// that is hidden or locked itself takes them. diff --git a/docs/mcp.md b/docs/mcp.md index 1bbe49574d..2aa1994574 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2848,7 +2848,10 @@ other files through `$`: [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too - (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` + (VectorCraft's own rule). A read with the text of a number that is not an array index, such as + `pageItems["-1"]`, `pageItems[1.5]` or `documents["NaN"]`, looks for an object of that name and gives `undefined` + when nothing has it, and `"-1" in pageItems` is true when an object has that name; `index(key)` takes a number as + a position only (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` take a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a54102e675..8ba494f9bb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1089,7 +1089,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - 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: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.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`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`). A script can check a member with `hasOwnProperty`, and can read a collection by name (a name that is the text of a number, such as `-1` or `1.5`, included) and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`.