Files
Graphite/node-graph/nodes/text/src/json.rs
Keavon Chambers 2090e9979a Make the data model use Item and List types universally, with nodes authored as rank-polymorphic kernels (#4335)
* Add rank polymorphism node audit classifying all 271 nodes

* Implement StaticType for Item<T>

* Generate Item and mapped List wire variants for nodes declaring an Item<T> primary input

* Migrate nine nodes to Item element-wise kernels, dissolving the blending trait boilerplate

* Document the Item kernel implementation and staging plan

* Route Item<Vector> through TaggedValue::TypeDefault

* Add executor integration tests covering the Item and List wire variants

* Collapse element-wise Item/List wire pairs to the List form for conversion insertion

* Migrate sixteen vector modifier nodes to Item element-wise kernels

* Migrate Sample Image, Extend Image to Bounds, and Dehaze to Item element-wise kernels

* Fix bevel_with_transform test to actually exercise the transform attribute

* Implement From<T> for Item<T>

* Register PromoteNode rank adapters wrapping bare values into Item wires

* Insert PromoteNode adapters for Item/List wire pair fields in the preprocessor

* Define a real promote node backing the PromoteNode registry identifiers

* Zip ranked Item connectors by frame slot in the mapped element-wise variant

* Register ItemToListNode singleton raise adapters

* Resolve Item wires against List connectors by inserting promotion adapters at construction

* Rank the Offset Points distance connector and prove mixed-rank resolution end-to-end

* Implement Clampable for Item and List wires with per-variant clamp bounds

* Rank the Round Corners radius connector, exercising hard bounds on a ranked wire

* Implement ApplyTransform for Item

* Add Item wire implementations to the Transform node, keeping rank-0 chains rank 0

* Detect element-wise nodes by lazy primary connectors declaring Output = Item

* Convert Transform to an Item kernel with ranked parameters, delivering the broadcast milestone

* Rename Apply Transform to Bake Transform, baking item transforms on Vector, DAffine2, and DVec2

* Promote bare wires onto Item connectors at resolution via WrapItemNode adapters

* Rank the numeric, vector, and boolean parameters across the migrated element-wise nodes

* Rank the enum, integer, and seed parameters, registering their rank adapters via a consolidated macro

* Amend the audit with the DashPattern value type resolution

* Migrate the string family to Item element-wise kernels

* Unwrap Item wires into bare legacy connectors at resolution via UnwrapItemNode adapters

* Shadow owned node parameters in bodies instead of mut in signatures

* Migrate the math family and string measure nodes to Item element-wise kernels

* Convert the comparison and clamp nodes to Item kernels, dropping unreachable &str rows

* Flat-map expander kernels returning List under the mapped variant's frame

* Migrate the expander nodes to Item kernels flat-mapping under the frame

* Remove the unused peel_list helper

* Rank the raster adjustment and blending kernels, recontextualizing shader nodes onto an Item stand-in

Migrate the 16 adjustment nodes, Mix, Color Overlay, and Gradient Map from whole-List kernels to rank-0 Item kernels, letting the macro derive the List-mapped (zip) variants. Move the Adjust and Blend per-element seams off List onto the element types (add the Raster<CPU> impls, drop the now-dead List impls).

Shader nodes keep their bodies verbatim: PerPixelAdjust re-emits the identical kernel against a transparent no_std Item stand-in, so every Item<T> connector and .element() call resolves to a zero-cost identity on the GPU while the uniform buffer stays bare repr(C). The macro peels Item off ranked uniform params, wraps the fetched texel and uniforms at the entry point, and unwraps the result. This drops the shader_node/Item incompatibility guard. Register rank adapters for the adjustment enums.

* Update the rank polymorphism roadmap for the landed shader-node and adjustments chunk

* Rename the GPU Item stand-in to ShaderItem, aliased as Item at its shader-node import sites

* Flip the vector shape generators to emit rank-0 Item<Vector>

The shape generators (Rectangle, Circle, Ellipse, Arc, Spiral, Polygon, Star, Arrow, Line, Grid, QR Code) each produced exactly one shape wrapped in a singleton List<Vector>. Emit Item<Vector> directly so they connect to the rank-0 content connector of the migrated Transform node. Downstream List consumers receive the value through the existing Item to List promotion.

Relax the element-wise validation so a `()` (generator) primary may return Item<T> without being element-wise. Adapt the Repeat on Points test, which still takes a List content connector, by raising the generator's Item output through a singleton wrapper node.

* Parse ranked Item<T> parameter defaults against the bare element type

A ranked `Item<T>` parameter's default value is a bare, unranked `T` (promoted to the wire at resolution), but the preprocessor was handed the wrapped `Item<T>` type and could not parse the literal, flooding the console with warnings and dropping the defaults. Key the field's default_type metadata off the peeled element type for concrete ranked parameters, leaving generic `Item<T>` primaries and skip_impl nodes untouched.

* Parse an element-wise primary's scalar default against the bare element type

An element-wise node's primary reports its default_type as the List wire form so an unconnected primary defaults to an empty list. But when the primary carries a scalar `#[default]` (such as Root's radicand), that literal must parse as a bare element, not a List. Key the primary's default_type off the bare element type when it has a Default value source, keeping the List form otherwise.

