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
1 change: 0 additions & 1 deletion Example/Example/Views/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import Combine
import SwiftUI

import Interact
import SelectableCollectionView

struct ContentView: View {
Expand Down
25 changes: 17 additions & 8 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ let package = Package(
dependencies: [
.package(path: "MacResources"),
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
.package(url: "https://github.com/inseven/interact.git", .upToNextMajor(from: "2.21.1")),
.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,7 +25,6 @@ let package = Package(
name: "SelectableCollectionView",
dependencies: [
.product(name: "Cassowary", package: "CassowarySwift"),
.product(name: "Interact", package: "Interact"),
.product(name: "Licensable", package: "Licensable"),
.product(name: "SelectableCollectionViewMacResources",
package: "MacResources",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// https://stackoverflow.com/questions/64429554/how-to-get-string-value-from-localizedstringkey

import SwiftUI

extension LocalizedStringKey {

private typealias FArgs = (CVarArg, Formatter?)

var localized: String? {
let mirror = Mirror(reflecting: self)
let key: String? = mirror.descendant("key") as? String

guard let key else {
return nil
}

var fargs: [FArgs] = []

if let arguments = mirror.descendant("arguments") as? Array<Any> {
for argument in arguments {
let argumentMirror = Mirror(reflecting: argument)

if let storage = argumentMirror.descendant("storage") {
let storageMirror = Mirror(reflecting: storage)

if let formatStyleValue = storageMirror.descendant("formatStyleValue") {
let formatStyleValueMirror = Mirror(reflecting: formatStyleValue)

guard var input = formatStyleValueMirror.descendant("input") as? CVarArg else {
continue
}

let formatter: Formatter? = nil

if let _ = formatStyleValueMirror.descendant("format") {
// Cast input to String
input = String(describing: input) as CVarArg
}

fargs.append((input, formatter))
} else if let storageValue = storageMirror.descendant("value") as? FArgs {
fargs.append(storageValue)
}
}
}
}

let string = NSLocalizedString(key, comment: "")

if mirror.descendant("hasFormatting") as? Bool ?? false {
return String.localizedStringWithFormat(
string,
fargs.map { arg, formatter in
formatter?.string(for: arg) ?? arg
}
)
} else {
return string
}
}
}
136 changes: 136 additions & 0 deletions Sources/SelectableCollectionView/Menus/MenuItem.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright (c) 2022-2024 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.

import SwiftUI

@available(iOS 15, *, macOS 12, *)
public struct MenuItem: Identifiable {

public enum ItemType {
case item(String, String?, ButtonRole?, () -> Void)
case separator
case menu(String, String?, [MenuItem])
}

public let id = UUID()

public let itemType: ItemType
public var isDisabled: Bool = false
public var underlyingKeyboardShortcut: KeyboardShortcut?

public init(_ title: LocalizedStringKey, systemImage: String? = nil, role: ButtonRole? = nil, action: @escaping () -> Void) {
self.itemType = .item(title.localized ?? "", systemImage, role, action)
}

public init(_ title: String, systemImage: String? = nil, role: ButtonRole? = nil, action: @escaping () -> Void) {
self.itemType = .item(title ?? "", systemImage, role, action)
}

public init(_ title: LocalizedStringKey, systemImage: String? = nil, @MenuItemBuilder items: () -> [MenuItem]) {
self.itemType = .menu(title.localized ?? "", systemImage, items())
}

public init(_ title: String, systemImage: String? = nil, @MenuItemBuilder items: () -> [MenuItem]) {
self.itemType = .menu(title ?? "", systemImage, items())
}

public init(_ title: String, action: @escaping () async -> Void) {
self.init(title) {
Task {
await action()
}
}
}

init(_ itemType: ItemType) {
self.itemType = itemType
}

public func disabled(_ isDisabled: Bool) -> Self {
var menuItem = self
menuItem.isDisabled = isDisabled
return menuItem
}

public func keyboardShortcut(_ key: KeyEquivalent, modifiers: EventModifiers = .command) -> MenuItem {
var menuItem = self
menuItem.underlyingKeyboardShortcut = KeyboardShortcut(key, modifiers: modifiers)
return menuItem
}

}

@available(iOS 15, *, macOS 12, *)
extension MenuItem: MenuItemsConvertible {

public func asMenuItems() -> [MenuItem] {
return [self]
}

}

@available(iOS 15, *, macOS 12, *)
public struct Separator: MenuItemsConvertible {

public init() {}

public func asMenuItems() -> [MenuItem] {
return [MenuItem(.separator)]
}

}

@available(iOS 15, *, macOS 12, *)
extension Divider: MenuItemsConvertible {

public func asMenuItems() -> [MenuItem] {
return [MenuItem(.separator)]
}

}

@available(iOS 15, *, macOS 12, *)
extension Array where Element == MenuItem {

@ViewBuilder public func asContextMenu() -> some View {
MenuView(menuItems: self)
}

}

extension View {

@available(iOS 16, *, macOS 13, *)
public func contextMenu<I>(forSelectionType itemType: I.Type = I.self,
@MenuItemBuilder menu: @escaping (Set<I>) -> [MenuItem],
primaryAction: ((Set<I>) -> Void)? = nil) -> some View where I : Hashable {
contextMenu(forSelectionType: itemType, menu: { items in
menu(items).asContextMenu()
}, primaryAction: primaryAction)
}

@available(iOS 16, *, macOS 13, *)
public func contextMenu(@MenuItemBuilder menu: @escaping () -> [MenuItem]) -> some View {
contextMenu(ContextMenu {
menu().asContextMenu()
})
}

}
65 changes: 65 additions & 0 deletions Sources/SelectableCollectionView/Menus/MenuItemsBuilder.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright (c) 2022-2024 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.

import Foundation

@available(iOS 15, *, macOS 12, *)
public protocol MenuItemsConvertible {
func asMenuItems() -> [MenuItem]
}

@available(iOS 15, *, macOS 12, *)
@resultBuilder public struct MenuItemBuilder {

public static func buildBlock() -> [MenuItem] {
return []
}

public static func buildBlock(_ items: MenuItem...) -> [MenuItem] {
return items
}

public static func buildBlock(_ values: MenuItemsConvertible...) -> [MenuItem] {
return values
.flatMap { $0.asMenuItems() }
}

public static func buildIf(_ value: MenuItemsConvertible?) -> MenuItemsConvertible {
return value ?? []
}

public static func buildEither(first: MenuItemsConvertible) -> MenuItemsConvertible {
first
}

public static func buildEither(second: MenuItemsConvertible) -> MenuItemsConvertible {
second
}

}

@available(iOS 15, *, macOS 12, *)
extension Array: MenuItemsConvertible where Element == MenuItem {

public func asMenuItems() -> [MenuItem] {
return self
}

}
57 changes: 57 additions & 0 deletions Sources/SelectableCollectionView/Menus/MenuView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright (c) 2022-2024 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.

import SwiftUI

@available(iOS 15, *, macOS 12, *)
struct MenuView: View {

let menuItems: [MenuItem]

var body: some View {
ForEach(menuItems) { menuItem in
switch menuItem.itemType {
case .item(let title, let systemImage, let role, let action):
Button(role: role, action: action) {
if let systemImage {
Label(title, systemImage: systemImage)
} else {
Text(title)
}
}
.keyboardShortcut(menuItem.underlyingKeyboardShortcut)
.disabled(menuItem.isDisabled)
case .separator:
Divider()
case .menu(let title, let systemImage, let items):
if let systemImage {
Menu(title, systemImage: systemImage) {
MenuView(menuItems: items)
}
} else {
Menu(title) {
MenuView(menuItems: items)
}
}
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ import SwiftUI

import SelectableCollectionViewMacResources

import Interact

#warning("TODO: Rename element to ID to avoid confusion?")

protocol CollectionViewContainerDelegate: NSObject {
Expand Down
Loading