SPB Git

Repository Public

FlowMapView.swift 13.5 KB 263 lines swift

1import SwiftUI23/// AURA Flow: the user's path between pages as a navigable tree. Tap a step to return to it; open a step in a new tab4/// to start a branch. A list of journeys on the side (a menu on iPhone) switches between paths.5struct FlowMapView: View {6    let trail: FlowTrail7    /// The step the current tab stands on.8    let currentNodeID: UUID?9    var isPrivate = false10    var isRecording = true11    var onOpen: (FlowNode, _ inNewTab: Bool) -> Void12    var onDeleteJourney: (UUID) -> Void13    var onDismiss: () -> Void1415    @Environment(\.horizontalSizeClass) private var sizeClass16    @Environment(\.auraPolicy) private var policy17    @State private var selectedRoot: UUID?1819    private var compact: Bool { sizeClass == .compact }20    private var journeys: [FlowJourney] { trail.journeys }21    private var activeRoot: UUID? { selectedRoot ?? currentNodeID.flatMap { trail.root(of: $0)?.id } ?? journeys.first?.id }2223    var body: some View {24        VStack(spacing: 0) {25            header26            Rectangle().fill(Aura.Palette.hairline).frame(height: 1)27            if journeys.isEmpty {28                AuraEmptyState(symbol: "point.3.connected.trianglepath.dotted", title: L("No path yet"),29                               message: isPrivate ? L("In private browsing the path is kept in memory only and disappears with the window.")30                                                  : (isRecording ? L("Search or follow a link: Flow shows how each page led to the next, and where you branched off.")31                                                                 : L("Flow is turned off in Settings.")))32            } else if compact {33                compactBody34            } else {35                HStack(spacing: 0) {36                    journeyList.frame(width: 250)37                    Rectangle().fill(Aura.Palette.hairline).frame(width: 1)38                    if let root = activeRoot { FlowTreeView(map: FlowMap(trail: trail, rootID: root), currentNodeID: currentNodeID, onOpen: onOpen).id(root) }39                }40            }41        }42        .background(Aura.Palette.surface)43        .accessibilityIdentifier("flow-map")44    }4546    private var header: some View {47        HStack(spacing: 10) {48            Image(systemName: "point.3.connected.trianglepath.dotted").foregroundStyle(Aura.gradient).font(.title3)49            VStack(alignment: .leading, spacing: 1) {50                Text("Flow").font(.headline)51                Text(L("%d steps · %d journeys", trail.nodes.count, journeys.count)).font(.caption).foregroundStyle(.secondary)52            }53            Spacer()54            if compact, journeys.count > 1 {55                Menu {56                    ForEach(journeys) { journey in Button(journey.root.displayTitle) { selectedRoot = journey.id } }57                } label: { Label(L("Journeys"), systemImage: "list.bullet").labelStyle(.iconOnly) }58            }59            Button(L("Done"), action: onDismiss).keyboardShortcut(.cancelAction).accessibilityIdentifier("flow-done")60        }61        .padding(.horizontal, 16).padding(.vertical, 12)62    }6364    private var journeyList: some View {65        ScrollView {66            LazyVStack(alignment: .leading, spacing: 2) {67                AuraSectionHeader(text: L("Journeys")).padding(.horizontal, 8).padding(.vertical, 6)68                ForEach(journeys) { journey in69                    Button { AuraMotion.perform(.standard) { selectedRoot = journey.id } } label: {70                        JourneyRow(journey: journey, isSelected: journey.id == activeRoot)71                    }72                    .buttonStyle(AuraPressStyle(scale: 0.98))73                    .contextMenu { Button(L("Forget This Journey"), role: .destructive) { onDeleteJourney(journey.id); if selectedRoot == journey.id { selectedRoot = nil } } }74                }75            }76            .padding(8)77        }78        .background(Aura.Palette.chrome.opacity(0.5))79    }8081    /// iPhone: the same tree as an indented list, with rails showing the depth and a mark on each fork.82    private var compactBody: some View {83        ScrollView {84            LazyVStack(alignment: .leading, spacing: 0) {85                if let root = activeRoot {86                    ForEach(preorder(from: root), id: \.node.id) { entry in87                        Button { onOpen(entry.node, false) } label: {88                            HStack(spacing: 0) {89                                ForEach(0..<min(entry.depth, 8), id: \.self) { _ in90                                    Rectangle().fill(Aura.Palette.hairline).frame(width: 1.5).padding(.horizontal, 8)91                                }92                                FlowNodeCard(node: entry.node, isCurrent: entry.node.id == currentNodeID, isFork: trail.children(of: entry.node.id).count > 1, compact: true)93                                    .padding(.vertical, 4)94                            }95                            .frame(minHeight: 52)96                        }97                        .buttonStyle(AuraPressStyle(scale: 0.98))98                        .contextMenu { nodeMenu(entry.node) }99                    }100                    Button(role: .destructive) { onDeleteJourney(root); selectedRoot = nil } label: { Label(L("Forget This Journey"), systemImage: "trash").font(.callout) }101                        .padding(.top, 18).frame(maxWidth: .infinity)102                }103            }104            .padding(.horizontal, 12).padding(.vertical, 10)105        }106    }107108    @ViewBuilder private func nodeMenu(_ node: FlowNode) -> some View {109        Button { onOpen(node, false) } label: { Label(L("Go Back to This Step"), systemImage: "arrow.uturn.backward") }110        Button { onOpen(node, true) } label: { Label(L("Branch in a New Tab"), systemImage: "arrow.triangle.branch") }111        Button { PlatformActions.copy(node.url) } label: { Label(L("Copy Link"), systemImage: "doc.on.doc") }112    }113114    private func preorder(from root: UUID) -> [(node: FlowNode, depth: Int)] {115        var out: [(FlowNode, Int)] = []116        var stack: [(UUID, Int)] = [(root, 0)]117        var seen = Set<UUID>()118        while let (id, depth) = stack.popLast() {119            guard seen.insert(id).inserted, let node = trail.node(id) else { continue }120            out.append((node, depth))121            for child in trail.children(of: id).reversed() { stack.append((child.id, depth + 1)) }122        }123        return out124    }125}126127private struct JourneyRow: View {128    let journey: FlowJourney129    let isSelected: Bool130131    var body: some View {132        HStack(spacing: 8) {133            Image(systemName: FlowNodeCard.symbol(journey.root.kind)).foregroundStyle(isSelected ? AnyShapeStyle(Aura.Palette.accent) : AnyShapeStyle(.secondary)).frame(width: 18)134            VStack(alignment: .leading, spacing: 1) {135                Text(journey.root.displayTitle).font(.system(size: 12.5, weight: .medium)).lineLimit(1)136                Text(L("%d steps", journey.nodeCount) + (journey.branchCount > 0 ? " · " + L("%d forks", journey.branchCount) : "") + " · " + journey.lastVisit.formatted(.relative(presentation: .named)))137                    .font(.system(size: 10.5)).foregroundStyle(.secondary).lineLimit(1)138            }139            Spacer(minLength: 0)140        }141        .padding(.horizontal, 8).padding(.vertical, 7)142        .background(RoundedRectangle(cornerRadius: 9, style: .continuous).fill(isSelected ? Aura.Palette.selected : .clear))143        .contentShape(Rectangle())144        .accessibilityAddTraits(isSelected ? .isSelected : [])145    }146}147148/// The tree of one journey, left to right. Native two-axis scrolling; edges are drawn in one canvas pass.149private struct FlowTreeView: View {150    let map: FlowMap151    let currentNodeID: UUID?152    let onOpen: (FlowNode, Bool) -> Void153    @Environment(\.auraPolicy) private var policy154    @State private var appeared = false155156    private let cell = CGSize(width: 232, height: 76)157    private let card = CGSize(width: 196, height: 54)158    private let inset: CGFloat = 28159160    private func center(_ placed: FlowMap.Placed) -> CGPoint {161        CGPoint(x: inset + CGFloat(placed.column) * cell.width + card.width / 2, y: inset + CGFloat(placed.row) * cell.height + card.height / 2)162    }163164    var body: some View {165        let size = CGSize(width: inset * 2 + CGFloat(max(map.columns, 1)) * cell.width, height: inset * 2 + CGFloat(max(map.rows, 1)) * cell.height)166        let onPath = Set(pathToCurrent)167        ScrollViewReader { proxy in168            ScrollView([.horizontal, .vertical]) {169                ZStack(alignment: .topLeading) {170                    Canvas(opaque: false, rendersAsynchronously: false) { context, _ in171                        for edge in map.edges {172                            guard let a = map.position(of: edge.from), let b = map.position(of: edge.to) else { continue }173                            let start = CGPoint(x: center(a).x + card.width / 2, y: center(a).y), end = CGPoint(x: center(b).x - card.width / 2, y: center(b).y)174                            var path = Path()175                            path.move(to: start)176                            let mid = (start.x + end.x) / 2177                            path.addCurve(to: end, control1: CGPoint(x: mid, y: start.y), control2: CGPoint(x: mid, y: end.y))178                            let active = onPath.contains(edge.from) && onPath.contains(edge.to)179                            if active {180                                context.stroke(path, with: .linearGradient(Gradient(colors: [Aura.Palette.violet, Aura.Palette.cyan]), startPoint: start, endPoint: end), lineWidth: 2.2)181                            } else {182                                context.stroke(path, with: .color(Color.primary.opacity(0.18)), lineWidth: 1.3)183                            }184                        }185                    }186                    .frame(width: size.width, height: size.height)187                    .accessibilityHidden(true)188189                    ForEach(Array(map.placed.enumerated()), id: \.element.id) { index, placed in190                        Button { onOpen(placed.node, false) } label: {191                            FlowNodeCard(node: placed.node, isCurrent: placed.id == currentNodeID, isFork: map.edges.filter { $0.from == placed.id }.count > 1, compact: false)192                                .frame(width: card.width, height: card.height)193                        }194                        .buttonStyle(AuraPressStyle(scale: 0.96))195                        .contextMenu {196                            Button(L("Go Back to This Step")) { onOpen(placed.node, false) }197                            Button(L("Branch in a New Tab")) { onOpen(placed.node, true) }198                            Button(L("Copy Link")) { PlatformActions.copy(placed.node.url) }199                        }200                        .position(center(placed))201                        .opacity(appeared ? 1 : 0)202                        .offset(x: appeared || !policy.allowsSpatial ? 0 : -14)203                        .animation(AuraMotion.animation(.expressive, policy: policy)?.delay(Double(min(placed.column, 12)) * 0.035), value: appeared)204                        .id(placed.id)205                        .accessibilityLabel(placed.node.displayTitle)206                        .accessibilityValue(placed.id == currentNodeID ? L("Current step") : placed.node.host)207                        .accessibilityIdentifier("flow-node")208                        .zIndex(Double(index))209                    }210                }211                .frame(width: size.width, height: size.height, alignment: .topLeading)212            }213            .onAppear {214                appeared = true215                if let currentNodeID, map.position(of: currentNodeID) != nil { proxy.scrollTo(currentNodeID, anchor: .center) }216            }217        }218    }219220    private var pathToCurrent: [UUID] {221        guard let currentNodeID else { return [] }222        var out: [UUID] = []223        var next: UUID? = currentNodeID224        while let id = next, let placed = map.position(of: id), out.count < 500 { out.append(id); next = placed.node.parentID }225        return out226    }227}228229struct FlowNodeCard: View {230    let node: FlowNode231    let isCurrent: Bool232    let isFork: Bool233    let compact: Bool234235    static func symbol(_ kind: FlowNode.Kind) -> String {236        switch kind {237        case .search: return "magnifyingglass"238        case .document: return "doc.richtext"239        case .page: return "globe"240        }241    }242243    var body: some View {244        HStack(spacing: 9) {245            Image(systemName: Self.symbol(node.kind)).font(.system(size: 12, weight: .semibold))246                .foregroundStyle(isCurrent ? AnyShapeStyle(Color.white) : AnyShapeStyle(.secondary))247                .frame(width: 26, height: 26)248                .background(Circle().fill(isCurrent ? AnyShapeStyle(Aura.gradient) : AnyShapeStyle(Aura.Palette.hover)))249            VStack(alignment: .leading, spacing: 1) {250                Text(node.displayTitle).font(.system(size: 12.5, weight: isCurrent ? .semibold : .medium)).lineLimit(1)251                Text(node.kind == .search ? "SP Search" : node.host).font(.system(size: 10.5)).foregroundStyle(.secondary).lineLimit(1)252            }253            Spacer(minLength: 0)254            if isFork { Image(systemName: "arrow.triangle.branch").font(.system(size: 10, weight: .semibold)).foregroundStyle(Aura.Palette.cyan).accessibilityLabel(L("Fork")) }255            if node.visits > 1 { Text("×\(node.visits)").font(.system(size: 10, weight: .medium, design: .rounded)).foregroundStyle(.tertiary) }256        }257        .padding(.horizontal, 9)258        .frame(maxWidth: .infinity, minHeight: compact ? 44 : 54, alignment: .leading)259        .auraSurface(.panel, radius: 13, luminous: isCurrent)260        .contentShape(Rectangle())261    }262}263
Files main
Menu

Theme