Skip to content

Instantly share code, notes, and snippets.

@juanarzola
Last active March 17, 2025 21:11
Show Gist options
  • Save juanarzola/ee50fc0671e9af8f64dc28866da54bd1 to your computer and use it in GitHub Desktop.
Save juanarzola/ee50fc0671e9af8f64dc28866da54bd1 to your computer and use it in GitHub Desktop.
Overlay with buttons used just for triggering keyboard shortcuts
//
// 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()
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment