From 47f56b481c44211350019d1e7a772eb2a080fbd0 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Wed, 23 Sep 2026 08:13:16 +0000 Subject: [PATCH] Store previewing and pinned order in the registry and stop rebuilding nodes to change their inputs --- document/graph-storage/src/attributes/attr.rs | 15 ++- document/graph-storage/src/crdt.rs | 12 +- document/graph-storage/src/document.rs | 16 +++ document/graph-storage/src/from_runtime.rs | 47 +++++++- document/graph-storage/src/lib.rs | 6 +- document/graph-storage/src/metadata_source.rs | 57 ++++++++- document/graph-storage/src/model.rs | 21 ---- document/graph-storage/src/to_runtime.rs | 39 ++++++- .../document/storage_tests/metadata_tests.rs | 44 +++++++ .../network_interface/editor_delta.rs | 108 ++++++++++-------- .../network_interface/editor_delta_tests.rs | 46 +++++++- .../network_interface/mutations.rs | 10 +- .../network_interface/storage_metadata.rs | 59 +++++++--- .../utility_types/network_interface/store.rs | 56 +++++++-- 14 files changed, 420 insertions(+), 116 deletions(-) diff --git a/document/graph-storage/src/attributes/attr.rs b/document/graph-storage/src/attributes/attr.rs index 3fde1be0f1..990413f9e2 100644 --- a/document/graph-storage/src/attributes/attr.rs +++ b/document/graph-storage/src/attributes/attr.rs @@ -31,8 +31,6 @@ pub mod node { pub mod session { pub mod network { - pub const PREVIEWING: &str = "ui::previewing"; - // TODO: Remove these graph ui nav-specific attributes pub const NAV_PTZ: &str = "ui::nav::ptz"; pub const NAV_TRANSFORM: &str = "ui::nav::transform"; @@ -60,6 +58,19 @@ pub mod network { /// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The /// node references use stable storage IDs, resolved back to runtime-local IDs on conversion. pub const SCOPE_INJECTIONS: &str = "scope_injections"; + + /// Whole-value LWW of which node the network renders instead of its export, together with what the + /// export reconnects to when the preview ends. Absent means the network is not previewing. + /// + /// Document state, not per-peer view state: previewing rewires the export, which is already shared, + /// so the note saying how to restore it has to be shared too. The node reference uses a stable + /// storage ID. + pub const PREVIEWING: &str = "ui::previewing"; + + /// Whole-vec LWW of the display order of the network's pinned nodes, as stable storage IDs. + /// Concurrent reorders do not merge, but the pinned set is already shared, and a shared set with + /// per-peer ordering would diverge with no way to reconcile. + pub const PINNED_ORDER: &str = "ui::pinned_order"; } pub mod delta { diff --git a/document/graph-storage/src/crdt.rs b/document/graph-storage/src/crdt.rs index bbe4710034..1052ffe216 100644 --- a/document/graph-storage/src/crdt.rs +++ b/document/graph-storage/src/crdt.rs @@ -1,4 +1,4 @@ -use crate::{Attributes, AttributesWrite, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev}; +use crate::{Attributes, AttributesWrite, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev}; use graphene_resource::ResourceHash; use serde::{Deserialize, Serialize}; @@ -109,6 +109,16 @@ pub enum RegistryDelta { index: u32, new_input: NodeInput, }, + /// A node's whole input list, for a change to the number or order of its slots that the + /// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent + /// per-slot edits are lost, which is inherent to the indices themselves moving. + /// + /// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes + /// with attribute ops on the same node instead of reverting them. + SetNodeInputs { + id: NodeId, + inputs: Vec, + }, ChangeNodeAttribute { id: NodeId, delta: AttributeDelta, diff --git a/document/graph-storage/src/document.rs b/document/graph-storage/src/document.rs index 71a6e3543e..d9e0656cc2 100644 --- a/document/graph-storage/src/document.rs +++ b/document/graph-storage/src/document.rs @@ -194,6 +194,10 @@ impl Document { RegistryDelta::RemoveNode { id, .. } => { registry.node_instances.remove(&id); } + RegistryDelta::SetNodeInputs { id, inputs } => { + let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?; + node.inputs = inputs; + } RegistryDelta::ChangeNodeInput { id, index, new_input } => { let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?; let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?; @@ -305,6 +309,14 @@ impl Document { } self.ensure_node_exists(target, *id)?; } + RegistryDelta::SetNodeInputs { id, inputs } => { + for slot in inputs { + if let NodeInput::Node { id: referenced, .. } = slot.input { + self.ensure_node_exists(target, referenced)?; + } + } + self.ensure_node_exists(target, *id)?; + } RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?, RegistryDelta::SetNetworkExport { id: network, export: export_target, .. @@ -342,6 +354,10 @@ impl Document { Ok(match delta { RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() }, RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() }, + &RegistryDelta::SetNodeInputs { id, .. } => { + let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?; + RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() } + } &RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => { let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?; let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?; diff --git a/document/graph-storage/src/from_runtime.rs b/document/graph-storage/src/from_runtime.rs index d6f89a12b9..44f140492a 100644 --- a/document/graph-storage/src/from_runtime.rs +++ b/document/graph-storage/src/from_runtime.rs @@ -345,7 +345,7 @@ fn convert_network( .collect::, ConversionError>>()?; let mut attributes = crate::Attributes::new(); - write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, TimeStamp::ORIGIN)?; + write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?; write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?; registry.networks.insert(network_id, Network { exports, attributes }); @@ -550,11 +550,40 @@ fn write_ui_attributes( Ok(()) } -fn write_ui_network_attributes(attributes: &mut crate::Attributes, metadata: &M, network_path: &[RuntimeNodeId], timestamp: TimeStamp) -> Result<(), ConversionError> { +/// Node references here are remapped to stable storage IDs for the same reason `write_scope_injections` +/// does it: a runtime ID is not stable across a round trip. +fn write_ui_network_attributes( + attributes: &mut crate::Attributes, + metadata: &M, + network_path: &[RuntimeNodeId], + parent_path: Option<&NodePath>, + network_id: NetworkId, + ids: NodeIds<'_, M>, + timestamp: TimeStamp, +) -> Result<(), ConversionError> { if let Some(reference) = metadata.reference(network_path) { attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp); } + let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id); + + // Absent means not previewing, so the inert default stays out of the registry. + let previewing = metadata.previewing(network_path); + if previewing.is_previewing() { + let stored = previewing.map_id(to_storage_id); + attributes + .set_serialized(network::PREVIEWING, &stored, timestamp) + .map_err(map_serialization_error(network::PREVIEWING))?; + } + + let pinned_order = metadata.pinned_order(network_path); + if !pinned_order.is_empty() { + let stored: Vec = pinned_order.into_iter().map(to_storage_id).collect(); + attributes + .set_serialized(network::PINNED_ORDER, &stored, timestamp) + .map_err(map_serialization_error(network::PINNED_ORDER))?; + } + Ok(()) } @@ -605,7 +634,9 @@ fn convert_input(input: &GraphCraftNodeInput, pa }) } -fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result { +/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an +/// import, and a reflection node.s metadata. Public for staging paths that rebuild a node.s slots. +pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result { let mut attributes = crate::Attributes::new(); let timestamp = TimeStamp::ORIGIN; @@ -792,7 +823,15 @@ impl<'m> ScopedConversion<'m> { .collect::, ConversionError>>()?; let mut attributes = crate::Attributes::new(); - write_ui_network_attributes(&mut attributes, self.ctx.metadata, local_path, TimeStamp::ORIGIN)?; + write_ui_network_attributes( + &mut attributes, + self.ctx.metadata, + local_path, + owner_path.as_ref(), + network_id, + self.ctx.ids(local_path), + TimeStamp::ORIGIN, + )?; write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?; registry.networks.insert(network_id, Network { exports, attributes }); diff --git a/document/graph-storage/src/lib.rs b/document/graph-storage/src/lib.rs index f60c492b3d..f5295dafc6 100644 --- a/document/graph-storage/src/lib.rs +++ b/document/graph-storage/src/lib.rs @@ -30,11 +30,11 @@ pub use session::*; #[cfg(any(feature = "conversion", test))] pub use from_runtime::{ - PathResolver, RuntimeConversion, ScopedConversion, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, - value_resource_ref, + PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes, + node_value_resource_refs, value_resource_ref, }; #[cfg(any(feature = "conversion", test))] -pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position}; +pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position, Previewing as StoredPreviewing, RootNode as StoredRootNode}; #[cfg(any(feature = "conversion", test))] pub use to_runtime::Declarations; diff --git a/document/graph-storage/src/metadata_source.rs b/document/graph-storage/src/metadata_source.rs index 50b110b695..29aa226dc1 100644 --- a/document/graph-storage/src/metadata_source.rs +++ b/document/graph-storage/src/metadata_source.rs @@ -7,6 +7,7 @@ use std::collections::HashMap; use core_types::uuid::NodeId as RuntimeNodeId; +use serde::{Deserialize, Serialize}; /// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per /// node, since every node carries an identity to restore even when it carries no `ui::*` attribute. @@ -36,15 +37,54 @@ pub struct NetworkMetadataEntry { /// Empty = root network. pub network_path: Vec, /// Stable storage id of this network. Lets the editor associate per-network, per-peer view state - /// (node-graph nav + previewing, in `session.json`) with a network across reparenting. + /// (the node-graph nav, in `session.json`) with a network across reparenting. pub network_id: crate::NetworkId, /// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag. pub reference: Option, + /// Which node the network renders instead of its export. Document state rather than view state: + /// previewing rewires the export, so the note saying how to put it back has to travel with it. + pub previewing: Previewing, + /// The display order of the network's pinned nodes. Shared for the same reason the pinned flag is: + /// a shared set with per-peer ordering could never reconcile. + pub pinned_order: Vec, } -impl NetworkMetadataEntry { - pub fn is_empty(&self) -> bool { - self.reference.is_none() +/// Which node a network renders instead of its export, and what the export reconnects to when the +/// preview ends. +/// +/// Generic over the ID space: runtime-local as a metadata source reports it, stable storage IDs once +/// written, so the reference survives a round trip even if runtime IDs are later reshuffled. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub enum Previewing { + #[default] + No, + Yes { + root_node_to_restore: Option>, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct RootNode { + pub node_id: Id, + pub output_index: u32, +} + +impl Previewing { + /// The previewed network's restore target, mapped through `map` into the other ID space. + pub fn map_id(self, map: impl FnOnce(Id) -> Other) -> Previewing { + match self { + Previewing::No => Previewing::No, + Previewing::Yes { root_node_to_restore } => Previewing::Yes { + root_node_to_restore: root_node_to_restore.map(|root| RootNode { + node_id: map(root.node_id), + output_index: root.output_index, + }), + }, + } + } + + pub fn is_previewing(&self) -> bool { + matches!(self, Previewing::Yes { .. }) } } @@ -104,6 +144,15 @@ pub trait NodeMetadataSource { fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> { None } + /// Which node the network renders instead of its export, with what the export reconnects to when + /// the preview ends. Node references are runtime-local, resolved on conversion. + fn previewing(&self, _network_path: &[RuntimeNodeId]) -> Previewing { + Previewing::No + } + /// The display order of the network's pinned nodes. + fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec { + Vec::new() + } } /// No-op metadata source. Use when there's nothing to attach (synthetic networks, CLI tools). diff --git a/document/graph-storage/src/model.rs b/document/graph-storage/src/model.rs index 1e23359e3c..5dc16385de 100644 --- a/document/graph-storage/src/model.rs +++ b/document/graph-storage/src/model.rs @@ -24,27 +24,6 @@ impl Node { self.network } - /// The same node with its input slots replaced, for a write that changes how many slots it has or - /// what order they are in, which `ChangeNodeInput` cannot express. - /// - /// The new slots carry no attributes: an insert shifts every later slot, so which attributes belong - /// where is the caller's to say, through a paired write of the whole input metadata array. - pub fn with_inputs(&self, inputs: impl IntoIterator, timestamp: TimeStamp) -> Self { - Self { - implementation: self.implementation.clone(), - inputs: inputs - .into_iter() - .map(|input| InputSlot { - input, - timestamp, - attributes: Attributes::new(), - }) - .collect(), - attributes: self.attributes.clone(), - network: self.network, - } - } - /// True if both nodes agree on every value-bearing field, ignoring slot/attribute timestamps. pub fn value_equal(&self, other: &Self) -> bool { if self.implementation != other.implementation || self.network != other.network { diff --git a/document/graph-storage/src/to_runtime.rs b/document/graph-storage/src/to_runtime.rs index d732be4b81..60eda22576 100644 --- a/document/graph-storage/src/to_runtime.rs +++ b/document/graph-storage/src/to_runtime.rs @@ -9,7 +9,7 @@ use graph_craft::{ProtoNodeIdentifier, Type, concrete}; use rustc_hash::{FxHashMap, FxHashSet}; use crate::attr::*; -use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry}; +use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, Previewing, RootNode}; use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId}; #[derive(Debug, thiserror::Error)] @@ -168,7 +168,7 @@ fn convert_network( let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?; if let Some(collector) = network_collector.as_mut() { - collector.push(extract_network_metadata(&network.attributes, metadata_path, network_id)); + collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id)); } let mut nodes: FxHashMap = FxHashMap::default(); @@ -264,11 +264,44 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R } } -fn extract_network_metadata(attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry { +/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way +/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped +/// rather than failing the conversion: the preview target or a pinned node can have been deleted. +fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry { + let to_runtime_id = |storage_id: NodeId| { + let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?; + let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(storage_id.0); + Some(RuntimeNodeId(local_id)) + }; + + let previewing = attributes + .get_typed::>(network::PREVIEWING) + .map(|stored| match stored { + Previewing::No => Previewing::No, + Previewing::Yes { root_node_to_restore } => Previewing::Yes { + root_node_to_restore: root_node_to_restore.and_then(|root| { + Some(RootNode { + node_id: to_runtime_id(root.node_id)?, + output_index: root.output_index, + }) + }), + }, + }) + .unwrap_or_default(); + + let pinned_order = attributes + .get_typed::>(network::PINNED_ORDER) + .unwrap_or_default() + .into_iter() + .filter_map(to_runtime_id) + .collect(); + NetworkMetadataEntry { network_path: network_path.to_vec(), network_id, reference: attributes.get_typed(node::ui::REFERENCE), + previewing, + pinned_order, } } diff --git a/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs b/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs index 31c3eb30fa..718a6d1e6c 100644 --- a/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/metadata_tests.rs @@ -11,6 +11,7 @@ use document_graph_storage::{NodeMetadataSource, PeerId, Registry}; use super::test_support::{load_demo, node_paths}; use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler; use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage}; +use crate::messages::portfolio::document::utility_types::network_interface::{Previewing, RootNode}; use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers; use graph_craft::document::NodeId; use graphene_std::vector::style::RenderMode; @@ -272,6 +273,49 @@ fn rebuilt_interface_keeps_storage_identities() { assert_eq!(reconverted_ids, stored_ids, "re-converting the rebuilt interface under a different peer changed the node identities"); } +/// Previewing and the pinned display order are document state, so they survive a registry round trip +/// rather than living in `session.json`. Both name nodes, and the stored form uses storage IDs, so +/// this also checks the reference resolves back to the right runtime node. +#[test] +fn previewing_and_pinned_order_round_trip_through_the_registry() { + let mut document = load_demo("changing-seasons.graphite"); + + let previewed = *document.network_interface.document_network().nodes.keys().next().expect("demo artwork should have nodes"); + let pinned: Vec<_> = document.network_interface.document_network().nodes.keys().copied().take(3).collect(); + assert_eq!(pinned.len(), 3, "demo artwork should have at least three nodes: fixture is wrong"); + + { + let interface = &mut document.network_interface; + let Some(mut network) = interface.network_mut(&[]) else { + panic!("the document network should resolve") + }; + network.set_previewing(Previewing::Yes { + root_node_to_restore: Some(RootNode { node_id: previewed, output_index: 0 }), + }); + network.set_pinned_order(pinned.clone()); + } + + let network = document.network_interface.document_network().clone(); + let view = StorageMetadataView::new(&document.network_interface); + let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed"); + let declarations = conversion.declarations().expect("rebuild declarations"); + let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime failed"); + let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed"); + + let rebuilt_metadata = rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve"); + assert_eq!( + rebuilt.previewing(&[]), + Previewing::Yes { + root_node_to_restore: Some(RootNode { node_id: previewed, output_index: 0 }), + }, + "previewing did not survive the registry round trip" + ); + assert_eq!( + rebuilt_metadata.persistent_metadata.pinned_node_order, pinned, + "the pinned display order did not survive the registry round trip" + ); +} + /// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into /// the view map, then apply it onto a fresh handler and confirm each field matches. #[test] diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs index d12a42026b..12e4e0122c 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs @@ -1,10 +1,11 @@ -use super::storage_metadata::position_from_runtime; +use super::storage_metadata::{position_from_runtime, previewing_from_runtime}; use super::{DocumentNodeMetadata, DocumentNodePersistentMetadata, LayerPosition, NodePosition, NodeTypePersistentMetadata}; -use super::{InputMetadata, InputPersistentMetadata}; +use super::{InputMetadata, InputPersistentMetadata, Previewing}; +use document_graph_storage::attr::network as network_attr; use document_graph_storage::attr::node as node_attr; use document_graph_storage::from_runtime::{ConversionError, DeclarationBytes}; use document_graph_storage::{AttributeDelta, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp}; -use document_graph_storage::{convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref}; +use document_graph_storage::{convert_input_attributes, convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref}; use graph_craft::application_io::resource::{ResourceId, ResourceRegistry}; use graph_craft::document::NodeId; use graph_craft::runtime_delta::RuntimeDelta; @@ -75,6 +76,11 @@ pub enum NodeMetadataChange { pub enum NetworkMetadataChange { /// The definition the network was instantiated from, dropped once it is edited away from it. Reference(Option), + /// Which node the network renders instead of its export, with what the export reconnects to when + /// the preview ends. + Previewing(Previewing), + /// The whole order, since the encoding is one array-valued attribute rather than a slot each. + PinnedOrder(Vec), } pub struct ConstructedOps { @@ -213,24 +219,23 @@ impl EditorDelta { } EditorDelta::Graph(RuntimeDelta::SetInputs { network_path, node_id, inputs }) => { - let global_id = resolver.node_id(network_path, *node_id); - let Some(existing) = working.node_instances.get(&global_id) else { - log::error!("Could not find node {global_id:?} to set the inputs of"); - return Ok(()); - }; + // Only the slots are written, so the node's attributes and everything nested under it are + // left as they are: an edit made earlier in this batch is not reverted by the rebuild. + // The slots' `ui::*` attributes arrive with the paired input metadata delta. + let inputs = inputs + .iter() + .map(|input| { + Ok(document_graph_storage::InputSlot { + input: resolver.convert_input_at(input, network_path)?, + timestamp: TimeStamp::ORIGIN, + attributes: convert_input_attributes(input)?, + }) + }) + .collect::, ConversionError>>()?; - let inputs = inputs.iter().map(|input| resolver.convert_input_at(input, network_path)).collect::, _>>()?; - - // `AddNode` refuses an ID that is already present, so the record is removed and re-added. - // Only this node's record: its nested network and everything under it keep their own - // entries, which is what separates this from `ReplaceNode`. - ops.push(RegistryDelta::RemoveNode { - id: global_id, - snapshot: existing.clone(), - }); - ops.push(RegistryDelta::AddNode { - id: global_id, - node: existing.with_inputs(inputs, TimeStamp::ORIGIN), + ops.push(RegistryDelta::SetNodeInputs { + id: resolver.node_id(network_path, *node_id), + inputs, }); } @@ -265,13 +270,32 @@ impl EditorDelta { } EditorDelta::NetworkMetadata { network_path, change } => { - let NetworkMetadataChange::Reference(reference) = change; - ops.push(RegistryDelta::ChangeNetworkAttribute { - id: resolver.network_id(network_path), - delta: AttributeDelta { + let delta = match change { + NetworkMetadataChange::Reference(reference) => AttributeDelta { key: node_attr::ui::REFERENCE.to_string(), value: reference.clone().map(serde_json::Value::String), }, + // The restore target is named by a runtime ID, which only the resolver can turn into + // the stable one a whole-document conversion would write. + NetworkMetadataChange::Previewing(previewing) => { + let stored = previewing_from_runtime(*previewing).map_id(|node_id| resolver.node_id(network_path, node_id)); + AttributeDelta { + key: network_attr::PREVIEWING.to_string(), + value: stored.is_previewing().then(|| serialize_attribute(network_attr::PREVIEWING, &stored)).transpose()?, + } + } + NetworkMetadataChange::PinnedOrder(order) => { + let stored: Vec<_> = order.iter().map(|node_id| resolver.node_id(network_path, *node_id)).collect(); + AttributeDelta { + key: network_attr::PINNED_ORDER.to_string(), + value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?, + } + } + }; + + ops.push(RegistryDelta::ChangeNetworkAttribute { + id: resolver.network_id(network_path), + delta, }); } } @@ -405,7 +429,7 @@ fn construct_metadata_snapshot( let mut encoded = Attributes::new(); encode_node_ui_attributes(&mut encoded, &source, &path, id, TimeStamp::ORIGIN)?; - for delta in ui_attribute_deltas(working_node.map(|node| node.attributes()), &encoded) { + for delta in ui_attribute_writes(working_node.map(|node| node.attributes()), &encoded) { ops.push(RegistryDelta::ChangeNodeAttribute { id: global_id, delta }); } @@ -413,7 +437,7 @@ fn construct_metadata_snapshot( let mut encoded = Attributes::new(); encode_input_ui_attributes(&mut encoded, &source, &path, id, input_index, TimeStamp::ORIGIN)?; let current = working_node.and_then(|node| node.inputs().get(input_index)).map(|slot| &slot.attributes); - for delta in ui_attribute_deltas(current, &encoded) { + for delta in ui_attribute_writes(current, &encoded) { ops.push(RegistryDelta::ChangeNodeInputAttribute { id: global_id, index: input_index.try_into().map_err(|_| ConversionError::IndexOverflow(input_index))?, @@ -452,23 +476,14 @@ fn construct_metadata_snapshot( Ok(()) } -/// Minimal ops transforming the `ui::`-prefixed subset of `current` into `encoded`, comparing -/// values only, since timestamps are re-stamped at staging. -fn ui_attribute_deltas(current: Option<&Attributes>, encoded: &Attributes) -> Vec { - ui_attribute_ops(current, encoded, true) -} - -/// Every `ui::` attribute of `encoded` plus a clear for each the slot no longer carries, restating -/// even the values that already match. +/// Every `ui::` attribute of `encoded`, plus a clear for each `ui::` key of `current` that `encoded` +/// does not carry. Values are compared only to decide what to clear, never to skip a write. /// -/// For a write that follows a wholesale replacement of the same slot in this batch: `current` is the -/// registry as it stood before the batch, so a value it agrees with may already have been cleared by -/// the earlier op, and skipping it would leave the slot empty. +/// Restating a value that already matches looks redundant but is load-bearing: `current` is the +/// registry as it stood before the batch, and these writes follow an op in the same batch that +/// rebuilt what they describe. A value the pre-batch state agrees with may already have been cleared +/// by that op, so skipping it would leave the attribute missing. fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Vec { - ui_attribute_ops(current, encoded, false) -} - -fn ui_attribute_ops(current: Option<&Attributes>, encoded: &Attributes, skip_unchanged: bool) -> Vec { let owned = |key: &str| key.starts_with("ui::"); let mut deltas = Vec::new(); @@ -480,13 +495,10 @@ fn ui_attribute_ops(current: Option<&Attributes>, encoded: &Attributes, skip_unc } } for (key, value) in encoded { - let unchanged = current.and_then(|current| current.get(key)).is_some_and(|existing| existing.value == value.value); - if !(skip_unchanged && unchanged) { - deltas.push(AttributeDelta { - key: key.clone(), - value: Some(value.value.clone()), - }); - } + deltas.push(AttributeDelta { + key: key.clone(), + value: Some(value.value.clone()), + }); } deltas.sort_by(|a, b| a.key.cmp(&b.key)); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs index 06301b28db..2a06327f49 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta_tests.rs @@ -1,6 +1,6 @@ use super::DocumentNodePersistentMetadata; use super::InputConnector; -use super::editor_delta::{EditorDelta, NodeMetadataChange, construct_batch}; +use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch}; use super::storage_metadata::StorageMetadataView; use crate::test_utils::test_prelude::*; use document_graph_storage::delta::compute_deltas; @@ -184,6 +184,11 @@ async fn per_field_metadata_edits_match_the_diff() { node_id: node, visible: false, }), + // Pinning a node also appends it to the network's display order, which is network state. + EditorDelta::NetworkMetadata { + network_path: Vec::new(), + change: NetworkMetadataChange::PinnedOrder(vec![node]), + }, ]; let constructed = construct(&editor, &deltas, &working); let diffed = compute_deltas(&working, &convert(&editor)); @@ -343,6 +348,45 @@ async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() { assert_same_stored_effect(&working, constructed, diffed, "emitted import addition"); } +/// An arity change rebuilds the node's whole record, so anything written to that node earlier in the +/// same batch has to survive it. Renaming first and adding the import second is the order that catches +/// a rebuild sourced from the pre-batch registry rather than from what the batch has done so far. +#[tokio::test] +async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + editor + .handle_message(DocumentMessage::GroupSelectedLayers { + group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer, + }) + .await; + + let group = editor + .active_document() + .network_interface + .document_network() + .nodes + .iter() + .find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_))) + .map(|(id, _)| *id) + .expect("the group should be a network node"); + + let working = convert(&editor); + editor.active_document_mut().network_interface.take_deltas(); + + editor.active_document_mut().network_interface.set_display_name(&group, "Renamed".to_string(), &[]); + editor + .active_document_mut() + .network_interface + .add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]); + + let emitted = editor.active_document_mut().network_interface.take_deltas(); + let constructed = construct(&editor, &emitted, &working); + let diffed = compute_deltas(&working, &convert(&editor)); + assert_same_stored_effect(&working, constructed, diffed, "rename then arity change"); +} + #[tokio::test] async fn removing_a_nested_network_node_matches_the_diff() { let mut editor = EditorTestUtils::create(); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs index 8fc92b93ea..5a0213f798 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs @@ -864,9 +864,9 @@ impl NodeNetworkInterface { // Prune this network's pinned display order down to the nodes that still exist, dropping any that were actually removed let surviving_nodes = self.nested_network(network_path).map(|network| network.nodes.keys().copied().collect::>()); if let Some(surviving_nodes) = surviving_nodes - && let Some(network_metadata) = self.network_metadata_mut(network_path) + && let Some(mut network) = self.network_mut(network_path) { - network_metadata.persistent_metadata.pinned_node_order.retain(|node_id| surviving_nodes.contains(node_id)); + network.retain_pinned(|node_id| surviving_nodes.contains(node_id)); } // Purge the deleted nodes' cached wire paths, since the per-node unload can no longer reach them once the nodes are gone @@ -1261,9 +1261,7 @@ impl NodeNetworkInterface { self.disconnect_input(&InputConnector::Export(0), network_path); } } - let Some(network_metadata) = self.network_metadata_mut(network_path) else { - return; - }; - network_metadata.persistent_metadata.previewing = new_previewing_state; + let Some(mut network) = self.network_mut(network_path) else { return }; + network.set_previewing(new_previewing_state); } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs index f5567889c1..3d6e4ccd6d 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap}; use document_graph_storage::attr::session; -use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position}; +use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position, StoredPreviewing, StoredRootNode}; use glam::IVec2; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork}; use graphene_std::vector::style::RenderMode; @@ -16,7 +16,7 @@ use graphene_std::vector::style::RenderMode; use super::memo_network::MemoNetwork; use super::{ DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata, - NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing, + NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing, RootNode, }; use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings; use crate::messages::portfolio::document::utility_types::misc::SnappingState; @@ -112,6 +112,47 @@ impl NodeMetadataSource for StorageMetadataView<'_> { let network_metadata = self.interface.network_metadata.nested_metadata(network_path)?; network_metadata.persistent_metadata.reference.as_deref() } + + fn previewing(&self, network_path: &[NodeId]) -> StoredPreviewing { + let Some(network_metadata) = self.interface.network_metadata.nested_metadata(network_path) else { + return StoredPreviewing::No; + }; + previewing_from_runtime(network_metadata.persistent_metadata.previewing) + } + + fn pinned_order(&self, network_path: &[NodeId]) -> Vec { + self.interface + .network_metadata + .nested_metadata(network_path) + .map(|network_metadata| network_metadata.persistent_metadata.pinned_node_order.clone()) + .unwrap_or_default() + } +} + +/// The runtime preview state in the shape storage stores, still holding runtime node IDs: the +/// conversion resolves those to storage IDs, since it is the only place that can. +pub fn previewing_from_runtime(previewing: Previewing) -> StoredPreviewing { + match previewing { + Previewing::No => StoredPreviewing::No, + Previewing::Yes { root_node_to_restore } => StoredPreviewing::Yes { + root_node_to_restore: root_node_to_restore.map(|root| StoredRootNode { + node_id: root.node_id, + output_index: root.output_index as u32, + }), + }, + } +} + +pub fn previewing_to_runtime(previewing: StoredPreviewing) -> Previewing { + match previewing { + StoredPreviewing::No => Previewing::No, + StoredPreviewing::Yes { root_node_to_restore } => Previewing::Yes { + root_node_to_restore: root_node_to_restore.map(|root| RootNode { + node_id: root.node_id, + output_index: root.output_index as usize, + }), + }, + } } impl DocumentSettings<'_> { @@ -231,13 +272,6 @@ pub fn collect_network_view_settings( settings.insert(session::network::NAV_WIDTH.to_string(), value); } - // Skip the inert `Previewing::No` default so a network that has never been previewed stays empty. - if !matches!(network_metadata.persistent_metadata.previewing, Previewing::No) - && let Ok(value) = serde_json::to_value(network_metadata.persistent_metadata.previewing) - { - settings.insert(session::network::PREVIEWING.to_string(), value); - } - if !settings.is_empty() { out.insert(network_id, settings); } @@ -277,11 +311,6 @@ pub fn apply_network_view_settings( { persistent.navigation_metadata.node_graph_width = width; } - if let Some(value) = settings.get(session::network::PREVIEWING) - && let Ok(previewing) = serde_json::from_value::(value.clone()) - { - persistent.previewing = previewing; - } } } @@ -296,6 +325,8 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries: if let Some(reference) = entry.reference { network_metadata.persistent_metadata.reference = Some(reference); } + network_metadata.persistent_metadata.previewing = previewing_to_runtime(entry.previewing); + network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order; } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/store.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/store.rs index cc23f7571e..1b6afca02a 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/store.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/store.rs @@ -357,6 +357,9 @@ impl NetworkMut<'_> { pub(crate) fn set_previewing(&mut self, previewing: Previewing) -> bool { let changed = self.metadata.previewing != previewing; self.metadata.previewing = previewing; + if changed { + self.emit(NetworkMetadataChange::Previewing(previewing)); + } changed } @@ -365,10 +368,8 @@ impl NetworkMut<'_> { let changed = self.metadata.reference != reference; self.metadata.reference = reference; if changed { - self.deltas.push(EditorDelta::NetworkMetadata { - network_path: self.network_path.to_vec(), - change: NetworkMetadataChange::Reference(self.metadata.reference.clone()), - }); + let change = NetworkMetadataChange::Reference(self.metadata.reference.clone()); + self.emit(change); } changed } @@ -377,17 +378,54 @@ impl NetworkMut<'_> { pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec) -> bool { let changed = self.metadata.pinned_node_order != pinned_node_order; self.metadata.pinned_node_order = pinned_node_order; + if changed { + let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone()); + self.emit(change); + } changed } /// Appends a newly pinned node to the display order, or drops one that is no longer pinned. - pub(crate) fn record_pinned(&mut self, node_id: NodeId, pinned: bool) { + pub(crate) fn record_pinned(&mut self, node_id: NodeId, pinned: bool) -> bool { let order = &mut self.metadata.pinned_node_order; - match pinned { - true if !order.contains(&node_id) => order.push(node_id), - true => {} - false => order.retain(|id| *id != node_id), + let changed = match pinned { + true if !order.contains(&node_id) => { + order.push(node_id); + true + } + true => false, + false => { + let before = order.len(); + order.retain(|id| *id != node_id); + order.len() != before + } + }; + + if changed { + let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone()); + self.emit(change); } + changed + } + + /// Drops every node the order names that is no longer in the network. + pub(crate) fn retain_pinned(&mut self, surviving: impl Fn(&NodeId) -> bool) -> bool { + let before = self.metadata.pinned_node_order.len(); + self.metadata.pinned_node_order.retain(&surviving); + + let changed = self.metadata.pinned_node_order.len() != before; + if changed { + let change = NetworkMetadataChange::PinnedOrder(self.metadata.pinned_node_order.clone()); + self.emit(change); + } + changed + } + + fn emit(&mut self, change: NetworkMetadataChange) { + self.deltas.push(EditorDelta::NetworkMetadata { + network_path: self.network_path.to_vec(), + change, + }); } /// The transform from node graph space to viewport space.