Repository Public
1import SwiftUI2#if os(macOS)3import AppKit4#endif56/// AURA Tab Constellation: the open tabs as cards floating in space, clustered by group and by site, with lines for7/// the relations between them. An alternative to the tab strip — never a replacement.8struct ConstellationView: View {9 let items: [ConstellationItem]10 let selectedID: UUID?11 var isPrivate = false12 var thumbnail: (UUID) -> PlatformImage? = { _ in nil }13 var icon: (UUID) -> PlatformImage? = { _ in nil }14 var onOpen: (UUID) -> Void15 var onClose: (Set<UUID>) -> Void16 /// Makes one tab group out of the given tabs.17 var onGroup: (Set<UUID>) -> Void18 /// A tab was dropped on a cluster: join that group (or leave groups when the cluster is not a group).19 var onMove: (UUID, ConstellationMap.Cluster) -> Void20 var onNewTab: () -> Void21 var onDismiss: () -> Void2223 @Environment(\.auraPolicy) private var policy24 @Environment(\.horizontalSizeClass) private var sizeClass25 @State private var viewport = AuraViewport()26 @State private var fitted = false27 @State private var query = ""28 @State private var picked = Set<UUID>()29 @State private var cursor: UUID?30 @State private var dragging: (id: UUID, translation: CGSize)?31 @State private var appeared = false32 @State private var searchFocus = 033 @FocusState private var keyboard: Bool3435 private var compact: Bool { sizeClass == .compact }36 private var cardSize: CGSize { compact ? CGSize(width: 132, height: 96) : CGSize(width: 168, height: 118) }37 private static let zoomRange: ClosedRange<CGFloat> = 0.18...2.23839 var body: some View {40 let map = ConstellationMap(items: items, cardSize: cardSize)41 let matching = ConstellationMap.filter(items, query: query)42 GeometryReader { proxy in43 ZStack {44 backdrop45 space(map: map, matching: matching, size: proxy.size)46 .contentShape(Rectangle())47 .gesture(panGesture)48 .simultaneousGesture(zoomGesture)49 .onScrollWheel { delta, zooming in50 if zooming { viewport.step(delta.height > 0 ? 1.06 : 0.94, range: Self.zoomRange) }51 else { viewport.offset.width += delta.width; viewport.offset.height += delta.height }52 }53 VStack {54 header(map: map)55 Spacer()56 controls(map: map, size: proxy.size)57 }58 .padding(compact ? 10 : 16)59 }60 .onAppear {61 if !fitted { viewport.scale = map.fittingScale(in: proxy.size, padding: compact ? 30 : 90); fitted = true }62 cursor = selectedID63 keyboard = true64 AuraMotion.perform(.expressive) { appeared = true }65 }66 .focusable()67 .focusEffectDisabled()68 .focused($keyboard)69 .onKeyPress(.leftArrow) { moveCursor(map, -1, 0) }70 .onKeyPress(.rightArrow) { moveCursor(map, 1, 0) }71 .onKeyPress(.upArrow) { moveCursor(map, 0, -1) }72 .onKeyPress(.downArrow) { moveCursor(map, 0, 1) }73 .onKeyPress(.return) { if let cursor { onOpen(cursor) }; return .handled }74 .onKeyPress(.space) { if let cursor { toggle(cursor) }; return .handled }75 .onKeyPress(.delete) { closePickedOrCursor(); return .handled }76 .onKeyPress(.escape) { if !picked.isEmpty { picked = [] } else { onDismiss() }; return .handled }77 .onKeyPress(characters: CharacterSet(charactersIn: "/")) { _ in searchFocus += 1; return .handled }78 }79 .accessibilityElement(children: .contain)80 .accessibilityLabel(L("Tab Constellation"))81 .accessibilityIdentifier("constellation")82 }8384 // MARK: Layers8586 private var backdrop: some View {87 ZStack {88 Aura.Palette.obsidian89 RadialGradient(colors: [(isPrivate ? Aura.Palette.violet : Aura.Palette.deepSpace).opacity(0.85), .clear], center: .center, startRadius: 0, endRadius: 900)90 RadialGradient(colors: [Aura.Palette.violet.opacity(0.16), .clear], center: .topLeading, startRadius: 0, endRadius: 700)91 }92 .ignoresSafeArea()93 .onTapGesture { picked = [] }94 }9596 private func screen(_ point: CGPoint, map: ConstellationMap, size: CGSize) -> CGPoint {97 CGPoint(x: size.width / 2 + (point.x - map.bounds.midX) * viewport.scale + viewport.offset.width,98 y: size.height / 2 + (point.y - map.bounds.midY) * viewport.scale + viewport.offset.height)99 }100101 private func world(_ point: CGPoint, map: ConstellationMap, size: CGSize) -> CGPoint {102 CGPoint(x: (point.x - size.width / 2 - viewport.offset.width) / viewport.scale + map.bounds.midX,103 y: (point.y - size.height / 2 - viewport.offset.height) / viewport.scale + map.bounds.midY)104 }105106 private func space(map: ConstellationMap, matching: Set<UUID>, size: CGSize) -> some View {107 ZStack {108 // Halos and lines in one canvas pass.109 Canvas(opaque: false, rendersAsynchronously: false) { context, _ in110 for cluster in map.clusters where cluster.kind != .loose {111 let c = screen(cluster.center, map: map, size: size)112 let r = cluster.radius * viewport.scale113 let color = Aura.Palette.identity(cluster.colorIndex)114 context.fill(Path(ellipseIn: CGRect(x: c.x - r, y: c.y - r, width: r * 2, height: r * 2)),115 with: .radialGradient(Gradient(colors: [color.opacity(0.16), color.opacity(0.05), .clear]), center: c, startRadius: 0, endRadius: r))116 }117 for link in map.links {118 guard let a = map.positions[link.from], let b = map.positions[link.to] else { continue }119 var path = Path()120 path.move(to: screen(a, map: map, size: size))121 path.addLine(to: screen(b, map: map, size: size))122 let dimmed = !(matching.contains(link.from) && matching.contains(link.to))123 switch link.kind {124 case .parent: context.stroke(path, with: .color(Aura.Palette.cyan.opacity(dimmed ? 0.12 : 0.55)), style: StrokeStyle(lineWidth: 1.4, dash: [5, 4]))125 case .group, .domain: context.stroke(path, with: .color(Color.white.opacity(dimmed ? 0.05 : 0.20)), lineWidth: 1)126 }127 }128 }129 .allowsHitTesting(false)130 .accessibilityHidden(true)131132 ForEach(map.clusters.filter { $0.kind != .loose }) { cluster in133 let c = screen(cluster.center, map: map, size: size)134 AuraChip(text: cluster.label.isEmpty ? L("Group") : cluster.label, symbol: cluster.kind == .group ? "square.stack.3d.up" : "globe",135 tint: Aura.Palette.identity(cluster.colorIndex))136 .position(x: c.x, y: c.y - cluster.radius * viewport.scale + 4)137 .opacity(viewport.scale > 0.32 ? 1 : 0)138 .allowsHitTesting(false)139 }140141 ForEach(Array(items.enumerated()), id: \.element.id) { index, item in142 if let p = map.positions[item.id] {143 let base = screen(p, map: map, size: size)144 let drag = dragging?.id == item.id ? dragging!.translation : .zero145 ConstellationCard(item: item, size: cardSize, lightweight: map.isLightweight || viewport.scale < 0.42,146 thumbnail: map.isLightweight ? nil : thumbnail(item.id), icon: icon(item.id),147 isCurrent: item.id == selectedID, isPicked: picked.contains(item.id), isCursor: item.id == cursor && keyboard,148 isDimmed: !matching.contains(item.id), onClose: { onClose([item.id]) })149 .scaleEffect(viewport.scale.clamped(0.42, 1.25) * (dragging?.id == item.id ? 1.06 : 1) * (appeared ? 1 : 0.3))150 .opacity(appeared ? 1 : 0)151 .animation(AuraMotion.animation(.expressive, policy: policy)?.delay(Double(min(index, 24)) * 0.012), value: appeared)152 .position(x: base.x + drag.width, y: base.y + drag.height)153 .zIndex(dragging?.id == item.id ? 10 : (item.id == selectedID ? 2 : 1))154 .onTapGesture { tap(item.id) }155 .gesture(cardDrag(item.id, map: map, size: size, origin: base))156 .contextMenu { cardMenu(item) }157 .accessibilityElement(children: .ignore)158 .accessibilityLabel(item.title)159 .accessibilityValue(item.groupName ?? item.domain)160 .accessibilityAddTraits(item.id == selectedID ? [.isButton, .isSelected] : .isButton)161 .accessibilityAction { onOpen(item.id) }162 .accessibilityAction(named: L("Close Tab")) { onClose([item.id]) }163 .accessibilityIdentifier("constellation-card")164 }165 }166 }167 }168169 @ViewBuilder private func cardMenu(_ item: ConstellationItem) -> some View {170 Button(L("Open")) { onOpen(item.id) }171 Button(picked.contains(item.id) ? L("Deselect") : L("Select")) { toggle(item.id) }172 if picked.count > 1 { Button(L("Group %d Tabs", picked.count)) { onGroup(picked); picked = [] } }173 if let url = item.url { Button(L("Copy Link")) { PlatformActions.copy(url) } }174 Divider()175 Button(picked.count > 1 && picked.contains(item.id) ? L("Close %d Tabs", picked.count) : L("Close Tab"), role: .destructive) {176 onClose(picked.count > 1 && picked.contains(item.id) ? picked : [item.id]); picked = []177 }178 }179180 private func header(map: ConstellationMap) -> some View {181 HStack(spacing: 10) {182 VStack(alignment: .leading, spacing: 1) {183 Text(L("Tab Constellation")).font(.system(size: compact ? 15 : 17, weight: .semibold, design: .rounded)).foregroundStyle(.white)184 Text(L("%d tabs · %d constellations", items.count, map.clusters.filter { $0.kind != .loose }.count)).font(.caption).foregroundStyle(.white.opacity(0.6))185 }186 Spacer()187 if map.isLightweight { AuraChip(text: L("Light view"), symbol: "bolt", tint: Aura.Palette.cyan) }188 Button(L("Done"), action: onDismiss).buttonStyle(.borderedProminent).keyboardShortcut(.cancelAction)189 .accessibilityIdentifier("constellation-done")190 }191 .environment(\.colorScheme, .dark)192 }193194 private func controls(map: ConstellationMap, size: CGSize) -> some View {195 VStack(spacing: 8) {196 if !picked.isEmpty {197 HStack(spacing: 10) {198 Text(L("%d selected", picked.count)).font(.callout.weight(.medium))199 Button(L("Group")) { onGroup(picked); picked = [] }.disabled(picked.count < 2)200 Button(L("Close"), role: .destructive) { onClose(picked); picked = [] }201 Button(L("Clear")) { picked = [] }202 }203 .buttonStyle(.bordered).padding(.horizontal, 12).padding(.vertical, 8)204 .auraSurface(.floating, radius: 18)205 .transition(AuraTransition.rise(.bottom, policy))206 }207 HStack(spacing: 8) {208 AuraSearchField(text: $query, placeholder: L("Search tabs"), height: 34, fontSize: 13.5, focusRequest: searchFocus, identifier: "constellation-search",209 onSubmit: { if let first = items.first(where: { ConstellationMap.filter(items, query: query).contains($0.id) }) { onOpen(first.id) } },210 onEscape: { query = ""; keyboard = true; return true })211 .frame(maxWidth: compact ? .infinity : 280)212 if !compact {213 AuraIconButton(symbol: "minus.magnifyingglass", label: L("Zoom Out")) { AuraMotion.perform(.standard) { viewport.step(0.8, range: Self.zoomRange) } }214 AuraIconButton(symbol: "plus.magnifyingglass", label: L("Zoom In")) { AuraMotion.perform(.standard) { viewport.step(1.25, range: Self.zoomRange) } }215 }216 AuraIconButton(symbol: "arrow.up.left.and.arrow.down.right", label: L("Fit All Tabs")) {217 AuraMotion.perform(.expressive) { viewport = AuraViewport(scale: map.fittingScale(in: size, padding: compact ? 30 : 90)) }218 }219 AuraIconButton(symbol: "plus", label: L("New Tab"), action: onNewTab)220 }221 .padding(6)222 .auraSurface(.floating, radius: 22)223 }224 .environment(\.colorScheme, .dark)225 .animation(AuraMotion.animation(.spring, policy: policy), value: picked.isEmpty)226 }227228 // MARK: Interaction229230 private var panGesture: some Gesture {231 DragGesture(minimumDistance: 4)232 .onChanged { viewport.pan(by: $0.translation) }233 .onEnded { _ in viewport.endPan() }234 }235236 private var zoomGesture: some Gesture {237 MagnifyGesture()238 .onChanged { viewport.zoom(by: $0.magnification, range: Self.zoomRange) }239 .onEnded { _ in viewport.endZoom() }240 }241242 /// The card follows the finger; let go over another constellation and it joins it, otherwise it springs back.243 private func cardDrag(_ id: UUID, map: ConstellationMap, size: CGSize, origin: CGPoint) -> some Gesture {244 DragGesture(minimumDistance: 8)245 .onChanged { dragging = (id, $0.translation) }246 .onEnded { value in247 let drop = world(CGPoint(x: origin.x + value.translation.width, y: origin.y + value.translation.height), map: map, size: size)248 let target = map.cluster(at: drop)249 let home = map.cluster(containing: id)250 AuraMotion.perform(.spring) { dragging = nil }251 if let target, target.id != home?.id {252 AuraHaptics.play(.snap)253 onMove(id, target)254 }255 }256 }257258 private func tap(_ id: UUID) {259 cursor = id260 #if os(macOS)261 if NSEvent.modifierFlags.contains(.command) || NSEvent.modifierFlags.contains(.shift) { toggle(id); return }262 #endif263 if !picked.isEmpty { toggle(id) } else { onOpen(id) }264 }265266 private func toggle(_ id: UUID) {267 AuraHaptics.play(.selection)268 if picked.contains(id) { picked.remove(id) } else { picked.insert(id) }269 }270271 private func closePickedOrCursor() {272 if !picked.isEmpty { onClose(picked); picked = [] } else if let cursor {273 let next = ConstellationMap(items: items, cardSize: cardSize).neighbour(of: cursor, dx: 1, dy: 0)274 onClose([cursor])275 self.cursor = next276 }277 }278279 private func moveCursor(_ map: ConstellationMap, _ dx: Int, _ dy: Int) -> KeyPress.Result {280 guard let current = cursor ?? selectedID ?? items.first?.id else { return .ignored }281 if let next = map.neighbour(of: current, dx: dx, dy: dy) { cursor = next } else if cursor == nil { cursor = current }282 return .handled283 }284}285286private struct ConstellationCard: View {287 let item: ConstellationItem288 let size: CGSize289 let lightweight: Bool290 let thumbnail: PlatformImage?291 let icon: PlatformImage?292 let isCurrent: Bool293 let isPicked: Bool294 let isCursor: Bool295 let isDimmed: Bool296 let onClose: () -> Void297 @State private var hovering = false298299 private var tint: Color { item.colorIndex.map(Aura.Palette.identity) ?? Aura.Palette.cyan }300301 var body: some View {302 Group {303 if lightweight { pill } else { card }304 }305 .overlay(alignment: .topLeading) {306 if isPicked {307 Image(systemName: "checkmark.circle.fill").font(.system(size: 18)).foregroundStyle(.white, Aura.Palette.accent).offset(x: -6, y: -6)308 }309 }310 .opacity(isDimmed ? 0.22 : 1)311 .scaleEffect(hovering ? 1.04 : 1)312 .animation(AuraMotion.animation(.quick), value: hovering)313 .animation(AuraMotion.animation(.quick), value: isDimmed)314 .onHover { hovering = $0 }315 .environment(\.colorScheme, .dark)316 }317318 private var ring: some View {319 RoundedRectangle(cornerRadius: lightweight ? 12 : 14, style: .continuous)320 .strokeBorder(isCurrent || isPicked || isCursor ? AnyShapeStyle(Aura.horizontalGradient) : AnyShapeStyle(Color.white.opacity(0.14)),321 lineWidth: isCurrent || isPicked ? 2 : (isCursor ? 2 : 1))322 }323324 private var card: some View {325 VStack(spacing: 0) {326 ZStack {327 Color(white: 0.11)328 if let thumbnail {329 Image(platformImage: thumbnail).resizable().aspectRatio(contentMode: .fill)330 .frame(width: size.width, height: size.height - 30, alignment: .top).clipped()331 } else {332 AuraSiteGlyph(image: icon, fallback: item.domain.isEmpty ? item.title : item.domain, size: 30, tint: tint)333 }334 }335 .frame(width: size.width, height: size.height - 30)336 HStack(spacing: 6) {337 AuraSiteGlyph(image: icon, fallback: item.domain.isEmpty ? item.title : item.domain, size: 14, tint: tint)338 Text(item.title).font(.system(size: 11, weight: .medium)).lineLimit(1).foregroundStyle(.white.opacity(0.92))339 Spacer(minLength: 0)340 if hovering {341 Button(action: onClose) { Image(systemName: "xmark").font(.system(size: 8, weight: .bold)).frame(width: 16, height: 16).background(Circle().fill(Color.white.opacity(0.16))) }342 .buttonStyle(AuraPressStyle(scale: 0.8)).foregroundStyle(.white)343 }344 }345 .padding(.horizontal, 8).frame(width: size.width, height: 30)346 .background(Color(white: 0.14))347 }348 .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))349 .overlay(ring)350 .shadow(color: (isCurrent ? Aura.Palette.violet : .black).opacity(isCurrent ? 0.5 : 0.45), radius: isCurrent ? 16 : 9, y: 5)351 }352353 private var pill: some View {354 HStack(spacing: 6) {355 AuraSiteGlyph(image: icon, fallback: item.domain.isEmpty ? item.title : item.domain, size: 16, tint: tint)356 Text(item.title).font(.system(size: 11.5, weight: .medium)).lineLimit(1).foregroundStyle(.white.opacity(0.92))357 }358 .padding(.horizontal, 9).frame(width: size.width, height: 30, alignment: .leading)359 .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(Color(white: 0.15)))360 .overlay(ring)361 .shadow(color: .black.opacity(0.35), radius: 5, y: 2)362 }363}364365extension Comparable {366 func clamped(_ low: Self, _ high: Self) -> Self { min(max(self, low), high) }367}368