KeyboardShortcuts icon indicating copy to clipboard operation
KeyboardShortcuts copied to clipboard

Convert NSEventModifierFlags to a symbolic representation

Open kopyl opened this issue 8 months ago • 6 comments

Do you know how I can safely convert a modifier from KeyboardShortcuts.Name.openTabsList.shortcut.modifiers to say "⇥"?

kopyl avatar Mar 11 '25 14:03 kopyl

I mean how safe would this be?

func modifierFlagsToSymbols(_ flags: NSEvent.ModifierFlags) -> String {
    var symbols = ""
    
    if flags.contains(.control) {
        symbols += "⌃"
    }
    if flags.contains(.option) {
        symbols += "⌥"
    }
    if flags.contains(.shift) {
        symbols += "⇧"
    }
    if flags.contains(.command) {
        symbols += "⌘"
    }
    if flags.contains(.function) {
        symbols += "fn"
    }
    
    return symbols
}

kopyl avatar Mar 11 '25 14:03 kopyl

Or something a bit cleaner

extension NSEvent.ModifierFlags {
    var symbolRepresentation: String {
        var symbols = ""

        if contains(.command) {
            symbols += "⌘"
        }
        if contains(.option) {
            symbols += "⌥"
        }
        if contains(.control) {
            symbols += "⌃"
        }
        if contains(.shift) {
            symbols += "⇧"
        }
        if contains(.capsLock) {
            symbols += "⇪"
        }

        return symbols
    }
}

To use it like KeyboardShortcuts.Name.openTabsList.shortcut?.modifiers.symbolRepresentation

kopyl avatar Mar 11 '25 15:03 kopyl

That looks fine, but you need to ensure the order is correct (that it follows the order macOS would put the symbols). We could add something for this here, but I want to avoid extending built-in types as it could cause conflicts with user's own extensions.

sindresorhus avatar Mar 13 '25 06:03 sindresorhus

@sindresorhus thank you.

By the way, I just used you library in one of my apps

https://apps.apple.com/us/app/tab-finder/id6741719894

Initially I just used HotKey library, but then users started asking to implement custom shortcuts and I looked into your library.

Initially I tried yours before using HotKey, but it was unable to add to my packages for some reason (it fixed now).

kopyl avatar Mar 13 '25 12:03 kopyl

@sindresorhus you could add the list of apps which use this package to the README.

kopyl avatar Mar 16 '25 07:03 kopyl

No, it requires too much maintenance.

sindresorhus avatar Mar 16 '25 08:03 sindresorhus