SPB Git

Repository Public

ReviewPanel.swift 22.9 KB 414 lines swift

1// ORIX Docs2// File: App/Sources/Sidebar/ReviewPanel.swift3// Description: The review panel: reviewer identity, change tracking and markup switches, the filtered list of tracked changes4//              with accept / reject, and the comment threads (edit, reply, resolve, delete).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel10import DocLayout1112private enum ChangeKindFilter: String, CaseIterable, Identifiable {13    case all, insertions, deletions, formatting14    var id: String { rawValue }15    var title: LocalizedStringKey {16        switch self { case .all: return "All Kinds"; case .insertions: return "Insertions"; case .deletions: return "Deletions"; case .formatting: return "Formatting" }17    }18    func includes(_ kind: TrackedChange.Kind) -> Bool {19        switch self {20        case .all: return true21        case .insertions: return kind == .insertion || kind == .paragraphInserted22        case .deletions: return kind == .deletion || kind == .paragraphDeleted23        case .formatting: return kind == .formatting24        }25    }26}2728private struct BulkResolution: Identifiable {29    let accept: Bool30    /// Revision ids to resolve; nil resolves every change of the document.31    let ids: Set<String>?32    let count: Int33    var id: String { "\(accept)-\(count)-\(ids?.count ?? -1)" }34}3536struct ReviewPanel: View {37    @Bindable var session: DocumentSession38    @State private var authorFilter: String?39    @State private var kindFilter = ChangeKindFilter.all40    @State private var pendingBulk: BulkResolution?41    @FocusState private var reviewerFocused: Bool4243    var body: some View {44        let _ = session.revision45        let _ = session.selectionRevision46        let doc = session.doc47        let allChanges = doc.trackedChanges()48        let authors = Array(Set(allChanges.map(\.author))).sorted()49        let activeAuthor = authorFilter.flatMap { authors.contains($0) ? $0 : nil }50        let changes = allChanges.filter { (activeAuthor == nil || $0.author == activeAuthor) && kindFilter.includes($0.kind) }51        let filtered = activeAuthor != nil || kindFilter != .all52        let comments = doc.commentsInDocumentOrder()5354        VStack(spacing: 0) {55            controls56            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)57            ScrollViewReader { proxy in58                ScrollView {59                    LazyVStack(alignment: .leading, spacing: 0) {60                        changesHeader(total: allChanges.count, shown: changes, authors: authors, activeAuthor: activeAuthor, filtered: filtered)61                        if allChanges.isEmpty {62                            ReviewHint(symbol: "pencil.and.outline", text: doc.settings.trackChanges63                                       ? "Tracking is on. Insertions, deletions and formatting changes will be listed here."64                                       : "No tracked changes. Turn on Track Changes to record every edit for review.")65                        } else if changes.isEmpty {66                            ReviewHint(symbol: "line.3.horizontal.decrease.circle", text: "No change matches the filters.")67                        } else {68                            ForEach(changes) { change in69                                ChangeRow(change: change, isCurrent: isSelected(change),70                                          select: { session.reveal(story: change.story, path: change.path, range: change.range) },71                                          resolve: { accept in resolve([change.revisionID], accept: accept) })72                            }73                        }74                        Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1).padding(.top, ORIX.Space.s)75                        SidebarSectionHeader(title: "Comments") {76                            if !comments.isEmpty {77                                let open = comments.filter { !$0.resolved }.count78                                Text(open == comments.count ? "\(comments.count)" : "\(open) open of \(comments.count)").accessibilityIdentifier("review-comment-count")79                            }80                            SidebarIconButton(symbol: "plus.bubble", label: "Add Comment on Selection") { session.run(.insertComment) }81                                .accessibilityIdentifier("review-add-comment")82                        }83                        .padding(.horizontal, ORIX.Space.m).padding(.top, ORIX.Space.m).padding(.bottom, ORIX.Space.s)84                        if comments.isEmpty {85                            ReviewHint(symbol: "text.bubble", text: "No comments. Select some text and choose Insert › Comment (⌥⌘M).")86                        } else {87                            ForEach(comments) { comment in88                                CommentCard(session: session, comment: comment, anchor: doc.commentAnchor(comment.id))89                                    .id(comment.id)90                                    .padding(.horizontal, ORIX.Space.s).padding(.bottom, ORIX.Space.s)91                            }92                        }93                    }94                    .padding(.bottom, ORIX.Space.m)95                }96                .onChange(of: session.pendingCommentFocus) { _, id in97                    if let id { withAnimation(ORIX.Motion.quick) { proxy.scrollTo(id, anchor: .center) } }98                }99                .onAppear { if let id = session.pendingCommentFocus { proxy.scrollTo(id, anchor: .center) } }100            }101        }102        .confirmationDialog(bulkTitle, isPresented: Binding(get: { pendingBulk != nil }, set: { if !$0 { pendingBulk = nil } }), presenting: pendingBulk) { bulk in103            Button(bulk.accept ? "Accept \(bulk.count) Changes" : "Reject \(bulk.count) Changes", role: bulk.accept ? nil : .destructive) {104                session.perform(bulk.accept ? String(localized: "Accept Changes") : String(localized: "Reject Changes")) { $0.resolveChanges(accept: bulk.accept, ids: bulk.ids) }105            }106            .accessibilityIdentifier("review-bulk-confirm")107            Button("Cancel", role: .cancel) {}108        } message: { bulk in109            Text(bulk.accept ? "The changes become part of the text and their markup disappears. You can undo this."110                 : "The text returns to what it was before these changes. You can undo this.")111        }112        .accessibilityIdentifier("review-panel")113    }114115    private var bulkTitle: Text {116        guard let bulk = pendingBulk else { return Text("") }117        return bulk.accept ? Text("Accept \(bulk.count) tracked changes?") : Text("Reject \(bulk.count) tracked changes?")118    }119120    // MARK: Controls121122    private var controls: some View {123        VStack(alignment: .leading, spacing: ORIX.Space.s) {124            SidebarSectionHeader(title: "Review").frame(height: 14)125            HStack(spacing: ORIX.Space.s) {126                Circle().fill(ReviewColors.color(for: session.author).color).frame(width: 8, height: 8).accessibilityHidden(true)127                TextField("Reviewer name", text: Binding(get: { session.author }, set: { session.author = $0; AppSettings.shared.reviewerName = $0 }))128                    .focused($reviewerFocused)129                    .modifier(SidebarFieldChrome(focused: reviewerFocused))130                    .help("Name recorded on your tracked changes and comments. It stays on this Mac and in the documents you edit.")131                    .accessibilityLabel(Text("Reviewer name"))132                    .accessibilityIdentifier("review-author")133            }134            VStack(spacing: 6) {135                Toggle(isOn: Binding(get: { session.doc.settings.trackChanges }, set: { if $0 != session.doc.settings.trackChanges { session.run(.trackChanges) } })) {136                    Text("Track Changes").frame(maxWidth: .infinity, alignment: .leading)137                }138                .accessibilityIdentifier("review-track-changes")139                Toggle(isOn: $session.showMarkup) { Text("Show Markup").frame(maxWidth: .infinity, alignment: .leading) }140                    .help("Show tracked changes with their markup, or the text as if every change were accepted.")141                    .accessibilityIdentifier("review-show-markup")142            }143            .toggleStyle(.switch).controlSize(.mini)144            .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text)145        }146        .padding(.horizontal, ORIX.Space.m).padding(.top, ORIX.Space.s).padding(.bottom, ORIX.Space.m)147    }148149    @ViewBuilder150    private func changesHeader(total: Int, shown: [TrackedChange], authors: [String], activeAuthor: String?, filtered: Bool) -> some View {151        VStack(alignment: .leading, spacing: ORIX.Space.s) {152            SidebarSectionHeader(title: "Changes") {153                if total > 0 { Text(filtered ? "\(shown.count) of \(total)" : "\(total)").accessibilityIdentifier("review-change-count") }154                BarButton(symbol: "chevron.up", help: "Previous Change", isEnabled: total > 0) { session.run(.previousChange) }155                BarButton(symbol: "chevron.down", help: "Next Change", isEnabled: total > 0) { session.run(.nextChange) }156            }157            if total > 0 {158                HStack(spacing: ORIX.Space.s) {159                    Picker("Author", selection: Binding(get: { activeAuthor }, set: { authorFilter = $0 })) {160                        Text("All Authors").tag(String?.none)161                        ForEach(authors, id: \.self) { Text($0).tag(String?.some($0)) }162                    }163                    .accessibilityIdentifier("review-filter-author")164                    Picker("Kind", selection: $kindFilter) {165                        ForEach(ChangeKindFilter.allCases) { Text($0.title).tag($0) }166                    }167                    .accessibilityIdentifier("review-filter-kind")168                }169                .labelsHidden().pickerStyle(.menu).controlSize(.small)170                HStack(spacing: ORIX.Space.s) {171                    let ids = filtered ? Set(shown.map(\.revisionID)) : nil172                    Button { pendingBulk = BulkResolution(accept: true, ids: ids, count: shown.count) } label: {173                        Label(filtered ? "Accept Shown" : "Accept All", systemImage: "checkmark").frame(maxWidth: .infinity)174                    }175                    .accessibilityIdentifier("review-accept-all")176                    Button { pendingBulk = BulkResolution(accept: false, ids: ids, count: shown.count) } label: {177                        Label(filtered ? "Reject Shown" : "Reject All", systemImage: "xmark").frame(maxWidth: .infinity)178                    }179                    .accessibilityIdentifier("review-reject-all")180                }181                .buttonStyle(ORIXButtonStyle(prominent: false))182                .disabled(shown.isEmpty).opacity(shown.isEmpty ? 0.45 : 1)183            }184        }185        .padding(.horizontal, ORIX.Space.m).padding(.top, ORIX.Space.s).padding(.bottom, ORIX.Space.s)186    }187188    private func isSelected(_ change: TrackedChange) -> Bool {189        let sel = session.selection190        guard sel.story == change.story, sel.start.path == change.path, sel.end.path == change.path else { return false }191        return sel.start.offset <= change.range.upperBound && sel.end.offset >= change.range.lowerBound && (!sel.isCaret || !change.range.isEmpty)192    }193194    private func resolve(_ ids: Set<String>, accept: Bool) {195        session.perform(accept ? String(localized: "Accept Change") : String(localized: "Reject Change")) { $0.resolveChanges(accept: accept, ids: ids) }196    }197}198199private struct ReviewHint: View {200    let symbol: String201    let text: LocalizedStringKey202    var body: some View {203        HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.s) {204            Image(systemName: symbol).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 14)205            Text(text).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)206        }207        .padding(.horizontal, ORIX.Space.m).padding(.vertical, ORIX.Space.s)208        .frame(maxWidth: .infinity, alignment: .leading)209        .accessibilityElement(children: .combine)210    }211}212213// MARK: - Tracked change row214215private struct ChangeRow: View {216    let change: TrackedChange217    let isCurrent: Bool218    let select: () -> Void219    let resolve: (Bool) -> Void220    @State private var hover = false221222    private var kind: (symbol: String, label: String) {223        switch change.kind {224        case .insertion: return ("plus", String(localized: "Inserted"))225        case .deletion: return ("minus", String(localized: "Deleted"))226        case .formatting: return ("textformat", String(localized: "Formatted"))227        case .paragraphInserted: return ("paragraphsign", String(localized: "Paragraph break inserted"))228        case .paragraphDeleted: return ("paragraphsign", String(localized: "Paragraph break deleted"))229        }230    }231232    private var excerpt: String? {233        switch change.kind {234        case .paragraphInserted, .paragraphDeleted: return nil235        default:236            let s = SidebarFormat.excerpt(change.text, limit: 110)237            return s.isEmpty ? nil : s238        }239    }240241    var body: some View {242        let color = ReviewColors.color(for: change.author).color243        HStack(alignment: .top, spacing: 6) {244            Button(action: select) {245                VStack(alignment: .leading, spacing: 3) {246                    HStack(spacing: 5) {247                        Circle().fill(color).frame(width: 7, height: 7)248                        Text(change.author.isEmpty ? String(localized: "Unknown author") : change.author)249                            .font(.system(size: 11.5, weight: .semibold)).foregroundStyle(ORIX.Palette.text).lineLimit(1)250                        Spacer(minLength: 4)251                        Text(SidebarFormat.date(change.date)).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).fixedSize()252                    }253                    Label(kind.label, systemImage: kind.symbol)254                        .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).labelStyle(.titleAndIcon)255                    if let excerpt {256                        Text(excerpt)257                            .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text.opacity(0.85))258                            .strikethrough(change.kind == .deletion, color: ORIX.Palette.textSecondary)259                            .underline(change.kind == .insertion, color: color)260                            .lineLimit(3).multilineTextAlignment(.leading)261                    }262                }263                .frame(maxWidth: .infinity, alignment: .leading)264                .contentShape(Rectangle())265            }266            .buttonStyle(.plain)267            .accessibilityElement(children: .ignore)268            .accessibilityLabel(Text("\(kind.label) by \(change.author): \(excerpt ?? "")"))269            .accessibilityAddTraits(isCurrent ? [.isButton, .isSelected] : .isButton)270            VStack(spacing: 3) {271                SidebarIconButton(symbol: "checkmark", label: "Accept Change", tint: ORIX.Palette.positive) { resolve(true) }272                    .accessibilityIdentifier("review-accept")273                SidebarIconButton(symbol: "xmark", label: "Reject Change", tint: ORIX.Palette.critical) { resolve(false) }274                    .accessibilityIdentifier("review-reject")275            }276        }277        .padding(.leading, 10).padding(.trailing, 8).padding(.vertical, 7)278        .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(isCurrent ? ORIX.Palette.accent.opacity(0.11) : (hover ? ORIX.Palette.text.opacity(0.05) : .clear)))279        .overlay(alignment: .leading) {280            RoundedRectangle(cornerRadius: 1).fill(isCurrent ? ORIX.Palette.accent : color.opacity(0.55)).frame(width: 2.5).padding(.vertical, 6)281        }282        .padding(.horizontal, ORIX.Space.s)283        .onHover { hover = $0 }284    }285}286287// MARK: - Comment thread288289private struct CommentCard: View {290    let session: DocumentSession291    let comment: Comment292    let anchor: (story: StoryID, path: ParaPath, range: Range<Int>, text: String)?293    @State private var draft = ""294    @State private var reply = ""295    @FocusState private var focus: Field?296297    private enum Field { case text, reply }298299    var body: some View {300        let color = ReviewColors.color(for: comment.author).color301        VStack(alignment: .leading, spacing: 6) {302            HStack(spacing: 5) {303                Circle().fill(color).frame(width: 7, height: 7)304                Text(comment.author.isEmpty ? String(localized: "Unknown author") : comment.author)305                    .font(.system(size: 11.5, weight: .semibold)).foregroundStyle(ORIX.Palette.text).lineLimit(1)306                if comment.resolved {307                    Label("Resolved", systemImage: "checkmark.circle.fill").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.positive).labelStyle(.titleAndIcon)308                }309                Spacer(minLength: 4)310                Text(SidebarFormat.date(comment.date)).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).fixedSize()311            }312            if let anchor {313                Button { session.reveal(story: anchor.story, path: anchor.path, range: anchor.range) } label: {314                    HStack(alignment: .top, spacing: 6) {315                        RoundedRectangle(cornerRadius: 1).fill(ORIX.Palette.secondary.opacity(0.8)).frame(width: 2)316                        Text(SidebarFormat.excerpt(anchor.text, limit: 90).isEmpty ? String(localized: "Object") : SidebarFormat.excerpt(anchor.text, limit: 90))317                            .font(.system(size: 11).italic()).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2).multilineTextAlignment(.leading)318                        Spacer(minLength: 0)319                    }320                    .fixedSize(horizontal: false, vertical: true)321                    .contentShape(Rectangle())322                }323                .buttonStyle(.plain)324                .help("Show the commented text")325                .accessibilityLabel(Text("Commented text: \(anchor.text)"))326                .accessibilityHint(Text("Shows it in the document"))327            }328            TextField("Write a comment", text: $draft, axis: .vertical)329                .lineLimit(1...8)330                .focused($focus, equals: .text)331                .modifier(SidebarFieldChrome(focused: focus == .text))332                .accessibilityLabel(Text("Comment text"))333                .accessibilityIdentifier("comment-text")334            ForEach(comment.replies) { r in335                HStack(alignment: .top, spacing: 6) {336                    Image(systemName: "arrow.turn.down.right").font(.system(size: 9, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary).padding(.top, 2)337                    VStack(alignment: .leading, spacing: 1) {338                        HStack(spacing: 5) {339                            Circle().fill(ReviewColors.color(for: r.author).color).frame(width: 6, height: 6)340                            Text(r.author).font(.system(size: 11, weight: .semibold)).foregroundStyle(ORIX.Palette.text).lineLimit(1)341                            Spacer(minLength: 4)342                            Text(SidebarFormat.date(r.date)).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).fixedSize()343                        }344                        Text(r.text).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text.opacity(0.9)).fixedSize(horizontal: false, vertical: true)345                            .textSelection(.enabled)346                    }347                }348                .accessibilityElement(children: .combine)349            }350            HStack(spacing: 4) {351                TextField("Reply", text: $reply)352                    .focused($focus, equals: .reply)353                    .modifier(SidebarFieldChrome(focused: focus == .reply))354                    .onSubmit { sendReply() }355                    .accessibilityLabel(Text("Reply"))356                    .accessibilityIdentifier("comment-reply")357                SidebarIconButton(symbol: comment.resolved ? "arrow.uturn.backward" : "checkmark", label: comment.resolved ? "Reopen Comment" : "Resolve Comment",358                                  tint: comment.resolved ? ORIX.Palette.textSecondary : ORIX.Palette.positive) {359                    let resolved = !comment.resolved, id = comment.id360                    commitText()361                    session.perform(resolved ? String(localized: "Resolve Comment") : String(localized: "Reopen Comment")) { $0.setComment(id, resolved: resolved) }362                }363                .accessibilityIdentifier("comment-resolve")364                SidebarIconButton(symbol: "trash", label: "Delete Comment", tint: ORIX.Palette.critical) { remove() }365                    .accessibilityIdentifier("comment-delete")366            }367        }368        .padding(ORIX.Space.s)369        .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.surface.opacity(comment.resolved ? 0.5 : 1)))370        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(focus != nil ? ORIX.Palette.accent.opacity(0.6) : ORIX.Palette.hairline))371        .onAppear { draft = comment.text; takePendingFocus() }372        .onChange(of: comment.text) { _, text in if focus != .text { draft = text } }373        .onChange(of: session.pendingCommentFocus) { _, _ in takePendingFocus() }374        .onChange(of: focus) { old, new in if old == .text, new != .text { commitText() } }375        .onDisappear { if draft != comment.text, !isBlank(draft) { commitText() } }376        .accessibilityElement(children: .contain)377        .accessibilityLabel(Text("Comment by \(comment.author)"))378        .accessibilityIdentifier("comment-card")379    }380381    private func isBlank(_ s: String) -> Bool { s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }382383    private func takePendingFocus() {384        guard session.pendingCommentFocus == comment.id else { return }385        session.pendingCommentFocus = nil386        DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { focus = .text }387    }388389    /// Stores the edited text. A comment left without any text and without replies is removed.390    private func commitText() {391        let id = comment.id, text = draft.trimmingCharacters(in: .whitespacesAndNewlines)392        guard session.doc.comments.contains(where: { $0.id == id }) else { return }393        if text.isEmpty {394            if comment.text.isEmpty && comment.replies.isEmpty { session.perform(String(localized: "Delete Comment")) { $0.removeComment(id) } }395            else { draft = comment.text }396        } else if text != comment.text {397            session.perform(String(localized: "Edit Comment")) { $0.editComment(id, text: text) }398        }399    }400401    private func sendReply() {402        let id = comment.id, text = reply.trimmingCharacters(in: .whitespacesAndNewlines)403        guard !text.isEmpty else { return }404        reply = ""405        session.perform(String(localized: "Reply to Comment")) { $0.replyToComment(id, text: text) }406    }407408    private func remove() {409        let id = comment.id410        focus = nil411        session.perform(String(localized: "Delete Comment")) { $0.removeComment(id) }412    }413}414
Files main
Menu

Theme