~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
263 lines · 7.4 KB Raw History
import HUDKit
import SwiftUI

/// The theme the workspace is drawn in, wherever the person is signed in:
/// the system's; HUD's, as getWorkspace lists them; the person's own
/// (`listThemes` of their DID), made in the web workspace; the one chosen,
/// when someone else made it; and everyone's to browse (`ThemeBrowser`).
/// Chosen, it shows at once; refused, it goes back, and says why.
struct ThemeChooser: View {
	let workspace: Workspace
	/// The person's own themes; nil until listed.
	@State private var yours: [Theme]?
	/// Why theirs couldn't be listed.
	@State private var yoursFailed: String?
	/// Why the theme chosen last was refused.
	@State private var refused: String?

	var body: some View {
		Form {
			if let refused {
				Section {
					Text(refused).foregroundStyle(.red)
				}
			}
			Section {
				ThemeRow(theme: nil, chosen: workspace.theme == nil) { choose(nil) }
				ForEach(workspace.themes) { theme in
					ThemeRow(theme: theme, chosen: workspace.theme?.id == theme.id) { choose(theme) }
				}
			} header: {
				Text("HUD's")
			}
			Section {
				if let yours, !yours.isEmpty {
					ForEach(yours) { theme in
						ThemeRow(theme: theme, chosen: workspace.theme?.id == theme.id) { choose(theme) }
					}
				} else if let yoursFailed {
					Text(yoursFailed).foregroundStyle(.secondary)
					Button("Try again") { Task { await listYours() } }
				} else if yours != nil {
					Text("You have no themes yet. Make one in the workspace on the web, and choose it here.")
						.foregroundStyle(.secondary)
				} else {
					ProgressView()
						.frame(maxWidth: .infinity)
				}
			} header: {
				Text("Yours")
			}
			if let chosen = someoneElses {
				Section {
					ThemeRow(theme: chosen, chosen: true, byline: true) { choose(chosen) }
				} header: {
					Text("Chosen")
				}
			}
			Section {
				NavigationLink {
					ThemeBrowser(workspace: workspace, refused: $refused)
				} label: {
					Label("Browse themes", systemImage: "square.grid.2x2")
				}
			} footer: {
				Text("Themes are made in the workspace on the web.")
			}
		}
		.navigationTitle("Theme")
		.navigationBarTitleDisplayMode(.inline)
		.task { await listYours() }
	}

	/// The theme chosen, when it is a person's not among the person's own:
	/// someone else's, or one of theirs deleted since.
	private var someoneElses: Theme? {
		guard let chosen = workspace.theme, chosen.uri != nil else { return nil }
		if chosen.creator?.did != workspace.me?.did { return chosen }
		guard let yours else { return nil }
		return yours.contains { $0.id == chosen.id } ? nil : chosen
	}

	/// Every theme the person made, page after page.
	private func listYours() async {
		guard let me = workspace.me?.did else {
			yours = []
			return
		}
		yoursFailed = nil
		var found: [Theme] = []
		var cursor: String?
		do {
			repeat {
				let page = try await workspace.client.listThemes(actor: me, limit: 50, cursor: cursor)
				found += page.themes
				cursor = page.cursor
			} while cursor != nil
			yours = found
		} catch HUDError.signIn {
			// Signed out: the session says so.
		} catch {
			yoursFailed = "Couldn't list your themes: \(error.localizedDescription)"
		}
	}

	private func choose(_ theme: Theme?) {
		Themes.choose(theme, workspace, refused: $refused)
	}
}

/// Everyone's themes, a page at a time, the next as the last is reached;
/// each with who made it. A tap draws the workspace in it.
struct ThemeBrowser: View {
	let workspace: Workspace
	/// Why the theme chosen last was refused.
	@Binding var refused: String?
	@State private var themes: [Theme] = []
	@State private var cursor: String?
	/// Every page is read.
	@State private var done = false
	@State private var loading = false
	/// Why the next page couldn't be read.
	@State private var failed: String?

