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.

Search the space's open tabs with "%" Tab in the command bar (#49) (#69)

Victor Kildahl50ede00980f7
diff --git a/Packages/CraCore/Sources/CraCore/TabSearchScope.swift b/Packages/CraCore/Sources/CraCore/TabSearchScope.swift
new file mode 100644
index 0000000..57e8d75
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/TabSearchScope.swift
@@ -0,0 +1,50 @@
+import Foundation
+
+/// The command bar scoped to the open tabs of the window's space (#49). Arc 1.171 scopes the bar
+/// to a site or to its commands (`ScopedSearchType`: siteSearch, typeTravel) and has no tab scope;
+/// this one is offered, entered and left the way Arc's are: "%" shows "Search Tabs Tab" at the end
+/// of the field, Tab puts the pill before it, Backspace on the empty field brings "%" back and
+/// Escape returns the bar to how it opened.
+public enum TabSearchScope {
+ public static let name = "Tabs"
+ public static let trigger = "%"
+ /// A text score (0…100) below this matched only scattered letters ("gtb" in "GitHub"), which
+ /// confuse a list this short more than they help.
+ public static let minimumScore = 50.0
+
+ /// The typed text offers the scope.
+ public static func isOffered(by query: String) -> Bool {
+ query.trimmingCharacters(in: .whitespaces) == trigger
+ }
+
+ public struct Candidate<ID: Hashable>: Equatable {
+ public let id: ID
+ /// How well the typed text matches the title or address, 0…100; ignored with nothing typed.
+ public let score: Double
+ /// nil for a tab not opened since launch.
+ public let lastActive: Date?
+
+ public init(id: ID, score: Double, lastActive: Date?) {
+ self.id = id
+ self.score = score
+ self.lastActive = lastActive
+ }
+ }
+
+ /// The rows, best first. With nothing typed every tab, the most recently used first and tabs
+ /// not opened since launch last, in the order given (the sidebar's). Typed, only the tabs that
+ /// match, the best match first and the more recently used of two equal ones.
+ public static func rank<ID>(_ tabs: [Candidate<ID>], typed: Bool) -> [ID] {
+ let kept = typed ? tabs.filter { $0.score >= minimumScore } : tabs
+ return kept.enumerated().sorted { a, b in
+ let x = a.element, y = b.element
+ if typed, x.score != y.score { return x.score > y.score }
+ switch (x.lastActive, y.lastActive) {
+ case let (p?, q?) where p != q: return p > q
+ case (_?, nil): return true
+ case (nil, _?): return false
+ default: return a.offset < b.offset
+ }
+ }.map(\.element.id)
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/TabSearchScopeTests.swift b/Packages/CraCore/Tests/CraCoreTests/TabSearchScopeTests.swift
new file mode 100644
index 0000000..abe2b19
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/TabSearchScopeTests.swift
@@ -0,0 +1,43 @@
+import CraCore
+import Foundation
+import Testing
+
+/// The command bar's "%" scope (#49): what offers it and the order of its rows.
+struct TabSearchScopeTests {
+ typealias C = TabSearchScope.Candidate<String>
+ let now = Date(timeIntervalSinceReferenceDate: 800_000_000)
+
+ @Test(arguments: [("%", true), (" % ", true), ("%a", false), ("50%", false), ("%%", false), ("", false)])
+ func percentAloneOffersTheScope(query: String, offered: Bool) {
+ #expect(TabSearchScope.isOffered(by: query) == offered)
+ }
+
+ /// "%" Tab lists the space's tabs: the latest first, tabs not opened since launch after them
+ /// in sidebar order.
+ @Test func nothingTypedListsByRecency() {
+ let tabs = [
+ C(id: "unopened-a", score: 0, lastActive: nil),
+ C(id: "old", score: 0, lastActive: now.addingTimeInterval(-3600)),
+ C(id: "unopened-b", score: 0, lastActive: nil),
+ C(id: "new", score: 0, lastActive: now),
+ ]
+ #expect(TabSearchScope.rank(tabs, typed: false) == ["new", "old", "unopened-a", "unopened-b"])
+ }
+
+ /// Typed: scattered-letter matches drop out, the best match leads and recency breaks ties.
+ @Test func typedRanksByMatchThenRecency() {
+ let tabs = [
+ C(id: "scattered", score: 45, lastActive: now),
+ C(id: "word", score: 85, lastActive: now.addingTimeInterval(-60)),
+ C(id: "prefix-old", score: 100, lastActive: now.addingTimeInterval(-600)),
+ C(id: "prefix-new", score: 100, lastActive: now),
+ C(id: "url", score: 55, lastActive: nil),
+ ]
+ #expect(TabSearchScope.rank(tabs, typed: true) == ["prefix-new", "prefix-old", "word", "url"])
+ }
+
+ @Test func noTabsNoRows() {
+ #expect(TabSearchScope.rank([C](), typed: false).isEmpty)
+ #expect(TabSearchScope.rank([C(id: "a", score: 10, lastActive: now)], typed: true).isEmpty)
+ }
+}
diff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swift
index dd983fd..57ec578 100644
--- a/Sources/Cra/Services/SuggestionEngine.swift
+++ b/Sources/Cra/Services/SuggestionEngine.swift
@@ -44,8 +44,8 @@ struct SuggestionResult {
var items: [Suggestion] = []
/// Host (or more) to complete the typed text to, e.g. "github.com".
var inlineCompletion: String?
- /// The site Tab scopes the bar to ("Search YouTube Tab").
- var siteSearch: SiteSearch?
+ /// What Tab scopes the bar to ("Search YouTube Tab", "Search Tabs Tab").
+ var scope: CommandBarScope?
var query: String = ""
}
@@ -122,7 +122,7 @@ final class SuggestionEngine {
}
result.items = Array(items.prefix(Self.maxRows))
result.inlineCompletion = completion?.text
- result.siteSearch = SiteSearch.match(q, completion: completion?.text)
+ result.scope = TabSearchScope.isOffered(by: query) ? .tabs : SiteSearch.match(q, completion: completion?.text).map(CommandBarScope.site)
return result
}
@@ -136,6 +136,25 @@ final class SuggestionEngine {
return result
}
+ /// The bar scoped to a space's open tabs ("%" Tab): its favorites, pinned and today tabs but
+ /// the one in front, and nothing from history, the archive or the network.
+ func suggestions(for rawQuery: String, inTabsOf spaceID: UUID, currentTabID: UUID?) -> SuggestionResult {
+ let query = rawQuery.trimmingCharacters(in: .whitespaces)
+ let q = query.lowercased()
+ var result = SuggestionResult(query: query)
+ let tabs = store.visibleTabs(in: spaceID).filter { $0.id != currentTabID && $0.tab != nil }
+ let byID = Dictionary(tabs.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
+ let ranked = TabSearchScope.rank(tabs.map { tab in
+ TabSearchScope.Candidate(id: tab.id, score: q.isEmpty ? 0 : textScore(q, title: tab.displayTitle, url: tab.tab?.url ?? ""),
+ lastActive: tab.tab?.timeLastActiveAt)
+ }, typed: !q.isEmpty)
+ result.items = ranked.prefix(Self.maxRows).compactMap { byID[$0] }.map { tab in
+ Suggestion(id: "tab:\(tab.id)", kind: .switchToTab(tab.id), title: tab.displayTitle, subtitle: Self.humanURL(tab.tab?.url ?? ""),
+ url: tab.tab?.url, faviconKey: tab.tab?.faviconKey, symbol: nil, trailing: "Switch to Tab", score: 0, spaceID: spaceID)
+ }
+ return result
+ }
+
// MARK: Search index
/// What scoring needs from a title and a URL. Worked out per keystroke for every tab,
@@ -489,6 +508,22 @@ final class SuggestionEngine {
}
}
+/// What Tab scopes the bar to, a pill before the field until Backspace on the empty field or
+/// Escape (Arc's ScopedSearchType).
+enum CommandBarScope: Equatable {
+ /// Arc's Site Search: "youtube" Tab searches YouTube.
+ case site(SiteSearch)
+ /// The open tabs of the window's space (#49).
+ case tabs
+
+ var name: String {
+ switch self {
+ case .site(let site): return site.name
+ case .tabs: return TabSearchScope.name
+ }
+ }
+}
+
/// Arc's Site Search: the sites it seeds into Chromium's keyword table (active, not
/// auto-added), with the pill colour each one gets in the bar.
struct SiteSearch: Equatable {
diff --git a/Sources/Cra/UI/CommandBar/CommandBarController.swift b/Sources/Cra/UI/CommandBar/CommandBarController.swift
index 75400e7..4319e7b 100644
--- a/Sources/Cra/UI/CommandBar/CommandBarController.swift
+++ b/Sources/Cra/UI/CommandBar/CommandBarController.swift
@@ -28,11 +28,11 @@ final class CommandBarController {
var highlight: Color = .accentColor.opacity(0.4)
var focusedSpaceID: UUID?
var spaceName: (UUID) -> String = { _ in "" }
- /// Arc's Site Search: Tab on "youtube" scopes the bar to YouTube (a pill before the
- /// field) until Backspace on an empty field or Escape.
- private(set) var siteSearch: SiteSearch?
- /// What was typed when Tab entered the site search; Backspace puts it back.
- private var siteSearchTyped = ""
+ /// Arc's scoped search: Tab on "youtube" scopes the bar to YouTube, on "%" to the space's open
+ /// tabs (a pill before the field) until Backspace on an empty field or Escape.
+ private(set) var scope: CommandBarScope?
+ /// What was typed when Tab entered the scope; Backspace puts it back.
+ private var scopeTyped = ""
private var openedPrefill: String?
unowned let engine: SuggestionEngine
@@ -46,7 +46,7 @@ final class CommandBarController {
}
var placeholder: String {
- if siteSearch != nil { return "Search…" }
+ if scope != nil { return "Search…" }
switch mode {
case .newTab: return "Search or enter URL…"
case .editURL: return "Edit URL or search…"
@@ -56,7 +56,7 @@ final class CommandBarController {
func open(mode: CommandBarMode, prefill: String?) {
engine.resetIndex()
self.mode = mode
- siteSearch = nil
+ scope = nil
openedPrefill = prefill
query = prefill ?? ""
fieldText = query
@@ -80,8 +80,13 @@ final class CommandBarController {
func update(query newQuery: String, allowCompletion: Bool) {
query = newQuery
self.allowCompletion = allowCompletion
- if let site = siteSearch {
- result = engine.suggestions(for: newQuery, in: site)
+ if let scope {
+ switch scope {
+ case .site(let site):
+ result = engine.suggestions(for: newQuery, in: site)
+ case .tabs:
+ result = engine.suggestions(for: newQuery, inTabsOf: focusedSpaceID ?? store.focusedSpaceID, currentTabID: store.selectedTabID)
+ }
selectedIndex = 0
previewText = nil
return
@@ -100,7 +105,7 @@ final class CommandBarController {
/// The search engine answered: list again, keeping the selected row where it still is.
private func relist() {
- guard siteSearch == nil else { return }
+ guard scope == nil else { return }
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 }
@@ -140,25 +145,25 @@ final class CommandBarController {
}
}
- /// Tab on text that starts a site search's host: scope the bar to that site.
- func enterSiteSearch() -> Bool {
- guard siteSearch == nil, previewText == nil, let site = result.siteSearch else { return false }
- siteSearchTyped = query
- siteSearch = site
+ /// Tab on text that starts a site search's host, or on "%": scope the bar to it.
+ func enterScope() -> Bool {
+ guard scope == nil, previewText == nil, let offered = result.scope else { return false }
+ scopeTyped = query
+ scope = offered
pushFieldText("")
return true
}
/// Backspace on the empty scoped field: back to what was typed, the hint showing again.
- func leaveSiteSearch() {
- guard siteSearch != nil else { return }
- siteSearch = nil
- pushFieldText(siteSearchTyped)
+ func leaveScope() {
+ guard scope != nil else { return }
+ scope = nil
+ pushFieldText(scopeTyped)
}
- /// Escape in a site search goes back to how the bar opened rather than closing it (Arc).
- func cancelSiteSearch() {
- guard siteSearch != nil else { return }
+ /// Escape in a scope goes back to how the bar opened rather than closing it (Arc).
+ func cancelScope() {
+ guard scope != nil else { return }
open(mode: mode, prefill: openedPrefill)
}
@@ -181,6 +186,8 @@ final class CommandBarController {
func commit(forceNewTab: Bool) {
let selected = result.items.indices.contains(selectedIndex) ? result.items[selectedIndex] : nil
+ // No tab matched: Return has nowhere to go, and the tabs scope never searches the web.
+ if scope == .tabs, selected == nil { return }
var typed = query
// Enter on the typed row with an inline completion goes to the completion.
if selectedIndex == 0, let c = result.inlineCompletion, selected?.id == "typed" { typed = c }
@@ -196,7 +203,7 @@ final class CommandBarController {
func close() {
guard isOpen else { return }
isOpen = false
- siteSearch = nil
+ scope = nil
engine.resetIndex()
onClose()
}
diff --git a/Sources/Cra/UI/CommandBar/CommandBarView.swift b/Sources/Cra/UI/CommandBar/CommandBarView.swift
index e24d35d..105fe4e 100644
--- a/Sources/Cra/UI/CommandBar/CommandBarView.swift
+++ b/Sources/Cra/UI/CommandBar/CommandBarView.swift
@@ -20,8 +20,8 @@ final class CommandBarView: NSView {
private let leadingIcon = NSImageView()
private let text: CommandTextField
private let info = NSImageView()
- /// Site Search: the scoped site's pill before the field, and "Search YouTube Tab" at the
- /// end of the row while the typed text would enter it (Arc 1.170, measured at 2x).
+ /// Scoped search: the scope's pill before the field, and "Search YouTube Tab" at the end of
+ /// the row while the typed text would enter it (Arc 1.170, measured at 2x).
private let pill = NSView()
private let pillLabel = NSTextField.sidebarLabel(size: 13, weight: .semibold)
private let hint = NSTextField.sidebarLabel(size: 13, weight: .semibold)
@@ -105,17 +105,20 @@ final class CommandBarView: NSView {
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
- let site = c.siteSearch
- info.isHidden = !c.query.isEmpty || site != nil
+ let scope = c.scope
+ // A site's brand colour; the tabs scope takes the space's, the colour of its rows.
+ let highlight: NSColor
+ if case .site(let site) = scope { highlight = NSColor(hex: site.color) } else { highlight = NSColor(c.highlight) }
+ info.isHidden = !c.query.isEmpty || scope != nil
divider.isHidden = items.isEmpty
- pill.isHidden = site == nil
- if let site {
- let color = NSColor(hex: site.color)
+ pill.isHidden = scope == nil
+ if let scope {
+ let color = highlight.withAlphaComponent(1)
pill.layer?.backgroundColor = color.cgColor
pill.layer?.shadowColor = color.cgColor
- pillLabel.stringValue = site.name
+ pillLabel.stringValue = scope.name
}
- let offered = site == nil && c.previewText == nil ? c.result.siteSearch : nil
+ let offered = scope == nil && c.previewText == nil ? c.result.scope : nil
hint.isHidden = offered == nil
keycap.isHidden = offered == nil
if let offered {
@@ -128,7 +131,7 @@ final class CommandBarView: NSView {
// Follows the row the arrows moved to; otherwise the completing top match.
let previewing = c.previewText != nil && items.indices.contains(c.selectedIndex)
let row = previewing ? items[c.selectedIndex] : items.first
- if site == nil, let s = row, let key = s.faviconKey, s.id != "typed", let img = favicons.image(forKey: key),
+ if scope == nil, let s = row, let key = s.faviconKey, s.id != "typed", let img = favicons.image(forKey: key),
previewing || c.result.inlineCompletion != nil || c.mode == .editURL {
leadingIcon.imageScaling = .scaleProportionallyUpOrDown
leadingIcon.image = img
@@ -157,7 +160,6 @@ final class CommandBarView: NSView {
rows.append(r)
addSubview(r)
}
- let highlight = site.map { NSColor(hex: $0.color) } ?? NSColor(c.highlight)
for (i, r) in rows.enumerated() {
guard i < items.count else { r.isHidden = true; continue }
r.isHidden = false
diff --git a/Sources/Cra/UI/CommandBar/CommandTextField.swift b/Sources/Cra/UI/CommandBar/CommandTextField.swift
index 233791d..1870ca9 100644
--- a/Sources/Cra/UI/CommandBar/CommandTextField.swift
+++ b/Sources/Cra/UI/CommandBar/CommandTextField.swift
@@ -132,9 +132,9 @@ final class CommandTextField {
controller.commit(forceNewTab: cmd)
return true
case #selector(NSResponder.cancelOperation(_:)):
- if controller.siteSearch != nil { controller.cancelSiteSearch() } else { controller.close() }
+ if controller.scope != nil { controller.cancelScope() } else { controller.close() }
return true
- case #selector(NSResponder.insertTab(_:)) where controller.enterSiteSearch():
+ case #selector(NSResponder.insertTab(_:)) where controller.enterScope():
return true
case #selector(NSResponder.insertTab(_:)), #selector(NSResponder.moveRight(_:)), #selector(NSResponder.moveToEndOfLine(_:)):
if pendingCompletion != nil, textView.selectedRange.length > 0 {
@@ -147,8 +147,8 @@ final class CommandTextField {
}
return selector == #selector(NSResponder.insertTab(_:))
case #selector(NSResponder.deleteBackward(_:)):
- if controller.siteSearch != nil, textView.string.isEmpty {
- controller.leaveSiteSearch()
+ if controller.scope != nil, textView.string.isEmpty {
+ controller.leaveScope()
return true
}
if pendingCompletion != nil, textView.selectedRange.length > 0 {
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index 5a1e620..ee94694 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -80,6 +80,13 @@ Legend: [O] observed in shipped artifact or data file, [I] inference, [U] unknow
in the site's colour (hard-coded, e.g. YouTube #FF0000, GitHub #743FC7; glow in the same colour) before the
field, placeholder "Search…", rows reduced to the typed search tinted with that colour. Backspace on the empty
field drops the pill and puts back what was typed; Escape returns to how the bar opened. Cra: SiteSearch.all.
+- [O] Scopes (1 Nov, Arc 1.171 Swift field names): `ScopedSearchType` has two cases, `siteSearch` and `typeTravel`;
+ there is no tab scope. The bar's state keeps `scopedSearchType`, `scopedSearchColor`,
+ `queryBeforeEnteringScopedSearch` (what Backspace puts back) and `postScopedSearchRestoration` (Escape); the
+ pill is `CommandBarInputScopedSearchPillView`. `migratedToTabOnlySiteSearchTrigger` and
+ `siteSearchSpaceTriggerEnabled` show Space was a trigger once and Tab is the only one now. Cra's "%" tab scope
+ (#49, Zen's idea) reuses all of it: "%" offers "Search Tabs Tab", the pill takes the space's colour (Arc has no
+ colour for a scope that isn't a site), rows are the bar's own tab rows. Cra: TabSearchScope, CommandBarScope.
- [O] Sidebar glyphs (29 Oct, 1x and 2x captures, fitted pixel by pixel): the tab row's hover ✕ is two 2 pt
round-capped strokes 4.25 pt out from a centre on a whole point, white 0.6 over the hover fill; at 1x it is
perfectly symmetric (176/142/85), which no SF Symbol size reproduces (xmark 13.5 bold is closest at 2x but