feat(ui): Mine/Starters rig toggle + seed starters into existing libraries
Two fixes so shipped starter rigs are actually reachable: - Seeding no longer requires an empty library. On launch it installs any factory rigs whose stable ids are missing, once per FactoryRigLibrary .seedVersion (a per-device UserDefaults marker). Existing users therefore receive the starters on their next launch; a starter the user later deletes stays deleted (the marker has advanced); bumping seedVersion when new starters ship re-runs catch-up for just the new ones. Idempotent by id, so iCloud-synced devices never duplicate. - Sidebar gains a segmented Mine / Starters toggle. "Mine" is the flat, reorderable user list; "Starters" groups the shipped rigs by category. A "Restore Starter Rigs" action (Starters empty-state button + library menu) re-installs missing starters on demand via RigLibraryBootstrap.restoreStarterRigs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -70,6 +70,11 @@ extension ChainRouter {
|
||||
@MainActor
|
||||
public enum FactoryRigLibrary {
|
||||
|
||||
/// Catalog seed version. Bump this whenever new factory rigs are added so first-run catch-up
|
||||
/// seeding re-runs on already-populated libraries and installs the newly-shipped starters. Never
|
||||
/// re-adds a rig the user has since deleted at the *same* version — the marker only advances.
|
||||
public static let seedVersion: Int = 1
|
||||
|
||||
/// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig.
|
||||
///
|
||||
/// Because factory rigs are seeded with their fixed ``FactoryRig/id``, an entry recalled from the
|
||||
|
||||
@@ -10,75 +10,101 @@ import LyrebirdShoeGaze
|
||||
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
|
||||
///
|
||||
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
|
||||
/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work —
|
||||
/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the
|
||||
/// library from the current working rig **only after** the real (possibly iCloud) contents are
|
||||
/// known, so a first launch can't create a duplicate "Default" rig on every synced device.
|
||||
/// initializer and hand to the UI). ``start(_:seedFrom:)`` then does the blocking work — resolving
|
||||
/// the iCloud-or-local location and the initial load — off the main thread, then performs a one-time
|
||||
/// catch-up seed of any missing shipped starter rigs.
|
||||
@MainActor
|
||||
public enum RigLibraryBootstrap {
|
||||
|
||||
/// `UserDefaults` key holding the highest ``FactoryRigLibrary/seedVersion`` this device has
|
||||
/// already seeded. Per-device (not synced): the seed is idempotent by stable rig id, so a device
|
||||
/// that receives the rigs via iCloud sync simply finds them already present and seeds nothing.
|
||||
private static let seedVersionKey: String = "net.realizedsound.shoegaze.factorySeedVersion"
|
||||
|
||||
/// Creates an auto-resolving store. Construct this synchronously at launch; call
|
||||
/// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
|
||||
/// ``start(_:seedFrom:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
|
||||
public static func makeStore() -> RigLibraryStore {
|
||||
RigLibraryStore()
|
||||
}
|
||||
|
||||
/// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still
|
||||
/// empty after loading (first run). Idempotent enough to call once at launch.
|
||||
/// Resolves + loads `store` off the main thread, then performs a one-time catch-up seed of any
|
||||
/// missing shipped starter rigs. Idempotent — safe to call once at every launch.
|
||||
///
|
||||
/// Seeding adds only factory rigs whose stable ids are **not already present**, so it never
|
||||
/// duplicates a rig and never touches the user's own rigs. It runs at most once per
|
||||
/// ``FactoryRigLibrary/seedVersion``: a first launch seeds every starter; a launch after an
|
||||
/// update that ships new starters seeds just the new ones; and a starter the user later deletes
|
||||
/// stays deleted (the version marker has already advanced). This deliberately replaces the old
|
||||
/// "only seed an empty library" rule so users who already had rigs still receive the starters.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - store: The store from ``makeStore()``.
|
||||
/// - shoeGaze: The session whose current rig seeds the library when it is first empty.
|
||||
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`.
|
||||
/// - shoeGaze: The working session (currently unused by seeding; kept for call-site stability
|
||||
/// and future working-rig seeding needs).
|
||||
public static func start(
|
||||
_ store: RigLibraryStore,
|
||||
seedFrom shoeGaze: ShoeGaze,
|
||||
seedName: String = "Default"
|
||||
seedFrom shoeGaze: ShoeGaze
|
||||
) async {
|
||||
await store.start()
|
||||
|
||||
// Seed only after the (possibly iCloud) library has loaded: an empty library here means a
|
||||
// genuine first run, not a not-yet-synced one.
|
||||
guard store.entries.isEmpty else { return }
|
||||
let defaults: UserDefaults = .standard
|
||||
let seededVersion: Int = defaults.integer(forKey: seedVersionKey) // 0 when never seeded
|
||||
guard seededVersion < FactoryRigLibrary.seedVersion else { return }
|
||||
|
||||
// First run: populate the library with the shipped starter rigs. These are built in
|
||||
// throwaway offline sessions, so they are independent of the current working graph. The
|
||||
// working session is intentionally left as-is (no `currentRigID`) — the user picks a starter
|
||||
// rig from the sidebar to load it, rather than the highlight pointing at a rig the working
|
||||
// graph has not actually loaded.
|
||||
// Seed the shipped starter rigs. `store.save` updates the in-memory library synchronously
|
||||
// (so the session sees every rig immediately) and persists to disk asynchronously — a disk
|
||||
// failure is logged by the store, not thrown here, so there is no per-entry rollback to do.
|
||||
// `save` throws only on a synchronous encode failure of this deterministic rig data, which
|
||||
// should not happen at runtime; if the build or an encode somehow fails, fall back to
|
||||
// seeding the working rig so the library is never left empty on first run.
|
||||
// Seed missing starters. Only advance the marker if seeding succeeded, so a transient failure
|
||||
// (which should not happen for this deterministic data) is retried on the next launch.
|
||||
if seedMissingFactoryRigs(into: store) {
|
||||
defaults.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds any shipped starter rig not already in `store`, keyed by stable id. Safe to call anytime.
|
||||
///
|
||||
/// Use this to drive a user-facing "Restore Starter Rigs" action: it re-adds starters the user
|
||||
/// deleted (and any newly-shipped ones) without disturbing their own rigs, and advances the seed
|
||||
/// marker so automatic catch-up seeding won't fight the manual restore.
|
||||
///
|
||||
/// - Parameter store: The library to seed into.
|
||||
/// - Returns: The number of starter rigs added (0 if all were already present).
|
||||
@discardableResult
|
||||
public static func restoreStarterRigs(into store: RigLibraryStore) -> Int {
|
||||
let added: Int = addMissingFactoryRigs(into: store)
|
||||
UserDefaults.standard.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey)
|
||||
return added
|
||||
}
|
||||
|
||||
/// Seeds missing starters, returning whether the operation completed without a build/encode error
|
||||
/// (so the caller knows whether to advance the seed marker).
|
||||
private static func seedMissingFactoryRigs(into store: RigLibraryStore) -> Bool {
|
||||
do {
|
||||
let entries: [RigEntry] = try FactoryRigLibrary.makeEntries()
|
||||
for entry: RigEntry in entries {
|
||||
try store.save(entry)
|
||||
}
|
||||
_ = try addMissingFactoryRigsThrowing(into: store)
|
||||
return true
|
||||
} catch {
|
||||
print("[RigLibraryBootstrap] seeding factory rigs failed: \(error)")
|
||||
seedWorkingRig(store, seedFrom: shoeGaze, seedName: seedName)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Seeds the working session's current rig as a single named library entry.
|
||||
///
|
||||
/// Last-resort fallback used only when the factory rigs could not be built; keeps the library
|
||||
/// from being left empty on first run.
|
||||
private static func seedWorkingRig(
|
||||
_ store: RigLibraryStore,
|
||||
seedFrom shoeGaze: ShoeGaze,
|
||||
seedName: String
|
||||
) {
|
||||
guard !shoeGaze.boards.isEmpty else { return }
|
||||
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
|
||||
/// Non-throwing convenience: seeds missing starters and returns the count added (0 on error).
|
||||
private static func addMissingFactoryRigs(into store: RigLibraryStore) -> Int {
|
||||
do {
|
||||
try store.save(entry)
|
||||
shoeGaze.currentRigID = entry.id
|
||||
return try addMissingFactoryRigsThrowing(into: store)
|
||||
} catch {
|
||||
print("[RigLibraryBootstrap] fallback seeding failed: \(error)")
|
||||
print("[RigLibraryBootstrap] restoring factory rigs failed: \(error)")
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the starter rigs and saves the ones whose ids are missing from `store`.
|
||||
///
|
||||
/// - Returns: The number of rigs added.
|
||||
/// - Throws: Any error from building the rigs or a synchronous encode failure in `store.save`.
|
||||
private static func addMissingFactoryRigsThrowing(into store: RigLibraryStore) throws -> Int {
|
||||
let existingIDs: Set<UUID> = Set(store.entries.map { $0.id })
|
||||
let missing: [RigEntry] = try FactoryRigLibrary.makeEntries().filter { !existingIDs.contains($0.id) }
|
||||
for entry: RigEntry in missing {
|
||||
try store.save(entry)
|
||||
}
|
||||
return missing.count
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,9 @@ struct RigLibrarySidebarView: View {
|
||||
let onImportArchive: () -> Void
|
||||
let onExportArchive: () -> Void
|
||||
|
||||
/// Invoked to (re-)install any shipped starter rigs missing from the library. Defaults to a no-op.
|
||||
var onRestoreStarters: () -> 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 = {}
|
||||
@@ -52,6 +55,16 @@ struct RigLibrarySidebarView: View {
|
||||
private static let timestampFormat: Date.FormatStyle =
|
||||
Date.FormatStyle(date: .abbreviated, time: .shortened)
|
||||
|
||||
/// Which group of rigs the list is currently showing.
|
||||
private enum RigTab: String, CaseIterable, Identifiable {
|
||||
case mine = "Mine"
|
||||
case starters = "Starters"
|
||||
var id: String { rawValue }
|
||||
}
|
||||
|
||||
/// The selected list tab. Defaults to the user's own rigs.
|
||||
@State private var tab: RigTab = .mine
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
var body: some View {
|
||||
@@ -99,46 +112,83 @@ struct RigLibrarySidebarView: View {
|
||||
|
||||
// MARK: - List
|
||||
|
||||
@ViewBuilder
|
||||
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)
|
||||
if !store.isLoaded {
|
||||
HStack(spacing: 6) {
|
||||
ProgressView().controlSize(.small)
|
||||
Text("Loading…")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||
}
|
||||
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
||||
.frame(maxHeight: .infinity, alignment: .top)
|
||||
} else {
|
||||
VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
||||
tabPicker
|
||||
ScrollView(.vertical, showsIndicators: true) {
|
||||
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
||||
switch tab {
|
||||
case .mine: mineList
|
||||
case .starters: startersList
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
/// Segmented Mine / Starters switch at the top of the list.
|
||||
private var tabPicker: some View {
|
||||
Picker("", selection: $tab) {
|
||||
ForEach(RigTab.allCases) { option in
|
||||
Text(option.rawValue).tag(option)
|
||||
}
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
.labelsHidden()
|
||||
}
|
||||
|
||||
/// The user's own rigs — a flat, reorderable list.
|
||||
@ViewBuilder
|
||||
private var mineList: some View {
|
||||
let userRigs: [RigEntry] = userEntries
|
||||
if userRigs.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)
|
||||
} else {
|
||||
ForEach(userRigs) { entry in
|
||||
rigRow(entry, reorderable: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The shipped starter rigs, grouped by category (fixed catalog order, not reorderable).
|
||||
@ViewBuilder
|
||||
private var startersList: some View {
|
||||
let sections: [(category: FactoryRigCategory, entries: [RigEntry])] = factorySections
|
||||
if sections.isEmpty {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("No starter rigs installed.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||
Button("Restore Starter Rigs") { onRestoreStarters() }
|
||||
.buttonStyle(.bordered)
|
||||
.tint(.orange)
|
||||
.controlSize(.small)
|
||||
}
|
||||
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
||||
} else {
|
||||
ForEach(sections, id: \.category) { section in
|
||||
sectionHeader(section.category.displayName)
|
||||
ForEach(section.entries) { entry in
|
||||
rigRow(entry, reorderable: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxHeight: .infinity)
|
||||
}
|
||||
|
||||
/// A small uppercase section header for a group of rigs.
|
||||
@@ -286,6 +336,8 @@ struct RigLibrarySidebarView: View {
|
||||
Button("Import Archive…") { onImportArchive() }
|
||||
Button("Export Archive…") { onExportArchive() }
|
||||
Divider()
|
||||
Button("Restore Starter Rigs") { onRestoreStarters() }
|
||||
Divider()
|
||||
Button("Erase All Rigs…", role: .destructive) { onEraseAll() }
|
||||
} label: {
|
||||
Image(systemName: "ellipsis.circle")
|
||||
|
||||
@@ -645,10 +645,18 @@ public struct ShoeGazeBuilderView: View {
|
||||
onEraseAll: { showEraseAllDialog = true },
|
||||
onImportArchive: { showImporter = true },
|
||||
onExportArchive: { exportArchiveAction() },
|
||||
onRestoreStarters: { restoreStarterRigs() },
|
||||
onShowCloudStatus: { showICloudUnavailableAlert = true }
|
||||
)
|
||||
}
|
||||
|
||||
/// (Re-)installs any shipped starter rigs missing from the library. Non-destructive: user rigs
|
||||
/// are untouched, and already-present starters are skipped (matched by stable id).
|
||||
private func restoreStarterRigs() {
|
||||
let added: Int = RigLibraryBootstrap.restoreStarterRigs(into: library)
|
||||
print("[ShoeGazeBuilderView] restored \(added) starter rig(s)")
|
||||
}
|
||||
|
||||
// MARK: - Sleep / iCloud status
|
||||
|
||||
/// Platform name for the settings app, used in the iCloud guidance alert.
|
||||
|
||||
Reference in New Issue
Block a user