* Add the DashPattern value type for stroke dash sequences

Introduce a rank-0 DashPattern value type (a Vec<f64> of alternating dash and gap lengths) so a stroke's dash pattern is a single frameable value rather than a rank-1 List<f64>. Register it as an auto-generated TaggedValue variant, parse its default from a comma or space separated string, and register its rank adapters. Not yet wired into the Stroke node.

* Rank the Fill and Stroke nodes element-wise and give Stroke a DashPattern connector

Migrate Fill and Stroke to element-wise Item<V> primaries (over Vector and Graphic element types) via a new element-level VectorItemMut trait, so styling one shape yields one shape and rank is preserved instead of promoting the input to a singleton List and emitting a List. The macro derives the List-mapped variant for genuine collections.

Wire the Stroke dash sequence to the new rank-0 DashPattern value type, collapsing the old content x paint x dash cartesian and dropping the IntoF64Vec trait. Update the stroke properties dash widget, the drawing tool, and graph-operation plumbing to read and write DashPattern, and migrate legacy F64Array, F64, and String dash inputs on document open.

Assign Colors stays a whole-collection node: each element's gradient position depends on its index among all siblings, which the element frame does not expose, so it keeps its List primary and the VectorListIterMut trait.

* Register rank adapters for the ranked Stroke enum parameters

The element-wise Stroke node ranks its align, cap, and paint order parameters as Item<StrokeAlign>, Item<StrokeCap>, and Item<PaintOrder>, but those enums lacked promotion adapters, so a bare default enum value could not be promoted to its Item wire and no Stroke variant resolved ("No construct found for node"). Register their rank adapters alongside StrokeJoin.

* Display Item wires in the Data panel without a List's ID column

Add a TableItemLayout impl for Item<T> and recognize Item wire types when introspecting graph data. An Item holds a single element, so it renders as a one-row table of the element plus its attributes with no leading index column, and it labels as its element type T rather than a List's T[]. Add ItemAttributeValues::get_any for the attribute widget dispatch.

* Register MonitorNode for Item wire types so the Data panel introspects them directly

Graph introspection wraps the inspected output in a generic MonitorNode typed to the wire. Without Item<T> monitor registrations, an Item<Vector> output could only be monitored after an Item to List promotion, so the Data panel captured and displayed a List<Vector> despite the connector being Item<Vector>. Register monitors for the Item types the element-wise nodes emit, and add the matching Data panel downcast entries.

* Color and double Item/List wires and cleave layer-stack connectors in the node graph

* Route wire color and rank through hidden nodes and refresh them on type changes

* Rework the DashPattern connector conversions with element-wise promotion and an explicit reducer node

* Rank the remaining value, context, aggregation, and transform nodes onto Item<T> wires

* Back DashPattern with a List<f64> so the Data panel can introspect its lengths

* Carry a single Item<T> through varargs so the Read context nodes emit Item<T> not List<T>

* Relax rank validation for aggregation shapes, add element adapters, and match variants by fewest promotions

* Rank the remaining bare and unnecessarily-List connectors across the node catalog

