Files
ShoeGaze/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift
T
josh fba32ff0aa feat(ui): group factory rigs by category in the rig sidebar
The rig-library sidebar now presents shipped starter rigs under their
FactoryRigCategory headers (Shoegaze Walls, Dreampop, Classic, Ambient,
Experimental) in fixed catalog order, with the user's own rigs under a
"My Rigs" header. Starter rows show a "Starter rig" subtitle and are not
reorderable; user rows keep drag-to-reorder and Move Up/Down (now scoped to
the user's own rigs). Grouping is presentational, so it stays correct
regardless of underlying library order.

Adds FactoryRigLibrary.category(for:) and rigs(in:) with tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 13:53:56 -07:00

304 lines
12 KiB
Swift

// RigLibrarySidebarView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// The rig library: a persistent left-hand listing of every saved rig, with controls to start a
/// new rig, save / save-as, duplicate, rename, delete, erase all, and import / export an archive.
///
/// Selecting a rig replaces the current working session (the host stops the engine, rebuilds the
/// graph, and restarts). This view is purely presentational — every action is delegated to the
/// host (`ShoeGazeBuilderView`) via closures so engine lifecycle and naming prompts stay in one
/// place.
struct RigLibrarySidebarView: View {
// MARK: - Layout constants
private static let width: CGFloat = 200
private static let rowSpacing: CGFloat = 4
private static let rowPadding: CGFloat = 8
private static let rowCorner: CGFloat = 6
private static let selectedOpacity: Double = 0.22
private static let subtitleOpacity: Double = 0.5
private static let headerOpacity: Double = 0.65
private static let emptyOpacity: Double = 0.4
// MARK: - Inputs
let store: RigLibraryStore
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig.
@Binding var currentRigID: UUID?
let onSelect: (RigEntry) -> Void
let onNew: () -> Void
let onSave: () -> Void
let onSaveAs: () -> Void
let onDuplicate: (RigEntry) -> Void
let onRename: (RigEntry) -> Void
let onDelete: (RigEntry) -> Void
let onEraseAll: () -> Void
let onImportArchive: () -> Void
let onExportArchive: () -> Void
/// Invoked when the local-only (iCloud-unavailable) status icon is tapped, so the host can
/// explain how to re-enable iCloud sync. Defaults to a no-op.
var onShowCloudStatus: () -> Void = {}
private static let timestampFormat: Date.FormatStyle =
Date.FormatStyle(date: .abbreviated, time: .shortened)
// MARK: - Body
var body: some View {
VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
header
Divider().overlay(Color.white.opacity(0.12))
rigList
Divider().overlay(Color.white.opacity(0.12))
actionBar
}
.frame(width: RigLibrarySidebarView.width)
}
// MARK: - Header
private var header: some View {
HStack(spacing: 6) {
Text("Rigs")
.font(.headline)
.foregroundStyle(Color.white)
Spacer()
cloudStatusIcon
}
}
/// Cloud icon when the library is iCloud-backed; a tappable slash when local-only (tap explains
/// how to re-enable sync).
@ViewBuilder
private var cloudStatusIcon: some View {
if store.isICloud {
Image(systemName: "icloud")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
.help("Synced with iCloud across your devices")
} else {
Button { onShowCloudStatus() } label: {
Image(systemName: "icloud.slash")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
}
.buttonStyle(.plain)
.help("iCloud unavailable — tap for details. Rigs are stored on this device only")
}
}
// MARK: - List
private var rigList: some View {
ScrollView(.vertical, showsIndicators: true) {
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
if !store.isLoaded {
HStack(spacing: 6) {
ProgressView().controlSize(.small)
Text("Loading…")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
}
.padding(.vertical, RigLibrarySidebarView.rowPadding)
} else if store.entries.isEmpty {
Text("No saved rigs yet.\nTap New or Save to add one.")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
.padding(.vertical, RigLibrarySidebarView.rowPadding)
}
// Shipped starter rigs, grouped by category (fixed catalog order, not reorderable).
ForEach(factorySections, id: \.category) { section in
sectionHeader(section.category.displayName)
ForEach(section.entries) { entry in
rigRow(entry, reorderable: false)
}
}
// The user's own rigs, reorderable. Only headed when starter rigs are also shown, so
// a library with no factory rigs (e.g. after Erase All) reads as a plain list.
let userRigs: [RigEntry] = userEntries
if !userRigs.isEmpty {
if !factorySections.isEmpty {
sectionHeader("My Rigs")
}
ForEach(userRigs) { entry in
rigRow(entry, reorderable: true)
}
}
}
}
.frame(maxHeight: .infinity)
}
/// A small uppercase section header for a group of rigs.
private func sectionHeader(_ title: String) -> some View {
Text(title.uppercased())
.font(.caption2)
.fontWeight(.semibold)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
.padding(.top, RigLibrarySidebarView.rowPadding)
.padding(.horizontal, 2)
.frame(maxWidth: .infinity, alignment: .leading)
}
/// One rig row. `reorderable` rows (the user's own rigs) accept drag-to-reorder and expose
/// Move Up / Down; starter rigs are fixed and show a "Starter rig" subtitle instead of a date.
@ViewBuilder
private func rigRow(_ entry: RigEntry, reorderable: Bool) -> some View {
let isSelected: Bool = entry.id == currentRigID
let button = Button {
onSelect(entry)
} label: {
VStack(alignment: .leading, spacing: 2) {
Text(entry.name)
.font(.subheadline)
.foregroundStyle(Color.white)
.lineLimit(1)
Text(reorderable
? entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat)
: "Starter rig")
.font(.caption2)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity))
.lineLimit(1)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(RigLibrarySidebarView.rowPadding)
.background(
RoundedRectangle(cornerRadius: RigLibrarySidebarView.rowCorner)
.fill(Color.orange.opacity(isSelected ? RigLibrarySidebarView.selectedOpacity : 0))
)
// Make the whole padded cell tappable, not just the text glyphs.
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.contextMenu {
rowContextMenu(entry, reorderable: reorderable)
}
if reorderable {
// Drag the row onto another to reorder; dropping inserts it just before the target. Works
// on macOS (mouse drag) and iPad (long-press drag); taps still select.
button
.draggable(entry.id.uuidString)
.dropDestination(for: String.self) { droppedIDs, _ in
guard let first: String = droppedIDs.first else { return false }
moveDragged(first, onto: entry)
return true
}
} else {
button
}
}
/// The context menu for a rig row. Move Up / Down appear only for reorderable (user) rigs.
@ViewBuilder
private func rowContextMenu(_ entry: RigEntry, reorderable: Bool) -> some View {
if reorderable {
Button("Move Up") { store.moveUp(entry) }
.disabled(isFirstUser(entry))
Button("Move Down") { store.moveDown(entry) }
.disabled(isLastUser(entry))
Divider()
}
Button("Rename…") { onRename(entry) }
Button("Duplicate…") { onDuplicate(entry) }
// Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the
// unreachable failure path the Share item is simply omitted.
if let shareItem: RigShareItem = try? RigShareItem(rig: entry) {
ShareLink(
item: shareItem,
preview: SharePreview(entry.name)
) {
Label("Share…", systemImage: "square.and.arrow.up")
}
}
Divider()
Button("Delete", role: .destructive) { onDelete(entry) }
}
// MARK: - Grouping
/// The starter-rig sections: each non-empty ``FactoryRigCategory`` present in the library, in
/// catalog order, paired with its entries (also in catalog order).
private var factorySections: [(category: FactoryRigCategory, entries: [RigEntry])] {
let byID: [UUID: RigEntry] = Dictionary(
store.entries.map { ($0.id, $0) },
uniquingKeysWith: { first, _ in first }
)
return FactoryRigCategory.allCases.compactMap { category in
let entries: [RigEntry] = FactoryRigLibrary.rigs(in: category).compactMap { byID[$0.id] }
return entries.isEmpty ? nil : (category, entries)
}
}
/// The user's own (non-factory) rigs, in library order.
private var userEntries: [RigEntry] {
store.entries.filter { !FactoryRigLibrary.isFactory($0.id) }
}
// MARK: - Reorder helpers
/// Whether `entry` is the first among the user's own rigs (so Move Up is disabled for it).
private func isFirstUser(_ entry: RigEntry) -> Bool {
userEntries.first?.id == entry.id
}
/// Whether `entry` is the last among the user's own rigs (so Move Down is disabled for it).
private func isLastUser(_ entry: RigEntry) -> Bool {
userEntries.last?.id == entry.id
}
/// Moves the dragged entry (by id string) to sit just before `target` in the set list.
private func moveDragged(_ draggedIDString: String, onto target: RigEntry) {
guard let draggedID: UUID = UUID(uuidString: draggedIDString), draggedID != target.id else { return }
var order: [UUID] = store.entries.map(\.id)
guard let from: Int = order.firstIndex(of: draggedID) else { return }
order.remove(at: from)
// Target's index in the post-removal array; inserting there drops the dragged row before it.
guard let to: Int = order.firstIndex(of: target.id) else { return }
order.insert(draggedID, at: to)
store.applyOrder(order)
}
// MARK: - Action bar
private var actionBar: some View {
HStack(spacing: 6) {
Button { onNew() } label: { Image(systemName: "plus") }
.help("New rig")
Button { onSave() } label: { Image(systemName: "square.and.arrow.down") }
.help("Save the current rig")
Button { onSaveAs() } label: { Image(systemName: "doc.on.doc") }
.help("Save the current rig as a new entry")
Spacer()
Menu {
Button("Import Archive…") { onImportArchive() }
Button("Export Archive…") { onExportArchive() }
Divider()
Button("Erase All Rigs…", role: .destructive) { onEraseAll() }
} label: {
Image(systemName: "ellipsis.circle")
}
#if os(macOS)
.menuStyle(.borderlessButton)
.fixedSize()
#endif
.help("Archive and library options")
}
.buttonStyle(.bordered)
.tint(.orange)
.padding(.top, 2)
}
}