Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Example/Example/Model/Creator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,8 @@ class Creator: CollectionViewStreamingCollection {
return
}
let index = Int.random(in: 0..<items.count)
var item = items[index]
let item = items[index]
item.count += 1
items[index] = item // We currently need to replace this because it's a struct.
collectionView?.updateItem(item, atIndex: index, items: items)
}

Expand Down
1 change: 1 addition & 0 deletions Example/Example/Views/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ struct ContentView: View {
primaryAction(selection)
}
} else {
// TODO: Think hard about memory leaks here.
SelectableCollectionView(model.filteredItems, selection: $model.selection, layout: layout) { item in
Cell(item: item, isPainted: model.isPainted)
} contextMenu: { selection in
Expand Down
4 changes: 0 additions & 4 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ let package = Package(
targets: ["SelectableCollectionView"]),
],
dependencies: [
.package(path: "MacResources"),
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
.package(url: "https://github.com/inseven/licensable.git", .upToNextMajor(from: "0.0.1")),
.package(url: "https://github.com/tribalworldwidelondon/CassowarySwift.git", from: "2.0.0"),
Expand All @@ -26,9 +25,6 @@ let package = Package(
dependencies: [
.product(name: "Cassowary", package: "CassowarySwift"),
.product(name: "Licensable", package: "Licensable"),
.product(name: "SelectableCollectionViewMacResources",
package: "MacResources",
condition: .when(platforms: [.macOS])),
],
resources: [.process("Resources")]),
.testTarget(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

import SwiftUI


// TODO: We need a decoupling proxy if we're not going to have memory leaks
/**
* Proxy protocol for managing a collection view.
*
Expand Down
103 changes: 103 additions & 0 deletions Sources/SelectableCollectionView/Views/CollectionViewCell.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Copyright (c) 2022-2026 Jason Morley
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#if os(macOS)

import SwiftUI

class CollectionViewCell<ID: Hashable, Content: View>: NSCollectionViewItem {

static var identifier: NSUserInterfaceItemIdentifier {
return NSUserInterfaceItemIdentifier(rawValue: "CollectionViewCell")
}

private var hostingView: NSHostingView<CollectionViewCellContent<ID, Content>>?
private var id: ID?
private var content: Content?
private var parentHasFocus: Bool = false
private var parentIsKey: Bool = false

override var isSelected: Bool {
didSet {
updateState()
}
}

override var highlightState: NSCollectionViewItem.HighlightState {
didSet {
updateState()
}
}

override func loadView() {
view = NSView()
}

func configure(_ content: Content?, id: ID?, parentHasFocus: Bool, parentIsKey: Bool) {
self.content = content
self.id = id
self.parentHasFocus = parentHasFocus
self.parentIsKey = parentIsKey
host()
}

private func updateState() {
host()
}

private func host() {

guard content != nil || hostingView != nil else {
return
}

let selectionColor = parentHasFocus && parentIsKey
? Color(nsColor: .selectedContentBackgroundColor)
: Color(nsColor: .unemphasizedSelectedContentBackgroundColor)
let rootView = CollectionViewCellContent(id: id,
content: content,
isSelected: isSelected,
highlightState: .init(highlightState),
selectionColor: selectionColor)

guard let hostingView else {
let hostingView = NSHostingView(rootView: rootView)
hostingView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(hostingView)
NSLayoutConstraint.activate([
hostingView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hostingView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
hostingView.topAnchor.constraint(equalTo: view.topAnchor),
hostingView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
self.hostingView = hostingView
return
}
hostingView.rootView = rootView
}

override func prepareForReuse() {
super.prepareForReuse()
configure(nil, id: nil, parentHasFocus: false, parentIsKey: false)
}

}

#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright (c) 2022-2026 Jason Morley
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#if os(macOS)

import SwiftUI

struct CollectionViewCellContent<ID: Hashable, Content: View>: View {

let id: ID?
let content: Content?
let isSelected: Bool
let highlightState: CollectionViewItemHighlightState
let selectionColor: Color

var body: some View {
if let content, let id {
content
.environment(\.isSelected, isSelected)
.environment(\.highlightState, highlightState)
.environment(\.selectionColor, selectionColor)
.id(id)
}
}

}

#endif
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ import Carbon
import Combine
import SwiftUI

import SelectableCollectionViewMacResources

public protocol CollectionViewContainerDelegate: NSObject {

associatedtype Element: Identifiable
Expand Down Expand Up @@ -67,7 +65,7 @@ public class CollectionViewContainer<Element: Identifiable, Content: View, Deleg

typealias Snapshot = NSDiffableDataSourceSnapshot<Section, Element.ID>
typealias DataSource = NSCollectionViewDiffableDataSource<Section, Element.ID>
typealias Cell = ShortcutItemView
typealias Cell = CollectionViewCell<Element.ID, Content>

private let scrollView: CustomScrollView
private let collectionView: InteractiveCollectionView
Expand All @@ -90,17 +88,26 @@ public class CollectionViewContainer<Element: Identifiable, Content: View, Deleg
super.init(frame: .zero)

dataSource = DataSource(collectionView: collectionView) { [weak self] collectionView, indexPath, id in
guard let view = collectionView.makeItem(withIdentifier: Cell.identifier,
for: indexPath) as? Cell else {
return Cell()
}
guard let self,
let item = self.items[id],
let view = collectionView.makeItem(withIdentifier: ShortcutItemView.identifier, for: indexPath) as? ShortcutItemView,
let content = self.delegate?.collectionViewContainer(self, contentForElement: item)
else {
return ShortcutItemView()
// Explicitly empty the cell. It may have been recycled, in which case returning it untouched would
// leave it showing the previous element's content.
view.configure(nil,
id: nil,
parentHasFocus: collectionView.isFirstResponder,
parentIsKey: collectionView.window?.isKeyWindow ?? false)
return view
}
view.configure(AnyView(content),
view.configure(content,
id: id,
parentHasFocus: collectionView.isFirstResponder,
parentIsKey: collectionView.window?.isKeyWindow ?? false)
view.element = item
return view
}

Expand All @@ -117,9 +124,7 @@ public class CollectionViewContainer<Element: Identifiable, Content: View, Deleg
collectionView.delegate = self
collectionView.interactionDelegate = self

let itemNib = NSNib(nibNamed: "ShortcutItemView", bundle: Resources.bundle)
collectionView.register(itemNib, forItemWithIdentifier: ShortcutItemView.identifier)
collectionView.register(ShortcutItemView.self, forItemWithIdentifier: ShortcutItemView.identifier)
collectionView.register(Cell.self, forItemWithIdentifier: Cell.identifier)

collectionView.isSelectable = true
collectionView.allowsMultipleSelection = true
Expand All @@ -141,16 +146,20 @@ public class CollectionViewContainer<Element: Identifiable, Content: View, Deleg
fatalError("init(coder:) has not been implemented")
}

// TODO: Take in a set of items to compare with and we can maybe do an intersection?
// TODO: Is it possible to restrict this to just the cells that have changed?
func updateVisibleItems() {
// Update the hosted item content.
for item in collectionView.visibleItems() {
guard let item = item as? ShortcutItemView,
let element = item.element as? Element else {
guard let item = item as? Cell,
let indexPath = collectionView.indexPath(for: item),
let id = dataSource?.itemIdentifier(for: indexPath),
let element = items[id],
let content = delegate?.collectionViewContainer(self, contentForElement: element)
else {
continue
}
let content = self.delegate?.collectionViewContainer(self, contentForElement: element)
item.configure(AnyView(content),
item.configure(content,
id: id,
parentHasFocus: collectionView.isFirstResponder,
parentIsKey: collectionView.window?.isKeyWindow ?? false)
}
Expand Down Expand Up @@ -280,7 +289,8 @@ public class CollectionViewContainer<Element: Identifiable, Content: View, Deleg
dispatchPrecondition(condition: .onQueue(.main))

// Cache the items.
for item in items {
self.items.removeAll()
for item in items {
self.items[item.id] = item
}

Expand All @@ -290,7 +300,7 @@ public class CollectionViewContainer<Element: Identifiable, Content: View, Deleg
snapshot.appendItems(items.map({ $0.id }), toSection: Section.none)
dataSource.apply(snapshot, animatingDifferences: true)

// TODO: Update the selection?
// TODO: Update the selection and the currently selected coordinate.
}

public func insertItem(_ item: Element, atIndex index: Int, items: [Element]) {
Expand Down
Loading