Skip to content

A platform for community discussion. Free, open, simple.

DEV: Support adding keybindings via plugins (#9177)

Mark VanLandingham40f1201b3966
diff --git a/app/assets/javascripts/discourse/lib/keyboard-shortcuts.js.es6 b/app/assets/javascripts/discourse/lib/keyboard-shortcuts.js.es6
index 59840f2b4d7..2a401e4fcd2 100644
--- a/app/assets/javascripts/discourse/lib/keyboard-shortcuts.js.es6
+++ b/app/assets/javascripts/discourse/lib/keyboard-shortcuts.js.es6
@@ -6,7 +6,7 @@ import { ajax } from "discourse/lib/ajax";
import { throttle } from "@ember/runloop";
import { INPUT_DELAY } from "discourse-common/config/environment";
-const bindings = {
+export let bindings = {
"!": { postAction: "showFlags" },
"#": { handler: "goToPost", anonymous: true },
"/": { handler: "toggleSearch", anonymous: true },
@@ -406,14 +406,16 @@ export default {
},
_globalBindToFunction(func, binding) {
- if (typeof this[func] === "function") {
+ let funcToBind = typeof func === "function" ? func : this[func];
+ if (typeof funcToBind === "function") {
this.keyTrapper.bindGlobal(binding, this[func].bind(this));
}
},
_bindToFunction(func, binding) {
- if (typeof this[func] === "function") {
- this.keyTrapper.bind(binding, this[func].bind(this));
+ let funcToBind = typeof func === "function" ? func : this[func];
+ if (typeof funcToBind === "function") {
+ this.keyTrapper.bind(binding, funcToBind.bind(this));
}
},
diff --git a/app/assets/javascripts/discourse/lib/plugin-api.js.es6 b/app/assets/javascripts/discourse/lib/plugin-api.js.es6
index bd55faf05c8..cdaaad0263c 100644
--- a/app/assets/javascripts/discourse/lib/plugin-api.js.es6
+++ b/app/assets/javascripts/discourse/lib/plugin-api.js.es6
@@ -1,3 +1,4 @@
+/*global Mousetrap:true*/
import deprecated from "discourse-common/lib/deprecated";
import { iconNode } from "discourse-common/lib/icon-library";
import { addDecorator } from "discourse/widgets/post-cooked";
@@ -50,9 +51,10 @@ import { addCategorySortCriteria } from "discourse/components/edit-category-sett
import { queryRegistry } from "discourse/widgets/widget";
import Composer from "discourse/models/composer";
import { on } from "@ember/object/evented";
+import KeyboardShortcuts, { bindings } from "discourse/lib/keyboard-shortcuts";
// If you add any methods to the API ensure you bump up this number
-const PLUGIN_API_VERSION = "0.8.38";
+const PLUGIN_API_VERSION = "0.8.39";
class PluginApi {
constructor(version, container) {
@@ -227,6 +229,14 @@ class PluginApi {
}
}
+ addKeyboardShortcut(shortcut, callback, opts = {}) {
+ shortcut = shortcut.trim().replace(/\s/g, ""); // Strip all whitespace
+ let newBinding = {};
+ newBinding[shortcut] = Object.assign({ handler: callback }, opts);
+ Object.assign(bindings, newBinding);
+ KeyboardShortcuts.bindEvents(Mousetrap, this.container);
+ }
+
/**
* addPosterIcon(callback)
*