SPB Git

Repository Public

LiveSeed.swift 5.8 KB 104 lines swift

1// SP Notes iOS2// File: App/LiveSeed.swift3// Description: DEBUG only (`SPNOTES_LIVE_SEED=1`, UI tests against the INTEGRATION server, never production): creates through the4//              API the few rows the hosted screens need to show something — two linked notes, a database with rows, a canvas, a5//              task, a reference — under fixed ids, so running it again (other simulator, other run) creates nothing twice.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9#if DEBUG10import Observation11import SPNotesCore12import SwiftUI1314@MainActor15@Observable16final class LiveSeed {17    static let shared = LiveSeed()18    static var isRequested: Bool { ProcessInfo.processInfo.environment["SPNOTES_LIVE_SEED"] == "1" }1920    enum ID {21        static let noteA = "5eed1111-0000-4000-8000-000000000001", noteB = "5eed1111-0000-4000-8000-000000000002"22        static let database = "5eed1111-0000-4000-8000-000000000003", canvas = "5eed1111-0000-4000-8000-000000000004"23        static let task = "5eed1111-0000-4000-8000-000000000005", reference = "5eed1111-0000-4000-8000-000000000006"24        static let relation = "5eed1111-0000-4000-8000-000000000007"25        static let rows = ["5eed1111-0000-4000-8000-000000000008", "5eed1111-0000-4000-8000-000000000009"]26        static let rowPages = ["5eed1111-0000-4000-8000-00000000000a", "5eed1111-0000-4000-8000-00000000000b"]27    }2829    /// nil while running; then "done" or what failed (shown to the UI test through an accessibility value).30    private(set) var state: String?31    private var started = false3233    func run(_ app: AppModel) async {34        guard Self.isRequested, !started else { return }35        started = true36        // never against production, whatever the environment says37        guard app.configuration.api.baseURL.host == "localhost" || app.configuration.api.baseURL.host == "127.0.0.1" else { state = "refused: not a local test server"; return }38        var problems: [String] = []39        func attempt(_ name: String, _ body: () async throws -> Void) async {40            do { try await body() } catch { problems.append("\(name): \(error)") }41        }42        _ = await app.syncAndWait()43        let api = app.api44        func paragraph(_ text: String) -> RawJSON {45            RawJSON(string: #"{"type":"doc","content":[{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"Contexte"}]},{"type":"paragraph","content":[{"type":"text","text":"\#(text)"}]},{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"Suite"}]},{"type":"paragraph","content":[{"type":"text","text":"Deuxième section de la page de test."}]}]}"#)46        }47        if (try? await app.store.page(id: ID.noteA)) == nil {48            await attempt("note A") { _ = try await api.createPage(PageDraft(id: ID.noteA, title: "UI · Hypothèse de loyer", content: paragraph("Les loyers suivent le revenu net du quartier.")), idempotencyKey: ID.noteA) }49        }50        if (try? await app.store.page(id: ID.noteB)) == nil {51            await attempt("note B") { _ = try await api.createPage(PageDraft(id: ID.noteB, title: "UI · Données de marché", content: paragraph("Relevé de quarante logements comparables.")), idempotencyKey: ID.noteB) }52        }53        // an existing relation answers 409 relation_exists: not a problem54        _ = try? await api.createRelation(RelationDraft(id: ID.relation, fromId: ID.noteB, toId: ID.noteA, relType: RelationType.supports))55        if (try? await app.store.page(id: ID.database)) == nil {56            await attempt("database page") { _ = try await api.createPage(PageDraft(id: ID.database, title: "UI · Immeubles", type: .database), idempotencyKey: ID.database) }57        }58        await attempt("database rows") {59            let database = try await api.database(id: ID.database)60            for (index, title) in ["UI · 12 rue Laurel", "UI · 255 montée Dalton"].enumerated() {61                _ = try await api.createDatabaseRow(databaseID: database.id, DatabaseRowDraft(id: ID.rows[index], pageId: ID.rowPages[index], title: title))62            }63        }64        if (try? await app.store.page(id: ID.canvas)) == nil {65            await attempt("canvas") { _ = try await app.repositories.canvases.create(title: "UI · Carte du projet", id: ID.canvas) }66        }67        if (try? await app.repositories.tasks.task(id: ID.task)) == nil {68            await attempt("task") { _ = try await app.repositories.tasks.create(title: "UI · Vérifier les comparables", priority: .high, pageId: ID.noteA, id: ID.task) }69        }70        await attempt("reference") {71            _ = try await api.createReference(ReferenceDraft(id: ID.reference, pageId: ID.noteA, citeKey: "rosen1974", entryType: "article", title: "Hedonic Prices and Implicit Markets", authors: ["Sherwin Rosen"], year: 1974))72        }73        _ = await app.syncAndWait()74        _ = await app.syncAndWait()75        state = problems.isEmpty ? "done" : problems.joined(separator: " | ")76    }77}7879private struct LiveSeedMarker: ViewModifier {80    @Environment(AppModel.self) private var app81    @State private var seed = LiveSeed.shared8283    func body(content: Content) -> some View {84        content85            .overlay(alignment: .topLeading) {86                if let state = seed.state {87                    Text(state).font(.system(size: 1)).foregroundStyle(.clear).frame(width: 2, height: 2).accessibilityIdentifier("live-seed-state").accessibilityLabel(state)88                }89            }90            .task { await seed.run(app) }91    }92}9394extension View {95    /// DEBUG: runs the live seed when asked and tells the UI tests when it is done.96    @ViewBuilder func liveSeedMarker() -> some View {97        if LiveSeed.isRequested { modifier(LiveSeedMarker()) } else { self }98    }99}100#else101import SwiftUI102extension View { func liveSeedMarker() -> some View { self } }103#endif104
Files main
Menu

Theme