chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.4.0 Latest 5 packages
0
0
import SwiftUI
import Testing
import UIKit
@testable import HUDKit
/// What a view draws, at 1 pixel a point, so a colour's pixels can be found.
@MainActor private func pixels<V: View>(_ view: V, size: CGSize) async throws -> (w: Int, h: Int, rgba: [UInt8]) {
let host = UIHostingController(rootView: view.frame(width: size.width, height: size.height, alignment: .topLeading).ignoresSafeArea())
host.safeAreaRegions = []
let window = UIWindow(frame: CGRect(origin: .zero, size: size))
window.rootViewController = host
window.makeKeyAndVisible()
host.view.layoutIfNeeded()
try await Task.sleep(for: .milliseconds(300))
host.view.layoutIfNeeded()
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let image = UIGraphicsImageRenderer(size: size, format: format).image { c in
host.view.layer.render(in: c.cgContext)
}
try image.pngData()?.write(to: URL(fileURLWithPath: "/tmp/look-\(Int(size.width))x\(Int(size.height)).png"))
let w = Int(size.width), h = Int(size.height)
var rgba = [UInt8](repeating: 0, count: w * h * 4)
let ctx = CGContext(data: &rgba, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
ctx.draw(image.cgImage!, in: CGRect(origin: .zero, size: size))
window.isHidden = true
return (w, h, rgba)
}
/// The box of the pixels near `rgb`, top-left origin.
private func box(_ p: (w: Int, h: Int, rgba: [UInt8]), _ rgb: (Int, Int, Int), within: CGRect? = nil, excluding: CGRect? = nil) -> CGRect? {
var x0 = Int.max, y0 = Int.max, x1 = -1, y1 = -1
for y in 0..<p.h {
for x in 0..<p.w {
let pt = CGPoint(x: Double(x) + 0.5, y: Double(y) + 0.5)
if let within, !within.contains(pt) { continue }
if let excluding, excluding.contains(pt) { continue }
let i = (y * p.w + x) * 4
let r = Int(p.rgba[i]), g = Int(p.rgba[i + 1]), b = Int(p.rgba[i + 2])
if abs(r - rgb.0) < 24, abs(g - rgb.1) < 24, abs(b - rgb.2) < 24 {
x0 = min(x0, x); y0 = min(y0, y); x1 = max(x1, x); y1 = max(y1, y)
}
}
}
return x1 < 0 ? nil : CGRect(x: x0, y: y0, width: x1 - x0 + 1, height: y1 - y0 + 1)
}
private func theme(_ palette: [String: JSON]) -> Theme {
Theme(["key": "test", "palette": .object(palette)])!
}
@Suite struct LookTests {
/// Grain's profile: the handle, then Follows you in a Stack beside it.
/// The badge is as wide as its words, not the rest of the row, and centred
/// on the handle's line.
@Test @MainActor func badgeFitsItsWordsBesideTheHandle() async throws {
let handle: JSON = ["c": "Text", "p": ["style": "muted", "runs": [["text": "@alice.test"]]]]
let badge: JSON = ["c": "Badge", "p": ["value": "Follows you"]]
let row: JSON = ["c": "Row", "p": ["gap": "sm", "align": "center"], "k": [handle, ["c": "Stack", "k": [badge]]]]
let look = theme(["background": "#ffffff", "soft": "#ff0000", "border": "#ff0000", "text": "#00ff00", "textMuted": "#0000ff", "textFaint": "#0000ff"])
let p = try await pixels(ResolvedNode(node: row).environment(\.hudTheme, look).background(.white), size: CGSize(width: 390, height: 80))
let pill = try #require(box(p, (255, 0, 0)))
let words = try #require(box(p, (142, 142, 147), excluding: pill.insetBy(dx: -2, dy: -2)))
#expect(pill.width < 120, "badge \(pill) stretches")
#expect(pill.minX > words.maxX)
#expect(abs(pill.midY - words.midY) <= 2, "badge \(pill) handle \(words)")
}
/// A filled button (Follow) in the look's primary with its onPrimary
/// words; with no look, in the text's colour.
@Test @MainActor func filledButtonInThePrimary() async throws {
let look = theme(["background": "#ffffff", "text": "#0d1424", "primary": "#4a5df9", "onPrimary": "#ffffff"])
let pill = ActionPill(symbol: nil, label: "Follow", done: false).fixedSize().padding(8)
let p = try await pixels(pill.environment(\.hudTheme, look).background(.black), size: CGSize(width: 200, height: 120))
let fill = try #require(box(p, (0x4a, 0x5d, 0xf9)))
#expect(fill.width > 60 && fill.height >= 34, "fill \(fill)")
#expect(box(p, (255, 255, 255), within: fill.insetBy(dx: 12, dy: 6)) != nil, "white words")
let plain = try await pixels(pill.environment(\.hudTheme, theme(["background": "#ffffff", "text": "#0d1424"])).background(.black), size: CGSize(width: 200, height: 120))
#expect(box(plain, (0x0d, 0x14, 0x24)) != nil)
#expect(box(plain, (0x4a, 0x5d, 0xf9)) == nil)
}
/// A link drawn as a button in a Stack (Grain's Message on Germ under
/// Following) spans the Stack in the primary, as an action's button.
@Test @MainActor func linkButtonSpansItsStack() async throws {
let look = theme(["background": "#000000", "text": "#0d1424", "primary": "#4a5df9", "onPrimary": "#ffffff"])
let link: JSON = ["c": "Link", "p": ["label": "Message on Germ", "open": ["url": "https://germnetwork.com/dm"], "style": "button"]]
let stack: JSON = ["c": "Stack", "k": [link]]
var context = ViewContext()
context.onOpenLink = { _ in }
let p = try await pixels(ResolvedNode(node: stack).environment(\.viewContext, context).environment(\.hudTheme, look).background(.black), size: CGSize(width: 390, height: 80))
let fill = try #require(box(p, (0x4a, 0x5d, 0xf9)))
#expect(fill.width > 370 && fill.height >= 34, "fill \(fill)")
}
}
extension LookTests {
/// A photo wider than its frame, fitted whole: once loaded, its bands are
/// what holds it (blue), not the placeholder's fill (green).
@Test @MainActor func fittedPhotoHasNoBands() async throws {
let url = FileManager.default.temporaryDirectory.appendingPathComponent("wide-\(UUID()).png")
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let png = UIGraphicsImageRenderer(size: CGSize(width: 80, height: 20), format: format).pngData { c in
UIColor.red.setFill()
c.fill(CGRect(x: 0, y: 0, width: 80, height: 20))
}
try png.write(to: url)
let picture = Picture(source: Source(src: url.absoluteString, fallback: nil), fit: .fit)
.frame(width: 100, height: 100)
.environment(\.hudTheme, theme(["soft": "#00ff00"]))
.background(Color(red: 0, green: 0, blue: 1))
let p = try await pixels(picture, size: CGSize(width: 100, height: 100))
let photo = try #require(box(p, (255, 0, 0)))
#expect(photo.height < 30, "photo \(photo)")
#expect(box(p, (0, 255, 0)) == nil, "a band is filled")
#expect(box(p, (0, 0, 255), within: CGRect(x: 0, y: 0, width: 100, height: 30)) != nil, "band shows what holds it")
}
}
extension LookTests {
/// A clamped text the server cut (Grain's feed's description) draws
/// what it cut it to, a "Show more" under it in the accent; one it did
/// not cut draws whole, with none: nothing is measured. Markdown alike.
@Test @MainActor func aClampedTextDrawsTheServersCut() async throws {
let look = theme(["background": "#ffffff", "accent": "#ff0000"])
let whole: JSON = [["text": .string(String(repeating: "word ", count: 80))]]
let size = CGSize(width: 390, height: 400)
let draw = { (node: JSON) in try await pixels(ResolvedNode(node: node).environment(\.hudTheme, look).background(.white), size: size) }
let cut = try await draw(["c": "RichText", "p": ["clamp": 2, "runs": whole, "shownRuns": [["text": "word word…"]]]])
let words = try #require(box(cut, (0, 0, 0)))
let more = try #require(box(cut, (255, 0, 0)))
#expect(words.height < 30, "the cut, one line: \(words)")
#expect(more.minY > words.maxY, "Show more \(more) under the words \(words)")
let fits = try await draw(["c": "RichText", "p": ["clamp": 2, "runs": whole]])
#expect(box(fits, (255, 0, 0)) == nil)
#expect(try #require(box(fits, (0, 0, 0))).height > 100, "drawn whole")
let paragraph = { (runs: JSON) -> JSON in ["kind": "paragraph", "runs": runs] }
let blocks = try await draw(["c": "RichText", "p": ["clamp": 2, "blocks": [paragraph(whole)], "shownBlocks": [paragraph([["text": "word word…"]])]]])
#expect(try #require(box(blocks, (0, 0, 0))).height < 30)
#expect(box(blocks, (255, 0, 0)) != nil)
}
}