SPB Git

Repository Public

StudioViews.swift 11.7 KB 199 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Studio/StudioViews.swift3// Description: Research Studio: the list of research projects (synced `project` objects) and the page of the open one, with its tabs — overview, notes, reviews, memory — and the export sheet.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89enum StudioTab: String, CaseIterable { case overview, notes, reviews, memory }1011/// Launch arguments (DEBUG): `-VQProject <id>`, `-VQTab overview|notes|reviews|memory|export|add`,12/// `-VQXNote <note id>`, `-VQXVersions 1` (the versions list of the note is open), `-VQXNoteMode write|split|preview`.13struct StudioView: View {14    let app: AppEnvironment15    @Bindable var model: WindowModel16    @State private var tab: StudioTab = .overview17    @State private var noteId: String?18    @State private var exporting = false19    @State private var adding = false20    @State private var deleting: String?21    @State private var showArchived = false22    @State private var consumedLaunch = false2324    private var collection: VQSyncedCollection<VQProject>? { app.sync.active?.projects }25    private var all: [VQObject<VQProject>] { (collection?.items ?? []).sorted { $0.updatedAt > $1.updatedAt } }26    private var active: [VQObject<VQProject>] { all.filter { $0.data.status != .archived } }27    private var archived: [VQObject<VQProject>] { all.filter { $0.data.status == .archived } }28    private var selected: VQObject<VQProject>? { model.projectId.flatMap { collection?[$0] } }2930    var body: some View {31        HStack(spacing: 0) {32            // one sheet per view: two `.sheet` modifiers on the same view do not both present33            list.frame(width: 236)34                .sheet(isPresented: $adding) { if let p = selected { AddItemsSheet(app: app, projectId: p.id, project: p.data).vqTheme(app.vqTheme) } }35            VHairline()36            detail.frame(minWidth: 0, maxWidth: .infinity, maxHeight: .infinity).clipped()37                .sheet(isPresented: $exporting) { if let p = selected { ProjectExportSheet(app: app, projectId: p.id, project: p.data).vqTheme(app.vqTheme) } }38        }39        .background(VQTokens.Palette.ink0)40        .onAppear { consumeLaunch() }41        .onChange(of: collection?.isLoaded) { _, _ in consumeLaunch() }42        .onChange(of: model.projectId) { _, _ in if consumedLaunch { tab = .overview; noteId = nil } }43        .confirmationDialog("Delete “\(deleting.flatMap { collection?[$0]?.data.title } ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {44            Button("Delete Project", role: .destructive) {45                if let id = deleting { if model.projectId == id { model.projectId = nil }; Task { await app.studio.deleteProject(id) } }46            }47        } message: { Text("The project page and its saved versions are erased from your account on every device. Its conversations, computations and notes are not deleted: they stay where they are.") }48    }4950    // MARK: list5152    private var list: some View {53        VStack(alignment: .leading, spacing: 0) {54            HStack {55                Overline("Research projects")56                Spacer()57                Button { create() } label: { Image(systemName: "plus").font(.system(size: 12, weight: .semibold)) }58                    .buttonStyle(.borderless).help("New project").disabled(collection == nil)59                    .accessibilityIdentifier("studio.new")60            }61            .padding(.horizontal, VQTokens.Space.s4).padding(.top, VQTokens.Space.s4).padding(.bottom, VQTokens.Space.s2)62            ScrollView {63                VStack(alignment: .leading, spacing: 2) {64                    ForEach(active) { row($0) }65                    if active.isEmpty, collection?.isLoaded == true {66                        Text("No project yet. A project gathers a question, its hypotheses, and the conversations, computations and notes that answer it.")67                            .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).padding(VQTokens.Space.s3).fixedSize(horizontal: false, vertical: true)68                    }69                    if !archived.isEmpty {70                        Button { showArchived.toggle() } label: {71                            HStack(spacing: 4) { Image(systemName: showArchived ? "chevron.down" : "chevron.right").font(.system(size: 8, weight: .bold)); Overline("Archived · \(archived.count)") }72                                .padding(.horizontal, VQTokens.Space.s3).padding(.vertical, 8).contentShape(Rectangle())73                        }74                        .buttonStyle(.plain).accessibilityIdentifier("studio.archived")75                        if showArchived { ForEach(archived) { row($0) } }76                    }77                }78                .padding(.horizontal, VQTokens.Space.s2)79            }80        }81        .background(VQTokens.Palette.ink1)82    }8384    private func row(_ o: VQObject<VQProject>) -> some View {85        let p = o.data86        return MasterRow(isSelected: model.projectId == o.id) { model.projectId = o.id } content: {87            VStack(alignment: .leading, spacing: 3) {88                HStack(spacing: 6) {89                    Text(p.title.isEmpty ? "Untitled project" : p.title).font(VQTokens.Typography.bodySm.font.weight(.medium)).foregroundStyle(VQTokens.Palette.text1).lineLimit(1)90                    if collection?.pendingIDs.contains(o.id) == true { PendingSyncMark() }91                    Spacer(minLength: 0)92                }93                HStack(spacing: 6) {94                    ProjectStatusDot(status: p.status?.known ?? .active)95                    Text("\(Self.statusTitle(p.status)) · \(Self.counts(p))").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(1)96                }97                Text("Updated \(VQFormat.relative(o.updatedAt, language: .en))").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(1)98            }99        }100        .accessibilityIdentifier("studio.project.\(p.title)")101        .contextMenu {102            Button(p.status == .archived ? "Unarchive" : "Archive") { app.studio.update(o.id) { $0.status = .known(p.status == .archived ? .active : .archived) } }103            Divider()104            Button("Delete…", role: .destructive) { deleting = o.id }105        }106    }107108    static func statusTitle(_ s: VQOpen<VQProject.Status>?) -> String {109        guard let s else { return "Active" }110        switch s.known { case .active?: return "Active"; case .paused?: return "Paused"; case .done?: return "Done"; case .archived?: return "Archived"; case nil: return s.rawValue.capitalized }111    }112113    /// "2 conversations · 1 note": the three most numerous kinds.114    static func counts(_ p: VQProject) -> String {115        var by: [String: Int] = [:]116        for it in p.items { by[it.type.known?.title.lowercased() ?? it.type.rawValue, default: 0] += 1 }117        guard !by.isEmpty else { return "empty" }118        return by.sorted { ($0.value, $1.key) > ($1.value, $0.key) }.prefix(3).map { "\($0.value) \($0.key)\($0.value == 1 ? "" : "s")" }.joined(separator: " · ")119    }120121    // MARK: detail122123    @ViewBuilder private var detail: some View {124        if app.sync.active == nil {125            CenteredEmpty { VQEmptyState(systemImage: "icloud.slash", title: "Sync is off", message: "Research projects are kept in your account. Sign in to see them.") }126        } else if collection?.isLoaded != true {127            VStack(alignment: .leading, spacing: VQTokens.Space.s4) { VQSkeletonText(lines: 3); VQSkeletonRows(rows: 5, columns: 3) }.padding(VQTokens.Space.s6).frame(maxHeight: .infinity, alignment: .top)128        } else if let o = selected {129            VStack(alignment: .leading, spacing: 0) {130                tabBar(o)131                Hairline()132                switch tab {133                case .overview: ProjectOverview(app: app, model: model, object: o, pending: collection?.pendingIDs.contains(o.id) == true, addExisting: { adding = true },134                                                openNote: { noteId = $0; tab = .notes }, openReviews: { tab = .reviews })135                case .notes: ProjectNotesPane(app: app, projectId: o.id, project: o.data, noteId: $noteId)136                case .reviews: ProjectReviewsPane(app: app, model: model, projectId: o.id, project: o.data)137                case .memory: ProjectMemoryPane(app: app, projectId: o.id, project: o.data)138                }139            }140            .id(o.id)141        } else {142            CenteredEmpty {143            VQEmptyState(systemImage: "books.vertical", title: "Research Studio",144                         message: "A project keeps a research question together with its hypotheses, data sources, conversations, computations, notes and reviews — and exports the whole as one document.") {145                Button("New Project") { create() }.buttonStyle(EmberButtonStyle()).accessibilityIdentifier("studio.new.empty")146            }147            }148        }149    }150151    private func tabBar(_ o: VQObject<VQProject>) -> some View {152        let notes = (app.sync.active?.notes.items ?? []).filter { $0.data.projectId == o.id }.count153        let reviews = ProjectReviewsPane.reviews(app: app, projectId: o.id, project: o.data).count154        let memories = app.studio.memories(project: o.id).count155        return HStack(spacing: VQTokens.Space.s3) {156            VQSegmentedControl("Project", selection: $tab, options: [157                .init(.overview, "Overview"), .init(.notes, notes > 0 ? "Notes · \(notes)" : "Notes"),158                .init(.reviews, reviews > 0 ? "Reviews · \(reviews)" : "Reviews"), .init(.memory, memories > 0 ? "Memory · \(memories)" : "Memory")])159                .accessibilityIdentifier("studio.tabs")160            Spacer()161            Text(o.data.title).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(1).opacity(tab == .overview ? 0 : 1)162            Button { exporting = true } label: { Label("Export…", systemImage: "square.and.arrow.up") }.controlSize(.small)163                .help("Export the project as PDF, Markdown, LaTeX or ZIP").accessibilityIdentifier("studio.export")164        }165        .padding(.horizontal, VQTokens.Space.s6).padding(.vertical, VQTokens.Space.s2)166        .task(id: o.id) {167            if app.studio.memory == nil { await app.studio.loadMemory() }168            if app.studio.bundles[o.id] == nil { await app.studio.loadBundle(o.id) }169        }170    }171172    private func create() {173        Task { if let id = await app.studio.createProject(title: app.options.isUITest ? "mac-test-ui project" : "Untitled project") { model.projectId = id; tab = .overview } }174    }175176    private func consumeLaunch() {177        guard !consumedLaunch, collection?.isLoaded == true else { return }178        consumedLaunch = true179        if let t = model.launchTab {180            if let known = StudioTab(rawValue: t) { tab = known; model.launchTab = nil }181            // a sheet asked for while the window is still appearing is dropped: present it once the window is up182            else if t == "export" { model.launchTab = nil; DispatchQueue.main.asyncAfter(deadline: .now() + 1) { exporting = selected != nil } }183            else if t == "add" { model.launchTab = nil; DispatchQueue.main.asyncAfter(deadline: .now() + 1) { adding = selected != nil } }184        }185        if let n = app.options.extra["Note"] { noteId = n }186        if selected?.data.status == .archived { showArchived = true }187    }188}189190struct ProjectStatusDot: View {191    let status: VQProject.Status192    var body: some View {193        Circle().fill(color).frame(width: 6, height: 6).accessibilityHidden(true)194    }195    private var color: Color {196        switch status { case .active: VQTokens.Palette.accent; case .paused: VQTokens.Palette.warn; case .done: VQTokens.Palette.info; case .archived: VQTokens.Palette.text3 }197    }198}199
Files main
Menu

Theme