* Add Graphic::None and the FillChoice paint value, making colors and gradients plain values

* Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill

* Restore generator frame-from-params ranking to the roadmap as a planned stage

* Rename the ranked-field adapter identifier from PromoteNode to FieldAdapterNode to reflect its full contract

* Unload only the wires whose displayed style changed when types update

* Peel wire rank in the editor's semantic type checks so rank-0 layers are recognized

* Restore the whole-List Transform variant so rank-1 content wires resolve again

* Register the Item wire forms for the Memoize and Context Modification infrastructure nodes

* Give every ranked connector a field adapter and add numeric cast variants for legacy wires

* Key a ranked param's type default off its Item wire form when no literal default exists

* Inherit the layer's content value when splicing a node into an empty chain

* Migrate stale List-form TypeDefault inputs to the definition's current default

* Generate the mapped wire variant only when the element-wise node has a frame source

* Let a bare wire feed a List connector via a wrap-raise adapter, costed as two rank steps

* Add a zip companion to the whole-List Transform so ranked List parameters pair per slot

* Add the Sum, Average, Minimum, Maximum, Any, and All list reducers

* Convert the measure family to element-wise Item kernels per the audit classification

* Prefer the bare element value over the Item type default so ranked params keep their widgets

* Rename GradientStopsUI to GradientUI

* Split Fill's optional transform into a _has_transform bool and a ranked _transform matrix

* Rename the migration-only OptionalDAffine2 TaggedValue to LegacyOptionalDAffine2

* Flow byte buffers as Item<Resource> instead of List<u8> across the byte nodes

* Macro-generate the list-content wire variant, retiring the hand-written Transform-zip, Area, and Centroid companions

* Let ()-primary generators take ranked params and frame over them via the mapped variant, ranking Circle's radius

* Rank the vector shape generators' params to Item, adding a rank-aware input grab to the introspection harness

* Rank the value, color, and text generator params to Item

* Rank the raster, web-request, and context-reader generator params to Item

* Fix the repeat and brush test wirings left behind by the param-ranking sweeps

* Delete the vestigial Some, Unwrap Option, and Size Of debug nodes

* Delete the Attach Attribute node, folding its role into Write Attribute

* Add the Filter and Sort list companion nodes

* Guard the removed-definition migration swap target with a test

* Add the Box Corners value type in place of the rectangle corner radius list

* Split Text to Vector's per-glyph mode into a Text to Vector Glyphs node

* Rank the Combine Channels node's channel connectors to Item

* Make Map Points an element-wise node

* Delete the deprecated Upload Texture node

* Update the implementation roadmap to reflect the landed stages

* Let monitor introspection read rank-0 wires, locking in the layer coercion promotion path

* Prefer the rank-0 default when disconnecting a rank-capable input

* Make Path Modify an element-wise node

* Wrap node paths in a NodeIdPath newtype so they flow as a single Item

* Give Item<Raster<CPU>> a default so an unconnected Brush background resolves

* Stop the Brush node from setting layer attributes its paint operation doesn't produce

* Present-gate Flatten Path's adopted layer path like its fill and stroke

* Gate carried layer attributes on static column presence, not runtime values

* Give the remaining graphic Item<T> types a default so unconnected primaries resolve

* Dispatch a ranked param's Properties widget from its rank-0 element type

* Make Extract Transform an element-wise node, restoring the Origins to Polyline body

* Rename Flatten Path to Combine Paths

* Stamp Legacy Layer Extend's adopted layer path as a readable NodeIdPath

* Drop the dead List<u8> and List<NodeId> wire rows

* Rank Flatten Graphic's Fully Flatten toggle to Item

* Update the implementation roadmap with the endgame scope

* Make Combine Paths a reducer that collapses the whole frame into one path

* Stop type-converter nodes from carrying the source's unrelated attributes

* Format the Origins to Polyline regression test

* Wrap the Brush node's trace in a BrushTrace newtype so it flows as one value

* Make Switch a framed element-wise select, bundling whole collections

* Widen and align element-type coverage across the list and graphic nodes

* Register the compiler's cache chain pair for every ranked enum and newtype wire

* Fix wire colors for Passthrough outputs, bundled lists, and bools, and widen list wires

