Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Research/ResearchSupport.swift3// Description: What the research views share: where they read workspace files from, status marks, code colouring,4// images from bytes.5import SwiftUI6import ImageIO7import VQuantKit89/// How the research views read the workspace. Built from the REST client in the apps; from fixtures in previews.10public struct ResearchDataSource: Sendable {11 public var textFile: @Sendable (_ path: String) async throws -> VQResearchFilePreview12 public var fileData: @Sendable (_ path: String) async throws -> Data13 public var runLogs: @Sendable (_ runId: String) async throws -> VQRunLogs14 public var inspect: @Sendable (_ path: String) async throws -> VQDatasetInspection1516 public init(textFile: @escaping @Sendable (String) async throws -> VQResearchFilePreview, fileData: @escaping @Sendable (String) async throws -> Data,17 runLogs: @escaping @Sendable (String) async throws -> VQRunLogs, inspect: @escaping @Sendable (String) async throws -> VQDatasetInspection) {18 self.textFile = textFile; self.fileData = fileData; self.runLogs = runLogs; self.inspect = inspect19 }2021 /// The workspace `workspaceId` (or `VQResearchSession.reference(sessionId:)`) through the REST client.22 public init(client: VQResearchAgentClient, workspaceId: String, logTail: Int = 8000, previewLines: Int = 400) {23 self.init(textFile: { try await client.textFile(workspaceId, path: $0, offset: 0, limit: previewLines) },24 fileData: { try await client.fileData(workspaceId, path: $0) },25 runLogs: { try await client.run($0, tail: logTail) },26 inspect: { try await client.inspect(workspaceId, path: $0) })27 }2829 /// Nothing can be read (a study shown from events only).30 public static let unavailable = ResearchDataSource(textFile: { _ in throw VQError(.notFound, message: VQL10n.string("No workspace.")) }, fileData: { _ in throw VQError(.notFound, message: VQL10n.string("No workspace.")) },31 runLogs: { _ in throw VQError(.notFound, message: VQL10n.string("No workspace.")) }, inspect: { _ in throw VQError(.notFound, message: VQL10n.string("No workspace.")) })3233 /// In-memory files (previews, snapshots, tests).34 public static func fixed(texts: [String: String] = [:], data: [String: Data] = [:], logs: [String: VQRunLogs] = [:], inspections: [String: VQDatasetInspection] = [:]) -> ResearchDataSource {35 ResearchDataSource(36 textFile: { path in37 guard let t = texts[path] else { throw VQError(.notFound, status: 404, message: VQL10n.string("File not found.")) }38 let lines = t.components(separatedBy: "\n").count39 return VQResearchFilePreview(json: ["path": .string(path), "bytes": .number(Double(t.utf8.count)), "totalLines": .number(Double(lines)), "from": 1, "to": .number(Double(lines)), "text": .string(t), "truncated": false])40 },41 fileData: { path in if let d = data[path] ?? texts[path].map({ Data($0.utf8) }) { return d }; throw VQError(.notFound, status: 404, message: VQL10n.string("File not found.")) },42 runLogs: { id in if let l = logs[id] { return l }; throw VQError(.notFound, status: 404, message: VQL10n.string("Run not found.")) },43 inspect: { path in if let i = inspections[path] { return i }; throw VQError(.notFound, status: 404, message: VQL10n.string("Not a dataset.")) })44 }45}4647public extension EnvironmentValues {48 /// Where the research views read workspace files, run logs and dataset profiles.49 @Entry var researchDataSource = ResearchDataSource.unavailable50}5152public extension View {53 func researchDataSource(_ source: ResearchDataSource) -> some View { environment(\.researchDataSource, source) }54}5556/// The outcome of an execution, an experiment or a run: a glyph and a word, never colour alone.57public struct ResearchStatusBadge: View {58 public enum Tone { case running, ok, failed, neutral }59 private let label: String60 private let symbol: String61 private let tone: Tone62 private let compact: Bool63 @Environment(\.vqTheme) private var theme6465 init(label: String, symbol: String, tone: Tone, compact: Bool) { self.label = label; self.symbol = symbol; self.tone = tone; self.compact = compact }6667 public init(_ status: VQLedgerStatus, compact: Bool = false, language: VQLanguage = .preferred) {68 switch status {69 case .running: self.init(label: VQL10n.string("running", language), symbol: "circle.dotted", tone: .running, compact: compact)70 case .ok: self.init(label: VQL10n.string("ok", language), symbol: "checkmark.circle", tone: .ok, compact: compact)71 case .failed: self.init(label: VQL10n.string("failed", language), symbol: "xmark.circle", tone: .failed, compact: compact)72 case .timeout: self.init(label: VQL10n.string("timed out", language), symbol: "clock.badge.xmark", tone: .failed, compact: compact)73 case .killed: self.init(label: VQL10n.string("killed (limit)", language), symbol: "stop.circle", tone: .failed, compact: compact)74 case .interrupted: self.init(label: VQL10n.string("interrupted", language), symbol: "pause.circle", tone: .failed, compact: compact)75 case .inconclusive: self.init(label: VQL10n.string("inconclusive", language), symbol: "questionmark.circle", tone: .neutral, compact: compact)76 case .abandoned: self.init(label: VQL10n.string("abandoned", language), symbol: "arrow.uturn.backward.circle", tone: .neutral, compact: compact)77 }78 }7980 public init(run status: VQOpen<VQResearchRun.Status>, compact: Bool = false, language: VQLanguage = .preferred) {81 switch status.known {82 case .running?: self.init(label: VQL10n.string("running", language), symbol: "circle.dotted", tone: .running, compact: compact)83 case .done?: self.init(label: VQL10n.string("done", language), symbol: "checkmark.circle", tone: .ok, compact: compact)84 case .failed?: self.init(label: VQL10n.string("failed", language), symbol: "xmark.circle", tone: .failed, compact: compact)85 case .timeout?: self.init(label: VQL10n.string("timed out", language), symbol: "clock.badge.xmark", tone: .failed, compact: compact)86 case .killed?: self.init(label: VQL10n.string("killed (limit)", language), symbol: "stop.circle", tone: .failed, compact: compact)87 case .cancelled?: self.init(label: VQL10n.string("cancelled", language), symbol: "minus.circle", tone: .neutral, compact: compact)88 case .interrupted?: self.init(label: VQL10n.string("interrupted", language), symbol: "pause.circle", tone: .failed, compact: compact)89 case nil: self.init(label: status.rawValue, symbol: "circle", tone: .neutral, compact: compact)90 }91 }9293 private var color: Color {94 switch tone {95 case .running: return VQP.accentText96 case .ok: return theme.upDown.up97 case .failed: return VQP.critical98 case .neutral: return VQP.warn99 }100 }101102 public var body: some View {103 HStack(spacing: 4) {104 Image(systemName: symbol).font(.system(size: 12, weight: .medium)).accessibilityHidden(true)105 if !compact { Text(label).vqFont(VQTokens.Typography.caption) }106 }107 .foregroundStyle(color)108 .fixedSize()109 .accessibilityElement(children: .ignore)110 .accessibilityLabel(label)111 }112}113114/// Python source with syntax colouring (keywords, strings, numbers, comments, definitions). Selectable; line numbers.115public struct ResearchCodeView: View {116 private let code: String117 private let lineNumbers: Bool118 private let maxLines: Int?119 private let plain: Bool120 @Environment(\.vqStaticRender) private var isStatic121 @Environment(\.vqTheme) private var theme122123 /// - Parameters:124 /// - maxLines: longer code is cut with a "… n more lines" mark (the list rows); nil shows everything.125 /// - language: only `"python"` is coloured; anything else is shown as plain mono text.126 public init(_ code: String, language: String = "python", lineNumbers: Bool = true, maxLines: Int? = nil) {127 self.code = code; self.lineNumbers = lineNumbers; self.maxLines = maxLines; self.plain = language != "python"128 }129130 static func color(_ kind: VQPythonSyntax.Kind) -> Color {131 switch kind {132 case .keyword: return VQP.info133 case .string: return VQTokens.UpDown.classic.up134 case .number: return VQP.warn135 case .comment: return VQP.text3136 case .decorator, .definition: return VQP.accentText137 case .builtin: return VQP.text2138 case .plain, .operator: return VQP.text1139 }140 }141142 /// The coloured text. Colouring is skipped above 60 000 characters (logs pasted as code): plain text is instant.143 public static func attributed(_ source: String, plain: Bool = false) -> AttributedString {144 var out = AttributedString(source)145 out.font = .system(size: 11.5, design: .monospaced)146 out.foregroundColor = VQP.text1147 guard !plain, source.utf16.count <= 60_000 else { return out }148 let utf16 = source.utf16149 for token in VQPythonSyntax.tokens(source) {150 guard let a = utf16.index(utf16.startIndex, offsetBy: token.range.lowerBound, limitedBy: utf16.endIndex),151 let b = utf16.index(utf16.startIndex, offsetBy: token.range.upperBound, limitedBy: utf16.endIndex),152 let lo = AttributedString.Index(a, within: out), let hi = AttributedString.Index(b, within: out) else { continue }153 out[lo..<hi].foregroundColor = color(token.kind)154 if token.kind == .comment { out[lo..<hi].font = .system(size: 11.5, design: .monospaced).italic() }155 if token.kind == .keyword || token.kind == .definition { out[lo..<hi].font = .system(size: 11.5, weight: .semibold, design: .monospaced) }156 }157 return out158 }159160 /// The coloured source cut into lines (colouring is done on the whole text first, so a string or a comment that161 /// spans lines keeps its colour on each of them).162 static func attributedLines(_ source: String, plain: Bool = false) -> [AttributedString] {163 let whole = attributed(source, plain: plain)164 var out: [AttributedString] = []165 var start = source.startIndex166 func take(_ end: String.Index) {167 if let a = AttributedString.Index(start, within: whole), let b = AttributedString.Index(end, within: whole), a < b { out.append(AttributedString(whole[a..<b])) }168 else { var blank = AttributedString(" "); blank.font = .system(size: 11.5, design: .monospaced); out.append(blank) }169 }170 var i = source.startIndex171 while i < source.endIndex {172 if source[i] == "\n" || source[i] == "\r\n" { take(i); start = source.index(after: i) }173 i = source.index(after: i)174 }175 take(source.endIndex)176 return out177 }178179 public var body: some View {180 let all = code.components(separatedBy: "\n")181 let shown = maxLines.map { Array(all.prefix($0)) } ?? all182 let text = shown.joined(separator: "\n")183 let block = HStack(alignment: .top, spacing: VQS.s3) {184 if lineNumbers {185 Text((1...max(1, shown.count)).map(String.init).joined(separator: "\n"))186 .font(.system(size: 11.5, design: .monospaced).monospacedDigit()).foregroundStyle(VQP.text3).multilineTextAlignment(.trailing).lineSpacing(3)187 .accessibilityHidden(true)188 }189 Text(Self.attributed(text, plain: plain)).lineSpacing(3).textSelection(.enabled).fixedSize(horizontal: !isStatic, vertical: true)190 }191 VStack(alignment: .leading, spacing: VQS.s1) {192 if isStatic {193 // an export cannot scroll: one row per line, long lines wrap under their own number194 let lines = Self.attributedLines(text, plain: plain)195 VStack(alignment: .leading, spacing: 3) {196 ForEach(Array(lines.enumerated()), id: \.offset) { i, line in197 HStack(alignment: .firstTextBaseline, spacing: VQS.s3) {198 if lineNumbers { Text("\(i + 1)").font(.system(size: 11.5, design: .monospaced).monospacedDigit()).foregroundStyle(VQP.text3).frame(width: 24, alignment: .trailing) }199 Text(line).fixedSize(horizontal: false, vertical: true)200 }201 }202 }203 .frame(maxWidth: .infinity, alignment: .leading)204 } else { ScrollView(.horizontal) { block } }205 if shown.count < all.count {206 Text(theme.l("… %lld more lines", all.count - shown.count)).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3)207 }208 }209 .padding(VQS.s3)210 .frame(maxWidth: .infinity, alignment: .leading)211 .background(RoundedRectangle(cornerRadius: VQTokens.Radius.sm, style: .continuous).fill(VQP.ink3))212 .accessibilityLabel(theme.l("Code"))213 }214}215216/// Console text (outputs, errors, log tails): mono, selectable, on a plate; errors carry a critical rule.217struct ResearchConsoleText: View {218 let text: String219 var isError = false220 var maxLines: Int? = 40221 @Environment(\.vqTheme) private var theme222 var body: some View {223 let lines = text.components(separatedBy: "\n")224 let shown = maxLines.map { lines.count > $0 ? Array(lines.suffix($0)) : lines } ?? lines225 // the one message the package itself writes on a cell (a cell cut with its generation); the rest is the server's226 let shownText = shown.joined(separator: "\n") == "Interrupted with the analysis." ? theme.l("Interrupted with the analysis.") : shown.joined(separator: "\n")227 VStack(alignment: .leading, spacing: 2) {228 if shown.count < lines.count { Text(theme.l("… %lld lines above", lines.count - shown.count)).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3) }229 Text(shownText).font(.system(size: 11, design: .monospaced)).foregroundStyle(VQP.text1).lineSpacing(2)230 .textSelection(.enabled).fixedSize(horizontal: false, vertical: true)231 }232 .padding(VQS.s3)233 .frame(maxWidth: .infinity, alignment: .leading)234 .background(RoundedRectangle(cornerRadius: VQTokens.Radius.sm, style: .continuous).fill(VQP.ink1))235 .overlay(alignment: .leading) { if isError { Rectangle().fill(VQP.critical).frame(width: 2) } }236 .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.sm, style: .continuous).strokeBorder(VQP.line, lineWidth: VQTokens.hairline))237 }238}239240/// A bitmap from bytes (PNG, JPEG…) without platform image types.241public enum VQImageData {242 public static func cgImage(_ data: Data) -> CGImage? {243 guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }244 return CGImageSourceCreateImageAtIndex(source, 0, nil)245 }246 public static func image(_ data: Data, label: String) -> Image? { cgImage(data).map { Image($0, scale: 1, label: Text(label)) } }247}248249/// Loads something once per id and shows a skeleton, the content, or why it failed.250struct ResearchLoader<Value: Sendable, Content: View, Placeholder: View>: View {251 let id: String252 let preloaded: Value?253 let load: @Sendable () async throws -> Value254 @ViewBuilder let content: (Value) -> Content255 @ViewBuilder let placeholder: () -> Placeholder256 @State private var value: Value?257 @State private var failure: String?258 @Environment(\.vqTheme) private var theme259260 var body: some View {261 Group {262 if let v = preloaded ?? value { content(v) }263 else if let failure {264 Label(failure, systemImage: "exclamationmark.triangle").vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3)265 } else { VQLoading { placeholder() } }266 }267 .task(id: id) {268 guard preloaded == nil else { return }269 value = nil; failure = nil270 do { value = try await load() }271 catch is CancellationError {}272 catch { failure = (error as? VQError)?.message ?? theme.l("Could not be read.") }273 }274 }275}276277func researchDuration(_ ms: Double?, _ theme: VQTheme) -> String? {278 guard let ms else { return nil }279 let t = VQFormat.duration(ms: ms, locale: theme.numberLocale)280 return t.isEmpty ? nil : t281}282