The Dolibarr ERP system comes with a comprehensive set of features, one of which is the bookmarks menu. This menu is especially handy for quickly accessing frequently used pages. The following JavaScript snippet enhances the bookmarks menu by allowing users to navigate through the bookmarks list using the up/down arrow keys right from the search field. It ensures a seamless and more intuitive user experience.
/**
* Arrow key navigation for the bookmarks dropdown in Dolibarr ERP.
*
* This script provides enhanced navigation for the bookmarks menu in Dolibarr
* ERP. Users can seamlessly navigate through bookmarks using arrow keys and
* close the dropdown with the Escape key.
*/
(function() {
// DOM references
const searchInput = document.getElementById('top-bookmark-search-input');
const dropdown = document.getElementById('dropdown-bookmarks-list');
const bookmarkItems = Array.from(dropdown.querySelectorAll('.bookmark-item'));
/**
* Find the next visible bookmark in the given direction.
*
* @param {number} fromIndex - Start search from this index.
* @param {number} direction - 1 for next, -1 for previous.
* @returns {HTMLElement|null} - The next visible bookmark or null.
*/
const getNextVisibleBookmark = (fromIndex, direction = 1) => {
// Iterate over bookmark items in the specified direction
for (let i = fromIndex + direction; i >= 0 && i < bookmarkItems.length; i += direction) {
// Return the first visible bookmark found
if (bookmarkItems[i].offsetParent !== null) {
return bookmarkItems[i];
}
}
return null;
};
// Listen for keydown events on the document
document.addEventListener('keydown', function(event) {
// If Escape key is pressed, simulate a click on the document to close the dropdown
if (event.key === "Escape") {
document.body.click();
return;
}
// Exit if the target is neither the search input nor a bookmark item
if (event.target !== searchInput && !event.target.classList.contains('bookmark-item')) return;
const isArrowDown = event.key === "ArrowDown";
const isArrowUp = event.key === "ArrowUp";
// Exit if neither arrow key is pressed
if (!isArrowDown && !isArrowUp) return;
// Prevent default arrow key actions
event.preventDefault();
// If on search input and arrow down is pressed, move to the first visible bookmark
if (event.target === searchInput && isArrowDown) {
const firstVisibleBookmark = getNextVisibleBookmark(-1);
firstVisibleBookmark && firstVisibleBookmark.focus();
} else {
const direction = isArrowDown ? 1 : -1;
const nextBookmark = getNextVisibleBookmark(bookmarkItems.indexOf(event.target), direction);
// Focus the next visible bookmark, or return to search input if at the
// top and arrow up is pressed
if (nextBookmark) {
nextBookmark.focus();
} else if (isArrowUp) {
searchInput.focus();
}
}
});
})();