Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Studio/ProjectOverview.swift3// Description: The page of a research project: editorial header (title, question, hypotheses with their status, data sources, summary — all edited in place), the composer that starts research inside the project, and its items as the server resolves them (open, remove, reorder by drag, add existing things).4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89struct ProjectOverview: View {10 let app: AppEnvironment11 let model: WindowModel12 let object: VQObject<VQProject>13 let pending: Bool14 let addExisting: () -> Void15 let openNote: (String) -> Void16 let openReviews: () -> Void1718 @State private var question = ""19 @State private var dropTarget: String?2021 private var id: String { object.id }22 private var p: VQProject { object.data }23 private var store: StudioStore { app.studio }2425 var body: some View {26 ScrollView {27 VStack(alignment: .leading, spacing: VQTokens.Space.s6) {28 header29 composer30 items31 }32 .padding(.horizontal, VQTokens.Space.s8).padding(.vertical, VQTokens.Space.s6)33 .frame(maxWidth: 920, alignment: .leading)34 .frame(maxWidth: .infinity, alignment: .leading)35 }36 // the bundle is the server's reading: asked again whenever the list of references changes37 .task(id: p.items.map { $0.id + $0.ref }) { await store.loadBundle(id) }38 }3940 // MARK: editorial header4142 private var header: some View {43 VStack(alignment: .leading, spacing: VQTokens.Space.s3) {44 Rectangle().fill(VQTokens.Palette.text1).frame(height: VQTokens.hairline)45 HStack(spacing: VQTokens.Space.s2) {46 Overline("Research project")47 Menu {48 ForEach(VQProject.Status.allCases, id: \.self) { s in Button(StudioView.statusTitle(.known(s))) { store.update(id) { $0.status = .known(s) } } }49 } label: {50 HStack(spacing: 5) { ProjectStatusDot(status: p.status?.known ?? .active); Text(StudioView.statusTitle(p.status)).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text2) }51 }52 .menuStyle(.borderlessButton).fixedSize().accessibilityIdentifier("project.status")53 if pending { PendingSyncMark() }54 Spacer()55 Text("Updated \(VQFormat.relative(object.updatedAt, language: .en)) · created \(VQFormat.date(object.createdAt, language: .en))").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)56 }57 InlineField(value: p.title, placeholder: "Project title", role: VQTokens.Typography.displayLg, identifier: "project.title", axis: .vertical) { t in58 let v = t.trimmingCharacters(in: .whitespacesAndNewlines)59 guard !v.isEmpty else { return false }60 store.update(id) { $0.title = v }; return true61 }62 .padding(.leading, -6)63 VStack(alignment: .leading, spacing: 2) {64 Overline("Question")65 InlineField(value: p.question ?? "", placeholder: "What is this project trying to answer?", font: .system(size: 17, weight: .regular, design: .serif),66 identifier: "project.question", axis: .vertical) { t in67 let v = t.trimmingCharacters(in: .whitespacesAndNewlines)68 store.update(id) { $0.question = v.isEmpty ? nil : v }; return true69 }70 .padding(.leading, -6)71 }72 hypotheses73 HStack(alignment: .top, spacing: VQTokens.Space.s8) {74 dataSources.frame(maxWidth: .infinity, alignment: .leading)75 VStack(alignment: .leading, spacing: 2) {76 Overline("Summary")77 InlineField(value: p.summary ?? "", placeholder: "Where the project stands, in a few sentences.", color: VQTokens.Palette.text1, identifier: "project.summary", axis: .vertical) { t in78 let v = t.trimmingCharacters(in: .whitespacesAndNewlines)79 store.update(id) { $0.summary = v.isEmpty ? nil : v }; return true80 }81 .padding(.leading, -6)82 }83 .frame(maxWidth: .infinity, alignment: .leading)84 }85 }86 }8788 private var hypotheses: some View {89 VStack(alignment: .leading, spacing: 4) {90 HStack {91 Overline("Hypotheses")92 Spacer()93 Button { store.update(id) { $0.hypotheses.append(VQProject.Hypothesis(text: "")) } } label: { Label("Add a hypothesis", systemImage: "plus") }94 .buttonStyle(.borderless).controlSize(.small).accessibilityIdentifier("project.hypothesis.add")95 }96 if p.hypotheses.isEmpty { Text("None stated.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text3) }97 ForEach(Array(p.hypotheses.enumerated()), id: \.element.id) { i, h in98 HStack(alignment: .firstTextBaseline, spacing: VQTokens.Space.s2) {99 Text("H\(i + 1)").font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text3).frame(width: 24, alignment: .leading)100 InlineField(value: h.text, placeholder: "State a testable hypothesis", identifier: "project.hypothesis.\(i)", axis: .vertical) { t in101 let v = t.trimmingCharacters(in: .whitespacesAndNewlines)102 editHypothesis(h.id) { $0.text = v }; return true103 }104 Menu {105 ForEach(VQProject.Hypothesis.Status.allCases, id: \.self) { s in Button(s.rawValue.capitalized) { editHypothesis(h.id) { $0.status = .known(s) } } }106 Divider()107 Button("Remove Hypothesis", role: .destructive) { store.update(id) { $0.hypotheses = $0.hypotheses.filter { $0.id != h.id } } }108 } label: { HypothesisStatusChip(status: h.status, up: app.settings.upColor) }109 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()110 .accessibilityIdentifier("project.hypothesis.status.\(i)")111 }112 .padding(.vertical, 2)113 Hairline()114 }115 }116 }117118 private func editHypothesis(_ hid: String, _ change: (inout VQProject.Hypothesis) -> Void) {119 store.update(id) { p in120 var list = p.hypotheses121 guard let i = list.firstIndex(where: { $0.id == hid }) else { return }122 change(&list[i]); p.hypotheses = list123 }124 }125126 private var dataSources: some View {127 VStack(alignment: .leading, spacing: 2) {128 HStack {129 Overline("Data sources")130 Spacer()131 Button { store.update(id) { $0.dataSources.append(VQProject.DataSource(provider: "")) } } label: { Image(systemName: "plus") }132 .buttonStyle(.borderless).controlSize(.small).help("Add a data source").accessibilityIdentifier("project.source.add")133 }134 if p.dataSources.isEmpty { Text("None listed.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text3) }135 ForEach(p.dataSources) { s in136 HStack(alignment: .firstTextBaseline, spacing: 2) {137 InlineField(value: s.provider, placeholder: "provider", role: VQTokens.Typography.numSm, color: VQTokens.Palette.text2) { t in138 editSource(s.id) { $0.provider = t.trimmingCharacters(in: .whitespaces) }; return true139 }.frame(width: 84)140 InlineField(value: s.description ?? "", placeholder: "What it provides", axis: .vertical) { t in141 let v = t.trimmingCharacters(in: .whitespacesAndNewlines)142 editSource(s.id) { $0.description = v.isEmpty ? nil : v }; return true143 }144 Button { store.update(id) { $0.dataSources = $0.dataSources.filter { $0.id != s.id } } } label: { Image(systemName: "xmark").font(.system(size: 9, weight: .semibold)) }145 .buttonStyle(.borderless).foregroundStyle(VQTokens.Palette.text3).help("Remove this source")146 }147 .padding(.leading, -6)148 }149 }150 }151152 private func editSource(_ sid: String, _ change: (inout VQProject.DataSource) -> Void) {153 store.update(id) { p in154 var list = p.dataSources155 guard let i = list.firstIndex(where: { $0.id == sid }) else { return }156 change(&list[i]); p.dataSources = list157 }158 }159160 // MARK: composer — hands the question to Research, filed in this project161162 private var composer: some View {163 VStack(alignment: .leading, spacing: VQTokens.Space.s2) {164 HStack(alignment: .bottom, spacing: VQTokens.Space.s2) {165 Image(systemName: "sparkles").foregroundStyle(VQTokens.Palette.accentText).padding(.bottom, 5)166 TextField("Research inside this project: ask a question, request an experiment…", text: $question, axis: .vertical)167 .textFieldStyle(.plain).font(VQTokens.Typography.body.font).lineLimit(1...5)168 .onSubmit { startResearch() }169 .accessibilityIdentifier("project.composer")170 Button("Open in Research") { startResearch() }.buttonStyle(EmberButtonStyle())171 .disabled(question.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)172 .accessibilityIdentifier("project.composer.send")173 }174 .padding(VQTokens.Space.s3)175 .background(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).fill(VQTokens.Palette.ink2))176 .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).strokeBorder(VQTokens.Palette.line))177 Text("Opens a new conversation in Research mode, filed in this project: the agent receives the question, hypotheses, data sources, note titles and project memory. Nothing is sent until you send it there.")178 .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)179 }180 }181182 private func startResearch() {183 let q = question.trimmingCharacters(in: .whitespacesAndNewlines)184 guard !q.isEmpty else { return }185 question = ""186 model.ask(AskDraft(text: q, mode: .research, projectId: id))187 }188189 // MARK: items190191 private var items: some View {192 VStack(alignment: .leading, spacing: 0) {193 HStack(alignment: .firstTextBaseline) {194 Text("Items").font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1)195 Text("\(p.items.count)").font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text3)196 if p.items.count > 1 { Text("drag to reorder").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }197 Spacer()198 Button { Task { if let n = await store.createNote(project: id, title: "Untitled note") { openNote(n) } } } label: { Label("New Note", systemImage: "square.and.pencil") }199 .accessibilityIdentifier("project.note.new")200 Button { addExisting() } label: { Label("Add Existing…", systemImage: "plus") }.accessibilityIdentifier("project.items.add")201 }202 .controlSize(.small)203 .padding(.bottom, VQTokens.Space.s2)204 if let e = store.bundleErrors[id] { Text("The server could not resolve the items: \(e)").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.warn).padding(.bottom, 4) }205 Hairline(strong: true)206 if p.items.isEmpty {207 Text("Nothing filed yet. Conversations started from this page are added by the server; computations, notes, portfolios and watchlists can be added by hand.")208 .font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text3).padding(.vertical, VQTokens.Space.s4).fixedSize(horizontal: false, vertical: true)209 }210 ForEach(p.items) { item in211 itemRow(item)212 .overlay(alignment: .top) { if dropTarget == item.id { Rectangle().fill(VQTokens.Palette.accent).frame(height: 2) } }213 .draggable(item.id) { Text(title(item)).font(VQTokens.Typography.bodySm.font).padding(6).background(RoundedRectangle(cornerRadius: 6).fill(VQTokens.Palette.ink3)) }214 .dropDestination(for: String.self) { ids, _ in215 guard let moved = ids.first, p.items.contains(where: { $0.id == moved }) else { return false }216 store.moveItem(id, item: moved, before: item.id); return true217 } isTargeted: { on in dropTarget = on ? item.id : (dropTarget == item.id ? nil : dropTarget) }218 Hairline()219 }220 if p.items.count > 1 {221 Color.clear.frame(height: 18).contentShape(Rectangle())222 .overlay(alignment: .top) { if dropTarget == "end" { Rectangle().fill(VQTokens.Palette.accent).frame(height: 2) } }223 .dropDestination(for: String.self) { ids, _ in224 guard let moved = ids.first, p.items.contains(where: { $0.id == moved }) else { return false }225 store.moveItem(id, item: moved, before: nil); return true226 } isTargeted: { on in dropTarget = on ? "end" : (dropTarget == "end" ? nil : dropTarget) }227 }228 }229 }230231 /// The title the person gave the item, else the server's, else what this Mac knows of the object.232 private func title(_ item: VQProject.Item) -> String {233 if let t = item.title, !t.isEmpty { return t }234 if let t = store.resolved(id, item: item.id)?.title, !t.isEmpty { return t }235 switch item.type.known {236 case .note?: if let t = app.sync.active?.notes[item.ref]?.data.title, !t.isEmpty { return t }237 case .portfolio?: if let t = app.sync.active?.portfolios[item.ref]?.data.name, !t.isEmpty { return t }238 case .watchlist?: if let t = app.sync.active?.watchlists[item.ref]?.data.name, !t.isEmpty { return t }239 case .chart?: if let t = app.sync.active?.charts[item.ref]?.data.symbol, !t.isEmpty { return t }240 case .conversation?: if let t = app.research.sessions.first(where: { $0.sessionId == item.ref })?.title { return t }241 default: break242 }243 return item.ref244 }245246 private func itemRow(_ item: VQProject.Item) -> some View {247 let resolved = store.resolved(id, item: item.id)248 let asked = store.isResolvedByServer(id, item: item.id)249 let unresolved = asked && resolved == nil250 let type = item.type.known251 return HStack(alignment: .top, spacing: VQTokens.Space.s3) {252 Image(systemName: "line.3.horizontal").font(.system(size: 10)).foregroundStyle(VQTokens.Palette.text3.opacity(0.6)).padding(.top, 5).help("Drag to reorder")253 Button { open(item) } label: {254 HStack(alignment: .top, spacing: VQTokens.Space.s3) {255 Image(systemName: type?.symbol ?? "questionmark.square.dashed").font(.system(size: 13)).foregroundStyle(unresolved ? VQTokens.Palette.text3 : VQTokens.Palette.text2).frame(width: 18).padding(.top, 2)256 VStack(alignment: .leading, spacing: 2) {257 HStack(spacing: VQTokens.Space.s2) {258 Text(title(item)).font(VQTokens.Typography.bodySm.font.weight(.medium)).foregroundStyle(unresolved ? VQTokens.Palette.text3 : VQTokens.Palette.text1).lineLimit(1)259 if let s = resolved?.status { ItemStatusChip(status: s) }260 if unresolved { QuietChip(text: "Unresolved", systemImage: "questionmark", tint: VQTokens.Palette.warn) }261 }262 Text(unresolved263 ? (type == .notebook || type == .dataset ? "\(type?.title ?? "Item") · kept as a reference: this kind has no server-side store." : "\(type?.title ?? item.type.rawValue) · the target no longer exists or is not yours (ref \(item.ref)).")264 : [type?.title ?? item.type.rawValue, resolved?.summary].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))265 .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(2).multilineTextAlignment(.leading)266 }267 Spacer(minLength: VQTokens.Space.s2)268 Text((resolved?.updatedAt ?? item.addedAt).map { VQFormat.relative($0, language: .en) } ?? "").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(1)269 }270 .contentShape(Rectangle())271 }272 .buttonStyle(.plain)273 .disabled(!canOpen(item, unresolved: unresolved))274 .accessibilityIdentifier("project.item.\(item.type.rawValue).\(title(item))")275 Menu {276 Button("Open") { open(item) }.disabled(!canOpen(item, unresolved: unresolved))277 Button("Move Up") { store.moveItem(id, item: item.id, by: -1) }278 Button("Move Down") { store.moveItem(id, item: item.id, by: 1) }279 Divider()280 Button("Remove from Project", role: .destructive) { store.removeItem(id, item: item.id) }281 } label: { Image(systemName: "ellipsis").font(.system(size: 11)).frame(width: 18, height: 18) }282 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()283 .help("Open, move or remove (removing does not delete the thing itself)")284 .accessibilityIdentifier("project.item.menu.\(title(item))")285 }286 .padding(.vertical, VQTokens.Space.s2)287 .contentShape(Rectangle())288 .contextMenu {289 Button("Open") { open(item) }.disabled(!canOpen(item, unresolved: unresolved))290 Button("Move Up") { store.moveItem(id, item: item.id, by: -1) }291 Button("Move Down") { store.moveItem(id, item: item.id, by: 1) }292 Divider()293 Button("Remove from Project", role: .destructive) { store.removeItem(id, item: item.id) }294 }295 }296297 private func canOpen(_ item: VQProject.Item, unresolved: Bool) -> Bool {298 guard !unresolved, let t = item.type.known else { return false }299 return t != .notebook && t != .dataset300 }301302 /// Each kind opens in its own place.303 private func open(_ item: VQProject.Item) {304 switch item.type.known {305 case .conversation?: model.openConversation(item.ref)306 case .quantJob?: model.openQuantJob(item.ref)307 case .note?: openNote(item.ref)308 case .portfolio?: model.openPortfolio(item.ref)309 case .watchlist?: model.watchlistId = item.ref; model.section = .watchlists310 case .chart?: model.show(.charting, symbol: app.sync.active?.charts[item.ref]?.data.symbol)311 case .review?: openReviews()312 case .report?: model.section = .documents313 case .notebook?, .dataset?, nil: break314 }315 }316}317318struct HypothesisStatusChip: View {319 let status: VQOpen<VQProject.Hypothesis.Status>320 let up: Color321 var body: some View {322 QuietChip(text: status.rawValue.capitalized, systemImage: symbol, tint: color)323 }324 private var symbol: String {325 switch status.known { case .open?, nil: "circle.dotted"; case .supported?: "checkmark"; case .rejected?: "xmark"; case .inconclusive?: "questionmark" }326 }327 private var color: Color {328 switch status.known { case .open?, nil: VQTokens.Palette.text2; case .supported?: VQTokens.Palette.info; case .rejected?: VQTokens.Palette.critical; case .inconclusive?: VQTokens.Palette.warn }329 }330}331332struct ItemStatusChip: View {333 let status: String334 var body: some View {335 QuietChip(text: status.replacingOccurrences(of: "_", with: " ").capitalized, tint: color)336 }337 private var color: Color {338 switch status { case "running": VQTokens.Palette.accentText; case "error", "failed": VQTokens.Palette.critical; case "cancelled", "interrupted": VQTokens.Palette.warn; default: VQTokens.Palette.text3 }339 }340}341