Files
wekan/client/lib/keyboard.js
T
Lauri Ojansivu 138f727ebb Card shortcuts open only their popup.
d, Shift+M and Shift+C on a hovered or selected minicard opened the card
first, and Shift+M / Shift+C then opened the card's hamburger menu and
clicked its item: card, menu and popup for one key. Now the Due date, Move
card or Copy card popup opens by itself next to the minicard, as a click on
a minicard's date or label opens only its popup, and the card stays closed.
On an opened card Move / Copy open next to its hamburger without showing the
menu; d there still clicks the card's own Due date control.

The popup is opened directly, so client/lib/cardShortcutPopup.js applies the
conditions the controls a click would use are rendered under: the board
allows due dates and the user may modify the card (a Worker only edits an
existing date), Move card for a board admin, Copy card for a member who is
not a Worker, both only with cardMenuWrites. Without them nothing opens.
tests/cardShortcutPopup.test.cjs drives the rules and ties each one to its
template condition; the browser specs check the card stays closed and no
menu is shown, and that a non-admin and disabled shortcuts open nothing.
The help-list check matched "Move Card to Archive" too and now matches the
action text exactly.

Thanks to mimZD and xet7 !

Fixes #6924.
2026-11-16 16:46:06 +02:00

592 lines
19 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import { Template } from 'meteor/templating';
import { ReactiveCache } from '/imports/reactiveCache';
import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import Cards from '/models/cards';
import { Filter } from '/client/lib/filter';
import { MultiSelection } from '/client/lib/multiSelection';
import { Utils } from '/client/lib/utils';
import { newHistoryRequestId, runKeystroke } from '/client/lib/historyKeyRequest';
import { historyRequestStorage, refreshPendingHistoryRequest } from '/client/lib/historyKeyRecovery';
import { findDueDateControl } from '/client/lib/dueDateHotkey';
import { findCardMenuOpener } from '/client/lib/cardMenuHotkey';
import { cardShortcutPopup, findMinicard } from '/client/lib/cardShortcutPopup';
// Late-bind Sidebar to avoid circular dependency (sidebar.js needs its template first)
let _Sidebar;
function getSidebar() {
if (!_Sidebar) _Sidebar = require('/client/features/sidebar/service').getSidebarInstance;
return _Sidebar();
}
const hotkeys = require('hotkeys-js').default;
// XXX There is no reason to define these shortcuts globally, they should be
// attached to a template (most of them will go in the `board` template).
// Configure hotkeys filter (replaces Mousetrap.stopCallback)
// CRITICAL: Return values are INVERTED from Mousetrap's stopCallback
// hotkeys filter: true = ALLOW shortcut, false = STOP shortcut
hotkeys.filter = (event) => {
// Are shortcuts enabled for the user?
if (ReactiveCache.getCurrentUser() && !ReactiveCache.getCurrentUser().isKeyboardShortcuts())
return false;
// Always handle escape
if (event.keyCode === 27)
return true;
// Make sure there are no selected characters
if (window.getSelection().type === "Range")
return false;
// Synthetic non-Latin keyboard events are dispatched on document, which has
// no element APIs. Keep filtering against the focused control in that case.
const currentElement = event.target instanceof Element
? event.target
: document.activeElement;
if (!currentElement) return false;
// If the current element is editable, we don't want to trigger an event
if (currentElement.isContentEditable)
return false;
// Make sure we are not in an input element
if (currentElement instanceof HTMLInputElement || currentElement instanceof HTMLSelectElement || currentElement instanceof HTMLTextAreaElement)
return false;
// A focused control keeps the keys it uses itself, and only those: Enter
// activates any of them, Space a button, summary or checkbox (not a link),
// and End, Home and the arrows move between tabs (A01). Every other key is
// still a shortcut. Refusing ALL keys left shortcuts dead after a click on
// a minicard - the minicard is a link, and clicking its date badge or its
// menu leaves that link focused - and after any popup closed, because
// closing returns focus to the button that opened it (#6755).
const keysOwnedBy = {
'button, a[href], summary, [role="button"], [role="tab"], [role="checkbox"]': [13],
'button, summary, [role="button"], [role="checkbox"]': [32],
'[role="tab"]': [35, 36, 37, 38, 39, 40],
};
if (Object.keys(keysOwnedBy).some(controls =>
keysOwnedBy[controls].includes(event.keyCode) && currentElement.closest(controls)))
return false;
// We can trigger events!
return true;
};
// Handle non-Latin keyboards
//
// Nothing to do here, on purpose (#6840). This used to re-dispatch a key typed on
// another script (a Farsi or Cyrillic letter) as its Latin key, for the old
// Mousetrap, which read the typed character. hotkeys-js does not: it resolves a
// key from `event.code` ('KeyD') and `keyCode`, whatever character the layout
// types, so it already runs the shortcut for the physical d key on any layout.
// The copy then ran every shortcut a SECOND time - the due date editor opened
// and the repeat clicked the same control, closing it again, so `d` "opens the
// popup and closes it at a glance" on a Farsi keyboard (and Shift+D did the same
// on a Latin one, #6750). tests/keyboardNonLatinOnce.test.cjs.
function getHoveredCardId() {
const card = $('.js-minicard:hover').get(0);
if (!card) return null;
return Blaze.getData(card)._id;
}
function getSelectedCardId() {
return Session.get('currentCard') || Session.get('selectedCard') || getHoveredCardId();
}
hotkeys('?', (event) => {
event.preventDefault();
FlowRouter.go('shortcuts');
});
hotkeys('w', (event) => {
event.preventDefault();
if (getSidebar().isOpen() && getSidebar().getView() === 'home') {
getSidebar().toggle();
} else {
getSidebar().setView();
}
});
hotkeys('q', (event) => {
event.preventDefault();
const currentBoardId = Session.get('currentBoard');
const currentUserId = Meteor.userId();
if (currentBoardId && currentUserId) {
Filter.members.toggle(currentUserId);
}
});
hotkeys('a', (event) => {
event.preventDefault();
const currentBoardId = Session.get('currentBoard');
const currentUserId = Meteor.userId();
if (currentBoardId && currentUserId) {
Filter.assignees.toggle(currentUserId);
}
});
hotkeys('x', (event) => {
event.preventDefault();
if (Filter.isActive()) {
Filter.reset();
}
});
hotkeys('f', (event) => {
event.preventDefault();
if (getSidebar().isOpen() && getSidebar().getView() === 'filter') {
getSidebar().toggle();
} else {
getSidebar().setView('filter');
}
});
hotkeys('/', (event) => {
event.preventDefault();
if (getSidebar().isOpen() && getSidebar().getView() === 'search') {
getSidebar().toggle();
} else {
getSidebar().setView('search');
}
});
hotkeys('down,up', (event, handler) => {
event.preventDefault();
if (!Utils.getCurrentCardId()) {
return;
}
const nextFunc = handler.key === 'down' ? 'next' : 'prev';
const nextCard = $('.js-minicard.is-selected')
[nextFunc]('.js-minicard')
.get(0);
if (nextCard) {
const nextCardId = Blaze.getData(nextCard)._id;
Utils.goCardId(nextCardId);
}
});
// Shift + number keys to remove labels in multiselect
const shiftNums = Array.from({length: 9}, (_, i) => `shift+${i + 1}`).join(',');
hotkeys(shiftNums, (event, handler) => {
event.preventDefault();
const num = parseInt(handler.key.split('+')[1]);
const currentUserId = Meteor.userId();
if (currentUserId === null) {
return;
}
const currentBoardId = Session.get('currentBoard');
const board = ReactiveCache.getBoard(currentBoardId);
if (!board) return;
const labels = board.labels;
if (MultiSelection.isActive()) {
const cardIds = MultiSelection.getSelectedCardIds();
for (const cardId of cardIds) {
const card = Cards.findOne(cardId);
if (num <= board.labels.length) {
card.removeLabel(labels[num - 1]["_id"]);
}
}
}
});
// Number keys to toggle labels
const nums = Array.from({length: 9}, (_, i) => i + 1).join(',');
hotkeys(nums, (event, handler) => {
event.preventDefault();
const num = parseInt(handler.key);
const currentUserId = Meteor.userId();
const currentBoardId = Session.get('currentBoard');
if (currentUserId === null) {
return;
}
const board = ReactiveCache.getBoard(currentBoardId);
if (!board) return;
const labels = board.labels;
if (MultiSelection.isActive() && ReactiveCache.getCurrentUser().isBoardMember()) {
const cardIds = MultiSelection.getSelectedCardIds();
for (const cardId of cardIds) {
const card = Cards.findOne(cardId);
if (num <= board.labels.length) {
card.addLabel(labels[num - 1]["_id"]);
}
}
return;
}
const cardId = getSelectedCardId();
if (!cardId) {
return;
}
if (ReactiveCache.getCurrentUser().isBoardMember()) {
const card = Cards.findOne(cardId);
if (num <= board.labels.length) {
card.toggleLabel(labels[num - 1]["_id"]);
}
}
});
// Ctrl+Alt + number keys to toggle assignees
const ctrlAltNums = Array.from({length: 9}, (_, i) => `ctrl+alt+${i + 1}`).join(',');
hotkeys(ctrlAltNums, (event, handler) => {
event.preventDefault();
// Make sure the current user is defined
if (!ReactiveCache.getCurrentUser())
return;
// Make sure the current user is a board member
if (!ReactiveCache.getCurrentUser().isBoardMember())
return;
const memberIndex = parseInt(handler.key.split("+").pop()) - 1;
const currentBoard = Utils.getCurrentBoard();
const validBoardMembers = currentBoard.memberUsers().filter(member => member.isBoardMember());
if (memberIndex >= validBoardMembers.length)
return;
const memberId = validBoardMembers[memberIndex]._id;
if (MultiSelection.isActive()) {
for (const cardId of MultiSelection.getSelectedCardIds())
Cards.findOne(cardId).toggleAssignee(memberId);
} else {
const cardId = getSelectedCardId();
if (!cardId)
return;
Cards.findOne(cardId).toggleAssignee(memberId);
}
});
hotkeys('m', (event) => {
event.preventDefault();
const cardId = getSelectedCardId();
if (!cardId) {
return;
}
const currentUserId = Meteor.userId();
if (currentUserId === null) {
return;
}
if (ReactiveCache.getCurrentUser().isBoardMember()) {
const card = Cards.findOne(cardId);
card.toggleAssignee(currentUserId);
}
});
hotkeys('space', (event) => {
event.preventDefault();
const cardId = getSelectedCardId();
if (!cardId) {
return;
}
const currentUserId = Meteor.userId();
if (currentUserId === null) {
return;
}
if (ReactiveCache.getCurrentUser().isBoardMember()) {
const card = Cards.findOne(cardId);
card.toggleMember(currentUserId);
}
});
const archiveCard = async (event) => {
event.preventDefault();
const cardId = getSelectedCardId();
if (!cardId) {
return;
}
const currentUserId = Meteor.userId();
if (currentUserId === null) {
return;
}
if (Utils.canModifyBoard()) {
const card = Cards.findOne(cardId);
await card.archive();
}
};
// Archive card has multiple shortcuts
hotkeys('c', archiveCard);
hotkeys('-', archiveCard);
// Same as above, this time for Persian keyboard.
// https://github.com/wekan/wekan/pull/5589#issuecomment-2516776519
hotkeys('\xf7', archiveCard);
// #6478: Undo / Redo the caller's last position change (card / list / swimlane
// move) with Ctrl+Z / Ctrl+Y (also Cmd+Z / Cmd+Shift+Z on macOS). The hotkeys
// filter above disables shortcuts inside inputs/textareas/contentEditable, so
// native text undo/redo keeps working while typing. Only enabled for members who
// can modify the board.
// Each keystroke carries a request ID kept in sessionStorage until the server
// answers, so a reply lost to a disconnect or reload is retried rather than
// repeated (client/lib/historyKeyRequest.js).
export function undoRedoLast(direction) {
const boardId = Session.get('currentBoard');
if (!boardId || !Utils.canModifyBoard()) {
return Promise.resolve();
}
const storage = historyRequestStorage();
// Whatever happens, the recovery notice shows what is still unanswered
// (client/lib/historyKeyRecovery.js).
return runKeystroke({
storage,
call: (method, ...args) => Meteor.callAsync(method, ...args),
boardId,
direction,
newId: newHistoryRequestId(),
}).catch(() => {}).then(() => refreshPendingHistoryRequest(storage));
}
hotkeys('ctrl+z, command+z', event => {
event.preventDefault();
undoRedoLast('undo');
});
hotkeys('ctrl+y, ctrl+shift+z, command+shift+z', event => {
event.preventDefault();
undoRedoLast('redo');
});
hotkeys('n', (event) => {
event.preventDefault();
const cardId = getSelectedCardId();
if (!cardId) {
return;
}
const currentUserId = Meteor.userId();
if (currentUserId === null) {
return;
}
if (Utils.canModifyBoard()) {
// Find the current hovered card
const card = Cards.findOne(cardId);
// Find the button and click it
$(`#js-list-${card.listId} .list-body .minicards .open-minicard-composer`).click();
}
});
// #6750: `d` (and Shift+D, so a capital D works too) opens the Due date
// editor of the OPENED card - the same popup as clicking the due date `+` or
// badge in the card details, by clicking that very control. Like every
// shortcut here it runs only through hotkeys.filter above: nothing when the
// user turned keyboard shortcuts off, nothing while typing in an input,
// textarea or contentEditable. It needs Utils.canModifyCard for the card; the
// card details render the control only for a user who may edit the due date,
// so without one nothing happens.
function clickDueDateControl(cardId) {
const card = ReactiveCache.getCard(cardId);
if (!card) return false;
const control = findDueDateControl(document, {
cardId,
canModifyCard: Utils.canModifyCard(card),
dataOf: element => Blaze.getData(element),
});
if (!control) return false;
control.click();
return true;
}
// #6840: the card's details render a moment AFTER the route names it - a few
// hundred milliseconds on a slow server. Pressing `d` right after opening a
// card found no control yet and did nothing, while the previous card's details
// were still on screen. So the click waits until THIS card's control is there,
// both for an opened card and for one `d` opens itself (#6755), and clicks it
// once; it gives up quietly after 3 seconds (no due dates on this board).
function clickDueDateControlWhenRendered(cardId) {
const started = Date.now();
const tryClick = () => {
if (Utils.getCurrentCardId() !== cardId) return;
if (clickDueDateControl(cardId)) return;
if (Date.now() - started < 3000) setTimeout(tryClick, 50);
};
tryClick();
}
export function openDueDateEditorOfOpenedCard() {
if (Meteor.userId() === null) return false;
const cardId = Utils.getCurrentCardId();
if (cardId) {
const card = ReactiveCache.getCard(cardId);
if (!card || !Utils.canModifyCard(card)) return false;
clickDueDateControlWhenRendered(cardId);
return true;
}
// #6755: with no card opened, `d` on a hovered or selected minicard - the
// card every other card shortcut here acts on - opens its Due date editor.
// #6924: only the editor, next to the minicard, as a click on the
// minicard's due date does; the card itself stays closed.
return openCardShortcutPopupAtMinicard('due');
}
hotkeys('d, shift+d', (event) => {
event.preventDefault();
openDueDateEditorOfOpenedCard();
});
// #6904: Shift+M opens Move card and Shift+C opens Copy card. Shift keeps them
// apart from `m` (assign yourself) and `c` (archive).
// #6924: each opens ONLY its popup. The popup is opened directly, so
// cardShortcutPopup (client/lib/cardShortcutPopup.js) applies the rules the
// controls a click would use are rendered under - the hamburger menu's Move
// card / Copy card items, the due date badge and its `+` - and without them
// nothing opens.
function cardShortcutFacts(card) {
const user = ReactiveCache.getCurrentUser();
const board = ReactiveCache.getBoard(card.boardId);
return {
canModifyCard: Utils.canModifyCard(card),
isBoardAdmin: Boolean(user && user.isBoardAdmin && user.isBoardAdmin()),
isWorker: Boolean(user && user.isWorker && user.isWorker()),
isReadOnly: Boolean(user && user.isReadOnly && user.isReadOnly()),
isReadAssignedOnly: Boolean(user && user.isReadAssignedOnly && user.isReadAssignedOnly()),
allowsDueDate: !board || board.allowsDueDate !== false,
hasDue: Boolean(card.getDue && card.getDue()),
};
}
// Opens the popup next to `anchor`, with the card as its data context - as
// the minicard's own menu and date badges open theirs (minicard.js,
// cardDate.js openDateEditor).
function openCardShortcutPopup(action, card, anchor) {
const name = cardShortcutPopup(action, cardShortcutFacts(card));
if (!name || !anchor) return false;
Popup.open(name).call(card, { currentTarget: anchor, target: anchor, preventDefault() {} });
return true;
}
// With no card opened: the hovered or selected minicard, the card every other
// card shortcut here acts on. The card is not opened.
function openCardShortcutPopupAtMinicard(action) {
const minicardId = Session.get('selectedCard') || getHoveredCardId();
const minicard = minicardId && ReactiveCache.getCard(minicardId);
if (!minicard) return false;
const anchor = findMinicard(document, minicardId, $('.js-minicard:hover').get(0));
return openCardShortcutPopup(action, minicard, anchor);
}
// #6840: an opened card's details render a moment after the route names it,
// so the popup waits for the card's hamburger to anchor to, and gives up
// after 3 seconds.
function openCardShortcutPopupWhenRendered(cardId, action) {
const started = Date.now();
const step = () => {
if (Utils.getCurrentCardId() !== cardId) return;
const card = ReactiveCache.getCard(cardId);
const anchor = card && findCardMenuOpener(document, { cardId, dataOf: element => Blaze.getData(element) });
if (anchor) {
openCardShortcutPopup(action, card, anchor);
return;
}
if (Date.now() - started < 3000) setTimeout(step, 50);
};
step();
}
export function openCardMenuActionOfOpenedCard(action) {
if (Meteor.userId() === null || !Utils.canModifyBoard()) return false;
const cardId = Utils.getCurrentCardId();
if (cardId) {
if (!ReactiveCache.getCard(cardId)) return false;
openCardShortcutPopupWhenRendered(cardId, action);
return true;
}
return openCardShortcutPopupAtMinicard(action);
}
hotkeys('shift+m', (event) => {
event.preventDefault();
openCardMenuActionOfOpenedCard('move');
});
hotkeys('shift+c', (event) => {
event.preventDefault();
openCardMenuActionOfOpenedCard('copy');
});
Template.keyboardShortcuts.helpers({
mapping: [
{
keys: ['w'],
action: 'shortcut-toggle-sidebar',
},
{
keys: ['q'],
action: 'shortcut-filter-my-cards',
},
{
keys: ['a'],
action: 'shortcut-filter-my-assigned-cards',
},
{
keys: ['n'],
action: 'add-card-to-bottom-of-list',
},
{
keys: ['f'],
action: 'shortcut-toggle-filterbar',
},
{
keys: ['/'],
action: 'shortcut-toggle-searchbar',
},
{
keys: ['x'],
action: 'shortcut-clear-filters',
},
{
keys: ['?'],
action: 'shortcut-show-shortcuts',
},
{
keys: ['ESC'],
action: 'shortcut-close-dialog',
},
{
keys: ['@'],
action: 'shortcut-autocomplete-members',
},
{
keys: ['SPACE'],
action: 'shortcut-add-self',
},
{
keys: ['m'],
action: 'shortcut-assign-self',
},
{
keys: ['d'],
action: 'shortcut-edit-due-date',
},
{
keys: ['SHIFT + m'],
action: 'moveCardPopup-title',
},
{
keys: ['SHIFT + c'],
action: 'copyCardPopup-title',
},
{
keys: ['c', '\xf7', '-'],
action: 'archive-card',
},
{
keys: ['number keys 1-9'],
action: 'toggle-labels'
},
{
keys: ['shift + number keys 1-9'],
action: 'remove-labels-multiselect'
},
{
keys: ['ctrl + alt + number keys 1-9'],
action: 'toggle-assignees'
},
],
});