diff --git a/app/javascript/packs/application.js b/app/javascript/packs/application.js index 395020c6d..f0eeef6f0 100644 --- a/app/javascript/packs/application.js +++ b/app/javascript/packs/application.js @@ -38,4 +38,5 @@ export { default as Note } from '../src/javascripts/notes.js'; export { default as PostModeMenu } from '../src/javascripts/post_mode_menu.js'; export { default as Utility } from '../src/javascripts/utility.js'; export { default as Ugoira } from '../src/javascripts/ugoira.js'; +export { default as Shortcuts } from '../src/javascripts/shortcuts.js'; export { default as TagScript } from '../src/javascripts/tag_script.js'; diff --git a/app/javascript/src/javascripts/shortcuts.js b/app/javascript/src/javascripts/shortcuts.js index 5cdc09666..444854ca5 100644 --- a/app/javascript/src/javascripts/shortcuts.js +++ b/app/javascript/src/javascripts/shortcuts.js @@ -6,6 +6,7 @@ let Shortcuts = {}; Shortcuts.initialize = function() { Utility.keydown("s", "scroll_down", Shortcuts.nav_scroll_down); Utility.keydown("w", "scroll_up", Shortcuts.nav_scroll_up); + Shortcuts.initialize_data_shortcuts(); Utility.keydown("q", "focus_search", function(e) { $("#tags, #search_name, #search_name_matches, #query").trigger("focus").selectEnd(); @@ -39,6 +40,40 @@ Shortcuts.initialize = function() { } } +// Bind keyboard shortcuts to links that have a `data-shortcut="..."` attribute. If multiple links have the +// same shortcut, then only the first link will be triggered by the shortcut. +// +// Add `data-shortcut-when="$selector"`, where `selector` is any valid jQuery selector, to make the shortcut +// active only when the link matches the selector. For example, `data-shortcut-when=":visible"` makes the +// shortcut apply only when the link is visible. +Shortcuts.initialize_data_shortcuts = function() { + $(document).off("keydown.danbooru.shortcut"); + + $("[data-shortcut]").each((_i, element) => { + const id = $(element).attr("id"); + const keys = $(element).attr("data-shortcut"); + const namespace = `shortcut.${id}`; + + const title = `Shortcut is ${keys.split(/\s+/).join(" or ")}`; + $(element).attr("title", title); + + Utility.keydown(keys, namespace, event => { + const e = $(`[data-shortcut="${keys}"]`).get(0); + const condition = $(e).attr("data-shortcut-when") || "*"; + + if ($(e).is(condition)) { + if ($(e).is("input, textarea")) { + e.focus(); + } else { + e.click(); + } + + event.preventDefault(); + } + }); + }); +}; + Shortcuts.nav_scroll_down = function() { var scroll_top = $(window).scrollTop() + ($(window).height() * 0.15); $(window).scrollTop(scroll_top);