~ 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
194 lines · 6.3 KB Raw History
import HUDKit
import SwiftUI

/// Signing in, by handle, as knotless's sign-in form: HUD's mark over a
/// field for the handle and a button. Whoever matches what is typed
/// (`place.hud.searchActors`, asked of the server as no one) takes the
/// mark's place right above the field, as the keyboard covers what is
/// under it; picking one signs in at once. The handle goes to the server as
/// the request's `login_hint`, so it goes straight on to the account's own
/// server. Signed out, the app's root; from Settings, another account
/// added. The system's look, whatever the theme.
struct SignInScreen: View {
	let browser: Browser
	/// What it says under the button, but for a failure.
	var why = "With your Bluesky or other atproto account."
	@State private var handle = ""
	@State private var found: [FoundActor] = []
	/// The handle just picked, which needs no more suggestions.
	@State private var picked: String?
	@FocusState private var typing: Bool
	@Environment(\.webAuthenticationSession) private var web
	/// A policy page shown in Safari over the screen, which may be a sheet.
	@State private var page: Page?

	/// The field's and the button's height.
	private static let control: CGFloat = 52
	/// A suggestion's least height.
	private static let row: CGFloat = 56
	private static let avatar: CGFloat = 30
	private static let corner: CGFloat = 20

	private var name: String { handle.trimmingCharacters(in: .whitespaces) }
	private var busy: Bool { browser.signingIn }
	private var ready: Bool { !name.isEmpty && !busy }
	private var suggesting: Bool { typing && !busy && !found.isEmpty && handle != picked }

	var body: some View {
		VStack(spacing: Space.s3) {
			Spacer(minLength: Space.s4)
			if suggesting {
				suggestions
			} else {
				Image("mark")
					.renderingMode(.template)
					.resizable()
					.scaledToFit()
					.frame(width: 112)
					.foregroundStyle(.primary)
					.accessibilityLabel("HUD")
				Spacer(minLength: Space.s4)
			}

			TextField("alice.bsky.social", text: $handle)
				.textContentType(.username)
				.textInputAutocapitalization(.never)
				.autocorrectionDisabled()
				.keyboardType(.URL)
				.submitLabel(.go)
				.focused($typing)
				.onSubmit(go)
				.padding(.horizontal, Space.s5)
				.frame(minHeight: Self.control)
				.background(Color(.secondarySystemBackground), in: .capsule)
				.accessibilityLabel("Your handle")

			Button(action: go) {
				Group {
					if busy {
						ProgressView().tint(Color(.systemBackground))
					} else {
						Text("Sign in").font(.body.weight(.semibold))
					}
				}
				.foregroundStyle(ready || busy ? Color(.systemBackground) : .secondary)
				.frame(maxWidth: .infinity, minHeight: Self.control)
				.background(ready || busy ? Color.primary : Color(.tertiarySystemFill), in: .capsule)
				.contentShape(.capsule)
			}
			.buttonStyle(.plain)
			.disabled(!ready)

			Group {
				if let failure = browser.signInError {
					Text(failure).foregroundStyle(.red)
				} else {
					Text(why).foregroundStyle(.secondary)
				}
			}
			.font(.footnote)
			.multilineTextAlignment(.center)
			.fixedSize(horizontal: false, vertical: true)

			Text(terms)
				.font(.caption)
				.foregroundStyle(.secondary)
				.tint(.secondary)
				.multilineTextAlignment(.center)
				.fixedSize(horizontal: false, vertical: true)
				.environment(\.openURL, OpenURLAction { url in
					page = Page(url: url)
					return .handled
				})
				.padding(.bottom, Space.s5)
		}
		.padding(.horizontal, Space.s5)
		.frame(maxWidth: .infinity, maxHeight: .infinity)
		.background(Color(.systemBackground))
		.contentShape(.rect)
		.onTapGesture { typing = false }
		.sheet(item: $page) { page in
			SafariView(url: page.url).ignoresSafeArea()
		}
		// Asked a moment after typing stops; one overtaken by more typing is let go.
		.task(id: handle) {
			guard handle != picked else { return }
			try? await Task.sleep(for: .milliseconds(150))
			guard !Task.isCancelled else { return }
			let actors = await FoundActor.search(handle, on: browser.serverURL)
			if !Task.isCancelled { found = actors }
		}
	}

	private var suggestions: some View {
		ScrollView {
			VStack(spacing: 0) {
				ForEach(found) { actor in
					Button { pick(actor) } label: {
						HStack(spacing: Space.s3) {
							avatar(actor)
							VStack(alignment: .leading, spacing: 0) {
								if let name = actor.displayName {
									Text(name).font(.subheadline.weight(.semibold)).lineLimit(1)
								}
								Text("@\(actor.handle)").font(.footnote).foregroundStyle(.secondary).lineLimit(1)
							}
							Spacer(minLength: 0)
						}
						.padding(.horizontal, Space.s4)
						.frame(minHeight: Self.row)
						.contentShape(.rect)
					}
					.buttonStyle(.plain)
					.accessibilityLabel(actor.displayName.map { "\($0), @\(actor.handle)" } ?? "@\(actor.handle)")
				}
			}
		}
		.scrollBounceBehavior(.basedOnSize)
		.frame(maxHeight: Self.row * CGFloat(found.count))
		.background(Color(.secondarySystemBackground), in: .rect(cornerRadius: Self.corner))
		.clipShape(.rect(cornerRadius: Self.corner))
		// It takes the room it asks for before the space above it does.
		.layoutPriority(1)
	}

	private func avatar(_ actor: FoundActor) -> some View {
		AsyncImage(url: actor.avatar) { phase in
			if let image = phase.image {
				image.resizable().scaledToFill()
			} else {
				Image(systemName: "person.crop.circle.fill")
					.resizable()
					.foregroundStyle(.tertiary)
			}
		}
		.frame(width: Self.avatar, height: Self.avatar)
		.clipShape(.circle)
		.accessibilityHidden(true)
	}

	/// Fills it in and goes on, as the button would.
	private func pick(_ actor: FoundActor) {
		picked = actor.handle
		handle = actor.handle
		go()
	}

	private func go() {
		guard ready else { return }
		typing = false
		let name = name
		Task { await browser.signIn(name, using: web) }
	}

	/// knotless's footnote: the policies, on this server's pages.
	private var terms: AttributedString {
		let base = browser.serverURL.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
		let markdown = "By signing in you accept our [Terms](\(base)/terms), [Privacy policy](\(base)/privacy) and [Community guidelines](\(base)/guidelines)."
		var text = (try? AttributedString(markdown: markdown)) ?? AttributedString(markdown)
		for run in text.runs where run.link != nil {
			text[run.range].underlineStyle = .single
		}
		return text
	}
}