* Represent List wire types structurally with Type::List, replacing name-parsed rank promotion

* Treat scope and data fields as environment, rank scope wires as Item, and feed the render boundary through a context vararg

* Delete the vestigial Clone debug node

* Reinstate Upload Texture as an element-wise node and fix the GPU variants' scope executor and rank adapters

* Rename Combine Paths back to Flatten Path, deferring that rename to its own PR

* Deduplicate the promotion adapter registrations into the field adapter macro

* Rank Write Attribute's value connector to Item<AttributeValueDyn>, retiring the UnwrapItem bridge

* Vertical wire styling

* Store the editor layer path attribute as a bare NodeIdPath, not an Item<NodeIdPath>

* Rank Context Modification's features connector to Item<ContextFeatures>, dropping the dead memoize row

* Rank Path Modify's modification parameter to Item<Box<VectorModification>>

* Rename the field adapter node family to input adapter

* Drop the dead bare scalar rows from Context Modification's implementations list

* Move the dynamic executor's test module into its own file

* Drop the registry's unreachable bare rows for Memoize, the cache chain, and ConvertNode

* Materialize stored TaggedValues as ranked Item wires at the source

* Remove the bare-wire promotion and adapter machinery made dead by ranked value materialization

* Plant the input adapter for List-only inputs, composing position conversion from standard rows

* Consolidate Into/Convert conversions into the input adapter umbrella and rename the rank adapter identifiers

* Fix grouped layers gaining a phantom None stack element from the FillChoice default hijacking every List<Graphic> disconnect

* Enforce ranked node inputs in the macro, rejecting bare wire declarations

* Remove the unit Context => () machinery rows, leaving () purely as the no-primary sentinel

* Add a --signatures rank-audit mode to node-docs for the ranked-wire migration

* Remove the node-docs --signatures rank-audit mode now that ranked wires are enforced

* Migrate legacy no-color values on the Black & White, Color Overlay, and Empty Image color inputs

* Rewrite the element-wise accessor wire type at the primary input, not raw index 0

* Register the cache chain for Resource wires, replacing the lone hand-written Monitor row

* Gate the remaining Raster<GPU> registry rows behind the gpu feature

* Let List<DVec2> wires erase to ListDyn for the attribute reader and element counter

* Rename Extract Element to Item at Index, Count Elements to List Length, and Omit Element to Remove at Index

* Store paint picks as plain color/gradient values, removing the FillChoice value type

* Code review restructuring

* Sort by the consumed sort_key attribute or natural element order, adding the Sort Key node

* Remove the new list-combinator and reducer nodes to defer them to a follow-up PR

* Parse Fill and Stroke color defaults through the paint wire's Graphic element

* Emit ranked implementation-row default types structurally so their element TypeIds survive to default-literal parsing

* Exempt the deliberate no-paint choice from the stale List-form TypeDefault migration

* Migrate the legacy 4-input Fill directly to the split has-transform shape

* Upgrade the demo artwork

* Fix the valid AI review findings: Item eq/hash contract, table-era no-paint migration, quantize List rows, and other smaller issues

* Remove the rank polymorphism working documents

* Hash Item attribute values directly instead of debug-formatting them, speeding up cached evaluation

* Replace the data panel's dead bare-wire downcast arms with full coverage of the ranked monitor row types

* Derive PartialEq for Item now that attributes participate in equality

* Extend the data panel's attribute dispatchers with the newly supported scalar and choice enum types

* Add List monitor rows for the framed numeric conversion outputs so inspecting them resolves, with matching data panel arms
2026-07-15 19:03:01 -07:00

486 lines
18 KiB
Rust

