mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
436c943196 | ||
|
|
5add0191f4 | ||
|
|
c7e9aaa016 |
No files matched your search
@@ -1,11 +1,11 @@
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
|
||||
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
|
||||
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
|
||||
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
|
||||
use crate::messages::portfolio::document::utility_types::misc::PTZ;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
@@ -34,6 +34,8 @@ pub struct NavigationMessageHandler {
|
||||
abortable_pan_start: Option<f64>,
|
||||
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
||||
artwork_behind_graph: bool,
|
||||
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
|
||||
graph_middle_click_start: Option<ViewportPosition>,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -99,6 +101,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
return;
|
||||
};
|
||||
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
|
||||
|
||||
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
|
||||
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
|
||||
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
|
||||
}
|
||||
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
@@ -341,6 +347,13 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
responses.add(ToolMessage::UpdateCursor);
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(NavigateToolMessage::End);
|
||||
|
||||
// Not a pan after all, but a middle click in the graph
|
||||
let middle_click_start = self.graph_middle_click_start.take();
|
||||
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
|
||||
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
||||
responses.add(NodeGraphMessage::MiddleClick);
|
||||
}
|
||||
}
|
||||
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
|
||||
self.finish_operation_with_click = false;
|
||||
@@ -417,6 +430,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
}
|
||||
NavigationMessage::PointerMove { snap } => {
|
||||
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
||||
self.graph_middle_click_start = None;
|
||||
}
|
||||
|
||||
match self.navigation_operation {
|
||||
NavigationOperation::None => {}
|
||||
NavigationOperation::Pan { .. } => {
|
||||
|
||||
@@ -170,6 +170,8 @@ pub enum NodeGraphMessage {
|
||||
PointerOutsideViewport {
|
||||
shift: Key,
|
||||
},
|
||||
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
|
||||
MiddleClick,
|
||||
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
||||
WireHoverTick,
|
||||
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
|
||||
@@ -437,6 +439,7 @@ impl NodeGraphMessage {
|
||||
| Self::PointerMove { .. }
|
||||
| Self::PointerUp
|
||||
| Self::PointerOutsideViewport { .. }
|
||||
| Self::MiddleClick
|
||||
| Self::WireHoverTick
|
||||
| Self::SendGlide
|
||||
| Self::GlideTick
|
||||
|
||||
@@ -1752,6 +1752,20 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.auto_panning.stop(&messages, responses);
|
||||
}
|
||||
}
|
||||
// Middle-clicking a node toggles its visibility
|
||||
NodeGraphMessage::MiddleClick => {
|
||||
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
|
||||
return;
|
||||
}
|
||||
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: breadcrumb_network_path.to_vec(),
|
||||
});
|
||||
}
|
||||
NodeGraphMessage::WireHoverTick => {
|
||||
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
|
||||
}
|
||||
|
||||
+57
@@ -3399,6 +3399,63 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
|
||||
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
|
||||
let graph_pan = |editor: &EditorTestUtils| {
|
||||
editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.network_metadata(&[])
|
||||
.unwrap()
|
||||
.persistent_metadata
|
||||
.navigation_metadata
|
||||
.node_graph_ptz
|
||||
.pan
|
||||
};
|
||||
let layer_in_viewport = |editor: &EditorTestUtils| {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
|
||||
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
||||
|
||||
(0..=(max.x - min.x) as i32)
|
||||
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
|
||||
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
|
||||
.expect("the layer should be pressable")
|
||||
};
|
||||
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
|
||||
editor_position: position,
|
||||
mouse_keys,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Pressed and released with a wobble too small to count as a drag
|
||||
let start = layer_in_viewport(&editor);
|
||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
||||
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
|
||||
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
|
||||
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
|
||||
|
||||
// Dragged away and back before the release
|
||||
let start = layer_in_viewport(&editor);
|
||||
let pan_before = graph_pan(&editor);
|
||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
||||
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
||||
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
|
||||
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
||||
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
|
||||
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert!(is_visible(&editor), "one undo should revert the middle click");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
import { getContext, onMount, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
|
||||
import type { DragToggleListener } from "/src/managers/drag-toggle";
|
||||
import { inspectorLayout } from "/src/stores/portfolio";
|
||||
import { createAutoScroller } from "/src/utility-functions/auto-scroll";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -23,7 +25,15 @@
|
||||
let lastDragClientY = 0;
|
||||
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
|
||||
|
||||
// Everything one middle-button drag across the section headers paints is one history step
|
||||
const dragToggleListener: DragToggleListener = {
|
||||
groups: ["inspector-section-visibility"],
|
||||
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
createDragToggleManager(dragToggleListener);
|
||||
|
||||
addEventListener("pointermove", draggingPointerMove);
|
||||
addEventListener("pointerup", draggingPointerUp);
|
||||
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
|
||||
@@ -36,6 +46,8 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
destroyDragToggleManager(dragToggleListener);
|
||||
|
||||
removeEventListener("pointermove", draggingPointerMove);
|
||||
removeEventListener("pointerup", draggingPointerUp);
|
||||
removeEventListener("pointercancel", abortDrag);
|
||||
|
||||
@@ -331,6 +331,7 @@
|
||||
}
|
||||
|
||||
const dragToggleListener: DragToggleListener = {
|
||||
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
|
||||
activeGroupChanged: (group) => {
|
||||
activeDragToggleGroup = group;
|
||||
},
|
||||
@@ -342,6 +343,15 @@
|
||||
editor.toggleNodeVisibilityLayerPanel(id);
|
||||
}
|
||||
|
||||
// Middle-clicking one of the chain's node buttons toggles that node's visibility
|
||||
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
|
||||
if (e.button !== 1) return;
|
||||
|
||||
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
|
||||
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
|
||||
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
|
||||
}
|
||||
|
||||
function toggleLayerLock(id: bigint) {
|
||||
editor.toggleLayerLock(id);
|
||||
}
|
||||
@@ -1194,6 +1204,7 @@
|
||||
on:pointerdown={(e) => layerPointerDown(e, listing)}
|
||||
on:click={(e) => selectLayerWithModifiers(e, listing)}
|
||||
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
|
||||
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
|
||||
on:pointerenter={() => hoverRow(index)}
|
||||
on:pointerleave={() => (hoveredRowIndex = undefined)}
|
||||
>
|
||||
@@ -1343,6 +1354,8 @@
|
||||
data-chain-node={slot.nodeIndex}
|
||||
data-chain-gap-before={slot.reorderablePosition}
|
||||
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -1359,12 +1372,17 @@
|
||||
: entry.chainExpanded
|
||||
? "Stop listing this layer's chain one node per row."
|
||||
: "List this layer's chain one node per row, beneath the layer."}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
|
||||
on:click={(e) => {
|
||||
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
|
||||
if (entry.chainNodes.length === 0) return;
|
||||
e.stopPropagation();
|
||||
editor.toggleLayerChainExpanded(listing.id);
|
||||
}}
|
||||
on:auxclick={(e) => {
|
||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
|
||||
}}
|
||||
>
|
||||
<IconLabel
|
||||
icon={entry.iconName}
|
||||
@@ -1395,10 +1413,15 @@
|
||||
data-chain-row-node={slot.nodeIndex}
|
||||
data-chain-gap-before={slot.reorderablePosition}
|
||||
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
|
||||
on:pointerdown={(e) => {
|
||||
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
|
||||
}}
|
||||
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
|
||||
on:auxclick={(e) => {
|
||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
|
||||
}}
|
||||
on:dblclick={(e) => {
|
||||
// Only the node's icon opens it in the graph
|
||||
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
|
||||
|
||||
@@ -41,6 +41,12 @@
|
||||
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
|
||||
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
|
||||
}
|
||||
|
||||
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
|
||||
if (e.button !== 1 || widgetData.disabled) return;
|
||||
|
||||
editor.toggleNodeVisibilityInspector(widgetData.id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- TODO: Implement collapsable sections with the Inspector system -->
|
||||
@@ -76,7 +82,16 @@
|
||||
{/if}
|
||||
{/each}
|
||||
{:else}
|
||||
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
|
||||
<button
|
||||
class="header"
|
||||
class:expanded
|
||||
class:expandable
|
||||
data-inspector-reorder-handle={reorderable ? "" : undefined}
|
||||
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
|
||||
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
|
||||
onclick={toggleExpandedWithModifiers}
|
||||
onauxclick={toggleVisibilityWithMiddleClick}
|
||||
>
|
||||
<div
|
||||
class="icon-slot"
|
||||
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
|
||||
|
||||
@@ -8,21 +8,30 @@
|
||||
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
|
||||
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
|
||||
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
|
||||
//
|
||||
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
|
||||
// rather than a click. Their gesture engages on the press, which toggles the source at once.
|
||||
|
||||
export type DragToggleListener = {
|
||||
// The groups whose gestures this listener is told about
|
||||
groups: string[];
|
||||
// Given the group of the pressed button, and undefined once the press ends
|
||||
activeGroupChanged?: (activeGroup: string | undefined) => void;
|
||||
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
|
||||
engagedChanged?: (engaged: boolean) => void;
|
||||
};
|
||||
|
||||
const MIDDLE_BUTTON = 1;
|
||||
|
||||
const listeners = new Set<DragToggleListener>();
|
||||
let activeGroup: string | undefined = undefined;
|
||||
let middleButtonGesture = false;
|
||||
let source: HTMLElement | undefined = undefined;
|
||||
let startingState: string | undefined = undefined;
|
||||
let visited = new WeakSet<Element>();
|
||||
let engaged = false;
|
||||
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
|
||||
let suppressNextAuxClick = false;
|
||||
|
||||
export function createDragToggleManager(listener: DragToggleListener) {
|
||||
listeners.add(listener);
|
||||
@@ -38,12 +47,13 @@ export function createDragToggleManager(listener: DragToggleListener) {
|
||||
window.addEventListener("blur", onPointerUp);
|
||||
// Capture phase on click suppresses the natural source-click before the button's handler runs
|
||||
window.addEventListener("click", onClickCapture, true);
|
||||
window.addEventListener("auxclick", onAuxClickCapture, true);
|
||||
}
|
||||
}
|
||||
|
||||
export function destroyDragToggleManager(listener: DragToggleListener) {
|
||||
// A consumer leaving mid-gesture still hears it end
|
||||
if (engaged) listener.engagedChanged?.(false);
|
||||
if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
|
||||
listeners.delete(listener);
|
||||
|
||||
// Uninstall the window event listeners only once the last consumer leaves
|
||||
@@ -54,83 +64,120 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
|
||||
window.removeEventListener("pointercancel", onPointerUp);
|
||||
window.removeEventListener("blur", onPointerUp);
|
||||
window.removeEventListener("click", onClickCapture, true);
|
||||
window.removeEventListener("auxclick", onAuxClickCapture, true);
|
||||
|
||||
activeGroup = undefined;
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
}
|
||||
}
|
||||
|
||||
function notifyActiveGroupChange(group: string | undefined) {
|
||||
activeGroup = group;
|
||||
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
function listenersOfGroup(group: string): DragToggleListener[] {
|
||||
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
|
||||
}
|
||||
|
||||
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
|
||||
function notifyActiveGroupChange(group: string | undefined) {
|
||||
const previousGroup = activeGroup;
|
||||
activeGroup = group;
|
||||
|
||||
const notifiedGroup = group || previousGroup;
|
||||
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
}
|
||||
|
||||
function groupAttribute(middleButton: boolean): string {
|
||||
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
|
||||
}
|
||||
|
||||
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
|
||||
if (!(target instanceof Element)) return undefined;
|
||||
const found = target.closest("[data-drag-toggle-group]");
|
||||
const found = target.closest(`[${groupAttribute(middleButton)}]`);
|
||||
return found instanceof HTMLElement ? found : undefined;
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (e.button !== 0) return;
|
||||
suppressNextClickFromSource = undefined;
|
||||
function memberState(member: HTMLElement): string | undefined {
|
||||
return member.getAttribute("data-drag-toggle-state") || undefined;
|
||||
}
|
||||
|
||||
const found = findMember(e.target || undefined);
|
||||
function toggle(member: HTMLElement) {
|
||||
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
|
||||
else member.click();
|
||||
}
|
||||
|
||||
function engage() {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
engaged = true;
|
||||
visited.add(source);
|
||||
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
|
||||
if (memberState(source) === startingState) toggle(source);
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
|
||||
const middleButton = e.button === MIDDLE_BUTTON;
|
||||
const found = findMember(e.target || undefined, middleButton);
|
||||
if (!found) return;
|
||||
|
||||
// Stop the event so sibling drag/select handlers on ancestors don't also engage
|
||||
e.stopPropagation();
|
||||
|
||||
middleButtonGesture = middleButton;
|
||||
source = found;
|
||||
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
|
||||
startingState = memberState(found);
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
|
||||
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
|
||||
|
||||
if (middleButton) engage();
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
const member = findMember(e.target || undefined);
|
||||
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return;
|
||||
const member = findMember(e.target || undefined, middleButtonGesture);
|
||||
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
|
||||
|
||||
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
|
||||
if (member === source || visited.has(member)) return;
|
||||
|
||||
// First crossing engages the drag and toggles the source as part of the operation
|
||||
if (!engaged) {
|
||||
engaged = true;
|
||||
visited.add(source);
|
||||
listeners.forEach((listener) => listener.engagedChanged?.(true));
|
||||
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
|
||||
}
|
||||
if (!engaged) engage();
|
||||
|
||||
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
|
||||
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
|
||||
if (memberState(member) !== startingState) return;
|
||||
|
||||
visited.add(member);
|
||||
member.click();
|
||||
toggle(member);
|
||||
}
|
||||
|
||||
function onPointerUp(e: Event) {
|
||||
if (!activeGroup) return;
|
||||
const endedGroup = activeGroup;
|
||||
|
||||
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again
|
||||
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source;
|
||||
// An engaged drag already toggled the source, so its release's click won't toggle it again
|
||||
if (engaged && source && e.type === "pointerup") {
|
||||
if (middleButtonGesture) suppressNextAuxClick = true;
|
||||
else suppressNextClickFromSource = source;
|
||||
}
|
||||
const wasEngaged = engaged;
|
||||
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(undefined);
|
||||
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
|
||||
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
|
||||
}
|
||||
|
||||
function onClickCapture(e: Event) {
|
||||
@@ -141,6 +188,15 @@ function onClickCapture(e: Event) {
|
||||
suppressNextClickFromSource = undefined;
|
||||
}
|
||||
|
||||
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
|
||||
function onAuxClickCapture(e: MouseEvent) {
|
||||
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
|
||||
suppressNextAuxClick = false;
|
||||
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
|
||||
import.meta.hot?.accept((newModule) => {
|
||||
const carried = Array.from(listeners);
|
||||
|
||||
@@ -360,15 +360,11 @@ impl NodeNetwork {
|
||||
};
|
||||
let value_node_id = gen_id();
|
||||
let merged_node_id = map_ids(id, value_node_id);
|
||||
let mut original_location = OriginalLocation {
|
||||
path: Some(path.to_vec()),
|
||||
let original_location = OriginalLocation {
|
||||
dependants: vec![vec![id]],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Some(path) = &mut original_location.path {
|
||||
path.push(value_node_id);
|
||||
}
|
||||
collection.insert(
|
||||
merged_node_id,
|
||||
DocumentNode {
|
||||
|
||||
@@ -63,7 +63,6 @@ fn flatten_add_expected() -> NodeNetwork {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(4)]),
|
||||
dependants: vec![vec![NodeId(10)]],
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -155,24 +155,14 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
)
|
||||
};
|
||||
}
|
||||
// Keeps an adapter row under the identifier the preprocessor names it by and repeats it under the adapter node's own identifier,
|
||||
// which the new compiler selects by signature
|
||||
macro_rules! also_under_own_identifier {
|
||||
($module:ident, $row:expr) => {{
|
||||
let row: (ProtoNodeIdentifier, NodeConstructor, NodeIOTypes) = $row;
|
||||
let own = (graphene_core::ops::$module::IDENTIFIER, row.1, row.2.clone());
|
||||
[row, own]
|
||||
}};
|
||||
}
|
||||
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
||||
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
||||
macro_rules! input_adapter_row {
|
||||
(from_element: $from:ty, element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
also_under_own_identifier!(into_item, input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||
also_under_own_identifier!(into_list, input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||
]
|
||||
.concat();
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
||||
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
||||
@@ -264,7 +254,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
$(
|
||||
entries.extend(input_adapter_node!(element: $element));
|
||||
entries.extend(also_under_own_identifier!(item_to_list, item_to_list_node!(element: $element)));
|
||||
entries.push(item_to_list_node!(element: $element));
|
||||
)*
|
||||
entries
|
||||
}};
|
||||
@@ -369,10 +359,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
||||
macro_rules! list_dyn_rows {
|
||||
($($element:ty),* $(,)?) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
$(also_under_own_identifier!(into, input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn)),)*
|
||||
]
|
||||
.concat();
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)*
|
||||
];
|
||||
entries
|
||||
}};
|
||||
}
|
||||
@@ -405,8 +394,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
($($element:ty),* $(,)?) => {{
|
||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
$(
|
||||
entries.extend(also_under_own_identifier!(bundle, bundle_node!(element: $element)));
|
||||
entries.extend(also_under_own_identifier!(unbundle, unbundle_node!(element: $element)));
|
||||
entries.push(bundle_node!(element: $element));
|
||||
entries.push(unbundle_node!(element: $element));
|
||||
)*
|
||||
entries
|
||||
}};
|
||||
@@ -466,11 +455,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
|
||||
macro_rules! embed_adapter_row {
|
||||
(from_element: $from:ty, element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
also_under_own_identifier!(embed_item, input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||
also_under_own_identifier!(embed_list, input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||
]
|
||||
.concat();
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
||||
input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
}
|
||||
@@ -487,11 +475,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
||||
macro_rules! convert_adapter_node {
|
||||
(from_element: $from:ty, element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
also_under_own_identifier!(convert_item, input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||
also_under_own_identifier!(convert_list, input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||
]
|
||||
.concat();
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
||||
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
}
|
||||
@@ -513,19 +500,13 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
||||
macro_rules! attribute_value_node {
|
||||
(Item<$element:ty>) => {
|
||||
also_under_own_identifier!(
|
||||
item_to_attribute_value,
|
||||
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
)
|
||||
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
};
|
||||
(List<$element:ty>) => {
|
||||
also_under_own_identifier!(
|
||||
list_to_attribute_value,
|
||||
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
)
|
||||
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
};
|
||||
}
|
||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
attribute_value_node!(Item<f64>),
|
||||
attribute_value_node!(Item<i64>),
|
||||
attribute_value_node!(Item<bool>),
|
||||
@@ -550,8 +531,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(List<Raster<GPU>>),
|
||||
attribute_value_node!(List<Graphic>),
|
||||
attribute_value_node!(List<Artboard>),
|
||||
]
|
||||
.concat();
|
||||
];
|
||||
node_types.extend(attribute_value_rows);
|
||||
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
||||
macro_rules! transform_list_node {
|
||||
|
||||
@@ -29,17 +29,6 @@ pub struct NodeFlags {
|
||||
pub forwards_input: bool,
|
||||
pub inject_scope: bool,
|
||||
pub asynchronous: bool,
|
||||
/// Whether type resolution may insert this node on an edge, from `#[node_macro::node(adapter(...))]`.
|
||||
pub adapter: Option<AdapterKind>,
|
||||
}
|
||||
|
||||
/// How an adapter node changes the wire it is inserted on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AdapterKind {
|
||||
/// Converts the wire's element into another element type.
|
||||
Conversion,
|
||||
/// Changes the wire's rank, like raising an `Item` onto a `List`.
|
||||
Rank,
|
||||
}
|
||||
|
||||
// Translation struct between macro and definition
|
||||
|
||||
@@ -3,7 +3,6 @@ use crate::vector::flatten::WorkingVector;
|
||||
use crate::vector::misc::{BezierHandles, HandleId, HandleType};
|
||||
use crate::vector::path::{CurveType, Path, curve_types_of};
|
||||
use core_types::list::{ATTR_ID, List};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DVec2;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
@@ -1086,16 +1085,49 @@ impl VectorModification {
|
||||
}
|
||||
}
|
||||
|
||||
// Intentionally non-deterministic: fields contain HashMaps with non-deterministic iteration order,
|
||||
// so we use a UUID to always bust the cache and force re-evaluation when any modification is present.
|
||||
// This will not actually lead to a cache invalidation in most cases due to the
|
||||
// graph inputs being wrapped in a `MemoHash` wrapper.
|
||||
// Hash sets and maps are hashed in key order, so equal modifications hash equally regardless of iteration order
|
||||
impl graphene_hash::CacheHash for PointModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.add.cache_hash(state);
|
||||
sorted_set(&self.remove).cache_hash(state);
|
||||
sorted_map(&self.delta).cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for SegmentModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.add.cache_hash(state);
|
||||
sorted_set(&self.remove).cache_hash(state);
|
||||
sorted_map(&self.start_point).cache_hash(state);
|
||||
sorted_map(&self.end_point).cache_hash(state);
|
||||
sorted_map(&self.handle_primary).cache_hash(state);
|
||||
sorted_map(&self.handle_end).cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for VectorModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
core::hash::Hash::hash(&generate_uuid(), state);
|
||||
self.points.cache_hash(state);
|
||||
self.segments.cache_hash(state);
|
||||
sorted_set(&self.add_g1_continuous).cache_hash(state);
|
||||
sorted_set(&self.remove_g1_continuous).cache_hash(state);
|
||||
sorted_set(&self.path_breaks).cache_hash(state);
|
||||
sorted_set(&self.turned_on_load).cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted_set<T: Ord>(set: &HashSet<T>) -> Vec<&T> {
|
||||
let mut items: Vec<_> = set.iter().collect();
|
||||
items.sort_unstable();
|
||||
items
|
||||
}
|
||||
|
||||
fn sorted_map<K: Ord, V>(map: &HashMap<K, V>) -> Vec<(&K, &V)> {
|
||||
let mut entries: Vec<_> = map.iter().collect();
|
||||
entries.sort_unstable_by_key(|&(key, _)| key);
|
||||
entries
|
||||
}
|
||||
|
||||
// TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples?
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Serializes as sorted `[[key, value], ...]` (sequence of pairs)
|
||||
@@ -1263,6 +1295,23 @@ mod tests {
|
||||
format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}")
|
||||
}
|
||||
|
||||
fn cache_hash(modification: &VectorModification) -> u64 {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
graphene_hash::CacheHash::cache_hash(modification, &mut hasher);
|
||||
std::hash::Hasher::finish(&hasher)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_modifications_hash_equally() {
|
||||
let (vector, paths) = mixed_geometry();
|
||||
|
||||
let first = VectorModification::create_from_vector(&vector, &paths);
|
||||
let second = VectorModification::create_from_vector(&vector, &paths);
|
||||
|
||||
assert_eq!(cache_hash(&first), cache_hash(&first));
|
||||
assert_eq!(cache_hash(&first), cache_hash(&second));
|
||||
}
|
||||
|
||||
/// Every curve type, a weld where they change, a smooth anchor, and a second subpath.
|
||||
fn mixed_geometry() -> (Vector, List<Path>) {
|
||||
let mut bezpath = BezPath::new();
|
||||
|
||||
@@ -838,14 +838,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
footprint_invariant,
|
||||
forwards_input,
|
||||
inject_scope,
|
||||
adapter,
|
||||
..
|
||||
} = attributes.flags;
|
||||
let adapter = match adapter {
|
||||
Some(AdapterKind::Conversion) => quote!(Some(gcore::registry::AdapterKind::Conversion)),
|
||||
Some(AdapterKind::Rank) => quote!(Some(gcore::registry::AdapterKind::Rank)),
|
||||
None => quote!(None),
|
||||
};
|
||||
let asynchronous = parsed.is_async;
|
||||
let version = attributes.version.unwrap_or(1);
|
||||
// A node returning a `Destructure` struct records its fields as output connectors
|
||||
@@ -1059,7 +1053,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
forwards_input: #forwards_input,
|
||||
inject_scope: #inject_scope,
|
||||
asynchronous: #asynchronous,
|
||||
adapter: #adapter,
|
||||
},
|
||||
version: #version,
|
||||
output_fields: #output_fields,
|
||||
|
||||
@@ -54,15 +54,6 @@ pub(crate) struct NodeFlags {
|
||||
pub(crate) no_partial: bool,
|
||||
/// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source.
|
||||
pub(crate) destructure_extractor: bool,
|
||||
/// Whether type resolution may insert this node on an edge, and how it changes the wire.
|
||||
pub(crate) adapter: Option<AdapterKind>,
|
||||
}
|
||||
|
||||
/// Mirrors `core_types::registry::AdapterKind`, which this proc-macro crate cannot depend on.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum AdapterKind {
|
||||
Conversion,
|
||||
Rank,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
@@ -566,25 +557,6 @@ impl Parse for NodeFnAttributes {
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., forwards_input, ...)]
|
||||
"forwards_input" => set_flag(&mut flags.forwards_input, meta, "forwards_input")?,
|
||||
// Marks the node as an adapter that type resolution may insert on an edge, either converting the wire's element type or changing its rank.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., adapter(conversion), ...)]
|
||||
// #[node_macro::node(..., adapter(rank), ...)]
|
||||
"adapter" => {
|
||||
let meta = meta.require_list()?;
|
||||
if flags.adapter.is_some() {
|
||||
return Err(Error::new_spanned(meta, "Multiple 'adapter' attributes are not allowed"));
|
||||
}
|
||||
let kind: Ident = meta
|
||||
.parse_args()
|
||||
.map_err(|_| Error::new_spanned(meta, "Expected 'conversion' or 'rank' for 'adapter', e.g., adapter(rank)"))?;
|
||||
flags.adapter = Some(match kind.to_string().as_str() {
|
||||
"conversion" => AdapterKind::Conversion,
|
||||
"rank" => AdapterKind::Rank,
|
||||
_ => return Err(Error::new_spanned(kind, "Expected 'conversion' or 'rank' for 'adapter', e.g., adapter(rank)")),
|
||||
});
|
||||
}
|
||||
// Instructs the preprocessor to make this node available as a scope.
|
||||
// Other nodes can then access it with `#[scope(node::IDENTIFIER)]`.
|
||||
//
|
||||
@@ -632,7 +604,7 @@ impl Parse for NodeFnAttributes {
|
||||
indoc!(
|
||||
r#"
|
||||
Unsupported attribute in `node`.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'adapter', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
|
||||
Example usage:
|
||||
#[node_macro::node(..., name("Test Node"), ...)]
|
||||
"#
|
||||
|
||||
@@ -13,19 +13,19 @@ fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
|
||||
}
|
||||
|
||||
/// Shifts a whole wire value onto a connector's type through the std `Into` trait, serving the whole-`List` erasure onto `ListDyn` under the input adapter identifier.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O {
|
||||
value.into()
|
||||
}
|
||||
|
||||
/// Raises an `Item` wire onto a `List` connector as its one-element list.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn item_to_list<'i, T: 'i + Send>(_: impl Ctx, value: Item<T>) -> List<T> {
|
||||
value.into()
|
||||
}
|
||||
|
||||
/// Boxes a ranked wire's element into a type-erased attribute value, carrying the cell's attributes through the wire.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
|
||||
_: impl Ctx,
|
||||
value: Item<T>,
|
||||
@@ -36,7 +36,7 @@ fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt:
|
||||
}
|
||||
|
||||
/// Boxes a whole `List` wire as one type-erased attribute value, for attributes whose per-item value is itself a collection.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
|
||||
_: impl Ctx,
|
||||
value: T,
|
||||
@@ -46,27 +46,27 @@ fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt:
|
||||
}
|
||||
|
||||
/// Wraps a whole `List` onto the wire as one rank-0 `Item<Bundle<T>>` so an entire collection can feed a connector that carries it as one opaque cell.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn bundle<'i, T: 'i + Send>(_: impl Ctx, value: List<T>) -> Item<Bundle<T>> {
|
||||
Item::new_from_element(Bundle(value))
|
||||
}
|
||||
|
||||
/// Unwraps a `Bundle` wire back into the whole `List` it carries, restoring the collection after it passed through a connector as one opaque cell.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn unbundle<'i, T: 'i + Send>(_: impl Ctx, value: Item<Bundle<T>>) -> List<T> {
|
||||
value.into_element().0
|
||||
}
|
||||
|
||||
/// Converts an `Item` wire's element to a different element type it can produce through the std `Into` trait,
|
||||
/// letting a convertible wire feed an `Item` connector whose element type it does not match by identity.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn into_item<'i, T: 'i + Send + Into<E>, E: 'i + Send>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
Item::from_parts(value.into(), attributes)
|
||||
}
|
||||
|
||||
/// The `List` counterpart of `into_item`, converting every element to a different element type it can produce.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
|
||||
value
|
||||
.into_iter()
|
||||
@@ -79,19 +79,19 @@ fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, valu
|
||||
|
||||
/// Moves a whole `Item` wire inside an element type like `Graphic` that embeds ranked values as its variants.
|
||||
/// The attributes describe the element they arrived with, so they travel inside it and the fresh envelope starts empty.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn embed_item<'i, T: 'i + Send, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
|
||||
Item::new_from_element(value.into())
|
||||
}
|
||||
|
||||
/// The `List` counterpart of `embed_item`, each item moving whole inside its own embedding element.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn embed_list<'i, T: 'i + Send + Clone, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
|
||||
value.into_iter().map(|item| Item::new_from_element(E::from(item))).collect()
|
||||
}
|
||||
|
||||
/// The [`Convert`]-based counterpart of `into_item`, casting an `Item` wire's element to a connector's numeric element type.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
|
||||
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -100,7 +100,7 @@ fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx +
|
||||
}
|
||||
|
||||
/// The `List` counterpart of `convert_item`, casting every element to the connector's numeric element type.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn convert_list<'i, T: 'i + Send + Clone + Convert<E, ()>, E: 'i + Send + Clone>(ctx: impl Ctx + ExtractFootprint, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
|
||||
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
|
||||
|
||||
|
||||
@@ -206,7 +206,6 @@ impl Preprocessor {
|
||||
forwards_input,
|
||||
inject_scope,
|
||||
asynchronous,
|
||||
adapter: _,
|
||||
},
|
||||
output_fields,
|
||||
context_features,
|
||||
|
||||
Reference in new issue
Block a user