import DocsKit import Foundation import RastrilloApple import RastrilloSnapshots import RastrilloTestSupport import SwiftUI import XCTest /// Docs' key screens for the screenshot gate (rastrillo/native /// RastrilloSnapshots): the library, Oficina ID onboarding as Docs shows it, /// Other ways to sign in, the team picker and, on the Mac, Settings. Drawn /// from fixtures with no server, keychain, App Group or network, in light and /// dark, and on iPhone at the default size and AX3. /// /// `native/scripts/snapshots.sh` runs it (compare, or record); `swift test` /// alone skips it, because baselines match only the OS that drew them. The /// Mac half runs from `swift test`; the iPhone half is the same file in the /// `DocsPhoneSnapshots` target of `ios/project.yml`. /// /// The editor's page is in EditorSnapshots.swift, with its own catalog: /// its document opens asynchronously, so its screens hold themselves /// unsettled until they are drawn. Bundled faces are registered first, or /// the baselines would record fallback faces. final class DocsSnapshots: XCTestCase { @MainActor func testKeyScreens() async throws { try XCTSkipUnless(ProcessInfo.processInfo.environment["RASTRILLO_SNAPSHOTS"] != nil, "Run with native/scripts/snapshots.sh") DocsFonts.register() let fixtures = await Fixtures.make() await assertSnapshots(of: Self.catalog(fixtures)) } @MainActor static func catalog(_ fixtures: Fixtures) -> SnapshotCatalog { var screens: [SnapshotScreen] = [ SnapshotScreen("library", mac: .fixed(width: 1000, height: 700), iphone: .fixed(width: 402, height: 874)) { Fixtures.library(["Quarterly plan", "Meeting notes, 12 January", "Letter to the landlord", "Recipes"]) }, SnapshotScreen("library-empty", mac: .fixed(width: 1000, height: 700), iphone: .fixed(width: 402, height: 874)) { Fixtures.library([]) }, SnapshotScreen("onboarding-welcome") { OficinaOnboardingView(model: fixtures.welcome, otherWays: {}) }, SnapshotScreen("onboarding-code") { OficinaOnboardingView(model: fixtures.code, otherWays: {}) }, SnapshotScreen("onboarding-teams") { OficinaOnboardingView(model: fixtures.teams, otherWays: {}) }, SnapshotScreen("other-ways", mac: .fixed(width: 520, height: 480), iphone: .fixed(width: 402, height: 640)) { RemountedOnScreen { DocsOtherWaysView(connection: Fixtures.connection()) {} } }, SnapshotScreen("team-picker", mac: .fixed(width: 460, height: 540), iphone: .fixed(width: 402, height: 720)) { DocsTeamPicker(model: fixtures.signedIn, current: fixtures.signedInState, otherWays: {}, signOut: {}, done: {}) }, SnapshotScreen("team-picker-blocked", mac: .fixed(width: 460, height: 540), iphone: .fixed(width: 402, height: 720)) { // Open documents or unsent changes: the switch and sign-out // are disabled, and the line says why. DocsTeamPicker(model: fixtures.signedIn, current: fixtures.signedInState, leaveCheck: { .sending }, otherWays: {}, signOut: {}, done: {}) }, ] #if os(macOS) screens.append(SnapshotScreen("settings", mac: .width(480), iphone: nil) { DocsSettingsView(account: .oficinaID(identity: "paul@tito.io", team: "Paul", teamLabel: "paulca"), block: nil, version: "0.1.0 (1)", manage: {}, signOut: {}, signIn: {}) }) screens.append(SnapshotScreen("settings-blocked", mac: .width(480), iphone: nil) { DocsSettingsView(account: .oficinaID(identity: "paul@tito.io", team: "Paul", teamLabel: "paulca"), block: .openDocuments, version: "0.1.0 (1)", manage: {}, signOut: {}, signIn: {}) }) screens.append(SnapshotScreen("settings-server", mac: .width(480), iphone: nil) { DocsSettingsView(account: .server(name: "Tito", host: "tito.docs.oficina.works"), block: nil, version: "0.1.0 (1)", manage: {}, signOut: {}, signIn: {}) }) #endif return SnapshotCatalog(app: "docs", settings: SnapshotSettings(tint: OficinaPalette.accent(.docs)), screens: screens) } } /// Oficina ID models walked to each step through the kit's in-memory Home, /// directory and instances, exactly as a person would get there: nothing /// touches the keychain, an App Group or the network. @MainActor final class Fixtures { static let origin = URL(string: "https://docs.snapshot.invalid")! let welcome: OficinaIDModel let code: OficinaIDModel let teams: OficinaIDModel let signedIn: OficinaIDModel let signedInState: OficinaSignedIn private init(welcome: OficinaIDModel, code: OficinaIDModel, teams: OficinaIDModel, signedIn: OficinaIDModel, state: OficinaSignedIn) { self.welcome = welcome; self.code = code; self.teams = teams; self.signedIn = signedIn; signedInState = state } static func make() async -> Fixtures { let welcome = model(), code = model(), teams = model(), signedIn = model() await welcome.start() await walk(code, to: 1) await walk(teams, to: 2) await walk(signedIn, to: 2) if case .teams(let list) = signedIn.step, let first = list.first { await signedIn.choose(first) } guard case .signedIn(let state) = signedIn.step else { preconditionFailure("fixture did not sign in: \(signedIn.step)") } return Fixtures(welcome: welcome, code: code, teams: teams, signedIn: signedIn, state: state) } private static func team(_ sqid: String, _ name: String, _ label: String) -> OficinaTeam { OficinaTeam(sqid: sqid, label: label, name: name, role: "member", apps: [OficinaTeamApp(app: "docs", origin: "https://\(label).docs.oficina.works", consumerID: "\(sqid)-docs")]) } private static func model() -> OficinaIDModel { let service = FakeOficinaIDService() service.addPerson(email: "paul@tito.io", identityID: "id-paul") let teams = [team("t1", "Paul", "paulca"), team("t2", "Tito", "tito"), team("t3", "Campbells", "campbells")] service.setTeams(teams, for: "id-paul") for team in teams { service.admit("id-paul", at: team.origin(for: "docs")!, as: .linked) } let suite = "DocsSnapshots.\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suite)! defaults.removePersistentDomain(forName: suite) let store = OficinaIDStore(shared: OficinaMemoryStore(), appPrivate: OficinaMemoryStore(), group: defaults) return OficinaIDModel(configuration: DocsOficinaSession.configuration, store: store, service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { SnapshotSettings.now }, appDefaults: defaults) } /// 1: the code step. 2: the team step, after the code. private static func walk(_ model: OficinaIDModel, to stage: Int) async { await model.start() model.continueWithEmail() model.email = "paul@tito.io" await model.submitEmail() guard stage > 1 else { return } model.code = FakeOficinaIDService.goodCode await model.submitCode() } /// A workspace whose server answers the document list and nothing else. static func library(_ titles: [String]) -> some View { let documents = titles.enumerated().map { #"{"sqid":"d\#($0.offset)","title":"\#($0.element)","shared":\#($0.offset == 1)}"# } let list = Data(#"{"documents":[\#(documents.joined(separator: ","))],"can_create":true}"#.utf8) let server = ScriptedTransport(origin: origin) { call in call.path.hasPrefix("/?") ? .respond(status: 200, body: list) : .respond(status: 404) } return DocsWorkspace(client: NativeHTTP(origin: origin), transport: { server }, accounts: {}, signOut: {}, accountsLabel: DocsOficinaSession.teamsTitle, signOutLabel: OficinaIDText.text("signOut", "paul@tito.io")) } /// A connection on a throwaway defaults suite and an origin no app holds /// a credential for, so `NativeConnection.init`'s legacy-credential /// migration can never find (and move) a real item. static func connection() -> NativeConnection { let suite = "DocsSnapshots.connection.\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suite)! defaults.removePersistentDomain(forName: suite) let connection = NativeConnection(defaultServer: origin.absoluteString, defaults: defaults, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied))) connection.serverAddress = "https://docs.oficina.works" return connection } } /// Builds its content again once it is on screen, and draws only that /// second build. On the Mac, "Other ways"'s rounded text fields (in the /// kit's `NativeSignInView`) are sometimes made 30 points tall instead of 24 /// when the screen is first built, more often under load, and keep that /// height: about one gate run in twenty under a light load, and both /// pictures of that run (finding 4 on #161). Built again inside a window /// that is already showing, they came out 24 every time (50 runs under /// the same load, 200 fields). struct RemountedOnScreen: View { @ViewBuilder let content: () -> Content @State private var built = false var body: some View { content().id(built).task { guard !built else { return } await Task.yield() built = true } } }