SPB Git

Repository Public

StudioPanels.swift 29.6 KB 476 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Studio/StudioPanels.swift3// Description: The other panes and sheets of a research project: automated reviews (always labelled as such), project memory (add, edit, pin, expiry, delete), export to PDF / Markdown / LaTeX / ZIP through a native save panel, and the picker that adds existing things to the project.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910// MARK: - Reviews1112struct ProjectReviewsPane: View {13    let app: AppEnvironment14    let model: WindowModel15    let projectId: String16    let project: VQProject1718    /// Reviews filed in the project, listed among its items, or whose target is one of its items.19    static func reviews(app: AppEnvironment, projectId: String, project: VQProject) -> [VQObject<VQReview>] {20        let items = project.items21        let listed = Set(items.filter { $0.type == .review }.map(\.ref))22        let targets = Set(items.map(\.ref))23        return (app.sync.active?.reviews.items ?? []).filter { r in24            r.data.projectId == projectId || listed.contains(r.id) || (r.data.target.map { targets.contains($0.id) } ?? false)25        }.sorted { ($0.data.startedAt ?? $0.updatedAt) > ($1.data.startedAt ?? $1.updatedAt) }26    }2728    var body: some View {29        let reviews = Self.reviews(app: app, projectId: projectId, project: project)30        ScrollView {31            VStack(alignment: .leading, spacing: VQTokens.Space.s5) {32                if reviews.isEmpty {33                    VQEmptyState(systemImage: "checkmark.seal", title: "No review yet",34                                 message: "An automated review checks a conversation, a computation or a note: deterministic checks first, then a reviewer model that re-queries the data. It is started with “Request review” on the thing to review, and appears here when it belongs to this project. It is never a human peer review.")35                }36                ForEach(reviews) { r in ReviewCard(app: app, model: model, review: r, project: project) }37            }38            .padding(.horizontal, VQTokens.Space.s8).padding(.vertical, VQTokens.Space.s6)39            .frame(maxWidth: 920, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)40        }41    }42}4344private struct ReviewCard: View {45    let app: AppEnvironment46    let model: WindowModel47    let review: VQObject<VQReview>48    let project: VQProject4950    var body: some View {51        let r = review.data52        VStack(alignment: .leading, spacing: VQTokens.Space.s3) {53            Rectangle().fill(VQTokens.Palette.text1).frame(height: VQTokens.hairline)54            HStack(spacing: VQTokens.Space.s2) {55                Image(systemName: "cpu").font(.system(size: 11)).foregroundStyle(VQTokens.Palette.text2)56                Text("Automated review — not a human peer review").font(VQTokens.Typography.overline.font).tracking(VQTokens.Typography.overline.tracking).textCase(.uppercase).foregroundStyle(VQTokens.Palette.text2)57                    .accessibilityIdentifier("review.label")58                Spacer()59                statusChip(r)60            }61            HStack(alignment: .firstTextBaseline, spacing: VQTokens.Space.s2) {62                Text(targetTitle(r)).font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1).lineLimit(2)63                Spacer()64                if let t = r.target, t.type.known != nil { Button { open(t) } label: { Label("Open Target", systemImage: "arrow.up.right") }.buttonStyle(.borderless).controlSize(.small) }65            }66            if let verdict = r.verdict, !verdict.isEmpty {67                VStack(alignment: .leading, spacing: 3) {68                    Overline("Verdict of the reviewer model")69                    VQMarkdownText(verdict)70                }71            } else if r.status == .running {72                Text("The reviewer model is still working; the deterministic checks below are already final.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text2)73            }74            if let e = r.error, !e.isEmpty { Text("The reviewer did not finish: \(e)").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.critical).fixedSize(horizontal: false, vertical: true) }75            let checks = r.checks76            if !checks.isEmpty {77                let errors = checks.filter { $0.severity == .error }.count, warnings = checks.filter { $0.severity == .warning }.count78                HStack(spacing: VQTokens.Space.s2) {79                    Overline("Checks · \(checks.count)")80                    if errors > 0 { QuietChip(text: "\(errors) error\(errors == 1 ? "" : "s")", tint: VQTokens.Palette.critical) }81                    if warnings > 0 { QuietChip(text: "\(warnings) warning\(warnings == 1 ? "" : "s")", tint: VQTokens.Palette.warn) }82                }83                VStack(alignment: .leading, spacing: 0) {84                    ForEach(checks) { c in85                        Hairline()86                        HStack(alignment: .top, spacing: VQTokens.Space.s3) {87                            Image(systemName: c.severity == .error ? "xmark.octagon.fill" : c.severity == .warning ? "exclamationmark.triangle.fill" : "info.circle")88                                .font(.system(size: 12)).foregroundStyle(c.severity == .error ? VQTokens.Palette.critical : c.severity == .warning ? VQTokens.Palette.warn : VQTokens.Palette.text3).frame(width: 16).padding(.top, 2)89                                .accessibilityLabel(c.severity.rawValue)90                            VStack(alignment: .leading, spacing: 3) {91                                HStack(spacing: 6) {92                                    Text(c.category.rawValue.capitalized).font(VQTokens.Typography.caption.font.weight(.semibold)).foregroundStyle(VQTokens.Palette.text2)93                                    Text(c.isFromReviewerModel ? "reviewer model" : "deterministic check").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)94                                }95                                Text(c.finding).font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text1).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)96                                if let ev = c.evidence, !ev.isEmpty { Text(ev).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }97                            }98                        }99                        .padding(.vertical, VQTokens.Space.s2)100                    }101                }102            }103            HStack(spacing: VQTokens.Space.s3) {104                if let m = r.model { Text("Reviewer: \(m)").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }105                if let s = r.startedAt { Text("Started \(VQFormat.dateTime(s, language: .en))").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }106                if let c = r.usage?.costUsd { Text("Cost \(VQFormat.cost(c, locale: app.numberLocale))").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }107            }108            if let d = r.disclaimer, !d.isEmpty { Text(d).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true) }109        }110        .accessibilityElement(children: .contain)111        .accessibilityIdentifier("review.card.\(review.id)")112    }113114    private func statusChip(_ r: VQReview) -> some View {115        switch r.status.known {116        case .done?: QuietChip(text: "Done", systemImage: "checkmark", tint: VQTokens.Palette.text2)117        case .error?: QuietChip(text: "Reviewer failed", systemImage: "xmark", tint: VQTokens.Palette.critical)118        case .running?: QuietChip(text: "Running", systemImage: "hourglass", tint: VQTokens.Palette.accentText)119        case nil: QuietChip(text: r.status.rawValue.capitalized)120        }121    }122123    private func targetTitle(_ r: VQReview) -> String {124        guard let t = r.target else { return "Review" }125        let kind: String126        switch t.type.known { case .session?: kind = "Conversation"; case .quantJob?: kind = "Computation"; case .note?: kind = "Note"; case nil: kind = t.type.rawValue.capitalized }127        if let item = project.items.first(where: { $0.ref == t.id }) {128            if let title = item.title ?? app.studio.bundles.values.lazy.flatMap(\.items).first(where: { $0.item.ref == t.id })?.resolved?.title { return "\(kind) · \(title)" }129        }130        if t.type == .note, let n = app.sync.active?.notes[t.id]?.data.title { return "\(kind) · \(n)" }131        return "\(kind) \(t.id.prefix(8))"132    }133134    private func open(_ t: VQReview.Target) {135        switch t.type.known {136        case .session?: model.openConversation(t.id)137        case .quantJob?: model.openQuantJob(t.id)138        case .note?, nil: break139        }140    }141}142143// MARK: - Memory (CONTRACT §6)144145struct ProjectMemoryPane: View {146    let app: AppEnvironment147    let projectId: String148    let project: VQProject149    @State private var draft = ""150    @State private var kind: VQMemory.Kind = .project151    @State private var pinned = false152153    private var store: StudioStore { app.studio }154155    var body: some View {156        let memories = store.memories(project: projectId)157        ScrollView {158            VStack(alignment: .leading, spacing: VQTokens.Space.s4) {159                Rectangle().fill(VQTokens.Palette.text1).frame(height: VQTokens.hairline)160                HStack(alignment: .firstTextBaseline) {161                    VStack(alignment: .leading, spacing: 3) {162                        Text("Project memory").font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1)163                        Text("What the agent is told in every conversation of this project — and only there. Memories of your account as a whole are in Agent.")164                            .font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true)165                    }166                    Spacer()167                    if store.memoryLoading { ProgressView().controlSize(.small) }168                    Button { Task { await store.loadMemory() } } label: { Image(systemName: "arrow.clockwise") }.buttonStyle(.borderless).help("Reload")169                }170                if let s = store.memory?.settings {171                    if !s.enabled { notice("Memory is switched off in your settings: nothing is injected into conversations, and the agent cannot save memories. You can still manage them here.", VQTokens.Palette.warn) }172                    else if let d = s.retentionDays { notice("Retention: an unpinned memory expires \(d) day\(d == 1 ? "" : "s") after it was written or last revised. Pinning exempts it.", VQTokens.Palette.text3) }173                }174                if let e = store.memoryError { notice(e, VQTokens.Palette.critical) }175                HStack(alignment: .bottom, spacing: VQTokens.Space.s2) {176                    TextField("Add a memory for this project (a definition, a data caveat, a decision…)", text: $draft, axis: .vertical)177                        .textFieldStyle(.plain).font(VQTokens.Typography.bodySm.font).lineLimit(1...4).onSubmit { add() }178                        .accessibilityIdentifier("memory.new")179                    Picker("Kind", selection: $kind) { ForEach(VQMemory.Kind.allCases, id: \.self) { Text($0.rawValue.capitalized).tag($0) } }.labelsHidden().controlSize(.small).fixedSize()180                    Toggle(isOn: $pinned) { Image(systemName: "pin") }.toggleStyle(.button).controlSize(.small).help("Pin: never expires by retention")181                    Button("Add") { add() }.buttonStyle(EmberButtonStyle()).disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty).accessibilityIdentifier("memory.add")182                }183                .padding(VQTokens.Space.s3)184                .background(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).fill(VQTokens.Palette.ink2))185                .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).strokeBorder(VQTokens.Palette.line))186                VStack(alignment: .leading, spacing: 0) {187                    if memories.isEmpty, store.memory != nil {188                        Text("No memory for this project.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text3).padding(.vertical, VQTokens.Space.s3)189                    }190                    ForEach(memories) { m in191                        Hairline()192                        MemoryRow(app: app, memory: m)193                    }194                    if !memories.isEmpty { Hairline() }195                }196            }197            .padding(.horizontal, VQTokens.Space.s8).padding(.vertical, VQTokens.Space.s6)198            .frame(maxWidth: 920, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)199        }200        .task { await store.loadMemory() }201    }202203    private func notice(_ t: String, _ c: Color) -> some View {204        Text(t).font(VQTokens.Typography.caption.font).foregroundStyle(c).fixedSize(horizontal: false, vertical: true)205    }206207    private func add() {208        let text = draft.trimmingCharacters(in: .whitespacesAndNewlines)209        guard !text.isEmpty else { return }210        draft = ""211        let k = kind, p = pinned212        Task { await store.addMemory(project: projectId, content: text, kind: k, pinned: p, expiresAt: nil) }213    }214}215216private struct MemoryRow: View {217    let app: AppEnvironment218    let memory: VQMemory219220    var body: some View {221        HStack(alignment: .top, spacing: VQTokens.Space.s3) {222            Button { Task { await app.studio.updateMemory(memory.id, VQMemoryChange(pinned: !memory.pinned)) } } label: {223                Image(systemName: memory.pinned ? "pin.fill" : "pin").font(.system(size: 11)).foregroundStyle(memory.pinned ? VQTokens.Palette.accentText : VQTokens.Palette.text3).frame(width: 18, height: 18)224            }225            .buttonStyle(.borderless).help(memory.pinned ? "Pinned: exempt from retention. Click to unpin." : "Pin (exempt from retention)")226            .accessibilityLabel(memory.pinned ? "Unpin" : "Pin").accessibilityIdentifier("memory.pin.\(memory.id)")227            VStack(alignment: .leading, spacing: 4) {228                InlineField(value: memory.content, placeholder: "Memory", identifier: "memory.content.\(memory.id)", axis: .vertical) { t in229                    let v = t.trimmingCharacters(in: .whitespacesAndNewlines)230                    guard !v.isEmpty else { return false }231                    Task { await app.studio.updateMemory(memory.id, VQMemoryChange(content: v)) }; return true232                }233                .padding(.leading, -6)234                HStack(spacing: VQTokens.Space.s2) {235                    if let k = memory.kind { QuietChip(text: k.rawValue.capitalized) }236                    QuietChip(text: memory.source == .agent ? "Written by the agent" : "Written by you", systemImage: memory.source == .agent ? "sparkles" : "person")237                    if let c = memory.createdAt { Text(VQFormat.date(c, language: .en)).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }238                    Menu {239                        Button("Never") { expire(nil) }240                        Button("In 30 days") { expire(30) }241                        Button("In 90 days") { expire(90) }242                        Button("In 1 year") { expire(365) }243                    } label: {244                        Text(memory.expiresAt.map { "Expires \(VQFormat.date($0, language: .en))" } ?? "No expiry date").font(VQTokens.Typography.caption.font)245                            .foregroundStyle(memory.expiresAt == nil ? VQTokens.Palette.text3 : VQTokens.Palette.warn)246                    }247                    .menuStyle(.borderlessButton).fixedSize().help("Set when this memory expires").accessibilityIdentifier("memory.expiry.\(memory.id)")248                }249            }250            Spacer(minLength: 0)251            Button { Task { await app.studio.deleteMemory(memory.id) } } label: { Image(systemName: "trash").font(.system(size: 11)) }252                .buttonStyle(.borderless).foregroundStyle(VQTokens.Palette.text3).help("Delete this memory").accessibilityIdentifier("memory.delete.\(memory.id)")253        }254        .padding(.vertical, VQTokens.Space.s2)255    }256257    private func expire(_ days: Int?) {258        let date = days.map { Date().addingTimeInterval(Double($0) * 86_400) }259        Task { await app.studio.updateMemory(memory.id, VQMemoryChange(expiresAt: .some(date))) }260    }261}262263// MARK: - Export264265struct ProjectExportSheet: View {266    let app: AppEnvironment267    let projectId: String268    let project: VQProject269    @State private var format: VQExportFormat = .pdf270    @State private var excluded = Set<String>()271    @State private var working = false272    @State private var failure: String?273    @State private var done: (info: VQProjectExport, saved: URL?)?274    @Environment(\.dismiss) private var dismiss275276    static func title(_ f: VQExportFormat) -> String { switch f { case .pdf: "PDF"; case .md: "Markdown"; case .tex: "LaTeX"; case .zip: "ZIP" } }277    static func type(_ f: VQExportFormat) -> UTType {278        switch f { case .pdf: .pdf; case .md: UTType(filenameExtension: "md") ?? .plainText; case .tex: UTType(filenameExtension: "tex") ?? .plainText; case .zip: .zip }279    }280281    var body: some View {282        let items = project.items283        VStack(alignment: .leading, spacing: 0) {284            VStack(alignment: .leading, spacing: 4) {285                Overline("Export project")286                Text(project.title).font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1).lineLimit(2)287            }288            .padding(VQTokens.Space.s5)289            Hairline()290            VStack(alignment: .leading, spacing: VQTokens.Space.s3) {291                HStack(spacing: VQTokens.Space.s3) {292                    VQSegmentedControl("Format", selection: $format, options: VQExportFormat.allCases.map { .init($0, Self.title($0)) }).accessibilityIdentifier("export.format")293                    Spacer()294                }295                Text(formatNote).font(VQTokens.Typography.caption.font).foregroundStyle(format == .tex || format == .zip ? VQTokens.Palette.warn : VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)296                    .accessibilityIdentifier("export.note")297                HStack {298                    Overline("Items · \(items.count - excluded.count) of \(items.count)")299                    Spacer()300                    Button("All") { excluded = [] }.buttonStyle(.borderless).controlSize(.small)301                    Button("None") { excluded = Set(items.map(\.id)) }.buttonStyle(.borderless).controlSize(.small)302                }303            }304            .padding(.horizontal, VQTokens.Space.s5).padding(.top, VQTokens.Space.s4).padding(.bottom, VQTokens.Space.s2)305            ScrollView {306                VStack(alignment: .leading, spacing: 0) {307                    ForEach(items) { it in308                        Toggle(isOn: Binding(get: { !excluded.contains(it.id) }, set: { on in if on { excluded.remove(it.id) } else { excluded.insert(it.id) } })) {309                            HStack(spacing: 6) {310                                Image(systemName: it.type.known?.symbol ?? "questionmark.square.dashed").font(.system(size: 11)).foregroundStyle(VQTokens.Palette.text2).frame(width: 16)311                                Text(it.title ?? app.studio.resolved(projectId, item: it.id)?.title ?? it.ref).font(VQTokens.Typography.bodySm.font).lineLimit(1)312                                Text(it.type.known?.title ?? it.type.rawValue).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)313                            }314                        }315                        .toggleStyle(.checkbox).padding(.vertical, 3)316                    }317                    if items.isEmpty { Text("The project has no item: the document will hold its question, hypotheses, data sources and summary.").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }318                }319                .padding(.horizontal, VQTokens.Space.s5)320            }321            .frame(minHeight: 60, maxHeight: 200)322            Hairline()323            VStack(alignment: .leading, spacing: VQTokens.Space.s2) {324                if let failure {325                    HStack(alignment: .top, spacing: 6) {326                        Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(VQTokens.Palette.critical)327                        Text(failure).font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text1).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)328                    }329                    .accessibilityIdentifier("export.error")330                }331                if let done {332                    HStack(alignment: .top, spacing: 6) {333                        Image(systemName: done.saved == nil ? "arrow.down.circle" : "checkmark.circle.fill").foregroundStyle(VQTokens.Palette.info)334                        Text(summary(done)).font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text1).fixedSize(horizontal: false, vertical: true)335                    }336                    .accessibilityIdentifier("export.result")337                }338                HStack {339                    Text("Built by the server from what is stored: methodology in Appendix A, provenance in Appendix B. The export is recorded in your audit trail.")340                        .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)341                    Spacer()342                    if working { ProgressView().controlSize(.small) }343                    Button("Close", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)344                    Button("Export \(Self.title(format))…") { run() }.buttonStyle(EmberButtonStyle()).keyboardShortcut(.defaultAction).disabled(working)345                        .accessibilityIdentifier("export.run")346                }347            }348            .padding(VQTokens.Space.s5)349        }350        .frame(width: 600)351        .background(VQTokens.Palette.ink1)352    }353354    private var formatNote: String {355        switch format {356        case .pdf: "A typeset research note rendered by the server. When its renderer is unavailable the server says so and nothing is produced."357        case .md: "One Markdown file: the project, each item's content, then the methodology and provenance appendices."358        case .tex: "LaTeX source — NOT compiled by the server (compiled: false). Figures are captioned placeholders; compile it yourself."359        case .zip: "report.md, report.tex (not compiled by the server), project.json and one JSON file per readable item."360        }361    }362363    private func summary(_ d: (info: VQProjectExport, saved: URL?)) -> String {364        var parts = ["\(d.info.format.uppercased()) built"]365        if let n = d.info.items { parts.append("\(n) item\(n == 1 ? "" : "s")") }366        if let b = d.info.bytes { parts.append(ByteCountFormatter.string(fromByteCount: Int64(b), countStyle: .file)) }367        if d.info.compiled == false { parts.append("LaTeX not compiled by the server") }368        return parts.joined(separator: " · ") + (d.saved.map { ". Saved as \($0.lastPathComponent)." } ?? ". Not saved (the save panel was cancelled).")369    }370371    private func run() {372        working = true; failure = nil; done = nil373        let f = format374        let include: [String]? = excluded.isEmpty ? nil : project.items.map(\.id).filter { !excluded.contains($0) }375        Task {376            defer { working = false }377            do {378                let file = try await app.studio.export(project: projectId, format: f, include: include)379                let ext = f.rawValue380                let base = project.title.isEmpty ? "project" : project.title.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: " ")381                let url = SavePanel.save(file.data, name: "\(base).\(ext)", types: [Self.type(f)])382                done = (file.info, url)383            } catch let e as VQError { failure = e.message.isEmpty ? e.userMessage : e.message }384            catch { failure = error.localizedDescription }385        }386    }387}388389// MARK: - Add existing things390391struct AddItemsSheet: View {392    let app: AppEnvironment393    let projectId: String394    let project: VQProject395    @State private var type: VQProject.Item.ItemType = .conversation396    @State private var search = ""397    @State private var picked: [String: VQProject.Item] = [:]398    @Environment(\.dismiss) private var dismiss399400    private struct Candidate: Identifiable { var ref: String; var title: String; var detail: String; var id: String { ref } }401    private static let types: [VQProject.Item.ItemType] = [.conversation, .quantJob, .note, .portfolio, .watchlist]402403    private var candidates: [Candidate] {404        let s = app.sync.active405        let list: [Candidate]406        switch type {407        case .conversation: list = app.research.sessions.map { Candidate(ref: $0.sessionId, title: $0.title, detail: $0.updated.map { VQFormat.relative($0, language: .en) } ?? "") }408        case .quantJob: list = app.studio.jobs.map { Candidate(ref: $0.id, title: StudioStore.jobTitle($0), detail: [$0.status.rawValue, $0.startedAt.map { VQFormat.relative($0, language: .en) }].compactMap { $0 }.joined(separator: " · ")) }409        case .note: list = (s?.notes.items ?? []).map { Candidate(ref: $0.id, title: $0.data.title.isEmpty ? "Untitled note" : $0.data.title, detail: $0.data.projectId == nil ? "Not in a project" : ($0.data.projectId == projectId ? "Note of this project" : "Note of another project")) }410        case .portfolio: list = (s?.portfolios.items ?? []).map { Candidate(ref: $0.id, title: $0.data.name, detail: PortfolioView.summary($0.data)) }411        case .watchlist: list = (s?.watchlists.items ?? []).map { Candidate(ref: $0.id, title: $0.data.name, detail: "\($0.data.symbols.count) symbols") }412        default: list = []413        }414        let q = search.trimmingCharacters(in: .whitespaces)415        return q.isEmpty ? list : list.filter { $0.title.localizedCaseInsensitiveContains(q) }416    }417418    var body: some View {419        let inProject = Set(project.items.filter { $0.type == type }.map(\.ref))420        VStack(alignment: .leading, spacing: 0) {421            VStack(alignment: .leading, spacing: VQTokens.Space.s3) {422                VStack(alignment: .leading, spacing: 4) {423                    Overline("Add to project")424                    Text(project.title).font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1).lineLimit(1)425                }426                HStack {427                    VQSegmentedControl("Kind", selection: $type, options: Self.types.map { .init($0, $0.title + "s") }).accessibilityIdentifier("additems.kind")428                    Spacer()429                    TextField("Filter", text: $search).textFieldStyle(.roundedBorder).controlSize(.small).frame(width: 150)430                }431            }432            .padding(VQTokens.Space.s5)433            Hairline()434            ScrollView {435                LazyVStack(alignment: .leading, spacing: 0) {436                    ForEach(candidates) { c in437                        let key = type.rawValue + "|" + c.ref438                        let already = inProject.contains(c.ref)439                        Button {440                            if picked[key] != nil { picked[key] = nil } else { picked[key] = VQProject.Item(type: type, ref: c.ref, title: c.title, addedAt: Date()) }441                        } label: {442                            HStack(spacing: VQTokens.Space.s2) {443                                Image(systemName: already ? "checkmark.circle" : picked[key] != nil ? "checkmark.circle.fill" : "circle")444                                    .foregroundStyle(already ? VQTokens.Palette.text3 : picked[key] != nil ? VQTokens.Palette.accent : VQTokens.Palette.text3)445                                Text(c.title.isEmpty ? c.ref : c.title).font(VQTokens.Typography.bodySm.font).foregroundStyle(already ? VQTokens.Palette.text3 : VQTokens.Palette.text1).lineLimit(1)446                                Spacer()447                                Text(already ? "Already in the project" : c.detail).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(1)448                            }449                            .padding(.horizontal, VQTokens.Space.s5).padding(.vertical, 7).contentShape(Rectangle())450                        }451                        .buttonStyle(.plain).disabled(already)452                        .accessibilityIdentifier("additems.row.\(c.title)")453                        Hairline()454                    }455                    if candidates.isEmpty { Text("Nothing to add here.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text3).padding(VQTokens.Space.s5) }456                }457            }458            .frame(height: 320)459            .background(VQTokens.Palette.ink0)460            Hairline()461            HStack {462                Text("Adding files a reference in the project; the thing itself stays where it is.").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)463                Spacer()464                Button("Cancel", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)465                Button("Add \(picked.count) Item\(picked.count == 1 ? "" : "s")") { app.studio.addItems(projectId, Array(picked.values)); dismiss() }466                    .buttonStyle(EmberButtonStyle()).keyboardShortcut(.defaultAction).disabled(picked.isEmpty)467                    .accessibilityIdentifier("additems.add")468            }469            .padding(VQTokens.Space.s5)470        }471        .frame(width: 680)472        .background(VQTokens.Palette.ink1)473        .task { await app.studio.loadJobs(); await app.research.refreshSessions() }474    }475}476
Files main
Menu

Theme