Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Cra 0.1.18: AppKit sidebar, search suggestions, extension icon styles, fixes #6–#11

Victor5f4c901f277c
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 345d82b..188ff5d 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -484,6 +484,39 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
for item in comps?.queryItems ?? [] { if let v = item.value { dict[item.name] = v } }
if let js = dict["devtoolsjs"] { main.debugRunInDevTools(js) }
if dict["embedDump"] != nil { NSLog("%@", main.embeddedPagesDump()); return }
+ // Tests that leave the pointer alone: scroll=dy,steps,x,y scrolls the scroll view at a
+ // point of the main window (from its top left); swipe=dx,steps plays a space swipe.
+ if let g = dict["scroll"]?.split(separator: ",").compactMap({ Double($0) }), g.count == 4, let w = main.window {
+ TestGesture.scroll(by: g[0], steps: Int(g[1]), at: NSPoint(x: g[2], y: w.frame.height - g[3]), in: w)
+ return
+ }
+ if let st = dict["status"] { main.browserManager(statusMessage: st); return }
+ // Opens what normally needs a pointer or a held key, for screenshots.
+ if let v = dict["downloads"] { main.sidebarUI.downloadsListOpen = v == "1"; return }
+ if let v = dict["banner"] { SoftwareUpdater.shared.debugUpdated(v == "none" ? nil : v); return }
+ if dict["switcher"] != nil { main.debugTabSwitcher(); return }
+ if dict["jumpPill"] != nil { SpaceListView.jumpToSelected(for: main.sidebarUI, space: store.focusedSpaceID); return }
+ if dict["littlePopup"] != nil { littleWindows.first?.togglePopup(); return }
+ if let c = dict["combine"], let content = main.window?.contentView {
+ let tabs = store.children(of: store.focusedSpace.todayContainerID).filter { $0.tab != nil }
+ guard tabs.count > 1 else { return }
+ let kind: CombineDropPreview.Kind = c == "folder" ? .folder : .split(leading: c == "leading")
+ let pal = store.focusedSpace.theme.palette
+ let v = CombineDropPreview(kind: kind, target: tabs[0], dragged: tabs[1], depth: 0, palette: pal, favicons: favicons)
+ v.frame = NSRect(x: 10, y: content.bounds.height - 420, width: 300, height: CraMetrics.rowHeight)
+ content.addSubview(v)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 4) { v.removeFromSuperview() }
+ return
+ }
+ if dict["siteControls"] != nil { main.debugSiteControls(); return }
+ if let t = dict["tooltip"], let content = main.window?.contentView {
+ ArcTooltipController.shared.debugShow(t, in: content, at: NSRect(x: 380, y: content.bounds.height - 120, width: 28, height: 28))
+ return
+ }
+ if let g = dict["swipe"]?.split(separator: ",").compactMap({ Double($0) }), g.count == 2 {
+ main.debugSpaceSwipe(dx: g[0], steps: Int(g[1]))
+ return
+ }
if let id = dict["extensionAction"] { main.runExtensionAction(id); return }
if let f = dict["floatingSidebar"] { if f == "1" { main.floatingSidebar?.show() } else { main.floatingSidebar?.hide(animated: true) }; return }
if let method = dict["bcdp"] {
diff --git a/Sources/Cra/Model/LiveFolderModel.swift b/Sources/Cra/Model/LiveFolderModel.swift
index 424031c..bd78bfe 100644
--- a/Sources/Cra/Model/LiveFolderModel.swift
+++ b/Sources/Cra/Model/LiveFolderModel.swift
@@ -43,6 +43,15 @@ struct LiveFolderData: Codable, Equatable {
var lastError: LiveFolderError?
/// Organizations that want a SAML sign-in before their pull requests show up (Arc: needsSSO).
var ssoOrganizations: [String] = []
+ /// The enterprise whose single sign-on GitHub sent a tab to (Enterprise Managed Users sign in
+ /// there, not at github.com/login): the folder's sign-in button goes there too.
+ var enterprise: String?
+
+ /// Where to sign in again.
+ var signInURL: String {
+ if let enterprise { return "https://github.com/enterprises/\(enterprise)/sso" }
+ return "https://github.com/login?return_to=%2Fpulls"
+ }
init() {}
init(from decoder: Decoder) throws {
@@ -53,6 +62,7 @@ struct LiveFolderData: Codable, Equatable {
lastFetch = try c.decodeIfPresent(Date.self, forKey: .lastFetch)
lastError = try? c.decodeIfPresent(LiveFolderError.self, forKey: .lastError)
ssoOrganizations = try c.decodeIfPresent([String].self, forKey: .ssoOrganizations) ?? []
+ enterprise = try c.decodeIfPresent(String.self, forKey: .enterprise)
}
}
diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swift
index 801e759..9e731c6 100644
--- a/Sources/Cra/Model/SidebarModel.swift
+++ b/Sources/Cra/Model/SidebarModel.swift
@@ -393,6 +393,16 @@ enum SearchEngine: String, Codable, CaseIterable, Identifiable {
case .kagi: return "https://kagi.com/search?q=\(q)"
}
}
+ /// Each engine's OpenSearch suggest endpoint, for the command bar's search suggestions.
+ func suggestURL(_ query: String) -> URL? {
+ guard let q = query.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else { return nil }
+ switch self {
+ case .google: return URL(string: "https://www.google.com/complete/search?client=chrome&ie=utf-8&oe=utf-8&q=\(q)")
+ case .duckduckgo: return URL(string: "https://duckduckgo.com/ac/?type=list&q=\(q)")
+ case .bing: return URL(string: "https://api.bing.com/osjson.aspx?query=\(q)")
+ case .kagi: return URL(string: "https://kagi.com/api/autosuggest?q=\(q)")
+ }
+ }
}
struct AppSettings: Codable, Equatable {
@@ -441,6 +451,9 @@ struct AppSettings: Codable, Equatable {
var tabSleep: TabSleepThreshold = .oneHour
/// Privacy ▸ "Always use secure connections": Chrome's HTTPS-Only Mode.
var httpsOnly: Bool = false
+ /// Arc's searchSuggestEnabled: the command bar asks the search engine for suggestions
+ /// as you type and fills its rows with them.
+ var searchSuggestions: Bool = true
init() {}
@@ -542,6 +555,7 @@ extension AppSettings {
tabSleepEnabled = try c.decodeIfPresent(Bool.self, forKey: .tabSleepEnabled) ?? false
tabSleep = (try? c.decodeIfPresent(TabSleepThreshold.self, forKey: .tabSleep)) ?? .oneHour
httpsOnly = try c.decodeIfPresent(Bool.self, forKey: .httpsOnly) ?? false
+ searchSuggestions = try c.decodeIfPresent(Bool.self, forKey: .searchSuggestions) ?? true
}
}
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swift
index 39a876d..076ac05 100644
--- a/Sources/Cra/Services/ExtensionStore.swift
+++ b/Sources/Cra/Services/ExtensionStore.swift
@@ -143,6 +143,151 @@ final class ExtensionStore {
NotificationCenter.default.post(name: .craPinnedExtensionsChanged, object: self)
}
+ // MARK: Toolbar icons (GitHub #9: a pinned extension's button in Cra's monochrome ink)
+
+ /// How a pinned extension's button draws, keyed by Chromium extension ID, so it survives
+ /// restarts and extension updates. The extension's own icon is untouched elsewhere.
+ struct IconStyle: Codable, Equatable {
+ /// Drawn as a template in the toolbar's ink instead of the extension's colours.
+ var monochrome = false
+ /// An SF Symbol in place of the extension's icon (always monochrome).
+ var symbol: String?
+ /// An image the user picked, copied into "Extension Icons".
+ var imageFile: String?
+ }
+
+ /// Symbols offered in place of an extension's icon.
+ static let iconSymbols = ["shield.lefthalf.filled", "lock.shield", "key", "lock", "person.badge.key",
+ "eye.slash", "hand.raised", "checkmark.shield", "bolt", "star", "bookmark",
+ "doc.text", "paintbrush", "globe", "puzzlepiece.extension"]
+
+ private static var iconStylesFile: URL { AppPaths.file("extension-icons.json") }
+ private static var customIconsDir: URL { AppPaths.supportDir.appendingPathComponent("Extension Icons", isDirectory: true) }
+
+ private(set) var iconStyles: [String: IconStyle] = {
+ guard let data = try? Data(contentsOf: ExtensionStore.iconStylesFile) else { return [:] }
+ return (try? JSONDecoder().decode([String: IconStyle].self, from: data)) ?? [:]
+ }()
+ /// One image per extension, so the toolbar sees the same object until the style changes.
+ @ObservationIgnored private var toolbarIcons: [String: NSImage] = [:]
+
+ func iconStyle(_ id: String) -> IconStyle { iconStyles[id] ?? IconStyle() }
+
+ func setIconStyle(_ id: String, _ style: IconStyle) {
+ let old = iconStyle(id)
+ guard style != old else { return }
+ if let file = old.imageFile, file != style.imageFile {
+ try? FileManager.default.removeItem(at: Self.customIconsDir.appendingPathComponent(file))
+ }
+ iconStyles[id] = style == IconStyle() ? nil : style
+ toolbarIcons[id] = nil
+ try? JSONEncoder().encode(iconStyles).write(to: Self.iconStylesFile, options: .atomic)
+ }
+
+ /// Copies `url` in as the extension's toolbar icon.
+ func setCustomIcon(_ id: String, from url: URL) throws {
+ guard NSImage(contentsOf: url) != nil else {
+ throw NSError(domain: "Cra", code: 1, userInfo: [NSLocalizedDescriptionKey: "That file is not an image."])
+ }
+ let fm = FileManager.default
+ try fm.createDirectory(at: Self.customIconsDir, withIntermediateDirectories: true)
+ // A new name each time: the old file is removed once the style no longer points at it.
+ let name = "\(id)-\(UUID().uuidString.prefix(8)).\(url.pathExtension.isEmpty ? "png" : url.pathExtension)"
+ try fm.copyItem(at: url, to: Self.customIconsDir.appendingPathComponent(name))
+ var style = iconStyle(id)
+ style.symbol = nil
+ style.imageFile = name
+ setIconStyle(id, style)
+ }
+
+ /// The pinned button's image: the extension's icon, the user's replacement, or either as a
+ /// template image (the button tints templates with the toolbar's ink).
+ func toolbarIcon(for e: Entry) -> NSImage? {
+ let style = iconStyle(e.extensionID)
+ if style == IconStyle() { return e.icon }
+ if let cached = toolbarIcons[e.extensionID] { return cached }
+ var image: NSImage?
+ if let symbol = style.symbol {
+ image = NSImage(systemSymbolName: symbol, accessibilityDescription: e.name)?
+ .withSymbolConfiguration(.init(pointSize: 15, weight: .regular))
+ image?.isTemplate = true
+ } else {
+ if let file = style.imageFile {
+ image = NSImage(contentsOf: Self.customIconsDir.appendingPathComponent(file)) ?? e.icon
+ } else if style.monochrome {
+ // From the largest icon: in the 16 px one a plate's edge and the mark blur together.
+ let manifest = (try? Data(contentsOf: e.url.appendingPathComponent("manifest.json")))
+ .flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }
+ image = manifest.flatMap { ExtensionImporter.icon(manifest: $0, folder: e.url, minPixels: 128) } ?? e.icon
+ } else {
+ image = e.icon
+ }
+ if style.monochrome { image = image.flatMap(Self.monochrome) }
+ }
+ toolbarIcons[e.extensionID] = image
+ return image
+ }
+
+ /// An icon as a one-ink template, the way Arc's own toolbar glyphs read. An icon drawn on a
+ /// plate (one colour covering most of it: Bitwarden's blue square, Vercel's black disc) keeps
+ /// what stands out from the plate, so Bitwarden becomes its shield. Without a plate, colour
+ /// reads as ink and white as none, so a white badge keeps only its mark. Ink is scaled so the
+ /// strongest is solid; a one-colour glyph (nothing stands out) keeps its silhouette.
+ static func monochrome(_ source: NSImage) -> NSImage? {
+ let n = 64
+ guard let ctx = CGContext(data: nil, width: n, height: n, bitsPerComponent: 8, bytesPerRow: n * 4,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(cgContext: ctx, flipped: false)
+ source.draw(in: NSRect(x: 0, y: 0, width: n, height: n), from: .zero, operation: .copy, fraction: 1)
+ NSGraphicsContext.restoreGraphicsState()
+ guard let data = ctx.data?.assumingMemoryBound(to: UInt8.self) else { return nil }
+ let count = n * n
+ // Premultiplied: divide the alpha back out before judging the colour.
+ func rgb(_ i: Int) -> (Double, Double, Double) {
+ let a = Double(data[i * 4 + 3]) / 255
+ return (Double(data[i * 4]) / 255 / a, Double(data[i * 4 + 1]) / 255 / a, Double(data[i * 4 + 2]) / 255 / a)
+ }
+ // The plate: the most common opaque colour (16 levels a channel), if it covers 40 % of the icon.
+ var buckets: [Int: (n: Int, r: Double, g: Double, b: Double)] = [:]
+ var visible = 0
+ for i in 0..<count where data[i * 4 + 3] > 12 {
+ visible += 1
+ guard data[i * 4 + 3] > 240 else { continue }
+ let (r, g, b) = rgb(i)
+ let key = Int(r * 15.99) << 8 | Int(g * 15.99) << 4 | Int(b * 15.99)
+ let o = buckets[key] ?? (0, 0, 0, 0)
+ buckets[key] = (o.n + 1, o.r + r, o.g + g, o.b + b)
+ }
+ let top = buckets.values.max { $0.n < $1.n }
+ let plate = top.flatMap { t in Double(t.n) >= Double(visible) * 0.4 ? (t.r / Double(t.n), t.g / Double(t.n), t.b / Double(t.n)) : nil }
+ var ink = [Double](repeating: 0, count: count)
+ var inkMax = 0.0
+ for i in 0..<count {
+ let a = Double(data[i * 4 + 3]) / 255
+ guard a > 0 else { continue }
+ let (r, g, b) = rgb(i)
+ if let p = plate {
+ ink[i] = a * min(1, ((r - p.0) * (r - p.0) + (g - p.1) * (g - p.1) + (b - p.2) * (b - p.2)).squareRoot() / 0.5)
+ } else {
+ ink[i] = a * max(0, 1 - (0.2126 * r + 0.7152 * g + 0.0722 * b))
+ }
+ inkMax = max(inkMax, ink[i])
+ }
+ let silhouette = inkMax < 0.08
+ for i in 0..<count {
+ let a = Double(data[i * 4 + 3]) / 255
+ let v = silhouette ? a : min(max((ink[i] / inkMax - 0.1) / 0.5, 0), 1)
+ let byte = UInt8((v * 255).rounded())
+ data[i * 4] = 0; data[i * 4 + 1] = 0; data[i * 4 + 2] = 0; data[i * 4 + 3] = byte
+ }
+ guard let cg = ctx.makeImage() else { return nil }
+ let image = NSImage(cgImage: cg, size: NSSize(width: 18, height: 18))
+ image.isTemplate = true
+ return image
+ }
+
/// Copies an unpacked extension folder (one that holds manifest.json) in.
func add(folder: URL) throws {
let fm = FileManager.default
diff --git a/Sources/Cra/Services/LiveFolderManager.swift b/Sources/Cra/Services/LiveFolderManager.swift
index 3bac200..1bb3907 100644
--- a/Sources/Cra/Services/LiveFolderManager.swift
+++ b/Sources/Cra/Services/LiveFolderManager.swift
@@ -30,6 +30,11 @@ final class LiveFolderManager {
static let triggerDelays: [TimeInterval] = [5, 45]
/// Arc's requestedTooSoon: clicks on refresh closer together than this do nothing.
static let minimumInterval: TimeInterval = 10
+ /// A folder that failed or waits for a sign-in tries again this often (a Mac waking up has no
+ /// network for a moment; an SSO session renews as soon as a GitHub page is opened).
+ nonisolated static let retryInterval: TimeInterval = 30
+ /// A GitHub page loaded while a folder waits for a sign-in: refresh once the page has settled.
+ @ObservationIgnored private var signInCheck: DispatchWorkItem?
/// CRA_LIVE_FOLDER_DEBUG=1 writes every GitHub response to <data dir>/live-folder-debug/.
private static let debug = ProcessInfo.processInfo.environment["CRA_LIVE_FOLDER_DEBUG"] == "1"
@@ -55,10 +60,16 @@ final class LiveFolderManager {
guard NSApp.isActive else { return }
for f in store?.liveFolders ?? [] {
let last = f.liveFolder?.lastFetch ?? .distantPast
- if Date().timeIntervalSince(last) >= age { refresh(f.id) }
+ let failing = f.liveFolder.map { $0.lastError != nil || Self.needsSignIn($0) } ?? false
+ if Date().timeIntervalSince(last) >= (failing ? min(age, Self.retryInterval) : age) { refresh(f.id) }
}
}
+ /// GitHub asked for a sign-in: to github.com, or SSO for an organization whose pull requests it held back.
+ nonisolated static func needsSignIn(_ live: LiveFolderData) -> Bool {
+ live.lastError == .notSignedIn || (live.lastError == nil && !live.ssoOrganizations.isEmpty)
+ }
+
/// `force` skips the gap between refreshes: the folder's filters just changed.
func refresh(_ id: UUID, force: Bool = false) {
guard let store, let live = store.item(id)?.liveFolder, !refreshing.contains(id) else { return }
@@ -98,7 +109,17 @@ final class LiveFolderManager {
let old = lastURL[tab]
lastURL[tab] = url
if lastURL.count > 500 { lastURL = [tab: url] }
- guard old != url, let pr = GitHubLiveClient.pullPath(url), !(store?.liveFolders.isEmpty ?? true) else { return }
+ guard old != url, let store, !store.liveFolders.isEmpty else { return }
+ let folders = store.liveFolders
+ guard let page = URL(string: url), page.host == "github.com" else { return }
+ // GitHub sends a signed-out Enterprise Managed User to /enterprises/<slug>/sso (JYSK, 29 Oct 2026).
+ let parts = page.path.split(separator: "/")
+ if parts.count == 3, parts[0] == "enterprises", parts[2] == "sso" {
+ let slug = String(parts[1])
+ for f in folders where f.liveFolder?.enterprise != slug { store.updateLiveFolder(f.id) { $0.enterprise = slug } }
+ }
+ if folders.contains(where: { $0.liveFolder.map(Self.needsSignIn) ?? false }) { checkSignIn() }
+ guard let pr = GitHubLiveClient.pullPath(url) else { return }
let oldPath = old.flatMap { URL(string: $0)?.path } ?? ""
let created = oldPath.hasPrefix("/\(pr.owner)/\(pr.repo)/compare")
let reviewed = url.contains("#pullrequestreview-") && !(old ?? "").contains("#pullrequestreview-")
@@ -110,6 +131,21 @@ final class LiveFolderManager {
}
}
+ /// Signing in ends on a GitHub page, and so does an SSO session that renews by itself (an
+ /// identity provider that signs in without asking, like JYSK's ADFS): the folder tries again a
+ /// moment after GitHub pages stop loading, instead of waiting for the next retry.
+ private func checkSignIn() {
+ signInCheck?.cancel()
+ let work = DispatchWorkItem { [weak self] in
+ for f in self?.store?.liveFolders ?? [] where f.liveFolder.map(Self.needsSignIn) ?? false {
+ let last = f.liveFolder?.lastFetch ?? .distantPast
+ if Date().timeIntervalSince(last) >= Self.minimumInterval { self?.refresh(f.id, force: true) }
+ }
+ }
+ signInCheck = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: work)
+ }
+
/// One search: the pulls page first (what Arc and Dia read), then GitHub's search page
/// when that comes back with nothing it can read.
private func fetch(_ query: String, profile: String?, label: String) async -> Result<GitHubLiveClient.Page, GitHubLiveClient.Failure> {
diff --git a/Sources/Cra/Services/SearchSuggestions.swift b/Sources/Cra/Services/SearchSuggestions.swift
new file mode 100644
index 0000000..d2aaea0
--- /dev/null
+++ b/Sources/Cra/Services/SearchSuggestions.swift
@@ -0,0 +1,78 @@
+import Foundation
+
+/// The search engine's own suggestions for what is typed. Arc takes them from Chromium's
+/// omnibox ("Chromium: Search Suggestion" / "Navigate Suggest"); CEF has no omnibox, so Cra
+/// asks the engine's suggest endpoint itself. They fill the command bar up to its five rows.
+@MainActor
+final class SearchSuggestions {
+ struct Item: Equatable {
+ let text: String
+ /// Set for a site suggestion (Google's NAVIGATION type), nil for a search.
+ let url: String?
+ }
+
+ private var cache: [String: [Item]] = [:]
+ /// The newest answer, narrowed to the query while the query's own answer loads, so rows
+ /// don't empty and refill on every keystroke.
+ private var last: (query: String, items: [Item])?
+ private var task: Task<Void, Never>?
+
+ /// No cookies: the request says nothing about who is typing beyond the text itself.
+ private let session: URLSession = {
+ let c = URLSessionConfiguration.ephemeral
+ c.timeoutIntervalForRequest = 3
+ c.httpAdditionalHeaders = ["Accept-Language": SearchSuggestions.acceptLanguage]
+ return URLSession(configuration: c)
+ }()
+
+ private static var acceptLanguage: String {
+ let langs = Locale.preferredLanguages.prefix(4)
+ return langs.enumerated().map { i, l in i == 0 ? l : "\(l);q=\(String(format: "%.1f", 1 - Double(i) * 0.2))" }.joined(separator: ",")
+ }
+
+ func items(for query: String, engine: SearchEngine) -> [Item] {
+ let q = query.lowercased()
+ if let hit = cache["\(engine.rawValue)|\(q)"] { return hit }
+ guard let last, q.hasPrefix(last.query) else { return [] }
+ return last.items.filter { $0.url == nil && $0.text.lowercased().hasPrefix(q) && $0.text.lowercased() != q }
+ }
+
+ func fetch(_ query: String, engine: SearchEngine, done: @escaping @MainActor () -> Void) {
+ task?.cancel()
+ let q = query.lowercased()
+ let key = "\(engine.rawValue)|\(q)"
+ guard cache[key] == nil, let url = engine.suggestURL(query) else { return }
+ task = Task { [session, weak self] in
+ guard let (data, response) = try? await session.data(from: url),
+ (response as? HTTPURLResponse)?.statusCode == 200, !Task.isCancelled, let self else { return }
+ let items = Self.parse(data)
+ self.cache[key] = items
+ self.last = (q, items)
+ done()
+ }
+ }
+
+ /// The command bar opened or closed.
+ func reset() {
+ task?.cancel()
+ task = nil
+ cache = [:]
+ last = nil
+ }
+
+ /// OpenSearch suggestions: `["query", ["one", "two", …], …]`. Google's chrome client adds
+ /// a fifth element whose "google:suggesttype" marks each entry QUERY, NAVIGATION, …
+ nonisolated static func parse(_ data: Data) -> [Item] {
+ let json = (try? JSONSerialization.jsonObject(with: data))
+ ?? String(data: data, encoding: .isoLatin1).flatMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) }
+ guard let a = json as? [Any], a.count > 1, let texts = a[1] as? [String] else { return [] }
+ let types = (a.count > 4 ? a[4] as? [String: Any] : nil)?["google:suggesttype"] as? [String] ?? []
+ return texts.enumerated().compactMap { i, text in
+ switch i < types.count ? types[i] : "QUERY" {
+ case "NAVIGATION": return Item(text: SuggestionEngine.humanURL(text), url: text)
+ case "CALCULATOR": return nil
+ default: return Item(text: text, url: nil)
+ }
+ }
+ }
+}
diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swift
index aeab83c..b7d8d8d 100644
--- a/Sources/Cra/Services/SidebarStore.swift
+++ b/Sources/Cra/Services/SidebarStore.swift
@@ -1085,8 +1085,11 @@ final class SidebarStore {
}
}
// Gone from the results (merged, reviewed, closed): marked now, removed once the grace is over.
+ // An organization whose SSO session lapsed only hid its pull requests: those stay as they are.
+ let ssoHidden = Set(ssoOrganizations.map { $0.lowercased() })
for id in existing.values {
guard var it = items[id], var t = it.tab, t.liveGoneAt == nil else { continue }
+ if let url = t.liveItemURL, let p = GitHubLiveClient.pullPath(url), ssoHidden.contains(p.owner.lowercased()) { continue }
t.liveGoneAt = Date()
it.data = .tab(t)
items[id] = it
diff --git a/Sources/Cra/Services/SoftwareUpdater.swift b/Sources/Cra/Services/SoftwareUpdater.swift
index 3860302..047412e 100644
--- a/Sources/Cra/Services/SoftwareUpdater.swift
+++ b/Sources/Cra/Services/SoftwareUpdater.swift
@@ -46,6 +46,7 @@ final class SoftwareUpdater: NSObject {
private(set) var foundRelease: Release?
/// The first launch after an update: "Cra Updated!" with See What's New.
private(set) var updatedTo: String?
+ func debugUpdated(_ v: String?) { updatedTo = v }
/// The close button on a banner hides it until the next launch (Arc counts these in
/// autoUpdateBannerDismissalCount).
var bannerDismissed = false
diff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swift
index 81173f0..27e9736 100644
--- a/Sources/Cra/Services/SuggestionEngine.swift
+++ b/Sources/Cra/Services/SuggestionEngine.swift
@@ -31,6 +31,9 @@ struct Suggestion: Identifiable, Equatable {
let trailing: String?
var score: Double
var spaceID: UUID? = nil
+ /// Matched only as scattered letters ("pota" in "grænselandsPOrTAl"): listed after the
+ /// search engine's suggestions, which Arc shows instead of such matches.
+ var loose = false
var tabID: UUID? {
if case .switchToTab(let id) = kind { return id }
return nil
@@ -51,6 +54,10 @@ struct SuggestionResult {
final class SuggestionEngine {
unowned let store: SidebarStore
unowned let bindings: KeyBindingRegistry
+ private let remote = SearchSuggestions()
+ /// Arc's command bar always lists five rows; search suggestions make up what the
+ /// tabs, history and commands don't fill, so the bar keeps its height while you type.
+ static let maxRows = 5
init(store: SidebarStore, bindings: KeyBindingRegistry) {
self.store = store
@@ -64,7 +71,7 @@ final class SuggestionEngine {
let q = query.lowercased()
var result = SuggestionResult(query: query)
if q.isEmpty {
- result.items = recentSuggestions(excluding: currentTabID)
+ result.items = Array(recentSuggestions(excluding: currentTabID).prefix(Self.maxRows))
return result
}
@@ -97,7 +104,13 @@ final class SuggestionEngine {
} else {
items.insert(typed, at: 0)
}
- result.items = Array(items.prefix(8))
+ if store.settings.searchSuggestions {
+ let at = items.firstIndex(where: \.loose) ?? items.count
+ if at < Self.maxRows {
+ items.insert(contentsOf: searchSuggestions(query, after: items).prefix(Self.maxRows - at), at: at)
+ }
+ }
+ result.items = Array(items.prefix(Self.maxRows))
result.inlineCompletion = completion?.text
return result
}
@@ -145,7 +158,35 @@ final class SuggestionEngine {
}
/// The command bar opened or closed: what it searches may have changed since.
- func resetIndex() { index = nil }
+ func resetIndex() {
+ index = nil
+ remote.reset()
+ }
+
+ /// Asks the search engine about `rawQuery`; `done` runs when its answer is in, to list again.
+ func fetchSearchSuggestions(for rawQuery: String, done: @escaping @MainActor () -> Void) {
+ let query = rawQuery.trimmingCharacters(in: .whitespaces)
+ guard store.settings.searchSuggestions, !query.isEmpty, !query.contains("://") else { return }
+ remote.fetch(query, engine: store.settings.searchEngine, done: done)
+ }
+
+ /// The engine's suggestions not already listed, as search rows (or site rows).
+ private func searchSuggestions(_ query: String, after items: [Suggestion]) -> [Suggestion] {
+ let engine = store.settings.searchEngine
+ let titles = Set(items.map { $0.title.lowercased() })
+ let urls = Set(items.compactMap(\.url))
+ return remote.items(for: query, engine: engine).compactMap { r in
+ let t = r.text.lowercased()
+ guard t != query.lowercased(), !titles.contains(t) else { return nil }
+ guard let url = r.url else {
+ return Suggestion(id: "sugg:\(t)", kind: .search, title: r.text, subtitle: "", url: engine.searchURL(r.text),
+ faviconKey: nil, symbol: "magnifyingglass", trailing: nil, score: 0)
+ }
+ guard !urls.contains(url) else { return nil }
+ return Suggestion(id: "sugg:\(url)", kind: .history, title: r.text, subtitle: "", url: url,
+ faviconKey: FaviconCache.key(for: url), symbol: "globe", trailing: nil, score: 0)
+ }
+ }
// MARK: Typed text
@@ -189,6 +230,7 @@ final class SuggestionEngine {
for (tab, key) in searchIndex.tabs where tab.id != current {
guard let t = tab.tab else { continue }
var score = Self.score(q, key)
+ let loose = score < Self.looseBelow && !(tab.title?.lowercased().hasPrefix(q) ?? false)
if let custom = tab.title?.lowercased(), custom.hasPrefix(q) { score += 40 }
if score < 30 { continue }
score += recencyBoost(t.timeLastActiveAt)
@@ -199,22 +241,27 @@ final class SuggestionEngine {
let pinned = store.isPinned(tab.id)
out.append(Suggestion(id: "tab:\(tab.id)", kind: .switchToTab(tab.id), title: tab.displayTitle,
subtitle: [spaceName, pinned ? "Pinned" : "", Self.humanURL(t.url)].filter { !$0.isEmpty }.joined(separator: " · "),
- url: t.url, faviconKey: t.faviconKey, symbol: nil, trailing: "Switch to Tab", score: score, spaceID: sid))
+ url: t.url, faviconKey: t.faviconKey, symbol: nil, trailing: "Switch to Tab", score: score, spaceID: sid, loose: loose))
}
return out
}
+ /// Below this a text score means only scattered letters matched (`fuzzy`).
+ private static let looseBelow = 50.0
+
private func archiveSuggestions(_ q: String) -> [Suggestion] {
var out: [Suggestion] = []
for (entry, key) in searchIndex.archive {
guard let t = entry.item.tab else { continue }
- var score = Self.score(q, key) * 0.85
+ let text = Self.score(q, key)
+ var score = text * 0.85
if score < 30 { continue }
score += recencyBoost(entry.archivedAt) * 0.5
let spaceName = entry.sourceSpaceID.flatMap { store.space($0)?.title } ?? ""
out.append(Suggestion(id: "arch:\(entry.id)", kind: .archived(entry.id), title: entry.item.displayTitle,
subtitle: ["Archived \(Self.relative(entry.archivedAt))", spaceName, Self.humanURL(t.url)].filter { !$0.isEmpty }.joined(separator: " · "),
- url: t.url, faviconKey: t.faviconKey, symbol: nil, trailing: "Restore", score: score))
+ url: t.url, faviconKey: t.faviconKey, symbol: nil, trailing: "Restore", score: score,
+ loose: text < Self.looseBelow))
}
return out
}
@@ -222,12 +269,13 @@ final class SuggestionEngine {
private func historySuggestions(_ q: String, openURLs: Set<String>) -> [Suggestion] {
var out: [Suggestion] = []
for (h, key) in searchIndex.history where !openURLs.contains(h.url) {
- var score = Self.score(q, key) * 0.8
+ let text = Self.score(q, key)
+ var score = text * 0.8
if score < 30 { continue }
score += min(Double(h.visitCount), 20) * 1.5 + recencyBoost(h.lastVisit) * 0.6
out.append(Suggestion(id: "hist:\(h.url)", kind: .history, title: h.title.isEmpty ? Self.humanURL(h.url) : h.title,
subtitle: Self.humanURL(h.url), url: h.url, faviconKey: FaviconCache.key(for: h.url),
- symbol: "clock", trailing: nil, score: score))
+ symbol: "clock", trailing: nil, score: score, loose: text < Self.looseBelow))
}
return out
}
diff --git a/Sources/Cra/Services/TestGesture.swift b/Sources/Cra/Services/TestGesture.swift
new file mode 100644
index 0000000..f29df87
--- /dev/null
+++ b/Sources/Cra/Services/TestGesture.swift
@@ -0,0 +1,21 @@
+import AppKit
+
+/// Scripted sidebar scrolls for background test instances (cra://debug?scroll=…): the scroll view
+/// under a point of the window moves a step every frame, as under a trackpad's momentum, while
+/// the pointer and the front app stay put.
+@MainActor
+enum TestGesture {
+ static func scroll(by dy: CGFloat, steps: Int, at point: NSPoint, in window: NSWindow, interval: TimeInterval = 1.0 / 120) {
+ guard let root = window.contentView?.superview,
+ let sv = root.hitTest(point)?.enclosingScrollView else { NSLog("Cra TestGesture: no scroll view"); return }
+ for i in 1...max(1, steps) {
+ DispatchQueue.main.asyncAfter(deadline: .now() + interval * Double(i)) {
+ let clip = sv.contentView
+ var origin = clip.bounds.origin
+ origin.y += dy * (sv.documentView?.isFlipped ?? true ? 1 : -1)
+ clip.scroll(to: clip.constrainBoundsRect(NSRect(origin: origin, size: clip.bounds.size)).origin)
+ sv.reflectScrolledClipView(clip)
+ }
+ }
+ }
+}
diff --git a/Sources/Cra/UI/AppKitControls.swift b/Sources/Cra/UI/AppKitControls.swift
new file mode 100644
index 0000000..c07d815
--- /dev/null
+++ b/Sources/Cra/UI/AppKitControls.swift
@@ -0,0 +1,63 @@
+import AppKit
+
+/// A borderless button that runs a closure: SwiftUI's `Button { } label: { Image(…) }` with
+/// `.buttonStyle(.plain)`, or a small push button with a title.
+final class ClosureButton: NSButton {
+ var onPress: () -> Void
+
+ /// A plain glyph: no bezel, no hover, the symbol in `tint`.
+ init(symbol: String, size: CGFloat, weight: NSFont.Weight = .regular, tint: NSColor = .labelColor, onPress: @escaping () -> Void) {
+ self.onPress = onPress
+ super.init(frame: .zero)
+ isBordered = false
+ imagePosition = .imageOnly
+ image = SidebarSymbols.image(symbol, size: size, weight: weight)
+ contentTintColor = tint
+ setButtonType(.momentaryChange)
+ target = self
+ action = #selector(fire)
+ sizeToFit()
+ }
+
+ /// A push button with a title.
+ init(title: String, controlSize: NSControl.ControlSize = .regular, onPress: @escaping () -> Void) {
+ self.onPress = onPress
+ super.init(frame: .zero)
+ self.title = title
+ bezelStyle = .push
+ self.controlSize = controlSize
+ font = .systemFont(ofSize: NSFont.systemFontSize(for: controlSize))
+ target = self
+ action = #selector(fire)
+ sizeToFit()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ @objc private func fire() { onPress() }
+}
+
+/// SwiftUI's `.background(.regularMaterial, in: RoundedRectangle(cornerRadius:))` with the
+/// hairline `.strokeBorder(Color.primary.opacity(0.1))` most of Cra's floating bits wear.
+final class MaterialCardView: NSVisualEffectView {
+ init(radius: CGFloat, material: NSVisualEffectView.Material = .popover, border: Bool = true) {
+ super.init(frame: .zero)
+ self.material = material
+ blendingMode = .withinWindow
+ state = .active
+ wantsLayer = true
+ layer?.cornerRadius = radius
+ layer?.cornerCurve = .continuous
+ layer?.masksToBounds = true
+ layer?.borderWidth = border ? 1 : 0
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func updateLayer() {
+ super.updateLayer()
+ effectiveAppearance.performAsCurrentDrawingAppearance {
+ layer?.borderColor = NSColor.labelColor.withAlphaComponent(0.1).cgColor
+ }
+ }
+}
diff --git a/Sources/Cra/UI/ArcTooltip.swift b/Sources/Cra/UI/ArcTooltip.swift
index 6f0d2fe..b98a08c 100644
--- a/Sources/Cra/UI/ArcTooltip.swift
+++ b/Sources/Cra/UI/ArcTooltip.swift
@@ -27,6 +27,10 @@ final class ArcTooltipController {
private struct WeakAnchor { weak var view: (any ArcTooltipTarget)? }
+ /// Set while a list scrolls under the pointer: no tip shows or starts waiting, and the
+ /// next one waits for the pointer to rest the full delay.
+ var paused = false { didSet { if paused { dismiss() } } }
+
private init() {
clickMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .keyDown]) { [weak self] e in
self?.dismiss()
@@ -52,7 +56,7 @@ final class ArcTooltipController {
cancelPending()
return
}
- if shownFor === target { return }
+ if shownFor === target || paused { return }
startTip(for: target)
}
@@ -66,7 +70,7 @@ final class ArcTooltipController {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: Self.idleDelay, repeats: false) { [weak self, weak view] _ in
Task { @MainActor in
- guard let self, let view, self.pendingFor === view else { return }
+ guard let self, let view, self.pendingFor === view, !self.paused else { return }
self.show(for: view)
}
}
@@ -94,17 +98,24 @@ final class ArcTooltipController {
pendingFor = nil
}
+ /// Testing: the tip for `help` over a rect of `view`, without a pointer.
+ func debugShow(_ help: String, in view: NSView, at rect: NSRect) {
+ let a = ArcTooltipAnchorView(frame: rect)
+ (a.text, a.keys) = ArcTooltipLabel.split(help)
+ view.addSubview(a)
+ show(for: a)
+ }
+
private func show(for view: any ArcTooltipTarget) {
cancelPending()
guard let window = view.hostWindow, !view.text.isEmpty else { return }
removePanel()
let p = LittleTooltipPanel()
let option = NSEvent.modifierFlags.contains(.option) ? view.optionText : nil
- let host = NSHostingView(rootView: ArcTooltipLabel(text: option ?? view.text, keys: option == nil ? view.keys : [],
- subtitle: option == nil ? view.subtitle : nil))
- let size = host.fittingSize
- host.setFrameSize(size)
- p.contentView = host
+ let label = ArcTooltipLabel(text: option ?? view.text, keys: option == nil ? view.keys : [],
+ subtitle: option == nil ? view.subtitle : nil)
+ let size = label.frame.size
+ p.contentView = label
// Buttons: off the bottom-trailing corner of a 16 pt box around the glyph.
// Rows: Arc's .cursor anchor, 13 pt right of and 14 pt below the pointer.
let r = view.screenFrame
@@ -283,61 +294,98 @@ extension View {
/// The tip itself: 28 pt navy capsule, 12 pt medium text, 18 pt key caps with a darker
/// bottom edge (Arc sidebar, 1x captures; Little Arc's larger tip is LittleTooltip).
-struct ArcTooltipLabel: View {
- let text: String
- let keys: [String]
- var subtitle: String? = nil
-
- static let capEdge = Color(red: 119 / 255, green: 122 / 255, blue: 211 / 255)
+final class ArcTooltipLabel: NSView {
+ static let capEdge = NSColor(red: 119 / 255, green: 122 / 255, blue: 211 / 255, alpha: 1)
static let maxTextWidth: CGFloat = 280
+ static let fill = NSColor(LittlePalette.tooltip)
+ static let ink = NSColor(LittlePalette.tooltipText)
+ static let cap = NSColor(LittlePalette.tooltipCap)
+ static let capGlyph = NSColor(LittlePalette.tooltipCapGlyph)
+ private static let font = NSFont.systemFont(ofSize: 12, weight: .medium)
static func width(of text: String) -> CGFloat {
- (text as NSString).size(withAttributes: [.font: NSFont.systemFont(ofSize: 12, weight: .medium)]).width
+ (text as NSString).size(withAttributes: [.font: font]).width
}
- private var wraps: Bool { Self.width(of: text) > Self.maxTextWidth }
-
- var body: some View {
- let multiline = wraps || subtitle != nil
- HStack(spacing: 7) {
- VStack(alignment: .leading, spacing: 1) {
- // Long titles wrap at a fixed width (ArcTooltipConfiguration.maxWidth; Arc's value is unknown).
- if wraps {
- Text(text).font(.system(size: 12, weight: .medium)).foregroundStyle(LittlePalette.tooltipText)
- .lineLimit(3)
- .frame(width: Self.maxTextWidth, alignment: .leading)
- .fixedSize(horizontal: false, vertical: true)
- } else {
- Text(text).font(.system(size: 12, weight: .medium)).foregroundStyle(LittlePalette.tooltipText)
- }
- if let subtitle {
- Text(subtitle).font(.system(size: 11)).foregroundStyle(LittlePalette.tooltipText.opacity(0.6))
- }
- }
- if !keys.isEmpty {
- HStack(spacing: 3) {
- ForEach(Array(keys.enumerated()), id: \.offset) { _, k in
- ZStack(alignment: .top) {
- RoundedRectangle(cornerRadius: 4, style: .continuous).fill(Self.capEdge)
- Text(k)
- .font(.system(size: 10, weight: .bold))
- .foregroundStyle(LittlePalette.tooltipCapGlyph)
- .frame(width: 18, height: 16)
- .background(RoundedRectangle(cornerRadius: 4, style: .continuous).fill(LittlePalette.tooltipCap))
- }
- .frame(width: 18, height: 18)
- }
- }
- }
- }
- .padding(.leading, 10)
- .padding(.trailing, keys.isEmpty ? 10 : 8)
- .padding(.vertical, multiline ? 6 : 0)
- .frame(minHeight: 28)
+ private let title = NSTextField(wrappingLabelWithString: "")
+ private let sub = NSTextField.sidebarLabel(size: 11)
+ private var caps: [NSView] = []
+ private let multiline: Bool
+
+ init(text: String, keys: [String], subtitle: String? = nil) {
+ let wraps = Self.width(of: text) > Self.maxTextWidth
+ multiline = wraps || subtitle != nil
+ super.init(frame: .zero)
+ wantsLayer = true
// No border: unlike Little Arc's tip, the sidebar one goes straight from fill to backdrop.
// Two or more lines get a rounded rectangle (Cra's choice; Arc's multi-line tip wasn't observed).
- .background(RoundedRectangle(cornerRadius: multiline ? 10 : 14, style: .circular).fill(LittlePalette.tooltip))
- .fixedSize()
+ layer?.backgroundColor = Self.fill.cgColor
+ layer?.cornerRadius = multiline ? 10 : 14
+ title.font = Self.font
+ title.textColor = Self.ink
+ title.stringValue = text
+ // Long titles wrap at a fixed width (ArcTooltipConfiguration.maxWidth; Arc's value is unknown).
+ title.maximumNumberOfLines = wraps ? 3 : 1
+ title.lineBreakMode = wraps ? .byWordWrapping : .byClipping
+ title.cell?.truncatesLastVisibleLine = true
+ addSubview(title)
+ if let subtitle {
+ sub.stringValue = subtitle
+ sub.textColor = Self.ink.withAlphaComponent(0.6)
+ addSubview(sub)
+ }
+ for k in keys {
+ let edge = NSView()
+ edge.wantsLayer = true
+ edge.layer?.backgroundColor = Self.capEdge.cgColor
+ edge.layer?.cornerRadius = 4
+ edge.layer?.cornerCurve = .continuous
+ let face = NSView(frame: NSRect(x: 0, y: 2, width: 18, height: 16))
+ face.wantsLayer = true
+ face.layer?.backgroundColor = Self.cap.cgColor
+ face.layer?.cornerRadius = 4
+ face.layer?.cornerCurve = .continuous
+ edge.addSubview(face)
+ let glyph = NSTextField.sidebarLabel(size: 10, weight: .bold)
+ glyph.stringValue = k
+ glyph.textColor = Self.capGlyph
+ glyph.alignment = .center
+ glyph.frame = NSRect(x: -SidebarText.inset, y: (16 - 13) / 2, width: 18 + 2 * SidebarText.inset, height: 13)
+ face.addSubview(glyph)
+ caps.append(edge)
+ addSubview(edge)
+ }
+ layoutContent()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ private var titleSize: NSSize {
+ let w = multiline && title.maximumNumberOfLines > 1 ? Self.maxTextWidth : ceil(Self.width(of: title.stringValue))
+ let h = title.cell?.cellSize(forBounds: NSRect(x: 0, y: 0, width: w + 2 * SidebarText.inset, height: 1000)).height ?? 15
+ return NSSize(width: w, height: ceil(h))
+ }
+
+ /// Lays the label out and sizes the view to fit (SwiftUI's .fixedSize()).
+ private func layoutContent() {
+ let ts = titleSize
+ let subSize = sub.superview == nil ? .zero : NSSize(width: ceil(sub.attributedStringValue.size().width), height: 14)
+ let textW = max(ts.width, subSize.width)
+ let textH = ts.height + (sub.superview == nil ? 0 : 1 + subSize.height)
+ let keysW = caps.isEmpty ? 0 : CGFloat(caps.count) * 18 + CGFloat(caps.count - 1) * 3
+ let contentH = max(textH, caps.isEmpty ? 0 : 18)
+ let h = max(28, contentH + (multiline ? 12 : 0))
+ let w = 10 + textW + (caps.isEmpty ? 0 : 7 + keysW) + (caps.isEmpty ? 10 : 8)
+ setFrameSize(NSSize(width: ceil(w), height: ceil(h)))
+ // VStack(spacing: 1), centred.
+ let top = (h + textH) / 2
+ title.frame = NSRect(x: 10 - SidebarText.inset, y: top - ts.height, width: ts.width + 2 * SidebarText.inset, height: ts.height)
+ sub.frame = NSRect(x: 10 - SidebarText.inset, y: top - ts.height - 1 - subSize.height, width: subSize.width + 2 * SidebarText.inset, height: subSize.height)
+ var x = 10 + textW + 7
+ for c in caps {
+ c.frame = NSRect(x: x, y: (h - 18) / 2, width: 18, height: 18)
+ x += 18 + 3
+ }
}
/// "Copy URL (⇧⌘C)" → ("Copy URL", ["⇧", "⌘", "C"]).
diff --git a/Sources/Cra/UI/CommandBar/CommandBarController.swift b/Sources/Cra/UI/CommandBar/CommandBarController.swift
index 7f9c3f4..7930a48 100644
--- a/Sources/Cra/UI/CommandBar/CommandBarController.swift
+++ b/Sources/Cra/UI/CommandBar/CommandBarController.swift
@@ -71,6 +71,27 @@ final class CommandBarController {
if !allowCompletion { result.inlineCompletion = nil }
selectedIndex = 0
previewText = nil
+ let typed = newQuery
+ engine.fetchSearchSuggestions(for: typed) { [weak self] in
+ guard let self, self.isOpen, self.query == typed else { return }
+ self.relist()
+ }
+ }
+
+ /// The search engine answered: list again, keeping the selected row where it still is.
+ private func relist() {
+ let selectedID = result.items.indices.contains(selectedIndex) ? result.items[selectedIndex].id : nil
+ result = engine.suggestions(for: query, mode: mode, currentTabID: store.selectedTabID)
+ if !allowCompletion { result.inlineCompletion = nil }
+ if let i = result.items.firstIndex(where: { $0.id == selectedID }) {
+ selectedIndex = i
+ } else {
+ selectedIndex = 0
+ if previewText != nil {
+ previewText = nil
+ previewVersion += 1
+ }
+ }
}
func moveSelection(by delta: Int) {
diff --git a/Sources/Cra/UI/CommandBar/CommandBarView.swift b/Sources/Cra/UI/CommandBar/CommandBarView.swift
index b63b766..a08e0d1 100644
--- a/Sources/Cra/UI/CommandBar/CommandBarView.swift
+++ b/Sources/Cra/UI/CommandBar/CommandBarView.swift
@@ -1,155 +1,320 @@
+import AppKit
import SwiftUI
-/// Arc's command bar: a wide translucent panel, input row with the top
-/// match's favicon, single-line rows "Title — url", the selected row tinted
-/// with the space color, "Switch to Tab" + arrow for open tabs.
-struct CommandBarView: View {
- let controller: CommandBarController
- @Environment(FaviconCache.self) private var favicons
- @Environment(\.colorScheme) private var scheme
-
+/// Arc's command bar: a wide translucent panel, input row with the top match's favicon,
+/// single-line rows "Title — url", the selected row tinted with the space color, "Switch to
+/// Tab" + arrow for open tabs. AppKit: the rows are reused views that change only what changed,
+/// so a keystroke costs the search and a few labels, not a SwiftUI pass over the bar.
+@MainActor
+final class CommandBarView: NSView {
static let rowHeight: CGFloat = 50
static let fieldHeight: CGFloat = 60
static func height(forRows n: Int) -> CGFloat { fieldHeight + (n == 0 ? 0 : CGFloat(n) * rowHeight + CGFloat(n - 1) * 2 + 20) }
- private var dark: Bool { scheme == .dark }
- @State private var shown = false
-
- /// Arc pops the bar in with a short fade and a hint of scale; driven by the
- /// controller's open state so it replays on every open.
- var body: some View {
- content
- .opacity(shown ? 1 : 0)
- .scaleEffect(shown ? 1 : 0.985, anchor: .top)
- .onChange(of: controller.isOpen, initial: true) { _, open in
- // Arc's bar appears and disappears within a single frame.
- var t = Transaction(); t.disablesAnimations = true
- withTransaction(t) { shown = open }
- }
+ private let controller: CommandBarController
+ private let favicons: FaviconCache
+ private let material = NSVisualEffectView()
+ private let tint = NSView()
+ private let border = CAShapeLayer()
+ private let shape = CAShapeLayer()
+ private let leadingIcon = NSImageView()
+ private let text: CommandTextField
+ private let info = NSImageView()
+ private let divider = NSView()
+ private var rows: [CommandBarRowView] = []
+ private var syncQueued = false
+ private var attached = false
+
+ init(controller: CommandBarController, favicons: FaviconCache) {
+ self.controller = controller
+ self.favicons = favicons
+ text = CommandTextField(controller: controller)
+ super.init(frame: .zero)
+ wantsLayer = true
+ material.blendingMode = .behindWindow
+ material.state = .active
+ tint.wantsLayer = true
+ layer?.mask = shape
+ border.fillColor = nil
+ border.lineWidth = 2
+ leadingIcon.imageScaling = .scaleProportionallyUpOrDown
+ leadingIcon.wantsLayer = true
+ leadingIcon.layer?.cornerCurve = .continuous
+ info.image = SidebarSymbols.image("info.circle", size: 16)
+ info.imageScaling = .scaleNone
+ info.contentTintColor = .secondaryLabelColor
+ divider.wantsLayer = true
+ for v in [material, tint, leadingIcon, text.field, info, divider] as [NSView] { addSubview(v) }
+ layer?.addSublayer(border)
+ border.zPosition = 10
+ sync()
}
- private var content: some View {
- let items = controller.result.items
- return VStack(spacing: 0) {
- HStack(spacing: 14) {
- leadingIcon.frame(width: 22, height: 22)
- CommandTextField(controller: controller)
- .frame(height: 30)
- if controller.query.isEmpty {
- Image(systemName: "info.circle")
- .font(.system(size: 16, weight: .regular))
- .foregroundStyle(.secondary)
- }
- }
- .padding(.horizontal, 22)
- .frame(height: Self.fieldHeight)
-
- if !items.isEmpty {
- Rectangle().fill(Color.primary.opacity(0.08)).frame(height: 1).padding(.horizontal, 16)
- VStack(spacing: 2) {
- ForEach(Array(items.enumerated()), id: \.element.id) { idx, s in
- SuggestionRow(suggestion: s, selected: idx == controller.selectedIndex,
- highlight: controller.highlight, focusedSpaceID: controller.focusedSpaceID,
- spaceName: controller.spaceName, queryEmpty: controller.query.isEmpty, dark: dark)
- .onHover { if $0 { controller.selectedIndex = idx } }
- .onTapGesture { controller.commit(s) }
- }
- }
- .padding(10)
- }
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private var dark: Bool { effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua }
+
+ override func viewDidChangeEffectiveAppearance() {
+ super.viewDidChangeEffectiveAppearance()
+ sync()
+ }
+
+ private func scheduleSync() {
+ guard !syncQueued else { return }
+ syncQueued = true
+ DispatchQueue.main.async { [weak self] in self?.sync() }
+ }
+
+ private func sync() {
+ syncQueued = false
+ withObservationTracking { apply() } onChange: { [weak self] in
+ Task { @MainActor in self?.scheduleSync() }
}
- .frame(width: controller.panelWidth)
- .background(dark ? AnyShapeStyle(Color.black.opacity(0.74)) : AnyShapeStyle(Color.white.opacity(0.7)))
- .background(.ultraThinMaterial)
- .clipShape(UnevenRoundedRectangle(topLeadingRadius: controller.attached ? 10 : 14, bottomLeadingRadius: 14,
- bottomTrailingRadius: 14, topTrailingRadius: controller.attached ? 10 : 14, style: .continuous))
- .overlay(UnevenRoundedRectangle(topLeadingRadius: controller.attached ? 10 : 14, bottomLeadingRadius: 14,
- bottomTrailingRadius: 14, topTrailingRadius: controller.attached ? 10 : 14, style: .continuous)
- .strokeBorder(Color.primary.opacity(dark ? 0.12 : 0.08)))
}
- @ViewBuilder private var leadingIcon: some View {
+ private func apply() {
+ let c = controller
+ let items = c.result.items
+ let dark = self.dark
+ text.update()
+ attached = c.attached
+ // Closest AppKit materials to SwiftUI's .ultraThinMaterial under the bar's tint (dark: compared
+ // pixel for pixel over the same page).
+ material.material = dark ? .hudWindow : .popover
+ tint.layer?.backgroundColor = (dark ? NSColor.black.withAlphaComponent(0.74) : NSColor.white.withAlphaComponent(0.7)).cgColor
+ border.strokeColor = NSColor.labelColor.withAlphaComponent(dark ? 0.12 : 0.08).cgColor
+ divider.layer?.backgroundColor = NSColor.labelColor.withAlphaComponent(0.08).cgColor
+ info.isHidden = !c.query.isEmpty
+ divider.isHidden = items.isEmpty
+
// Follows the row the arrows moved to; otherwise the completing top match.
- let previewing = controller.previewText != nil && controller.result.items.indices.contains(controller.selectedIndex)
- let row = previewing ? controller.result.items[controller.selectedIndex] : controller.result.items.first
+ let previewing = c.previewText != nil && items.indices.contains(c.selectedIndex)
+ let row = previewing ? items[c.selectedIndex] : items.first
if let s = row, let key = s.faviconKey, s.id != "typed", let img = favicons.image(forKey: key),
- previewing || controller.result.inlineCompletion != nil || controller.mode == .editURL {
- Image(nsImage: img).resizable().interpolation(.high).aspectRatio(contentMode: .fit)
- .frame(width: 20, height: 20).clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))
+ previewing || c.result.inlineCompletion != nil || c.mode == .editURL {
+ leadingIcon.imageScaling = .scaleProportionallyUpOrDown
+ leadingIcon.image = img
+ leadingIcon.contentTintColor = nil
+ leadingIcon.layer?.cornerRadius = 5
+ leadingIcon.layer?.masksToBounds = true
+ leadingIcon.frame.size = NSSize(width: 20, height: 20)
} else {
- Image(systemName: controller.mode == .editURL ? "info.circle" : "magnifyingglass")
- .font(.system(size: 17, weight: .medium))
- .foregroundStyle(.secondary)
+ leadingIcon.imageScaling = .scaleNone
+ leadingIcon.image = SidebarSymbols.image(c.mode == .editURL ? "info.circle" : "magnifyingglass", size: 17, weight: .medium)
+ leadingIcon.contentTintColor = .secondaryLabelColor
+ leadingIcon.layer?.masksToBounds = false
+ leadingIcon.frame.size = NSSize(width: 22, height: 22)
}
+
+ while rows.count < items.count {
+ let r = CommandBarRowView()
+ r.onHover = { [weak self, weak r] in
+ guard let self, let r, let i = self.rows.firstIndex(where: { $0 === r }) else { return }
+ if self.controller.selectedIndex != i { self.controller.selectedIndex = i }
+ }
+ r.onClick = { [weak self, weak r] in
+ guard let self, let r, let i = self.rows.firstIndex(where: { $0 === r }), self.controller.result.items.indices.contains(i) else { return }
+ self.controller.commit(self.controller.result.items[i])
+ }
+ rows.append(r)
+ addSubview(r)
+ }
+ let highlight = NSColor(c.highlight)
+ for (i, r) in rows.enumerated() {
+ guard i < items.count else { r.isHidden = true; continue }
+ r.isHidden = false
+ let s = items[i]
+ r.show(s, icon: s.faviconKey.flatMap { favicons.image(forKey: $0) }, selected: i == c.selectedIndex, highlight: highlight,
+ otherSpace: s.spaceID.flatMap { $0 != c.focusedSpaceID && s.tabID != nil ? c.spaceName($0) : nil },
+ queryEmpty: c.query.isEmpty, dark: dark)
+ }
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ let b = bounds
+ material.frame = b
+ tint.frame = b
+ let top: CGFloat = attached ? 10 : 14
+ let path = Self.path(b, top: top, bottom: 14)
+ shape.frame = b
+ shape.path = path
+ border.frame = b
+ border.path = path
+ // Input row: 22 pt in, icon 22, 14 apart, the field 30 tall, the info glyph at the end.
+ let fh = Self.fieldHeight
+ let icon = leadingIcon.frame.size
+ leadingIcon.frame = NSRect(x: 22 + (22 - icon.width) / 2, y: (fh - icon.height) / 2, width: icon.width, height: icon.height)
+ var right = b.width - 22
+ if !info.isHidden {
+ info.frame = NSRect(x: right - 18, y: (fh - 18) / 2, width: 18, height: 18)
+ right -= 18 + 14
+ }
+ let x: CGFloat = 22 + 22 + 14
+ text.field.frame = NSRect(x: x - 1.5, y: (fh - 30) / 2 + 2, width: max(0, right - x), height: 30)
+ divider.frame = NSRect(x: 16, y: fh, width: max(0, b.width - 32), height: 1)
+ var y: CGFloat = fh + 10
+ for r in rows where !r.isHidden {
+ r.frame = NSRect(x: 10, y: y, width: b.width - 20, height: Self.rowHeight)
+ y += Self.rowHeight + 2
+ }
+ }
+
+ /// UnevenRoundedRectangle: smaller top corners while the bar hangs from the toolbar.
+ private static func path(_ r: CGRect, top: CGFloat, bottom: CGFloat) -> CGPath {
+ let p = CGMutablePath()
+ // Flipped view: minY is the top edge.
+ p.move(to: CGPoint(x: r.minX + top, y: r.minY))
+ p.addLine(to: CGPoint(x: r.maxX - top, y: r.minY))
+ p.addArc(tangent1End: CGPoint(x: r.maxX, y: r.minY), tangent2End: CGPoint(x: r.maxX, y: r.minY + top), radius: top)
+ p.addLine(to: CGPoint(x: r.maxX, y: r.maxY - bottom))
+ p.addArc(tangent1End: CGPoint(x: r.maxX, y: r.maxY), tangent2End: CGPoint(x: r.maxX - bottom, y: r.maxY), radius: bottom)
+ p.addLine(to: CGPoint(x: r.minX + bottom, y: r.maxY))
+ p.addArc(tangent1End: CGPoint(x: r.minX, y: r.maxY), tangent2End: CGPoint(x: r.minX, y: r.maxY - bottom), radius: bottom)
+ p.addLine(to: CGPoint(x: r.minX, y: r.minY + top))
+ p.addArc(tangent1End: CGPoint(x: r.minX, y: r.minY), tangent2End: CGPoint(x: r.minX + top, y: r.minY), radius: top)
+ p.closeSubpath()
+ return p
}
}
-struct SuggestionRow: View {
- let suggestion: Suggestion
- let selected: Bool
- let highlight: Color
- let focusedSpaceID: UUID?
- let spaceName: (UUID) -> String
- let queryEmpty: Bool
- let dark: Bool
- @Environment(FaviconCache.self) private var favicons
-
- private var isTab: Bool { suggestion.tabID != nil }
- private var otherSpace: String? {
- guard isTab, let sid = suggestion.spaceID, sid != focusedSpaceID else { return nil }
- return spaceName(sid)
+/// One suggestion: icon, "Title — detail", and "Switch to Tab" + arrow for open tabs.
+final class CommandBarRowView: NSView {
+ var onHover: () -> Void = {}
+ var onClick: () -> Void = {}
+ private let iconBox = NSView()
+ private let icon = NSImageView()
+ private let emoji = NSTextField.sidebarLabel(size: 16)
+ private let label = NSTextField.sidebarLabel(size: 15)
+ private let trailing = NSTextField.sidebarLabel(size: 14, weight: .medium)
+ private let arrowBox = NSView()
+ private let arrow = NSImageView()
+ private var shown: (Suggestion, NSImage?, Bool, NSColor, String?, Bool, Bool)?
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerRadius = 10
+ layer?.cornerCurve = .continuous
+ iconBox.wantsLayer = true
+ iconBox.layer?.cornerRadius = 6
+ iconBox.layer?.cornerCurve = .continuous
+ icon.imageScaling = .scaleProportionallyUpOrDown
+ arrowBox.wantsLayer = true
+ arrowBox.layer?.cornerRadius = 6
+ arrowBox.layer?.cornerCurve = .continuous
+ arrow.image = SidebarSymbols.image("arrow.right", size: 12, weight: .bold)
+ arrow.imageScaling = .scaleNone
+ label.lineBreakMode = .byTruncatingMiddle
+ trailing.textColor = .secondaryLabelColor
+ for v in [iconBox, icon, emoji, label, trailing, arrowBox, arrow] as [NSView] { addSubview(v) }
}
- var body: some View {
- HStack(spacing: 14) {
- icon.frame(width: 26, height: 26)
- (Text(suggestion.title).font(.system(size: 15, weight: .semibold)).foregroundStyle(.primary)
- + Text(detailText).font(.system(size: 15)).foregroundStyle(.secondary))
- .lineLimit(1)
- .truncationMode(.middle)
- Spacer(minLength: 8)
- if isTab {
- Text(otherSpace ?? (queryEmpty ? "" : "Switch to Tab"))
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(.secondary)
- Image(systemName: "arrow.right")
- .font(.system(size: 12, weight: .bold))
- .foregroundStyle(.primary.opacity(0.8))
- .frame(width: 22, height: 22)
- .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(Color.primary.opacity(0.1)))
- } else if let t = suggestion.trailing {
- Text(t).font(.system(size: 13, weight: .medium)).foregroundStyle(.secondary)
- }
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ func show(_ s: Suggestion, icon image: NSImage?, selected: Bool, highlight: NSColor, otherSpace: String?, queryEmpty: Bool, dark: Bool) {
+ if let o = shown, o.0 == s, o.1 === image, o.2 == selected, o.3 == highlight, o.4 == otherSpace, o.5 == queryEmpty, o.6 == dark { return }
+ let sameContent = shown.map { $0.0 == s && $0.1 === image && $0.4 == otherSpace && $0.5 == queryEmpty && $0.6 == dark } ?? false
+ shown = (s, image, selected, highlight, otherSpace, queryEmpty, dark)
+ layer?.backgroundColor = (selected ? highlight : .clear).cgColor
+ guard !sameContent else { return }
+ if let image {
+ icon.isHidden = false
+ emoji.isHidden = true
+ iconBox.isHidden = false
+ icon.image = image
+ icon.imageScaling = .scaleProportionallyUpOrDown
+ icon.contentTintColor = nil
+ iconBox.layer?.backgroundColor = (dark ? NSColor.white.withAlphaComponent(0.14) : NSColor.black.withAlphaComponent(0.06)).cgColor
+ } else if case .switchSpace = s.kind, let t = s.trailing {
+ icon.isHidden = true
+ iconBox.isHidden = true
+ emoji.isHidden = false
+ emoji.stringValue = t
+ } else {
+ iconBox.isHidden = true
+ emoji.isHidden = true
+ icon.isHidden = false
+ icon.image = SidebarSymbols.image(s.symbol ?? "globe", size: 15, weight: .medium)
+ icon.imageScaling = .scaleNone
+ icon.contentTintColor = .secondaryLabelColor
+ }
+ let t = NSMutableAttributedString(string: s.title, attributes: [.font: NSFont.systemFont(ofSize: 15, weight: .semibold), .foregroundColor: NSColor.labelColor])
+ t.append(NSAttributedString(string: Self.detail(s), attributes: [.font: NSFont.systemFont(ofSize: 15), .foregroundColor: NSColor.secondaryLabelColor]))
+ label.attributedStringValue = t
+ let isTab = s.tabID != nil
+ if isTab {
+ trailing.font = .systemFont(ofSize: 14, weight: .medium)
+ trailing.stringValue = otherSpace ?? (queryEmpty ? "" : "Switch to Tab")
+ } else {
+ trailing.font = .systemFont(ofSize: 13, weight: .medium)
+ trailing.stringValue = s.trailing ?? ""
}
- .padding(.horizontal, 14)
- .frame(height: CommandBarView.rowHeight)
- .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(selected ? highlight : .clear))
- .contentShape(Rectangle())
+ arrowBox.isHidden = !isTab
+ arrow.isHidden = !isTab
+ arrow.contentTintColor = NSColor.labelColor.withAlphaComponent(0.8)
+ arrowBox.layer?.backgroundColor = NSColor.labelColor.withAlphaComponent(0.1).cgColor
+ needsLayout = true
}
- private var detailText: String {
- switch suggestion.kind {
+ private static func detail(_ s: Suggestion) -> String {
+ switch s.kind {
case .switchToTab, .search, .command, .switchSpace, .moveToSpace, .moveToFolder: return ""
- case .archived: return suggestion.subtitle.isEmpty ? "" : " — \(suggestion.subtitle)"
+ case .archived: return s.subtitle.isEmpty ? "" : " — \(s.subtitle)"
default:
- guard let url = suggestion.url else { return "" }
+ guard let url = s.url else { return "" }
let human = SuggestionEngine.humanURL(url)
- return human.lowercased() == suggestion.title.lowercased() ? "" : " — \(human)"
+ return human.lowercased() == s.title.lowercased() ? "" : " — \(human)"
}
}
- @ViewBuilder private var icon: some View {
- if let key = suggestion.faviconKey, let img = favicons.image(forKey: key) {
- Image(nsImage: img).resizable().interpolation(.high).aspectRatio(contentMode: .fit)
- .frame(width: 18, height: 18)
- .padding(4)
- .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(dark ? Color.white.opacity(0.14) : Color.black.opacity(0.06)))
- } else if case .switchSpace = suggestion.kind, let t = suggestion.trailing {
- Text(t).font(.system(size: 16))
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ // padding 14, icon 26, 14 apart, the title, Spacer(min 8), trailing text, 14, arrow box 22.
+ iconBox.frame = NSRect(x: 14, y: (h - 26) / 2, width: 26, height: 26)
+ if iconBox.isHidden {
+ icon.frame = iconBox.frame
} else {
- Image(systemName: suggestion.symbol ?? "globe")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(.secondary)
+ icon.frame = iconBox.frame.insetBy(dx: 4, dy: 4)
+ }
+ let es = emoji.intrinsicContentSize
+ emoji.frame = NSRect(x: 14 + (26 - es.width) / 2, y: (h - es.height) / 2, width: es.width, height: es.height)
+ var right = bounds.width - 14
+ if !arrowBox.isHidden {
+ arrowBox.frame = NSRect(x: right - 22, y: (h - 22) / 2, width: 22, height: 22)
+ arrow.frame = arrowBox.frame
+ right -= 22 + 14
+ }
+ if !trailing.stringValue.isEmpty {
+ let tw = ceil(trailing.attributedStringValue.size().width)
+ let th = trailing.intrinsicContentSize.height
+ trailing.frame = NSRect(x: right - tw - SidebarText.inset, y: (h - th) / 2, width: tw + 2 * SidebarText.inset, height: th)
+ right -= tw + 14
+ } else if !arrowBox.isHidden {
+ // The empty label still takes its spacing in the HStack.
+ right -= 14
}
+ let x: CGFloat = 14 + 26 + 14
+ let ls = label.intrinsicContentSize
+ label.frame = NSRect(x: x - SidebarText.inset, y: (h - ls.height) / 2, width: max(0, right - 8 - x) + 2 * SidebarText.inset, height: ls.height)
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { onHover() }
+ override func mouseMoved(with event: NSEvent) { onHover() }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { onClick() }
}
}
diff --git a/Sources/Cra/UI/CommandBar/CommandTextField.swift b/Sources/Cra/UI/CommandBar/CommandTextField.swift
index 5310faa..2748381 100644
--- a/Sources/Cra/UI/CommandBar/CommandTextField.swift
+++ b/Sources/Cra/UI/CommandBar/CommandTextField.swift
@@ -1,13 +1,32 @@
import AppKit
-import SwiftUI
-/// NSTextField wrapper with Chrome/Arc-style inline completion: the
+/// The command bar's NSTextField with Chrome/Arc-style inline completion: the
/// completed suffix is inserted selected, so typing replaces it and
-/// Backspace removes it without re-completing.
-struct CommandTextField: NSViewRepresentable {
+/// Backspace removes it without re-completing. CommandBarView calls `update`
+/// whenever the controller changes.
+@MainActor
+final class CommandTextField {
let controller: CommandBarController
+ let field: NSTextField
+ private let coordinator: Coordinator
- func makeNSView(context: Context) -> NSTextField {
+ init(controller: CommandBarController) {
+ self.controller = controller
+ coordinator = Coordinator(controller: controller)
+ field = Self.makeField(controller: controller, coordinator: coordinator)
+ }
+
+ func update() {
+ Self.update(field, controller: controller, coordinator: coordinator)
+ // A completion needs the field's editor, which exists once the field is first responder
+ // (made so on the next turn when the bar opens): apply what is pending again then.
+ DispatchQueue.main.async { [weak self] in
+ guard let self else { return }
+ Self.update(self.field, controller: self.controller, coordinator: self.coordinator)
+ }
+ }
+
+ private static func makeField(controller: CommandBarController, coordinator: Coordinator) -> NSTextField {
let field = NSTextField(string: controller.fieldText)
field.isBordered = false
field.isBezeled = false
@@ -15,22 +34,17 @@ struct CommandTextField: NSViewRepresentable {
field.focusRingType = .none
field.font = .systemFont(ofSize: 20, weight: .regular)
field.placeholderString = controller.placeholder
- field.delegate = context.coordinator
+ field.delegate = coordinator
field.lineBreakMode = .byTruncatingTail
field.cell?.usesSingleLineMode = true
field.cell?.wraps = false
field.cell?.isScrollable = true
- context.coordinator.field = field
- DispatchQueue.main.async {
- field.window?.makeFirstResponder(field)
- field.currentEditor()?.selectAll(nil)
- }
+ coordinator.field = field
return field
}
- func updateNSView(_ field: NSTextField, context: Context) {
+ private static func update(_ field: NSTextField, controller: CommandBarController, coordinator coord: Coordinator) {
field.placeholderString = controller.placeholder
- let coord = context.coordinator
if coord.appliedVersion != controller.fieldTextVersion {
coord.appliedVersion = controller.fieldTextVersion
coord.suppressChange = true
@@ -55,8 +69,6 @@ struct CommandTextField: NSViewRepresentable {
}
}
- func makeCoordinator() -> Coordinator { Coordinator(controller: controller) }
-
@MainActor
final class Coordinator: NSObject, NSTextFieldDelegate {
let controller: CommandBarController
diff --git a/Sources/Cra/UI/ContentToolbarView.swift b/Sources/Cra/UI/ContentToolbarView.swift
deleted file mode 100644
index 9db24ee..0000000
--- a/Sources/Cra/UI/ContentToolbarView.swift
+++ /dev/null
@@ -1,300 +0,0 @@
-import SwiftUI
-
-/// Arc's toolbar above the page: lock + URL (monospaced), copy link, DevTools,
-/// sidebar toggle. With no tab it carries the nav buttons and a centered
-/// "Search or Enter URL…" placeholder instead.
-struct ContentToolbarView: View {
- let palette: SpacePalette
- /// Split view: this toolbar belongs to one pane (nil = the window's single toolbar).
- var paneTabID: UUID? = nil
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var hoverURL = false
-
- private var tab: SidebarItem? {
- if let id = paneTabID { return store.item(id) }
- return store.selectedTab(window: ui.windowID)
- }
- private var onCard: Bool { tab != nil && !isEmptyPane }
- /// Arc's empty pane ("Search or Enter URL…" on the tinted card).
- private var isEmptyPane: Bool { tab?.isEmptyTab ?? false }
- private var inSplit: Bool { paneTabID != nil && ui.splitPaneIDs.count > 1 }
- private var isFocusedPane: Bool { paneTabID == nil || store.selectedTabID(window: ui.windowID) == paneTabID }
- private var nav: TabNavState {
- if let id = paneTabID { return ui.navState(for: id) }
- return TabNavState(canGoBack: ui.canGoBack, canGoForward: ui.canGoForward, isLoading: ui.isLoading, themeColor: ui.pageThemeColor)
- }
- private func navigate(_ what: String) {
- if let id = paneTabID { actions.paneNavigate(id, what); return }
- switch what {
- case "goBack": actions.goBack()
- case "goForward": actions.goForward()
- default: actions.reload()
- }
- }
- private func editURL() {
- if let id = paneTabID { actions.editPaneURL(id) } else { actions.openCommandBar(tab == nil ? .newTab : .editURL) }
- }
- @Environment(FaviconCache.self) private var favicons
-
- /// Arc's toolbar colour: the page's theme-color when it declares one
- /// (Messenger's white included), else a dark favicon colour, else the
- /// space tint.
- private var cardHex: String? {
- let theme = nav.themeColor
- if theme != "none", !theme.isEmpty, HexColor.components(theme) != nil { return theme }
- return nil
- }
- // Arc: the bar is white until the page reports a colour, then takes that colour.
- private var cardFill: Color { cardHex.map { Color(hex: $0) } ?? .white }
- private var cardIsLight: Bool { (cardHex.flatMap(HexColor.luminance) ?? 1) > 0.6 }
- private var fg: Color { onCard ? (cardIsLight ? Color.black.opacity(0.8) : Color(hex: "#E4E0D4")) : palette.textSecondary }
- private var fgDim: Color { onCard ? (cardIsLight ? Color.black.opacity(0.6) : Color(hex: "#F0E6CC").opacity(0.9)) : palette.textTertiary }
-
- /// Dia's nav-bar status ("Copied Current URL") replaces the URL in the focused pane's bar.
- private var status: ToolbarStatus? { isFocusedPane ? ui.toolbarStatus : nil }
-
- private var developerMode: Bool { !inSplit && (tab?.tab.map { store.settings.isDeveloperMode(url: $0.url) } ?? false) }
-
- /// Arc's default bar: nav buttons at the left, the friendly URL centred
- /// (host bright, path dimmer) behind a link glyph. Split panes drop the
- /// refresh button (measured on Arc 1.170: only ← → in a pane).
- @ViewBuilder private func defaultBar(_ t: TabData) -> some View {
- let human = SuggestionEngine.humanURL(t.url)
- let host = AppSettings.siteKey(for: t.url) ?? human
- let path = human.hasPrefix(host) ? String(human.dropFirst(host.count)) : ""
- HStack(spacing: 0) {
- // Toggle first, centred 30 pt from the card edge (Arc, sidebar hidden), then ← → ↻ at 37 pt pitch.
- if !inSplit { sidebarToggle }
- ToolbarIcon(symbol: "arrow.left", fg: fgDim, help: "Go Back (⌘[)", enabled: nav.canGoBack, width: 37, iconSize: 15) { navigate("goBack") }
- ToolbarIcon(symbol: "arrow.right", fg: fgDim, help: "Go Forward (⌘])", enabled: nav.canGoForward, width: 37, iconSize: 15) { navigate("goForward") }
- if !inSplit {
- ToolbarIcon(symbol: nav.isLoading ? "xmark" : "arrow.clockwise", fg: fgDim, help: "Refresh (⌘R)", width: 37, iconSize: 15) { navigate("reload") }
- }
- }
- .padding(.leading, inSplit ? 2.5 : 11.5)
- Spacer(minLength: 8)
- Button { editURL() } label: {
- HStack(spacing: 7) {
- if let status {
- Image(systemName: status.symbol).font(.system(size: 12, weight: .medium)).foregroundStyle(fgDim)
- Text(status.text).font(.system(size: 13)).foregroundStyle(fgDim).lineLimit(1)
- } else {
- Image(systemName: "link").font(.system(size: 12, weight: .medium)).foregroundStyle(fgDim)
- (Text(host).foregroundStyle(fg) + Text(path).foregroundStyle(fgDim))
- .font(.system(size: 13))
- .lineLimit(1)
- .truncationMode(.tail)
- }
- }
- .id(status?.id)
- .transition(.opacity)
- .padding(.horizontal, 10)
- .frame(height: 28)
- .background(RoundedRectangle(cornerRadius: 7).fill(hoverURL ? Color.white.opacity(0.08) : .clear))
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .onHover { hoverURL = $0 }
- .arcTooltip(t.url, followsCursor: true)
- Spacer(minLength: 8)
- }
-
- /// Arc's empty split pane: disabled ← →, the placeholder centred, nothing else.
- @ViewBuilder private var emptyPaneBar: some View {
- HStack(spacing: 0) {
- ToolbarIcon(symbol: "arrow.left", fg: fgDim, enabled: false, width: 37, iconSize: 15) {}
- ToolbarIcon(symbol: "arrow.right", fg: fgDim, enabled: false, width: 37, iconSize: 15) {}
- }
- .padding(.leading, 1)
- Spacer(minLength: 8)
- Button { editURL() } label: {
- Text("Search or Enter URL…")
- .font(.system(size: 13))
- .foregroundStyle(palette.textTertiary)
- .lineLimit(1)
- }
- .buttonStyle(.plain)
- Spacer(minLength: 8)
- }
-
- var body: some View {
- let tab = self.tab
- HStack(spacing: 6) {
- if tab != nil, isEmptyPane {
- emptyPaneBar
- } else if let tab, let t = tab.tab, !developerMode {
- defaultBar(t)
- } else if let tab, let t = tab.tab {
- if !inSplit { sidebarToggle.padding(.leading, 11.5) }
- Button { editURL() } label: {
- HStack(spacing: 12) {
- Image(systemName: status?.symbol ?? (t.url.hasPrefix("https://") ? "lock.fill" : "globe"))
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(fgDim)
- .frame(width: 14)
- Text(status?.text ?? t.url)
- .font(status == nil ? .system(size: 12, design: .monospaced) : .system(size: 13))
- .foregroundStyle(status == nil ? fg : fgDim)
- .lineLimit(1)
- .truncationMode(.tail)
- Spacer(minLength: 0)
- }
- .id(status?.id)
- .transition(.opacity)
- .padding(.horizontal, 6)
- .frame(height: 28)
- .background(RoundedRectangle(cornerRadius: 6).fill(hoverURL ? Color.white.opacity(0.08) : .clear))
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .onHover { hoverURL = $0 }
- .padding(.leading, 8)
- } else {
- HStack(spacing: 0) {
- sidebarToggle
- ToolbarIcon(symbol: "arrow.left", fg: fgDim, enabled: false, width: 37, iconSize: 15) {}
- ToolbarIcon(symbol: "arrow.right", fg: fgDim, enabled: false, width: 37, iconSize: 15) {}
- ToolbarIcon(symbol: "arrow.clockwise", fg: fgDim, enabled: false, width: 37, iconSize: 15) {}
- }
- .padding(.leading, 11.5)
- Spacer()
- Button { editURL() } label: {
- Text("Search or Enter URL…")
- .font(.system(size: 13))
- .foregroundStyle(palette.textTertiary)
- }
- .buttonStyle(.plain)
- Spacer()
- }
- if tab != nil && developerMode && !inSplit {
- Spacer(minLength: 8)
- ToolbarIcon(symbol: "link", fg: fgDim, help: "Copy URL (⇧⌘C)") { actions.performAction("copyURL") }
- toolbarDivider
- ToolbarIcon(symbol: "terminal", fg: fgDim, help: "Developer Tools (⌥⌘I)") { actions.performAction("devTools") }
- }
- // Also on the no-tab bar (Arc keeps them there).
- if !inSplit, !isEmptyPane { trailingButtons }
- if inSplit, let id = paneTabID {
- // Observed on Arc 1.170: the focused pane shows the split options
- // button before its close button; other panes only the close button.
- if isFocusedPane, !isEmptyPane {
- Menu {
- Button("Separate Tab from Split") { actions.separatePane(id) }
- Button("Flip Split View Orientation") { actions.performAction("flipSplitOrientation") }
- Divider()
- Button("Copy Link") { actions.performAction("copyURL") }
- Divider()
- Button("Close this Split Pane") { actions.closePane(id) }
- } label: {
- Image(systemName: "rectangle.split.2x1")
- .font(.system(size: 13, weight: .regular))
- .foregroundStyle(fgDim)
- .frame(width: 26, height: 26)
- .contentShape(Rectangle())
- }
- .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)
- .frame(width: 26)
- .arcTooltip("Split View Options")
- }
- ToolbarIcon(symbol: "xmark", fg: isEmptyPane ? palette.textSecondary : fgDim, help: "Close this Split Pane (⌃⇧-)", width: 30, iconSize: 14) { actions.closePane(id) }
- .padding(.trailing, 4)
- }
- }
- .frame(height: CraMetrics.toolbarHeight)
- .contentShape(Rectangle())
- // A click anywhere on the bar edits the URL (a pane's click also focuses it). No
- // double-click-to-zoom here: a count-2 gesture makes SwiftUI hold every single
- // click, the URL button's included, until the double-click interval has passed.
- .onTapGesture { editURL() }
- .background(onCard ? cardFill : (isEmptyPane ? Color.clear : (palette.isDark ? Color.white.opacity(0.025) : Color.black.opacity(0.03))))
- .overlay(alignment: .bottom) {
- // No hairline under the bar on the card: the bar and the page read as one surface (Arc draws one).
- if !onCard, !isEmptyPane { Rectangle().fill(palette.isDark ? Color.white.opacity(0.07) : Color.black.opacity(0.07)).frame(height: 1) }
- }
- .ignoresSafeArea()
- }
-}
-
-private extension ContentToolbarView {
- /// Arc's right end of the bar: pinned extensions, the Extensions button (menu with
- /// every extension and pinning), then Split View.
- var trailingButtons: some View {
- let extensions = ExtensionStore.shared
- return HStack(spacing: 0) {
- ForEach(extensions.pinnedIDs, id: \.self) { id in
- if let e = extensions.entries.first(where: { $0.extensionID == id }) {
- ToolbarImageButton(image: e.icon, help: e.name) { actions.runExtension(id) }
- }
- }
- if !extensions.entries.isEmpty {
- ToolbarIcon(symbol: "slider.horizontal.2.square", fg: fgDim, help: "Extensions", width: 34, iconSize: 16) {
- actions.showExtensionsMenu()
- }
- }
- ToolbarIcon(symbol: "square.split.2x1", fg: fgDim, help: "Add Split View (⌃⇧=)", width: 34, iconSize: 16) {
- actions.performAction("addSplitView")
- }
- }
- .padding(.trailing, 6)
- }
-
- var sidebarToggle: some View {
- ToolbarIcon(symbol: "sidebar.left", fg: fgDim, help: store.window(ui.windowID).sidebarVisible ? "Hide Sidebar (⌘S)" : "Show Sidebar (⌘S)",
- width: 37, iconSize: 15.5) { actions.toggleSidebar() }
- }
-
- var toolbarDivider: some View {
- Rectangle().fill(cardIsLight ? Color.black.opacity(0.15) : Color.white.opacity(0.22)).frame(width: 1, height: 14).padding(.horizontal, 5)
- }
-}
-
-struct ToolbarIcon: View {
- let symbol: String
- let fg: Color
- var help: String = ""
- var enabled: Bool = true
- var width: CGFloat = 26
- var iconSize: CGFloat = 13
- let action: () -> Void
- @State private var hover = false
- var body: some View {
- Button(action: action) {
- Image(systemName: symbol)
- .font(.system(size: iconSize, weight: .regular))
- .foregroundStyle(enabled ? fg : fg.opacity(0.4))
- .frame(width: width, height: 26)
- .background(RoundedRectangle(cornerRadius: 7).fill(hover && enabled ? Color.white.opacity(0.1) : .clear))
- }
- .buttonStyle(.plain)
- .disabled(!enabled)
- .onHover { hover = $0 }
- .arcTooltip(help)
- }
-}
-
-/// A pinned extension in the toolbar: its manifest icon at 18 pt (Arc), puzzle piece without one.
-struct ToolbarImageButton: View {
- let image: NSImage?
- var help: String = ""
- let action: () -> Void
- @State private var hover = false
- var body: some View {
- Button(action: action) {
- Group {
- if let image {
- Image(nsImage: image).resizable().interpolation(.high).aspectRatio(contentMode: .fit)
- } else {
- Image(systemName: "puzzlepiece.extension").resizable().aspectRatio(contentMode: .fit)
- }
- }
- .frame(width: 18, height: 18)
- .frame(width: 34, height: 26)
- .background(RoundedRectangle(cornerRadius: 7).fill(hover ? Color.white.opacity(0.1) : .clear))
- }
- .buttonStyle(.plain)
- .onHover { hover = $0 }
- .arcTooltip(help)
- }
-}
diff --git a/Sources/Cra/UI/ExtensionsMenu.swift b/Sources/Cra/UI/ExtensionsMenu.swift
index ecb891c..223d2aa 100644
--- a/Sources/Cra/UI/ExtensionsMenu.swift
+++ b/Sources/Cra/UI/ExtensionsMenu.swift
@@ -1,4 +1,5 @@
import AppKit
+import UniformTypeIdentifiers
/// The menu bar's Extensions menu, after Dia 1.54 (Extensions, between History and
/// Window): one row per extension with its 16 pt icon, in plain ordinal name order
@@ -52,6 +53,67 @@ final class ExtensionsMenu: NSObject, NSMenuDelegate, NSMenuItemValidation {
pin.submenu = pinMenu
pin.isEnabled = !entries.isEmpty
menu.addItem(pin)
+
+ let icons = NSMenuItem(title: "Toolbar Icons", action: nil, keyEquivalent: "")
+ let iconsMenu = NSMenu(title: "Toolbar Icons")
+ for e in entries {
+ let item = NSMenuItem(title: e.name, action: nil, keyEquivalent: "")
+ item.image = Self.menuIcon(store.toolbarIcon(for: e))
+ item.submenu = Self.iconMenu(for: e)
+ iconsMenu.addItem(item)
+ }
+ icons.submenu = iconsMenu
+ icons.isEnabled = !entries.isEmpty
+ menu.addItem(icons)
+ }
+
+ /// How one extension's toolbar button draws: its own icon, monochrome, a symbol or an
+ /// image file (GitHub #9). Also the pinned button's context menu.
+ static func iconMenu(for e: ExtensionStore.Entry) -> NSMenu {
+ let store = ExtensionStore.shared
+ let id = e.extensionID
+ let style = store.iconStyle(id)
+ let menu = NSMenu(title: e.name)
+
+ let original = BlockMenuItem(title: "Original Icon") { store.setIconStyle(id, .init()) }
+ original.state = style == .init() ? .on : .off
+ menu.addItem(original)
+ let mono = BlockMenuItem(title: "Monochrome") {
+ var s = store.iconStyle(id)
+ s.monochrome.toggle()
+ s.symbol = nil
+ store.setIconStyle(id, s)
+ }
+ mono.state = style.monochrome && style.symbol == nil ? .on : .off
+ menu.addItem(mono)
+ menu.addItem(.separator())
+
+ let symbols = NSMenuItem(title: "Symbol", action: nil, keyEquivalent: "")
+ let symbolMenu = NSMenu(title: "Symbol")
+ for name in ExtensionStore.iconSymbols {
+ let item = BlockMenuItem(title: name) {
+ var s = store.iconStyle(id)
+ s.symbol = name
+ s.imageFile = nil
+ store.setIconStyle(id, s)
+ }
+ item.image = NSImage(systemSymbolName: name, accessibilityDescription: name)
+ item.state = style.symbol == name ? .on : .off
+ symbolMenu.addItem(item)
+ }
+ symbols.submenu = symbolMenu
+ symbols.state = style.symbol != nil ? .on : .off
+ menu.addItem(symbols)
+ let choose = BlockMenuItem(title: "Choose Image…") {
+ let panel = NSOpenPanel()
+ panel.allowedContentTypes = [.image]
+ panel.message = "Choose an icon for \(e.name)'s toolbar button"
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ do { try store.setCustomIcon(id, from: url) } catch { NSAlert(error: error).runModal() }
+ }
+ choose.state = style.imageFile != nil ? .on : .off
+ menu.addItem(choose)
+ return menu
}
func validateMenuItem(_ item: NSMenuItem) -> Bool {
diff --git a/Sources/Cra/UI/Overlays.swift b/Sources/Cra/UI/Overlays.swift
index f0a4af2..518a2d0 100644
--- a/Sources/Cra/UI/Overlays.swift
+++ b/Sources/Cra/UI/Overlays.swift
@@ -1,6 +1,5 @@
import AppKit
import Observation
-import SwiftUI
struct DownloadToast: Identifiable, Equatable {
let id: UInt32
@@ -28,59 +27,174 @@ final class OverlayState {
var toasts: [DownloadToast] = []
}
-struct StatusBubble: View {
- let overlay: OverlayState
- var body: some View {
- if !overlay.status.isEmpty {
- Text(overlay.status)
- .font(.system(size: 11))
- .lineLimit(1)
- .truncationMode(.middle)
- .padding(.horizontal, 8)
- .padding(.vertical, 4)
- .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 6, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Color.primary.opacity(0.1)))
- .padding(6)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
+/// The link under the pointer, bottom left over the page. AppKit: it changes on every link the
+/// pointer crosses.
+final class StatusBubbleView: NSView {
+ private let overlay: OverlayState
+ private let bubble = NSVisualEffectView()
+ private let label = NSTextField.sidebarLabel(size: 11)
+
+ init(overlay: OverlayState) {
+ self.overlay = overlay
+ super.init(frame: .zero)
+ bubble.material = .popover
+ bubble.blendingMode = .withinWindow
+ bubble.state = .active
+ bubble.wantsLayer = true
+ bubble.layer?.cornerRadius = 6
+ bubble.layer?.cornerCurve = .continuous
+ bubble.layer?.masksToBounds = true
+ bubble.layer?.borderWidth = 1
+ label.lineBreakMode = .byTruncatingMiddle
+ label.textColor = .labelColor
+ // SwiftUI's .thinMaterial is lighter than any AppKit material: the popover material at
+ // about four fifths matches it over Cra's pages; the text stays on top at full strength.
+ bubble.alphaValue = 0.81
+ addSubview(bubble)
+ addSubview(label)
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ private func observe() {
+ let text = withObservationTracking { overlay.status } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
}
+ label.stringValue = text
+ bubble.isHidden = text.isEmpty
+ label.isHidden = text.isEmpty
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ bubble.layer?.borderColor = NSColor.labelColor.withAlphaComponent(0.1).cgColor
+ let s = label.attributedStringValue.size()
+ let w = min(ceil(s.width) + 16, max(0, bounds.width - 12))
+ let h = ceil(s.height) + 8
+ bubble.frame = NSRect(x: 6, y: 6, width: w, height: h)
+ label.frame = NSRect(x: 6 + 8 - SidebarText.inset, y: 6 + (h - ceil(s.height)) / 2, width: w - 16 + 2 * SidebarText.inset, height: ceil(s.height))
}
}
-struct FindBar: View {
- let overlay: OverlayState
- let onFind: (String, Bool) -> Void // query, forward
- let onClose: () -> Void
- @FocusState private var focused: Bool
-
- var body: some View {
- if overlay.findVisible {
- @Bindable var overlay = overlay
- HStack(spacing: 6) {
- Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
- TextField("Find in page", text: $overlay.findQuery)
- .textFieldStyle(.plain)
- .frame(maxWidth: .infinity)
- .focused($focused)
- .onSubmit { onFind(overlay.findQuery, !(NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false)) }
- .onChange(of: overlay.findQuery) { _, q in onFind(q, true) }
- .onExitCommand { onClose() }
- if !overlay.findQuery.isEmpty, let count = overlay.findMatchCount {
- Text("\(count == 0 ? 0 : overlay.findActiveMatch)/\(count)")
- .font(.system(size: 11).monospacedDigit())
- .foregroundStyle(.secondary)
- .fixedSize()
- }
- Button { onFind(overlay.findQuery, false) } label: { Image(systemName: "chevron.up") }.buttonStyle(.plain)
- Button { onFind(overlay.findQuery, true) } label: { Image(systemName: "chevron.down") }.buttonStyle(.plain)
- Button { onClose() } label: { Image(systemName: "xmark") }.buttonStyle(.plain)
- }
- .padding(.horizontal, 10)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Color.primary.opacity(0.1)))
- .onAppear { focused = true }
- .onChange(of: overlay.findFocusToken) { _, _ in focused = true }
+/// Find in page, top trailing over the page: glyph, field, "2/7", previous, next, close.
+final class FindBarView: NSView, NSTextFieldDelegate {
+ private let overlay: OverlayState
+ private let onFind: (String, Bool) -> Void // query, forward
+ private let onClose: () -> Void
+ private let card = MaterialCardView(radius: 10)
+ private let glyph = NSImageView()
+ private let field = NSTextField()
+ private let count = NSTextField.sidebarLabel(size: 11)
+ private var buttons: [ClosureButton] = []
+ private var lastQuery = ""
+ private var lastFocusToken = 0
+ private var wasVisible = false
+
+ init(overlay: OverlayState, onFind: @escaping (String, Bool) -> Void, onClose: @escaping () -> Void) {
+ self.overlay = overlay
+ self.onFind = onFind
+ self.onClose = onClose
+ super.init(frame: .zero)
+ addSubview(card)
+ glyph.image = SidebarSymbols.image("magnifyingglass", size: 13)
+ glyph.contentTintColor = .secondaryLabelColor
+ glyph.imageScaling = .scaleNone
+ addSubview(glyph)
+ field.isBordered = false
+ field.drawsBackground = false
+ field.focusRingType = .none
+ field.font = .systemFont(ofSize: 13)
+ field.placeholderString = "Find in page"
+ field.usesSingleLineMode = true
+ field.cell?.isScrollable = true
+ field.delegate = self
+ addSubview(field)
+ count.font = .monospacedDigitSystemFont(ofSize: 11, weight: .regular)
+ count.textColor = .secondaryLabelColor
+ addSubview(count)
+ for (symbol, run) in [("chevron.up", { [weak self] in self.map { $0.onFind($0.overlay.findQuery, false) } }),
+ ("chevron.down", { [weak self] in self.map { $0.onFind($0.overlay.findQuery, true) } }),
+ ("xmark", { [weak self] in self?.onClose() })] as [(String, () -> Void)] {
+ let b = ClosureButton(symbol: symbol, size: 13, onPress: run)
+ buttons.append(b)
+ addSubview(b)
}
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ private func observe() {
+ let (visible, query, matches, active, token) = withObservationTracking {
+ (overlay.findVisible, overlay.findQuery, overlay.findMatchCount, overlay.findActiveMatch, overlay.findFocusToken)
+ } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ for v in subviews { v.isHidden = !visible }
+ if field.stringValue != query { field.stringValue = query }
+ // Like SwiftUI's .onChange on the query: every change, typed or set, searches.
+ if visible, query != lastQuery { onFind(query, true) }
+ lastQuery = query
+ if let matches, !query.isEmpty {
+ count.stringValue = "\(matches == 0 ? 0 : active)/\(matches)"
+ count.isHidden = !visible
+ } else {
+ count.stringValue = ""
+ count.isHidden = true
+ }
+ if visible, !wasVisible || token != lastFocusToken { window?.makeFirstResponder(field) }
+ wasVisible = visible
+ lastFocusToken = token
+ needsLayout = true
+ }
+
+ override func viewDidMoveToWindow() {
+ super.viewDidMoveToWindow()
+ if overlay.findVisible { window?.makeFirstResponder(field) }
+ }
+
+ func controlTextDidChange(_ obj: Notification) {
+ overlay.findQuery = field.stringValue
+ }
+
+ func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
+ switch selector {
+ case #selector(NSResponder.insertNewline(_:)):
+ onFind(overlay.findQuery, !(NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false))
+ return true
+ case #selector(NSResponder.cancelOperation(_:)):
+ onClose()
+ return true
+ default:
+ return false
+ }
+ }
+
+ override func layout() {
+ super.layout()
+ card.frame = bounds
+ let h = bounds.height
+ // padding 10, glyph, 6, field (flexible), 6, count, 6, ▲, 6, ▼, 6, ✕, padding 10.
+ var x = bounds.width - 10
+ for b in buttons.reversed() {
+ let s = b.image?.size ?? .zero
+ b.frame = NSRect(x: x - s.width, y: (h - s.height) / 2, width: s.width, height: s.height)
+ x -= s.width + 6
+ }
+ if !count.isHidden {
+ let w = ceil(count.attributedStringValue.size().width)
+ count.frame = NSRect(x: x - w - SidebarText.inset, y: (h - 14) / 2, width: w + 2 * SidebarText.inset, height: 14)
+ x -= w + 6
+ }
+ let gw = glyph.image?.size.width ?? 14
+ glyph.frame = NSRect(x: 10, y: 0, width: gw, height: h)
+ let fx = 10 + gw + 6
+ let fh = ceil(field.intrinsicContentSize.height)
+ field.frame = NSRect(x: fx - SidebarText.inset, y: (h - fh) / 2, width: max(0, x - fx + 2 * SidebarText.inset), height: fh)
}
}
@@ -101,52 +215,121 @@ final class FindBarPanel: NSPanel {
}
}
-struct ToastStack: View {
- let overlay: OverlayState
- let onDismiss: (UInt32) -> Void
- var body: some View {
- VStack(alignment: .trailing, spacing: 6) {
- ForEach(overlay.toasts) { t in
- HStack(spacing: 10) {
- Image(systemName: t.state == 1 ? "checkmark.circle.fill" : (t.state == 0 ? "arrow.down.circle" : "exclamationmark.circle"))
- .foregroundStyle(t.state == 1 ? .green : .secondary)
- VStack(alignment: .leading, spacing: 2) {
- Text(t.name).font(.system(size: 12, weight: .medium)).lineLimit(1)
- if t.state == 0 {
- ProgressView(value: Double(max(0, t.percent)), total: 100).controlSize(.small)
- } else {
- Text(t.state == 1 ? "Downloaded" : (t.state == 2 ? "Cancelled" : "Failed")).font(.system(size: 11)).foregroundStyle(.secondary)
- }
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- if t.state == 1 {
- Button("Show") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: t.path)]) }
- .controlSize(.small)
- }
- // Hides the toast only; the download carries on (the Library still has it).
- Button { onDismiss(t.id) } label: {
- Image(systemName: "xmark").font(.system(size: 9, weight: .semibold)).foregroundStyle(.secondary)
- .frame(width: 16, height: 16).contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- }
- .padding(10)
- .frame(width: 300)
- .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Color.primary.opacity(0.1)))
- }
+/// Download toasts, bottom trailing over the page, newest at the bottom.
+final class ToastStackView: NSView {
+ private let overlay: OverlayState
+ private let onDismiss: (UInt32) -> Void
+ private var rows: [UInt32: ToastRowView] = [:]
+ private var order: [UInt32] = []
+
+ static let rowSize = NSSize(width: 300, height: 52)
+
+ init(overlay: OverlayState, onDismiss: @escaping (UInt32) -> Void) {
+ self.overlay = overlay
+ self.onDismiss = onDismiss
+ super.init(frame: .zero)
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ private func observe() {
+ let toasts = withObservationTracking { overlay.toasts } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ let ids = Set(toasts.map(\.id))
+ for (id, r) in rows where !ids.contains(id) { r.removeFromSuperview(); rows[id] = nil }
+ for t in toasts {
+ let r = rows[t.id] ?? {
+ let r = ToastRowView { [weak self] in self?.onDismiss(t.id) }
+ rows[t.id] = r
+ addSubview(r)
+ return r
+ }()
+ r.show(t)
+ }
+ order = toasts.map(\.id)
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ // VStack(spacing: 6) inside padding 10, pinned bottom trailing.
+ var y: CGFloat = 10
+ for id in order.reversed() {
+ guard let r = rows[id] else { continue }
+ r.frame = NSRect(x: bounds.width - 10 - Self.rowSize.width, y: y, width: Self.rowSize.width, height: Self.rowSize.height)
+ y += Self.rowSize.height + 6
}
- .padding(10)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
}
}
-/// Arc shows a faint, slightly lighter card over the gradient when no tab is selected.
-struct EmptyContentView: View {
- let space: Space
- var body: some View {
- // Fill under the titlebar too: the safe-area edge otherwise cuts through the toolbar.
- (space.theme.palette.isDark ? Color.white.opacity(0.04) : Color.black.opacity(0.03))
- .ignoresSafeArea()
+private final class ToastRowView: NSView {
+ private let card = MaterialCardView(radius: 10)
+ private let icon = NSImageView()
+ private let name = NSTextField.sidebarLabel(size: 12, weight: .medium)
+ private let detail = NSTextField.sidebarLabel(size: 11)
+ private let progress = NSProgressIndicator()
+ private let show = ClosureButton(title: "Show", controlSize: .small) {}
+ private let close: ClosureButton
+ private var path = ""
+
+ init(onDismiss: @escaping () -> Void) {
+ // Hides the toast only; the download carries on (the Library still has it).
+ close = ClosureButton(symbol: "xmark", size: 9, weight: .semibold, tint: .secondaryLabelColor, onPress: onDismiss)
+ super.init(frame: .zero)
+ addSubview(card)
+ icon.imageScaling = .scaleNone
+ addSubview(icon)
+ addSubview(name)
+ detail.textColor = .secondaryLabelColor
+ addSubview(detail)
+ progress.style = .bar
+ progress.controlSize = .small
+ progress.isIndeterminate = false
+ progress.minValue = 0
+ progress.maxValue = 100
+ addSubview(progress)
+ show.onPress = { [weak self] in
+ guard let self else { return }
+ NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: self.path)])
+ }
+ addSubview(show)
+ addSubview(close)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func show(_ t: DownloadToast) {
+ path = t.path
+ icon.image = SidebarSymbols.image(t.state == 1 ? "checkmark.circle.fill" : (t.state == 0 ? "arrow.down.circle" : "exclamationmark.circle"), size: 13)
+ icon.contentTintColor = t.state == 1 ? .systemGreen : .secondaryLabelColor
+ name.stringValue = t.name
+ progress.isHidden = t.state != 0
+ progress.doubleValue = Double(max(0, t.percent))
+ detail.isHidden = t.state == 0
+ detail.stringValue = t.state == 1 ? "Downloaded" : (t.state == 2 ? "Cancelled" : "Failed")
+ show.isHidden = t.state != 1
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ card.frame = bounds
+ let h = bounds.height
+ // padding 10: icon, 10, name over status (flexible), 10, Show, 10, ✕ 16×16, padding 10.
+ var x = bounds.width - 10 - 16
+ close.frame = NSRect(x: x, y: (h - 16) / 2, width: 16, height: 16)
+ if !show.isHidden {
+ let s = show.fittingSize
+ x -= 10 + s.width
+ show.frame = NSRect(x: x, y: (h - s.height) / 2, width: s.width, height: s.height)
+ }
+ let iw = icon.image?.size.width ?? 15
+ icon.frame = NSRect(x: 10, y: 0, width: iw, height: h)
+ let tx = 10 + iw + 10, tw = max(0, x - 10 - tx)
+ name.frame = NSRect(x: tx - SidebarText.inset, y: h / 2 + 1, width: tw + 2 * SidebarText.inset, height: 15)
+ detail.frame = NSRect(x: tx - SidebarText.inset, y: h / 2 - 15, width: tw + 2 * SidebarText.inset, height: 14)
+ progress.frame = NSRect(x: tx, y: h / 2 - 11, width: tw, height: 6)
}
}
diff --git a/Sources/Cra/UI/PaneToolbarView.swift b/Sources/Cra/UI/PaneToolbarView.swift
new file mode 100644
index 0000000..b4ddb18
--- /dev/null
+++ b/Sources/Cra/UI/PaneToolbarView.swift
@@ -0,0 +1,544 @@
+import AppKit
+import SwiftUI
+
+/// Arc's toolbar above the page, in AppKit: nav buttons, the friendly URL (or the full URL in
+/// developer mode), extensions and Split View. With no tab it carries the nav buttons and a
+/// centred "Search or Enter URL…" placeholder; an empty split pane shows only that.
+///
+/// One bar per pane card. A tab switch points the same bar at another tab; the bar reads the
+/// store inside an observation scope and changes only the views whose state changed, so a
+/// button under the pointer keeps its hover.
+@MainActor
+final class PaneToolbarView: NSView {
+ /// Split view: the pane's tab (nil = the window's selected tab).
+ var paneTabID: UUID? { didSet { if paneTabID != oldValue { sync() } } }
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let actions: SidebarActions
+
+ private struct Model: Equatable {
+ enum Kind: Equatable { case noTab, emptyPane, normal, developer }
+ struct Ext: Equatable { let id: String; let name: String; let icon: NSImage? }
+ var kind = Kind.noTab
+ var inSplit = false
+ var focusedPane = true
+ var canGoBack = false
+ var canGoForward = false
+ var isLoading = false
+ var url = ""
+ var host = ""
+ var path = ""
+ var status: ToolbarStatus?
+ var sidebarVisible = true
+ var pinned: [Ext] = []
+ var hasExtensions = false
+ var fill = NSColor.clear
+ var fg = NSColor.labelColor
+ var fgDim = NSColor.secondaryLabelColor
+ var placeholder = NSColor.tertiaryLabelColor
+ var closeTint = NSColor.secondaryLabelColor
+ var hairline: NSColor?
+ var dividerColor = NSColor.clear
+ }
+
+ private var model = Model()
+ private var syncQueued = false
+ private var buttons: [String: ToolbarGlyphButton] = [:]
+ /// Left group, then trailing items, as laid out.
+ private var left: [ToolbarGlyphButton] = []
+ private var right: [NSView] = []
+ private let urlButton = ToolbarURLButton()
+ private let placeholderLabel = NSTextField.sidebarLabel(size: 13)
+ private let hairline = NSView()
+ private let devDivider = NSView()
+ private var press: NSEvent?
+
+ init(paneTabID: UUID?, store: SidebarStore, ui: SidebarUIState, actions: SidebarActions) {
+ self.paneTabID = paneTabID
+ self.store = store
+ self.ui = ui
+ self.actions = actions
+ super.init(frame: .zero)
+ wantsLayer = true
+ hairline.wantsLayer = true
+ devDivider.wantsLayer = true
+ placeholderLabel.stringValue = "Search or Enter URL…"
+ urlButton.action = { [weak self] in self?.editURL() }
+ for v in [hairline, devDivider, urlButton, placeholderLabel] as [NSView] {
+ v.isHidden = true
+ addSubview(v)
+ }
+ sync()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ // MARK: Model
+
+ private func scheduleSync() {
+ guard !syncQueued else { return }
+ syncQueued = true
+ DispatchQueue.main.async { [weak self] in self?.sync() }
+ }
+
+ private func sync() {
+ syncQueued = false
+ let m = withObservationTracking { build() } onChange: { [weak self] in
+ Task { @MainActor in self?.scheduleSync() }
+ }
+ guard m != model else { return }
+ let old = model
+ model = m
+ apply(old: old)
+ }
+
+ private func build() -> Model {
+ var m = Model()
+ let palette = store.focusedSpace(window: ui.windowID).theme.palette
+ let item = paneTabID.flatMap { store.item($0) } ?? (paneTabID == nil ? store.selectedTab(window: ui.windowID) : nil)
+ m.inSplit = paneTabID != nil && ui.splitPaneIDs.count > 1
+ m.focusedPane = paneTabID == nil || store.selectedTabID(window: ui.windowID) == paneTabID
+ let nav = paneTabID.map { ui.navState(for: $0) }
+ ?? TabNavState(canGoBack: ui.canGoBack, canGoForward: ui.canGoForward, isLoading: ui.isLoading, themeColor: ui.pageThemeColor)
+ m.canGoBack = nav.canGoBack
+ m.canGoForward = nav.canGoForward
+ m.isLoading = nav.isLoading
+ m.status = m.focusedPane ? ui.toolbarStatus : nil
+ m.sidebarVisible = store.window(ui.windowID).sidebarVisible
+ if let item, item.isEmptyTab {
+ m.kind = .emptyPane
+ } else if let t = item?.tab {
+ m.kind = !m.inSplit && store.settings.isDeveloperMode(url: t.url) ? .developer : .normal
+ m.url = t.url
+ let human = SuggestionEngine.humanURL(t.url)
+ m.host = AppSettings.siteKey(for: t.url) ?? human
+ m.path = human.hasPrefix(m.host) ? String(human.dropFirst(m.host.count)) : ""
+ }
+ let extensions = ExtensionStore.shared
+ m.hasExtensions = !extensions.entries.isEmpty
+ m.pinned = extensions.pinnedIDs.compactMap { id in
+ extensions.entries.first { $0.extensionID == id }.map { Model.Ext(id: id, name: $0.name, icon: extensions.toolbarIcon(for: $0)) }
+ }
+ // Arc's toolbar colour: the page's theme-color when it declares one, else white until the
+ // page reports one (MainWindowController.browserManagerDidUpdate uses the same rule).
+ let onCard = m.kind == .normal || m.kind == .developer
+ let theme = nav.themeColor
+ let cardHex = theme != "none" && !theme.isEmpty && HexColor.components(theme) != nil ? theme : nil
+ let light = (cardHex.flatMap(HexColor.luminance) ?? 1) > 0.6
+ if onCard {
+ m.fill = cardHex.map { NSColor(hex: $0) } ?? .white
+ m.fg = light ? NSColor.black.withAlphaComponent(0.8) : NSColor(hex: "#E4E0D4")
+ m.fgDim = light ? NSColor.black.withAlphaComponent(0.6) : NSColor(hex: "#F0E6CC").withAlphaComponent(0.9)
+ } else {
+ m.fill = m.kind == .emptyPane ? .clear : (palette.isDark ? NSColor.white.withAlphaComponent(0.025) : NSColor.black.withAlphaComponent(0.03))
+ m.fg = NSColor(palette.textSecondary)
+ m.fgDim = NSColor(palette.textTertiary)
+ // No hairline under the bar on the card: the bar and the page read as one surface (Arc draws one).
+ if m.kind != .emptyPane { m.hairline = palette.isDark ? NSColor.white.withAlphaComponent(0.07) : NSColor.black.withAlphaComponent(0.07) }
+ }
+ m.placeholder = NSColor(palette.textTertiary)
+ m.closeTint = m.kind == .emptyPane ? NSColor(palette.textSecondary) : m.fgDim
+ m.dividerColor = light ? NSColor.black.withAlphaComponent(0.15) : NSColor.white.withAlphaComponent(0.22)
+ return m
+ }
+
+ // MARK: Views
+
+ private func button(_ key: String, _ make: () -> ToolbarGlyphButton) -> ToolbarGlyphButton {
+ if let b = buttons[key] { return b }
+ let b = make()
+ buttons[key] = b
+ addSubview(b)
+ return b
+ }
+
+ private func glyph(_ key: String, _ symbol: String, help: String, enabled: Bool = true, width: CGFloat = 26, iconSize: CGFloat = 13,
+ tint: NSColor? = nil, action: @escaping (PaneToolbarView) -> Void) -> ToolbarGlyphButton {
+ let b = button(key) { ToolbarGlyphButton() }
+ b.configure(symbol: symbol, image: nil, help: help, enabled: enabled, width: width, iconSize: iconSize, tint: tint ?? model.fgDim)
+ b.action = { [weak self] in if let self { action(self) } }
+ return b
+ }
+
+ private func apply(old: Model) {
+ let m = model
+ layer?.backgroundColor = m.fill.cgColor
+ hairline.isHidden = m.hairline == nil
+ hairline.layer?.backgroundColor = m.hairline?.cgColor
+ var l: [ToolbarGlyphButton] = []
+ var r: [NSView] = []
+ let toggle = { self.glyph("toggle", "sidebar.left", help: m.sidebarVisible ? "Hide Sidebar (⌘S)" : "Show Sidebar (⌘S)",
+ width: 37, iconSize: 15.5) { $0.actions.toggleSidebar() } }
+ switch m.kind {
+ case .noTab:
+ l = [toggle(),
+ glyph("back", "arrow.left", help: "", enabled: false, width: 37, iconSize: 15) { _ in },
+ glyph("forward", "arrow.right", help: "", enabled: false, width: 37, iconSize: 15) { _ in },
+ glyph("reload", "arrow.clockwise", help: "", enabled: false, width: 37, iconSize: 15) { _ in }]
+ case .emptyPane:
+ l = [glyph("back", "arrow.left", help: "", enabled: false, width: 37, iconSize: 15) { _ in },
+ glyph("forward", "arrow.right", help: "", enabled: false, width: 37, iconSize: 15) { _ in }]
+ case .normal:
+ // Toggle first, centred 30 pt from the card edge (Arc, sidebar hidden), then ← → ↻ at 37 pt
+ // pitch. Split panes drop the toggle and refresh (Arc 1.170: only ← → in a pane).
+ if !m.inSplit { l.append(toggle()) }
+ l.append(glyph("back", "arrow.left", help: "Go Back (⌘[)", enabled: m.canGoBack, width: 37, iconSize: 15) { $0.navigate("goBack") })
+ l.append(glyph("forward", "arrow.right", help: "Go Forward (⌘])", enabled: m.canGoForward, width: 37, iconSize: 15) { $0.navigate("goForward") })
+ if !m.inSplit {
+ l.append(glyph("reload", m.isLoading ? "xmark" : "arrow.clockwise", help: "Refresh (⌘R)", width: 37, iconSize: 15) { $0.navigate("reload") })
+ }
+ case .developer:
+ if !m.inSplit { l.append(toggle()) }
+ r.append(glyph("copy", "link", help: "Copy URL (⇧⌘C)") { $0.actions.performAction("copyURL") })
+ r.append(devDivider)
+ r.append(glyph("devtools", "terminal", help: "Developer Tools (⌥⌘I)") { $0.actions.performAction("devTools") })
+ }
+ // Arc's right end of the bar: pinned extensions, the Extensions button, then Split View;
+ // also on the no-tab bar. A split pane has its options (focused pane only) and close.
+ if !m.inSplit, m.kind != .emptyPane {
+ for e in m.pinned {
+ let b = button("ext:" + e.id) { ToolbarGlyphButton() }
+ b.configure(symbol: nil, image: e.icon, help: e.name, enabled: true, width: 34, iconSize: 18, tint: m.fgDim)
+ let id = e.id
+ b.action = { [weak self] in self?.actions.runExtension(id) }
+ b.menuProvider = { ExtensionStore.shared.entries.first { $0.extensionID == id }.map(ExtensionsMenu.iconMenu) }
+ r.append(b)
+ }
+ if m.hasExtensions {
+ r.append(glyph("extensions", "slider.horizontal.2.square", help: "Extensions", width: 34, iconSize: 16) { $0.actions.showExtensionsMenu() })
+ }
+ r.append(glyph("split", "square.split.2x1", help: "Add Split View (⌃⇧=)", width: 34, iconSize: 16) { $0.actions.performAction("addSplitView") })
+ }
+ if m.inSplit, let id = paneTabID {
+ if m.focusedPane, m.kind != .emptyPane {
+ r.append(glyph("splitOptions", "rectangle.split.2x1", help: "Split View Options") { $0.showSplitMenu(from: $0.buttons["splitOptions"]) })
+ }
+ r.append(glyph("close", "xmark", help: "Close this Split Pane (⌃⇧-)", width: 30, iconSize: 14, tint: m.closeTint) { $0.actions.closePane(id) })
+ }
+ devDivider.layer?.backgroundColor = m.dividerColor.cgColor
+ let used = Set((l as [NSView] + r).map(ObjectIdentifier.init))
+ for (k, b) in buttons where !used.contains(ObjectIdentifier(b)) {
+ b.removeFromSuperview()
+ buttons[k] = nil
+ }
+ devDivider.isHidden = !r.contains { $0 === devDivider }
+ left = l
+ right = r
+
+ switch m.kind {
+ case .normal, .developer:
+ urlButton.isHidden = false
+ placeholderLabel.isHidden = true
+ urlButton.show(host: m.host, path: m.path, url: m.url, developer: m.kind == .developer, status: m.status,
+ fg: m.fg, fgDim: m.fgDim, animated: old.status?.id != m.status?.id && window != nil)
+ case .noTab, .emptyPane:
+ urlButton.isHidden = true
+ placeholderLabel.isHidden = false
+ placeholderLabel.textColor = m.placeholder
+ }
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ let h = bounds.height, w = bounds.width
+ let m = model
+ hairline.frame = NSRect(x: 0, y: h - 1, width: w, height: 1)
+ // Left group: icons edge to edge.
+ var x: CGFloat = m.kind == .emptyPane ? 1 : (m.inSplit ? 2.5 : 11.5)
+ for b in left {
+ b.frame = NSRect(x: x, y: (h - 26) / 2, width: b.width, height: 26)
+ x += b.width
+ }
+ let leftEnd = left.isEmpty ? 0 : x
+ // Right group, from the trailing edge: pinned extensions … Split View 6 pt in; a split pane's
+ // close 4 pt in; developer copy · divider · DevTools spaced like the HStack around them.
+ var rx = w - (m.inSplit ? 4 : (right.isEmpty ? 0 : 6))
+ var trailing = right
+ var devGroup: [NSView] = []
+ if m.kind == .developer, let i = trailing.firstIndex(where: { $0 === devDivider }) {
+ devGroup = Array(trailing[(i - 1)...(i + 1)])
+ trailing.removeSubrange((i - 1)...(i + 1))
+ }
+ for v in trailing.reversed() {
+ let bw = (v as? ToolbarGlyphButton)?.width ?? 26
+ rx -= bw
+ v.frame = NSRect(x: rx, y: (h - 26) / 2, width: bw, height: 26)
+ }
+ if !devGroup.isEmpty {
+ if !trailing.isEmpty { rx -= 6 }
+ for v in devGroup.reversed() {
+ if v === devDivider {
+ rx -= 6 + 5 + 1
+ v.frame = NSRect(x: rx, y: (h - 14) / 2, width: 1, height: 14)
+ rx -= 5 + 6
+ } else {
+ rx -= 26
+ v.frame = NSRect(x: rx, y: (h - 26) / 2, width: 26, height: 26)
+ }
+ }
+ }
+ let rightStart = rx
+ // The middle, between the groups with the HStack's 6 pt spacing around it.
+ let a = leftEnd + (left.isEmpty ? 0 : 6), b = rightStart - (right.isEmpty ? 0 : 6)
+ switch m.kind {
+ case .normal:
+ // Spacer(min 8) either side, the URL centred between them.
+ let room = max(0, b - a - 2 * (8 + 6))
+ let uw = min(urlButton.idealWidth, room)
+ let ux = a + (b - a - uw) / 2
+ urlButton.frame = NSRect(x: ux, y: (h - 28) / 2, width: uw, height: 28)
+ case .developer:
+ // The URL fills half the room after its 8 pt lead; a Spacer(min 8) takes the rest.
+ let start = a + 8
+ let room = max(0, b - start - 6 - 8)
+ urlButton.frame = NSRect(x: start, y: (h - 28) / 2, width: room / 2 + 8, height: 28)
+ case .noTab, .emptyPane:
+ let s = placeholderLabel.intrinsicContentSize
+ let pw = min(ceil(placeholderLabel.attributedStringValue.size().width), max(0, b - a))
+ placeholderLabel.frame = NSRect(x: a + (b - a - pw) / 2 - SidebarText.inset, y: (h - s.height) / 2,
+ width: pw + 2 * SidebarText.inset, height: s.height)
+ }
+ }
+
+ // MARK: Actions
+
+ private func navigate(_ what: String) {
+ if let id = paneTabID { actions.paneNavigate(id, what); return }
+ switch what {
+ case "goBack": actions.goBack()
+ case "goForward": actions.goForward()
+ default: actions.reload()
+ }
+ }
+
+ private func editURL() {
+ if let id = paneTabID { actions.editPaneURL(id) } else { actions.openCommandBar(model.kind == .noTab ? .newTab : .editURL) }
+ }
+
+ private func showSplitMenu(from view: NSView?) {
+ guard let id = paneTabID, let view else { return }
+ let menu = NSMenu()
+ let items: [(String, () -> Void)?] = [
+ ("Separate Tab from Split", { [weak self] in self?.actions.separatePane(id) }),
+ ("Flip Split View Orientation", { [weak self] in self?.actions.performAction("flipSplitOrientation") }),
+ nil,
+ ("Copy Link", { [weak self] in self?.actions.performAction("copyURL") }),
+ nil,
+ ("Close this Split Pane", { [weak self] in self?.actions.closePane(id) }),
+ ]
+ for entry in items {
+ guard let (title, run) = entry else { menu.addItem(.separator()); continue }
+ menu.addItem(ToolbarMenuAction.item(title, run))
+ }
+ menu.popUp(positioning: nil, at: NSPoint(x: 0, y: view.bounds.height + 4), in: view)
+ }
+
+ // A click anywhere on the bar edits the URL (a pane's click also focuses it); a drag moves
+ // the window, as on Arc's toolbar.
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func mouseDown(with event: NSEvent) { press = event }
+ override func mouseDragged(with event: NSEvent) {
+ guard let p = press else { return }
+ if hypot(event.locationInWindow.x - p.locationInWindow.x, event.locationInWindow.y - p.locationInWindow.y) > 3 {
+ press = nil
+ window?.performDrag(with: p)
+ }
+ }
+ override func mouseUp(with event: NSEvent) {
+ guard press != nil else { return }
+ press = nil
+ editURL()
+ }
+}
+
+private final class ToolbarMenuAction: NSObject {
+ let run: () -> Void
+ init(_ run: @escaping () -> Void) { self.run = run }
+ @objc func fire() { run() }
+
+ static func item(_ title: String, _ run: @escaping () -> Void) -> NSMenuItem {
+ let a = ToolbarMenuAction(run)
+ let item = NSMenuItem(title: title, action: #selector(fire), keyEquivalent: "")
+ item.target = a
+ item.representedObject = a
+ return item
+ }
+}
+
+/// ToolbarIcon / ToolbarImageButton: a glyph (or an extension's icon) with a rounded hover fill.
+final class ToolbarGlyphButton: NSView {
+ var action: () -> Void = {}
+ /// Right-click menu (a pinned extension's icon options).
+ var menuProvider: (() -> NSMenu?)?
+ private(set) var width: CGFloat = 26
+ private let imageView = NSImageView()
+ private var tip: ArcTooltipAnchorView?
+ private var enabled = true
+ private var hovering = false { didSet { if hovering != oldValue { refreshFill() } } }
+ private var shown: (String?, NSImage?, CGFloat, NSColor, Bool)?
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerRadius = 7
+ layer?.cornerCurve = .continuous
+ imageView.imageScaling = .scaleNone
+ addSubview(imageView)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func configure(symbol: String?, image: NSImage?, help: String, enabled: Bool, width: CGFloat, iconSize: CGFloat, tint: NSColor) {
+ self.width = width
+ self.enabled = enabled
+ if shown == nil || shown!.0 != symbol || shown!.1 !== image || shown!.2 != iconSize || shown!.3 != tint || shown!.4 != enabled {
+ shown = (symbol, image, iconSize, tint, enabled)
+ if let symbol {
+ imageView.imageScaling = .scaleNone
+ imageView.image = SidebarSymbols.image(symbol, size: iconSize)
+ imageView.contentTintColor = enabled ? tint : tint.withAlphaComponent(tint.alphaComponent * 0.4)
+ } else {
+ imageView.imageScaling = .scaleProportionallyUpOrDown
+ imageView.image = image ?? SidebarSymbols.image("puzzlepiece.extension", size: iconSize)
+ // A monochrome extension icon (ExtensionStore.toolbarIcon) is a template: the bar's ink.
+ imageView.contentTintColor = image == nil || image?.isTemplate == true ? tint : nil
+ }
+ }
+ let iconBox = symbol == nil ? NSSize(width: iconSize, height: iconSize) : nil
+ imageView.frame = iconBox.map { NSRect(x: (width - $0.width) / 2, y: (26 - $0.height) / 2, width: $0.width, height: $0.height) }
+ ?? NSRect(x: 0, y: 0, width: width, height: 26)
+ if help.isEmpty {
+ tip?.removeFromSuperview()
+ tip = nil
+ } else if let tip {
+ (tip.text, tip.keys) = ArcTooltipLabel.split(help)
+ } else {
+ tip = ArcTooltipAnchorView.attach(to: self, help: help)
+ }
+ refreshFill()
+ }
+
+ private func refreshFill() {
+ layer?.backgroundColor = (hovering && enabled ? NSColor.white.withAlphaComponent(0.1) : .clear).cgColor
+ }
+
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if enabled, bounds.contains(convert(event.locationInWindow, from: nil)) { action() }
+ }
+ override func menu(for event: NSEvent) -> NSMenu? { menuProvider?() }
+}
+
+/// The URL in the middle of the bar: link glyph, host bright and path dimmer (the full URL in
+/// monospace after a lock in developer mode), or the nav-bar status in its place.
+final class ToolbarURLButton: NSView {
+ var action: () -> Void = {}
+ private let content = NSView()
+ private let icon = NSImageView()
+ private let label = NSTextField.sidebarLabel(size: 13)
+ private let tip: ArcTooltipAnchorView
+ private var developer = false
+ private var hovering = false { didSet { refreshFill() } }
+
+ override init(frame: NSRect) {
+ tip = ArcTooltipAnchorView(frame: .zero)
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerCurve = .continuous
+ icon.imageScaling = .scaleNone
+ content.wantsLayer = true
+ content.addSubview(icon)
+ content.addSubview(label)
+ addSubview(content)
+ tip.followsCursor = true
+ tip.frame = bounds
+ tip.autoresizingMask = [.width, .height]
+ addSubview(tip)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ /// The text's natural width plus padding; the bar centres and clips the button to it.
+ var idealWidth: CGFloat {
+ ceil(10 + iconWidth + 7 + label.attributedStringValue.size().width + 10)
+ }
+
+ /// The glyph's own width, as SwiftUI lays an Image out; developer mode boxes it at 14 pt.
+ private var iconWidth: CGFloat { developer ? 14 : ceil(icon.image?.size.width ?? 12) }
+
+ func show(host: String, path: String, url: String, developer: Bool, status: ToolbarStatus?, fg: NSColor, fgDim: NSColor, animated: Bool) {
+ self.developer = developer
+ tip.text = url
+ if animated {
+ // SwiftUI's .transition(.opacity) on the status swap.
+ let fade = CATransition()
+ fade.type = .fade
+ fade.duration = 0.15
+ content.layer?.add(fade, forKey: "fade")
+ }
+ if let status {
+ icon.image = SidebarSymbols.image(status.symbol, size: 12, weight: .medium)
+ icon.contentTintColor = fgDim
+ label.attributedStringValue = NSAttributedString(string: status.text, attributes: [.font: NSFont.systemFont(ofSize: 13), .foregroundColor: fgDim])
+ } else if developer {
+ icon.image = SidebarSymbols.image(url.hasPrefix("https://") ? "lock.fill" : "globe", size: 11, weight: .semibold)
+ icon.contentTintColor = fgDim
+ label.attributedStringValue = NSAttributedString(string: url, attributes: [.font: NSFont.monospacedSystemFont(ofSize: 12, weight: .regular), .foregroundColor: fg])
+ } else {
+ icon.image = SidebarSymbols.image("link", size: 12, weight: .medium)
+ icon.contentTintColor = fgDim
+ let s = NSMutableAttributedString(string: host, attributes: [.font: NSFont.systemFont(ofSize: 13), .foregroundColor: fg])
+ s.append(NSAttributedString(string: path, attributes: [.font: NSFont.systemFont(ofSize: 13), .foregroundColor: fgDim]))
+ label.attributedStringValue = s
+ }
+ label.lineBreakMode = .byTruncatingTail
+ layer?.cornerRadius = developer ? 6 : 7
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ content.frame = bounds
+ let h = bounds.height
+ let pad: CGFloat = developer ? 6 : 10
+ let iconW = iconWidth
+ let gap: CGFloat = developer ? 12 : 7
+ icon.frame = NSRect(x: pad, y: 0, width: iconW, height: h)
+ let lh = label.intrinsicContentSize.height
+ let lx = pad + iconW + gap
+ label.frame = NSRect(x: lx - SidebarText.inset, y: (h - lh) / 2, width: max(0, bounds.width - lx - pad) + 2 * SidebarText.inset, height: lh)
+ }
+
+ private func refreshFill() {
+ layer?.backgroundColor = (hovering ? NSColor.white.withAlphaComponent(0.08) : .clear).cgColor
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { action() }
+ }
+}
diff --git a/Sources/Cra/UI/Settings/AdvancedPane.swift b/Sources/Cra/UI/Settings/AdvancedPane.swift
index d2d420d..dcd487d 100644
--- a/Sources/Cra/UI/Settings/AdvancedPane.swift
+++ b/Sources/Cra/UI/Settings/AdvancedPane.swift
@@ -30,6 +30,7 @@ struct AdvancedPane: View {
}
.labelsHidden()
.fixedSize()
+ SettingsCheckbox(title: "Show search suggestions", isOn: $store.settings.searchSuggestions)
}
SettingsFormRow(label: "When quitting Cra:") {
SettingsCheckbox(title: "Warn before quitting", isOn: $store.settings.warnBeforeQuitting)
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index a3fcbcc..cb14f8d 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -22,8 +22,8 @@ final class ShellView: NSView {
var usesBackdropLayer: Bool { vibrantLight && !vibrantDark && backdropLayer != nil }
/// Lifts the dark blur toward Arc's mid-grey base before the gradient goes on.
let vibrancyLift = NSView()
- let backgroundHost: NSHostingView<SpaceBackground>
- let sidebarHost: SidebarHostingView
+ let backgroundHost: NSView
+ let sidebarHost: NSView
let resizeHandle = ResizeHandleView()
/// The content area (card minus nothing): holds the pane cards and handles.
let contentContainer = NSView()
@@ -53,7 +53,7 @@ final class ShellView: NSView {
var onPaneResizeEnded: (([UUID: CGFloat]) -> Void)?
var onPaneResizeBegan: (() -> Void)?
/// Builds a pane's toolbar (the window controller owns the environment).
- var makeToolbar: ((UUID?) -> AnyView)?
+ var makeToolbar: ((UUID?) -> NSView)?
/// Where the status bubble, toasts and find bar live (the content container, or an
/// overlay panel's content view when pages are separate windows).
private(set) var overlayParent: NSView
@@ -61,10 +61,11 @@ final class ShellView: NSView {
private var animatingFrames = false
/// Set while panes animate open/closed; layout() keeps their frames.
private var animatingPanes = false
- let placeholderHost: NSHostingView<AnyView>
- let statusHost: NSHostingView<AnyView>
- let toastHost: NSHostingView<AnyView>
- let findHost: NSHostingView<AnyView>
+ /// Arc's faint card over the gradient while no tab is selected.
+ let placeholderHost = NSView()
+ let statusHost: NSView
+ let toastHost: NSView
+ let findHost: NSView
/// Stand-in pane id for the no-tab state (toolbar on the gradient, no card).
static let noTabID = UUID(uuidString: "00000000-0000-0000-0000-000000000001")!
@@ -140,13 +141,12 @@ final class ShellView: NSView {
var toastCount = 0
private var trackingArea: NSTrackingArea?
- init(frame: NSRect, background: SpaceBackground, sidebar: AnyView, toolbar: AnyView, placeholder: AnyView, status: AnyView, toasts: AnyView, find: AnyView) {
- backgroundHost = NSHostingView(rootView: background)
- sidebarHost = SidebarHostingView(rootView: sidebar)
- placeholderHost = NSHostingView(rootView: placeholder)
- statusHost = NSHostingView(rootView: status)
- toastHost = NSHostingView(rootView: toasts)
- findHost = NSHostingView(rootView: find)
+ init(frame: NSRect, background: NSView, sidebar: NSView, toolbar: NSView, status: NSView, toasts: NSView, find: NSView) {
+ backgroundHost = background
+ sidebarHost = sidebar
+ statusHost = status
+ toastHost = toasts
+ findHost = find
overlayParent = contentContainer
super.init(frame: frame)
wantsLayer = true
@@ -200,8 +200,7 @@ final class ShellView: NSView {
self.layoutSubtreeIfNeeded()
}
contentContainer.addSubview(placeholderHost)
- for h in [statusHost, toastHost, findHost] {
- h.sizingOptions = []
+ for h in [statusHost, toastHost, findHost] as [NSView] {
h.isHidden = true
contentContainer.addSubview(h)
}
@@ -212,7 +211,6 @@ final class ShellView: NSView {
contentContainer.addSubview(card)
paneCards = [card]
paneIDs = []
- sidebarHost.sizingOptions = []
sidebarHost.wantsLayer = true
sidebarHost.layer?.cornerCurve = .continuous
addSubview(sidebarHost)
@@ -230,8 +228,6 @@ final class ShellView: NSView {
return paneCards.first
}
func card(for id: UUID) -> PaneCardView? { paneCards.first { $0.tabID == id } }
- /// The focused pane's toolbar (compatibility with the single-pane shell).
- var toolbarHost: NSHostingView<AnyView>? { focusedCard?.toolbarHost }
/// The focused pane's page area; the parking view when there is none.
var webContainer: NSView { (hasTab ? focusedCard?.webArea : nil) ?? parkingView }
@@ -259,7 +255,7 @@ final class ShellView: NSView {
if paneCards.count == 1, shownIDs.count == 1, let card = paneCards.first,
(card.tabID == ShellView.noTabID) == (shownIDs[0] == ShellView.noTabID) {
let id = shownIDs[0]
- card.retarget(to: id, toolbar: makeToolbar?(id == ShellView.noTabID ? nil : id) ?? AnyView(EmptyView()))
+ card.retarget(to: id)
card.pageColor = pageColors[id]
card.toolbarColor = toolbarColors[id]
card.hasPage = id != ShellView.noTabID && !empty.contains(id)
@@ -273,7 +269,7 @@ final class ShellView: NSView {
if let existing = paneCards.first(where: { $0.tabID == id }) {
cards.append(existing)
} else {
- let card = PaneCardView(tabID: id, toolbar: makeToolbar?(id == ShellView.noTabID ? nil : id) ?? AnyView(EmptyView()))
+ let card = PaneCardView(tabID: id, toolbar: makeToolbar?(id == ShellView.noTabID ? nil : id) ?? NSView())
card.isDark = isDarkTheme
card.pageColor = pageColors[id]
card.toolbarColor = toolbarColors[id]
@@ -538,6 +534,9 @@ final class ShellView: NSView {
}
placeholderHost.frame = cb
placeholderHost.isHidden = hasTab
+ // The no-tab card is rounded like a page's (GitHub #6: a new window showed a square one).
+ placeholderHost.layer?.cornerRadius = cardCornerRadius
+ placeholderHost.layer?.cornerCurve = .continuous
parkingView.frame = cb
// DevTools docks inside the focused card, right of its page.
@@ -653,43 +652,6 @@ final class ShellView: NSView {
}
}
-/// Hosts the SwiftUI sidebar. The window is movable by its background; while
-/// the pointer is over a draggable row or tile the window controller turns that
-/// off, so a press starts SwiftUI's `.draggable` instead of a window drag.
-final class SidebarHostingView: NSHostingView<AnyView> {
- /// SwiftUI's hosting view turns down the click that brings an inactive window forward, so
- /// that click only activates Cra. Controls marked `.actsOnFirstClick()` take it too: after
- /// an automatic update Cra restarts in the background, and "See What's New" took two clicks.
- override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
- if let event, FirstClickArea.Anchor.contains(event) { return true }
- return super.acceptsFirstMouse(for: event)
- }
-}
-
-/// Marks the area of a sidebar control that acts on the window's activating click.
-private struct FirstClickArea: NSViewRepresentable {
- func makeNSView(context: Context) -> Anchor { Anchor() }
- func updateNSView(_ nsView: Anchor, context: Context) {}
-
- final class Anchor: NSView {
- private static let all = NSHashTable<Anchor>.weakObjects()
-
- override init(frame: NSRect) {
- super.init(frame: frame)
- Self.all.add(self)
- }
- required init?(coder: NSCoder) { fatalError() }
-
- static func contains(_ event: NSEvent) -> Bool {
- all.allObjects.contains { $0.window === event.window && $0.bounds.contains($0.convert(event.locationInWindow, from: nil)) }
- }
- }
-}
-
-extension View {
- func actsOnFirstClick() -> some View { background(FirstClickArea().allowsHitTesting(false)) }
-}
-
/// Thin vertical strip between sidebar and content that drags the width.
final class ResizeHandleView: NSView {
var onDrag: ((CGFloat) -> Void)?
diff --git a/Sources/Cra/UI/Sidebar/DownloadsTray.swift b/Sources/Cra/UI/Sidebar/DownloadsTray.swift
index 2b211fd..4abf137 100644
--- a/Sources/Cra/UI/Sidebar/DownloadsTray.swift
+++ b/Sources/Cra/UI/Sidebar/DownloadsTray.swift
@@ -1,5 +1,4 @@
import AppKit
-import SwiftUI
/// Arc's downloads list: hovering the Library button lists the recent downloads over the
/// bottom of the sidebar, newest at the bottom, and the tab list behind them fades out.
@@ -27,69 +26,177 @@ extension SidebarUIState {
}
}
-struct DownloadsTray: View {
- let palette: SpacePalette
- @Environment(SidebarUIState.self) private var ui
- private var history: DownloadHistory { .shared }
-
- var body: some View {
- let entries = history.recent
- let open = ui.downloadsListOpen
- TimelineView(.periodic(from: .now, by: 1)) { context in
- VStack(alignment: .leading, spacing: DownloadsTrayMetrics.rowPitch - DownloadsTrayMetrics.thumbnail) {
- ForEach(Array(entries.enumerated()), id: \.element.id) { i, entry in
- let fromBottom = Double(entries.count - 1 - i)
- DownloadsTrayRow(entry: entry, palette: palette, now: context.date)
- .opacity(open ? 1 : 0)
- .offset(y: open ? 0 : 5)
- .animation(open ? .easeOut(duration: 0.12).delay(fromBottom * 0.025)
- : .easeIn(duration: 0.05).delay(fromBottom * 0.015), value: open)
- }
+/// The list itself, pinned to the bottom of the tab list's area.
+@MainActor
+final class DownloadsTrayView: NSView {
+ private let ui: SidebarUIState
+ var colors = SidebarColors() { didSet { if colors.isDark != oldValue.isDark { for r in rows { r.colors = colors } } } }
+ private var rows: [DownloadsTrayRowView] = []
+ private var shownOpen = false
+ private var ticker: Timer?
+
+ init(ui: SidebarUIState) {
+ self.ui = ui
+ super.init(frame: .zero)
+ wantsLayer = true
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private func observe() {
+ let (entries, open, _) = withObservationTracking {
+ (DownloadHistory.shared.recent, ui.downloadsListOpen, DownloadHistory.shared.thumbnails.count)
+ } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ while rows.count < entries.count {
+ let r = DownloadsTrayRowView()
+ r.colors = colors
+ r.alphaValue = shownOpen ? 1 : 0
+ rows.append(r)
+ addSubview(r)
+ }
+ while rows.count > entries.count { rows.removeLast().removeFromSuperview() }
+ for (r, e) in zip(rows, entries) { r.show(e) }
+ refreshAges()
+ if open != shownOpen { animate(open: open) }
+ // TimelineView(.periodic(by: 1)): the ages tick while the list is up.
+ if open, ticker == nil {
+ ticker = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
+ MainActor.assumeIsolated { self?.refreshAges() }
}
+ } else if !open {
+ ticker?.invalidate()
+ ticker = nil
+ }
+ needsLayout = true
+ }
+
+ private func refreshAges() {
+ let now = Date()
+ for r in rows { r.now = now }
+ }
+
+ /// Rows rise 5 pt and fade in bottom first, 25 ms apart; they drop back faster.
+ private func animate(open: Bool) {
+ shownOpen = open
+ let n = rows.count
+ for (i, r) in rows.enumerated() {
+ guard let layer = r.layer else { continue }
+ let fromBottom = Double(n - 1 - i)
+ let delay = open ? fromBottom * 0.025 : fromBottom * 0.015
+ let fromOpacity = layer.presentation()?.opacity ?? layer.opacity
+ let fromShift = (layer.presentation()?.value(forKeyPath: "sublayerTransform.translation.y") as? CGFloat) ?? (open ? 5 : 0)
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ r.alphaValue = open ? 1 : 0
+ layer.sublayerTransform = CATransform3DMakeTranslation(0, open ? 0 : 5, 0)
+ CATransaction.commit()
+ let fade = CABasicAnimation(keyPath: "opacity")
+ fade.fromValue = fromOpacity
+ fade.toValue = open ? 1 : 0
+ let move = CABasicAnimation(keyPath: "sublayerTransform.translation.y")
+ move.fromValue = fromShift
+ move.toValue = open ? 0 : 5
+ let group = CAAnimationGroup()
+ group.animations = [fade, move]
+ group.duration = open ? 0.12 : 0.05
+ group.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) + delay
+ group.fillMode = .backwards
+ group.timingFunction = CAMediaTimingFunction(name: open ? .easeOut : .easeIn)
+ layer.add(group, forKey: "openClose")
+ }
+ }
+
+ override func layout() {
+ super.layout()
+ // VStack spacing 16 between 40 pt rows, 2 pt lower than the area (.offset(y: 2)).
+ for (i, r) in rows.enumerated() {
+ r.frame = NSRect(x: 0, y: 2 + CGFloat(i) * DownloadsTrayMetrics.rowPitch, width: bounds.width, height: DownloadsTrayMetrics.thumbnail)
}
- .frame(maxWidth: .infinity, alignment: .leading)
- .contentShape(Rectangle())
- .allowsHitTesting(open)
- .onHover { ui.downloadsListHovered = $0; ui.downloadsHoverChanged() }
- .offset(y: 2)
+ }
+
+ // MARK: Pointer
+
+ override func hitTest(_ point: NSPoint) -> NSView? { shownOpen ? super.hitTest(point) : nil }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { setHovered(ui.downloadsListOpen) }
+ override func mouseMoved(with event: NSEvent) { setHovered(ui.downloadsListOpen) }
+ override func mouseExited(with event: NSEvent) { setHovered(false) }
+
+ private func setHovered(_ h: Bool) {
+ guard ui.downloadsListHovered != h else { return }
+ ui.downloadsListHovered = h
+ ui.downloadsHoverChanged()
}
}
-private struct DownloadsTrayRow: View {
- let entry: DownloadHistory.Entry
- let palette: SpacePalette
- let now: Date
- private var ink: Color { palette.isDark ? .white : .black }
-
- var body: some View {
- Button { NSWorkspace.shared.open(URL(fileURLWithPath: entry.path)) } label: {
- HStack(spacing: 13) {
- Group {
- if let image = DownloadHistory.shared.thumbnail(for: entry.path) {
- Image(nsImage: image).resizable().aspectRatio(contentMode: .fill)
- } else {
- Color.white.opacity(0.9)
- }
- }
- .frame(width: DownloadsTrayMetrics.thumbnail, height: DownloadsTrayMetrics.thumbnail)
- .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))
- VStack(alignment: .leading, spacing: -1) {
- Text((entry.path as NSString).lastPathComponent)
- .font(.system(size: 14))
- .foregroundStyle(ink.opacity(0.82))
- .lineLimit(1).truncationMode(.middle)
- Text(Self.age.localizedString(for: min(entry.date, now), relativeTo: now))
- .font(.system(size: 12))
- .foregroundStyle(ink.opacity(0.5))
- }
- .padding(.top, 1)
- }
- .padding(.leading, 8)
- .frame(maxWidth: .infinity, alignment: .leading)
- .contentShape(Rectangle())
+private final class DownloadsTrayRowView: NSView, NSDraggingSource {
+ var colors = SidebarColors() { didSet { refresh() } }
+ private var entry: DownloadHistory.Entry?
+ var now = Date() { didSet { refreshAge() } }
+ private let thumb = NSView()
+ private let name = NSTextField.sidebarLabel(size: 14)
+ private let age = NSTextField.sidebarLabel(size: 12)
+ private var downAt: NSPoint?
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ thumb.wantsLayer = true
+ thumb.layer?.cornerRadius = 6
+ thumb.layer?.cornerCurve = .continuous
+ thumb.layer?.masksToBounds = true
+ thumb.layer?.contentsGravity = .resizeAspectFill
+ addSubview(thumb)
+ name.lineBreakMode = .byTruncatingMiddle
+ addSubview(name)
+ addSubview(age)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ /// Also when only a thumbnail arrived.
+ func show(_ e: DownloadHistory.Entry) {
+ entry = e
+ refresh()
+ }
+
+ private func refresh() {
+ let ink: NSColor = colors.isDark ? .white : .black
+ name.textColor = ink.withAlphaComponent(0.82)
+ age.textColor = ink.withAlphaComponent(0.5)
+ guard let entry else { return }
+ name.stringValue = (entry.path as NSString).lastPathComponent
+ if let image = DownloadHistory.shared.thumbnail(for: entry.path) {
+ // .aspectRatio(contentMode: .fill): the layer fills and crops.
+ let scale = window?.backingScaleFactor ?? 2
+ var rect = NSRect(x: 0, y: 0, width: DownloadsTrayMetrics.thumbnail, height: DownloadsTrayMetrics.thumbnail)
+ thumb.layer?.contents = image.cgImage(forProposedRect: &rect, context: nil, hints: [.ctm: AffineTransform(scale: scale)])
+ thumb.layer?.contentsScale = scale
+ thumb.layer?.backgroundColor = nil
+ } else {
+ thumb.layer?.contents = nil
+ thumb.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.9).cgColor
}
- .buttonStyle(.plain)
- .onDrag { NSItemProvider(contentsOf: URL(fileURLWithPath: entry.path)) ?? NSItemProvider() }
+ refreshAge()
+ }
+
+ private func refreshAge() {
+ guard let entry else { return }
+ let s = Self.age.localizedString(for: min(entry.date, now), relativeTo: now)
+ if age.stringValue != s { age.stringValue = s }
}
/// "54 seconds ago", "6 minutes ago".
@@ -98,29 +205,42 @@ private struct DownloadsTrayRow: View {
f.unitsStyle = .full
return f
}()
-}
-/// Hides the tab list under the downloads list and fades it back in above it. One
-/// gradient sized by a GeometryReader: fixed-height layers here raised the sidebar's
-/// minimum height and the window grew to fit them.
-struct DownloadsTrayMask: View {
- let rows: Int
- let open: Bool
-
- var body: some View {
- ZStack {
- Color.black.opacity(open ? 0 : 1)
- GeometryReader { g in
- let h = max(g.size.height, 1)
- let clearTop = max(0, h - DownloadsTrayMetrics.listHeight(rows: rows) - 1)
- let fadeTop = max(0, clearTop - DownloadsTrayMetrics.fade)
- LinearGradient(stops: [.init(color: .black, location: fadeTop / h),
- .init(color: .clear, location: clearTop / h),
- .init(color: .clear, location: 1)],
- startPoint: .top, endPoint: .bottom)
- }
- .opacity(open ? 1 : 0)
- }
- .animation(open ? .easeOut(duration: 0.18) : .easeOut(duration: 0.13).delay(0.08), value: open)
+ override func layout() {
+ super.layout()
+ let t = DownloadsTrayMetrics.thumbnail
+ thumb.frame = NSRect(x: 8, y: 0, width: t, height: t)
+ // HStack(spacing: 13); VStack(spacing: -1) of 17 + 15 with 1 pt on top, centred.
+ let x = 8 + t + 13, w = max(0, bounds.width - x)
+ let top = (t - 32) / 2 + 1
+ name.frame = NSRect(x: x - SidebarText.inset, y: top, width: w + 2 * SidebarText.inset, height: 17)
+ age.frame = NSRect(x: x - SidebarText.inset, y: top + 16, width: w + 2 * SidebarText.inset, height: 15)
+ }
+
+ // MARK: Click and drag
+
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ override func mouseDown(with event: NSEvent) { downAt = event.locationInWindow }
+
+ override func mouseDragged(with event: NSEvent) {
+ guard let start = downAt, let entry else { return }
+ let p = event.locationInWindow
+ guard hypot(p.x - start.x, p.y - start.y) > 3 else { return }
+ downAt = nil
+ let item = NSDraggingItem(pasteboardWriter: URL(fileURLWithPath: entry.path) as NSURL)
+ let image = DownloadHistory.shared.thumbnail(for: entry.path) ?? NSWorkspace.shared.icon(forFile: entry.path)
+ item.setDraggingFrame(thumb.frame, contents: image)
+ beginDraggingSession(with: [item], event: event, source: self)
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ defer { downAt = nil }
+ guard downAt != nil, let entry, bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
+ NSWorkspace.shared.open(URL(fileURLWithPath: entry.path))
+ }
+
+ func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
+ context == .outsideApplication ? [.copy, .generic] : .copy
}
}
diff --git a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
deleted file mode 100644
index 8982e70..0000000
--- a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
+++ /dev/null
@@ -1,220 +0,0 @@
-import SwiftUI
-import UniformTypeIdentifiers
-
-/// Arc's "top apps": a 4-wide grid of favorite tiles. Arc shares them between
-/// spaces; in Cra every space has its own.
-struct FavoritesGrid: View {
- let space: Space
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var targeted = false
-
- private let columns = Array(repeating: GridItem(.flexible(), spacing: 8), count: 4)
-
- var body: some View {
- let favorites = store.tabs(under: space.favoritesContainerID)
- VStack(spacing: 0) {
- if !favorites.isEmpty {
- LazyVGrid(columns: columns, spacing: 8) {
- ForEach(favorites) { item in FavoriteCell(item: item, space: space, palette: palette) }
- }
- }
- RoundedRectangle(cornerRadius: 10, style: .continuous)
- .strokeBorder(palette.textTertiary.opacity(targeted ? 0.6 : 0), style: StrokeStyle(lineWidth: 1, dash: [4, 3]))
- .background(RoundedRectangle(cornerRadius: 10).fill(targeted ? palette.hoverFill : .clear))
- .frame(height: targeted ? 36 : (favorites.isEmpty ? 8 : 6))
- .overlay {
- if targeted { Text("Add to Favorites").font(.system(size: 11, weight: .medium)).foregroundStyle(palette.textSecondary) }
- }
- .padding(.top, favorites.isEmpty ? 0 : 4)
- .animation(.easeOut(duration: 0.15), value: targeted)
- .dropDestination(for: SidebarDragItem.self) { items, _ in
- guard let d = items.first else { return false }
- store.addToFavorites(d.id, in: space.id)
- return true
- } isTargeted: { targeted = $0 }
- }
- }
-}
-
-/// Arc's keyboard-focus ring: 2pt systemYellow with black 6/6 dashes, inside the edge.
-struct FocusRing: View {
- let radius: CGFloat
- var body: some View {
- ZStack {
- RoundedRectangle(cornerRadius: radius, style: .continuous)
- .strokeBorder(Color(red: 1, green: 0.8, blue: 0), lineWidth: 2)
- RoundedRectangle(cornerRadius: radius, style: .continuous)
- .strokeBorder(Color.black.opacity(0.92), style: StrokeStyle(lineWidth: 2, dash: [6, 6]))
- }
- .allowsHitTesting(false)
- }
-}
-
-struct FavoriteCell: View {
- let item: SidebarItem
- let space: Space
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(FaviconCache.self) private var favicons
- @Environment(\.sidebarActions) private var actions
- @State private var hover = false
- @State private var targeted = false
-
- private var selected: Bool { store.isSelected(item.id, inSpace: space.id, window: ui.windowID) }
- private var tileColor: String? { item.tab?.tileColor }
- private var tileIsDark: Bool { tileColor.flatMap(HexColor.luminance).map { $0 < 0.5 } ?? palette.isDark }
-
- var body: some View {
- let session = ui
- ZStack {
- if let tileColor {
- // A picked color keeps its hue in every state; hover and selection shade it.
- RoundedRectangle(cornerRadius: 13).fill(Color(hex: tileColor))
- if selected || hover || targeted {
- RoundedRectangle(cornerRadius: 13).fill(tileIsDark ? Color.white.opacity(0.12) : Color.black.opacity(0.07))
- }
- } else {
- // Arc 1.170: 13pt circular corners; the active tile is the hover fill
- // with a 2pt darker rim, inactive tiles sit ~4.5% darker than the sidebar.
- RoundedRectangle(cornerRadius: 13)
- // Arc 1.170 over white: tile 207/194/166, hovered tile 197/184/158 (another ~4.5% black on top of the tile fill).
- .fill(selected ? (palette.isDark ? Color.white.opacity(0.13) : Color.white.opacity(0.38))
- : (hover || targeted ? (palette.isDark ? Color.white.opacity(0.15) : Color.black.opacity(0.09)) : palette.pillFill))
- }
- if selected {
- RoundedRectangle(cornerRadius: 13)
- .strokeBorder(tileIsDark ? Color.white.opacity(0.14) : Color.black.opacity(0.17), lineWidth: 2)
- }
- if ui.keyboardFocusID == item.id { FocusRing(radius: 13) }
- FaviconView(key: item.tab?.iconKey, palette: palette, size: 20, onDark: tileIsDark)
- if item.isUnread && !selected {
- Circle().fill((tileColor == nil ? palette.textPrimary : (tileIsDark ? .white : .black)).opacity(0.6)).frame(width: 6, height: 6)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)
- .padding(5)
- }
- }
- .frame(height: 47)
- .contentShape(RoundedRectangle(cornerRadius: 13))
- .onHover { hover = $0; ui.hoverDraggable(item.id, $0) }
- .onTapGesture { ui.keyboardFocusID = nil; store.selectTab(item.id, window: ui.windowID) }
- .arcTooltip(item.displayTitle, followsCursor: true)
- .draggable(SidebarDragItem.begin(item.id, session))
- .dropDestination(for: SidebarDragItem.self) { items, location in
- guard let d = items.first, d.id != item.id,
- let idx = store.item(space.favoritesContainerID)?.children.firstIndex(of: item.id) else { return false }
- store.moveItem(d.id, to: space.favoritesContainerID, index: idx + (location.x > 30 ? 1 : 0))
- return true
- } isTargeted: { targeted = $0 }
- .contextMenu {
- Button("Remove from Favorites") { store.removeFromFavorites(item.id) }
- Button("Rename…") { ui.renamingID = item.id }
- Button("Copy Link") {
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(item.tab?.url ?? "", forType: .string)
- }
- if let t = item.tab, t.url != t.savedURL { Button("Back to Pinned Page") { actions.resetPinnedTab(item.id) } }
- Button("Make This the Pinned Page") { store.setPinnedHomeToCurrent(item.id) }
- Divider()
- Button("Change Icon…") { pickIcon() }
- if let key = item.tab?.customIconKey {
- Button("Use Site Icon") {
- store.setCustomIcon(nil, for: item.id)
- favicons.removeCustomIcon(key)
- }
- }
- tileColorMenu
- Divider()
- Button("Close") { actions.closeTab(item.id) }
- Button("Archive") { store.archiveTab(item.id, reason: .manual) }
- }
- }
-
- private var tileColorMenu: some View {
- Menu("Tile Color") {
- colorToggle("Default", hex: nil)
- ForEach(TileColor.presets, id: \.hex) { colorToggle($0.name, hex: $0.hex) }
- if let tileColor, !TileColor.presets.contains(where: { $0.hex == tileColor }) {
- colorToggle("Custom", hex: tileColor)
- }
- Button("Other Color…") {
- let id = item.id
- TileColorPanel.shared.show(tileColor) { [store] hex in store.setTileColor(hex, for: [id]) }
- }
- Divider()
- Button("Use This Color for All Favorites") {
- store.setTileColor(tileColor, for: store.tabs(under: space.favoritesContainerID).map(\.id))
- }
- }
- }
-
- private func colorToggle(_ name: String, hex: String?) -> some View {
- Toggle(isOn: Binding(get: { tileColor == hex }, set: { _ in store.setTileColor(hex, for: [item.id]) })) {
- Label { Text(name) } icon: { Image(nsImage: TileColor.swatch(hex)) }
- }
- }
-
- private func pickIcon() {
- let panel = NSOpenPanel()
- panel.allowedContentTypes = [.image]
- panel.allowsMultipleSelection = false
- panel.prompt = "Use Icon"
- panel.message = "Choose an image for \(item.displayTitle)."
- guard panel.runModal() == .OK, let url = panel.url else { return }
- guard let key = favicons.importCustomIcon(from: url) else { NSSound.beep(); return }
- let old = item.tab?.customIconKey
- store.setCustomIcon(key, for: item.id)
- if let old { favicons.removeCustomIcon(old) }
- }
-}
-
-/// Tile backgrounds offered in a favorite's "Tile Color" menu.
-enum TileColor {
- static let presets: [(name: String, hex: String)] = [
- ("White", "#FFFFFF"), ("Light Gray", "#D9D9DE"), ("Graphite", "#48484A"), ("Black", "#000000"),
- ("Red", "#FF453A"), ("Orange", "#FF9F0A"), ("Yellow", "#FFD60A"), ("Green", "#30D158"),
- ("Teal", "#40C8E0"), ("Blue", "#0A84FF"), ("Purple", "#BF5AF2"), ("Pink", "#FF375F"),
- ]
-
- /// A 12pt dot for the menu; Default is drawn hollow.
- static func swatch(_ hex: String?) -> NSImage {
- NSImage(size: NSSize(width: 12, height: 12), flipped: false) { rect in
- let path = NSBezierPath(ovalIn: rect.insetBy(dx: 0.5, dy: 0.5))
- if let hex { NSColor(hex: hex).setFill(); path.fill() }
- NSColor.secondaryLabelColor.setStroke()
- path.lineWidth = 1
- path.stroke()
- return true
- }
- }
-}
-
-/// Routes the shared color panel to whichever favorite asked for it last.
-@MainActor
-final class TileColorPanel: NSObject {
- static let shared = TileColorPanel()
- private var onChange: ((String) -> Void)?
-
- func show(_ hex: String?, onChange: @escaping (String) -> Void) {
- let panel = NSColorPanel.shared
- // Detach first so seeding the color doesn't recolor the previous tile.
- panel.setTarget(nil)
- panel.setAction(nil)
- panel.showsAlpha = false
- panel.isContinuous = true
- if let hex { panel.color = NSColor(hex: hex) }
- self.onChange = onChange
- panel.setTarget(self)
- panel.setAction(#selector(changed(_:)))
- panel.orderFront(nil)
- }
-
- @objc private func changed(_ panel: NSColorPanel) {
- guard let c = panel.color.usingColorSpace(.sRGB) else { return }
- onChange?(String(format: "#%02X%02X%02X", Int((c.redComponent * 255).rounded()),
- Int((c.greenComponent * 255).rounded()), Int((c.blueComponent * 255).rounded())))
- }
-}
diff --git a/Sources/Cra/UI/Sidebar/LibraryView.swift b/Sources/Cra/UI/Sidebar/LibraryView.swift
index cbb80f4..e7e9363 100644
--- a/Sources/Cra/UI/Sidebar/LibraryView.swift
+++ b/Sources/Cra/UI/Sidebar/LibraryView.swift
@@ -1,5 +1,4 @@
import AppKit
-import SwiftUI
/// The Library's pages Cra has (Arc's rail also lists Media, Easels, Spaces and Boosts).
enum LibraryPage: String, CaseIterable {
@@ -33,222 +32,349 @@ enum LibraryMetrics {
static let extraWidth: CGFloat = 70
}
-struct LibraryView: View {
- let page: LibraryPage
- let palette: SpacePalette
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
-
- var body: some View {
- HStack(spacing: 0) {
- rail
- LibraryList(page: page, palette: palette)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
- }
- .foregroundStyle(palette.textPrimary)
- .onExitCommand { actions.closeLibrary() }
+/// The Library column: the page rail on the left, the page's search and list on the right.
+@MainActor
+final class LibraryView: NSView {
+ private let store: SidebarStore
+ private let actions: SidebarActions
+ private let favicons: FaviconCache
+ private let rail = LibraryRailView()
+ private let list: LibraryListView
+ var page: LibraryPage { didSet { if page != oldValue { pageChanged() } } }
+ var palette: SpacePalette { didSet { apply() } }
+
+ init(page: LibraryPage, palette: SpacePalette, store: SidebarStore, actions: SidebarActions, favicons: FaviconCache) {
+ self.page = page
+ self.palette = palette
+ self.store = store
+ self.actions = actions
+ self.favicons = favicons
+ list = LibraryListView(page: page, store: store, actions: actions, favicons: favicons)
+ super.init(frame: .zero)
+ rail.onPick = { actions.showLibrary($0) }
+ rail.onBack = { actions.closeLibrary() }
+ list.onEscape = { actions.closeLibrary() }
+ addSubview(rail)
+ addSubview(list)
+ apply()
+ pageChanged()
}
- private var ink: Color { palette.isDark ? .white : .black }
+ required init?(coder: NSCoder) { fatalError() }
- private var rail: some View {
- VStack(spacing: 0) {
- Spacer(minLength: CraMetrics.titleAreaHeight)
- VStack(spacing: 20) {
- ForEach(LibraryPage.allCases, id: \.self) { p in
- LibraryRailButton(page: p, selected: p == page, palette: palette) { actions.showLibrary(p) }
- }
- }
- Spacer(minLength: 0)
- HStack {
- SidebarIconButton(symbol: "arrow.left", palette: palette, help: "Exit the Library (Esc)", size: 32, height: 32,
- iconSize: 15, weight: .regular) { actions.closeLibrary() }
- Spacer(minLength: 0)
- }
- .padding(.leading, 8)
- .padding(.bottom, 8)
- }
- .frame(width: LibraryMetrics.rail - 1)
- .frame(maxHeight: .infinity)
- .background(LinearGradient(colors: [ink.opacity(0.02), ink.opacity(0.045)], startPoint: .leading, endPoint: .trailing))
- .overlay(alignment: .trailing) { Rectangle().fill(ink.opacity(0.09)).frame(width: 1).offset(x: 1) }
- .padding(.trailing, 1)
+ override var isFlipped: Bool { true }
+
+ private func pageChanged() {
+ rail.show(page: page)
+ list.page = page
}
-}
-private struct LibraryRailButton: View {
- let page: LibraryPage
- let selected: Bool
- let palette: SpacePalette
- let action: () -> Void
- @State private var hover = false
- private var ink: Color { palette.isDark ? .white : .black }
-
- var body: some View {
- Button(action: action) {
- VStack(spacing: 0) {
- Image(systemName: selected ? page.selectedSymbol : page.symbol)
- .font(.system(size: 17, weight: .medium))
- .symbolRenderingMode(selected ? .palette : .monochrome)
- .foregroundStyle(selected ? AnyShapeStyle(.white) : AnyShapeStyle(ink.opacity(0.6)),
- selected ? AnyShapeStyle(Color.accentColor) : AnyShapeStyle(ink.opacity(0.6)))
- .frame(height: 20)
- .padding(.top, 21)
- Text(page.title)
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(ink.opacity(selected ? 0.82 : 0.6))
- .lineLimit(1)
- .padding(.top, 9)
- Spacer(minLength: 0)
- }
- .frame(width: 97, height: 80)
- .background(RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(ink.opacity(selected ? 0.07 : (hover ? 0.04 : 0))))
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .onHover { hover = $0 }
- .accessibilityLabel(page.title)
+ private func apply() {
+ rail.colors = SidebarColors(palette)
+ list.colors = SidebarColors(palette)
+ }
+
+ override func viewDidMoveToWindow() {
+ super.viewDidMoveToWindow()
+ list.focusSearch()
+ }
+
+ override func cancelOperation(_ sender: Any?) { actions.closeLibrary() }
+
+ override func layout() {
+ super.layout()
+ rail.frame = NSRect(x: 0, y: 0, width: LibraryMetrics.rail, height: bounds.height)
+ list.frame = NSRect(x: LibraryMetrics.rail, y: 0, width: max(0, bounds.width - LibraryMetrics.rail), height: bounds.height)
}
}
-/// The page's list column: search, then the downloads or the archived tabs by day.
-private struct LibraryList: View {
- let page: LibraryPage
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(\.sidebarActions) private var actions
- @State private var query = ""
- @FocusState private var searchFocused: Bool
- private var ink: Color { palette.isDark ? .white : .black }
-
- var body: some View {
- VStack(spacing: 0) {
- searchRow
- .padding(.top, 10)
- .padding(.leading, 7)
- .padding(.trailing, 8)
- ScrollView {
- LazyVStack(alignment: .leading, spacing: 0, pinnedViews: []) {
- switch page {
- case .downloads: downloads
- case .archive: archive
- }
- }
- .padding(.bottom, 12)
- }
- .scrollIndicators(.never)
+/// The rail: a faint wash brightening to the right, ending in a hairline; the page buttons
+/// centred; the back arrow at the bottom.
+private final class LibraryRailView: NSView {
+ var onPick: (LibraryPage) -> Void = { _ in }
+ var onBack: () -> Void = {}
+ var colors = SidebarColors() { didSet { refresh() } }
+ private let wash = CAGradientLayer()
+ private let hairline = CALayer()
+ private var buttons: [LibraryRailButton] = []
+ private var back: SidebarGlyphButton?
+ private var page: LibraryPage = .downloads
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ wash.startPoint = CGPoint(x: 0, y: 0.5)
+ wash.endPoint = CGPoint(x: 1, y: 0.5)
+ layer?.addSublayer(wash)
+ layer?.addSublayer(hairline)
+ for p in LibraryPage.allCases {
+ let b = LibraryRailButton(page: p)
+ b.onPress = { [weak self] in self?.onPick(p) }
+ buttons.append(b)
+ addSubview(b)
}
- .onChange(of: page) { _, _ in query = "" }
- .onAppear { searchFocused = true }
- }
-
- private var searchRow: some View {
- HStack(spacing: 4) {
- HStack(spacing: 10) {
- Image(systemName: "magnifyingglass")
- .font(.system(size: 14))
- .foregroundStyle(ink.opacity(0.5))
- TextField(page.searchPrompt, text: $query)
- .textFieldStyle(.plain)
- .font(.system(size: 14))
- .focused($searchFocused)
- }
- .padding(.horizontal, 12)
- .frame(height: 36)
- .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(ink.opacity(0.08)))
- menu
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ func show(page: LibraryPage) {
+ self.page = page
+ refresh()
+ }
+
+ private func refresh() {
+ let ink: NSColor = colors.isDark ? .white : .black
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ wash.colors = [ink.withAlphaComponent(0.02).cgColor, ink.withAlphaComponent(0.045).cgColor]
+ hairline.backgroundColor = ink.withAlphaComponent(0.09).cgColor
+ CATransaction.commit()
+ for b in buttons { b.show(selected: b.page == page, ink: ink) }
+ if back == nil {
+ let b = SidebarGlyphButton(symbol: "arrow.left", size: 32, height: 32, iconSize: 15, weight: .regular,
+ help: "Exit the Library (Esc)", colors: colors) { [weak self] in self?.onBack() }
+ addSubview(b)
+ back = b
}
+ back?.colors = colors
+ needsLayout = true
}
- /// Arc's Filter button; Cra's holds the page's actions.
- private var menu: some View {
- Menu {
- switch page {
- case .downloads:
- Button("Open Downloads Folder") {
- NSWorkspace.shared.open(FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0])
- }
- case .archive:
- Button("Clear Archive") { store.clearArchive() }.disabled(store.archive.isEmpty)
- }
- } label: {
- Image(systemName: "ellipsis")
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(ink.opacity(0.7))
- .frame(width: 36, height: 36)
- .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(ink.opacity(0.05)))
- .contentShape(Rectangle())
+ override func layout() {
+ super.layout()
+ let w = LibraryMetrics.rail - 1, h = bounds.height
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ wash.frame = NSRect(x: 0, y: 0, width: w, height: h)
+ hairline.frame = NSRect(x: w, y: 0, width: 1, height: h)
+ CATransaction.commit()
+ // Spacer(minLength: title area), the buttons 20 apart, Spacer, the back arrow 8 pt in.
+ let group = CGFloat(buttons.count) * 80 + CGFloat(max(0, buttons.count - 1)) * 20
+ let free = max(0, h - group - 40)
+ let top = max(CraMetrics.titleAreaHeight, free / 2)
+ for (i, b) in buttons.enumerated() {
+ b.frame = NSRect(x: (w - 97) / 2, y: top + CGFloat(i) * 100, width: 97, height: 80)
}
- .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)
- .frame(width: 36)
+ back?.frame = NSRect(x: 8, y: h - 8 - 32, width: 32, height: 32)
}
+}
- private var needle: String { query.lowercased().trimmingCharacters(in: .whitespaces) }
+private final class LibraryRailButton: NSView {
+ let page: LibraryPage
+ var onPress: () -> Void = {}
+ private let glyph = NSImageView()
+ private let label = NSTextField.sidebarLabel(size: 12, weight: .semibold)
+ private var selected = false
+ private var ink = NSColor.white
+ private var hovering = false { didSet { if hovering != oldValue { refresh() } } }
+
+ init(page: LibraryPage) {
+ self.page = page
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = 12
+ layer?.cornerCurve = .continuous
+ glyph.imageScaling = .scaleNone
+ addSubview(glyph)
+ label.stringValue = page.title
+ label.alignment = .center
+ addSubview(label)
+ setAccessibilityLabel(page.title)
+ setAccessibilityRole(.button)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
- // MARK: Downloads
+ override var isFlipped: Bool { true }
- @ViewBuilder private var downloads: some View {
- let all = DownloadHistory.shared.entries.reversed().filter { FileManager.default.fileExists(atPath: $0.path) }
- let shown = needle.isEmpty ? all : all.filter { ($0.path as NSString).lastPathComponent.lowercased().contains(needle) }
- if shown.isEmpty {
- empty(symbol: "arrow.down.circle", title: all.isEmpty ? "Nothing here yet!" : "No matches",
- detail: all.isEmpty ? "Files you download show up here." : nil)
+ func show(selected: Bool, ink: NSColor) {
+ self.selected = selected
+ self.ink = ink
+ refresh()
+ }
+
+ private func refresh() {
+ let config = NSImage.SymbolConfiguration(pointSize: 17, weight: .medium)
+ if selected {
+ // The filled glyph in palette mode: white mark on the accent colour.
+ glyph.image = NSImage(systemSymbolName: page.selectedSymbol, accessibilityDescription: nil)?
+ .withSymbolConfiguration(config.applying(.init(paletteColors: [.white, .controlAccentColor])))
+ glyph.contentTintColor = nil
} else {
- ForEach(grouped(shown, date: \.date), id: \.0) { label, entries in
- header(label)
- ForEach(entries) { LibraryDownloadRow(entry: $0, palette: palette) }
- }
+ glyph.image = NSImage(systemSymbolName: page.symbol, accessibilityDescription: nil)?.withSymbolConfiguration(config)
+ glyph.contentTintColor = ink.withAlphaComponent(0.6)
}
+ label.textColor = ink.withAlphaComponent(selected ? 0.82 : 0.6)
+ layer?.backgroundColor = ink.withAlphaComponent(selected ? 0.07 : (hovering ? 0.04 : 0)).cgColor
}
- // MARK: Archive
+ override func layout() {
+ super.layout()
+ // The glyph in a 20 pt band 21 pt down, the label 9 pt under it.
+ glyph.frame = NSRect(x: 0, y: 21, width: bounds.width, height: 20)
+ label.frame = NSRect(x: 0, y: 50, width: bounds.width, height: 15)
+ }
- @ViewBuilder private var archive: some View {
- let shown = needle.isEmpty ? store.archive : store.archive.filter {
- $0.item.displayTitle.lowercased().contains(needle) || ($0.item.tab?.url.lowercased().contains(needle) ?? false)
- }
- if shown.isEmpty {
- empty(symbol: "archivebox", title: store.archive.isEmpty ? "Nothing here yet!" : "No matches",
- detail: store.archive.isEmpty ? "Tabs you close end up here." : nil)
- } else {
- ForEach(grouped(shown, date: \.archivedAt), id: \.0) { label, entries in
- header(label)
- ForEach(entries) { e in
- LibraryArchiveRow(entry: e, palette: palette) { actions.restoreArchived(e.id) }
- }
- }
- }
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
}
- // MARK: Pieces
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { onPress() }
+ }
+}
+
+/// The page's list column: search, then the downloads or the archived tabs by day.
+private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDataSource, NSTableViewDelegate {
+ enum Row {
+ case header(String)
+ case download(DownloadHistory.Entry)
+ case archived(ArchivedItem)
+ }
- private func header(_ label: String) -> some View {
- Text(label)
- .font(.system(size: 13, weight: .semibold))
- .foregroundStyle(ink.opacity(0.6))
- .padding(.leading, 11)
- .padding(.top, 18)
- .padding(.bottom, 6)
+ private let store: SidebarStore
+ private let actions: SidebarActions
+ private let favicons: FaviconCache
+ var onEscape: () -> Void = {}
+ var page: LibraryPage { didSet { if page != oldValue { field.stringValue = ""; query = ""; field.placeholderString = page.searchPrompt; reload() } } }
+ var colors = SidebarColors() { didSet { if colors != oldValue { refresh(); table.reloadData() } } }
+ private var query = ""
+ private var rows: [Row] = []
+ private let searchBox = NSView()
+ private let searchGlyph = NSImageView()
+ private let field = NSTextField()
+ private let menuButton = NSView()
+ private let menuGlyph = NSImageView()
+ private let scroll = NSScrollView()
+ private let table = NSTableView()
+ private let empty = LibraryEmptyView()
+
+ init(page: LibraryPage, store: SidebarStore, actions: SidebarActions, favicons: FaviconCache) {
+ self.page = page
+ self.store = store
+ self.actions = actions
+ self.favicons = favicons
+ super.init(frame: .zero)
+ searchBox.wantsLayer = true
+ searchBox.layer?.cornerRadius = 12
+ searchBox.layer?.cornerCurve = .continuous
+ addSubview(searchBox)
+ searchGlyph.image = SidebarSymbols.image("magnifyingglass", size: 14)
+ searchGlyph.imageScaling = .scaleNone
+ searchBox.addSubview(searchGlyph)
+ field.isBordered = false
+ field.drawsBackground = false
+ field.focusRingType = .none
+ field.font = .systemFont(ofSize: 14)
+ field.placeholderString = page.searchPrompt
+ field.usesSingleLineMode = true
+ field.cell?.isScrollable = true
+ field.delegate = self
+ searchBox.addSubview(field)
+ menuButton.wantsLayer = true
+ menuButton.layer?.cornerRadius = 12
+ menuButton.layer?.cornerCurve = .continuous
+ menuGlyph.image = SidebarSymbols.image("ellipsis", size: 14, weight: .medium)
+ menuGlyph.imageScaling = .scaleNone
+ menuGlyph.frame = NSRect(x: 0, y: 0, width: 36, height: 36)
+ menuButton.addSubview(menuGlyph)
+ addSubview(menuButton)
+ let column = NSTableColumn(identifier: .init("row"))
+ table.addTableColumn(column)
+ table.headerView = nil
+ table.backgroundColor = .clear
+ table.intercellSpacing = .zero
+ table.selectionHighlightStyle = .none
+ table.style = .plain
+ table.usesAutomaticRowHeights = false
+ table.columnAutoresizingStyle = .uniformColumnAutoresizingStyle
+ table.dataSource = self
+ table.delegate = self
+ table.menu = NSMenu()
+ table.menu?.delegate = self
+ scroll.documentView = table
+ scroll.drawsBackground = false
+ scroll.hasVerticalScroller = false
+ scroll.hasHorizontalScroller = false
+ scroll.contentInsets = NSEdgeInsets(top: 0, left: 0, bottom: 12, right: 0)
+ scroll.automaticallyAdjustsContentInsets = false
+ addSubview(scroll)
+ addSubview(empty)
+ observe()
}
- private func empty(symbol: String, title: String, detail: String?) -> some View {
- VStack(spacing: 8) {
- Image(systemName: symbol)
- .font(.system(size: 30, weight: .light))
- .foregroundStyle(ink.opacity(0.45))
- .padding(.bottom, 4)
- Text(title).font(.system(size: 17, weight: .semibold)).foregroundStyle(ink.opacity(0.9))
- if let detail {
- Text(detail).font(.system(size: 14)).foregroundStyle(ink.opacity(0.7)).multilineTextAlignment(.center)
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ func focusSearch() {
+ DispatchQueue.main.async { [weak self] in
+ guard let self, let w = self.window else { return }
+ w.makeFirstResponder(self.field)
+ }
+ }
+
+ private func observe() {
+ withObservationTracking {
+ _ = store.archive
+ _ = DownloadHistory.shared.entries
+ _ = DownloadHistory.shared.thumbnails.count
+ } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ reload()
+ }
+
+ private var needle: String { query.lowercased().trimmingCharacters(in: .whitespaces) }
+
+ private func reload() {
+ var out: [Row] = []
+ switch page {
+ case .downloads:
+ let all = DownloadHistory.shared.entries.reversed().filter { FileManager.default.fileExists(atPath: $0.path) }
+ let shown = needle.isEmpty ? all : all.filter { ($0.path as NSString).lastPathComponent.lowercased().contains(needle) }
+ for (label, entries) in Self.grouped(shown, date: \.date) {
+ out.append(.header(label))
+ out += entries.map { .download($0) }
+ }
+ empty.show(symbol: "arrow.down.circle", title: all.isEmpty ? "Nothing here yet!" : "No matches",
+ detail: all.isEmpty ? "Files you download show up here." : nil)
+ case .archive:
+ let shown = needle.isEmpty ? store.archive : store.archive.filter {
+ $0.item.displayTitle.lowercased().contains(needle) || ($0.item.tab?.url.lowercased().contains(needle) ?? false)
}
+ for (label, entries) in Self.grouped(shown, date: \.archivedAt) {
+ out.append(.header(label))
+ out += entries.map { .archived($0) }
+ }
+ empty.show(symbol: "archivebox", title: store.archive.isEmpty ? "Nothing here yet!" : "No matches",
+ detail: store.archive.isEmpty ? "Tabs you close end up here." : nil)
}
- .frame(maxWidth: .infinity)
- .padding(.horizontal, 16)
- .padding(.top, 260)
+ rows = out
+ empty.isHidden = !out.isEmpty
+ scroll.isHidden = out.isEmpty
+ table.reloadData()
+ refresh()
+ }
+
+ private func refresh() {
+ let ink: NSColor = colors.isDark ? .white : .black
+ searchBox.layer?.backgroundColor = ink.withAlphaComponent(0.08).cgColor
+ searchGlyph.contentTintColor = ink.withAlphaComponent(0.5)
+ field.textColor = colors.textPrimary
+ menuButton.layer?.backgroundColor = ink.withAlphaComponent(0.05).cgColor
+ menuGlyph.contentTintColor = ink.withAlphaComponent(0.7)
+ empty.ink = ink
}
- private func grouped<T>(_ items: [T], date: KeyPath<T, Date>) -> [(String, [T])] {
+ private static func grouped<T>(_ items: [T], date: KeyPath<T, Date>) -> [(String, [T])] {
let cal = Calendar.current
let df = DateFormatter()
df.dateStyle = .medium
@@ -262,122 +388,334 @@ private struct LibraryList: View {
}
return order.map { ($0, groups[$0]!) }
}
-}
-/// Arc's archive row: 24 pt icon, title over the URL, 56 pt apart.
-private struct LibraryArchiveRow: View {
- let entry: ArchivedItem
- let palette: SpacePalette
- let restore: () -> Void
- @Environment(SidebarStore.self) private var store
- @Environment(FaviconCache.self) private var favicons
- @State private var hover = false
- private var ink: Color { palette.isDark ? .white : .black }
-
- var body: some View {
- Button(action: restore) {
- HStack(spacing: 10) {
- Group {
- if let img = favicons.image(forKey: entry.item.tab?.faviconKey) {
- Image(nsImage: img).resizable().frame(width: 16, height: 16)
- } else {
- Color.clear
- }
- }
- .frame(width: 24, height: 24)
- .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(ink.opacity(0.04)))
- VStack(alignment: .leading, spacing: 1) {
- Text(entry.item.displayTitle)
- .font(.system(size: 14))
- .foregroundStyle(ink.opacity(0.82))
- .lineLimit(1)
- Text(SuggestionEngine.humanURL(entry.item.tab?.url ?? ""))
- .font(.system(size: 12))
- .foregroundStyle(ink.opacity(0.55))
- .lineLimit(1).truncationMode(.tail)
- }
- Spacer(minLength: 0)
+ override func layout() {
+ super.layout()
+ // HStack(spacing: 4) 10 pt down, 7 pt in, 8 pt from the right: the field, the ⋯ button.
+ let w = bounds.width
+ searchBox.frame = NSRect(x: 7, y: 10, width: max(0, w - 7 - 8 - 4 - 36), height: 36)
+ menuButton.frame = NSRect(x: w - 8 - 36, y: 10, width: 36, height: 36)
+ let gw = searchGlyph.image?.size.width ?? 14
+ searchGlyph.frame = NSRect(x: 12, y: 0, width: gw, height: 36)
+ let fh = ceil(field.intrinsicContentSize.height)
+ let fx = 12 + gw + 10
+ field.frame = NSRect(x: fx - SidebarText.inset, y: (36 - fh) / 2, width: max(0, searchBox.bounds.width - fx - 12) + 2 * SidebarText.inset, height: fh)
+ scroll.frame = NSRect(x: 0, y: 46, width: w, height: max(0, bounds.height - 46))
+ table.tableColumns.first?.width = w
+ empty.frame = scroll.frame
+ }
+
+ // MARK: Search
+
+ func controlTextDidChange(_ obj: Notification) {
+ query = field.stringValue
+ reload()
+ }
+
+ func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
+ if selector == #selector(NSResponder.cancelOperation(_:)) { onEscape(); return true }
+ return false
+ }
+
+ // MARK: ⋯ menu (Arc's Filter button; Cra's holds the page's actions)
+
+ override func mouseDown(with event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ guard menuButton.frame.contains(p) else { return super.mouseDown(with: event) }
+ let menu = NSMenu()
+ menu.autoenablesItems = false
+ switch page {
+ case .downloads:
+ MenuItems.add(menu, "Open Downloads Folder") {
+ NSWorkspace.shared.open(FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0])
}
- .padding(.leading, 9)
- .padding(.trailing, 8)
- .frame(height: 52)
- .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(hover ? palette.hoverFill : .clear))
- .contentShape(Rectangle())
+ case .archive:
+ let store = store
+ MenuItems.add(menu, "Clear Archive", enabled: !store.archive.isEmpty) { store.clearArchive() }
}
- .buttonStyle(.plain)
- .padding(.horizontal, 4)
- .padding(.vertical, 2)
- .onHover { hover = $0 }
- .arcTooltip(entry.item.tab?.url ?? "")
- .contextMenu {
- Button("Restore", action: restore)
- Button("Copy Link") {
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(entry.item.tab?.url ?? "", forType: .string)
- }
- Divider()
- Button("Remove from Archive") { store.removeFromArchive(entry.id) }
+ menu.popUp(positioning: nil, at: NSPoint(x: menuButton.frame.minX, y: menuButton.frame.maxY + 4), in: self)
+ }
+
+ // MARK: Table
+
+ func numberOfRows(in tableView: NSTableView) -> Int { rows.count }
+
+ func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
+ if case .header = rows[row] { return 40 }
+ return 56
+ }
+
+ func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
+ switch rows[row] {
+ case .header(let label):
+ let v = tableView.makeView(withIdentifier: .init("header"), owner: nil) as? LibraryHeaderCell ?? LibraryHeaderCell()
+ v.identifier = .init("header")
+ v.show(label, ink: colors.isDark ? .white : .black)
+ return v
+ case .download(let e):
+ let v = tableView.makeView(withIdentifier: .init("item"), owner: nil) as? LibraryItemCell ?? LibraryItemCell()
+ v.identifier = .init("item")
+ v.showDownload(e, colors: colors)
+ return v
+ case .archived(let e):
+ let v = tableView.makeView(withIdentifier: .init("item"), owner: nil) as? LibraryItemCell ?? LibraryItemCell()
+ v.identifier = .init("item")
+ v.showArchived(e, icon: favicons.image(forKey: e.item.tab?.faviconKey), colors: colors) { [actions] in actions.restoreArchived(e.id) }
+ return v
}
}
+
+ func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { false }
}
-/// A download: its Quick Look thumbnail, the file name and when it arrived (the hover list's row).
-private struct LibraryDownloadRow: View {
- let entry: DownloadHistory.Entry
- let palette: SpacePalette
- @State private var hover = false
- private var ink: Color { palette.isDark ? .white : .black }
- private var url: URL { URL(fileURLWithPath: entry.path) }
-
- var body: some View {
- Button { NSWorkspace.shared.open(url) } label: {
- HStack(spacing: 10) {
- Group {
- if let image = DownloadHistory.shared.thumbnail(for: entry.path) {
- Image(nsImage: image).resizable().aspectRatio(contentMode: .fill)
- } else {
- ink.opacity(0.04)
- }
- }
- .frame(width: 32, height: 32)
- .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))
- VStack(alignment: .leading, spacing: 1) {
- Text(url.lastPathComponent)
- .font(.system(size: 14))
- .foregroundStyle(ink.opacity(0.82))
- .lineLimit(1).truncationMode(.middle)
- Text(Self.age.localizedString(for: min(entry.date, Date()), relativeTo: Date()))
- .font(.system(size: 12))
- .foregroundStyle(ink.opacity(0.55))
- .lineLimit(1)
- }
- Spacer(minLength: 0)
+extension LibraryListView: NSMenuDelegate {
+ /// The row's context menu, built for the row under the pointer.
+ func menuNeedsUpdate(_ menu: NSMenu) {
+ menu.removeAllItems()
+ let row = table.clickedRow
+ guard rows.indices.contains(row) else { return }
+ switch rows[row] {
+ case .header: break
+ case .archived(let e):
+ let actions = actions, store = store
+ MenuItems.add(menu, "Restore") { actions.restoreArchived(e.id) }
+ MenuItems.add(menu, "Copy Link") {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(e.item.tab?.url ?? "", forType: .string)
}
- .padding(.leading, 5)
- .padding(.trailing, 8)
- .frame(height: 52)
- .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(hover ? palette.hoverFill : .clear))
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .padding(.horizontal, 4)
- .padding(.vertical, 2)
- .onHover { hover = $0 }
- .onDrag { NSItemProvider(contentsOf: url) ?? NSItemProvider() }
- .contextMenu {
- Button("Open") { NSWorkspace.shared.open(url) }
- Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([url]) }
- Divider()
- Button("Copy") {
+ menu.addItem(.separator())
+ MenuItems.add(menu, "Remove from Archive") { store.removeFromArchive(e.id) }
+ case .download(let e):
+ let url = URL(fileURLWithPath: e.path)
+ MenuItems.add(menu, "Open") { NSWorkspace.shared.open(url) }
+ MenuItems.add(menu, "Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([url]) }
+ menu.addItem(.separator())
+ MenuItems.add(menu, "Copy") {
NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects([url as NSURL])
}
}
}
+}
+
+private final class LibraryHeaderCell: NSView {
+ private let label = NSTextField.sidebarLabel(size: 13, weight: .semibold)
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ addSubview(label)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ func show(_ text: String, ink: NSColor) {
+ label.stringValue = text
+ label.textColor = ink.withAlphaComponent(0.6)
+ }
+
+ override func layout() {
+ super.layout()
+ // 11 pt in, 18 pt above, 6 pt below.
+ label.frame = NSRect(x: 11 - SidebarText.inset, y: 18, width: bounds.width - 11, height: 16)
+ }
+}
+
+/// An archived tab (24 pt icon tile, title over URL) or a download (32 pt thumbnail, name over
+/// age): 52 pt tall inside 4 × 2 pt of padding, the space's hover fill under the pointer.
+private final class LibraryItemCell: NSView, NSDraggingSource {
+ private let card = FlippedView()
+ private let tile = NSView()
+ private let icon = NSImageView()
+ private let title = NSTextField.sidebarLabel(size: 14)
+ private let detail = NSTextField.sidebarLabel(size: 12)
+ private var tip: ArcTooltipAnchorView?
+ private var colors = SidebarColors()
+ private var download: DownloadHistory.Entry?
+ private var restore: (() -> Void)?
+ private var downAt: NSPoint?
+ private var hovering = false { didSet { if hovering != oldValue { refreshHover() } } }
private static let age: RelativeDateTimeFormatter = {
let f = RelativeDateTimeFormatter()
f.unitsStyle = .full
return f
}()
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ card.wantsLayer = true
+ card.layer?.cornerRadius = 10
+ card.layer?.cornerCurve = .continuous
+ addSubview(card)
+ tile.wantsLayer = true
+ tile.layer?.cornerRadius = 6
+ tile.layer?.cornerCurve = .continuous
+ tile.layer?.masksToBounds = true
+ tile.layer?.contentsGravity = .resizeAspectFill
+ card.addSubview(tile)
+ icon.imageScaling = .scaleProportionallyUpOrDown
+ tile.addSubview(icon)
+ card.addSubview(title)
+ card.addSubview(detail)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ func showArchived(_ e: ArchivedItem, icon image: NSImage?, colors: SidebarColors, restore: @escaping () -> Void) {
+ self.colors = colors
+ download = nil
+ self.restore = restore
+ let ink: NSColor = colors.isDark ? .white : .black
+ tile.layer?.contents = nil
+ tile.layer?.backgroundColor = ink.withAlphaComponent(0.04).cgColor
+ icon.isHidden = image == nil
+ icon.image = image
+ title.stringValue = e.item.displayTitle
+ title.lineBreakMode = .byTruncatingTail
+ detail.stringValue = SuggestionEngine.humanURL(e.item.tab?.url ?? "")
+ let url = e.item.tab?.url ?? ""
+ if let tip { (tip.text, tip.keys) = (url, []) } else if !url.isEmpty { tip = ArcTooltipAnchorView.attach(to: self, help: url) }
+ tip?.text = url
+ apply(ink: ink)
+ }
+
+ func showDownload(_ e: DownloadHistory.Entry, colors: SidebarColors) {
+ self.colors = colors
+ download = e
+ restore = nil
+ let ink: NSColor = colors.isDark ? .white : .black
+ icon.isHidden = true
+ if let image = DownloadHistory.shared.thumbnail(for: e.path) {
+ var rect = NSRect(x: 0, y: 0, width: 32, height: 32)
+ let scale = window?.backingScaleFactor ?? 2
+ tile.layer?.contents = image.cgImage(forProposedRect: &rect, context: nil, hints: [.ctm: AffineTransform(scale: scale)])
+ tile.layer?.contentsScale = scale
+ tile.layer?.backgroundColor = nil
+ } else {
+ tile.layer?.contents = nil
+ tile.layer?.backgroundColor = ink.withAlphaComponent(0.04).cgColor
+ }
+ title.stringValue = (e.path as NSString).lastPathComponent
+ title.lineBreakMode = .byTruncatingMiddle
+ detail.stringValue = Self.age.localizedString(for: min(e.date, Date()), relativeTo: Date())
+ tip?.text = ""
+ apply(ink: ink)
+ }
+
+ private func apply(ink: NSColor) {
+ title.textColor = ink.withAlphaComponent(0.82)
+ detail.textColor = ink.withAlphaComponent(0.55)
+ refreshHover()
+ needsLayout = true
+ }
+
+ private func refreshHover() {
+ card.layer?.backgroundColor = (hovering ? colors.hoverFill : .clear).cgColor
+ }
+
+ override func layout() {
+ super.layout()
+ card.frame = bounds.insetBy(dx: 4, dy: 2)
+ let h = card.bounds.height
+ // Archived: 24 pt tile 9 pt in; download: 32 pt thumbnail 5 pt in; the text 10 pt after.
+ let isDownload = download != nil
+ let t: CGFloat = isDownload ? 32 : 24
+ let x: CGFloat = isDownload ? 5 : 9
+ tile.frame = NSRect(x: x, y: (h - t) / 2, width: t, height: t)
+ icon.frame = NSRect(x: (t - 16) / 2, y: (t - 16) / 2, width: 16, height: 16)
+ // HStack(spacing: 10) ends in a Spacer, so the text stops 10 + 8 pt short of the edge.
+ let tx = x + t + 10, tw = max(0, card.bounds.width - tx - 18)
+ // VStack(spacing: 1) of 17 + 15, centred.
+ let top = (h - 33) / 2
+ title.frame = NSRect(x: tx - SidebarText.inset, y: top, width: tw + 2 * SidebarText.inset, height: 17)
+ detail.frame = NSRect(x: tx - SidebarText.inset, y: top + 18, width: tw + 2 * SidebarText.inset, height: 15)
+ }
+
+ // MARK: Pointer
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+
+ override func mouseDown(with event: NSEvent) { downAt = event.locationInWindow }
+
+ override func mouseDragged(with event: NSEvent) {
+ guard let start = downAt, let download else { return }
+ let p = event.locationInWindow
+ guard hypot(p.x - start.x, p.y - start.y) > 3 else { return }
+ downAt = nil
+ let item = NSDraggingItem(pasteboardWriter: URL(fileURLWithPath: download.path) as NSURL)
+ item.setDraggingFrame(convert(tile.frame, from: card), contents: DownloadHistory.shared.thumbnail(for: download.path) ?? NSWorkspace.shared.icon(forFile: download.path))
+ beginDraggingSession(with: [item], event: event, source: self)
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ defer { downAt = nil }
+ guard downAt != nil, bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
+ if let download { NSWorkspace.shared.open(URL(fileURLWithPath: download.path)) } else { restore?() }
+ }
+
+ func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
+ context == .outsideApplication ? [.copy, .generic] : .copy
+ }
+}
+
+private final class LibraryEmptyView: NSView {
+ var ink = NSColor.white { didSet { refresh() } }
+ private let glyph = NSImageView()
+ private let title = NSTextField.sidebarLabel(size: 17, weight: .semibold)
+ private let detail = NSTextField(wrappingLabelWithString: "")
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ glyph.imageScaling = .scaleNone
+ addSubview(glyph)
+ title.alignment = .center
+ addSubview(title)
+ detail.font = .systemFont(ofSize: 14)
+ detail.alignment = .center
+ addSubview(detail)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ func show(symbol: String, title text: String, detail d: String?) {
+ glyph.image = SidebarSymbols.image(symbol, size: 30, weight: .light)
+ title.stringValue = text
+ detail.stringValue = d ?? ""
+ detail.isHidden = d == nil
+ refresh()
+ }
+
+ private func refresh() {
+ glyph.contentTintColor = ink.withAlphaComponent(0.45)
+ title.textColor = ink.withAlphaComponent(0.9)
+ detail.textColor = ink.withAlphaComponent(0.7)
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ // 260 pt down, 16 pt in: the glyph (+4), 8, the title, 8, the detail.
+ let w = max(0, bounds.width - 32)
+ let gh = glyph.image?.size.height ?? 30
+ var y: CGFloat = 260 - 46
+ glyph.frame = NSRect(x: 16, y: y, width: w, height: gh)
+ y += gh + 4 + 8
+ title.frame = NSRect(x: 16, y: y, width: w, height: 21)
+ y += 21 + 8
+ let dh = detail.cell?.cellSize(forBounds: NSRect(x: 0, y: 0, width: w, height: 200)).height ?? 17
+ detail.frame = NSRect(x: 16, y: y, width: w, height: ceil(dh))
+ }
}
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarJumpPill.swift b/Sources/Cra/UI/Sidebar/List/SidebarJumpPill.swift
new file mode 100644
index 0000000..3f970be
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/List/SidebarJumpPill.swift
@@ -0,0 +1,181 @@
+import AppKit
+
+/// Dia's "back to the open tab" pill (TabList.TabOverflowIndicatorView, its geometry from
+/// TabOverflowGeometryTracker): while the selected tab's row is scrolled out of the list, a
+/// dark capsule with its favicon and an arrow pointing at it sits 7 pt inside the list edge
+/// the tab is past. A click scrolls the tab to the middle of the list.
+///
+/// Measured on a Dia capture (2x): a 51 × 28 pt capsule, fill #1F1C1C, a 0.5 pt light inner
+/// edge (~10 % white) inside a 0.5 pt dark outer edge (~45 % black), no larger shadow;
+/// 10.5 pt in, the 16 pt favicon, 7 pt, a thin 9 pt arrow in #ADACAC, 10.5 pt out. A split
+/// shows its tabs' favicons as a small facepile (Dia's `facepile`).
+@MainActor
+final class SidebarJumpPill: NSView {
+ enum Edge { case top, bottom }
+
+ static let inset: CGFloat = 7
+ private static let height: CGFloat = 28
+ private static let padding: CGFloat = 10.5
+ private static let icon: CGFloat = 16
+ /// Each further favicon of a split overlaps the one before by this much.
+ private static let overlap: CGFloat = 5
+ private static let fill = NSColor(srgbRed: 0x1F / 255, green: 0x1C / 255, blue: 0x1C / 255, alpha: 1)
+ private static let fillHover = NSColor(srgbRed: 0x2A / 255, green: 0x27 / 255, blue: 0x27 / 255, alpha: 1)
+
+ var onClick: () -> Void = {}
+ private(set) var edge: Edge?
+ private let body = NSView()
+ private let innerEdge = CAShapeLayer()
+ private var icons: [SidebarFaviconView] = []
+ private let arrow = NSImageView()
+ /// What the favicons show: their keys and whether each image had loaded.
+ private var shownIcons: [String] = []
+ private var hovering = false { didSet { if hovering != oldValue { refreshFill() } } }
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ isHidden = true
+ body.wantsLayer = true
+ if let l = body.layer {
+ l.cornerRadius = Self.height / 2
+ l.cornerCurve = .continuous
+ l.borderWidth = 0.5
+ l.borderColor = NSColor.black.withAlphaComponent(0.45).cgColor
+ innerEdge.fillColor = nil
+ innerEdge.strokeColor = NSColor.white.withAlphaComponent(0.1).cgColor
+ innerEdge.lineWidth = 0.5
+ l.addSublayer(innerEdge)
+ }
+ addSubview(body)
+ arrow.imageScaling = .scaleNone
+ arrow.contentTintColor = NSColor(srgbRed: 0xAD / 255, green: 0xAC / 255, blue: 0xAC / 255, alpha: 1)
+ body.addSubview(arrow)
+ setAccessibilityRole(.button)
+ setAccessibilityLabel("Scroll to the open tab")
+ refreshFill()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ /// The pill's size for these many favicons.
+ static func size(icons n: Int) -> NSSize {
+ let iconsW = icon + CGFloat(max(0, n - 1)) * (icon - overlap)
+ return NSSize(width: ceil(padding + iconsW + 7 + 7 + padding), height: height)
+ }
+
+ /// Shows the pill at `edge` with these favicons, or hides it (nil).
+ func show(edge newEdge: Edge?, icons items: [(image: NSImage?, flip: Bool, key: String?)], animated: Bool) {
+ if let newEdge {
+ if Self.signature(items) != shownIcons { setIcons(items) }
+ arrow.image = SidebarSymbols.image(newEdge == .top ? "arrow.up" : "arrow.down", size: 10.5, weight: .light)
+ }
+ guard newEdge != edge else { return }
+ let appearing = edge == nil
+ edge = newEdge
+ needsLayout = true
+ if let newEdge {
+ isHidden = false
+ alphaValue = 1
+ guard animated, appearing, let layer = body.layer else { return }
+ // In from the edge it points at: fade in while sliding 4 pt, sprung.
+ layoutSubtreeIfNeeded()
+ let fade = CABasicAnimation(keyPath: "opacity")
+ fade.fromValue = 0
+ fade.toValue = 1
+ fade.duration = 0.18
+ layer.add(fade, forKey: "fade")
+ let move = CASpringAnimation(perceptualDuration: 0.32, bounce: 0.2)
+ move.keyPath = "sublayerTransform"
+ move.fromValue = CATransform3DMakeTranslation(0, newEdge == .top ? -4 : 4, 0)
+ move.toValue = CATransform3DIdentity
+ move.duration = move.settlingDuration
+ self.layer?.add(move, forKey: "rise")
+ } else if animated {
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.15
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ animator().alphaValue = 0
+ } completionHandler: { [weak self] in
+ MainActor.assumeIsolated {
+ guard let self, self.edge == nil else { return }
+ self.isHidden = true
+ self.hovering = false
+ }
+ }
+ } else {
+ isHidden = true
+ hovering = false
+ }
+ }
+
+ private func setIcons(_ items: [(image: NSImage?, flip: Bool, key: String?)]) {
+ icons.forEach { $0.removeFromSuperview() }
+ // Mono glyphs flip to white on the dark pill.
+ var dark = SidebarColors()
+ dark.isDark = true
+ dark.textTertiary = NSColor.white.withAlphaComponent(0.5)
+ icons = items.prefix(3).map { item in
+ let v = SidebarFaviconView(size: Self.icon)
+ v.show(item.image, flip: item.flip, colors: dark)
+ body.addSubview(v)
+ return v
+ }
+ shownIcons = Self.signature(items)
+ let size = Self.size(icons: icons.count)
+ setFrameSize(size)
+ needsLayout = true
+ }
+
+ private static func signature(_ items: [(image: NSImage?, flip: Bool, key: String?)]) -> [String] {
+ items.map { "\($0.key ?? "-")|\($0.image.map { ObjectIdentifier($0).hashValue } ?? 0)|\($0.flip)" }
+ }
+
+ private func refreshFill() {
+ body.layer?.backgroundColor = (hovering ? Self.fillHover : Self.fill).cgColor
+ for v in icons.dropFirst() {
+ v.layer?.borderColor = (hovering ? Self.fillHover : Self.fill).cgColor
+ }
+ }
+
+ override func layout() {
+ super.layout()
+ body.frame = bounds
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ let r = body.bounds.insetBy(dx: 0.75, dy: 0.75)
+ innerEdge.path = CGPath(roundedRect: r, cornerWidth: r.height / 2, cornerHeight: r.height / 2, transform: nil)
+ CATransaction.commit()
+ var x = Self.padding
+ for (i, v) in icons.enumerated() {
+ v.frame = NSRect(x: x, y: (bounds.height - Self.icon) / 2, width: Self.icon, height: Self.icon)
+ if i > 0 {
+ v.layer?.borderWidth = 1.5
+ v.layer?.borderColor = (hovering ? Self.fillHover : Self.fill).cgColor
+ }
+ x += Self.icon - Self.overlap
+ }
+ let arrowX = Self.padding + (Self.icon + CGFloat(max(0, icons.count - 1)) * (Self.icon - Self.overlap)) + 7
+ arrow.frame = NSRect(x: arrowX, y: 0, width: 7, height: bounds.height)
+ }
+
+ // MARK: Pointer
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override func hitTest(_ point: NSPoint) -> NSView? { edge == nil || isHidden ? nil : super.hitTest(point).map { _ in self } }
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { onClick() }
+ }
+}
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift b/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift
new file mode 100644
index 0000000..611120c
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift
@@ -0,0 +1,279 @@
+import AppKit
+
+/// The tab list's context menus (the SwiftUI rows' .contextMenu, item for item).
+@MainActor
+enum SidebarMenus {
+ private final class Action: NSObject {
+ let run: () -> Void
+ init(_ run: @escaping () -> Void) { self.run = run }
+ @objc func fire() { run() }
+ }
+
+ private static func menu() -> NSMenu {
+ let m = NSMenu()
+ m.autoenablesItems = false
+ return m
+ }
+
+ @discardableResult
+ private static func add(_ menu: NSMenu, _ title: String, enabled: Bool = true, on: Bool? = nil, _ run: @escaping () -> Void) -> NSMenuItem {
+ let a = Action(run)
+ let item = NSMenuItem(title: title, action: #selector(Action.fire), keyEquivalent: "")
+ item.target = a
+ item.representedObject = a
+ item.isEnabled = enabled
+ if let on { item.state = on ? .on : .off }
+ menu.addItem(item)
+ return item
+ }
+
+ private static func note(_ menu: NSMenu, _ title: String) {
+ let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")
+ item.isEnabled = false
+ menu.addItem(item)
+ }
+
+ private static func submenu(_ menu: NSMenu, _ title: String) -> NSMenu {
+ let sub = Self.menu()
+ let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")
+ item.submenu = sub
+ menu.addItem(item)
+ return sub
+ }
+
+ private static func copy(_ string: String) {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(string, forType: .string)
+ }
+
+ // MARK: Tabs
+
+ static func tab(_ m: TabRowModel, list: SpaceListView) -> NSMenu {
+ let store = list.store, ui = list.ui, actions = list.actions
+ let id = m.id
+ let menu = menu()
+ let group = list.closeGroup(for: id)
+ if group.count > 1 {
+ folderItems(menu, ui.group(for: id, in: store), list: list)
+ menu.addItem(.separator())
+ add(menu, "Close \(group.count) Tabs") { list.closeTabs(group) }
+ add(menu, "Deselect All") { ui.clearPicks() }
+ return menu
+ }
+ guard let item = store.item(id), let tab = item.tab else { return menu }
+ if m.pinned {
+ add(menu, "Unpin Tab") { store.unpinTab(id) }
+ } else {
+ add(menu, "Pin Tab") { store.pinTab(id) }
+ }
+ if store.isFavorite(id) {
+ add(menu, "Remove from Favorites") { store.removeFromFavorites(id) }
+ } else {
+ add(menu, "Add to Favorites") { store.addToFavorites(id) }
+ }
+ menu.addItem(.separator())
+ add(menu, "Rename…") { ui.renamingID = id }
+ if item.title != nil { add(menu, "Use Page Title") { store.rename(id, to: nil) } }
+ add(menu, "Duplicate") { _ = store.duplicateTab(id) }
+ add(menu, "Copy Link") { copy(tab.url) }
+ add(menu, tab.muted ? "Unmute" : "Mute") {
+ store.setMuted(id, !tab.muted)
+ actions.performAction("muteTab:\(id)")
+ }
+ if m.pinned {
+ menu.addItem(.separator())
+ if m.navigatedAway { add(menu, "Back to Pinned Page") { actions.resetPinnedTab(id) } }
+ add(menu, "Make This the Pinned Page") { store.setPinnedHomeToCurrent(id) }
+ }
+ menu.addItem(.separator())
+ let spaces = submenu(menu, "Move to Space")
+ let current = store.spaceID(ofItem: id)
+ for s in store.orderedSpaces {
+ add(spaces, "\(s.emoji) \(s.title)", enabled: s.id != current) { store.moveTab(id, toSpace: s.id) }
+ }
+ folderItems(menu, [id], list: list)
+ menu.addItem(.separator())
+ if m.pinned {
+ if store.isSelected(id, window: ui.windowID) || ui.loadedTabIDs.contains(id) {
+ add(menu, "Close and Keep Pinned") { actions.closeTab(id) }
+ }
+ add(menu, "Archive Tab") { store.archiveTab(id, reason: .manual) }
+ } else {
+ add(menu, "Archive") { actions.closeTab(id) }
+ }
+ return menu
+ }
+
+ /// Move to Folder / New Folder for this tab, or for every picked tab.
+ private static func folderItems(_ menu: NSMenu, _ ids: [UUID], list: SpaceListView) {
+ let store = list.store, ui = list.ui
+ let folders = store.children(of: store.focusedSpace(window: ui.windowID).pinnedContainerID).filter { $0.isFolder && !$0.isLiveFolder }
+ if !folders.isEmpty {
+ let sub = submenu(menu, ids.count > 1 ? "Move \(ids.count) Tabs to Folder" : "Move to Folder")
+ for f in folders {
+ add(sub, f.title ?? "Folder", enabled: !ids.allSatisfy { store.item($0)?.parentID == f.id }) {
+ store.moveItems(ids, to: f.id, index: nil)
+ }
+ }
+ }
+ add(menu, ids.count > 1 ? "New Folder with \(ids.count) Tabs" : "New Folder with Tab") {
+ ui.renamingID = store.createFolder(with: ids).id
+ }
+ }
+
+ // MARK: Folders
+
+ private static func iconColor(_ menu: NSMenu, _ item: SidebarItem, list: SpaceListView) {
+ let sub = submenu(menu, "Icon Color")
+ let id = item.id
+ for (title, style) in [("Auto", FolderIconStyle?.none), ("White", .white), ("Black", .black)] {
+ add(sub, title, on: item.folderIcon == style) { list.store.setFolderIcon(style, for: id) }
+ }
+ }
+
+ static func folder(_ item: SidebarItem, list: SpaceListView) -> NSMenu {
+ let store = list.store, ui = list.ui
+ let id = item.id
+ let menu = menu()
+ add(menu, "Rename…") { ui.renamingID = id }
+ add(menu, "New Folder Inside") {
+ let f = store.createFolder(named: "New Folder", in: id, index: 0)
+ store.setExpanded(id, true)
+ ui.renamingID = f.id
+ }
+ iconColor(menu, item, list: list)
+ menu.addItem(.separator())
+ add(menu, "Delete Folder (archives tabs)") { store.deleteFolder(id) }
+ return menu
+ }
+
+ /// The live folder's menu (Arc: SidebarMenu+ListContextMenu liveFolderContextMenu).
+ static func liveFolder(_ item: SidebarItem, list: SpaceListView) -> NSMenu {
+ let store = list.store, ui = list.ui, actions = list.actions
+ let manager = LiveFolderManager.shared
+ let id = item.id
+ let live = item.liveFolder ?? LiveFolderData()
+ let menu = menu()
+ note(menu, manager.refreshing.contains(id) ? "Updating…" : LiveFolderText.lastUpdate(live))
+ add(menu, "Refresh") { manager.refresh(id) }
+ menu.addItem(.separator())
+ for (title, attribute) in [("My Pull Requests", GitHubLiveFilter.Attributes.authored),
+ ("Review Requests", .reviewRequests),
+ ("Team Review Requests", .teamReviewRequests)] {
+ let on = live.filter.attributes.contains(attribute)
+ add(menu, title, on: on) {
+ store.updateLiveFolder(id) { l in
+ if on { l.filter.attributes.remove(attribute) } else { l.filter.attributes.insert(attribute) }
+ }
+ manager.refresh(id, force: true)
+ }
+ }
+ let repos = manager.repositories[id] ?? live.filter.hiddenRepositories
+ if !repos.isEmpty {
+ let sub = submenu(menu, "Repositories")
+ note(sub, "This list is generated based on your currently active pull requests.")
+ sub.addItem(.separator())
+ for repo in repos {
+ let shown = !live.filter.hiddenRepositories.contains(repo)
+ add(sub, repo, on: shown) {
+ store.updateLiveFolder(id) { l in
+ l.filter.hiddenRepositories.removeAll { $0 == repo }
+ if shown { l.filter.hiddenRepositories.append(repo) }
+ }
+ manager.refresh(id, force: true)
+ }
+ }
+ }
+ if live.lastError == .notSignedIn {
+ menu.addItem(.separator())
+ add(menu, "Sign In to GitHub…") { actions.openURL(live.signInURL) }
+ } else if !live.ssoOrganizations.isEmpty {
+ menu.addItem(.separator())
+ note(menu, "SSO ensures all of your organizations’ PRs appear")
+ for org in live.ssoOrganizations {
+ add(menu, "Sign In to \(org) with SSO…") { actions.openURL("https://github.com/orgs/\(org)/sso") }
+ }
+ }
+ menu.addItem(.separator())
+ add(menu, "Rename…") { ui.renamingID = id }
+ iconColor(menu, item, list: list)
+ add(menu, "Copy All Links as Markdown", enabled: !item.children.isEmpty) {
+ let lines = store.children(of: id).compactMap { c in c.tab.map { "- [\(c.displayTitle)](\($0.liveItemURL ?? $0.url))" } }
+ copy(lines.joined(separator: "\n"))
+ }
+ menu.addItem(.separator())
+ add(menu, "Delete Live Folder") { confirmDeleteLiveFolder(item, store: store) }
+ return menu
+ }
+
+ /// Arc asks first ("Delete your %@ Live Folder?") and says how to get it back.
+ static func confirmDeleteLiveFolder(_ item: SidebarItem, store: SidebarStore) {
+ let alert = NSAlert()
+ alert.messageText = "Delete your \(item.title ?? "Pull Requests") Live Folder?"
+ alert.informativeText = "You can add it again with New GitHub Live Folder in the sidebar’s menu or the command bar."
+ alert.addButton(withTitle: "Delete")
+ alert.addButton(withTitle: "Cancel")
+ alert.buttons.first?.hasDestructiveAction = true
+ let id = item.id
+ if let window = NSApp.keyWindow {
+ alert.beginSheetModal(for: window) { if $0 == .alertFirstButtonReturn { store.deleteFolder(id) } }
+ } else if alert.runModal() == .alertFirstButtonReturn {
+ store.deleteFolder(id)
+ }
+ }
+
+ // MARK: Splits
+
+ static func split(_ m: SplitRowModel, list: SpaceListView) -> NSMenu {
+ let store = list.store, ui = list.ui, actions = list.actions
+ let id = m.id
+ let menu = menu()
+ let children = m.cells.map(\.id)
+ add(menu, "Separate All Tabs") { store.separateAll(id) }
+ add(menu, store.item(id)?.split?.orientation == .vertical ? "Convert to Horizontal Split View" : "Convert to Vertical Split View") {
+ store.flipSplitOrientation(id)
+ }
+ add(menu, "Add Pane") {
+ if let first = children.first {
+ actions.focusPane(first)
+ actions.performAction("addSplitView")
+ }
+ }
+ menu.addItem(.separator())
+ add(menu, "Rename…") { ui.renamingID = id }
+ menu.addItem(.separator())
+ add(menu, m.today ? "Archive All" : "Close All") { for c in children { actions.closeTab(c) } }
+ return menu
+ }
+
+ static func splitCell(_ id: UUID, list: SpaceListView) -> NSMenu {
+ let store = list.store, actions = list.actions
+ let menu = menu()
+ add(menu, "Separate Tab from Split") { store.separateFromSplit(id) }
+ add(menu, "Copy Link") { copy(store.item(id)?.tab?.url ?? "") }
+ menu.addItem(.separator())
+ add(menu, "Close") { actions.closeTab(id) }
+ return menu
+ }
+
+ // MARK: The list
+
+ static func spaceList(_ list: SpaceListView) -> NSMenu {
+ let store = list.store, actions = list.actions
+ let space = list.spaceID
+ let menu = menu()
+ add(menu, "New Tab") { actions.openCommandBar(.newTab) }
+ add(menu, "New Folder") { actions.performAction("newFolder") }
+ add(menu, "New GitHub Live Folder", enabled: store.liveFolder(.github, inSpace: space) == nil) {
+ actions.performAction("newGitHubLiveFolder")
+ }
+ menu.addItem(.separator())
+ if let s = store.space(space), !store.children(of: s.todayContainerID).isEmpty {
+ add(menu, "Clear Today") { store.clearToday(space) }
+ }
+ if let s = store.space(space) {
+ add(menu, "Edit Space…") { actions.editSpace(s) }
+ }
+ return menu
+ }
+}
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift
new file mode 100644
index 0000000..71a5ea8
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift
@@ -0,0 +1,1416 @@
+import AppKit
+import SwiftUI
+
+// The rows of a space's tab list, drawn by AppKit (see SpaceListView). Each row is a plain
+// layer-backed view: hover comes from the list's one tracking area, clicks and drags from the
+// row's own mouse events. Rows draw what their model says and nothing else; the list rebuilds
+// the models when the store changes and hands a row a new one only when it differs.
+
+/// The palette's colours as AppKit colours, converted once per list update.
+struct SidebarColors: Equatable {
+ var isDark = false
+ var textPrimary = NSColor.labelColor
+ var textSecondary = NSColor.secondaryLabelColor
+ var textTertiary = NSColor.tertiaryLabelColor
+ var hoverFill = NSColor.clear
+ var selectedFill = NSColor.clear
+ var separator = NSColor.separatorColor
+ var pillFill = NSColor.clear
+
+ init() {}
+
+ init(_ p: SpacePalette) {
+ isDark = p.isDark
+ textPrimary = NSColor(p.textPrimary)
+ textSecondary = NSColor(p.textSecondary)
+ textTertiary = NSColor(p.textTertiary)
+ hoverFill = NSColor(p.hoverFill)
+ selectedFill = NSColor(p.selectedFill)
+ separator = NSColor(p.separator)
+ pillFill = NSColor(p.pillFill)
+ }
+
+ /// SidebarIconButton's glyph tone outside the header (no active state).
+ var glyph: NSColor { isDark ? NSColor.white.withAlphaComponent(0.55) : NSColor.black.withAlphaComponent(0.26) }
+ /// A one-colour favicon or GitHub's mark on the sidebar.
+ var monoGlyph: NSColor { isDark ? NSColor.white.withAlphaComponent(0.92) : NSColor.black.withAlphaComponent(0.85) }
+}
+
+enum SidebarSymbols {
+ static func image(_ name: String, size: CGFloat, weight: NSFont.Weight = .regular) -> NSImage? {
+ NSImage(systemSymbolName: name, accessibilityDescription: nil)?
+ .withSymbolConfiguration(.init(pointSize: size, weight: weight))
+ }
+}
+
+enum SidebarText {
+ /// NSTextField draws its text this far in from its frame; labels are placed that much
+ /// further left so the text lands where SwiftUI's Text put it.
+ static let inset: CGFloat = 2
+}
+
+extension NSTextField {
+ static func sidebarLabel(size: CGFloat, weight: NSFont.Weight = .regular) -> NSTextField {
+ let l = NSTextField(labelWithString: "")
+ l.font = .systemFont(ofSize: size, weight: weight)
+ l.lineBreakMode = .byTruncatingTail
+ l.usesSingleLineMode = true
+ l.maximumNumberOfLines = 1
+ l.cell?.truncatesLastVisibleLine = true
+ return l
+ }
+}
+
+/// SidebarIconButton for AppKit rows: a glyph with a rounded hover fill and an Arc tooltip.
+final class SidebarGlyphButton: NSView {
+ var action: () -> Void
+ let size: NSSize
+ private let glyph = NSImageView()
+ private var tip: ArcTooltipAnchorView?
+ private var hovering = false { didSet { refresh() } }
+ var colors: SidebarColors { didSet { if colors != oldValue { refresh() } } }
+
+ /// Header buttons follow the app's active state (nil: the plain sidebar tone).
+ var active: Bool? { didSet { if active != oldValue { refresh() } } }
+ var enabled = true { didSet { if enabled != oldValue { refresh() } } }
+
+ init(symbol: String, size: CGFloat, height: CGFloat? = nil, iconSize: CGFloat, weight: NSFont.Weight = .medium, help: String,
+ optionHelp: String? = nil, colors: SidebarColors, action: @escaping () -> Void) {
+ self.size = NSSize(width: size, height: height ?? min(size, 28))
+ self.colors = colors
+ self.action = action
+ super.init(frame: NSRect(origin: .zero, size: self.size))
+ wantsLayer = true
+ layer?.cornerRadius = 7
+ layer?.cornerCurve = .continuous
+ glyph.image = SidebarSymbols.image(symbol, size: iconSize, weight: weight)
+ glyph.imageScaling = .scaleNone
+ glyph.frame = bounds
+ glyph.autoresizingMask = [.width, .height]
+ addSubview(glyph)
+ if !help.isEmpty {
+ tip = ArcTooltipAnchorView.attach(to: self, help: help)
+ tip?.optionText = optionHelp
+ }
+ refresh()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func setSymbol(_ symbol: String, iconSize: CGFloat, weight: NSFont.Weight = .medium, help: String) {
+ glyph.image = SidebarSymbols.image(symbol, size: iconSize, weight: weight)
+ if let tip { (tip.text, tip.keys) = ArcTooltipLabel.split(help) } else if !help.isEmpty { tip = ArcTooltipAnchorView.attach(to: self, help: help) }
+ }
+
+ /// Arc 1.170 draws these glyphs at roughly 26% black while the app is in the background; with
+ /// the app active its header glyphs darken to ~59% black, disabled ones stay at ~24%.
+ private func refresh() {
+ let tint: NSColor
+ if colors.isDark {
+ tint = enabled ? NSColor.white.withAlphaComponent(0.55) : colors.textTertiary.withAlphaComponent(colors.textTertiary.alphaComponent * 0.55)
+ } else if let active {
+ tint = NSColor.black.withAlphaComponent(enabled && active ? 0.59 : 0.24)
+ } else {
+ tint = enabled ? colors.glyph : colors.textTertiary.withAlphaComponent(colors.textTertiary.alphaComponent * 0.55)
+ }
+ glyph.contentTintColor = tint
+ layer?.backgroundColor = (hovering && enabled ? colors.hoverFill : .clear).cgColor
+ }
+
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func viewDidMoveToWindow() {
+ super.viewDidMoveToWindow()
+ // A button that appears under a resting pointer (a row's hover buttons) is hovered at once.
+ if let w = window { hovering = bounds.contains(convert(w.mouseLocationOutsideOfEventStream, from: nil)) }
+ }
+
+ // Rows hide their buttons rather than remove them; a button shown again under the pointer is hovered.
+ override func viewDidHide() { hovering = false }
+ override func viewDidUnhide() { viewDidMoveToWindow() }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if enabled, bounds.contains(convert(event.locationInWindow, from: nil)) { action() }
+ }
+}
+
+/// FaviconView for AppKit rows: the cached favicon, one-colour glyphs flipped to suit the fill,
+/// a globe while there is none.
+final class SidebarFaviconView: NSImageView {
+ private var shown: (NSImage?, Bool, Bool)?
+
+ init(size: CGFloat = CraMetrics.favicon) {
+ super.init(frame: NSRect(x: 0, y: 0, width: size, height: size))
+ imageScaling = .scaleProportionallyUpOrDown
+ wantsLayer = true
+ layer?.cornerCurve = .continuous
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ func show(_ icon: NSImage?, flip: Bool, colors: SidebarColors) {
+ if let s = shown, s.0 === icon, s.1 == flip, s.2 == colors.isDark { return }
+ shown = (icon, flip, colors.isDark)
+ let size = frame.width
+ if let icon {
+ imageScaling = .scaleProportionallyUpOrDown
+ if flip {
+ let t = icon.copy() as! NSImage
+ t.isTemplate = true
+ image = t
+ contentTintColor = colors.monoGlyph
+ } else {
+ image = icon
+ contentTintColor = nil
+ }
+ layer?.cornerRadius = size * 0.22
+ layer?.masksToBounds = true
+ } else {
+ imageScaling = .scaleNone
+ image = SidebarSymbols.image("globe", size: size * 0.8)
+ contentTintColor = colors.textTertiary
+ layer?.masksToBounds = false
+ }
+ }
+
+ func showGitHubMark(colors: SidebarColors, color: NSColor? = nil) {
+ shown = nil
+ imageScaling = .scaleProportionallyUpOrDown
+ image = GitHubMark.image
+ contentTintColor = color ?? colors.monoGlyph
+ layer?.masksToBounds = false
+ }
+}
+
+/// Arc's folder glyph: the outline over a filled folder while closed, GitHub's mark on a live folder.
+final class FolderGlyphView: NSView {
+ private let fill = NSImageView()
+ private let outline = NSImageView()
+ private let mark = NSImageView()
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ for v in [fill, outline] {
+ v.imageScaling = .scaleNone
+ v.autoresizingMask = [.width, .height]
+ v.frame = bounds
+ addSubview(v)
+ }
+ fill.image = SidebarSymbols.image("folder.fill", size: 15)
+ outline.image = SidebarSymbols.image("folder", size: 15)
+ mark.image = GitHubMark.image
+ mark.imageScaling = .scaleProportionallyUpOrDown
+ addSubview(mark)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ func show(expanded: Bool, live: Bool, tint: NSColor, fillColor: NSColor) {
+ fill.isHidden = expanded
+ fill.contentTintColor = fillColor
+ outline.contentTintColor = tint
+ mark.isHidden = !live
+ mark.contentTintColor = tint
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ mark.frame = NSRect(x: (bounds.width - 7) / 2, y: (bounds.height - 7) / 2 + 1.5, width: 7, height: 7)
+ }
+}
+
+/// Arc's keyboard-focus ring: 2 pt systemYellow with black 6/6 dashes, inside the edge.
+final class FocusRingLayer: CALayer {
+ private let yellow = CAShapeLayer()
+ private let dashes = CAShapeLayer()
+ private var radius = CraMetrics.rowCorner
+
+ convenience init(radius: CGFloat) {
+ self.init()
+ self.radius = radius
+ }
+
+ override init() {
+ super.init()
+ for l in [yellow, dashes] {
+ l.fillColor = nil
+ l.lineWidth = 2
+ addSublayer(l)
+ }
+ yellow.strokeColor = NSColor(red: 1, green: 0.8, blue: 0, alpha: 1).cgColor
+ dashes.strokeColor = NSColor.black.withAlphaComponent(0.92).cgColor
+ dashes.lineDashPattern = [6, 6]
+ }
+
+ override init(layer: Any) { super.init(layer: layer) }
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func layoutSublayers() {
+ super.layoutSublayers()
+ let path = CGPath(roundedRect: bounds.insetBy(dx: 1, dy: 1), cornerWidth: radius - 1, cornerHeight: radius - 1, transform: nil)
+ for l in [yellow, dashes] {
+ l.frame = bounds
+ l.path = path
+ }
+ }
+}
+
+/// What a drag over the list does to one row (SidebarDropPreview).
+struct DropDecor: Equatable {
+ var dimmed = false
+ var nudge: CGFloat = 0
+ /// "Move to Folder" / "Add to Split" on a folder or split the drop goes into.
+ var badge: Badge?
+ /// The row turns into what the drop makes.
+ var combine: CombineDropPreview.Kind?
+ var combineDragged: UUID?
+
+ struct Badge: Equatable {
+ let symbol: String
+ let label: String
+ }
+}
+
+// MARK: - Row base
+
+@MainActor
+class SidebarRowView: NSView {
+ weak var list: SpaceListView?
+ let key: SpaceListView.RowKey
+ var colors: SidebarColors
+ var isHovered = false { didSet { if isHovered != oldValue { hoverChanged() } } }
+ private(set) var decor = DropDecor()
+ private var badgeView: DropBadgeView?
+ private var combineView: NSView?
+ private var press: (event: NSEvent, point: NSPoint)?
+ /// The hover/selection fill. Arc 1.170 draws it 36 pt tall on the 41 pt row pitch, so two
+ /// filled rows keep a 5 pt gap (GitHub #10: Cra filled all 40 pt and rows touched).
+ private let fillLayer = CALayer()
+ static let fillInset: CGFloat = 2
+ var fillRect: CGRect { bounds.insetBy(dx: 0, dy: Self.fillInset) }
+
+ init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
+ self.key = key
+ self.list = list
+ self.colors = colors
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = CraMetrics.rowCorner
+ layer?.cornerCurve = .continuous
+ fillLayer.cornerRadius = CraMetrics.rowCorner
+ fillLayer.cornerCurve = .continuous
+ // Changes show at once, as the view's own layer background did.
+ fillLayer.actions = ["backgroundColor": NSNull(), "position": NSNull(), "bounds": NSNull()]
+ layer?.insertSublayer(fillLayer, at: 0)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ func hoverChanged() { refreshBackground() }
+ /// The row's resting fill (hover, selection).
+ func baseFill() -> NSColor { .clear }
+ /// Pointer moved within a hovered row (split rows track which pane it is over).
+ func hoverMoved(to point: NSPoint) {}
+ /// The item a press at `point` drags; nil when the row can't be dragged.
+ func dragItemID(at point: NSPoint) -> UUID? { nil }
+ func click(_ event: NSEvent, at point: NSPoint) {}
+ func contextMenu(at point: NSPoint) -> NSMenu? { nil }
+ /// The tooltip owner under the pointer.
+ func tooltipTarget(at point: NSPoint) -> (any ArcTooltipTarget)? { nil }
+ func setColors(_ c: SidebarColors) {
+ guard c != colors else { return }
+ colors = c
+ refreshBackground()
+ }
+
+ func refreshBackground() {
+ var fill = baseFill()
+ if decor.combine != nil { fill = .clear } else if decor.badge != nil, fill == .clear { fill = colors.selectedFill }
+ fillLayer.backgroundColor = fill.cgColor
+ }
+
+ override func layout() {
+ super.layout()
+ fillLayer.frame = fillRect
+ }
+
+ func applyDecor(_ d: DropDecor, animated: Bool) {
+ guard d != decor else { return }
+ let old = decor
+ decor = d
+ let alpha: CGFloat = d.combine != nil ? 0 : (d.dimmed ? 0.4 : 1)
+ for v in subviews where v !== combineView { animated ? (v.animator().alphaValue = alpha) : (v.alphaValue = alpha) }
+ if let badge = d.badge {
+ let v = badgeView ?? DropBadgeView()
+ if badgeView == nil {
+ badgeView = v
+ v.frame = fillRect
+ v.autoresizingMask = [.width, .height]
+ addSubview(v)
+ }
+ v.show(badge, colors: colors)
+ v.alphaValue = alpha
+ } else if let v = badgeView {
+ badgeView = nil
+ v.removeFromSuperview()
+ }
+ if d.combine != old.combine || d.combineDragged != old.combineDragged {
+ combineView?.removeFromSuperview()
+ combineView = nil
+ if let kind = d.combine, let dragged = d.combineDragged, let list, let target = list.store.item(itemIDForCombine),
+ let draggedItem = list.store.item(dragged) {
+ let depth = list.depth(of: key)
+ let host = CombineDropPreview(kind: kind, target: target, dragged: draggedItem, depth: depth,
+ palette: list.palette, favicons: list.favicons)
+ host.frame = bounds
+ host.autoresizingMask = [.width, .height]
+ addSubview(host)
+ combineView = host
+ }
+ }
+ refreshBackground()
+ }
+
+ /// The item a combine preview draws as the drop's target.
+ var itemIDForCombine: UUID { if case .item(let id) = key { return id }; return UUID() }
+
+ // Clicks act on release (SwiftUI's tap); a press that moves 3 pt starts the row's drag.
+ override func mouseDown(with event: NSEvent) {
+ press = (event, convert(event.locationInWindow, from: nil))
+ }
+
+ override func mouseDragged(with event: NSEvent) {
+ guard let p = press else { return }
+ let q = convert(event.locationInWindow, from: nil)
+ guard hypot(q.x - p.point.x, q.y - p.point.y) > 3 else { return }
+ press = nil
+ if let id = dragItemID(at: p.point) { list?.beginDrag(id, from: self, event: p.event) }
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ guard let p = press else { return }
+ press = nil
+ click(event, at: p.point)
+ }
+
+ override func menu(for event: NSEvent) -> NSMenu? {
+ contextMenu(at: convert(event.locationInWindow, from: nil))
+ }
+}
+
+/// The badge a folder or split shows while a drop would go into it.
+private final class DropBadgeView: NSView {
+ private let pill = NSView()
+ private let icon = NSImageView()
+ private let label = NSTextField.sidebarLabel(size: 11, weight: .semibold)
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerRadius = CraMetrics.rowCorner
+ layer?.cornerCurve = .continuous
+ layer?.borderWidth = 1.5
+ pill.wantsLayer = true
+ pill.layer?.cornerRadius = 11
+ pill.shadow = NSShadow()
+ pill.layer?.shadowOpacity = 0.08
+ pill.layer?.shadowRadius = 2
+ pill.layer?.shadowOffset = CGSize(width: 0, height: -1)
+ addSubview(pill)
+ pill.addSubview(icon)
+ pill.addSubview(label)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ func show(_ badge: DropDecor.Badge, colors: SidebarColors) {
+ layer?.borderColor = colors.textPrimary.withAlphaComponent(0.3).cgColor
+ pill.layer?.backgroundColor = NSColor.white.withAlphaComponent(colors.isDark ? 0.14 : 0.9).cgColor
+ icon.image = SidebarSymbols.image(badge.symbol, size: 10, weight: .semibold)
+ icon.contentTintColor = colors.textPrimary
+ label.stringValue = badge.label
+ label.textColor = colors.textPrimary
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ let ls = label.intrinsicContentSize
+ let w = 8 + 12 + 4 + ls.width + 8
+ pill.frame = NSRect(x: bounds.width - 8 - w, y: (bounds.height - 22) / 2, width: w, height: 22)
+ icon.frame = NSRect(x: 8, y: 5, width: 12, height: 12)
+ label.frame = NSRect(x: 24, y: (22 - ls.height) / 2, width: ls.width, height: ls.height)
+ }
+}
+
+// MARK: - Tab row
+
+struct TabRowModel: Equatable {
+ var id: UUID
+ var depth: Int
+ var pinned: Bool
+ var title: String
+ var customTitle: Bool
+ var renameText: String
+ var subtitle: String?
+ var icon: NSImage?
+ var flipIcon: Bool
+ var githubMark: Bool
+ var editing: Bool
+ var selected: Bool
+ var highlighted: Bool
+ var capturing: Bool
+ var muted: Bool
+ var unread: Bool
+ var navigatedAway: Bool
+ var closeGroup: Int
+ var focusRing: Bool
+}
+
+final class TabRowView: SidebarRowView, ArcTooltipTarget, NSTextFieldDelegate {
+ private(set) var model: TabRowModel?
+ private let favicon = SidebarFaviconView()
+ private let titleLabel = NSTextField.sidebarLabel(size: 14)
+ private let subtitleLabel = NSTextField.sidebarLabel(size: 11)
+ private var renameField: NSTextField?
+ private var accessories: [NSView] = []
+ private var focusRing: FocusRingLayer?
+
+ override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
+ super.init(key: key, list: list, colors: colors)
+ addSubview(favicon)
+ addSubview(titleLabel)
+ addSubview(subtitleLabel)
+ setAccessibilityElement(true)
+ setAccessibilityRole(.button)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func apply(_ m: TabRowModel) {
+ guard m != model else { return }
+ model = m
+ if m.githubMark { favicon.showGitHubMark(colors: colors) } else { favicon.show(m.icon, flip: m.flipIcon, colors: colors) }
+ titleLabel.stringValue = m.title
+ titleLabel.textColor = colors.textPrimary
+ subtitleLabel.stringValue = m.subtitle ?? ""
+ subtitleLabel.textColor = colors.textTertiary
+ subtitleLabel.isHidden = m.subtitle == nil
+ setAccessibilityLabel(m.title)
+ if m.editing != (renameField != nil) { m.editing ? beginRename(m.renameText) : endRename() }
+ if m.focusRing != (focusRing != nil) {
+ if m.focusRing {
+ let r = FocusRingLayer()
+ r.frame = bounds
+ r.zPosition = 10
+ layer?.addSublayer(r)
+ focusRing = r
+ } else {
+ focusRing?.removeFromSuperlayer()
+ focusRing = nil
+ }
+ }
+ rebuildAccessories()
+ refreshBackground()
+ }
+
+ override func setColors(_ c: SidebarColors) {
+ guard c != colors else { return }
+ super.setColors(c)
+ if let m = model { model = nil; apply(m) }
+ }
+
+ override func baseFill() -> NSColor {
+ guard let m = model else { return .clear }
+ return m.highlighted ? colors.selectedFill : (isHovered ? colors.hoverFill : .clear)
+ }
+
+ override func refreshBackground() {
+ super.refreshBackground()
+ let lifted = model?.highlighted == true && !colors.isDark && decor.combine == nil
+ layer?.shadowOpacity = lifted ? 0.06 : 0
+ if lifted {
+ layer?.shadowColor = NSColor.black.cgColor
+ layer?.shadowRadius = 3
+ layer?.shadowOffset = CGSize(width: 0, height: -1)
+ layer?.shadowPath = CGPath(roundedRect: fillRect, cornerWidth: CraMetrics.rowCorner, cornerHeight: CraMetrics.rowCorner, transform: nil)
+ }
+ }
+
+ override func hoverChanged() {
+ super.hoverChanged()
+ rebuildAccessories()
+ }
+
+ /// Recording dot, mute, unread dot, and on hover "back to pinned page" and close. Made once
+ /// per row and shown or hidden: hover moves from row to row on every frame of a scroll.
+ private lazy var captureDot: NSView = {
+ let dot = NSView(frame: NSRect(x: 0, y: 0, width: 16, height: 16))
+ let c = CALayer()
+ c.frame = CGRect(x: 4.5, y: 4.5, width: 7, height: 7)
+ c.cornerRadius = 3.5
+ c.backgroundColor = NSColor.systemRed.cgColor
+ dot.wantsLayer = true
+ dot.layer?.addSublayer(c)
+ _ = ArcTooltipAnchorView.attach(to: dot, help: "This tab is using your camera or microphone")
+ return dot
+ }()
+ private lazy var muteButton = SidebarGlyphButton(symbol: "speaker.slash.fill", size: 20, iconSize: 10, help: "Unmute Tab", colors: colors) { [weak self] in
+ guard let self, let id = self.model?.id, let list = self.list else { return }
+ list.store.setMuted(id, false)
+ list.actions.performAction("muteTab:\(id)")
+ }
+ private lazy var unreadDot: NSView = {
+ let dot = NSView(frame: NSRect(x: 0, y: 0, width: 6, height: 6))
+ dot.wantsLayer = true
+ dot.layer?.cornerRadius = 3
+ return dot
+ }()
+ private lazy var resetButton = SidebarGlyphButton(symbol: "arrow.uturn.backward", size: 22, iconSize: 13, help: "Back to pinned page", colors: colors) { [weak self] in
+ guard let self, let id = self.model?.id else { return }
+ self.list?.actions.resetPinnedTab(id)
+ }
+ private lazy var closeButton = SidebarGlyphButton(symbol: "xmark", size: Self.closeSize, iconSize: 13, help: "", colors: colors) {}
+ private static let closeSize: CGFloat = 22
+ private var closeKind = ""
+
+ private func rebuildAccessories() {
+ guard let m = model, list != nil else { return }
+ let id = m.id
+ var shown: [NSView] = []
+ if m.capturing { shown.append(captureDot) }
+ if m.muted { muteButton.colors = colors; shown.append(muteButton) }
+ if m.unread && !m.selected && !isHovered {
+ unreadDot.layer?.backgroundColor = colors.textPrimary.withAlphaComponent(0.55).cgColor
+ shown.append(unreadDot)
+ }
+ if isHovered && !m.editing {
+ if m.navigatedAway { resetButton.colors = colors; shown.append(resetButton) }
+ // Arc: the open pinned tab shows a minus (it unloads and stays pinned); any other pinned
+ // tab an ✕ that archives it out of the pinned section; Today tabs an ✕ that archives.
+ let kind = m.closeGroup > 1 ? "group\(m.closeGroup)" : (m.pinned && m.selected ? "keep" : (m.pinned ? "archivePinned" : "archive"))
+ if kind != closeKind {
+ closeKind = kind
+ switch kind {
+ case "keep":
+ closeButton.setSymbol("minus", iconSize: 13, help: "Close and Keep Pinned (⌘W)")
+ closeButton.action = { [weak self] in self?.list?.closeTabs([id]) }
+ case "archivePinned":
+ closeButton.setSymbol("xmark", iconSize: 13, help: "Archive this tab")
+ closeButton.action = { [weak self] in self?.list?.store.archiveTab(id, reason: .manual) }
+ default:
+ closeButton.setSymbol("xmark", iconSize: 13, help: m.closeGroup > 1 ? "Close \(m.closeGroup) Tabs (⌘W)" : "Archive (⌘W)")
+ closeButton.action = { [weak self] in
+ guard let list = self?.list else { return }
+ list.closeTabs(list.closeGroup(for: id))
+ }
+ }
+ }
+ closeButton.colors = colors
+ shown.append(closeButton)
+ }
+ guard shown.map(ObjectIdentifier.init) != accessories.map(ObjectIdentifier.init) else { return }
+ for v in accessories where !shown.contains(where: { $0 === v }) { v.isHidden = true }
+ for v in shown {
+ if v.superview == nil { addSubview(v) }
+ v.isHidden = false
+ }
+ accessories = shown
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ guard let m = model else { return }
+ let h = bounds.height
+ var x = 8 + CGFloat(m.depth) * CraMetrics.indent
+ favicon.frame = NSRect(x: x, y: (h - CraMetrics.favicon) / 2, width: CraMetrics.favicon, height: CraMetrics.favicon)
+ x += CraMetrics.favicon + 11
+ // HStack(spacing: 11) with a Spacer(minLength: 4) between the text and the trailing items.
+ var right = bounds.width - 6
+ for v in accessories.reversed() {
+ // The unread dot is centred where the close button shows on hover, which is also
+ // under a live folder's refresh button (FolderRowView, Arc lines them up too).
+ let s = v.frame.size
+ let slot = v === unreadDot ? Self.closeSize : s.width
+ v.frame = NSRect(x: right - slot / 2 - s.width / 2, y: (h - s.height) / 2, width: s.width, height: s.height)
+ right = v.frame.minX - 11
+ }
+ let textWidth = max(0, right - 4 - 11 - x)
+ let th = titleLabel.intrinsicContentSize.height
+ if m.subtitle != nil {
+ let sh = subtitleLabel.intrinsicContentSize.height
+ let top = (h - th - 1 - sh) / 2
+ titleLabel.frame = NSRect(x: x - SidebarText.inset, y: top, width: textWidth + 2 * SidebarText.inset, height: th)
+ subtitleLabel.frame = NSRect(x: x - SidebarText.inset, y: top + th + 1, width: textWidth + 2 * SidebarText.inset, height: sh)
+ } else {
+ titleLabel.frame = NSRect(x: x - SidebarText.inset, y: (h - th) / 2, width: textWidth + 2 * SidebarText.inset, height: th)
+ }
+ if let f = renameField {
+ let fh = f.intrinsicContentSize.height
+ f.frame = NSRect(x: x - SidebarText.inset, y: (h - fh) / 2, width: max(0, bounds.width - 6 - x + SidebarText.inset), height: fh)
+ }
+ focusRing?.frame = fillRect
+ if layer?.shadowOpacity ?? 0 > 0 {
+ layer?.shadowPath = CGPath(roundedRect: fillRect, cornerWidth: CraMetrics.rowCorner, cornerHeight: CraMetrics.rowCorner, transform: nil)
+ }
+ }
+
+ // MARK: Rename
+
+ private func beginRename(_ text: String) {
+ let f = NSTextField(string: text)
+ f.isBordered = false
+ f.drawsBackground = false
+ f.focusRingType = .none
+ f.font = .systemFont(ofSize: 14)
+ f.textColor = colors.textPrimary
+ f.delegate = self
+ f.cell?.isScrollable = true
+ renameField = f
+ addSubview(f)
+ titleLabel.isHidden = true
+ subtitleLabel.isHidden = true
+ needsLayout = true
+ DispatchQueue.main.async { [weak self, weak f] in
+ guard let f, let w = self?.window else { return }
+ w.makeFirstResponder(f)
+ }
+ }
+
+ private func endRename() {
+ guard let f = renameField else { return }
+ renameField = nil
+ f.delegate = nil
+ if let w = window, let editor = f.currentEditor(), w.firstResponder === editor { w.makeFirstResponder(nil) }
+ f.removeFromSuperview()
+ titleLabel.isHidden = false
+ subtitleLabel.isHidden = model?.subtitle == nil
+ }
+
+ private func commitRename() {
+ guard let m = model, let list, list.ui.renamingID == m.id, let f = renameField else { return }
+ list.store.rename(m.id, to: f.stringValue)
+ list.ui.renamingID = nil
+ }
+
+ func control(_ control: NSControl, textView: NSTextView, doCommandBy sel: Selector) -> Bool {
+ if sel == #selector(NSResponder.cancelOperation(_:)) { list?.ui.renamingID = nil; return true }
+ if sel == #selector(NSResponder.insertNewline(_:)) { commitRename(); return true }
+ return false
+ }
+
+ func controlTextDidEndEditing(_ obj: Notification) { commitRename() }
+
+ // MARK: Events
+
+ override func dragItemID(at point: NSPoint) -> UUID? { model?.editing == true ? nil : model?.id }
+
+ override func click(_ event: NSEvent, at point: NSPoint) {
+ guard let m = model, let list else { return }
+ // A click on the row (not the field) ends a rename, so it can never get stuck.
+ if m.editing { commitRename() }
+ list.clickTab(m.id, event: event)
+ }
+
+ override func contextMenu(at point: NSPoint) -> NSMenu? {
+ guard let m = model, let list else { return nil }
+ return SidebarMenus.tab(m, list: list)
+ }
+
+ override func tooltipTarget(at point: NSPoint) -> (any ArcTooltipTarget)? { self }
+
+ // ArcTooltipTarget: the title by the pointer; like Arc (didShowRenameHint),
+ // "Double-click to rename" rides along once.
+ var text: String { model.map { $0.editing ? "" : $0.title } ?? "" }
+ var keys: [String] { [] }
+ var followsCursor: Bool { true }
+ var subtitle: String? {
+ UserDefaults.standard.bool(forKey: "didShowRenameHint") || model?.customTitle != false ? nil : "Double-click to rename"
+ }
+ var optionText: String? { nil }
+ var onShow: (() -> Void)? {
+ { [weak self] in
+ if self?.model?.customTitle == false { UserDefaults.standard.set(true, forKey: "didShowRenameHint") }
+ }
+ }
+ var screenFrame: NSRect { window?.convertToScreen(convert(bounds, to: nil)) ?? .zero }
+ var hostWindow: NSWindow? { window }
+}
+
+// MARK: - Folder row
+
+struct FolderRowModel: Equatable {
+ var id: UUID
+ var depth: Int
+ var title: String
+ var renameText: String
+ var editing: Bool
+ var expanded: Bool
+ var live: Bool
+ var tint: NSColor
+ var fill: NSColor
+ var tabCount: Int
+ var liveBusy: Bool
+ /// The warning button's tip after a failed refresh.
+ var liveError: String?
+ /// Where the warning button signs in, when GitHub asked for that (else it tries again).
+ var liveSignInURL: String?
+ var liveHelp: String
+}
+
+final class FolderRowView: SidebarRowView, NSTextFieldDelegate {
+ private(set) var model: FolderRowModel?
+ private let glyph = FolderGlyphView(frame: NSRect(x: 0, y: 0, width: CraMetrics.favicon, height: 20))
+ private let titleLabel = NSTextField.sidebarLabel(size: 14, weight: .medium)
+ private var renameField: NSTextField?
+ private var accessory: NSView?
+
+ override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
+ super.init(key: key, list: list, colors: colors)
+ addSubview(glyph)
+ addSubview(titleLabel)
+ setAccessibilityElement(true)
+ setAccessibilityRole(.button)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func apply(_ m: FolderRowModel) {
+ guard m != model else { return }
+ model = m
+ glyph.show(expanded: m.expanded, live: m.live, tint: m.tint, fillColor: m.fill)
+ titleLabel.stringValue = m.title
+ titleLabel.textColor = colors.textPrimary
+ setAccessibilityLabel(m.title)
+ if m.editing != (renameField != nil) { m.editing ? beginRename(m.renameText) : endRename() }
+ rebuildAccessory()
+ refreshBackground()
+ }
+
+ override func setColors(_ c: SidebarColors) {
+ guard c != colors else { return }
+ super.setColors(c)
+ if let m = model { model = nil; apply(m) }
+ }
+
+ override func baseFill() -> NSColor { isHovered ? colors.hoverFill : .clear }
+
+ override func hoverChanged() {
+ super.hoverChanged()
+ rebuildAccessory()
+ }
+
+ /// A live folder's refresh button (spinner while it runs, warning after a failure);
+ /// a closed folder's tab count on hover.
+ private func rebuildAccessory() {
+ accessory?.removeFromSuperview()
+ accessory = nil
+ guard let m = model, let list else { return }
+ let id = m.id
+ let hover = isHovered && !m.editing
+ if m.live {
+ if m.liveBusy {
+ // A spinner fills its frame: the glyph's size, centred where the refresh button sits.
+ let slot = NSView(frame: NSRect(x: 0, y: 0, width: 26, height: 26))
+ let p = NSProgressIndicator(frame: NSRect(x: 7, y: 7, width: 12, height: 12))
+ p.style = .spinning
+ p.controlSize = .mini
+ p.isIndeterminate = true
+ p.startAnimation(nil)
+ slot.addSubview(p)
+ accessory = slot
+ } else if let error = m.liveError {
+ // Arc keeps the warning on hover too ("Sign back in to GitHub."): a click signs in, or tries again.
+ let signIn = m.liveSignInURL
+ accessory = SidebarGlyphButton(symbol: "exclamationmark.triangle", size: 26, iconSize: 13, weight: .regular,
+ help: error, colors: colors) { [weak list] in
+ if let signIn { list?.actions.openURL(signIn) } else { LiveFolderManager.shared.refresh(id) }
+ }
+ } else if hover {
+ accessory = SidebarGlyphButton(symbol: "arrow.clockwise", size: 26, iconSize: 12, help: m.liveHelp, colors: colors) {
+ LiveFolderManager.shared.refresh(id)
+ }
+ }
+ } else if hover && !m.expanded {
+ let l = NSTextField.sidebarLabel(size: 11, weight: .medium)
+ l.stringValue = "\(m.tabCount)"
+ l.textColor = colors.textTertiary
+ l.sizeToFit()
+ accessory = l
+ }
+ _ = list
+ if let a = accessory { addSubview(a) }
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ guard let m = model else { return }
+ let h = bounds.height
+ var x = 8 + CGFloat(m.depth) * CraMetrics.indent
+ glyph.frame = NSRect(x: x, y: (h - 20) / 2, width: CraMetrics.favicon, height: 20)
+ x += CraMetrics.favicon + 11
+ var right = bounds.width
+ if let a = accessory {
+ let s = a.frame.size
+ // A live folder's button is centred over its tabs' unread dots and close buttons (17 pt in).
+ right -= (m.live ? 4 : 8) + s.width
+ a.frame = NSRect(x: right, y: (h - s.height) / 2, width: s.width, height: s.height)
+ right -= 11
+ }
+ let th = titleLabel.intrinsicContentSize.height
+ titleLabel.frame = NSRect(x: x - SidebarText.inset, y: (h - th) / 2, width: max(0, right - 8 - 11 - x) + 2 * SidebarText.inset, height: th)
+ if let f = renameField {
+ let fh = f.intrinsicContentSize.height
+ f.frame = NSRect(x: x - SidebarText.inset, y: (h - fh) / 2, width: max(0, bounds.width - 8 - x + SidebarText.inset), height: fh)
+ }
+ }
+
+ private func beginRename(_ text: String) {
+ let f = NSTextField(string: text)
+ f.isBordered = false
+ f.drawsBackground = false
+ f.focusRingType = .none
+ f.font = .systemFont(ofSize: 14, weight: .medium)
+ f.textColor = colors.textPrimary
+ f.delegate = self
+ f.cell?.isScrollable = true
+ renameField = f
+ addSubview(f)
+ titleLabel.isHidden = true
+ needsLayout = true
+ DispatchQueue.main.async { [weak self, weak f] in
+ guard let f, let w = self?.window else { return }
+ w.makeFirstResponder(f)
+ }
+ }
+
+ private func endRename() {
+ guard let f = renameField else { return }
+ renameField = nil
+ f.delegate = nil
+ if let w = window, let editor = f.currentEditor(), w.firstResponder === editor { w.makeFirstResponder(nil) }
+ f.removeFromSuperview()
+ titleLabel.isHidden = false
+ }
+
+ private func commitRename() {
+ guard let m = model, let list, list.ui.renamingID == m.id, let f = renameField else { return }
+ list.store.rename(m.id, to: f.stringValue.isEmpty ? "Folder" : f.stringValue)
+ list.ui.renamingID = nil
+ }
+
+ func control(_ control: NSControl, textView: NSTextView, doCommandBy sel: Selector) -> Bool {
+ if sel == #selector(NSResponder.cancelOperation(_:)) { list?.ui.renamingID = nil; return true }
+ if sel == #selector(NSResponder.insertNewline(_:)) { commitRename(); return true }
+ return false
+ }
+
+ func controlTextDidEndEditing(_ obj: Notification) { commitRename() }
+
+ override func dragItemID(at point: NSPoint) -> UUID? { model?.editing == true ? nil : model?.id }
+
+ // Every click toggles, however fast they come: double-click-to-rename made quick
+ // open/close clicks start a rename that then swallowed the clicks. Rename is in the menu.
+ override func click(_ event: NSEvent, at point: NSPoint) {
+ guard let m = model, let list else { return }
+ if m.editing { commitRename() }
+ list.store.setExpanded(m.id, !m.expanded)
+ }
+
+ override func contextMenu(at point: NSPoint) -> NSMenu? {
+ guard let m = model, let list, let item = list.store.item(m.id) else { return nil }
+ return item.isLiveFolder ? SidebarMenus.liveFolder(item, list: list) : SidebarMenus.folder(item, list: list)
+ }
+}
+
+// MARK: - Split row
+
+struct SplitRowModel: Equatable {
+ struct Cell: Equatable {
+ var id: UUID
+ var title: String
+ var icon: NSImage?
+ var flipIcon: Bool
+ }
+ var id: UUID
+ var depth: Int
+ var today: Bool
+ var selected: Bool
+ var focusRing: Bool
+ var cells: [Cell]
+}
+
+/// Arc's split cell (SplitViewCellView): the panes side by side, hairlines between them.
+final class SplitRowView: SidebarRowView {
+ private(set) var model: SplitRowModel?
+ private var cells: [SplitCellView] = []
+ private var separators: [NSView] = []
+ private var focusRing: FocusRingLayer?
+
+ func apply(_ m: SplitRowModel) {
+ guard m != model else { return }
+ model = m
+ if cells.map(\.cellID) != m.cells.map(\.id) {
+ cells.forEach { $0.removeFromSuperview() }
+ separators.forEach { $0.removeFromSuperview() }
+ cells = m.cells.map { SplitCellView(cellID: $0.id, row: self) }
+ separators = (0..<max(0, m.cells.count - 1)).map { _ in
+ let v = NSView()
+ v.wantsLayer = true
+ return v
+ }
+ cells.forEach { addSubview($0) }
+ separators.forEach { addSubview($0) }
+ }
+ for (c, cm) in zip(cells, m.cells) { c.apply(cm, colors: colors) }
+ for s in separators { s.layer?.backgroundColor = colors.separator.cgColor }
+ if m.focusRing != (focusRing != nil) {
+ if m.focusRing {
+ let r = FocusRingLayer()
+ r.zPosition = 10
+ layer?.addSublayer(r)
+ focusRing = r
+ } else {
+ focusRing?.removeFromSuperlayer()
+ focusRing = nil
+ }
+ }
+ refreshBackground()
+ needsLayout = true
+ }
+
+ override func setColors(_ c: SidebarColors) {
+ guard c != colors else { return }
+ super.setColors(c)
+ if let m = model { model = nil; apply(m) }
+ }
+
+ override func baseFill() -> NSColor {
+ guard let m = model else { return .clear }
+ return m.selected ? colors.selectedFill : (isHovered ? colors.hoverFill : .clear)
+ }
+
+ override func refreshBackground() {
+ super.refreshBackground()
+ let lifted = model?.selected == true && !colors.isDark && decor.combine == nil
+ layer?.shadowOpacity = lifted ? 0.06 : 0
+ if lifted {
+ layer?.shadowColor = NSColor.black.cgColor
+ layer?.shadowRadius = 3
+ layer?.shadowOffset = CGSize(width: 0, height: -1)
+ layer?.shadowPath = CGPath(roundedRect: fillRect, cornerWidth: CraMetrics.rowCorner, cornerHeight: CraMetrics.rowCorner, transform: nil)
+ }
+ }
+
+ override func hoverChanged() {
+ super.hoverChanged()
+ if !isHovered { cells.forEach { $0.hovering = false } }
+ }
+
+ override func hoverMoved(to point: NSPoint) {
+ for c in cells { c.hovering = c.frame.contains(point) }
+ }
+
+ override func layout() {
+ super.layout()
+ guard let m = model, !cells.isEmpty else { return }
+ let x0 = CGFloat(m.depth) * CraMetrics.indent
+ let n = CGFloat(cells.count)
+ let w = (bounds.width - x0 - (n - 1)) / n
+ var x = x0
+ for (i, c) in cells.enumerated() {
+ if i > 0 {
+ separators[i - 1].frame = NSRect(x: x, y: SplitRowMetrics.separatorInset, width: 1, height: bounds.height - 2 * SplitRowMetrics.separatorInset)
+ x += 1
+ }
+ c.frame = NSRect(x: x, y: 0, width: w, height: bounds.height)
+ x += w
+ }
+ focusRing?.frame = fillRect
+ }
+
+ private func cell(at point: NSPoint) -> SplitCellView? { cells.first { $0.frame.contains(point) } }
+
+ override func dragItemID(at point: NSPoint) -> UUID? { cell(at: point)?.cellID }
+
+ override func click(_ event: NSEvent, at point: NSPoint) {
+ guard let c = cell(at: point), let list else { return }
+ list.store.selectTab(c.cellID, window: list.ui.windowID)
+ }
+
+ override func contextMenu(at point: NSPoint) -> NSMenu? {
+ guard let m = model, let list else { return nil }
+ if let c = cell(at: point) { return SidebarMenus.splitCell(c.cellID, list: list) }
+ return SidebarMenus.split(m, list: list)
+ }
+
+ override func tooltipTarget(at point: NSPoint) -> (any ArcTooltipTarget)? { cell(at: point) }
+}
+
+enum SplitRowMetrics {
+ static let separatorInset: CGFloat = 9
+}
+
+/// One pane inside the split row (Arc: SplitViewCellChildItemView).
+final class SplitCellView: NSView, ArcTooltipTarget {
+ let cellID: UUID
+ private weak var row: SplitRowView?
+ private let favicon = SidebarFaviconView()
+ private let titleLabel = NSTextField.sidebarLabel(size: 14)
+ private var close: SidebarGlyphButton?
+ private var title = ""
+ var hovering = false { didSet { if hovering != oldValue { refreshClose() } } }
+
+ init(cellID: UUID, row: SplitRowView) {
+ self.cellID = cellID
+ self.row = row
+ super.init(frame: .zero)
+ addSubview(favicon)
+ addSubview(titleLabel)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+ // Presses go to the row, which knows which pane they are on; the close button keeps its own.
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ if let close, close.frame.contains(convert(point, from: superview)) { return close }
+ return nil
+ }
+
+ func apply(_ m: SplitRowModel.Cell, colors: SidebarColors) {
+ title = m.title
+ favicon.show(m.icon, flip: m.flipIcon, colors: colors)
+ titleLabel.stringValue = m.title
+ titleLabel.textColor = colors.textPrimary
+ close?.colors = colors
+ needsLayout = true
+ }
+
+ private func refreshClose() {
+ close?.removeFromSuperview()
+ close = nil
+ guard hovering, let row, let list = row.list else { needsLayout = true; return }
+ let id = cellID
+ let b = SidebarGlyphButton(symbol: "xmark", size: 20, iconSize: 11, help: "Close pane", optionHelp: "Separate from Split View", colors: row.colors) { [weak list] in
+ // Option-click un-splits instead of closing (Arc flag option-click-split-tab-close-button-to-unsplit).
+ if NSEvent.modifierFlags.contains(.option) { list?.store.separateFromSplit(id) } else { list?.actions.closeTab(id) }
+ }
+ addSubview(b)
+ close = b
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ favicon.frame = NSRect(x: 8, y: (h - CraMetrics.favicon) / 2, width: CraMetrics.favicon, height: CraMetrics.favicon)
+ var right = bounds.width - 4
+ if let close {
+ right -= 20
+ close.frame = NSRect(x: right, y: (h - 20) / 2, width: 20, height: 20)
+ right -= 8
+ }
+ let th = titleLabel.intrinsicContentSize.height
+ let x = 8 + CraMetrics.favicon + 8
+ titleLabel.frame = NSRect(x: x - SidebarText.inset, y: (h - th) / 2, width: max(0, right - 2 - 8 - x) + 2 * SidebarText.inset, height: th)
+ }
+
+ var text: String { title }
+ var keys: [String] { [] }
+ var followsCursor: Bool { true }
+ var subtitle: String? { nil }
+ var optionText: String? { nil }
+ var onShow: (() -> Void)? { nil }
+ var screenFrame: NSRect { window?.convertToScreen(convert(bounds, to: nil)) ?? .zero }
+ var hostWindow: NSWindow? { window }
+}
+
+// MARK: - Small rows
+
+struct LiveStatusModel: Equatable {
+ var text: String
+ var url: String?
+ var depth: Int
+}
+
+/// A line inside an open live folder with nothing to show, or when GitHub can't be read.
+final class LiveStatusRowView: SidebarRowView {
+ private(set) var model: LiveStatusModel?
+ private let label: NSTextField = {
+ let l = NSTextField(wrappingLabelWithString: "")
+ l.font = .systemFont(ofSize: 12)
+ l.maximumNumberOfLines = 3
+ l.lineBreakMode = .byTruncatingTail
+ return l
+ }()
+
+ override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
+ super.init(key: key, list: list, colors: colors)
+ addSubview(label)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ static func leading(depth: Int) -> CGFloat { 8 + CGFloat(depth) * CraMetrics.indent + CraMetrics.favicon + 11 }
+
+ static func height(_ m: LiveStatusModel, width: CGFloat) -> CGFloat {
+ let w = max(1, width - leading(depth: m.depth) - 10)
+ let font = NSFont.systemFont(ofSize: 12)
+ let line = ceil(font.ascender - font.descender + font.leading)
+ let r = (m.text as NSString).boundingRect(with: NSSize(width: w, height: line * 3), options: [.usesLineFragmentOrigin],
+ attributes: [.font: font])
+ return ceil(min(r.height, line * 3)) + 16
+ }
+
+ func apply(_ m: LiveStatusModel) {
+ guard m != model else { return }
+ model = m
+ label.stringValue = m.text
+ refreshColors()
+ needsLayout = true
+ }
+
+ private func refreshColors() {
+ label.textColor = model?.url != nil && isHovered ? colors.textSecondary : colors.textTertiary
+ }
+
+ override func setColors(_ c: SidebarColors) {
+ super.setColors(c)
+ refreshColors()
+ }
+
+ override func baseFill() -> NSColor { model?.url != nil && isHovered ? colors.hoverFill : .clear }
+
+ override func hoverChanged() {
+ super.hoverChanged()
+ refreshColors()
+ }
+
+ override func layout() {
+ super.layout()
+ guard let m = model else { return }
+ let x = Self.leading(depth: m.depth)
+ label.frame = NSRect(x: x - SidebarText.inset, y: 8, width: max(0, bounds.width - x - 10) + 2 * SidebarText.inset, height: max(0, bounds.height - 16))
+ }
+
+ override func click(_ event: NSEvent, at point: NSPoint) {
+ if let url = model?.url { list?.actions.openURL(url) }
+ }
+}
+
+final class NewTabRowView: SidebarRowView {
+ private let plus = NSImageView()
+ private let label = NSTextField.sidebarLabel(size: 14)
+
+ override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
+ super.init(key: key, list: list, colors: colors)
+ plus.image = SidebarSymbols.image("plus", size: 13, weight: .medium)
+ plus.imageScaling = .scaleNone
+ label.stringValue = "New Tab"
+ addSubview(plus)
+ addSubview(label)
+ setAccessibilityElement(true)
+ setAccessibilityRole(.button)
+ setAccessibilityLabel("New Tab")
+ refreshColors()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ private func refreshColors() {
+ let c = isHovered ? colors.textPrimary : colors.textSecondary
+ plus.contentTintColor = c
+ label.textColor = c
+ }
+
+ override func setColors(_ c: SidebarColors) {
+ super.setColors(c)
+ refreshColors()
+ }
+
+ override func baseFill() -> NSColor { isHovered ? colors.selectedFill : .clear }
+
+ override func hoverChanged() {
+ super.hoverChanged()
+ refreshColors()
+ }
+
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ plus.frame = NSRect(x: 8, y: 0, width: CraMetrics.favicon, height: h)
+ let th = label.intrinsicContentSize.height
+ let x = 8 + CraMetrics.favicon + 9
+ label.frame = NSRect(x: x - SidebarText.inset, y: (h - th) / 2, width: max(0, bounds.width - 10 - x) + 2 * SidebarText.inset, height: th)
+ }
+
+ override func click(_ event: NSEvent, at point: NSPoint) { list?.actions.openCommandBar(.newTab) }
+}
+
+/// The line between pinned and Today; "Clear" shows on hover.
+final class DividerRowView: SidebarRowView {
+ private let line = NSView()
+ private var clear: ClearButton?
+ private var hasToday = false
+
+ override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
+ super.init(key: key, list: list, colors: colors)
+ line.wantsLayer = true
+ addSubview(line)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var mouseDownCanMoveWindow: Bool { true }
+ override func mouseDown(with event: NSEvent) { super.mouseDown(with: event) }
+
+ func apply(hasToday: Bool) {
+ self.hasToday = hasToday
+ refresh()
+ }
+
+ override func setColors(_ c: SidebarColors) {
+ super.setColors(c)
+ refresh()
+ }
+
+ override func hoverChanged() { refresh() }
+
+ private func refresh() {
+ line.layer?.backgroundColor = colors.separator.cgColor
+ line.alphaValue = hasToday ? 1 : 0
+ let show = isHovered && hasToday
+ if show, clear == nil, let list {
+ let b = ClearButton(colors: colors) { [weak list] in
+ guard let list else { return }
+ list.store.clearToday(list.spaceID)
+ }
+ b.alphaValue = 0
+ addSubview(b)
+ clear = b
+ b.animator().alphaValue = 1
+ } else if !show, let b = clear {
+ clear = nil
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.15
+ b.animator().alphaValue = 0
+ } completionHandler: { b.removeFromSuperview() }
+ }
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ var right = bounds.width - 20
+ if let clear {
+ let s = clear.fittingSize
+ clear.frame = NSRect(x: right - s.width, y: (bounds.height - s.height) / 2, width: s.width, height: s.height)
+ right -= s.width + 8
+ }
+ line.frame = NSRect(x: 20, y: (bounds.height - 1) / 2, width: max(0, right - 20), height: 1)
+ }
+
+ private final class ClearButton: NSView {
+ private let label = NSTextField.sidebarLabel(size: 11, weight: .semibold)
+ private let action: () -> Void
+
+ init(colors: SidebarColors, action: @escaping () -> Void) {
+ self.action = action
+ super.init(frame: .zero)
+ label.stringValue = "Clear"
+ label.textColor = colors.textSecondary
+ label.sizeToFit()
+ addSubview(label)
+ frame.size = label.frame.size
+ _ = ArcTooltipAnchorView.attach(to: self, help: "Clear Today tabs")
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var fittingSize: NSSize { label.frame.size }
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func hitTest(_ point: NSPoint) -> NSView? { frame.contains(point) ? self : nil }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { action() }
+ }
+ }
+}
+
+/// "Drop to Pin": an empty pinned list opens a target while a drag is on.
+final class PinPlaceholderRowView: SidebarRowView {
+ private let border = CAShapeLayer()
+ private let icon = NSImageView()
+ private let label = NSTextField.sidebarLabel(size: 12, weight: .medium)
+ private var active = false
+
+ override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {
+ super.init(key: key, list: list, colors: colors)
+ border.fillColor = nil
+ border.lineWidth = 1
+ border.lineDashPattern = [4, 3]
+ layer?.addSublayer(border)
+ icon.image = SidebarSymbols.image("pin", size: 11, weight: .semibold)
+ icon.imageScaling = .scaleNone
+ label.stringValue = "Drop to Pin"
+ addSubview(icon)
+ addSubview(label)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func apply(active: Bool) {
+ self.active = active
+ refresh()
+ }
+
+ override func setColors(_ c: SidebarColors) {
+ super.setColors(c)
+ refresh()
+ }
+
+ override func baseFill() -> NSColor { active ? colors.hoverFill : .clear }
+
+ private func refresh() {
+ border.strokeColor = colors.textTertiary.withAlphaComponent(active ? 0.6 : 0.3).cgColor
+ icon.contentTintColor = colors.textSecondary
+ label.textColor = colors.textSecondary
+ refreshBackground()
+ }
+
+ override func layout() {
+ super.layout()
+ border.frame = bounds
+ border.path = CGPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), cornerWidth: CraMetrics.rowCorner, cornerHeight: CraMetrics.rowCorner, transform: nil)
+ let ls = label.intrinsicContentSize
+ let w = 14 + 6 + ls.width
+ let x = (bounds.width - w) / 2
+ icon.frame = NSRect(x: x, y: 0, width: 14, height: bounds.height)
+ label.frame = NSRect(x: x + 20, y: (bounds.height - ls.height) / 2, width: ls.width, height: ls.height)
+ }
+}
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarView.swift b/Sources/Cra/UI/Sidebar/List/SidebarView.swift
new file mode 100644
index 0000000..4f9484c
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/List/SidebarView.swift
@@ -0,0 +1,956 @@
+import AppKit
+
+/// The whole left column in AppKit, laid out like Arc: traffic lights + sidebar toggle with the
+/// nav buttons at the right of the top row, the space pager (favorites, header, tab list), the
+/// update banner and the dock. The Library takes the column over while it is open.
+@MainActor
+final class SidebarView: NSView {
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let actions: SidebarActions
+ private let favicons: FaviconCache
+ private let tabs = FlippedView()
+ private let topBar: SidebarTopBarView
+ private let pager: SpacePagerView
+ private let trayHost: DownloadsTrayView
+ private let trayMask = CAGradientLayer()
+ private let bannerHost = UpdateBannerView()
+ private let dock: SpaceDockView
+ private var libraryHost: LibraryView?
+ private var palette: SpacePalette
+ private var lastSpaceID: UUID?
+ private var shownLibrary: LibraryPage?
+
+ init(store: SidebarStore, ui: SidebarUIState, actions: SidebarActions, favicons: FaviconCache) {
+ self.store = store
+ self.ui = ui
+ self.actions = actions
+ self.favicons = favicons
+ palette = store.focusedSpace(window: ui.windowID).theme.palette
+ topBar = SidebarTopBarView(store: store, ui: ui, actions: actions)
+ pager = SpacePagerView(store: store, ui: ui, actions: actions, favicons: favicons)
+ trayHost = DownloadsTrayView(ui: ui)
+ dock = SpaceDockView(store: store, ui: ui, actions: actions)
+ super.init(frame: .zero)
+ wantsLayer = true
+ pager.wantsLayer = true
+ trayMask.startPoint = CGPoint(x: 0.5, y: 0)
+ trayMask.endPoint = CGPoint(x: 0.5, y: 1)
+ for v in [topBar, pager, trayHost, bannerHost, dock] as [NSView] { tabs.addSubview(v) }
+ addSubview(tabs)
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private func observe() {
+ var bannerHeight: CGFloat = 0
+ let (space, library, trayOpen, recentCount) = withObservationTracking {
+ let space = store.focusedSpace(window: ui.windowID)
+ bannerHeight = UpdateBannerView.isShown ? 60 : 0
+ return (space, ui.libraryPage, ui.downloadsListOpen, DownloadHistory.shared.recent.count)
+ } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ let paletteChanged = lastSpaceID == nil || space.theme != store.space(lastSpaceID ?? space.id)?.theme || space.id != lastSpaceID
+ if space.id != lastSpaceID {
+ if lastSpaceID != nil { ui.clearPicks() }
+ lastSpaceID = space.id
+ }
+ if paletteChanged || palette.isDark != space.theme.palette.isDark {
+ palette = space.theme.palette
+ let colors = SidebarColors(palette)
+ trayHost.colors = colors
+ bannerHost.colors = colors
+ libraryHost?.palette = palette
+ }
+ self.bannerHeight = bannerHeight
+ updateTrayMask(open: trayOpen, rows: recentCount)
+ showLibrary(library)
+ needsLayout = true
+ }
+
+ private var bannerHeight: CGFloat = 0
+
+ /// DownloadsTrayMask: the tab list is hidden from 3 pt above the downloads list's first row
+ /// and fades back in over the 170 pt above that.
+ private func updateTrayMask(open: Bool, rows: Int) {
+ let h = max(pager.bounds.height, 1)
+ let clearTop = max(0, h - DownloadsTrayMetrics.listHeight(rows: rows) - 1)
+ let fadeTop = max(0, clearTop - DownloadsTrayMetrics.fade)
+ CATransaction.begin()
+ CATransaction.setAnimationDuration(open ? 0.18 : 0.13)
+ if !open { CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: .easeOut)) }
+ trayMask.frame = pager.bounds
+ trayMask.locations = [0, NSNumber(value: Double(fadeTop / h)), NSNumber(value: Double(clearTop / h)), 1]
+ let opaque = NSColor.black.cgColor, clear = NSColor.clear.cgColor
+ trayMask.colors = open ? [opaque, opaque, clear, clear] : [opaque, opaque, opaque, opaque]
+ CATransaction.commit()
+ if pager.layer?.mask !== trayMask { pager.layer?.mask = trayMask }
+ trayHost.isHidden = rows == 0
+ }
+
+ /// The Library takes over the column: in from a little to the left, out to the left past its
+ /// rail while the tab list fades back in.
+ private func showLibrary(_ page: LibraryPage?) {
+ guard page != shownLibrary else { return }
+ let opening = shownLibrary == nil && page != nil
+ shownLibrary = page
+ if let page {
+ let host = libraryHost ?? {
+ let h = LibraryView(page: page, palette: palette, store: store, actions: actions, favicons: favicons)
+ addSubview(h)
+ libraryHost = h
+ return h
+ }()
+ host.page = page
+ host.frame = bounds
+ if opening {
+ host.alphaValue = 0
+ host.frame = bounds.offsetBy(dx: -24, dy: 0)
+ }
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.05
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ host.animator().alphaValue = 1
+ host.animator().frame = bounds
+ tabs.animator().alphaValue = 0
+ }
+ } else if let host = libraryHost {
+ libraryHost = nil
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.1
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ host.animator().alphaValue = 0
+ host.animator().frame = bounds.offsetBy(dx: -LibraryMetrics.rail, dy: 0)
+ tabs.animator().alphaValue = 1
+ } completionHandler: {
+ host.removeFromSuperview()
+ }
+ }
+ }
+
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ if let host = libraryHost {
+ // `point` is in the superview's space; the host sits in this (flipped) view's.
+ let p = convert(point, from: superview)
+ return host.hitTest(p) ?? (bounds.contains(p) ? self : nil)
+ }
+ return super.hitTest(point)
+ }
+
+ override func layout() {
+ super.layout()
+ let b = bounds
+ tabs.frame = b
+ libraryHost?.frame = b
+ let th = topBar.preferredHeight
+ topBar.frame = NSRect(x: 0, y: 0, width: b.width, height: th)
+ // Arc's list viewport ends 50 pt above the window bottom; the dock sits centred in that band.
+ let dockH: CGFloat = 36
+ dock.frame = NSRect(x: 10, y: b.height - 6 - dockH, width: b.width - 20, height: dockH)
+ let bannerTop = b.height - 6 - dockH - 8 - bannerHeight
+ bannerHost.frame = NSRect(x: 0, y: bannerTop, width: b.width, height: bannerHeight)
+ pager.frame = NSRect(x: 0, y: th, width: b.width, height: max(0, bannerTop - th))
+ let rows = DownloadHistory.shared.recent.count
+ let trayH = DownloadsTrayMetrics.listHeight(rows: rows) + 4
+ trayHost.frame = NSRect(x: 0, y: pager.frame.maxY - trayH, width: b.width, height: trayH)
+ updateTrayMask(open: ui.downloadsListOpen, rows: rows)
+ }
+}
+
+/// A container that lays its subviews out from the top.
+final class FlippedView: NSView {
+ override var isFlipped: Bool { true }
+}
+
+// MARK: - Top bar
+
+/// Row 1: traffic lights, the sidebar toggle right after them, nav buttons right-aligned. When
+/// the toolbar is hidden the URL pill moves into the sidebar on a second row.
+///
+/// Toolbar hidden, measured on Arc 1.170 (window capture and AX tree, 26 Oct): toggle and
+/// ← → ↻ are 32 pt buttons centred 1 pt above the traffic lights, the nav buttons 2 pt apart
+/// and 6 pt from the sidebar edge, no ⌄ menu. The URL pill spans the sidebar 8 pt in from each
+/// side, 36 pt tall, 2 pt under the title area, radius 10, the bare host in 13 pt at 12 pt in.
+/// Its accessories (pinned extensions, copy link, site controls) show while the header is hovered.
+final class SidebarTopBarView: NSView {
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let actions: SidebarActions
+ private var colors = SidebarColors()
+ private var compact = false
+ private var devNav = false
+ private var buttons: [String: SidebarGlyphButton] = [:]
+ private var rowButtons: [SidebarGlyphButton] = []
+ private var chevron: NSView?
+ private let pill = SidebarURLPill()
+ private var hoverHeader = false { didSet { if hoverHeader != oldValue { pill.showAccessories = hoverHeader } } }
+ private var syncQueued = false
+
+ var preferredHeight: CGFloat { CraMetrics.titleAreaHeight + (compact ? 2 + 36 + 8 : 0) }
+
+ init(store: SidebarStore, ui: SidebarUIState, actions: SidebarActions) {
+ self.store = store
+ self.ui = ui
+ self.actions = actions
+ super.init(frame: .zero)
+ pill.actions = actions
+ addSubview(pill)
+ sync()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private func sync() {
+ syncQueued = false
+ withObservationTracking { apply() } onChange: { [weak self] in
+ Task { @MainActor in
+ guard let self, !self.syncQueued else { return }
+ self.syncQueued = true
+ self.sync()
+ }
+ }
+ }
+
+ private func button(_ key: String, symbol: String, help: String, size: CGFloat, height: CGFloat, iconSize: CGFloat,
+ weight: NSFont.Weight = .regular, active: Bool?, enabled: Bool = true, action: @escaping () -> Void) -> SidebarGlyphButton {
+ let b = buttons[key] ?? {
+ let b = SidebarGlyphButton(symbol: symbol, size: size, height: height, iconSize: iconSize, weight: weight, help: help, colors: colors, action: action)
+ buttons[key] = b
+ addSubview(b)
+ return b
+ }()
+ b.setSymbol(symbol, iconSize: iconSize, weight: weight, help: help)
+ b.colors = colors
+ b.active = active
+ b.enabled = enabled
+ b.action = action
+ return b
+ }
+
+ private func apply() {
+ let wasCompact = compact
+ compact = !store.settings.showToolbar
+ colors = SidebarColors(store.focusedSpace(window: ui.windowID).theme.palette)
+ let tab = store.selectedTab(window: ui.windowID)
+ devNav = !compact && (tab?.tab.map { store.settings.isDeveloperMode(url: $0.url) } ?? false)
+ let active = ui.appActive
+ let reloadSymbol = ui.isLoading ? "xmark" : "arrow.clockwise"
+ var shown: [SidebarGlyphButton] = []
+ if compact {
+ // The toolbar carries the sidebar toggle; this one only stands in while the toolbar is hidden.
+ shown.append(button("toggle", symbol: "sidebar.left", help: "Hide Sidebar (⌘S)", size: 32, height: 32, iconSize: 15.5, active: active) { [weak self] in self?.actions.toggleSidebar() })
+ shown.append(button("back", symbol: "arrow.left", help: "Go Back (⌘[)", size: 32, height: 32, iconSize: 15, active: active, enabled: ui.canGoBack) { [weak self] in self?.actions.goBack() })
+ shown.append(button("forward", symbol: "arrow.right", help: "Go Forward (⌘])", size: 32, height: 32, iconSize: 15, active: active, enabled: ui.canGoForward) { [weak self] in self?.actions.goForward() })
+ shown.append(button("reload", symbol: reloadSymbol, help: "Refresh (⌘R)", size: 32, height: 32, iconSize: 15, active: active) { [weak self] in self?.actions.reload() })
+ } else if devNav {
+ shown.append(button("dback", symbol: "arrow.left", help: "Go Back (⌘[)", size: 34, height: 28, iconSize: 15, active: nil, enabled: ui.canGoBack) { [weak self] in self?.actions.goBack() })
+ shown.append(button("dforward", symbol: "arrow.right", help: "Go Forward (⌘])", size: 34, height: 28, iconSize: 15, active: nil, enabled: ui.canGoForward) { [weak self] in self?.actions.goForward() })
+ shown.append(button("dreload", symbol: reloadSymbol, help: "Refresh (⌘R)", size: 24, height: 24, iconSize: 15, active: nil) { [weak self] in self?.actions.reload() })
+ }
+ for (k, b) in buttons where !shown.contains(where: { $0 === b }) {
+ b.removeFromSuperview()
+ buttons[k] = nil
+ }
+ rowButtons = shown
+ if devNav, chevron == nil {
+ let c = DevMenuChevron(actions: actions)
+ addSubview(c)
+ chevron = c
+ } else if !devNav, let c = chevron {
+ c.removeFromSuperview()
+ chevron = nil
+ }
+ (chevron as? DevMenuChevron)?.tint = colors.textTertiary
+ pill.isHidden = !compact
+ if compact {
+ let url = tab?.tab?.url ?? ""
+ let host = URL(string: url)?.host ?? ""
+ let text = tab == nil ? "Search or Enter URL…" : (host.isEmpty ? SuggestionEngine.humanURL(url) : host.replacingOccurrences(of: "www.", with: ""))
+ let ext = ExtensionStore.shared
+ let pinned = ext.pinnedIDs.compactMap { id in ext.entries.first { $0.extensionID == id }.map { (id, $0.name, $0.icon) } }
+ pill.show(text: text, url: url, hasTab: tab != nil, status: ui.toolbarStatus, colors: colors, active: active,
+ pinned: pinned, hasExtensions: !ext.entries.isEmpty)
+ }
+ needsLayout = true
+ if wasCompact != compact { superview?.superview?.needsLayout = true }
+ }
+
+ override func layout() {
+ super.layout()
+ let w = bounds.width
+ if compact {
+ // Row 1: 71 pt for the traffic lights, the toggle, then ← → ↻ 2 pt apart, 6 pt from the edge.
+ let y = CraMetrics.titleRowCenter - 17
+ if let t = rowButtons.first { t.frame = NSRect(x: 6 + 71 + 2, y: y, width: 32, height: 32) }
+ var x = w - 6
+ for b in rowButtons.dropFirst().reversed() {
+ x -= 32
+ b.frame = NSRect(x: x, y: y, width: 32, height: 32)
+ x -= 2
+ }
+ pill.frame = NSRect(x: 8, y: CraMetrics.titleAreaHeight + 2, width: w - 16, height: 36)
+ } else if devNav {
+ let y = CraMetrics.titleRowCenter - 14
+ var x = w - 6
+ if let c = chevron {
+ x -= 12
+ c.frame = NSRect(x: x, y: y, width: 12, height: 28)
+ }
+ for b in rowButtons.reversed() {
+ x -= b.size.width
+ b.frame = NSRect(x: x, y: y + (28 - b.size.height) / 2, width: b.size.width, height: b.size.height)
+ }
+ }
+ }
+
+ // A double click on the empty strip does the title bar's double-click action; a drag moves
+ // the window.
+ override var mouseDownCanMoveWindow: Bool { false }
+ private var press: NSEvent?
+ override func mouseDown(with event: NSEvent) {
+ if event.clickCount == 2, convert(event.locationInWindow, from: nil).y < CraMetrics.titleAreaHeight {
+ press = nil
+ actions.titleBarDoubleClick()
+ return
+ }
+ press = event
+ }
+ override func mouseDragged(with event: NSEvent) {
+ guard let p = press else { return }
+ if hypot(event.locationInWindow.x - p.locationInWindow.x, event.locationInWindow.y - p.locationInWindow.y) > 3 {
+ press = nil
+ window?.performDrag(with: p)
+ }
+ }
+ override func mouseUp(with event: NSEvent) { press = nil }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+ override func mouseEntered(with event: NSEvent) { hoverHeader = true }
+ override func mouseExited(with event: NSEvent) { hoverHeader = false }
+}
+
+/// The ⌄ after the developer-mode nav buttons: page actions in a menu.
+private final class DevMenuChevron: NSView {
+ private let actions: SidebarActions
+ private let image = NSImageView()
+ var tint: NSColor = .tertiaryLabelColor { didSet { image.contentTintColor = tint } }
+
+ init(actions: SidebarActions) {
+ self.actions = actions
+ super.init(frame: .zero)
+ image.image = SidebarSymbols.image("chevron.down", size: 8, weight: .bold)
+ image.imageScaling = .scaleNone
+ image.autoresizingMask = [.width, .height]
+ addSubview(image)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func layout() {
+ super.layout()
+ image.frame = bounds
+ }
+
+ override func mouseDown(with event: NSEvent) {
+ let m = NSMenu()
+ m.autoenablesItems = false
+ let a = actions
+ MenuItems.add(m, "Refresh the Page") { a.performAction("reload") }
+ MenuItems.add(m, "Force Refresh the Page") { a.performAction("hardReload") }
+ m.addItem(.separator())
+ MenuItems.add(m, "View Source") { a.performAction("viewSource") }
+ MenuItems.add(m, "Developer Tools") { a.performAction("devTools") }
+ m.popUp(positioning: nil, at: NSPoint(x: 0, y: -4), in: self)
+ }
+}
+
+/// The URL pill on the sidebar's second row while the toolbar is hidden.
+final class SidebarURLPill: NSView {
+ var actions: SidebarActions?
+ var showAccessories = false { didSet { if showAccessories != oldValue { refreshAccessories(animated: true) } } }
+ private let label = NSTextField.sidebarLabel(size: 13)
+ private let statusIcon = NSImageView()
+ private let tip: ArcTooltipAnchorView
+ private var accessories: [NSView] = []
+ private var hovering = false { didSet { if hovering != oldValue { refreshFill() } } }
+ private var colors = SidebarColors()
+ private var hasTab = false
+ private var model: (pinned: [(String, String, NSImage?)], hasExtensions: Bool, active: Bool)?
+
+ override init(frame: NSRect) {
+ tip = ArcTooltipAnchorView(frame: .zero)
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerRadius = 10
+ layer?.cornerCurve = .continuous
+ label.lineBreakMode = .byTruncatingMiddle
+ statusIcon.imageScaling = .scaleNone
+ addSubview(statusIcon)
+ addSubview(label)
+ tip.followsCursor = true
+ tip.autoresizingMask = [.width, .height]
+ addSubview(tip)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ func show(text: String, url: String, hasTab: Bool, status: ToolbarStatus?, colors: SidebarColors, active: Bool,
+ pinned: [(String, String, NSImage?)], hasExtensions: Bool) {
+ self.colors = colors
+ self.hasTab = hasTab
+ tip.text = url
+ if let status {
+ statusIcon.isHidden = false
+ statusIcon.image = SidebarSymbols.image(status.symbol, size: 10, weight: .semibold)
+ statusIcon.contentTintColor = colors.textSecondary
+ label.stringValue = status.text
+ label.textColor = colors.textSecondary
+ } else {
+ statusIcon.isHidden = true
+ label.stringValue = text
+ label.textColor = hasTab ? colors.textPrimary : colors.textTertiary
+ }
+ model = (pinned, hasExtensions, active)
+ refreshAccessories(animated: false)
+ refreshFill()
+ needsLayout = true
+ }
+
+ private func refreshFill() {
+ layer?.backgroundColor = (hovering ? colors.selectedFill : colors.pillFill).cgColor
+ }
+
+ /// Arc's URL-bar accessories: pinned extensions, Copy Link, then the site controls.
+ private func refreshAccessories(animated: Bool) {
+ accessories.forEach { $0.removeFromSuperview() }
+ accessories = []
+ guard showAccessories, hasTab, let m = model, let actions else { needsLayout = true; return }
+ for (id, name, icon) in m.pinned {
+ let b = ToolbarGlyphButton()
+ b.configure(symbol: nil, image: icon, help: name, enabled: true, width: 28, iconSize: 16, tint: colors.textSecondary)
+ b.action = { actions.runExtension(id) }
+ accessories.append(b)
+ }
+ let copy = SidebarGlyphButton(symbol: "link", size: 28, height: 28, iconSize: 14, weight: .regular, help: "Copy URL (⇧⌘C)", colors: colors) { actions.performAction("copyURL") }
+ copy.active = m.active
+ accessories.append(copy)
+ if m.hasExtensions {
+ let e = SidebarGlyphButton(symbol: "slider.horizontal.2.square", size: 28, height: 28, iconSize: 15, weight: .regular, help: "Extensions", colors: colors) { actions.showExtensionsMenu() }
+ e.active = m.active
+ accessories.append(e)
+ }
+ for v in accessories {
+ addSubview(v)
+ if animated {
+ v.alphaValue = 0
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.15
+ v.animator().alphaValue = 1
+ }
+ }
+ }
+ needsLayout = true
+ }
+
+ /// The accessories' hover fill is the sidebar's, not the toolbar's.
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ var right = bounds.width - 5
+ for v in accessories.reversed() {
+ right -= 28
+ v.frame = NSRect(x: right, y: (h - 28) / 2, width: 28, height: 28)
+ right -= 1
+ }
+ var x: CGFloat = 12
+ if !statusIcon.isHidden {
+ statusIcon.frame = NSRect(x: x, y: 0, width: 12, height: h)
+ x += 12 + 6
+ }
+ let lh = label.intrinsicContentSize.height
+ label.frame = NSRect(x: x - SidebarText.inset, y: (h - lh) / 2, width: max(0, right - x) + 2 * SidebarText.inset, height: lh)
+ tip.frame = NSRect(x: 0, y: 0, width: right, height: h)
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
+ actions?.openCommandBar(hasTab ? .editURL : .newTab)
+ }
+}
+
+// MARK: - Dock
+
+/// Bottom row like Arc's: the Library at the left, tiny space icons in the middle (inactive ones
+/// dimmed), "+" at the right. Arc 1.170 (SidebarDock, an NSCollectionView): 34×32 pt cells side
+/// by side with no gap, so a press anywhere between two icons still lands on a space.
+final class SpaceDockView: NSView {
+ static let cell = CGSize(width: 34, height: 32)
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let actions: SidebarActions
+ private let library: LibraryButtonView
+ private let plus: SidebarGlyphButton
+ private var cells: [UUID: SpaceCellView] = [:]
+ private var order: [UUID] = []
+ private var focused: UUID?
+ private var incognito = false
+ private var colors = SidebarColors()
+ private var hovered: UUID? { didSet { if hovered != oldValue { refreshCells() } } }
+ private var reorder: (id: UUID, from: Int, to: Int, start: NSPoint, moved: Bool)?
+ private var syncQueued = false
+
+ init(store: SidebarStore, ui: SidebarUIState, actions: SidebarActions) {
+ self.store = store
+ self.ui = ui
+ self.actions = actions
+ library = LibraryButtonView(ui: ui, actions: actions)
+ plus = SidebarGlyphButton(symbol: "plus", size: 28, iconSize: 13, help: "New Space", colors: SidebarColors()) { actions.editSpace(nil) }
+ super.init(frame: .zero)
+ addSubview(library)
+ addSubview(plus)
+ sync()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private func sync() {
+ syncQueued = false
+ var spaces: [Space] = []
+ withObservationTracking {
+ colors = SidebarColors(store.focusedSpace(window: ui.windowID).theme.palette)
+ incognito = store.window(ui.windowID).isIncognito
+ spaces = incognito ? [] : store.orderedSpaces
+ focused = store.focusedSpaceID(window: ui.windowID)
+ } onChange: { [weak self] in
+ Task { @MainActor in
+ guard let self, !self.syncQueued else { return }
+ self.syncQueued = true
+ self.sync()
+ }
+ }
+ library.colors = colors
+ plus.colors = colors
+ plus.isHidden = incognito
+ let ids = spaces.map(\.id)
+ for (id, c) in cells where !ids.contains(id) {
+ c.removeFromSuperview()
+ cells[id] = nil
+ }
+ for s in spaces {
+ let c = cells[s.id] ?? {
+ let c = SpaceCellView(spaceID: s.id, store: store, ui: ui)
+ cells[s.id] = c
+ addSubview(c)
+ return c
+ }()
+ c.show(emoji: s.emoji, title: s.title)
+ }
+ order = ids
+ refreshCells()
+ needsLayout = true
+ }
+
+ private func refreshCells() {
+ for (id, c) in cells {
+ c.setState(selected: id == focused, hovered: hovered == id && reorder == nil, pressed: reorder?.id == id, colors: colors)
+ }
+ }
+
+ private var stripX: CGFloat { (bounds.width - CGFloat(order.count) * Self.cell.width) / 2 }
+
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ library.frame = NSRect(x: 0, y: (h - 28) / 2, width: 28, height: 28)
+ plus.frame = NSRect(x: bounds.width - 28, y: (h - 28) / 2, width: 28, height: 28)
+ placeCells(animated: false)
+ }
+
+ /// The dragged space follows the pointer; the ones it passes slide a cell the other way, like
+ /// the gap Arc's collection view opens at the proposed drop index.
+ private func placeCells(animated: Bool, dragX: CGFloat = 0) {
+ let w = Self.cell.width
+ let y = (bounds.height - Self.cell.height) / 2
+ for (i, id) in order.enumerated() {
+ guard let c = cells[id] else { continue }
+ var x = stripX + CGFloat(i) * w
+ if let r = reorder {
+ if r.id == id { x += dragX } else if r.from < i && i <= r.to { x -= w } else if r.to <= i && i < r.from { x += w }
+ }
+ let f = NSRect(x: x, y: y, width: w, height: Self.cell.height)
+ if animated && reorder?.id != id { c.animator().frame = f } else { c.frame = f }
+ }
+ if let r = reorder, let c = cells[r.id] { c.removeFromSuperview(); addSubview(c) }
+ }
+
+ private func index(at p: NSPoint) -> Int? {
+ let i = Int(floor((p.x - stripX) / Self.cell.width))
+ guard p.y >= 0, p.y <= bounds.height, i >= 0, i < order.count, p.x >= stripX else { return nil }
+ return i
+ }
+
+ // Arc's dock items take the mouse themselves (SidebarDockItemView overrides mouseDown:/mouseUp:):
+ // a press never moves the window, and every click counts.
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ let p = convert(point, from: superview)
+ if index(at: p) != nil { return self }
+ return super.hitTest(point)
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ private func point(_ e: NSEvent) -> NSPoint { convert(e.locationInWindow, from: nil) }
+
+ override func mouseMoved(with event: NSEvent) {
+ guard reorder == nil else { return }
+ let i = index(at: point(event))
+ hovered = i.map { order[$0] }
+ for (j, id) in order.enumerated() { if let c = cells[id] { j == i ? ArcTooltipController.shared.mouseMoved(in: c) : ArcTooltipController.shared.mouseExited(c) } }
+ }
+ override func mouseEntered(with event: NSEvent) { mouseMoved(with: event) }
+ override func mouseExited(with event: NSEvent) {
+ if reorder == nil { hovered = nil }
+ for c in cells.values { ArcTooltipController.shared.mouseExited(c) }
+ }
+
+ override func mouseDown(with event: NSEvent) {
+ let p = point(event)
+ guard let i = index(at: p) else { return }
+ reorder = (order[i], i, i, p, false)
+ refreshCells()
+ }
+
+ override func mouseDragged(with event: NSEvent) {
+ guard var r = reorder else { return }
+ let p = point(event)
+ let dx = p.x - r.start.x
+ if !r.moved && abs(dx) < 3 && abs(p.y - r.start.y) < 3 { return }
+ r.moved = true
+ let w = Self.cell.width
+ let clamped = min(max(dx, -CGFloat(r.from) * w), CGFloat(order.count - 1 - r.from) * w)
+ let to = min(max(r.from + Int((clamped / w).rounded()), 0), order.count - 1)
+ let changed = to != r.to
+ r.to = to
+ reorder = r
+ if changed {
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.2
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ placeCells(animated: true, dragX: clamped)
+ }
+ } else {
+ placeCells(animated: false, dragX: clamped)
+ }
+ }
+
+ /// A release inside the pressed cell that didn't move the space switches to it, so a shaky
+ /// click still counts; a moved space slides into its cell and the order is saved.
+ override func mouseUp(with event: NSEvent) {
+ guard let r = reorder else { return }
+ let p = point(event)
+ guard r.to != r.from else {
+ reorder = nil
+ if index(at: p) == r.from { store.focusSpace(r.id, window: ui.windowID) }
+ hovered = index(at: p).map { order[$0] }
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.15
+ placeCells(animated: true)
+ }
+ refreshCells()
+ return
+ }
+ // `moveSpace` indexes the full space order; land next to the space now in that cell.
+ let target = store.spaceOrder.firstIndex(of: order[r.to]) ?? r.to
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.15
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ placeCells(animated: true, dragX: CGFloat(r.to - r.from) * Self.cell.width)
+ cells[r.id]?.animator().frame.origin.x = stripX + CGFloat(r.to) * Self.cell.width
+ } completionHandler: { [weak self] in
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ self.reorder = nil
+ self.store.moveSpace(r.id, to: target)
+ self.refreshCells()
+ }
+ }
+ }
+
+ override func menu(for event: NSEvent) -> NSMenu? {
+ guard let i = index(at: point(event)), let space = store.space(order[i]) else { return nil }
+ let store = self.store, ui = self.ui, actions = self.actions
+ let m = NSMenu()
+ m.autoenablesItems = false
+ MenuItems.add(m, "Edit Space…") { actions.editSpace(space) }
+ m.addItem(.separator())
+ MenuItems.add(m, "Move Left") { if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: max(0, i - 1)) } }
+ MenuItems.add(m, "Move Right") { if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: i + 1) } }
+ m.addItem(.separator())
+ MenuItems.add(m, "Delete Space…") {
+ store.focusSpace(space.id, window: ui.windowID)
+ actions.performAction("deleteSpace")
+ }
+ return m
+ }
+}
+
+/// One space in the dock: its emoji, dimmed and desaturated unless selected, hovered or pressed.
+/// A tab dragged onto it moves there; held over it, Arc switches to that space so the tab can be
+/// carried into its list.
+final class SpaceCellView: NSView, ArcTooltipTarget {
+ private let spaceID: UUID
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let emoji = NSTextField.sidebarLabel(size: 13)
+ private let emojiHolder = NSView()
+ private var title = ""
+ private var selected = false
+ private var colors = SidebarColors()
+ private var state: (Bool, Bool, Bool)?
+ private var targeted = false { didSet { if targeted != oldValue { refreshFill() } } }
+ private var lit = false
+
+ init(spaceID: UUID, store: SidebarStore, ui: SidebarUIState) {
+ self.spaceID = spaceID
+ self.store = store
+ self.ui = ui
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = 6
+ emojiHolder.wantsLayer = true
+ emojiHolder.layerUsesCoreImageFilters = true
+ emoji.alignment = .center
+ emojiHolder.addSubview(emoji)
+ addSubview(emojiHolder)
+ registerForDraggedTypes([.craSidebarItem])
+ setAccessibilityElement(true)
+ setAccessibilityRole(.button)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ func show(emoji text: String, title: String) {
+ emoji.stringValue = text
+ self.title = title
+ setAccessibilityLabel(title)
+ needsLayout = true
+ }
+
+ func setState(selected: Bool, hovered: Bool, pressed: Bool, colors: SidebarColors) {
+ self.selected = selected
+ self.colors = colors
+ lit = selected || hovered || pressed
+ emojiHolder.alphaValue = lit ? 1 : 0.45
+ emojiHolder.layer?.filters = lit ? nil : [CIFilter(name: "CIColorControls", parameters: ["inputSaturation": 0.2])!]
+ refreshFill(hovered || pressed)
+ }
+
+ /// Arc's hovered/pressed cell on a dark space: white at ~7.8%, 6 pt corners.
+ private func refreshFill(_ on: Bool? = nil) {
+ let fill = colors.isDark ? NSColor.white.withAlphaComponent(0.078) : NSColor.black.withAlphaComponent(0.05)
+ let show = targeted || (on ?? (lit && !selected))
+ layer?.backgroundColor = (show ? fill : .clear).cgColor
+ }
+
+ override func layout() {
+ super.layout()
+ emojiHolder.frame = bounds
+ let h = emoji.intrinsicContentSize.height
+ emoji.frame = NSRect(x: 0, y: (bounds.height - h) / 2, width: bounds.width, height: h)
+ }
+
+ override func accessibilityPerformPress() -> Bool {
+ store.focusSpace(spaceID, window: ui.windowID)
+ return true
+ }
+
+ private func draggedID(_ info: NSDraggingInfo) -> UUID? {
+ guard let data = info.draggingPasteboard.data(forType: .craSidebarItem),
+ let d = try? JSONDecoder().decode(SidebarDragItem.self, from: data) else { return nil }
+ return d.id
+ }
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
+ guard draggedID(sender) != nil else { return [] }
+ targeted = true
+ if !selected {
+ let id = spaceID
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
+ guard let self, self.targeted else { return }
+ self.store.focusSpace(id, window: self.ui.windowID)
+ }
+ }
+ return sender.draggingSourceOperationMask.contains(.move) ? .move : .copy
+ }
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
+ draggedID(sender) == nil ? [] : (sender.draggingSourceOperationMask.contains(.move) ? .move : .copy)
+ }
+ override func draggingExited(_ sender: NSDraggingInfo?) { targeted = false }
+ override func draggingEnded(_ sender: NSDraggingInfo) { targeted = false }
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ targeted = false
+ guard let id = draggedID(sender) else { return false }
+ store.moveTab(id, toSpace: spaceID)
+ return true
+ }
+
+ var text: String { title }
+ var keys: [String] { [] }
+ var followsCursor: Bool { false }
+ var subtitle: String? { nil }
+ var optionText: String? { nil }
+ var onShow: (() -> Void)? { nil }
+ var screenFrame: NSRect { window?.convertToScreen(convert(bounds, to: nil)) ?? .zero }
+ var hostWindow: NSWindow? { window }
+}
+
+/// Arc's Library button (a box with a confetti puff, drawn by LibraryGlyph) and, over it, the
+/// latest download's "bin" (DownloadsUI.DownloadToLibrary): the file's thumbnail, 32 pt with
+/// 8 pt corners, up and to the right of the glyph. It drops in from 6 pt above, overshoots 12 pt
+/// below and settles (Arc 1.170 at 60 fps), and is faint while the window is in the background.
+final class LibraryButtonView: NSView {
+ private let ui: SidebarUIState
+ private let actions: SidebarActions
+ private let glyph = NSImageView()
+ private let tip: ArcTooltipAnchorView
+ private let bin = NSView()
+ private let binImage = CALayer()
+ private let binTip: ArcTooltipAnchorView
+ private var shownDownload: UInt32?
+ private var hovering = false { didSet { if hovering != oldValue { refresh() } } }
+ var colors = SidebarColors() { didSet { if colors != oldValue { glyph.image = LibraryGlyph.image(dark: colors.isDark); refresh() } } }
+ static let binOffset = CGSize(width: 9, height: -12)
+
+ init(ui: SidebarUIState, actions: SidebarActions) {
+ self.ui = ui
+ self.actions = actions
+ tip = ArcTooltipAnchorView(frame: .zero)
+ binTip = ArcTooltipAnchorView(frame: .zero)
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = 7
+ layer?.cornerCurve = .continuous
+ glyph.imageScaling = .scaleNone
+ glyph.image = LibraryGlyph.image(dark: false)
+ addSubview(glyph)
+ (tip.text, tip.keys) = ArcTooltipLabel.split("Library (⇧⌘L)")
+ addSubview(tip)
+ bin.wantsLayer = true
+ binImage.cornerRadius = 8
+ binImage.cornerCurve = .continuous
+ binImage.masksToBounds = true
+ binImage.contentsGravity = .resizeAspectFill
+ bin.layer?.addSublayer(binImage)
+ bin.addSubview(binTip)
+ bin.isHidden = true
+ addSubview(bin)
+ ui.libraryAnchor = self
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ private func observe() {
+ let (download, active) = withObservationTracking { (ui.recentDownload, ui.appActive) } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ guard let download else { bin.isHidden = true; shownDownload = nil; return }
+ bin.isHidden = false
+ binImage.contents = download.image
+ bin.alphaValue = active ? 1 : 0.4
+ binTip.text = (download.path as NSString).lastPathComponent
+ if shownDownload != download.id {
+ shownDownload = download.id
+ drop()
+ }
+ }
+
+ private func drop() {
+ let y = CAKeyframeAnimation(keyPath: "transform.translation.y")
+ // Flipped view: positive y is down on screen.
+ y.values = [-6, 12, 12, -2, 0].map { NSNumber(value: Double($0) * (bin.layer?.isGeometryFlipped == true ? 1 : -1)) }
+ y.keyTimes = [0, 0.15, 0.2, 0.33, 0.4].map { NSNumber(value: $0 / 0.4) }
+ y.timingFunctions = [CAMediaTimingFunction(name: .easeInEaseOut), CAMediaTimingFunction(name: .linear),
+ CAMediaTimingFunction(name: .easeInEaseOut), CAMediaTimingFunction(name: .easeInEaseOut)]
+ y.duration = 0.4
+ let fade = CABasicAnimation(keyPath: "opacity")
+ fade.fromValue = 0
+ fade.toValue = 1
+ fade.duration = 0.05
+ bin.layer?.add(y, forKey: "drop")
+ bin.layer?.add(fade, forKey: "fade")
+ }
+
+ private func refresh() {
+ layer?.backgroundColor = (hovering ? colors.hoverFill : .clear).cgColor
+ }
+
+ override func layout() {
+ super.layout()
+ glyph.frame = bounds
+ tip.frame = bounds
+ let c = NSPoint(x: bounds.midX + Self.binOffset.width, y: bounds.midY + Self.binOffset.height)
+ bin.frame = NSRect(x: c.x - 16, y: c.y - 16, width: 32, height: 32)
+ binImage.frame = bin.bounds
+ binTip.frame = bin.bounds
+ }
+
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ let p = convert(point, from: superview)
+ if !bin.isHidden, bin.frame.contains(p) { return self }
+ return bounds.contains(p) ? self : nil
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+ override func mouseEntered(with event: NSEvent) { hovering = true; ui.libraryHovered = true; ui.downloadsHoverChanged() }
+ override func mouseExited(with event: NSEvent) { hovering = false; ui.libraryHovered = false; ui.downloadsHoverChanged() }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ if !bin.isHidden, bin.frame.contains(p), let path = ui.recentDownload?.path {
+ NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
+ } else if bounds.contains(p) {
+ actions.toggleLibrary()
+ }
+ }
+}
diff --git a/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift b/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift
new file mode 100644
index 0000000..5912214
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift
@@ -0,0 +1,651 @@
+import AppKit
+import SwiftUI
+
+/// One space's page in the pager: Arc's favorites grid and space header, fixed, over the
+/// space's tab list, which scrolls (Arc 1.170). All AppKit: a space switch or swipe moves this
+/// view's layer and nothing in it lays out or re-renders.
+@MainActor
+final class SpaceColumnView: NSView {
+ let spaceID: UUID
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let actions: SidebarActions
+ private let favicons: FaviconCache
+ private let favorites: FavoritesGridView
+ private let header: SpaceHeaderView
+ private let list: SpaceListView
+
+ init(spaceID: UUID, store: SidebarStore, ui: SidebarUIState, actions: SidebarActions, favicons: FaviconCache) {
+ self.spaceID = spaceID
+ self.store = store
+ self.ui = ui
+ self.actions = actions
+ self.favicons = favicons
+ favorites = FavoritesGridView(spaceID: spaceID, store: store, ui: ui, actions: actions, favicons: favicons)
+ header = SpaceHeaderView(spaceID: spaceID, store: store, actions: actions)
+ list = SpaceListView(spaceID: spaceID, store: store, ui: ui, actions: actions, favicons: favicons)
+ super.init(frame: .zero)
+ favorites.onHeightChange = { [weak self] animated in self?.relayout(animated: animated) }
+ addSubview(list)
+ addSubview(favorites)
+ addSubview(header)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private func relayout(animated: Bool) {
+ guard animated, window != nil else { needsLayout = true; return }
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.15
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ ctx.allowsImplicitAnimation = true
+ place(animated: true)
+ }
+ }
+
+ override func layout() {
+ super.layout()
+ place(animated: false)
+ }
+
+ private func place(animated: Bool) {
+ let w = bounds.width
+ let fh = favorites.height(forWidth: w - 16)
+ let set = { (v: NSView, f: NSRect) in if v.frame != f { animated ? (v.animator().frame = f) : (v.frame = f) } }
+ set(favorites, NSRect(x: 8, y: 0, width: w - 16, height: fh))
+ set(header, NSRect(x: 10, y: fh, width: w - 20, height: 31))
+ let top = fh + 31 + 3
+ set(list, NSRect(x: 0, y: top, width: w, height: max(0, bounds.height - top)))
+ }
+}
+
+// MARK: - Space header
+
+/// The space's emoji and name. Arc: a click collapses or expands the pinned tabs; the menu is
+/// on right-click; the chevron shows on hover.
+final class SpaceHeaderView: NSView {
+ private let spaceID: UUID
+ private let store: SidebarStore
+ private let actions: SidebarActions
+ private let emoji = NSTextField.sidebarLabel(size: 12)
+ private let title = NSTextField.sidebarLabel(size: 14, weight: .medium)
+ private let chevron = NSImageView()
+ private var hovering = false { didSet { if hovering != oldValue { refresh() } } }
+ private var collapsed = false
+ private var colors = SidebarColors()
+ private var syncQueued = false
+
+ init(spaceID: UUID, store: SidebarStore, actions: SidebarActions) {
+ self.spaceID = spaceID
+ self.store = store
+ self.actions = actions
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = 8
+ chevron.image = SidebarSymbols.image("chevron.down", size: 8, weight: .bold)
+ chevron.imageScaling = .scaleNone
+ chevron.wantsLayer = true
+ for v in [emoji, title, chevron] { addSubview(v) }
+ sync()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ private func sync() {
+ syncQueued = false
+ withObservationTracking {
+ guard let space = store.space(spaceID) else { return }
+ emoji.stringValue = space.emoji
+ title.stringValue = space.title
+ colors = SidebarColors(space.theme.palette)
+ collapsed = store.isPinnedCollapsed(spaceID)
+ } onChange: { [weak self] in
+ Task { @MainActor in
+ guard let self, !self.syncQueued else { return }
+ self.syncQueued = true
+ self.sync()
+ }
+ }
+ refresh()
+ }
+
+ private func refresh() {
+ title.textColor = colors.textSecondary
+ chevron.contentTintColor = colors.textTertiary
+ chevron.alphaValue = hovering ? 1 : 0
+ layer?.backgroundColor = (hovering ? colors.hoverFill : .clear).cgColor
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ // HStack(spacing: 8), 7 pt in.
+ let es = emoji.intrinsicContentSize
+ let ew = ceil(emoji.attributedStringValue.size().width)
+ emoji.frame = NSRect(x: 7 - SidebarText.inset, y: (h - es.height) / 2, width: ew + 2 * SidebarText.inset, height: es.height)
+ var x = 7 + ew + 8
+ let tw = min(ceil(title.attributedStringValue.size().width), max(0, bounds.width - x - 30))
+ let th = title.intrinsicContentSize.height
+ title.frame = NSRect(x: x - SidebarText.inset, y: (h - th) / 2, width: tw + 2 * SidebarText.inset, height: th)
+ x += tw + 8
+ chevron.frame = NSRect(x: x, y: (h - 10) / 2, width: 10, height: 10)
+ chevron.layer?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
+ chevron.layer?.position = CGPoint(x: chevron.frame.midX, y: chevron.frame.midY)
+ chevron.layer?.setAffineTransform(CGAffineTransform(rotationAngle: collapsed ? .pi / 2 : 0))
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { store.togglePinnedCollapsed(spaceID) }
+ }
+
+ override func menu(for event: NSEvent) -> NSMenu? {
+ guard let space = store.space(spaceID) else { return nil }
+ let store = self.store, actions = self.actions, id = spaceID
+ let m = NSMenu()
+ m.autoenablesItems = false
+ MenuItems.add(m, collapsed ? "Expand Pinned Tabs" : "Collapse Pinned Tabs") { store.togglePinnedCollapsed(id) }
+ m.addItem(.separator())
+ MenuItems.add(m, "Edit Space…") { actions.editSpace(space) }
+ MenuItems.add(m, "New Folder") { actions.performAction("newFolder") }
+ MenuItems.add(m, "New GitHub Live Folder", enabled: store.liveFolder(.github, inSpace: id) == nil) { actions.performAction("newGitHubLiveFolder") }
+ m.addItem(.separator())
+ MenuItems.add(m, "Clear Today") { store.clearToday(id) }
+ m.addItem(.separator())
+ MenuItems.add(m, "New Space…") { actions.editSpace(nil) }
+ MenuItems.add(m, "Delete Space…") { actions.performAction("deleteSpace") }
+ return m
+ }
+}
+
+/// Closure-backed menu items for AppKit menus.
+@MainActor
+enum MenuItems {
+ private final class Action: NSObject {
+ let run: () -> Void
+ init(_ run: @escaping () -> Void) { self.run = run }
+ @objc func fire() { run() }
+ }
+
+ @discardableResult
+ static func add(_ menu: NSMenu, _ title: String, enabled: Bool = true, on: Bool? = nil, image: NSImage? = nil, _ run: @escaping () -> Void) -> NSMenuItem {
+ let a = Action(run)
+ let item = NSMenuItem(title: title, action: #selector(Action.fire), keyEquivalent: "")
+ item.target = a
+ item.representedObject = a
+ item.isEnabled = enabled
+ item.image = image
+ if let on { item.state = on ? .on : .off }
+ menu.addItem(item)
+ return item
+ }
+
+ static func submenu(_ menu: NSMenu, _ title: String) -> NSMenu {
+ let sub = NSMenu()
+ sub.autoenablesItems = false
+ let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")
+ item.submenu = sub
+ menu.addItem(item)
+ return sub
+ }
+}
+
+// MARK: - Favorites
+
+/// Arc's "top apps": a 4-wide grid of favorite tiles, 8 pt apart, and under it a strip that
+/// opens into "Add to Favorites" while a tab is dragged over it. Arc shares them between
+/// spaces; in Cra every space has its own.
+final class FavoritesGridView: NSView {
+ private let spaceID: UUID
+ let store: SidebarStore
+ let ui: SidebarUIState
+ let actions: SidebarActions
+ let favicons: FaviconCache
+ var onHeightChange: (Bool) -> Void = { _ in }
+ private var tiles: [UUID: FavoriteTileView] = [:]
+ private var order: [UUID] = []
+ private let strip = FavoritesDropStrip()
+ private(set) var palette: SpacePalette?
+ private var syncQueued = false
+
+ init(spaceID: UUID, store: SidebarStore, ui: SidebarUIState, actions: SidebarActions, favicons: FaviconCache) {
+ self.spaceID = spaceID
+ self.store = store
+ self.ui = ui
+ self.actions = actions
+ self.favicons = favicons
+ super.init(frame: .zero)
+ strip.onDrop = { [weak self] id in
+ guard let self else { return false }
+ self.store.addToFavorites(id, in: self.spaceID)
+ return true
+ }
+ strip.onTargetChange = { [weak self] _ in self?.onHeightChange(true) }
+ addSubview(strip)
+ sync()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private struct TileModel: Equatable {
+ var title: String
+ var icon: NSImage?
+ var glyphDark: Bool?
+ var tileColor: String?
+ var selected: Bool
+ var unread: Bool
+ var focus: Bool
+ }
+
+ private func sync() {
+ syncQueued = false
+ var models: [(UUID, TileModel)] = []
+ var palette: SpacePalette?
+ withObservationTracking {
+ guard let space = store.space(spaceID) else { return }
+ palette = space.theme.palette
+ for item in store.tabs(under: space.favoritesContainerID) {
+ let key = item.tab?.iconKey
+ let icon = favicons.image(forKey: key)
+ models.append((item.id, TileModel(title: item.displayTitle, icon: icon, glyphDark: icon == nil ? nil : favicons.glyphIsDark(forKey: key),
+ tileColor: item.tab?.tileColor,
+ selected: store.isSelected(item.id, inSpace: spaceID, window: ui.windowID),
+ unread: item.isUnread, focus: ui.keyboardFocusID == item.id)))
+ }
+ } onChange: { [weak self] in
+ Task { @MainActor in
+ guard let self, !self.syncQueued else { return }
+ self.syncQueued = true
+ self.sync()
+ }
+ }
+ self.palette = palette
+ let ids = models.map(\.0)
+ let countChanged = ids.count != order.count
+ for (id, t) in tiles where !ids.contains(id) {
+ t.removeFromSuperview()
+ tiles[id] = nil
+ }
+ for (id, m) in models {
+ let t = tiles[id] ?? {
+ let t = FavoriteTileView(itemID: id, spaceID: spaceID, grid: self)
+ tiles[id] = t
+ addSubview(t)
+ return t
+ }()
+ if let palette {
+ t.show(title: m.title, icon: m.icon, glyphDark: m.glyphDark, tileColor: m.tileColor, selected: m.selected,
+ unread: m.unread, focus: m.focus, palette: palette)
+ }
+ }
+ order = ids
+ if let palette { strip.palette = palette }
+ strip.hasFavorites = !ids.isEmpty
+ needsLayout = true
+ if countChanged { onHeightChange(false) }
+ }
+
+ private var rows: Int { (order.count + 3) / 4 }
+
+ func height(forWidth w: CGFloat) -> CGFloat {
+ let grid = rows == 0 ? 0 : CGFloat(rows) * 47 + CGFloat(rows - 1) * 8
+ return grid + (order.isEmpty ? 0 : 4) + strip.height
+ }
+
+ override func layout() {
+ super.layout()
+ let w = bounds.width
+ let cw = (w - 3 * 8) / 4
+ for (i, id) in order.enumerated() {
+ let r = i / 4, c = i % 4
+ tiles[id]?.frame = NSRect(x: CGFloat(c) * (cw + 8), y: CGFloat(r) * (47 + 8), width: cw, height: 47)
+ }
+ let grid = rows == 0 ? 0 : CGFloat(rows) * 47 + CGFloat(rows - 1) * 8
+ strip.frame = NSRect(x: 0, y: grid + (order.isEmpty ? 0 : 4), width: w, height: strip.height)
+ }
+
+ func moveFavorite(_ dragged: UUID, before target: UUID, after: Bool) {
+ guard dragged != target, let space = store.space(spaceID),
+ let idx = store.item(space.favoritesContainerID)?.children.firstIndex(of: target) else { return }
+ store.moveItem(dragged, to: space.favoritesContainerID, index: idx + (after ? 1 : 0))
+ }
+
+ func spaceFavoriteIDs() -> [UUID] {
+ guard let space = store.space(spaceID) else { return [] }
+ return store.tabs(under: space.favoritesContainerID).map(\.id)
+ }
+}
+
+/// The drop strip under the grid: 6–8 pt of nothing, 36 pt "Add to Favorites" while targeted.
+final class FavoritesDropStrip: NSView {
+ var onDrop: (UUID) -> Bool = { _ in false }
+ var onTargetChange: (Bool) -> Void = { _ in }
+ var palette: SpacePalette? { didSet { refresh() } }
+ var hasFavorites = true
+ private(set) var targeted = false { didSet { if targeted != oldValue { refresh(); onTargetChange(targeted) } } }
+ private let border = CAShapeLayer()
+ private let label = NSTextField.sidebarLabel(size: 11, weight: .medium)
+
+ var height: CGFloat { targeted ? 36 : (hasFavorites ? 6 : 8) }
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerRadius = 10
+ border.fillColor = nil
+ border.lineWidth = 1
+ border.lineDashPattern = [4, 3]
+ layer?.addSublayer(border)
+ label.stringValue = "Add to Favorites"
+ label.alignment = .center
+ addSubview(label)
+ registerForDraggedTypes([.craSidebarItem])
+ refresh()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ private func refresh() {
+ guard let p = palette else { return }
+ let colors = SidebarColors(p)
+ border.strokeColor = colors.textTertiary.withAlphaComponent(targeted ? 0.6 : 0).cgColor
+ layer?.backgroundColor = (targeted ? colors.hoverFill : .clear).cgColor
+ label.textColor = colors.textSecondary
+ label.isHidden = !targeted
+ }
+
+ override func layout() {
+ super.layout()
+ border.frame = bounds
+ border.path = CGPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), cornerWidth: 10, cornerHeight: 10, transform: nil)
+ let lh = label.intrinsicContentSize.height
+ label.frame = NSRect(x: 0, y: (bounds.height - lh) / 2, width: bounds.width, height: lh)
+ }
+
+ private func draggedID(_ info: NSDraggingInfo) -> UUID? {
+ guard let data = info.draggingPasteboard.data(forType: .craSidebarItem),
+ let d = try? JSONDecoder().decode(SidebarDragItem.self, from: data) else { return nil }
+ return d.id
+ }
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
+ guard draggedID(sender) != nil else { return [] }
+ targeted = true
+ return sender.draggingSourceOperationMask.contains(.move) ? .move : .copy
+ }
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
+ draggedID(sender) == nil ? [] : (sender.draggingSourceOperationMask.contains(.move) ? .move : .copy)
+ }
+ override func draggingExited(_ sender: NSDraggingInfo?) { targeted = false }
+ override func draggingEnded(_ sender: NSDraggingInfo) { targeted = false }
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ targeted = false
+ guard let id = draggedID(sender) else { return false }
+ return onDrop(id)
+ }
+}
+
+/// A favorite tile. Arc 1.170: 13 pt circular corners; the active tile is the hover fill with a
+/// 2 pt darker rim; inactive tiles sit ~4.5% darker than the sidebar. A picked tile colour keeps
+/// its hue in every state; hover and selection shade it.
+final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {
+ let itemID: UUID
+ private let spaceID: UUID
+ private weak var grid: FavoritesGridView?
+ private let shade = CALayer()
+ /// The selected tile's 2 pt rim, under the focus ring (a layer border would draw over it).
+ private let rim = CALayer()
+ private let favicon = SidebarFaviconView(size: 20)
+ private let unreadDot = CALayer()
+ private var focusRing: FocusRingLayer?
+ private var model: (title: String, icon: NSImage?, glyphDark: Bool?, tileColor: String?, selected: Bool, unread: Bool, focus: Bool, palette: SpacePalette)?
+ private var hovering = false { didSet { if hovering != oldValue { refresh() } } }
+ private var targeted = false { didSet { if targeted != oldValue { refresh() } } }
+ private var press: NSEvent?
+
+ init(itemID: UUID, spaceID: UUID, grid: FavoritesGridView) {
+ self.itemID = itemID
+ self.spaceID = spaceID
+ self.grid = grid
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = 13
+ shade.cornerRadius = 13
+ layer?.addSublayer(shade)
+ rim.cornerRadius = 13
+ rim.zPosition = 5
+ layer?.addSublayer(rim)
+ addSubview(favicon)
+ unreadDot.cornerRadius = 3
+ layer?.addSublayer(unreadDot)
+ registerForDraggedTypes([.craSidebarItem])
+ setAccessibilityElement(true)
+ setAccessibilityRole(.button)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ func show(title: String, icon: NSImage?, glyphDark: Bool?, tileColor: String?, selected: Bool, unread: Bool, focus: Bool, palette: SpacePalette) {
+ model = (title, icon, glyphDark, tileColor, selected, unread, focus, palette)
+ setAccessibilityLabel(title)
+ refresh()
+ }
+
+ private var tileIsDark: Bool {
+ guard let m = model else { return false }
+ return m.tileColor.flatMap(HexColor.luminance).map { $0 < 0.5 } ?? m.palette.isDark
+ }
+
+ private func refresh() {
+ guard let m = model else { return }
+ let dark = tileIsDark
+ let colors = SidebarColors(m.palette)
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ if let hex = m.tileColor {
+ layer?.backgroundColor = NSColor(hex: hex).cgColor
+ shade.backgroundColor = (m.selected || hovering || targeted ? (dark ? NSColor.white.withAlphaComponent(0.12) : NSColor.black.withAlphaComponent(0.07)) : .clear).cgColor
+ } else {
+ let fill: NSColor = m.selected ? (m.palette.isDark ? NSColor.white.withAlphaComponent(0.13) : NSColor.white.withAlphaComponent(0.38))
+ : (hovering || targeted ? (m.palette.isDark ? NSColor.white.withAlphaComponent(0.15) : NSColor.black.withAlphaComponent(0.09)) : NSColor(m.palette.pillFill))
+ layer?.backgroundColor = fill.cgColor
+ shade.backgroundColor = NSColor.clear.cgColor
+ }
+ rim.borderWidth = m.selected ? 2 : 0
+ rim.borderColor = (dark ? NSColor.white.withAlphaComponent(0.14) : NSColor.black.withAlphaComponent(0.17)).cgColor
+ var faviconColors = colors
+ faviconColors.isDark = dark
+ favicon.show(m.icon, flip: m.icon != nil && m.glyphDark == dark, colors: faviconColors)
+ unreadDot.isHidden = !(m.unread && !m.selected)
+ unreadDot.backgroundColor = (m.tileColor == nil ? colors.textPrimary : (dark ? NSColor.white : NSColor.black)).withAlphaComponent(0.6).cgColor
+ if m.focus != (focusRing != nil) {
+ if m.focus {
+ let r = FocusRingLayer(radius: 13)
+ r.zPosition = 10
+ layer?.addSublayer(r)
+ focusRing = r
+ } else {
+ focusRing?.removeFromSuperlayer()
+ focusRing = nil
+ }
+ }
+ CATransaction.commit()
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ shade.frame = bounds
+ rim.frame = bounds
+ favicon.frame = NSRect(x: (bounds.width - 20) / 2, y: (bounds.height - 20) / 2, width: 20, height: 20)
+ unreadDot.frame = CGRect(x: bounds.width - 5 - 6, y: 5, width: 6, height: 6)
+ focusRing?.frame = bounds
+ CATransaction.commit()
+ }
+
+ // MARK: Pointer
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true; ArcTooltipController.shared.mouseMoved(in: self) }
+ override func mouseMoved(with event: NSEvent) { ArcTooltipController.shared.mouseMoved(in: self) }
+ override func mouseExited(with event: NSEvent) { hovering = false; ArcTooltipController.shared.mouseExited(self) }
+
+ override func mouseDown(with event: NSEvent) { press = event }
+ override func mouseDragged(with event: NSEvent) {
+ guard let p = press, let grid else { return }
+ guard hypot(event.locationInWindow.x - p.locationInWindow.x, event.locationInWindow.y - p.locationInWindow.y) > 3 else { return }
+ press = nil
+ grid.ui.draggingID = itemID
+ let pb = NSPasteboardItem()
+ if let data = try? JSONEncoder().encode(SidebarDragItem(id: itemID)) { pb.setData(data, forType: .craSidebarItem) }
+ let item = NSDraggingItem(pasteboardWriter: pb)
+ let rep = bitmapImageRepForCachingDisplay(in: bounds)
+ if let rep { cacheDisplay(in: bounds, to: rep) }
+ let fill = layer?.backgroundColor.flatMap { NSColor(cgColor: $0) } ?? .clear
+ let image = NSImage(size: bounds.size, flipped: false) { r in
+ fill.setFill()
+ NSBezierPath(roundedRect: r, xRadius: 13, yRadius: 13).fill()
+ rep?.draw(in: r)
+ return true
+ }
+ item.setDraggingFrame(bounds, contents: image)
+ beginDraggingSession(with: [item], event: p, source: self)
+ }
+ override func mouseUp(with event: NSEvent) {
+ guard press != nil, let grid else { return }
+ press = nil
+ grid.ui.keyboardFocusID = nil
+ grid.store.selectTab(itemID, window: grid.ui.windowID)
+ }
+
+ func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
+ context == .withinApplication ? [.move, .copy, .generic, .private] : []
+ }
+
+ func draggingSession(_ session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
+ grid?.ui.draggingID = nil
+ if grid?.ui.listDrop != nil { grid?.ui.listDrop = nil }
+ }
+
+ // MARK: Drops (reorder)
+
+ private func draggedID(_ info: NSDraggingInfo) -> UUID? {
+ guard let data = info.draggingPasteboard.data(forType: .craSidebarItem),
+ let d = try? JSONDecoder().decode(SidebarDragItem.self, from: data), d.id != itemID else { return nil }
+ return d.id
+ }
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
+ guard draggedID(sender) != nil else { return [] }
+ targeted = true
+ return sender.draggingSourceOperationMask.contains(.move) ? .move : .copy
+ }
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
+ draggedID(sender) == nil ? [] : (sender.draggingSourceOperationMask.contains(.move) ? .move : .copy)
+ }
+ override func draggingExited(_ sender: NSDraggingInfo?) { targeted = false }
+ override func draggingEnded(_ sender: NSDraggingInfo) { targeted = false }
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ targeted = false
+ guard let id = draggedID(sender) else { return false }
+ grid?.moveFavorite(id, before: itemID, after: convert(sender.draggingLocation, from: nil).x > 30)
+ return true
+ }
+
+ // MARK: Menu
+
+ override func menu(for event: NSEvent) -> NSMenu? {
+ guard let grid, let item = grid.store.item(itemID) else { return nil }
+ let store = grid.store, ui = grid.ui, actions = grid.actions, favicons = grid.favicons
+ let id = itemID
+ let tileColor = item.tab?.tileColor
+ let m = NSMenu()
+ m.autoenablesItems = false
+ MenuItems.add(m, "Remove from Favorites") { store.removeFromFavorites(id) }
+ MenuItems.add(m, "Rename…") { ui.renamingID = id }
+ MenuItems.add(m, "Copy Link") {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(item.tab?.url ?? "", forType: .string)
+ }
+ if let t = item.tab, t.url != t.savedURL { MenuItems.add(m, "Back to Pinned Page") { actions.resetPinnedTab(id) } }
+ MenuItems.add(m, "Make This the Pinned Page") { store.setPinnedHomeToCurrent(id) }
+ m.addItem(.separator())
+ MenuItems.add(m, "Change Icon…") { [weak self] in self?.pickIcon() }
+ if let key = item.tab?.customIconKey {
+ MenuItems.add(m, "Use Site Icon") {
+ store.setCustomIcon(nil, for: id)
+ favicons.removeCustomIcon(key)
+ }
+ }
+ let colors = MenuItems.submenu(m, "Tile Color")
+ MenuItems.add(colors, "Default", on: tileColor == nil, image: TileColor.swatch(nil)) { store.setTileColor(nil, for: [id]) }
+ for p in TileColor.presets {
+ MenuItems.add(colors, p.name, on: tileColor == p.hex, image: TileColor.swatch(p.hex)) { store.setTileColor(p.hex, for: [id]) }
+ }
+ if let tileColor, !TileColor.presets.contains(where: { $0.hex == tileColor }) {
+ MenuItems.add(colors, "Custom", on: true, image: TileColor.swatch(tileColor)) { store.setTileColor(tileColor, for: [id]) }
+ }
+ MenuItems.add(colors, "Other Color…") {
+ TileColorPanel.shared.show(tileColor) { hex in store.setTileColor(hex, for: [id]) }
+ }
+ colors.addItem(.separator())
+ MenuItems.add(colors, "Use This Color for All Favorites") { [weak grid] in
+ guard let grid else { return }
+ store.setTileColor(tileColor, for: grid.spaceFavoriteIDs())
+ }
+ m.addItem(.separator())
+ MenuItems.add(m, "Close") { actions.closeTab(id) }
+ MenuItems.add(m, "Archive") { store.archiveTab(id, reason: .manual) }
+ return m
+ }
+
+ private func pickIcon() {
+ guard let grid, let item = grid.store.item(itemID) else { return }
+ let panel = NSOpenPanel()
+ panel.allowedContentTypes = [.image]
+ panel.allowsMultipleSelection = false
+ panel.prompt = "Use Icon"
+ panel.message = "Choose an image for \(item.displayTitle)."
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ guard let key = grid.favicons.importCustomIcon(from: url) else { NSSound.beep(); return }
+ let old = item.tab?.customIconKey
+ grid.store.setCustomIcon(key, for: itemID)
+ if let old { grid.favicons.removeCustomIcon(old) }
+ }
+
+ // ArcTooltipTarget: the title by the pointer.
+ var text: String { model?.title ?? "" }
+ var keys: [String] { [] }
+ var followsCursor: Bool { true }
+ var subtitle: String? { nil }
+ var optionText: String? { nil }
+ var onShow: (() -> Void)? { nil }
+ var screenFrame: NSRect { window?.convertToScreen(convert(bounds, to: nil)) ?? .zero }
+ var hostWindow: NSWindow? { window }
+}
diff --git a/Sources/Cra/UI/Sidebar/List/SpaceListView.swift b/Sources/Cra/UI/Sidebar/List/SpaceListView.swift
new file mode 100644
index 0000000..190f391
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/List/SpaceListView.swift
@@ -0,0 +1,1010 @@
+import AppKit
+import SwiftUI
+import UniformTypeIdentifiers
+
+extension NSPasteboard.PasteboardType {
+ static let craSidebarItem = NSPasteboard.PasteboardType(UTType.craSidebarItem.identifier)
+}
+
+/// A space's pinned and Today list, drawn by AppKit like Arc's sidebar (an AppKit list of
+/// cells), not SwiftUI. Scrolling moves one clip view; nothing is laid out or diffed per frame.
+/// The list reads the store inside an observation scope, rebuilds its flat row models when
+/// anything it read changes (once per run loop turn), and hands each row view a new model only
+/// when it differs. Hover is one tracking area for the whole list, so scrolling under a resting
+/// pointer costs a lookup, not a tracking-area pass over every row.
+@MainActor
+final class SpaceListView: NSView, NSDraggingSource {
+ enum RowKey: Hashable {
+ case item(UUID)
+ case liveStatus(UUID)
+ case placeholder
+ case divider
+ case newTab
+ }
+
+ enum Content: Equatable {
+ case tab(TabRowModel)
+ case folder(FolderRowModel)
+ case split(SplitRowModel)
+ case liveStatus(LiveStatusModel)
+ case placeholder(active: Bool)
+ case divider(hasToday: Bool)
+ case newTab
+ }
+
+ struct Row {
+ let key: RowKey
+ var content: Content
+ var decor = DropDecor()
+ /// Item rows: where the item sits, for drops.
+ var itemID: UUID?
+ var parent: UUID?
+ var index = 0
+ var depth = 0
+ var frame = CGRect.zero
+ }
+
+ let spaceID: UUID
+ let store: SidebarStore
+ let ui: SidebarUIState
+ let actions: SidebarActions
+ let favicons: FaviconCache
+ private(set) var palette: SpacePalette
+ private let scrollView = SpaceListScrollView()
+ private let document = SpaceListDocument()
+ private(set) var rows: [Row] = []
+ /// Rows before the divider (pinned and its placeholder).
+ private var pinnedCount = 0
+ private var views: [RowKey: SidebarRowView] = [:]
+ private var colors = SidebarColors()
+ private var pinnedFrame = CGRect.zero
+ private var todayFrame = CGRect.zero
+ /// Bottom of the last row; the list keeps Arc's ~121 pt of empty space after it.
+ private var contentBottom: CGFloat = 0
+ private var highlightPinned = false
+ private var highlightToday = false
+ private var dropLineSpec: SidebarListDrop.Line?
+ private let topHairline = NSView()
+ private let bottomHairline = NSView()
+ private var hairlineState = (top: false, bottom: false)
+ private let pinnedHighlight = CALayer()
+ private let todayHighlight = CALayer()
+ private let dropLine = CALayer()
+ private let jumpPill = SidebarJumpPill()
+ private var syncQueued = false
+ private var synced = false
+ private var laidOutWidth: CGFloat = -1
+ private weak var hovered: SidebarRowView?
+ private weak var tipTarget: (any ArcTooltipTarget)?
+ /// While the list scrolls, rows slide under the pointer: no tips until it has rested.
+ private var scrolling = false
+ private var scrollRest: Task<Void, Never>?
+ private var lastRenaming: UUID?
+ let autoscroller = DragAutoscroller()
+ private static let all = NSHashTable<SpaceListView>.weakObjects()
+
+ /// A swipe slides the lists under a resting pointer: their hover ends until it settles.
+ static func endHover(for ui: SidebarUIState) {
+ for l in all.allObjects where l.ui === ui { l.hoverAt(nil) }
+ }
+
+ static func refreshHover(for ui: SidebarUIState) {
+ for l in all.allObjects where l.ui === ui { l.refreshHover() }
+ }
+
+ init(spaceID: UUID, store: SidebarStore, ui: SidebarUIState, actions: SidebarActions, favicons: FaviconCache) {
+ self.spaceID = spaceID
+ self.store = store
+ self.ui = ui
+ self.actions = actions
+ self.favicons = favicons
+ palette = (store.space(spaceID) ?? store.focusedSpace(window: ui.windowID)).theme.palette
+ super.init(frame: .zero)
+ wantsLayer = true
+ scrollView.drawsBackground = false
+ scrollView.contentView.drawsBackground = false
+ scrollView.hasVerticalScroller = false
+ scrollView.hasHorizontalScroller = false
+ scrollView.horizontalScrollElasticity = .none
+ scrollView.verticalScrollElasticity = .allowed
+ scrollView.automaticallyAdjustsContentInsets = false
+ document.list = self
+ document.wantsLayer = true
+ scrollView.documentView = document
+ scrollView.contentView.postsBoundsChangedNotifications = true
+ NotificationCenter.default.addObserver(self, selector: #selector(scrolled), name: NSView.boundsDidChangeNotification, object: scrollView.contentView)
+ addSubview(scrollView)
+ for h in [topHairline, bottomHairline] {
+ h.wantsLayer = true
+ h.alphaValue = 0
+ addSubview(h)
+ }
+ jumpPill.onClick = { [weak self] in self?.scrollToSelected() }
+ addSubview(jumpPill)
+ for l in [pinnedHighlight, todayHighlight] {
+ l.cornerRadius = 10
+ l.zPosition = -1
+ l.opacity = 0
+ document.layer?.addSublayer(l)
+ }
+ dropLine.cornerRadius = 1
+ dropLine.zPosition = 5
+ dropLine.opacity = 0
+ document.layer?.addSublayer(dropLine)
+ document.registerForDraggedTypes([.craSidebarItem])
+ autoscroller.anchor = document
+ Self.all.add(self)
+ sync()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ override func layout() {
+ super.layout()
+ scrollView.frame = bounds
+ topHairline.frame = NSRect(x: 0, y: 0, width: bounds.width, height: 1)
+ bottomHairline.frame = NSRect(x: 0, y: bounds.height - 1, width: bounds.width, height: 1)
+ if bounds.width != laidOutWidth {
+ laidOutWidth = bounds.width
+ layoutRows()
+ placeViews(animated: false, fresh: [], gone: [])
+ materialize()
+ }
+ updateHairlines(animated: false)
+ updateJumpPill(animated: false)
+ }
+
+ // MARK: Model
+
+ private func scheduleSync() {
+ guard !syncQueued else { return }
+ syncQueued = true
+ DispatchQueue.main.async { [weak self] in self?.sync() }
+ }
+
+ private func sync() {
+ syncQueued = false
+ let built = withObservationTracking { build() } onChange: { [weak self] in
+ Task { @MainActor in self?.scheduleSync() }
+ }
+ if let built { apply(built) }
+ }
+
+ private struct Built {
+ var rows: [Row]
+ var pinnedCount: Int
+ var palette: SpacePalette
+ var highlightPinned: Bool
+ var highlightToday: Bool
+ var line: SidebarListDrop.Line?
+ }
+
+ private func build() -> Built? {
+ guard let space = store.space(spaceID) else { return nil }
+ let palette = space.theme.palette
+ let window = ui.windowID
+ let drop = ui.listDrop
+ let picks = ui.multiSelection
+ let renaming = ui.renamingID
+ let focusID = ui.keyboardFocusID
+ let capturing = ui.capturingTabIDs
+ let refreshing = LiveFolderManager.shared.refreshing
+ var out: [Row] = []
+
+ func icon(_ key: String?) -> (NSImage?, Bool) {
+ guard let img = favicons.image(forKey: key) else { return (nil, false) }
+ return (img, favicons.glyphIsDark(forKey: key) == palette.isDark)
+ }
+
+ func decor(_ id: UUID) -> DropDecor {
+ guard let drop else { return DropDecor() }
+ var d = DropDecor()
+ d.nudge = drop.rowAbove == id ? -SidebarListMetrics.nudge : (drop.rowBelow == id ? SidebarListMetrics.nudge : 0)
+ d.dimmed = drop.draggedID == id || (picks.count > 1 && picks.contains(drop.draggedID) && picks.contains(id))
+ switch drop.target {
+ case .into(let t)? where t == id:
+ d.badge = store.item(id)?.isFolder == true ? .init(symbol: "folder", label: "Move to Folder") : .init(symbol: "rectangle.split.3x1", label: "Add to Split")
+ case .split(let t, let leading)? where t == id:
+ d.combine = .split(leading: leading)
+ d.combineDragged = drop.draggedID
+ case .newFolder(let t)? where t == id:
+ d.combine = .folder
+ d.combineDragged = drop.draggedID
+ default: break
+ }
+ return d
+ }
+
+ func add(_ item: SidebarItem, depth: Int, pinned: Bool, parent: UUID, index: Int) {
+ var row = Row(key: .item(item.id), content: .newTab, decor: decor(item.id), itemID: item.id, parent: parent, index: index, depth: depth)
+ if item.isFolder {
+ let expanded = store.isExpanded(item.id)
+ let glyph = palette.folderColors(item.folderIcon)
+ row.content = .folder(FolderRowModel(
+ id: item.id, depth: depth, title: item.title ?? "Folder", renameText: item.title ?? "",
+ editing: renaming == item.id, expanded: expanded, live: item.isLiveFolder,
+ tint: NSColor(glyph.tint), fill: NSColor(glyph.fill),
+ tabCount: expanded ? 0 : store.tabs(under: item.id).count,
+ liveBusy: refreshing.contains(item.id), liveError: item.liveFolder.flatMap(LiveFolderText.warning)?.help,
+ liveSignInURL: item.liveFolder.flatMap(LiveFolderText.warning)?.signInURL,
+ liveHelp: LiveFolderText.refreshHelp(item.liveFolder)))
+ out.append(row)
+ guard expanded else { return }
+ let kids = item.children
+ for c in store.children(of: item.id) {
+ add(c, depth: depth + 1, pinned: pinned, parent: item.id, index: kids.firstIndex(of: c.id) ?? 0)
+ }
+ if item.isLiveFolder, let m = Self.liveStatus(item) {
+ out.append(Row(key: .liveStatus(item.id), content: .liveStatus(LiveStatusModel(text: m.text, url: m.url, depth: depth + 1))))
+ }
+ } else if let tab = item.tab {
+ let selected = store.isSelected(item.id, window: window)
+ let navigatedAway = pinned && tab.url != tab.savedURL && !tab.savedURL.isEmpty
+ let (img, flip) = icon(tab.iconKey)
+ row.content = .tab(TabRowModel(
+ id: item.id, depth: depth, pinned: pinned, title: item.displayTitle, customTitle: item.title != nil,
+ renameText: item.title ?? item.displayTitle, subtitle: Self.subtitle(tab, navigatedAway: navigatedAway),
+ icon: img, flipIcon: flip, githubMark: tab.liveItemURL != nil && tab.customIconKey == nil,
+ editing: renaming == item.id, selected: selected,
+ highlighted: picks.isEmpty ? selected : picks.contains(item.id),
+ capturing: capturing.contains(item.id), muted: tab.muted, unread: item.isUnread,
+ navigatedAway: navigatedAway,
+ closeGroup: picks.contains(item.id) && picks.count > 1 ? picks.count : 1,
+ focusRing: focusID == item.id))
+ out.append(row)
+ } else if item.isSplit {
+ let children = store.children(of: item.id).filter(\.isTab)
+ let cells = children.map { c -> SplitRowModel.Cell in
+ let (img, flip) = icon(c.tab?.iconKey)
+ return .init(id: c.id, title: c.displayTitle, icon: img, flipIcon: flip)
+ }
+ row.content = .split(SplitRowModel(
+ id: item.id, depth: depth, today: !pinned,
+ selected: children.contains { store.isSelected($0.id, window: window) },
+ focusRing: focusID.map { f in children.contains { $0.id == f } } ?? false,
+ cells: cells))
+ out.append(row)
+ }
+ }
+
+ let pinnedKids = store.item(space.pinnedContainerID)?.children ?? []
+ let pinnedItems = store.listedPinnedItems(in: space, window: window)
+ for item in pinnedItems {
+ add(item, depth: 0, pinned: true, parent: space.pinnedContainerID, index: pinnedKids.firstIndex(of: item.id) ?? 0)
+ }
+ let section = dropSection(drop)
+ // With nothing pinned the list is 8 pt tall; a drag opens a real target. Not when
+ // collapsed: the placeholder would claim an empty list and open under the pointer,
+ // taking drops meant for the top of Today.
+ if pinnedKids.isEmpty && drop != nil {
+ out.append(Row(key: .placeholder, content: .placeholder(active: section == .pinned)))
+ }
+ let pinnedCount = out.count
+ let todayKids = store.item(space.todayContainerID)?.children ?? []
+ out.append(Row(key: .divider, content: .divider(hasToday: !todayKids.isEmpty)))
+ let atTop = store.settings.newTabButtonAtTop
+ if atTop { out.append(Row(key: .newTab, content: .newTab)) }
+ for item in store.children(of: space.todayContainerID) {
+ add(item, depth: 0, pinned: false, parent: space.todayContainerID, index: todayKids.firstIndex(of: item.id) ?? 0)
+ }
+ if !atTop { out.append(Row(key: .newTab, content: .newTab)) }
+ return Built(rows: out, pinnedCount: pinnedCount, palette: palette,
+ highlightPinned: section == .pinned && !pinnedItems.isEmpty, highlightToday: section == .today,
+ line: drop?.line)
+ }
+
+ /// Arc shows the host under a pinned tab only when it has left the pinned site (navigating
+ /// within the same host shows nothing); a live folder's pull request shows its author.
+ private static func subtitle(_ tab: TabData, navigatedAway: Bool) -> String? {
+ if let author = tab.liveSubtitle, URL(string: tab.url)?.host == "github.com" { return author }
+ guard navigatedAway, let host = URL(string: tab.url)?.host, let saved = URL(string: tab.savedURL)?.host,
+ host.replacingOccurrences(of: "www.", with: "") != saved.replacingOccurrences(of: "www.", with: "") else { return nil }
+ return host.replacingOccurrences(of: "www.", with: "")
+ }
+
+ /// A line inside the open live folder when there are no pull requests to show, or GitHub
+ /// can't be read (Arc: "Sign back in to GitHub.", "Login with SSO to unlock this folder").
+ private static func liveStatus(_ item: SidebarItem) -> (text: String, url: String?)? {
+ guard let live = item.liveFolder, item.children.isEmpty else { return nil }
+ switch live.lastError {
+ case .notSignedIn?: return ("Sign back in to GitHub.", live.signInURL)
+ case .some: return ("We’re having trouble connecting to GitHub; click here to see your Pull Requests.", "https://github.com/pulls")
+ case nil:
+ if let org = live.ssoOrganizations.first { return ("Login with SSO to unlock this folder", "https://github.com/orgs/\(org)/sso") }
+ if live.lastFetch == nil { return nil }
+ return ("Pull requests from you and your team will show up here automatically", nil)
+ }
+ }
+
+ /// Which list a drop lands in, when that pins or unpins the dragged item; that list
+ /// lights up while the drag hovers.
+ private func dropSection(_ drop: SidebarListDrop?) -> SidebarSection? {
+ guard let drop, let target = drop.target else { return nil }
+ let lands: SidebarSection
+ switch target {
+ case .insert(let parent, _): lands = isPinnedList(parent) ? .pinned : .today
+ case .into(let id): lands = isPinnedList(id) ? .pinned : .today
+ case .newFolder: lands = .pinned
+ case .split: lands = .today
+ }
+ return lands == (isPinnedList(drop.draggedID) ? .pinned : .today) ? nil : lands
+ }
+
+ private func isPinnedList(_ id: UUID) -> Bool {
+ if case .pinned? = store.rootContainer(of: id) { return true }
+ return false
+ }
+
+ private func apply(_ b: Built) {
+ palette = b.palette
+ let newColors = SidebarColors(b.palette)
+ let recolor = newColors != colors
+ colors = newColors
+ let oldFrames = Dictionary(rows.map { ($0.key, $0.frame) }, uniquingKeysWith: { a, _ in a })
+ rows = b.rows
+ pinnedCount = b.pinnedCount
+ highlightPinned = b.highlightPinned
+ highlightToday = b.highlightToday
+ dropLineSpec = b.line
+ layoutRows()
+
+ var fresh: [SidebarRowView] = []
+ var keep = Set<RowKey>()
+ let range = wantedRange()
+ for row in rows where Self.inRange(placed(row), range) {
+ keep.insert(row.key)
+ var view = views[row.key]
+ if let v = view, !Self.fits(v, row.content) {
+ retire(v)
+ view = nil
+ }
+ if view == nil {
+ let v = makeView(row)
+ views[row.key] = v
+ document.addSubview(v)
+ fresh.append(v)
+ view = v
+ }
+ guard let view else { continue }
+ if recolor { view.setColors(colors) }
+ configure(view, row.content)
+ }
+ var gone: [SidebarRowView] = []
+ for (k, v) in views where !keep.contains(k) {
+ views[k] = nil
+ gone.append(v)
+ }
+ let moved = rows.contains { row in oldFrames[row.key].map { $0 != row.frame } ?? false }
+ let animate = synced && window != nil && ui.spaceSwipe == 0 && (!fresh.isEmpty || !gone.isEmpty || moved)
+ for row in rows { views[row.key]?.applyDecor(row.decor, animated: synced) }
+ placeViews(animated: animate, fresh: fresh, gone: gone)
+ materializedAt = scrollView.contentView.bounds.minY
+ updateDropChrome()
+ synced = true
+ if let h = hovered, h.superview == nil || gone.contains(h) { hovered = nil }
+ refreshHover()
+ scrollToRenaming()
+ updateJumpPill(animated: synced)
+ }
+
+ private static func fits(_ v: SidebarRowView, _ c: Content) -> Bool {
+ switch c {
+ case .tab: return v is TabRowView
+ case .folder: return v is FolderRowView
+ case .split: return v is SplitRowView
+ case .liveStatus: return v is LiveStatusRowView
+ case .placeholder: return v is PinPlaceholderRowView
+ case .divider: return v is DividerRowView
+ case .newTab: return v is NewTabRowView
+ }
+ }
+
+ private func makeView(_ row: Row) -> SidebarRowView {
+ switch row.content {
+ case .tab: return TabRowView(key: row.key, list: self, colors: colors)
+ case .folder: return FolderRowView(key: row.key, list: self, colors: colors)
+ case .split: return SplitRowView(key: row.key, list: self, colors: colors)
+ case .liveStatus: return LiveStatusRowView(key: row.key, list: self, colors: colors)
+ case .placeholder: return PinPlaceholderRowView(key: row.key, list: self, colors: colors)
+ case .divider: return DividerRowView(key: row.key, list: self, colors: colors)
+ case .newTab: return NewTabRowView(key: row.key, list: self, colors: colors)
+ }
+ }
+
+ private func configure(_ v: SidebarRowView, _ c: Content) {
+ switch c {
+ case .tab(let m): (v as? TabRowView)?.apply(m)
+ case .folder(let m): (v as? FolderRowView)?.apply(m)
+ case .split(let m): (v as? SplitRowView)?.apply(m)
+ case .liveStatus(let m): (v as? LiveStatusRowView)?.apply(m)
+ case .placeholder(let active): (v as? PinPlaceholderRowView)?.apply(active: active)
+ case .divider(let hasToday): (v as? DividerRowView)?.apply(hasToday: hasToday)
+ case .newTab: break
+ }
+ }
+
+ // MARK: Rows near the screen
+
+ /// Rows get views only within a screen or so of what shows, like NSTableView's cells: on
+ /// every frame of a scroll AppKit walks every view in the list to update tracking areas.
+ private var materializedAt: CGFloat = 0
+
+ private func wantedRange() -> (CGFloat, CGFloat) {
+ let clip = scrollView.contentView.bounds
+ let margin = max(400, clip.height)
+ return (clip.minY - margin, clip.maxY + margin)
+ }
+
+ private static func inRange(_ f: CGRect, _ r: (CGFloat, CGFloat)) -> Bool { f.maxY >= r.0 && f.minY <= r.1 }
+
+ private func materialize() {
+ materializedAt = scrollView.contentView.bounds.minY
+ let range = wantedRange()
+ for row in rows {
+ let inside = Self.inRange(placed(row), range)
+ if inside, views[row.key] == nil {
+ let v = makeView(row)
+ views[row.key] = v
+ document.addSubview(v)
+ configure(v, row.content)
+ v.applyDecor(row.decor, animated: false)
+ v.frame = placed(row)
+ } else if !inside, let v = views[row.key] {
+ views[row.key] = nil
+ retire(v)
+ }
+ }
+ }
+
+ private func retire(_ v: SidebarRowView) {
+ if hovered === v { hovered = nil }
+ v.removeFromSuperview()
+ }
+
+ func depth(of key: RowKey) -> Int { rows.first { $0.key == key }?.depth ?? 0 }
+
+ // MARK: Layout
+
+ /// SpaceSectionView's stacks: 3 pt on top, pinned rows (at least 8 pt), the 18 pt divider,
+ /// then Today; rows 1 pt apart and 10 pt in from the sides.
+ private func layoutRows() {
+ let width = bounds.width
+ let inner = max(0, width - 20)
+ var y: CGFloat = 3
+ let pinnedTop = y
+ for i in 0..<rows.count {
+ let isDivider = rows[i].key == .divider
+ if i == pinnedCount {
+ pinnedFrame = NSRect(x: 10, y: pinnedTop, width: inner, height: y - pinnedTop)
+ y = pinnedTop + max(8, y - pinnedTop)
+ }
+ if isDivider {
+ rows[i].frame = NSRect(x: 0, y: y, width: width, height: 18)
+ y += 18
+ continue
+ }
+ let first = i == 0 || i == pinnedCount + 1
+ if !first { y += CraMetrics.rowSpacing }
+ let h: CGFloat
+ if case .liveStatus(let m) = rows[i].content { h = LiveStatusRowView.height(m, width: inner) } else { h = CraMetrics.rowHeight }
+ rows[i].frame = NSRect(x: 10, y: y, width: inner, height: h)
+ y += h
+ }
+ let todayTop = rows.indices.contains(pinnedCount) ? rows[pinnedCount].frame.maxY : y
+ todayFrame = NSRect(x: 10, y: todayTop, width: inner, height: max(0, y - todayTop))
+ contentBottom = y
+ let height = max(y + 121, scrollView.contentView.bounds.height)
+ if document.frame.size != NSSize(width: width, height: height) {
+ document.frame = NSRect(x: 0, y: 0, width: width, height: height)
+ }
+ }
+
+ private func placed(_ row: Row) -> NSRect { row.frame.offsetBy(dx: 0, dy: row.decor.nudge) }
+
+ private func placeViews(animated: Bool, fresh: [SidebarRowView], gone: [SidebarRowView]) {
+ guard animated else {
+ for row in rows { views[row.key]?.frame = placed(row) }
+ gone.forEach { $0.removeFromSuperview() }
+ return
+ }
+ let freshSet = Set(fresh.map(ObjectIdentifier.init))
+ for row in rows {
+ guard let v = views[row.key], freshSet.contains(ObjectIdentifier(v)) else { continue }
+ // Rows opening inside a folder drop in from just above; others fade in place.
+ v.frame = placed(row).offsetBy(dx: 0, dy: row.depth > 0 ? -6 : 0)
+ v.alphaValue = 0
+ }
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = SidebarListMetrics.duration
+ ctx.timingFunction = SidebarListMetrics.timing
+ ctx.allowsImplicitAnimation = true
+ for row in rows {
+ guard let v = views[row.key] else { continue }
+ if v.frame != placed(row) { v.animator().frame = placed(row) }
+ if freshSet.contains(ObjectIdentifier(v)) { v.animator().alphaValue = 1 }
+ }
+ for v in gone { v.animator().alphaValue = 0 }
+ } completionHandler: {
+ gone.forEach { $0.removeFromSuperview() }
+ }
+ }
+
+ private func updateDropChrome() {
+ let fill = colors.hoverFill.cgColor
+ CATransaction.begin()
+ CATransaction.setAnimationDuration(0.2)
+ pinnedHighlight.backgroundColor = fill
+ todayHighlight.backgroundColor = fill
+ pinnedHighlight.frame = pinnedFrame.insetBy(dx: -2, dy: 0)
+ todayHighlight.frame = todayFrame.insetBy(dx: -2, dy: 0)
+ pinnedHighlight.opacity = highlightPinned ? 1 : 0
+ todayHighlight.opacity = highlightToday ? 1 : 0
+ if let line = dropLineSpec {
+ dropLine.backgroundColor = colors.textPrimary.withAlphaComponent(0.5).cgColor
+ if dropLine.opacity == 0 {
+ CATransaction.setDisableActions(true)
+ dropLine.frame = NSRect(x: line.minX, y: line.y - 1, width: max(0, line.maxX - line.minX), height: 2)
+ CATransaction.setDisableActions(false)
+ } else {
+ dropLine.frame = NSRect(x: line.minX, y: line.y - 1, width: max(0, line.maxX - line.minX), height: 2)
+ }
+ dropLine.opacity = 1
+ } else {
+ dropLine.opacity = 0
+ }
+ CATransaction.commit()
+ }
+
+ // MARK: Scrolling
+
+ @objc private func scrolled() {
+ if abs(scrollView.contentView.bounds.minY - materializedAt) > 120 { materialize() }
+ if !scrolling {
+ scrolling = true
+ if let t = tipTarget { ArcTooltipController.shared.mouseExited(t) }
+ tipTarget = nil
+ ArcTooltipController.shared.paused = true
+ }
+ scrollRest?.cancel()
+ scrollRest = Task { @MainActor [weak self] in
+ try? await Task.sleep(for: .milliseconds(200))
+ guard !Task.isCancelled else { return }
+ ArcTooltipController.shared.paused = false
+ self?.scrolling = false
+ self?.refreshHover()
+ }
+ updateHairlines(animated: true)
+ updateJumpPill(animated: true)
+ refreshHover()
+ }
+
+ // MARK: Jump to the open tab (Dia)
+
+ /// The selected tab's row (a split row when the tab is in one) and the item IDs whose
+ /// favicons stand for it. A tab in a closed folder has no row: the folder stands in for it.
+ private func selectedRow() -> (row: Row, tabs: [UUID])? {
+ for row in rows {
+ switch row.content {
+ case .tab(let m) where m.selected: return (row, [m.id])
+ case .split(let m) where m.selected: return (row, m.cells.map(\.id))
+ default: continue
+ }
+ }
+ guard let id = store.selectedTabID(in: spaceID, window: ui.windowID) else { return nil }
+ var parent = store.item(id)?.parentID
+ while let p = parent {
+ if let row = rows.first(where: { $0.key == .item(p) }) { return (row, [id]) }
+ parent = store.item(p)?.parentID
+ }
+ return nil
+ }
+
+ /// Dia's TabOverflowGeometryTracker: the pill shows while the selected row is wholly
+ /// past an edge of the visible list, at that edge.
+ private func updateJumpPill(animated: Bool) {
+ let visible = scrollView.contentView.bounds
+ var edge: SidebarJumpPill.Edge?
+ var tabs: [UUID] = []
+ if let (row, ids) = selectedRow(), visible.height > 0 {
+ let f = placed(row)
+ if f.maxY <= visible.minY { edge = .top } else if f.minY >= visible.maxY { edge = .bottom }
+ tabs = ids
+ }
+ let icons = tabs.map { id -> (image: NSImage?, flip: Bool, key: String?) in
+ let key = store.item(id)?.tab?.iconKey
+ return (favicons.image(forKey: key), favicons.glyphIsDark(forKey: key) == true, key)
+ }
+ jumpPill.show(edge: edge, icons: icons, animated: animated && window != nil)
+ guard let edge else { return }
+ let size = SidebarJumpPill.size(icons: min(3, icons.count))
+ let y = edge == .top ? SidebarJumpPill.inset : bounds.height - SidebarJumpPill.inset - size.height
+ let frame = NSRect(x: ((bounds.width - size.width) / 2).rounded(), y: y, width: size.width, height: size.height)
+ if jumpPill.frame != frame { jumpPill.frame = frame }
+ }
+
+ /// Testing: the jump pill's click on the focused space's list.
+ static func jumpToSelected(for ui: SidebarUIState, space: UUID) {
+ for l in all.allObjects where l.ui === ui && l.spaceID == space { l.scrollToSelected() }
+ }
+
+ /// Scrolls the selected tab to the middle of the list (as far as the list allows).
+ private func scrollToSelected() {
+ guard let (row, _) = selectedRow() else { return }
+ let clip = scrollView.contentView
+ let visible = clip.bounds
+ let f = placed(row)
+ let y = min(max(0, f.midY - visible.height / 2), max(0, document.frame.height - visible.height))
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.45
+ ctx.timingFunction = CAMediaTimingFunction(controlPoints: 0.3, 0, 0.2, 1)
+ clip.animator().setBoundsOrigin(NSPoint(x: 0, y: y))
+ } completionHandler: { [weak self] in
+ MainActor.assumeIsolated { self?.scrollView.reflectScrolledClipView(clip) }
+ }
+ }
+
+ /// Arc 1.170 draws a full-width 1 pt hairline (~5% black over the light theme) at an edge of
+ /// the list only while rows are hidden past it, fading over ~0.25 s.
+ private func updateHairlines(animated: Bool) {
+ let clip = scrollView.contentView.bounds
+ let state = (top: clip.minY > 0.5, bottom: contentBottom - clip.minY > clip.height + 0.5)
+ let color = (colors.isDark ? NSColor.white.withAlphaComponent(0.07) : NSColor.black.withAlphaComponent(0.05)).cgColor
+ topHairline.layer?.backgroundColor = color
+ bottomHairline.layer?.backgroundColor = color
+ guard state != hairlineState || !animated else { return }
+ hairlineState = state
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = animated ? 0.25 : 0
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ topHairline.animator().alphaValue = state.top ? 1 : 0
+ bottomHairline.animator().alphaValue = state.bottom ? 1 : 0
+ }
+ }
+
+ /// A new folder starts renaming at the top of pinned, maybe scrolled away.
+ private func scrollToRenaming() {
+ let id = ui.renamingID
+ defer { lastRenaming = id }
+ guard let id, id != lastRenaming, let row = rows.first(where: { $0.key == .item(id) }) else { return }
+ let clip = scrollView.contentView
+ let visible = clip.bounds
+ guard row.frame.minY < visible.minY || row.frame.maxY > visible.maxY else { return }
+ let y = min(max(0, row.frame.midY - visible.height / 2), max(0, document.frame.height - visible.height))
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.25
+ ctx.timingFunction = SidebarListMetrics.timing
+ clip.animator().setBoundsOrigin(NSPoint(x: 0, y: y))
+ }
+ }
+
+ // MARK: Hover
+
+ func pointerMoved(_ event: NSEvent?) {
+ hoverAt(event?.locationInWindow)
+ }
+
+ private func refreshHover() {
+ guard let w = window else { return }
+ let p = w.mouseLocationOutsideOfEventStream
+ let inside = document.visibleRect.contains(document.convert(p, from: nil)) && w.isVisible
+ hoverAt(inside && document.isMouseInside ? p : nil)
+ }
+
+ private func hoverAt(_ windowPoint: NSPoint?) {
+ var target: SidebarRowView?
+ var local = NSPoint.zero
+ // A swipe slides the strip under the pointer: no hover until it settles.
+ if let wp = windowPoint, ui.spaceSwipe == 0, ui.libraryPage == nil {
+ let p = document.convert(wp, from: nil)
+ if document.visibleRect.contains(p), let row = rows.first(where: { placed($0).contains(p) }), let v = views[row.key] {
+ target = v
+ local = v.convert(wp, from: nil)
+ }
+ }
+ if hovered !== target {
+ hovered?.isHovered = false
+ hovered = target
+ target?.isHovered = true
+ if let t = target as? TabRowView, let id = t.model?.id {
+ if ui.hoveredTabID != id { ui.hoveredTabID = id }
+ } else if let h = ui.hoveredTabID, views[.item(h)] != nil {
+ ui.hoveredTabID = nil
+ }
+ }
+ target?.hoverMoved(to: local)
+ let tip = scrolling ? nil : target?.tooltipTarget(at: local)
+ if let old = tipTarget, old !== tip { ArcTooltipController.shared.mouseExited(old) }
+ tipTarget = tip
+ if let tip { ArcTooltipController.shared.mouseMoved(in: tip) }
+ }
+
+ // MARK: Clicks
+
+ func clickTab(_ id: UUID, event: NSEvent) {
+ let flags = event.modifierFlags.intersection([.command, .shift])
+ if !flags.isEmpty {
+ ui.pick(id, range: flags.contains(.shift), in: store)
+ } else if event.clickCount == 2 {
+ ui.renamingID = id
+ } else {
+ ui.clearPicks(anchor: id)
+ if ui.keyboardFocusID != nil { ui.keyboardFocusID = nil }
+ store.selectTab(id, window: ui.windowID)
+ }
+ }
+
+ /// Close acts on every picked tab when this row is one of them.
+ func closeGroup(for id: UUID) -> [UUID] {
+ ui.multiSelection.contains(id) && ui.multiSelection.count > 1 ? Array(ui.multiSelection) : [id]
+ }
+
+ func closeTabs(_ ids: [UUID]) {
+ // The open tab goes last so closing it doesn't hop through tabs about to close.
+ let open = store.selectedTabID(window: ui.windowID)
+ let ordered = ids.filter { $0 != open } + ids.filter { $0 == open }
+ for id in ordered { actions.closeTab(id) }
+ ui.multiSelection.subtract(ids)
+ }
+
+ func listMenu() -> NSMenu? { SidebarMenus.spaceList(self) }
+
+ // MARK: Drag source
+
+ func beginDrag(_ id: UUID, from row: SidebarRowView, event: NSEvent) {
+ hoverAt(nil)
+ ui.draggingID = id
+ let pb = NSPasteboardItem()
+ if let data = try? JSONEncoder().encode(SidebarDragItem(id: id)) { pb.setData(data, forType: .craSidebarItem) }
+ let item = NSDraggingItem(pasteboardWriter: pb)
+ item.setDraggingFrame(row.bounds, contents: dragImage(of: row))
+ row.beginDraggingSession(with: [item], event: event, source: self)
+ }
+
+ /// The row as it looks at rest, on a rounded card.
+ private func dragImage(of row: SidebarRowView) -> NSImage {
+ let size = row.bounds.size
+ let rep = row.bitmapImageRepForCachingDisplay(in: row.bounds)
+ if let rep { row.cacheDisplay(in: row.bounds, to: rep) }
+ let fill = colors.isDark ? NSColor(white: 0.18, alpha: 0.92) : NSColor(white: 1, alpha: 0.92)
+ return NSImage(size: size, flipped: false) { r in
+ fill.setFill()
+ NSBezierPath(roundedRect: r, xRadius: CraMetrics.rowCorner, yRadius: CraMetrics.rowCorner).fill()
+ rep?.draw(in: r)
+ return true
+ }
+ }
+
+ func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
+ context == .withinApplication ? [.move, .copy, .generic, .private] : []
+ }
+
+ func draggingSession(_ session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
+ autoscroller.stop()
+ ui.draggingID = nil
+ if ui.listDrop != nil { ui.listDrop = nil }
+ }
+
+ // MARK: Drop target
+
+ func dragUpdated(_ info: NSDraggingInfo, entered: Bool) -> NSDragOperation {
+ // Rows here set draggingID when the drag starts; a drag from another window only says
+ // what it carries through the pasteboard.
+ if entered, let data = info.draggingPasteboard.data(forType: .craSidebarItem),
+ let d = try? JSONDecoder().decode(SidebarDragItem.self, from: data), ui.draggingID != d.id {
+ ui.draggingID = d.id
+ }
+ autoscroller.update()
+ guard let id = ui.draggingID, store.item(id) != nil else { return [] }
+ let drop = resolve(dragged: id, at: document.convert(info.draggingLocation, from: nil))
+ if drop != ui.listDrop {
+ ui.listDrop = drop
+ // A tick when a row starts offering to combine, so the change of meaning is felt as well as seen.
+ switch drop.target {
+ case .split?, .newFolder?:
+ if store.settings.hapticFeedbackOnReorder { NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now) }
+ default: break
+ }
+ // Spring-loaded folders: hovering a closed folder opens it.
+ if case .into(let f)? = drop.target, store.item(f)?.isFolder == true, !store.isExpanded(f) {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [ui, store] in
+ guard ui.listDrop?.target == .into(f) else { return }
+ store.setExpanded(f, true)
+ }
+ }
+ }
+ return info.draggingSourceOperationMask.contains(.move) ? .move : .copy
+ }
+
+ func dragExited() {
+ autoscroller.stop()
+ if ui.listDrop != nil { ui.listDrop = nil }
+ }
+
+ func performDrop(_ info: NSDraggingInfo) -> Bool {
+ autoscroller.stop()
+ guard let id = ui.draggingID, store.item(id) != nil else { return false }
+ let point = document.convert(info.draggingLocation, from: nil)
+ let drop = ui.listDrop ?? resolve(dragged: id, at: point)
+ ui.listDrop = nil
+ applyDrop(drop)
+ // A click whose pointer slipped 3 pt became a drag; let go on its own row it is still a
+ // click, so the tab opens (GitHub #7: "a single click on a tab sometimes did nothing").
+ if drop.target == nil, store.item(id)?.isTab == true, ui.multiSelection.count <= 1,
+ rows.first(where: { $0.itemID == id })?.frame.contains(point) == true {
+ ui.clearPicks(anchor: id)
+ store.selectTab(id, window: ui.windowID)
+ }
+ // Dia: Tabs ▸ "Haptic feedback when reordering tabs".
+ if drop.target != nil, store.settings.hapticFeedbackOnReorder {
+ NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .drawCompleted)
+ }
+ ui.draggingID = nil
+ return true
+ }
+
+ private func applyDrop(_ drop: SidebarListDrop) {
+ let id = drop.draggedID
+ // A picked tab carries the other picks along (a split still takes one pane).
+ let group = ui.group(for: id, in: store)
+ switch drop.target {
+ case .insert(let parent, let index)?:
+ store.moveItems(group, to: parent, index: index)
+ case .newFolder(let tab)?:
+ if let folder = store.createFolder(combining: tab, with: group) { ui.renamingID = folder.id }
+ case .split(let tab, let leading)?:
+ store.createSplit(with: leading ? [id, tab] : [tab, id], at: tab)
+ case .into(let target)?:
+ if store.item(target)?.isFolder == true {
+ store.moveItems(group, to: target, index: nil)
+ store.setExpanded(target, true)
+ } else {
+ store.moveItem(id, to: target, index: nil)
+ }
+ case nil:
+ break
+ }
+ }
+
+ private func isInside(_ id: UUID, _ ancestor: UUID) -> Bool {
+ var cur = store.item(id)?.parentID
+ var hops = 0
+ while let c = cur, hops < 64 {
+ if c == ancestor { return true }
+ cur = store.item(c)?.parentID
+ hops += 1
+ }
+ return false
+ }
+
+ /// Top and bottom quarters of a row insert before/after it; the middle combines: a folder
+ /// takes the item, a Today tab makes a split (the dragged tab goes on the side of the row
+ /// it hovers), a pinned tab makes a new folder, a split row takes a pane.
+ func resolve(dragged id: UUID, at p: CGPoint) -> SidebarListDrop {
+ guard let space = store.space(spaceID) else { return SidebarListDrop(draggedID: id) }
+ let items = rows.filter { $0.itemID != nil }
+ let group = ui.group(for: id, in: store)
+ let isTab = store.item(id)?.isTab == true
+ let half = CraMetrics.rowSpacing / 2
+ var target: SidebarListDrop.Target?
+
+ if let r = items.first(where: { p.y >= $0.frame.minY - half && p.y < $0.frame.maxY + half }),
+ let rid = r.itemID, let parent = r.parent, let item = store.item(rid) {
+ let f = (p.y - r.frame.minY) / max(1, r.frame.height)
+ let middle = (0.25..<0.75).contains(f)
+ let before = SidebarListDrop.Target.insert(parent: parent, index: r.index)
+ let after = SidebarListDrop.Target.insert(parent: parent, index: r.index + 1)
+ if group.contains(rid) || isInside(rid, id) {
+ target = nil
+ } else if item.isFolder {
+ if f < 0.25 { target = before }
+ else if f >= 0.75 { target = store.isExpanded(rid) ? .insert(parent: rid, index: 0) : after }
+ else { target = .into(rid) }
+ } else if middle && isTab && item.isTab {
+ target = isInside(rid, space.todayContainerID)
+ ? .split(with: rid, leading: p.x < r.frame.midX)
+ : .newFolder(with: rid)
+ } else if middle && isTab && item.isSplit {
+ target = .into(rid)
+ } else {
+ target = f < 0.5 ? before : after
+ }
+ } else {
+ // Between sections or past the last row: the divider splits pinned from today.
+ if p.y < (pinnedFrame.maxY + todayFrame.minY) / 2 {
+ target = .insert(parent: space.pinnedContainerID, index: p.y < pinnedFrame.minY ? 0 : store.children(of: space.pinnedContainerID).count)
+ } else {
+ // The New Tab row may lead Today, so its first tab, not the section, marks the top.
+ let firstToday = items.first { $0.parent == space.todayContainerID }?.frame.minY ?? todayFrame.minY
+ target = .insert(parent: space.todayContainerID, index: p.y < firstToday ? 0 : store.children(of: space.todayContainerID).count)
+ }
+ }
+
+ // Dropping next to itself, or a folder into itself, changes nothing.
+ if case .insert(let parent, let index)? = target {
+ if parent == id || isInside(parent, id) {
+ target = nil
+ } else if group.count == 1, store.item(id)?.parentID == parent, let old = store.item(parent)?.children.firstIndex(of: id), index == old || index == old + 1 {
+ target = nil
+ }
+ }
+
+ // A live folder fills itself: nothing goes into it from outside, and its tabs make no new folders.
+ switch target {
+ case .into(let f)? where store.item(f)?.isLiveFolder == true: target = nil
+ case .insert(let parent, _)? where store.item(parent)?.isLiveFolder == true && store.item(id)?.parentID != parent: target = nil
+ case .newFolder(let tab)? where store.item(store.item(tab)?.parentID ?? tab)?.isLiveFolder == true: target = nil
+ default: break
+ }
+
+ var drop = SidebarListDrop(draggedID: id, target: target)
+ guard case .insert(let parent, let index)? = target else { return drop }
+ let kids = store.item(parent)?.children ?? []
+ var y: CGFloat?
+ if index < kids.count, let f = items.first(where: { $0.itemID == kids[index] })?.frame {
+ y = f.minY - half
+ } else if index > 0, let r = items.last(where: { $0.itemID == kids[index - 1] || ($0.itemID.map { isInside($0, kids[index - 1]) } ?? false) }) {
+ y = r.frame.maxY + half
+ } else if store.item(parent)?.isFolder == true, let f = items.first(where: { $0.itemID == parent })?.frame {
+ y = f.maxY + half
+ }
+ // An empty pinned list shows its own placeholder instead of a line.
+ guard let y else { return drop }
+ let depth = items.first { $0.itemID == parent }.map { $0.depth + 1 } ?? 0
+ drop.line = .init(y: y, minX: todayFrame.minX + 8 + CGFloat(depth) * CraMetrics.indent, maxX: todayFrame.maxX - 6)
+ drop.rowAbove = items.last { $0.frame.maxY <= y + 1 }?.itemID
+ drop.rowBelow = items.first { $0.frame.minY >= y - 1 }?.itemID
+ return drop
+ }
+}
+
+enum SidebarListMetrics {
+ /// Rows either side of the insertion line ease this far apart.
+ static let nudge: CGFloat = 3
+ /// SwiftUI's .snappy(duration: 0.22, extraBounce: 0), which the list's changes used.
+ static let duration: TimeInterval = 0.22
+ static let timing = CAMediaTimingFunction(controlPoints: 0.2, 0.9, 0.25, 1)
+}
+
+/// The list's scroll view. Space swipes are read by the window controller's scroll monitor,
+/// which has to see every event of a gesture: responsive scrolling takes a gesture's events
+/// off that path once it starts over the list, and a horizontal gesture never scrolls a list.
+final class SpaceListScrollView: NSScrollView {
+ override class var isCompatibleWithResponsiveScrolling: Bool { false }
+
+ override func scrollWheel(with event: NSEvent) {
+ if event.hasPreciseScrollingDeltas, event.momentumPhase.isEmpty, abs(event.scrollingDeltaX) > abs(event.scrollingDeltaY) { return }
+ super.scrollWheel(with: event)
+ }
+}
+
+/// The list's document: rows sit on it, it takes drops, hovers and the list's own menu.
+final class SpaceListDocument: NSView {
+ weak var list: SpaceListView?
+ private(set) var isMouseInside = false
+
+ override var isFlipped: Bool { true }
+ override class var isCompatibleWithResponsiveScrolling: Bool { false }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ // activeAlways: the key window is often a page, not the sidebar's.
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect],
+ owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { isMouseInside = true; list?.pointerMoved(event) }
+ override func mouseMoved(with event: NSEvent) { isMouseInside = true; list?.pointerMoved(event) }
+ override func mouseExited(with event: NSEvent) { isMouseInside = false; list?.pointerMoved(nil) }
+
+ // Right-click on empty list space; rows have their own menus.
+ override func menu(for event: NSEvent) -> NSMenu? { list?.listMenu() }
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { list?.dragUpdated(sender, entered: true) ?? [] }
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { list?.dragUpdated(sender, entered: false) ?? [] }
+ override func draggingExited(_ sender: NSDraggingInfo?) { list?.dragExited() }
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { list?.performDrop(sender) ?? false }
+ override func draggingEnded(_ sender: NSDraggingInfo) { list?.dragExited() }
+}
diff --git a/Sources/Cra/UI/Sidebar/List/SpacePagerView.swift b/Sources/Cra/UI/Sidebar/List/SpacePagerView.swift
new file mode 100644
index 0000000..906e77b
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/List/SpacePagerView.swift
@@ -0,0 +1,156 @@
+import AppKit
+import SwiftUI
+
+/// Dia's paging container in AppKit: every space's column (favorites, header, tab list) sits
+/// side by side on a strip, the strip follows a swipe 1:1, then a spring settles it on a page.
+/// The page index places the strip by frame; the rest of the travel is a translation of the
+/// pager's sublayers, which Core Animation moves on its own. A swipe or a settle never lays out,
+/// diffs or redraws a row.
+@MainActor
+final class SpacePagerView: NSView {
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let actions: SidebarActions
+ private let favicons: FaviconCache
+ private let strip = NSView()
+ private var columns: [UUID: NSView] = [:]
+ /// The page the strip's frame was placed at, and the width it was placed with.
+ private var placedIndex = 0
+ private var placedWidth: CGFloat = 0
+ private var placedSwipe: CGFloat = 0
+ /// The translation (points) the model layer holds; the presentation may still be springing.
+ private var offset: CGFloat = 0
+ /// Release speed for the next settle, relative to the distance left (Dia's spring).
+ private var pendingVelocity: Double = 0
+ private var ownSettle: Int?
+ private static let settleKey = "settle"
+
+ init(store: SidebarStore, ui: SidebarUIState, actions: SidebarActions, favicons: FaviconCache) {
+ self.store = store
+ self.ui = ui
+ self.actions = actions
+ self.favicons = favicons
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.masksToBounds = true
+ strip.wantsLayer = true
+ addSubview(strip)
+ ui.observeSpaceSwipe { [weak self] in self?.swipeChanged() }
+ observeSpaces()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ // The strip takes no clicks or hovers under the fingers, nor while the Library covers it.
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ ui.spaceSwipe != 0 || ui.libraryPage != nil ? nil : super.hitTest(point)
+ }
+
+ private func observeSpaces() {
+ withObservationTracking {
+ _ = store.pagedSpaces(window: ui.windowID).map(\.id)
+ _ = store.focusedSpaceID(window: ui.windowID)
+ } onChange: { [weak self] in
+ Task { @MainActor in self?.observeSpaces() }
+ }
+ needsLayout = true
+ }
+
+ private func swipeChanged() {
+ let swipe = ui.spaceSwipe
+ if swipe == 0 {
+ pendingVelocity = ui.spaceSettleVelocity
+ needsLayout = true
+ return
+ }
+ if placedSwipe == 0 { SpaceListView.endHover(for: ui) }
+ // Under the fingers the strip follows at once, without a layout pass.
+ layer?.removeAnimation(forKey: Self.settleKey)
+ setOffset(-swipe * placedWidth)
+ placedSwipe = swipe
+ }
+
+ private func column(for id: UUID) -> NSView {
+ if let c = columns[id] { return c }
+ let host = SpaceColumnView(spaceID: id, store: store, ui: ui, actions: actions, favicons: favicons)
+ columns[id] = host
+ strip.addSubview(host)
+ return host
+ }
+
+ override func layout() {
+ super.layout()
+ let width = bounds.width, height = bounds.height
+ let ids = store.pagedSpaces(window: ui.windowID).map(\.id)
+ let index = ids.firstIndex(of: store.focusedSpaceID(window: ui.windowID)) ?? 0
+ for (id, c) in columns where !ids.contains(id) {
+ c.removeFromSuperview()
+ columns[id] = nil
+ }
+ // Where the strip shows now, in pages (mid-spring if one runs).
+ let shown = presentedPosition()
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ strip.frame = NSRect(x: -CGFloat(index) * width, y: 0, width: CGFloat(max(1, ids.count)) * width, height: height)
+ for (i, id) in ids.enumerated() {
+ let f = NSRect(x: CGFloat(i) * width, y: 0, width: width, height: height)
+ let c = column(for: id)
+ if c.frame != f { c.frame = f }
+ }
+ CATransaction.commit()
+
+ let swipe = ui.spaceSwipe
+ defer {
+ placedIndex = index
+ placedWidth = width
+ placedSwipe = swipe
+ }
+ if swipe != 0 {
+ // Fingers on the trackpad: follow them exactly.
+ layer?.removeAnimation(forKey: Self.settleKey)
+ setOffset(-swipe * width)
+ } else if index != placedIndex || placedSwipe != 0, let shown, abs(shown - CGFloat(index)) > 0.002, width > 0 {
+ settle(from: -(shown - CGFloat(index)) * width)
+ } else if layer?.animation(forKey: Self.settleKey) == nil {
+ setOffset(0)
+ }
+ }
+
+ private func presentedPosition() -> CGFloat? {
+ guard placedWidth > 0 else { return nil }
+ let tx = (layer?.presentation()?.value(forKeyPath: "sublayerTransform.translation.x") as? CGFloat) ?? offset
+ return CGFloat(placedIndex) - tx / placedWidth
+ }
+
+ private func setOffset(_ x: CGFloat) {
+ offset = x
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ layer?.sublayerTransform = CATransform3DMakeTranslation(x, 0, 0)
+ CATransaction.commit()
+ }
+
+ /// Dia settles pages with a zero-bounce spring that picks up the release speed.
+ private func settle(from x: CGFloat) {
+ let spring = CASpringAnimation(perceptualDuration: 0.4, bounce: 0)
+ spring.keyPath = "sublayerTransform.translation.x"
+ spring.fromValue = x
+ spring.toValue = 0
+ spring.initialVelocity = pendingVelocity
+ spring.duration = spring.settlingDuration
+ pendingVelocity = 0
+ let generation = ui.beginSpaceSettle()
+ ownSettle = generation
+ CATransaction.begin()
+ CATransaction.setCompletionBlock { [weak self] in
+ guard let self else { return }
+ if self.ownSettle == generation { self.ui.endSpaceSettle(generation) }
+ SpaceListView.refreshHover(for: self.ui)
+ }
+ setOffset(0)
+ layer?.add(spring, forKey: Self.settleKey)
+ CATransaction.commit()
+ }
+}
diff --git a/Sources/Cra/UI/Sidebar/LiveFolderViews.swift b/Sources/Cra/UI/Sidebar/LiveFolderViews.swift
index ed07915..fc3b0a3 100644
--- a/Sources/Cra/UI/Sidebar/LiveFolderViews.swift
+++ b/Sources/Cra/UI/Sidebar/LiveFolderViews.swift
@@ -1,9 +1,8 @@
import AppKit
import SwiftUI
-// The parts of a folder row that differ for a live folder (Arc's GitHub "Pull Requests" folder):
-// the GitHub glyph, a refresh button, the folder menu with its filters, and a line inside the
-// folder when it has nothing to show or GitHub can't be read.
+// Shared by the live folder's rows and menu (SidebarRowViews, SidebarMenus): GitHub's mark and
+// the folder's status lines.
/// GitHub's mark (Primer Octicons mark-github, MIT) for the live folder and its tabs (Arc: the
/// GithubFavicon asset and customInfo.iconType "github"). github.com's own favicon is no stand-in:
@@ -17,198 +16,6 @@ enum GitHubMark {
}()
}
-/// The mark on its own: a live folder's tabs (Arc draws GithubFavicon for them).
-struct GitHubMarkIcon: View {
- let palette: SpacePalette
- var size: CGFloat = CraMetrics.favicon
- var color: Color?
- var body: some View {
- Image(nsImage: GitHubMark.image)
- .resizable()
- .interpolation(.high)
- .aspectRatio(contentMode: .fit)
- .foregroundStyle(color ?? (palette.isDark ? Color.white.opacity(0.92) : Color.black.opacity(0.85)))
- .frame(width: size, height: size)
- }
-}
-
-/// Arc's live folder glyph: the folder it draws for any folder, with GitHub's mark on its
-/// front in the outline colour (seen in Arc 1.170, 27 Oct 2026).
-struct LiveFolderIcon: View {
- let palette: SpacePalette
- let style: FolderIconStyle?
- let expanded: Bool
- var body: some View {
- let glyph = palette.folderColors(style)
- ZStack {
- if !expanded {
- Image(systemName: "folder.fill").foregroundStyle(glyph.fill)
- }
- Image(systemName: "folder").foregroundStyle(glyph.tint)
- GitHubMarkIcon(palette: palette, size: 7, color: glyph.tint)
- .offset(y: 1.5)
- }
- .font(.system(size: 15, weight: .regular))
- }
-}
-
-/// Trailing refresh button. It spins while a refresh runs; a failed refresh leaves a warning
-/// in its place until the next one works.
-struct LiveFolderAccessory: View {
- let item: SidebarItem
- let palette: SpacePalette
- let hover: Bool
- private var manager: LiveFolderManager { .shared }
-
- var body: some View {
- let live = item.liveFolder
- let busy = manager.refreshing.contains(item.id)
- if busy {
- ProgressView().controlSize(.mini).frame(width: 26, height: 26)
- } else if let error = live?.lastError {
- // Arc keeps the warning on hover too; here a click tries again.
- SidebarIconButton(symbol: "exclamationmark.triangle", palette: palette, help: "\(LiveFolderText.status(error)). Click to try again.",
- size: 26, iconSize: 13, weight: .regular) {
- manager.refresh(item.id)
- }
- } else if hover {
- SidebarIconButton(symbol: "arrow.clockwise", palette: palette, help: LiveFolderText.refreshHelp(live),
- size: 26, iconSize: 12) {
- manager.refresh(item.id)
- }
- }
- }
-}
-
-/// A line inside the open folder when there are no pull requests to show, or GitHub can't be
-/// read (Arc's live folder cells: "Sign back in to GitHub.", "Login with SSO to unlock this folder").
-struct LiveFolderStatusRow: View {
- let item: SidebarItem
- let depth: Int
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(\.sidebarActions) private var actions
- @State private var hover = false
-
- private var message: (text: String, url: String?)? {
- guard let live = item.liveFolder, item.children.isEmpty else { return nil }
- switch live.lastError {
- case .notSignedIn?: return ("Sign back in to GitHub.", "https://github.com/login")
- case .some: return ("We’re having trouble connecting to GitHub; click here to see your Pull Requests.", "https://github.com/pulls")
- case nil:
- if let org = live.ssoOrganizations.first { return ("Login with SSO to unlock this folder", "https://github.com/orgs/\(org)/sso") }
- if live.lastFetch == nil { return nil }
- return ("Pull requests from you and your team will show up here automatically", nil)
- }
- }
-
- var body: some View {
- if let message {
- Text(message.text)
- .font(.system(size: 12))
- .foregroundStyle(message.url != nil && hover ? palette.textSecondary : palette.textTertiary)
- .lineLimit(3)
- .fixedSize(horizontal: false, vertical: true)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(.leading, 8 + CGFloat(depth) * CraMetrics.indent + CraMetrics.favicon + 11)
- .padding(.trailing, 10)
- .padding(.vertical, 8)
- .background(RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)
- .fill(message.url != nil && hover ? palette.hoverFill : .clear))
- .contentShape(Rectangle())
- .onHover { hover = $0 }
- .onTapGesture { if let url = message.url { actions.openURL(url) } }
- }
- }
-}
-
-/// The live folder's context menu (Arc: SidebarMenu+ListContextMenu liveFolderContextMenu).
-struct LiveFolderMenu: View {
- let item: SidebarItem
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- private var manager: LiveFolderManager { .shared }
-
- var body: some View {
- let live = item.liveFolder ?? LiveFolderData()
- Text(manager.refreshing.contains(item.id) ? "Updating…" : LiveFolderText.lastUpdate(live))
- Button("Refresh") { manager.refresh(item.id) }
- Divider()
- filterToggle("My Pull Requests", .authored, live)
- filterToggle("Review Requests", .reviewRequests, live)
- filterToggle("Team Review Requests", .teamReviewRequests, live)
- let repos = manager.repositories[item.id] ?? live.filter.hiddenRepositories
- if !repos.isEmpty {
- Menu("Repositories") {
- Text("This list is generated based on your currently active pull requests.")
- Divider()
- ForEach(repos, id: \.self) { repo in
- Toggle(repo, isOn: Binding(
- get: { !live.filter.hiddenRepositories.contains(repo) },
- set: { on in
- store.updateLiveFolder(item.id) { l in
- l.filter.hiddenRepositories.removeAll { $0 == repo }
- if !on { l.filter.hiddenRepositories.append(repo) }
- }
- manager.refresh(item.id, force: true)
- }))
- }
- }
- }
- if !live.ssoOrganizations.isEmpty {
- Divider()
- Text("SSO ensures all of your organizations’ PRs appear")
- ForEach(live.ssoOrganizations, id: \.self) { org in
- Button("Sign In to \(org) with SSO…") { actions.openURL("https://github.com/orgs/\(org)/sso") }
- }
- }
- Divider()
- Button("Rename…") { ui.renamingID = item.id }
- Picker("Icon Color", selection: Binding(get: { item.folderIcon }, set: { store.setFolderIcon($0, for: item.id) })) {
- Text("Auto").tag(FolderIconStyle?.none)
- Text("White").tag(FolderIconStyle?.some(.white))
- Text("Black").tag(FolderIconStyle?.some(.black))
- }
- Button("Copy All Links as Markdown") {
- let lines = store.children(of: item.id).compactMap { c in c.tab.map { "- [\(c.displayTitle)](\($0.liveItemURL ?? $0.url))" } }
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(lines.joined(separator: "\n"), forType: .string)
- }
- .disabled(item.children.isEmpty)
- Divider()
- Button("Delete Live Folder") { confirmDelete() }
- }
-
- private func filterToggle(_ title: String, _ attribute: GitHubLiveFilter.Attributes, _ live: LiveFolderData) -> some View {
- Toggle(title, isOn: Binding(
- get: { live.filter.attributes.contains(attribute) },
- set: { on in
- store.updateLiveFolder(item.id) { l in
- if on { l.filter.attributes.insert(attribute) } else { l.filter.attributes.remove(attribute) }
- }
- manager.refresh(item.id, force: true)
- }))
- }
-
- /// Arc asks first ("Delete your %@ Live Folder?") and says how to get it back.
- private func confirmDelete() {
- let alert = NSAlert()
- alert.messageText = "Delete your \(item.title ?? "Pull Requests") Live Folder?"
- alert.informativeText = "You can add it again with New GitHub Live Folder in the sidebar’s menu or the command bar."
- alert.addButton(withTitle: "Delete")
- alert.addButton(withTitle: "Cancel")
- alert.buttons.first?.hasDestructiveAction = true
- let id = item.id
- let delete = { withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.deleteFolder(id) } }
- if let window = NSApp.keyWindow {
- alert.beginSheetModal(for: window) { if $0 == .alertFirstButtonReturn { delete() } }
- } else if alert.runModal() == .alertFirstButtonReturn {
- delete()
- }
- }
-}
-
enum LiveFolderText {
private static let relative: RelativeDateTimeFormatter = {
let f = RelativeDateTimeFormatter()
@@ -228,6 +35,17 @@ enum LiveFolderText {
return "Refresh · \(lastUpdate(live))"
}
+ /// The folder's warning button: Arc's tip, and where a click signs in (nil: it tries again).
+ static func warning(_ live: LiveFolderData) -> (help: String, signInURL: String?)? {
+ switch live.lastError {
+ case .notSignedIn?: return ("Sign back in to GitHub.", live.signInURL)
+ case let error?: return ("\(status(error)). Click to try again.", nil)
+ case nil:
+ guard let org = live.ssoOrganizations.first else { return nil }
+ return ("Login with SSO to unlock this folder", "https://github.com/orgs/\(org)/sso")
+ }
+ }
+
static func status(_ error: LiveFolderError) -> String {
switch error {
case .notSignedIn: return "Not signed in to GitHub"
diff --git a/Sources/Cra/UI/Sidebar/SidebarItemView.swift b/Sources/Cra/UI/Sidebar/SidebarItemView.swift
index 41f2363..ea9ac48 100644
--- a/Sources/Cra/UI/Sidebar/SidebarItemView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarItemView.swift
@@ -2,32 +2,6 @@ import SwiftUI
enum SidebarSection { case favorites, pinned, today }
-/// A tab or a folder (with its children when expanded).
-struct SidebarItemView: View {
- let item: SidebarItem
- let depth: Int
- let palette: SpacePalette
- let section: SidebarSection
- @Environment(SidebarStore.self) private var store
-
- var body: some View {
- if item.isFolder {
- FolderRow(item: item, depth: depth, palette: palette)
- if store.isExpanded(item.id) {
- ForEach(store.children(of: item.id)) { child in
- SidebarItemView(item: child, depth: depth + 1, palette: palette, section: section)
- .transition(.asymmetric(insertion: .opacity.combined(with: .offset(y: -6)), removal: .opacity))
- }
- if item.isLiveFolder { LiveFolderStatusRow(item: item, depth: depth + 1, palette: palette) }
- }
- } else if item.isTab {
- TabRow(item: item, depth: depth, palette: palette, section: section)
- } else if item.isSplit {
- SplitRow(item: item, depth: depth, palette: palette, section: section)
- }
- }
-}
-
struct FaviconView: View {
let key: String?
let palette: SpacePalette
@@ -57,378 +31,3 @@ struct FaviconView: View {
}
}
}
-
-struct TabRow: View {
- let item: SidebarItem
- let depth: Int
- let palette: SpacePalette
- let section: SidebarSection
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var hover = false
- @State private var draft = ""
- @FocusState private var renameFocused: Bool
- @AppStorage("didShowRenameHint") private var didShowRenameHint = false
-
- private var tab: TabData { item.tab! }
- private var selected: Bool { store.isSelected(item.id, window: ui.windowID) }
- /// While tabs are ⌘/⇧-picked the highlight follows the picks, not the open tab.
- private var highlighted: Bool { ui.multiSelection.isEmpty ? selected : ui.multiSelection.contains(item.id) }
- /// Close acts on every picked tab when this row is one of them.
- private var closeGroup: [UUID] { ui.multiSelection.contains(item.id) && ui.multiSelection.count > 1 ? Array(ui.multiSelection) : [item.id] }
- private var editing: Bool { ui.renamingID == item.id }
- private var loaded: Bool { ui.loadedTabIDs.contains(item.id) }
- private var pinned: Bool { section != .today }
- private var navigatedAway: Bool { pinned && tab.url != tab.savedURL && !tab.savedURL.isEmpty }
- /// Arc shows the host under a pinned tab only when it has left the pinned
- /// site (navigating within the same host shows nothing).
- private var subtitle: String? {
- // A live folder's pull request shows its author (Arc's sidebarItemSubtitleTextField, mine too).
- if let author = tab.liveSubtitle, URL(string: tab.url)?.host == "github.com" { return author }
- guard navigatedAway, let host = URL(string: tab.url)?.host, let saved = URL(string: tab.savedURL)?.host,
- host.replacingOccurrences(of: "www.", with: "") != saved.replacingOccurrences(of: "www.", with: "") else { return nil }
- return host.replacingOccurrences(of: "www.", with: "")
- }
-
- var body: some View {
- let session = ui
- HStack(spacing: 11) {
- Group {
- if tab.liveItemURL != nil && tab.customIconKey == nil {
- GitHubMarkIcon(palette: palette)
- } else {
- FaviconView(key: tab.iconKey, palette: palette)
- }
- }
- .frame(width: CraMetrics.favicon)
- if editing {
- TextField("", text: $draft)
- .textFieldStyle(.plain)
- .font(.system(size: 14))
- .focused($renameFocused)
- .onSubmit { commitRename() }
- .onExitCommand { ui.renamingID = nil }
- .onAppear { draft = item.title ?? item.displayTitle; renameFocused = true }
- .onChange(of: renameFocused) { _, f in if !f && editing { commitRename() } }
- } else {
- VStack(alignment: .leading, spacing: 1) {
- Text(item.displayTitle)
- .font(.system(size: 14))
- .foregroundStyle(palette.textPrimary)
- .lineLimit(1)
- .truncationMode(.tail)
- if let subtitle {
- Text(subtitle).font(.system(size: 11)).foregroundStyle(palette.textTertiary).lineLimit(1)
- }
- }
- }
- Spacer(minLength: 4)
- if ui.capturingTabIDs.contains(item.id) {
- // Arc's recording indicator; a red dot by the title, with Arc's tooltip.
- Circle().fill(Color.red).frame(width: 7, height: 7)
- .frame(width: 16, height: 16)
- .contentShape(Rectangle())
- .arcTooltip("This tab is using your camera or microphone")
- }
- if tab.muted {
- SidebarIconButton(symbol: "speaker.slash.fill", palette: palette, help: "Unmute Tab", size: 20, iconSize: 10) {
- store.setMuted(item.id, false)
- actions.performAction("muteTab:\(item.id)")
- }
- }
- if item.isUnread && !selected && !hover {
- Circle().fill(palette.textPrimary.opacity(0.55)).frame(width: 6, height: 6)
- }
- if hover && !editing {
- if navigatedAway {
- SidebarIconButton(symbol: "arrow.uturn.backward", palette: palette, help: "Back to pinned page", size: 22) {
- actions.resetPinnedTab(item.id)
- }
- }
- if closeGroup.count > 1 {
- SidebarIconButton(symbol: "xmark", palette: palette, help: "Close \(closeGroup.count) Tabs (⌘W)", size: 22) {
- closeTabs(closeGroup)
- }
- } else if pinned && selected {
- // Arc: the open pinned tab shows a minus; it unloads and stays pinned.
- SidebarIconButton(symbol: "minus", palette: palette, help: "Close and Keep Pinned (⌘W)", size: 22) {
- closeTabs([item.id])
- }
- } else if pinned {
- // Arc: any other pinned tab shows ✕, which archives it out of the pinned section.
- SidebarIconButton(symbol: "xmark", palette: palette, help: "Archive this tab", size: 22) {
- withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.archiveTab(item.id, reason: .manual) }
- }
- } else {
- SidebarIconButton(symbol: "xmark", palette: palette, help: "Archive (⌘W)", size: 22) {
- closeTabs(closeGroup)
- }
- }
- }
- }
- .padding(.leading, 8 + CGFloat(depth) * CraMetrics.indent)
- .padding(.trailing, 6)
- .frame(height: CraMetrics.rowHeight)
- .background(
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)
- .fill(highlighted ? palette.selectedFill : (hover ? palette.hoverFill : .clear))
- .shadow(color: highlighted && !palette.isDark ? .black.opacity(0.06) : .clear, radius: 3, y: 1)
- )
- .overlay { if ui.keyboardFocusID == item.id { FocusRing(radius: CraMetrics.rowCorner) } }
- .contentShape(Rectangle())
- .onHover { inside in
- hover = inside
- ui.hoverDraggable(item.id, inside)
- if inside { ui.hoveredTabID = item.id } else if ui.hoveredTabID == item.id { ui.hoveredTabID = nil }
- }
- .onTapGesture {
- let event = NSApp.currentEvent
- let flags = event?.modifierFlags.intersection([.command, .shift]) ?? []
- if !flags.isEmpty {
- ui.pick(item.id, range: flags.contains(.shift), in: store)
- } else if event?.clickCount == 2 {
- ui.renamingID = item.id
- } else {
- // A click on the row (not the field) ends a rename, so it can never get stuck.
- if editing { commitRename() }
- ui.clearPicks(anchor: item.id)
- ui.keyboardFocusID = nil
- store.selectTab(item.id, window: ui.windowID)
- }
- }
- .draggable(SidebarDragItem.begin(item.id, session)) {
- // Dragging one of several picked tabs moves them all.
- HStack(spacing: 8) {
- FaviconView(key: tab.iconKey, palette: palette)
- Text(item.displayTitle).font(.system(size: 14)).lineLimit(1)
- if closeGroup.count > 1 {
- Text("\(closeGroup.count)")
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(.white)
- .padding(.horizontal, 6)
- .frame(minWidth: 18, minHeight: 18)
- .background(Capsule().fill(Color.accentColor))
- }
- }
- .padding(8)
- .background(RoundedRectangle(cornerRadius: 8).fill(.regularMaterial))
- }
- .contextMenu { TabRowMenu(item: item, pinned: pinned, navigatedAway: navigatedAway, closeGroup: closeGroup, close: closeTabs) }
- // Arc's row tip is the tab's title by the pointer; the close buttons' own tips win over it.
- // Like Arc (didShowRenameHint), "Double-click to rename" rides along once.
- .arcTooltip(editing ? "" : item.displayTitle, followsCursor: true,
- subtitle: didShowRenameHint || item.title != nil ? nil : "Double-click to rename",
- onShow: { if !didShowRenameHint && item.title == nil { didShowRenameHint = true } })
- .modifier(SidebarDropPreview(id: item.id, palette: palette, depth: depth))
- }
-
- private func commitRename() {
- guard editing else { return }
- store.rename(item.id, to: draft)
- ui.renamingID = nil
- }
-
- private func closeTabs(_ ids: [UUID]) {
- // The open tab goes last so closing it doesn't hop through tabs about to close.
- let open = store.selectedTabID(window: ui.windowID)
- let ordered = ids.filter { $0 != open } + ids.filter { $0 == open }
- withAnimation(.snappy(duration: 0.22, extraBounce: 0)) {
- for id in ordered { actions.closeTab(id) }
- ui.multiSelection.subtract(ids)
- }
- }
-}
-
-/// A tab row's context menu. Its own view: what it reads from the store (folders, spaces,
-/// favorites) would otherwise make every row's body depend on all of it, and every row
-/// re-rendered on each store change (a tab switch, a page title).
-private struct TabRowMenu: View {
- let item: SidebarItem
- let pinned: Bool
- let navigatedAway: Bool
- let closeGroup: [UUID]
- let close: ([UUID]) -> Void
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
-
- private var tab: TabData { item.tab! }
-
- var body: some View {
- if closeGroup.count > 1 {
- folderMenu(ui.group(for: item.id, in: store))
- Divider()
- Button("Close \(closeGroup.count) Tabs") { close(closeGroup) }
- Button("Deselect All") { ui.clearPicks() }
- } else {
- singleTabMenu
- }
- }
-
- /// Move to Folder / New Folder for this tab, or for every picked tab.
- @ViewBuilder
- private func folderMenu(_ ids: [UUID]) -> some View {
- let folders = store.children(of: store.focusedSpace(window: ui.windowID).pinnedContainerID).filter { $0.isFolder && !$0.isLiveFolder }
- if !folders.isEmpty {
- Menu(ids.count > 1 ? "Move \(ids.count) Tabs to Folder" : "Move to Folder") {
- ForEach(folders) { f in
- Button(f.title ?? "Folder") {
- withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.moveItems(ids, to: f.id, index: nil) }
- }
- .disabled(ids.allSatisfy { store.item($0)?.parentID == f.id })
- }
- }
- }
- Button(ids.count > 1 ? "New Folder with \(ids.count) Tabs" : "New Folder with Tab") {
- withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { ui.renamingID = store.createFolder(with: ids).id }
- }
- }
-
- @ViewBuilder
- private var singleTabMenu: some View {
- if pinned {
- Button("Unpin Tab") { store.unpinTab(item.id) }
- } else {
- Button("Pin Tab") { store.pinTab(item.id) }
- }
- if store.isFavorite(item.id) {
- Button("Remove from Favorites") { store.removeFromFavorites(item.id) }
- } else {
- Button("Add to Favorites") { store.addToFavorites(item.id) }
- }
- Divider()
- Button("Rename…") { ui.renamingID = item.id }
- if item.title != nil { Button("Use Page Title") { store.rename(item.id, to: nil) } }
- Button("Duplicate") { store.duplicateTab(item.id) }
- Button("Copy Link") {
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(tab.url, forType: .string)
- }
- Button(tab.muted ? "Unmute" : "Mute") { store.setMuted(item.id, !tab.muted); actions.performAction("muteTab:\(item.id)") }
- if pinned {
- Divider()
- if navigatedAway { Button("Back to Pinned Page") { actions.resetPinnedTab(item.id) } }
- Button("Make This the Pinned Page") { store.setPinnedHomeToCurrent(item.id) }
- }
- Divider()
- Menu("Move to Space") {
- ForEach(store.orderedSpaces) { s in
- Button("\(s.emoji) \(s.title)") { store.moveTab(item.id, toSpace: s.id) }
- .disabled(s.id == store.spaceID(ofItem: item.id))
- }
- }
- folderMenu([item.id])
- Divider()
- if pinned {
- if store.isSelected(item.id, window: ui.windowID) || ui.loadedTabIDs.contains(item.id) {
- Button("Close and Keep Pinned") { actions.closeTab(item.id) }
- }
- Button("Archive Tab") { store.archiveTab(item.id, reason: .manual) }
- } else {
- Button("Archive") { actions.closeTab(item.id) }
- }
- }
-}
-
-struct FolderRow: View {
- let item: SidebarItem
- let depth: Int
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @State private var hover = false
- @State private var draft = ""
- @FocusState private var renameFocused: Bool
-
- private var expanded: Bool { store.isExpanded(item.id) }
- private var editing: Bool { ui.renamingID == item.id }
-
- var body: some View {
- let session = ui
- let glyph = palette.folderColors(item.folderIcon)
- HStack(spacing: 11) {
- if item.isLiveFolder {
- LiveFolderIcon(palette: palette, style: item.folderIcon, expanded: expanded).frame(width: CraMetrics.favicon)
- } else {
- ZStack {
- if !expanded {
- Image(systemName: "folder.fill").foregroundStyle(glyph.fill)
- }
- Image(systemName: "folder").foregroundStyle(glyph.tint)
- }
- .font(.system(size: 15, weight: .regular))
- .frame(width: CraMetrics.favicon)
- }
- if editing {
- TextField("", text: $draft)
- .textFieldStyle(.plain)
- .font(.system(size: 14, weight: .medium))
- .focused($renameFocused)
- .onSubmit { commitRename() }
- .onExitCommand { ui.renamingID = nil }
- .onAppear { draft = item.title ?? ""; renameFocused = true }
- .onChange(of: renameFocused) { _, f in if !f && editing { commitRename() } }
- } else {
- Text(item.title ?? "Folder")
- .font(.system(size: 14, weight: .medium))
- .lineLimit(1)
- }
- Spacer()
- if item.isLiveFolder {
- LiveFolderAccessory(item: item, palette: palette, hover: hover && !editing)
- .padding(.trailing, 7)
- } else if hover && !expanded {
- Text("\(store.tabs(under: item.id).count)")
- .font(.system(size: 11, weight: .medium))
- .foregroundStyle(palette.textTertiary)
- .padding(.trailing, 8)
- }
- }
- .padding(.leading, 8 + CGFloat(depth) * CraMetrics.indent)
- .frame(height: CraMetrics.rowHeight)
- .background(RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous).fill(hover ? palette.hoverFill : .clear))
- .contentShape(Rectangle())
- .onHover { hover = $0; ui.hoverDraggable(item.id, $0) }
- // Every click toggles, however fast they come: double-click-to-rename made
- // quick open/close clicks start a rename that then swallowed the clicks.
- // Rename stays in the context menu. No count: 2 gesture either: it makes
- // SwiftUI hold every single click for the double-click interval.
- .onTapGesture {
- if editing { commitRename() }
- withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.setExpanded(item.id, !expanded) }
- }
- .draggable(SidebarDragItem.begin(item.id, session))
- .contextMenu {
- if item.isLiveFolder {
- LiveFolderMenu(item: item)
- } else {
- folderMenu
- }
- }
- .modifier(SidebarDropPreview(id: item.id, palette: palette))
- }
-
- @ViewBuilder
- private var folderMenu: some View {
- Button("Rename…") { ui.renamingID = item.id }
- Button("New Folder Inside") {
- let f = store.createFolder(named: "New Folder", in: item.id, index: 0)
- store.setExpanded(item.id, true)
- ui.renamingID = f.id
- }
- Picker("Icon Color", selection: Binding(get: { item.folderIcon }, set: { store.setFolderIcon($0, for: item.id) })) {
- Text("Auto").tag(FolderIconStyle?.none)
- Text("White").tag(FolderIconStyle?.some(.white))
- Text("Black").tag(FolderIconStyle?.some(.black))
- }
- Divider()
- Button("Delete Folder (archives tabs)") { store.deleteFolder(item.id) }
- }
-
- private func commitRename() {
- guard editing else { return }
- store.rename(item.id, to: draft.isEmpty ? "Folder" : draft)
- ui.renamingID = nil
- }
-}
diff --git a/Sources/Cra/UI/Sidebar/SidebarListDrop.swift b/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
index 179c1f5..3e0ce8b 100644
--- a/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
@@ -1,9 +1,8 @@
import AppKit
-import SwiftUI
/// What releasing a sidebar drag over the space's list would do right now. The
/// rows read it to draw the live preview (insertion line, rows easing apart,
-/// the row a drop would combine with) and the delegate applies it on drop.
+/// the row a drop would combine with) and SpaceListView applies it on drop.
struct SidebarListDrop: Equatable {
enum Target: Equatable {
/// Before the child at `index` of `parent` (`index == count` appends).
@@ -33,16 +32,15 @@ struct SidebarListDrop: Equatable {
var rowBelow: UUID?
}
-/// Scrolls a space's list while a drag hovers near its top or bottom edge.
-/// SwiftUI's ScrollView has no autoscroll for custom drops, so with a long
-/// pinned list everything past the fold (Today included) was out of reach.
+/// Scrolls a space's list while a drag hovers near its top or bottom edge, so
+/// with a long pinned list everything past the fold (Today included) stays in reach.
@MainActor
final class DragAutoscroller {
/// Edge band, and the speed at the very edge in points per second.
static let band: CGFloat = 48
static let maxSpeed: CGFloat = 900
- fileprivate weak var anchor: NSView?
+ weak var anchor: NSView?
private var timer: Timer?
private var lastTick: CFTimeInterval = 0
@@ -89,446 +87,215 @@ final class DragAutoscroller {
clip.scroll(to: r.origin)
sv.reflectScrolledClipView(clip)
}
-
- /// Placed inside the list so the scroller can find the scroll view around it.
- struct Anchor: NSViewRepresentable {
- let scroller: DragAutoscroller
- func makeNSView(context: Context) -> NSView { PassThroughView() }
- func updateNSView(_ view: NSView, context: Context) { scroller.anchor = view }
- }
-
- private final class PassThroughView: NSView {
- override func hitTest(_ point: NSPoint) -> NSView? { nil }
- }
}
-/// One drop delegate for the whole pinned + today list. Per-row drop
-/// destinations only report entered/exited, so the list hit-tests the pointer
-/// against the rows' frames itself on every move.
-struct SidebarListDropDelegate: DropDelegate {
- static let coordinateSpace = "sidebarList"
- static let nudge: CGFloat = 3
- static let animation = Animation.snappy(duration: 0.2, extraBounce: 0)
-
- let space: Space
- let store: SidebarStore
- let ui: SidebarUIState
- let autoscroller: DragAutoscroller
-
- func validateDrop(info: DropInfo) -> Bool { info.hasItemsConforming(to: [.craSidebarItem]) }
-
- func dropEntered(info: DropInfo) {
- // Rows here set draggingID when the drag starts; a drag from another
- // window only says what it carries through the pasteboard.
- if let provider = info.itemProviders(for: [.craSidebarItem]).first {
- _ = provider.loadTransferable(type: SidebarDragItem.self) { [ui] result in
- guard case .success(let d) = result else { return }
- DispatchQueue.main.async { ui.draggingID = d.id }
- }
- }
- update(info)
- }
-
- func dropUpdated(info: DropInfo) -> DropProposal? {
- update(info)
- return DropProposal(operation: .move)
- }
-
- func dropExited(info: DropInfo) {
- autoscroller.stop()
- withAnimation(Self.animation) { ui.listDrop = nil }
- }
-
- func performDrop(info: DropInfo) -> Bool {
- autoscroller.stop()
- guard let id = ui.draggingID, store.item(id) != nil else { return false }
- let drop = ui.listDrop ?? resolve(dragged: id, at: info.location)
- withAnimation(Self.animation) {
- ui.listDrop = nil
- apply(drop)
- }
- // Dia: Tabs ▸ "Haptic feedback when reordering tabs".
- if drop.target != nil, store.settings.hapticFeedbackOnReorder {
- NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .drawCompleted)
- }
- ui.draggingID = nil
- return true
- }
-
- private func update(_ info: DropInfo) {
- autoscroller.update()
- guard let id = ui.draggingID, store.item(id) != nil else { return }
- let drop = resolve(dragged: id, at: info.location)
- guard drop != ui.listDrop else { return }
- withAnimation(Self.animation) { ui.listDrop = drop }
- // A tick when a row starts offering to combine, so the change of meaning is felt as well as seen.
- switch drop.target {
- case .split?, .newFolder?:
- if store.settings.hapticFeedbackOnReorder {
- NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now)
- }
- default: break
- }
- // Spring-loaded folders: hovering a closed folder opens it.
- if case .into(let f)? = drop.target, store.item(f)?.isFolder == true, !store.isExpanded(f) {
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [ui, store] in
- guard ui.listDrop?.target == .into(f) else { return }
- withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.setExpanded(f, true) }
- }
- }
- }
+/// A tab row while another tab hovers over its middle, drawn as the row the
+/// drop makes: in Today the row splits open and the dragged tab slides into a
+/// dashed pane on the side it will take (the split row's own layout), moving
+/// across when the pointer crosses the row's middle; in Pinned it becomes a
+/// "New Folder" row with both tabs' icons dropping into a stack.
+/// What dropping a row onto another would make, drawn over the target row: a split with the
+/// dragged tab sliding in beside it under a dashed outline, or a new folder with both icons.
+@MainActor
+final class CombineDropPreview: NSView {
+ enum Kind: Equatable { case split(leading: Bool), folder }
- private func apply(_ drop: SidebarListDrop) {
- let id = drop.draggedID
- // A picked tab carries the other picks along (a split still takes one pane).
- let group = ui.group(for: id, in: store)
- switch drop.target {
- case .insert(let parent, let index)?:
- store.moveItems(group, to: parent, index: index)
- case .newFolder(let tab)?:
- if let folder = store.createFolder(combining: tab, with: group) { ui.renamingID = folder.id }
- case .split(let tab, let leading)?:
- store.createSplit(with: leading ? [id, tab] : [tab, id], at: tab)
- case .into(let target)?:
- if store.item(target)?.isFolder == true {
- store.moveItems(group, to: target, index: nil)
- store.setExpanded(target, true)
- } else {
- store.moveItem(id, to: target, index: nil)
- }
- case nil:
- break
+ private let kind: Kind
+ private let target: SidebarItem
+ private let dragged: SidebarItem
+ private let depth: Int
+ private let palette: SpacePalette
+ private let colors: SidebarColors
+ private let favicons: FaviconCache
+ private let card = NSView()
+ private var didOpen = false
+
+ init(kind: Kind, target: SidebarItem, dragged: SidebarItem, depth: Int, palette: SpacePalette, favicons: FaviconCache) {
+ self.kind = kind
+ self.target = target
+ self.dragged = dragged
+ self.depth = depth
+ self.palette = palette
+ colors = SidebarColors(palette)
+ self.favicons = favicons
+ super.init(frame: .zero)
+ wantsLayer = true
+ card.wantsLayer = true
+ if let l = card.layer {
+ l.cornerRadius = CraMetrics.rowCorner
+ l.cornerCurve = .continuous
+ l.backgroundColor = colors.selectedFill.cgColor
+ l.borderWidth = 1.5
+ l.shadowColor = NSColor.black.cgColor
+ l.shadowOpacity = palette.isDark ? 0.25 : 0.1
}
+ addSubview(card)
}
- // MARK: Hit testing
+ required init?(coder: NSCoder) { fatalError() }
- private struct Row {
- let item: SidebarItem
- let parent: UUID
- let index: Int
- let depth: Int
- let frame: CGRect
- }
-
- /// Rows as drawn: pinned (expanded folders open), then today. Frames stay
- /// recorded for rows that are no longer drawn (a collapsed pinned list),
- /// so only drawn rows may be hit.
- private func visibleRows() -> [Row] {
- var out: [Row] = []
- func walk(_ rows: [SidebarItem], _ depth: Int) {
- for c in rows {
- guard let f = ui.rowFrames[c.id], let parent = c.parentID,
- let i = store.item(parent)?.children.firstIndex(of: c.id) else { continue }
- out.append(Row(item: c, parent: parent, index: i, depth: depth, frame: f))
- if c.isFolder, store.isExpanded(c.id) { walk(store.children(of: c.id), depth + 1) }
- }
- }
- walk(store.listedPinnedItems(in: space, window: ui.windowID), 0)
- walk(store.children(of: space.todayContainerID), 0)
- return out
- }
+ override var isFlipped: Bool { true }
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
- private func isInside(_ id: UUID, _ ancestor: UUID) -> Bool {
- var cur = store.item(id)?.parentID
- var hops = 0
- while let c = cur, hops < 64 {
- if c == ancestor { return true }
- cur = store.item(c)?.parentID
- hops += 1
- }
- return false
+ /// `withAnimation(.spring(duration: 0.34, bounce: 0.22)) { open = true }` on appear.
+ private static func spring(_ layer: CALayer?, _ key: String, from: Any, to: Any) {
+ let a = CASpringAnimation(perceptualDuration: 0.34, bounce: 0.22)
+ a.keyPath = key
+ a.fromValue = from
+ a.toValue = to
+ a.duration = a.settlingDuration
+ layer?.add(a, forKey: key)
}
- /// Top and bottom quarters of a row insert before/after it; the middle
- /// combines: a folder takes the item, a Today tab makes a split (the
- /// dragged tab goes on the side of the row it hovers), a pinned tab makes
- /// a new folder, a split row takes a pane.
- func resolve(dragged id: UUID, at p: CGPoint) -> SidebarListDrop {
- let rows = visibleRows()
- let group = ui.group(for: id, in: store)
- let isTab = store.item(id)?.isTab == true
- let half = CraMetrics.rowSpacing / 2
- var target: SidebarListDrop.Target?
-
- if let r = rows.first(where: { p.y >= $0.frame.minY - half && p.y < $0.frame.maxY + half }) {
- let f = (p.y - r.frame.minY) / max(1, r.frame.height)
- let middle = (0.25..<0.75).contains(f)
- let before = SidebarListDrop.Target.insert(parent: r.parent, index: r.index)
- let after = SidebarListDrop.Target.insert(parent: r.parent, index: r.index + 1)
- if group.contains(r.item.id) || isInside(r.item.id, id) {
- target = nil
- } else if r.item.isFolder {
- if f < 0.25 { target = before }
- else if f >= 0.75 { target = store.isExpanded(r.item.id) ? .insert(parent: r.item.id, index: 0) : after }
- else { target = .into(r.item.id) }
- } else if middle && isTab && r.item.isTab {
- target = isInside(r.item.id, space.todayContainerID)
- ? .split(with: r.item.id, leading: p.x < r.frame.midX)
- : .newFolder(with: r.item.id)
- } else if middle && isTab && r.item.isSplit {
- target = .into(r.item.id)
- } else {
- target = f < 0.5 ? before : after
- }
- } else {
- // Between sections or past the last row: the divider splits pinned from today.
- let pinned = ui.rowFrames[space.pinnedContainerID] ?? .zero
- let today = ui.rowFrames[space.todayContainerID] ?? .zero
- if p.y < (pinned.maxY + today.minY) / 2 {
- target = .insert(parent: space.pinnedContainerID, index: p.y < pinned.minY ? 0 : store.children(of: space.pinnedContainerID).count)
- } else {
- // The New Tab row may lead Today, so its first tab, not the section, marks the top.
- let firstToday = rows.first { $0.parent == space.todayContainerID }?.frame.minY ?? today.minY
- target = .insert(parent: space.todayContainerID, index: p.y < firstToday ? 0 : store.children(of: space.todayContainerID).count)
- }
- }
-
- // Dropping next to itself, or a folder into itself, changes nothing.
- if case .insert(let parent, let index)? = target {
- if parent == id || isInside(parent, id) {
- target = nil
- } else if group.count == 1, store.item(id)?.parentID == parent, let old = store.item(parent)?.children.firstIndex(of: id), index == old || index == old + 1 {
- target = nil
- }
- }
-
- // A live folder fills itself: nothing goes into it from outside, and its tabs make no new folders.
- switch target {
- case .into(let f)? where store.item(f)?.isLiveFolder == true: target = nil
- case .insert(let parent, _)? where store.item(parent)?.isLiveFolder == true && store.item(id)?.parentID != parent: target = nil
- case .newFolder(let tab)? where store.item(store.item(tab)?.parentID ?? tab)?.isLiveFolder == true: target = nil
- default: break
- }
-
- var drop = SidebarListDrop(draggedID: id, target: target)
- guard case .insert(let parent, let index)? = target else { return drop }
- let kids = store.item(parent)?.children ?? []
- var y: CGFloat?
- if index < kids.count, let f = rows.first(where: { $0.item.id == kids[index] })?.frame {
- y = f.minY - half
- } else if index > 0, let r = rows.last(where: { $0.item.id == kids[index - 1] || isInside($0.item.id, kids[index - 1]) }) {
- y = r.frame.maxY + half
- } else if store.item(parent)?.isFolder == true, let f = ui.rowFrames[parent] {
- y = f.maxY + half
+ override func layout() {
+ super.layout()
+ guard !didOpen, bounds.width > 0 else { return }
+ didOpen = true
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ card.frame = bounds
+ if let l = card.layer {
+ l.borderColor = colors.textPrimary.withAlphaComponent(0.35).cgColor
+ l.shadowRadius = 6
+ l.shadowOffset = CGSize(width: 0, height: -2)
+ Self.spring(l, "borderColor", from: colors.textPrimary.withAlphaComponent(0).cgColor, to: l.borderColor!)
+ Self.spring(l, "shadowRadius", from: 2.0, to: 6.0)
+ Self.spring(l, "shadowOffset", from: CGSize(width: 0, height: -1), to: l.shadowOffset)
+ // .scaleEffect(0.97 → 1), from the card's centre.
+ let small = bounds.insetBy(dx: bounds.width * 0.015, dy: bounds.height * 0.015)
+ Self.spring(l, "bounds.size", from: small.size, to: bounds.size)
+ Self.spring(l, "position", from: CGPoint(x: small.minX, y: small.minY), to: l.position)
}
- // An empty pinned list shows its own placeholder instead of a line.
- guard let y, let section = ui.rowFrames[space.todayContainerID] else { return drop }
- let depth = rows.first { $0.item.id == parent }.map { $0.depth + 1 } ?? 0
- drop.line = .init(y: y, minX: section.minX + 8 + CGFloat(depth) * CraMetrics.indent, maxX: section.maxX - 6)
- drop.rowAbove = rows.last { $0.frame.maxY <= y + 1 }?.item.id
- drop.rowBelow = rows.first { $0.frame.minY >= y - 1 }?.item.id
- return drop
- }
-}
-
-/// Registers a row's frame for the list's drop delegate and draws the live
-/// drop preview on it: the dragged row dims, the rows either side of the
-/// insertion line ease apart, a tab the drop would combine with turns into
-/// what it becomes (a split row or a folder), and a folder or split that
-/// would take the item lights up with a label.
-struct SidebarDropPreview: ViewModifier {
- let id: UUID
- let palette: SpacePalette
- var depth = 0
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
-
- func body(content: Content) -> some View {
- let drop = ui.listDrop
- let nudge: CGFloat = drop?.rowAbove == id ? -SidebarListDropDelegate.nudge : (drop?.rowBelow == id ? SidebarListDropDelegate.nudge : 0)
- let badge = badge(for: drop?.target)
- let combine = combine(for: drop)
- content
- .background {
- if badge != nil {
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)
- .fill(palette.selectedFill)
- .transition(.opacity)
- }
- }
- .overlay {
- if let badge {
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)
- .strokeBorder(palette.textPrimary.opacity(0.3), lineWidth: 1.5)
- .overlay(alignment: .trailing) {
- HStack(spacing: 4) {
- Image(systemName: badge.symbol).font(.system(size: 10, weight: .semibold))
- Text(badge.label).font(.system(size: 11, weight: .semibold))
- }
- .foregroundStyle(palette.textPrimary)
- .padding(.horizontal, 8)
- .frame(height: 22)
- .background(Capsule().fill(palette.isDark ? Color.white.opacity(0.14) : Color.white.opacity(0.9)))
- .shadow(color: .black.opacity(0.08), radius: 2, y: 1)
- .padding(.trailing, 8)
- }
- .transition(.scale(scale: 0.96).combined(with: .opacity))
- .allowsHitTesting(false)
- }
- }
- .opacity(combine != nil ? 0 : (drop.map { isDragged($0.draggedID) } ?? false ? 0.4 : 1))
- .overlay {
- if let combine, let target = store.item(id), let dragged = store.item(combine.dragged) {
- CombineDropPreview(kind: combine.kind, target: target, dragged: dragged, depth: depth, palette: palette)
- .transition(.opacity)
- .allowsHitTesting(false)
- }
- }
- .visualEffect { content, _ in content.offset(y: nudge) }
- // Measured outside the nudge: frames that moved with it fed back into the hit test,
- // so a pointer near a row edge fell into the widened gap, the target jumped to the
- // end of the list, the nudge moved away and the target came back, over and over.
- .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(SidebarListDropDelegate.coordinateSpace)) } action: { ui.rowFrames[id] = $0 }
- }
-
- /// This row is being dragged, itself or as one of the picked tabs.
- private func isDragged(_ draggedID: UUID) -> Bool {
- draggedID == id || (ui.multiSelection.count > 1 && ui.multiSelection.contains(draggedID) && ui.multiSelection.contains(id))
- }
-
- private func combine(for drop: SidebarListDrop?) -> (kind: CombineDropPreview.Kind, dragged: UUID)? {
- switch drop?.target {
- case .split(let t, let leading)? where t == id: return (.split(leading: leading), drop!.draggedID)
- case .newFolder(let t)? where t == id: return (.folder, drop!.draggedID)
- default: return nil
+ switch kind {
+ case .split(let leading): buildSplit(leading: leading)
+ case .folder: buildFolder()
}
+ CATransaction.commit()
}
- private func badge(for target: SidebarListDrop.Target?) -> (symbol: String, label: String)? {
- guard case .into(let t)? = target, t == id else { return nil }
- return store.item(id)?.isFolder == true ? ("folder", "Move to Folder") : ("rectangle.split.3x1", "Add to Split")
+ // MARK: Split
+
+ private func cell(_ item: SidebarItem, width: CGFloat) -> NSView {
+ let v = NSView()
+ v.wantsLayer = true
+ let icon = SidebarFaviconView()
+ icon.show(favicons.image(forKey: item.tab?.iconKey), flip: favicons.glyphIsDark(forKey: item.tab?.iconKey) == palette.isDark, colors: colors)
+ let h = bounds.height
+ icon.frame = NSRect(x: 8, y: (h - CraMetrics.favicon) / 2, width: CraMetrics.favicon, height: CraMetrics.favicon)
+ v.addSubview(icon)
+ let label = NSTextField.sidebarLabel(size: 14)
+ label.stringValue = item.displayTitle
+ label.textColor = colors.textPrimary
+ // HStack(spacing: 8) after 8 pt, Spacer(minLength: 2), 4 pt trailing.
+ let x = 8 + CraMetrics.favicon + 8
+ label.frame = NSRect(x: x - SidebarText.inset, y: (h - 17) / 2, width: max(0, width - x - 14) + 2 * SidebarText.inset, height: 17)
+ v.addSubview(label)
+ return v
}
-}
-
-/// A tab row while another tab hovers over its middle, drawn as the row the
-/// drop makes: in Today the row splits open and the dragged tab slides into a
-/// dashed pane on the side it will take (the split row's own layout), moving
-/// across when the pointer crosses the row's middle; in Pinned it becomes a
-/// "New Folder" row with both tabs' icons dropping into a stack.
-struct CombineDropPreview: View {
- enum Kind: Equatable { case split(leading: Bool), folder }
- let kind: Kind
- let target: SidebarItem
- let dragged: SidebarItem
- let depth: Int
- let palette: SpacePalette
- @State private var open = false
-
- var body: some View {
- Group {
- switch kind {
- case .split(let leading): split(leading: leading)
- case .folder: folder
- }
- }
- .frame(height: CraMetrics.rowHeight)
- .background(
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)
- .fill(palette.selectedFill)
- .shadow(color: .black.opacity(palette.isDark ? 0.25 : 0.1), radius: open ? 6 : 2, y: open ? 2 : 1)
- )
- .overlay(
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)
- .strokeBorder(palette.textPrimary.opacity(open ? 0.35 : 0), lineWidth: 1.5)
- )
- .scaleEffect(open ? 1 : 0.97)
- .onAppear {
- withAnimation(.spring(duration: 0.34, bounce: 0.22)) { open = true }
- }
- }
-
- private func split(leading: Bool) -> some View {
- GeometryReader { geo in
- let pane = max(0, (geo.size.width - 1) / 2)
- HStack(spacing: 0) {
- // Identified cells, so switching sides slides them past each other.
- ForEach(leading ? [dragged, target] : [target, dragged]) { item in
- if item.id == target.id {
- cell(target)
- .frame(maxWidth: .infinity)
- } else {
- cell(dragged)
- .background(
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner - 3, style: .continuous)
- .fill(palette.hoverFill)
- .overlay(
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner - 3, style: .continuous)
- .strokeBorder(palette.textPrimary.opacity(0.45), style: StrokeStyle(lineWidth: 1.25, dash: [4, 3]))
- )
- .padding(4)
- )
- .frame(width: open ? pane : 0)
- .opacity(open ? 1 : 0)
- .offset(x: open ? 0 : (leading ? -12 : 12))
- .clipped()
- }
- }
- }
- .overlay {
- Rectangle().fill(palette.separator)
- .frame(width: 1)
- .padding(.vertical, SplitRow.Metrics.separatorInset)
- .opacity(open ? 1 : 0)
- }
- }
- .padding(.leading, CGFloat(depth) * CraMetrics.indent)
+ private func buildSplit(leading: Bool) {
+ let x0 = CGFloat(depth) * CraMetrics.indent
+ let w = max(0, bounds.width - x0), h = bounds.height
+ let pane = max(0, (w - 1) / 2)
+ let targetCell = cell(target, width: w - pane)
+ let draggedCell = cell(dragged, width: pane)
+ // The dragged half: a dashed box 4 pt in, clipped while it opens.
+ let dash = CAShapeLayer()
+ dash.fillColor = colors.hoverFill.cgColor
+ dash.strokeColor = colors.textPrimary.withAlphaComponent(0.45).cgColor
+ dash.lineWidth = 1.25
+ dash.lineDashPattern = [4, 3]
+ // Never narrower than its corners: CGPath refuses radii wider than half the rect.
+ let r = CraMetrics.rowCorner - 3
+ let box = { (width: CGFloat) in CGPath(roundedRect: NSRect(x: 4.625, y: 4.625, width: max(2 * r, width - 9.25), height: max(2 * r, h - 9.25)),
+ cornerWidth: r, cornerHeight: r, transform: nil) }
+ dash.path = box(pane)
+ draggedCell.layer?.insertSublayer(dash, at: 0)
+ draggedCell.layer?.masksToBounds = true
+ addSubview(targetCell)
+ addSubview(draggedCell)
+ let targetOpen = NSRect(x: leading ? x0 + pane : x0, y: 0, width: w - pane, height: h)
+ let draggedOpen = NSRect(x: leading ? x0 : x0 + w - pane, y: 0, width: pane, height: h)
+ targetCell.frame = targetOpen
+ draggedCell.frame = draggedOpen
+ // Closed: the target fills the row, the dragged half is 0 wide and 12 pt outside it.
+ Self.spring(targetCell.layer, "position", from: CGPoint(x: x0, y: 0), to: targetCell.layer!.position)
+ Self.spring(targetCell.layer, "bounds.size.width", from: w, to: w - pane)
+ let draggedFromX = leading ? x0 - 12 : x0 + w + 12
+ Self.spring(draggedCell.layer, "position", from: CGPoint(x: draggedFromX, y: 0), to: draggedCell.layer!.position)
+ Self.spring(draggedCell.layer, "bounds.size.width", from: 0.0, to: pane)
+ Self.spring(draggedCell.layer, "opacity", from: 0.0, to: 1.0)
+ Self.spring(dash, "path", from: box(9.25), to: dash.path!)
+ let line = NSView(frame: NSRect(x: x0 + w / 2 - 0.5, y: SplitRowMetrics.separatorInset, width: 1, height: h - 2 * SplitRowMetrics.separatorInset))
+ line.wantsLayer = true
+ line.layer?.backgroundColor = colors.separator.cgColor
+ addSubview(line)
+ Self.spring(line.layer, "opacity", from: 0.0, to: 1.0)
}
- private func cell(_ item: SidebarItem) -> some View {
- HStack(spacing: 8) {
- FaviconView(key: item.tab?.iconKey, palette: palette)
- .frame(width: CraMetrics.favicon)
- Text(item.displayTitle)
- .font(.system(size: 14))
- .foregroundStyle(palette.textPrimary)
- .lineLimit(1)
- .truncationMode(.tail)
- Spacer(minLength: 2)
+ // MARK: Folder
+
+ private func buildFolder() {
+ let x0 = 8 + CGFloat(depth) * CraMetrics.indent
+ let h = bounds.height
+ let tones = palette.folderColors(nil)
+ // The folder: its outline over its fill, popping from 40%.
+ let folder = CALayer()
+ folder.frame = NSRect(x: x0, y: (h - 16) / 2, width: CraMetrics.favicon, height: 16)
+ for (name, color) in [("folder.fill", NSColor(tones.fill)), ("folder", NSColor(tones.tint))] {
+ let l = CALayer()
+ l.frame = folder.bounds
+ l.contentsGravity = .center
+ l.contentsScale = window?.backingScaleFactor ?? 2
+ l.contents = NSImage(systemSymbolName: name, accessibilityDescription: nil)?
+ .withSymbolConfiguration(.init(pointSize: 15, weight: .regular).applying(.init(paletteColors: [color])))
+ folder.addSublayer(l)
}
- .padding(.leading, 8)
- .padding(.trailing, 4)
- .frame(maxHeight: .infinity)
+ layer?.addSublayer(folder)
+ Self.spring(folder, "transform.scale", from: 0.4, to: 1.0)
+ Self.spring(folder, "opacity", from: 0.0, to: 1.0)
+ let label = NSTextField.sidebarLabel(size: 14, weight: .medium)
+ label.stringValue = "New Folder"
+ label.textColor = colors.textPrimary
+ let lx = x0 + CraMetrics.favicon + 11
+ label.frame = NSRect(x: lx - SidebarText.inset, y: (h - 17) / 2, width: max(0, bounds.width - lx - 60) + 2 * SidebarText.inset, height: 17)
+ addSubview(label)
+ // Both icons stacked 14 pt from the trailing edge, fanning out.
+ let cx = bounds.width - 6 - 14 - 10
+ let back = stackedIcon(target, centre: CGPoint(x: cx, y: h / 2))
+ let front = stackedIcon(dragged, centre: CGPoint(x: cx, y: h / 2))
+ // SwiftUI's angles and offsets as they are: this view is flipped, y grows down like SwiftUI's.
+ back.transform = CATransform3DConcat(CATransform3DMakeRotation(-6 * .pi / 180, 0, 0, 1), CATransform3DMakeTranslation(-5, 0, 0))
+ front.transform = CATransform3DConcat(CATransform3DMakeRotation(7 * .pi / 180, 0, 0, 1), CATransform3DMakeTranslation(6, 0, 0))
+ Self.spring(back, "transform", from: CATransform3DIdentity, to: back.transform)
+ Self.spring(front, "transform", from: CATransform3DMakeTranslation(22, -8, 0), to: front.transform)
+ Self.spring(front, "opacity", from: 0.0, to: 1.0)
}
- private var folder: some View {
- HStack(spacing: 11) {
- ZStack {
- Image(systemName: "folder.fill").foregroundStyle(palette.folderFill)
- Image(systemName: "folder").foregroundStyle(palette.folderTint)
- }
- .font(.system(size: 15, weight: .regular))
- .frame(width: CraMetrics.favicon)
- .scaleEffect(open ? 1 : 0.4)
- .opacity(open ? 1 : 0)
- Text("New Folder")
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(palette.textPrimary)
- .lineLimit(1)
- Spacer(minLength: 4)
- ZStack {
- stackedIcon(target)
- .rotationEffect(.degrees(open ? -6 : 0))
- .offset(x: open ? -5 : 0)
- stackedIcon(dragged)
- .rotationEffect(.degrees(open ? 7 : 0))
- .offset(x: open ? 6 : 22, y: open ? 0 : -8)
- .opacity(open ? 1 : 0)
- }
- .padding(.trailing, 14)
+ private func stackedIcon(_ item: SidebarItem, centre: CGPoint) -> CALayer {
+ let l = CALayer()
+ l.bounds = CGRect(x: 0, y: 0, width: 20, height: 20)
+ l.position = centre
+ l.cornerRadius = 5
+ l.cornerCurve = .continuous
+ l.backgroundColor = (palette.isDark ? NSColor(white: 0.22, alpha: 1) : .white).cgColor
+ l.shadowColor = NSColor.black.cgColor
+ l.shadowOpacity = 0.15
+ l.shadowRadius = 1.5
+ l.shadowOffset = CGSize(width: 0, height: 0.5)
+ let icon = SidebarFaviconView(size: 14)
+ icon.show(favicons.image(forKey: item.tab?.iconKey), flip: favicons.glyphIsDark(forKey: item.tab?.iconKey) == palette.isDark, colors: colors)
+ let face = CALayer()
+ face.frame = CGRect(x: 3, y: 3, width: 14, height: 14)
+ face.contentsGravity = .resizeAspect
+ face.contentsScale = window?.backingScaleFactor ?? 2
+ face.cornerRadius = 14 * 0.22
+ face.masksToBounds = true
+ if let image = icon.image {
+ face.contents = image.layerContents(forContentsScale: face.contentsScale)
}
- .padding(.leading, 8 + CGFloat(depth) * CraMetrics.indent)
- .padding(.trailing, 6)
- }
-
- private func stackedIcon(_ item: SidebarItem) -> some View {
- FaviconView(key: item.tab?.iconKey, palette: palette, size: 14)
- .padding(3)
- .background(
- RoundedRectangle(cornerRadius: 5, style: .continuous)
- .fill(palette.isDark ? Color(white: 0.22) : .white)
- .shadow(color: .black.opacity(0.15), radius: 1.5, y: 0.5)
- )
+ l.addSublayer(face)
+ layer?.addSublayer(l)
+ return l
}
}
diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
index 27aa0f4..462c825 100644
--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
@@ -1,254 +1,5 @@
import SwiftUI
-/// The whole left column, laid out like Arc: traffic lights + sidebar toggle,
-/// nav buttons at the right of the top row, favorites, muted space header,
-/// pinned, divider, today, new tab, and the dock at the bottom.
-struct SidebarRootView: View {
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
-
- var body: some View {
- let palette = store.focusedSpace(window: ui.windowID).theme.palette
- // The Library takes over the sidebar (LibraryView: in from a little to the left,
- // out to the left while the tab list fades back in).
- ZStack(alignment: .topLeading) {
- tabs
- .opacity(ui.libraryPage == nil ? 1 : 0)
- .allowsHitTesting(ui.libraryPage == nil)
- if let page = ui.libraryPage {
- LibraryView(page: page, palette: palette)
- .ignoresSafeArea()
- .transition(.asymmetric(insertion: .offset(x: -24).combined(with: .opacity),
- removal: .offset(x: -LibraryMetrics.rail).combined(with: .opacity)))
- }
- }
- }
-
- private var tabs: some View {
- let space = store.focusedSpace(window: ui.windowID)
- let palette = space.theme.palette
- return VStack(spacing: 0) {
- SidebarTopBar(palette: palette)
- // Dia's paging container: every space's list sits side by side and the
- // strip follows the swipe 1:1, then a spring settles it on a page.
- GeometryReader { g in
- let spaces = store.pagedSpaces(window: ui.windowID)
- let index = CGFloat(spaces.firstIndex { $0.id == space.id } ?? 0)
- SpacePagerStrip(index: index, width: g.size.width) {
- HStack(alignment: .top, spacing: 0) {
- ForEach(spaces) { s in
- // Arc 1.170 keeps favorites and the space header fixed; only the
- // space's tab list scrolls (SpaceSectionView owns that scroll view).
- // Favorites belong to the space, so they page with it.
- VStack(spacing: 0) {
- FavoritesGrid(space: s, palette: s.theme.palette)
- .padding(.horizontal, 8)
- SpaceSectionView(space: s, palette: s.theme.palette)
- }
- .foregroundStyle(s.theme.palette.textPrimary)
- .frame(width: g.size.width, height: g.size.height, alignment: .top)
- }
- }
- }
- }
- .frame(maxHeight: .infinity, alignment: .top)
- .clipped()
- .mask { DownloadsTrayMask(rows: DownloadHistory.shared.recent.count, open: ui.downloadsListOpen) }
- .overlay(alignment: .bottom) { DownloadsTray(palette: palette) }
- UpdateBanner(palette: palette)
- .padding(.horizontal, 8)
- // Arc's list viewport ends 50pt above the window bottom; the dock sits centred in that band.
- SpaceDock(palette: palette)
- .padding(.horizontal, 10)
- .padding(.top, 8)
- .padding(.bottom, 6)
- }
- .foregroundStyle(palette.textPrimary)
- .ignoresSafeArea()
- .onChange(of: space.id) { _, _ in ui.clearPicks() }
- .animation(ui.spaceSettleAnimation, value: space.id)
- }
-}
-
-/// Row 1: traffic lights, the sidebar toggle right after them, nav buttons
-/// right-aligned (Arc puts them here when the toolbar shows the URL). When the
-/// toolbar is hidden the URL pill moves into the sidebar on a second row.
-///
-/// Toolbar hidden, measured on Arc 1.170 (window capture and AX tree, 26 Oct): toggle and
-/// ← → ↻ are 32 pt buttons centred 1 pt above the traffic lights, the nav buttons 2 pt apart
-/// and 6 pt from the sidebar edge, no ⌄ menu. The URL pill spans the sidebar 8 pt in from
-/// each side, 36 pt tall, 2 pt under the title area, radius 10, the bare host in 13 pt at
-/// 12 pt in. Its accessories (pinned extensions, copy link, site controls) are absent from
-/// the AX tree while the header isn't hovered.
-struct SidebarTopBar: View {
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var hoverPill = false
- @State private var hoverHeader = false
-
- var body: some View {
- let compact = !store.settings.showToolbar
- VStack(spacing: 0) {
- HStack(spacing: 2) {
- Spacer().frame(width: compact ? 71 : 72)
- // The toolbar carries the sidebar toggle; this one only stands in while the toolbar is hidden.
- if compact {
- SidebarIconButton(symbol: "sidebar.left", palette: palette, help: "Hide Sidebar (⌘S)", size: 32, height: 32,
- iconSize: 15.5, weight: .regular, active: ui.appActive) { actions.toggleSidebar() }
- }
- Spacer()
- if compact {
- headerNavButtons
- } else if let t = store.selectedTab(window: ui.windowID)?.tab, store.settings.isDeveloperMode(url: t.url) {
- navButtons
- }
- }
- .frame(height: compact ? 32 : 28)
- .padding(.top, compact ? CraMetrics.titleRowCenter - 17 : CraMetrics.titleRowCenter - 14)
- .padding(.bottom, compact ? CraMetrics.titleAreaHeight - CraMetrics.titleRowCenter - 15 : CraMetrics.titleAreaHeight - CraMetrics.titleRowCenter - 14)
- .padding(.horizontal, 6)
- .contentShape(Rectangle())
- .onTapGesture(count: 2) { actions.titleBarDoubleClick() }
- if compact {
- urlPill
- .padding(.horizontal, 8)
- .padding(.top, 2)
- .padding(.bottom, 8)
- }
- }
- .onHover { hoverHeader = $0 }
- }
-
- /// Arc's row-1 ← → ↻ with the toolbar hidden (no ⌄ menu there).
- private var headerNavButtons: some View {
- HStack(spacing: 2) {
- SidebarIconButton(symbol: "arrow.left", palette: palette, help: "Go Back (⌘[)", enabled: ui.canGoBack, size: 32, height: 32,
- iconSize: 15, weight: .regular, active: ui.appActive) { actions.goBack() }
- SidebarIconButton(symbol: "arrow.right", palette: palette, help: "Go Forward (⌘])", enabled: ui.canGoForward, size: 32, height: 32,
- iconSize: 15, weight: .regular, active: ui.appActive) { actions.goForward() }
- SidebarIconButton(symbol: ui.isLoading ? "xmark" : "arrow.clockwise", palette: palette, help: "Refresh (⌘R)", size: 32, height: 32,
- iconSize: 15, weight: .regular, active: ui.appActive) { actions.reload() }
- }
- }
-
- private var navButtons: some View {
- HStack(spacing: 0) {
- SidebarIconButton(symbol: "arrow.left", palette: palette, help: "Go Back (⌘[)", enabled: ui.canGoBack, size: 34, iconSize: 15, weight: .regular) { actions.goBack() }
- SidebarIconButton(symbol: "arrow.right", palette: palette, help: "Go Forward (⌘])", enabled: ui.canGoForward, size: 34, iconSize: 15, weight: .regular) { actions.goForward() }
- SidebarIconButton(symbol: ui.isLoading ? "xmark" : "arrow.clockwise", palette: palette, help: "Refresh (⌘R)", size: 24, iconSize: 15, weight: .regular) { actions.reload() }
- Menu {
- Button("Refresh the Page") { actions.performAction("reload") }
- Button("Force Refresh the Page") { actions.performAction("hardReload") }
- Divider()
- Button("View Source") { actions.performAction("viewSource") }
- Button("Developer Tools") { actions.performAction("devTools") }
- } label: {
- Image(systemName: "chevron.down")
- .font(.system(size: 8, weight: .bold))
- .foregroundStyle(palette.textTertiary)
- .frame(width: 12, height: 28)
- .contentShape(Rectangle())
- }
- .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)
- .frame(width: 12)
- }
- }
-
- private var urlPill: some View {
- let tab = store.selectedTab(window: ui.windowID)
- let url = tab?.tab?.url ?? ""
- let host = URL(string: url)?.host ?? ""
- let shape = RoundedRectangle(cornerRadius: 10, style: .continuous)
- return HStack(spacing: 0) {
- Button {
- actions.openCommandBar(tab == nil ? .newTab : .editURL)
- } label: {
- HStack(spacing: 6) {
- // Without the toolbar, the nav-bar status ("Copied Current URL") shows here.
- if let status = ui.toolbarStatus {
- Image(systemName: status.symbol).font(.system(size: 10, weight: .semibold)).foregroundStyle(palette.textSecondary)
- Text(status.text)
- .font(.system(size: 13))
- .foregroundStyle(palette.textSecondary)
- .lineLimit(1)
- } else {
- Text(tab == nil ? "Search or Enter URL…" : (host.isEmpty ? SuggestionEngine.humanURL(url) : host.replacingOccurrences(of: "www.", with: "")))
- .font(.system(size: 13))
- .foregroundStyle(tab == nil ? palette.textTertiary : palette.textPrimary)
- .lineLimit(1).truncationMode(.middle)
- }
- Spacer(minLength: 0)
- }
- .id(ui.toolbarStatus?.id)
- .transition(.opacity)
- .padding(.leading, 12)
- .frame(maxHeight: .infinity)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- if hoverHeader && tab != nil {
- pillAccessories
- .padding(.trailing, 5)
- .transition(.opacity)
- }
- }
- .frame(height: 36)
- .background(shape.fill(hoverPill ? palette.selectedFill : palette.pillFill))
- .contentShape(shape)
- .onHover { hoverPill = $0 }
- .animation(.easeOut(duration: 0.15), value: hoverHeader)
- .arcTooltip(url, followsCursor: true)
- }
-
- /// Arc's URL-bar accessories: pinned extensions, Copy Link, then the site controls
- /// (Cra's Extensions menu, the same button as the toolbar's).
- private var pillAccessories: some View {
- let extensions = ExtensionStore.shared
- return HStack(spacing: 1) {
- ForEach(extensions.pinnedIDs, id: \.self) { id in
- if let e = extensions.entries.first(where: { $0.extensionID == id }) {
- PillImageButton(image: e.icon, palette: palette, help: e.name) { actions.runExtension(id) }
- }
- }
- SidebarIconButton(symbol: "link", palette: palette, help: "Copy URL (⇧⌘C)", size: 28, height: 28,
- iconSize: 14, weight: .regular, active: ui.appActive) { actions.performAction("copyURL") }
- if !extensions.entries.isEmpty {
- SidebarIconButton(symbol: "slider.horizontal.2.square", palette: palette, help: "Extensions", size: 28, height: 28,
- iconSize: 15, weight: .regular, active: ui.appActive) { actions.showExtensionsMenu() }
- }
- }
- }
-}
-
-/// A pinned extension in the sidebar's URL pill: its icon at 16 pt.
-private struct PillImageButton: View {
- let image: NSImage?
- let palette: SpacePalette
- var help: String = ""
- let action: () -> Void
- @State private var hover = false
- var body: some View {
- Button(action: action) {
- Group {
- if let image {
- Image(nsImage: image).resizable().interpolation(.high).aspectRatio(contentMode: .fit)
- } else {
- Image(systemName: "puzzlepiece.extension").resizable().aspectRatio(contentMode: .fit)
- }
- }
- .frame(width: 16, height: 16)
- .frame(width: 28, height: 28)
- .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(hover ? palette.hoverFill : .clear))
- }
- .buttonStyle(.plain)
- .onHover { hover = $0 }
- .arcTooltip(help)
- }
-}
-
struct SidebarIconButton: View {
let symbol: String
let palette: SpacePalette
@@ -288,305 +39,3 @@ struct SidebarIconButton: View {
.arcTooltip(help, optionHelp: optionHelp)
}
}
-
-/// Space header, pinned (folders allowed), divider, today, new-tab row.
-struct SpaceSectionView: View {
- let space: Space
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var hoverDivider = false
- /// Arc 1.170 draws a full-width 1pt hairline (~5% black over the light theme) at an edge of
- /// the list only while rows are hidden past it, fading over ~0.25s. Only whether rows hide
- /// past each edge is kept, not the rows' frame: that changed on every frame of a scroll and
- /// re-ran this whole list's body each time.
- @State private var scrolledUnderTop = false
- @State private var rowsBelowBottom = false
- @State private var viewportHeight: CGFloat = 0
- @State private var autoscroller = DragAutoscroller()
-
- var body: some View {
- VStack(alignment: .leading, spacing: 0) {
- SpaceHeader(space: space, palette: palette)
- .padding(.horizontal, 10)
- .padding(.bottom, 3)
- ScrollViewReader { proxy in
- ScrollView(.vertical, showsIndicators: false) {
- rows
- .padding(.top, 3)
- .onGeometryChange(for: Bool.self) { $0.frame(in: .named(Self.scrollSpace)).minY < -0.5 } action: { scrolledUnderTop = $0 }
- .onGeometryChange(for: Bool.self) { [viewportHeight] in $0.frame(in: .named(Self.scrollSpace)).maxY > viewportHeight + 0.5 } action: { rowsBelowBottom = $0 }
- // Arc leaves ~121pt of empty list after the last row at full scroll.
- .padding(.bottom, 121)
- .overlay(alignment: .topLeading) { dropLine }
- .background(DragAutoscroller.Anchor(scroller: autoscroller))
- .contentShape(Rectangle())
- // Right-click on empty list space; rows have their own menus.
- .contextMenu { SpaceListMenu(space: space) }
- .onDrop(of: [.craSidebarItem], delegate: SidebarListDropDelegate(space: space, store: store, ui: ui, autoscroller: autoscroller))
- // Safety net: a drag that ended without an exit callback leaves no preview behind.
- .onContinuousHover { _ in if ui.listDrop != nil, NSEvent.pressedMouseButtons == 0 { ui.listDrop = nil } }
- .coordinateSpace(name: SidebarListDropDelegate.coordinateSpace)
- }
- // A new folder starts renaming at the top of pinned, maybe scrolled away.
- .onChange(of: ui.renamingID) { _, id in
- guard let id else { return }
- withAnimation(.snappy(duration: 0.25, extraBounce: 0)) { proxy.scrollTo(id) }
- }
- }
- .coordinateSpace(name: Self.scrollSpace)
- .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { viewportHeight = $0 }
- .overlay(alignment: .top) { edgeHairline.opacity(scrolledUnderTop ? 1 : 0) }
- .overlay(alignment: .bottom) { edgeHairline.opacity(rowsBelowBottom ? 1 : 0) }
- .animation(.easeInOut(duration: 0.25), value: scrolledUnderTop)
- .animation(.easeInOut(duration: 0.25), value: rowsBelowBottom)
- }
- }
-
- private static let scrollSpace = "spaceSectionScroll"
-
- @ViewBuilder
- private var dropLine: some View {
- if let line = ui.listDrop?.line {
- Capsule()
- .fill(palette.textPrimary.opacity(0.5))
- .frame(width: max(0, line.maxX - line.minX), height: 2)
- .offset(x: line.minX, y: line.y - 1)
- .transition(.opacity)
- .allowsHitTesting(false)
- }
- }
-
- /// Which list a drop lands in, when that pins or unpins the dragged item;
- /// that list lights up while the drag hovers.
- private var dropSection: SidebarSection? {
- guard let drop = ui.listDrop, let target = drop.target else { return nil }
- let lands: SidebarSection
- switch target {
- case .insert(let parent, _): lands = isPinnedList(parent) ? .pinned : .today
- case .into(let id): lands = isPinnedList(id) ? .pinned : .today
- case .newFolder: lands = .pinned
- case .split: lands = .today
- }
- return lands == (isPinnedList(drop.draggedID) ? .pinned : .today) ? nil : lands
- }
-
- private func isPinnedList(_ id: UUID) -> Bool {
- if case .pinned? = store.rootContainer(of: id) { return true }
- return false
- }
-
- private var pinPlaceholder: some View {
- let active = dropSection == .pinned
- return HStack(spacing: 6) {
- Image(systemName: "pin").font(.system(size: 11, weight: .semibold))
- Text("Drop to Pin").font(.system(size: 12, weight: .medium))
- }
- .foregroundStyle(palette.textSecondary)
- .frame(maxWidth: .infinity)
- .frame(height: CraMetrics.rowHeight)
- .background(
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)
- .strokeBorder(palette.textTertiary.opacity(active ? 0.6 : 0.3), style: StrokeStyle(lineWidth: 1, dash: [4, 3]))
- .background(RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous).fill(active ? palette.hoverFill : .clear))
- )
- .transition(.opacity.combined(with: .scale(scale: 0.96, anchor: .top)))
- }
-
- private var edgeHairline: some View {
- Rectangle()
- .fill(palette.isDark ? Color.white.opacity(0.07) : Color.black.opacity(0.05))
- .frame(height: 1)
- .allowsHitTesting(false)
- }
-
- private var rows: some View {
- let todayItems = store.children(of: space.todayContainerID)
- let pinnedItems = store.listedPinnedItems(in: space, window: ui.windowID)
- return VStack(alignment: .leading, spacing: 0) {
- VStack(spacing: CraMetrics.rowSpacing) {
- ForEach(pinnedItems) { item in
- SidebarItemView(item: item, depth: 0, palette: palette, section: .pinned)
- .id(item.id)
- }
- // With nothing pinned the list is 8pt tall; a drag opens a real target.
- // Not when collapsed: the placeholder would claim an empty list and
- // open under the pointer, taking drops meant for the top of Today.
- if store.children(of: space.pinnedContainerID).isEmpty && ui.listDrop != nil { pinPlaceholder }
- }
- .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(SidebarListDropDelegate.coordinateSpace)) } action: { ui.rowFrames[space.pinnedContainerID] = $0 }
- .padding(.horizontal, 10)
- .frame(minHeight: 8)
- .background(RoundedRectangle(cornerRadius: 10).fill(dropSection == .pinned && !pinnedItems.isEmpty ? palette.hoverFill : .clear).padding(.horizontal, 8))
-
- // Divider between pinned and today; "Clear" shows on hover.
- HStack {
- Rectangle().fill(palette.separator).frame(height: 1)
- .opacity(todayItems.isEmpty ? 0 : 1)
- if hoverDivider && !todayItems.isEmpty {
- Button("Clear") { store.clearToday(space.id) }
- .buttonStyle(.plain)
- .arcTooltip("Clear Today tabs")
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(palette.textSecondary)
- .transition(.opacity)
- }
- }
- .frame(height: 18)
- .padding(.horizontal, 20)
- .contentShape(Rectangle())
- .onHover { hoverDivider = $0 }
- .animation(.easeOut(duration: 0.15), value: hoverDivider)
-
- VStack(spacing: CraMetrics.rowSpacing) {
- if store.settings.newTabButtonAtTop { NewTabRow(palette: palette) }
- ForEach(todayItems) { item in
- SidebarItemView(item: item, depth: 0, palette: palette, section: .today)
- .id(item.id)
- }
- if !store.settings.newTabButtonAtTop { NewTabRow(palette: palette) }
- }
- .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(SidebarListDropDelegate.coordinateSpace)) } action: { ui.rowFrames[space.todayContainerID] = $0 }
- .padding(.horizontal, 10)
- .background(RoundedRectangle(cornerRadius: 10).fill(dropSection == .today ? palette.hoverFill : .clear).padding(.horizontal, 8))
- }
- }
-}
-
-struct SpaceHeader: View {
- let space: Space
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(\.sidebarActions) private var actions
- @State private var hover = false
-
- private var collapsed: Bool { store.isPinnedCollapsed(space.id) }
-
- private func toggle() {
- withAnimation(.easeInOut(duration: 0.25)) { store.togglePinnedCollapsed(space.id) }
- }
-
- // Arc: a click on the space name collapses or expands the pinned tabs; the menu is on right-click.
- var body: some View {
- Button(action: toggle) {
- HStack(spacing: 8) {
- Text(space.emoji).font(.system(size: 12))
- Text(space.title)
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(palette.textSecondary)
- .lineLimit(1)
- Image(systemName: "chevron.down")
- .font(.system(size: 8, weight: .bold))
- .foregroundStyle(palette.textTertiary)
- .rotationEffect(.degrees(collapsed ? -90 : 0))
- .opacity(hover ? 1 : 0)
- Spacer()
- }
- .padding(.horizontal, 7)
- .frame(height: 31)
- .background(RoundedRectangle(cornerRadius: 8).fill(hover ? palette.hoverFill : .clear))
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .onHover { hover = $0 }
- .contextMenu {
- Button(collapsed ? "Expand Pinned Tabs" : "Collapse Pinned Tabs", action: toggle)
- Divider()
- Button("Edit Space…") { actions.editSpace(space) }
- Button("New Folder") { actions.performAction("newFolder") }
- Button("New GitHub Live Folder") { actions.performAction("newGitHubLiveFolder") }
- .disabled(store.liveFolder(.github, inSpace: space.id) != nil)
- Divider()
- Button("Clear Today") { store.clearToday(space.id) }
- Divider()
- Button("New Space…") { actions.editSpace(nil) }
- Button("Delete Space…") { actions.performAction("deleteSpace") }
- }
- }
-}
-
-struct NewTabRow: View {
- let palette: SpacePalette
- @Environment(\.sidebarActions) private var actions
- @State private var hover = false
- var body: some View {
- Button { actions.openCommandBar(.newTab) } label: {
- HStack(spacing: 9) {
- Image(systemName: "plus")
- .font(.system(size: 13, weight: .medium))
- .frame(width: CraMetrics.favicon)
- Text("New Tab")
- .font(.system(size: 14))
- Spacer()
- }
- .foregroundStyle(hover ? palette.textPrimary : palette.textSecondary)
- .padding(.leading, 8)
- .padding(.trailing, 10)
- .frame(height: CraMetrics.rowHeight)
- .background(RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous).fill(hover ? palette.selectedFill : .clear))
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .onHover { hover = $0 }
- }
-}
-
-/// The space list's context menu. Its own view: finding the live folder walks every item,
-/// which would make the whole list re-render on any change to any item.
-private struct SpaceListMenu: View {
- let space: Space
- @Environment(SidebarStore.self) private var store
- @Environment(\.sidebarActions) private var actions
-
- var body: some View {
- Button("New Tab") { actions.openCommandBar(.newTab) }
- Button("New Folder") { actions.performAction("newFolder") }
- Button("New GitHub Live Folder") { actions.performAction("newGitHubLiveFolder") }
- .disabled(store.liveFolder(.github, inSpace: space.id) != nil)
- Divider()
- if !store.children(of: space.todayContainerID).isEmpty {
- Button("Clear Today") { store.clearToday(space.id) }
- }
- Button("Edit Space…") { actions.editSpace(space) }
- }
-}
-
-/// The strip of space lists. It moves as a render effect, never by layout: a layout offset
-/// moved the geometry of every row in every space on every frame, re-ran hover for the rows
-/// sliding under a resting pointer and had SwiftUI rebuild its key view loop (~1 s of main
-/// thread over six swipes). The page index places the strip at once; what is left to travel,
-/// a live swipe or the spring after a space change, is the render offset. The strip takes no
-/// clicks or hovers under the fingers. Only this view reads the swipe; the caller builds the lists.
-private struct SpacePagerStrip<Content: View>: View {
- let index: CGFloat
- let width: CGFloat
- @ViewBuilder let content: Content
- @Environment(SidebarUIState.self) private var ui
- /// Pages still to travel after a space change by click or shortcut; springs to 0.
- @State private var shift: CGFloat = 0
-
- var body: some View {
- let x = -(ui.spaceSwipe + shift) * width
- content
- .offset(x: -index * width)
- .animation(nil, value: index)
- .visualEffect { view, _ in view.offset(x: x) }
- // Off only under the fingers: ignoring clicks for the whole spring made the sidebar
- // feel unresponsive right after a space change.
- .allowsHitTesting(ui.spaceSwipe == 0 && shift == 0)
- .onChange(of: index) { old, new in
- // A swipe re-bases itself (MainWindowController.endSpaceSwipe).
- guard !ui.spaceSettling else { return }
- var instant = Transaction()
- instant.disablesAnimations = true
- withTransaction(instant) { shift = old - new }
- let generation = ui.beginSpaceSettle()
- withAnimation(ui.spaceSettleAnimation, completionCriteria: .logicallyComplete) {
- shift = 0
- } completion: {
- ui.endSpaceSettle(generation)
- }
- }
- }
-}
diff --git a/Sources/Cra/UI/Sidebar/SpaceDock.swift b/Sources/Cra/UI/Sidebar/SpaceDock.swift
index 7f9b329..9549b59 100644
--- a/Sources/Cra/UI/Sidebar/SpaceDock.swift
+++ b/Sources/Cra/UI/Sidebar/SpaceDock.swift
@@ -1,350 +1,44 @@
+import AppKit
import SwiftUI
-/// Bottom row like Arc's: library/archive at the left, tiny space icons in
-/// the middle (inactive ones dimmed), "+" at the right.
-struct SpaceDock: View {
- let palette: SpacePalette
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var reorder: SpaceReorder?
- @State private var hovered: UUID?
-
- /// Arc 1.170 (SidebarDock, an NSCollectionView): 34×32 pt cells side by side with no
- /// gap, so a press anywhere between two icons still lands on a space.
- static let cell = CGSize(width: 34, height: 32)
+/// Arc's Library glyph: a filled box with a small confetti puff (cloud, dot, triangle) rising
+/// from it. Drawn once per theme brightness into an image for the dock's Library button.
+struct LibraryGlyph: View {
+ let dark: Bool
var body: some View {
- HStack(spacing: 0) {
- LibraryButton(palette: palette) { actions.toggleLibrary() }
- Spacer(minLength: 0)
- // An incognito window has one space of its own: nothing to switch to or add.
- if !store.window(ui.windowID).isIncognito {
- let spaces = store.orderedSpaces
- HStack(spacing: 0) {
- ForEach(Array(spaces.enumerated()), id: \.element.id) { index, space in
- SpaceDockButton(space: space, palette: palette,
- selected: space.id == store.focusedSpaceID(window: ui.windowID),
- hovered: hovered == space.id && reorder == nil,
- pressed: reorder?.id == space.id)
- .offset(x: offset(of: space.id, at: index))
- .zIndex(reorder?.id == space.id ? 1 : 0)
- }
+ let ink = dark ? Color.white.opacity(0.55) : Color.black.opacity(0.26)
+ ZStack(alignment: .top) {
+ // Arc's box has no lid line: a 13×10 rounded box with a light slot near the top.
+ RoundedRectangle(cornerRadius: 2.5, style: .continuous)
+ .frame(width: 14, height: 11)
+ .overlay(alignment: .top) {
+ Capsule().fill(dark ? Color.black.opacity(0.5) : Color.white.opacity(0.7))
+ .frame(width: 5, height: 1.6).padding(.top, 2.4)
}
- .overlay(SpaceDockMouse(
- cellWidth: Self.cell.width, count: spaces.count,
- hover: { i in hovered = i.map { spaces[$0].id } },
- press: { i in reorder = SpaceReorder(id: spaces[i].id, from: i, to: i) },
- drag: { drag(by: $0, count: spaces.count) },
- release: { inside in release(inside: inside, spaces: spaces) },
- menu: { menu(for: spaces[$0]) }))
- Spacer(minLength: 0)
- SidebarIconButton(symbol: "plus", palette: palette, help: "New Space") { actions.editSpace(nil) }
- }
- }
- .frame(height: 36)
- }
-
- /// The dragged space follows the pointer; the ones it passes slide a cell the other way,
- /// like the gap Arc's collection view opens at the proposed drop index.
- private func offset(of id: UUID, at index: Int) -> CGFloat {
- guard let r = reorder else { return 0 }
- if r.id == id { return r.dx }
- if r.from < index && index <= r.to { return -Self.cell.width }
- if r.to <= index && index < r.from { return Self.cell.width }
- return 0
- }
-
- private func drag(by t: CGSize, count: Int) {
- guard var r = reorder, !r.settling else { return }
- if !r.moved && abs(t.width) < 3 && abs(t.height) < 3 { return }
- r.moved = true
- let w = Self.cell.width
- r.dx = min(max(t.width, -CGFloat(r.from) * w), CGFloat(count - 1 - r.from) * w)
- let to = min(max(r.from + Int((r.dx / w).rounded()), 0), count - 1)
- if to != r.to {
- reorder?.dx = r.dx
- withAnimation(.easeOut(duration: 0.2)) { r.to = to; reorder = r }
- } else {
- reorder = r
- }
- }
-
- /// A release inside the pressed cell that didn't move the space switches to it, so a
- /// shaky click still counts; a moved space slides into its cell and the order is saved.
- private func release(inside: Bool, spaces: [Space]) {
- guard let r = reorder, !r.settling else { return }
- guard r.to != r.from else {
- if inside { store.focusSpace(r.id, window: ui.windowID) }
- withAnimation(.easeOut(duration: 0.15)) { reorder = nil }
- return
- }
- reorder?.settling = true
- // `moveSpace` indexes the full space order; land next to the space now in that cell.
- let target = store.spaceOrder.firstIndex(of: spaces[r.to].id) ?? r.to
- withAnimation(.easeOut(duration: 0.15)) {
- reorder?.dx = CGFloat(r.to - r.from) * Self.cell.width
- } completion: {
- withTransaction(Transaction(animation: nil)) {
- store.moveSpace(r.id, to: target)
- reorder = nil
+ .offset(y: 8)
+ HStack(alignment: .bottom, spacing: 1) {
+ Image(systemName: "cloud.fill").font(.system(size: 7, weight: .bold))
+ Circle().frame(width: 2, height: 2).offset(y: -4)
+ Image(systemName: "triangle.fill").font(.system(size: 4, weight: .bold)).offset(y: -1)
}
+ .offset(x: 2, y: -1)
}
- }
-
- private func menu(for space: Space) -> NSMenu {
- let menu = NSMenu()
- menu.addItem(BlockMenuItem(title: "Edit Space…") { actions.editSpace(space) })
- menu.addItem(.separator())
- menu.addItem(BlockMenuItem(title: "Move Left") {
- if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: max(0, i - 1)) }
- })
- menu.addItem(BlockMenuItem(title: "Move Right") {
- if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: i + 1) }
- })
- menu.addItem(.separator())
- menu.addItem(BlockMenuItem(title: "Delete Space…") {
- store.focusSpace(space.id, window: ui.windowID)
- actions.performAction("deleteSpace")
- })
- return menu
- }
-}
-
-private struct SpaceReorder {
- let id: UUID
- let from: Int
- var to: Int
- var dx: CGFloat = 0
- var moved = false
- /// Released; the space is sliding into its new cell.
- var settling = false
-}
-
-/// Arc's dock items take the mouse themselves (SidebarDockItemView overrides mouseDown:/mouseUp:).
-/// This AppKit view over the strip does the same, so a press there never moves the window,
-/// and every click counts (a SwiftUI drag gesture here dropped every other press).
-private struct SpaceDockMouse: NSViewRepresentable {
- let cellWidth: CGFloat
- let count: Int
- let hover: (Int?) -> Void
- let press: (Int) -> Void
- let drag: (CGSize) -> Void
- let release: (_ inside: Bool) -> Void
- let menu: (Int) -> NSMenu
-
- func makeNSView(context: Context) -> MouseView { MouseView() }
- func updateNSView(_ view: MouseView, context: Context) { view.config = self }
-
- final class MouseView: NSView {
- var config: SpaceDockMouse?
- private var pressed: (index: Int, start: NSPoint)?
- private var hovered: Int? {
- didSet { if hovered != oldValue { config?.hover(hovered) } }
- }
-
- override var isFlipped: Bool { true }
- override var mouseDownCanMoveWindow: Bool { false }
- override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
-
- private func point(_ event: NSEvent) -> NSPoint { convert(event.locationInWindow, from: nil) }
- private func cell(_ i: Int) -> NSRect {
- NSRect(x: CGFloat(i) * (config?.cellWidth ?? 34), y: 0, width: config?.cellWidth ?? 34, height: bounds.height)
- }
- private func index(at p: NSPoint) -> Int? {
- guard let config, bounds.contains(p) else { return nil }
- let i = Int(p.x / config.cellWidth)
- return i < config.count ? i : nil
- }
-
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- for t in trackingAreas { removeTrackingArea(t) }
- addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect],
- owner: self))
- }
- override func mouseEntered(with event: NSEvent) { if pressed == nil { hovered = index(at: point(event)) } }
- override func mouseMoved(with event: NSEvent) { if pressed == nil { hovered = index(at: point(event)) } }
- override func mouseExited(with event: NSEvent) { if pressed == nil { hovered = nil } }
-
- override func mouseDown(with event: NSEvent) {
- let p = point(event)
- guard let i = index(at: p) else { return }
- pressed = (i, p)
- config?.press(i)
- }
- override func mouseDragged(with event: NSEvent) {
- guard let pressed else { return }
- let p = point(event)
- config?.drag(CGSize(width: p.x - pressed.start.x, height: p.y - pressed.start.y))
- }
- override func mouseUp(with event: NSEvent) {
- guard let i = pressed?.index else { return }
- pressed = nil
- let p = point(event)
- config?.release(cell(i).contains(p))
- hovered = index(at: p)
- }
- override func menu(for event: NSEvent) -> NSMenu? {
- index(at: point(event)).flatMap { config?.menu($0) }
- }
- }
-}
-
-struct SpaceDockButton: View {
- let space: Space
- let palette: SpacePalette
- let selected: Bool
- var hovered = false
- var pressed = false
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var targeted = false
-
- /// Arc's hovered/pressed cell on a dark space: white at ~7.8% (39,33,51 over 21,14,34), 6 pt corners.
- private var cellFill: Color { palette.isDark ? .white.opacity(0.078) : .black.opacity(0.05) }
-
- var body: some View {
- Text(space.emoji)
- .font(.system(size: 13))
- .frame(width: SpaceDock.cell.width, height: SpaceDock.cell.height)
- .opacity(selected || hovered || pressed ? 1 : 0.45)
- .saturation(selected || hovered || pressed ? 1 : 0.2)
- .background(RoundedRectangle(cornerRadius: 6).fill(targeted || hovered || pressed ? cellFill : .clear))
- .contentShape(Rectangle())
- .arcTooltip(space.title)
- // Arc exposes each cell as a button named after the space.
- .accessibilityElement()
- .accessibilityLabel(space.title)
- .accessibilityAddTraits(.isButton)
- .accessibilityAction { store.focusSpace(space.id, window: ui.windowID) }
- .dropDestination(for: SidebarDragItem.self) { items, _ in
- guard let d = items.first else { return false }
- store.moveTab(d.id, toSpace: space.id)
- return true
- } isTargeted: { t in
- targeted = t
- // Arc: holding a dragged item over a space switches to it, so the
- // item can be carried into that space's list and dropped in place.
- guard t, !selected else { return }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- if targeted { store.focusSpace(space.id, window: ui.windowID) }
- }
- }
- }
-}
-
-
-/// Arc's Library glyph: a filled box with a small confetti puff (cloud, dot,
-/// triangle) rising from it. Same hit area and hover fill as `SidebarIconButton`.
-struct LibraryButton: View {
- let palette: SpacePalette
- let action: () -> Void
- @Environment(SidebarUIState.self) private var ui
- @State private var hover = false
-
- /// Where Arc's download bin rests relative to the Library glyph's centre: up and to
- /// the right, the glyph's box peeking out under its lower-left corner.
- static let binOffset = CGSize(width: 9, height: -12)
-
- var body: some View {
- libraryGlyph
- .background(LibraryAnchor(ui: ui))
- .overlay {
- if let download = ui.recentDownload {
- DownloadBin(download: download, dimmed: !ui.appActive)
- .offset(Self.binOffset)
- }
- }
- }
-
- private var libraryGlyph: some View {
- let ink = palette.isDark ? Color.white.opacity(0.55) : Color.black.opacity(0.26)
- return Button(action: action) {
- ZStack(alignment: .top) {
- // Arc's box has no lid line: a 13×10 rounded box with a light slot near the top.
- RoundedRectangle(cornerRadius: 2.5, style: .continuous)
- .frame(width: 14, height: 11)
- .overlay(alignment: .top) {
- Capsule().fill(palette.isDark ? Color.black.opacity(0.5) : Color.white.opacity(0.7))
- .frame(width: 5, height: 1.6).padding(.top, 2.4)
- }
- .offset(y: 8)
- HStack(alignment: .bottom, spacing: 1) {
- Image(systemName: "cloud.fill").font(.system(size: 7, weight: .bold))
- Circle().frame(width: 2, height: 2).offset(y: -4)
- Image(systemName: "triangle.fill").font(.system(size: 4, weight: .bold)).offset(y: -1)
- }
- .offset(x: 2, y: -1)
- }
- .foregroundStyle(ink)
- .frame(width: 28, height: 28)
- .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(hover ? palette.hoverFill : .clear))
- }
- .buttonStyle(.plain)
- .onHover { hover = $0; ui.libraryHovered = $0; ui.downloadsHoverChanged() }
- .arcTooltip("Library (⇧⌘L)")
- }
-}
-
-/// Arc's download "bin" (DownloadsUI.DownloadToLibrary): the file's thumbnail, 32 pt with
-/// 8 pt corners, lands over the Library button as the download glyph is launched at it.
-/// It drops in from 6 pt above, overshoots 12 pt below, and settles (measured on Arc 1.170
-/// at 60 fps). Arc draws it faint while its window is in the background.
-private struct DownloadBin: View {
- let download: RecentDownload
- let dimmed: Bool
- @Environment(SidebarUIState.self) private var ui
- /// Keyframes run when their trigger changes, and the bin is a new view per download.
- @State private var drops = 0
-
- var body: some View {
- Button { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: download.path)]) } label: {
- Image(nsImage: download.image)
- .resizable()
- .aspectRatio(contentMode: .fill)
- .frame(width: 32, height: 32)
- .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
- .opacity(dimmed ? 0.4 : 1)
- .keyframeAnimator(initialValue: BinMotion(), trigger: drops) { content, m in
- content.offset(y: m.y).opacity(m.opacity)
- } keyframes: { _ in
- KeyframeTrack(\.y) {
- LinearKeyframe(-6, duration: 0)
- CubicKeyframe(12, duration: 0.15)
- LinearKeyframe(12, duration: 0.05)
- CubicKeyframe(-2, duration: 0.13)
- CubicKeyframe(0, duration: 0.07)
- }
- KeyframeTrack(\.opacity) {
- LinearKeyframe(0, duration: 0)
- LinearKeyframe(1, duration: 0.05)
- }
- }
- }
- .buttonStyle(.plain)
+ // The stack is laid out by the box alone (11 pt), so the puff above it left the glyph
+ // 3.5 pt low, its box on the button's bottom edge (GitHub #11). Centre puff + box.
+ .offset(y: -3.5)
+ .foregroundStyle(ink)
.frame(width: 28, height: 28)
- .onHover { ui.libraryHovered = $0; ui.downloadsHoverChanged() }
- .arcTooltip((download.path as NSString).lastPathComponent)
- .onAppear { drops += 1 }
- .onChange(of: download.id) { drops += 1 }
}
-}
-private struct BinMotion {
- var y: CGFloat = 0
- var opacity: Double = 1
-}
+ @MainActor private static var cache: [Bool: NSImage] = [:]
-/// Hands the Library button's NSView to the window controller, which aims download
-/// flights at it (the sidebar can live in the window or in the floating sidebar panel).
-private struct LibraryAnchor: NSViewRepresentable {
- let ui: SidebarUIState
- func makeNSView(context: Context) -> NSView {
- let v = NSView()
- ui.libraryAnchor = v
- return v
+ @MainActor static func image(dark: Bool) -> NSImage? {
+ if let img = cache[dark] { return img }
+ let r = ImageRenderer(content: LibraryGlyph(dark: dark))
+ r.scale = NSScreen.main?.backingScaleFactor ?? 2
+ let img = r.nsImage
+ cache[dark] = img
+ return img
}
- func updateNSView(_ nsView: NSView, context: Context) { ui.libraryAnchor = nsView }
}
diff --git a/Sources/Cra/UI/Sidebar/TileColor.swift b/Sources/Cra/UI/Sidebar/TileColor.swift
new file mode 100644
index 0000000..220c88a
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/TileColor.swift
@@ -0,0 +1,50 @@
+import SwiftUI
+import UniformTypeIdentifiers
+
+/// Tile backgrounds offered in a favorite's "Tile Color" menu.
+enum TileColor {
+ static let presets: [(name: String, hex: String)] = [
+ ("White", "#FFFFFF"), ("Light Gray", "#D9D9DE"), ("Graphite", "#48484A"), ("Black", "#000000"),
+ ("Red", "#FF453A"), ("Orange", "#FF9F0A"), ("Yellow", "#FFD60A"), ("Green", "#30D158"),
+ ("Teal", "#40C8E0"), ("Blue", "#0A84FF"), ("Purple", "#BF5AF2"), ("Pink", "#FF375F"),
+ ]
+
+ /// A 12pt dot for the menu; Default is drawn hollow.
+ static func swatch(_ hex: String?) -> NSImage {
+ NSImage(size: NSSize(width: 12, height: 12), flipped: false) { rect in
+ let path = NSBezierPath(ovalIn: rect.insetBy(dx: 0.5, dy: 0.5))
+ if let hex { NSColor(hex: hex).setFill(); path.fill() }
+ NSColor.secondaryLabelColor.setStroke()
+ path.lineWidth = 1
+ path.stroke()
+ return true
+ }
+ }
+}
+
+/// Routes the shared color panel to whichever favorite asked for it last.
+@MainActor
+final class TileColorPanel: NSObject {
+ static let shared = TileColorPanel()
+ private var onChange: ((String) -> Void)?
+
+ func show(_ hex: String?, onChange: @escaping (String) -> Void) {
+ let panel = NSColorPanel.shared
+ // Detach first so seeding the color doesn't recolor the previous tile.
+ panel.setTarget(nil)
+ panel.setAction(nil)
+ panel.showsAlpha = false
+ panel.isContinuous = true
+ if let hex { panel.color = NSColor(hex: hex) }
+ self.onChange = onChange
+ panel.setTarget(self)
+ panel.setAction(#selector(changed(_:)))
+ panel.orderFront(nil)
+ }
+
+ @objc private func changed(_ panel: NSColorPanel) {
+ guard let c = panel.color.usingColorSpace(.sRGB) else { return }
+ onChange?(String(format: "#%02X%02X%02X", Int((c.redComponent * 255).rounded()),
+ Int((c.greenComponent * 255).rounded()), Int((c.blueComponent * 255).rounded())))
+ }
+}
diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swift
index 8db0ad7..3fe6f4b 100644
--- a/Sources/Cra/UI/SidebarUIState.swift
+++ b/Sources/Cra/UI/SidebarUIState.swift
@@ -66,7 +66,10 @@ final class SidebarUIState {
var splitDropTarget: SplitDropTarget?
/// Live space swipe, in pages away from the focused space (+ toward the next one);
/// 0 at rest. The sidebar pages and the window tint follow it (Dia: PageSwipeController).
- var spaceSwipe: CGFloat = 0
+ var spaceSwipe: CGFloat = 0 { didSet { for f in spaceSwipeObservers { f() } } }
+ /// The space pager and the window tint follow the swipe directly in AppKit, not through SwiftUI.
+ @ObservationIgnored private var spaceSwipeObservers: [() -> Void] = []
+ func observeSpaceSwipe(_ f: @escaping () -> Void) { spaceSwipeObservers.append(f) }
/// Release velocity for the settle spring, relative to the distance left to travel.
var spaceSettleVelocity: Double = 0
/// The strip is springing onto its page (after a swipe or a space change); it takes no
@@ -100,8 +103,6 @@ final class SidebarUIState {
var selectionAnchor: UUID?
/// A sidebar drag over the space's list and what releasing it would do.
var listDrop: SidebarListDrop?
- /// Row and section frames in the list's coordinate space, for hit-testing drags.
- @ObservationIgnored var rowFrames: [UUID: CGRect] = [:]
/// Dia's nav-bar status: a short confirmation shown in place of the URL
/// ("Copied Current URL"), then the URL comes back.
var toolbarStatus: ToolbarStatus?
diff --git a/Sources/Cra/UI/SiteControlCenter.swift b/Sources/Cra/UI/SiteControlCenter.swift
index cbf94de..f54e579 100644
--- a/Sources/Cra/UI/SiteControlCenter.swift
+++ b/Sources/Cra/UI/SiteControlCenter.swift
@@ -1,5 +1,4 @@
import AppKit
-import SwiftUI
/// Arc 1.170's Site Control Center: the sliders button at the end of the toolbar and of the
/// sidebar's URL pill (SiteControlCenterView in ARC_SiteControlCenter). Geometry and colours
@@ -28,14 +27,35 @@ enum SiteControlCenterMetrics {
static let gap: CGFloat = 8
}
-struct SiteControlCenterView: View {
- let url: String
- let dark: Bool
- let actions: SiteControlCenterActions
- @Environment(SidebarStore.self) private var store
+/// The popover's content: built in one pass from the store and the extension list, and built
+/// again when either changes (pinning, a setting switch).
+@MainActor
+final class SiteControlCenterView: NSView {
+ private typealias M = SiteControlCenterMetrics
+ private let url: String
+ private let colors: SiteControlCenterColors
+ private let actions: SiteControlCenterActions
+ private let store: SidebarStore
private var extensions: ExtensionStore { .shared }
- private var colors: SiteControlCenterColors { SiteControlCenterColors(dark: dark) }
+ init(url: String, dark: Bool, actions: SiteControlCenterActions, store: SidebarStore) {
+ self.url = url
+ colors = SiteControlCenterColors(dark: dark)
+ self.actions = actions
+ self.store = store
+ super.init(frame: NSRect(x: 0, y: 0, width: M.width, height: 100))
+ wantsLayer = true
+ layer?.backgroundColor = colors.background.cgColor
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ var onResize: (NSSize) -> Void = { _ in }
+
+ private var isSecure: Bool { url.hasPrefix("https://") || url.hasPrefix("chrome://") || url.hasPrefix("chrome-extension://") }
/// Arc: pinned extensions in toolbar order, then the rest by name.
private var orderedExtensions: [ExtensionStore.Entry] {
@@ -46,78 +66,88 @@ struct SiteControlCenterView: View {
return pinned + rest
}
- private var isSecure: Bool { url.hasPrefix("https://") || url.hasPrefix("chrome://") || url.hasPrefix("chrome-extension://") }
-
- var body: some View {
- VStack(alignment: .leading, spacing: 0) {
- actionRow
- .padding(.bottom, 11)
- SiteControlCenterSection(title: "Extensions", hoverText: "Manage", colors: colors, onHeaderClick: actions.manageExtensions) {
- extensionGrid
- }
- .padding(.bottom, 15)
- SiteControlCenterSection(title: "Settings", hoverText: nil, colors: colors, onHeaderClick: {}) {
- settings
- }
- Rectangle().fill(colors.divider).frame(height: 1)
- .padding(.top, 13).padding(.bottom, 12)
- footer
+ private func observe() {
+ withObservationTracking {
+ _ = extensions.entries
+ _ = extensions.pinnedIDs
+ _ = store.settings
+ } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
}
- .padding(.top, 9)
- .padding([.horizontal, .bottom], SiteControlCenterMetrics.inset)
- .frame(width: SiteControlCenterMetrics.width)
+ build()
}
- private var actionRow: some View {
- HStack(spacing: SiteControlCenterMetrics.gap) {
- SiteControlCenterActionButton(symbol: "square.and.arrow.up", help: "Share", colors: colors, action: actions.share)
- SiteControlCenterActionButton(symbol: "link", help: "Copy URL", colors: colors, action: actions.copyURL)
- SiteControlCenterActionButton(symbol: "camera", help: "Capture this page", colors: colors, action: actions.capture)
- SiteControlCenterActionButton(symbol: "text.viewfinder", help: "Capture the full page", colors: colors, action: actions.captureFullPage)
+ private func build() {
+ subviews.forEach { $0.removeFromSuperview() }
+ let x = M.inset, w = M.width - 2 * M.inset
+ var y: CGFloat = 9
+ // The four raised action buttons.
+ for (i, (symbol, help, run)) in [("square.and.arrow.up", "Share", actions.share), ("link", "Copy URL", actions.copyURL),
+ ("camera", "Capture this page", actions.capture),
+ ("text.viewfinder", "Capture the full page", actions.captureFullPage)].enumerated() {
+ let b = SiteActionButton(symbol: symbol, help: help, colors: colors, action: run)
+ b.frame = NSRect(x: x + CGFloat(i) * (M.tile.width + M.gap), y: y, width: M.tile.width, height: M.tile.height)
+ addSubview(b)
}
- }
-
- private var extensionGrid: some View {
- let columns = Array(repeating: GridItem(.fixed(SiteControlCenterMetrics.tile.width), spacing: SiteControlCenterMetrics.gap), count: 4)
- return LazyVGrid(columns: columns, alignment: .leading, spacing: SiteControlCenterMetrics.gap) {
- ForEach(orderedExtensions) { e in
- SiteControlCenterExtensionButton(entry: e, pinned: extensions.isPinned(e.extensionID), colors: colors,
- run: { actions.runExtension(e.extensionID) },
- togglePin: { extensions.setPinned(e.extensionID, !extensions.isPinned(e.extensionID)) })
- }
- SiteControlCenterTile(colors: colors, help: "Add Extension", action: actions.addExtension) {
- Image(systemName: "plus").font(.system(size: 14, weight: .medium)).foregroundStyle(colors.text)
- }
+ y += M.tile.height + 11
+ // Extensions: a 4-column grid of tiles, then "+".
+ let ext = SiteSectionView(title: "Extensions", hoverText: "Manage", colors: colors, onHeaderClick: actions.manageExtensions)
+ var tiles: [NSView] = orderedExtensions.map { e in
+ SiteExtensionTile(entry: e, pinned: extensions.isPinned(e.extensionID), colors: colors,
+ run: { [actions] in actions.runExtension(e.extensionID) },
+ togglePin: { ExtensionStore.shared.setPinned(e.extensionID, !ExtensionStore.shared.isPinned(e.extensionID)) })
}
- }
-
- private var settings: some View {
+ let add = SiteTile(colors: colors, help: "Add Extension", action: actions.addExtension)
+ add.setGlyph(SidebarSymbols.image("plus", size: 14, weight: .medium), tint: colors.text)
+ tiles.append(add)
+ for (i, t) in tiles.enumerated() {
+ t.frame = NSRect(x: CGFloat(i % 4) * (M.tile.width + M.gap), y: 27 + CGFloat(i / 4) * (M.tile.height + M.gap),
+ width: M.tile.width, height: M.tile.height)
+ ext.addSubview(t)
+ }
+ for case let t as SiteExtensionTile in tiles { ext.addSubview(t.badge) }
+ let rows = (tiles.count + 3) / 4
+ let extH = 27 + CGFloat(rows) * M.tile.height + CGFloat(rows - 1) * M.gap
+ ext.frame = NSRect(x: x, y: y, width: w, height: extH)
+ addSubview(ext)
+ y += extH + 15
+ // Settings: three switch rows.
+ let settings = SiteSectionView(title: "Settings", hoverText: nil, colors: colors, onHeaderClick: {})
let developer = store.settings.isDeveloperMode(url: url)
- return VStack(alignment: .leading, spacing: 10) {
- SiteControlCenterSettingRow(symbol: "hammer.fill", title: "Developer Mode", subtitle: developer ? "On" : "Off",
- active: developer, colors: colors) { store.settings.toggleDeveloperMode(url: url) }
- SiteControlCenterSettingRow(symbol: "shield.fill", title: "Block Ads & Trackers",
- subtitle: store.settings.blockAdsAndTrackers ? "On" : "Off",
- active: store.settings.blockAdsAndTrackers, colors: colors) { store.settings.blockAdsAndTrackers.toggle() }
- SiteControlCenterSettingRow(symbol: "gearshape.fill", title: "Automatic Picture-In-Picture",
- subtitle: store.settings.autoPictureInPicture ? "Allowed" : "Disabled",
- active: store.settings.autoPictureInPicture, colors: colors) { store.settings.autoPictureInPicture.toggle() }
+ let store = store, url = url
+ let rowsSpec: [(String, String, String, Bool, () -> Void)] = [
+ ("hammer.fill", "Developer Mode", developer ? "On" : "Off", developer, { store.settings.toggleDeveloperMode(url: url) }),
+ ("shield.fill", "Block Ads & Trackers", store.settings.blockAdsAndTrackers ? "On" : "Off",
+ store.settings.blockAdsAndTrackers, { store.settings.blockAdsAndTrackers.toggle() }),
+ ("gearshape.fill", "Automatic Picture-In-Picture", store.settings.autoPictureInPicture ? "Allowed" : "Disabled",
+ store.settings.autoPictureInPicture, { store.settings.autoPictureInPicture.toggle() }),
+ ]
+ for (i, r) in rowsSpec.enumerated() {
+ let row = SiteSettingRow(symbol: r.0, title: r.1, subtitle: r.2, active: r.3, colors: colors, action: r.4)
+ row.frame = NSRect(x: 0, y: 27 + CGFloat(i) * 43, width: 208, height: 33)
+ settings.addSubview(row)
}
- }
-
- private var footer: some View {
- HStack(spacing: 0) {
- HStack(spacing: 6) {
- Image(systemName: isSecure ? "lock.fill" : "lock.open.fill").font(.system(size: 12, weight: .semibold))
- Text(isSecure ? "Secure" : "Not Secure").font(.system(size: 14, weight: .semibold))
- }
- .foregroundStyle(colors.text)
- .padding(.horizontal, 10)
- .frame(height: 32)
- .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(colors.footerFill))
- .arcTooltip(isSecure ? "Your connection to this site is secure" : "Your connection to this site is not secure")
- Spacer(minLength: 0)
- SiteControlCenterMoreButton(colors: colors, actions: actions)
+ let setH = 27 + 3 * 33 + 2 * 10
+ settings.frame = NSRect(x: x, y: y, width: w, height: CGFloat(setH))
+ addSubview(settings)
+ y += CGFloat(setH) + 13
+ let divider = NSView(frame: NSRect(x: x, y: y, width: w, height: 1))
+ divider.wantsLayer = true
+ divider.layer?.backgroundColor = colors.divider.cgColor
+ addSubview(divider)
+ y += 1 + 12
+ // Footer: the connection state, the More menu.
+ let secure = SiteSecurityPill(secure: isSecure, colors: colors)
+ secure.frame.origin = NSPoint(x: x, y: y)
+ addSubview(secure)
+ let more = SiteMoreButton(colors: colors, actions: actions)
+ more.frame = NSRect(x: x + w - 32, y: y, width: 32, height: 32)
+ addSubview(more)
+ y += 32 + M.inset
+ let size = NSSize(width: M.width, height: y)
+ if frame.size != size {
+ setFrameSize(size)
+ onResize(size)
}
}
}
@@ -125,219 +155,366 @@ struct SiteControlCenterView: View {
/// Arc's site control center palette (dark values sampled from Arc 1.170; light ones mirror them).
struct SiteControlCenterColors {
let dark: Bool
- var background: Color { dark ? Color(hex: "#272728") : Color(hex: "#F4F4F5") }
- var tile: Color { dark ? .white.opacity(0.07) : .black.opacity(0.05) }
- var tileHover: Color { dark ? .white.opacity(0.09) : .black.opacity(0.08) }
- var text: Color { dark ? Color(hex: "#DCDCDC") : Color(hex: "#232325") }
- var header: Color { dark ? Color(hex: "#D4D4D5") : Color(hex: "#2A2A2C") }
- var secondary: Color { dark ? Color(hex: "#979798") : Color(hex: "#6E6E73") }
- var divider: Color { dark ? .white.opacity(0.1) : .black.opacity(0.1) }
- var footerFill: Color { dark ? Color(hex: "#363536") : .black.opacity(0.05) }
- var moreFill: Color { dark ? Color(hex: "#403F40") : .black.opacity(0.08) }
+ var background: NSColor { dark ? NSColor(hex: "#272728") : NSColor(hex: "#F4F4F5") }
+ var tile: NSColor { dark ? .white.withAlphaComponent(0.07) : .black.withAlphaComponent(0.05) }
+ var tileHover: NSColor { dark ? .white.withAlphaComponent(0.09) : .black.withAlphaComponent(0.08) }
+ var text: NSColor { dark ? NSColor(hex: "#DCDCDC") : NSColor(hex: "#232325") }
+ var header: NSColor { dark ? NSColor(hex: "#D4D4D5") : NSColor(hex: "#2A2A2C") }
+ var secondary: NSColor { dark ? NSColor(hex: "#979798") : NSColor(hex: "#6E6E73") }
+ var divider: NSColor { dark ? .white.withAlphaComponent(0.1) : .black.withAlphaComponent(0.1) }
+ var footerFill: NSColor { dark ? NSColor(hex: "#363536") : .black.withAlphaComponent(0.05) }
+ var moreFill: NSColor { dark ? NSColor(hex: "#403F40") : .black.withAlphaComponent(0.08) }
/// Pinned badge and active setting circles.
/// Light themes invert Arc's dark-theme pair: a near-white badge vanishes on light tiles.
- var accent: Color { dark ? Color(hex: "#F0F1FE") : Color(hex: "#232325") }
- var inactive: Color { dark ? Color(hex: "#6A6A6F") : Color(hex: "#C7C7CC") }
- var pinHover: Color { dark ? Color(hex: "#7F7E85") : Color(hex: "#8E8E93") }
- var glyphOnAccent: Color { dark ? Color(hex: "#232325") : .white }
- var glyphOnInactive: Color { dark ? Color(hex: "#232325") : Color(hex: "#3A3A3C") }
+ var accent: NSColor { dark ? NSColor(hex: "#F0F1FE") : NSColor(hex: "#232325") }
+ var inactive: NSColor { dark ? NSColor(hex: "#6A6A6F") : NSColor(hex: "#C7C7CC") }
+ var pinHover: NSColor { dark ? NSColor(hex: "#7F7E85") : NSColor(hex: "#8E8E93") }
+ var glyphOnAccent: NSColor { dark ? NSColor(hex: "#232325") : .white }
+ var glyphOnInactive: NSColor { dark ? NSColor(hex: "#232325") : NSColor(hex: "#3A3A3C") }
/// The pin glyph: cut out of the badge in the panel colour (dark), white on light themes.
- var pinGlyph: Color { dark ? background : .white }
- func actionFill(hovered: Bool) -> [Color] {
- dark ? [Color(hex: hovered ? "#3C3C3C" : "#363636"), Color(hex: hovered ? "#272727" : "#212121")]
- : [Color(hex: hovered ? "#FFFFFF" : "#FDFDFD"), Color(hex: hovered ? "#F2F2F2" : "#EDEDED")]
+ var pinGlyph: NSColor { dark ? background : .white }
+ func actionFill(hovered: Bool) -> [NSColor] {
+ dark ? [NSColor(hex: hovered ? "#3C3C3C" : "#363636"), NSColor(hex: hovered ? "#272727" : "#212121")]
+ : [NSColor(hex: hovered ? "#FFFFFF" : "#FDFDFD"), NSColor(hex: hovered ? "#F2F2F2" : "#EDEDED")]
}
- var actionHighlight: Color { dark ? Color(hex: "#69696A") : .white }
- var actionOutline: Color { dark ? Color(hex: "#141115") : .black.opacity(0.14) }
+ var actionHighlight: NSColor { dark ? NSColor(hex: "#69696A") : .white }
+ var actionOutline: NSColor { dark ? NSColor(hex: "#141115") : .black.withAlphaComponent(0.14) }
}
-/// A titled section; hovering it shows `hoverText` at the header's right end (Arc: "Manage").
-private struct SiteControlCenterSection<Content: View>: View {
- let title: String
- let hoverText: String?
- let colors: SiteControlCenterColors
- let onHeaderClick: () -> Void
- @ViewBuilder let content: Content
- @State private var hovered = false
-
- var body: some View {
- VStack(alignment: .leading, spacing: 10) {
- HStack(spacing: 0) {
- Text(title).font(.system(size: 14, weight: .bold)).foregroundStyle(colors.header)
- Spacer(minLength: 0)
- if let hoverText, hovered {
- Button(action: onHeaderClick) {
- Text(hoverText).font(.system(size: 12, weight: .semibold)).foregroundStyle(colors.secondary)
- }
- .buttonStyle(.plain)
- }
- }
- .frame(height: 17)
- content
- }
- .contentShape(Rectangle())
- .onHover { hovered = $0 }
+/// A view that tracks the pointer and acts on release, the base of the popover's controls.
+private class SiteHoverView: NSView {
+ var hovered = false { didSet { if hovered != oldValue { refresh(); onHover() } } }
+ var onClick: () -> Void = {}
+ var onHover: () -> Void = {}
+
+ override var isFlipped: Bool { true }
+
+ func refresh() {}
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovered = true }
+ override func mouseExited(with event: NSEvent) { hovered = false }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { onClick() }
}
}
-private struct SiteControlCenterTile<Label: View>: View {
- let colors: SiteControlCenterColors
- var help: String = ""
- let action: () -> Void
- @ViewBuilder let label: Label
- @State private var hovered = false
-
- var body: some View {
- Button(action: action) {
- label
- .frame(width: SiteControlCenterMetrics.tile.width, height: SiteControlCenterMetrics.tile.height)
- .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(hovered ? colors.tileHover : colors.tile))
- .contentShape(Rectangle())
+/// A titled section; hovering it shows `hoverText` at the header's right end (Arc: "Manage").
+private final class SiteSectionView: SiteHoverView {
+ private let manage: NSTextField?
+ private let onHeaderClick: () -> Void
+
+ init(title: String, hoverText: String?, colors: SiteControlCenterColors, onHeaderClick: @escaping () -> Void) {
+ self.onHeaderClick = onHeaderClick
+ manage = hoverText.map { t in
+ let l = NSTextField.sidebarLabel(size: 12, weight: .semibold)
+ l.stringValue = t
+ l.textColor = colors.secondary
+ l.alignment = .right
+ return l
+ }
+ super.init(frame: .zero)
+ let label = NSTextField.sidebarLabel(size: 14, weight: .bold)
+ label.stringValue = title
+ label.textColor = colors.header
+ label.frame = NSRect(x: -SidebarText.inset, y: 0, width: 200, height: 17)
+ addSubview(label)
+ if let manage {
+ manage.isHidden = true
+ addSubview(manage)
}
- .buttonStyle(.plain)
- .onHover { hovered = $0 }
- .arcTooltip(help)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func refresh() { manage?.isHidden = !hovered }
+
+ override func layout() {
+ super.layout()
+ manage?.frame = NSRect(x: bounds.width - 80 + SidebarText.inset, y: 1, width: 80, height: 15)
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ guard let manage, !manage.isHidden, manage.frame.contains(convert(event.locationInWindow, from: nil)) else { return }
+ onHeaderClick()
}
}
-private struct SiteControlCenterActionButton: View {
- let symbol: String
- let help: String
+private class SiteTile: SiteHoverView {
let colors: SiteControlCenterColors
- let action: () -> Void
-
- @State private var hovered = false
-
- /// Arc draws these raised: a top-lit gradient, a light top edge and a dark outline.
- var body: some View {
- let shape = RoundedRectangle(cornerRadius: 7, style: .continuous)
- Button(action: action) {
- Image(systemName: symbol).font(.system(size: 15, weight: .regular)).foregroundStyle(colors.text)
- .frame(width: SiteControlCenterMetrics.tile.width, height: SiteControlCenterMetrics.tile.height)
- .background(shape.fill(LinearGradient(colors: colors.actionFill(hovered: hovered), startPoint: .top, endPoint: .bottom)))
- .overlay(shape.inset(by: 0.5).stroke(LinearGradient(colors: [colors.actionHighlight, .clear], startPoint: .top, endPoint: .center), lineWidth: 1))
- .overlay(shape.stroke(colors.actionOutline, lineWidth: 0.5))
- .contentShape(Rectangle())
+ private let glyph = NSImageView()
+
+ init(colors: SiteControlCenterColors, help: String, action: @escaping () -> Void) {
+ self.colors = colors
+ super.init(frame: .zero)
+ onClick = action
+ wantsLayer = true
+ layer?.cornerRadius = 7
+ layer?.cornerCurve = .continuous
+ glyph.imageScaling = .scaleProportionallyDown
+ addSubview(glyph)
+ if !help.isEmpty { _ = ArcTooltipAnchorView.attach(to: self, help: help) }
+ refresh()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func setGlyph(_ image: NSImage?, tint: NSColor?, size: CGFloat? = nil) {
+ glyph.image = image
+ glyph.contentTintColor = tint
+ glyph.imageScaling = size == nil ? .scaleNone : .scaleProportionallyUpOrDown
+ glyphSize = size
+ needsLayout = true
+ }
+
+ private var glyphSize: CGFloat?
+
+ override func refresh() { layer?.backgroundColor = (hovered ? colors.tileHover : colors.tile).cgColor }
+
+ override func layout() {
+ super.layout()
+ if let s = glyphSize {
+ glyph.frame = NSRect(x: (bounds.width - s) / 2, y: (bounds.height - s) / 2, width: s, height: s)
+ } else {
+ glyph.frame = bounds
}
- .buttonStyle(.plain)
- .onHover { hovered = $0 }
- .arcTooltip(help)
}
}
/// An extension tile: click runs it, the badge pins or unpins it (Arc's
/// SiteControlCenterExtensionPinButton, "Pin" / "Unpin").
-private struct SiteControlCenterExtensionButton: View {
- let entry: ExtensionStore.Entry
- let pinned: Bool
- let colors: SiteControlCenterColors
- let run: () -> Void
- let togglePin: () -> Void
- @State private var hovered = false
-
- var body: some View {
- ZStack(alignment: .topLeading) {
- Button(action: run) {
- Group {
- if let icon = entry.icon {
- Image(nsImage: icon).resizable().interpolation(.high).frame(width: 16, height: 16)
- } else {
- Image(systemName: "puzzlepiece.extension.fill").font(.system(size: 13)).foregroundStyle(colors.secondary)
- }
- }
- .frame(width: SiteControlCenterMetrics.tile.width, height: SiteControlCenterMetrics.tile.height)
- .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(hovered ? colors.tileHover : colors.tile))
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .arcTooltip(entry.name)
- .accessibilityLabel(entry.name)
- if pinned || hovered {
- Button(action: togglePin) {
- Image(systemName: "pin.fill")
- .font(.system(size: 8, weight: .bold))
- .rotationEffect(.degrees(45))
- .foregroundStyle(colors.pinGlyph)
- .frame(width: 14, height: 14)
- .background(Circle().fill(pinned ? colors.accent : colors.pinHover))
- .overlay(Circle().strokeBorder(colors.background, lineWidth: 1))
- .contentShape(Circle())
- }
- .buttonStyle(.plain)
- .arcTooltip(pinned ? "Unpin" : "Pin")
- .accessibilityLabel(pinned ? "Unpin" : "Pin")
- .offset(x: 37, y: 21)
- }
+private final class SiteExtensionTile: SiteTile {
+ private let pinned: Bool
+ /// The 14 pt pin badge hangs off the tile's bottom-right corner, 37 × 21 pt in. It sits
+ /// next to the tile in the grid, above it, so nothing clips it (SwiftUI's .offset).
+ let badge = SiteHoverView()
+ private let pinGlyph = NSImageView()
+
+ init(entry: ExtensionStore.Entry, pinned: Bool, colors: SiteControlCenterColors, run: @escaping () -> Void, togglePin: @escaping () -> Void) {
+ self.pinned = pinned
+ super.init(colors: colors, help: entry.name, action: run)
+ if let icon = entry.icon {
+ setGlyph(icon, tint: nil, size: 16)
+ } else {
+ setGlyph(SidebarSymbols.image("puzzlepiece.extension.fill", size: 13), tint: colors.secondary)
}
- .frame(width: SiteControlCenterMetrics.tile.width, height: SiteControlCenterMetrics.tile.height, alignment: .topLeading)
- .onHover { hovered = $0 }
+ setAccessibilityLabel(entry.name)
+ badge.onClick = togglePin
+ badge.onHover = { [weak self] in self?.refresh() }
+ pinGlyph.image = Self.badgeImage(fill: pinned ? colors.accent : colors.pinHover, ring: colors.background, glyph: colors.pinGlyph)
+ pinGlyph.imageScaling = .scaleNone
+ pinGlyph.frame = NSRect(x: 0, y: 0, width: 14, height: 14)
+ badge.addSubview(pinGlyph)
+ _ = ArcTooltipAnchorView.attach(to: badge, help: pinned ? "Unpin" : "Pin")
+ badge.setAccessibilityLabel(pinned ? "Unpin" : "Pin")
+ refresh()
}
-}
-private struct SiteControlCenterSettingRow: View {
- let symbol: String
- let title: String
- let subtitle: String
- let active: Bool
- let colors: SiteControlCenterColors
- let action: () -> Void
- @State private var hovered = false
-
- var body: some View {
- Button(action: action) {
- HStack(spacing: 8) {
- Image(systemName: symbol)
- .font(.system(size: 13, weight: .semibold))
- .foregroundStyle(active ? colors.glyphOnAccent : colors.glyphOnInactive)
- .frame(width: 32, height: 32)
- .background(Circle().fill(active ? colors.accent : colors.inactive))
- VStack(alignment: .leading, spacing: 0) {
- Text(title).font(.system(size: 14, weight: .semibold)).foregroundStyle(colors.text)
- .lineLimit(1).truncationMode(.tail)
- Text(subtitle).font(.system(size: 13)).foregroundStyle(colors.secondary)
- }
- Spacer(minLength: 0)
- }
- .frame(width: 208, height: 33, alignment: .leading)
- .contentShape(Rectangle())
- .opacity(hovered ? 0.85 : 1)
+ required init?(coder: NSCoder) { fatalError() }
+
+ /// The badge as one image: the circle, a 1 pt ring in the panel colour inside its edge, and
+ /// the pin turned 45° clockwise.
+ private static func badgeImage(fill: NSColor, ring: NSColor, glyph: NSColor) -> NSImage {
+ NSImage(size: NSSize(width: 14, height: 14), flipped: false) { r in
+ fill.setFill()
+ NSBezierPath(ovalIn: r).fill()
+ ring.setStroke()
+ let edge = NSBezierPath(ovalIn: r.insetBy(dx: 0.5, dy: 0.5))
+ edge.lineWidth = 1
+ edge.stroke()
+ guard let pin = NSImage(systemSymbolName: "pin.fill", accessibilityDescription: nil)?
+ .withSymbolConfiguration(.init(pointSize: 8, weight: .bold).applying(.init(paletteColors: [glyph]))) else { return true }
+ let t = NSAffineTransform()
+ t.translateX(by: r.midX, yBy: r.midY)
+ t.rotate(byDegrees: -45)
+ t.concat()
+ pin.draw(in: NSRect(x: -pin.size.width / 2, y: -pin.size.height / 2, width: pin.size.width, height: pin.size.height))
+ return true
}
- .buttonStyle(.plain)
- .onHover { hovered = $0 }
- .accessibilityLabel("\(title), \(subtitle)")
+ }
+
+ override func setFrameOrigin(_ newOrigin: NSPoint) {
+ super.setFrameOrigin(newOrigin)
+ badge.frame = NSRect(x: newOrigin.x + 37, y: newOrigin.y + 21, width: 14, height: 14)
+ }
+
+ override func refresh() {
+ super.refresh()
+ badge.isHidden = !(pinned || hovered || badge.hovered)
}
}
+/// Arc draws these raised: a top-lit gradient, a light top edge and a dark outline.
+private final class SiteActionButton: SiteHoverView {
+ private let colors: SiteControlCenterColors
+ private let fill = CAGradientLayer()
+ private let highlight = CAGradientLayer()
+ private let highlightMask = CAShapeLayer()
+ private let outline = CAShapeLayer()
+ private let glyph = NSImageView()
+
+ init(symbol: String, help: String, colors: SiteControlCenterColors, action: @escaping () -> Void) {
+ self.colors = colors
+ super.init(frame: .zero)
+ onClick = action
+ wantsLayer = true
+ fill.cornerRadius = 7
+ fill.cornerCurve = .continuous
+ fill.masksToBounds = true
+ layer?.addSublayer(fill)
+ highlight.colors = [colors.actionHighlight.cgColor, colors.actionHighlight.withAlphaComponent(0).cgColor]
+ highlight.locations = [0, 1]
+ highlightMask.fillColor = nil
+ highlightMask.strokeColor = NSColor.black.cgColor
+ highlightMask.lineWidth = 1
+ highlight.mask = highlightMask
+ layer?.addSublayer(highlight)
+ outline.fillColor = nil
+ outline.strokeColor = colors.actionOutline.cgColor
+ outline.lineWidth = 0.5
+ layer?.addSublayer(outline)
+ glyph.image = SidebarSymbols.image(symbol, size: 15)
+ glyph.contentTintColor = colors.text
+ glyph.imageScaling = .scaleNone
+ addSubview(glyph)
+ _ = ArcTooltipAnchorView.attach(to: self, help: help)
+ refresh()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func refresh() {
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ fill.colors = colors.actionFill(hovered: hovered).map(\.cgColor)
+ CATransaction.commit()
+ }
+
+ override func layout() {
+ super.layout()
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ fill.frame = bounds
+ // Flipped: the fill and highlight run from the top (y 0) down.
+ fill.startPoint = CGPoint(x: 0.5, y: 0)
+ fill.endPoint = CGPoint(x: 0.5, y: 1)
+ highlight.frame = bounds
+ highlight.startPoint = CGPoint(x: 0.5, y: 0)
+ highlight.endPoint = CGPoint(x: 0.5, y: 0.5)
+ highlightMask.path = CGPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), cornerWidth: 6.5, cornerHeight: 6.5, transform: nil)
+ outline.path = CGPath(roundedRect: bounds, cornerWidth: 7, cornerHeight: 7, transform: nil)
+ CATransaction.commit()
+ glyph.frame = bounds
+ }
+}
+
+private final class SiteSettingRow: SiteHoverView {
+ init(symbol: String, title: String, subtitle: String, active: Bool, colors: SiteControlCenterColors, action: @escaping () -> Void) {
+ super.init(frame: .zero)
+ onClick = action
+ wantsLayer = true
+ let circle = NSView(frame: NSRect(x: 0, y: 0.5, width: 32, height: 32))
+ circle.wantsLayer = true
+ circle.layer?.cornerRadius = 16
+ circle.layer?.backgroundColor = (active ? colors.accent : colors.inactive).cgColor
+ let glyph = NSImageView(frame: circle.bounds)
+ glyph.image = SidebarSymbols.image(symbol, size: 13, weight: .semibold)
+ glyph.contentTintColor = active ? colors.glyphOnAccent : colors.glyphOnInactive
+ glyph.imageScaling = .scaleNone
+ circle.addSubview(glyph)
+ addSubview(circle)
+ // VStack(spacing: 0) of 17 + 16, 8 pt after the circle and 8 pt before the Spacer.
+ let t = NSTextField.sidebarLabel(size: 14, weight: .semibold)
+ t.stringValue = title
+ t.textColor = colors.text
+ t.frame = NSRect(x: 40 - SidebarText.inset, y: 0, width: 160 + 2 * SidebarText.inset, height: 17)
+ addSubview(t)
+ let s = NSTextField.sidebarLabel(size: 13)
+ s.stringValue = subtitle
+ s.textColor = colors.secondary
+ s.frame = NSRect(x: 40 - SidebarText.inset, y: 17, width: 160 + 2 * SidebarText.inset, height: 16)
+ addSubview(s)
+ setAccessibilityLabel("\(title), \(subtitle)")
+ setAccessibilityRole(.button)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func refresh() { alphaValue = hovered ? 0.85 : 1 }
+}
+
+private final class SiteSecurityPill: NSView {
+ init(secure: Bool, colors: SiteControlCenterColors) {
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = 8
+ layer?.cornerCurve = .continuous
+ layer?.backgroundColor = colors.footerFill.cgColor
+ let lock = NSImageView()
+ lock.image = SidebarSymbols.image(secure ? "lock.fill" : "lock.open.fill", size: 12, weight: .semibold)
+ lock.contentTintColor = colors.text
+ lock.imageScaling = .scaleNone
+ let label = NSTextField.sidebarLabel(size: 14, weight: .semibold)
+ label.stringValue = secure ? "Secure" : "Not Secure"
+ label.textColor = colors.text
+ let lw = lock.image?.size.width ?? 10
+ let tw = ceil(label.attributedStringValue.size().width)
+ setFrameSize(NSSize(width: 10 + lw + 6 + tw + 10, height: 32))
+ lock.frame = NSRect(x: 10, y: 0, width: lw, height: 32)
+ label.frame = NSRect(x: 10 + lw + 6 - SidebarText.inset, y: (32 - 17) / 2, width: tw + 2 * SidebarText.inset, height: 17)
+ addSubview(lock)
+ addSubview(label)
+ _ = ArcTooltipAnchorView.attach(to: self, help: secure ? "Your connection to this site is secure" : "Your connection to this site is not secure")
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+}
+
/// Arc's footer "…": Clear Cache, Clear Cookies, Manage Extensions, Add Extension, All Site Settings.
-private struct SiteControlCenterMoreButton: View {
- let colors: SiteControlCenterColors
- let actions: SiteControlCenterActions
- @State private var hovered = false
-
- var body: some View {
- Button(action: showMenu) {
- Image(systemName: "ellipsis").font(.system(size: 13, weight: .bold)).foregroundStyle(colors.text)
- .frame(width: 32, height: 32)
- .background(Circle().fill(colors.moreFill).brightness(hovered ? 0.04 : 0))
- .contentShape(Circle())
+private final class SiteMoreButton: SiteHoverView {
+ private let colors: SiteControlCenterColors
+
+ init(colors: SiteControlCenterColors, actions: SiteControlCenterActions) {
+ self.colors = colors
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = 16
+ let glyph = NSImageView(frame: NSRect(x: 0, y: 0, width: 32, height: 32))
+ glyph.image = SidebarSymbols.image("ellipsis", size: 13, weight: .bold)
+ glyph.contentTintColor = colors.text
+ glyph.imageScaling = .scaleNone
+ addSubview(glyph)
+ _ = ArcTooltipAnchorView.attach(to: self, help: "More")
+ setAccessibilityLabel("More")
+ setAccessibilityRole(.button)
+ onClick = {
+ let menu = NSMenu()
+ func add(_ title: String, _ action: @escaping () -> Void) { menu.addItem(BlockMenuItem(title: title, action: action)) }
+ add("Clear Cache", actions.clearCache)
+ add("Clear Cookies", actions.clearCookies)
+ menu.addItem(.separator())
+ add("Manage Extensions", actions.manageExtensions)
+ add("Add Extension", actions.addExtension)
+ menu.addItem(.separator())
+ add("All Site Settings", actions.siteSettings)
+ menu.popUp(positioning: nil, at: NSEvent.mouseLocation, in: nil)
}
- .buttonStyle(.plain)
- .onHover { hovered = $0 }
- .arcTooltip("More")
- .accessibilityLabel("More")
+ refresh()
}
- private func showMenu() {
- let menu = NSMenu()
- func add(_ title: String, _ action: @escaping () -> Void) { menu.addItem(BlockMenuItem(title: title, action: action)) }
- add("Clear Cache", actions.clearCache)
- add("Clear Cookies", actions.clearCookies)
- menu.addItem(.separator())
- add("Manage Extensions", actions.manageExtensions)
- add("Add Extension", actions.addExtension)
- menu.addItem(.separator())
- add("All Site Settings", actions.siteSettings)
- menu.popUp(positioning: nil, at: NSEvent.mouseLocation, in: nil)
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func refresh() {
+ // SwiftUI's .brightness(0.04) on hover.
+ let c = colors.moreFill.usingColorSpace(.sRGB) ?? colors.moreFill
+ layer?.backgroundColor = (hovered ? NSColor(srgbRed: min(1, c.redComponent + 0.04), green: min(1, c.greenComponent + 0.04),
+ blue: min(1, c.blueComponent + 0.04), alpha: c.alphaComponent) : c).cgColor
}
}
@@ -379,11 +556,11 @@ final class SiteControlCenterPopover: NSObject, NSPopoverDelegate {
acts.siteSettings = closing(actions.siteSettings)
acts.clearCache = closing(actions.clearCache)
acts.clearCookies = closing(actions.clearCookies)
- let root = SiteControlCenterView(url: url, dark: dark, actions: acts)
- .environment(store)
- .background(SiteControlCenterColors(dark: dark).background)
- let host = NSHostingController(rootView: AnyView(root))
- host.sizingOptions = [.preferredContentSize]
+ let content = SiteControlCenterView(url: url, dark: dark, actions: acts, store: store)
+ let host = NSViewController()
+ host.view = content
+ host.preferredContentSize = content.frame.size
+ content.onResize = { [weak host] in host?.preferredContentSize = $0 }
p.contentViewController = host
popover = p
p.show(relativeTo: rect, of: view, preferredEdge: .minY)
diff --git a/Sources/Cra/UI/SplitView/PaneCardView.swift b/Sources/Cra/UI/SplitView/PaneCardView.swift
index 6051acc..66c4370 100644
--- a/Sources/Cra/UI/SplitView/PaneCardView.swift
+++ b/Sources/Cra/UI/SplitView/PaneCardView.swift
@@ -7,9 +7,8 @@ import SwiftUI
/// tinted card with nothing but the toolbar.
final class PaneCardView: NSView {
private(set) var tabID: UUID
- let toolbarHost: NSHostingView<AnyView>
- /// The theme the toolbar's root view was made with: it is rebuilt only when that changes.
- var toolbarTheme: SpaceTheme?
+ /// The pane's toolbar (PaneToolbarView); it follows the card's tab itself.
+ let toolbarHost: NSView
/// Where the Chromium view lives (or where the page window is positioned).
let webArea = NSView()
/// Hairline under the toolbar when the pane has no page (Arc draws it on the tinted card).
@@ -49,26 +48,25 @@ final class PaneCardView: NSView {
var showsElsewhere = false { didSet { elsewhereView.isHidden = !showsElsewhere } }
private let elsewhereView = NSView()
- /// The card shows another tab now (a tab switch with one pane before and after). Building
- /// a new card made a new SwiftUI toolbar host on every switch.
- func retarget(to id: UUID, toolbar: AnyView) {
+ /// The card shows another tab now (a tab switch with one pane before and after): the same
+ /// card and toolbar follow it.
+ func retarget(to id: UUID) {
tabID = id
- toolbarHost.rootView = toolbar
+ (toolbarHost as? PaneToolbarView)?.paneTabID = id == ShellView.noTabID ? nil : id
frozenWebBounds = nil
showsElsewhere = false
elsewhereSnapshot = nil
needsLayout = true
}
- init(tabID: UUID, toolbar: AnyView) {
+ init(tabID: UUID, toolbar: NSView) {
self.tabID = tabID
- toolbarHost = NSHostingView(rootView: toolbar)
+ toolbarHost = toolbar
super.init(frame: .zero)
wantsLayer = true
layer?.cornerRadius = cornerRadius
layer?.cornerCurve = .continuous
layer?.masksToBounds = true
- toolbarHost.sizingOptions = []
webArea.wantsLayer = true
webArea.autoresizesSubviews = false
pageBackground.wantsLayer = true
diff --git a/Sources/Cra/UI/SplitView/SplitRow.swift b/Sources/Cra/UI/SplitView/SplitRow.swift
deleted file mode 100644
index 4b1ba5d..0000000
--- a/Sources/Cra/UI/SplitView/SplitRow.swift
+++ /dev/null
@@ -1,111 +0,0 @@
-import SwiftUI
-
-/// Arc's sidebar cell for a split (SplitViewCellView): one row holding the
-/// panes side by side, each with favicon + title and its own close button,
-/// hairlines between them; the whole row highlights when the split is shown.
-struct SplitRow: View {
- let item: SidebarItem
- let depth: Int
- let palette: SpacePalette
- let section: SidebarSection
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var hover = false
-
- private var children: [SidebarItem] { store.children(of: item.id).filter { $0.isTab } }
- private var selected: Bool { children.contains { store.isSelected($0.id, window: ui.windowID) } }
-
- enum Metrics {
- static let separatorInset: CGFloat = 9
- }
-
- var body: some View {
- HStack(spacing: 0) {
- ForEach(Array(children.enumerated()), id: \.element.id) { i, child in
- if i > 0 {
- Rectangle().fill(palette.separator).frame(width: 1).padding(.vertical, Metrics.separatorInset)
- }
- SplitChildCell(item: child, palette: palette, groupHovered: hover, groupSelected: selected, focused: store.isSelected(child.id, window: ui.windowID))
- }
- }
- .padding(.leading, CGFloat(depth) * CraMetrics.indent)
- .frame(height: CraMetrics.rowHeight)
- .background(
- RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)
- .fill(selected ? palette.selectedFill : (hover ? palette.hoverFill : .clear))
- .shadow(color: selected && !palette.isDark ? .black.opacity(0.06) : .clear, radius: 3, y: 1)
- )
- .overlay { if let f = ui.keyboardFocusID, children.contains(where: { $0.id == f }) { FocusRing(radius: CraMetrics.rowCorner) } }
- .contentShape(Rectangle())
- .onHover { hover = $0 }
- .contextMenu {
- Button("Separate All Tabs") { store.separateAll(item.id) }
- Button(item.split?.orientation == .vertical ? "Convert to Horizontal Split View" : "Convert to Vertical Split View") { store.flipSplitOrientation(item.id) }
- Button("Add Pane") { if let first = children.first { actions.focusPane(first.id); actions.performAction("addSplitView") } }
- Divider()
- Button("Rename…") { ui.renamingID = item.id }
- Divider()
- Button(section == .today ? "Archive All" : "Close All") { for c in children { actions.closeTab(c.id) } }
- }
- .modifier(SidebarDropPreview(id: item.id, palette: palette))
- }
-}
-
-/// One pane inside the split row (Arc: SplitViewCellChildItemView).
-struct SplitChildCell: View {
- let item: SidebarItem
- let palette: SpacePalette
- let groupHovered: Bool
- let groupSelected: Bool
- let focused: Bool
- @Environment(SidebarStore.self) private var store
- @Environment(SidebarUIState.self) private var ui
- @Environment(\.sidebarActions) private var actions
- @State private var hover = false
-
- var body: some View {
- let session = ui
- HStack(spacing: 8) {
- FaviconView(key: item.tab?.iconKey, palette: palette)
- .frame(width: CraMetrics.favicon)
- Text(item.displayTitle)
- .font(.system(size: 14))
- .foregroundStyle(palette.textPrimary)
- .lineLimit(1)
- .truncationMode(.tail)
- Spacer(minLength: 2)
- if hover {
- SidebarIconButton(symbol: "xmark", palette: palette, help: "Close pane", optionHelp: "Separate from Split View", size: 20, iconSize: 11) {
- // Option-click un-splits instead of closing (Arc flag option-click-split-tab-close-button-to-unsplit).
- if NSEvent.modifierFlags.contains(.option) { store.separateFromSplit(item.id) } else { actions.closeTab(item.id) }
- }
- .transition(.opacity)
- }
- }
- .padding(.leading, 8)
- .padding(.trailing, 4)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .contentShape(Rectangle())
- .onHover { hover = $0; ui.hoverDraggable(item.id, $0) }
- .onTapGesture { store.selectTab(item.id, window: ui.windowID) }
- .draggable(SidebarDragItem.begin(item.id, session)) {
- HStack(spacing: 8) {
- FaviconView(key: item.tab?.iconKey, palette: palette)
- Text(item.displayTitle).font(.system(size: 14)).lineLimit(1)
- }
- .padding(8)
- .background(RoundedRectangle(cornerRadius: 8).fill(.regularMaterial))
- }
- .contextMenu {
- Button("Separate Tab from Split") { store.separateFromSplit(item.id) }
- Button("Copy Link") {
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(item.tab?.url ?? "", forType: .string)
- }
- Divider()
- Button("Close") { actions.closeTab(item.id) }
- }
- .arcTooltip(item.displayTitle, followsCursor: true)
- }
-}
diff --git a/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift b/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift
index 609714d..e129459 100644
--- a/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift
+++ b/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift
@@ -69,6 +69,15 @@ final class TabSwitcher {
DispatchQueue.main.asyncAfter(deadline: .now() + TabSwitcherMetrics.showDelay, execute: work)
}
+ /// Testing: open on the second card without a held key.
+ func debugOpen(_ list: [Item]) {
+ guard list.count > 1 else { return }
+ items = list
+ selectedIndex = 1
+ isOpen = true
+ onShow()
+ }
+
func move(_ delta: Int) {
guard !items.isEmpty else { return }
let n = items.count
diff --git a/Sources/Cra/UI/TabSwitcher/TabSwitcherView.swift b/Sources/Cra/UI/TabSwitcher/TabSwitcherView.swift
index 32d63e0..004f7a1 100644
--- a/Sources/Cra/UI/TabSwitcher/TabSwitcherView.swift
+++ b/Sources/Cra/UI/TabSwitcher/TabSwitcherView.swift
@@ -31,103 +31,203 @@ enum TabSwitcherMetrics {
}
}
-struct TabSwitcherView: View {
- let switcher: TabSwitcher
+/// The switcher panel: a dark rounded slab of cards, each a page thumbnail over its favicon
+/// and title, the selected one on the space's highlight.
+@MainActor
+final class TabSwitcherView: NSView {
private typealias M = TabSwitcherMetrics
+ private let switcher: TabSwitcher
+ private let favicons: FaviconCache
+ private let panel = NSView()
+ private let innerLine = CALayer()
+ private var cards: [TabSwitcherCardView] = []
- var body: some View {
- let dark = switcher.isDark
- let shape = RoundedRectangle(cornerRadius: M.cornerRadius, style: .continuous)
- HStack(spacing: M.cardSpacing) {
- ForEach(Array(switcher.items.enumerated()), id: \.element.id) { i, item in
- card(item, selected: i == switcher.selectedIndex, dark: dark)
- .contentShape(Rectangle())
- .onContinuousHover { phase in
- if case .active = phase { switcher.hover(i) }
- }
- .onTapGesture { switcher.click(i) }
- }
+ init(switcher: TabSwitcher, favicons: FaviconCache) {
+ self.switcher = switcher
+ self.favicons = favicons
+ super.init(frame: .zero)
+ wantsLayer = true
+ panel.wantsLayer = true
+ if let l = panel.layer {
+ l.cornerRadius = M.cornerRadius
+ l.cornerCurve = .continuous
+ l.borderWidth = 1
+ l.shadowColor = NSColor.black.cgColor
+ l.shadowRadius = 24
+ l.shadowOffset = CGSize(width: 0, height: -10)
+ innerLine.borderWidth = 1
+ innerLine.cornerRadius = M.cornerRadius - 1
+ innerLine.cornerCurve = .continuous
+ l.addSublayer(innerLine)
}
- .padding(.horizontal, M.paddingH)
- .padding(.vertical, M.paddingV)
- // Arc: #1C1B1A inside a near-black outer line and a 23% white inner line.
- .background(shape.fill(dark ? Color(red: 28 / 255, green: 27 / 255, blue: 26 / 255) : Color(white: 0.97)))
- .overlay(shape.inset(by: 1).strokeBorder(dark ? Color.white.opacity(0.23) : Color.white.opacity(0.8), lineWidth: 1))
- .overlay(shape.strokeBorder(dark ? Color.black.opacity(0.92) : Color.black.opacity(0.12), lineWidth: 1))
- .shadow(color: .black.opacity(dark ? 0.3 : 0.18), radius: 24, y: 10)
- .padding(M.shadowMargin)
- .environment(\.colorScheme, dark ? .dark : .light)
+ addSubview(panel)
+ observe()
}
- private func card(_ item: TabSwitcher.Item, selected: Bool, dark: Bool) -> some View {
- VStack(alignment: .leading, spacing: 0) {
- thumbnail(item, dark: dark)
- .frame(width: M.thumbnail.width, height: M.thumbnail.height)
- .clipShape(RoundedRectangle(cornerRadius: M.thumbnailCornerRadius, style: .continuous))
- .shadow(color: .black.opacity(dark ? 0.4 : 0.15), radius: 7, y: 3)
- .padding(.leading, M.thumbnailOrigin.x)
- .padding(.top, M.thumbnailOrigin.y)
- HStack(spacing: 8) {
- favicon(item, dark: dark)
- Text(item.title)
- // Arc's titles measure as SF 14 medium (ink width and cap height match).
- .font(.system(size: 14, weight: .medium))
- .foregroundStyle(dark ? Color.white : Color.black.opacity(0.85))
- .lineLimit(1)
- .truncationMode(.tail)
+ required init?(coder: NSCoder) { fatalError() }
+
+ private func observe() {
+ let (items, selected, dark, highlight) = withObservationTracking {
+ (switcher.items, switcher.selectedIndex, switcher.isDark, switcher.highlight)
+ } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ appearance = NSAppearance(named: dark ? .darkAqua : .aqua)
+ if let l = panel.layer {
+ // Arc: #1C1B1A inside a near-black outer line and a 23% white inner line.
+ l.backgroundColor = (dark ? NSColor(red: 28 / 255, green: 27 / 255, blue: 26 / 255, alpha: 1) : NSColor(white: 0.97, alpha: 1)).cgColor
+ l.borderColor = NSColor.black.withAlphaComponent(dark ? 0.92 : 0.12).cgColor
+ l.shadowOpacity = dark ? 0.3 : 0.18
+ innerLine.borderColor = NSColor.white.withAlphaComponent(dark ? 0.23 : 0.8).cgColor
+ }
+ while cards.count < items.count {
+ let c = TabSwitcherCardView()
+ c.onHover = { [weak self, weak c] in
+ guard let self, let c, let i = self.cards.firstIndex(where: { $0 === c }) else { return }
+ self.switcher.hover(i)
+ }
+ c.onClick = { [weak self, weak c] in
+ guard let self, let c, let i = self.cards.firstIndex(where: { $0 === c }) else { return }
+ self.switcher.click(i)
}
- .padding(.leading, 13.5)
- .padding(.trailing, 10.5)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ cards.append(c)
+ panel.addSubview(c)
}
- .frame(width: M.card.width, height: M.card.height, alignment: .topLeading)
- .background {
- if selected { RoundedRectangle(cornerRadius: M.cardCornerRadius, style: .continuous).fill(switcher.highlight) }
+ while cards.count > items.count { cards.removeLast().removeFromSuperview() }
+ let fill = NSColor(highlight)
+ for (i, (c, item)) in zip(cards, items).enumerated() {
+ let icon = item.iconKey.flatMap { favicons.image(forKey: $0) }
+ let flip = icon != nil && favicons.glyphIsDark(forKey: item.iconKey) == dark
+ c.show(item, icon: switcher.palette == nil ? nil : icon, flip: flip, selected: i == selected, highlight: fill, dark: dark)
}
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ let p = bounds.insetBy(dx: M.shadowMargin, dy: M.shadowMargin)
+ panel.frame = p
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ innerLine.frame = panel.bounds.insetBy(dx: 1, dy: 1)
+ CATransaction.commit()
+ for (i, c) in cards.enumerated() {
+ c.frame = NSRect(x: M.paddingH + CGFloat(i) * (M.card.width + M.cardSpacing), y: M.paddingV,
+ width: M.card.width, height: M.card.height)
+ }
+ }
+}
+
+private final class TabSwitcherCardView: NSView {
+ private typealias M = TabSwitcherMetrics
+ var onHover: () -> Void = {}
+ var onClick: () -> Void = {}
+ private let lift = CALayer()
+ private let thumb = CALayer()
+ private let favicon = NSImageView()
+ private let placeholder = NSView()
+ private let title = NSTextField.sidebarLabel(size: 14, weight: .medium)
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerRadius = M.cardCornerRadius
+ layer?.cornerCurve = .continuous
+ lift.shadowColor = NSColor.black.cgColor
+ lift.shadowRadius = 7
+ lift.shadowOffset = CGSize(width: 0, height: -3)
+ lift.cornerRadius = M.thumbnailCornerRadius
+ lift.cornerCurve = .continuous
+ thumb.cornerRadius = M.thumbnailCornerRadius
+ thumb.cornerCurve = .continuous
+ thumb.masksToBounds = true
+ thumb.contentsGravity = .resizeAspectFill
+ lift.addSublayer(thumb)
+ layer?.addSublayer(lift)
+ favicon.imageScaling = .scaleProportionallyUpOrDown
+ favicon.wantsLayer = true
+ favicon.layer?.cornerRadius = M.favicon * 0.22
+ favicon.layer?.cornerCurve = .continuous
+ favicon.layer?.masksToBounds = true
+ addSubview(favicon)
+ placeholder.wantsLayer = true
+ placeholder.layer?.cornerRadius = 4.5
+ placeholder.layer?.cornerCurve = .continuous
+ addSubview(placeholder)
+ addSubview(title)
}
- @ViewBuilder
- private func thumbnail(_ item: TabSwitcher.Item, dark: Bool) -> some View {
+ required init?(coder: NSCoder) { fatalError() }
+
+ func show(_ item: TabSwitcher.Item, icon: NSImage?, flip: Bool, selected: Bool, highlight: NSColor, dark: Bool) {
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ layer?.backgroundColor = selected ? highlight.cgColor : nil
+ lift.shadowOpacity = dark ? 0.4 : 0.15
if let image = item.snapshot {
- Image(nsImage: image).resizable().interpolation(.high).aspectRatio(contentMode: .fill)
+ thumb.contents = image.layerContents(forContentsScale: window?.backingScaleFactor ?? 2)
+ thumb.backgroundColor = nil
} else {
// A tab never seen since launch: Arc shows an empty #1C1C1C card.
- Rectangle().fill(dark ? Color(white: 28 / 255) : Color(white: 0.9))
+ thumb.contents = nil
+ thumb.backgroundColor = (dark ? NSColor(white: 28 / 255, alpha: 1) : NSColor(white: 0.9, alpha: 1)).cgColor
}
- }
-
- @ViewBuilder
- private func favicon(_ item: TabSwitcher.Item, dark: Bool) -> some View {
- if let palette = switcher.palette, item.iconKey != nil {
- FaviconIconOrPlaceholder(key: item.iconKey, palette: palette, dark: dark)
+ CATransaction.commit()
+ // Arc's switcher draws a missing favicon as a faint rounded square, not a globe.
+ if let icon {
+ favicon.isHidden = false
+ placeholder.isHidden = true
+ if flip {
+ let t = icon.copy() as! NSImage
+ t.isTemplate = true
+ favicon.image = t
+ favicon.contentTintColor = dark ? NSColor.white.withAlphaComponent(0.92) : NSColor.black.withAlphaComponent(0.85)
+ } else {
+ favicon.image = icon
+ favicon.contentTintColor = nil
+ }
} else {
- FaviconPlaceholder(dark: dark)
+ favicon.isHidden = true
+ placeholder.isHidden = false
+ placeholder.layer?.backgroundColor = (dark ? NSColor.white.withAlphaComponent(0.14) : NSColor.black.withAlphaComponent(0.1)).cgColor
}
+ // Arc's titles measure as SF 14 medium (ink width and cap height match).
+ title.stringValue = item.title
+ title.textColor = dark ? .white : NSColor.black.withAlphaComponent(0.85)
+ needsLayout = true
}
-}
-/// Arc's switcher draws a missing favicon as a faint rounded square, not a globe.
-private struct FaviconIconOrPlaceholder: View {
- let key: String?
- let palette: SpacePalette
- let dark: Bool
- @Environment(FaviconCache.self) private var favicons
+ override func layout() {
+ super.layout()
+ let h = bounds.height
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ lift.frame = NSRect(x: M.thumbnailOrigin.x, y: h - M.thumbnailOrigin.y - M.thumbnail.height,
+ width: M.thumbnail.width, height: M.thumbnail.height)
+ lift.shadowPath = CGPath(roundedRect: lift.bounds, cornerWidth: M.thumbnailCornerRadius, cornerHeight: M.thumbnailCornerRadius, transform: nil)
+ thumb.frame = lift.bounds
+ CATransaction.commit()
+ // The title row fills what is left under the thumbnail, centred.
+ let rowTop = M.thumbnailOrigin.y + M.thumbnail.height
+ let mid = h - (rowTop + (h - rowTop) / 2)
+ let f = NSRect(x: 13.5, y: mid - M.favicon / 2, width: M.favicon, height: M.favicon)
+ favicon.frame = f
+ placeholder.frame = f
+ let tx = 13.5 + M.favicon + 8
+ title.frame = NSRect(x: tx - SidebarText.inset, y: mid - 17 / 2, width: bounds.width - tx - 10.5 + 2 * SidebarText.inset, height: 17)
+ }
- var body: some View {
- if favicons.image(forKey: key) != nil {
- FaviconView(key: key, palette: palette, size: TabSwitcherMetrics.favicon, onDark: dark)
- } else {
- FaviconPlaceholder(dark: dark)
- }
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
}
-}
-private struct FaviconPlaceholder: View {
- let dark: Bool
- var body: some View {
- RoundedRectangle(cornerRadius: 4.5, style: .continuous)
- .fill(dark ? Color.white.opacity(0.14) : Color.black.opacity(0.1))
- .frame(width: TabSwitcherMetrics.favicon, height: TabSwitcherMetrics.favicon)
+ override func mouseEntered(with event: NSEvent) { onHover() }
+ override func mouseMoved(with event: NSEvent) { onHover() }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { onClick() }
}
}
diff --git a/Sources/Cra/UI/Theme.swift b/Sources/Cra/UI/Theme.swift
index 805e468..4d0f98f 100644
--- a/Sources/Cra/UI/Theme.swift
+++ b/Sources/Cra/UI/Theme.swift
@@ -210,19 +210,9 @@ struct NoiseOverlay: View {
struct SpaceBackground: View {
let palette: SpacePalette
- /// The main window passes the store so the tint follows a space swipe.
- var pager: SpacePager?
var body: some View {
- if let pager {
- let spaces = pager.store.pagedSpaces(window: pager.ui.windowID)
- let focused = pager.store.focusedSpaceID(window: pager.ui.windowID)
- let index = spaces.firstIndex { $0.id == focused } ?? 0
- PagedSpaceBackground(palettes: spaces.map(\.theme.palette), position: Double(index) + Double(pager.ui.spaceSwipe))
- .animation(pager.ui.spaceSettleAnimation, value: focused)
- } else {
- gradient
- }
+ gradient
}
private var gradient: some View {
@@ -257,40 +247,208 @@ struct SpaceBackground: View {
}
}
-struct SpacePager {
- let store: SidebarStore
- let ui: SidebarUIState
+/// The main window's background in AppKit: the paged space gradient (Core Animation) under the
+/// theme's noise. It follows the window's focused space itself; a space switch used to rebuild a
+/// SwiftUI background whenever the theme changed.
+@MainActor
+final class SpaceBackgroundView: NSView {
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let gradient: PagedGradientView
+ private let noise = ThemeNoiseView()
+
+ init(store: SidebarStore, ui: SidebarUIState) {
+ self.store = store
+ self.ui = ui
+ gradient = PagedGradientView(store: store, ui: ui)
+ super.init(frame: .zero)
+ wantsLayer = true
+ addSubview(gradient)
+ addSubview(noise)
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ private func observe() {
+ let palette = withObservationTracking { store.focusedSpace(window: ui.windowID).theme.palette } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ noise.apply(palette)
+ }
+
+ override func layout() {
+ super.layout()
+ gradient.frame = bounds
+ noise.frame = bounds
+ }
+
}
-/// The window tint while paging between spaces: the two neighbouring spaces'
-/// gradients mixed colour by colour at the fractional page position (Dia blends
-/// its space tint with the paging progress). Animatable, so the settle spring
-/// drives it frame by frame.
-struct PagedSpaceBackground: View, Animatable {
- let palettes: [SpacePalette]
- var position: Double
+/// NoiseOverlay in AppKit: the noise texture tiled in points, drawn once per size, at 9–10%,
+/// multiplied over light themes, screened over dark.
+final class ThemeNoiseView: NSView {
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
- var animatableData: Double {
- get { position }
- set { position = newValue }
+ func apply(_ palette: SpacePalette) {
+ alphaValue = palette.noise * (palette.isDark ? 0.1 : 0.09)
+ wantsLayer = true
+ layer?.compositingFilter = palette.isDark ? "screenBlendMode" : "multiplyBlendMode"
}
- var body: some View {
+ override func draw(_ dirtyRect: NSRect) {
+ NSColor(patternImage: NoiseTexture.image).setFill()
+ dirtyRect.fill()
+ }
+}
+
+/// SpaceBackground(palette:) in AppKit, for a view that shows one palette (the floating sidebar).
+final class PaletteBackgroundView: NSView {
+ var palette: SpacePalette { didSet { apply() } }
+ private let gradient = CAGradientLayer()
+ private let noise = ThemeNoiseView()
+
+ init(palette: SpacePalette) {
+ self.palette = palette
+ super.init(frame: .zero)
+ wantsLayer = true
+ gradient.startPoint = CGPoint(x: 0.5, y: 1)
+ gradient.endPoint = CGPoint(x: 0.5, y: 0)
+ layer?.addSublayer(gradient)
+ addSubview(noise)
+ apply()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ private func apply() {
+ let stops = SpaceBackground.stops(palette)
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ gradient.colors = stops.map(\.color.cgColor)
+ gradient.locations = stops.map { NSNumber(value: $0.location) }
+ CATransaction.commit()
+ noise.apply(palette)
+ }
+
+ override func layout() {
+ super.layout()
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ gradient.frame = bounds
+ CATransaction.commit()
+ noise.frame = bounds
+ }
+}
+
+/// The window tint while paging between spaces: the two neighbouring spaces' gradients mixed
+/// colour by colour at the fractional page position (Dia blends its space tint with the paging
+/// progress). A gradient layer set straight from the swipe, and sprung by Core Animation when it
+/// settles: in SwiftUI it re-rendered and re-laid out the window's background on every frame.
+@MainActor
+final class PagedGradientView: NSView {
+ private let store: SidebarStore
+ private let ui: SidebarUIState
+ private let gradient = CAGradientLayer()
+ private var placed: (index: Int, ids: [UUID], swipe: CGFloat)?
+ private var pendingVelocity = 0.0
+ private static let samples = 5
+ private static let settleKey = "settle"
+
+ init(store: SidebarStore, ui: SidebarUIState) {
+ self.store = store
+ self.ui = ui
+ super.init(frame: .zero)
+ wantsLayer = true
+ gradient.startPoint = CGPoint(x: 0.5, y: 1)
+ gradient.endPoint = CGPoint(x: 0.5, y: 0)
+ gradient.locations = (0..<Self.samples).map { NSNumber(value: Double($0) / Double(Self.samples - 1)) }
+ layer?.addSublayer(gradient)
+ ui.observeSpaceSwipe { [weak self] in self?.swipeChanged() }
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ private func observe() {
+ withObservationTracking {
+ _ = store.pagedSpaces(window: ui.windowID).map(\.theme)
+ _ = store.focusedSpaceID(window: ui.windowID)
+ _ = CraTuning.shared.gradientAlphaScale
+ } onChange: { [weak self] in
+ Task { @MainActor in
+ self?.placed = nil
+ self?.observe()
+ }
+ }
+ needsLayout = true
+ }
+
+ private func swipeChanged() {
+ if ui.spaceSwipe == 0 { pendingVelocity = ui.spaceSettleVelocity }
+ // Under the fingers the tint follows at once; a settle waits for the space change.
+ if ui.spaceSwipe != 0 { update() } else { needsLayout = true }
+ }
+
+ override func layout() {
+ super.layout()
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ gradient.frame = bounds
+ CATransaction.commit()
+ update()
+ }
+
+ private func update() {
+ let spaces = store.pagedSpaces(window: ui.windowID)
+ guard !spaces.isEmpty else { return }
+ let ids = spaces.map(\.id)
+ let index = ids.firstIndex(of: store.focusedSpaceID(window: ui.windowID)) ?? 0
+ let palettes = spaces.map(\.theme.palette)
+ let swipe = ui.spaceSwipe
+ let target = Self.colors(palettes, at: Double(index) + Double(swipe))
+ let moved = placed.map { $0.index != index || $0.swipe != 0 } ?? false
+ let sameSpaces = placed?.ids == ids
+ placed = (index, ids, swipe)
+ if swipe == 0, moved, sameSpaces, let from = gradient.presentation()?.colors ?? gradient.colors {
+ let spring = CASpringAnimation(perceptualDuration: 0.4, bounce: 0)
+ spring.keyPath = "colors"
+ spring.fromValue = from
+ spring.toValue = target
+ spring.initialVelocity = pendingVelocity
+ spring.duration = spring.settlingDuration
+ pendingVelocity = 0
+ setColors(target)
+ gradient.add(spring, forKey: Self.settleKey)
+ } else {
+ if swipe != 0 { gradient.removeAnimation(forKey: Self.settleKey) }
+ setColors(target)
+ }
+ }
+
+ private func setColors(_ colors: [CGColor]) {
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ gradient.colors = colors
+ CATransaction.commit()
+ }
+
+ static func colors(_ palettes: [SpacePalette], at position: Double) -> [CGColor] {
let last = max(0, palettes.count - 1)
let p = min(max(position, 0), Double(last))
let lo = Int(p.rounded(.down)), hi = min(last, lo + 1)
let f = p - Double(lo)
let a = palettes[lo], b = palettes[hi]
- let samples = 5
- let stops = (0..<samples).map { k -> Gradient.Stop in
+ return (0..<samples).map { k in
let t = Double(k) / Double(samples - 1)
- return Gradient.Stop(color: Color(nsColor: Self.mix(Self.color(a, at: t), Self.color(b, at: t), f)), location: t)
+ return mix(color(a, at: t), color(b, at: t), f).cgColor
}
- ZStack {
- LinearGradient(stops: stops, startPoint: .top, endPoint: .bottom)
- NoiseOverlay(amount: a.noise + (b.noise - a.noise) * f, isDark: f < 0.5 ? a.isDark : b.isDark)
- }
- .ignoresSafeArea()
}
private static func color(_ palette: SpacePalette, at t: Double) -> NSColor {
diff --git a/Sources/Cra/UI/Updates/UpdateBanner.swift b/Sources/Cra/UI/Updates/UpdateBanner.swift
index f0a792e..cb8c641 100644
--- a/Sources/Cra/UI/Updates/UpdateBanner.swift
+++ b/Sources/Cra/UI/Updates/UpdateBanner.swift
@@ -1,75 +1,174 @@
-import SwiftUI
+import AppKit
/// Arc's software-update sidebar banners (SidebarBanner `updateAvailable` and `updateSummary`),
/// above the space dock. Copy from Arc 1.170's strings: "An update is ready!" / "Click to
/// restart", "New Arc Version Available", and after the restart "Updated!" with "See What's
/// New". The banner never appeared on this Mac during the analysis, so its look follows
/// Cra's sidebar cards rather than a capture.
-struct UpdateBanner: View {
- let palette: SpacePalette
- @State private var hover = false
- @State private var hoverClose = false
-
- private struct Content {
+@MainActor
+final class UpdateBannerView: NSView {
+ private struct Content: Equatable {
var symbol: String
var title: String
var subtitle: String
- var action: @MainActor () -> Void
}
- @MainActor private var content: Content? {
+ /// What the banner says, or nil when there is nothing to say.
+ static var isShown: Bool { content != nil }
+
+ private static var content: Content? {
let u = SoftwareUpdater.shared
if u.readyRelease != nil, !u.bannerDismissed {
- return Content(symbol: "arrow.down.circle.fill", title: "An update is ready!", subtitle: "Click to restart") { u.installAndRelaunch() }
+ return Content(symbol: "arrow.down.circle.fill", title: "An update is ready!", subtitle: "Click to restart")
}
if let r = u.foundRelease, !u.bannerDismissed {
- return Content(symbol: "arrow.down.circle", title: "New Cra Version Available", subtitle: "Cra \(r.version)") { u.showFoundUpdate() }
+ return Content(symbol: "arrow.down.circle", title: "New Cra Version Available", subtitle: "Cra \(r.version)")
}
if u.updatedTo != nil {
- return Content(symbol: "heart.circle.fill", title: "Cra Updated!", subtitle: "See What's New") { u.openReleaseNotes() }
+ return Content(symbol: "heart.circle.fill", title: "Cra Updated!", subtitle: "See What's New")
}
return nil
}
- var body: some View {
- Group {
- if let c = content {
- HStack(spacing: 10) {
- Image(systemName: c.symbol)
- .font(.system(size: 20))
- .foregroundStyle(palette.textPrimary)
- VStack(alignment: .leading, spacing: 1) {
- Text(c.title).font(.system(size: 13, weight: .semibold))
- Text(c.subtitle).font(.system(size: 12)).foregroundStyle(palette.textSecondary)
- }
- .lineLimit(1)
- Spacer(minLength: 0)
- }
- .padding(.horizontal, 12)
- .frame(height: 52)
- .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(hover ? palette.selectedFill : palette.hoverFill))
- .overlay(alignment: .topTrailing) {
- if hover {
- Image(systemName: "xmark")
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(palette.textSecondary)
- .frame(width: 18, height: 18)
- .background(Circle().fill(hoverClose ? palette.hoverFill : .clear))
- .contentShape(Circle())
- .onHover { hoverClose = $0 }
- .onTapGesture { SoftwareUpdater.shared.dismissBanner() }
- .padding(6)
- .arcTooltip("Dismiss")
- }
- }
- .contentShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
- .actsOnFirstClick()
- .onHover { hover = $0 }
- .onTapGesture { c.action() }
- .padding(.top, 8)
- .transition(.move(edge: .bottom).combined(with: .opacity))
- }
+ private static func perform() {
+ let u = SoftwareUpdater.shared
+ if u.readyRelease != nil, !u.bannerDismissed { u.installAndRelaunch() }
+ else if u.foundRelease != nil, !u.bannerDismissed { u.showFoundUpdate() }
+ else if u.updatedTo != nil { u.openReleaseNotes() }
+ }
+
+ var colors = SidebarColors() { didSet { if colors != oldValue { refresh() } } }
+ private let card = NSView()
+ private let icon = NSImageView()
+ private let title = NSTextField.sidebarLabel(size: 13, weight: .semibold)
+ private let subtitle = NSTextField.sidebarLabel(size: 12)
+ private let close = NSView()
+ private let closeGlyph = NSImageView()
+ private var shown: Content?
+ private var hovering = false { didSet { if hovering != oldValue { refresh() } } }
+ private var hoveringClose = false { didSet { if hoveringClose != oldValue { refresh() } } }
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ card.wantsLayer = true
+ card.layer?.cornerRadius = 10
+ card.layer?.cornerCurve = .continuous
+ // Hidden until there is something to say: the host is 0 pt tall then, and the card
+ // would hang over the dock.
+ card.isHidden = true
+ addSubview(card)
+ icon.imageScaling = .scaleNone
+ card.addSubview(icon)
+ card.addSubview(title)
+ card.addSubview(subtitle)
+ close.wantsLayer = true
+ close.layer?.cornerRadius = 9
+ closeGlyph.image = SidebarSymbols.image("xmark", size: 9, weight: .bold)
+ closeGlyph.imageScaling = .scaleNone
+ closeGlyph.frame = NSRect(x: 0, y: 0, width: 18, height: 18)
+ close.addSubview(closeGlyph)
+ _ = ArcTooltipAnchorView.attach(to: close, help: "Dismiss")
+ close.isHidden = true
+ card.addSubview(close)
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private func observe() {
+ let content = withObservationTracking { Self.content } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
+ }
+ guard content != shown else { return }
+ let appearing = shown == nil && content != nil
+ shown = content
+ card.isHidden = content == nil
+ guard let content else { return }
+ icon.image = SidebarSymbols.image(content.symbol, size: 20)
+ title.stringValue = content.title
+ subtitle.stringValue = content.subtitle
+ needsLayout = true
+ // .transition(.move(edge: .bottom).combined(with: .opacity)), easeInOut 0.25.
+ if appearing, let layer = card.layer {
+ layoutSubtreeIfNeeded()
+ let fade = CABasicAnimation(keyPath: "opacity")
+ fade.fromValue = 0
+ let move = CABasicAnimation(keyPath: "position.y")
+ move.fromValue = layer.position.y - bounds.height
+ move.toValue = layer.position.y
+ let group = CAAnimationGroup()
+ group.animations = [fade, move]
+ group.duration = 0.25
+ group.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ layer.add(group, forKey: "appear")
+ }
+ }
+
+ private func refresh() {
+ card.layer?.backgroundColor = (hovering ? colors.selectedFill : colors.hoverFill).cgColor
+ icon.contentTintColor = colors.textPrimary
+ title.textColor = colors.textPrimary
+ subtitle.textColor = colors.textSecondary
+ closeGlyph.contentTintColor = colors.textSecondary
+ close.layer?.backgroundColor = (hoveringClose ? colors.hoverFill : .clear).cgColor
+ close.isHidden = !hovering
+ }
+
+ override func layout() {
+ super.layout()
+ // .padding(.horizontal, 8), .padding(.top, 8), 52 tall.
+ card.frame = NSRect(x: 8, y: 8, width: max(0, bounds.width - 16), height: 52)
+ let h: CGFloat = 52
+ let iw = icon.image?.size.width ?? 20
+ icon.frame = NSRect(x: 12, y: 0, width: iw, height: h)
+ let tx = 12 + iw + 10, tw = max(0, card.bounds.width - tx - 12)
+ // VStack(spacing: 1): 16 + 1 + 15, centred.
+ let top = (h - 32) / 2
+ title.frame = NSRect(x: tx - SidebarText.inset, y: h - top - 16, width: tw + 2 * SidebarText.inset, height: 16)
+ subtitle.frame = NSRect(x: tx - SidebarText.inset, y: h - top - 32, width: tw + 2 * SidebarText.inset, height: 15)
+ close.frame = NSRect(x: card.bounds.width - 6 - 18, y: h - 6 - 18, width: 18, height: 18)
+ }
+
+ // MARK: Pointer
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { track(event) }
+ override func mouseMoved(with event: NSEvent) { track(event) }
+ override func mouseExited(with event: NSEvent) { hovering = false; hoveringClose = false }
+
+ private func track(_ event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ hovering = shown != nil && card.frame.contains(p)
+ hoveringClose = hovering && close.frame.contains(card.convert(p, from: self))
+ }
+
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ guard shown != nil, card.frame.contains(convert(point, from: superview)) else { return nil }
+ return self
+ }
+
+ /// After an automatic update Cra restarts in the background; "See What's New" acts on the
+ /// click that brings the window forward.
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+ override var mouseDownCanMoveWindow: Bool { false }
+
+ override func mouseDown(with event: NSEvent) {}
+
+ override func mouseUp(with event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ guard card.frame.contains(p) else { return }
+ if hovering, close.frame.contains(card.convert(p, from: self)) {
+ SoftwareUpdater.shared.dismissBanner()
+ } else {
+ Self.perform()
}
- .animation(.easeInOut(duration: 0.25), value: content?.title)
}
}
diff --git a/Sources/Cra/UI/Windows/DownloadFlight.swift b/Sources/Cra/UI/Windows/DownloadFlight.swift
index ed12b55..8e23044 100644
--- a/Sources/Cra/UI/Windows/DownloadFlight.swift
+++ b/Sources/Cra/UI/Windows/DownloadFlight.swift
@@ -135,7 +135,3 @@ enum DownloadFlight {
}
}()
}
-
-private final class FlippedView: NSView {
- override var isFlipped: Bool { true }
-}
diff --git a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
index 84de6e3..e6ac465 100644
--- a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
+++ b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
@@ -14,13 +14,19 @@ final class ExtensionPopupWindow: NSWindow {
/// Chrome's bubble draws a transparent margin around the page.
static let bubbleInset: CGFloat = 7
static let titleBarHeight: CGFloat = 28
- private static let savedOriginKey = "extensionPopupWindowTopLeft"
+ /// Where the user dragged a popup to, relative to its anchor. (Cra ≤ 0.1.17 kept an
+ /// absolute screen point under "extensionPopupWindowTopLeft"; that one is dropped.)
+ private static let savedOffsetKey = "extensionPopupWindowOffset"
private static var current: ExtensionPopupWindow?
private weak var bubble: NSWindow?
- /// The frame's top-left (screen): under the anchor, or where the user left it.
- private var topLeft = NSPoint.zero
+ /// The top-right point (screen) the popup hangs from: right edge of its button, under the bar.
+ private var anchor = NSPoint.zero
+ /// Where the user dragged the frame, from hanging right under the anchor.
+ private var offset = NSPoint.zero
+ /// The frame's top-left when a title-bar drag began.
+ private var dragStart = NSPoint.zero
private var observers: [NSObjectProtocol] = []
private var placing = false
/// A title-bar drag is under way (willMove is only posted for those, not when the main
@@ -52,12 +58,14 @@ final class ExtensionPopupWindow: NSWindow {
}
/// Wraps Chrome's popup `bubble`; `anchor` is the top-right point (screen) it hangs from
- /// until the user moves the window.
+ /// (its right edge stays there as Chrome resizes the page), moved by the user's last drag.
static func present(_ bubble: NSWindow, anchor: NSPoint) {
current?.dismiss(closingBubble: false)
let w = ExtensionPopupWindow()
w.bubble = bubble
- w.topLeft = placement(anchor: anchor, width: bubble.frame.width - 2 * bubbleInset)
+ w.anchor = anchor
+ UserDefaults.standard.removeObject(forKey: "extensionPopupWindowTopLeft")
+ w.offset = savedOffset ?? .zero
w.appearance = bubble.parent?.effectiveAppearance ?? NSApp.effectiveAppearance
w.backgroundColor = .windowBackgroundColor
current = w
@@ -97,7 +105,11 @@ final class ExtensionPopupWindow: NSWindow {
MainActor.assumeIsolated { w?.dismiss(closingBubble: true) }
})
w.observers.append(NotificationCenter.default.addObserver(forName: NSWindow.willMoveNotification, object: w, queue: .main) { [weak w] _ in
- MainActor.assumeIsolated { w?.dragging = true }
+ MainActor.assumeIsolated {
+ guard let w else { return }
+ w.dragging = true
+ w.dragStart = NSPoint(x: w.frame.minX, y: w.frame.maxY)
+ }
})
w.observers.append(NotificationCenter.default.addObserver(forName: NSWindow.didMoveNotification, object: w, queue: .main) { [weak w] _ in
MainActor.assumeIsolated { w?.userMoved() }
@@ -118,7 +130,8 @@ final class ExtensionPopupWindow: NSWindow {
defer { placing = false }
let inset = Self.bubbleInset
let size = NSSize(width: bubble.frame.width - 2 * inset, height: bubble.frame.height - 2 * inset + Self.titleBarHeight)
- var topLeft = self.topLeft
+ // Right edge on the anchor whatever width the page reports (Bitwarden grows after it loads).
+ var topLeft = NSPoint(x: anchor.x - size.width + offset.x, y: anchor.y + offset.y)
if let screen = (bubble.screen ?? NSScreen.main)?.visibleFrame {
topLeft.x = min(max(topLeft.x, screen.minX + 4), screen.maxX - size.width - 4)
topLeft.y = min(max(topLeft.y, screen.minY + size.height + 4), screen.maxY)
@@ -131,23 +144,28 @@ final class ExtensionPopupWindow: NSWindow {
private func userMoved() {
guard dragging, !placing, bubble != nil else { return }
- topLeft = NSPoint(x: frame.minX, y: frame.maxY)
- Self.savedTopLeft = topLeft
+ let moved = NSPoint(x: frame.minX, y: frame.maxY)
+ // A click on the title bar that barely moved it is not a new place.
+ guard hypot(moved.x - dragStart.x, moved.y - dragStart.y) > 4 else { return }
+ offset = NSPoint(x: moved.x - (anchor.x - frame.width), y: moved.y - anchor.y)
+ Self.savedOffset = offset
}
- /// Top-left of a popup window `width` wide: where the user last left one, else hanging
- /// from `anchor` (top-right).
+ /// Top-left of a popup window `width` wide: hanging from `anchor` (top-right), moved by
+ /// where the user last dragged one to. The drag is kept relative to the anchor, so the
+ /// popup follows its button when the browser window moves or changes screen (GitHub #8:
+ /// an absolute screen point made it open in "random" places).
static func placement(anchor: NSPoint, width: CGFloat) -> NSPoint {
- savedTopLeft ?? NSPoint(x: anchor.x - width, y: anchor.y)
+ let offset = savedOffset ?? .zero
+ return NSPoint(x: anchor.x - width + offset.x, y: anchor.y + offset.y)
}
- private static var savedTopLeft: NSPoint? {
+ private static var savedOffset: NSPoint? {
get {
- guard let s = UserDefaults.standard.string(forKey: savedOriginKey) else { return nil }
- let p = NSPointFromString(s)
- return p == .zero ? nil : p
+ guard let s = UserDefaults.standard.string(forKey: savedOffsetKey) else { return nil }
+ return NSPointFromString(s)
}
- set { UserDefaults.standard.set(newValue.map(NSStringFromPoint), forKey: savedOriginKey) }
+ set { UserDefaults.standard.set(newValue.map(NSStringFromPoint), forKey: savedOffsetKey) }
}
override func performClose(_ sender: Any?) { dismiss(closingBubble: true) }
@@ -232,7 +250,8 @@ final class ExtensionPageWindow: NSWindow, NSWindowDelegate, @preconcurrency Cra
private unowned let app: AppDelegate
private var browser: CraBrowser?
- private var topLeft: NSPoint
+ /// The frame's top-right (screen): the page grows to the left, away from its button.
+ private var topRight: NSPoint
private var pageSize: NSSize?
private var measureTimer: Timer?
private var closing = false
@@ -256,7 +275,8 @@ final class ExtensionPageWindow: NSWindow, NSWindowDelegate, @preconcurrency Cra
private init(url: String, anchor: NSPoint, app: AppDelegate) {
self.app = app
let start = NSSize(width: 360, height: 240)
- topLeft = ExtensionPopupWindow.placement(anchor: anchor, width: start.width)
+ let tl = ExtensionPopupWindow.placement(anchor: anchor, width: start.width)
+ topRight = NSPoint(x: tl.x + start.width, y: tl.y)
super.init(contentRect: NSRect(origin: .zero, size: start), styleMask: [.titled, .closable, .fullSizeContentView],
backing: .buffered, defer: false)
titlebarAppearsTransparent = true
@@ -293,7 +313,7 @@ final class ExtensionPageWindow: NSWindow, NSWindowDelegate, @preconcurrency Cra
private func frame(for page: NSSize) -> NSRect {
let h = page.height + ExtensionPopupWindow.titleBarHeight
- var tl = topLeft
+ var tl = NSPoint(x: topRight.x - page.width, y: topRight.y)
if let screen = (screen ?? NSScreen.main)?.visibleFrame {
tl.x = min(max(tl.x, screen.minX + 4), screen.maxX - page.width - 4)
tl.y = min(max(tl.y, screen.minY + h + 4), screen.maxY)
@@ -363,7 +383,7 @@ final class ExtensionPageWindow: NSWindow, NSWindowDelegate, @preconcurrency Cra
// MARK: Window
func windowDidMove(_ notification: Notification) {
- topLeft = NSPoint(x: frame.minX, y: frame.maxY)
+ topRight = NSPoint(x: frame.maxX, y: frame.maxY)
}
/// Like a popup: clicking anywhere else closes it (the page's own window is a child,
diff --git a/Sources/Cra/UI/Windows/FloatingSidebar.swift b/Sources/Cra/UI/Windows/FloatingSidebar.swift
index 580751a..5d88979 100644
--- a/Sources/Cra/UI/Windows/FloatingSidebar.swift
+++ b/Sources/Cra/UI/Windows/FloatingSidebar.swift
@@ -1,5 +1,4 @@
import AppKit
-import SwiftUI
/// Arc's floating sidebar: with the sidebar hidden, touching the window's left
/// edge slides the sidebar in over the page; it leaves when the pointer does.
@@ -25,7 +24,7 @@ final class FloatingSidebarController {
private let slider = NSView()
private let blur = NSVisualEffectView()
private let lift = NSView()
- private var gradientHost: NSHostingView<SpaceBackground>?
+ private var gradientHost: PaletteBackgroundView?
private var trafficLights: FloatingTrafficLights?
enum Metrics {
@@ -117,8 +116,7 @@ final class FloatingSidebarController {
lift.wantsLayer = true
lift.autoresizingMask = [.width, .height]
slider.addSubview(lift)
- let g = NSHostingView(rootView: SpaceBackground(palette: palette()))
- g.sizingOptions = []
+ let g = PaletteBackgroundView(palette: palette())
g.autoresizingMask = [.width, .height]
slider.addSubview(g)
gradientHost = g
@@ -133,7 +131,7 @@ final class FloatingSidebarController {
let pal = palette()
let t = CraTuning.shared
for v in [blur, lift, gradientHost as NSView?].compactMap({ $0 }) { v.frame = slider.bounds }
- gradientHost?.rootView = SpaceBackground(palette: pal)
+ gradientHost?.palette = pal
blur.isHidden = !pal.vibrant
lift.isHidden = !pal.vibrant
blur.material = pal.isDark ? .underWindowBackground : t.material
diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swift
index 5e85781..cdfb3ff 100644
--- a/Sources/Cra/UI/Windows/LittleWindowController.swift
+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift
@@ -28,7 +28,7 @@ final class LittleWindowState {
/// Pointer hover, tracked by AppKit (SwiftUI's onHover sleeps while the
/// Chrome page window, a child, is the key window).
var hover: LittleHover = .none
- /// Width of the "Open in" button, reported by SwiftUI for hit-testing.
+ /// Width of the "Open in" button, reported by LittleToolbarView for hit-testing.
var openButtonWidth: CGFloat = 160
init(targetSpaceID: UUID) { self.targetSpaceID = targetSpaceID }
@@ -117,7 +117,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
private var favicon: NSImage?
private var promoted = false
private var commandPanel: CommandBarPanel!
- private var commandHost: NSHostingView<AnyView>!
+ private var commandHost: CommandBarView!
private var commandBarOpenedAt = Date.distantPast
private var commandObserving = false
private var popup: LittlePopupPanel?
@@ -155,7 +155,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
window.appearance = NSAppearance(named: .darkAqua)
window.backgroundColor = LittlePalette.barNS
window.contentView = shell
- shell.toolbarHost.rootView = AnyView(LittleToolbar(state: state, actions: actions).environment(app.store))
+ shell.setToolbar(LittleToolbarView(state: state, actions: actions, store: app.store))
shell.onHover = { [weak self] h in
guard let self, self.state.hover != h else { return }
self.state.hover = h
@@ -171,7 +171,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
actions.closePopup = { [weak self] in self?.closePopup() }
commandPanel = CommandBarPanel()
- commandHost = NSHostingView(rootView: AnyView(CommandBarView(controller: commandBar).environment(app.favicons)))
+ commandHost = CommandBarView(controller: commandBar, favicons: app.favicons)
commandPanel.contentView = commandHost
commandPanel.delegate = self
commandBar.onCommit = { [weak self] s, typed, mode, force in self?.handleCommit(s, typed: typed, mode: mode, forceNewTab: force) }
@@ -417,10 +417,9 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
private func showTooltip(_ text: String, caps: [String], for h: LittleHover) {
guard let window, state.hover == h, popup == nil, !commandBar.isOpen else { return }
let panel = LittleTooltipPanel()
- let host = NSHostingView(rootView: AnyView(LittleTooltip(text: text, caps: caps)))
- let size = host.fittingSize
- host.setFrameSize(size)
- panel.contentView = host
+ let tip = LittleTooltipView(text: text, caps: caps)
+ let size = tip.frame.size
+ panel.contentView = tip
let w = window.frame.width
// Centred under the control; the chevron tip hugs the right edge like Arc's.
let cx: CGFloat = switch h {
@@ -455,11 +454,9 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
tooltipTimer?.invalidate(); hideTooltip()
commandBar.close()
let panel = LittlePopupPanel()
- let view = LittleSpacesPopup(state: state, onPick: { [weak self] sid in self?.closePopup(); self?.promote(to: sid) },
- onClose: { [weak self] in self?.closePopup() })
- .environment(store)
- let host = NSHostingView(rootView: AnyView(view))
- panel.contentView = host
+ panel.contentView = LittleSpacesPopup(state: state, store: store,
+ onPick: { [weak self] sid in self?.closePopup(); self?.promote(to: sid) },
+ onClose: { [weak self] in self?.closePopup() })
panel.delegate = self
let rows = min(store.spaceOrder.count, 6)
let h = LittleMetrics.popupHeaderHeight + CGFloat(rows) * LittleMetrics.popupRowHeight
@@ -737,7 +734,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
/// The navy strip on top, the page edge to edge below.
final class LittleShellView: NSView {
- let toolbarHost = FirstMouseHostingView(rootView: AnyView(EmptyView()))
+ private(set) var toolbarHost = NSView()
let page = NSView()
/// Reports the page area (window coordinates) so a Chrome-style page window can follow it.
var onPageFrame: ((NSRect) -> Void)?
@@ -751,12 +748,6 @@ final class LittleShellView: NSView {
super.init(frame: frame)
wantsLayer = true
layer?.backgroundColor = LittlePalette.barNS.cgColor
- toolbarHost.sizingOptions = []
- toolbarHost.isOverControl = { [weak self] p in
- guard let self else { return false }
- // p is in the strip's own coordinates (flipped SwiftUI space: y from the top).
- return self.hoverTarget(x: p.x, y: self.toolbarHost.isFlipped ? p.y : LittleMetrics.barHeight - p.y) != .none
- }
addSubview(toolbarHost)
page.wantsLayer = true
page.layer?.cornerCurve = .continuous
@@ -769,6 +760,18 @@ final class LittleShellView: NSView {
required init?(coder: NSCoder) { fatalError() }
+ func setToolbar(_ toolbar: LittleToolbarView) {
+ toolbar.isOverControl = { [weak self] p in
+ guard let self else { return false }
+ // p is in the strip's own coordinates (flipped: y from the top).
+ return self.hoverTarget(x: p.x, y: p.y) != .none
+ }
+ toolbarHost.removeFromSuperview()
+ toolbarHost = toolbar
+ addSubview(toolbar, positioned: .below, relativeTo: page)
+ needsLayout = true
+ }
+
override func updateTrackingAreas() {
super.updateTrackingAreas()
if let t = trackingArea { removeTrackingArea(t) }
@@ -785,7 +788,7 @@ final class LittleShellView: NSView {
onHover?(inBar ? hoverTarget(x: p.x, y: bounds.height - p.y) : .none)
}
- /// Mirrors LittleToolbar's layout (pill from x 83, 10pt gap, button, 7pt margin).
+ /// Mirrors LittleToolbarView's layout (pill from x 83, 10pt gap, button, 7pt margin).
private func hoverTarget(x: CGFloat, y: CGFloat) -> LittleHover {
guard y >= 8, y <= 8 + LittleMetrics.controlHeight else { return .none }
let w = bounds.width
@@ -867,18 +870,6 @@ final class LittleWindow: NSWindow {
}
}
-/// The strip's buttons work on the first click even when the page window holds key
-/// status, and only the empty parts of the strip drag the window (a press on the
-/// pill or the button must not start a window-move session).
-final class FirstMouseHostingView: NSHostingView<AnyView> {
- var isOverControl: ((NSPoint) -> Bool)?
- override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
- override var mouseDownCanMoveWindow: Bool {
- guard let window, let isOverControl else { return true }
- return !isOverControl(convert(window.mouseLocationOutsideOfEventStream, from: nil))
- }
-}
-
/// Borderless, non-activating tooltip panel (never takes key status).
final class LittleTooltipPanel: NSPanel {
override var canBecomeKey: Bool { false }
@@ -899,32 +890,47 @@ final class LittleTooltipPanel: NSPanel {
}
/// Arc's hover tip: 28pt navy pill, 14pt semibold text, 20pt key caps.
-struct LittleTooltip: View {
- let text: String
- let caps: [String]
- var body: some View {
- HStack(spacing: 6) {
- Text(text).font(.system(size: 14, weight: .semibold)).foregroundStyle(LittlePalette.tooltipText)
- if !caps.isEmpty {
- HStack(spacing: 4) {
- ForEach(caps, id: \.self) { c in
- Text(c)
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(LittlePalette.tooltipCapGlyph)
- .frame(width: 20, height: 20)
- .background(RoundedRectangle(cornerRadius: 5, style: .continuous).fill(LittlePalette.tooltipCap))
- }
- }
- .padding(.leading, 2)
- }
+final class LittleTooltipView: NSView {
+ init(text: String, caps: [String]) {
+ super.init(frame: .zero)
+ let font = NSFont.systemFont(ofSize: 14, weight: .semibold)
+ let textW = ceil((text as NSString).size(withAttributes: [.font: font]).width)
+ let capsW = caps.isEmpty ? 0 : 2 + CGFloat(caps.count) * 20 + CGFloat(caps.count - 1) * 4
+ let pillW = 10 + textW + (caps.isEmpty ? 0 : 6 + capsW) + (caps.isEmpty ? 10 : 6)
+ // .padding(2) around the 28 pt pill.
+ setFrameSize(NSSize(width: pillW + 4, height: 32))
+ let pill = NSView(frame: NSRect(x: 2, y: 2, width: pillW, height: 28))
+ pill.wantsLayer = true
+ pill.layer?.backgroundColor = NSColor(LittlePalette.tooltip).cgColor
+ pill.layer?.cornerRadius = 10
+ pill.layer?.cornerCurve = .continuous
+ pill.layer?.borderWidth = 1
+ pill.layer?.borderColor = NSColor(LittlePalette.tooltipBorder).cgColor
+ addSubview(pill)
+ let label = NSTextField.sidebarLabel(size: 14, weight: .semibold)
+ label.stringValue = text
+ label.textColor = NSColor(LittlePalette.tooltipText)
+ label.frame = NSRect(x: 10 - SidebarText.inset, y: (28 - 17) / 2, width: textW + 2 * SidebarText.inset, height: 17)
+ pill.addSubview(label)
+ var x = 10 + textW + 6 + 2
+ for c in caps {
+ let cap = NSView(frame: NSRect(x: x, y: 4, width: 20, height: 20))
+ cap.wantsLayer = true
+ cap.layer?.backgroundColor = NSColor(LittlePalette.tooltipCap).cgColor
+ cap.layer?.cornerRadius = 5
+ cap.layer?.cornerCurve = .continuous
+ let glyph = NSTextField.sidebarLabel(size: 12, weight: .semibold)
+ glyph.stringValue = c
+ glyph.textColor = NSColor(LittlePalette.tooltipCapGlyph)
+ glyph.alignment = .center
+ glyph.frame = NSRect(x: -SidebarText.inset, y: (20 - 15) / 2, width: 20 + 2 * SidebarText.inset, height: 15)
+ cap.addSubview(glyph)
+ pill.addSubview(cap)
+ x += 24
}
- .padding(.leading, 10)
- .padding(.trailing, caps.isEmpty ? 10 : 6)
- .frame(height: 28)
- .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(LittlePalette.tooltip))
- .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(LittlePalette.tooltipBorder, lineWidth: 1))
- .padding(2)
}
+
+ required init?(coder: NSCoder) { fatalError() }
}
/// Borderless child panel for the spaces menu; takes the keyboard for filtering.
@@ -945,210 +951,347 @@ final class LittlePopupPanel: NSPanel {
}
}
-// MARK: - SwiftUI
+// MARK: - Strip
-/// The strip: search pill with puzzle + link icons, split "Open in <Space> ⌘O | ⌄".
-struct LittleToolbar: View {
- let state: LittleWindowState
- let actions: LittleWindowActions
- @Environment(SidebarStore.self) private var store
- private var hoverPill: Bool { state.hover == .pill }
- private var hoverOpen: Bool { state.hover == .open }
- private var hoverChevron: Bool { state.hover == .chevron }
-
- private var human: String { SuggestionEngine.humanURL(state.url) }
- private var targetSpace: Space { store.space(state.targetSpaceID) ?? store.focusedSpace }
-
- var body: some View {
- HStack(spacing: LittleMetrics.pillGap) {
- pill
- openIn
- }
- .padding(.leading, LittleMetrics.pillLeft)
- .padding(.trailing, LittleMetrics.rightMargin)
- .frame(height: LittleMetrics.barHeight)
- .frame(maxWidth: .infinity)
- .background(LittlePalette.bar)
- .ignoresSafeArea()
- }
-
- private var pill: some View {
- ZStack {
- Button { actions.openCommandBar() } label: {
- HStack(spacing: 0) {
- Image(systemName: "magnifyingglass")
- .font(.system(size: 13, weight: .medium))
- .foregroundStyle(LittlePalette.icon)
- .frame(width: 34, alignment: .center)
- Spacer(minLength: 0)
- }
- .overlay {
- Text(state.url.isEmpty ? "" : human)
- .font(.system(size: 13))
- .foregroundStyle(LittlePalette.text)
- .lineLimit(1)
- .truncationMode(.tail)
- .padding(.horizontal, 80)
- }
- .frame(maxWidth: .infinity)
- .frame(height: LittleMetrics.controlHeight)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- HStack(spacing: 5) {
- Spacer(minLength: 0)
- LittleIcon(symbol: "puzzlepiece.extension", size: 15, hover: state.hover == .puzzle) {}
- LittleIcon(symbol: "link", size: 14, hover: state.hover == .link) { actions.copyURL() }
- }
- .padding(.trailing, 2)
+/// The strip's controls, drawn by AppKit: the address pill (search glyph, centred URL, the
+/// extensions and copy-link icons) and the "Open in <Space> ⌘O | ⌄" button. Hover comes from
+/// the shell's tracking (`state.hover`); clicks land here. They work on the first click even
+/// when the page window holds key status, and only the empty parts of the strip drag the
+/// window (a press on the pill or the button must not start a window-move session).
+@MainActor
+final class LittleToolbarView: NSView {
+ private let state: LittleWindowState
+ private let actions: LittleWindowActions
+ private let store: SidebarStore
+ private let pill = NSView()
+ private let search = NSImageView()
+ private let urlLabel = NSTextField.sidebarLabel(size: 13)
+ private let puzzle = LittleIconView(symbol: "puzzlepiece.extension", size: 15)
+ private let link = LittleIconView(symbol: "link", size: 14)
+ private let openButton = NSView()
+ private let openPart = NSView()
+ private let openLabel = NSTextField.sidebarLabel(size: 13, weight: .medium)
+ private let badge = NSView()
+ private let badgeLabel = NSTextField.sidebarLabel(size: 11, weight: .medium)
+ private let divider = NSView()
+ private let chevronPart = NSView()
+ private let chevron = NSImageView()
+ /// Asked by the shell: does a press here hit a control (else it moves the window)?
+ var isOverControl: ((NSPoint) -> Bool)?
+
+ init(state: LittleWindowState, actions: LittleWindowActions, store: SidebarStore) {
+ self.state = state
+ self.actions = actions
+ self.store = store
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.backgroundColor = LittlePalette.barNS.cgColor
+ pill.wantsLayer = true
+ pill.layer?.cornerRadius = 8
+ pill.layer?.cornerCurve = .continuous
+ addSubview(pill)
+ search.image = SidebarSymbols.image("magnifyingglass", size: 13, weight: .medium)
+ search.contentTintColor = NSColor(LittlePalette.icon)
+ search.imageScaling = .scaleNone
+ pill.addSubview(search)
+ urlLabel.textColor = NSColor(LittlePalette.text)
+ urlLabel.alignment = .center
+ pill.addSubview(urlLabel)
+ pill.addSubview(puzzle)
+ pill.addSubview(link)
+ openButton.wantsLayer = true
+ openButton.layer?.backgroundColor = LittlePalette.buttonNS.cgColor
+ openButton.layer?.cornerRadius = 7
+ openButton.layer?.cornerCurve = .continuous
+ openButton.layer?.masksToBounds = true
+ openButton.layer?.borderWidth = 1
+ openButton.layer?.borderColor = NSColor(LittlePalette.buttonBorder).cgColor
+ addSubview(openButton)
+ openPart.wantsLayer = true
+ openButton.addSubview(openPart)
+ openPart.addSubview(openLabel)
+ badge.wantsLayer = true
+ badge.layer?.cornerRadius = 4
+ badge.layer?.cornerCurve = .continuous
+ badge.layer?.backgroundColor = NSColor(LittlePalette.badge).cgColor
+ badgeLabel.stringValue = "⌘O"
+ badgeLabel.textColor = NSColor(LittlePalette.badgeText)
+ badge.addSubview(badgeLabel)
+ openPart.addSubview(badge)
+ divider.wantsLayer = true
+ divider.layer?.backgroundColor = NSColor(LittlePalette.buttonBorder).cgColor
+ openButton.addSubview(divider)
+ chevronPart.wantsLayer = true
+ chevron.imageScaling = .scaleNone
+ chevron.contentTintColor = NSColor(LittlePalette.label)
+ chevronPart.addSubview(chevron)
+ openButton.addSubview(chevronPart)
+ observe()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ private func observe() {
+ let (url, hover, popupOpen, space) = withObservationTracking {
+ (state.url, state.hover, state.popupOpen, store.space(state.targetSpaceID) ?? store.focusedSpace)
+ } onChange: { [weak self] in
+ Task { @MainActor in self?.observe() }
}
- .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(hoverPill ? LittlePalette.pillHover : LittlePalette.pill))
- .help(state.url)
- }
-
- private var openIn: some View {
- let space = targetSpace
- return HStack(spacing: 0) {
- Button { actions.promote(nil) } label: {
- HStack(spacing: 0) {
- (Text("Open in ").font(.system(size: 13, weight: .medium)).foregroundStyle(LittlePalette.label)
- + Text(space.title).font(.system(size: 13, weight: .bold)).foregroundStyle(LittlePalette.spaceName(space.theme)))
- .lineLimit(1)
- Text("⌘O")
- .font(.system(size: 11, weight: .medium))
- .foregroundStyle(LittlePalette.badgeText)
- .padding(.horizontal, 5)
- .frame(height: 16)
- .background(RoundedRectangle(cornerRadius: 4, style: .continuous).fill(LittlePalette.badge))
- .padding(.leading, 6)
- }
- .padding(.leading, 10)
- .padding(.trailing, 8)
- .frame(height: LittleMetrics.controlHeight)
- .background(hoverOpen ? LittlePalette.buttonHover : .clear)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .disabled(state.url.isEmpty)
- .help("Open this page in \(space.title) as a tab (⌘O)")
- Rectangle().fill(LittlePalette.buttonBorder).frame(width: 1, height: LittleMetrics.controlHeight)
- Button { actions.togglePopup() } label: {
- Image(systemName: state.popupOpen ? "chevron.up" : "chevron.down")
- .font(.system(size: 10, weight: .bold))
- .foregroundStyle(LittlePalette.label)
- .frame(width: LittleMetrics.chevronWidth, height: LittleMetrics.controlHeight)
- .background(hoverChevron ? LittlePalette.buttonHover : .clear)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
+ urlLabel.stringValue = url.isEmpty ? "" : SuggestionEngine.humanURL(url)
+ pill.toolTip = url
+ pill.layer?.backgroundColor = NSColor(hover == .pill ? LittlePalette.pillHover : LittlePalette.pill).cgColor
+ puzzle.hovered = hover == .puzzle
+ link.hovered = hover == .link
+ let text = NSMutableAttributedString(string: "Open in ", attributes: [.font: NSFont.systemFont(ofSize: 13, weight: .medium),
+ .foregroundColor: NSColor(LittlePalette.label)])
+ text.append(NSAttributedString(string: space.title, attributes: [.font: NSFont.systemFont(ofSize: 13, weight: .bold),
+ .foregroundColor: NSColor(LittlePalette.spaceName(space.theme))]))
+ openLabel.attributedStringValue = text
+ openButton.toolTip = "Open this page in \(space.title) as a tab (⌘O)"
+ openPart.layer?.backgroundColor = hover == .open ? NSColor(LittlePalette.buttonHover).cgColor : nil
+ chevronPart.layer?.backgroundColor = hover == .chevron ? NSColor(LittlePalette.buttonHover).cgColor : nil
+ chevron.image = SidebarSymbols.image(popupOpen ? "chevron.up" : "chevron.down", size: 10, weight: .bold)
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ let w = bounds.width, ch = LittleMetrics.controlHeight, y: CGFloat = 8
+ // Open button: 10 + "Open in <space>" + 6 + ⌘O (5 + text + 5) + 8 | 1 | 29.
+ let tw = ceil(openLabel.attributedStringValue.size().width)
+ let bw = ceil(badgeLabel.attributedStringValue.size().width) + 10
+ let partW = 10 + tw + 6 + bw + 8
+ let openW = partW + 1 + LittleMetrics.chevronWidth
+ if state.openButtonWidth != openW { state.openButtonWidth = openW }
+ openButton.frame = NSRect(x: w - LittleMetrics.rightMargin - openW, y: y, width: openW, height: ch)
+ openPart.frame = NSRect(x: 0, y: 0, width: partW, height: ch)
+ openLabel.frame = NSRect(x: 10 - SidebarText.inset, y: (ch - 16) / 2, width: tw + 2 * SidebarText.inset, height: 16)
+ badge.frame = NSRect(x: 10 + tw + 6, y: (ch - 16) / 2, width: bw, height: 16)
+ badgeLabel.frame = NSRect(x: 5 - SidebarText.inset, y: (16 - 14) / 2, width: bw - 10 + 2 * SidebarText.inset, height: 14)
+ divider.frame = NSRect(x: partW, y: 0, width: 1, height: ch)
+ chevronPart.frame = NSRect(x: partW + 1, y: 0, width: LittleMetrics.chevronWidth, height: ch)
+ chevron.frame = chevronPart.bounds
+ // The pill fills the rest from x 83.
+ let pillW = max(0, openButton.frame.minX - LittleMetrics.pillGap - LittleMetrics.pillLeft)
+ pill.frame = NSRect(x: LittleMetrics.pillLeft, y: y, width: pillW, height: ch)
+ search.frame = NSRect(x: 0, y: 0, width: 34, height: ch)
+ // The URL is centred over the whole pill, 80 pt clear of each end.
+ urlLabel.frame = NSRect(x: 80 - SidebarText.inset, y: (ch - 16) / 2, width: max(0, pillW - 160) + 2 * SidebarText.inset, height: 16)
+ link.frame = NSRect(x: pillW - 2 - 26, y: 2, width: 26, height: 26)
+ puzzle.frame = NSRect(x: pillW - 2 - 26 - 5 - 26, y: 2, width: 26, height: 26)
+ }
+
+ // MARK: Clicks
+
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ override var mouseDownCanMoveWindow: Bool {
+ guard let window, let isOverControl else { return true }
+ return !isOverControl(convert(window.mouseLocationOutsideOfEventStream, from: nil))
+ }
+
+ /// Presses on the empty strip move the window before they get here (mouseDownCanMoveWindow).
+ override func mouseDown(with event: NSEvent) {}
+
+ override func mouseUp(with event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ if openButton.frame.contains(p) {
+ if chevronPart.frame.contains(openButton.convert(p, from: self)) { actions.togglePopup() }
+ else if !state.url.isEmpty { actions.promote(nil) }
+ } else if pill.frame.contains(p) {
+ let q = pill.convert(p, from: self)
+ if link.frame.contains(q) { actions.copyURL() }
+ else if !puzzle.frame.contains(q) { actions.openCommandBar() }
}
- .background(LittlePalette.button)
- .clipShape(RoundedRectangle(cornerRadius: 7, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: 7, style: .continuous).strokeBorder(LittlePalette.buttonBorder, lineWidth: 1))
- .fixedSize()
- .background(GeometryReader { g in
- Color.clear
- .onAppear { state.openButtonWidth = g.size.width }
- .onChange(of: g.size.width) { _, w in state.openButtonWidth = w }
- })
}
}
/// Icon in the pill: 26pt hover square, brighter glyph.
-struct LittleIcon: View {
- let symbol: String
- let size: CGFloat
- var hover = false
- var help: String = ""
- let action: () -> Void
- var body: some View {
- Button(action: action) {
- Image(systemName: symbol)
- .font(.system(size: size, weight: .regular))
- .foregroundStyle(hover ? LittlePalette.iconHot : LittlePalette.icon)
- .frame(width: 26, height: 26)
- .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(hover ? LittlePalette.iconHover : .clear))
- .contentShape(Rectangle())
+private final class LittleIconView: NSView {
+ private let glyph = NSImageView()
+ var hovered = false {
+ didSet {
+ glyph.contentTintColor = NSColor(hovered ? LittlePalette.iconHot : LittlePalette.icon)
+ layer?.backgroundColor = hovered ? NSColor(LittlePalette.iconHover).cgColor : nil
}
- .buttonStyle(.plain)
- .help(help)
}
+
+ init(symbol: String, size: CGFloat) {
+ super.init(frame: NSRect(x: 0, y: 0, width: 26, height: 26))
+ wantsLayer = true
+ layer?.cornerRadius = 6
+ layer?.cornerCurve = .continuous
+ glyph.image = SidebarSymbols.image(symbol, size: size)
+ glyph.imageScaling = .scaleNone
+ glyph.contentTintColor = NSColor(LittlePalette.icon)
+ glyph.frame = bounds
+ glyph.autoresizingMask = [.width, .height]
+ addSubview(glyph)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
}
/// Arc's LittleBrowserMoveMenu: "Search Spaces…" with a chevron-up button, then
/// one 54pt row per space (40pt tile with the emoji on the space colour).
-struct LittleSpacesPopup: View {
- let state: LittleWindowState
- let onPick: (UUID) -> Void
- let onClose: () -> Void
- @Environment(SidebarStore.self) private var store
- @State private var query = ""
- @State private var selected = 0
- @FocusState private var focused: Bool
-
- private var spaces: [Space] {
- let q = query.trimmingCharacters(in: .whitespaces).lowercased()
- let all = store.orderedSpaces
- return q.isEmpty ? all : all.filter { $0.title.lowercased().contains(q) }
- }
-
- var body: some View {
- let list = spaces
- VStack(spacing: 0) {
- HStack(spacing: 10) {
- Image(systemName: "magnifyingglass").font(.system(size: 13, weight: .medium)).foregroundStyle(LittlePalette.icon)
- TextField("Search Spaces…", text: $query)
- .textFieldStyle(.plain)
- .font(.system(size: 14))
- .foregroundStyle(.white.opacity(0.9))
- .focused($focused)
- .onSubmit { if list.indices.contains(selected) { onPick(list[selected].id) } }
- .onExitCommand { onClose() }
- .onMoveCommand { dir in
- guard !list.isEmpty else { return }
- if dir == .down { selected = (selected + 1) % list.count }
- if dir == .up { selected = (selected - 1 + list.count) % list.count }
- }
- Button { onClose() } label: {
- Image(systemName: "chevron.up")
- .font(.system(size: 11, weight: .bold))
- .foregroundStyle(.white.opacity(0.9))
- .frame(width: 28, height: 28)
- .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(LittlePalette.popupButton))
- }
- .buttonStyle(.plain)
- }
- .padding(.leading, 14)
- .padding(.trailing, 9)
- .frame(height: LittleMetrics.popupHeaderHeight)
- ForEach(Array(list.prefix(6).enumerated()), id: \.element.id) { i, s in
- Button { onPick(s.id) } label: {
- HStack(spacing: 12) {
- ZStack {
- RoundedRectangle(cornerRadius: 9, style: .continuous).fill(Color(hex: s.theme.accent ?? s.theme.colors.first ?? "#888888"))
- Text(s.emoji).font(.system(size: 20))
- }
- .frame(width: 40, height: 40)
- Text(s.title).font(.system(size: 15, weight: .semibold)).foregroundStyle(.white.opacity(0.88)).lineLimit(1)
- Spacer(minLength: 0)
- }
- .padding(.horizontal, 14)
- .frame(height: LittleMetrics.popupRowHeight)
- .background(i == selected ? LittlePalette.buttonHover : .clear)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .onHover { if $0 { selected = i } }
- }
+@MainActor
+final class LittleSpacesPopup: NSView, NSTextFieldDelegate {
+ private let state: LittleWindowState
+ private let store: SidebarStore
+ private let onPick: (UUID) -> Void
+ private let onClose: () -> Void
+ private let field = NSTextField()
+ private let close = NSView()
+ private var rows: [NSView] = []
+ private var list: [Space] = []
+ private var selected = 0 { didSet { refreshSelection() } }
+
+ init(state: LittleWindowState, store: SidebarStore, onPick: @escaping (UUID) -> Void, onClose: @escaping () -> Void) {
+ self.state = state
+ self.store = store
+ self.onPick = onPick
+ self.onClose = onClose
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.backgroundColor = LittlePalette.buttonNS.cgColor
+ layer?.cornerRadius = 12
+ layer?.cornerCurve = .continuous
+ layer?.masksToBounds = true
+ layer?.borderWidth = 1
+ layer?.borderColor = NSColor(LittlePalette.buttonBorder).cgColor
+ let h = LittleMetrics.popupHeaderHeight
+ let glass = NSImageView(frame: NSRect(x: 14, y: 0, width: 16, height: h))
+ glass.image = SidebarSymbols.image("magnifyingglass", size: 13, weight: .medium)
+ glass.contentTintColor = NSColor(LittlePalette.icon)
+ glass.imageScaling = .scaleNone
+ addSubview(glass)
+ field.isBordered = false
+ field.drawsBackground = false
+ field.focusRingType = .none
+ field.font = .systemFont(ofSize: 14)
+ field.textColor = NSColor.white.withAlphaComponent(0.9)
+ field.placeholderString = "Search Spaces…"
+ field.usesSingleLineMode = true
+ field.cell?.isScrollable = true
+ field.delegate = self
+ addSubview(field)
+ close.wantsLayer = true
+ close.layer?.cornerRadius = 6
+ close.layer?.cornerCurve = .continuous
+ close.layer?.backgroundColor = NSColor(LittlePalette.popupButton).cgColor
+ let up = NSImageView(frame: NSRect(x: 0, y: 0, width: 28, height: 28))
+ up.image = SidebarSymbols.image("chevron.up", size: 11, weight: .bold)
+ up.contentTintColor = NSColor.white.withAlphaComponent(0.9)
+ up.imageScaling = .scaleNone
+ close.addSubview(up)
+ addSubview(close)
+ // Set in init, so didSet doesn't run: highlight by hand.
+ selected = max(0, store.orderedSpaces.firstIndex { $0.id == state.targetSpaceID } ?? 0)
+ rebuild()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ override func viewDidMoveToWindow() {
+ super.viewDidMoveToWindow()
+ window?.makeFirstResponder(field)
+ }
+
+ private func rebuild() {
+ let q = field.stringValue.trimmingCharacters(in: .whitespaces).lowercased()
+ list = q.isEmpty ? store.orderedSpaces : store.orderedSpaces.filter { $0.title.lowercased().contains(q) }
+ rows.forEach { $0.removeFromSuperview() }
+ rows = list.prefix(6).map { s in
+ let row = FlippedView()
+ row.wantsLayer = true
+ let tile = NSView(frame: NSRect(x: 14, y: (LittleMetrics.popupRowHeight - 40) / 2, width: 40, height: 40))
+ tile.wantsLayer = true
+ tile.layer?.cornerRadius = 9
+ tile.layer?.cornerCurve = .continuous
+ tile.layer?.backgroundColor = NSColor(hex: s.theme.accent ?? s.theme.colors.first ?? "#888888").cgColor
+ let emoji = NSTextField.sidebarLabel(size: 20)
+ emoji.stringValue = s.emoji
+ emoji.alignment = .center
+ emoji.frame = NSRect(x: -SidebarText.inset, y: (40 - 25) / 2, width: 40 + 2 * SidebarText.inset, height: 25)
+ tile.addSubview(emoji)
+ row.addSubview(tile)
+ let title = NSTextField.sidebarLabel(size: 15, weight: .semibold)
+ title.stringValue = s.title
+ title.textColor = NSColor.white.withAlphaComponent(0.88)
+ title.frame = NSRect(x: 14 + 40 + 12 - SidebarText.inset, y: (LittleMetrics.popupRowHeight - 18) / 2,
+ width: LittleMetrics.popupWidth - 66 - 14 + 2 * SidebarText.inset, height: 18)
+ row.addSubview(title)
+ addSubview(row)
+ return row
}
- .frame(width: LittleMetrics.popupWidth)
- .background(LittlePalette.button)
- .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(LittlePalette.buttonBorder, lineWidth: 1))
- .onAppear {
- focused = true
- selected = max(0, store.orderedSpaces.firstIndex { $0.id == state.targetSpaceID } ?? 0)
+ needsLayout = true
+ refreshSelection()
+ }
+
+ private func refreshSelection() {
+ for (i, r) in rows.enumerated() {
+ r.layer?.backgroundColor = i == selected ? NSColor(LittlePalette.buttonHover).cgColor : nil
}
- .onChange(of: query) { _, _ in selected = 0 }
+ }
+
+ override func layout() {
+ super.layout()
+ let h = LittleMetrics.popupHeaderHeight, w = bounds.width
+ close.frame = NSRect(x: w - 9 - 28, y: (h - 28) / 2, width: 28, height: 28)
+ let fx: CGFloat = 14 + 16 + 10
+ let fh = ceil(field.intrinsicContentSize.height)
+ field.frame = NSRect(x: fx - SidebarText.inset, y: (h - fh) / 2, width: close.frame.minX - 10 - fx + 2 * SidebarText.inset, height: fh)
+ for (i, r) in rows.enumerated() {
+ r.frame = NSRect(x: 0, y: h + CGFloat(i) * LittleMetrics.popupRowHeight, width: w, height: LittleMetrics.popupRowHeight)
+ }
+ }
+
+ // MARK: Keys and pointer
+
+ func controlTextDidChange(_ obj: Notification) {
+ rebuild()
+ selected = 0
+ }
+
+ func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
+ switch selector {
+ case #selector(NSResponder.insertNewline(_:)):
+ if list.indices.contains(selected) { onPick(list[selected].id) }
+ case #selector(NSResponder.cancelOperation(_:)):
+ onClose()
+ case #selector(NSResponder.moveDown(_:)):
+ if !list.isEmpty { selected = (selected + 1) % list.count }
+ case #selector(NSResponder.moveUp(_:)):
+ if !list.isEmpty { selected = (selected - 1 + list.count) % list.count }
+ default:
+ return false
+ }
+ return true
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseMoved, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))
+ }
+
+ override func mouseMoved(with event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ if let i = rows.firstIndex(where: { $0.frame.contains(p) }), i != selected { selected = i }
+ }
+
+ override func mouseDown(with event: NSEvent) {}
+
+ override func mouseUp(with event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ if close.frame.contains(p) { onClose(); return }
+ if let i = rows.firstIndex(where: { $0.frame.contains(p) }), list.indices.contains(i) { onPick(list[i].id) }
}
}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 04e0e1f..f1ac175 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -15,7 +15,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
private(set) var browsers: BrowserManager!
private(set) var shell: ShellView!
private var commandPanel: CommandBarPanel!
- private var commandHost: NSHostingView<AnyView>!
+ private var commandHost: CommandBarView!
let tabSwitcher = TabSwitcher()
private let tabSwitcherPanel = TabSwitcherPanel()
private var spaceEditor: NSWindow?
@@ -81,18 +81,14 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let store = app.store
let palette = focusedSpace.theme.palette
- let env: (AnyView) -> AnyView = { v in
- AnyView(v.environment(store).environment(self.sidebarUI).environment(app.favicons).environment(\.sidebarActions, self.sidebarActions))
- }
shell = ShellView(frame: window.contentView!.bounds,
- background: SpaceBackground(palette: palette, pager: SpacePager(store: store, ui: sidebarUI)),
- sidebar: env(AnyView(SidebarRootView())),
- toolbar: env(AnyView(ContentToolbarView(palette: palette))),
- placeholder: AnyView(EmptyContentView(space: focusedSpace)),
- status: AnyView(StatusBubble(overlay: overlay)),
- toasts: AnyView(ToastStack(overlay: overlay, onDismiss: { [weak self] id in self?.removeToast(id) })),
- find: AnyView(FindBar(overlay: overlay, onFind: { [weak self] q, fwd in self?.find(q, forward: fwd) },
- onClose: { [weak self] in self?.hideFindBar() })))
+ background: SpaceBackgroundView(store: store, ui: sidebarUI),
+ sidebar: SidebarView(store: store, ui: sidebarUI, actions: sidebarActions, favicons: app.favicons),
+ toolbar: PaneToolbarView(paneTabID: nil, store: store, ui: sidebarUI, actions: sidebarActions),
+ status: StatusBubbleView(overlay: overlay),
+ toasts: ToastStackView(overlay: overlay, onDismiss: { [weak self] id in self?.removeToast(id) }),
+ find: FindBarView(overlay: overlay, onFind: { [weak self] q, fwd in self?.find(q, forward: fwd) },
+ onClose: { [weak self] in self?.hideFindBar() }))
shell.sidebarWidth = CGFloat(store.prefs.sidebarWidth)
shell.sidebarVisible = sidebarVisible
shell.showToolbar = store.settings.showToolbar
@@ -122,9 +118,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
sidebarUI.onPointerOverDraggableChange = { [weak window] over in window?.isMovableByWindowBackground = !over }
browsers.paneHost = { [weak self] id in self?.shell.card(for: id)?.webArea }
shell.makeToolbar = { [weak self] id in
- guard let self else { return AnyView(EmptyView()) }
- return AnyView(ContentToolbarView(palette: self.focusedSpace.theme.palette, paneTabID: id)
- .environment(self.store).environment(self.sidebarUI).environment(app.favicons).environment(\.sidebarActions, self.sidebarActions))
+ guard let self else { return NSView() }
+ return PaneToolbarView(paneTabID: id, store: self.store, ui: self.sidebarUI, actions: self.sidebarActions)
}
shell.onPaneResizeBegan = { [weak self] in self?.pageWindowsFollowLive = true }
shell.onPaneResizeEnded = { [weak self] factors in
@@ -136,10 +131,10 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
commandPanel = CommandBarPanel()
- commandHost = NSHostingView(rootView: AnyView(CommandBarView(controller: commandBar).environment(app.favicons)))
+ commandHost = CommandBarView(controller: commandBar, favicons: app.favicons)
commandPanel.contentView = commandHost
commandPanel.delegate = self
- tabSwitcherPanel.contentView = NSHostingView(rootView: TabSwitcherView(switcher: tabSwitcher).environment(app.favicons))
+ tabSwitcherPanel.contentView = TabSwitcherView(switcher: tabSwitcher, favicons: app.favicons)
tabSwitcher.onShow = { [weak self] in self?.showTabSwitcherPanel() }
tabSwitcher.onHide = { [weak self] in self?.hideTabSwitcherPanel() }
tabSwitcher.onCommit = { [weak self] id in
@@ -238,7 +233,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
// Toolbar buttons are ~34 pt wide and the click lands near the middle: the popup's
// right edge lines up with the button's (Chrome anchors popups that way).
- sidebarActions.runExtension = { [weak self] id in self?.runExtensionAction(id, buttonRightX: NSEvent.mouseLocation.x + 17) }
+ sidebarActions.runExtension = { [weak self] id in self?.runExtensionAction(id, buttonRightX: Self.extensionButtonRightX()) }
sidebarActions.showExtensionsMenu = { [weak self] in self?.showToolbarExtensionsMenu() }
// Popups from an extension's shortcut or chrome.action.openPopup() hang where the
// menu bar's do: under the toolbar at the card's right end of the window in use.
@@ -287,8 +282,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// views show beyond the palette they observe themselves.
if shownTheme != space.theme {
shownTheme = space.theme
- shell.backgroundHost.rootView = SpaceBackground(palette: palette, pager: SpacePager(store: store, ui: sidebarUI))
- shell.placeholderHost.rootView = AnyView(EmptyContentView(space: space))
+ shell.placeholderHost.wantsLayer = true
+ shell.placeholderHost.layer?.backgroundColor = (palette.isDark ? NSColor.white.withAlphaComponent(0.04) : NSColor.black.withAlphaComponent(0.03)).cgColor
shell.isDarkTheme = palette.isDark
window?.appearance = NSAppearance(named: palette.isDark ? .darkAqua : .aqua)
// Vibrant themes see through to the desktop like Arc; others are opaque.
@@ -317,10 +312,6 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let live = panes.filter { !elsewhere.contains($0) }
let liveFocus = selected.flatMap { elsewhere.contains($0) ? nil : $0 }
for c in shell.paneCards {
- if c.toolbarTheme != space.theme {
- c.toolbarTheme = space.theme
- c.toolbarHost.rootView = shell.makeToolbar?(c.tabID == ShellView.noTabID ? nil : c.tabID) ?? AnyView(EmptyView())
- }
c.showsElsewhere = elsewhere.contains(c.tabID)
c.elsewhereSnapshot = c.showsElsewhere ? app.runtime(for: c.tabID)?.snapshot : nil
}
@@ -431,7 +422,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
syncSidebarUI()
let colors = browsers.runtimes.compactMapValues { $0.backgroundColor.isEmpty ? nil : $0.backgroundColor }
if colors != shell.pageColors { shell.pageColors = colors }
- // Same rule as ContentToolbarView.cardHex.
+ // Same rule as PaneToolbarView's bar colour.
let bars = browsers.runtimes.compactMapValues { rt in HexColor.components(rt.themeColor) != nil ? rt.themeColor : nil }
if bars != shell.toolbarColors { shell.toolbarColors = bars }
if tabID == browsers.visibleTabID { window?.title = store.item(tabID)?.displayTitle ?? "Cra" }
@@ -530,7 +521,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
host.isVisible, !anchor.isHiddenOrHasHiddenAncestor {
// Aim at the bin's centre (screen coordinates are y-up, the offset is SwiftUI's y-down).
let glyph = host.convertToScreen(anchor.convert(anchor.bounds, to: nil))
- let bin = NSPoint(x: glyph.midX + LibraryButton.binOffset.width, y: glyph.midY - LibraryButton.binOffset.height)
+ let bin = NSPoint(x: glyph.midX + LibraryButtonView.binOffset.width, y: glyph.midY - LibraryButtonView.binOffset.height)
flight = DownloadFlight.launch(over: window, from: NSEvent.mouseLocation, to: bin)
}
let id = download.identifier
@@ -1434,6 +1425,17 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
sidebarUI.spaceSettleVelocity = 0
}
+ /// A space swipe of `steps` trackpad samples `dx` apart, 8 ms apart (cra://debug?swipe=).
+ func debugSpaceSwipe(dx: CGFloat, steps: Int) {
+ beginSpaceSwipe()
+ for i in 1...max(1, steps) {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.008 * Double(i)) { [weak self] in
+ self?.trackSpaceSwipe(by: dx, at: ProcessInfo.processInfo.systemUptime)
+ }
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.008 * Double(steps + 1)) { [weak self] in self?.endSpaceSwipe() }
+ }
+
private func trackSpaceSwipe(by dx: CGFloat, at time: TimeInterval) {
let width = max(1, shell.sidebarWidth)
swipeTravel += dx
@@ -1470,10 +1472,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
if !(0..<store.spaceOrder.count).contains(index + step) { step = 0 }
let remaining = CGFloat(step) - pages
sidebarUI.spaceSettleVelocity = abs(remaining) > 0.001 ? Double(max(-4, min(12, velocity / remaining))) : 0
- // The new space becomes the strip's page at once, with the swipe re-based so nothing moves,
- // and only the swipe springs home. It moves the strip as a render effect; animating the
- // page change moved every row's layout on every frame of the settle.
- let generation = sidebarUI.beginSpaceSettle()
+ // The new space becomes the strip's page at once and the swipe returns to rest; the space
+ // pager and the window tint spring from where they show to the page in Core Animation
+ // (SpacePagerView, PagedGradientView), so a busy main thread doesn't stop the settle.
if step != 0 {
var instant = Transaction()
instant.disablesAnimations = true
@@ -1482,11 +1483,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
store.focusSpace(store.spaceOrder[index + step], window: windowID)
}
}
- withAnimation(sidebarUI.spaceSettleAnimation, completionCriteria: .logicallyComplete) {
- sidebarUI.spaceSwipe = 0
- } completion: { [weak self] in
- self?.sidebarUI.endSpaceSettle(generation)
- }
+ sidebarUI.spaceSwipe = 0
// Clicks and shortcuts that switch spaces later start from rest.
DispatchQueue.main.async { [weak self] in self?.sidebarUI.spaceSettleVelocity = 0 }
}
@@ -1529,6 +1526,21 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
}
+ /// The right edge (screen x) of the pinned-extension button under the pointer, in the
+ /// toolbar or the sidebar's URL pill (also in the floating sidebar's panel), so a popup
+ /// hangs from the same place wherever the button was clicked (GitHub #8).
+ private static func extensionButtonRightX() -> CGFloat {
+ let mouse = NSEvent.mouseLocation
+ let number = NSWindow.windowNumber(at: mouse, belowWindowWithWindowNumber: 0)
+ if let w = NSApp.window(withWindowNumber: number), let content = w.contentView {
+ let p = w.convertPoint(fromScreen: mouse)
+ var v = content.hitTest(content.superview?.convert(p, from: nil) ?? p)
+ while let view = v, !(view is ToolbarGlyphButton) { v = view.superview }
+ if let button = v { return w.convertToScreen(button.convert(button.bounds, to: nil)).maxX }
+ }
+ return mouse.x + 17
+ }
+
/// No page for Chrome's popup to attach to (no tab open, no DevTools pipe, a page it
/// cannot reach): the popup page in a popup-sized window under the button, else the
/// options page, else Chrome's details page for the extension.
@@ -1543,6 +1555,20 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
}
+ func debugSiteControls() { showToolbarExtensionsMenu() }
+
+ func debugTabSwitcher() {
+ let theme = focusedSpace.theme
+ let dark = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ tabSwitcher.isDark = dark
+ tabSwitcher.highlight = theme.switcherHighlight(dark: dark)
+ tabSwitcher.palette = theme.palette
+ tabSwitcher.debugOpen(store.recentTabs(in: focusedSpaceID, limit: TabSwitcherMetrics.maxItems).compactMap { id in
+ guard let it = store.item(id), let tab = it.tab else { return nil }
+ return TabSwitcher.Item(id: id, title: it.displayTitle, iconKey: tab.iconKey, snapshot: browsers.runtime(for: id)?.snapshot)
+ })
+ }
+
/// Arc's sliders button (toolbar and URL pill): the Site Control Center, hung under the
/// button the pointer is on (buttons are 32 × 28).
private func showToolbarExtensionsMenu() {
@@ -2040,7 +2066,7 @@ final class CraWindow: NSWindow {
private func isTitleStrip(_ view: NSView?) -> Bool {
var v = view
while let current = v {
- if current is SidebarHostingView { return false }
+ if current is SidebarView { return false }
if let shell = current as? ShellView, shell.contentFullscreen { return false }
v = current.superview
}
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index 3b65944..ddf0ef7 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -1434,9 +1434,12 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
size_t result_size) override {
NSString* json = [[NSString alloc] initWithBytes:result length:result_size encoding:NSUTF8StringEncoding] ?: @"";
NSNumber* key = @(message_id);
+ // Capture the table, not `this`: the tab can close before this block runs, and
+ // CraBrowser's dealloc then frees the observer (read freed memory, crashed 29 Oct).
+ NSMutableDictionary<NSNumber*, void (^)(NSString*, NSString*)>* table = pending;
dispatch_async(dispatch_get_main_queue(), ^{
- void (^done)(NSString*, NSString*) = pending[key];
- [pending removeObjectForKey:key];
+ void (^done)(NSString*, NSString*) = table[key];
+ [table removeObjectForKey:key];
if (done) success ? done(json, nil) : done(nil, json);
});
}
@@ -2098,6 +2101,19 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {
- (BOOL)isHandlingSendEvent { return _handlingSendEvent; }
- (void)setHandlingSendEvent:(BOOL)handlingSendEvent { _handlingSendEvent = handlingSendEvent; }
+// A background test instance (CRA_TEST_BACKGROUND, HitchMonitor.swift) never takes the front:
+// Chromium activates the app whenever it shows one of its windows.
+static BOOL CraTestBackground(void) {
+ static BOOL background = [NSProcessInfo.processInfo.environment[@"CRA_TEST_BACKGROUND"] isEqualToString:@"1"];
+ return background;
+}
+- (void)activateIgnoringOtherApps:(BOOL)flag {
+ if (!CraTestBackground()) [super activateIgnoringOtherApps:flag];
+}
+- (void)activate {
+ if (!CraTestBackground()) [super activate];
+}
+
// A Chromium page view, wherever it lives: in its own window, or embedded in a Cra
// window's pane (EmbeddedPages.swift), where sendEvent's other two checks miss it.
static BOOL CraIsInPageView(NSView* v) {
diff --git a/docs/development.md b/docs/development.md
index b236108..1d4f08d 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -54,6 +54,19 @@ To measure smoothness, add `CRA_HITCH_LOG=/tmp/cra-hitch.log`: every main-thread
there delays input and scrolling too. Compare builds by running the same command
script against each.
+`CRA_TEST_BACKGROUND=1` keeps a test instance behind whatever you are using: its windows
+open at the back and it ignores every request to activate (Chromium's included). Launch it
+with `open -g -n --env …` so macOS doesn't bring it forward either. Two command-file hooks
+drive the sidebar without touching the pointer: `cra://debug?swipe=-14,22` plays a space
+swipe (22 trackpad samples of 14 pt) and `cra://debug?scroll=30,30,150,700` scrolls the
+scroll view at x 150, y 700 of the window (from its top left) 30 pt a frame for 30 frames.
+Measure them with `sample <pid> 6 1` and compare the main thread's busy time between builds.
+
+The sidebar's tab list and space pager are AppKit (`UI/Sidebar/List`): rows are plain
+layer-backed views rebuilt from the store when it changes, a swipe moves the pager's layers
+and the window tint (`PagedGradientView`) in Core Animation, and SwiftUI keeps the favorites,
+space header, top bar and dock.
+
Pages are embedded in their pane cards (`EmbeddedPages.swift`): Chromium's page views move
from their Chrome window into the card, like Arc and Dia, and the Chrome window stays behind
empty, click-through and never key. Pages go back into their window while DevTools is open.