Files
ShoeGaze/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift
T
josh d41ba37093 Add signal-flow pedalboard builder UI
Interactive builder views in LyrebirdShoeGazeUI:

- PedalPaletteView: vertical sidebar listing every pedal (tap to append
  to the main chain, drag "add:<type>" onto a lane) plus routing actions
  (Stereo Split / Parallel Split / Merge to Mono).
- BoardFlowView: left-to-right signal-flow board driven by
  board.orderedSegments. Pedal cards joined by pink connector lines
  (double for stereo width); split regions render as two stacked L/R
  (A/B) lanes you fill independently by dropping pedals; per-card trash,
  drag-to-reorder within a lane, region route/mode controls, and a
  region trash. Reads shoeGaze.boards[index] fresh each body (index is
  the stable anchor across rebuilds).
- ShoeGazeBuilderView: sidebar + vertically-centered flow board, with
  transport, input picker, board picker, and JSON save/load (NSSavePanel
  / NSOpenPanel on macOS, fileExporter/Importer on iOS via
  RigFileDocument).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 09:32:09 -07:00

435 lines
17 KiB
Swift

// 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:<type>"`) onto a lane to append it 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 emptyLaneOpacity: Double = 0.4
/// 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?
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 ScrollView([.horizontal, .vertical], showsIndicators: true) {
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)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
// 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 .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)
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 .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) -> some View {
let payload: String = "movemain:\(linearIndex)"
return 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)
}
}
// 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)
.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:") {
append(type: type, lane: .main)
return true
}
if let src: Int = payload.afterPrefix("movemain:").flatMap(Int.init) {
reorderMain(from: src, onto: ontoLinear)
return true
}
return false
}
private func handleLaneDrop(_ items: [String], lane: PedalLane) -> Bool {
dropTarget = nil
guard let payload: String = parse(items), let type: String = payload.afterPrefix("add:") else {
return false
}
append(type: type, lane: lane)
return true
}
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:") {
append(type: type, lane: lane)
return true
}
// Reorder within the same lane only: "movebranch:<region>:<side>:<index>".
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
}
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(type: type, to: board, lane: lane) }
catch { print("[BoardFlowView] appendPedal 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))
}
}