SPB Git

Repository Public License

EvolveAndPublishViews.swift 16.3 KB 284 lines swift

1import PrismObjectModel2import PrismProjectStore3import PrismRenderer4import PrismSatellitePublisher5import PrismIconKit6import SwiftUI78struct EvolveView: View {9    @Bindable var model: StudioModel10    @Bindable var session: ProjectSession11    @State private var rollbackTarget: SnapshotRecord?12    @State private var checking = false1314    var body: some View {15        ResizableSplit(initial: .second(330), minFirst: 380, minSecond: 260) {16            ScrollView {17                VStack(alignment: .leading, spacing: 14) {18                    if let proposal = session.proposal {19                        proposalCard(proposal)20                    } else {21                        ContentUnavailableView("No pending change", systemImage: "arrow.triangle.branch",22                                               description: Text("Ask for a change in the composer below. PRISM shows the proposal here; nothing is applied until you approve it."))23                            .frame(maxWidth: .infinity, minHeight: 160)24                    }25                    Divider()26                    Text("Conversation").font(.headline)27                    ForEach(session.conversation.suffix(40)) { ChatBubble(item: $0) }28                }29                .padding(18)30                .frame(maxWidth: .infinity, alignment: .leading)31            }32        } second: {33            VStack(alignment: .leading, spacing: 8) {34                Text("Versions").font(.headline)35                Text("Every saved version can be restored. Rolling back never changes your data.").font(.caption).foregroundStyle(.secondary)36                List(session.snapshots) { snapshot in37                    HStack {38                        VStack(alignment: .leading, spacing: 2) {39                            Text(snapshot.label).lineLimit(2)40                            Text("v\(snapshot.blueprintVersion) · \(snapshot.createdAt.formatted(date: .abbreviated, time: .shortened))").font(.caption).foregroundStyle(.secondary)41                        }42                        Spacer()43                        if snapshot.id == session.snapshots.first?.id { Text("Current").font(.caption).foregroundStyle(.secondary) }44                        else { Button("Roll Back") { rollbackTarget = snapshot } }45                    }46                }47                .listStyle(.inset)48            }49            .padding(14)50        }51        .confirmationDialog("Roll back to “\(rollbackTarget?.label ?? "")”?", isPresented: Binding(get: { rollbackTarget != nil }, set: { if !$0 { rollbackTarget = nil } }), presenting: rollbackTarget) { target in52            Button("Roll Back") { session.rollback(to: target) }53        } message: { _ in Text("The app's definition returns to that version. Your data stays exactly as it is, and you can roll forward again.") }54    }5556    private func proposalCard(_ proposal: Proposal) -> some View {57        VStack(alignment: .leading, spacing: 10) {58            Label("Proposed change · version \(proposal.blueprint.version)", systemImage: "doc.badge.gearshape").font(.title3.bold())59            if !proposal.message.isEmpty { Text(proposal.message).foregroundStyle(.secondary) }60            VStack(alignment: .leading, spacing: 4) {61                ForEach(proposal.diff.added) { o in DiffLine(symbol: "plus.circle.fill", color: .green, text: "\(o.name.isEmpty ? o.id : o.name)", detail: o.type) }62                ForEach(proposal.diff.removed) { o in DiffLine(symbol: "minus.circle.fill", color: .red, text: "\(o.name.isEmpty ? o.id : o.name)", detail: o.type) }63                ForEach(proposal.diff.changed) { c in DiffLine(symbol: "pencil.circle.fill", color: .orange, text: c.name.isEmpty ? c.id : c.name, detail: c.fields.joined(separator: ", ")) }64                if !proposal.diff.appFields.isEmpty { DiffLine(symbol: "gearshape.fill", color: .secondary, text: "App settings", detail: proposal.diff.appFields.joined(separator: ", ")) }65            }66            if !proposal.diff.addedPermissions.isEmpty {67                Label("Asks for new permissions: \(proposal.diff.addedPermissions.joined(separator: ", "))", systemImage: "lock.open.trianglebadge.exclamationmark").foregroundStyle(.orange)68            }69            if !proposal.migration.createdTables.isEmpty || !proposal.migration.addedColumns.isEmpty {70                Label("Data: adds \((proposal.migration.createdTables + proposal.migration.addedColumns).joined(separator: ", ")). Nothing is removed.", systemImage: "cylinder.split.1x2").font(.callout)71            }72            if proposal.checksRun {73                VStack(alignment: .leading, spacing: 2) { ForEach(proposal.checkLines, id: \.self) { Text($0).font(.callout.monospaced()) } }74                    .padding(8).background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 8))75            }76            HStack {77                Button { checking = true; Task { await session.runProposalChecks(); checking = false } } label: { Label(proposal.checksRun ? "Run Checks Again" : "Run Checks", systemImage: "checklist") }78                    .disabled(checking)79                Button("Approve and Apply") { session.approveProposal() }80                    .buttonStyle(.borderedProminent)81                    .disabled(!proposal.checksPassed)82                    .help(proposal.checksPassed ? "Apply this change; the current version stays available for rollback" : "Run the checks first; approval needs them to pass")83                Button("Discard", role: .destructive) { session.discardProposal() }84                if checking { ProgressView().controlSize(.small) }85            }86        }87        .padding(14)88        .frame(maxWidth: .infinity, alignment: .leading)89        .background(.background.secondary, in: RoundedRectangle(cornerRadius: 12))90        .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(.separator))91    }92}9394struct DiffLine: View {95    let symbol: String96    let color: Color97    let text: String98    let detail: String99100    var body: some View {101        HStack(alignment: .firstTextBaseline, spacing: 8) {102            Image(systemName: symbol).foregroundStyle(color).accessibilityHidden(true)103            Text(text)104            Text(detail).font(.caption.monospaced()).foregroundStyle(.secondary).lineLimit(2)105        }106        .accessibilityElement(children: .combine)107    }108}109110struct PublishView: View {111    @Bindable var model: StudioModel112    @Bindable var session: ProjectSession113    @State private var directory: URL?114    @State private var version = ""115    @State private var identity = ""116    @State private var identities: [String] = []117    @State private var confirmUninstall = false118    @State private var removeData = false119120    private var target: URL { directory ?? session.installed.map { URL(fileURLWithPath: $0.appPath).deletingLastPathComponent() } ?? session.defaultPublishDirectory }121122    var body: some View {123        ScrollView {124            VStack(alignment: .leading, spacing: 18) {125                Text("Publish as a desktop app").font(.title2.bold())126                Text("PRISM makes a separate macOS app with its own icon, window and Dock entry. It contains its own copy of the PRISM runtime, so it runs without PRISM.")127                    .foregroundStyle(.secondary)128129                if let blueprint = session.blueprint {130                    let designed = blueprint.icon.map { IconSpec.problems($0).isEmpty } ?? false131                    HStack(spacing: 14) {132                        if let image = IconRenderer.nsImage(SatelliteIcon.spec(for: blueprint, appId: blueprint.id), pixels: 256) {133                            Image(nsImage: image).resizable().frame(width: 84, height: 84).accessibilityLabel("App icon of \(blueprint.name)")134                        }135                        VStack(alignment: .leading, spacing: 4) {136                            Text(blueprint.name).font(.headline)137                            Text(designed ? "Icon designed for this app by the builder." : "This icon is drawn from the app's name. Ask the builder to “design an icon for this app” for a custom one.")138                                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)139                        }140                    }141                }142143                let errors = session.currentIssues.errors144                if !errors.isEmpty {145                    Label("Fix \(errors.count) problem(s) before publishing: \(errors[0].message)", systemImage: "xmark.octagon.fill").foregroundStyle(.red)146                }147                if model.publisher == nil {148                    Label("The satellite runtime is missing from this copy of PRISM, so publishing is unavailable.", systemImage: "exclamationmark.triangle.fill").foregroundStyle(.orange)149                }150151                GroupBox("Destination") {152                    Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 8) {153                        GridRow {154                            Text("Folder")155                            HStack {156                                Text(target.path).lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary)157                                Button("Choose…") { if let url = chooseFolder() { directory = url; session.preparePublish(directory: url, version: effectiveVersion, signingIdentity: effectiveIdentity) } }158                            }159                        }160                        GridRow {161                            Text("Version")162                            TextField("1.0.0", text: $version).frame(width: 110).textFieldStyle(.roundedBorder).accessibilityLabel("Version")163                        }164                        GridRow {165                            Text("Signature")166                            Picker("Signature", selection: $identity) {167                                Text("Ad hoc (this Mac only)").tag("")168                                ForEach(identities, id: \.self) { Text($0).tag($0) }169                            }170                            .labelsHidden().frame(maxWidth: 420)171                        }172                    }173                    .padding(6)174                }175176                HStack {177                    Button("Review Publish Plan") { session.preparePublish(directory: target, version: effectiveVersion, signingIdentity: effectiveIdentity) }178                        .disabled(model.publisher == nil || !errors.isEmpty || session.isPublishing)179                    if session.isPublishing { ProgressView().controlSize(.small); Text("Publishing and verifying…").foregroundStyle(.secondary) }180                }181182                if let plan = session.publishPlan { planCard(plan) }183                if let error = session.publishError { Label(error, systemImage: "xmark.octagon.fill").foregroundStyle(.red).textSelection(.enabled) }184                if let result = session.publishResult { resultCard(result) }185                if let installed = session.installed { installedCard(installed) }186            }187            .padding(24)188            .frame(maxWidth: 760, alignment: .leading)189            .frame(maxWidth: .infinity, alignment: .leading)190        }191        .onAppear {192            if version.isEmpty { version = session.nextVersion() }193            identities = SatellitePublisher.signingIdentities()194        }195        .confirmationDialog("Uninstall “\(session.record.name)”?", isPresented: $confirmUninstall) {196            Button("Uninstall, Keep Its Data") { session.uninstallSatellite(removeData: false) }197            Button("Uninstall and Delete Its Data", role: .destructive) { session.uninstallSatellite(removeData: true) }198        } message: { Text("The desktop app is removed. The project in PRISM is not affected.") }199    }200201    private var effectiveVersion: String { version.isEmpty ? session.nextVersion() : version }202    private var effectiveIdentity: String? { identity.isEmpty ? nil : identity }203204    private func chooseFolder() -> URL? {205        let panel = NSOpenPanel()206        panel.canChooseDirectories = true207        panel.canChooseFiles = false208        panel.canCreateDirectories = true209        panel.directoryURL = target210        panel.prompt = "Choose"211        return panel.runModal() == .OK ? panel.url : nil212    }213214    private func planCard(_ plan: PublishPlan) -> some View {215        GroupBox(plan.isUpdate ? "Update plan" : "Publish plan") {216            VStack(alignment: .leading, spacing: 8) {217                LabeledContent("App", value: "\(plan.manifest.displayName) \(plan.manifest.version)")218                LabeledContent("Bundle identifier", value: plan.manifest.appId)219                LabeledContent("Installs to", value: plan.destination.path)220                LabeledContent("Components", value: "\(plan.manifest.components.count) catalog component types")221                Divider()222                Text("Permissions").font(.headline)223                if plan.manifest.permissions.isEmpty { Text("None").foregroundStyle(.secondary) }224                ForEach(plan.manifest.permissions, id: \.self) { p in225                    HStack {226                        Image(systemName: plan.addedPermissions.contains(p) && plan.isUpdate ? "plus.circle.fill" : "checkmark.circle").foregroundStyle(plan.addedPermissions.contains(p) && plan.isUpdate ? .orange : .secondary)227                        Text(p).font(.callout.monospaced())228                        if plan.addedPermissions.contains(p) && plan.isUpdate { Text("new").font(.caption).foregroundStyle(.orange) }229                    }230                }231                ForEach(plan.removedPermissions, id: \.self) { p in Label("\(p) (no longer used)", systemImage: "minus.circle").foregroundStyle(.secondary) }232                Divider()233                Text("What to expect").font(.headline)234                ForEach(plan.notes, id: \.self) { Label($0, systemImage: "info.circle").font(.callout).foregroundStyle(.secondary) }235                if plan.isUpdate { Label("The current version is kept so you can roll back.", systemImage: "arrow.uturn.backward.circle").font(.callout).foregroundStyle(.secondary) }236                Button(plan.isUpdate ? "Approve and Update" : "Approve and Publish") { Task { await session.publish() } }237                    .buttonStyle(.borderedProminent)238                    .disabled(session.isPublishing)239            }240            .padding(6)241            .frame(maxWidth: .infinity, alignment: .leading)242        }243    }244245    private func resultCard(_ result: PublishResult) -> some View {246        GroupBox("Result") {247            VStack(alignment: .leading, spacing: 6) {248                Label("Installed at \(result.installed.appPath)", systemImage: "checkmark.circle.fill").foregroundStyle(.green)249                Text(result.signatureSummary).font(.caption.monospaced()).foregroundStyle(.secondary).textSelection(.enabled)250                if let report = session.launchReport {251                    Divider()252                    Text("Launch verification").font(.headline)253                    ForEach(report.lines, id: \.0) { line in254                        Label(line.0, systemImage: line.1 ? "checkmark.circle.fill" : "xmark.circle.fill").foregroundStyle(line.1 ? .green : .red).font(.callout)255                    }256                    if let failure = report.failure { Text(failure).font(.callout).foregroundStyle(.red) }257                }258            }259            .padding(6)260            .frame(maxWidth: .infinity, alignment: .leading)261        }262    }263264    private func installedCard(_ installed: InstalledSatellite) -> some View {265        GroupBox("Installed desktop app") {266            VStack(alignment: .leading, spacing: 8) {267                LabeledContent("Version", value: installed.version)268                LabeledContent("Location", value: installed.appPath)269                LabeledContent("Signature", value: installed.signing)270                HStack {271                    Button("Open") { NSWorkspace.shared.open(URL(fileURLWithPath: installed.appPath)) }272                    Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: installed.appPath)]) }273                    Button("Roll Back to \(installed.previousVersion ?? "previous")") { session.rollbackSatellite() }274                        .disabled(installed.previousPath == nil)275                        .help(installed.previousPath == nil ? "No earlier published version is kept" : "Put the previously published version back")276                    Button("Uninstall…", role: .destructive) { confirmUninstall = true }277                }278            }279            .padding(6)280            .frame(maxWidth: .infinity, alignment: .leading)281        }282    }283}284
Files main
Menu

Theme