import AppKit import SwiftUI import ShotdeckCore /// The Redline window: every session on the left, the selected session's pages in the /// middle, and that session's review details / PDF / session facts on the right. /// This is where history, text entry and file facts live; the popover only glances at /// the current session and fires the two main actions. struct SessionsWindowView: View { @Environment(AppModel.self) private var model @State private var searchText = "" @State private var selectedCaptureID: UUID? @State private var showInspector = true var body: some View { // Three explicit columns rather than NavigationSplitView: the window has a // fixed, always-visible inspector, and a plain split keeps the sidebar rows and // the inspector rendering deterministically in every window state. HStack(spacing: 0) { sidebar .frame(width: 230) Divider() detail .frame(maxWidth: .infinity, maxHeight: .infinity) if showInspector { Divider() SessionInspector(session: selectedSession) .frame(width: 300) } } .frame(minWidth: 900, minHeight: 560) .controlSize(.regular) .background(Color(nsColor: .windowBackgroundColor)) .onChange(of: model.selectedSessionID) { _, _ in selectedCaptureID = nil } } private var selectedSession: CaptureSession { model.selectedSession ?? model.session } // MARK: - Sidebar private var sidebar: some View { VStack(spacing: 0) { HStack(spacing: 6) { Image(systemName: "magnifyingglass") .foregroundStyle(.secondary) TextField("Search sessions", text: $searchText) .textFieldStyle(.plain) if !searchText.isEmpty { Button { searchText = "" } label: { Image(systemName: "xmark.circle.fill") .foregroundStyle(.secondary) } .buttonStyle(.plain) .accessibilityLabel("Clear search") } } .padding(.horizontal, 8) .padding(.vertical, 5) .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 6, style: .continuous)) .padding(8) List(selection: selection) { ForEach(sections) { section in Section(section.title) { ForEach(section.sessions) { session in SessionRow(session: session) .tag(session.id) } } } } .listStyle(.sidebar) if sections.isEmpty { Text(searchText.isEmpty ? "No sessions yet." : "No session matches “\(searchText)”.") .font(.caption) .foregroundStyle(.secondary) .multilineTextAlignment(.center) .padding(12) } } .background(Color(nsColor: .controlBackgroundColor)) } private var sections: [AppModel.SessionGroup] { model.groupedSections(for: model.sessions(matching: searchText)) } private var selection: Binding { Binding( get: { model.selectedSession?.id }, set: { model.selectSession($0) } ) } // MARK: - Detail private var detail: some View { VStack(alignment: .leading, spacing: 0) { header Divider() if let document = model.returnedDocument(for: selectedSession), document.isCommented { ReturnedBanner(document: document, session: selectedSession) Divider() } pages } .background(Color(nsColor: .textBackgroundColor)) } private var header: some View { HStack(alignment: .center, spacing: 10) { VStack(alignment: .leading, spacing: 1) { HStack(spacing: 6) { Text(laneTitle) .font(.system(size: 15, weight: .semibold)) .lineLimit(1) .truncationMode(.tail) if model.selectedIsCurrent { Text("Current") .font(.system(size: 9, weight: .semibold)) .padding(.horizontal, 5) .padding(.vertical, 1) .background(.quaternary, in: Capsule()) } } Text(subtitle) .font(.caption) .foregroundStyle(.secondary) .lineLimit(1) } .layoutPriority(0) Spacer(minLength: 12) Button { showInspector.toggle() } label: { Image(systemName: "sidebar.right") } .buttonStyle(.borderless) .help(showInspector ? "Hide the inspector" : "Show the inspector") .accessibilityLabel(showInspector ? "Hide the inspector" : "Show the inspector") // What the next capture takes, in the same place as the verbs. Menu { ForEach(CaptureScope.allCases, id: \.self) { scope in Button { Task { await model.chooseCaptureScope(scope) await model.captureNow() } } label: { Text("\(scope.menuTitle) — capture now") } } Divider() Button("Choose New Area…") { Task { await model.rePickRegion() } } } label: { HStack(spacing: 4) { Image(systemName: scopeSymbol) Text("\(model.captureScope.displayName) · \(scopeDetail)") .lineLimit(1) } } .menuStyle(.borderlessButton) .fixedSize() .help("What Capture takes") .accessibilityLabel("Capture: \(model.captureTargetDescription)") if model.captureScope == .area { Button("Choose Area…") { Task { await model.rePickRegion() } } .fixedSize() .help("Pick a new area to capture") } Button { Task { await model.newSession() } } label: { Label("New Session", systemImage: "plus.square.on.square") } .keyboardShortcut("n", modifiers: .command) .disabled(model.isSending) .fixedSize() .help("Keep this session and start a fresh one, then ask where to capture (⌘N)") Button { Task { await model.captureNow() } } label: { Label(model.isCapturing ? "Capturing…" : "Capture", systemImage: "viewfinder") } .disabled(model.isCapturing || !model.selectedIsCurrent) .fixedSize() Button { guard let sender = model as? SendCapable else { return } let anchor = NSApp.keyWindow?.contentView Task { await sender.send(anchor: anchor) } } label: { Label(sendTitle, systemImage: "paperplane.fill") } .buttonStyle(.borderedProminent) .layoutPriority(1) .keyboardShortcut("s", modifiers: .command) .disabled(!model.selectedIsCurrent || model.session.isEmpty || model.isSending) .help(model.transport == .oneDrive ? "Save the PDF to the OneDrive folder (⌘S)" : "AirDrop the PDF (⌘S)") } .padding(.horizontal, 16) .padding(.vertical, 10) } private var laneTitle: String { let lane = selectedSession.context.lane if !lane.isEmpty { return lane } return selectedSession.id == model.session.id ? "Current session" : selectedSession.shortID } private var subtitle: String { let pages = selectedSession.captures.count let pageWord = "\(pages) page\(pages == 1 ? "" : "s")" return "\(pageWord) · \(model.state(of: selectedSession).label)" } private var sendTitle: String { model.transport == .oneDrive ? "Save…" : "Send…" } private var scopeSymbol: String { switch model.captureScope { case .area: return "rectangle.dashed" case .window: return "macwindow" case .browser: return "safari" case .screen: return "display" } } /// Short form for the header: the area size, or what a window scope grabs. private var scopeDetail: String { switch model.captureScope { case .area: guard let region = model.region else { return "not set" } return "\(Int(region.rect.width)) × \(Int(region.rect.height))" case .window: return "front window" case .browser: return "browser" case .screen: guard let region = model.region else { return "all" } return "Display \(region.displayNumber)" } } // MARK: - Pages @ViewBuilder private var pages: some View { if selectedSession.isEmpty { emptyState } else { ScrollView { VStack(alignment: .leading, spacing: 12) { HStack(alignment: .firstTextBaseline, spacing: 8) { Text("Pages") .font(.headline) Text(pagesCaption) .font(.caption) .foregroundStyle(.secondary) Spacer(minLength: 8) Button("Remove Page") { removeSelectedPage() } .disabled(!model.selectedIsCurrent || selectedCaptureID == nil) } LazyVGrid( columns: [GridItem(.adaptive(minimum: 200, maximum: 240), spacing: 16)], alignment: .leading, spacing: 18 ) { ForEach(selectedSession.captures) { capture in PageCard( capture: capture, session: selectedSession, isSelected: selectedCaptureID == capture.id, canRemove: model.selectedIsCurrent ) { selectedCaptureID = capture.id } } } } .padding(16) } .onDeleteCommand { removeSelectedPage() } } } private var pagesCaption: String { model.selectedIsCurrent ? "In PDF order · Delete removes the selected page" : "In the order they were sent" } private var emptyState: some View { VStack(spacing: 10) { Image(systemName: "viewfinder") .font(.system(size: 28, weight: .light)) .foregroundStyle(.secondary) Text("No pages in this session") .font(.headline) Text(emptyStateDetail) .font(.caption) .foregroundStyle(.secondary) .multilineTextAlignment(.center) .frame(maxWidth: 320) HStack(spacing: 8) { Button("Choose Area…") { Task { await model.rePickRegion() } } Button("Capture \(model.hotkeyDisplayString)") { Task { await model.captureNow() } } .buttonStyle(.borderedProminent) } .padding(.top, 4) } .frame(maxWidth: .infinity, maxHeight: .infinity) .padding(24) } private var emptyStateDetail: String { if model.region == nil { return "Choose the part of the screen you review, then capture it. Each capture becomes one page of the PDF." } return "Press \(model.hotkeyDisplayString) to capture the saved area. Each capture becomes one page of the PDF." } private func removeSelectedPage() { guard model.selectedIsCurrent, let id = selectedCaptureID else { return } selectedCaptureID = nil Task { await model.removeCapture(id: id) } } } // MARK: - Sidebar row private struct SessionRow: View { @Environment(AppModel.self) private var model let session: CaptureSession var body: some View { let state = model.state(of: session) VStack(alignment: .leading, spacing: 1) { HStack(spacing: 5) { Text(lane) .lineLimit(1) if state == .current { Text("Current") .font(.system(size: 9, weight: .semibold)) .padding(.horizontal, 5) .padding(.vertical, 1) .background(.quaternary, in: Capsule()) } Spacer(minLength: 4) Text(DubaiTime.checkTime(session.createdAt)) .font(.caption) .foregroundStyle(.secondary) .monospacedDigit() } Text(detail(state)) .font(.caption) .foregroundStyle(state.isReturned ? AnyShapeStyle(.orange) : AnyShapeStyle(.secondary)) .lineLimit(1) } .padding(.vertical, 2) .accessibilityElement(children: .combine) .accessibilityLabel("\(lane), \(DubaiTime.checkTime(session.createdAt)), \(session.captures.count) pages, \(state.label)") } private var lane: String { let lane = session.context.lane return lane.isEmpty ? session.shortID : lane } private func detail(_ state: AppModel.SessionDisplayState) -> String { let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")" if case .returned(let marked) = state { return "\(pages) · came back with \(marked) page\(marked == 1 ? "" : "s") marked" } return "\(pages) · \(state.label)" } } // MARK: - Page card private struct PageCard: View { @Environment(AppModel.self) private var model let capture: Capture let session: CaptureSession let isSelected: Bool let canRemove: Bool let select: () -> Void @State private var hovering = false var body: some View { VStack(alignment: .leading, spacing: 5) { ZStack(alignment: .topLeading) { thumbnail if hovering && canRemove { Button("Remove") { Task { await model.removeCapture(id: capture.id) } } .font(.caption2.weight(.semibold)) .buttonStyle(.plain) .foregroundStyle(.white) .padding(.horizontal, 6) .padding(.vertical, 2) .background(.black.opacity(0.65), in: Capsule()) .padding(6) } } .overlay { RoundedRectangle(cornerRadius: 5, style: .continuous) .strokeBorder(isSelected ? Color.accentColor : .clear, lineWidth: 2) } .frame(maxWidth: 240, alignment: .leading) .onHover { hovering = $0 } .onTapGesture(perform: select) HStack(spacing: 6) { Text("Page \(capture.sequence)") .font(.caption.weight(isSelected ? .semibold : .regular)) Spacer(minLength: 4) Text(DubaiTime.checkTime(capture.capturedAt)) .font(.caption) .foregroundStyle(.secondary) .monospacedDigit() } } } @ViewBuilder private var thumbnail: some View { let url = model.imageURL(for: capture, in: session) if let image = NSImage(contentsOf: url) { Image(nsImage: image) .resizable() .aspectRatio(contentMode: .fit) .frame(maxWidth: .infinity) .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) .overlay { RoundedRectangle(cornerRadius: 4, style: .continuous) .strokeBorder(.quaternary, lineWidth: 0.5) } } else { RoundedRectangle(cornerRadius: 4, style: .continuous) .fill(.quaternary) .frame(height: 96) .overlay { Text("Image missing") .font(.caption2) .foregroundStyle(.secondary) } } } } // MARK: - Returned banner private struct ReturnedBanner: View { @Environment(AppModel.self) private var model let document: ReturnedDocument let session: CaptureSession var body: some View { HStack(spacing: 8) { Image(systemName: "pencil.and.outline") .foregroundStyle(.orange) Text(message) .font(.callout) Spacer(minLength: 8) Button("Open PDF") { NSWorkspace.shared.open(document.fileURL) } if model.sentPDFURL(for: session) != nil { Button("Show Original") { model.revealSentPDF(session) } } } .padding(.horizontal, 16) .padding(.vertical, 8) .background(.orange.opacity(0.1)) } private var message: String { let marked = document.annotatedPages.count return "Came back with marks on \(marked) page\(marked == 1 ? "" : "s")." } } // MARK: - Inspector private struct SessionInspector: View { @Environment(AppModel.self) private var model let session: CaptureSession var body: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { reviewDetails if !model.selectedIsCurrent { Text("Past sessions are read-only: the PDF already carries these values.") .font(.caption) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } pdfFacts sessionFacts } .padding(14) } .background(Color(nsColor: .windowBackgroundColor)) } private var reviewDetails: some View { VStack(alignment: .leading, spacing: 6) { Text("Review details") .font(.headline) GroupBox { VStack(spacing: 0) { contextRow("Lane", prompt: "dev03, customer test lane…", \.lane, focusOnRequest: true) RowDivider() contextRow("Deployed", prompt: "build that is live", \.deployedVersion) RowDivider() contextRow("Commit", prompt: "git SHA", \.commit) RowDivider() contextRow("Reviewer", prompt: "who is reviewing", \.reviewer) RowDivider() contextRow("Note", prompt: "what this session covers", \.note) } } Text("Printed on every page of the PDF. A new session starts with these values.") .font(.caption) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } } @ViewBuilder private func contextRow( _ label: String, prompt: String, _ field: WritableKeyPath, focusOnRequest: Bool = false ) -> some View { if model.selectedIsCurrent { EditableContextRow(label: label, prompt: prompt, field: field, focusOnRequest: focusOnRequest) } else { HStack(alignment: .firstTextBaseline, spacing: 8) { Text(label) .foregroundStyle(.secondary) .frame(width: 74, alignment: .leading) Text(displayValue(field)) .frame(maxWidth: .infinity, alignment: .leading) .textSelection(.enabled) } .padding(.vertical, 5) } } private func displayValue(_ field: KeyPath) -> String { let value = session.context[keyPath: field] return value.isEmpty ? "—" : value } private var pdfFacts: some View { VStack(alignment: .leading, spacing: 6) { Text("PDF") .font(.headline) GroupBox { VStack(spacing: 0) { FactRow(label: "File name", value: pdfFileName, selectable: true) RowDivider() FactRow(label: "Pages", value: "\(session.captures.count)") RowDivider() FactRow( label: "Sends via", value: model.transport == .oneDrive ? "OneDrive folder" : "AirDrop") RowDivider() FactRow(label: "Status", value: model.state(of: session).label) } } } } private var pdfFileName: String { if let name = session.pdfFileName { return name } return model.selectedIsCurrent ? model.nextPDFFileNameHint : "—" } private var sessionFacts: some View { VStack(alignment: .leading, spacing: 6) { Text("Session") .font(.headline) GroupBox { VStack(spacing: 0) { FactRow(label: "Started", value: DubaiTime.stamp(session.createdAt)) RowDivider() FactRow(label: "ID", value: session.shortID, monospaced: true) RowDivider() HStack { Text("Files") .foregroundStyle(.secondary) Spacer(minLength: 8) Button(model.selectedIsCurrent ? "Show Captures" : "Show in Finder") { model.revealSessionCaptures(session) } .buttonStyle(.link) } .padding(.vertical, 5) } } } } } private struct RowDivider: View { var body: some View { Divider().padding(.leading, 0) } } /// One editable review-detail row. The text lives in local state while typing and is /// written through to the open session's manifest; it re-seeds whenever the session's /// stored details change underneath it (a new session inheriting them, for example). private struct EditableContextRow: View { @Environment(AppModel.self) private var model let label: String let prompt: String let field: WritableKeyPath let focusOnRequest: Bool @State private var text: String = "" @State private var lastSynced: String = "" @FocusState private var focused: Bool var body: some View { HStack(spacing: 8) { Text(label) .foregroundStyle(.secondary) .frame(width: 74, alignment: .leading) TextField(prompt, text: $text) .textFieldStyle(.roundedBorder) .controlSize(.small) .focused($focused) .accessibilityLabel(label) .onSubmit { push() } .onChange(of: text) { _, _ in push() } } .padding(.vertical, 5) .onAppear { seed(from: stored) } .onChange(of: model.session.context) { _, newValue in let incoming = newValue[keyPath: field] guard incoming != lastSynced else { return } seed(from: incoming) } .onChange(of: model.session.id) { _, _ in seed(from: stored) } .onChange(of: model.laneFocusRequest) { _, _ in if focusOnRequest { focused = true } } } private var stored: String { model.session.context[keyPath: field] } private func seed(from value: String) { text = value lastSynced = value } private func push() { guard text != lastSynced else { return } lastSynced = text model.updateContext(field, text) } } private struct FactRow: View { let label: String let value: String var monospaced: Bool = false var selectable: Bool = false var body: some View { HStack(alignment: .firstTextBaseline, spacing: 8) { Text(label) .foregroundStyle(.secondary) Spacer(minLength: 8) Text(value) .font(monospaced ? .system(.body, design: .monospaced) : .body) .lineLimit(1) .truncationMode(.middle) .textSelection(.enabled) .help(value) } .padding(.vertical, 5) } } // MARK: - Window presentation extension AppModel: SessionsWindowPresenting { private static var sessionsWindowController: NSWindowController? public func presentSessionsWindow(focusLane: Bool) { if focusLane { requestLaneFocus() } if let existing = Self.sessionsWindowController { existing.window?.makeKeyAndOrderFront(nil) NSApp.activate() return } let hosting = NSHostingController(rootView: SessionsWindowView().environment(self)) let window = NSWindow(contentViewController: hosting) window.title = "Redline" window.styleMask = [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView] window.titlebarAppearsTransparent = false window.isReleasedWhenClosed = false window.setContentSize(NSSize(width: 1240, height: 760)) window.minSize = NSSize(width: 1000, height: 600) window.center() window.setFrameAutosaveName("RedlineSessionsWindow") let controller = NSWindowController(window: window) Self.sessionsWindowController = controller controller.showWindow(nil) NSApp.activate() } }