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

/// A screen of the stack: its call's answer drawn as `StepView` draws it,
/// what opens from it on a screen of its own, a tab chosen in it on this
/// screen, in place of what it drew.
struct StepScreen: View {
	let step: Step
	let browser: Browser

	var body: some View {
		StepView(step: step, browser: browser, open: { browser.go($0) }, replace: { browser.replace(step, with: $0) })
			.hudText()
			.navigationTitle(step.title)
			.navigationBarTitleDisplayMode(.inline)
	}
}

/// A call's answer drawn by HUDKit, a page more loaded as the foot of its
/// list comes on screen, pulled down to load it afresh: a screen of the
/// stack, or a tile's body. A conversation (`Drawn.pagesItself`) scrolls
/// itself, its earlier messages loaded at its top and read afresh once it
/// sent. What opens from it goes to `open`, a tab's call
/// to `replace`; links in Safari. A call that needs an account says so in
/// place of its error; signed out (a Debug build's `-call` at launch), with
/// the way back to signing in.
/// A list newest first (a tree with `latest`) is asked now and then, while
/// on screen with the app active, whether something newer came: then a
/// button over its top says so, and goes to its top and reads it again.
/// Nothing newer is put in under the reader.
struct StepView: View {
	let step: Step
	let browser: Browser
	let open: @MainActor (Call) -> Void
	let replace: @MainActor (Call) -> Void
	@State private var context = ViewContext()
	/// The step whose context is wired: its result is drawn only then, as
	/// what it opens and writes is read from the context as it draws, and a
	/// context wired after (a step read before, drawn again as its tile
	/// comes back on screen) would leave its links opening nothing.
	@State private var wired: ObjectIdentifier?
	@Environment(\.scenePhase) private var phase

	/// How often a list newest first asks whether something newer came, and
	/// how long after it was read or asked it asks again as it comes back.
	private static let peekEvery: Duration = .seconds(60)
	private static let peekAfter: TimeInterval = 30

	var body: some View {
		Group {
			if !step.needsSignIn, let drawn = step.drawn, drawn.pagesItself, wired == ObjectIdentifier(step) {
				ResultView(drawn: drawn, context: context, onRetry: { Task { await step.load(browser.client) } })
			} else {
				ScrollViewReader { proxy in
					ScrollView {
						// Lazy, so the foot appears (and asks for a page more) only as
						// it comes on screen, not as soon as it is built.
						LazyVStack(alignment: .leading, spacing: Space.s3) {
							if step.needsSignIn {
								signIn
							} else if let drawn = step.drawn, wired == ObjectIdentifier(step) {
								ResultView(drawn: drawn, context: context, onRetry: { Task { await step.load(browser.client) } })
								foot(drawn)
							} else {
								ProgressView()
									.frame(maxWidth: .infinity)
									.padding(.top, 80)
							}
						}
						.frame(maxWidth: .infinity, alignment: .leading)
						.padding(.horizontal, Space.s3)
						.environment(\.listBleed, Space.s3)
						// A bleeding picture or map first meets the bar: no padding over it.
						.padding(.top, step.drawn?.leadsWithBleed == true && !step.needsSignIn ? 0 : Space.s2)
						.padding(.bottom, Space.s2)
						.id(Self.top)
					}
					.keepingScroll(of: step, drawn: wired == ObjectIdentifier(step) && step.drawn != nil)
					.overlay(alignment: .top) {
						if step.fresh, let noun = step.drawn?.latest?.noun {
							newer(noun) {
								withAnimation { proxy.scrollTo(Self.top, anchor: .top) }
								Task { await refresh() }
							}
						}
					}
				}
			}
		}
		.background(.tileSurface)
		.refreshable { await refresh() }
		// Another step in its place (a tab chosen in a tile): read and drawn afresh.
		.task(id: ObjectIdentifier(step)) {
			if step.drawn == nil { await step.load(browser.client) }
			configure()
		}
		// On screen with the app active: asked whether something newer came,
		// at once where it was read or asked long enough ago, then every
		// minute, until something did.
		.task(id: Peeking(step: ObjectIdentifier(step), active: phase == .active, listed: step.drawn?.latest != nil, fresh: step.fresh)) {
			guard phase == .active, !step.fresh, step.drawn?.latest != nil else { return }
			if Date.now.timeIntervalSince(step.checked) >= Self.peekAfter { await step.peek(browser.client) }
			while !Task.isCancelled, !step.fresh {
				try? await Task.sleep(for: Self.peekEvery)
				if Task.isCancelled { return }
				await step.peek(browser.client)
			}
		}
		.onDisappear { Task { await browser.feedback.flush() } }
	}