	var body: some View {
		List {
			if let refused {
				Section {
					Text(refused).foregroundStyle(.red)
				}
			}
			Section {
				ForEach(themes) { theme in
					ThemeRow(theme: theme, chosen: workspace.theme?.id == theme.id, byline: true) {
						Themes.choose(theme, workspace, refused: $refused)
					}
				}
				if let failed {
					Text(failed).foregroundStyle(.secondary)
					Button("Try again") { Task { await more() } }
				} else if !done {
					ProgressView()
						.frame(maxWidth: .infinity)
						.task(id: cursor) { await more() }
				}
			}
		}
		.overlay {
			if done, themes.isEmpty {
				ContentUnavailableView("No themes yet", systemImage: "paintpalette", description: Text("Themes people make in the workspace on the web show here."))
			}
		}
		.navigationTitle("Themes")
		.navigationBarTitleDisplayMode(.inline)
		.refreshable {
			themes = []
			cursor = nil
			done = false
			failed = nil
			await more()
		}
	}

	/// The next page, after those read.
	private func more() async {
		guard !loading, !done else { return }
		loading = true
		defer { loading = false }
		do {
			let page = try await workspace.client.listThemes(cursor: cursor)
			let seen = Set(themes.map(\.id))
			themes += page.themes.filter { !seen.contains($0.id) }
			failed = nil
			done = page.cursor == nil || page.cursor == cursor
			cursor = page.cursor
		} catch HUDError.signIn {
			// Signed out: the session says so.
			done = true
		} catch {
			failed = "Couldn't list themes: \(error.localizedDescription)"
		}
	}
}

/// Choosing a theme: drawn at once; refused, as it was, with why.
@MainActor
private enum Themes {
	static func choose(_ theme: Theme?, _ workspace: Workspace, refused: Binding<String?>) {
		refused.wrappedValue = nil
		Task {
			do {
				try await workspace.setTheme(theme)
			} catch HUDError.signIn {
				// Signed out: the session says so.
			} catch {
				refused.wrappedValue = "Couldn't change the theme: \(error.localizedDescription)"
			}
		}
	}
}

/// A theme to choose (nil: the system's): its swatch, name and, with
/// `byline`, who made it; a check where it is chosen.
private struct ThemeRow: View {
	let theme: Theme?
	let chosen: Bool
	var byline = false
	let choose: () -> Void

	var body: some View {
		Button(action: choose) {
			HStack {
				Label {
					VStack(alignment: .leading, spacing: 2) {
						Text(theme?.name ?? "System")
							.foregroundStyle(.primary)
						if byline, let creator = theme?.creator {
							Text("by \(creator.handle.map { "@\($0)" } ?? creator.did)")
								.font(.footnote)
								.foregroundStyle(.secondary)
						}
					}
				} icon: {
					if let palette = theme?.palette {
						ThemeSwatch(palette: palette)
					} else if let theme {
						Image(systemName: theme.colorScheme == .dark ? "moon" : "sun.max")
					} else {
						Image(systemName: "circle.lefthalf.filled")
					}
				}
				Spacer(minLength: 0)
				if chosen {
					Image(systemName: "checkmark")
						.foregroundStyle(.tint)
						.accessibilityHidden(true)
				}
			}
			.contentShape(.rect)
		}
		.accessibilityAddTraits(chosen ? .isSelected : [])
	}
}

/// A palette in small: its body, edged in its border, with its accent and
/// its text on it.
private struct ThemeSwatch: View {
	let palette: Palette

	var body: some View {
		RoundedRectangle(cornerRadius: 5, style: .continuous)
			.fill(palette[.background] ?? .clear)
			.overlay(alignment: .leading) {
				HStack(spacing: 3) {
					Circle().fill(palette[.accent] ?? .clear).frame(width: 8, height: 8)
					Capsule().fill(palette[.text] ?? .clear).frame(width: 9, height: 3)
				}
				.padding(.leading, 4)
			}
			.overlay(RoundedRectangle(cornerRadius: 5, style: .continuous).strokeBorder(palette[.border] ?? .clear, lineWidth: 1))
			.frame(width: 28, height: 20)
			.accessibilityHidden(true)
	}
}