diff --git a/Copy/App/AppCoordinator.swift b/Copy/App/AppCoordinator.swift index 21f1af8..ff979e8 100644 --- a/Copy/App/AppCoordinator.swift +++ b/Copy/App/AppCoordinator.swift @@ -54,7 +54,8 @@ final class AppCoordinator { hideDuringScreenSharing: settings.hideDuringScreenSharing, compactShelf: settings.compactShelf, theme: settings.shelfTheme, - floatingShelf: settings.floatingShelf) { [weak self] in + floatingShelf: settings.floatingShelf, + miniShelfSize: settings.miniShelfSize.size) { [weak self] in guard let self else { return NSView() } let host = ShelfHostingView(rootView: ShelfRootView(viewModel: self.shelfViewModel)) // Drags onto the pinboard tabs (cards to file, tabs to reorder) are tracked by @@ -96,6 +97,8 @@ final class AppCoordinator { event.modifierFlags.intersection([.command, .option, .control]).isEmpty, let chars = event.charactersIgnoringModifiers, chars.count == 1, let first = chars.first, first.isLetter { + // The mini shelf searches only once its lens button opens the field. + if viewModel.isMiniShelf && !viewModel.miniSearchShown { return true } viewModel.updateSearchText(viewModel.searchQuery.text + (event.characters ?? chars)) viewModel.focusSearchRequested = true return true @@ -124,6 +127,8 @@ final class AppCoordinator { (1...9).contains(digitValue) { if digitValue == 1 { viewModel.selectTab(.history) + } else if viewModel.isMiniShelf && !viewModel.miniShowsPinboards { + // No pinboard column showing, so no board to switch to. } else { let index = digitValue - 2 if viewModel.pinboards.indices.contains(index), let id = viewModel.pinboards[index].id { @@ -148,15 +153,25 @@ final class AppCoordinator { // never falls through to the plain ⌘V paste action below. let shortcutModifiers = event.modifierFlags.intersection([.command, .option, .control, .shift]) switch event.keyCode { - case 123: // left arrow + // The mini shelf lists its items top to bottom; its left/right arrows stay with + // the search field. + case 125 where viewModel.isMiniShelf: // down arrow + viewModel.moveSelection(1) + return true + case 126 where viewModel.isMiniShelf: // up arrow + viewModel.moveSelection(-1) + return true + case 123 where !viewModel.isMiniShelf: // left arrow viewModel.moveSelection(-1) return true - case 124: // right arrow + case 124 where !viewModel.isMiniShelf: // right arrow viewModel.moveSelection(1) return true case 53: // escape if viewModel.previewShown { viewModel.previewShown = false + } else if viewModel.miniSearchShown { + viewModel.closeMiniSearch() } else if !viewModel.searchQuery.isEmpty { viewModel.clearSearch() } else { @@ -468,6 +483,9 @@ final class AppCoordinator { settings.onCompactShelfChange = { [weak self] compact in self?.shelfController.setCompactShelf(compact) } + settings.onMiniShelfSizeChange = { [weak self] size in + self?.shelfController.setMiniShelfSize(size.size) + } settings.onShelfThemeChange = { [weak self] theme in self?.shelfController.setTheme(theme) self?.pasteStackController.setTheme(theme) @@ -626,19 +644,26 @@ final class AppCoordinator { /// `shelfViewModel`/`shelfController` are both created once and reused for the /// app's lifetime, so without this the permission banner would only ever reflect /// whatever was true the very first time the shelf ever appeared. - func toggleShelf() { - if !shelfController.isVisible { - shelfViewModel.refreshPermissionState() + /// `mode` nil opens the one chosen in Settings (`SettingsStore.shelfMode`). + func toggleShelf(mode: ShelfMode? = nil) { + if shelfController.isVisible { + shelfController.hide(restoreFocus: true) + } else { + showShelf(mode: mode ?? settings.shelfMode) } - shelfController.toggle() + } + + private func showShelf(mode: ShelfMode) { + shelfViewModel.refreshPermissionState() + shelfViewModel.prepareToShow(mini: mode == .mini) + shelfController.show(mode: mode) } /// Opens the shelf (if not already open) and immediately shows `CreateItemSheet`, /// for the status menu's "New Item…" action. func newItem() { if !shelfController.isVisible { - shelfViewModel.refreshPermissionState() - shelfController.show() + showShelf(mode: settings.shelfMode) } shelfViewModel.beginCreate() } @@ -671,8 +696,7 @@ final class AppCoordinator { /// the user presses the hotkey again to actually advance once the shelf is visible. func selectNextPinboard() { guard shelfController.isVisible else { - shelfViewModel.refreshPermissionState() - shelfController.show() + showShelf(mode: settings.shelfMode) return } let pinboards = shelfViewModel.pinboards diff --git a/Copy/App/AppDelegate.swift b/Copy/App/AppDelegate.swift index e888d35..82bb416 100644 --- a/Copy/App/AppDelegate.swift +++ b/Copy/App/AppDelegate.swift @@ -6,6 +6,9 @@ import Sparkle extension KeyboardShortcuts.Name { static let toggleShelf = Self("toggleShelf", initial: .init(.v, modifiers: [.command, .shift])) + /// No default shortcut — the user opts in from Settings. Opens whichever shelf + /// `toggleShelf` doesn't (`SettingsStore.shelfMode`), so both stay a keystroke away. + static let toggleAlternateShelf = Self("toggleAlternateShelf") static let togglePasteStack = Self("togglePasteStack", initial: .init(.c, modifiers: [.command, .shift])) static let pasteNextFromStack = Self("pasteNextFromStack", initial: .init(.n, modifiers: [.control, .option, .command])) /// No default shortcut — the user opts in from Settings. Pastes the most recent @@ -161,6 +164,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { KeyboardShortcuts.onKeyDown(for: .toggleShelf) { [weak self] in self?.coordinator.toggleShelf() } + KeyboardShortcuts.onKeyDown(for: .toggleAlternateShelf) { [weak self] in + guard let coordinator = self?.coordinator else { return } + coordinator.toggleShelf(mode: coordinator.settings.shelfMode.other) + } KeyboardShortcuts.onKeyDown(for: .togglePasteStack) { [weak self] in self?.coordinator.togglePasteStack() } diff --git a/Copy/Settings/GeneralSettings.swift b/Copy/Settings/GeneralSettings.swift index 1cdc927..3a42f5e 100644 --- a/Copy/Settings/GeneralSettings.swift +++ b/Copy/Settings/GeneralSettings.swift @@ -21,12 +21,33 @@ struct GeneralSettings: View { var body: some View { Form { + Section { + Picker("Shelf Layout", selection: $settings.shelfMode) { + ForEach(ShelfMode.allCases) { mode in Text(mode.title).tag(mode) } + } + .pickerStyle(.segmented) + Picker("Mini Shelf Size", selection: $settings.miniShelfSize) { + ForEach(MiniShelfSize.allCases) { size in Text(size.title).tag(size) } + } + .pickerStyle(.segmented) + // Only applies while the layout is Mini. + .disabled(settings.shelfMode == .full) + } footer: { + Text(settings.shelfMode == .full + ? "Open Copy shows the full shelf along the bottom of the screen. Set a shortcut for the mini shelf in Shortcuts." + : "Open Copy shows the mini shelf above the text cursor, or at the pointer when the app doesn't report one. Set a shortcut for the full shelf in Shortcuts.") + .font(.footnote) + .foregroundStyle(.secondary) + } + Section { Picker("Shelf Size", selection: $settings.compactShelf) { Text("Standard").tag(false) Text("Compact").tag(true) } .pickerStyle(.segmented) + // Only applies while the layout is Full. + .disabled(settings.shelfMode == .mini) } footer: { Text("Compact shows smaller cards so more fit in the shelf at once.") .font(.footnote) @@ -39,6 +60,8 @@ struct GeneralSettings: View { Text("Floating").tag(true) } .pickerStyle(.segmented) + // Only applies while the layout is Full. + .disabled(settings.shelfMode == .mini) } footer: { Text("Floating adds space around the shelf and rounds every corner.") .font(.footnote) diff --git a/Copy/Settings/SettingsStore.swift b/Copy/Settings/SettingsStore.swift index 46aee17..8078ede 100644 --- a/Copy/Settings/SettingsStore.swift +++ b/Copy/Settings/SettingsStore.swift @@ -49,6 +49,45 @@ enum ShelfTheme: String, CaseIterable, Identifiable { } } +/// Which shelf the Open Copy hotkey opens: the full-width shelf at the screen's edge, or +/// the mini shelf above the text cursor. +enum ShelfMode: String, CaseIterable, Identifiable { + case full, mini + var id: Self { self } + var title: String { self == .full ? "Full" : "Mini" } + var other: ShelfMode { self == .full ? .mini : .full } +} + +/// The mini shelf's three sizes, and how many lines of each card's text they show. +enum MiniShelfSize: String, CaseIterable, Identifiable { + case small, medium, large + var id: Self { self } + + var title: String { + switch self { + case .small: return "Small" + case .medium: return "Medium" + case .large: return "Large" + } + } + + var size: CGSize { + switch self { + case .small: return CGSize(width: 280, height: 320) + case .medium: return CGSize(width: 340, height: 400) + case .large: return CGSize(width: 400, height: 480) + } + } + + var previewLines: Int { + switch self { + case .small: return 1 + case .medium: return 2 + case .large: return 3 + } + } +} + /// How long unfavorited, unpinned history items are kept before pruning. enum RetentionPeriod: String, CaseIterable { case unlimited @@ -159,6 +198,8 @@ final class SettingsStore { static let hideSecretsKey = "hideSecrets" static let secretLifetimeKey = "secretLifetime" static let pasteStackExternalAccessKey = "pasteStackExternalAccessEnabled" + static let shelfModeKey = "shelfMode" + static let miniShelfSizeKey = "miniShelfSize" var retention: RetentionPeriod { didSet { @@ -255,6 +296,26 @@ final class SettingsStore { } @ObservationIgnored var onFloatingShelfChange: ((Bool) -> Void)? + /// Which shelf the Open Copy hotkey opens. Full by default. The other one has its own + /// optional hotkey (`KeyboardShortcuts.Name.toggleAlternateShelf`). + var shelfMode: ShelfMode { + didSet { + guard shelfMode != oldValue else { return } + defaults.set(shelfMode.rawValue, forKey: Self.shelfModeKey) + } + } + + /// Pushed to the panel controller by `onMiniShelfSizeChange`, which resizes an open + /// mini shelf in place. + var miniShelfSize: MiniShelfSize { + didSet { + guard miniShelfSize != oldValue else { return } + defaults.set(miniShelfSize.rawValue, forKey: Self.miniShelfSizeKey) + onMiniShelfSizeChange?(miniShelfSize) + } + } + @ObservationIgnored var onMiniShelfSizeChange: ((MiniShelfSize) -> Void)? + /// Masks secrets on cards, previews and titles (`SecretDetector`). Display only: the /// stored and pasted text is unchanged. var hideSecrets: Bool { @@ -388,6 +449,9 @@ final class SettingsStore { favoritesEnabled = (defaults.object(forKey: Self.favoritesEnabledKey) as? Bool) ?? true floatingShelf = (defaults.object(forKey: Self.floatingShelfKey) as? Bool) ?? false compactShelf = (defaults.object(forKey: Self.compactShelfKey) as? Bool) ?? false + shelfMode = defaults.string(forKey: Self.shelfModeKey).flatMap(ShelfMode.init(rawValue:)) ?? .full + miniShelfSize = defaults.string(forKey: Self.miniShelfSizeKey) + .flatMap(MiniShelfSize.init(rawValue:)) ?? .medium if let raw = defaults.string(forKey: Self.shelfThemeKey), let saved = ShelfTheme(rawValue: raw) { shelfTheme = saved } else { diff --git a/Copy/Settings/ShortcutsSettings.swift b/Copy/Settings/ShortcutsSettings.swift index 2edb8cd..23cc449 100644 --- a/Copy/Settings/ShortcutsSettings.swift +++ b/Copy/Settings/ShortcutsSettings.swift @@ -15,6 +15,8 @@ struct ShortcutsSettings: View { KeyboardShortcuts.Recorder("Open Copy:", name: .toggleShelf) { _ in settings.onShelfHotkeyChange?() } + KeyboardShortcuts.Recorder(settings.shelfMode == .full ? "Open Mini Shelf:" : "Open Full Shelf:", + name: .toggleAlternateShelf) KeyboardShortcuts.Recorder("Paste Stack:", name: .togglePasteStack) KeyboardShortcuts.Recorder("Quick Paste Latest:", name: .quickPasteLatest) KeyboardShortcuts.Recorder("Next Pinboard:", name: .nextPinboard) diff --git a/Copy/Shelf/ItemCardView.swift b/Copy/Shelf/ItemCardView.swift index e43a400..5a3b534 100644 --- a/Copy/Shelf/ItemCardView.swift +++ b/Copy/Shelf/ItemCardView.swift @@ -221,106 +221,24 @@ struct ItemCardView: View { // never animates content changes; skipped under Reduce Motion. .animation(reduceMotion ? nil : .spring(response: 0.26, dampingFraction: 0.72), value: isSelected) .contextMenu { - if canShowInHistory { - Button("Show in History", action: onShowInHistory) - .keyboardShortcut("g", modifiers: .command) - Divider() - } - Button("Paste", action: onPaste) - Button("Paste as Plain Text", action: onPastePlain) - if item.kind == .link || item.kind == .file { - Button("Open", action: onOpen) - .keyboardShortcut("o", modifiers: .command) - } - if item.recognizedText?.isEmpty == false { - Button("Copy Text", action: onCopyText) - } - if item.kind == .file, !quickLookURLs.isEmpty { - Button("Quick Look", action: onQuickLook) - } - if item.kind == .image { - Button("Rotate Left") { onRotate(false) } - Button("Rotate Right") { onRotate(true) } - } - Divider() - if isEditable { - Button("Edit…", action: onEdit) - .keyboardShortcut("e", modifiers: .command) - } else if item.kind == .color { - Button("Adjust Color…", action: onAdjustColor) - } - Button("Rename…", action: onBeginInlineRename) - if favoritesEnabled { - Button(item.isFavorite ? "Unfavorite" : "Favorite", action: onToggleFavorite) - } - Menu("Add to Pinboard") { - if pinboards.isEmpty { - Text("No Pinboards") - } else { - ForEach(pinboards, id: \.id) { pinboard in - Button { - if let id = pinboard.id { onAddToPinboard(id) } - } label: { - Label(pinboard.name, systemImage: pinboard.symbol) - } - } - } - } - Button("Add to Paste Stack", action: onAddToPasteStack) - if isEditable, item.plainText?.isEmpty == false { - Button("Split into Paste Stack…", action: onSplitToPasteStack) - } - if currentPinboardID != nil { - Button("Remove from Pinboard", action: onRemoveFromPinboard) - } - Divider() - Button("Delete", role: .destructive, action: onDelete) + CardContextMenu( + item: item, pinboards: pinboards, currentPinboardID: currentPinboardID, + favoritesEnabled: favoritesEnabled, canShowInHistory: canShowInHistory, + hasQuickLook: item.kind == .file && !quickLookURLs.isEmpty, + onPaste: onPaste, onPastePlain: onPastePlain, onEdit: onEdit, onAdjustColor: onAdjustColor, + onRename: onBeginInlineRename, onToggleFavorite: onToggleFavorite, + onAddToPinboard: onAddToPinboard, onRemoveFromPinboard: onRemoveFromPinboard, + onAddToPasteStack: onAddToPasteStack, onSplitToPasteStack: onSplitToPasteStack, + onCopyText: onCopyText, onQuickLook: onQuickLook, onOpen: onOpen, + onShowInHistory: onShowInHistory, onRotate: onRotate, onDelete: onDelete) } .onDrag(dragProvider) { dragPreview } .modifier(CardClickGesture(onClick: onClick)) } - /// A small chip shown under the cursor while dragging, instead of SwiftUI's default - /// full-size snapshot of the card. The full card covered the little pinboard tabs, - /// making it impossible to tell which one you were about to drop onto; this keeps the - /// tabs (and their drop highlight) visible. + /// A small chip shown under the cursor while dragging (see `CardDragPreview`). private var dragPreview: some View { - HStack(spacing: 6) { - dragPreviewGlyph - Text(item.displayTitle(hidingSecrets: masksSecrets)) - .font(.system(size: 12, weight: .medium)) - .lineLimit(1) - .truncationMode(.tail) - if dragBadgeCount > 1 { - Text("+\(dragBadgeCount - 1)") - .font(.system(size: 11, weight: .bold, design: .rounded)) - .foregroundStyle(.white) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Capsule().fill(Color.accentColor)) - } - } - .padding(.horizontal, 10) - .padding(.vertical, 7) - .frame(maxWidth: 240) - .background(Capsule().fill(Color(nsColor: .windowBackgroundColor))) - .overlay(Capsule().stroke(Color.primary.opacity(0.15), lineWidth: 1)) - } - - @ViewBuilder private var dragPreviewGlyph: some View { - Group { - if item.kind == .image { - Image(systemName: "photo").foregroundStyle(.secondary) - } else if item.kind == .color { - Circle().fill(Tokens.color(fromHex: item.plainText ?? "")) - } else if let icon = AppIconCache.icon(forBundleID: item.appBundleID) { - Image(nsImage: icon).resizable() - } else { - Image(systemName: "doc.on.clipboard").foregroundStyle(.secondary) - } - } - .font(.system(size: 13)) - .frame(width: 16, height: 16) + CardDragPreview(item: item, masksSecrets: masksSecrets, badgeCount: dragBadgeCount) } private var header: some View { @@ -544,6 +462,146 @@ struct ItemCardView: View { } } +/// A card's right-click menu, shared by the full shelf's cards and the mini shelf's rows. +struct CardContextMenu: View { + let item: ClipItem + let pinboards: [Pinboard] + let currentPinboardID: Int64? + let favoritesEnabled: Bool + let canShowInHistory: Bool + let hasQuickLook: Bool + let onPaste: () -> Void + let onPastePlain: () -> Void + let onEdit: () -> Void + let onAdjustColor: () -> Void + let onRename: () -> Void + let onToggleFavorite: () -> Void + let onAddToPinboard: (Int64) -> Void + let onRemoveFromPinboard: () -> Void + let onAddToPasteStack: () -> Void + let onSplitToPasteStack: () -> Void + let onCopyText: () -> Void + let onQuickLook: () -> Void + let onOpen: () -> Void + let onShowInHistory: () -> Void + let onRotate: (Bool) -> Void + let onDelete: () -> Void + + private var isEditable: Bool { + switch item.kind { + case .text, .richText, .link: return true + case .image, .file, .color: return false + } + } + + var body: some View { + if canShowInHistory { + Button("Show in History", action: onShowInHistory) + .keyboardShortcut("g", modifiers: .command) + Divider() + } + Button("Paste", action: onPaste) + Button("Paste as Plain Text", action: onPastePlain) + if item.kind == .link || item.kind == .file { + Button("Open", action: onOpen) + .keyboardShortcut("o", modifiers: .command) + } + if item.recognizedText?.isEmpty == false { + Button("Copy Text", action: onCopyText) + } + if hasQuickLook { + Button("Quick Look", action: onQuickLook) + } + if item.kind == .image { + Button("Rotate Left") { onRotate(false) } + Button("Rotate Right") { onRotate(true) } + } + Divider() + if isEditable { + Button("Edit…", action: onEdit) + .keyboardShortcut("e", modifiers: .command) + } else if item.kind == .color { + Button("Adjust Color…", action: onAdjustColor) + } + Button("Rename…", action: onRename) + if favoritesEnabled { + Button(item.isFavorite ? "Unfavorite" : "Favorite", action: onToggleFavorite) + } + Menu("Add to Pinboard") { + if pinboards.isEmpty { + Text("No Pinboards") + } else { + ForEach(pinboards, id: \.id) { pinboard in + Button { + if let id = pinboard.id { onAddToPinboard(id) } + } label: { + Label(pinboard.name, systemImage: pinboard.symbol) + } + } + } + } + Button("Add to Paste Stack", action: onAddToPasteStack) + if isEditable, item.plainText?.isEmpty == false { + Button("Split into Paste Stack…", action: onSplitToPasteStack) + } + if currentPinboardID != nil { + Button("Remove from Pinboard", action: onRemoveFromPinboard) + } + Divider() + Button("Delete", role: .destructive, action: onDelete) + } +} + +/// A small chip shown under the cursor while dragging a card, instead of SwiftUI's default +/// full-size snapshot of it. The full card covered the little pinboard tabs, making it +/// impossible to tell which one you were about to drop onto; this keeps the tabs (and +/// their drop highlight) visible. +struct CardDragPreview: View { + let item: ClipItem + let masksSecrets: Bool + /// How many cards the drag carries; more than one shows a "+N" badge. + var badgeCount: Int = 1 + + var body: some View { + HStack(spacing: 6) { + glyph + Text(item.displayTitle(hidingSecrets: masksSecrets)) + .font(.system(size: 12, weight: .medium)) + .lineLimit(1) + .truncationMode(.tail) + if badgeCount > 1 { + Text("+\(badgeCount - 1)") + .font(.system(size: 11, weight: .bold, design: .rounded)) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(Color.accentColor)) + } + } + .padding(.horizontal, 10) + .padding(.vertical, 7) + .frame(maxWidth: 240) + .background(Capsule().fill(Color(nsColor: .windowBackgroundColor))) + .overlay(Capsule().stroke(Color.primary.opacity(0.15), lineWidth: 1)) + } + + @ViewBuilder private var glyph: some View { + Group { + if item.kind == .image { + Image(systemName: "photo").foregroundStyle(.secondary) + } else if item.kind == .color { + Circle().fill(Tokens.color(fromHex: item.plainText ?? "")) + } else if let icon = AppIconCache.icon(forBundleID: item.appBundleID) { + Image(nsImage: icon).resizable() + } else { + Image(systemName: "doc.on.clipboard").foregroundStyle(.secondary) + } + } + .font(.system(size: 13)) + .frame(width: 16, height: 16) + } +} + struct LinkFaviconView: View { let item: ClipItem let store: ItemStore @@ -586,7 +644,7 @@ struct LinkFaviconView: View { /// card is being renamed (`ItemCardView.isInlineRenaming`). Enter commits, Escape /// reverts without saving, and losing focus (clicking away) commits — the field /// is auto-focused on appear so typing can start immediately. -private struct InlineTitleField: View { +struct InlineTitleField: View { let initialText: String let onCommit: (String) -> Void let onCancel: () -> Void @@ -665,7 +723,7 @@ private struct InlineTitleField: View { /// Double-click-to-paste is instead handled without a timed gesture: the first click /// selects, and a click on the already-sole-selected card pastes (see /// `ShelfViewModel.handleCardClick`), so a fast double-click still pastes with no delay. -private struct CardClickGesture: ViewModifier { +struct CardClickGesture: ViewModifier { let onClick: (NSEvent.ModifierFlags) -> Void func body(content: Content) -> some View { diff --git a/Copy/Shelf/MiniShelfView.swift b/Copy/Shelf/MiniShelfView.swift new file mode 100644 index 0000000..8e01343 --- /dev/null +++ b/Copy/Shelf/MiniShelfView.swift @@ -0,0 +1,593 @@ +import AppKit +import CopyCore +import KeyboardShortcuts +import SwiftUI + +/// The mini shelf: a small panel that opens above the text cursor (see +/// `ShelfPanelController.show(mode:)`), with the history as a vertical list. It runs on the +/// same `ShelfViewModel` as the full shelf, so search, pinboards, selection, paste, drag and +/// drop, and the paste stack all behave the same; only the layout differs. +struct MiniShelfView: View { + @Bindable var viewModel: ShelfViewModel + @FocusState private var searchFocused: Bool + @State private var permissionBannerDismissed = false + + static let cornerRadius: CGFloat = 14 + /// Room the lists leave at their bottom for the floating buttons. + static let controlsClearance: CGFloat = 40 + + var body: some View { + VStack(spacing: 0) { + if !viewModel.accessibilityTrusted && !permissionBannerDismissed { + PermissionBanner(onDismiss: { permissionBannerDismissed = true }) + } + HStack(spacing: 0) { + if viewModel.miniShowsPinboards { + MiniPinboardRail(viewModel: viewModel) + Divider() + } + VStack(spacing: 0) { + if viewModel.miniSearchShown { + SearchTokenField(viewModel: viewModel, placeholder: searchPlaceholder, + focused: $searchFocused, fitsDropdownToField: true) + .padding([.horizontal, .top], 8) + // Above the list so the suggestions float over it. + .zIndex(1) + } + MiniItemsList(viewModel: viewModel) + } + } + } + .overlay(alignment: .bottomLeading) { + MiniShelfControls(viewModel: viewModel) + .padding(8) + } + .modifier(SearchFocusSync(viewModel: viewModel, focused: $searchFocused)) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .glassSurface(cornerRadius: Self.cornerRadius) + .clipShape(RoundedRectangle(cornerRadius: Self.cornerRadius, style: .continuous)) + } + + /// On a pinboard, names the board so the user knows the search is scoped to it. + private var searchPlaceholder: String { + if case .pinboard(let id) = viewModel.tab, + let name = viewModel.pinboards.first(where: { $0.id == id })?.name { + return "Search \(name)" + } + return "Search or filter…" + } +} + +/// The search, paste stack and pinboard-column buttons, floating over the shelf's +/// bottom-left corner rather than taking a column of their own. +private struct MiniShelfControls: View { + @Bindable var viewModel: ShelfViewModel + + private var stackHotkey: String { + KeyboardShortcuts.getShortcut(for: .togglePasteStack)?.description ?? "⇧⌘C" + } + + var body: some View { + HStack(spacing: 1) { + button("magnifyingglass", on: viewModel.miniSearchShown, + help: viewModel.miniSearchShown ? "Close Search" : "Search") { + viewModel.toggleMiniSearch() + } + button("square.stack.3d.up", on: viewModel.isPasteStackOn, help: "Paste Stack (\(stackHotkey))") { + viewModel.onTogglePasteStack?() + } + button("sidebar.left", on: viewModel.miniShowsPinboards, + help: viewModel.miniShowsPinboards ? "Hide Pinboards" : "Show Pinboards") { + viewModel.miniShowsPinboards.toggle() + } + } + .padding(2) + // Blurs the cards under it, not what is behind the window (see `DropdownBackdrop`). + .background(DropdownBackdrop(cornerRadius: 9)) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .strokeBorder(Color(nsColor: .separatorColor).opacity(0.5), lineWidth: 0.5) + ) + .shadow(color: .black.opacity(0.18), radius: 6, y: 2) + } + + private func button(_ symbol: String, on: Bool, help: String, action: @escaping () -> Void) -> some View { + IconButton(systemName: symbol, fontSize: 11, size: CGSize(width: 24, height: 22), + tint: on ? Color.accentColor : .secondary, help: help, action: action) + } +} + +/// The pinboard column: History, then each pinboard as a small circle. Cards dropped on a +/// circle are filed into that board; like the full shelf's tabs, each circle publishes its +/// frame so `ShelfHostingView` can resolve the drop. +private struct MiniPinboardRail: View { + @Bindable var viewModel: ShelfViewModel + + var body: some View { + ScrollView(.vertical, showsIndicators: false) { + VStack(spacing: 8) { + MiniRailCircle(label: "History", symbol: "clock", isSelected: viewModel.tab == .history) { + viewModel.selectTab(.history) + } + Rectangle() + .fill(Color(nsColor: .separatorColor)) + .frame(width: 18, height: 1) + ForEach(viewModel.pinboards, id: \.id) { pinboard in + MiniRailCircle( + label: pinboard.name, + symbol: pinboard.symbol, + emoji: pinboard.emoji, + tint: pinboard.tint, + isSelected: pinboard.id.map { viewModel.tab == .pinboard($0) } ?? false, + isDropTargeted: pinboard.id != nil && viewModel.dropTargetedPinboardID == pinboard.id + ) { + if let id = pinboard.id { viewModel.selectTab(.pinboard(id)) } + } + .background( + GeometryReader { geo in + Color.clear.preference( + key: PinboardTabFramesKey.self, + value: pinboard.id.map { [$0: geo.frame(in: .named("shelfRoot"))] } ?? [:] + ) + } + ) + } + } + .padding(.top, 10) + .padding(.bottom, MiniShelfView.controlsClearance) + .frame(maxWidth: .infinity) + } + .frame(width: 44) + // A real backing so a card dropped on a circle routes to this panel instead of + // passing through the glass to the window behind (see `ShelfTabs`). + .background(Color.primary.opacity(0.03)) + } +} + +private struct MiniRailCircle: View { + let label: String + let symbol: String + var emoji: String? = nil + var tint: String = "" + let isSelected: Bool + var isDropTargeted: Bool = false + let action: () -> Void + @State private var isHovering = false + + private var tintColor: Color? { tint.isEmpty ? nil : Tokens.color(fromHex: tint) } + private var ringColor: Color { isDropTargeted ? (tintColor ?? .accentColor) : .accentColor } + + var body: some View { + ZStack { + Circle().fill(fill) + if let emoji, !emoji.isEmpty { + Text(emoji).font(.system(size: 13)) + } else if let tintColor { + Circle().fill(tintColor).frame(width: 12, height: 12) + } else { + Image(systemName: symbol) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(isSelected ? Color.primary : Color.primary.opacity(0.72)) + } + } + .frame(width: 28, height: 28) + .overlay(Circle().strokeBorder(ringColor, lineWidth: isDropTargeted ? 2 : 1.5) + .opacity(isSelected || isDropTargeted ? 1 : 0)) + .scaleEffect(isDropTargeted ? 1.12 : 1) + .animation(.spring(response: 0.2, dampingFraction: 0.7), value: isDropTargeted) + // A tap gesture, not a Button, so a card dragged onto it isn't fought for the + // mouse-up (see `TabPill`). + .contentShape(Circle()) + .onTapGesture(perform: action) + .onHover { isHovering = $0 } + .help(label) + .accessibilityElement(children: .ignore) + .accessibilityLabel(label) + .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton) + } + + private var fill: Color { + if isDropTargeted { return (tintColor ?? .accentColor).opacity(0.24) } + if let tintColor, isSelected { return tintColor.opacity(0.22) } + if isSelected { return Color.primary.opacity(0.1) } + return isHovering ? Color.primary.opacity(0.08) : Color.primary.opacity(0.04) + } +} + +/// The history as a vertical list of compact rows. +private struct MiniItemsList: View { + @Bindable var viewModel: ShelfViewModel + + private var currentPinboardID: Int64? { + if case .pinboard(let id) = viewModel.tab { return id } + return nil + } + + var body: some View { + if viewModel.items.isEmpty { + ShelfEmptyState(viewModel: viewModel) + .padding(.bottom, MiniShelfView.controlsClearance) + } else { + ScrollViewReader { proxy in + ScrollView(.vertical, showsIndicators: false) { + LazyVStack(spacing: 6) { + ForEach(Array(viewModel.items.enumerated()), id: \.element.uuid) { index, item in + if index == viewModel.favoritesCount, + viewModel.favoritesCount > 0, + viewModel.favoritesCount < viewModel.items.count { + MiniFavoritesDivider() + } + row(item, index: index) + .id(item.uuid) + // Widens the fetch window as the list nears its oldest row. + .onAppear { + viewModel.loadMoreIfNeeded(at: index) + viewModel.fetchLinkPreviewIfNeeded(for: item) + } + } + } + .padding(.horizontal, 8) + .padding(.top, 8) + .padding(.bottom, MiniShelfView.controlsClearance) + // A real backing so the scroll wheel over a gap reaches the list. + .background(Color.black.opacity(0.001)) + } + .onChange(of: viewModel.selection.primary) { _, newPrimary in + guard let newPrimary else { return } + if NSWorkspace.shared.accessibilityDisplayShouldReduceMotion { + proxy.scrollTo(newPrimary) + } else { + withAnimation(.easeOut(duration: 0.12)) { proxy.scrollTo(newPrimary) } + } + } + } + } + } + + private func row(_ item: ClipItem, index: Int) -> some View { + MiniItemRow( + item: item, + isSelected: viewModel.isSelected(item), + isInlineRenaming: viewModel.inlineRenamingItemID == item.id, + store: viewModel.store, + pinboards: viewModel.pinboards, + currentPinboardID: currentPinboardID, + favoritesEnabled: viewModel.settings.favoritesEnabled, + previewLines: viewModel.settings.miniShelfSize.previewLines, + isFlashing: viewModel.flashItemID == item.uuid, + hideSecrets: viewModel.settings.hideSecrets, + secretsRevealed: viewModel.revealedSecretIDs.contains(item.uuid), + pasteNumber: (viewModel.optionHeld && index < 9) ? index + 1 : nil, + canShowInHistory: !viewModel.searchQuery.isEmpty || currentPinboardID != nil, + onClick: { modifiers in viewModel.handleCardClick(item, modifiers: modifiers) }, + onHoverChanged: { hovering in + if hovering { + viewModel.hoveredItemID = item.uuid + } else if viewModel.hoveredItemID == item.uuid { + viewModel.hoveredItemID = nil + } + }, + onPaste: { viewModel.requestPaste(item, plain: false) }, + onPastePlain: { viewModel.requestPaste(item, plain: true) }, + onEdit: { viewModel.beginEdit(item) }, + onAdjustColor: { viewModel.beginAdjustColor(item) }, + onBeginInlineRename: { viewModel.beginInlineRename(item) }, + onCommitInlineRename: { viewModel.commitInlineRename(item, to: $0) }, + onCancelInlineRename: { viewModel.cancelInlineRename() }, + onToggleFavorite: { viewModel.toggleFavorite(item) }, + onToggleSecrets: { viewModel.toggleSecretsRevealed(item) }, + onAddToPinboard: { id in viewModel.addItem(item, toPinboard: id) }, + onRemoveFromPinboard: { + if let currentPinboardID { viewModel.removeItem(item, fromPinboard: currentPinboardID) } + }, + onAddToPasteStack: { viewModel.addToPasteStack(item) }, + onSplitToPasteStack: { viewModel.splittingItem = item }, + onCopyText: { viewModel.copyText(item) }, + onQuickLook: { viewModel.quickLook(item) }, + onOpen: { viewModel.open(item) }, + onShowInHistory: { viewModel.showInHistory(item) }, + onRotate: { viewModel.rotateImage(item, clockwise: $0) }, + onDelete: { viewModel.delete(item) }, + dragProvider: { viewModel.dragProvider(for: item) }, + dragBadgeCount: viewModel.isSelected(item) ? viewModel.selection.selected.count : 1 + ) + // Space previews the selected row, as it does a card in the full shelf. + .popover(isPresented: Binding( + get: { viewModel.isSelected(item) && item.uuid == viewModel.selection.primary && viewModel.previewShown }, + set: { viewModel.previewShown = $0 } + ), arrowEdge: .trailing) { + PreviewPane(item: item, store: viewModel.store, + hideSecrets: viewModel.settings.hideSecrets, + secretsRevealed: viewModel.revealedSecretIDs.contains(item.uuid), + onToggleSecrets: { viewModel.toggleSecretsRevealed(item) }) + } + } +} + +/// The rule between the leading favorites and the rest, the list's version of the full +/// shelf's `FavoritesDivider`. +private struct MiniFavoritesDivider: View { + var body: some View { + HStack(spacing: 5) { + Image(systemName: "star.fill") + .font(.system(size: 8)) + .foregroundStyle(.secondary) + RoundedRectangle(cornerRadius: 1, style: .continuous) + .fill(Color(nsColor: .separatorColor).opacity(0.8)) + .frame(height: 1) + } + .padding(.horizontal, 4) + .accessibilityLabel("Favorites divider") + } +} + +/// One history item in the mini shelf. Mirrors `ItemCardView`'s inputs and actions (the +/// same right-click menu, drag chip and click handling) in a compact row. +private struct MiniItemRow: View { + let item: ClipItem + let isSelected: Bool + let isInlineRenaming: Bool + let store: ItemStore + let pinboards: [Pinboard] + let currentPinboardID: Int64? + let favoritesEnabled: Bool + /// Lines of text the row shows, from the mini shelf's size. + let previewLines: Int + let isFlashing: Bool + let hideSecrets: Bool + let secretsRevealed: Bool + let pasteNumber: Int? + let canShowInHistory: Bool + let onClick: (NSEvent.ModifierFlags) -> Void + let onHoverChanged: (Bool) -> Void + let onPaste: () -> Void + let onPastePlain: () -> Void + let onEdit: () -> Void + let onAdjustColor: () -> Void + let onBeginInlineRename: () -> Void + let onCommitInlineRename: (String) -> Void + let onCancelInlineRename: () -> Void + let onToggleFavorite: () -> Void + let onToggleSecrets: () -> Void + let onAddToPinboard: (Int64) -> Void + let onRemoveFromPinboard: () -> Void + let onAddToPasteStack: () -> Void + let onSplitToPasteStack: () -> Void + let onCopyText: () -> Void + let onQuickLook: () -> Void + let onOpen: () -> Void + let onShowInHistory: () -> Void + let onRotate: (Bool) -> Void + let onDelete: () -> Void + let dragProvider: () -> NSItemProvider + let dragBadgeCount: Int + + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var isHovering = false + + private static let bodyCap = 1_500 + + private var masksSecrets: Bool { hideSecrets && !secretsRevealed } + + private var isEditable: Bool { + switch item.kind { + case .text, .richText, .link: return true + case .image, .file, .color: return false + } + } + + /// Earns the row its eye button. Only evaluated while the actions show. + private var hasSecret: Bool { + guard hideSecrets, isEditable, let text = item.plainText else { return false } + return SecretDetector.maskedPrefix(text, count: Self.bodyCap) != String(text.prefix(Self.bodyCap)) + } + + private func displayText(_ text: String) -> String { + masksSecrets ? SecretDetector.maskedPrefix(text, count: Self.bodyCap) : String(text.prefix(Self.bodyCap)) + } + + /// The custom title if set; otherwise "Image" for images, or the source app. + private var headerLabel: String { + if let title = item.title, !title.isEmpty { return title } + if item.kind == .image { return "Image" } + return item.appName ?? "Unknown" + } + + var body: some View { + HStack(alignment: .top, spacing: 8) { + leadingIcon + VStack(alignment: .leading, spacing: 3) { + header + content + } + } + .padding(8) + .frame(maxWidth: .infinity, alignment: .leading) + .background( + ZStack { + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(Color(nsColor: .controlBackgroundColor)) + if isSelected { + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(Color.accentColor.opacity(0.12)) + } + } + ) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .stroke(isSelected ? Color.accentColor : Color(nsColor: .separatorColor), + lineWidth: isSelected ? 1.5 : 0.5) + ) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .stroke(Color.accentColor, lineWidth: 2.5) + .opacity(isFlashing ? 1 : 0) + .animation(reduceMotion ? nil : .easeInOut(duration: 0.4), value: isFlashing) + ) + .contentShape(RoundedRectangle(cornerRadius: 9, style: .continuous)) + .onHover { hovering in + if reduceMotion { + isHovering = hovering + } else { + withAnimation(.easeOut(duration: 0.12)) { isHovering = hovering } + } + onHoverChanged(hovering) + } + .animation(reduceMotion ? nil : .spring(response: 0.26, dampingFraction: 0.72), value: isSelected) + .contextMenu { + CardContextMenu( + item: item, pinboards: pinboards, currentPinboardID: currentPinboardID, + favoritesEnabled: favoritesEnabled, canShowInHistory: canShowInHistory, + hasQuickLook: item.kind == .file && !QuickLookController.fileURLs(for: item, store: store).isEmpty, + onPaste: onPaste, onPastePlain: onPastePlain, onEdit: onEdit, onAdjustColor: onAdjustColor, + onRename: onBeginInlineRename, onToggleFavorite: onToggleFavorite, + onAddToPinboard: onAddToPinboard, onRemoveFromPinboard: onRemoveFromPinboard, + onAddToPasteStack: onAddToPasteStack, onSplitToPasteStack: onSplitToPasteStack, + onCopyText: onCopyText, onQuickLook: onQuickLook, onOpen: onOpen, + onShowInHistory: onShowInHistory, onRotate: onRotate, onDelete: onDelete) + } + .onDrag(dragProvider) { + CardDragPreview(item: item, masksSecrets: masksSecrets, badgeCount: dragBadgeCount) + } + .modifier(CardClickGesture(onClick: onClick)) + } + + @ViewBuilder private var leadingIcon: some View { + Group { + if item.kind == .image { + Image(systemName: "photo") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } else if let icon = AppIconCache.icon(forBundleID: item.appBundleID) { + Image(nsImage: icon).resizable() + } else { + Image(systemName: "doc.on.clipboard") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } + } + .frame(width: 16, height: 16) + } + + /// Name and age; on hover or selection the age gives way to the small favorite and + /// delete buttons, so they never sit over the text. + private var header: some View { + HStack(spacing: 4) { + if isInlineRenaming { + InlineTitleField(initialText: item.title ?? "", onCommit: onCommitInlineRename, + onCancel: onCancelInlineRename) + } else { + Text(headerLabel) + .font(Tokens.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + Spacer(minLength: 4) + if let pasteNumber { + Text("⌥\(pasteNumber)") + .font(.system(size: 9, weight: .semibold, design: .rounded)) + .foregroundStyle(.white) + .padding(.horizontal, 4) + .padding(.vertical, 1) + .background(Capsule().fill(Color.accentColor)) + } else if isHovering || isSelected { + actions.transition(.opacity) + } else { + if favoritesEnabled && item.isFavorite { + Image(systemName: "star.fill") + .font(.system(size: 8)) + .foregroundStyle(.yellow) + .accessibilityLabel("Favorite") + } + Text(Tokens.relativeFormatter.localizedString(for: item.lastUsedAt, relativeTo: Date())) + .font(Tokens.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .fixedSize() + } + } + } + .frame(height: 16) + } + + private var actions: some View { + HStack(spacing: 0) { + if hasSecret { + smallButton(secretsRevealed ? "eye.slash" : "eye", + help: secretsRevealed ? "Hide secrets" : "Show secrets", action: onToggleSecrets) + } + if favoritesEnabled { + smallButton(item.isFavorite ? "star.fill" : "star", + tint: item.isFavorite ? .yellow : .secondary, + help: item.isFavorite ? "Remove from favorites" : "Favorite", + action: onToggleFavorite) + } + smallButton("trash", help: "Delete", action: onDelete) + } + } + + private func smallButton(_ symbol: String, tint: Color = .secondary, help: String, + action: @escaping () -> Void) -> some View { + IconButton(systemName: symbol, fontSize: 9, size: CGSize(width: 18, height: 16), + tint: tint, help: help, action: action) + } + + @ViewBuilder private var content: some View { + switch item.kind { + case .text, .richText: + if let hex = HexColor.normalized(item.plainText ?? "") { + swatch(hex) + } else { + Text(displayText(item.plainText ?? "")) + .font(isCode ? Tokens.bodyMono : Tokens.cardBody) + .lineLimit(previewLines) + .frame(maxWidth: .infinity, alignment: .leading) + } + case .link: + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 4) { + LinkFaviconView(item: item, store: store) + Text(item.linkTitle ?? URL(string: item.plainText ?? "")?.host ?? "Link") + .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + } + if previewLines > 1 { + Text(displayText(item.plainText ?? "")) + .font(Tokens.bodyMono) + .foregroundStyle(.secondary) + .lineLimit(previewLines - 1) + } + } + case .image: + CardThumbnail(item: item, store: store) + .frame(width: thumbnailSize.width, height: thumbnailSize.height) + case .file: + HStack(spacing: 6) { + FileThumbnail(item: item, store: store, compact: true) + .frame(width: thumbnailSize.height, height: thumbnailSize.height) + Text(item.plainText ?? "File") + .font(Tokens.cardBody) + .lineLimit(previewLines) + } + case .color: + swatch(item.plainText ?? "") + } + } + + /// Grows with the preview lines, so every size keeps its rhythm. + private var thumbnailSize: CGSize { + CGSize(width: 48 + CGFloat(previewLines) * 16, height: 18 + CGFloat(previewLines) * 14) + } + + private var isCode: Bool { + CodeHighlightCache.shared.result(for: item.plainText ?? "", uuid: item.uuid, cap: Self.bodyCap).language != nil + } + + private func swatch(_ hex: String) -> some View { + HStack(spacing: 6) { + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Tokens.color(fromHex: hex)) + .frame(width: 22, height: 16) + Text(hex).font(Tokens.cardBody) + } + } +} diff --git a/Copy/Shelf/PinboardDropCatcher.swift b/Copy/Shelf/PinboardDropCatcher.swift index 0317374..9eff966 100644 --- a/Copy/Shelf/PinboardDropCatcher.swift +++ b/Copy/Shelf/PinboardDropCatcher.swift @@ -21,17 +21,25 @@ struct PinboardTabFramesKey: PreferenceKey { } /// Maps a point in the shelf's top-left coordinate space (`"shelfRoot"`, which is also the -/// hosting view's) to the pinboard tab under it, using the frames each tab publishes. +/// hosting view's) to the pinboard tab under it, using the frames each tab publishes. The +/// full shelf lays its tabs out in a row; the mini shelf in a column (`vertical`). enum PinboardTabHitTest { - static func pinboard(at point: CGPoint, in frames: [Int64: CGRect]) -> Int64? { + static func pinboard(at point: CGPoint, in frames: [Int64: CGRect], vertical: Bool = false) -> Int64? { guard !frames.isEmpty else { return nil } // Exact hit first (cursor squarely inside a pill). if let hit = frames.first(where: { $0.value.contains(point) })?.key { return hit } - // Otherwise resolve by column, not by an inflated rectangle: the pills are only ~24pt - // tall and sit in a single row, so matching a raw point against thin, near-touching - // frames misses at edges and picks arbitrarily where inflated frames overlap. Instead, - // accept any drop within the tab-row's vertical band and map it to the tab whose X - // range holds the cursor — or the nearest tab center when between columns. + // A column is a row turned on its side: swap the axes and resolve it the same way. + guard vertical else { return nearest(to: point, in: frames) } + let swapped = frames.mapValues { CGRect(x: $0.minY, y: $0.minX, width: $0.height, height: $0.width) } + return nearest(to: CGPoint(x: point.y, y: point.x), in: swapped) + } + + /// Resolves by column, not by an inflated rectangle: the pills are only ~24pt tall and + /// sit in a single row, so matching a raw point against thin, near-touching frames misses + /// at edges and picks arbitrarily where inflated frames overlap. Instead, accept any drop + /// within the tab-row's vertical band and map it to the tab whose X range holds the + /// cursor — or the nearest tab center when between columns. + private static func nearest(to point: CGPoint, in frames: [Int64: CGRect]) -> Int64? { let rowTop = frames.values.map(\.minY).min() ?? 0 let rowBottom = frames.values.map(\.maxY).max() ?? 0 guard point.y >= rowTop - 14, point.y <= rowBottom + 14 else { return nil } @@ -81,11 +89,13 @@ struct PinboardDropCallout: Equatable { /// card will land in (the tab alone is small, and the drag chip sits on top of it), then /// briefly confirms the drop. It glides from tab to tab as the /// drag moves along the row. Laid over the whole shelf in the `"shelfRoot"` space, where -/// the tab frames are measured, so it can hang below the header over the cards. +/// the tab frames are measured, so it can hang below the header over the cards. In the +/// mini shelf's pinboard column (`vertical`) it pops out to the side of the tab instead. struct PinboardDropCalloutLayer: View { let callout: PinboardDropCallout? let pinboards: [Pinboard] let tabFrames: [Int64: CGRect] + var vertical: Bool = false @Environment(\.accessibilityReduceMotion) private var reduceMotion var body: some View { @@ -94,16 +104,26 @@ struct PinboardDropCalloutLayer: View { if let callout, let pinboard = pinboards.first(where: { $0.id == callout.pinboardID }), let tab = tabFrames[callout.pinboardID] { - PinboardDropCalloutView(callout: callout, pinboard: pinboard, - arrowX: tab.width / 2 + Self.leadingInset) - // Positioned by alignment guides, not `.offset`, so the view's real frame - // sits under the tab: the pop-out transition then scales from the tab, - // and moving to another tab animates as a layout change. - .alignmentGuide(.leading) { _ in -(tab.minX - Self.leadingInset) } - .alignmentGuide(.top) { _ in -(tab.maxY + 3) } - .transition(reduceMotion - ? .opacity - : .scale(scale: 0.35, anchor: UnitPoint(x: 0.12, y: 0)).combined(with: .opacity)) + // Positioned by alignment guides, not `.offset`, so the view's real frame + // sits beside the tab: the pop-out transition then scales from the tab, + // and moving to another tab animates as a layout change. + if vertical { + PinboardDropCalloutView(callout: callout, pinboard: pinboard, arrowEdge: .leading, + arrowOffset: nil) + .alignmentGuide(.leading) { _ in -(tab.maxX + 3) } + .alignmentGuide(.top) { d in -(tab.midY - d.height / 2) } + .transition(reduceMotion + ? .opacity + : .scale(scale: 0.35, anchor: .leading).combined(with: .opacity)) + } else { + PinboardDropCalloutView(callout: callout, pinboard: pinboard, arrowEdge: .top, + arrowOffset: tab.width / 2 + Self.leadingInset) + .alignmentGuide(.leading) { _ in -(tab.minX - Self.leadingInset) } + .alignmentGuide(.top) { _ in -(tab.maxY + 3) } + .transition(reduceMotion + ? .opacity + : .scale(scale: 0.35, anchor: UnitPoint(x: 0.12, y: 0)).combined(with: .opacity)) + } } } .allowsHitTesting(false) @@ -119,8 +139,10 @@ struct PinboardDropCalloutLayer: View { private struct PinboardDropCalloutView: View { let callout: PinboardDropCallout let pinboard: Pinboard - /// The arrow's x position, from the callout's leading edge. - let arrowX: CGFloat + /// The edge the arrow points out of, toward the tab. + let arrowEdge: CalloutShape.ArrowEdge + /// The arrow's position along that edge, from its start; nil centers it. + let arrowOffset: CGFloat? private var boardColor: Color { pinboard.tint.isEmpty ? .accentColor : Tokens.color(fromHex: pinboard.tint) @@ -154,12 +176,12 @@ private struct PinboardDropCalloutView: View { .padding(.leading, 8) .padding(.trailing, 12) .padding(.vertical, 6) - .padding(.top, CalloutShape.arrowHeight) + .padding(arrowEdge == .top ? .top : .leading, CalloutShape.arrowHeight) .fixedSize() // Plain system material with a hairline, like a native popover: the board's color // lives only in the badge, the same small dose of it the tab itself carries. .background { - let shape = CalloutShape(arrowX: arrowX) + let shape = CalloutShape(arrowEdge: arrowEdge, arrowOffset: arrowOffset) shape.fill(.regularMaterial) shape.stroke(Color.primary.opacity(0.12), lineWidth: 0.5) } @@ -188,30 +210,45 @@ private struct PinboardDropCalloutView: View { } } -/// A rounded bubble with a small arrow on top, pointing up at the tab. -private struct CalloutShape: Shape { +/// A rounded bubble with a small arrow pointing at the tab: on top for the full shelf's +/// tab row, on the leading side for the mini shelf's column. +struct CalloutShape: Shape { + enum ArrowEdge { case top, leading } + static let arrowHeight: CGFloat = 6 private static let arrowWidth: CGFloat = 14 private static let cornerRadius: CGFloat = 10 - var arrowX: CGFloat + var arrowEdge: ArrowEdge + /// Along the arrow's edge, from its start; nil centers it. + var arrowOffset: CGFloat? var animatableData: CGFloat { - get { arrowX } - set { arrowX = newValue } + get { arrowOffset ?? 0 } + set { if arrowOffset != nil { arrowOffset = newValue } } } func path(in rect: CGRect) -> Path { - let body = CGRect(x: rect.minX, y: rect.minY + Self.arrowHeight, - width: rect.width, height: rect.height - Self.arrowHeight) + let inset = Self.arrowHeight + let body = arrowEdge == .top + ? CGRect(x: rect.minX, y: rect.minY + inset, width: rect.width, height: rect.height - inset) + : CGRect(x: rect.minX + inset, y: rect.minY, width: rect.width - inset, height: rect.height) let bubble = Path(roundedRect: body, cornerRadius: Self.cornerRadius, style: .continuous) let halfWidth = Self.arrowWidth / 2 - let x = min(max(rect.minX + arrowX, body.minX + Self.cornerRadius + halfWidth), - body.maxX - Self.cornerRadius - halfWidth) + let margin = Self.cornerRadius + halfWidth var arrow = Path() - arrow.move(to: CGPoint(x: x - halfWidth, y: body.minY + 1)) - arrow.addQuadCurve(to: CGPoint(x: x, y: rect.minY), control: CGPoint(x: x - 2, y: body.minY)) - arrow.addQuadCurve(to: CGPoint(x: x + halfWidth, y: body.minY + 1), control: CGPoint(x: x + 2, y: body.minY)) + switch arrowEdge { + case .top: + let x = min(max(rect.minX + (arrowOffset ?? rect.width / 2), body.minX + margin), body.maxX - margin) + arrow.move(to: CGPoint(x: x - halfWidth, y: body.minY + 1)) + arrow.addQuadCurve(to: CGPoint(x: x, y: rect.minY), control: CGPoint(x: x - 2, y: body.minY)) + arrow.addQuadCurve(to: CGPoint(x: x + halfWidth, y: body.minY + 1), control: CGPoint(x: x + 2, y: body.minY)) + case .leading: + let y = min(max(rect.minY + (arrowOffset ?? rect.height / 2), body.minY + margin), body.maxY - margin) + arrow.move(to: CGPoint(x: body.minX + 1, y: y - halfWidth)) + arrow.addQuadCurve(to: CGPoint(x: rect.minX, y: y), control: CGPoint(x: body.minX, y: y - 2)) + arrow.addQuadCurve(to: CGPoint(x: body.minX + 1, y: y + halfWidth), control: CGPoint(x: body.minX, y: y + 2)) + } arrow.closeSubpath() return bubble.union(arrow) } diff --git a/Copy/Shelf/SearchTokenField.swift b/Copy/Shelf/SearchTokenField.swift index 366497f..1d2547a 100644 --- a/Copy/Shelf/SearchTokenField.swift +++ b/Copy/Shelf/SearchTokenField.swift @@ -10,6 +10,9 @@ struct SearchTokenField: View { @Bindable var viewModel: ShelfViewModel var placeholder: String @FocusState.Binding var focused: Bool + /// The mini shelf is too narrow for the hint panel, and its suggestions take the + /// field's own width. + var fitsDropdownToField = false private var textBinding: Binding { Binding(get: { viewModel.searchQuery.text }, @@ -39,9 +42,9 @@ struct SearchTokenField: View { ) .overlay(alignment: .topLeading) { if viewModel.suggestionsVisible { - SuggestionsDropdown(viewModel: viewModel) + SuggestionsDropdown(viewModel: viewModel, width: fitsDropdownToField ? nil : 240) .offset(y: 36) - } else if focused && viewModel.searchQuery.text.isEmpty { + } else if focused && viewModel.searchQuery.text.isEmpty && !fitsDropdownToField { // Discovery: what you can type. Informational only (no keyboard capture), so // ⏎ still pastes the selected card while this is showing. SearchHintPanel() @@ -129,6 +132,8 @@ private struct SearchPill: View { /// by `AppCoordinator.onKeyEvent`) is filled with the accent color. private struct SuggestionsDropdown: View { @Bindable var viewModel: ShelfViewModel + /// nil fills the field's width. + var width: CGFloat? var body: some View { VStack(spacing: 1) { @@ -140,7 +145,8 @@ private struct SuggestionsDropdown: View { } } .padding(4) - .frame(width: 240, alignment: .leading) + .frame(width: width, alignment: .leading) + .frame(maxWidth: width == nil ? .infinity : nil, alignment: .leading) .background(DropdownBackdrop(cornerRadius: 10)) .overlay( RoundedRectangle(cornerRadius: 10, style: .continuous) @@ -198,7 +204,7 @@ private struct TokenIcon: View { /// They float over the cards, so this blurs the shelf's own content beneath them. SwiftUI's /// `Material` can't do that on macOS: it samples what is behind the window, so the panel /// showed the desktop or another app through the shelf instead of the cards under it. -private struct DropdownBackdrop: NSViewRepresentable { +struct DropdownBackdrop: NSViewRepresentable { let cornerRadius: CGFloat func makeNSView(context: Context) -> NSVisualEffectView { diff --git a/Copy/Shelf/ShelfPanelController.swift b/Copy/Shelf/ShelfPanelController.swift index 11339d9..16099ee 100644 --- a/Copy/Shelf/ShelfPanelController.swift +++ b/Copy/Shelf/ShelfPanelController.swift @@ -159,6 +159,8 @@ final class ShelfPanelController: NSObject, NSWindowDelegate { /// The close animation: how long it takes and how far the shelf sinks while it fades. private static let closeDuration: TimeInterval = 0.2 private static let closeDrop: CGFloat = 26 + /// How far the mini shelf travels toward or away from the cursor as it opens and closes. + private static let miniTravel: CGFloat = 8 var onKeyEvent: ((NSEvent) -> Bool)? /// Called on every modifier-key change while the shelf is open (⌘-hold hints). @@ -188,13 +190,21 @@ final class ShelfPanelController: NSObject, NSWindowDelegate { private var floatingShelf: Bool private var compactShelf: Bool private var theme: ShelfTheme + /// Which shelf is showing, or showed last. + private(set) var mode: ShelfMode = .full + private var miniShelfSize: CGSize + /// What the open mini shelf is placed against (the caret, or the pointer), kept so a + /// size change can re-place it, and which side of it the shelf opened on. + private var miniAnchor: CGRect? + private var miniOpensBelow = false init(hideDuringScreenSharing: Bool, compactShelf: Bool, theme: ShelfTheme, - floatingShelf: Bool, makeContent: @escaping () -> NSView) { + floatingShelf: Bool, miniShelfSize: CGSize, makeContent: @escaping () -> NSView) { self.hideDuringScreenSharing = hideDuringScreenSharing self.compactShelf = compactShelf self.theme = theme self.floatingShelf = floatingShelf + self.miniShelfSize = miniShelfSize self.makeContent = makeContent } @@ -225,7 +235,7 @@ final class ShelfPanelController: NSObject, NSWindowDelegate { /// mirrors `setHideDuringScreenSharing`'s live-update shape above. func setCompactShelf(_ compact: Bool) { compactShelf = compact - guard isVisible, let panel, + guard isVisible, mode == .full, let panel, let screen = NSScreen.screens.first(where: { NSMouseInRect(NSEvent.mouseLocation, $0.frame, false) }) ?? NSScreen.main else { return } @@ -235,24 +245,36 @@ final class ShelfPanelController: NSObject, NSWindowDelegate { func setFloatingShelf(_ floating: Bool) { floatingShelf = floating - guard let panel, panel.isVisible, !isHiding, let screen = panel.screen else { return } + guard mode == .full, let panel, panel.isVisible, !isHiding, let screen = panel.screen else { return } setShelfContentOffset(0, in: panel) panel.setFrame(ShelfLayout.frame(visibleFrame: screen.visibleFrame, height: currentShelfHeight, floating: floating), display: true) } - var isVisible: Bool { panel?.isVisible ?? false } - - func toggle() { - isVisible ? hide(restoreFocus: true) : show() + /// Re-places an open mini shelf at its new size, against the same anchor. + func setMiniShelfSize(_ size: CGSize) { + miniShelfSize = size + guard mode == .mini, let panel, panel.isVisible, !isHiding, let anchor = miniAnchor, + let screen = panel.screen else { return } + let placement = MiniShelfLayout.placement(size: size, anchor: anchor, visibleFrame: screen.visibleFrame) + miniOpensBelow = placement.opensBelow + panel.setFrame(placement.frame, display: true) } - func show() { + var isVisible: Bool { panel?.isVisible ?? false } + + func show(mode: ShelfMode) { previousApp = NSWorkspace.shared.frontmostApplication + // The mini shelf opens at the text cursor, read while the target app still has + // focus; without one it opens at the pointer. + let caret = mode == .mini ? CaretLocator.caretRect() : nil + let pointer = NSEvent.mouseLocation + let anchorPoint = caret.map { CGPoint(x: $0.minX, y: $0.midY) } ?? pointer guard let screen = NSScreen.screens.first(where: { - NSMouseInRect(NSEvent.mouseLocation, $0.frame, false) + NSMouseInRect(anchorPoint, $0.frame, false) }) ?? NSScreen.main else { return } + self.mode = mode let frame = ShelfLayout.frame(visibleFrame: screen.visibleFrame, height: currentShelfHeight, floating: floatingShelf) let panel = self.panel ?? makePanel() self.panel = panel @@ -270,7 +292,28 @@ final class ShelfPanelController: NSObject, NSWindowDelegate { let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion setShelfContentOffset(0, in: panel) - if floatingShelf { + if mode == .mini { + let anchor = caret ?? CGRect(origin: pointer, size: .zero) + let placement = MiniShelfLayout.placement(size: miniShelfSize, anchor: anchor, + visibleFrame: screen.visibleFrame) + miniAnchor = anchor + miniOpensBelow = placement.opensBelow + // Pops out of the cursor: fades in while moving a few points away from it. + // Like the floating shelf, it doesn't activate Copy, so the app being typed in + // keeps its active look. + panel.setFrame(placement.frame, display: false) + panel.alphaValue = reduceMotion ? 1 : 0 + setShelfContentOffset(reduceMotion ? 0 : miniTravelTowardAnchor, in: panel) + panel.makeKeyAndOrderFront(nil) + if !reduceMotion { + NSAnimationContext.runAnimationGroup { context in + context.duration = 0.16 + context.timingFunction = CAMediaTimingFunction(name: .easeOut) + panel.animator().alphaValue = 1 + shelfContentView(in: panel)?.animator().setFrameOrigin(.zero) + } + } + } else if floatingShelf { // Keep the window on its display: only its clipped content slides, so it // cannot leak onto another monitor placed below this one. panel.setFrame(frame, display: false) @@ -341,7 +384,8 @@ final class ShelfPanelController: NSObject, NSWindowDelegate { // Accelerating, with no ease at the end: the shelf leaves, it doesn't settle. context.timingFunction = CAMediaTimingFunction(controlPoints: 0.4, 0, 1, 1) panel.animator().alphaValue = 0 - shelfContentView(in: panel)?.animator().setFrameOrigin(NSPoint(x: 0, y: -Self.closeDrop)) + let drop = mode == .mini ? miniTravelTowardAnchor : -Self.closeDrop + shelfContentView(in: panel)?.animator().setFrameOrigin(NSPoint(x: 0, y: drop)) } completionHandler: { [weak self] in // NSAnimationContext runs its completion on the main thread; the closure's // `@Sendable` type just can't see that statically. @@ -374,6 +418,12 @@ final class ShelfPanelController: NSObject, NSWindowDelegate { // MARK: - Private + /// The content offset that moves the mini shelf toward its anchor: down when it sits + /// above the cursor, up when below. + private var miniTravelTowardAnchor: CGFloat { + miniOpensBelow ? Self.miniTravel : -Self.miniTravel + } + private func shelfContentView(in panel: KeyablePanel) -> NSView? { (panel.contentView as? ShelfClippingView)?.shelfContent } diff --git a/Copy/Shelf/ShelfRootView.swift b/Copy/Shelf/ShelfRootView.swift index 4303a3d..c3e1893 100644 --- a/Copy/Shelf/ShelfRootView.swift +++ b/Copy/Shelf/ShelfRootView.swift @@ -42,6 +42,38 @@ struct ShelfRootView: View { } var body: some View { + Group { + if viewModel.isMiniShelf { + MiniShelfView(viewModel: viewModel) + } else { + fullShelf + } + } + // Drags onto the pinboard tabs (cards to file, tabs to reorder) are taken by the + // hosting view in AppKit, not by a SwiftUI `.onDrop` (see `ShelfHostingView`). It + // maps the pointer to a tab using each tab's frame, collected via + // PinboardTabFramesKey below. + .coordinateSpace(name: "shelfRoot") + .onPreferenceChange(PinboardTabFramesKey.self) { viewModel.pinboardTabFrames = $0 } + // Pops out of the tab under a card drag to name the board it will land in. + .overlay { + PinboardDropCalloutLayer(callout: viewModel.dropCallout, + pinboards: viewModel.pinboards, + tabFrames: viewModel.pinboardTabFrames, + vertical: viewModel.isMiniShelf) + } + // Pro-dark: force the marketing electric-blue accent regardless of the system + // accent color. The forced dark appearance itself is set on the panel window in + // `ShelfPanelController`, which cascades to this hosted content. + .tint(viewModel.settings.shelfTheme == .dark ? Tokens.electricBlue : nil) + // Edit/Create/Adjust Color/Tips are shown as a centered child window over the + // shelf (see `ShelfModalHostView`), not as attached sheets that overflow off the + // bottom of the screen. This view is always on screen while the shelf is open, so + // it reliably drives the host window's show/hide as the modal state changes. + .onChange(of: hasActiveModal) { _, active in viewModel.onModalPresent?(active) } + } + + private var fullShelf: some View { VStack(spacing: 0) { if showsPermissionBanner { PermissionBanner(onDismiss: { permissionBannerDismissed = true }) @@ -65,12 +97,6 @@ struct ShelfRootView: View { topTrailingRadius: 12, style: .continuous )) - // Drags onto the pinboard tabs (cards to file, tabs to reorder) are taken by the - // hosting view in AppKit, not by a SwiftUI `.onDrop` (see `ShelfHostingView`). It - // maps the pointer to a tab using each tab's frame, collected via - // PinboardTabFramesKey below. - .coordinateSpace(name: "shelfRoot") - .onPreferenceChange(PinboardTabFramesKey.self) { viewModel.pinboardTabFrames = $0 } // Drag-select: press in the shelf's empty space — the card row or the header — and // sweep over cards. A press on a card or a pinboard tab never starts one // (`beginCardSweep` refuses it), so those keep their own click and drag. `.local` @@ -90,21 +116,6 @@ struct ShelfRootView: View { } ) .overlay { CardSweepRectangle(sweep: viewModel.cardSweep) } - // Pops out of the tab under a card drag to name the board it will land in. - .overlay { - PinboardDropCalloutLayer(callout: viewModel.dropCallout, - pinboards: viewModel.pinboards, - tabFrames: viewModel.pinboardTabFrames) - } - // Pro-dark: force the marketing electric-blue accent regardless of the system - // accent color. The forced dark appearance itself is set on the panel window in - // `ShelfPanelController`, which cascades to this hosted content. - .tint(viewModel.settings.shelfTheme == .dark ? Tokens.electricBlue : nil) - // Edit/Create/Adjust Color/Tips are shown as a centered child window over the - // shelf (see `ShelfModalHostView`), not as attached sheets that overflow off the - // bottom of the screen. This view is always on screen while the shelf is open, so - // it reliably drives the host window's show/hide as the modal state changes. - .onChange(of: hasActiveModal) { _, active in viewModel.onModalPresent?(active) } } private var hasActiveModal: Bool { @@ -117,7 +128,7 @@ struct ShelfRootView: View { /// existing material) shown while Accessibility isn't granted, since without it /// `AppCoordinator.pasteFromShelf` can only place the item on the clipboard rather /// than actually paste it into the frontmost app. -private struct PermissionBanner: View { +struct PermissionBanner: View { let onDismiss: () -> Void var body: some View { @@ -182,30 +193,41 @@ private struct ShelfHeader: View { } .padding(.horizontal, Tokens.shelfPadding) .padding(.vertical, 8) - // Not auto-focused on open — the shelf opens in browse mode. Keep the view model in - // sync with the field's focus, and honor a focus request from the key handler - // (type-to-search). - .onChange(of: searchFocused) { _, focused in viewModel.isSearchFieldFocused = focused } - .onChange(of: viewModel.endSearchEditingRequested) { _, requested in - if requested { - searchFocused = false - viewModel.endSearchEditingRequested = false + // Not auto-focused on open — the shelf opens in browse mode. + .modifier(SearchFocusSync(viewModel: viewModel, focused: $searchFocused)) + } +} + +/// Keeps the view model in sync with the search field's focus, and honors its requests to +/// focus the field (type-to-search) or leave it (a click elsewhere). Shared by the full +/// shelf's header and the mini shelf's search row. +struct SearchFocusSync: ViewModifier { + let viewModel: ShelfViewModel + @FocusState.Binding var focused: Bool + + func body(content: Content) -> some View { + content + .onChange(of: focused) { _, focused in viewModel.isSearchFieldFocused = focused } + .onChange(of: viewModel.endSearchEditingRequested) { _, requested in + if requested { + focused = false + viewModel.endSearchEditingRequested = false + } } - } - .onChange(of: viewModel.focusSearchRequested) { _, requested in - if requested { - searchFocused = true - viewModel.focusSearchRequested = false - // Focusing select-alls the field, so the letter that started the search - // would be replaced by the next keystroke. Move the caret to the end once - // focus lands (type-to-search only — a manual click keeps its position). - DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { - if let editor = NSApp.keyWindow?.firstResponder as? NSTextView { - editor.selectedRange = NSRange(location: editor.string.count, length: 0) + .onChange(of: viewModel.focusSearchRequested) { _, requested in + if requested { + focused = true + viewModel.focusSearchRequested = false + // Focusing select-alls the field, so the letter that started the search + // would be replaced by the next keystroke. Move the caret to the end once + // focus lands (type-to-search only — a manual click keeps its position). + DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { + if let editor = NSApp.keyWindow?.firstResponder as? NSTextView { + editor.selectedRange = NSRange(location: editor.string.count, length: 0) + } } } } - } } } @@ -695,7 +717,7 @@ private struct FavoritesDivider: View { } /// Empty state for the items row, tailored to the active tab and search state. -private struct ShelfEmptyState: View { +struct ShelfEmptyState: View { let viewModel: ShelfViewModel private var symbolName: String { diff --git a/Copy/Shelf/ShelfViewModel.swift b/Copy/Shelf/ShelfViewModel.swift index 066f8e2..8d684b7 100644 --- a/Copy/Shelf/ShelfViewModel.swift +++ b/Copy/Shelf/ShelfViewModel.swift @@ -77,6 +77,21 @@ final class ShelfViewModel { tab = newTab } var pinboards: [Pinboard] = [] + /// Whether the shelf is showing as the mini shelf (`MiniShelfView`) rather than the + /// full one. Set by `AppCoordinator` before each open. + var isMiniShelf = false + /// The mini shelf's search field, opened from its lens button. Cleared when it closes. + var miniSearchShown = false + /// Whether the mini shelf shows its pinboard column. Toggled from the shelf itself and + /// remembered across launches; hiding it returns to History, so the list is never + /// filtered by a board that isn't on screen. + var miniShowsPinboards = UserDefaults.standard.bool(forKey: ShelfViewModel.miniShowsPinboardsKey) { + didSet { + UserDefaults.standard.set(miniShowsPinboards, forKey: Self.miniShowsPinboardsKey) + if !miniShowsPinboards, tab != .history { selectTab(.history) } + } + } + static let miniShowsPinboardsKey = "miniShelfShowsPinboards" var selection = ShelfSelection() /// The drag-select in the card row: its rectangle and which cards it touches. The /// selection it produces is applied in `updateCardSweep`. @@ -361,6 +376,23 @@ final class ShelfViewModel { refresh() } + /// The mini shelf's lens button: opens its search field focused, or closes it. + func toggleMiniSearch() { + if miniSearchShown { + closeMiniSearch() + } else { + miniSearchShown = true + // Next turn, once the field is in the window and can take focus. + DispatchQueue.main.async { [weak self] in self?.focusSearchRequested = true } + } + } + + /// Closing the mini shelf's search field also drops its search. + func closeMiniSearch() { + miniSearchShown = false + if !searchQuery.isEmpty { clearSearch() } + } + /// "Show in History": clears the search, switches to the History tab, and (once the /// observation delivers) selects the item so the existing scroll-to animation centers /// on it, with a brief flash. Only reaches items within the recent History window. @@ -415,12 +447,19 @@ final class ShelfViewModel { cachedApps = [] isSearchFieldFocused = false focusSearchRequested = false + miniSearchShown = false shelfDragEnded() dropCallout = nil cardSweep.end() endSearchEditingRequested = false } + /// Called by `AppCoordinator` right before each open, with the shelf about to show. + func prepareToShow(mini: Bool) { + isMiniShelf = mini + if mini, !miniShowsPinboards, tab != .history { tab = .history } + } + /// Called by `AppCoordinator.toggleShelf()` right before showing the panel — see /// the `accessibilityTrusted` doc comment for why a one-time `.onAppear` read isn't /// enough. @@ -897,7 +936,7 @@ final class ShelfViewModel { /// under it — the filing target for cards, the insertion edge for a dragged tab — and /// returns whether there is one, which decides whether the drop is accepted there. func shelfDragMoved(_ kind: ShelfDrag.Kind, to point: CGPoint) -> Bool { - let target = PinboardTabHitTest.pinboard(at: point, in: pinboardTabFrames) + let target = PinboardTabHitTest.pinboard(at: point, in: pinboardTabFrames, vertical: isMiniShelf) switch kind { case .cards: if dropTargetedPinboardID != target { @@ -941,7 +980,7 @@ final class ShelfViewModel { shelfDragEnded() let uuids = payloadUUIDs ?? recorded guard !uuids.isEmpty, - let id = PinboardTabHitTest.pinboard(at: point, in: pinboardTabFrames), + let id = PinboardTabHitTest.pinboard(at: point, in: pinboardTabFrames, vertical: isMiniShelf), let pinboard = pinboards.first(where: { $0.id == id }) else { return false } @@ -966,7 +1005,7 @@ final class ShelfViewModel { if case .pinboard(let id) = activeShelfDrag { recorded = id } shelfDragEnded() guard let sourceID = payloadID ?? recorded, - let targetID = PinboardTabHitTest.pinboard(at: point, in: pinboardTabFrames) else { + let targetID = PinboardTabHitTest.pinboard(at: point, in: pinboardTabFrames, vertical: isMiniShelf) else { return false } if sourceID != targetID { diff --git a/Copy/Support/CaretLocator.swift b/Copy/Support/CaretLocator.swift new file mode 100644 index 0000000..1acb3b5 --- /dev/null +++ b/Copy/Support/CaretLocator.swift @@ -0,0 +1,66 @@ +import AppKit +import ApplicationServices + +/// Finds the text cursor in the frontmost app through Accessibility, for placing the mini +/// shelf. Returns nil when Accessibility is off or the app doesn't report a usable cursor +/// (many Chromium and Electron apps don't); the caller then falls back to the pointer. +enum CaretLocator { + /// The caret's rect in AppKit screen coordinates (origin bottom-left). + static func caretRect() -> CGRect? { + guard AXIsProcessTrusted() else { return nil } + let systemWide = AXUIElementCreateSystemWide() + // A hung app must not stall the hotkey. + AXUIElementSetMessagingTimeout(systemWide, 0.15) + guard let focused = copyAttribute(kAXFocusedUIElementAttribute, of: systemWide), + CFGetTypeID(focused) == AXUIElementGetTypeID(), + let rangeValue = copyAttribute(kAXSelectedTextRangeAttribute, of: focused as! AXUIElement), + CFGetTypeID(rangeValue) == AXValueGetTypeID() else { return nil } + let element = focused as! AXUIElement + var range = CFRange() + guard AXValueGetValue(rangeValue as! AXValue, .cfRange, &range), range.location >= 0 else { return nil } + + // An empty selection often has no bounds, so measure the character after it, then + // the one before it, and use the edge that touches the caret. + if let rect = bounds(of: range, in: element) { + return toAppKit(range.length == 0 ? CGRect(x: rect.minX, y: rect.minY, width: 0, height: rect.height) : rect) + } + if let next = bounds(of: CFRange(location: range.location, length: 1), in: element) { + return toAppKit(CGRect(x: next.minX, y: next.minY, width: 0, height: next.height)) + } + if range.location > 0, let previous = bounds(of: CFRange(location: range.location - 1, length: 1), in: element) { + return toAppKit(CGRect(x: previous.maxX, y: previous.minY, width: 0, height: previous.height)) + } + return nil + } + + private static func copyAttribute(_ name: String, of element: AXUIElement) -> CFTypeRef? { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else { return nil } + return value + } + + /// The range's bounds in Accessibility's top-left screen space, if the app reports a + /// real, on-screen rect for it. + private static func bounds(of range: CFRange, in element: AXUIElement) -> CGRect? { + var range = range + guard let rangeValue = AXValueCreate(.cfRange, &range) else { return nil } + var value: CFTypeRef? + guard AXUIElementCopyParameterizedAttributeValue(element, kAXBoundsForRangeParameterizedAttribute as CFString, + rangeValue, &value) == .success, + let value, CFGetTypeID(value) == AXValueGetTypeID() else { return nil } + var rect = CGRect.zero + guard AXValueGetValue(value as! AXValue, .cgRect, &rect), rect.height > 0, + rect.origin != .zero else { return nil } + return rect + } + + /// Accessibility measures from the primary display's top-left corner; AppKit from its + /// bottom-left. Rejects a rect that lands on no display. + private static func toAppKit(_ rect: CGRect) -> CGRect? { + guard let primary = NSScreen.screens.first else { return nil } + let flipped = CGRect(x: rect.minX, y: primary.frame.maxY - rect.maxY, width: rect.width, height: rect.height) + let probe = CGPoint(x: flipped.minX, y: flipped.midY) + guard NSScreen.screens.contains(where: { $0.frame.contains(probe) }) else { return nil } + return flipped + } +} diff --git a/CopyCore/Sources/CopyCore/Models/MiniShelfLayout.swift b/CopyCore/Sources/CopyCore/Models/MiniShelfLayout.swift new file mode 100644 index 0000000..16450b1 --- /dev/null +++ b/CopyCore/Sources/CopyCore/Models/MiniShelfLayout.swift @@ -0,0 +1,32 @@ +import Foundation + +/// Where the mini shelf opens: just above the text cursor (or the pointer, when the app +/// reports no cursor), below it when there isn't room above, and always on screen. +/// AppKit screen coordinates, origin bottom-left. +public enum MiniShelfLayout { + /// Space between the anchor and the shelf. + public static let gap: CGFloat = 6 + /// The shelf's closest approach to a screen edge. + public static let edgeInset: CGFloat = 8 + /// How far left of the anchor the shelf starts, so its cards begin near the cursor. + public static let leadingOffset: CGFloat = 16 + + public struct Placement: Equatable { + public let frame: CGRect + public let opensBelow: Bool + } + + /// `anchor` is the caret's rect, or a zero-size rect at the pointer. + public static func placement(size: CGSize, anchor: CGRect, visibleFrame: CGRect) -> Placement { + let bounds = visibleFrame.insetBy(dx: edgeInset, dy: edgeInset) + let width = min(size.width, bounds.width) + let height = min(size.height, bounds.height) + let roomAbove = bounds.maxY - (anchor.maxY + gap) + let roomBelow = anchor.minY - gap - bounds.minY + let opensBelow = roomAbove < height && roomBelow > roomAbove + let x = min(max(anchor.minX - leadingOffset, bounds.minX), bounds.maxX - width) + let y = min(max(opensBelow ? anchor.minY - gap - height : anchor.maxY + gap, bounds.minY), + bounds.maxY - height) + return Placement(frame: CGRect(x: x, y: y, width: width, height: height), opensBelow: opensBelow) + } +} diff --git a/CopyCore/Tests/CopyCoreTests/MiniShelfLayoutTests.swift b/CopyCore/Tests/CopyCoreTests/MiniShelfLayoutTests.swift new file mode 100644 index 0000000..8711b7d --- /dev/null +++ b/CopyCore/Tests/CopyCoreTests/MiniShelfLayoutTests.swift @@ -0,0 +1,54 @@ +import XCTest +@testable import CopyCore + +final class MiniShelfLayoutTests: XCTestCase { + private let screen = CGRect(x: 0, y: 0, width: 1440, height: 900) + private let size = CGSize(width: 340, height: 400) + + func testOpensJustAboveTheCaret() { + let caret = CGRect(x: 600, y: 200, width: 2, height: 18) + let placement = MiniShelfLayout.placement(size: size, anchor: caret, visibleFrame: screen) + XCTAssertFalse(placement.opensBelow) + XCTAssertEqual(placement.frame.minY, caret.maxY + MiniShelfLayout.gap) + XCTAssertEqual(placement.frame.minX, caret.minX - MiniShelfLayout.leadingOffset) + XCTAssertEqual(placement.frame.size, size) + } + + func testOpensBelowWhenThereIsNoRoomAbove() { + let caret = CGRect(x: 600, y: 780, width: 2, height: 18) + let placement = MiniShelfLayout.placement(size: size, anchor: caret, visibleFrame: screen) + XCTAssertTrue(placement.opensBelow) + XCTAssertEqual(placement.frame.maxY, caret.minY - MiniShelfLayout.gap) + } + + func testStaysOnScreenNearTheEdges() { + for caret in [CGRect(x: 1430, y: 100, width: 2, height: 18), CGRect(x: 2, y: 100, width: 2, height: 18)] { + let frame = MiniShelfLayout.placement(size: size, anchor: caret, visibleFrame: screen).frame + XCTAssertTrue(screen.insetBy(dx: MiniShelfLayout.edgeInset, dy: MiniShelfLayout.edgeInset).contains(frame)) + } + } + + func testUsesTheSideWithMoreRoomWhenNeitherFits() { + let short = CGRect(x: 0, y: 0, width: 1440, height: 500) + let caret = CGRect(x: 600, y: 300, width: 2, height: 18) + let placement = MiniShelfLayout.placement(size: size, anchor: caret, visibleFrame: short) + XCTAssertTrue(placement.opensBelow) + XCTAssertTrue(short.contains(placement.frame)) + } + + func testPointerAnchorOnAnOffsetDisplay() { + let display = CGRect(x: -1920, y: 900, width: 1920, height: 1080) + let pointer = CGRect(x: -1000, y: 1200, width: 0, height: 0) + let placement = MiniShelfLayout.placement(size: size, anchor: pointer, visibleFrame: display) + XCTAssertFalse(placement.opensBelow) + XCTAssertEqual(placement.frame.minY, 1200 + MiniShelfLayout.gap) + XCTAssertTrue(display.contains(placement.frame)) + } + + func testShrinksToFitATinyScreen() { + let tiny = CGRect(x: 0, y: 0, width: 300, height: 300) + let frame = MiniShelfLayout.placement(size: size, anchor: CGRect(x: 150, y: 150, width: 0, height: 0), + visibleFrame: tiny).frame + XCTAssertTrue(tiny.contains(frame)) + } +}