// BoardFlowView.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import SwiftUI import LyrebirdUI import LyrebirdShoeGaze /// A left→right signal-flow view of one `PedalBoard`: live pedal cards joined by connector lines, /// with split regions shown as two stacked lanes you can fill independently. /// /// Binds to `ShoeGaze` (`@Observable`) and reads the live board via `shoeGaze.boards[boardIndex]`. /// All edits go through the lane-addressed API (`appendPedal`/`removePedal`/`movePedal`, /// `appendStereoSplit`/`appendParallelSplit`/`appendMergeToMono`/`removeSegment`), which rebuild /// the board in place — so the index is the stable anchor and the `PedalBoard` reference is never /// cached. Region segments are addressed by their index in `board.orderedSegments`. /// /// Interaction: /// - Drag a palette pedal (`"add:"`) onto an existing card to insert it before that card, or /// onto empty lane space to append there; tap a palette pedal to append to the main chain. /// - Drag a card onto another card in the same lane to reorder; the corner trash removes it. /// - Connector lines render mono (single) or stereo (double) based on the running channel width. /// /// - Parameters: /// - shoeGaze: The `ShoeGaze` manager that owns the board. /// - boardIndex: Index into `shoeGaze.boards`. Renders a placeholder when out of range. public struct BoardFlowView: View { // MARK: - Constants private static let placeholderOpacity: Double = 0.55 private static let stageSpacing: CGFloat = 0 private static let connectorWidth: CGFloat = 26 private static let connectorThickness: CGFloat = 2 private static let stereoLineGap: CGFloat = 6 private static let laneSpacing: CGFloat = 10 private static let laneMinWidth: CGFloat = 240 private static let laneLabelWidth: CGFloat = 22 private static let regionPadding: CGFloat = 10 private static let regionCornerRadius: CGFloat = 12 private static let regionBrightness: Double = 0.09 private static let regionBorderOpacity: Double = 0.35 private static let trashPadding: CGFloat = 6 private static let trashOpacity: Double = 0.8 private static let badgeFontSize: CGFloat = 11 private static let badgeOpacity: Double = 0.6 private static let dropHighlightWidth: CGFloat = 2 private static let splitToggleSpacing: CGFloat = 6 private static let splitToggleWidth: CGFloat = 200 private static let emptyLaneOpacity: Double = 0.4 /// Extra height the content may exceed the viewport by before vertical scrolling turns on, so a /// sub-pixel rounding difference doesn't flip the axis set on and off. private static let verticalScrollSlack: CGFloat = 1 /// Signal-path accent (the pink/magenta connector colour). private static let flowColor: Color = Color(red: 0.92, green: 0.32, blue: 0.70) // MARK: - Properties private let shoeGaze: ShoeGaze private let boardIndex: Int /// Identifier of the lane/card currently hovered as a drop target, for highlight. @State private var dropTarget: String? /// Measured height of the flow content, used to enable vertical scrolling only when the stacked /// lanes exceed the viewport height (tall parallel splits). Otherwise scrolling stays horizontal. @State private var contentHeight: CGFloat = 0 public init(shoeGaze: ShoeGaze, boardIndex: Int) { self.shoeGaze = shoeGaze self.boardIndex = boardIndex } // MARK: - Body public var body: some View { if boardIndex < 0 || boardIndex >= shoeGaze.boards.count { Text("No board at index \(boardIndex).") .foregroundStyle(Color.secondary.opacity(BoardFlowView.placeholderOpacity)) } else { let board: PedalBoard = shoeGaze.boards[boardIndex] flow(board: board) } } private func flow(board: PedalBoard) -> some View { let stages: [StageModel] = stageModels(board: board) return GeometryReader { proxy in let viewportHeight: CGFloat = proxy.size.height // Lock to horizontal, adding the vertical axis only when the chain is taller than the // viewport (deep parallel splits) so it can be reached instead of clipped. let axes: Axis.Set = contentHeight > viewportHeight + BoardFlowView.verticalScrollSlack ? [.horizontal, .vertical] : .horizontal ScrollView(axes, showsIndicators: true) { // The spacers centre the chain vertically when it is shorter than the viewport; when // it overflows, the min-height floor is already exceeded so they collapse to zero and // the chain scrolls. Pedals keep their intrinsic height either way — the window no // longer stretches them. VStack(spacing: 0) { Spacer(minLength: 0) chainRow(board: board, stages: stages) Spacer(minLength: 0) } .frame(minHeight: viewportHeight) } .frame(maxWidth: .infinity, maxHeight: .infinity) .onPreferenceChange(BoardFlowContentHeightKey.self) { height in contentHeight = height } } } /// The left→right chain of endpoints, connectors and stage cards. Reports its own intrinsic /// height through `BoardFlowContentHeightKey` so `flow` can decide whether vertical scrolling is /// needed. Each pedal sizes to its own content, so the row is only as tall as its tallest card — /// a short pedal stays short next to a tall one. private func chainRow(board: PedalBoard, stages: [StageModel]) -> some View { HStack(alignment: .center, spacing: BoardFlowView.stageSpacing) { endpoint("IN") ForEach(stages) { stage in connector(stereo: stage.stereoIn) stageView(stage) } connector(stereo: board.width == 2) endpoint(board.width == 2 ? "OUT ⇒" : "OUT") } .padding(.vertical, BoardFlowView.regionPadding) .background( GeometryReader { contentProxy in Color.clear.preference( key: BoardFlowContentHeightKey.self, value: contentProxy.size.height ) } ) } // MARK: - Stage model /// View-model for one top-level segment: its index (the lane region index), the live segment, /// the main-chain linear index for `.pedal`, and the channel width entering the stage. private struct StageModel: Identifiable { let id: Int let segmentIndex: Int let segment: BoardSegment let linearIndex: Int? let stereoIn: Bool } /// Walks `board.orderedSegments`, tagging each with a linear pedal index and the running width. private func stageModels(board: PedalBoard) -> [StageModel] { var models: [StageModel] = [] var linearCounter: Int = 0 var stereo: Bool = false for (index, segment) in board.orderedSegments.enumerated() { let stereoIn: Bool = stereo var linearIndex: Int? switch segment { case .pedal(let pedal): linearIndex = linearCounter linearCounter += 1 if pedal.channelKind != .mono { stereo = true } case .stereoSplit: stereo = true case .stereoUnzip: stereo = true case .parallel: break case .mergeToMono: stereo = false } models.append( StageModel( id: index, segmentIndex: index, segment: segment, linearIndex: linearIndex, stereoIn: stereoIn ) ) } return models } // MARK: - Stage dispatch @ViewBuilder private func stageView(_ stage: StageModel) -> some View { switch stage.segment { case .pedal(let pedal): mainPedalCard(pedal: pedal, linearIndex: stage.linearIndex ?? 0, segmentIndex: stage.segmentIndex) case .stereoSplit(let section): regionNode( title: "STEREO SPLIT", segmentIndex: stage.segmentIndex, leftLabel: "L", rightLabel: "R", leftPedals: section.left.pedals, rightPedals: section.right.pedals, control: AnyView(StereoRouteControlView(section: section)) ) case .stereoUnzip(let section): regionNode( title: "STEREO UNZIP", segmentIndex: stage.segmentIndex, leftLabel: "L", rightLabel: "R", leftPedals: section.left.pedals, rightPedals: section.right.pedals, control: AnyView(StereoRouteControlView(section: section)) ) case .parallel(let section): regionNode( title: "PARALLEL", segmentIndex: stage.segmentIndex, leftLabel: "A", rightLabel: "B", leftPedals: section.branchA.pedals, rightPedals: section.branchB.pedals, control: AnyView(SplitterView(splitter: section.splitter)) ) case .mergeToMono: mergeNode(segmentIndex: stage.segmentIndex) } } // MARK: - Connectors private func connector(stereo: Bool) -> some View { ZStack { if stereo { VStack(spacing: BoardFlowView.stereoLineGap) { line line } } else { line } } .frame(width: BoardFlowView.connectorWidth) } private var line: some View { Capsule() .fill(BoardFlowView.flowColor) .frame(height: BoardFlowView.connectorThickness) } private func endpoint(_ text: String) -> some View { Text(text) .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold).monospaced()) .foregroundStyle(BoardFlowView.flowColor) } // MARK: - Main pedal card private func mainPedalCard(pedal: Pedal, linearIndex: Int, segmentIndex: Int) -> some View { let payload: String = "movemain:\(linearIndex)" let card: some View = PedalView(pedal: pedal) .overlay(alignment: .topTrailing) { trashButton { deleteSegment(forLinear: linearIndex) } } .overlay { dropOutline(active: dropTarget == payload) } .draggable(payload) .dropDestination(for: String.self) { items, _ in handleMainDrop(items, ontoLinear: linearIndex) } isTargeted: { hovering in dropTarget = hovering ? payload : (dropTarget == payload ? nil : dropTarget) } return VStack(spacing: BoardFlowView.splitToggleSpacing) { card // Stereo-producing pedals (Ping-Pong, Octave Splitter) offer a choice: keep one stereo // flow downstream, or split the L/R channels into independent lanes (a stereo unzip). if pedal.channelKind != .mono { splitToggle(segmentIndex: segmentIndex) } } } /// A "Stereo flow / Split L/R" segmented control for a stereo-producing pedal. "Split L/R" /// inserts a stereo-unzip region right after the pedal; "Stereo flow" removes it. private func splitToggle(segmentIndex: Int) -> some View { let binding: Binding = Binding( get: { guard let board: PedalBoard = board else { return false } return shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) }, set: { split in guard let board: PedalBoard = board else { return } do { if split { guard !shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return } _ = try shoeGaze.insertStereoUnzip(afterSegment: segmentIndex, in: board) } else { // Only remove the next segment if it is in fact this pedal's unzip region — // it may have been removed via the region's own trash button. guard shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return } _ = try shoeGaze.removeSegment(at: segmentIndex + 1, from: board) } } catch { print("[BoardFlowView] split toggle failed: \(error)") } } ) return Picker("", selection: binding) { Text("Stereo flow").tag(false) Text("Split L/R").tag(true) } .pickerStyle(.segmented) .labelsHidden() .frame(maxWidth: BoardFlowView.splitToggleWidth) } // MARK: - Region node (stereo split / parallel) private func regionNode( title: String, segmentIndex: Int, leftLabel: String, rightLabel: String, leftPedals: [Pedal], rightPedals: [Pedal], control: AnyView ) -> some View { VStack(alignment: .leading, spacing: BoardFlowView.laneSpacing) { HStack(spacing: 8) { Text(title) .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold)) .foregroundStyle(BoardFlowView.flowColor) Spacer() control trashButton { removeSegment(at: segmentIndex) } } laneRow(label: leftLabel, pedals: leftPedals, lane: .left(region: segmentIndex)) laneRow(label: rightLabel, pedals: rightPedals, lane: .right(region: segmentIndex)) } .padding(BoardFlowView.regionPadding) .background( RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) .fill(Color(white: BoardFlowView.regionBrightness)) .overlay( RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) .stroke(BoardFlowView.flowColor.opacity(BoardFlowView.regionBorderOpacity), lineWidth: 1) ) ) } private func laneRow(label: String, pedals: [Pedal], lane: PedalLane) -> some View { let laneID: String = "lane:\(lane.regionIndex ?? -1):\(lane.isLeftBranch ? "L" : "R")" return HStack(alignment: .center, spacing: BoardFlowView.stageSpacing) { Text(label) .font(.system(size: BoardFlowView.badgeFontSize, weight: .bold).monospaced()) .foregroundStyle(Color.white.opacity(BoardFlowView.badgeOpacity)) .frame(width: BoardFlowView.laneLabelWidth) if pedals.isEmpty { Text("drop a pedal here") .font(.caption) .foregroundStyle(Color.white.opacity(BoardFlowView.emptyLaneOpacity)) .frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading) .padding(.vertical, BoardFlowView.regionPadding) } else { ForEach(Array(pedals.enumerated()), id: \.offset) { pair in connector(stereo: false) branchPedalCard(pedal: pair.element, lane: lane, index: pair.offset) } } } .frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading) // Make the whole lane frame hit-testable: an empty lane is mostly transparent, so without // this the drop target has almost no area and releases land on nothing (the bug where // dropping into an empty Stereo Unzip / Split / Parallel lane did nothing). .contentShape(Rectangle()) .overlay { dropOutline(active: dropTarget == laneID) } .dropDestination(for: String.self) { items, _ in handleLaneDrop(items, lane: lane) } isTargeted: { hovering in dropTarget = hovering ? laneID : (dropTarget == laneID ? nil : dropTarget) } } private func branchPedalCard(pedal: Pedal, lane: PedalLane, index: Int) -> some View { let payload: String = "movebranch:\(lane.regionIndex ?? -1):\(lane.isLeftBranch ? "L" : "R"):\(index)" return PedalView(pedal: pedal) .overlay(alignment: .topTrailing) { trashButton { removePedal(at: index, lane: lane) } } .overlay { dropOutline(active: dropTarget == payload) } .draggable(payload) .dropDestination(for: String.self) { items, _ in handleBranchCardDrop(items, lane: lane, ontoIndex: index) } isTargeted: { hovering in dropTarget = hovering ? payload : (dropTarget == payload ? nil : dropTarget) } } private func mergeNode(segmentIndex: Int) -> some View { VStack(spacing: 4) { Text("⇒ MONO") .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold)) .foregroundStyle(BoardFlowView.flowColor) trashButton { removeSegment(at: segmentIndex) } } .padding(BoardFlowView.regionPadding) .background( RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) .stroke(BoardFlowView.flowColor.opacity(BoardFlowView.regionBorderOpacity), lineWidth: 1) ) } // MARK: - Shared bits private func trashButton(_ action: @escaping () -> Void) -> some View { Button(role: .destructive, action: action) { Image(systemName: "trash.circle.fill") .foregroundStyle(Color.white.opacity(BoardFlowView.trashOpacity)) } .buttonStyle(.plain) .padding(BoardFlowView.trashPadding) } @ViewBuilder private func dropOutline(active: Bool) -> some View { if active { RoundedRectangle(cornerRadius: 8) .stroke(BoardFlowView.flowColor, lineWidth: BoardFlowView.dropHighlightWidth) } } // MARK: - Drop handling private func parse(_ items: [String]) -> String? { items.first } private func handleMainDrop(_ items: [String], ontoLinear: Int) -> Bool { dropTarget = nil guard let payload: String = parse(items) else { return false } if let type: String = payload.afterPrefix("add:") { // Dropped a palette pedal ONTO a chain card → insert before that card. insert(type: type, at: ontoLinear, lane: .main) return true } if let src: Int = payload.afterPrefix("movemain:").flatMap(Int.init) { reorderMain(from: src, onto: ontoLinear) return true } // A branch pedal dragged back onto the main chain → cross-lane move. return moveAcross(payload, toLane: .main) } private func handleLaneDrop(_ items: [String], lane: PedalLane) -> Bool { dropTarget = nil guard let payload: String = parse(items) else { return false } if let type: String = payload.afterPrefix("add:") { append(type: type, lane: lane) return true } // A pedal from the main chain or another lane dragged into this lane → cross-lane move. return moveAcross(payload, toLane: lane) } private func handleBranchCardDrop(_ items: [String], lane: PedalLane, ontoIndex: Int) -> Bool { dropTarget = nil guard let payload: String = parse(items) else { return false } // Guard against a payload minted before a rebuild changed the segment layout: the encoded // region index must still point at a live region segment. if let region: Int = lane.regionIndex, let liveBoard: PedalBoard = board, region >= liveBoard.orderedSegments.count { return false } if let type: String = payload.afterPrefix("add:") { // Dropped a palette pedal ONTO a branch card → insert before that card. insert(type: type, at: ontoIndex, lane: lane) return true } // Reorder within the same lane: "movebranch:::". let parts: [Substring] = payload.split(separator: ":") if parts.count == 4, parts[0] == "movebranch", Int(parts[1]) == lane.regionIndex, (parts[2] == "L") == lane.isLeftBranch, let src: Int = Int(parts[3]) { reorderBranch(from: src, onto: ontoIndex, lane: lane) return true } // A pedal from the main chain or a different lane dropped onto a card here → cross-lane move. return moveAcross(payload, toLane: lane) } /// Moves a pedal addressed by a `movemain:`/`movebranch:` payload into `destination`, /// preserving its parameters. Returns `false` if the payload isn't a recognised move. private func moveAcross(_ payload: String, toLane destination: PedalLane) -> Bool { guard let board: PedalBoard = board else { return false } let sourceLane: PedalLane let sourceIndex: Int if let mainIndex: Int = payload.afterPrefix("movemain:").flatMap(Int.init) { sourceLane = .main sourceIndex = mainIndex } else { let parts: [Substring] = payload.split(separator: ":") guard parts.count == 4, parts[0] == "movebranch", let region: Int = Int(parts[1]), let index: Int = Int(parts[3]) else { return false } sourceLane = (parts[2] == "L") ? .left(region: region) : .right(region: region) sourceIndex = index } do { _ = try shoeGaze.movePedal(from: sourceLane, at: sourceIndex, to: destination, in: board) return true } catch { print("[BoardFlowView] cross-lane move failed: \(error)") return false } } // MARK: - Edit actions private var board: PedalBoard? { guard boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return nil } return shoeGaze.boards[boardIndex] } private func append(type: String, lane: PedalLane) { guard let board: PedalBoard = board else { return } do { _ = try shoeGaze.appendPedal(PedalType(type), to: board, lane: lane) } catch { print("[BoardFlowView] appendPedal failed: \(error)") } } private func insert(type: String, at index: Int, lane: PedalLane) { guard let board: PedalBoard = board else { return } do { _ = try shoeGaze.insertPedal(PedalType(type), at: index, to: board, lane: lane) } catch { print("[BoardFlowView] insertPedal failed: \(error)") } } private func reorderMain(from source: Int, onto target: Int) { guard source != target, let board: PedalBoard = board else { return } // Convert "dropped ONTO the card at `target`" into movePedal's insert-before `toOffset`: // a forward move lands after the target (target + 1); a backward move lands before it. let destination: Int = source < target ? target + 1 : target do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: .main) } catch { print("[BoardFlowView] movePedal(main) failed: \(error)") } } private func reorderBranch(from source: Int, onto target: Int, lane: PedalLane) { guard source != target, let board: PedalBoard = board else { return } let destination: Int = source < target ? target + 1 : target do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: lane) } catch { print("[BoardFlowView] movePedal(branch) failed: \(error)") } } private func removePedal(at index: Int, lane: PedalLane) { guard let board: PedalBoard = board else { return } do { _ = try shoeGaze.removePedal(at: index, from: board, lane: lane) } catch { print("[BoardFlowView] removePedal failed: \(error)") } } private func deleteSegment(forLinear linearIndex: Int) { // A main-chain pedal: remove by its lane index (preserves regions). removePedal(at: linearIndex, lane: .main) } private func removeSegment(at segmentIndex: Int) { guard let board: PedalBoard = board else { return } do { _ = try shoeGaze.removeSegment(at: segmentIndex, from: board) } catch { print("[BoardFlowView] removeSegment failed: \(error)") } } } private extension String { /// Returns the remainder after `prefix`, or `nil` if the string doesn't start with it. func afterPrefix(_ prefix: String) -> String? { guard hasPrefix(prefix) else { return nil } return String(dropFirst(prefix.count)) } } /// Carries the measured height of the flow content up to `BoardFlowView`, which compares it to the /// viewport height to decide whether the vertical scroll axis is needed. private struct BoardFlowContentHeightKey: PreferenceKey { static let defaultValue: CGFloat = 0 static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } }