|
// |
|
// KeyboardShortcutButtons.swift |
|
// Learn |
|
// |
|
// Created by Juan Arzola on 3/15/25. |
|
// Copyright © 2025 Juan Arzola. All rights reserved. |
|
// |
|
|
|
import SwiftUI |
|
import UIKit |
|
|
|
extension View { |
|
public func keyboardShortcuts(_ commands: [Command]) -> some View { |
|
overlay { |
|
KeyboardShortcutButtons(commands: commands) |
|
.frame(width: 0, height: 0) |
|
} |
|
} |
|
} |
|
|
|
struct KeyboardShortcutButtons: View { |
|
let commands: [Command] |
|
|
|
var body: some View { |
|
ForEach(0..<commands.count, id: \.self) { index in |
|
let command = commands[index] |
|
Button { |
|
command.action() |
|
|
|
} label: { |
|
Text(command.title) |
|
} |
|
.keyboardShortcut( |
|
command.input, |
|
modifiers: command.modifierFlags |
|
) |
|
.opacity(0) |
|
.allowsHitTesting(false) |
|
.frame(width: 0, height: 0) |
|
} |
|
} |
|
} |
|
|
|
public struct Command { |
|
let title: LocalizedStringKey |
|
let input: KeyEquivalent |
|
var modifierFlags: EventModifiers = .command |
|
let action: () -> Void |
|
} |
|
|
|
#Preview { |
|
KeyboardShortcutButtons(commands: [ |
|
Command( |
|
title: "New Card", |
|
input: "n", |
|
modifierFlags: .command, |
|
action: {} |
|
) |
|
]) |
|
} |
|
|
|
// sample usage: |
|
/* |
|
|
|
extension View { |
|
func cardListKeyCommands(for container: ContainerKind) -> some View { |
|
modifier(CardListKeyboardShortcutsViewModifier(container: container)) |
|
} |
|
} |
|
|
|
struct CardListKeyboardShortcutsViewModifier: ViewModifier { |
|
let container: ContainerKind |
|
|
|
@State private var isNewCardEditorPresented = false |
|
@Environment(\.modelContext) private var modelContext |
|
@Environment(\.vaultUUID) private var vaultUUID |
|
|
|
func body(content: Content) -> some View { |
|
content.keyboardShortcuts([ |
|
Command( |
|
title: "New Card", |
|
input: "n", |
|
action: { isNewCardEditorPresented = true } |
|
) |
|
]) |
|
.sheet(isPresented: $isNewCardEditorPresented) { |
|
NewCardEditorStack( |
|
folder: try? container.folder(in: modelContext, vaultUUID: vaultUUID) |
|
) { _ in |
|
isNewCardEditorPresented = false |
|
} |
|
.theme() |
|
} |
|
} |
|
} |
|
*/ |