	/// The top of its scroll, which the button saying something newer came goes to.
	private static let top = "top"

	/// What the polling task restarts on.
	private struct Peeking: Hashable {
		let step: ObjectIdentifier
		let active: Bool
		let listed: Bool
		let fresh: Bool
	}

	/// Read afresh, its feed told anew of what is seen.
	private func refresh() async {
		step.told = []
		await step.load(browser.client)
		configure()
	}

	/// The button over its top saying something newer came ("New posts"):
	/// a piece of glass, as what floats over content is.
	private func newer(_ noun: String, action: @escaping () -> Void) -> some View {
		Button(action: action) {
			Label("New \(noun)", systemImage: "arrow.up")
				.font(.subheadline.weight(.semibold))
				.padding(.horizontal, Space.s3)
				.padding(.vertical, Space.s2)
				.hudGlass(in: Capsule(), interactive: true) { $0.background(.bar, in: Capsule()) }
		}
		.buttonStyle(.plain)
		.padding(.top, Space.s2)
		.transition(.move(edge: .top).combined(with: .opacity))
	}

	private var signIn: some View {
		ContentUnavailableView {
			Label("Sign in to see this", systemImage: "person.crop.circle.badge.questionmark")
		} description: {
			Text("This needs your account, signed in to this server.")
		} actions: {
			if browser.session == nil {
				Button("Sign in") { browser.path = [] }
					.buttonStyle(.borderedProminent)
			}
		}
	}

	@ViewBuilder
	private func foot(_ drawn: Drawn) -> some View {
		if drawn.nextPage != nil {
			Group {
				if let error = step.moreError {
					VStack(spacing: Space.s2) {
						Text(error).font(.footnote).foregroundStyle(.secondary)
						Button("Try again") { Task { await step.loadMore(browser.client) } }
					}
				} else if let next = drawn.nextPage {
					// One spinner a page: the next page's appears afresh, and asks
					// for it as it comes on screen.
					ProgressView()
						.id(next)
						.onAppear { Task { await step.loadMore(browser.client) } }
				}
			}
			.frame(maxWidth: .infinity)
			.padding(.vertical, Space.s4)
		}
	}

