A platform for community discussion. Free, open, simple.
DEV: Add context option to addKeyboardShortcut for scoped bindings (#38077)
Régis Hanol01a421e144c8
diff --git a/frontend/discourse/app/services/keyboard-shortcuts.js b/frontend/discourse/app/services/keyboard-shortcuts.jsindex 3a708fb9df7..7c0bcf70bd8 100644--- a/frontend/discourse/app/services/keyboard-shortcuts.js+++ b/frontend/discourse/app/services/keyboard-shortcuts.js@@ -270,11 +270,41 @@ export default class KeyboardShortcutLib extends Service {** - click - allows to provide a selector on which a click event* will be triggered, eg: { click: ".topic.last .title" }+ * - context - a CSS selector string or function that scopes the shortcut.+ * When provided, the shortcut only fires if the context matches+ * (element exists in DOM / function returns truthy). Otherwise,+ * the previously-bound handler for this key fires instead.**/addShortcut(shortcut, callback, opts = {}) {// we trim but leave whitespace between characters, as shortcuts// like `z z` are valid for ItsATrap- this.bindKey(shortcut.trim(), { handler: callback, ...opts });+ shortcut = shortcut.trim();++ if (opts.context) {+ const contextTest =+ typeof opts.context === "function"+ ? opts.context+ : () => document.querySelector(opts.context) !== null;++ const dm = this.keyTrapper._directMap;+ const previousCallback =+ dm[shortcut + ":undefined"] ||+ dm[shortcut + ":keypress"] ||+ dm[shortcut + ":keydown"] ||+ dm[shortcut + ":keyup"];++ const originalCallback = callback;+ callback = function (...args) {+ if (contextTest()) {+ return originalCallback(...args);+ }+ if (previousCallback) {+ return previousCallback(...args);+ }+ };+ }++ this.bindKey(shortcut, { handler: callback, ...opts });if (opts.help) {addExtraKeyboardShortcutHelp(opts.help);}diff --git a/frontend/discourse/tests/unit/lib/keyboard-shortcuts-test.js b/frontend/discourse/tests/unit/lib/keyboard-shortcuts-test.jsindex 425d52f97da..49ebde832f9 100644--- a/frontend/discourse/tests/unit/lib/keyboard-shortcuts-test.js+++ b/frontend/discourse/tests/unit/lib/keyboard-shortcuts-test.js@@ -36,4 +36,135 @@ module("Unit | Utility | keyboard-shortcuts", function (hooks) {keyboardShortcuts.prevSection();assert.true(spy.calledWith(-1), "_changeSection is called with -1");});++ module("addShortcut context option", function () {+ test("fires new handler when CSS selector context matches", function (assert) {+ const ks = this.owner.lookup("service:keyboard-shortcuts");+ let handlerACalled = false;+ let handlerBCalled = false;++ ks.addShortcut("x", () => (handlerACalled = true), { anonymous: true });++ const el = document.createElement("div");+ el.classList.add("test-context-target");+ document.body.appendChild(el);++ try {+ ks.addShortcut("x", () => (handlerBCalled = true), {+ anonymous: true,+ context: ".test-context-target",+ });++ // Simulate keypress via ItsATrap+ ks.keyTrapper.trigger("x");++ assert.true(handlerBCalled, "new handler fires when context matches");+ assert.false(handlerACalled, "previous handler does not fire");+ } finally {+ el.remove();+ }+ });++ test("falls back to previous handler when context does not match", function (assert) {+ const ks = this.owner.lookup("service:keyboard-shortcuts");+ let handlerACalled = false;+ let handlerBCalled = false;++ ks.addShortcut("y", () => (handlerACalled = true), { anonymous: true });+ ks.addShortcut("y", () => (handlerBCalled = true), {+ anonymous: true,+ context: ".nonexistent-element",+ });++ ks.keyTrapper.trigger("y");++ assert.true(handlerACalled, "previous handler fires as fallback");+ assert.false(handlerBCalled, "new handler does not fire");+ });++ test("no error when no previous binding exists and context does not match", function (assert) {+ const ks = this.owner.lookup("service:keyboard-shortcuts");+ let called = false;++ ks.addShortcut("q w", () => (called = true), {+ anonymous: true,+ context: ".nonexistent-element",+ });++ ks.keyTrapper.trigger("q w");++ assert.false(called, "handler does not fire");+ });++ test("function context is evaluated", function (assert) {+ const ks = this.owner.lookup("service:keyboard-shortcuts");+ let contextActive = false;+ let handlerACalled = false;+ let handlerBCalled = false;++ ks.addShortcut("z", () => (handlerACalled = true), { anonymous: true });+ ks.addShortcut("z", () => (handlerBCalled = true), {+ anonymous: true,+ context: () => contextActive,+ });++ ks.keyTrapper.trigger("z");+ assert.true(handlerACalled, "fallback fires when function returns false");+ assert.false(handlerBCalled);++ handlerACalled = false;+ contextActive = true;+ ks.keyTrapper.trigger("z");+ assert.true(+ handlerBCalled,+ "new handler fires when function returns true"+ );+ assert.false(handlerACalled);+ });++ test("chained context bindings fall back correctly", function (assert) {+ const ks = this.owner.lookup("service:keyboard-shortcuts");+ const calls = [];++ ks.addShortcut("w", () => calls.push("original"), { anonymous: true });+ ks.addShortcut("w", () => calls.push("plugin-a"), {+ anonymous: true,+ context: ".plugin-a-active",+ });+ ks.addShortcut("w", () => calls.push("plugin-b"), {+ anonymous: true,+ context: ".plugin-b-active",+ });++ // Neither context matches — should fall through to original+ ks.keyTrapper.trigger("w");+ assert.deepEqual(calls, ["original"]);++ calls.length = 0;+ const elA = document.createElement("div");+ elA.classList.add("plugin-a-active");+ document.body.appendChild(elA);++ try {+ // plugin-b context doesn't match, falls to plugin-a which matches+ ks.keyTrapper.trigger("w");+ assert.deepEqual(calls, ["plugin-a"]);+ } finally {+ elA.remove();+ }++ calls.length = 0;+ const elB = document.createElement("div");+ elB.classList.add("plugin-b-active");+ document.body.appendChild(elB);++ try {+ // plugin-b context matches+ ks.keyTrapper.trigger("w");+ assert.deepEqual(calls, ["plugin-b"]);+ } finally {+ elB.remove();+ }+ });+ });});