### Import SwiftFlow Source: https://github.com/aaurelions/swiftflow/blob/main/docs/guide/installation.md Imports the SwiftFlow module in any file that uses the library. ```swift import SwiftFlow ``` -------------------------------- ### Quick Start (AI-Agent Flow) Source: https://github.com/aaurelions/swiftflow/blob/main/SKILL.md Basic SwiftFlow setup with nodes, edges, and canvas rendering. Requires iOS 17.0+, macOS 13.0+, Swift 6.1+. Uses @State for nodes and edges, applyNodeChanges/applyEdgeChanges for updates, and addEdge for connections. The overlay adds Background, Controls, and MiniMap. ```swift import SwiftUI import SwiftFlow // 1. Define state @State var nodes: [Node] = [ Node(id: "1", position: XYPosition(x: 0, y: 0), data: "Input"), Node(id: "2", position: XYPosition(x: 250, y: 100), data: "Output"), ] @State var edges: [FlowEdge] = [ FlowEdge(id: "e1-2", source: "1", target: "2"), ] // 2. Render canvas SwiftFlow( nodes: nodes, edges: edges, onNodesChange: { nodes = applyNodeChanges($0, nodes: nodes) }, onEdgesChange: { edges = applyEdgeChanges($0, edges: edges) }, onConnect: { edges = addEdge($0, edges: edges) } ) { node in Text(node.data).padding().background(.white).cornerRadius(8) } overlay: { Background(variant: .dots) Controls() MiniMap() } ``` -------------------------------- ### Preview for StateManagementExample Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/state-management.md SwiftUI preview for the state management example. ```swift // MARK: - Preview #Preview { StateManagementExample() } ``` -------------------------------- ### Basic Setup: FlowEditor View with Nodes and Edges Source: https://github.com/aaurelions/swiftflow/blob/main/docs/guide/getting-started.md Create a SwiftUI view that owns graph state and renders the canvas. It defines nodes and edges, and passes change handlers to SwiftFlow to update state. ```swift import SwiftUI import SwiftFlow struct FlowEditor: View { @State var nodes: [Node] = [ Node(id: "1", position: XYPosition(x: 100, y: 100), data: "Start"), Node(id: "2", position: XYPosition(x: 300, y: 100), data: "Process"), Node(id: "3", position: XYPosition(x: 500, y: 100), data: "End"), ] @State var edges: [FlowEdge] = [ FlowEdge(id: "e1-2", source: "1", target: "2"), FlowEdge(id: "e2-3", source: "2", target: "3"), ] var body: some View { SwiftFlow( nodes: nodes, edges: edges, onNodesChange: { changes in nodes = applyNodeChanges(changes, nodes: nodes) }, onEdgesChange: { changes in edges = applyEdgeChanges(changes, edges: edges) }, onConnect: { connection in edges = addEdge(connection, edges: edges) } ) { node in Text(node.data) .padding(.horizontal, 16) .padding(.vertical, 10) .background(RoundedRectangle(cornerRadius: 8).fill(.white)) .overlay(RoundedRectangle(cornerRadius: 8).stroke(.gray, lineWidth: 1.5)) .shadow(color: .black.opacity(0.1), radius: 2) } } } ``` -------------------------------- ### SwiftUI preview for custom nodes example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/custom-nodes.md Provides a preview for the custom nodes example, instantiating CustomNodesExample(). ```swift #Preview { CustomNodesExample() } ``` -------------------------------- ### Preview for serialization example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/serialization.md SwiftUI preview that displays the SerializationExample view. Used for interactive development in Xcode. ```swift // MARK: - Preview #Preview { SerializationExample() } ``` -------------------------------- ### onInit Usage Example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/callbacks.md Example usage of onInit to load a saved graph when the canvas finishes initializing. ```swift onInit: { loadSavedGraph() } ``` -------------------------------- ### Usage example: highlight connected nodes Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/graph-utilities.md Shows how to get incoming and outgoing nodes for a selected node and collect their IDs into a set. ```swift // Highlight all nodes connected to the selected node @State var connectedIds: Set = [] func updateConnectedNodes() { guard let selected = nodes.first(where: \.selected) else { return } let incomers = getIncomers(node: selected, nodes: nodes, edges: edges) let outgoers = getOutgoers(node: selected, nodes: nodes, edges: edges) connectedIds = Set(incomers.map(\.id) + outgoers.map(\.id)) } ``` -------------------------------- ### #Preview - AutoLayoutExample Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/auto-layout.md SwiftUI preview for the AutoLayoutExample view, allowing live switching between layout types. ```swift // MARK: - Preview #Preview { AutoLayoutExample() } ``` -------------------------------- ### ViewportControlsExample with SwiftFlowInstance and viewport controls Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/viewport-controls.md SwiftUI example demonstrating imperative viewport control with SwiftFlowInstance: fitView, zoomIn/zoomOut, reset, coordinate conversion, and hover tracking. Includes a toolbar with zoom percentage, MiniMap, and custom node position panel. ```swift // Display node positions in flow coords Panel(position: .topLeft) { VStack(alignment: .leading, spacing: 2) { Text("Node Positions").font(.caption2).bold() ForEach(nodes.prefix(5), id: \.id) { node in Text("\(node.id): (x:\(Int(node.position.x)), y:\(Int(node.position.y)))") .font(.system(size: 9, design: .monospaced)) } } .padding(6) .background(.ultraThinMaterial) .cornerRadius(6) } } .onContinuousHover { phase in switch phase { case .active(let location): let flowPos = instance.screenToFlowPosition(location) hoverFlowPoint = String(format: "(%.0f, %.0f)", flowPos.x, flowPos.y) let screenPos = instance.flowToScreenPosition(flowPos) flowToScreenInfo = String(format: "(%.0f, %.0f)", screenPos.x, screenPos.y) case .ended: hoverFlowPoint = "—" flowToScreenInfo = "—" } } } .frame(maxWidth: .infinity, maxHeight: .infinity) } } // MARK: - Preview #Preview { ViewportControlsExample() } ``` -------------------------------- ### getOutgoers usage example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/graph-utilities.md Shows how to call getOutgoers to get successor nodes. ```swift let successors = getOutgoers(node: myNode, nodes: nodes, edges: edges) ``` -------------------------------- ### SwiftUI Auto Layout Example with Tree, Force, Grid, and Left-to-Right Layouts Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/auto-layout.md Complete SwiftUI example demonstrating all three layout algorithms (tree, force-directed, grid) plus a left-to-right tree variant, with live switching via buttons. Uses SwiftFlow's computeAutoLayout to apply the selected algorithm and includes a Reset button to restore the initial graph. The SwiftFlow view renders custom nodes with handles, a dotted background, controls, and a minimap. ```swift import SwiftUI import SwiftFlow // MARK: - Data Models struct LayoutNodeData: Equatable, Sendable, Codable { var label: String } // MARK: - Content View struct AutoLayoutExample: View { @State var nodes: [Node] = makeInitialNodes() @State var edges: [FlowEdge] = makeInitialEdges() @State var activeLayout: String = "tree" var body: some View { VStack(spacing: 0) { // Layout selector HStack(spacing: 8) { Text("Layout:") .font(.caption).foregroundColor(.secondary) layoutButton("Tree", "tree") layoutButton("Force", "force") layoutButton("Grid", "grid") layoutButton("L→R", "leftright") Spacer() Button("Reset") { nodes = makeInitialNodes() edges = makeInitialEdges() } .buttonStyle(.bordered) .controlSize(.small) } .padding(.horizontal) .padding(.vertical, 8) .background(.ultraThinMaterial) SwiftFlow( nodes: nodes, edges: edges, onNodesChange: { nodes = applyNodeChanges($0, nodes: nodes) }, onEdgesChange: { edges = applyEdgeChanges($0, edges: edges) }, onConnect: { edges = addEdge($0, edges: edges, defaults: DefaultEdgeOptions( type: .smoothstep, markerEnd: .arrowClosed )) }, fitView: true, fitViewOptions: FitViewOptions(padding: 60, maxZoom: 2.0, duration: 0.4) ) { node in HStack(spacing: 0) { Handle(nodeId: node.id, id: "in", type: .target, position: .left) Text(node.data.label) .font(.system(size: 12)) .padding(.horizontal, 12) .padding(.vertical, 8) Handle(nodeId: node.id, id: "out", type: .source, position: .right) } .background( RoundedRectangle(cornerRadius: 6) .fill(.white) .shadow(color: .black.opacity(0.06), radius: 2, y: 1) ) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(node.selected ? .blue : .gray.opacity(0.3), lineWidth: 1) ) } overlay: { Background(variant: .dots, gap: 30) Controls(position: .bottomLeft) MiniMap() } } .frame(maxWidth: .infinity, maxHeight: .infinity) } // MARK: - Layout Buttons func layoutButton(_ title: String, _ id: String) -> some View { Button(title) { activeLayout = id applyLayout(id) } .buttonStyle(.borderedProminent) .controlSize(.small) .tint(activeLayout == id ? .blue : .gray.opacity(0.3)) } func applyLayout(_ id: String) { let algorithm: LayoutAlgorithm switch id { case "tree": algorithm = .tree(direction: .topToBottom, nodeSpacing: 60, levelSpacing: 120) case "force": algorithm = .forceDirected(iterations: 120, idealLength: 200, repulsion: 6000) case "grid": algorithm = .grid(columns: 4, nodeSpacing: 80) case "leftright": algorithm = .tree(direction: .leftToRight, nodeSpacing: 60, levelSpacing: 150) default: return } let changes = computeAutoLayout( nodes: nodes, edges: edges, algorithm: algorithm ) nodes = applyNodeChanges(changes, nodes: nodes) } } // MARK: - Initial Graph func makeInitialNodes() -> [Node] { [ Node(id: "root", position: .zero, data: LayoutNodeData(label: "Root")), Node(id: "a1", position: .zero, data: LayoutNodeData(label: "Child A1")), Node(id: "a2", position: .zero, data: LayoutNodeData(label: "Child A2")), Node(id: "a3", position: .zero, data: LayoutNodeData(label: "Child A3")), Node(id: "b1", position: .zero, data: LayoutNodeData(label: "Child B1")), Node(id: "b2", position: .zero, data: LayoutNodeData(label: "Child B2")), Node(id: "c1", position: .zero, data: LayoutNodeData(label: "Leaf C1")), Node(id: "c2", position: .zero, data: LayoutNodeData(label: "Leaf C2")), Node(id: "c3", position: .zero, data: LayoutNodeData(label: "Leaf C3")), Node(id: "orphan", position: .zero, data: LayoutNodeData(label: "Orphan")), ] } ``` -------------------------------- ### Create demo nodes for serialization example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/serialization.md Defines a function that returns an array of Node with four nodes representing services (Auth, Database, Cache, API Gateway). Each node includes position, label, value, and configuration data. ```swift func makeDemoNodes() -> [Node] { [ Node(id: "n1", position: XYPosition(x: 100, y: 150), data: SerNodeData(label: "Auth Service", value: "v2.1.0", config: NodeConfig(color: "blue", shape: "rectangle", size: "large"))), Node(id: "n2", position: XYPosition(x: 400, y: 80), data: SerNodeData(label: "Database", value: "pg-14", config: NodeConfig(color: "green", shape: "rectangle", size: "medium"))), Node(id: "n3", position: XYPosition(x: 400, y: 220), data: SerNodeData(label: "Cache", value: "redis-7", config: NodeConfig(color: "red", shape: "circle", size: "small"))), Node(id: "n4", position: XYPosition(x: 650, y: 150), data: SerNodeData(label: "API Gateway", value: "v3.0.0", config: NodeConfig(color: "yellow", shape: "rectangle", size: "medium"))), ] } ``` -------------------------------- ### Resizable Nodes Example - SwiftUI View Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/resizable-nodes.md Defines the main example view with resizable nodes, edges, and a SwiftFlow canvas. It sets up node data models, initial nodes and edges, and configures the SwiftFlow view with snap-to-grid, node rendering, and overlay components. Includes handlers for node changes, edge changes, and connections, plus helper functions to duplicate and delete nodes while managing connected edges. ```swift import SwiftUI import SwiftFlow // MARK: - Data Models struct ResizeNodeData: Equatable, Sendable, Codable { var title: String var content: String } // MARK: - Content View struct ResizableNodesExample: View { @State var nodes: [Node] = [ Node( id: "note1", position: XYPosition(x: 100, y: 100), data: ResizeNodeData(title: "Meeting Notes", content: "Discuss Q4 roadmap and resource allocation for the engineering team."), type: "note", width: 240, height: 160 ), Node( id: "note2", position: XYPosition(x: 400, y: 100), data: ResizeNodeData(title: "Action Items", content: "1. Update API schema\n2. Fix edge rendering\n3. Write unit tests\n4. Deploy to staging"), type: "note", width: 200, height: 200 ), Node( id: "card1", position: XYPosition(x: 100, y: 350), data: ResizeNodeData(title: "Product Card", content: "Price: $29.99\nIn stock: Yes\nSKU: PROD-001"), type: "card", width: 220, height: 130 ), ] @State var edges: [FlowEdge] = [ FlowEdge(id: "e1", source: "note1", target: "note2", type: .smoothstep, markerEnd: .arrowClosed), FlowEdge(id: "e2", source: "note2", target: "card1", type: .smoothstep, markerEnd: .arrowClosed), ] var body: some View { SwiftFlow( nodes: nodes, edges: edges, onNodesChange: { nodes = applyNodeChanges($0, nodes: nodes) }, onEdgesChange: { edges = applyEdgeChanges($0, edges: edges) }, onConnect: { edges = addEdge($0, edges: edges) }, snapToGrid: true, snapGrid: (x: 10, y: 10) ) { node in ResizableNodeView(node: node, onResize: { w, h in nodes = applyNodeChanges([ .dimensions(id: node.id, width: w, height: h) ], nodes: nodes) }, onDuplicate: { duplicateNode(node) }, onDelete: { deleteNode(node) } ) } overlay: { Background(variant: .lines, color: .gray.opacity(0.1), gap: 40) Controls() MiniMap() } .frame(maxWidth: .infinity, maxHeight: .infinity) } func duplicateNode(_ node: Node) { var copy = node copy.id = "\(node.id)-copy-\(nodes.count)" copy.position = XYPosition(x: node.position.x + 40, y: node.position.y + 40) copy.selected = false nodes = applyNodeChanges([.add(item: copy)], nodes: nodes) } func deleteNode(_ node: Node) { let connectedEdgeIds = edges .filter { $0.source == node.id || $0.target == node.id } .map(\.id) nodes = applyNodeChanges([.remove(id: node.id)], nodes: nodes) edges = applyEdgeChanges(connectedEdgeIds.map { .remove(id: $0) }, edges: edges) } } ``` -------------------------------- ### Force-directed usage example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/auto-layout.md Example of using the force-directed algorithm with custom parameters. Zero or negative iterations leave positions unchanged; more iterations improve layout quality but take longer. Async variant recommended for large graphs. ```swift let changes = computeAutoLayout(nodes: nodes, edges: edges, algorithm: .forceDirected(iterations: 200, idealLength: 150, repulsion: 8000)) ``` -------------------------------- ### Tree layout usage examples Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/auto-layout.md Examples of using the tree algorithm with different directions and custom spacing. Shows top-to-bottom, left-to-right, and custom spacing configurations. ```swift // Top-to-bottom flow let changes = computeAutoLayout(nodes: nodes, edges: edges, algorithm: .tree(direction: .topToBottom)) // Left-to-right flow let changes = computeAutoLayout(nodes: nodes, edges: edges, algorithm: .tree(direction: .leftToRight)) // With custom spacing let changes = computeAutoLayout(nodes: nodes, edges: edges, algorithm: .tree(direction: .topToBottom, nodeSpacing: 80, levelSpacing: 200)) ``` -------------------------------- ### SwiftUI Serialization Example with SwiftFlow Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/serialization.md Full graph serialization example: JSON export, import, file save/load, clipboard copy/paste, and Codable data models. Includes UI with toolbar, canvas, and JSON preview sidebar. ```swift import SwiftUI import SwiftFlow import UniformTypeIdentifiers // MARK: - Data Models (must be Codable for serialization) struct SerNodeData: Equatable, Sendable, Codable { var label: String var value: String var config: NodeConfig } struct NodeConfig: Equatable, Sendable, Codable { var color: String // "red", "blue", "green", "yellow" var shape: String // "circle", "rectangle", "diamond" var size: String // "small", "medium", "large" } struct SerEdgeData: Equatable, Sendable, Codable, Hashable { var relation: String // "depends_on", "references", "extends" var weight: Double var description: String } // MARK: - Content View struct SerializationExample: View { @State var nodes: [Node] = makeDemoNodes() @State var edges: [FlowEdge] = makeDemoEdges() @State var viewport: Viewport = .identity @State var statusMessage: String = "Ready" @State var jsonPreview: String = "" var body: some View { VStack(spacing: 0) { // Toolbar HStack(spacing: 8) { Text("Serialization Demo") .font(.headline) Spacer() Button("Save") { saveToDisk() } .buttonStyle(.borderedProminent) .controlSize(.small) Button("Load") { loadFromDisk() } .buttonStyle(.bordered) .controlSize(.small) Divider().frame(height: 20) Button("Export JSON") { exportJSON() } .buttonStyle(.bordered) .controlSize(.small) Button("Copy JSON") { copyJSON() } .buttonStyle(.bordered) .controlSize(.small) Button("Reset") { nodes = makeDemoNodes() edges = makeDemoEdges() statusMessage = "Reset to defaults" } .buttonStyle(.bordered) .controlSize(.small) .tint(.orange) } .padding(.horizontal, 12) .padding(.vertical, 8) .background(.ultraThinMaterial) HStack(spacing: 0) { // Canvas SwiftFlow( nodes: nodes, edges: edges, onNodesChange: { nodes = applyNodeChanges($0, nodes: nodes) }, onEdgesChange: { edges = applyEdgeChanges($0, edges: edges) }, onConnect: { edges = addEdge($0, edges: edges) }, onViewportChange: { viewport = $0 } ) { node in SerNodeView(node: node) } overlay: { Background(variant: .dots, gap: 25) Controls(position: .bottomLeft) MiniMap() } .frame(maxWidth: .infinity, maxHeight: .infinity) // JSON preview sidebar if !jsonPreview.isEmpty { VStack(alignment: .leading, spacing: 4) { HStack { Text("JSON Preview") .font(.caption.bold()) Spacer() Button("✕") { jsonPreview = "" } .buttonStyle(.plain) .font(.caption) } .padding(.horizontal, 8) .padding(.top, 6) ScrollView { Text(jsonPreview) .font(.system(size: 9, design: .monospaced)) .foregroundColor(.primary) .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) .padding(8) } } .frame(width: 280) .background(Color(white: 0.12)) } } } .frame(minWidth: 800, minHeight: 500) .overlay(alignment: .bottom) { Text(statusMessage) .font(.caption) .padding(.horizontal, 12) .padding(.vertical, 4) .background(.ultraThinMaterial) .cornerRadius(4) .padding(8) } } // MARK: - Serialization Actions ``` -------------------------------- ### Creating edges examples Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/models.md Shows three ways to create edges: basic, styled with arrowhead and label, and with custom data. ```swift // Basic edge let edge = FlowEdge(id: "e1", source: "1", target: "2") ``` ```swift // Styled edge with arrowhead and label let edge = FlowEdge( id: "e1-2", source: "1", target: "2", sourceHandle: "out", targetHandle: "in", type: .smoothstep, label: "flows to", animated: true, markerEnd: EdgeMarker(type: .arrowClosed) ) ``` ```swift // Edge with custom data struct FlowData: Equatable, Sendable, Codable, Hashable { var weight: Double } let edge = Edge( id: "e1", source: "1", target: "2", data: FlowData(weight: 1.0) ) ``` -------------------------------- ### EdgeStyle example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/guide/theming.md Defines a FlowEdge with custom styling that overrides theme defaults. Properties include strokeColor, strokeWidth, and opacity. ```swift let styledEdge = FlowEdge( id: "styled-edge", source: "1", target: "2", style: EdgeStyle( strokeColor: .purple, strokeWidth: 3, opacity: 0.8 ) ) ``` -------------------------------- ### Create demo edges for serialization example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/serialization.md Defines a function that returns an array of FlowEdge with four edges connecting the demo nodes. Each edge specifies source/target, type, label, marker end, and data including relation, weight, and description. ```swift func makeDemoEdges() -> [FlowEdge] { [ FlowEdge(id: "e1", source: "n1", target: "n2", type: .smoothstep, label: "depends_on", markerEnd: .arrowClosed, data: SerEdgeData(relation: "depends_on", weight: 1.0, description: "Auth requires database")), FlowEdge(id: "e2", source: "n1", target: "n3", type: .smoothstep, label: "uses", markerEnd: .arrowClosed, data: SerEdgeData(relation: "references", weight: 0.5, description: "Auth uses cache")), FlowEdge(id: "e3", source: "n2", target: "n4", type: .smoothstep, label: "feeds", markerEnd: .arrowClosed, data: SerEdgeData(relation: "depends_on", weight: 1.0, description: "Gateway reads from database")), FlowEdge(id: "e4", source: "n3", target: "n4", type: .smoothstep, label: "feeds", markerEnd: .arrowClosed, data: SerEdgeData(relation: "depends_on", weight: 0.8, description: "Gateway reads from cache")), ] } ``` -------------------------------- ### SwiftUI viewport controls with SwiftFlowInstance Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/viewport-controls.md Shows programmatic viewport control using SwiftFlowInstance: fit-to-view, zoom, center, coordinate conversion, and auto-fit on load. Includes data models, node/edge setup, toolbar buttons, and a SwiftFlow canvas with fitView, zoomIn/zoomOut, reset, and coordinate info. ```swift import SwiftUI import SwiftFlow // MARK: - Data Models struct VPNodeData: Equatable, Sendable, Codable { var label: String } // MARK: - Content View struct ViewportControlsExample: View { @State var nodes: [Node] = [ Node(id: "1", position: XYPosition(x: -200, y: -100), data: VPNodeData(label: "Top-Left")), Node(id: "2", position: XYPosition(x: 400, y: -100), data: VPNodeData(label: "Top-Right")), Node(id: "3", position: XYPosition(x: -200, y: 300), data: VPNodeData(label: "Bottom-Left")), Node(id: "4", position: XYPosition(x: 400, y: 300), data: VPNodeData(label: "Bottom-Right")), Node(id: "5", position: XYPosition(x: 100, y: 100), data: VPNodeData(label: "Center")), ] @State var edges: [FlowEdge] = [ FlowEdge(id: "e1", source: "5", target: "1", type: .bezier, markerEnd: .arrowClosed), FlowEdge(id: "e2", source: "5", target: "2", type: .bezier, markerEnd: .arrowClosed), FlowEdge(id: "e3", source: "5", target: "3", type: .bezier, markerEnd: .arrowClosed), FlowEdge(id: "e4", source: "5", target: "4", type: .bezier, markerEnd: .arrowClosed), ] @StateObject var instance = SwiftFlowInstance() @State var hoverFlowPoint: String = "—" @State var flowToScreenInfo: String = "—" var body: some View { VStack(spacing: 0) { // Viewport control toolbar HStack(spacing: 6) { Button("Fit All") { instance.fitView(nodes: nodes, nodeSizes: instance.nodeSizes) } .buttonStyle(.bordered) Button("Fit Center") { let options = FitViewOptions( padding: 100, maxZoom: 3.0, duration: 0.6, nodeIds: ["5"] ) instance.fitView(nodes: nodes, nodeSizes: instance.nodeSizes, options: options) } .buttonStyle(.bordered) Divider().frame(height: 20) Button(action: { instance.zoomIn() }) { Image(systemName: "plus.magnifyingglass") } .buttonStyle(.bordered) Button(action: { instance.zoomOut() }) { Image(systemName: "minus.magnifyingglass") } .buttonStyle(.bordered) Text(String(format: "%.0f%%", instance.viewport.zoom * 100)) .font(.caption.monospaced()) .frame(minWidth: 40) Divider().frame(height: 20) Button(action: { instance.reset() }) { Image(systemName: "arrow.counterclockwise") } .buttonStyle(.bordered) Spacer() // Coordinate info VStack(alignment: .trailing, spacing: 2) { Text("Flow → Screen: \(flowToScreenInfo)") .font(.system(size: 9, design: .monospaced)) Text("Hover Flow: \(hoverFlowPoint)") .font(.system(size: 9, design: .monospaced)) } .foregroundColor(.secondary) } .padding(.horizontal, 10) .padding(.vertical, 6) .background(.ultraThinMaterial) SwiftFlow( nodes: nodes, edges: edges, onNodesChange: { nodes = applyNodeChanges($0, nodes: nodes) }, onEdgesChange: { edges = applyEdgeChanges($0, edges: edges) }, onConnect: { edges = addEdge($0, edges: edges) }, swiftFlowInstance: instance, fitView: true, fitViewOptions: FitViewOptions(padding: 80, maxZoom: 1.5, duration: 0.5) ) { node in Text(node.data.label) .font(.system(size: 13)) .padding(.horizontal, 14) .padding(.vertical, 8) .background( RoundedRectangle(cornerRadius: 8) .fill(.white) .shadow(color: .black.opacity(0.08), radius: 3, y: 1) ) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(.gray.opacity(0.3), lineWidth: 1) ) } overlay: { Background(variant: .dots, gap: 25) Controls(position: .bottomLeft) MiniMap() } } } } ``` -------------------------------- ### ConnectionNodeView with role-based handles Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/connection-validation.md SwiftUI view for a node in the connection validation example. It renders input/output handles based on the node's role (input, process, output) and colors them accordingly. Includes a preview using ConnectionValidationExample. ```swift struct ConnectionNodeView: View { let node: Node private var roleColor: Color { switch node.data.nodeRole { case "input": return .green case "process": return .blue case "output": return .orange default: return .gray } } var body: some View { HStack(spacing: 0) { // Input handles (for process and output nodes) if node.data.nodeRole != "input" { Handle( nodeId: node.id, id: "in", type: .target, position: .left, color: roleColor ) } VStack(spacing: 2) { Text(node.data.label) .font(.system(size: 12, weight: .semibold)) Text(node.data.nodeRole.uppercased()) .font(.system(size: 9)) .foregroundColor(roleColor) } .padding(.horizontal, 16) .padding(.vertical, 10) // Output handles (for input and process nodes) if node.data.nodeRole != "output" { Handle( nodeId: node.id, id: "out", type: .source, position: .right, color: roleColor ) } } .background( RoundedRectangle(cornerRadius: 8) .fill(.white) .shadow(color: .black.opacity(0.06), radius: 2, y: 1) ) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(node.selected ? Color.blue : Color.gray.opacity(0.3), lineWidth: node.selected ? 2 : 1) ) } } // MARK: - Preview #Preview { ConnectionValidationExample() } ``` -------------------------------- ### SwiftFlowStore state management example with programmatic node/edge manipulation Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/state-management.md Shows a complete SwiftUI view using SwiftFlowStore with typed node and edge data, programmatic node/edge manipulation, viewport control, and serialization. Includes toolbar actions for adding tasks, fitting the view, saving, and loading, plus a canvas with context menus, fitView options, and overlays like Background, Controls, MiniMap, and a legend Panel. ```swift import SwiftUI import SwiftFlow // MARK: - Data Models struct TaskData: Equatable, Sendable, Codable { var name: String var assignee: String var status: String // "pending", "active", "done" } struct TaskEdgeData: Equatable, Sendable, Codable, Hashable { var dependencyType: String // "blocking", "sequential", "optional" } // MARK: - Content View struct StateManagementExample: View { @StateObject var store = SwiftFlowStore( nodes: [ Node( id: "t1", position: XYPosition(x: 100, y: 100), data: TaskData(name: "Design API", assignee: "Alice", status: "done") ), Node( id: "t2", position: XYPosition(x: 400, y: 50), data: TaskData(name: "Implement Backend", assignee: "Bob", status: "active") ), Node( id: "t3", position: XYPosition(x: 400, y: 200), data: TaskData(name: "Build Frontend", assignee: "Charlie", status: "pending") ), Node( id: "t4", position: XYPosition(x: 700, y: 125), data: TaskData(name: "Integration Tests", assignee: "Alice", status: "pending") ), ], edges: [ FlowEdge( id: "e-t1-t2", source: "t1", target: "t2", data: TaskEdgeData(dependencyType: "blocking") ), FlowEdge( id: "e-t1-t3", source: "t1", target: "t3", data: TaskEdgeData(dependencyType: "sequential") ), FlowEdge( id: "e-t2-t4", source: "t2", target: "t4", data: TaskEdgeData(dependencyType: "blocking") ), FlowEdge( id: "e-t3-t4", source: "t3", target: "t4", data: TaskEdgeData(dependencyType: "blocking") ), ] ) var body: some View { VStack(spacing: 0) { // Toolbar HStack { Text("Task Dependency Graph") .font(.headline) Spacer() Button("Add Task") { addRandomTask() } Button("Fit All") { store.viewport = .identity // reset first // Fit is handled by MiniMap/Controls or instance } Button("Save") { saveGraph() } .disabled(!store.nodesInitialized) Button("Load") { loadGraph() } } .padding() .background(.ultraThinMaterial) Divider() // Canvas SwiftFlow( nodes: store.nodes, edges: store.edges, onNodesChange: { store.onNodesChange($0) }, onEdgesChange: { store.onEdgesChange($0) }, onConnect: { connection in store.onConnect( connection, defaults: DefaultEdgeOptions( type: .smoothstep, markerEnd: EdgeMarker(type: .arrowClosed) ) ) }, onNodeContextMenu: { node in store.deleteElements(nodeIds: [node.id], edgeIds: []) }, onEdgeContextMenu: { edge in store.deleteElements(nodeIds: [], edgeIds: [edge.id]) }, fitView: true, fitViewOptions: FitViewOptions(padding: 80, maxZoom: 1.5, duration: 0.5) ) { node in TaskNodeView(node: node) } overlay: { Background(variant: .dots, gap: 30) Controls(position: .bottomLeft) MiniMap(position: .bottomRight) // Status legend Panel(position: .topLeft) { VStack(alignment: .leading, spacing: 4) { Text("Legend").font(.caption).bold() HStack { Circle().fill(.green).frame(width: 8, height: 8); Text("Done").font(.caption) } HStack { Circle().fill(.blue).frame(width: 8, height: 8); Text("Active").font(.caption) } HStack { Circle().fill(.gray).frame(width: 8, height: 8); Text("Pending").font(.caption) } } .padding(8) .background(.ultraThinMaterial) .cornerRadius(8) } } } } ``` -------------------------------- ### Grid usage example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/auto-layout.md Example of using the grid algorithm with custom columns and spacing. Nodes are placed in row-major order; best for graphs without strong hierarchical structure. ```swift let changes = computeAutoLayout(nodes: nodes, edges: edges, algorithm: .grid(columns: 3, nodeSpacing: 60)) ``` -------------------------------- ### NodeStyle example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/guide/theming.md Defines a Node with custom styling that overrides theme defaults. Properties include backgroundColor, borderColor, borderWidth, borderRadius, and opacity. ```swift let styledNode = Node( id: "styled", position: XYPosition(x: 100, y: 100), data: "Custom", style: NodeStyle( backgroundColor: .orange.opacity(0.2), borderColor: .orange, borderWidth: 2, borderRadius: 12, opacity: 0.9 ) ) ``` -------------------------------- ### onMoveStart / onMove / onMoveEnd usage for tracking movement Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/callbacks.md Example usage of the movement callbacks to show a grid on start, update cursor position during move, and hide the grid on end. ```swift onMoveStart: { _ in showGrid = true }, onMove: { vp in updateCursorPosition(vp) }, onMoveEnd: { _ in showGrid = false } ``` -------------------------------- ### makeInitialEdges() - Define flow edges for AI example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/examples/ai-flow.md Creates an array of FEdge objects connecting nodes in the AI flow. Used to set up the initial graph structure in ContentView.swift. ```swift func makeInitialEdges() -> [FEdge] { [ FEdge(id: "e3", source: "prompt", target: "openRouter", sourceHandle: "out", targetHandle: "prompt"), FEdge(id: "e4", source: "image", target: "openRouter", sourceHandle: "out", targetHandle: "image"), FEdge(id: "e5", source: "openRouter", target: "outText", sourceHandle: "text", targetHandle: "in"), FEdge(id: "e6", source: "openRouter", target: "outImage", sourceHandle: "image", targetHandle: "in"), FEdge(id: "m1", source: "mInKey", target: "scriptAuth", sourceHandle: "out", targetHandle: "in1"), FEdge(id: "m2", source: "mInModel", target: "scriptBody", sourceHandle: "out", targetHandle: "in1"), FEdge(id: "m3", source: "mInImage", target: "scriptBody", sourceHandle: "out", targetHandle: "in2"), FEdge(id: "m4", source: "mInPrompt", target: "scriptBody", sourceHandle: "out", targetHandle: "in3"), FEdge(id: "m13", source: "mConns", target: "scriptBody", sourceHandle: "out", targetHandle: "in4"), FEdge(id: "m5", source: "mMethod", target: "httpReq", sourceHandle: "out", targetHandle: "method"), FEdge(id: "m6", source: "mUrl", target: "httpReq", sourceHandle: "out", targetHandle: "url"), FEdge(id: "m7", source: "scriptAuth", target: "httpReq", sourceHandle: "out", targetHandle: "headers"), FEdge(id: "m8", source: "scriptBody", target: "httpReq", sourceHandle: "out", targetHandle: "body"), FEdge(id: "m9", source: "httpReq", target: "pathText", sourceHandle: "out", targetHandle: "json"), FEdge(id: "m10", source: "httpReq", target: "pathImage", sourceHandle: "out", targetHandle: "json"), FEdge(id: "m11", source: "pathText", target: "mOutText", sourceHandle: "out", targetHandle: "in"), FEdge(id: "m12", source: "pathImage", target: "mOutImage", sourceHandle: "out", targetHandle: "in"), ] } ``` -------------------------------- ### getNodeConnections usage examples Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/swiftflow-store.md Shows how to fetch all connections, incoming only (handleType: .target), and outgoing only (handleType: .source) for a node. ```swift // All connections let all = store.getNodeConnections(nodeId: "node-1") // Incoming only (edges pointing to this node) let incoming = store.getNodeConnections(nodeId: "node-1", handleType: .target) // Outgoing only (edges from this node) let outgoing = store.getNodeConnections(nodeId: "node-1", handleType: .source) ``` -------------------------------- ### getConnectedEdges usage examples Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/graph-utilities.md Shows how to call both overloads of getConnectedEdges. ```swift let connected = getConnectedEdges(node: myNode, edges: edges) ``` ```swift let allConnected = getConnectedEdges(nodes: selectedNodes, edges: edges) ``` -------------------------------- ### getIncomers usage example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/graph-utilities.md Shows how to call getIncomers and print the count of incoming edges. ```swift let predecessors = getIncomers(node: myNode, nodes: nodes, edges: edges) print("\(myNode.id) has \(predecessors.count) incoming edges") ``` -------------------------------- ### onInit Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/callbacks.md Callback that fires once when the canvas finishes initializing. Useful for loading saved graphs or performing setup. ```APIDOC ## Callback: onInit ### Description Fires once when the canvas finishes initializing. ### Signature ```swift onInit: (() -> Void)? ``` ### Example ```swift onInit: { loadSavedGraph() } ``` ``` -------------------------------- ### getNodesData(ids:) usage example Source: https://github.com/aaurelions/swiftflow/blob/main/docs/api/swiftflow-store.md Shows how to batch-fetch node data and iterate over the results, printing each id and its data. ```swift let data = store.getNodesData(ids: ["node-1", "node-2"]) for (id, nodeData) in data { print("\(id): \(nodeData)") } ```