use core_types::list::{Item, List};
use core_types::{ATTR_TYPE, Ctx};
use serde_json::Value;
use crate::unescape_string;
// ===========
// Format JSON
// ===========
/// Reformats a JSON string with control over indentation, line breaking, and spacing. Trailing commas are tolerated. Otherwise-invalid JSON input is returned unchanged.
#[node_macro::node(name("Format JSON"), category("Text: JSON"))]
fn format_json(
_: impl Ctx,
/// The JSON string to reformat.
#[name("JSON")]
json: Item<String>,
/// Removes optional spaces within curly brackets and after colons and commas.
compact: Item<bool>,
/// Break arrays and objects across multiple lines when they exceed the line break length.
#[default(true)]
#[name("Multi-Line")]
multi_line: Item<bool>,
/// The indentation string used for each nesting level. Escape sequences like `\t` (the tab character) are supported. Two or four spaces are also common choices.
#[default("\\t")]
indent: Item<String>,
/// The maximum line length before a container (array or object) is broken across lines. Set this to 0 to always break containers. (Requires *Multi-Line* to take effect.)
///
/// This is not a maximum line length guarantee. Deep nesting and long keys or values may exceed this length.
#[default(120)]
break_length: Item<u32>,
/// Always break a container (array or object) across lines if it holds another container, even if it would fit within the break length. (Requires *Multi-Line* to take effect.)
#[default(true)]
break_nested: Item<bool>,
) -> Item<String> {
let mut json = json;
let (compact, multi_line, break_length, break_nested) = (*compact.element(), *multi_line.element(), *break_length.element(), *break_nested.element());
let indent = indent.element().clone();
let cleaned = strip_trailing_commas(json.element());
let Ok(value) = serde_json::from_str::<serde_json::Value>(&cleaned) else { return json };
let indent = unescape_string(indent);
let colon = if compact { ":" } else { ": " };
let comma_space = if compact { "," } else { ", " };
let line_width = break_length as usize;
let result = if multi_line {
format_value(&value, 0, &indent, colon, comma_space, compact, break_nested, line_width)
} else {
format_inline(&value, colon, comma_space, compact)
};
*json.element_mut() = result;
json
}
/// Strips trailing commas before `]` and `}` to accept JSON-with-trailing-commas input.
/// Respects string literals so commas inside strings are left untouched.
fn strip_trailing_commas(json: &str) -> String {
let mut output = String::with_capacity(json.len());
let mut chars = json.chars().peekable();
let mut in_string = false;
while let Some(c) = chars.next() {
if in_string {
output.push(c);
// Skip escaped characters inside strings
if c == '\\'
&& let Some(escaped) = chars.next()
{
output.push(escaped);
} else if c == '"' {
in_string = false;
}
continue;
}
match c {
'"' => {
in_string = true;
output.push(c);
}
',' => {
// Skip any whitespace after the comma
while chars.peek().is_some_and(|c| c.is_ascii_whitespace()) {
chars.next();
}
// Drop trailing commas (before `]` or `}`), but keep all others
if !chars.peek().is_some_and(|&c| c == ']' || c == '}') {
output.push(',');
}
}
_ => output.push(c),
}
}
output
}
/// Formats a JSON value as a single unbroken line.
fn format_inline(value: &serde_json::Value, colon: &str, comma_space: &str, compact: bool) -> String {
match value {
serde_json::Value::Array(arr) => {
let inner: Vec<String> = arr.iter().map(|v| format_inline(v, colon, comma_space, compact)).collect();
format!("[{}]", inner.join(comma_space))
}
serde_json::Value::Object(obj) => {
let inner: Vec<String> = obj
.iter()
.map(|(k, v)| format!("{}{}{}", serde_json::to_string(k).unwrap_or_default(), colon, format_inline(v, colon, comma_space, compact)))
.collect();
let joined = inner.join(comma_space);
if compact || joined.is_empty() { format!("{{{joined}}}") } else { format!("{{ {joined} }}") }
}
other => serde_json::to_string(other).unwrap_or_default(),
}
}
/// Formats a JSON value, optionally breaking containers across lines when they contain other containers or exceed the line break length limit.
#[allow(clippy::too_many_arguments)]
fn format_value(value: &serde_json::Value, depth: usize, indent: &str, colon: &str, comma_space: &str, compact: bool, break_nested: bool, line_width: usize) -> String {
// Checks whether any direct child of a container is itself a container.
let contains_containers = |value: &serde_json::Value| {
// Checks whether a JSON value is a container (array or object).
let is_container = |value: &serde_json::Value| matches!(value, serde_json::Value::Array(_) | serde_json::Value::Object(_));
match value {
serde_json::Value::Array(arr) => arr.iter().any(is_container),
serde_json::Value::Object(obj) => obj.values().any(is_container),
_ => false,
}
};
match value {
serde_json::Value::Array(arr) if !arr.is_empty() => {
// Try inline if children are all leaves (or break_nested is off) and it fits
if !break_nested || !contains_containers(value) {
let inline = format_inline(value, colon, comma_space, compact);
let current_indent_width = indent.len() * depth;
if current_indent_width + inline.len() <= line_width {
return inline;
}
}
// Break across lines
let child_indent = indent.repeat(depth + 1);
let closing_indent = indent.repeat(depth);
let items: Vec<String> = arr
.iter()
.map(|v| format!("{child_indent}{}", format_value(v, depth + 1, indent, colon, comma_space, compact, break_nested, line_width)))
.collect();
format!("[\n{}\n{closing_indent}]", items.join(",\n"))
}
serde_json::Value::Object(obj) if !obj.is_empty() => {
// Try inline if children are all leaves (or break_nested is off) and it fits
if !break_nested || !contains_containers(value) {
let inline = format_inline(value, colon, comma_space, compact);
let current_indent_width = indent.len() * depth;
if current_indent_width + inline.len() <= line_width {
return inline;
}
}
// Break across lines
let child_indent = indent.repeat(depth + 1);
let closing_indent = indent.repeat(depth);
let entries: Vec<String> = obj
.iter()
.map(|(k, v)| {
let key = serde_json::to_string(k).unwrap_or_default();
let val = format_value(v, depth + 1, indent, colon, comma_space, compact, break_nested, line_width);
format!("{child_indent}{key}{colon}{val}")
})
.collect();
format!("{{\n{}\n{closing_indent}}}", entries.join(",\n"))
}
other => serde_json::to_string(other).unwrap_or_default(),
}
}
// ================
// Query JSON (All)
// ================
/// Extracts a single matched value from a JSON string using a path expression (see that parameter's description for its syntax). If no matches are found, an empty string is returned. If multiple values are matched, the first is returned. To read all matches, use the **Query JSON All** node.
///
/// This is useful in conjunction with the nodes:
/// • **String to Number**: convert numeric query results to numbers.
/// • **String Value** → **Equals**: convert "true", "false", or "null" query results to bools.
#[node_macro::node(name("Query JSON"), category("Text: JSON"))]
fn query_json(
_: impl Ctx,
/// The JSON string to extract a value from.
#[name("JSON")]
json: Item<String>,
/// Determines which contained value to extract from within the JSON.
///
/// The path syntax is like JavaScript's accessor syntax that follows an array/object value. It also supports negative indexing to count backwards from the end. Additionally, `[]` accesses all array and object values instead of just one.
///
/// Examples:
/// Use `[2]` or `[-1]` to get the last value, and `[1]` or `[-2]` for the middle value, of `["a", "b", "c"]`.
/// Use `.size` or `["size"]` to get the `size` property of `{ "size": 10 }`. The latter form is required if the key contains spaces or special characters like `["this key with spaces!"]`.
/// Use chained accessors like `.fonts[0].name` to query deeper.
/// Use the `[]` accessor to query all elements, like `.fonts[].weights[]` to get every weight of every font.
path: Item<String>,
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
#[default(true)]
unquote_strings: Item<bool>,
) -> Item<String> {
let mut json = json;
let path = path.element().clone();
let unquote_strings = *unquote_strings.element();
let cleaned = strip_trailing_commas(json.element());
let result = match (serde_json::from_str::<Value>(&cleaned), parse_json_path(path.trim())) {
(Ok(value), Some(segments)) => {
let mut results = Vec::new();
resolve_all(&value, &segments, !unquote_strings, &mut results);
results.into_iter().next().map(|(text, _ty)| text).unwrap_or_default()
}
_ => String::new(),
};
*json.element_mut() = result;
json
}
/// Extracts every matched value from a JSON string using a path expression (see that parameter's description for its syntax). A list of zero or more resultant strings is produced. The `[]` path accessor is used to read more than one value.
///
/// Each item carries a `type` attribute holding the matched value's JSON type (`"string"`, `"number"`, `"bool"`, `"null"`, `"object"`, or `"array"`).
///
/// This is useful in conjunction with the nodes:
/// • **Index Elements**: access the `N`th query result.
/// • **String to Number**: convert numeric query results to numbers.
/// • **String Value** → **Equals**: convert "true", "false", or "null" query results to bools.
#[node_macro::node(name("Query JSON All"), category("Text: JSON"))]
fn query_json_all(
_: impl Ctx,
/// The JSON string to extract values from.
#[name("JSON")]
json: Item<String>,
/// Determines which contained values to extract from within the JSON.
///
/// The path syntax is like JavaScript's accessor syntax that follows an array/object value. It also supports negative indexing to count backwards from the end. Additionally, `[]` accesses all array and object values instead of just one.
///
/// Examples:
/// Use `[2]` or `[-1]` to get the last value, and `[1]` or `[-2]` for the middle value, of `["a", "b", "c"]`.
/// Use `.size` or `["size"]` to get the `size` property of `{ "size": 10 }`. The latter form is required if the key contains spaces or special characters like `["this key with spaces!"]`.
/// Use chained accessors like `.fonts[0].name` to query deeper.
/// Use the `[]` accessor to query all elements, like `.fonts[].weights[]` to get every weight of every font.
path: Item<String>,
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
#[default(true)]
unquote_strings: Item<bool>,
) -> List<String> {
let cleaned = strip_trailing_commas(json.element());
let Ok(value): Result<Value, _> = serde_json::from_str(&cleaned) else { return List::new() };
let Some(segments) = parse_json_path(path.element().trim()) else { return List::new() };
let mut results = Vec::new();
resolve_all(&value, &segments, !*unquote_strings.element(), &mut results);
results.into_iter().map(|(text, ty)| Item::new_from_element(text).with_attribute(ATTR_TYPE, ty.to_string())).collect()
}
/// A parsed segment of a JSON access path.
enum JsonPathSegment {
/// Access an object key, e.g. `.name` or `["my key"]`.
Key(String),
/// Access an array element by index, e.g. `[0]` or `[-1]`.
Index(i32),
/// Iterate all elements of an array or object values, e.g. `[]`.
IterateAll,
}
/// Parses a JSON access path like `users[0].name` or `.["my key"][].value` into segments.
/// Returns `None` on syntax errors.
fn parse_json_path(path: &str) -> Option<Vec<JsonPathSegment>> {
let mut segments = Vec::new();
let mut chars = path.chars().peekable();
// Skip optional leading dot
if chars.peek() == Some(&'.') {
chars.next();
if chars.peek() == Some(&'.') {
return None;
}
}
while chars.peek().is_some() {
if chars.peek() == Some(&'[') {
chars.next(); // consume '['
if chars.peek() == Some(&']') {
// Empty brackets: iterate all
chars.next();
segments.push(JsonPathSegment::IterateAll);
} else if matches!(chars.peek(), Some(&'"') | Some(&'\'')) {
// Quoted key: ["my key"] or ['my key']
let closing_quote = chars.next().unwrap(); // consume opening quote
let mut key = String::new();
while let Some(&c) = chars.peek() {
if c == closing_quote {
chars.next(); // consume closing quote
break;
}
if c == '\\' {
chars.next();
match chars.next() {
Some('"') => key.push('"'),
Some('\'') => key.push('\''),
Some('\\') => key.push('\\'),
Some('/') => key.push('/'),
Some('b') => key.push('\x08'),
Some('f') => key.push('\x0C'),
Some('n') => key.push('\n'),
Some('r') => key.push('\r'),
Some('t') => key.push('\t'),
Some('u') => {
// Decode a 4-hex-digit Unicode escape sequence, only consuming verified hex digits
let mut hex_digits = [0_u8; 4];
let mut count = 0;
for digit in &mut hex_digits {
match chars.peek() {
Some(c) if c.is_ascii_hexdigit() => {
*digit = chars.next().unwrap() as u8;
count += 1;
}
_ => break,
}
}
let hex = &hex_digits[..count];
if count == 4
&& let Ok(hex_str) = core::str::from_utf8(hex)
&& let Ok(code_point) = u32::from_str_radix(hex_str, 16)
&& let Some(byte) = char::from_u32(code_point)
{
key.push(byte);
} else {
key.push('\\');
key.push('u');
for &byte in hex {
key.push(byte as char);
}
}
}
Some(other) => {
key.push('\\');
key.push(other);
}
None => key.push('\\'),
}
} else {
key.push(c);
chars.next();
}
}
// Require the closing ']'
if chars.peek() == Some(&']') {
chars.next();
} else {
return None;
}
segments.push(JsonPathSegment::Key(key));
} else {
// Numeric index: [0] or [-1]
let mut num_str = String::new();
while let Some(&c) = chars.peek() {
if c == ']' {
chars.next();
break;
}
num_str.push(c);
chars.next();
}
if let Ok(index) = num_str.trim().parse::<i32>() {
segments.push(JsonPathSegment::Index(index));
} else {
return None;
}
}
} else if chars.peek() == Some(&'.') {
// Dot separator before next key
chars.next();
if chars.peek() == Some(&'.') || chars.peek().is_none() {
return None;
}
} else {
// Bare key: read until dot or bracket
let mut key = String::new();
while let Some(&c) = chars.peek() {
if c == '.' || c == '[' {
break;
}
key.push(c);
chars.next();
}
if !key.is_empty() {
segments.push(JsonPathSegment::Key(key));
}
}
}
Some(segments)
}
/// Converts a JSON value to its string representation.
/// Strings are quoted by default to produce valid JSON syntax. When `quote_strings` is false, surrounding quotes are stripped.
fn json_value_to_string(value: &serde_json::Value, quote_strings: bool) -> String {
match value {
serde_json::Value::String(s) if !quote_strings => s.clone(),
other => other.to_string(),
}
}
/// Returns a short JSON-type name (`"string"`, `"number"`, `"bool"`, `"null"`, `"object"`, `"array"`) for a parsed value.
fn json_value_type_name(value: &serde_json::Value) -> &'static str {
match value {
serde_json::Value::String(_) => "string",
serde_json::Value::Number(_) => "number",
serde_json::Value::Bool(_) => "bool",
serde_json::Value::Null => "null",
serde_json::Value::Object(_) => "object",
serde_json::Value::Array(_) => "array",
}
}
/// Navigates a JSON value by one path segment, returning the resulting value (or `None` if the path is invalid).
fn json_navigate<'a>(value: &'a serde_json::Value, segment: &JsonPathSegment) -> Option<&'a serde_json::Value> {
match segment {
JsonPathSegment::Key(key) => value.as_object().and_then(|obj| obj.get(key)),
JsonPathSegment::Index(index) => {
let arr = value.as_array()?;
let resolved = if *index < 0 { arr.len().checked_sub(index.unsigned_abs() as usize)? } else { *index as usize };
arr.get(resolved)
}
JsonPathSegment::IterateAll => None, // Handled by resolve_all
}
}
/// Recursively resolves a path against a JSON value, fanning out at each `[]` and collecting leaf results.
fn resolve_all(value: &serde_json::Value, segments: &[JsonPathSegment], quote_strings: bool, results: &mut Vec<(String, &'static str)>) {
// Find the next IterateAll in the remaining segments
let Some(iterate_position) = segments.iter().position(|s| matches!(s, JsonPathSegment::IterateAll)) else {
// No more [] segments, navigate the rest linearly
let mut current = value;
for segment in segments {
let Some(next) = json_navigate(current, segment) else { return };
current = next;
}
results.push((json_value_to_string(current, quote_strings), json_value_type_name(current)));
return;
};
// Navigate to the array/object before the []
let mut current = value;
for segment in &segments[..iterate_position] {
let Some(next) = json_navigate(current, segment) else { return };
current = next;
}
// Fan out over elements and recurse with the remaining path
let remaining = &segments[iterate_position + 1..];
match current {
serde_json::Value::Array(arr) => {
for element in arr {
resolve_all(element, remaining, quote_strings, results);
}
}
serde_json::Value::Object(obj) => {
for element in obj.values() {
resolve_all(element, remaining, quote_strings, results);
}
}
_ => {}
}
}