	/// The context the result draws with: its tree's trust (an untrusted
	/// view's writes ask first), where its clicks go, and what its feed is
	/// told. Writes need the account: a result made as none (no
	/// `_meta.viewer`) draws no actions and no forms; a form's photos
	/// upload through the workspace's client, as the account.
	private func configure() {
		defer { wired = ObjectIdentifier(step) }
		let browser = browser
		let step = step
		let open = open
		let ui: JSON? = if case .tree(let ui) = step.drawn { ui } else { nil }
		// Its URLs were held to its view's origins on the server.
		context.trusted = ui?["trusted"] == .bool(true)
		// An account a mention names opens in the app the tree is of, where
		// it has a page (`ui.people`), else across its apps.
		let people = ui?["people"]?.string
		context.onOpenActor = { actor in
			if let people {
				open(Call("describe_app", ["domain": .string(people), "actor": .string(actor)]))
			} else {
				open(Call("describe_repo", ["actor": .string(actor)]))
			}
		}
		context.onOpenLink = { browser.open($0) }
		context.onReplace = replace
		context.player = browser.player
		context.playerOrigin = AnyHashable(step)
		if step.viewer == nil {
			context.onAction = nil
			context.onTool = nil
			context.onUpload = nil
		} else {
			context.onAction = { (call: ActionCall) async throws -> String? in
				let result = try await browser.client.call(call.tool)
				if result.isError { throw HUDError.tool(result.text.isEmpty ? "The action failed." : result.text) }
				return result.created
			}
			context.onTool = { call in
				let result = try await browser.client.call(call)
				if result.isError { throw HUDError.tool(result.text.isEmpty ? "HUD couldn't do that." : result.text) }
				return result.structuredContent ?? [:]
			}
			if let client = browser.workspace?.client {
				context.onUpload = { bytes, progress in
					try await client.uploadBlob(bytes) { fraction in Task { @MainActor in progress(fraction) } }
				}
			} else {
				context.onUpload = nil
			}
		}
		context.onMore = {
			await step.loadMore(browser.client)
			if let error = step.moreError { throw HUDError.tool(error) }
		}
		context.onReload = { await step.load(browser.client) }
		configure(report: ui?["report"])
	}

	/// What a tree's feed is told (`ui.report`, `{ feed, seen }`), where
	/// `seen` says it may be: each item's `report` as it comes on screen, as
	/// it is opened, and with the event of an interaction it asks for.
	private func configure(report: JSON?) {
		let browser = browser
		let step = step
		let open = open
		guard let feed = report?["feed"]?.string, report?["seen"] == .bool(true) else {
			context.onCall = { call, _ in open(call) }
			context.onSeen = nil
			context.onInteraction = nil
			return
		}
		context.onCall = { call, report in
			if let report { browser.feedback.add(feed, report.merged(with: ["event": .string(Interactions.clickthrough)])) }
			open(call)
		}
		context.onSeen = { report in
			guard let uri = report["item"]?.string, !step.told.contains(uri) else { return }
			step.told.insert(uri)
			browser.feedback.add(feed, report.merged(with: ["event": .string(Interactions.seen)]))
		}
		context.onInteraction = { event, report in
			try await browser.feedback.now(feed, report.merged(with: ["event": .string(event)]))
		}
	}
}

extension View {
	/// Keep how far `step`'s scroll view is scrolled in `step`, and scroll
	/// back there once its result is `drawn` again, as the web's tile does
	/// with its body's `scrollTop`: a tile's view goes as it scrolls off the
	/// strip, its step stays. iOS 17 has no way to read or set an offset, so
	/// there it starts at the top.
	@ViewBuilder
	func keepingScroll(of step: Step, drawn: Bool) -> some View {
		if #available(iOS 18, *) {
			modifier(KeepsScroll(step: step, drawn: drawn))
		} else {
			self
		}
	}
}

@available(iOS 18, *)
private struct KeepsScroll: ViewModifier {
	let step: Step
	let drawn: Bool
	@State private var position = ScrollPosition(edge: .top)
	/// The step scrolled back to where it was; until then, the offset the
	/// scroll view starts at (its top) is not kept over the one it had.
	@State private var restored: ObjectIdentifier?

	func body(content: Content) -> some View {
		content
			.scrollPosition($position)
			.onScrollGeometryChange(for: CGFloat.self) { $0.contentOffset.y + $0.contentInsets.top } action: { _, y in
				if restored == ObjectIdentifier(step) { step.offset = max(y, 0) }
			}
			.task(id: Restore(step: ObjectIdentifier(step), drawn: drawn)) {
				guard drawn, restored != ObjectIdentifier(step) else { return }
				// Once what it draws is laid out, so there is somewhere to go.
				await Task.yield()
				if step.offset > 0 { position.scrollTo(y: step.offset) }
				restored = ObjectIdentifier(step)
			}
	}

	private struct Restore: Hashable {
		let step: ObjectIdentifier
		let drawn: Bool
	}
}