Compare commits

...
Author SHA1 Message Date
Keavon Chambers 838918bc28 WIP expose button type picker 2026-10-08 13:51:44 -07:00
Keavon Chambers f8f3ca5a53 Let documents saved with NaN numbers open, and stop tools from creating them (#4659)
* Let documents saved with NaN numbers open, and stop tools from creating them

* Clamp the node graph's loaded zoom along with the canvas's
2026-10-08 04:53:48 -07:00
Keavon Chambers a2f8a5dd6a Add expect assertions, console error checks, and scenario folders to the web editor driver (#4658)
* Add expect assertions, console error checks, and scenario folders to the web editor driver

* Fail a scenario folder run on unreadable entries instead of skipping them
2026-10-08 03:39:39 -07:00
Keavon Chambers 4c3fabbaa5 Add the web editor driver and control protocol (#4657)
* Add the web editor driver, a Rust port of the editor driver run with `cargo run drive`, built on a new editor control protocol crate with Playwright kept only for browser input and screenshots

* Refuse oversized step counts and empty page sizes, stop Vite if its record can't be saved, center the crosshair on half-pixel pointers, skip Wasm Opt for drive, and re-save the demo artwork
2026-10-08 02:17:20 -07:00
Keavon Chambers e391d10831 Change the 'Evaluate Path' node's tangent output from an angle to a vector and add a normal vector output (#4656) 2026-10-07 18:30:13 -07:00
Keavon Chambers 45f0d21f25 Lint the website with the frontend's ESLint config instead of a separate copy, selecting elements by data attributes (#4655)
* Lint the website with the frontend's ESLint config instead of a diverging copy, selecting elements by data attributes

* Give the crate graph's marker attribute a value, cache npm in the website workflow, and mention installing the website's packages
2026-10-07 16:05:42 -07:00
Keavon Chambers 24746da590 Rename the 'Split/Combine Channels' and 'Split/Combine Vec2' nodes to 'Image to Channels' and 'Vec2 to Numbers' and inverses (#4654)
* Rename the 'Split/Combine Channels' and 'Split/Combine Vec2' nodes to 'Image to Channels', 'Channels to Image', 'Vec2 to Numbers', and 'Numbers to Vec2'

* Fix a Clippy warning in the preprocessor's resource and animation curve input replacement
2026-10-07 13:28:29 -07:00
Keavon Chambers 8ef7432e33 Rework 'Split Vec2' and 'Split Channels' as multi-output nodes and merge 'Position/Tangent on Path' into 'Evaluate Path' (#4645) 2026-10-07 12:33:20 -07:00
Dennis Kobert e4bcb13b2a Retire hot ops at their authored stamps (#4637)
Retire hot ops at their authored stamps, index history, and reserve the retirement time
2026-10-07 18:53:44 +00:00
Dennis Kobert 275d3d0af9 Change CRDT logic to use tombstoning instead of ad-hoc resurrection (#4636)
Make every registry field, existence included, last-writer-wins with presence stamps and tombstones
2026-10-07 16:19:26 +00:00
GavinandTimon 02a60ce521 Add animation curves and animation curve node input preprocessing (#4290)
* add: f-curve implementation

* add: proof of concept animation nodes

* fix: improve f-curves performance and correctness

* chore: remove hardcoded animation curve value node

* fix: ensure keyframes meet preconditions when deserializing AnimationCurve

* refactor: move animation types into new crate

* fix: evaluate animation curves based on current animation time

* add: AnimationCurve preprocessing and node input visiting

* fix: remove dead node checks in preprocessor

* Review

---------

Co-authored-by: Timon <[email protected]>
2026-10-07 14:26:14 +00:00
James Lindsay d033921124 Improve document_migration_upgrades time complexity to remove O(n^2) (#4626) 2026-10-07 13:38:32 +00:00
Keavon Chambers 4e4dc189f2 Add node macro support for multi-output nodes, with a Destructure derive on the returned struct (#4557) 2026-10-07 03:05:36 -07:00
Keavon Chambers 59aa4510d0 Fix the Pen tool misplacing anchors and losing a handle when joining another layer's path (#4652)
* Fix the Pen tool misplacing anchors and losing a handle when joining another layer's path

* Keep the latest pointer move made while a join waits for the merged path, so a quick drag still shapes the handle
2026-10-07 01:34:07 -07:00
Dennis Kobert e38fab2245 Record the user behind each peer, with last-writer-wins registration (#4635)
* Make Attributes a struct

* Record the user behind each peer, with last-writer-wins registration
2026-10-05 20:53:09 +00:00
James Lindsay 7ec230b71a Ensure the test executor always finishes deferred messages (#4630)
* Ensure the test exeuctor always finishes deferred messages

* Fail after 16 iterations
2026-10-05 20:49:40 +00:00
James LindsayandKeavon Chambers 8f323f09bc Update convert_case to 0.12 and add tests confirming the 'String Capitalization' node's behavior is unchanged (#4604)
* Add tests for String Capitalization node and update convert_case dependency

* Add a sample_str variable to the test

* Keep 'String Capitalization' joiner output unchanged by dropping empty words after the convert_case 0.12 bump

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-10-04 05:32:27 +00:00
Keavon Chambers 38e4036230 Fix the Path tool showing a small box selection square when clicking during animation playback (#4648) 2026-10-03 21:29:15 -07:00
Keavon Chambers 658f03704f Rewrite the 'Image Color Palette' node using Wu's color quantizer in OkLab (#4642)
* Rewrite the 'Image Color Palette' node using Wu's color quantizer in OkLab

* Weight alpha at 16-bit precision in the 'Image Color Palette' node so faint pixels count
2026-10-02 22:58:04 -07:00
Keavon Chambers 34eedcc3ac Add a math expression widget with typeset math, syntax highlighting, tooltips, and completions (#4633)
Add a math expression widget with typeset math italics and syntax highlighting
2026-10-02 19:00:07 -07:00
Keavon Chambers bb7c1a2073 Add an ESLint rule requiring DOM queries to select elements by data-* attributes (#4641) 2026-10-02 17:22:03 -07:00
198 changed files with 15991 additions and 5957 deletions

No files matched your search

+15 -2
View File
@@ -7,9 +7,15 @@ on:
- master
paths:
- website/**
- frontend/eslint.config.js
- frontend/eslint-require-data-selectors.js
- frontend/package-lock.json
pull_request:
paths:
- website/**
- frontend/eslint.config.js
- frontend/eslint-require-data-selectors.js
- frontend/package-lock.json
env:
CARGO_TERM_COLOR: always
INDEX_HTML_HEAD_INCLUSION: <script defer data-domain="graphite.art" data-api="/visit/event" src="/visit/script.hash.js"></script>
@@ -30,6 +36,10 @@ jobs:
uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: |
frontend/package-lock.json
website/package-lock.json
- name: 🕸 Install Zola
uses: taiki-e/install-action@v2
@@ -55,9 +65,12 @@ jobs:
cargo run -p crate-hierarchy-viz -- website/generated
cargo run -p editor-message-tree -- website/generated
- name: 🔧 Install website npm dependencies
- name: 🔧 Install website and frontend npm dependencies
run: |
cd website
# The website is linted by the frontend's ESLint config and the tools it installs
cd frontend
npm ci
cd ../website
npm ci
- name: 📃 Generate node catalog documentation
Generated
+50 -2
View File
@@ -831,9 +831,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "convert_case"
version = "0.8.0"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baaaa0ecca5b51987b9423ccdc971514dd8b0bb7b4060b983d3664dad3f1f89f"
checksum = "1af709f1f33454bf52eadfc8c78b3b9ef9cb26fb54d16dc9cd9a7299f899fd1b"
dependencies = [
"unicode-segmentation",
]
@@ -2040,6 +2040,7 @@ dependencies = [
"dyn-any",
"glam 0.33.10",
"graph-craft",
"graphene-animation",
"graphene-application-io",
"graphene-core",
"graphene-hash",
@@ -2066,6 +2067,17 @@ dependencies = [
"wgpu-executor",
]
[[package]]
name = "graphene-animation"
version = "0.0.0"
dependencies = [
"dyn-any",
"glam 0.33.10",
"graphene-hash",
"kurbo",
"serde",
]
[[package]]
name = "graphene-application-io"
version = "0.0.0"
@@ -2129,6 +2141,7 @@ dependencies = [
"core-types",
"dyn-any",
"glam 0.33.10",
"graphene-animation",
"graphene-hash",
"graphic-types",
"log",
@@ -2413,6 +2426,15 @@ dependencies = [
"zip",
]
[[package]]
name = "graphite-editor-control-protocol"
version = "0.0.0"
dependencies = [
"glam 0.33.10",
"serde",
"serde_json",
]
[[package]]
name = "graphite-proc-macros"
version = "0.0.0"
@@ -2990,6 +3012,7 @@ dependencies = [
"futures",
"glam 0.33.10",
"graph-craft",
"graphene-animation",
"graphene-core",
"graphene-std",
"gungraun",
@@ -3427,7 +3450,9 @@ name = "math-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam 0.33.10",
"graphene-core",
"graphic-types",
"log",
"math-parser",
@@ -4397,10 +4422,15 @@ checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
name = "preprocessor"
version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"futures",
"glam 0.33.10",
"graph-craft",
"graphene-std",
"interpreted-executor",
"log",
"node-macro",
]
[[package]]
@@ -4612,11 +4642,13 @@ name = "raster-nodes"
version = "0.0.0"
dependencies = [
"bytemuck",
"color",
"core-types",
"dyn-any",
"fastnoise-lite",
"futures",
"glam 0.33.10",
"graphene-core",
"graphene-hash",
"graphene-resource",
"image",
@@ -6873,6 +6905,22 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "web-editor-driver"
version = "0.0.0"
dependencies = [
"base64",
"clap",
"getrandom 0.3.3",
"glam 0.33.10",
"graphite-editor-control-protocol",
"image",
"interprocess",
"serde",
"serde_json",
"windows-sys 0.61.2",
]
[[package]]
name = "web-sys"
version = "0.3.98"
+5 -1
View File
@@ -12,6 +12,7 @@ members = [
"document/graph-storage",
"document/container",
"editor",
"editor/control-protocol",
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
@@ -35,6 +36,7 @@ members = [
"tools/third-party-licenses",
"tools/editor-message-tree",
"tools/node-docs",
"tools/web-editor-driver",
]
default-members = [
"editor",
@@ -77,6 +79,7 @@ preprocessor = { path = "node-graph/preprocessor" }
math-parser = { path = "libraries/math-parser" }
graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" }
graphene-animation = { path = "node-graph/libraries/animation" }
core-types = { path = "node-graph/libraries/core-types" }
no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
@@ -106,6 +109,7 @@ wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
wgpu-sync = { path = "libraries/wgpu-sync" }
graphite-proc-macros = { path = "proc-macros" }
graphite-editor = { path = "editor" }
graphite-editor-control-protocol = { path = "editor/control-protocol" }
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
ipsum = { path = "libraries/ipsum" }
@@ -123,7 +127,7 @@ env_logger = "0.11"
log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
ctor = "0.2"
convert_case = "0.8"
convert_case = "0.12"
titlecase = "3.6"
fancy-regex = "0.18.0"
unicode-segmentation = "1.13.2"
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplicationLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3]Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed"Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<allocLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":1415828794531Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
+10 -2
View File
@@ -146,6 +146,7 @@ impl<L: Layout> Gdd<L> {
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let session_state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
@@ -194,8 +195,15 @@ impl<L: Layout> Gdd<L> {
if options.include_registry {
// With history, the persisted snapshot is the retired registry and the hot log layers on top
// (mirrors `Session::load`); without history it must be the full working registry, since
// `bootstrap_from_registry` reconstructs the whole document from it alone.
let snapshot = if options.include_history { export_session.retired_registry() } else { export_session.registry() };
// `bootstrap_from_registry` reconstructs the whole document from it alone. That document starts a history of
// its own, so the tombstones go.
let live;
let snapshot = if options.include_history {
export_session.retired_registry()
} else {
live = export_session.registry().without_tombstones();
&live
};
sink.write_entry(&io::path_for(self.layout.registry_basename(), codecs.registry), &codecs.registry.write_single(snapshot)?)?;
}
+10 -5
View File
@@ -16,7 +16,7 @@ use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -141,18 +141,19 @@ impl<L: Layout> Gdd<L> {
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
let peer = session_state.peer_id;
let user = session_state.user_id;
let mut session = match (has_registry, has_history) {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, registry)?
Session::bootstrap_from_registry(peer, user, registry)?
}
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
@@ -178,7 +179,11 @@ impl<L: Layout> Gdd<L> {
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
let codecs = manifest.codecs;
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
let session_state = SessionState { peer_id: peer, ..Default::default() };
let session_state = SessionState {
peer_id: peer,
user_id: UserId(peer.0),
..Default::default()
};
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
let session = Session::with_peer(peer);
+5 -6
View File
@@ -134,7 +134,7 @@ impl<L: Layout> Gdd<L> {
/// advanced past what the working copy reflects, so the caller should treat the document as needing
/// re-persist (mirrors [`stage_runtime_snapshot`](Self::stage_runtime_snapshot)).
pub fn apply_hot_op(&mut self, op: HotOp) -> Result<(), Error> {
self.session.apply_hot_op(op.clone())?;
self.session.replay_hot_op(op.clone())?;
self.append_hot_frame(&op)?;
Ok(())
}
@@ -194,6 +194,7 @@ impl<L: Layout> Gdd<L> {
fn persist_session_state(&mut self) -> Result<(), Error> {
let state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
@@ -205,12 +206,10 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
Ok(())
}
+4 -1
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{NetworkId, PeerId, Rev, Value};
use document_graph_storage::{NetworkId, PeerId, Rev, UserId, Value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,6 +15,9 @@ pub struct SessionState {
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// The person using this device, registered in the CRDT so undo and authorship follow them across peer ids.
#[serde(default)]
pub user_id: UserId,
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
/// document (no commits yet).
#[serde(default)]
+40 -2
View File
@@ -596,11 +596,19 @@ fn first_commit_registers_peer_and_survives_reopen() {
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
assert_eq!(
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"first commit registers the peer"
);
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
assert_eq!(
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"registration survives reopen"
);
});
}
@@ -682,3 +690,33 @@ fn declarations_round_trip_through_byte_store() {
}
});
}
#[cfg(feature = "conversion")]
#[test]
fn an_export_without_history_drops_tombstones() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::{Network, NetworkId, RegistryDelta};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let id = NetworkId(7);
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
.unwrap();
gdd.stage_constructed_ops(vec![RegistryDelta::RemoveNetwork { id, snapshot: Network::default() }], &Default::default(), &empty_byte_store())
.unwrap();
assert!(gdd.registry().removed_networks.contains_key(&id));
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("flat");
let options = ExportOptions {
include_history: false,
..ExportOptions::default()
};
gdd.export(&dest, ExportFormat::Folder, options, &empty_byte_store(), None)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
let reopened = GddV1::open(&dest).await.unwrap_or_else(|error| panic!("open failed: {error:?}"));
assert!(reopened.registry().removed_networks.is_empty(), "a document without history starts without tombstones");
});
}
@@ -0,0 +1,69 @@
// Staging a whole document after a recorded batch, and what a reopen must carry over.
#![cfg(feature = "conversion")]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NoMetadata, PeerId, Registry};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_resource::ResourceRegistry;
fn network_with_one_node() -> NodeNetwork {
let node = DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
call_argument: concrete!(()),
..Default::default()
};
NodeNetwork {
nodes: [(NodeId(1), node)].into_iter().collect(),
..Default::default()
}
}
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
#[test]
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
let store = HashMapResourceStorage::new();
let resources = ResourceRegistry::new();
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
.expect("first whole-document stage");
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
let hot_before = gdd.session().hot_log().len();
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
.expect("the runtime already matches what was staged");
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
}
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
#[test]
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
use document_graph_storage::{AttributeDelta, HotOp, RegistryDelta, TimeStamp, Value};
let set = |value: u32, counter: u64| HotOp {
op: RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: "k".into(),
value: Some(Value::from(serde_json::json!(value))),
},
},
timestamp: TimeStamp { counter, peer: PeerId(22) },
};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
gdd.apply_hot_op(set(1, 1)).unwrap();
gdd.apply_hot_op(set(2, 2)).unwrap();
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
let retired = gdd.session().retired_registry().clone();
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap();
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
assert_eq!(reopened.session().hot_log().len(), 1);
});
}
+175 -25
View File
@@ -1,6 +1,6 @@
use crate::{TimeStamp, Value, ValueError, from_value, to_value};
use crate::{AttributeDelta, TimeStamp, Value, ValueError, from_value, to_value};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::collections::{BTreeMap, btree_map};
/// Attribute keys. Glob-import (`use crate::attr::*`) at conversion sites.
///
@@ -8,64 +8,214 @@ use std::collections::BTreeMap;
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// A type-erased attribute value paired with the timestamp at which it was last set.
/// An attribute value and when it was last set. A deleted key stays as a stamped tombstone, which readers see as absent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AttributeValue {
pub value: Value,
pub timestamp: TimeStamp,
// No skipping: the registry is positional on disk.
#[serde(default)]
pub deleted: bool,
}
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp }
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: Value::None,
timestamp,
deleted: true,
}
}
}
pub type Attributes = BTreeMap<String, AttributeValue>;
/// Attribute keys and their values, each last-writer-wins on its own timestamp. A key the map lacks is deleted as of
/// its floor, when the map was last written whole.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Attributes {
entries: BTreeMap<String, AttributeValue>,
#[serde(default)]
floor: TimeStamp,
}
impl Attributes {
pub fn new() -> Self {
Self::default()
}
/// An empty map written whole at `floor`, which deletes every key older than it.
pub fn empty_at(floor: TimeStamp) -> Self {
Self { entries: BTreeMap::new(), floor }
}
/// When the map was last written whole.
pub fn floor(&self) -> TimeStamp {
self.floor
}
/// Carries `floor` with the entries, so they land as the map they were taken from rather than as a new write.
pub fn set_floor(&mut self, floor: TimeStamp) {
self.floor = floor;
}
pub fn get(&self, key: &str) -> Option<&AttributeValue> {
self.entries.get(key)
}
pub fn contains_key(&self, key: &str) -> bool {
self.entries.contains_key(key)
}
/// Every entry, tombstones included.
pub fn iter(&self) -> btree_map::Iter<'_, String, AttributeValue> {
self.entries.iter()
}
pub fn keys(&self) -> btree_map::Keys<'_, String, AttributeValue> {
self.entries.keys()
}
/// The live entries: every key that is not a tombstone.
pub fn live(&self) -> impl Iterator<Item = (&String, &AttributeValue)> {
self.entries.iter().filter(|(_, value)| !value.deleted)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn insert(&mut self, key: String, value: AttributeValue) -> Option<AttributeValue> {
self.entries.insert(key, value)
}
pub fn remove(&mut self, key: &str) -> Option<AttributeValue> {
self.entries.remove(key)
}
/// Lands a single-key write if it is newer than the key's value, or than the floor for a key the map lacks. A
/// deletion leaves a tombstone.
pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp, force: bool) {
let AttributeDelta { key, value } = delta;
let decided = self.get(&key).map_or(self.floor, |existing| existing.timestamp);
if !force && timestamp <= decided {
return;
}
let entry = match value {
Some(value) => AttributeValue::new(value, timestamp),
None => AttributeValue::deleted(timestamp),
};
self.insert(key, entry);
}
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts `value` under `key`.
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp);
pub fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
}
/// Serializes `value` and inserts it under `key`.
fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
pub fn set_serialized<T: serde::Serialize>(&mut self, key: &str, value: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
self.set(key, to_value(value)?, timestamp);
Ok(())
}
/// Inserts only when `value != default`, so the read side falls back to the same default.
fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
pub fn set_if_not_default<T: serde::Serialize + PartialEq>(&mut self, key: &str, value: &T, default: &T, timestamp: TimeStamp) -> Result<(), ValueError> {
if value != default {
self.set_serialized(key, value, timestamp)?;
}
Ok(())
}
}
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
self.insert(key.to_string(), AttributeValue { value, timestamp });
/// Deserializes the value under `key`, or `None` if missing, deleted or undecodable.
pub fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
}
}
/// Typed read helpers for `Attributes`.
pub trait AttributesRead {
/// Deserializes the value under `key`, or `None` if missing or undecodable.
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T>;
/// Same as `get_typed`, falling back to `default`.
fn get_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
pub fn get_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
self.get_typed(key).unwrap_or(default)
}
/// Same as `get_typed`, falling back to `T::default()`.
fn get_or_default<T: serde::de::DeserializeOwned + Default>(&self, key: &str) -> T {
pub fn get_or_default<T: serde::de::DeserializeOwned + Default>(&self, key: &str) -> T {
self.get_typed(key).unwrap_or_default()
}
/// Writes the map whole at `timestamp`: the floor deletes every other key without a tombstone per key.
pub(crate) fn stamp(&mut self, timestamp: TimeStamp) {
self.entries.retain(|_, value| !value.deleted);
self.entries.values_mut().for_each(|value| value.timestamp = timestamp);
self.floor = timestamp;
}
/// Stamps what arrives unstamped: the whole map if it carries no floor, else only the entries at the origin.
pub(crate) fn stamp_unstamped(&mut self, timestamp: TimeStamp) {
if self.floor == TimeStamp::ORIGIN {
return self.stamp(timestamp);
}
self.entries
.values_mut()
.filter(|value| value.timestamp == TimeStamp::ORIGIN)
.for_each(|value| value.timestamp = timestamp);
}
/// Folds `other` in key by key: the newer entry wins, and a key only one map holds dies if the other map's floor is
/// newer, as that map was written whole after it.
pub(crate) fn merge(&mut self, other: Attributes) {
self.entries.retain(|_, value| value.timestamp >= other.floor);
for (key, value) in other.entries {
match self.entries.entry(key) {
btree_map::Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
btree_map::Entry::Vacant(entry) if value.timestamp >= self.floor => {
entry.insert(value);
}
_ => {}
}
}
self.floor = self.floor.max(other.floor);
}
/// The newest stamp the map carries, its floor included.
pub(crate) fn newest(&self) -> TimeStamp {
self.entries.values().map(|value| value.timestamp).fold(self.floor, TimeStamp::max)
}
}
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).and_then(|v| from_value(&v.value).ok())
impl FromIterator<(String, AttributeValue)> for Attributes {
fn from_iter<I: IntoIterator<Item = (String, AttributeValue)>>(iter: I) -> Self {
Self {
entries: iter.into_iter().collect(),
floor: TimeStamp::ORIGIN,
}
}
}
impl Extend<(String, AttributeValue)> for Attributes {
fn extend<I: IntoIterator<Item = (String, AttributeValue)>>(&mut self, iter: I) {
self.entries.extend(iter);
}
}
impl IntoIterator for Attributes {
type Item = (String, AttributeValue);
type IntoIter = btree_map::IntoIter<String, AttributeValue>;
fn into_iter(self) -> Self::IntoIter {
self.entries.into_iter()
}
}
impl<'a> IntoIterator for &'a Attributes {
type Item = (&'a String, &'a AttributeValue);
type IntoIter = btree_map::Iter<'a, String, AttributeValue>;
fn into_iter(self) -> Self::IntoIter {
self.entries.iter()
}
}
+43 -36
View File
@@ -1,16 +1,10 @@
use crate::{
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value,
attr, compute_rev,
};
use crate::{Attributes, Implementation, 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};
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
///
/// `reverse` is state-dependent undo bookkeeping (it captures pre-state at the moment the forward
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
/// observing the same forward delta against different local states would otherwise compute
/// different Revs for the same logical op.
/// `reverse` is undo bookkeeping that depends on local state, so it is stored but left out of the identity hash.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delta {
pub id: Rev,
@@ -25,6 +19,10 @@ pub struct Delta {
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
#[serde(default)]
pub attributes: Attributes,
/// When the delta entered history, in Unix milliseconds by the retiring peer's clock; display only and outside the rev.
/// Zero means unrecorded, saving the tag byte of an `Option`. Last, since the history codec is positional.
#[serde(default)]
pub(crate) retired_at_ms: u64,
}
impl Delta {
@@ -38,6 +36,7 @@ impl Delta {
kind,
reverse,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -58,6 +57,7 @@ impl Delta {
reverse: kind.clone(),
kind,
attributes: Attributes::default(),
retired_at_ms: 0,
}
}
@@ -79,6 +79,11 @@ impl Delta {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
}
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
pub fn retired_at(&self) -> Option<u64> {
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
/// via `new`/`merge`; differs only if `id` was tampered with or the hash derivation changed.
pub fn recomputed_id(&self) -> Rev {
@@ -101,8 +106,7 @@ pub enum RegistryDelta {
id: NodeId,
node: Node,
},
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
/// the registry, mirroring `RemoveNetwork`.
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
RemoveNode {
id: NodeId,
snapshot: Node,
@@ -155,13 +159,12 @@ pub enum RegistryDelta {
id: NetworkId,
network: Network,
},
/// `snapshot` lets the reverse delta rebuild without re-walking history.
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
RemoveNetwork {
id: NetworkId,
snapshot: Network,
},
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
AddResource {
id: ResourceId,
entry: ResourceEntry,
@@ -190,9 +193,7 @@ pub enum RegistryDelta {
id: ResourceId,
key: SourceKey,
},
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
/// First write wins; conflicting re-registration errors. Duplicate identical registration
/// is a no-op. Not LWW — the mapping is forever.
/// Registers a device's `PeerId` to the `UserId` behind it; the newest registration wins.
RegisterPeer {
peer: PeerId,
user: UserId,
@@ -221,28 +222,34 @@ pub struct AttributeDelta {
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
AttributeDelta {
key: delta.key.clone(),
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
}
}
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
let AttributeDelta { key, value } = delta;
match value {
Some(value) => match attributes.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
if force || timestamp > entry.get().timestamp {
entry.insert(AttributeValue { value, timestamp });
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(AttributeValue { value, timestamp });
}
},
None => {
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
if should_remove {
attributes.remove(&key);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unrecorded_retired_at_costs_one_byte_and_round_trips() {
let base = Delta::new(
None,
PeerId(1),
TimeStamp { counter: 1, peer: PeerId(1) },
RegistryDelta::Other(Value::None),
RegistryDelta::Other(Value::None),
);
let mut stamped = base.clone();
stamped.retired_at_ms = 1_790_000_000_000;
let bare_base = postcard::to_allocvec(&base).expect("encode");
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
assert_eq!(decoded.retired_at(), None);
}
}
+10 -7
View File
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
}
for (key, _) in &from.sources {
for (key, _) in from.live_sources() {
if to.source(key).is_none() {
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
}
}
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
for (key, to_source) in &to.sources {
for (key, to_source) in to.live_sources() {
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
deltas.push(RegistryDelta::AddSource {
id,
@@ -196,15 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
for key in from.keys() {
if !to.contains_key(key) {
for (key, _) in from.live() {
if to.get(key).is_none_or(|value| value.deleted) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
for (key, to_value) in to.live() {
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(to_value.value.clone()),
@@ -298,7 +298,7 @@ mod tests {
#[test]
fn test_compute_deltas_change_network_attribute() {
use crate::{AttributesWrite, TimeStamp};
use crate::TimeStamp;
let mut from = Registry::default();
from.networks.insert(NetworkId(0), Network::default());
@@ -340,6 +340,7 @@ mod tests {
crate::AttributeValue {
value: Value::Str("old".into()),
timestamp: stamp(0),
deleted: false,
},
);
from.node_instances.insert(NodeId(42), node);
@@ -350,6 +351,7 @@ mod tests {
crate::AttributeValue {
value: Value::Str("new".into()),
timestamp: stamp(1),
deleted: false,
},
);
@@ -375,6 +377,7 @@ mod tests {
crate::AttributeValue {
value: Value::Str("value".into()),
timestamp: stamp(1),
deleted: false,
},
);
+513 -244
View File
@@ -1,23 +1,24 @@
use std::collections::HashMap;
use std::hash::Hash;
use crate::{
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp, Value,
apply_attribute_delta, reverse_attribute_delta,
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput, PeerId,
PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, Rev, SourceValue, TimeStamp, Tombstone, UserId, Value, reverse_attribute_delta,
};
use std::borrow::Cow;
#[derive(Clone, Debug)]
pub struct Document {
/// Working registry: retired state with the current hot ops applied on top. This is what live
/// reads and `registry()` observe, and what undo/redo force-apply against.
/// reads and `registry()` observe.
pub(crate) working_registry: Registry,
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
pub(crate) hot_log: Vec<HotOp>,
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
/// new edits win
/// hot-polluted working state) and advances it. It equals the working registry whenever the hot log is
/// empty.
pub(crate) retired_snapshot: Registry,
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
pub(crate) head: Option<Rev>,
@@ -28,9 +29,8 @@ pub struct Document {
pub(crate) redo_stack: Vec<Rev>,
pub(crate) clock: LamportClock,
pub(crate) peer: PeerId,
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
/// Commits after this can be rewritten silently; commits at or before this are published
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
pub(crate) user: UserId,
/// The latest retired commit a peer holds: commits after it undo silently, commits up to it stay.
pub(crate) last_broadcast_rev: Option<Rev>,
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
@@ -39,6 +39,22 @@ pub struct Document {
}
impl Document {
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
Self {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
user,
last_broadcast_rev: None,
next_node_counter: 0,
}
}
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
/// truncated; the counter is shared across peers and persisted with the document.
pub fn next_node_id(&mut self) -> NodeId {
@@ -51,42 +67,6 @@ impl Document {
NodeId(u64::from_le_bytes(truncated))
}
pub(crate) fn restore_node_from_history(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNode { id, .. } if id == node_id))
.ok_or(CrdtError::NodeNotInHistory(node_id))?;
self.revert_delta(target, delta)
}
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
// which is what we want to re-apply.
let delta = self
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
self.revert_delta(target, delta)
}
/// Search every delta reachable from `head` (following all parents, including a merge's
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
/// ancestry reachability, so a node added only on a merged-in branch is still found.
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
while let Some(rev) = queue.pop_front() {
let Some(delta) = self.history.get(rev) else { continue };
if predicate(delta) {
return Some(delta.clone());
}
for parent in delta.all_parents() {
if seen.insert(parent) {
queue.push_back(parent);
}
}
}
None
}
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
/// the same timestamp as the forward op it undoes.
@@ -100,26 +80,21 @@ impl Document {
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
}
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
/// Doesn't touch history or `head` — hot ops are transient.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
/// Stage a local op onto the working registry and the hot log.
pub(crate) fn stage_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
self.hot_log.push(hot_op);
Ok(())
}
/// Replay a hot op recovered from persisted state. Idempotent on structural ops so that
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
/// than an error.
/// Replay a persisted or received hot op. One already reflected in the registry changes nothing.
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
self.hot_log.push(hot_op);
Ok(())
}
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
/// targets, Remove on missing ones) since hot ops already produced the structural state.
/// The point is to bump field timestamps to T_retire via the LWW arms.
/// Apply a retired commit and record it in history.
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
for parent in delta.all_parents() {
if !self.history.contains(parent) {
@@ -135,26 +110,24 @@ impl Document {
fn registry_mut(&mut self, target: RegistryTarget) -> &mut Registry {
match target {
RegistryTarget::Working => &mut self.working_registry,
RegistryTarget::Snapshot => &mut self.retired_snapshot,
RegistryTarget::Retired => &mut self.retired_snapshot,
}
}
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
match target {
RegistryTarget::Working => &self.working_registry,
RegistryTarget::Snapshot => &self.retired_snapshot,
RegistryTarget::Retired => &self.retired_snapshot,
}
}
/// New local/remote op against the working registry: add ops error on duplicate targets and
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
/// A fresh local edit against the working registry; see [`ApplyMode::Strict`].
#[cfg(test)]
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Strict)
}
/// Replay/retire against the working registry: structural ops skip duplicate/missing targets (the
/// state is already present from hot ops or a prior snapshot); LWW arms still gate on strict `>`.
/// An op from a peer or from persisted state, against the working registry.
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
}
@@ -166,146 +139,180 @@ impl Document {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
}
/// Applies one op. Every field, existence included, is last-writer-wins on a timestamp, so ops fold alike in any order:
/// an addition writes every field, a removal keeps the content as a tombstone, a newer write or reference revives an
/// older removal, and a write to an entity never seen lands on a placeholder until its addition arrives.
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
// Advance the local clock past every observed op, including ones that subsequently no-op or
// error. Observation is about causality knowledge, not about whether the op took effect.
self.clock.observe(timestamp);
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
// LWW arms assign unconditionally only under `Force`.
let idempotent = mode != ApplyMode::Live;
let strict = mode == ApplyMode::Strict;
let force = mode == ApplyMode::Force;
// Resurrect any concurrently-removed targets the op references before binding the registry
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
self.ensure_referenced_exist(target, &op)?;
let registry = self.registry_mut(target);
match op {
RegistryDelta::AddNode { id, node } => {
if registry.node_instances.contains_key(&id) {
if idempotent {
// Hot ops already created this node; skip rather than error.
return Ok(());
}
if strict && registry.node_instances.contains_key(&id) {
return Err(CrdtError::NodeAlreadyExists(id));
}
registry.node_instances.insert(id, node);
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp, force);
}
RegistryDelta::RemoveNode { id, .. } => {
registry.node_instances.remove(&id);
RegistryDelta::RemoveNode { id, snapshot } => {
remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp, force);
}
RegistryDelta::SetNodeInputs { id, inputs } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
// The list is one value rather than independently mergeable slots, so the newest slot stands in
// for a timestamp the list itself does not carry, and an older write is dropped whole.
let newest = node.inputs.iter().map(|slot| slot.timestamp).max().unwrap_or(TimeStamp::ORIGIN);
if force || timestamp > newest {
// The slots arrive carrying the placeholder timestamp they were built with, so they take this
// op's instead. Leaving the placeholder would reset every slot to the origin and make each
// later per-slot gate vacuously true, letting a stale write win.
node.inputs = inputs.into_iter().map(|slot| crate::InputSlot { timestamp, ..slot }).collect();
RegistryDelta::SetNodeInputs { id, mut inputs } => {
inputs.iter_mut().for_each(|slot| stamp_listed_slot(slot, timestamp));
let referenced: Vec<NodeId> = inputs
.iter()
.filter_map(|slot| match slot.input {
NodeInput::Node { id, .. } => Some(id),
_ => None,
})
.collect();
ensure_seen(registry, &referenced, mode)?;
write_node(registry, id, timestamp, mode, |node| {
if force {
node.inputs = inputs;
node.inputs_timestamp = timestamp;
} else {
merge_inputs(node, inputs, timestamp);
}
Ok(())
})?;
for referenced in referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
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))?;
if force || timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
let referenced = match new_input {
NodeInput::Node { id, .. } => Some(id),
_ => None,
};
ensure_seen(registry, referenced.as_slice(), mode)?;
write_node(registry, id, timestamp, mode, |node| {
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
if force || timestamp > input.timestamp {
input.input = new_input;
input.timestamp = timestamp;
}
Ok(())
})?;
if let Some(referenced) = referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
if force || timestamp > node.implementation_timestamp {
node.implementation = implementation;
node.implementation_timestamp = timestamp;
ensure_seen(registry, &[id], mode)?;
if let Implementation::Network(network) = implementation {
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
}
write_node(registry, id, timestamp, mode, |node| {
if force || timestamp > node.implementation_timestamp {
node.implementation = implementation;
node.implementation_timestamp = timestamp;
}
Ok(())
})?;
}
RegistryDelta::ChangeNodeAttribute { id, delta } => {
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
write_node(registry, id, timestamp, mode, |node| {
node.attributes.apply_delta(delta, timestamp, force);
Ok(())
})?;
}
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
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))?;
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
write_node(registry, id, timestamp, mode, |node| {
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
input.attributes.apply_delta(delta, timestamp, force);
Ok(())
})?;
}
RegistryDelta::SetNetworkExport { id, index, export } => {
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
let slot_idx = index as usize;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
let referenced = match export {
Some(NodeInput::Node { id, .. }) => Some(id),
_ => None,
};
ensure_seen(registry, referenced.as_slice(), mode)?;
write_network(registry, id, timestamp, mode, |net| {
let slot_idx = index as usize;
if slot_idx >= net.exports.len() {
if slot_idx >= MAX_EXPORT_SLOTS {
return Err(CrdtError::ExportSlotOutOfBounds(index));
}
// Past the end of a newer list the slot is gone, as with input slots.
if !force && timestamp <= net.exports_timestamp {
return Ok(());
}
let shape = net.exports_timestamp;
net.exports.resize_with(slot_idx + 1, || ExportSlot { target: None, timestamp: shape });
}
net.exports.resize(
slot_idx + 1,
ExportSlot {
target: None,
timestamp: TimeStamp::ORIGIN,
},
);
}
let existing = &mut net.exports[slot_idx];
if force || timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
let existing = &mut net.exports[slot_idx];
if force || timestamp > existing.timestamp {
existing.target = export;
existing.timestamp = timestamp;
}
Ok(())
})?;
if let Some(referenced) = referenced {
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
}
}
RegistryDelta::AddNetwork { id, network: contents } => {
if registry.networks.contains_key(&id) {
if idempotent {
return Ok(());
}
RegistryDelta::AddNetwork { id, network } => {
if strict && registry.networks.contains_key(&id) {
return Err(CrdtError::NetworkAlreadyExists(id));
}
registry.networks.insert(id, contents);
add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp, force);
}
RegistryDelta::RemoveNetwork { id, .. } => {
registry.networks.remove(&id);
RegistryDelta::RemoveNetwork { id, snapshot } => {
remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp, force);
}
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
write_network(registry, id, timestamp, mode, |net| {
net.attributes.apply_delta(delta, timestamp, force);
Ok(())
})?;
}
RegistryDelta::SetResourceHash { id, hash } => {
let entry = registry.resources.entry(id).or_default();
if force || timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
upsert_resource(registry, id, timestamp, |entry| {
if force || timestamp > entry.hash_timestamp {
entry.hash = hash;
entry.hash_timestamp = timestamp;
}
});
}
RegistryDelta::AddSource { id, key, source } => {
let entry = registry.resources.entry(id).or_default();
let value = SourceValue { source, timestamp };
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
upsert_resource(registry, id, timestamp, |entry| {
let value = SourceValue { source, timestamp, deleted: false };
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
});
}
RegistryDelta::RemoveSource { id, key } => {
if let Some(entry) = registry.resources.get_mut(&id) {
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
upsert_resource(registry, id, timestamp, |entry| {
if force {
entry.force_remove_source(&key);
} else {
entry.remove_source(&key, timestamp);
}
}
});
}
RegistryDelta::AddResource { id, entry } => {
registry.resources.insert(id, entry);
add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp, force);
}
RegistryDelta::RemoveResource { id, .. } => {
registry.resources.remove(&id);
RegistryDelta::RemoveResource { id, snapshot } => {
remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp, force);
}
RegistryDelta::RegisterPeer { peer, user } => match registry.peer_users.get(&peer) {
Some(existing) if *existing != user => return Err(CrdtError::PeerRegistrationConflict(peer)),
Some(_) => {}
None => {
registry.peer_users.insert(peer, user);
RegistryDelta::RegisterPeer { peer, user } => {
// The newest registration of a device wins, whatever order they land in.
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.timestamp) {
registry.peer_users.insert(peer, PeerRegistration { user, timestamp });
}
},
}
RegistryDelta::ChangeDocumentAttribute { delta } => {
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
registry.attributes.apply_delta(delta, timestamp, force);
}
// Merge is a structural sync point only; it mutates no registry state.
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
@@ -313,99 +320,42 @@ impl Document {
Ok(())
}
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
/// before the node. No-op for ops that reference nothing absent.
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
match op {
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
if let NodeInput::Node { id: referenced, .. } = new_input {
self.ensure_node_exists(target, *referenced)?;
}
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::SetNodeImplementation { id, implementation } => {
if let crate::Implementation::Network(network) = implementation {
self.ensure_network_exists(target, *network)?;
}
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, ..
} => {
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
self.ensure_node_exists(target, *referenced)?;
}
self.ensure_network_exists(target, *network)?;
}
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
_ => {}
}
Ok(())
}
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
self.restore_node_from_history(target, node_id)?;
}
Ok(())
}
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
if !self.registry_ref(target).networks.contains_key(&network_id) {
self.restore_network_from_history(target, network_id)?;
}
Ok(())
}
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
/// [`RegistryTarget::Retired`] so LWW reverses (export target, inputs, attributes, resource hash)
/// capture the true pre-op value rather than the hot-polluted working state.
///
/// A write reads its pre-op value from wherever it lands: the live entity, its tombstone, or for an
/// entity never seen, a placeholder.
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
let registry = self.registry_ref(target);
let node = |id: NodeId| registry.node_or_removed(id).map_or_else(|| Cow::Owned(Node::placeholder()), Cow::Borrowed);
let unset = InputSlot::unset(TimeStamp::ORIGIN);
let network = |id: NetworkId| registry.network_or_removed(id);
let resource = |id: ResourceId| registry.resources.get(&id).or_else(|| registry.removed_resources.get(&id).map(|mark| &mark.content));
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::SetNodeImplementation { id, .. } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation.clone(),
}
}
&RegistryDelta::SetNodeInputs { id, .. } => RegistryDelta::SetNodeInputs { id, inputs: node(id).inputs.clone() },
&RegistryDelta::SetNodeImplementation { id, .. } => RegistryDelta::SetNodeImplementation {
id,
implementation: node(id).implementation.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))?;
let node = node(id);
let slot = node.inputs().get(input_idx as usize).unwrap_or(&unset);
RegistryDelta::ChangeNodeInput {
id,
index: input_idx,
new_input: slot.input.clone(),
}
}
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
RegistryDelta::ChangeNodeAttribute {
id,
delta: reverse_attribute_delta(delta, node.attributes()),
}
}
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => RegistryDelta::ChangeNodeAttribute {
id,
delta: reverse_attribute_delta(delta, node(id).attributes()),
},
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
let node = node(id);
let input = node.inputs().get(index as usize).unwrap_or(&unset);
RegistryDelta::ChangeNodeInputAttribute {
id,
index,
@@ -413,15 +363,15 @@ impl Document {
}
}
&RegistryDelta::SetNetworkExport { id, index, .. } => {
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
// since pre-forward there was no export to point at.
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
// Absent network or slot: pre-op there was no export to point at.
let export_target = network(id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
RegistryDelta::SetNetworkExport { id, index, export: export_target }
}
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
let empty = Attributes::new();
let current = network(id).map_or(&empty, |net| &net.attributes);
RegistryDelta::ChangeNetworkAttribute {
id,
delta: reverse_attribute_delta(delta, current),
@@ -435,9 +385,9 @@ impl Document {
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
id,
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
hash: resource(id).and_then(|entry| entry.hash),
},
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
&RegistryDelta::AddSource { id, key, .. } => match resource(id).and_then(|entry| entry.source(&key)) {
// The slot already held a source: undo restores it.
Some(existing) => RegistryDelta::AddSource {
id,
@@ -447,7 +397,7 @@ impl Document {
// The slot was empty: undo removes what this op added.
None => RegistryDelta::RemoveSource { id, key },
},
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
&RegistryDelta::RemoveSource { id, key } => match resource(id).and_then(|entry| entry.source(&key)) {
Some(existing) => RegistryDelta::AddSource {
id,
key,
@@ -475,22 +425,341 @@ impl Document {
}
}
/// An entity whose existence and every field are last-writer-wins on a timestamp.
pub(crate) trait Entity: Sized {
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
fn presence(&self) -> TimeStamp;
fn set_presence(&mut self, timestamp: TimeStamp);
/// Stamps every field at `timestamp`, the way an addition writes all of them.
fn stamp_all(&mut self, timestamp: TimeStamp);
/// Folds `other` in, keeping whichever value of each field is newer.
fn merge(&mut self, other: Self);
/// Content for writes to land on before the addition, every field at the origin so the addition's win.
fn placeholder() -> Self;
}
impl Entity for Node {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, timestamp: TimeStamp) {
self.presence = timestamp;
}
fn placeholder() -> Self {
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
}
fn stamp_all(&mut self, timestamp: TimeStamp) {
self.presence = timestamp;
self.network_timestamp = timestamp;
self.inputs_timestamp = timestamp;
self.implementation_timestamp = timestamp;
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
self.attributes.stamp(timestamp);
}
fn merge(&mut self, other: Self) {
if other.network_timestamp > self.network_timestamp {
self.network = other.network;
self.network_timestamp = other.network_timestamp;
}
if other.implementation_timestamp > self.implementation_timestamp {
self.implementation = other.implementation;
self.implementation_timestamp = other.implementation_timestamp;
}
merge_inputs(self, other.inputs, other.inputs_timestamp);
self.attributes.merge(other.attributes);
self.presence = self.presence.max(other.presence);
}
}
impl Entity for Network {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, timestamp: TimeStamp) {
self.presence = timestamp;
}
fn placeholder() -> Self {
Network::default()
}
fn stamp_all(&mut self, timestamp: TimeStamp) {
self.presence = timestamp;
self.exports_timestamp = timestamp;
self.exports.iter_mut().for_each(|slot| slot.timestamp = timestamp);
self.attributes.stamp(timestamp);
}
fn merge(&mut self, other: Self) {
// As `merge_inputs`: the newer list decides the slot count, and a slot written after that shape survives past it.
let (mut newer, shape, older) = if other.exports_timestamp > self.exports_timestamp {
(other.exports, other.exports_timestamp, std::mem::take(&mut self.exports))
} else {
(std::mem::take(&mut self.exports), self.exports_timestamp, other.exports)
};
for (index, incoming) in older.into_iter().enumerate() {
if index >= newer.len() {
if incoming.timestamp <= shape {
continue;
}
newer.resize_with(index + 1, || ExportSlot { target: None, timestamp: shape });
}
if incoming.timestamp > newer[index].timestamp {
newer[index] = incoming;
}
}
self.exports = newer;
self.exports_timestamp = shape;
self.attributes.merge(other.attributes);
self.presence = self.presence.max(other.presence);
}
}
impl Entity for ResourceEntry {
fn presence(&self) -> TimeStamp {
self.presence
}
fn set_presence(&mut self, timestamp: TimeStamp) {
self.presence = timestamp;
}
fn placeholder() -> Self {
ResourceEntry::default()
}
fn stamp_all(&mut self, timestamp: TimeStamp) {
self.presence = timestamp;
self.hash_timestamp = timestamp;
self.stamp_sources(timestamp);
}
fn merge(&mut self, other: Self) {
if other.hash_timestamp > self.hash_timestamp {
self.hash = other.hash;
self.hash_timestamp = other.hash_timestamp;
}
self.merge_sources(other.sources, other.sources_timestamp);
self.presence = self.presence.max(other.presence);
}
}
fn stamp_slot(slot: &mut InputSlot, timestamp: TimeStamp) {
slot.timestamp = timestamp;
slot.attributes.stamp(timestamp);
}
/// Stamps a slot of a written input list. Attributes carried over with their own stamps keep them, and a floor carried
/// with them, so they only win where they already did; what arrives unstamped is written at `timestamp`.
fn stamp_listed_slot(slot: &mut InputSlot, timestamp: TimeStamp) {
slot.timestamp = timestamp;
slot.attributes.stamp_unstamped(timestamp);
}
/// Folds an input list stamped `timestamp` into the node's: the newer list decides the slot count, a slot written after that
/// shape survives past it, and a slot both hold keeps its newer value, so list and slot writes land alike in any order.
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, timestamp: TimeStamp) {
let (mut newer, shape, older) = if timestamp > node.inputs_timestamp {
(other, timestamp, std::mem::take(&mut node.inputs))
} else {
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
};
// A slot the older list lacks was absent as of that list's shape, as a write past its end would find it.
let older_shape = if shape == timestamp { node.inputs_timestamp } else { timestamp };
for slot in newer.iter_mut().skip(older.len()) {
slot.attributes.merge(Attributes::empty_at(older_shape));
}
for (index, incoming) in older.into_iter().enumerate() {
if index >= newer.len() {
if slot_newest(&incoming) <= shape {
continue;
}
newer.resize_with(index + 1, || InputSlot::unset(shape));
}
let slot = &mut newer[index];
if incoming.timestamp > slot.timestamp {
slot.input = incoming.input;
slot.timestamp = incoming.timestamp;
}
slot.attributes.merge(incoming.attributes);
}
node.inputs = newer;
node.inputs_timestamp = shape;
}
/// The newest write the slot carries, its attributes included.
fn slot_newest(slot: &InputSlot) -> TimeStamp {
slot.timestamp.max(slot.attributes.newest())
}
/// The slot at `index` for a write at `timestamp`; past the end it exists only if the write is newer than the list's shape.
fn slot_for_write(node: &mut Node, index: usize, timestamp: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
if index >= node.inputs.len() {
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Strict {
return Err(CrdtError::InputIndexOutOfBounds(index));
}
if mode != ApplyMode::Force && timestamp <= node.inputs_timestamp {
return Ok(None);
}
let shape = node.inputs_timestamp;
node.inputs.resize_with(index + 1, || InputSlot::unset(shape));
}
Ok(node.inputs.get_mut(index))
}
/// The entity's content wherever it sits: live, or held by its tombstone.
fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'a mut HashMap<K, Tombstone<T>>, id: K) -> Option<&'a mut T> {
live.get_mut(&id).or_else(|| dead.get_mut(&id).map(|mark| &mut mark.content))
}
/// Revives a removed entity whose presence has grown past its removal. A placeholder stays dead.
fn revive_if_newer<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.timestamp) {
let mark = dead.remove(&id).expect("checked above");
live.insert(id, mark.content);
}
}
/// Folds an addition's or removal's content into what is held under `id`. It proves the entity was added, so a placeholder
/// holding it stops being one.
fn merge_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
// The placeholder holds only early writes: they land on the real content as if the addition came first.
let early = std::mem::replace(&mut mark.content, content);
mark.content.merge(early);
mark.placeholder = false;
} else if let Some(existing) = content_mut(live, dead, id) {
existing.merge(content);
} else {
live.insert(id, content);
}
revive_if_newer(live, dead, id);
}
/// An addition at `timestamp`: every field written at `timestamp`, live unless a newer removal holds it dead.
fn add_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, timestamp: TimeStamp, force: bool) {
if force {
dead.remove(&id);
live.insert(id, content);
return;
}
content.stamp_all(timestamp);
merge_entity(live, dead, id, content);
}
/// A removal at `timestamp`: dead unless a newer addition or write holds it live. The snapshot folds in first, so a removal of an
/// entity never seen still lands.
fn remove_entity<K: Hash + Eq + Copy, T: Entity>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, timestamp: TimeStamp, force: bool) {
merge_entity(live, dead, id, snapshot);
if let Some(mark) = dead.get_mut(&id) {
mark.timestamp = if force { timestamp } else { mark.timestamp.max(timestamp) };
} else if live.get(&id).is_some_and(|content| force || timestamp > content.presence()) {
let content = live.remove(&id).expect("checked above");
dead.insert(
id,
Tombstone {
content,
timestamp,
placeholder: false,
},
);
}
}
/// A write at `timestamp` to the entity under `id`, wherever its content sits: it revives an older removal, and lands on a
/// placeholder for an entity never seen. A fresh local edit on one gets `missing()` instead.
fn write_entity<K: Hash + Eq + Copy, T: Entity>(
live: &mut HashMap<K, T>,
dead: &mut HashMap<K, Tombstone<T>>,
id: K,
timestamp: TimeStamp,
mode: ApplyMode,
missing: impl FnOnce() -> CrdtError,
f: impl FnOnce(&mut T) -> Result<(), CrdtError>,
) -> Result<(), CrdtError> {
let force = mode == ApplyMode::Force;
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
if unseen {
if mode == ApplyMode::Strict {
return Err(missing());
}
dead.insert(
id,
Tombstone {
content: T::placeholder(),
timestamp: TimeStamp::ORIGIN,
placeholder: true,
},
);
}
let content = content_mut(live, dead, id).expect("held above");
if let Err(error) = f(content) {
// A rejected op changes nothing, so the placeholder made for it goes too.
if unseen {
dead.remove(&id);
}
return Err(error);
}
content.set_presence(content.presence().max(timestamp));
if force && let Some(mark) = dead.remove(&id) {
live.insert(id, mark.content);
}
revive_if_newer(live, dead, id);
Ok(())
}
/// A fresh local edit cannot name a node never seen. Checked before an op's first write, so a refused op changes nothing.
fn ensure_seen(registry: &Registry, ids: &[NodeId], mode: ApplyMode) -> Result<(), CrdtError> {
let unseen = |id: &&NodeId| !registry.node_instances.contains_key(id) && !registry.removed_nodes.contains_key(id);
match ids.iter().find(unseen) {
Some(&id) if mode == ApplyMode::Strict => Err(CrdtError::TargetNodeDoesNotExist(id)),
_ => Ok(()),
}
}
/// [`write_entity()`] to a node; with a no-op `f`, records a reference to it.
fn write_node(registry: &mut Registry, id: NodeId, timestamp: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
write_entity(
&mut registry.node_instances,
&mut registry.removed_nodes,
id,
timestamp,
mode,
|| CrdtError::TargetNodeDoesNotExist(id),
f,
)
}
fn write_network(registry: &mut Registry, id: NetworkId, timestamp: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
write_entity(&mut registry.networks, &mut registry.removed_networks, id, timestamp, mode, || CrdtError::NetworkDoesNotExist(id), f)
}
/// [`write_entity()`] for a resource, creating an entry never seen first, since single-field resource ops are upserts.
fn upsert_resource(registry: &mut Registry, id: ResourceId, timestamp: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
registry.resources.insert(
id,
ResourceEntry {
presence: timestamp,
..ResourceEntry::default()
},
);
}
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
f(entry);
entry.set_presence(entry.presence().max(timestamp));
revive_if_newer(&mut registry.resources, &mut registry.removed_resources, id);
}
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
/// live hot ops) or the retired snapshot (retired deltas only). Retirement targets the snapshot so
/// reverses capture pre-op values; the hot path and undo/redo target the working copy.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum RegistryTarget {
Working,
Snapshot,
Retired,
}
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
/// How [`Document::apply_op_with`] treats what it finds.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ApplyMode {
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
Live,
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
/// A fresh local edit: adding what exists or writing to what was never seen is an error.
Strict,
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
Idempotent,
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
/// Silent-zone undo/redo rewind: every write lands, whatever its timestamp.
Force,
}
+28 -6
View File
@@ -11,8 +11,8 @@ use serde::Serialize;
use crate::attr::*;
use crate::metadata_source::{NoMetadata, NodeMetadataSource};
use crate::{
AttributesWrite, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value,
ValueError, from_value, to_value,
ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ProtoNode, ROOT_NETWORK, Registry, ResourceHash, ResourceId, TimeStamp, Value, ValueError, from_value,
to_value,
};
fn map_serialization_error(key: &str) -> impl FnOnce(ValueError) -> ConversionError + '_ {
@@ -221,11 +221,13 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
peer,
};
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
entry.force_set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
);
}
@@ -339,7 +341,15 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
write_ui_network_attributes(&mut attributes, node_network, 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 });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
exports_timestamp: TimeStamp::ORIGIN,
attributes,
},
);
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
@@ -411,6 +421,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
let mut inputs = Vec::with_capacity(doc_node.inputs.len());
for (input_index, input) in doc_node.inputs.iter().enumerate() {
let mut input_attrs = convert_input_attributes(input)?;
input_attrs.set_floor(timestamp);
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
inputs.push(InputSlot {
@@ -432,7 +443,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
let mut attributes = crate::Attributes::new();
let mut attributes = crate::Attributes::empty_at(timestamp);
attributes
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
@@ -449,6 +460,9 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
Ok(Node {
presence: timestamp,
network_timestamp: timestamp,
inputs_timestamp: timestamp,
implementation,
implementation_timestamp: timestamp,
inputs,
@@ -812,7 +826,15 @@ impl<'m> ScopedConversion<'m> {
write_ui_network_attributes(&mut attributes, node_network, 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 });
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
exports_timestamp: TimeStamp::ORIGIN,
attributes,
},
);
Ok(())
}
+49 -10
View File
@@ -3,21 +3,26 @@
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
//! collaboration where the leader serializes retired commits), so appending preserves the order by
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
//! which re-sorts the combined set into the canonical order to restore the invariant.
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
//! a canonical sort.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp, Value};
use crate::{CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
/// Every rev some delta names as a parent.
referenced: HashSet<Rev>,
/// Deltas no other delta names as a parent.
tips: HashSet<Rev>,
/// Content hashes the deltas name, from resource additions and removals.
resource_hashes: HashSet<ResourceHash>,
}
impl History {
@@ -27,8 +32,9 @@ impl History {
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
let mut history = Self::default();
deltas.into_iter().for_each(|delta| history.push(delta));
history
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -39,6 +45,11 @@ impl History {
self.index.contains_key(&rev)
}
/// The content hashes named by any resource addition or removal in history.
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
&self.resource_hashes
}
pub fn len(&self) -> usize {
self.deltas.len()
}
@@ -51,10 +62,25 @@ impl History {
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
RegistryDelta::SetResourceHash { hash: Some(hash), .. } => {
self.resource_hashes.insert(*hash);
}
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
for parent in delta.all_parents() {
self.referenced.insert(parent);
self.tips.remove(&parent);
}
if !self.referenced.contains(&delta.id) {
self.tips.insert(delta.id);
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
@@ -119,11 +145,24 @@ impl History {
}
}
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
let mut seen = HashSet::new();
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
while let Some(rev) = stack.pop() {
if seen.insert(rev)
&& let Some(delta) = self.get(rev)
{
stack.extend(delta.all_parents());
}
}
seen
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
tips.sort_unstable();
tips
}
+2
View File
@@ -56,6 +56,8 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
/// slot index forcing an unbounded `exports` allocation.
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
+1
View File
@@ -42,6 +42,7 @@ pub use to_runtime::Declarations;
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod round_trip;
}
+63 -9
View File
@@ -4,14 +4,23 @@ use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// The latest addition or write, so a concurrent removal resolves by stamp; see [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub(crate) network: NetworkId,
/// When the node was last added, which decides its network between concurrent additions of one id.
#[serde(default)]
pub(crate) network_timestamp: TimeStamp,
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
#[serde(default)]
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
/// When the input list last changed shape, so list and slot writes resolve alike in either order.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) attributes: Attributes,
pub(crate) network: NetworkId,
}
impl Node {
@@ -47,15 +56,25 @@ impl Node {
attributes_value_equal(&self.attributes, &other.attributes)
}
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
/// slot by position.
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
Self {
presence: TimeStamp::ORIGIN,
network_timestamp: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
attributes: Attributes::new(),
network,
}
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self {
implementation: Implementation::ProtoNode(ResourceId::new()),
implementation_timestamp: TimeStamp::default(),
inputs: vec![],
attributes: Attributes::new(),
network: crate::ROOT_NETWORK,
}
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
}
}
@@ -68,6 +87,22 @@ pub struct InputSlot {
pub attributes: Attributes,
}
impl InputSlot {
/// A slot holding nothing, stamped `timestamp`.
pub fn unset(timestamp: TimeStamp) -> Self {
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
Self {
input: NodeInput::Value {
value: Value::Str("None".to_string()),
exposed: false,
},
timestamp,
attributes: Attributes::empty_at(timestamp),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeInput {
Node {
@@ -97,7 +132,13 @@ pub enum Implementation {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// The latest addition or write; see [`Node::presence`](crate::Node).
#[serde(default)]
pub(crate) presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// When the export list last changed shape; see [`Node::inputs_timestamp`](crate::Node).
#[serde(default)]
pub(crate) exports_timestamp: TimeStamp,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
@@ -125,7 +166,7 @@ impl Network {
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
/// on concurrent `SetExport` ops.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ExportSlot {
pub target: Option<NodeInput>,
pub timestamp: TimeStamp,
@@ -159,6 +200,19 @@ mod tests {
}
}
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
/// in step with how `TaggedValue::None` serializes.
#[test]
fn unset_input_slot_deserializes_as_tagged_value_none() {
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
panic!("a fresh slot holds a value input");
};
let tagged: graph_craft::document::value::TaggedValue = crate::from_value(value).expect("the unset slot value must deserialize");
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
}
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
/// the same network without that slot, so the soak oracle doesn't false-report drift.
#[test]
+107 -21
View File
@@ -1,7 +1,10 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document. Every field, existence included, is last-writer-wins on a timestamp, so the registry depends on the
/// set of ops applied and not their order. A removed entity keeps a tombstone: an older op lands on it, a newer one
/// revives the entity.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
@@ -9,13 +12,58 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
pub peer_users: HashMap<PeerId, UserId>,
/// Which person each device is, from `RegistryDelta::RegisterPeer`, so undo and authorship scope by person.
pub peer_users: HashMap<PeerId, PeerRegistration>,
pub attributes: Attributes,
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub timestamp: TimeStamp,
}
/// A removed entity's content, for reviving it, and its removal stamp.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub timestamp: TimeStamp,
/// Nothing has added the entity yet: it stays dead until an addition folds in, the content holding writes that came first.
#[serde(default)]
pub placeholder: bool,
}
impl Registry {
/// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold.
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
}
/// The network under `id`, live or as it was when removed.
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
/// The live entities alone, for a document starting a history of its own: tombstones only order removals against ops
/// that share this one.
pub fn without_tombstones(&self) -> Registry {
Registry {
removed_nodes: HashMap::new(),
removed_networks: HashMap::new(),
removed_resources: HashMap::new(),
..self.clone()
}
}
/// True if both registries agree on every value-bearing field, ignoring per-slot and
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
@@ -85,10 +133,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if a.len() != b.len() {
if a.live().count() != b.live().count() {
return false;
}
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
a.live().all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
}
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
@@ -100,54 +148,92 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
a.iter().all(|(id, entry)| {
b.get(id).is_some_and(|other| {
entry.hash == other.hash
&& entry.sources.len() == other.sources.len()
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
&& entry.live_sources().count() == other.live_sources().count()
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
})
})
}
/// Stable identity for any timestamped slot in a `Registry`. Used by `order_consistent`.
/// Stable identity for any timestamp in a `Registry`, tombstoned content and existence stamps included. Used by
/// `order_consistent`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum TimestampKey {
/// A whole-entity stamp under its field name: presence, a shape or floor, a removal.
Node(NodeId, &'static str),
NodeInput(NodeId, usize),
NodeInputFloor(NodeId, usize),
NodeInputAttribute(NodeId, usize, String),
NodeAttribute(NodeId, String),
Network(NetworkId, &'static str),
NetworkExport(NetworkId, usize),
NetworkAttribute(NetworkId, String),
DocumentAttribute(String),
ResourceHash(ResourceId),
Resource(ResourceId, &'static str),
ResourceSource(ResourceId, SourceKey),
Document(&'static str),
PeerRegistration(PeerId),
}
fn collect_timestamps(registry: &Registry) -> HashMap<TimestampKey, TimeStamp> {
let mut out = HashMap::new();
for (node_id, node) in &registry.node_instances {
let nodes = registry.node_instances.iter().chain(registry.removed_nodes.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, node) in nodes {
for (field, timestamp) in [
("presence", node.presence),
("network", node.network_timestamp),
("inputs", node.inputs_timestamp),
("implementation", node.implementation_timestamp),
("attributes", node.attributes.floor()),
] {
out.insert(TimestampKey::Node(id, field), timestamp);
}
for (i, slot) in node.inputs.iter().enumerate() {
out.insert(TimestampKey::NodeInput(*node_id, i), slot.timestamp);
out.insert(TimestampKey::NodeInput(id, i), slot.timestamp);
out.insert(TimestampKey::NodeInputFloor(id, i), slot.attributes.floor());
for (key, value) in &slot.attributes {
out.insert(TimestampKey::NodeInputAttribute(*node_id, i, key.clone()), value.timestamp);
out.insert(TimestampKey::NodeInputAttribute(id, i, key.clone()), value.timestamp);
}
}
for (key, value) in &node.attributes {
out.insert(TimestampKey::NodeAttribute(*node_id, key.clone()), value.timestamp);
out.insert(TimestampKey::NodeAttribute(id, key.clone()), value.timestamp);
}
}
for (network_id, network) in &registry.networks {
let networks = registry.networks.iter().chain(registry.removed_networks.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, network) in networks {
for (field, timestamp) in [("presence", network.presence), ("exports", network.exports_timestamp), ("attributes", network.attributes.floor())] {
out.insert(TimestampKey::Network(id, field), timestamp);
}
for (i, slot) in network.exports.iter().enumerate() {
out.insert(TimestampKey::NetworkExport(*network_id, i), slot.timestamp);
out.insert(TimestampKey::NetworkExport(id, i), slot.timestamp);
}
for (key, value) in &network.attributes {
out.insert(TimestampKey::NetworkAttribute(*network_id, key.clone()), value.timestamp);
out.insert(TimestampKey::NetworkAttribute(id, key.clone()), value.timestamp);
}
}
out.insert(TimestampKey::Document("attributes"), registry.attributes.floor());
for (key, value) in &registry.attributes {
out.insert(TimestampKey::DocumentAttribute(key.clone()), value.timestamp);
}
for (id, entry) in &registry.resources {
out.insert(TimestampKey::ResourceHash(*id), entry.hash_timestamp);
for (source_key, source_value) in &entry.sources {
out.insert(TimestampKey::ResourceSource(*id, *source_key), source_value.timestamp);
let resources = registry.resources.iter().chain(registry.removed_resources.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, entry) in resources {
for (field, timestamp) in [("presence", entry.presence), ("hash", entry.hash_timestamp), ("sources", entry.sources_timestamp)] {
out.insert(TimestampKey::Resource(id, field), timestamp);
}
for (source_key, source_value) in &entry.sources {
out.insert(TimestampKey::ResourceSource(id, *source_key), source_value.timestamp);
}
}
for (&id, mark) in &registry.removed_nodes {
out.insert(TimestampKey::Node(id, "removed"), mark.timestamp);
}
for (&id, mark) in &registry.removed_networks {
out.insert(TimestampKey::Network(id, "removed"), mark.timestamp);
}
for (&id, mark) in &registry.removed_resources {
out.insert(TimestampKey::Resource(id, "removed"), mark.timestamp);
}
for (&peer, registration) in &registry.peer_users {
out.insert(TimestampKey::PeerRegistration(peer), registration.timestamp);
}
out
}
+107 -31
View File
@@ -18,6 +18,20 @@ pub struct SourceKey {
pub struct SourceValue {
pub source: Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, which readers see as absent.
#[serde(default)]
pub deleted: bool,
}
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
source: Value::None,
timestamp,
deleted: true,
}
}
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
@@ -26,8 +40,12 @@ pub struct SourceValue {
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// The latest addition or write; see [`Node::presence`](crate::Node).
pub(crate) presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition; a key the chain lacks is deleted as of then.
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
@@ -39,12 +57,22 @@ impl<'de> Deserialize<'de> for ResourceEntry {
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
@@ -57,7 +85,13 @@ impl<'de> Deserialize<'de> for ResourceEntry {
true
});
Ok(Self { sources, hash, hash_timestamp })
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
}
}
@@ -68,52 +102,89 @@ impl ResourceEntry {
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let priority = Priority::new(0.).expect("0. is finite");
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
let sources = vec![(
SourceKey { priority, peer },
SourceValue {
source: embedded,
timestamp,
deleted: false,
},
)];
Self {
presence: timestamp,
sources,
sources_timestamp: timestamp,
hash: Some(hash),
hash_timestamp: timestamp,
}
}
/// The source body and timestamp stored under `key`, if any.
/// The live source stored under `key`, if any; a tombstone is absent.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => self.sources.insert(index, (key, value)),
}
/// The live sources in precedence order, tombstones skipped.
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
}
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
fn deciding_timestamp(&self, key: &SourceKey) -> TimeStamp {
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
}
fn put(&mut self, key: SourceKey, value: SourceValue) {
match self.find(&key) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
/// whether anything was removed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) if timestamp > self.sources[index].1.timestamp => {
self.sources.remove(index);
true
/// Writes the chain whole at `timestamp`: the floor deletes every other key without a tombstone per key.
pub(crate) fn stamp_sources(&mut self, timestamp: TimeStamp) {
self.sources.retain(|(_, value)| !value.deleted);
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = timestamp);
self.sources_timestamp = timestamp;
}
/// Folds another chain in key by key, as attribute maps merge.
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
for (key, value) in other {
match self.find(&key) {
Ok(index) if value.timestamp > self.sources[index].1.timestamp => self.sources[index].1 = value,
Err(index) if value.timestamp >= self.sources_timestamp => self.sources.insert(index, (key, value)),
_ => {}
}
_ => false,
}
self.sources_timestamp = self.sources_timestamp.max(other_floor);
}
/// Insert or LWW-overwrite the entry at `key`; a re-set wins only with a strictly newer stamp.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
if value.timestamp > self.deciding_timestamp(&key) {
self.put(key, value);
}
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind, or building an entry).
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
self.put(key, value);
}
/// Remove the source at `key` if `timestamp` is newer than what decides it, leaving a tombstone. Returns whether it landed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
if timestamp <= self.deciding_timestamp(key) {
return false;
}
self.put(*key, SourceValue::deleted(timestamp));
true
}
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
@@ -130,15 +201,14 @@ impl ResourceEntry {
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
pub fn has_embedded_source(&self) -> bool {
self.sources
.iter()
self.live_sources()
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
}
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
/// highest-precedence fallback.
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
SourceKey {
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
peer,
@@ -247,12 +317,15 @@ mod tests {
SourceValue {
source: Value::Float(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
let unsorted = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![source(2.), source(0.), source(1.)],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
@@ -277,11 +350,14 @@ mod tests {
SourceValue {
source: Value::Str(body.into()),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
let with_duplicates = ResourceEntry {
presence: TimeStamp::ORIGIN,
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![entry(5, "newer"), entry(1, "older")],
hash: None,
hash_timestamp: TimeStamp::ORIGIN,
+63 -76
View File
@@ -29,22 +29,15 @@ impl Session {
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
}
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
/// `Session::new`.
/// A session for `peer` standing for itself as a person, for tests and tools without a stored identity.
pub fn with_peer(peer: PeerId) -> Self {
Self::with_identity(peer, UserId(peer.0))
}
/// A session for device `peer` used by person `user`, whom its registration records.
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
Self {
document: Document {
working_registry: Registry::default(),
retired_snapshot: Registry::default(),
history: History::new(),
hot_log: Vec::new(),
head: None,
redo_stack: Vec::new(),
clock: LamportClock::new(peer),
peer,
last_broadcast_rev: None,
next_node_counter: 0,
},
document: Document::empty(peer, user),
remote_tips: HashMap::new(),
}
}
@@ -53,6 +46,15 @@ impl Session {
self.document.peer
}
pub fn user(&self) -> UserId {
self.document.user
}
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
}
pub fn registry(&self) -> &Registry {
&self.document.working_registry
}
@@ -142,16 +144,16 @@ impl Session {
///
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
if pending.is_empty() {
return Ok(Vec::new());
}
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
let user = UserId(self.document.peer.0);
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
let (peer, user) = (self.document.peer, self.document.user);
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
}
let mut staged = Vec::with_capacity(pending.len());
@@ -160,7 +162,7 @@ impl Session {
op,
timestamp: self.document.clock.tick(),
};
self.document.apply_hot_op(hot_op.clone())?;
self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict)?;
staged.push(hot_op);
}
Ok(staged)
@@ -168,19 +170,23 @@ impl Session {
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
///
/// Operates on the *retired snapshot*: reverses are computed against and forward ops applied to it,
/// so each `reverse` captures the true pre-op value rather than the hot-polluted working state. The
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
/// equal the snapshot when there are none), so it is left untouched.
/// Operates on the retired snapshot, so each `reverse` holds the true pre-op state; the working registry already
/// reflects the ops, staged before retirement or equal to the snapshot when nothing is hot.
///
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
/// applied hot op) so duplicate structural inserts no-op rather than error.
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
let target = RegistryTarget::Snapshot;
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
}
/// [`commit_ops`](Self::commit_ops) for ops paired with their authored stamp (`None` to mint one), which retirement keeps
/// so LWW resolves as it did live.
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
let target = RegistryTarget::Retired;
let ops = ops.into_iter();
let mut produced = Vec::with_capacity(ops.size_hint().0);
for op in ops {
for (op, authored_at) in ops {
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
@@ -189,9 +195,9 @@ impl Session {
}
let reverse = self.document.compute_reverse_delta(target, &op)?;
let timestamp = self.document.clock.tick();
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
let parent = self.document.head;
let author = self.document.peer;
let author = timestamp.peer;
let delta = Delta::new(parent, author, timestamp, op, reverse);
let rev = delta.id;
@@ -202,7 +208,7 @@ impl Session {
{
return Err(CrdtError::NotFoundInHistory(parent));
}
let mode = if idempotent { ApplyMode::Idempotent } else { ApplyMode::Live };
let mode = if idempotent { ApplyMode::Idempotent } else { ApplyMode::Strict };
self.document.apply_op_with(target, delta.kind.clone(), delta.timestamp, mode)?;
self.document.history.push(delta);
self.document.head = Some(rev);
@@ -215,7 +221,7 @@ impl Session {
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
/// (topological) order.
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
pub fn load(peer: PeerId, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
let mut clock = LamportClock::new(peer);
for delta in &history {
clock.observe(delta.timestamp);
@@ -228,13 +234,11 @@ impl Session {
retired_snapshot: registry.clone(),
working_registry: registry,
history: History::from_ordered(history),
hot_log: Vec::new(),
head,
redo_stack,
clock,
peer,
last_broadcast_rev: None,
next_node_counter,
..Document::empty(peer, user)
},
remote_tips: HashMap::new(),
}
@@ -242,8 +246,8 @@ impl Session {
/// Rebuild the registry from scratch by applying every delta in causal order.
/// `deltas` must be in causal order (every parent before its children).
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_peer(peer);
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
let mut session = Self::with_identity(peer, user);
session.document.next_node_counter = next_node_counter;
for delta in deltas {
@@ -258,11 +262,6 @@ impl Session {
Ok(session)
}
/// Apply a hot op without going through the broadcast stream.
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
self.document.apply_hot_op(hot_op)
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
/// where the registry may already reflect the op's effect from a prior retired snapshot.
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
@@ -301,25 +300,28 @@ impl Session {
Ok(Some(merge_rev))
}
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
///
/// Today: one retired delta per hot op. Coarsening is a future step.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
let mut drained = Vec::new();
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
for hot_op in self.document.hot_log.drain(..) {
if hot_op.timestamp <= up_to {
drained.push(hot_op);
} else {
remaining.push(hot_op);
}
/// The retired snapshot as history alone gives it: the fold of `head`'s ancestry, leaving out undone deltas kept for redo.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
let reachable = self.document.history.ancestors(self.document.head);
let mut scratch = Document::empty(self.document.peer, self.document.user);
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
}
self.document.hot_log = remaining;
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
Ok(scratch.working_registry)
}
pub fn history_len(&self) -> usize {
self.document.history.len()
}
/// Promote every hot op stamped at or before `up_to` into retired deltas in hot-log order, each keeping its authored
/// stamp.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| hot_op.timestamp <= up_to);
self.document.hot_log = kept;
let ops = drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
self.commit_ops_authored_at(ops, true)
}
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
pub fn mark_interaction_end(&mut self, rev: Rev) {
@@ -435,9 +437,9 @@ impl Session {
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
let ops = crate::delta::compute_deltas(&Registry::default(), &registry);
let mut session = Self::with_peer(peer);
let mut session = Self::with_identity(peer, user);
session.commit_ops(ops, false)?;
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
session.document.working_registry = session.document.retired_snapshot.clone();
@@ -465,18 +467,10 @@ impl Session {
/// interaction's `AddResource` from the working registry, so a redoable (or re-undoable) interaction's
/// resources no longer appear in `registry().resources` even though redo still needs them. Resource GC
/// must keep this whole set alive, not just the current head's, or undo then redo loses declaration
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot and `SetResourceHash`.
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
for delta in self.document.history.iter() {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
_ => {}
}
}
hashes.extend(self.document.history.resource_hashes());
hashes
}
@@ -542,7 +536,7 @@ impl Session {
}
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
/// test can observe a failure (e.g. `NotFoundInHistory`).
#[cfg(test)]
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
self.commit_ops(std::iter::once(op), false).map(|_| ())
@@ -594,10 +588,6 @@ pub enum CrdtError {
ExportSlotOutOfBounds(u32),
#[error("Delta {0} not found in history")]
NotFoundInHistory(Rev),
#[error("No history entry resurrects node {0}")]
NodeNotInHistory(NodeId),
#[error("No history entry resurrects network {0}")]
NetworkNotInHistory(NetworkId),
#[error("Nothing to undo")]
NothingToUndo,
#[error("Nothing to redo")]
@@ -606,9 +596,6 @@ pub enum CrdtError {
NodeAlreadyExists(NodeId),
#[error("Network {0} already exists")]
NetworkAlreadyExists(NetworkId),
/// PeerId is already registered to a different UserId.
#[error("Peer {0:?} is already registered to a different user")]
PeerRegistrationConflict(PeerId),
#[error("Delta stored under {stored} hashes to {expected}")]
RevMismatch { stored: Rev, expected: Rev },
}
@@ -0,0 +1,90 @@
use crate::{AttributeDelta, CrdtError, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
value: Some(Value::from(serde_json::json!(value))),
},
}
}
fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
}
}
/// Every op commutes, so the snapshot folds to the working registry's values whatever the log order.
#[test]
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
let mut host = Session::with_peer(PeerId(1));
// The log is in arrival order: a guest's later-stamped op sits ahead of an earlier one.
let hot = |op, counter, peer| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
};
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
host.replay_hot_op(late.clone()).expect("the late-stamped op lands first");
host.replay_hot_op(own.clone()).expect("the earlier-stamped op lands second");
host.retire(own.timestamp).expect("retire");
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
host.retire(late.timestamp).expect("retire the rest");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
}
#[test]
fn newest_peer_registration_wins_in_any_order() {
// Registration rides the staging path, so the steps go through the hot log and retire.
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
let hot = session.stage_ops([op]).expect("stage");
session.retire(hot.last().expect("staged").timestamp).expect("retire");
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
stage_and_retire(&mut device, set_attribute("first", 1));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
// The person at the device changes, so the next batch registers again.
device.document.user = UserId(20);
stage_and_retire(&mut device, set_attribute("second", 2));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 2, "one registration per person the device stood for");
let mut other = Session::with_peer(PeerId(2));
for delta in device.cloned_deltas().into_iter().rev() {
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
}
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
}
#[test]
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
let mut s = Session::with_peer(PeerId(1));
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
s.stage_ops([
RegistryDelta::AddNetwork {
id: NetworkId(1),
network: Network::default(),
},
RegistryDelta::AddNode { id: NodeId(1), node },
])
.unwrap();
let before = s.registry().clone();
let refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
}]);
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
}
+494 -51
View File
@@ -42,7 +42,9 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
timestamp: observed,
};
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
document
.stage_hot_op(hot_op, crate::document::ApplyMode::Strict)
.expect("RemoveNode on absent node is a no-op, not an error");
assert!(
document.clock.counter >= observed.counter,
@@ -263,7 +265,11 @@ fn first_contribution_registers_the_peer() {
let registrations = first.iter().filter(|hot_op| matches!(hot_op.op, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 1, "exactly one RegisterPeer on first contribution");
assert!(matches!(first[0].op, RegistryDelta::RegisterPeer { .. }), "RegisterPeer must precede the edit ops");
assert_eq!(session.registry().peer_users.get(&PeerId(7)), Some(&crate::UserId(7)), "peer mapped to its UserId");
assert_eq!(
session.registry().peer_users.get(&PeerId(7)).map(|registration| registration.user),
Some(crate::UserId(7)),
"peer mapped to its UserId"
);
// A second, distinct contribution must not re-register.
let mut other_network = tiny_network();
@@ -284,9 +290,9 @@ fn first_contribution_registers_the_peer() {
assert_eq!(fresh.registry().peer_users, peers_before, "a no-op batch must not add a registration");
}
/// A SetExport against a removed network must restore the network from history rather than error.
/// A SetExport newer than a network's removal revives the network from its tombstone instead of erroring.
#[test]
fn set_export_resurrects_absent_network() {
fn set_network_export_revives_a_removed_network() {
let mut document = fresh_document(PeerId(1));
let network_id = NetworkId(7);
@@ -304,7 +310,7 @@ fn set_export_resurrects_absent_network() {
snapshot: Network::default(),
},
);
assert!(!document.working_registry.networks.contains_key(&network_id), "network should be removed before the resurrection test");
assert!(!document.working_registry.networks.contains_key(&network_id), "network should be removed before the revival");
commit_op(
&mut document,
@@ -315,12 +321,12 @@ fn set_export_resurrects_absent_network() {
},
);
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have resurrected the network");
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have revived the network");
}
/// Cascading resurrection: bringing a node back must also restore its owning network when absent.
/// An addition into a removed network is evidence the network exists, so it brings the network back.
#[test]
fn add_node_resurrects_owning_network() {
fn add_node_revives_its_removed_network() {
use crate::Node;
let mut document = fresh_document(PeerId(1));
@@ -345,18 +351,13 @@ fn add_node_resurrects_owning_network() {
let node = Node { network: network_id, ..Node::dummy() };
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node });
assert!(
document.working_registry.networks.contains_key(&network_id),
"AddNode should have cascaded a resurrection of the owning network"
);
assert!(document.working_registry.networks.contains_key(&network_id), "AddNode should have revived the owning network");
assert!(document.working_registry.node_instances.contains_key(&node_id), "the node itself should also be present");
}
/// Reverting the same removal twice (the moral equivalent of two peers concurrently resurrecting
/// the same node) must not error on the second apply. Today the second revert hits
/// `apply_op(AddNode, false)` against a present node and returns `NodeAlreadyExists`.
/// Two peers reverting one removal: the second revival is not newer than the first, so it lands once.
#[test]
fn concurrent_resurrection_via_revert_is_idempotent() {
fn the_same_revival_arriving_twice_lands_once() {
use crate::Node;
let mut document = fresh_document(PeerId(1));
@@ -373,40 +374,19 @@ fn concurrent_resurrection_via_revert_is_idempotent() {
let node = Node { network: network_id, ..Node::dummy() };
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node: node.clone() });
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the resurrection test");
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the revival");
document.restore_node_from_history(RegistryTarget::Working, node_id).expect("first resurrection should succeed");
assert!(document.working_registry.node_instances.contains_key(&node_id), "first resurrection should bring the node back");
let revive = RegistryDelta::AddNode {
id: node_id,
node: Node { network: network_id, ..Node::dummy() },
};
let at = document.clock.tick();
document.apply_op_idempotent(revive.clone(), at).expect("first revival");
assert!(document.working_registry.node_instances.contains_key(&node_id), "the first revival brings the node back");
let second = document.restore_node_from_history(RegistryTarget::Working, node_id);
assert!(second.is_ok(), "second resurrection of an already-present node should be a no-op, got {second:?}");
}
/// History-based resurrection must work when the matching delta is the *root* commit. The history
/// walk used to drop the root (its empty parent list short-circuited the iterator before yielding
/// it), so a node removed by the very first commit could not be restored.
#[test]
fn restore_node_from_root_commit() {
use crate::Node;
let mut document = fresh_document(PeerId(1));
let node_id = NodeId(42);
let node = Node::dummy();
// Seed the working state so the root commit can remove the node (its reverse is the `AddNode` the
// resurrection looks for). This `RemoveNode` is the only commit, so the match sits at the root.
document.working_registry.networks.insert(ROOT_NETWORK, Network::default());
document.retired_snapshot.networks.insert(ROOT_NETWORK, Network::default());
document.working_registry.node_instances.insert(node_id, node.clone());
document.retired_snapshot.node_instances.insert(node_id, node.clone());
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed by the root commit");
document
.restore_node_from_history(RegistryTarget::Working, node_id)
.expect("resurrection from the root commit should succeed");
assert!(document.working_registry.node_instances.contains_key(&node_id), "node must be restored from the root commit");
let second = document.apply_op_idempotent(revive, at);
assert!(second.is_ok(), "the same revival again is a no-op, got {second:?}");
assert!(document.working_registry.node_instances.contains_key(&node_id));
}
/// Erroring ops still bump the clock: we observed the timestamp on the wire, the fact that the
@@ -563,7 +543,10 @@ fn remove_source_reverse_restores_prior() {
}
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
assert!(document.working_registry.resources.get(&id).unwrap().sources.is_empty(), "source removed");
assert!(
document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(),
"source removed, a tombstone left"
);
// Applying the reverse restores the chain.
document.apply_op(reverse, ts(6, 1)).unwrap();
@@ -623,7 +606,16 @@ use crate::{ResourceEntry, ResourceStore, SourceValue};
fn entry_with_source(priority: f64, peer: u64, body: Value, hash: Option<ResourceHash>) -> ResourceEntry {
ResourceEntry {
sources: vec![(source_key(priority, peer), SourceValue { source: body, timestamp: ts(1, peer) })],
presence: ts(1, peer),
sources: vec![(
source_key(priority, peer),
SourceValue {
source: body,
timestamp: ts(1, peer),
deleted: false,
},
)],
sources_timestamp: TimeStamp::ORIGIN,
hash,
hash_timestamp: ts(1, peer),
}
@@ -674,6 +666,7 @@ fn compute_deltas_diffs_resources_and_round_trips() {
SourceValue {
source: Value::Str("url".into()),
timestamp: ts(1, 1),
deleted: false,
},
);
to.insert(kept, kept_entry);
@@ -699,6 +692,8 @@ fn compute_deltas_diffs_resources_and_round_trips() {
// Apply the diff to a document seeded with `from`, then check it matches `to` by value.
let mut document = fresh_document(PeerId(1));
document.working_registry = registry_with_resources(from);
// A clock is past every stamp in the registry it edits, as a session's persisted clock is.
document.clock.observe(ts(1, 1));
for op in deltas {
let timestamp = document.clock.tick();
document.apply_op(op, timestamp).expect("apply resource delta");
@@ -746,6 +741,15 @@ fn all_referenced_resource_hashes_survives_undo() {
session.all_referenced_resource_hashes().contains(&hash),
"the undone interaction's resource must still be reported so GC keeps its bytes for redo"
);
// A later hash change, undone, keeps the new hash reported too: redo puts it back.
session.redo().expect("redo");
let changed = ResourceHash::from(&b"changed-bytes"[..]);
let hot_ops = session.stage_ops([crate::RegistryDelta::SetResourceHash { id, hash: Some(changed) }]).expect("stage hash change");
let revs = session.retire(hot_ops.last().expect("staged").timestamp).expect("retire");
session.mark_interaction_end(*revs.last().expect("one retired delta"));
session.undo().expect("undo the hash change");
assert!(session.all_referenced_resource_hashes().contains(&changed), "the undone hash change keeps its bytes for redo");
}
/// A commit that produces no deltas must not touch the redo stack. Redo is only abandoned by a real
@@ -811,7 +815,7 @@ fn embed_resource_sources_preserves_unretired_hot_ops() {
/// ordered (`BTreeMap`): a hash-randomized map would give the same logical delta different `Rev`s.
#[test]
fn add_node_rev_is_independent_of_attribute_insertion_order() {
use crate::{AttributeValue, AttributesWrite, Implementation};
use crate::{AttributeValue, Implementation};
let keys = ["ui::position", "ui::display_name", "ui::locked", "ui::pinned", "call_argument", "context_features"];
@@ -836,6 +840,9 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
}];
Node {
presence: Default::default(),
network_timestamp: Default::default(),
inputs_timestamp: Default::default(),
implementation: implementation.clone(),
implementation_timestamp: Default::default(),
inputs,
@@ -880,3 +887,439 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
}
fn add_network(id: u64) -> RegistryDelta {
let network = Network::default();
RegistryDelta::AddNetwork { id: NetworkId(id), network }
}
fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
let delta = crate::AttributeDelta {
key: key.into(),
value: Some(Value::from(value)),
};
RegistryDelta::ChangeNodeAttribute { id, delta }
}
fn hot_op(op: RegistryDelta, counter: u64, peer: u64) -> HotOp {
HotOp { op, timestamp: ts(counter, peer) }
}
/// So the snapshot and a replay keep the LWW winner the live view did, whether the straggler retires with it or after.
#[test]
fn retirement_preserves_the_live_lww_winner() {
for straggler_retires_alone in [false, true] {
let mut host = Session::with_peer(PeerId(1));
let winner = hot_op(set_document_attribute("k", 1), 10, 2);
host.replay_hot_op(winner.clone()).expect("apply winner");
if straggler_retires_alone {
host.retire(winner.timestamp).expect("retire winner");
}
host.replay_hot_op(hot_op(set_document_attribute("k", 2), 5, 3)).expect("apply straggler");
host.retire(winner.timestamp).expect("retire");
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
let replayed = host.snapshot_from_history().expect("refold");
let values = [value(host.registry()), value(host.retired_registry()), value(&replayed)];
assert_eq!(values, [(); 3].map(|_| Some(Value::from(serde_json::json!(1)))), "straggler retires alone: {straggler_retires_alone}");
}
}
/// Random ops over a few colliding ids fold to one registry in any order. Removal snapshots are constant or, as a remover
/// sends them, a fold of some earlier ops.
#[test]
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
use crate::{Implementation, Priority, ResourceEntry, SourceKey, SourceValue, UserId};
use graphene_resource::{ResourceHash, ResourceId};
struct Lcg(u64);
impl Lcg {
fn below(&mut self, bound: u64) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 33) % bound
}
}
/// Folds the ops in order.
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
let mut document = fresh_document(PeerId(9));
for (op, at) in ops {
document.apply_op_idempotent(op.clone(), *at).unwrap_or_else(|error| panic!("{op:?} at {at:?}: {error}"));
}
document.working_registry
}
fn random_op(rng: &mut Lcg, at: TimeStamp, seen: &[(RegistryDelta, TimeStamp)], real_snapshots: bool) -> RegistryDelta {
let node_id = NodeId(1 + rng.below(4));
let network_id = NetworkId(1 + rng.below(3));
let resource_id = ResourceId::from(1 + rng.below(2));
let input = |rng: &mut Lcg| match rng.below(3) {
0 => crate::NodeInput::Node {
id: NodeId(1 + rng.below(4)),
index: 0,
},
_ => crate::NodeInput::Value {
value: Value::from(serde_json::json!(rng.below(100))),
exposed: false,
},
};
// A write, or a deletion one time in four.
let attribute = |rng: &mut Lcg, key: &str| crate::AttributeDelta {
key: key.into(),
value: (rng.below(4) > 0).then(|| Value::from(serde_json::json!(rng.below(100)))),
};
let key = |rng: &mut Lcg| SourceKey {
priority: Priority::new(rng.below(2) as f64).expect("finite"),
peer: PeerId(1 + rng.below(2).min(at.peer.0)),
};
// What a remover saw: some of the ops before it. Two snapshots agreeing on a stamp then agree on the value,
// which a fabricated snapshot only does by being constant.
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>());
match rng.below(22) {
0 => {
// An export list of its own, so additions of different lengths meet.
let exports = (0..rng.below(3))
.map(|_| crate::ExportSlot {
target: Some(input(rng)),
timestamp: TimeStamp::ORIGIN,
})
.collect();
RegistryDelta::AddNetwork {
id: network_id,
network: Network { exports, ..Default::default() },
}
}
1 => {
let snapshot = if real_snapshots { saw(rng).networks.get(&network_id).cloned() } else { Some(Network::default()) };
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveNetwork { id: network_id, snapshot })
}
2 | 3 => RegistryDelta::AddNode {
id: node_id,
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 1 + rng.below(2) as usize),
},
4 => {
let fabricated = || Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 2);
let snapshot = if real_snapshots { saw(rng).node_instances.get(&node_id).cloned() } else { Some(fabricated()) };
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveNode { id: node_id, snapshot })
}
5 | 6 => RegistryDelta::ChangeNodeInput {
id: node_id,
index: rng.below(3) as u32,
new_input: input(rng),
},
7 => RegistryDelta::SetNodeInputs {
id: node_id,
inputs: (0..1 + rng.below(3))
.map(|_| {
let mut slot = InputSlot {
input: input(rng),
timestamp: TimeStamp::ORIGIN,
attributes: Default::default(),
};
// Half the time a slot carries attributes over with earlier stamps, as an implementation swap does.
if rng.below(2) == 0 {
let floor = TimeStamp {
counter: 1 + rng.below(at.counter),
peer: PeerId(1 + rng.below(3)),
};
let label = TimeStamp {
counter: floor.counter + rng.below(at.counter - floor.counter + 1),
..floor
};
slot.attributes
.insert("label".into(), crate::AttributeValue::new(Value::from(serde_json::json!(rng.below(100))), label));
slot.attributes.set_floor(floor);
}
slot
})
.collect(),
},
8 => {
let key = ["name", "lock"][rng.below(2) as usize];
RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: attribute(rng, key),
}
}
9 => RegistryDelta::SetNodeImplementation {
id: node_id,
implementation: match rng.below(2) {
0 => Implementation::Network(network_id),
_ => Implementation::ProtoNode(ResourceId::from(rng.below(3))),
},
},
10 => RegistryDelta::SetNetworkExport {
id: network_id,
index: rng.below(2) as u32,
export: match rng.below(2) {
0 => None,
_ => Some(input(rng)),
},
},
11 => RegistryDelta::AddResource {
id: resource_id,
entry: ResourceEntry::default(),
},
12 => {
let snapshot = if real_snapshots {
saw(rng).resources.get(&resource_id).cloned()
} else {
Some(ResourceEntry::default())
};
snapshot.map_or(RegistryDelta::Other(Value::None), |snapshot| RegistryDelta::RemoveResource { id: resource_id, snapshot })
}
13 => RegistryDelta::SetResourceHash {
id: resource_id,
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
},
14 => RegistryDelta::AddSource {
id: resource_id,
key: key(rng),
source: Value::from(serde_json::json!(rng.below(100))),
},
15 => RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index: rng.below(3) as u32,
delta: attribute(rng, "label"),
},
16 => RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: attribute(rng, "name"),
},
17 => RegistryDelta::RemoveSource { id: resource_id, key: key(rng) },
18 => RegistryDelta::RegisterPeer {
peer: PeerId(1 + rng.below(2)),
user: UserId(rng.below(3)),
},
19 => RegistryDelta::ChangeDocumentAttribute { delta: attribute(rng, "doc") },
_ => {
// A resource added whole, with content.
let mut entry = ResourceEntry {
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
..Default::default()
};
let source = SourceValue {
source: Value::from(serde_json::json!(rng.below(100))),
timestamp: TimeStamp::ORIGIN,
deleted: false,
};
entry.set_source(key(rng), source);
RegistryDelta::AddResource { id: resource_id, entry }
}
}
}
for real_snapshots in [false, true] {
for seed in 0..300u64 {
let mut rng = Lcg(seed);
let mut ops: Vec<(RegistryDelta, TimeStamp)> = Vec::new();
for i in 0..8 + rng.below(24) {
let at = TimeStamp {
counter: 1 + i,
peer: PeerId(1 + rng.below(3)),
};
let op = random_op(&mut rng, at, &ops, real_snapshots);
ops.push((op, at));
}
let reference = fold(&ops);
for _ in 0..6 {
let mut shuffled = ops.clone();
for i in (1..shuffled.len()).rev() {
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
}
let order: Vec<u64> = shuffled.iter().map(|(_, at)| at.counter).collect();
assert_eq!(fold(&shuffled), reference, "seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}");
}
}
}
}
/// An entry stamped at its map's floor was written with it, so folding a removal's snapshot keeps it.
#[test]
fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
let mut document = fresh_document(PeerId(1));
let id = NodeId(4);
let mut node = Node::new(ROOT_NETWORK, crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 1);
node.attributes.set("ui::name", Value::from(serde_json::json!("Layer")), TimeStamp::ORIGIN);
node.inputs[0].attributes.set("reflection_metadata", Value::from(serde_json::json!("meta")), TimeStamp::ORIGIN);
commit_op(&mut document, add_network(ROOT_NETWORK.0));
commit_op(&mut document, RegistryDelta::AddNode { id, node });
// A removal and a newer write, which revives the node from the tombstone.
let removal = RegistryDelta::RemoveNode {
id,
snapshot: document.working_registry.node_instances[&id].clone(),
};
let removed_at = document.clock.tick();
document.apply_op_idempotent(removal.clone(), removed_at).expect("removal");
let written_at = document.clock.tick();
document.apply_op_idempotent(change_node_attribute(id, "ui::lock", serde_json::json!(true)), written_at).expect("write");
let revived = &document.working_registry.node_instances[&id];
assert_eq!(revived.attributes.get_typed::<String>("ui::name").as_deref(), Some("Layer"));
assert_eq!(revived.inputs()[0].attributes.get_typed::<String>("reflection_metadata").as_deref(), Some("meta"));
// The same removal replayed into the live node is too old to land and changes nothing.
let mut replayed = document.clone();
replayed.apply_op_idempotent(removal, removed_at).expect("a replayed removal");
assert_eq!(replayed.working_registry, document.working_registry);
}
#[test]
fn a_refused_replayed_op_changes_nothing() {
use crate::{Implementation, NodeInput};
let mut document = fresh_document(PeerId(1));
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
for (op, counter) in [
(add_network(1), 1),
(RegistryDelta::AddNode { id: NodeId(1), node: node.clone() }, 2),
(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, 3),
(RegistryDelta::RemoveNode { id: NodeId(2), snapshot: node }, 4),
] {
document.apply_op_idempotent(op, ts(counter, 5)).unwrap();
}
let before = document.working_registry.clone();
let out_of_bounds = RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 1 << 20,
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
};
assert!(document.apply_op_idempotent(out_of_bounds, ts(5, 5)).is_err());
assert_eq!(document.working_registry, before);
}
/// An implementation swap carries a slot's `ui::*` attributes over as the editor held them; a concurrent rename and a
/// concurrent first-time attribute on that slot both survive it, whichever lands first.
#[test]
fn an_implementation_swap_keeps_concurrent_slot_attribute_writes() {
use crate::Implementation;
use graphene_resource::ResourceId;
let slot_attribute = |key: &str, value: &str| RegistryDelta::ChangeNodeInputAttribute {
id: NodeId(1),
index: 0,
delta: crate::AttributeDelta {
key: key.into(),
value: Some(Value::from(serde_json::json!(value))),
},
};
let mut base = fresh_document(PeerId(1));
commit_op(&mut base, add_network(1));
let node = Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 1);
commit_op(&mut base, RegistryDelta::AddNode { id: NodeId(1), node });
commit_op(&mut base, slot_attribute("ui::name", "a"));
// The swap as the editor builds it: the new slot with the held slot's `ui::*` attributes and floor carried over.
let held = base.working_registry.node_instances[&NodeId(1)].inputs()[0].clone();
let mut carried = InputSlot::unset(TimeStamp::ORIGIN);
carried.attributes.set_floor(held.attributes.floor());
carried.attributes.extend(held.attributes.into_iter().filter(|(key, value)| key.starts_with("ui::") && !value.deleted));
let swap = (RegistryDelta::SetNodeInputs { id: NodeId(1), inputs: vec![carried] }, ts(20, 1));
let rename = (slot_attribute("ui::name", "b"), ts(10, 2));
let describe = (slot_attribute("ui::description", "d"), ts(11, 2));
for order in [[&swap, &rename, &describe], [&rename, &describe, &swap]] {
let mut document = base.clone();
for (op, at) in order {
document.apply_op_idempotent(op.clone(), *at).expect("apply");
}
let slot = &document.working_registry.node_instances[&NodeId(1)].inputs()[0];
assert_eq!(
slot.attributes.get("ui::name").map(|value| value.value.clone()),
Some(Value::from(serde_json::json!("b"))),
"the rename survives"
);
assert!(slot.attributes.get("ui::description").is_some_and(|value| !value.deleted), "the first-time attribute survives");
}
}
/// Re-adding a removed network with a shorter export list drops the slots past its end, whichever lands first.
#[test]
fn a_network_re_added_shorter_keeps_only_its_own_exports() {
use crate::ExportSlot;
let export = |node: u64| ExportSlot {
target: Some(crate::NodeInput::Node { id: NodeId(node), index: 0 }),
timestamp: TimeStamp::ORIGIN,
};
let network = |exports: Vec<ExportSlot>| Network { exports, ..Default::default() };
let added = (
RegistryDelta::AddNetwork {
id: NetworkId(1),
network: network(vec![export(1), export(2)]),
},
ts(1, 1),
);
let removed = (
RegistryDelta::RemoveNetwork {
id: NetworkId(1),
snapshot: network(vec![export(1), export(2)]),
},
ts(2, 1),
);
let re_added = (
RegistryDelta::AddNetwork {
id: NetworkId(1),
network: network(vec![export(3)]),
},
ts(3, 2),
);
for order in [[&added, &removed, &re_added], [&re_added, &removed, &added]] {
let mut document = fresh_document(PeerId(9));
for (op, at) in order {
document.apply_op_idempotent(op.clone(), *at).expect("apply");
}
let exports = &document.working_registry.networks[&NetworkId(1)].exports;
assert_eq!(exports.iter().map(|slot| slot.target.clone()).collect::<Vec<_>>(), vec![export(3).target]);
}
}
/// Two registries ordering a removal differently against a write are not order-consistent, though their values agree.
#[test]
fn order_consistency_covers_removal_stamps() {
let with_removal_at = |counter: u64| {
let mut document = fresh_document(PeerId(1));
let node = Node::new(NetworkId(1), crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 0);
document.apply_op_idempotent(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, ts(3, 1)).expect("add");
document
.apply_op_idempotent(RegistryDelta::RemoveNode { id: NodeId(1), snapshot: node }, ts(counter, 1))
.expect("remove");
document.working_registry
};
let (earlier, later) = (with_removal_at(2), with_removal_at(4));
assert!(earlier.value_equal(&later));
assert!(!earlier.order_consistent(&later));
}
/// An input naming a node whose addition has not arrived renders as a dangling input, as one naming a removed node does,
/// rather than failing the conversion: the placeholder knows nothing of the node's network.
#[test]
fn an_input_naming_a_node_not_yet_added_renders_dangling() {
use crate::Implementation;
let (nested, empty, owner, inner, unseen) = (NetworkId(5), NetworkId(6), NodeId(1), NodeId(2), NodeId(3));
let mut document = fresh_document(PeerId(1));
let ops = [
add_network(ROOT_NETWORK.0),
add_network(nested.0),
add_network(empty.0),
RegistryDelta::AddNode {
id: owner,
node: Node::new(ROOT_NETWORK, Implementation::Network(nested), 0),
},
RegistryDelta::AddNode {
id: inner,
node: Node::new(nested, Implementation::Network(empty), 1),
},
RegistryDelta::ChangeNodeInput {
id: inner,
index: 0,
new_input: crate::NodeInput::Node { id: unseen, index: 0 },
},
];
for (counter, op) in (1..).zip(ops) {
document.apply_op_idempotent(op, ts(counter, 2)).expect("apply");
}
assert!(document.working_registry.removed_nodes.get(&unseen).is_some_and(|mark| mark.placeholder));
document.working_registry.to_runtime_with_metadata(&crate::Declarations::new()).expect("converts with a dangling input");
}
@@ -650,7 +650,6 @@ fn node_input_f64_round_trips_bit_exact() {
/// Conversion must reject this rather than silently collapse them and drop a node.
#[test]
fn duplicate_runtime_node_id_is_rejected() {
use crate::AttributesWrite;
use crate::TimeStamp;
use crate::to_runtime::ConversionError;
@@ -717,7 +716,6 @@ fn scope_injections_round_trip() {
/// network) must error rather than emit an injection pointing at a nonexistent runtime node.
#[test]
fn dangling_scope_injection_is_rejected() {
use crate::AttributesWrite;
use crate::TimeStamp;
use crate::to_runtime::ConversionError;
@@ -757,6 +755,9 @@ fn cyclic_network_reference_is_rejected() {
registry.node_instances.insert(
crate::NodeId(0),
Node {
presence: Default::default(),
network_timestamp: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(child_network_id),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
@@ -767,6 +768,9 @@ fn cyclic_network_reference_is_rejected() {
registry.node_instances.insert(
crate::NodeId(1),
Node {
presence: Default::default(),
network_timestamp: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(crate::ROOT_NETWORK),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
+35 -27
View File
@@ -10,7 +10,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
use crate::attr::*;
use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry};
use crate::{AttributesRead, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
use crate::{Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value};
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
@@ -51,19 +51,7 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
// flat `node_instances` map, which would be quadratic on graphs with many networks.
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &self.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
let context = ConversionContext {
registry: self,
declarations,
nodes_by_network,
};
let context = ConversionContext::new(self, declarations);
// Reject cycles up front so the recursive conversion below can assume the network reference
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
@@ -82,7 +70,7 @@ impl Registry {
let mut registry = graphene_resource::ResourceRegistry::new();
for (id, entry) in &self.resources {
for (_, source) in &entry.sources {
for (_, source) in entry.live_sources() {
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
registry.push_source_back(id, decoded);
}
@@ -104,6 +92,26 @@ struct ConversionContext<'a> {
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
}
impl<'a> ConversionContext<'a> {
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &registry.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
Self {
registry,
declarations,
nodes_by_network,
}
}
}
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
/// lands it under the id the editor's metadata is keyed by.
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
}
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
///
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
@@ -166,7 +174,7 @@ fn convert_network(
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
) -> Result<NodeNetwork, ConversionError> {
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
if let Some(collector) = network_collector.as_mut() {
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
@@ -174,8 +182,8 @@ fn convert_network(
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
let local_id = node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0);
let runtime_id = RuntimeNodeId(local_id);
let runtime_id = runtime_node_id(global_id, node);
let local_id = runtime_id.0;
if let Some(collector) = node_collector.as_mut() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
@@ -232,8 +240,7 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
});
};
let local_id = referenced.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(storage_id.0);
Ok((key, (RuntimeNodeId(local_id), ty)))
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
})
.collect()
}
@@ -271,8 +278,7 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
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_typed(node::ORIGINAL_NODE_ID).unwrap_or(storage_id.0);
Some(RuntimeNodeId(local_id))
Some(runtime_node_id(storage_id, node))
};
let pinned_order = attributes
@@ -293,7 +299,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
let input_data: HashMap<String, Value> = attributes
.iter()
.live()
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
.collect();
@@ -335,20 +341,22 @@ fn convert_node(
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
Ok(match input {
NodeInput::Node { id: node_id, index: output_index } => {
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// A node removed concurrently keeps its id, as the editor holds a dangling input. So does one whose addition has not
// arrived yet, though its placeholder knows nothing of its network.
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
let placeholder = registry.removed_nodes.get(node_id).is_some_and(|mark| mark.placeholder);
// Runtime references are local to one network. A cross-network reference would remap to a
// local ID that doesn't exist in the current runtime network, so reject it.
if referenced.network != network_id {
if !placeholder && referenced.network != network_id {
return Err(ConversionError::CrossNetworkReference {
network: network_id,
referenced: *node_id,
});
}
let local_id = referenced.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(node_id.0);
GraphCraftNodeInput::Node {
node_id: RuntimeNodeId(local_id),
node_id: runtime_node_id(*node_id, referenced),
output_index: *output_index as usize,
}
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "graphite-editor-control-protocol"
description = "The commands, results, and scenarios that scripts, QA, and agents use to operate the Graphite editor"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Workspace dependencies
serde = { workspace = true }
serde_json = { workspace = true }
glam = { workspace = true, features = ["serde"] }
+354
View File
@@ -0,0 +1,354 @@
//! The commands that scripts, QA, and agents send to operate the Graphite editor the way a person does, the results they get back,
//! the scenario files that hold a sequence of commands, and the messages that carry them between a client and an editor host.
//!
//! Each message travels as one line of JSON.
use glam::{DVec2, UVec2};
use serde::{Deserialize, Serialize};
use std::num::NonZeroU32;
use std::path::PathBuf;
/// Increases whenever a change would break a client or host written against an earlier version.
pub const PROTOCOL_VERSION: u32 = 1;
/// Which origin a point is measured from.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Space {
/// The page's top left corner.
#[default]
Page,
/// The document viewport's top left corner.
Viewport,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MouseButton {
#[default]
Left,
Middle,
Right,
}
/// An area of the page, in CSS pixels.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Rectangle {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
/// Frames captured along a drag and laid out in one image, each marked with where the pointer was.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Filmstrip {
/// Where the image is written, with a relative path landing in the host's output directory.
pub path: PathBuf,
/// How many frames to capture, spread evenly along the drag.
pub frames: Option<NonZeroU32>,
/// Limits each frame to the document viewport (`"viewport"`) or the first element matching a CSS selector.
pub region: Option<String>,
/// Limits each frame to an exact area of the page, overriding the region.
pub clip: Option<Rectangle>,
}
/// One step of operating the editor with the mouse and keyboard, or of observing the result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase", deny_unknown_fields)]
pub enum Command {
/// Moves the pointer one small step per rendered frame, as a real pointer does, or in the given number of steps.
Move { to: DVec2, space: Option<Space>, steps: Option<NonZeroU32> },
/// Presses a mouse button.
Down { button: Option<MouseButton> },
/// Releases a mouse button.
Up { button: Option<MouseButton> },
/// Moves the pointer to a point and clicks there, with the keys held from before the first press.
Click {
at: DVec2,
space: Option<Space>,
button: Option<MouseButton>,
count: Option<NonZeroU32>,
keys: Option<Vec<String>>,
},
/// Drags between two points with the keys held from before the press.
/// With `release` set to false, the button and keys stay held once the drag succeeds.
Drag {
from: DVec2,
to: DVec2,
space: Option<Space>,
button: Option<MouseButton>,
keys: Option<Vec<String>>,
steps: Option<NonZeroU32>,
release: Option<bool>,
filmstrip: Option<Filmstrip>,
},
/// Holds a key, named as in `KeyboardEvent.key` or `KeyboardEvent.code`, such as `Shift` or `KeyP`.
KeyDown { key: String },
/// Releases a held key.
KeyUp { key: String },
/// Taps a key, or a combination such as `Control+KeyZ`, where a final `+` is the plus key itself.
Press { key: String },
/// Types text into the focused field.
Type { text: String },
/// Turns the mouse wheel, in notches of up to 100 pixels, optionally after moving the pointer to a point.
Scroll { delta: DVec2, at: Option<DVec2>, space: Option<Space> },
/// Pauses for a number of milliseconds.
Wait { milliseconds: u64 },
/// Waits until the editor stops redrawing, giving up after the timeout in milliseconds.
WaitIdle { timeout: Option<u64> },
/// Captures the page, or part of it, optionally marking the pointer with a crosshair.
Screenshot {
path: PathBuf,
cursor: Option<bool>,
region: Option<String>,
clip: Option<Rectangle>,
},
/// Finds elements by a `data-*` attribute name, the visible text they contain, or both.
Locate { data: Option<String>, text: Option<String> },
/// Fails unless the page shows the expected elements, found as `locate` finds them and narrowed to those with a field holding `value`.
/// With only a `value`, it looks among every field. It expects exactly `count` elements, or at least one without a count.
Expect {
data: Option<String>,
text: Option<String>,
value: Option<String>,
count: Option<u32>,
},
/// Changes the size of the page, in CSS pixels.
Resize { size: UVec2 },
/// Reports the state of the session.
Status {},
}
impl Command {
/// The name the command is given by its `type` field.
pub fn name(&self) -> &'static str {
match self {
Command::Move { .. } => "move",
Command::Down { .. } => "down",
Command::Up { .. } => "up",
Command::Click { .. } => "click",
Command::Drag { .. } => "drag",
Command::KeyDown { .. } => "keyDown",
Command::KeyUp { .. } => "keyUp",
Command::Press { .. } => "press",
Command::Type { .. } => "type",
Command::Scroll { .. } => "scroll",
Command::Wait { .. } => "wait",
Command::WaitIdle { .. } => "waitIdle",
Command::Screenshot { .. } => "screenshot",
Command::Locate { .. } => "locate",
Command::Expect { .. } => "expect",
Command::Resize { .. } => "resize",
Command::Status {} => "status",
}
}
}
/// An element found by a `locate` command.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Located {
#[serde(rename = "box")]
pub bounds: Rectangle,
pub center: DVec2,
/// The start of the element's text, with its whitespace collapsed.
pub text: String,
/// What the element holds if it is a field, or else what the first field inside it holds.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionStatus {
pub url: String,
pub size: UVec2,
pub pointer: DVec2,
/// Where the document viewport is on the page, if one is open.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub viewport: Option<Rectangle>,
pub held_keys: Vec<String>,
pub held_buttons: Vec<MouseButton>,
pub crashed: bool,
}
/// What came of one command.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandResult {
/// The `type` of the command this reports on.
#[serde(rename = "type")]
pub command: String,
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// Where a screenshot or filmstrip was written.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<PathBuf>,
/// The pointer's position on the page in each frame of a filmstrip, in the order the frames are laid out.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frames: Option<Vec<DVec2>>,
/// Whether the editor stopped redrawing before the timeout.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub located: Option<Vec<Located>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<SessionStatus>,
/// The errors the page logged since the previous command, or for the first, since it loaded.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub console_errors: Vec<String>,
}
impl CommandResult {
pub fn succeeded(command: &Command) -> Self {
Self {
command: command.name().to_string(),
ok: true,
..Default::default()
}
}
pub fn failed(command: &Command, error: String) -> Self {
Self {
command: command.name().to_string(),
ok: false,
error: Some(error),
..Default::default()
}
}
}
/// Reads the steps of a scenario file, which holds one command per line written as JSON, leaving out blank lines and `//` comments.
pub fn parse_scenario(text: &str) -> Result<Vec<Command>, String> {
text.lines()
.enumerate()
.filter(|(_, line)| {
let line = line.trim();
!line.is_empty() && !line.starts_with("//")
})
.map(|(index, line)| serde_json::from_str(line).map_err(|error| format!("Line {}: {error}", index + 1)))
.collect()
}
/// A message from a client to an editor host.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum ClientMessage {
/// Attaches to the session, which the host refuses unless the protocol version matches and the token is the host's own.
Attach { version: u32, token: String },
/// Performs commands in order, stopping at the first that fails, since the later ones were written assuming it succeeded.
/// With `fail_on_console_errors`, a command also fails if the page has logged an error since the previous one.
Perform {
id: u64,
commands: Vec<Command>,
#[serde(default)]
fail_on_console_errors: bool,
},
/// Ends the session and closes the editor.
Shutdown,
}
/// A message from an editor host to a client.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum HostMessage {
/// Accepts a connection, naming the host's process so a client can tell it apart from one that has replaced it.
Attached { version: u32, process_id: u32 },
/// Turns away a connection, after which the host closes it.
Refused { reason: String },
/// Reports on each command performed, in order.
Results { id: u64, results: Vec<CommandResult> },
/// Confirms a shutdown, after which the connection closes once the host has exited.
ShuttingDown,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scenario_steps_parse() {
let steps = parse_scenario(
r#"// Draw a rectangle
{ "type": "resize", "size": [1600, 1000] }
{ "type": "press", "key": "KeyM" }
// Drag out the rectangle
{ "type": "drag", "from": [200, 150], "to": [500, 350], "space": "viewport", "filmstrip": { "path": "drag.png", "frames": 4 } }
{ "type": "waitIdle" }
{ "type": "screenshot", "path": "rectangle.png", "region": "viewport" }
{ "type": "status" }
"#,
)
.unwrap();
assert_eq!(steps.len(), 6);
assert_eq!(steps[0], Command::Resize { size: UVec2::new(1600, 1000) });
assert!(
matches!(&steps[2], Command::Drag { to, space: Some(Space::Viewport), filmstrip: Some(Filmstrip { frames: Some(frames), .. }), .. } if *to == DVec2::new(500., 350.) && frames.get() == 4)
);
assert_eq!(steps[5], Command::Status {});
}
#[test]
fn scenario_mistakes_name_their_line() {
let error = parse_scenario("// A mistake on the third line\n{ \"type\": \"status\" }\n{ \"type\": \"teleport\" }").unwrap_err();
assert!(error.starts_with("Line 3:"));
}
#[test]
fn qa_fields_parse() {
let steps = parse_scenario("{ \"type\": \"expect\", \"data\": \"layer\", \"count\": 0 }\n{ \"type\": \"expect\", \"value\": \"500.26\" }").unwrap();
assert!(matches!(steps[0], Command::Expect { count: Some(0), .. }));
assert!(matches!(&steps[1], Command::Expect { value: Some(value), count: None, .. } if value == "500.26"));
// Clients that predate the option leave it out
let perform: ClientMessage = serde_json::from_str(r#"{ "type": "perform", "id": 1, "commands": [] }"#).unwrap();
assert!(matches!(perform, ClientMessage::Perform { fail_on_console_errors: false, .. }));
}
#[test]
fn mistakes_are_refused() {
// A misspelled field
assert!(serde_json::from_str::<Command>(r#"{ "type": "move", "to": [1, 2], "stpes": 3 }"#).is_err());
// A count that must be a positive integer
assert!(serde_json::from_str::<Command>(r#"{ "type": "click", "at": [1, 2], "count": 0 }"#).is_err());
// An unknown command
assert!(serde_json::from_str::<Command>(r#"{ "type": "teleport", "to": [1, 2] }"#).is_err());
// A field on a command that takes none
assert!(serde_json::from_str::<Command>(r#"{ "type": "status", "milliseconds": 5 }"#).is_err());
}
#[test]
fn names_match_the_type_field() {
let commands = [Command::KeyDown { key: "Shift".into() }, Command::WaitIdle { timeout: None }, Command::Status {}];
for command in commands {
let json = serde_json::to_value(&command).unwrap();
assert_eq!(json["type"], command.name());
}
}
}
+1 -1
View File
@@ -490,7 +490,7 @@ mod test {
});
// Check if the graph renders
if let Err(e) = editor.eval_graph().await {
if let Err(e) = editor.eval_graph_until_finished().await {
print_problem_to_terminal_on_failure(&format!("Failed to evaluate the graph for document '{document_name}':\n{e}"));
}
@@ -3,6 +3,7 @@ use super::utility_types::{MouseCursorIcon, PersistedState};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage};
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, NodeGraphErrorDiagnostic,
@@ -207,6 +208,23 @@ pub enum FrontendMessage {
layout_target: LayoutTarget,
diff: Vec<WidgetDiff>, // TODO: Align this with what's generated
},
/// The tokens of what a math expression widget holds, for it to color and typeset once they arrive, and the names offered to
/// finish the one at the caret, where they were asked for.
UpdateMathExpressionAnalysis {
#[serde(rename = "widgetId")]
widget_id: WidgetId,
source: String,
tokens: Vec<MathExpressionToken>,
tooltips: Vec<MathExpressionTooltip>,
completions: Option<MathExpressionCompletions>,
},
/// The value of math typed in a math expression widget's number popover, written as a number, or `None` where it isn't a finite real number.
UpdateMathExpressionEvaluation {
#[serde(rename = "widgetId")]
widget_id: WidgetId,
source: String,
result: Option<String>,
},
UpdateImportReorderIndex {
#[serde(rename = "importIndex")]
index: Option<usize>,
@@ -35,4 +35,19 @@ pub enum LayoutMessage {
widget_id: WidgetId,
file: DroppedFile,
},
/// Tokenizes what a math expression widget holds as it is typed, replying with what the frontend colors and typesets, and with
/// the names that finish the one at the caret, where the caret is given. Unless they're `asked` for, as by a shortcut, names are
/// offered only once part of one is typed.
AnalyzeMathExpression {
layout_target: LayoutTarget,
widget_id: WidgetId,
source: String,
caret: Option<u32>,
asked: bool,
},
/// Evaluates math typed in a math expression widget's number popover, replying with its value written as the number to take its place.
EvaluateMathExpression {
widget_id: WidgetId,
source: String,
},
}
@@ -1,4 +1,7 @@
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
use crate::messages::layout::utility_types::math_expression::{
MathExpressionTokens, math_expression_completions, math_expression_error, math_expression_error_ranges, math_expression_number, math_expression_tokens,
};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::prelude::*;
@@ -91,6 +94,41 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
responses.add((dropdown_input.on_file_drop.callback)(&file));
}
}
LayoutMessage::AnalyzeMathExpression {
layout_target,
widget_id,
source,
caret,
asked,
} => {
let Some(layout) = self.layouts.get(layout_target as usize) else {
warn!("AnalyzeMathExpression referenced an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
return;
};
let Some(widget_instance) = layout.iter().find(|widget| widget.widget_id == widget_id) else {
warn!("AnalyzeMathExpression referenced an invalid widget ID. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
return;
};
let Widget::MathExpressionInput(input) = &*widget_instance.widget else {
warn!("AnalyzeMathExpression referenced a widget other than a MathExpressionInput. `widget_id: {widget_id}`");
return;
};
// The reply carries the source it read, so the frontend can drop one that a later keystroke has outdated
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.accepts_reducers);
let completions = caret.map(|caret| math_expression_completions(&source, caret, asked));
responses.add(FrontendMessage::UpdateMathExpressionAnalysis {
widget_id,
source,
tokens,
tooltips,
completions,
});
}
LayoutMessage::EvaluateMathExpression { widget_id, source } => {
let result = math_expression_number(&source);
responses.add(FrontendMessage::UpdateMathExpressionEvaluation { widget_id, source, result });
}
}
}
@@ -320,6 +358,29 @@ impl LayoutMessageHandler {
responses.add(callback_message);
}
Widget::ImageLabel(_) => {}
Widget::MathExpressionInput(math_expression_input) => {
let callback_message = match action {
WidgetValueAction::Commit => (math_expression_input.on_commit.callback)(&()),
WidgetValueAction::Update => {
let Some(update_value) = value.as_str() else {
error!("MathExpressionInput update was not of type: string");
return;
};
// The widget is resent as stored, so its tokens and errors must be for its new value rather than its old one
let accepts_reducers = math_expression_input.accepts_reducers;
let error = math_expression_error(update_value, accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, accepts_reducers);
math_expression_input.tokens = tokens;
math_expression_input.tooltips = tooltips;
math_expression_input.errors = math_expression_error_ranges(update_value, error.as_ref());
math_expression_input.value = update_value.into();
(math_expression_input.on_update.callback)(math_expression_input)
}
};
responses.add(callback_message);
}
Widget::ShortcutLabel(_) => {}
Widget::IconLabel(_) => {}
Widget::NodeCatalog(node_type_input) => match action {
@@ -377,7 +438,31 @@ impl LayoutMessageHandler {
Widget::ParameterExposeButton(parameter_expose_button) => {
let callback_message = match action {
WidgetValueAction::Commit => (parameter_expose_button.on_commit.callback)(&()),
WidgetValueAction::Update => (parameter_expose_button.on_update.callback)(parameter_expose_button),
WidgetValueAction::Update => {
let Some(value_path) = value.as_array() else {
error!("ParameterExposeButton update was not of type: array");
return;
};
// Process the bare button click, since no menu is involved if we're given an empty array.
if value_path.is_empty() {
(parameter_expose_button.on_update.callback)(parameter_expose_button)
}
// Process the menu list entry click, since we have a path to the value of the contained menu entry.
else {
let mut current_submenu = &parameter_expose_button.menu_list_children;
let mut final_entry: Option<&MenuListEntry> = None;
for value in value_path.iter().filter_map(|v| v.as_str().map(|s| s.to_string())) {
let Some(next_entry) = current_submenu.iter().flatten().find(|e| e.value == value) else { return };
current_submenu = &next_entry.children;
final_entry = Some(next_entry);
}
(final_entry.unwrap().on_commit.callback)(&())
}
}
};
responses.add(callback_message);
@@ -147,6 +147,23 @@ pub trait Diffable: Clone + PartialEq {
fn replace_widget_ids(&mut self, layout_target: LayoutTarget, widget_path: &mut Vec<usize>, checkbox_map: &HashMap<CheckboxId, CheckboxId>);
}
/// Hashes menu list entry sections, with each entry's children, for the frontend to cache a menu list by.
pub fn hash_menu_list_entry_sections(entry_sections: &MenuListEntrySections) -> u64 {
fn hash_into(hasher: &mut DefaultHasher, entry_sections: &MenuListEntrySections) {
for (index, entries) in entry_sections.iter().enumerate() {
index.hash(hasher);
for entry in entries {
entry.hash(hasher);
hash_into(hasher, &entry.children);
}
}
}
let mut hasher = DefaultHasher::new();
hash_into(&mut hasher, entry_sections);
hasher.finish()
}
/// Computes a deterministic WidgetId based on layout target, path, and widget type.
fn compute_widget_id(layout_target: LayoutTarget, widget_path: &[usize], widget: &Widget) -> WidgetId {
let mut hasher = DefaultHasher::new();
@@ -454,6 +471,7 @@ impl LayoutGroup {
Widget::IconLabel(x) => &mut x.tooltip_description,
Widget::ImageButton(x) => &mut x.tooltip_description,
Widget::ImageLabel(x) => &mut x.tooltip_description,
Widget::MathExpressionInput(x) => &mut x.tooltip_description,
Widget::NumberInput(x) => &mut x.tooltip_description,
Widget::PopoverButton(x) => &mut x.tooltip_description,
Widget::TextAreaInput(x) => &mut x.tooltip_description,
@@ -815,6 +833,7 @@ pub enum Widget {
IconLabel(IconLabel),
ImageButton(ImageButton),
ImageLabel(ImageLabel),
MathExpressionInput(MathExpressionInput),
ShortcutLabel(ShortcutLabel),
NodeCatalog(NodeCatalog),
NumberInput(NumberInput),
@@ -878,6 +897,7 @@ impl DiffUpdate {
Widget::ShortcutLabel(widget) => widget.shortcut.as_mut(),
Widget::IconLabel(_)
| Widget::ImageLabel(_)
| Widget::MathExpressionInput(_)
| Widget::NodeCatalog(_)
| Widget::ReferencePointInput(_)
| Widget::RadioInput(_)
@@ -924,28 +944,6 @@ impl DiffUpdate {
}
}
// Hash the menu list entry sections for caching purposes
let hash_menu_list_entry_sections = |entry_sections: &MenuListEntrySections| {
struct RecursiveHasher<'a> {
hasher: DefaultHasher,
hash_fn: &'a dyn Fn(&mut RecursiveHasher, &MenuListEntrySections),
}
let mut recursive_hasher = RecursiveHasher {
hasher: DefaultHasher::new(),
hash_fn: &|recursive_hasher, entry_sections| {
for (index, entries) in entry_sections.iter().enumerate() {
index.hash(&mut recursive_hasher.hasher);
for entry in entries {
entry.hash(&mut recursive_hasher.hasher);
(recursive_hasher.hash_fn)(recursive_hasher, &entry.children);
}
}
},
};
(recursive_hasher.hash_fn)(&mut recursive_hasher, entry_sections);
recursive_hasher.hasher.finish()
};
// Apply shortcut conversions to all widgets that have menu lists
let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget {
Widget::DropdownInput(dropdown_input) => {
@@ -956,6 +954,10 @@ impl DiffUpdate {
apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping);
text_button.menu_list_children_hash = hash_menu_list_entry_sections(&text_button.menu_list_children);
}
Widget::ParameterExposeButton(parameter_expose_button) => {
apply_action_shortcut_to_menu_lists(&mut parameter_expose_button.menu_list_children, action_input_mapping);
parameter_expose_button.menu_list_children_hash = hash_menu_list_entry_sections(&parameter_expose_button.menu_list_children);
}
_ => {}
};
@@ -0,0 +1,266 @@
//! What the math parser reads of an expression, converted for a math expression widget into the UTF-16 code units its frontend's strings use.
use crate::messages::layout::utility_types::layout_widget::hash_menu_list_entry_sections;
use crate::messages::layout::utility_types::widget_prelude::*;
use math_parser::parser::{ErrorMessage, ParseError};
/// The source's UTF-16 length up to each byte, so the parser's byte offsets convert to the frontend's code units in one lookup.
fn utf16_offsets(source: &str) -> Vec<u32> {
let mut units = vec![0_u32; source.len() + 1];
let mut count = 0;
for (byte, character) in source.char_indices() {
units[byte..byte + character.len_utf8()].fill(count);
count += character.len_utf16() as u32;
}
units[source.len()] = count;
units
}
/// Why a math expression fails to parse, or `None` when it parses. Where the node applies a lone operator or function name like
/// `+` or `min` across its items, that counts as valid too.
pub fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<ParseError> {
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
return None;
}
math_parser::ast::Node::try_parse_from_str(expression).err()
}
/// The stretches of a math expression its parse error points at, for the frontend to underline. An empty span, where something is
/// missing like at the end of the input, has nothing to underline, so it widens to the character before it, past any whitespace.
pub fn math_expression_error_ranges(source: &str, error: Option<&ParseError>) -> Vec<MathExpressionRange> {
let units = utf16_offsets(source);
let spans = error.into_iter().flat_map(|error| error.messages().iter().filter_map(ErrorMessage::span));
spans
.filter_map(|span| {
let before = source.get(..span.start)?.trim_end();
let span = match before.chars().next_back() {
Some(character) if span.is_empty() => before.len() - character.len_utf8()..before.len(),
_ => span,
};
Some(MathExpressionRange {
start: *units.get(span.start)?,
end: *units.get(span.end)?,
})
})
.collect()
}
/// The names offered to finish the one being typed in a math expression, in sections by kind, each entry's value being the text
/// that replaces the stretch of code units from `start` to `end`, the name the caret is in or beside. A call's `()` takes the caret
/// between them, except that a suffixed form's `_`, like `log_`'s, is selected instead, for its suffix to be typed over or after it.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MathExpressionCompletions {
pub start: u32,
pub end: u32,
pub entries: MenuListEntrySections,
#[serde(rename = "entriesHash")]
pub entries_hash: u64,
/// The index among all the sections' entries of the one fitting what's typed best, which starts highlighted.
pub best: u32,
}
/// The names offered to finish the one the caret, given in code units, stands in or beside. Unless they're `asked` for, as by a
/// shortcut rather than by typing, they're offered only once part of a name is typed before the caret.
pub fn math_expression_completions(source: &str, caret: u32, asked: bool) -> MathExpressionCompletions {
let units = utf16_offsets(source);
// Each character's bytes share the offset of its first, so the first byte reaching the caret begins the character after it
let byte = units.partition_point(|&unit| unit < caret).min(source.len());
let completions = math_parser::completion::completions(source, byte, asked);
let best = completions.best as u32;
// A function comes with the parentheses of its call, unless they're already there, spaced or not
let parenthesized = source.get(completions.end..).unwrap_or_default().trim_start().starts_with('(');
let mut entries: MenuListEntrySections = Vec::new();
let mut previous_kind = None;
for offer in completions.offers {
if previous_kind != Some(offer.kind) {
entries.push(Vec::new());
previous_kind = Some(offer.kind);
}
if let Some(section) = entries.last_mut() {
let insertion = if offer.signature.is_some() && !parenthesized {
format!("{}()", offer.name)
} else {
offer.name.to_string()
};
let label = offer.signature.unwrap_or_else(|| offer.name.to_string());
// A builtin is named at the row's end and hovers with the tooltip it has where it's written
let entry = MenuListEntry::new(insertion).label(label);
let entry = match offer.tooltip {
Some(tooltip) => entry
.annotation(tooltip.label.clone())
.tooltip_label(tooltip.label)
.tooltip_description(tooltip.description)
.tooltip_code(tooltip.form.unwrap_or_default()),
None => entry,
};
section.push(entry);
}
}
MathExpressionCompletions {
start: units[completions.start],
end: units[completions.end],
entries_hash: hash_menu_list_entry_sections(&entries),
entries,
best,
}
}
/// The value of math typed in place of a number, written as a number literal, or `None` where it isn't a finite real number.
pub fn math_expression_number(source: &str) -> Option<String> {
use math_parser::value::{Number, Value};
let Value::Number(number) = math_parser::evaluate(source).ok()?.ok()?.into_value()?;
if let Number::Integer(integer) = number {
return Some(integer.to_string());
}
let real = graphene_std::math::float_noise::round_away_float_noise(number.as_real()?);
if !real.is_finite() {
return None;
}
// A magnitude far from 1 is written in scientific notation, which a literal can hold too
let magnitude = real.abs();
Some(if magnitude != 0. && !(1e-6..1e16).contains(&magnitude) {
format!("{real:e}")
} else {
real.to_string()
})
}
/// A math expression's tokens for the frontend to color and typeset, each naming its tooltip by its index among the tooltips, which
/// are listed once each however many tokens share one, like a matrix literal's brackets and separators.
pub struct MathExpressionTokens {
pub tokens: Vec<MathExpressionToken>,
pub tooltips: Vec<MathExpressionTooltip>,
}
/// The tokens of a math expression for the frontend to color and typeset, with the parser's byte offsets converted to code units.
pub fn math_expression_tokens(source: &str, accepts_reducers: bool) -> MathExpressionTokens {
let units = utf16_offsets(source);
let mut tooltips: Vec<MathExpressionTooltip> = Vec::new();
let tokens = math_parser::highlight::highlight(source, accepts_reducers).into_iter().map(|token| {
let tooltip = token.tooltip.map(|tooltip| MathExpressionTooltip {
label: tooltip.label,
form: tooltip.form,
description: tooltip.description,
signature: tooltip.signature.map(|signature| MathExpressionSignature {
opening: signature.opening,
parameters: signature.parameters.into_iter().map(str::to_string).collect(),
separator: signature.separator.to_string(),
closing: signature.closing.to_string(),
range: signature.range.to_string(),
pointers: signature
.pointers
.into_iter()
.map(|pointer| MathExpressionPointer {
line: pointer.line as u32,
column: pointer.column as u32,
arrow: pointer.arrow.to_string(),
})
.collect(),
lines: signature.lines.into_iter().map(|line| line as u32).collect(),
}),
});
let tooltip = tooltip.map(|tooltip| match tooltips.iter().position(|listed| *listed == tooltip) {
Some(index) => index as u32,
None => {
tooltips.push(tooltip);
(tooltips.len() - 1) as u32
}
});
MathExpressionToken {
start: units[token.start],
end: units[token.end],
role: token.role.into(),
superscript: token.superscript,
subscript: token.subscript.map(|offset| units[token.start + offset] - units[token.start]),
partner: token.partner.map(|partner| partner as u32),
separates: token.separates.map(|opener| opener as u32),
tooltip,
literal: token.literal.map(|literal| MathExpressionLiteral {
start: units[literal.start],
after_operand: literal.after_operand,
}),
}
});
let tokens = tokens.collect();
MathExpressionTokens { tokens, tooltips }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn math_typed_for_a_number_is_written_as_its_value() {
assert_eq!(math_expression_number("1/4").as_deref(), Some("0.25"));
assert_eq!(math_expression_number("0.1 + 0.2").as_deref(), Some("0.3"), "float noise is rounded away");
assert_eq!(math_expression_number("2^60").as_deref(), Some("1152921504606846976"), "an integer stays exact");
assert_eq!(math_expression_number("-pi").as_deref(), Some("-3.14159265359"), "rounding away noise keeps 12 significant digits");
assert_eq!(math_expression_number("10^-9 / 4").as_deref(), Some("2.5e-10"), "a tiny magnitude is written in scientific notation");
// Anything other than a finite real number has no number to write
for source in ["1/0", "2i", "x + 1", "I", "2 +"] {
assert_eq!(math_expression_number(source), None, "`{source}`");
}
}
#[test]
fn math_expression_completions_count_code_units_and_group_by_kind() {
// `π` is one code unit and `𝑥` two, so the typed `ta` begins 6 units in, though 9 bytes in
let completions = math_expression_completions("π𝑥 + ta", 8, false);
assert_eq!((completions.start, completions.end), (6, 8));
assert_eq!(
math_expression_completions("x wh", 4, false).best,
1,
"`where` is highlighted after `within`, which only holds the letters"
);
// A function shows its signature while its call is what's inserted
let sections = |completions: MathExpressionCompletions| {
let section = |section: &Vec<MenuListEntry>| section.iter().map(|entry| (entry.value.clone(), entry.label.clone())).collect::<Vec<_>>();
completions.entries.iter().map(section).collect::<Vec<_>>()
};
let pair = |value: &str, label: &str| (value.to_string(), label.to_string());
assert_eq!(
sections(completions),
[
vec![pair("tan()", "tan(θ)"), pair("tanh()", "tanh(x)"), pair("translation()", "translation(A)")],
vec![pair("τ", "τ"), pair("tau", "tau")]
]
);
// Parentheses already after the name, spaced or not, are the call's own
assert_eq!(
sections(math_expression_completions("ta (2)", 2, false)),
[
vec![pair("tan", "tan(θ)"), pair("tanh", "tanh(x)"), pair("translation", "translation(A)")],
vec![pair("τ", "τ"), pair("tau", "tau")]
]
);
// A suffixed form comes with its call's parentheses like any function
let completions = math_expression_completions("log", 3, false);
assert_eq!(sections(completions), [vec![pair("log_()", "log_(x)"), pair("log()", "log(x, b?)")]]);
// An operator typed in ASCII offers its typeset alias in place of it
let completions = math_expression_completions("!", 1, false);
assert_eq!((completions.start, completions.end), (0, 1));
assert_eq!(sections(completions), [vec![pair("¬", "¬")]]);
// Typing where no name is begun offers nothing, unless the names are asked for
assert!(math_expression_completions("2 + ", 4, false).entries.is_empty());
assert!(!math_expression_completions("2 + ", 4, true).entries.is_empty());
}
}
@@ -1,4 +1,5 @@
pub mod layout_widget;
pub mod math_expression;
pub mod tooltip_markdown;
pub mod widgets;
@@ -96,6 +96,13 @@ pub struct ParameterExposeButton {
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
// Children
#[serde(rename = "menuListChildren")]
pub menu_list_children: MenuListEntrySections,
#[serde(rename = "menuListChildrenHash")]
#[widget_builder(skip)]
pub menu_list_children_hash: u64,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
@@ -138,6 +138,8 @@ pub struct MenuListEntry {
pub label: String,
#[widget_builder(string)]
pub icon: Option<IconName>,
/// Text at the row's right end, in the place of a shortcut, like the name of a completion.
pub annotation: String,
pub disabled: bool,
// Children
@@ -156,6 +158,9 @@ pub struct MenuListEntry {
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
/// Code at the right of the tooltip's header, like a completion's signature.
#[serde(rename = "tooltipCode")]
pub tooltip_code: String,
// Callbacks
#[serde(skip)]
@@ -171,6 +176,7 @@ impl std::hash::Hash for MenuListEntry {
self.value.hash(state);
self.label.hash(state);
self.icon.hash(state);
self.annotation.hash(state);
self.disabled.hash(state);
}
}
@@ -499,6 +505,153 @@ pub struct TextInput {
pub on_commit: WidgetCallback<()>,
}
/// A math expression's text field, typeset with math italics and syntax highlighting as it is edited.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, WidgetBuilder)]
#[derivative(Debug, PartialEq, Default)]
pub struct MathExpressionInput {
// Content
#[widget_builder(constructor)]
pub value: String,
/// The value's tokens, which the frontend colors and typesets, as it does the tokens sent for each edit while typing.
pub tokens: Vec<MathExpressionToken>,
/// What hovering each token shows, listed once each however many tokens share one.
pub tooltips: Vec<MathExpressionTooltip>,
/// The stretches of the value its parse errors point at, which the frontend underlines.
pub errors: Vec<MathExpressionRange>,
/// Whether a lone operator or function name like `+` or `max` is an expression, applied across a list as by the Math node.
#[serde(skip)]
pub accepts_reducers: bool,
pub disabled: bool,
// Tooltips
#[serde(rename = "tooltipLabel")]
pub tooltip_label: String,
#[serde(rename = "tooltipDescription")]
pub tooltip_description: String,
#[serde(rename = "tooltipShortcut")]
pub tooltip_shortcut: Option<ActionShortcut>,
// Callbacks
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_update: WidgetCallback<MathExpressionInput>,
#[serde(skip)]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
pub on_commit: WidgetCallback<()>,
}
/// A stretch of a math expression with the role its spelling gives it, in the UTF-16 code units the frontend's strings use.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MathExpressionToken {
pub start: u32,
pub end: u32,
pub role: MathExpressionRole,
/// How many exponents deep it stands, 0 outside any.
pub superscript: u8,
/// Where a name's subscript begins, in code units from its start.
pub subscript: Option<u32>,
/// The index among the tokens of the delimiter pairing with this one.
pub partner: Option<u32>,
/// For a comma or semicolon, the index among the tokens of the opener of the group whose parts it separates.
pub separates: Option<u32>,
/// The index among the tooltips of what hovering the token shows: a builtin's, constant's, or operator's documentation, or the
/// drawing of a matrix or range literal.
pub tooltip: Option<u32>,
/// For a finite number, the literal it's part of, which the frontend can adjust as one value.
pub literal: Option<MathExpressionLiteral>,
}
/// A number as the frontend may adjust it as one value, written from its start to the end of the number's token.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MathExpressionLiteral {
/// Where it begins, at any sign right before the number.
pub start: u32,
/// Whether it follows an operand it multiplies, where a sign written before it would subtract instead.
#[serde(rename = "afterOperand")]
pub after_operand: bool,
}
/// A math expression token's hover text, in the tooltip Markdown subset.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MathExpressionTooltip {
pub label: String,
/// How it's written, like `sin(θ)`, `a + b`, or `π`, which the frontend shows beside the label.
pub form: Option<String>,
pub description: String,
/// The signature of a call or matrix literal, which its form shows, for the frontend to mark the argument or entry being typed in it.
pub signature: Option<MathExpressionSignature>,
}
/// A call's or matrix literal's parameters between its delimiters, like `sin(` and `)` or `[` and `]`.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MathExpressionSignature {
pub opening: String,
pub parameters: Vec<String>,
pub separator: String,
pub closing: String,
/// For a call, the range of its results, like `[0, ∞]`, written after an arrow.
pub range: String,
/// For a drawn matrix literal, the arrow pointing at each entry's row or column, for the frontend to draw at the one being typed.
pub pointers: Vec<MathExpressionPointer>,
/// For a call, the description line explaining each parameter, for the frontend to mark the one being typed.
pub lines: Vec<u32>,
}
/// An arrow to draw into a tooltip description's code block, at a character of one of its lines.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MathExpressionPointer {
pub line: u32,
pub column: u32,
pub arrow: String,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum MathExpressionRole {
Number,
Variable,
Matrix,
Basis,
Function,
Keyword,
Operator,
Bracket,
MatrixLiteral,
Error,
}
impl From<math_parser::highlight::Role> for MathExpressionRole {
fn from(role: math_parser::highlight::Role) -> Self {
use math_parser::highlight::Role;
match role {
Role::Number => Self::Number,
Role::Variable => Self::Variable,
Role::Matrix => Self::Matrix,
Role::Basis => Self::Basis,
Role::Function => Self::Function,
Role::Keyword => Self::Keyword,
Role::Operator => Self::Operator,
Role::Bracket => Self::Bracket,
Role::MatrixLiteral => Self::MatrixLiteral,
Role::Error => Self::Error,
}
}
}
/// A stretch of a math expression, in the UTF-16 code units the frontend's strings use.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MathExpressionRange {
pub start: u32,
pub end: u32,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Default, Derivative, serde::Serialize, serde::Deserialize, WidgetBuilder)]
#[derivative(Debug, PartialEq)]
@@ -735,7 +735,7 @@ impl LayoutHolder for MenuBarMessageHandler {
.icon(if message_logging_verbosity_off {
#[cfg(not(target_os = "macos"))]
{
"SmallDot".to_string()
"DataSourceValue".to_string()
}
#[cfg(target_os = "macos")]
{
@@ -749,7 +749,7 @@ impl LayoutHolder for MenuBarMessageHandler {
.icon(if message_logging_verbosity_names {
#[cfg(not(target_os = "macos"))]
{
"SmallDot".to_string()
"DataSourceValue".to_string()
}
#[cfg(target_os = "macos")]
{
@@ -763,7 +763,7 @@ impl LayoutHolder for MenuBarMessageHandler {
.icon(if message_logging_verbosity_contents {
#[cfg(not(target_os = "macos"))]
{
"SmallDot".to_string()
"DataSourceValue".to_string()
}
#[cfg(target_os = "macos")]
{
@@ -11,13 +11,12 @@ use graphene_std::animation::RealTimeMode;
use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::core_types::misc::format_f64;
use graphene_std::extract_xy::XY;
use graphene_std::gradient::Gradient;
use graphene_std::list::{Item, List, NodeIdPath};
use graphene_std::math::float_noise::round_away_float_noise;
use graphene_std::memo::IORecord;
use graphene_std::raster::{
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute,
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
@@ -238,13 +237,11 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<TextDenomination>,
List<DesaturateMethod>,
List<RedGreenBlue>,
List<RedGreenBlueAlpha>,
List<RelativeAbsolute>,
List<SelectiveColorChoice>,
List<TonalRange>,
List<AdjustmentChannel>,
List<HueSaturationRange>,
List<XY>,
List<ScaleType>,
List<ReferencePoint>,
List<CentroidType>,
@@ -294,13 +291,11 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
Item<TextDenomination>,
Item<DesaturateMethod>,
Item<RedGreenBlue>,
Item<RedGreenBlueAlpha>,
Item<RelativeAbsolute>,
Item<SelectiveColorChoice>,
Item<TonalRange>,
Item<AdjustmentChannel>,
Item<HueSaturationRange>,
Item<XY>,
Item<ScaleType>,
Item<ReferencePoint>,
Item<CentroidType>,
@@ -1034,13 +1029,11 @@ impl_table_item_layout_for_choice_enum!(
TextDenomination,
DesaturateMethod,
RedGreenBlue,
RedGreenBlueAlpha,
RelativeAbsolute,
SelectiveColorChoice,
TonalRange,
AdjustmentChannel,
HueSaturationRange,
XY,
ScaleType,
CentroidType,
BooleanOperation,
@@ -1251,13 +1244,11 @@ macro_rules! known_item_types {
TextDenomination,
DesaturateMethod,
RedGreenBlue,
RedGreenBlueAlpha,
RelativeAbsolute,
SelectiveColorChoice,
TonalRange,
AdjustmentChannel,
HueSaturationRange,
XY,
ScaleType,
ReferencePoint,
CentroidType,
@@ -188,8 +188,8 @@ fn diff_attributes(out: &mut String, label: &str, stored: &document_graph_storag
let (differing_values, differing_timestamps): (Vec<_>, Vec<_>) = stored_keys
.intersection(&target_keys)
.copied()
.filter(|k| stored.get(*k) != target.get(*k))
.partition(|k| stored.get(*k).map(|v| &v.value) != target.get(*k).map(|v| &v.value));
.filter(|k| stored.get(k) != target.get(k))
.partition(|k| stored.get(k).map(|v| &v.value) != target.get(k).map(|v| &v.value));
let _ = writeln!(
out,
@@ -37,7 +37,7 @@ use document_graph_storage::Declarations;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::value::{TaggedValue, deserialize_replacing_null_floats_with_zero};
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graph_craft::list;
use graphene_std::Cover;
@@ -2174,7 +2174,7 @@ impl DocumentMessageHandler {
}
pub fn deserialize_document(serialized_content: &str) -> Result<Self, EditorError> {
let document_message_handler = serde_json::from_str::<DocumentMessageHandler>(serialized_content)
let document_message_handler = deserialize_replacing_null_floats_with_zero::<DocumentMessageHandler>(serialized_content)
.or_else(|e| {
log::warn!("Failed to directly load document with the following error: {e}. Trying old DocumentMessageHandler.");
// TODO: Eventually remove this document upgrade code
@@ -4368,7 +4368,7 @@ mod document_message_handler_tests {
})
.await;
let instrumented = editor.eval_graph().await.unwrap();
let instrumented = editor.eval_graph_until_finished().await.unwrap();
// The emptiness guards keep these assertions honest: a wrong `Output` type on `grab_all_input` yields no records at all, which would otherwise pass without checking anything
let base_lengths: Vec<usize> = instrumented
@@ -15,9 +15,7 @@ use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::*;
use graph_craft::document::*;
use graph_craft::{concrete, list};
use graphene_std::extract_xy::XY;
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
#[allow(unused_imports)]
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
@@ -676,114 +674,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
description: Cow::Borrowed("TODO"),
properties: None,
},
DocumentNodeDefinition {
identifier: "Split Channels",
category: "Raster: Channels",
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::node(NodeId(0), 0),
NodeInput::node(NodeId(1), 0),
NodeInput::node(NodeId(2), 0),
NodeInput::node(NodeId(3), 0),
],
nodes: [
NodeTemplate {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 4)),
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::import(list!(Raster<CPU>), 0),
NodeInput::value(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha), false),
],
implementation: NodeTemplateImplementation::ProtoNode(raster_nodes::adjustments::extract_channel::IDENTIFIER),
call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 6)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Raster<CPU>), true)],
input_metadata: vec![("Image", "TODO").into()],
output_names: vec!["".to_string(), "Red".to_string(), "Green".to_string(), "Blue".to_string(), "Alpha".to_string()],
..Default::default()
},
description: Cow::Borrowed("TODO"),
properties: None,
},
DocumentNodeDefinition {
identifier: "Split Vec2",
category: "Math: Vec2",
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::X), false)],
implementation: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::import(item!(DVec2), 0), NodeInput::value(TaggedValue::XY(XY::Y), false)],
implementation: NodeTemplateImplementation::ProtoNode(extract_xy::extract_xy::IDENTIFIER),
call_argument: generic!(T),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), true)],
input_metadata: vec![("Vec2", "TODO").into()],
output_names: vec!["".to_string(), "X".to_string(), "Y".to_string()],
..Default::default()
},
description: Cow::Borrowed(
"Decomposes the X and Y components of a vec2.\n\
\n\
The inverse of this node is **Combine Vec2**, which composes a vec2 from its X and Y components.",
),
properties: None,
},
DocumentNodeDefinition {
identifier: "Extract",
category: "",
@@ -1671,7 +1561,7 @@ impl InputTypeConstraint {
pub fn collect_node_types() -> Vec<FrontendNodeType> {
DOCUMENT_NODE_TYPES
.iter()
.filter(|(_, definition)| !definition.category.is_empty())
.filter(|(_, definition)| !registry::is_hidden_category(definition.category))
.map(|(identifier, definition)| {
let mut name = definition.node_template.display_name.clone();
if name.is_empty() {
@@ -1751,8 +1641,6 @@ mod test {
})
.await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
editor.eval_graph().await.expect("the Origins to Polyline chain should type-resolve and evaluate");
}
// Guards the unconnected Path input, whose default must match the rank of the Morph connector it feeds
@@ -1772,8 +1660,6 @@ mod test {
})
.await;
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
editor.eval_graph().await.expect("the Blend network should type-resolve and evaluate");
}
}
@@ -42,6 +42,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
description,
properties,
context_features,
output_fields,
..
} = metadata;
@@ -66,6 +67,20 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
};
let inputs = preprocessor::node_inputs(fields, first_node_io);
// A multi-output node names each output after its field, leaving the hidden primary output unnamed
let output_names = output_fields
.as_ref()
.map(|destructure| {
(0..destructure.number_of_outputs())
.map(|output_index| {
let field = destructure.field_index_for_output(output_index).and_then(|field_index| destructure.fields.get(field_index));
field.map_or_else(String::new, |field| field.name.to_string())
})
.collect()
})
.unwrap_or_default();
definitions_map.insert(
identifier,
DocumentNodeDefinition {
@@ -85,6 +100,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
})
.collect(),
output_names,
..Default::default()
},
category,
@@ -83,7 +83,7 @@ pub struct NodeGraphMessageHandler {
pub wire_in_progress_to_connector: Option<DVec2>,
/// The data type determining the color of the wire being dragged.
pub wire_in_progress_type: FrontendGraphDataType,
/// State for the context menu popups.
/// State for the context menus.
pub context_menu: Option<ContextMenuInformation>,
/// Index of selected node to be deselected on pointer up when shift clicking an already selected node
pub deselect_on_pointer_up: Option<usize>,
@@ -784,7 +784,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let clicked_input = network_interface.input_connector_from_click(click, selection_network_path);
let clicked_output = network_interface.output_connector_from_click(click, selection_network_path);
let network_metadata = network_interface.network_metadata(selection_network_path).unwrap();
// Create the add node popup on right click, then exit
// Create the add node menu on right click, then exit
if right_click {
// Abort dragging a node
if self.drag_start.is_some() {
@@ -2,7 +2,8 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodePropertiesContext};
use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_block, markdown_code_span};
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -20,10 +21,9 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, No
use graph_craft::{Type, concrete, item};
use graphene_std::animation::RealTimeMode;
use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::raster::{
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha,
RelativeAbsolute, SelectiveColorChoice, TonalRange,
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TextAlign};
@@ -41,7 +41,7 @@ use graphene_std::vector::style::{
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::MessagePart;
use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf;
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
@@ -82,7 +82,59 @@ pub fn commit_value<T>(_: &T) -> Message {
DocumentMessage::AddTransaction.into()
}
pub fn expose_widget(node_id: NodeId, index: usize, data_type: FrontendGraphDataType, exposed: bool) -> WidgetInstance {
pub fn expose_widget(
node_id: NodeId,
index: usize,
data_type: FrontendGraphDataType,
resolved_type: String,
valid_types: Vec<Type>,
is_subnetwork: bool,
is_wired: bool,
exposed: bool,
) -> WidgetInstance {
let input_connector = InputConnector::node_at_index(node_id, index);
// Subnetwork inputs and wired inputs are read-only here: the type follows the subgraph or the upstream wire automatically.
// Only unconnected protonode inputs accept a manual choice that picks among multiple type implementations.
let entries_clickable = !is_subnetwork && !is_wired;
let type_entries: Vec<MenuListEntry> = if valid_types.is_empty() {
// Fall back to a single read-only entry when no valid types are available (e.g., a type-resolution error).
vec![MenuListEntry::new("type").label(resolved_type.clone()).disabled(true)]
} else {
valid_types
.into_iter()
.enumerate()
.map(|(i, ty)| {
let label = ty.nested_type().to_string();
let is_active = label == resolved_type;
let is_clickable = entries_clickable && !is_active;
let mut entry = MenuListEntry::new(format!("type-{i}")).label(label).disabled(!is_clickable);
// The active entry gets a bullet-point icon (the small filled circle) to mark it as the current selection.
if is_active {
entry = entry.icon("DataSourceValue");
}
if is_clickable {
entry = entry.on_commit(move |_| {
NodeGraphMessage::SetInputValue {
node_id,
input_index: index,
value: TaggedValue::from_type_or_none(&ty).into(),
}
.into()
});
}
entry
})
.collect()
};
let type_submenu = vec![type_entries];
ParameterExposeButton::new()
.exposed(exposed)
.data_type(data_type)
@@ -91,14 +143,24 @@ pub fn expose_widget(node_id: NodeId, index: usize, data_type: FrontendGraphData
} else {
"Expose this parameter as a node input in the graph."
})
.on_update(move |_parameter| Message::Batched {
messages: Box::new([NodeGraphMessage::ExposeInput {
input_connector: InputConnector::node_at_index(node_id, index),
set_to_exposed: !exposed,
start_transaction: true,
}
.into()]),
})
.menu_list_children(vec![vec![
MenuListEntry::new("value").label("Value").icon("DataSourceValue").children(type_submenu.clone()).on_commit(move |_| {
NodeGraphMessage::ExposeInput {
input_connector,
set_to_exposed: false,
start_transaction: true,
}
.into()
}),
MenuListEntry::new("graph").label("Graph").icon("DataSourceGraph").children(type_submenu).on_commit(move |_| {
NodeGraphMessage::ExposeInput {
input_connector,
set_to_exposed: true,
start_transaction: true,
}
.into()
}),
]])
.widget_instance()
}
@@ -152,6 +214,10 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
parameter_widgets_info.node_id,
parameter_widgets_info.index,
parameter_widgets_info.input_type,
parameter_widgets_info.resolved_type.clone(),
parameter_widgets_info.valid_types.clone(),
parameter_widgets_info.is_subnetwork,
parameter_widgets_info.is_wired,
input.is_exposed(),
));
}
@@ -348,8 +414,6 @@ pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, optio
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
@@ -417,58 +481,55 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
widgets
}
/// A math expression's text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
/// A math expression's typeset text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return text_widget(parameter_widgets_info);
};
let Some(error) = math_expression_error(expression, accepts_reducers) else {
return text_widget(parameter_widgets_info);
};
let error = math_expression_error(expression, accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, accepts_reducers);
let input = MathExpressionInput::new(expression.clone())
.tokens(tokens)
.tooltips(tooltips)
.accepts_reducers(accepts_reducers)
.errors(math_expression_error_ranges(expression, error.as_ref()))
.on_update(parameter_widgets_info.update_value(|x: &MathExpressionInput| TaggedValue::String(x.value.clone())))
.on_commit(commit_value)
.widget_instance();
// The 12px icon is padded to a checkbox's 16px so the field still lines up with the rows around it
// The icon holds the assist area, blank without an error so an edit making or fixing one leaves the field in place, and its 12px is
// padded to a checkbox's 16px so the field lines up with the rows around it
let icon = match &error {
Some(error) => IconLabel::new("Warning")
.tooltip_label("Invalid Math Expression")
.tooltip_description(math_expression_error_description(error)),
None => IconLabel::new("Empty12px"),
};
parameter_widgets_info.blank_assist = false;
let mut widgets = start_widgets(&parameter_widgets_info);
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
IconLabel::new("Warning").tooltip_label("Invalid Math Expression").tooltip_description(error).widget_instance(),
icon.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextInput::new(expression.clone())
.on_update(parameter_widgets_info.update_value(|x: &TextInput| TaggedValue::String(x.value.clone())))
.on_commit(commit_value)
.widget_instance(),
input,
]);
widgets
}
/// Why a math expression fails to parse, as tooltip Markdown, or `None` when it parses. Where the node applies a lone operator or
/// function name like `+` or `min` across its items, that counts as valid too. An error at a place in the expression repeats the
/// expression with carets under that place, as a compiler does.
fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<String> {
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
return None;
}
let error = math_parser::ast::Node::try_parse_from_str(expression).err()?;
/// A parse error's messages as tooltip Markdown, leaving the places they point at for the field to underline.
fn math_expression_error_description(error: &ParseError) -> String {
// The quoted code may be the expression's own text, so it goes in a span nothing inside can close, and the prose is escaped
let messages = error.messages().iter().map(|message| {
let parts = message.parts().iter().map(|part| match part {
MessagePart::Text(text) => escape_markdown(text),
MessagePart::Code(code) => markdown_code_span(code),
});
let prose = parts.collect::<String>();
// The carets and their label line up under the expression's characters, with one caret where the span is empty, like at the end of the input
let Some(span) = message.span() else { return prose };
let indent = " ".repeat(expression.get(..span.start).map_or(0, |text| text.chars().count()));
let carets = "^".repeat(expression.get(span.start..span.end).map_or(0, |text| text.chars().count()).max(1));
format!("{prose}\n{}", markdown_code_block(&format!("{expression}\n{indent}{carets}\n{indent}error here")))
parts.collect::<String>()
});
Some(messages.collect::<Vec<_>>().join("\n"))
messages.collect::<Vec<_>>().join("\n")
}
pub fn text_area_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetInstance> {
@@ -3100,6 +3161,14 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
default_type = field.default_type.clone();
}
// Prefer the input's currently stored value type over the protonode's default. This is what lets a user-chosen
// type (e.g. swapping `f64` for `DVec2`) drive the widget, instead of always rendering the registry default.
if let Some(document_node) = context.network_interface.document_node(&node_id, context.selection_network_path)
&& let Some(NodeInput::Value { tagged_value, .. }) = document_node.inputs.get(input_index)
{
break 'early_return tagged_value.ty();
}
if let Some(default) = default_type {
break 'early_return default;
}
@@ -3520,6 +3589,10 @@ pub struct ParameterWidgetsInfo<'a> {
name: String,
description: String,
input_type: FrontendGraphDataType,
resolved_type: String,
valid_types: Vec<Type>,
is_subnetwork: bool,
is_wired: bool,
blank_assist: bool,
exposable: bool,
fonts: &'a FontsMessageHandler,
@@ -3549,11 +3622,28 @@ impl<'a> ParameterWidgetsInfo<'a> {
/// Reference the parameter by a runtime input index, for callers that receive the index dynamically (e.g. widget overrides).
pub fn at_index(node_id: NodeId, index: usize, blank_assist: bool, context: &'a mut NodePropertiesContext) -> ParameterWidgetsInfo<'a> {
let (name, description) = context.network_interface.displayed_input_name_and_description(&node_id, index, context.selection_network_path);
let input_type = context
.network_interface
.input_type_not_invalid(&InputConnector::node_at_index(node_id, index), context.selection_network_path)
.displayed_type();
let input_connector = InputConnector::node_at_index(node_id, index);
let type_source = context.network_interface.input_type_not_invalid(&input_connector, context.selection_network_path);
let input_type = type_source.displayed_type();
let resolved_type = type_source.resolved_type_node_string();
// Start with the contextually-valid set. When that's empty for a protonode (e.g. a fresh node with no downstream
// constraints), fall back to every input type the protonode is registered with so the user can still pick.
let mut valid_types = context.network_interface.complete_valid_input_types(&input_connector, context.selection_network_path);
let implementation = context.network_interface.implementation(&node_id, context.selection_network_path);
let is_subnetwork = matches!(implementation, Some(DocumentNodeImplementation::Network(_)));
if valid_types.is_empty()
&& let Some(DocumentNodeImplementation::ProtoNode(protonode_id)) = implementation
&& let Some(implementations) = interpreted_executor::node_registry::NODE_REGISTRY.get(protonode_id)
{
valid_types = implementations.keys().filter_map(|node_io| node_io.inputs.get(index).cloned()).collect();
}
// Dedupe by the displayed type name so repeated implementations sharing the same input type collapse to one entry.
let mut seen_type_names = std::collections::HashSet::new();
valid_types.retain(|ty| seen_type_names.insert(ty.nested_type().to_string()));
let document_node = context.network_interface.document_node(&node_id, context.selection_network_path);
let is_wired = document_node.and_then(|node| node.inputs.get(index)).is_some_and(|input| matches!(input, NodeInput::Node { .. }));
ParameterWidgetsInfo {
document_id: context.document_id,
@@ -3567,6 +3657,10 @@ impl<'a> ParameterWidgetsInfo<'a> {
name,
description,
input_type,
resolved_type,
valid_types,
is_subnetwork,
is_wired,
blank_assist,
exposable: true,
}
@@ -3767,33 +3861,48 @@ mod tests {
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
}
fn description(expression: &str) -> Option<String> {
math_expression_error(expression, false).map(|error| math_expression_error_description(&error))
}
fn underlined(expression: &str) -> Vec<(u32, u32)> {
let error = math_expression_error(expression, false);
math_expression_error_ranges(expression, error.as_ref()).into_iter().map(|range| (range.start, range.end)).collect()
}
#[test]
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
assert_eq!(math_expression_error(expression, accepts_reducers), None, "`{expression}`");
assert!(math_expression_error(expression, accepts_reducers).is_none(), "`{expression}`");
}
assert!(math_expression_error("2 +", false).is_some());
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
assert_eq!(math_expression_error("sin(I)", true).as_deref(), Some("A matrix stands where a value is needed"));
assert_eq!(description("sin(I)").as_deref(), Some("A matrix stands where a value is needed"));
}
#[test]
fn math_expression_errors_quote_the_expression_safely() {
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting, and the expression
// repeats in a block below with labeled carets under the error's span
assert_eq!(math_expression_error("`abc", false).as_deref(), Some("`` `abc `` is not recognized\n```\n`abc\n^^^^\nerror here\n```"));
assert_eq!(
math_expression_error("7 % 3", false).as_deref(),
Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`\n```\n7 % 3\n ^\n error here\n```")
);
assert!(math_expression_error("(1", false).unwrap().ends_with("\n(1\n ^\n error here\n```"));
assert!(math_expression_error("πx @ 2", false).unwrap().ends_with("\nπx @ 2\n ^\n error here\n```"));
assert!(!math_expression_error("sin(I)", false).unwrap().contains('^'), "a sort error has no place to point at");
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
assert_eq!(description("7 % 3").as_deref(), Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`"));
// A quoted token like `*` is a code span, so it can't pair with another into italics
let error = math_expression_error("2 * * 3", false).unwrap();
let prose = error.lines().next().unwrap();
assert!(prose.starts_with("Found `*`, expected ") && !prose.split('`').step_by(2).any(|text| text.contains('*')), "{error}");
let error = description("2 * * 3").unwrap();
assert!(error.starts_with("Found `*`, expected ") && !error.split('`').step_by(2).any(|text| text.contains('*')), "{error}");
}
#[test]
fn math_expression_errors_underline_the_place_they_point_at() {
assert_eq!(underlined("`abc"), [(0, 4)]);
assert_eq!(underlined("7 % 3"), [(2, 3)]);
assert_eq!(underlined("πx @ 2"), [(3, 4)], "offsets count UTF-16 code units");
assert_eq!(underlined("𝑥 @ 2"), [(3, 4)], "a character beyond the Basic Multilingual Plane is two units");
assert!(underlined("sin(I)").is_empty(), "a sort error has no place to point at unless it blames a name");
assert_eq!(underlined("i - r where r = -63..64"), [(12, 13)]);
// Where something is missing at the end, the character before it is underlined, past any whitespace
assert_eq!(underlined("(1"), [(1, 2)]);
assert_eq!(underlined("2 + "), [(2, 3)]);
}
}
@@ -546,8 +546,6 @@ async fn image_node_with_no_file_still_evaluates() {
value: TaggedValue::TypeDefault(item!(Resource)).into(),
})
.await;
editor.eval_graph().await.expect("an Image node with no file chosen should still evaluate");
}
/// Undoing an image paste reverts the interaction's `AddResource` in the `Gdd` cursor while the runtime keeps
@@ -666,11 +666,18 @@ pub struct PTZ {
/// Angle in radians.
tilt: f64,
/// Scale factor.
#[serde(deserialize_with = "deserialize_clamped_zoom")]
zoom: f64,
/// Flipped status.
pub flip: bool,
}
/// A zoom outside the allowed range, like a non-finite one loaded as 0, would leave the view unusable.
fn deserialize_clamped_zoom<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
let zoom = <f64 as serde::Deserialize>::deserialize(deserializer)?;
Ok(zoom.clamp(crate::consts::VIEWPORT_ZOOM_SCALE_MIN, crate::consts::VIEWPORT_ZOOM_SCALE_MAX))
}
impl Default for PTZ {
fn default() -> Self {
Self {
@@ -54,6 +54,7 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, No
use graphene_std::Appearance;
use graphene_std::ContextDependencies;
use graphene_std::math::quad::Quad;
use graphene_std::registry::MULTI_OUTPUT_NODES;
use graphene_std::transform::Footprint;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint};
use graphene_std::vector::{Vector, VectorModificationType};
@@ -4,7 +4,7 @@ use super::{InputMetadata, InputPersistentMetadata};
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, Value};
use document_graph_storage::{AttributeDelta, AttributeValue, Attributes, Implementation, NodeMetadataSource, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp, Value};
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;
@@ -381,15 +381,37 @@ fn construct_structural_additions(
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
// wrote to its name, lock or pin.
match batch.node(id).is_some() {
true => {
match batch.node(id) {
Some(held) => {
// The swap did not write the slots' `ui::*` attributes, so they carry over to the slots that survive it with
// their stamps, tombstones and the held floor, losing to a concurrent write. The other attributes the new implementation
// lacks go by tombstone instead.
let inputs = node
.inputs()
.iter()
.enumerate()
.map(|(index, slot)| {
let mut slot = slot.clone();
if let Some(previous) = held.inputs().get(index) {
for (key, value) in previous.attributes.iter() {
if key.starts_with("ui::") {
slot.attributes.insert(key.clone(), value.clone());
} else if !value.deleted && !slot.attributes.contains_key(key) {
slot.attributes.insert(key.clone(), AttributeValue::deleted(TimeStamp::ORIGIN));
}
}
slot.attributes.set_floor(previous.attributes.floor());
}
slot
})
.collect();
ops.push(RegistryDelta::SetNodeImplementation {
id,
implementation: node.implementation().clone(),
});
ops.push(RegistryDelta::SetNodeInputs { id, inputs: node.inputs().to_vec() });
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
}
false => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
}
batch.record_addition(id, node);
}
@@ -497,6 +519,7 @@ fn construct_metadata_snapshot(
let current = batch
.network(network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.filter(|value| !value.deleted)
.map(|value| value.value.clone());
if current != target {
ops.push(RegistryDelta::ChangeNetworkAttribute {
@@ -533,19 +556,19 @@ fn construct_metadata_snapshot(
Ok(())
}
/// Every `ui::` attribute of `encoded`, plus a clear for each `ui::` key of `current` that `encoded`
/// Every `ui::` attribute of `encoded`, plus a clear for each live `ui::` key of `current` that `encoded`
/// does not carry. Values are compared only to decide what to clear, never to skip a write.
///
/// 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<AttributeDelta> {
pub(super) fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Vec<AttributeDelta> {
let owned = |key: &str| key.starts_with("ui::");
let mut deltas = Vec::new();
if let Some(current) = current {
for key in current.keys() {
for (key, _) in current.live() {
if owned(key) && !encoded.contains_key(key) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
@@ -1,6 +1,6 @@
use super::DocumentNodePersistentMetadata;
use super::InputConnector;
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch};
use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange, construct_batch, ui_attribute_writes};
use super::storage_metadata::StorageMetadataView;
use crate::test_utils::test_prelude::*;
use document_graph_storage::delta::compute_deltas;
@@ -611,4 +611,39 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
!deltas.iter().any(|delta| matches!(delta, EditorDelta::NodeMetadataSnapshot { node_id, .. } if *node_id == node)),
"the node's own metadata should not be restated by a swap that did not write it"
);
// The slots that survive the swap keep the names and descriptions the registry holds for them.
let Some((id, inputs)) = ops.iter().find_map(|op| match op {
RegistryDelta::SetNodeInputs { id, inputs } => Some((id, inputs)),
_ => None,
}) else {
panic!("the swap should restate the slots")
};
let held: Vec<_> = working.node_instances[id]
.inputs()
.iter()
.take(inputs.len())
.flat_map(|slot| slot.attributes.live().filter(|(key, _)| key.starts_with("ui::")))
.collect();
assert!(!held.is_empty(), "the surviving slots should hold ui attributes for this to check anything");
for (index, slot) in inputs.iter().enumerate() {
for (key, value) in working.node_instances[id].inputs()[index].attributes.live().filter(|(key, _)| key.starts_with("ui::")) {
assert_eq!(slot.attributes.get(key), Some(value), "slot {index} lost {key}");
}
}
}
/// A `ui::` key the registry already holds as deleted is not cleared again on every snapshot.
#[test]
fn a_deleted_ui_key_is_not_cleared_again() {
use document_graph_storage::{AttributeValue, Attributes, TimeStamp, Value};
let at = TimeStamp { counter: 3, peer: PeerId(1) };
let current: Attributes = [
("ui::name".to_string(), AttributeValue::deleted(at)),
("ui::locked".to_string(), AttributeValue::new(Value::Bool(true), at)),
]
.into_iter()
.collect();
let writes = ui_attribute_writes(Some(&current), &Attributes::new());
assert_eq!(writes.iter().map(|write| write.key.as_str()).collect::<Vec<_>>(), ["ui::locked"]);
}
@@ -32,10 +32,7 @@ impl NodeNetworkInterface {
}
}
let number_of_outputs = match &document_node.implementation {
DocumentNodeImplementation::Network(network) => network.exports.len(),
_ => 1,
};
let number_of_outputs = self.number_of_outputs(node_id, network_path);
// If the node has a hidden primary output, do not display the first output
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..number_of_outputs {
@@ -985,6 +985,16 @@ impl NodeNetworkInterface {
self.invalidate_node_appearance(node_id, network_path);
}
/// Replaces the full list of output port names for a node. Used by document migrations that turn a single-output node
/// into a multi-output one, since the port labels are otherwise unnamed and fall back to the type name.
pub fn set_output_names(&mut self, node_id: &NodeId, output_names: Vec<String>, network_path: &[NodeId]) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in set_output_names");
return;
};
node.set_output_names(output_names);
}
pub fn set_import_export_name(&mut self, name: String, index: ImportOrExport, network_path: &[NodeId]) {
let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else {
log::error!("Could not get encapsulating network in set_import_export_name");
@@ -81,7 +81,7 @@ impl TypeSource {
}
}
/// Used when searching for nodes in the add Node popup.
/// Used when searching for nodes in the add node menu.
pub fn add_node_string(self) -> Option<String> {
self.compiled_nested_type().map(|ty| format!("type:{ty}"))
}
@@ -377,6 +377,20 @@ impl NodeNetworkInterface {
}
}
/// Whether a multi-output node is framed over a list, which happens when a list reaches any input its single-item variant takes as an `Item`.
fn multi_output_node_is_mapped(&self, node_id: &NodeId, identifier: &ProtoNodeIdentifier, mapped_type: &Type, network_path: &[NodeId]) -> bool {
let Some(implementations) = NODE_REGISTRY.get(identifier) else { return false };
let Some(single_item_variant) = implementations.keys().find(|node_io| node_io.return_value.nested_type() != mapped_type) else {
return false;
};
single_item_variant
.inputs
.iter()
.enumerate()
.any(|(input_index, declared_type)| matches!(declared_type.nested_type(), Type::Item(_)) && self.input_type(&InputConnector::node_at_index(*node_id, input_index), network_path).is_list())
}
pub fn output_type(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> TypeSource {
match output_connector {
OutputConnector::Node { node_id, output_index } => {
@@ -395,10 +409,26 @@ impl NodeNetworkInterface {
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER => {
self.input_type(&InputConnector::primary_input(*node_id), network_path)
}
DocumentNodeImplementation::ProtoNode(_) => match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
None => TypeSource::Unknown,
},
DocumentNodeImplementation::ProtoNode(identifier) => {
// A multi-output proto node's field output types are recorded in the registry, as lists in its mapped variant.
// The hidden primary output has no field, so it falls through to the compiled types below.
if let Some(metadata) = graphene_std::registry::MULTI_OUTPUT_NODES.get(identifier)
&& let Some(field_index) = metadata.field_index_for_output(*output_index)
{
return match metadata.fields.get(field_index) {
Some(field) => {
let is_mapped = self.multi_output_node_is_mapped(node_id, identifier, &metadata.mapped_type, network_path);
TypeSource::Compiled(if is_mapped { field.mapped_ty.clone() } else { field.ty.clone() })
}
None => TypeSource::Error("Output index out of range for proto node"),
};
}
match self.resolved_types.types.get(&[network_path, &[*node_id]].concat()) {
Some(resolved_type) => TypeSource::Compiled(resolved_type.output.clone()),
None => TypeSource::Unknown,
}
}
DocumentNodeImplementation::Extract => TypeSource::Compiled(concrete!(())),
}
}
@@ -244,6 +244,8 @@ impl<'a, 'p> NetworkView<'a, 'p> {
pub fn number_of_outputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
Ok(match self.implementation(node_id)? {
DocumentNodeImplementation::Network(nested_network) => nested_network.exports.len(),
// A multi-output proto node has an output for each field of the struct it returns
DocumentNodeImplementation::ProtoNode(identifier) => MULTI_OUTPUT_NODES.get(identifier).map_or(1, |metadata| metadata.number_of_outputs()),
_ => 1,
})
}
@@ -264,6 +266,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
pub fn hidden_primary_output(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(match self.implementation(node_id)? {
DocumentNodeImplementation::Network(network) => network.exports.first().is_none_or(|input| !input.is_exposed()),
DocumentNodeImplementation::ProtoNode(identifier) => MULTI_OUTPUT_NODES.get(identifier).is_some_and(|metadata| metadata.hidden_primary_output()),
_ => false,
})
}
@@ -14,6 +14,8 @@ use graph_craft::{Type, concrete, item, list};
use graphene_std::Color;
use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::extract_xy::XY;
use graphene_std::raster::RedGreenBlueAlpha;
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
@@ -53,6 +55,13 @@ fn into_group_aliases() -> impl Iterator<Item = &'static &'static str> {
.flat_map(|replacement| replacement.aliases)
}
/// Clears a migrated node's stored display name if it was only the replaced node's default name, so it shows its new node's name instead.
fn reset_default_display_name(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], old_default_name: &str) {
if document.network_interface.display_name(node_id, network_path) == old_default_name {
document.network_interface.set_display_name(node_id, String::new(), network_path);
}
}
const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
// ================================
// blending
@@ -82,10 +91,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::animation::animation_time::IDENTIFIER,
aliases: &["graphene_core::animation::AnimationTimeNode"],
},
NodeReplacement {
node: graphene_std::extract_xy::extract_xy::IDENTIFIER,
aliases: &["graphene_core::ops::ExtractXyNode"],
},
NodeReplacement {
node: graphene_std::ops::passthrough::IDENTIFIER,
aliases: &[
@@ -428,8 +433,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"math_nodes::AsU64Node",
],
},
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Combine Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Combine Vec2' node.
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
NodeReplacement {
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
aliases: &[
@@ -440,6 +445,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_math_nodes::CoordinateValueNode",
],
},
NodeReplacement {
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
aliases: &["math_nodes::CombineVec2Node"],
},
// ================================
// path bool
// ================================
@@ -502,8 +511,12 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::combine_channels::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::CombineChannelsNode", "graphene_std::raster::CombineChannelsNode"],
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
aliases: &[
"raster_nodes::std_nodes::CombineChannelsNode",
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
"graphene_std::raster::CombineChannelsNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
@@ -525,14 +538,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::extract_channel::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ExtractChannelNode",
"graphene_core::raster::adjustments::ExtractChannelNode",
"graphene_core::raster::ExtractChannelNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
@@ -935,10 +940,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::vector::scatter_points::IDENTIFIER,
aliases: &["graphene_core::vector::PoissonDiskPointsNode", "core_types::vector::PoissonDiskPointsNode"],
},
NodeReplacement {
node: graphene_std::vector::position_on_path::IDENTIFIER,
aliases: &["graphene_core::vector::PositionOnPathNode"],
},
NodeReplacement {
node: graphene_std::vector::round_corners::IDENTIFIER,
aliases: &["graphene_core::vector::RoundCornersNode"],
@@ -971,10 +972,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::vector::stroke::IDENTIFIER,
aliases: &["graphene_core::vector::StrokeNode"],
},
NodeReplacement {
node: graphene_std::vector::tangent_on_path::IDENTIFIER,
aliases: &["graphene_core::vector::TangentOnPathNode"],
},
NodeReplacement {
node: graphene_std::vector::as_vector::IDENTIFIER,
aliases: &[
@@ -1385,6 +1382,199 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
let split_wrapper_replacements = [
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
];
for (old_reference, new_identifier) in split_wrapper_replacements {
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network(old_reference.into()))).then_some((*node_id, path)))
.collect();
for (node_id, network_path) in &split_nodes {
let old_output_count = document.network_interface.number_of_outputs(node_id, network_path);
let output_shift = usize::from(!document.network_interface.hidden_primary_output(node_id, network_path));
// Pre-load `outward_wires` so the chain-break check inside `set_input` resolves the original upstream→node wire from cache
// rather than triggering a fresh rebuild from the (already-mutated) post-`replace_inputs` state, which would orphan wires.
let downstream_by_output: Vec<Vec<InputConnector>> = match document.network_interface.outward_wires(network_path) {
Some(outward_wires) if output_shift > 0 => (0..old_output_count)
.map(|output_index| outward_wires.get(&OutputConnector::node(*node_id, output_index)).cloned().unwrap_or_default())
.collect(),
_ => Vec::new(),
};
let new_reference = DefinitionIdentifier::ProtoNode(new_identifier.clone());
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
let mut node_template = definition.default_node_template();
let output_names = definition.node_template.output_names.clone();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
document.network_interface.set_output_names(node_id, output_names, network_path);
reset_default_display_name(document, node_id, network_path, old_reference);
if let Some(input) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
}
for (old_output_index, downstream) in downstream_by_output.iter().enumerate() {
for input_connector in downstream {
document
.network_interface
.set_input(input_connector, NodeInput::node(*node_id, old_output_index + output_shift), network_path);
}
}
}
}
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
const EXTRACT_CHANNEL: [&str; 4] = [
"raster_nodes::adjustments::ExtractChannelNode",
"graphene_raster_nodes::adjustments::ExtractChannelNode",
"graphene_core::raster::adjustments::ExtractChannelNode",
"graphene_core::raster::ExtractChannelNode",
];
let extract_nodes: Vec<(NodeId, Vec<NodeId>, ProtoNodeIdentifier, &str)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
if EXTRACT_XY.contains(&name) {
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
} else if EXTRACT_CHANNEL.contains(&name) {
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
} else {
None
}
})
.collect();
for (node_id, network_path, new_identifier, old_default_name) in &extract_nodes {
// Capture the old output's downstream connections before mutating, so they can be moved to the extracted field's output
let downstream_from_output = document
.network_interface
.outward_wires(network_path)
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(*node_id, 0)))
.cloned()
.unwrap_or_default();
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(new_identifier.clone())) else {
continue;
};
let mut node_template = definition.default_node_template();
let output_names = definition.node_template.output_names.clone();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
document.network_interface.set_output_names(node_id, output_names, network_path);
reset_default_display_name(document, node_id, network_path, old_default_name);
if let Some(input) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
}
// The field outputs follow the hidden primary output, in X, Y or red, green, blue, alpha order
let output_index = match old_inputs.get(1).and_then(|input| input.as_value()) {
Some(TaggedValue::XY(XY::X) | TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Red)) => 1,
Some(TaggedValue::XY(XY::Y) | TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Green)) => 2,
Some(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Blue)) => 3,
Some(TaggedValue::RedGreenBlueAlpha(RedGreenBlueAlpha::Alpha)) => 4,
_ => {
log::warn!("Old \"{old_default_name}\" node {node_id} has no fixed axis or channel to migrate, so its wires use the first field output");
1
}
};
for input_connector in &downstream_from_output {
document.network_interface.set_input(input_connector, NodeInput::node(*node_id, output_index), network_path);
}
}
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
const TANGENT_ON_PATH: &str = "graphene_core::vector::TangentOnPathNode";
let evaluate_path_nodes: Vec<(NodeId, Vec<NodeId>, bool)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
match identifier.as_str() {
POSITION_ON_PATH => Some((*node_id, path, false)),
TANGENT_ON_PATH => Some((*node_id, path, true)),
_ => None,
}
})
.collect();
for (node_id, network_path, is_tangent) in &evaluate_path_nodes {
// Capture the old output's downstream connections before mutating, so a tangent node's wires can be moved onto the inserted angle conversion
let downstream_from_output = document
.network_interface
.outward_wires(network_path)
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(*node_id, 0)))
.cloned()
.unwrap_or_default();
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::evaluate_path::IDENTIFIER);
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
let mut node_template = definition.default_node_template();
let output_names = definition.node_template.output_names.clone();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
// The old single-output nodes have no output names, so set them to match the new multi-output node's "Position", "Tangent", and "Normal" ports
document.network_interface.set_output_names(node_id, output_names, network_path);
reset_default_display_name(document, node_id, network_path, if *is_tangent { "Tangent on Path" } else { "Position on Path" });
// Forward the shared inputs: content, progression, reverse, and parameterized distance
for (index, input) in old_inputs.iter().take(4).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
if *is_tangent && !downstream_from_output.is_empty() {
let Some(inverse_tangent_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::tangent_inverse::IDENTIFIER)) else {
log::error!("Could not resolve the Inverse Tangent node while migrating Tangent on Path node {node_id}");
continue;
};
// Feed the tangent direction into the inserted "Inverse Tangent" node, carrying over the old radians input (true when absent, since radians was once the only option)
let inverse_tangent_id = NodeId::new();
document
.network_interface
.insert_node(inverse_tangent_id, inverse_tangent_definition.default_node_template(), network_path);
let radians = old_inputs.get(4).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::Bool(true), false));
document.network_interface.set_input(&InputConnector::node_at_index(inverse_tangent_id, 1), radians, network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(inverse_tangent_id, 0), NodeInput::node(*node_id, 1), network_path);
if let Some(position) = document.network_interface.position(node_id, network_path) {
document.network_interface.shift_absolute_node_position(&inverse_tangent_id, position + IVec2::new(7, 0), network_path);
}
// Move the tangent node's downstream connections from its old single output to the inserted angle conversion
for input_connector in &downstream_from_output {
document.network_interface.set_input(input_connector, NodeInput::node(inverse_tangent_id, 0), network_path);
}
}
}
// Record which old text nodes are chain-positioned now, before `migrate_node`'s staged input-count migrations run, since those set
// the upstream chain to absolute; the split below re-chains exactly the nodes that were originally part of a layer chain.
let text_nodes_in_chain: std::collections::HashSet<NodeId> = document
@@ -1408,6 +1598,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
for (node_id, node, network_path) in &nodes {
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
}
create_layer_stacks(document);
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> converter pair, which reuses the same proto
// identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current 12-input
@@ -2243,22 +2434,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Bool(true), false), network_path);
}
// Upgrade the 'Tangent on Path' node to include a boolean input for whether the output should be in radians, which was previously the only option but is now not the default
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::tangent_on_path::IDENTIFIER) && inputs_count == 4 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), old_inputs[2].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[3].clone(), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 4), NodeInput::value(TaggedValue::Bool(true), false), network_path);
}
// Upgrade the Modulo node to include a boolean input for whether the output should be always positive, which was previously not an option
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::modulo::IDENTIFIER) && inputs_count == 2 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -2274,10 +2449,10 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
// into the 'Combine Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
let combine_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::combine_vec_2::IDENTIFIER);
let mut node_template = resolve_document_node_type(&combine_vec2_reference)?.default_node_template();
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
@@ -3102,34 +3277,35 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
// ==================================
// PUT ALL MIGRATIONS ABOVE THIS LINE
// ==================================
Some(())
}
// Ensure layers are positioned as stacks if they are upstream siblings of another layer
/// Ensure layers are positioned as stacks if they are upstream siblings of another layer
fn create_layer_stacks(document: &mut DocumentMessageHandler) {
document.network_interface.load_structure();
let all_layers = LayerNodeIdentifier::ROOT_PARENT.descendants(document.network_interface.document_metadata()).collect::<Vec<_>>();
for layer in all_layers {
let (downstream_node, input_index) = document
let Some((downstream_node, input_index)) = document
.network_interface
.outward_wires(&[])
.and_then(|outward_wires| outward_wires.get(&OutputConnector::node(layer.to_node(), 0)))
.and_then(|outward_wires| outward_wires.first())
.and_then(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())))?;
.and_then(|input_connector| input_connector.node_id().map(|node_id| (node_id, input_connector.input_index())))
else {
continue;
};
// If the downstream node is a layer and the input is the first input and the current layer is not in a stack
if input_index == 0 && document.network_interface.is_layer(&downstream_node, &[]) && !document.network_interface.is_stack(&layer.to_node(), &[]) {
// Ensure the layer is horizontally aligned with the downstream layer to prevent changing the layout of old files
let (Some(layer_position), Some(downstream_position)) = (document.network_interface.position(&layer.to_node(), &[]), document.network_interface.position(&downstream_node, &[])) else {
log::error!("Could not get position for layer {:?} or downstream node {} when opening file", layer.to_node(), downstream_node);
return None;
continue;
};
if layer_position.x == downstream_position.x {
document.network_interface.set_stack_position_calculated_offset(&layer.to_node(), &downstream_node, &[]);
}
}
}
Some(())
}
/// Migrates document nodes whose catalog definitions have been removed.
@@ -3273,6 +3449,37 @@ mod tests {
}
}
#[test]
fn null_floats_load_as_zero() {
use crate::messages::portfolio::document::utility_types::misc::PTZ;
use graph_craft::document::value::deserialize_replacing_null_floats_with_zero;
#[derive(serde::Deserialize)]
struct Example {
position: DVec2,
scale: f64,
opacity: Option<f64>,
}
let content = "{\n\t\"position\": [1.5, null],\n\t\"scale\": null,\n\t\"opacity\": null\n}";
let example = deserialize_replacing_null_floats_with_zero::<Example>(content).expect("a `null` in place of a float should load");
assert_eq!(example.position, DVec2::new(1.5, 0.));
assert_eq!(example.scale, 0.);
assert_eq!(example.opacity, None);
// A `null` standing in for something other than a float is still an error
let content = r#"{"position": null, "scale": 1, "opacity": 1}"#;
assert!(deserialize_replacing_null_floats_with_zero::<Example>(content).is_err());
// Node input values are parsed from an intermediate JSON value, which carries no error positions
let input = serde_json::from_str::<NodeInput>(r#"{"Value":{"tagged_value":{"DVec2":[null,2.5]},"exposed":false}}"#).expect("a `null` in a node input value should load");
assert_eq!(input.as_value(), Some(&TaggedValue::DVec2(DVec2::new(0., 2.5))));
// A zoom of 0 would make the view's transform singular
let ptz = deserialize_replacing_null_floats_with_zero::<PTZ>(r#"{"pan":[0.0,0.0],"tilt":0.0,"zoom":null,"flip":false}"#).expect("a `null` zoom should load");
assert_eq!(ptz.zoom(), crate::consts::VIEWPORT_ZOOM_SCALE_MIN);
}
// The removed-definition blocks above abort silently via `?` if their swap target ever leaves the catalog
#[test]
fn removed_definition_swap_targets_resolve() {
@@ -63,7 +63,7 @@ mod test_ellipse {
}
async fn get_ellipse(editor: &mut EditorTestUtils) -> Vec<ResolvedEllipse> {
let instrumented = match editor.eval_graph().await {
let instrumented = match editor.eval_graph_until_finished().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
@@ -575,7 +575,7 @@ mod test_artboard {
use graphene_std::list::List;
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
let instrumented = match editor.eval_graph().await {
let instrumented = match editor.eval_graph_until_finished().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
@@ -269,7 +269,7 @@ mod test_fill {
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
let instrumented = match editor.eval_graph().await {
let instrumented = match editor.eval_graph_until_finished().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
@@ -3135,7 +3135,6 @@ mod test_gradient {
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
assert!(get_upstream_gradient_value_node_id(layer, &editor.active_document().network_interface).is_some());
editor.eval_graph().await.expect("graph should evaluate");
let bounds = editor.active_document().metadata().bounding_box_with_transform(layer, DAffine2::IDENTITY);
assert_eq!(bounds, Some([DVec2::ZERO, DVec2::X]), "a linear expanse's local bounds should be its canonical gradient line");
@@ -3149,7 +3148,6 @@ mod test_gradient {
options: super::GradientOptionsUpdate::Form(GradientForm::Radial),
})
.await;
editor.eval_graph().await.expect("graph should evaluate");
let bounds = editor.active_document().metadata().bounding_box_with_transform(layer, DAffine2::IDENTITY);
assert_eq!(bounds, Some([DVec2::splat(-1.), DVec2::splat(1.)]), "a radial expanse's local bounds should be its unit circle");
@@ -3,7 +3,7 @@ use super::tool_prelude::*;
use crate::consts::{
COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, COLOR_OVERLAY_GRAY, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_GREEN_25, COLOR_OVERLAY_RED, COLOR_OVERLAY_RED_25, DEFAULT_STROKE_WIDTH,
DOUBLE_CLICK_MILLISECONDS, DRAG_DIRECTION_MODE_DETERMINATION_THRESHOLD, DRAG_THRESHOLD, DRILL_THROUGH_THRESHOLD, HANDLE_ROTATE_SNAP_ANGLE, SEGMENT_INSERTION_DISTANCE, SEGMENT_OVERLAY_SIZE,
SELECTION_THRESHOLD, SELECTION_TOLERANCE,
SELECTION_THRESHOLD,
};
use crate::messages::clipboard::utility_types::{ClipboardItem, ClipboardVectorEntry};
use crate::messages::input_mapper::utility_types::macros::action_shortcut_manual;
@@ -640,16 +640,10 @@ impl PathToolData {
self.selection_mode.unwrap_or(SelectionMode::Touched)
}
/// The viewport-space rectangle spanned by the drag so far, which has zero size until the pointer moves.
pub fn selection_box(&self, metadata: &DocumentMetadata) -> [DVec2; 2] {
// Convert previous mouse position to viewport space first
let document_to_viewport = metadata.document_to_viewport;
let previous_mouse = document_to_viewport.transform_point2(self.previous_mouse_position);
if previous_mouse == self.drag_start_pos {
let tolerance = DVec2::splat(SELECTION_TOLERANCE);
[self.drag_start_pos - tolerance, self.drag_start_pos + tolerance]
} else {
[self.drag_start_pos, previous_mouse]
}
let previous_mouse = metadata.document_to_viewport.transform_point2(self.previous_mouse_position);
[self.drag_start_pos, previous_mouse]
}
fn update_selection_status(&mut self, shape_editor: &mut ShapeState, document: &DocumentMessageHandler) {
@@ -69,6 +69,10 @@ pub enum PenToolMessage {
append_to_selected: Key,
},
DragStop,
/// Sent by a press to place its anchor, after the graph has re-evaluated if the press merged two layers.
PlacePressedAnchor {
merged: bool,
},
PointerMove {
snap_angle: Key,
break_handle: Key,
@@ -403,7 +407,10 @@ struct PenToolData {
auto_panning: AutoPanning,
modifiers: ModifierState,
buffering_merged_vector: bool,
/// The layer's transform to document space as it was when a press joined the layer to another, kept while that press waits for the merged path to place its anchor in.
merging_from: Option<DAffine2>,
/// The release, confirmation, and latest pointer move that arrive during that wait.
held_input: Vec<PenToolMessage>,
previous_handle_start_pos: DVec2,
previous_handle_end_pos: Option<DVec2>,
@@ -462,6 +469,8 @@ impl PenToolData {
self.point_index = 0;
self.suppress_lock_angle = false;
self.suppress_snap_angle = false;
self.merging_from = None;
self.held_input.clear();
self.snap_manager.cleanup(responses);
}
@@ -610,16 +619,18 @@ impl PenToolData {
self.point_index == 0 && self.latest_point().is_some_and(|point| point.pos == self.next_point)
}
// When the vector transform changes, the positions of the points must be recalculated.
fn recalculate_latest_points_position(&mut self, document: &DocumentMessageHandler) {
// When the layer's space changes, its points are found again and their handles follow
fn recalculate_latest_points_position(&mut self, document: &DocumentMessageHandler, layer_to_document: DAffine2) {
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
if let (Some(layer), None) = (selected_layers.next(), selected_layers.next()) {
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return };
let into_merged = self.merging_from.map_or(DAffine2::IDENTITY, |previous| layer_to_document.inverse() * previous);
for point in &mut self.latest_points {
let Some(pos) = vector.point_domain.position_from_id(point.id) else { continue };
point.handle_start = pos + into_merged.transform_vector2(point.handle_start - point.pos);
point.pos = pos;
point.handle_start = point.pos;
}
}
}
@@ -1564,6 +1575,27 @@ impl Fsm for PenToolFsmState {
}
let ToolMessage::Pen(event) = event else { return self };
// A press waiting for its layers to merge keeps its release, confirmation, and latest move for once its anchor is placed
if tool_data.merging_from.is_some() {
match event {
PenToolMessage::DragStop | PenToolMessage::Confirm => {
tool_data.held_input.push(event);
return self;
}
PenToolMessage::PointerMove { .. } => {
// A move reads where the pointer is when it's handled, so only the latest one counts
if matches!(tool_data.held_input.last(), Some(PenToolMessage::PointerMove { .. })) {
tool_data.held_input.pop();
}
tool_data.held_input.push(event);
return self;
}
PenToolMessage::DragStart { .. } | PenToolMessage::PointerOutsideViewport { .. } | PenToolMessage::GRS { .. } => return self,
_ => {}
}
}
match (self, event) {
(PenToolFsmState::PlacingAnchor | PenToolFsmState::GRSHandle, PenToolMessage::GRS { grab, rotate, scale }) => {
let Some(layer) = layer else { return PenToolFsmState::PlacingAnchor };
@@ -1913,52 +1945,72 @@ impl Fsm for PenToolFsmState {
self
}
(state, PenToolMessage::RecalculateLatestPointsPosition) => {
tool_data.recalculate_latest_points_position(document);
tool_data.recalculate_latest_points_position(document, transform);
state
}
(PenToolFsmState::PlacingAnchor, PenToolMessage::DragStart { append_to_selected }) => {
(PenToolFsmState::PlacingAnchor, PenToolMessage::DragStart { .. }) => {
let point = SnapCandidatePoint::handle(document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position));
let snapped = tool_data.snap_manager.free_snap(&SnapData::new(document, input, viewport), &point, SnapTypeConfiguration::default());
let viewport_vec = document.metadata().document_to_viewport.transform_point2(snapped.snapped_point_document);
// Early return if the buffer was started and this message is being run again after the buffer (so that place_anchor updates the state with the newly merged vector)
if tool_data.buffering_merged_vector {
if let Some(layer) = layer {
tool_data.buffering_merged_vector = false;
tool_data.handle_mode = HandleMode::ColinearLocked;
tool_data.bend_from_previous_point(SnapData::new(document, input, viewport), transform, layer, shape_editor, responses);
tool_data.place_anchor(SnapData::new(document, input, viewport), transform, input.mouse.position, responses);
// The anchor goes where its preview is shown for where the pointer is pressed
tool_data.place_anchor(SnapData::new(document, input, viewport), transform, input.mouse.position, responses);
// Each segment placement is its own history step, spanning from this click through the release that finalizes it
responses.add(DocumentMessage::StartTransaction);
// Merge two layers if the point is connected to the end point of another path
// This might not be the correct solution to artboards being included as the other layer,
// which occurs due to the `compute_modified_vector` call in `should_extend` using the click targets for a layer instead of vector.
let layers = LayerNodeIdentifier::ROOT_PARENT
.descendants(document.metadata())
.filter(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]));
if let Some((other_layer, _, _)) = should_extend(document, viewport_vec, crate::consts::SNAP_POINT_TOLERANCE, layers) {
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
if let Some(current_layer) = selected_layers
.next()
.filter(|current_layer| selected_layers.next().is_none() && *current_layer != other_layer)
.or(tool_data.current_layer.filter(|layer| *layer != other_layer))
{
merge_layers(document, current_layer, other_layer, responses);
tool_data.merging_from = Some(transform);
}
tool_data.buffering_merged_vector = false;
PenToolFsmState::DraggingHandle(tool_data.handle_mode)
} else {
// Each segment placement is its own history step, spanning from this click through the release that finalizes it
responses.add(DocumentMessage::StartTransaction);
// Merge two layers if the point is connected to the end point of another path
// This might not be the correct solution to artboards being included as the other layer,
// which occurs due to the `compute_modified_vector` call in `should_extend` using the click targets for a layer instead of vector.
let layers = LayerNodeIdentifier::ROOT_PARENT
.descendants(document.metadata())
.filter(|layer| !document.network_interface.is_artboard(&layer.to_node(), &[]));
if let Some((other_layer, _, _)) = should_extend(document, viewport_vec, crate::consts::SNAP_POINT_TOLERANCE, layers) {
let selected_nodes = document.network_interface.selected_nodes();
let mut selected_layers = selected_nodes.selected_layers(document.metadata());
if let Some(current_layer) = selected_layers
.next()
.filter(|current_layer| selected_layers.next().is_none() && *current_layer != other_layer)
.or(tool_data.current_layer.filter(|layer| *layer != other_layer))
{
merge_layers(document, current_layer, other_layer, responses);
}
}
// Even if no buffer was started, the message still has to be run again in order to call bend_from_previous_point
tool_data.buffering_merged_vector = true;
responses.add(PenToolMessage::DragStart { append_to_selected });
PenToolFsmState::PlacingAnchor
}
// Merging changes the space the layer's points are in, so the anchor is placed once the merged path has been evaluated
let merged = tool_data.merging_from.is_some();
let place = PenToolMessage::PlacePressedAnchor { merged }.into();
if merged {
responses.add(DeferMessage::AfterGraphRun { messages: vec![place] });
} else {
responses.add(place);
}
PenToolFsmState::PlacingAnchor
}
(PenToolFsmState::PlacingAnchor, PenToolMessage::PlacePressedAnchor { merged }) => {
// The preview is carried into the merged layer's space, unless the wait for that layer was called off
if merged {
let Some(previous) = tool_data.merging_from.take() else { return self };
tool_data.next_point = (transform.inverse() * previous).transform_point2(tool_data.next_point);
}
if let Some(layer) = layer {
tool_data.handle_mode = HandleMode::ColinearLocked;
tool_data.bend_from_previous_point(SnapData::new(document, input, viewport), transform, layer, shape_editor, responses);
let pressed = (document.metadata().document_to_viewport * transform).transform_point2(tool_data.next_point);
tool_data.place_anchor(SnapData::new(document, input, viewport), transform, pressed, responses);
}
// The input held back during the wait follows the press
for held in tool_data.held_input.drain(..) {
responses.add(held);
}
PenToolFsmState::DraggingHandle(tool_data.handle_mode)
}
(PenToolFsmState::PlacingAnchor, PenToolMessage::RemovePreviousHandle) => {
if let Some(last_point) = tool_data.latest_point_mut() {
@@ -2378,8 +2430,12 @@ impl Fsm for PenToolFsmState {
#[cfg(test)]
mod test_pen_tool {
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::test_utils::test_prelude::*;
use graphene_std::vector::Vector;
use glam::DAffine2;
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::{SegmentId, Vector};
/// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away.
fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, Vector)> {
@@ -2614,4 +2670,218 @@ mod test_pen_tool {
editor.left_mouseup(off_the_line.x, off_the_line.y, ModifierKeys::CONTROL).await;
assert_anchors(&editor, &[A, B, off_the_line]);
}
/// The path's anchors in viewport space, in placement order.
fn anchor_positions(editor: &EditorTestUtils) -> Vec<DVec2> {
let (layer, vector) = drawn_path(editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
vector.point_domain.positions().iter().map(|&position| layer_to_viewport.transform_point2(position)).collect()
}
/// Draws a path from A to B, begins another at D, and brings the pointer to where a click would end it on the first one's last anchor.
async fn bring_a_second_path_to_the_end_of_the_first(editor: &mut EditorTestUtils) -> DVec2 {
click_pen(editor, A).await;
click_pen(editor, B).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
click_pen(editor, D).await;
let join = B + DVec2::new(3., 2.);
editor.move_mouse(join.x, join.y, ModifierKeys::empty(), MouseKeys::empty()).await;
join
}
fn assert_the_two_paths_are_joined(editor: &EditorTestUtils) {
assert_path_shape(editor, 3, 2);
let anchors = anchor_positions(editor);
for expected in [A, B, D] {
assert!(anchors.iter().any(|anchor| anchor.distance(expected) < 1e-6), "no anchor is at {expected} among {anchors:?}");
}
}
#[tokio::test]
async fn ending_a_path_on_the_end_of_another_joins_the_two() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let join = bring_a_second_path_to_the_end_of_the_first(&mut editor).await;
editor.left_mousedown(join.x, join.y, ModifierKeys::empty()).await;
editor.left_mouseup(join.x, join.y, ModifierKeys::empty()).await;
assert_the_two_paths_are_joined(&editor);
}
/// Presses at a position without the graph being evaluated afterward, as when more input arrives before the graph has caught up.
fn press_without_evaluating(editor: &mut EditorTestUtils, position: DVec2) {
let editor_mouse_state = pointer_state(position, MouseKeys::LEFT);
let modifier_keys = ModifierKeys::empty();
editor.editor.handle_message(InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys });
}
fn pointer_state(editor_position: DVec2, mouse_keys: MouseKeys) -> EditorPointerState {
EditorPointerState {
editor_position,
mouse_keys,
..Default::default()
}
}
#[tokio::test]
async fn a_release_that_comes_before_the_paths_have_merged_still_joins_them() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let join = bring_a_second_path_to_the_end_of_the_first(&mut editor).await;
press_without_evaluating(&mut editor, join);
let editor_mouse_state = pointer_state(join, MouseKeys::empty());
let modifier_keys = ModifierKeys::empty();
editor.editor.handle_message(InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys });
editor.eval_graph_until_finished().await.expect("The graph should evaluate");
assert_the_two_paths_are_joined(&editor);
}
#[tokio::test]
async fn a_pointer_that_moves_before_the_paths_have_merged_leaves_the_join_where_it_was_pressed() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let join = bring_a_second_path_to_the_end_of_the_first(&mut editor).await;
press_without_evaluating(&mut editor, join);
let away = join + DVec2::new(40., 60.);
let editor_mouse_state = pointer_state(away, MouseKeys::LEFT);
let modifier_keys = ModifierKeys::empty();
editor.editor.handle_message(InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys });
editor.eval_graph_until_finished().await.expect("The graph should evaluate");
editor.left_mouseup(away.x, away.y, ModifierKeys::empty()).await;
assert_the_two_paths_are_joined(&editor);
}
/// Where every anchor and handle of the drawn path is in the viewport, in an order that lets two drawings be compared.
fn manipulator_positions(editor: &EditorTestUtils) -> Vec<DVec2> {
let (layer, vector) = drawn_path(editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let handles = vector
.segment_domain
.ids()
.iter()
.flat_map(|&segment| [ManipulatorPointId::PrimaryHandle(segment), ManipulatorPointId::EndHandle(segment)])
.filter_map(|handle| handle.get_position(&vector));
let mut positions: Vec<DVec2> = vector
.point_domain
.positions()
.iter()
.copied()
.chain(handles)
.map(|position| layer_to_viewport.transform_point2(position))
.collect();
positions.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
positions
}
#[tokio::test]
async fn a_drag_released_before_the_paths_have_merged_shapes_the_join_as_one_released_after() {
let away = |join: DVec2| join + DVec2::new(40., 60.);
// Pressing on the end of the first path, dragging out a handle, and releasing once the paths have merged
let mut settled = EditorTestUtils::create();
settled.new_document().await;
let join = bring_a_second_path_to_the_end_of_the_first(&mut settled).await;
settled.left_mousedown(join.x, join.y, ModifierKeys::empty()).await;
settled.move_mouse(away(join).x, away(join).y, ModifierKeys::empty(), MouseKeys::LEFT).await;
settled.left_mouseup(away(join).x, away(join).y, ModifierKeys::empty()).await;
// The same drag, all of it arriving before the graph has caught up
let mut hurried = EditorTestUtils::create();
hurried.new_document().await;
let join = bring_a_second_path_to_the_end_of_the_first(&mut hurried).await;
press_without_evaluating(&mut hurried, join);
let modifier_keys = ModifierKeys::empty();
let editor_mouse_state = pointer_state(away(join), MouseKeys::LEFT);
hurried.editor.handle_message(InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys });
let editor_mouse_state = pointer_state(away(join), MouseKeys::empty());
hurried.editor.handle_message(InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys });
hurried.eval_graph_until_finished().await.expect("The graph should evaluate");
assert_the_two_paths_are_joined(&hurried);
let (settled, hurried) = (manipulator_positions(&settled), manipulator_positions(&hurried));
assert!(settled.len() > 3, "the settled drag should have drawn handles, not only the three anchors");
assert_eq!(settled.len(), hurried.len(), "settled {settled:?}, hurried {hurried:?}");
assert!(settled.iter().zip(&hurried).all(|(a, b)| a.distance(*b) < 1e-6), "settled {settled:?}, hurried {hurried:?}");
}
#[tokio::test]
async fn escape_before_the_paths_have_merged_leaves_only_the_first_path() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let join = bring_a_second_path_to_the_end_of_the_first(&mut editor).await;
press_without_evaluating(&mut editor, join);
let (key, modifier_keys, key_repeat) = (Key::Escape, ModifierKeys::empty(), false);
editor.editor.handle_message(InputPreprocessorMessage::KeyDown { key, modifier_keys, key_repeat });
editor.eval_graph_until_finished().await.expect("The graph should evaluate");
editor.left_mouseup(join.x, join.y, ModifierKeys::empty()).await;
assert_anchors(&editor, &[A, B]);
}
#[tokio::test]
async fn a_join_from_a_turned_layer_keeps_the_handle_dragged_out_of_the_previous_anchor() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
click_pen(&mut editor, A).await;
click_pen(&mut editor, B).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
// The second path's layer is turned and stretched once its first anchor is down
click_pen(&mut editor, D).await;
let layer = editor.get_selected_layer().await.expect("The second path should be selected");
let transform = DAffine2::from_scale_angle_translation(DVec2::new(1.5, 0.8), 0.6, DVec2::ZERO);
let (transform_in, skip_rerender) = (TransformIn::Local, false);
let turn = GraphOperationMessage::TransformChange {
layer,
transform,
transform_in,
skip_rerender,
};
editor.handle_message(turn).await;
let document = editor.active_document();
let vector = document.network_interface.compute_modified_vector(layer).expect("The second path should have a vector");
let first = document.metadata().transform_to_viewport(layer).transform_point2(vector.point_domain.positions()[0]);
// Its next anchor has a handle dragged out of it
let (anchor, handle) = (DVec2::new(260., 240.), DVec2::new(300., 270.));
editor.move_mouse(anchor.x, anchor.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(anchor.x, anchor.y, ModifierKeys::empty()).await;
editor.move_mouse(handle.x, handle.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor.left_mouseup(handle.x, handle.y, ModifierKeys::empty()).await;
click_pen(&mut editor, B + DVec2::new(3., 2.)).await;
assert_path_shape(&editor, 4, 3);
let anchors = anchor_positions(&editor);
for expected in [A, B, first, anchor] {
assert!(anchors.iter().any(|anchor| anchor.distance(expected) < 1e-6), "no anchor is at {expected} among {anchors:?}");
}
// The joining segment leaves that anchor toward where its handle was dragged
let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let leaves_the_anchor = |&segment: &SegmentId| {
let start = vector.segment_start_from_id(segment).and_then(|point| vector.point_domain.position_from_id(point));
start.is_some_and(|start| layer_to_viewport.transform_point2(start).distance(anchor) < 1e-6)
};
let joining = vector
.segment_domain
.ids()
.iter()
.copied()
.find(|segment| leaves_the_anchor(segment))
.expect("A segment should leave the anchor");
let leaving = ManipulatorPointId::PrimaryHandle(joining).get_position(&vector).expect("The joining segment should have a handle");
let leaving = layer_to_viewport.transform_point2(leaving);
assert!(leaving.distance(handle) < 1e-6, "the joining segment's handle is at {leaving}");
}
}
@@ -763,11 +763,6 @@ mod test_spline_tool {
// Finish the spline
editor.handle_message(SplineToolMessage::Confirm).await;
// Evaluate the graph to ensure everything is processed
if let Err(e) = editor.eval_graph().await {
panic!("Graph evaluation failed: {e}");
}
// Get the layer and vector data
let document = editor.active_document();
let network_interface = &document.network_interface;
@@ -803,11 +798,6 @@ mod test_spline_tool {
editor.handle_message(SplineToolMessage::Confirm).await;
// Evaluating the graph to ensure everything is processed
if let Err(e) = editor.eval_graph().await {
panic!("Graph evaluation failed: {e}");
}
// Get the layer and vector data
let document = editor.active_document();
let network_interface = &document.network_interface;
@@ -841,11 +831,6 @@ mod test_spline_tool {
editor.handle_message(SplineToolMessage::Confirm).await;
// Evaluating the graph to ensure everything is processed
if let Err(e) = editor.eval_graph().await {
panic!("Graph evaluation failed: {e}");
}
// Get the layer and vector data
let document = editor.active_document();
let network_interface = &document.network_interface;
@@ -881,9 +866,6 @@ mod test_spline_tool {
editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(150., 100.), ModifierKeys::empty()).await;
editor.handle_message(SplineToolMessage::Confirm).await;
if let Err(e) = editor.eval_graph().await {
panic!("Graph evaluation failed: {e}");
}
// Get the layer and vector data
let document = editor.active_document();
@@ -566,18 +566,18 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
let to_mouse_final_old = self.state.project_onto_constrained(to_mouse_final_old, axis_constraint);
let to_mouse_start = self.state.project_onto_constrained(to_mouse_start, axis_constraint);
let change = {
// Starting on the pivot leaves no distance to measure the scale against
let start_transform_dist = to_mouse_start.length_squared();
if start_transform_dist > f64::EPSILON {
let previous_frame_dist = to_mouse_final.dot(to_mouse_start);
let current_frame_dist = to_mouse_final_old.dot(to_mouse_start);
let start_transform_dist = to_mouse_start.length_squared();
let change = (current_frame_dist - previous_frame_dist) / start_transform_dist;
let change = if self.slow { change / SLOWING_DIVISOR } else { change };
(current_frame_dist - previous_frame_dist) / start_transform_dist
};
let change = if self.slow { change / SLOWING_DIVISOR } else { change };
scale = scale.increment_amount(change);
self.transform_operation = TransformOperation::Scaling(scale);
self.transform_operation.apply_transform_operation(&mut selected, &self.state, document);
scale = scale.increment_amount(change);
self.transform_operation = TransformOperation::Scaling(scale);
self.transform_operation.apply_transform_operation(&mut selected, &self.state, document);
}
}
};
}
@@ -1187,6 +1187,30 @@ mod test_transform_layer {
assert!(new_scale_y > 0., "After rescaling, scale factor Y should be nonzero");
}
#[tokio::test]
async fn test_scale_starting_on_pivot() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let document = editor.active_document();
let layer = document.metadata().all_layers().next().unwrap();
// The pivot is at the center of the rectangle
editor.move_mouse(50., 50., ModifierKeys::empty(), MouseKeys::NONE).await;
editor.handle_message(TransformLayerMessage::BeginScale).await;
editor.move_mouse(150., 150., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
increments_key: Key::Control,
})
.await;
editor.handle_message(TransformLayerMessage::ApplyTransformOperation { final_transform: true }).await;
let final_transform = get_layer_transform(&mut editor, layer).await.unwrap();
assert!(final_transform.is_finite(), "Scaling from the pivot should leave the transform finite, got: {final_transform:?}");
}
#[tokio::test]
async fn test_transform_with_different_selections() {
let mut editor = EditorTestUtils::create();
+6
View File
@@ -117,6 +117,12 @@ impl NodeGraphExecutor {
(node_runtime, node_executor)
}
/// Allows the test runner to see if any more executions have been queued.
#[cfg(test)]
pub fn current_execution_id(&self) -> u64 {
self.current_execution_id
}
/// Execute the network by flattening it and creating a borrow stack.
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
let execution_id = self.current_execution_id;
+49 -29
View File
@@ -34,45 +34,57 @@ impl EditorTestUtils {
Self { editor, runtime }
}
pub fn eval_graph<'a>(&'a mut self) -> impl std::future::Future<Output = Result<Instrumented, String>> + 'a {
// An inner function is required since async functions in traits are a bit weird
async fn run<'a>(editor: &'a mut Editor, runtime: &'a mut NodeRuntime) -> Result<Instrumented, String> {
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
/// Submit an evaluation to the executor, run the runtime, and process the results.
///
/// If a deferred message triggers a second graph run, this will not occur. See [`Self::eval_graph_until_finished`] for this behaviour.
async fn eval_graph_once(&mut self) -> Result<Instrumented, String> {
let portfolio = &mut self.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(format!("update_node_graph_instrumented failed\n\n{e}")),
};
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(format!("update_node_graph_instrumented failed\n\n{e}")),
};
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
runtime.run().await;
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
self.runtime.run().await;
let mut messages = VecDeque::new();
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
return Err(format!("Graph should render\n\n{e}"));
}
let frontend_messages = messages.into_iter().flat_map(|message| editor.handle_message(message));
let mut messages = VecDeque::new();
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut messages) {
return Err(format!("Graph should render\n\n{e}"));
}
let frontend_messages = messages.into_iter().flat_map(|message| self.editor.handle_message(message));
for message in frontend_messages {
message.check_node_graph_error();
}
Ok(instrumented)
for message in frontend_messages {
message.check_node_graph_error();
}
run(&mut self.editor, &mut self.runtime)
Ok(instrumented)
}
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, String> {
const MAX_ITERATIONS: usize = 16;
for _iteration in 0..MAX_ITERATIONS {
let execution_id = self.portfolio_message_handler().executor.current_execution_id();
let result = self.eval_graph_once().await?;
// If there have been no other executions queued (other than the one we just queued ourselves above) then finish
if execution_id + 1 >= self.portfolio_message_handler().executor.current_execution_id() {
return Ok(result);
}
}
return Err(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping"));
}
pub async fn handle_message(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
let frontend_messages_from_msg = self.editor.handle_message(message);
// Required to process any buffered messages
if let Err(e) = self.eval_graph().await {
if let Err(e) = self.eval_graph_until_finished().await {
panic!("Failed to evaluate graph: {e}");
}
@@ -165,12 +177,20 @@ impl EditorTestUtils {
.await;
}
pub fn portfolio_message_handler(&self) -> &PortfolioMessageHandler {
&self.editor.dispatcher.message_handlers.portfolio_message_handler
}
pub fn portfolio_message_handler_mut(&mut self) -> &mut PortfolioMessageHandler {
&mut self.editor.dispatcher.message_handlers.portfolio_message_handler
}
pub fn active_document(&self) -> &DocumentMessageHandler {
self.editor.dispatcher.message_handlers.portfolio_message_handler.active_document().unwrap()
self.portfolio_message_handler().active_document().unwrap()
}
pub fn active_document_mut(&mut self) -> &mut DocumentMessageHandler {
self.editor.dispatcher.message_handlers.portfolio_message_handler.active_document_mut().unwrap()
self.portfolio_message_handler_mut().active_document_mut().unwrap()
}
pub async fn move_mouse(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys, mouse_keys: MouseKeys) {
+261
View File
@@ -0,0 +1,261 @@
// An ESLint rule requiring DOM queries to select elements by their `data-*` attributes, which markup sets for scripts to find it by,
// rather than by element types, classes, IDs, or other attributes, which are free to change with the markup's structure and styling
import { pathToFileURL } from "node:url";
import parseSelector from "postcss-selector-parser";
// Stands in for each `${…}` interpolation of a template literal while its selector is read
const INTERPOLATION = String.fromCodePoint(0xe000);
const SELECTOR_METHODS = ["querySelector", "querySelectorAll", "closest", "matches"];
const ELEMENTS_BY_METHODS = ["getElementById", "getElementsByClassName", "getElementsByName", "getElementsByTagName", "getElementsByTagNameNS"];
// Pseudo-classes taking a list of selectors, which are held to the rule too, where `:has()` takes relative ones that may begin with a combinator
const SELECTOR_LIST_PSEUDO_CLASSES = ["not", "is", "where", "matches", "-webkit-any", "-moz-any", "host", "host-context"];
const RELATIVE_SELECTOR_LIST_PSEUDO_CLASSES = ["has"];
// Pseudo-classes taking a microsyntax that may end with `of` and a list of selectors
const OF_SELECTOR_PSEUDO_CLASSES = ["nth-child", "nth-last-child"];
const MALFORMED = { messageId: "malformed", part: "" };
const requireDataSelectors = {
meta: {
type: "problem",
docs: {
description: "Require DOM queries to select elements by `data-*` attributes rather than by element type, class, ID, or other attributes.",
},
schema: [],
messages: {
typeSelector: "Select by a `data-*` attribute rather than the element type `{{part}}`.",
classSelector: "Select by a `data-*` attribute rather than the class `{{part}}`, since classes are for styling.",
idSelector: "Select by a `data-*` attribute rather than the ID `{{part}}`.",
attributeSelector: "Select by a `data-*` attribute rather than the attribute `{{part}}`.",
malformed: "This CSS selector is malformed, with an unbalanced bracket, parenthesis, quote, or combinator.",
elementsBy: "Select with `querySelector` or `querySelectorAll` and a `data-*` attribute rather than with `{{part}}`.",
},
},
create: (context) => ({
CallExpression: (node) => {
const method = methodName(node.callee);
if (method === undefined) return;
if (ELEMENTS_BY_METHODS.includes(method)) {
context.report({ node: node.callee.property, messageId: "elementsBy", data: { part: method } });
return;
}
if (!SELECTOR_METHODS.includes(method)) return;
const argument = node.arguments[0];
const selector = selectorText(argument);
if (selector === undefined) return;
const problem = selectorListProblem(selector, false);
if (problem) context.report({ node: argument, messageId: problem.messageId, data: { part: problem.part.replaceAll(INTERPOLATION, "${…}") } });
},
}),
};
export default requireDataSelectors;
// The name of the method a call is made on, like `querySelector` in `element.querySelector(…)` or `element["querySelector"](…)`
function methodName(callee) {
if (callee.type !== "MemberExpression") return undefined;
if (!callee.computed && callee.property.type === "Identifier") return callee.property.name;
if (callee.computed && callee.property.type === "Literal" && typeof callee.property.value === "string") return callee.property.value;
return undefined;
}
// A selector written as a string or template literal, with each interpolation marked, or `undefined` where it's computed some other way
function selectorText(argument) {
if (argument?.type === "Literal" && typeof argument.value === "string") return argument.value;
if (argument?.type === "TemplateLiteral") return argument.quasis.map((quasi) => quasi.value.cooked ?? quasi.value.raw).join(INTERPOLATION);
return undefined;
}
// The first problem with a list of comma-separated selectors, if any, where a relative list may begin each selector with a combinator
function selectorListProblem(list, relative) {
let parsed;
try {
parsed = parseSelector().astSync(list);
} catch {
return MALFORMED;
}
return selectorsProblem(parsed.nodes, relative);
}
// The first problem with parsed selectors, if any, which the parser leaves to be found where its combinators stand or what its parts name
function selectorsProblem(selectors, relative) {
return selectors.map((selector) => combinatorProblem(selector.nodes, relative) ?? selector.nodes.map(nodeProblem).find(Boolean)).find(Boolean);
}
// A selector with no parts, or a combinator with no compound selector on either side of it, which the parser accepts but a browser rejects
function combinatorProblem(nodes, relative) {
if (nodes.length === 0) return MALFORMED;
const combinator = (node) => node?.type === "combinator";
if (combinator(nodes[0]) && !relative) return MALFORMED;
if (combinator(nodes[nodes.length - 1])) return MALFORMED;
if (nodes.some((node, index) => combinator(node) && combinator(nodes[index + 1]))) return MALFORMED;
return undefined;
}
// The problem with one part of a compound selector, if any
function nodeProblem(node) {
const part = String(node).trim();
switch (node.type) {
// An interpolation may stand for a whole selector rather than an element type, so it's left unchecked
case "tag":
return node.value.includes(INTERPOLATION) ? undefined : { messageId: "typeSelector", part };
// A class or ID is one whatever an interpolation names it
case "class":
return { messageId: "classSelector", part };
case "id":
return { messageId: "idSelector", part };
// An interpolated name may be anything, including a `data-*` attribute
case "attribute": {
const name = node.attribute.toLowerCase();
return name.startsWith("data-") || name.includes(INTERPOLATION) ? undefined : { messageId: "attributeSelector", part };
}
case "pseudo":
return pseudoClassArgumentProblem(node);
// The universal and nesting selectors, and combinators, name nothing
default:
return undefined;
}
}
// The first problem with the selectors a pseudo-class takes as its argument, if it takes any, where pseudo-elements take none
function pseudoClassArgumentProblem(node) {
if (node.value.startsWith("::")) return undefined;
const name = node.value.slice(1).toLowerCase();
if (SELECTOR_LIST_PSEUDO_CLASSES.includes(name)) return selectorsProblem(node.nodes, false);
if (RELATIVE_SELECTOR_LIST_PSEUDO_CLASSES.includes(name)) return selectorsProblem(node.nodes, true);
// The parser reads a microsyntax like `2n + 1` as selectors too, so only the selectors after `of` are read again on their own
if (OF_SELECTOR_PSEUDO_CLASSES.includes(name)) {
const written = String(node).trim();
const argument = written.slice(node.value.length + 1, -1);
const of = /\sof\s/i.exec(argument);
return of ? selectorListProblem(argument.slice(of.index + of[0].length), false) : undefined;
}
return undefined;
}
// Running this file directly with `node eslint-require-data-selectors.js` tests the rule after a change, where RuleTester throws at the first case that fails
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const { RuleTester } = await import("eslint");
const query = (selector) => `element.querySelector(${selector})`;
const invalid = (code, messageId) => ({ code, errors: [{ messageId }] });
new RuleTester().run("require-data-selectors", requireDataSelectors, {
valid: [
// Data attributes joined by every combinator, spaced or not, and compounded
query(`"[data-foo]"`),
query(`"[data-foo] [data-bar]"`),
query(`"[data-foo] > [data-bar]"`),
query(`"[data-foo]>[data-bar]"`),
query(`"[data-foo] ~ [data-bar]"`),
query(`"[data-foo]~[data-bar]"`),
query(`"[data-foo] + [data-bar]"`),
query(`"[data-foo]+[data-bar]"`),
query(`" [data-foo][data-bar] "`),
query(`"[data-foo], [data-bar] [data-baz]"`),
// Attribute values, operators, and case flags
query(`"[data-foo='a, b] (c)']"`),
query(`"[data-foo = \\"x\\"]"`),
query(`"[data-foo~=x i]"`),
query(`"[data-foo|=en]"`),
query(`"[DATA-FOO]"`),
// Pseudo-classes, and the universal selector, which name no element type
query(`":scope > [data-tab]"`),
query(`"[data-input]:enabled"`),
query(`":hover"`),
query(`"[data-foo] *"`),
query(`"[data-foo]::before"`),
query(`"[data-foo]:not([data-bar])"`),
query(`":is([data-a], [data-b]) > [data-c]"`),
query(`":where([data-a])"`),
query(`"[data-a]:has(> [data-b], + [data-c])"`),
query(`"[data-list] > :nth-child(2n + 1 of [data-item])"`),
query(`"[data-list] > :nth-child(2n+1)"`),
// Interpolations in an attribute's value or name, or standing for whole selectors
query(`\`[data-token="\${index}"]\``),
query("`[data-${name}]`"),
query("`[${attribute}]`"),
query("`${selector} > [data-foo]`"),
query("`:is(${selectors})`"),
// Every method that takes a selector, called on anything, optionally, or by a computed name
`element.querySelectorAll("[data-foo]")`,
`element.closest("[data-foo]")`,
`element.matches(":focus-visible")`,
`element?.querySelector("[data-foo]")`,
`element["closest"]("[data-foo]")`,
// Selectors computed some other way, and other methods
`element.querySelector(selector)`,
`element.closest(prefix + "foo")`,
`list.find(".foo")`,
`element.getAttribute("class")`,
`layers.getElementsByDepth(2)`,
],
invalid: [
// Element types, classes, IDs, and other attributes
invalid(query(`".foo"`), "classSelector"),
invalid(query(`"div"`), "typeSelector"),
invalid(query(`"div.foo"`), "typeSelector"),
invalid(query(`"#foo"`), "idSelector"),
invalid(query(`"div#foo"`), "typeSelector"),
invalid(query(`"div#foo.bar"`), "typeSelector"),
invalid(query(`"svg|rect"`), "typeSelector"),
invalid(query(`"foo[data-bar]"`), "typeSelector"),
invalid(query(`"[foo][data-bar]"`), "attributeSelector"),
invalid(query(`"[data-bar][foo]"`), "attributeSelector"),
invalid(query(`"[title]"`), "attributeSelector"),
invalid(query(`"foo[title]"`), "typeSelector"),
invalid(query(`"[data-foo] input"`), "typeSelector"),
invalid(query(`"[data-foo] > .bar"`), "classSelector"),
invalid(query(`"[data-foo], .bar"`), "classSelector"),
// Within the selectors a pseudo-class takes
invalid(query(`"[data-foo]:not(.bar)"`), "classSelector"),
invalid(query(`"[data-foo]:not([disabled])"`), "attributeSelector"),
invalid(query(`":is([data-a], div)"`), "typeSelector"),
invalid(query(`":has(> span)"`), "typeSelector"),
invalid(query(`":nth-child(2 of .item)"`), "classSelector"),
// A class or attribute is one whatever an interpolation names it, as is a non-data attribute with an interpolated value
invalid(query("`.${name}`"), "classSelector"),
invalid(query(`\`[for="checkbox-\${id}"]\``), "attributeSelector"),
// Unbalanced brackets, parentheses, quotes, or combinators
invalid(query(`"[data-foo"`), "malformed"),
invalid(query(`"[data-foo]]"`), "malformed"),
invalid(query(`"[data-foo]:not([data-bar]"`), "malformed"),
invalid(query(`"[data-foo='bar]"`), "malformed"),
invalid(query(`"[data-foo] >"`), "malformed"),
invalid(query(`"> [data-foo]"`), "malformed"),
invalid(query(`"[data-foo] > > [data-bar]"`), "malformed"),
invalid(query(`"[data-a],,[data-b]"`), "malformed"),
invalid(query(`""`), "malformed"),
// Every method that takes a selector, and those selecting by other means
invalid(`element.closest("button")`, "typeSelector"),
invalid(`element.matches(".foo")`, "classSelector"),
invalid(`self?.div()?.querySelector(".text-input input")`, "classSelector"),
invalid(`element["querySelectorAll"]("div")`, "typeSelector"),
invalid(`document.getElementById("foo")`, "elementsBy"),
invalid(`element.getElementsByClassName("foo")`, "elementsBy"),
invalid(`element.getElementsByTagName("div")`, "elementsBy"),
invalid(`document.getElementsByName("foo")`, "elementsBy"),
],
});
}
+6
View File
@@ -5,6 +5,8 @@ import pluginPrettier from "eslint-plugin-prettier";
import pluginSvelte from "eslint-plugin-svelte";
import globals from "globals";
import ts from "typescript-eslint";
// eslint-disable-next-line no-restricted-imports -- The config loads the rule from beside it, where absolute paths like `/src` don't resolve
import requireDataSelectors from "./eslint-require-data-selectors.js";
const importOrder = {
alphabetize: { order: "asc", caseInsensitive: true },
@@ -38,6 +40,7 @@ export default defineConfig([
{
plugins: {
prettier: pluginPrettier,
graphite: { rules: { "require-data-selectors": requireDataSelectors } },
},
settings: {
"import/parsers": { "@typescript-eslint/parser": [".ts"] },
@@ -123,6 +126,9 @@ export default defineConfig([
"import/no-relative-packages": "error",
"import/no-named-as-default-member": "off",
"import/order": ["error", importOrder],
// Graphite's own rules (for project conventions)
"graphite/require-data-selectors": "error",
},
},
{
+11
View File
@@ -7,6 +7,7 @@
"name": "graphite-web-frontend",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@fontsource/stix-two-math": "5.3.0",
"source-code-pro": "2.42.0",
"source-sans-pro": "2.45.0"
},
@@ -21,6 +22,7 @@
"eslint-plugin-svelte": "^3.17.0",
"globals": "^17.4.0",
"license-checker-rseidelsohn": "^4.4.2",
"postcss-selector-parser": "^7.1.1",
"prettier": "^3.8.1",
"prettier-plugin-svelte": "^3.5.1",
"sass": "^1.99.0",
@@ -222,6 +224,15 @@
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
"node_modules/@fontsource/stix-two-math": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/stix-two-math/-/stix-two-math-5.3.0.tgz",
"integrity": "sha512-negoeozw6VSXjZMozwKRSm/dhCQT62csZcuea9I8KYqPaZq/8KbbBBrA02ZHF7AyuR5mVML/p+q0bwFuSIf2GQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@humanfs/core": {
"version": "0.19.1",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",
+2
View File
@@ -11,6 +11,7 @@
"//": "NOTE: `source-sans-pro` is never to be upgraded to 3.x because that renders 1px above its intended position.",
"///": "Waiting on <https://github.com/import-js/eslint-plugin-import/issues/3227> before we can update @eslint/js and eslint to 10.x",
"dependencies": {
"@fontsource/stix-two-math": "5.3.0",
"source-code-pro": "2.42.0",
"source-sans-pro": "2.45.0"
},
@@ -25,6 +26,7 @@
"eslint-plugin-svelte": "^3.17.0",
"globals": "^17.4.0",
"license-checker-rseidelsohn": "^4.4.2",
"postcss-selector-parser": "^7.1.1",
"prettier": "^3.8.1",
"prettier-plugin-svelte": "^3.5.1",
"sass": "^1.99.0",
+11
View File
@@ -12,6 +12,7 @@
import { createDialogStore, destroyDialogStore } from "/src/stores/dialog";
import { createDocumentStore, destroyDocumentStore } from "/src/stores/document";
import { createFullscreenStore, destroyFullscreenStore } from "/src/stores/fullscreen";
import { createMathExpressionStore, destroyMathExpressionStore } from "/src/stores/math-expression";
import { createNodeGraphStore, destroyNodeGraphStore } from "/src/stores/node-graph";
import { createPortfolioStore, destroyPortfolioStore } from "/src/stores/portfolio";
import { createTooltipStore, destroyTooltipStore } from "/src/stores/tooltip";
@@ -33,6 +34,7 @@
portfolio: createPortfolioStore(subscriptions, editor),
appWindow: createAppWindowStore(subscriptions),
colorPicker: createColorPickerStore(subscriptions),
mathExpression: createMathExpressionStore(subscriptions),
};
Object.entries(stores).forEach(([key, store]) => setContext(key, store));
@@ -62,6 +64,7 @@
destroyPortfolioStore();
destroyAppWindowStore();
destroyColorPickerStore();
destroyMathExpressionStore();
// Managers
destroyClipboardManager();
@@ -376,4 +379,12 @@
font-stretch: normal;
src: url("/node_modules/source-code-pro/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2") format("woff2");
}
@font-face {
font-family: "STIX Two Math";
font-weight: 400;
font-style: normal;
font-stretch: normal;
src: url("/node_modules/@fontsource/stix-two-math/files/stix-two-math-latin-400-normal.woff2") format("woff2");
}
</style>
@@ -42,7 +42,7 @@
editor.openColorPicker(colorOrGradient, allowNone, disabled);
// Auto-select the hex color code text input. Deferred so the layout has time to render after the picker opens.
setTimeout(() => {
const hexInput = self?.div()?.querySelector(".text-input input");
const hexInput = self?.div()?.querySelector("[data-text-input] [data-input-element]");
if (hexInput instanceof HTMLInputElement) hexInput.select();
}, 0);
} else if (!isOpen && lastOpen) {
@@ -16,7 +16,7 @@
let self: FloatingMenu | undefined;
onMount(() => {
// Focus the button which is marked as emphasized, or otherwise the first button, in the popup
// Focus the button which is marked as emphasized, or otherwise the first button, in the dialog
const button = self?.div?.()?.querySelector("[data-emphasized]") || self?.div?.()?.querySelector("[data-text-button]");
const emphasizedOrFirstButton = button instanceof HTMLButtonElement ? button : undefined;
emphasizedOrFirstButton?.focus();
@@ -11,6 +11,7 @@
import Separator from "/src/components/widgets/labels/Separator.svelte";
import ShortcutLabel from "/src/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import { targetIsTextField } from "/src/utility-functions/input";
import type { MenuListEntry, MenuDirection } from "/wrapper/pkg/graphite_wasm_wrapper";
let self: FloatingMenu | undefined;
@@ -34,9 +35,14 @@
export let direction: MenuDirection = "Bottom";
export let minWidth = 0;
export let drawIcon = false;
export let monospace = false;
export let interactive = false;
export let scrollableY = false;
export let virtualScrolling = false;
// Whether the highlight moves to each new active entry given while the menu is open
export let highlightFollowsActiveEntry = false;
// Use `Popover` to draw a tail pointing at the spawner. Defaults to `Dropdown` (no tail), which the menu bar uses. Recursive submenus always use `Dropdown`.
export let type: "Dropdown" | "Popover" = "Dropdown";
// Keep the child references outside of the entries array so as to avoid infinite recursion.
let childReferences: MenuList[][] = [];
@@ -44,6 +50,7 @@
let search = "";
let reactiveEntries = entries;
let highlighted: MenuListEntry | undefined = activeEntry;
let lastActiveEntry: { value: string | undefined; entriesHash: bigint } = { value: activeEntry?.value, entriesHash };
let virtualScrollingEntriesStart = 0;
let keydownListenerAdded = false;
let destroyed = false;
@@ -59,6 +66,7 @@
$: watchEntriesHash(entriesHash);
$: watchRemeasureWidth(filteredEntries, drawIcon);
$: watchHighlightedWithSearch(filteredEntries, open);
$: watchActiveEntry(activeEntry, entriesHash);
$: virtualScrollingEntryHeight = virtualScrolling ? 20 : 0;
$: filteredEntries = reactiveEntries.map((section) => section.filter((entry) => inSearch(search, entry)));
@@ -103,10 +111,31 @@
}
}
// An active entry given while the menu is open takes the highlight and is scrolled into view, unless it's the same one among the same
// entries given again, as any layout update does, which leaves the highlight wherever it was moved
function watchActiveEntry(activeEntry: MenuListEntry | undefined, entriesHash: bigint) {
const given = { value: activeEntry?.value, entriesHash };
const repeated = given.value === lastActiveEntry.value && given.entriesHash === lastActiveEntry.entriesHash;
lastActiveEntry = given;
if (!highlightFollowsActiveEntry || !open || !activeEntry || repeated) return;
highlighted = activeEntry;
// Once its row is drawn, unless the highlight has moved on by then
tick().then(() => {
if (open && highlighted?.value === activeEntry.value) setHighlighted(activeEntry);
});
}
// Detect when the user types, which creates a search box
async function startSearch(e: KeyboardEvent) {
// Only accept single-character symbol inputs other than space
if (e.key.length !== 1 || e.key === " ") return;
// Nor a shortcut's key, though AltGr, which also reports Ctrl, types characters
if ((e.ctrlKey || e.metaKey) && !e.getModifierState("AltGraph")) {
// The browser's own action for it, like saving the page, stays held back, except a text field's editing shortcuts
if (!targetIsTextField(e.target || undefined)) e.preventDefault();
return;
}
// Stop shortcuts being activated
e.stopPropagation();
@@ -365,9 +394,7 @@
// Click on a highlighted entry with the enter key
if (menuOpen && highlighted && e.key === "Enter") {
// Handle clicking on an option if enter is pressed
if (!highlighted.children?.length) onEntryClick(highlighted);
else openSubmenu(highlighted);
pickHighlighted();
// Stop the event from triggering a press on a new dialog
e.preventDefault();
@@ -413,27 +440,35 @@
return false;
}
// Picks the highlighted entry as clicking it would, returning whether there was one to pick
export function pickHighlighted(): boolean {
if (!open || !highlighted) return false;
if (!highlighted.children?.length) onEntryClick(highlighted);
else openSubmenu(highlighted);
return true;
}
export function setHighlighted(newHighlight: MenuListEntry | undefined) {
highlighted = newHighlight;
// Scroll into view
let container = scroller?.div?.();
if (!container || !highlighted) return;
let containerBoundingRect = container.getBoundingClientRect();
let highlightedIndex = filteredEntries.flat().findIndex((entry) => entry.value === highlighted?.value);
const highlightedIndex = filteredEntries.flat().findIndex((entry) => entry.value === highlighted?.value);
let selectedBoundingRect = new DOMRect();
if (virtualScrollingEntryHeight) {
// Special case for virtual scrolling
selectedBoundingRect.y = highlightedIndex * virtualScrollingEntryHeight - container.scrollTop + containerBoundingRect.y;
selectedBoundingRect.height = virtualScrollingEntryHeight;
} else {
let entries = Array.from(container.children).filter((element) => element.classList.contains("row"));
let element = entries[highlightedIndex - startIndex];
if (!element) return;
containerBoundingRect = element.getBoundingClientRect();
// Without virtual scrolling, every row exists and the floating menu around them is what scrolls, so the row is brought into its view
if (!virtualScrollingEntryHeight) {
const rows = Array.from(container.children).filter((element) => element.classList.contains("row"));
rows[highlightedIndex - startIndex]?.scrollIntoView({ block: "nearest" });
return;
}
const containerBoundingRect = container.getBoundingClientRect();
const selectedBoundingRect = new DOMRect();
selectedBoundingRect.y = highlightedIndex * virtualScrollingEntryHeight - container.scrollTop + containerBoundingRect.y;
selectedBoundingRect.height = virtualScrollingEntryHeight;
if (containerBoundingRect.y > selectedBoundingRect.y) {
container.scrollBy(0, selectedBoundingRect.y - containerBoundingRect.y);
}
@@ -448,7 +483,7 @@
{open}
on:open={({ detail }) => (open = detail)}
on:naturalWidth
type="Dropdown"
{type}
windowEdgeMargin={0}
escapeCloses={false}
{direction}
@@ -482,6 +517,7 @@
tooltipLabel={entry.tooltipLabel}
tooltipDescription={entry.tooltipDescription}
tooltipShortcut={entry.tooltipShortcut}
tooltipCode={entry.tooltipCode}
on:click={() => !entry.disabled && onEntryClick(entry)}
on:pointerenter={() => !entry.disabled && onEntryPointerEnter(entry)}
on:pointerleave={() => !entry.disabled && onEntryPointerLeave(entry)}
@@ -507,6 +543,7 @@
<TextLabel
class="entry-label"
{monospace}
classes={{
"font-preview": Boolean(entry.font),
"font-loaded": loadedFontsGeneration >= 0 && loadedFonts.has(entry.value),
@@ -518,11 +555,13 @@
{#if entry.tooltipShortcut?.shortcut.length}
<ShortcutLabel shortcut={entry.tooltipShortcut} />
{:else if entry.annotation}
<TextLabel class="entry-annotation">{entry.annotation}</TextLabel>
{/if}
{#if entry.children?.length}
<IconLabel class="submenu-arrow" icon="DropdownArrow" />
{:else}
{:else if !entry.annotation || entry.tooltipShortcut?.shortcut.length}
<div class="no-submenu-arrow"></div>
{/if}
@@ -542,6 +581,7 @@
entriesHash={entry.childrenHash || 0n}
{minWidth}
{drawIcon}
{monospace}
{scrollableY}
bind:this={childReferences[sectionIndex][entryIndex + startIndex]}
/>
@@ -564,6 +604,13 @@
.floating-menu-container .floating-menu-content.floating-menu-content {
padding: 4px 0;
// A row scrolled into view at either end keeps the padding beyond it in view too
scroll-padding: 4px 0;
// Where the menu itself scrolls, its entries keep their full height so the padding after them is reached too
> .layout-col:not(.scrollable-y) {
flex-shrink: 0;
}
.separator {
margin: 4px 0;
@@ -609,10 +656,17 @@
margin: 0 4px;
}
.shortcut-label {
.shortcut-label,
.entry-annotation {
margin-left: 12px;
}
// Styled like a shortcut's keys, which it takes the place of, but inset from the row's end like the label from its start
.entry-annotation {
margin-right: 4px;
color: var(--color-8-uppergray);
}
.submenu-arrow {
transform: rotate(270deg);
}
@@ -5,19 +5,25 @@
import ShortcutLabel from "/src/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { TooltipStore } from "/src/stores/tooltip";
import { parseMarkdown } from "/src/utility-functions/markdown";
import type { EditorWrapper, LabeledShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
// Marks where each code span or block goes while the prose around it is formatted, which HTML-escaped text can't hold since it has no `<`
const CODE_PLACEHOLDER = "<>";
const tooltip = getContext<TooltipStore>("tooltip");
const editor = getContext<EditorWrapper>("editor");
// The tooltip a component shows for part of itself, given with the bounds of that part, rather than the hovered element's at the pointer
export let given: { label: string; description: string; code: string; bounds: { left: number; top: number; bottom: number } } | undefined = undefined;
let self: FloatingMenu | undefined;
$: label = parseMarkdown(filterTodo($tooltip.element?.getAttribute("data-tooltip-label")?.trim()));
$: description = parseMarkdown(filterTodo($tooltip.element?.getAttribute("data-tooltip-description")?.trim()));
$: shortcutJSON = $tooltip.element?.getAttribute("data-tooltip-shortcut")?.trim();
$: element = given ? undefined : $tooltip.element;
$: label = parseMarkdown(filterTodo((given?.label || element?.getAttribute("data-tooltip-label"))?.trim()));
$: description = parseMarkdown(filterTodo((given?.description || element?.getAttribute("data-tooltip-description"))?.trim()));
$: code = parseMarkdown((given?.code || element?.getAttribute("data-tooltip-code"))?.trim());
$: shortcutJSON = element?.getAttribute("data-tooltip-shortcut")?.trim();
// A given tooltip stands below its bounds from their left, or above them where there's no room below, rather than clearing the pointer below it
$: position = given ? { x: given.bounds.left, y: (given.bounds.top + given.bounds.bottom) / 2 } : $tooltip.position;
$: gap = given ? (given.bounds.bottom - given.bounds.top) / 2 : undefined;
$: shortcut = ((shortcutJSON) => {
if (!shortcutJSON) return undefined;
try {
@@ -35,117 +41,12 @@
if (text?.trim().toUpperCase() === "TODO" && !editor.inDevelopmentMode()) return "";
return text;
}
// Renders the tooltip subset of Markdown: `code` spans, fenced code blocks, **bold**, and *italic*, where a backslash makes a following
// backslash, asterisk, or backtick literal. The text is HTML-escaped before anything else and code is never formatted, so no text yields other markup.
function parseMarkdown(markdown: string | undefined): string | undefined {
if (!markdown) return undefined;
const escaped = markdown.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
const codeElements: string[] = [];
let text = "";
let index = 0;
while (index < escaped.length) {
// A backslash makes a following backslash, asterisk, or backtick literal, written as an entity that no formatting matches
if (escaped[index] === "\\" && ["\\", "*", "`"].includes(escaped[index + 1])) {
text += `&#${escaped.charCodeAt(index + 1)};`;
index += 2;
continue;
}
if (escaped[index] === "`") {
const fenceEnd = endOfBacktickRun(escaped, index);
const fenceLength = fenceEnd - index;
// A run of three or more backticks alone on a line opens a code block that only a line of at least as many closes, as in CommonMark
const atLineStart = index === 0 || escaped[index - 1] === "\n";
if (atLineStart && fenceLength >= 3 && escaped[fenceEnd] === "\n") {
const contentStart = fenceEnd + 1;
const { contentEnd, blockEnd } = endOfCodeBlock(escaped, contentStart, fenceLength);
// The fence lines are the block's edges, so the line break before the block isn't a blank line above it
if (text.endsWith("\n")) text = text.slice(0, -1);
codeElements.push(`<pre><code>${escaped.slice(contentStart, contentEnd)}</code></pre>`);
text += CODE_PLACEHOLDER;
index = blockEnd;
continue;
}
// Otherwise the run opens a code span that only a run of the same length closes
const closing = nextBacktickRunOfLength(escaped, fenceEnd, fenceLength);
if (closing === undefined) {
text += escaped.slice(index, fenceEnd);
index = fenceEnd;
continue;
}
// One space is trimmed from each end when both have one, so a span can begin or end with a backtick
let code = escaped.slice(fenceEnd, closing);
if (code.startsWith(" ") && code.endsWith(" ") && /[^ ]/.test(code)) code = code.slice(1, -1);
codeElements.push(`<code>${code}</code>`);
text += CODE_PLACEHOLDER;
index = closing + fenceLength;
continue;
}
text += escaped[index];
index += 1;
}
let codeElementIndex = 0;
return (
text
// .split("\n")
// .map((line) => line.trim())
// .join("\n")
// .split("\n\n")
// .map((paragraph) => paragraph.replaceAll("\n", " "))
// .join("\n\n")
// Bold
.replace(/\*\*((?:(?!\*\*).)+)\*\*/g, "<strong>$1</strong>")
// Italic
.replace(/\*([^*]+)\*/g, "<em>$1</em>")
// Code spans and blocks
.replaceAll(CODE_PLACEHOLDER, () => codeElements[codeElementIndex++])
);
}
// The end of a code block's content from `from`, and of the closing line of at least `fenceLength` backticks after it, or the text's end when none closes it
function endOfCodeBlock(text: string, from: number, fenceLength: number): { contentEnd: number; blockEnd: number } {
const closingLine = new RegExp(`^\`{${fenceLength},}$`, "gm");
closingLine.lastIndex = from;
const closing = closingLine.exec(text);
if (!closing) return { contentEnd: text.length, blockEnd: text.length };
return { contentEnd: Math.max(from, closing.index - 1), blockEnd: Math.min(closing.index + closing[0].length + 1, text.length) };
}
// The index just past the run of backticks starting at `start`
function endOfBacktickRun(text: string, start: number): number {
let end = start;
while (text[end] === "`") end += 1;
return end;
}
// The start of the next run of exactly `length` backticks at or after `from`, skipping longer and shorter runs
function nextBacktickRunOfLength(text: string, from: number, length: number): number | undefined {
let start = text.indexOf("`", from);
while (start !== -1) {
const end = endOfBacktickRun(text, start);
if (end - start === length) return start;
start = text.indexOf("`", end);
}
return undefined;
}
</script>
{#if label || description}
<div class="tooltip" style:top={`${$tooltip.position.y}px`} style:left={`${$tooltip.position.x}px`}>
<FloatingMenu open={true} type="Tooltip" direction="Bottom" bind:this={self}>
{#if label || shortcut}
<div class="tooltip" style:top={`${position.y}px`} style:left={`${position.x}px`}>
<FloatingMenu open={true} type="Tooltip" direction="Bottom" alignment={given ? "Start" : "Center"} {gap} bind:this={self}>
{#if label || shortcut || code}
<LayoutRow class="tooltip-header">
{#if label}
<TextLabel class="tooltip-label">{@html label}</TextLabel>
@@ -153,6 +54,9 @@
{#if shortcut}
<ShortcutLabel shortcut={{ shortcut }} />
{/if}
{#if code}
<TextLabel class="tooltip-code" monospace={true}>{@html code}</TextLabel>
{/if}
</LayoutRow>
{/if}
{#if description}
@@ -184,6 +88,16 @@
margin-left: 8px;
}
.tooltip-code {
margin-left: auto;
padding-left: 8px;
color: var(--color-b-lightgray);
strong {
color: var(--color-e-nearwhite);
}
}
.tooltip-description {
color: var(--color-b-lightgray);
}
@@ -42,11 +42,17 @@
export let minWidth = 0;
export let escapeCloses = true;
export let strayCloses = true;
// Whether a popover points at what it's anchored to with a tail, which it leaves room for
export let tail = true;
// Whether a menu opening up or down lines up with the start of what it's anchored to, as a dropdown does by default, or centers on it
export let alignment: "Start" | "Center" | undefined = undefined;
// The space from what the menu is anchored to, in place of the room its type leaves for a tail or the pointer
export let gap: number | undefined = undefined;
const editor = getContext<EditorWrapper>("editor");
const menuId = String(Math.random()).substring(2);
let tail: HTMLDivElement | undefined;
let tailElement: HTMLDivElement | undefined;
let self: HTMLDivElement | undefined;
let floatingMenuContainer: HTMLDivElement | undefined;
let floatingMenuContent: LayoutCol | undefined;
@@ -60,6 +66,11 @@
resizeObserverCallback(entries);
});
// The menu is placed again when its content resizes while open, since a change within the slot doesn't fire `afterUpdate()`
const contentResizeObserver = new ResizeObserver(() => {
if (!measuringOngoingGuard) positionAndStyleFloatingMenu();
});
let dialogResizeObserver: ResizeObserver | undefined;
let wasOpen = open;
let measuringOngoing = false;
@@ -72,7 +83,8 @@
$: onFloatingMenuOpenChange(menuId, open && type !== "Tooltip" && type !== "Cursor", editor);
$: minWidthStyleValue = measuringOngoing ? "0" : `${Math.max(minWidth, minWidthParentWidth)}px`;
$: displayTail = open && type === "Popover";
$: displayTail = open && type === "Popover" && tail;
$: startAligned = (alignment || (type === "Dropdown" ? "Start" : "Center")) === "Start";
$: displayContainer = open || measuringOngoing;
$: extraClasses = Object.entries(classes)
.flatMap(([className, stateName]) => (stateName ? [className] : []))
@@ -107,12 +119,18 @@
containerResizeObserver.disconnect();
containerResizeObserver.observe(floatingMenuContainer);
}
const floatingMenuContentDiv = floatingMenuContent?.div?.();
if (floatingMenuContentDiv) {
contentResizeObserver.disconnect();
contentResizeObserver.observe(floatingMenuContentDiv);
}
}
// Switching from open to closed
if (!isOpen && wasOpen) {
// Clean up observation of the now-closed floating menu
containerResizeObserver.disconnect();
contentResizeObserver.disconnect();
window.removeEventListener("pointermove", pointerMoveHandler);
window.removeEventListener("keydown", keyDownHandler);
@@ -160,11 +178,15 @@
});
dialogResizeObserver.observe(floatingMenuContentDiv);
}
// A menu created open never sees `open` change to start watching its content
if (open && floatingMenuContentDiv) contentResizeObserver.observe(floatingMenuContentDiv);
});
onDestroy(() => {
onFloatingMenuOpenChange(menuId, false, editor);
containerResizeObserver.disconnect();
contentResizeObserver.disconnect();
dialogResizeObserver?.disconnect();
window.removeEventListener("pointermove", pointerMoveHandler);
window.removeEventListener("keydown", keyDownHandler);
@@ -193,6 +215,12 @@
const floatingMenuContentDiv = floatingMenuContent?.div?.();
if (!self || !floatingMenuContainer || !floatingMenuContent || !floatingMenuContentDiv) return;
// A menu opening up or down is pinned to a window side only while it would cross that side, so it's measured unpinned, letting it go once it fits again
if (direction === "Top" || direction === "Bottom") {
floatingMenuContainer.style.setProperty("--content-left", "initial");
floatingMenuContainer.style.setProperty("--content-right", "initial");
}
const windowBounds = document.documentElement.getBoundingClientRect();
const floatingMenuBounds = self.getBoundingClientRect();
const floatingMenuContainerBounds = floatingMenuContainer.getBoundingClientRect();
@@ -232,19 +260,20 @@
const inParentFloatingMenu = Boolean(floatingMenuContainer.closest("[data-floating-menu-content]"));
const noPosition = Boolean(floatingMenuContainer.closest("[data-floating-menu-no-position]"));
if (!inParentFloatingMenu && !noPosition) {
let tailOffset = 0;
if (type === "Popover") tailOffset = 10;
if (type === "Tooltip") tailOffset = direction === "Bottom" ? 20 : 10;
let offset = 0;
if (type === "Popover" && tail) offset = 10;
if (type === "Tooltip") offset = direction === "Bottom" ? 20 : 10;
if (gap !== undefined) offset = gap;
if (direction === "Bottom") floatingMenuContainer.style.setProperty("--content-top", `${tailOffset + floatingMenuBounds.y}px`);
if (direction === "Top") floatingMenuContainer.style.setProperty("--content-bottom", `${tailOffset + (windowBounds.height - floatingMenuBounds.y)}px`);
if (direction === "Right") floatingMenuContainer.style.setProperty("--content-left", `${tailOffset + floatingMenuBounds.x}px`);
if (direction === "Left") floatingMenuContainer.style.setProperty("--content-right", `${tailOffset + (windowBounds.width - floatingMenuBounds.x)}px`);
if (direction === "Bottom") floatingMenuContainer.style.setProperty("--content-top", `${offset + floatingMenuBounds.y}px`);
if (direction === "Top") floatingMenuContainer.style.setProperty("--content-bottom", `${offset + (windowBounds.height - floatingMenuBounds.y)}px`);
if (direction === "Right") floatingMenuContainer.style.setProperty("--content-left", `${offset + floatingMenuBounds.x}px`);
if (direction === "Left") floatingMenuContainer.style.setProperty("--content-right", `${offset + (windowBounds.width - floatingMenuBounds.x)}px`);
if (tail && direction === "Bottom") tail.style.top = `${floatingMenuBounds.y}px`;
if (tail && direction === "Top") tail.style.bottom = `${windowBounds.height - floatingMenuBounds.y}px`;
if (tail && direction === "Right") tail.style.left = `${floatingMenuBounds.x}px`;
if (tail && direction === "Left") tail.style.right = `${windowBounds.width - floatingMenuBounds.x}px`;
if (tailElement && direction === "Bottom") tailElement.style.top = `${floatingMenuBounds.y}px`;
if (tailElement && direction === "Top") tailElement.style.bottom = `${windowBounds.height - floatingMenuBounds.y}px`;
if (tailElement && direction === "Right") tailElement.style.left = `${floatingMenuBounds.x}px`;
if (tailElement && direction === "Left") tailElement.style.right = `${windowBounds.width - floatingMenuBounds.x}px`;
}
type Edge = "Top" | "Bottom" | "Left" | "Right";
@@ -496,12 +525,14 @@
<div
class={`floating-menu ${direction.toLowerCase()} ${type.toLowerCase()} ${className} ${extraClasses}`.trim()}
class:no-tail={!tail}
class:start-aligned={startAligned}
style={`${styleName} ${extraStyles}`.trim() || undefined}
bind:this={self}
{...$$restProps}
>
{#if displayTail}
<div class="tail" bind:this={tail}></div>
<div class="tail" bind:this={tailElement}></div>
{/if}
{#if displayContainer}
<div class="floating-menu-container" bind:this={floatingMenuContainer} on:wheel|stopPropagation>
@@ -618,12 +649,12 @@
}
}
&.top.dropdown .floating-menu-container,
&.bottom.dropdown .floating-menu-container {
&.top.start-aligned > .floating-menu-container,
&.bottom.start-aligned > .floating-menu-container {
justify-content: left;
}
&.popover {
&.popover:not(.no-tail) {
--floating-menu-content-offset: 10px;
}
@@ -716,22 +747,22 @@
}
}
&.top .floating-menu-container {
&.top > .floating-menu-container {
justify-content: center;
margin-bottom: var(--floating-menu-content-offset);
}
&.bottom .floating-menu-container {
&.bottom > .floating-menu-container {
justify-content: center;
margin-top: var(--floating-menu-content-offset);
}
&.left .floating-menu-container {
&.left > .floating-menu-container {
align-items: center;
margin-right: var(--floating-menu-content-offset);
}
&.right .floating-menu-container {
&.right > .floating-menu-container {
align-items: center;
margin-left: var(--floating-menu-content-offset);
}
@@ -10,6 +10,7 @@
export let tooltipLabel: string | undefined = undefined;
export let tooltipDescription: string | undefined = undefined;
export let tooltipShortcut: ActionShortcut | undefined = undefined;
export let tooltipCode: string | undefined = undefined;
// TODO: Add middle-click drag scrolling
export let scrollableX = false;
export let scrollableY = false;
@@ -33,6 +34,7 @@
data-tooltip-label={tooltipLabel}
data-tooltip-description={tooltipDescription}
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
data-tooltip-code={tooltipCode || undefined}
data-scrollable-x={scrollableX ? "" : undefined}
data-scrollable-y={scrollableY ? "" : undefined}
class={`layout-row ${className} ${extraClasses}`.trim()}
+2 -2
View File
@@ -131,7 +131,7 @@
await tick();
const query = list?.div?.()?.querySelector("[data-text-input]:not([disabled])");
const query = list?.div?.()?.querySelector("[data-layer-name-input]:enabled");
const textInput = (query instanceof HTMLInputElement && query) || undefined;
textInput?.select();
}
@@ -617,7 +617,7 @@
{/if}
<LayoutRow class="layer-name" on:dblclick={() => onEditLayerName(listing)}>
<input
data-text-input
data-layer-name-input
type="text"
value={listing.entry.alias}
placeholder={listing.entry.implementationName}
@@ -60,7 +60,7 @@
if (!handle) return;
// Don't begin a drag when pressing one of the header's own buttons (pin/delete/visibility); only the header itself grabs
if (target.closest("button") !== handle) return;
if (target.closest("[data-icon-button]")) return;
const section = target.closest("[data-properties-reorderable-section]");
const nodeIdAttribute = section?.getAttribute("data-node-id");
@@ -12,6 +12,7 @@
import ColorInput from "/src/components/widgets/inputs/ColorInput.svelte";
import ColorPresetsInput from "/src/components/widgets/inputs/ColorPresetsInput.svelte";
import DropdownInput from "/src/components/widgets/inputs/DropdownInput.svelte";
import MathExpressionInput from "/src/components/widgets/inputs/MathExpressionInput.svelte";
import NumberInput from "/src/components/widgets/inputs/NumberInput.svelte";
import RadioInput from "/src/components/widgets/inputs/RadioInput.svelte";
import ReferencePointInput from "/src/components/widgets/inputs/ReferencePointInput.svelte";
@@ -182,7 +183,7 @@
component: ParameterExposeButton,
getProps: (props, index) => ({
...props,
action: () => widgetValueCommitAndUpdate(index, undefined, true),
$$events: { selectedEntryValuePath: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, false) },
}),
},
IconButton: {
@@ -215,6 +216,21 @@
action: () => widgetValueCommitAndUpdate(index, undefined, true),
}),
},
MathExpressionInput: {
component: MathExpressionInput,
getProps: (props, index) => ({
...props,
widgetId: widgets[index].widgetId,
analyze: (source: string, caret?: number, asked = false) => editor.analyzeMathExpression(layoutTarget, widgets[index].widgetId, source, caret, asked),
evaluate: (source: string) => editor.evaluateMathExpression(widgets[index].widgetId, source),
$$events: {
commitText: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, true),
updateText: (e: CustomEvent) => widgetValueUpdate(index, e.detail, true),
startHistoryTransaction: () => widgetValueCommit(index, props.value),
commitHistoryTransaction: () => editor.endTransaction(),
},
}),
},
NodeCatalog: {
component: NodeCatalog,
getProps: (props, index) => ({
@@ -51,6 +51,7 @@
data-tooltip-description={tooltipDescription}
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
data-drag-droppable={actionDragDrop ? "" : undefined}
data-icon-button
tabindex={emphasized ? -1 : 0}
{...$$restProps}
>
@@ -1,27 +1,44 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import MenuList from "/src/components/floating-menus/MenuList.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import type { FrontendGraphDataType, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { FrontendGraphDataType, ActionShortcut, MenuListEntry } from "/wrapper/pkg/graphite_wasm_wrapper";
const dispatch = createEventDispatcher<{ selectedEntryValuePath: string[] }>();
let self: MenuList;
// Content
export let exposed: boolean;
export let dataType: FrontendGraphDataType;
// Children
export let menuListChildren: MenuListEntry[][] = [];
export let menuListChildrenHash: bigint = 0n;
// Tooltips
export let tooltipLabel: string | undefined = undefined;
export let tooltipDescription: string | undefined = undefined;
export let tooltipShortcut: ActionShortcut | undefined = undefined;
// Callbacks
export let action: (e?: MouseEvent) => void;
function onClick(e: MouseEvent) {
// Focus the target so that keyboard inputs are sent to the dropdown
if (e.target instanceof HTMLElement) e.target.focus();
// Open the menu list floating menu
if (self) self.open = true;
}
</script>
<LayoutRow class="parameter-expose-button">
<button
class:exposed
class:open={self?.open}
style:--data-type-color={`var(--color-data-${dataType.toLowerCase()})`}
style:--data-type-color-dim={`var(--color-data-${dataType.toLowerCase()}-dim)`}
on:click={action}
on:click={onClick}
data-tooltip-label={tooltipLabel}
data-tooltip-description={tooltipDescription}
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
data-floating-menu-spawner
tabindex="-1"
>
{#if !exposed}
@@ -42,6 +59,16 @@
</svg>
{/if}
</button>
<MenuList
on:selectedEntryValuePath={({ detail }) => dispatch("selectedEntryValuePath", detail)}
open={false}
entries={menuListChildren}
entriesHash={menuListChildrenHash}
direction="Bottom"
type="Popover"
drawIcon={true}
bind:this={self}
/>
</LayoutRow>
<style lang="scss">
@@ -49,6 +76,7 @@
display: flex;
align-items: center;
flex: 0 0 auto;
position: relative;
max-height: 24px;
button {
@@ -70,7 +98,8 @@
fill: var(--data-type-color);
}
&:hover {
&:hover,
&.open {
.outline {
fill: var(--data-type-color);
}
@@ -80,5 +109,12 @@
}
}
}
// Anchor the floating menu's tail to the bottom-center of the small button.
// Scoped to the direct child so nested submenu floating menus aren't affected.
> :global(.floating-menu) {
left: 50%;
bottom: 0;
}
}
</style>
@@ -61,6 +61,7 @@
class:checked
class:mixed
for={`checkbox-input-${id}`}
data-checkbox-label={id}
on:keydown={(e) => e.key === "Enter" && toggleCheckboxFromLabel(e)}
data-tooltip-label={tooltipLabel}
data-tooltip-description={tooltipDescription}
@@ -10,6 +10,7 @@
value: "",
label: "-",
icon: undefined,
annotation: "",
disabled: false,
children: [],
childrenHash: 0n,
@@ -17,6 +18,7 @@
tooltipLabel: "",
tooltipDescription: "",
tooltipShortcut: undefined,
tooltipCode: "",
};
const dispatch = createEventDispatcher<{ selectedIndex: number; hoverInEntry: number; hoverOutEntry: number; fileDrop: File }>();
@@ -76,7 +76,7 @@
</script>
<!-- This is a base component, extended by others like NumberInput and TextInput. It should not be used directly. -->
<LayoutRow class={`field-input ${className}`} classes={{ disabled, narrow, monospace, ...classes }} style={styleName} {styles} {tooltipLabel} {tooltipDescription} {tooltipShortcut}>
<LayoutRow class={`field-input ${className}`} classes={{ disabled, narrow, monospace, ...classes }} style={styleName} {styles} {tooltipLabel} {tooltipDescription} {tooltipShortcut} {...$$restProps}>
{#if !textarea}
<input
type="text"
@@ -113,6 +113,7 @@
on:keydown={(e) => e.key === "Escape" && cancel()}
on:pointerdown
on:contextmenu={(e) => hideContextMenu && e.preventDefault()}
data-input-element
></textarea>
{/if}
{#if label}
File diff suppressed because it is too large. Load diff
@@ -3,6 +3,8 @@
import { preventEscapeClosingParentFloatingMenu } from "/src/components/layout/FloatingMenu.svelte";
import FieldInput from "/src/components/widgets/inputs/FieldInput.svelte";
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS } from "/src/managers/input";
import { clampedDigit, compareDecimal, digitAt, digitIndex, formatDecimal, parseDecimal, roundDecimal, sameDigit, stepDigit } from "/src/utility-functions/decimal";
import type { Decimal, Digit } from "/src/utility-functions/decimal";
import { roundAwayFloatNoise } from "/src/utility-functions/numbers";
import { browserVersion } from "/src/utility-functions/platform";
import type { ActionShortcut, EditorWrapper, NumberInputIncrementBehavior, NumberInputMode } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -14,6 +16,8 @@
const dispatch = createEventDispatcher<{
value: number | undefined;
exactValue: string;
digit: Digit;
commitText: string;
startHistoryTransaction: undefined;
commitHistoryTransaction: undefined;
@@ -51,6 +55,12 @@
export let displayDecimalPlaces = 2;
export let unit = "";
export let unitIsHiddenWhenEditing = true;
/// When given, the value as exact decimal text like `-2.50` or `1.5e-3`, shown as written and stepped digit by digit with no float rounding.
/// New text is emitted with `exactValue`, and typed text that isn't a number with `commitText`. Only the "Increment" mode with the "Add" behavior and no label supports it.
export let exact: string | undefined = undefined;
/// With `exact`, the digit that dragging and the arrows step, which is underlined. Dragging the underline onto another digit emits that
/// digit with `digit`.
export let digit: Digit = { part: "mantissa", place: 0 };
// Sizing
export let minWidth = 0;
@@ -65,7 +75,7 @@
let self: FieldInput | undefined;
let inputRangeElement: HTMLInputElement | undefined;
let text = displayText(value, unit);
let text = exact ?? displayText(value, unit);
let editing = false;
let isDragging = false;
let pressingArrow = false;
@@ -83,6 +93,17 @@
let rangeSliderClickDragState: "Ready" | "Deciding" | "Dragging" | "Aborted" = "Ready";
// Stores the initial value upon beginning to drag so it can be restored upon aborting. Set to `undefined` when not dragging.
let initialValueBeforeDragging: number | undefined = undefined;
// The exact mode's counterpart to `initialValueBeforeDragging`.
let initialExactBeforeDragging: string | undefined = undefined;
// The exact mode's value a drag steps from, and whether it steps the digit after the stepped one, with Shift.
let exactDragBase: { text: string; finer: boolean } | undefined = undefined;
// The exact mode's copy of the text drawing the stepped digit's underline, and the digit that underline is being dragged to.
let digitMark: HTMLSpanElement | undefined;
let markDragDigit: Digit | undefined = undefined;
// The digit a drag or arrow press steps throughout, which the underline shows unclamped until it ends.
let steppingDigit: Digit | undefined = undefined;
let markDragStartX = 0;
let markDragMoved = false;
// Stores the total value change during the process of dragging the slider. Set to 0 when not dragging.
let cumulativeDragDelta = 0;
// Track whether the Shift key is currently held down.
@@ -100,6 +121,10 @@
let sliderAbortTimeout2: ReturnType<typeof setTimeout> | undefined;
$: watchValue(value, unit);
$: if (exact !== undefined && !editing) text = exact;
$: present = exact !== undefined || value !== undefined;
// A number of only one digit, like `0` or `-1`, has no other digit to move the underline to, so it isn't shown
$: markedDigit = exact !== undefined && writtenDigits(text).length > 1 ? digitIndex(text, markDragDigit || steppingDigit || clampedDigit(text, digit)) : undefined;
$: sliderStepValue = isInteger ? (step === undefined ? 1 : step) : "any";
$: styles = {
...(minWidth > 0 ? { "min-width": `${minWidth}px` } : {}),
@@ -163,6 +188,9 @@
// Don't update if the slider is currently being dragged (we don't want the backend fighting with the user's drag)
if (rangeSliderClickDragState === "Dragging") return;
// Exact mode shows its own text instead
if (exact !== undefined) return;
// Draw a dash if the value is undefined
if (value === undefined) {
text = "-";
@@ -211,6 +239,125 @@
return newValueValidated;
}
// The exact mode's counterpart to `updateValue`, held within `min` and `max`, which returns the held number. It's written as `written`
// where that's its value, or as already written where it's unchanged, so a number like `.5` or `1E3` keeps its spelling.
function updateExact(decimal: Decimal, written?: string): Decimal {
const bound = (limit: number | undefined) => (typeof limit === "number" ? parseDecimal(`${limit}`) : undefined);
const [lower, upper] = [bound(min), bound(max)];
let held = decimal;
if (lower && compareDecimal(held, lower) < 0) held = lower;
if (upper && compareDecimal(held, upper) > 0) held = upper;
const current = exact === undefined ? undefined : parseDecimal(exact);
if (written !== undefined && compareDecimal(held, decimal) === 0) text = written;
else if (exact !== undefined && current && compareDecimal(held, current) === 0) text = exact;
else text = formatDecimal(held);
if (text !== exact) dispatch("exactValue", text);
return held;
}
// Pressing the stepped digit's underline starts dragging it onto another digit, which becomes the stepped one when released
function onMarkPointerDown(e: PointerEvent) {
if (disabled || e.button !== BUTTON_LEFT || !(e.currentTarget instanceof HTMLElement)) return;
// Keeps the focus where it is
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
markDragDigit = clampedDigit(text, digit);
markDragStartX = e.clientX;
markDragMoved = false;
}
function onMarkPointerMove(e: PointerEvent) {
if (markDragDigit === undefined) return;
// A press only becomes a drag once it moves a few pixels
markDragMoved ||= Math.abs(e.clientX - markDragStartX) > 3;
if (markDragMoved) markDragDigit = digitNearest(e.clientX) || markDragDigit;
}
// A release ends a drag where it is, and a click that didn't drag moves the underline to the next digit on the right, or with Shift on
// the left, showing it can move
function onMarkPointerUp(released: boolean, backward = false) {
if (markDragDigit === undefined) return;
const chosen = released && !markDragMoved ? nextDigit(markDragDigit, backward) : markDragDigit;
if (!sameDigit(chosen, digit)) dispatch("digit", chosen);
markDragDigit = undefined;
}
// The digits of a number as written, left to right
function writtenDigits(written: string): Digit[] {
return Array.from(written).flatMap((_, index) => digitAt(written, index) || []);
}
// The digit after another, or before it going backward, wrapping around past either end
function nextDigit(from: Digit, backward: boolean): Digit {
const digits = writtenDigits(text);
const current = digits.findIndex((written) => sameDigit(written, from));
if (backward) return digits[current - 1] || digits[digits.length - 1] || from;
return digits[current + 1] || digits[0] || from;
}
// The digit the underline shows, which a drag or arrow press steps, kept as the chosen one where it was clamped onto the number's own digits
function useShownDigit(): Digit {
const shown = clampedDigit(text, digit);
if (!sameDigit(shown, digit)) dispatch("digit", shown);
return shown;
}
// The digit drawn nearest a horizontal position, measured on the underline's copy of the text
function digitNearest(x: number): Digit | undefined {
if (!digitMark) return undefined;
const walker = document.createTreeWalker(digitMark, NodeFilter.SHOW_TEXT);
const range = document.createRange();
let index = 0;
let nearest: { digit: Digit; distance: number } | undefined = undefined;
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const length = node.textContent?.length || 0;
for (let offset = 0; offset < length; offset += 1, index += 1) {
const written = digitAt(text, index);
if (written === undefined) continue;
range.setStart(node, offset);
range.setEnd(node, offset + 1);
const { left, right } = range.getBoundingClientRect();
const distance = Math.abs((left + right) / 2 - x);
if (!nearest || distance < nearest.distance) nearest = { digit: written, distance };
}
}
return nearest?.digit;
}
// Steps the digit once per 10 pixels, or with Shift the digit after it, and with Ctrl rounds away the digits after it, both only in the
// mantissa since an exponent ends at its ones
function exactDragUpdate(delta: number, slow: boolean, snapping: boolean, initial: string) {
const stepping = steppingDigit || digit;
const finer = slow && stepping.part === "mantissa";
// Changing the speed partway through a drag steps on from the value shown
if (exactDragBase?.finer !== finer) {
exactDragBase = { text: exactDragBase ? text : initial, finer };
cumulativeDragDelta = 0;
}
const decimal = parseDecimal(exactDragBase.text);
if (!decimal) return;
cumulativeDragDelta += delta;
const steps = Math.trunc(cumulativeDragDelta / 10);
const stepped = stepDigit(decimal, finer ? { part: "mantissa", place: stepping.place - 1 } : stepping, steps);
// Dragging on past `min` or `max` builds up no movement, so dragging back steps on from the value it was held to
const wanted = snapping && stepping.part === "mantissa" ? roundDecimal(stepped, stepping.place) : stepped;
if (compareDecimal(updateExact(wanted), wanted) !== 0) {
exactDragBase = { text, finer };
cumulativeDragDelta = 0;
}
}
// ================
// HELPER FUNCTIONS
// ================
@@ -255,7 +402,8 @@
// The number shown when editing the field, with floating point imprecision noise removed
const noFloatingImprecisionText = value === undefined ? undefined : numberText(roundAwayFloatNoise(value));
if (value === undefined) text = "";
if (exact !== undefined) text = exact;
else if (value === undefined) text = "";
else if (unitIsHiddenWhenEditing) text = `${noFloatingImprecisionText}`;
else text = `${noFloatingImprecisionText}${unPluralize(unit, value)}`;
@@ -272,6 +420,21 @@
// The `unFocus()` call at the bottom of this function and in `onTextChangeCanceled()` causes this function to be run again, so this check skips a second run.
if (!editing) return;
// Exact mode keeps a typed number as written, and hands any other typed text to its owner to evaluate, showing the old value meanwhile
if (exact !== undefined) {
const typed = parseDecimal(text);
if (typed) {
updateExact(typed, text.trim());
} else {
dispatch("commitText", text);
text = exact;
}
editing = false;
self?.unFocus();
return;
}
// The backend evaluates the math, validates against this widget's constraints, and (only when changed) applies it within a history transaction before resending the widget.
dispatch("commitText", text);
@@ -283,6 +446,13 @@
}
function onTextChangeCanceled() {
if (exact !== undefined) {
text = exact;
editing = false;
self?.unFocus();
return;
}
updateValue(undefined);
const valueOrZero = value !== undefined ? value : 0;
@@ -299,10 +469,17 @@
// =============================
function onIncrementPointerDown(e: PointerEvent, direction: "Decrease" | "Increase") {
if (value === undefined || e.button !== BUTTON_LEFT) return;
if (!present || e.button !== BUTTON_LEFT) return;
const actions: Record<NumberInputIncrementBehavior, () => void> = {
Add: () => {
// Exact mode steps the underlined digit
const decimal = exact !== undefined ? parseDecimal(text) : undefined;
if (decimal) {
updateExact(stepDigit(decimal, steppingDigit || digit, direction === "Increase" ? 1 : -1));
return;
}
const directionAddend = direction === "Increase" ? step : -step;
const newValue = value !== undefined ? value + directionAddend : undefined;
updateValue(newValue);
@@ -330,6 +507,8 @@
pressingArrow = true;
initialValueBeforeDragging = value;
initialExactBeforeDragging = exact;
if (exact !== undefined) steppingDigit = useShownDigit();
let afterInitialDelay = false;
sendAction();
repeatTimeout = setTimeout(sendAction, PRESS_REPEAT_DELAY_MS);
@@ -338,11 +517,14 @@
function onIncrementPointerUp() {
pressingArrow = false;
steppingDigit = undefined;
clearTimeout(repeatTimeout);
removeEventListener("keydown", incrementPressAbort);
}
function incrementPressAbort(e: KeyboardEvent | MouseEvent) {
// Only abort if the user right clicks or presses Escape
// Only abort a press still in progress, if the user right clicks or presses Escape
if (!pressingArrow) return;
if (e instanceof KeyboardEvent && e.key !== "Escape") return;
if (e instanceof MouseEvent && e.button !== BUTTON_RIGHT) return;
@@ -350,8 +532,11 @@
if (element) preventEscapeClosingParentFloatingMenu(element);
pressingArrow = false;
steppingDigit = undefined;
clearTimeout(repeatTimeout);
updateValue(initialValueBeforeDragging);
const initialExact = initialExactBeforeDragging === undefined ? undefined : parseDecimal(initialExactBeforeDragging);
if (initialExact) updateExact(initialExact, initialExactBeforeDragging);
else updateValue(initialValueBeforeDragging);
removeEventListener("keydown", incrementPressAbort);
}
@@ -369,7 +554,7 @@
function onDragPointerDown(e: PointerEvent) {
// Only drag the number with left click (and when it's valid to do so)
if (e.button !== BUTTON_LEFT || mode !== "Increment" || value === undefined || disabled || editing) return;
if (e.button !== BUTTON_LEFT || mode !== "Increment" || !present || disabled || editing) return;
// Remove the text entry cursor from any other selected text field
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
@@ -439,6 +624,9 @@
editor.appWindowPointerLock();
}
initialValueBeforeDragging = value;
initialExactBeforeDragging = exact;
if (exact !== undefined) steppingDigit = useShownDigit();
exactDragBase = undefined;
cumulativeDragDelta = 0;
// Tell the backend that we are beginning a transaction for the history system
@@ -456,11 +644,17 @@
// Confirm on release by setting the reset value to the current value, so once the pointer lock ends,
// the value is set to itself instead of the initial (abort) value in the "pointerlockchange" event handler function.
initialValueBeforeDragging = value;
if (initialExactBeforeDragging !== undefined) initialExactBeforeDragging = text;
cumulativeDragDelta = 0;
if (usePointerLock) document.exitPointerLock();
else pointerLockChange();
};
// Moves the value by a drag's horizontal movement, in whichever mode the input is in
const dragUpdate = (delta: number, slow: boolean, snapping: boolean) => {
if (initialExactBeforeDragging !== undefined) exactDragUpdate(delta, slow, snapping, initialExactBeforeDragging);
else if (initialValueBeforeDragging !== undefined) pointerLockMoveUpdate(delta, slow, snapping, initialValueBeforeDragging);
};
const pointerMove = (e: PointerEvent) => {
// TODO: Display a fake cursor over the top of the page which wraps around the edges of the editor.
@@ -480,18 +674,13 @@
}
// Calculate and then update the dragged value offset, slowed down by 10x when Shift is held.
if (ignoredFirstMovement && initialValueBeforeDragging !== undefined) {
pointerLockMoveUpdate(e.movementX, e.shiftKey, e.ctrlKey, initialValueBeforeDragging);
}
if (ignoredFirstMovement) dragUpdate(e.movementX, e.shiftKey, e.ctrlKey);
ignoredFirstMovement = true;
};
// On desktop we don't get `pointermove` events while in pointer lock (CEF doesn't support pointer lock).
// We have to listen for our custom `pointerlockmove` events instead.
const pointerLockMove = ({ detail }: WindowEventMap["pointerlockmove"]) => {
if (ignoredFirstMovement && initialValueBeforeDragging !== undefined) {
const delta = detail.x;
pointerLockMoveUpdate(delta, shiftKeyDown, ctrlKeyDown, initialValueBeforeDragging);
}
if (ignoredFirstMovement) dragUpdate(detail.x, shiftKeyDown, ctrlKeyDown);
ignoredFirstMovement = true;
};
const pointerLockChange = () => {
@@ -502,8 +691,13 @@
if (isSafari) document.body.classList.remove("cursor-hidden");
// Reset the value to the initial value if the drag was aborted, or to the current value if it was just confirmed by changing the initial value to the current value.
updateValue(initialValueBeforeDragging);
const initialExact = initialExactBeforeDragging === undefined ? undefined : parseDecimal(initialExactBeforeDragging);
if (initialExact) updateExact(initialExact, initialExactBeforeDragging);
else updateValue(initialValueBeforeDragging);
initialValueBeforeDragging = undefined;
initialExactBeforeDragging = undefined;
exactDragBase = undefined;
steppingDigit = undefined;
cumulativeDragDelta = 0;
// Clean up the event listeners.
@@ -791,7 +985,19 @@
spellcheck={false}
bind:this={self}
>
{#if value !== undefined}
{#if markedDigit !== undefined}
<span class="digit-mark" class:dragging={markDragDigit !== undefined} bind:this={digitMark}
>{text.slice(0, markedDigit)}<span
class="marked"
role="presentation"
on:pointerdown={onMarkPointerDown}
on:pointermove={onMarkPointerMove}
on:pointerup={(e) => onMarkPointerUp(true, e.shiftKey)}
on:lostpointercapture={() => onMarkPointerUp(false)}>{text[markedDigit]}</span
>{text.slice(markedDigit + 1)}</span
>
{/if}
{#if present}
{#if mode === "Increment" && incrementBehavior !== "None"}
<button
class="arrow left"
@@ -841,6 +1047,81 @@
--widget-height: 20px;
}
// Laid out like the field's text, which it mirrors in transparent characters
.digit-mark {
position: absolute;
inset: 0;
margin: 0 8px;
padding: 3px 0;
line-height: calc(var(--widget-height) - 6px);
text-align: center;
white-space: pre;
overflow: hidden;
color: transparent;
pointer-events: none;
// Brightened while hovered or dragged
.marked {
position: relative;
text-decoration: underline;
text-decoration-color: var(--color-8-uppergray);
text-decoration-thickness: 1px;
text-underline-offset: 2px;
// The press target, a strip from about 6px above the underline down to the field's bottom edge
&::after {
content: "";
position: absolute;
left: 0;
right: 0;
top: calc(100% - 8px);
bottom: -3px;
pointer-events: auto;
cursor: pointer;
}
}
// Thickened by 1px both above and below, and its digit drawn over the dimmed field's own so it alone stays bright
.marked:hover,
&.dragging .marked {
color: var(--color-e-nearwhite);
text-decoration-color: var(--color-e-nearwhite);
text-decoration-thickness: 3px;
text-underline-offset: 1px;
}
// On the digit too, which holds the drag's pointer capture and so sets the cursor once the pointer moves
&.dragging .marked,
&.dragging .marked::after {
cursor: grabbing;
}
}
input[type="text"]:focus ~ .digit-mark {
display: none;
}
// A disabled field's underline only marks the stepped digit, with no press target to hover or drag
&.disabled .digit-mark .marked::after {
pointer-events: none;
}
// Hovering or dragging the underline dims the rest of the field, so it reads as what's being pointed at
&:has(.digit-mark .marked:hover),
&:has(.digit-mark.dragging) {
input[type="text"] {
color: var(--color-8-uppergray);
}
.arrow.right::before {
border-color: transparent transparent transparent var(--color-8-uppergray);
}
.arrow.left::after {
border-color: transparent var(--color-8-uppergray) transparent transparent;
}
}
&.increment {
--arrow-radius: 3px;
@@ -90,6 +90,7 @@
{tooltipDescription}
{tooltipShortcut}
{placeholder}
data-text-input
bind:this={self}
/>
@@ -56,11 +56,11 @@
}
function handlePointerEnter() {
document.querySelector(`[for="checkbox-input-${forCheckbox}"]`)?.classList.add("label-is-hovered");
document.querySelector(`[data-checkbox-label="${forCheckbox}"]`)?.classList.add("label-is-hovered");
}
function handlePointerLeave() {
document.querySelector(`[for="checkbox-input-${forCheckbox}"]`)?.classList.remove("label-is-hovered");
document.querySelector(`[data-checkbox-label="${forCheckbox}"]`)?.classList.remove("label-is-hovered");
}
onMount(() => watchForCheckbox(forCheckbox));
+6 -2
View File
@@ -134,6 +134,9 @@ import Copy from "/../branding/assets/icon-16px-solid/copy.svg";
import Credits from "/../branding/assets/icon-16px-solid/credits.svg";
import CustomColor from "/../branding/assets/icon-16px-solid/custom-color.svg";
import Cut from "/../branding/assets/icon-16px-solid/cut.svg";
import DataSourceGraph from "/../branding/assets/icon-16px-solid/data-source-graph.svg";
import DataSourceTimeline from "/../branding/assets/icon-16px-solid/data-source-timeline.svg";
import DataSourceValue from "/../branding/assets/icon-16px-solid/data-source-value.svg";
import DeselectAll from "/../branding/assets/icon-16px-solid/deselect-all.svg";
import Edit from "/../branding/assets/icon-16px-solid/edit.svg";
import Empty from "/../branding/assets/icon-16px-solid/empty.svg";
@@ -201,7 +204,6 @@ import Save from "/../branding/assets/icon-16px-solid/save.svg";
import SelectAll from "/../branding/assets/icon-16px-solid/select-all.svg";
import SelectParent from "/../branding/assets/icon-16px-solid/select-parent.svg";
import Settings from "/../branding/assets/icon-16px-solid/settings.svg";
import SmallDot from "/../branding/assets/icon-16px-solid/small-dot.svg";
import StackBottom from "/../branding/assets/icon-16px-solid/stack-bottom.svg";
import StackHollow from "/../branding/assets/icon-16px-solid/stack-hollow.svg";
import StackLower from "/../branding/assets/icon-16px-solid/stack-lower.svg";
@@ -274,6 +276,9 @@ const SOLID_16PX = {
Credits: { svg: Credits, size: 16 },
CustomColor: { svg: CustomColor, size: 16 },
Cut: { svg: Cut, size: 16 },
DataSourceGraph: { svg: DataSourceGraph, size: 16 },
DataSourceTimeline: { svg: DataSourceTimeline, size: 16 },
DataSourceValue: { svg: DataSourceValue, size: 16 },
DeselectAll: { svg: DeselectAll, size: 16 },
Edit: { svg: Edit, size: 16 },
Empty: { svg: Empty, size: 16 },
@@ -341,7 +346,6 @@ const SOLID_16PX = {
SelectAll: { svg: SelectAll, size: 16 },
SelectParent: { svg: SelectParent, size: 16 },
Settings: { svg: Settings, size: 16 },
SmallDot: { svg: SmallDot, size: 16 },
Stack: { svg: Stack, size: 16 },
StackBottom: { svg: StackBottom, size: 16 },
StackHollow: { svg: StackHollow, size: 16 },
+6 -1
View File
@@ -1,5 +1,6 @@
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import { insertAtCaret, readAtCaret } from "/src/utility-functions/clipboard";
import { targetIsTextField } from "/src/utility-functions/input";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
@@ -17,7 +18,11 @@ export function createClipboardManager(subscriptions: SubscriptionsRouter, edito
});
subscriptions.subscribeFrontendMessage("TriggerSelectionRead", async (data) => {
editor.readSelection(readAtCaret(data.cut), data.cut);
const content = readAtCaret(data.cut);
// A text field with nothing selected has nothing to copy, rather than leaving the shortcut to act on the selected layers
if (content === undefined && targetIsTextField(window.document.activeElement || undefined)) return;
editor.readSelection(content, data.cut);
});
subscriptions.subscribeFrontendMessage("TriggerSelectionWrite", async (data) => {
+73
View File
@@ -0,0 +1,73 @@
import { writable } from "svelte/store";
import type { Writable } from "svelte/store";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { MathExpressionCompletions, MathExpressionToken, MathExpressionTooltip } from "/wrapper/pkg/graphite_wasm_wrapper";
// The backend's reply to the text a math expression widget last sent it, which the widget displays only once its tokens arrive
export type MathExpressionAnalysis = { source: string; tokens: MathExpressionToken[]; tooltips: MathExpressionTooltip[]; completions: MathExpressionCompletions | undefined };
// The backend's reply to math typed in a math expression widget's number popover, with its value written as a number where it has one
export type MathExpressionEvaluation = { source: string; result: string | undefined };
// Each widget's latest reply of each kind, by its widget ID
export type MathExpressionStoreState = {
analyses: Map<string, MathExpressionAnalysis>;
evaluations: Map<string, MathExpressionEvaluation>;
};
const initialState: MathExpressionStoreState = {
analyses: new Map(),
evaluations: new Map(),
};
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
// Persist the store across HMR so subscriptions stay live.
const store: Writable<MathExpressionStoreState> = import.meta.hot?.data?.store || writable<MathExpressionStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store;
export type MathExpressionStore = {
subscribe: typeof subscribe;
// Drops a widget's replies once it's gone
forget: (widgetId: string) => void;
};
export function createMathExpressionStore(subscriptions: SubscriptionsRouter): MathExpressionStore {
destroyMathExpressionStore();
subscriptionsRouter = subscriptions;
subscriptions.subscribeFrontendMessage("UpdateMathExpressionAnalysis", (data) => {
update((state) => {
state.analyses.set(String(data.widgetId), { source: data.source, tokens: data.tokens, tooltips: data.tooltips, completions: data.completions });
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateMathExpressionEvaluation", (data) => {
update((state) => {
state.evaluations.set(String(data.widgetId), { source: data.source, result: data.result });
return state;
});
});
return {
subscribe,
forget: (widgetId: string) => {
update((state) => {
state.analyses.delete(widgetId);
state.evaluations.delete(widgetId);
return state;
});
},
};
}
export function destroyMathExpressionStore() {
const subscriptions = subscriptionsRouter;
if (!subscriptions) return;
subscriptions.unsubscribeFrontendMessage("UpdateMathExpressionAnalysis");
subscriptions.unsubscribeFrontendMessage("UpdateMathExpressionEvaluation");
}
+6 -5
View File
@@ -25,14 +25,15 @@ const initialState: TooltipStoreState = {
fullscreenShortcut: undefined,
};
type Listener = { eventName: keyof DocumentEventMap; action(event: Event): void };
type Listener = { eventName: keyof DocumentEventMap; action(event: Event): void; capture?: boolean };
const tooltipEventListeners: Listener[] = [
{ eventName: "mouseover", action: onMouseOver },
{ eventName: "mousemove", action: onMouseMove },
{ eventName: "mouseleave", action: onMouseLeave },
{ eventName: "mousedown", action: closeTooltip },
{ eventName: "keydown", action: closeTooltip },
{ eventName: "wheel", action: closeTooltip },
// Heard on the way down, since a floating menu or a field with its menu open stops these from bubbling up
{ eventName: "keydown", action: closeTooltip, capture: true },
{ eventName: "wheel", action: closeTooltip, capture: true },
];
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
@@ -69,7 +70,7 @@ export function createTooltipStore(subscriptions: SubscriptionsRouter) {
});
});
tooltipEventListeners.forEach(({ eventName, action }) => document.addEventListener(eventName, action));
tooltipEventListeners.forEach(({ eventName, action, capture }) => document.addEventListener(eventName, action, { capture }));
return { subscribe };
}
@@ -84,7 +85,7 @@ export function destroyTooltipStore() {
subscriptions.unsubscribeFrontendMessage("SendShortcutAltClick");
subscriptions.unsubscribeFrontendMessage("SendShortcutFullscreen");
tooltipEventListeners.forEach(({ eventName, action }) => document.removeEventListener(eventName, action));
tooltipEventListeners.forEach(({ eventName, action, capture }) => document.removeEventListener(eventName, action, { capture }));
}
// Listen for mouse movements onto tooltip-bearing HTML elements to track the future target of a tooltip
@@ -25,6 +25,13 @@ export function readAtCaret(cut: boolean): string | undefined {
return selectedText;
}
// A field that handles copying itself, like one displaying its text in other glyphs, gives the text it would put on the clipboard
if (element instanceof HTMLElement && element.isContentEditable) {
const clipboardData = new DataTransfer();
const handled = !element.dispatchEvent(new ClipboardEvent(cut ? "cut" : "copy", { clipboardData, bubbles: true, cancelable: true }));
if (handled) return clipboardData.getData("text/plain") || undefined;
}
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) {
return undefined;
@@ -63,6 +70,10 @@ export function insertAtCaret(text: string) {
const newPos = start + text.length;
element.selectionStart = element.selectionEnd = newPos;
} else if (element instanceof HTMLElement && element.isContentEditable) {
// A field that applies its own edits, like one displaying its text in other glyphs, takes the text as it would a paste
const handled = !element.dispatchEvent(new InputEvent("beforeinput", { inputType: "insertFromPaste", data: text, bubbles: true, cancelable: true }));
if (handled) return;
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return;
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff. Show more