DropdownMenu
OrganismAccessible dropdown using role="menu" + role="menuitem". Closes on Escape and outside click. Supports left/right alignment, icons, separators, danger and disabled items, and arrow-key navigation. Items take an optional id, href, group, order, hidden and disabledReason so other modules can contribute entries; portal escapes clipping parents.
<%- include('modules/ui/DropdownMenu', {
id: 'actions-menu',
trigger: '<button>Actions</button>',
items: [
{ label: 'View', icon: '<i class="fa-solid fa-eye"></i>' },
{ label: 'Edit', icon: '<i class="fa-solid fa-pen"></i>' },
{ label: 'Duplicate', icon: '<i class="fa-solid fa-copy"></i>' }
]
}) %>
<%- include('modules/ui/DropdownMenu', {
id: 'row-menu',
align: 'right',
trigger: '<button aria-label="More options"><i class="fa-solid fa-ellipsis-vertical"></i></button>',
items: [
{ label: 'Open', icon: '...' },
{ label: 'Rename', icon: '...' },
{ label: 'Archive', icon: '...', disabled: true },
{ type: 'separator' },
{ label: 'Delete', icon: '...', danger: true }
]
}) %>
Jane Doe
jane@example.com
<%- include('modules/ui/DropdownMenu', {
id: 'account-menu',
trigger: '<button>Account</button>',
header: '<div class="px-3 py-2">...</div>',
items: [
{ label: 'Profile', icon: '...' },
{ label: 'Settings', icon: '...' },
{ type: 'separator' },
{ label: 'Sign out', icon: '...', danger: true }
]
}) %>
<%# Items sort by group (ranked by their lowest order) and order; a separator splits groups. %>
<%- include('modules/ui/DropdownMenu', {
trigger: '<button type="button" class="…">Contact</button>',
items: [
{ id: 'edit', label: 'Edit', group: 'record', order: 10 },
{ id: 'call', label: 'Call', group: 'contact', order: 20, href: '/calls/new' },
{ id: 'sign', label: 'Send for signature', group: 'contact', order: 30, disabled: true, disabledReason: 'Add an email address first' },
{ id: 'campaign', label: 'Add to campaign', group: 'contact', order: 40, hidden: !canMarket },
{ id: 'delete', label: 'Delete', group: 'danger', order: 1000, danger: true },
]
}) %>
<%
var _id = locals.id || 'dropdown-' + Math.random().toString(36).substr(2, 9);
var _align = locals.align || 'left';
var _trigger = locals.trigger || '';
var _header = locals.header || '';
var _className = locals.className || '';
// portal: the open menu moves to document.body with fixed positioning, so a clipping
// parent (a table's overflow wrapper) cannot cut it off.
var _portal = !!locals.portal;
var alignClass = _align === 'right' ? 'right-0' : 'left-0';
// Items take optional id, href, order, group, hidden and disabledReason (parity with
// kui-react arrangeMenuItems). Hidden items are left out; when any item sets group or
// order, items are laid out by group (ranked by their lowest order, like CSS order:
// missing is 0, ties keep array order) with a separator between groups.
var _items = (function (items) {
var isEntry = function (it) { return it.type !== 'separator'; };
var ord = function (it) { return (typeof it.order === 'number' && isFinite(it.order)) ? it.order : 0; };
var visible = items.filter(function (it) { return !it.hidden; });
var grouped = visible.some(function (it) { return isEntry(it) && (it.group !== undefined || it.order !== undefined); });
if (!grouped) {
if (visible.length === items.length) return visible;
var tidy = [];
visible.forEach(function (it) {
if (!isEntry(it) && (tidy.length === 0 || !isEntry(tidy[tidy.length - 1]))) return;
tidy.push(it);
});
while (tidy.length && !isEntry(tidy[tidy.length - 1])) tidy.pop();
return tidy;
}
var buckets = [];
visible.filter(isEntry).forEach(function (it, i) {
var b = buckets.filter(function (x) { return x.key === it.group; })[0];
if (!b) { b = { key: it.group, first: i, rank: ord(it), items: [] }; buckets.push(b); }
b.rank = Math.min(b.rank, ord(it));
b.items.push({ it: it, i: i });
});
buckets.sort(function (a, b) { return a.rank - b.rank || a.first - b.first; });
var out = [];
buckets.forEach(function (b, bi) {
if (bi > 0) out.push({ type: 'separator' });
b.items.sort(function (x, y) { return ord(x.it) - ord(y.it) || x.i - y.i; });
b.items.forEach(function (x) { out.push(x.it); });
});
return out;
})(locals.items || []);
%>
<%- include('./Overlays/shared/focus-trap.js') %>
<div
id="<%= _id %>"
class="relative inline-block<%= _className ? ' ' + _className : '' %>"
>
<div data-dropdown-trigger-wrap>
<%- _trigger %>
</div>
<div
id="<%= _id %>-menu"
role="menu"
aria-labelledby="<%= _id %>-trigger"
hidden
<% if (_portal) { %>data-dropdown-portal="<%= _align %>"<% } %>
class="absolute z-[60] mt-1 min-w-[10rem] rounded-lg border border-border bg-surface-raised shadow-lg py-1 <%= alignClass %>"
>
<% if (_header) { %>
<div class="border-b border-border mb-1">
<%- _header %>
</div>
<% } %>
<% _items.forEach(function (item, i) { %>
<% if (item.type === 'separator') { %>
<div role="separator" class="my-1 border-t border-border"></div>
<% } else {
var isDanger = !!item.danger;
var isDisabled = !!item.disabled;
var stateClass = isDanger
? 'text-error hover:bg-error-subtle'
: 'text-text-primary hover:bg-surface-overlay';
var disClass = isDisabled ? ' opacity-50 cursor-not-allowed' : '';
var reasonId = isDisabled && item.disabledReason ? _id + '-reason-' + i : '';
var itemCls = 'flex w-full items-center gap-2 px-3 py-2 text-sm text-left transition-colors focus-visible:outline-none focus-visible:bg-surface-overlay ' + stateClass + disClass;
%>
<% if (item.href && !isDisabled) { %>
<a
role="menuitem"
href="<%= item.href %>"
<% if (item.id) { %>data-item-id="<%= item.id %>"<% } %>
<% if (item.onClick) { %>onclick="<%= item.onClick %>; closeDropdownMenu(<%= JSON.stringify(String(_id)) %>)"<% } else { %>onclick="closeDropdownMenu(<%= JSON.stringify(String(_id)) %>)"<% } %>
class="<%= itemCls %>"
>
<% if (item.icon) { %><span aria-hidden="true"><%- item.icon %></span><% } %>
<%= item.label %>
</a>
<% } else { %>
<button
role="menuitem"
type="button"
<% if (isDisabled) { %>disabled<% } %>
<% if (item.id) { %>data-item-id="<%= item.id %>"<% } %>
<% if (reasonId) { %>title="<%= item.disabledReason %>" aria-label="<%= item.label %>" aria-describedby="<%= reasonId %>"<% } %>
<% if (item.onClick) { %>onclick="<%= item.onClick %>; closeDropdownMenu(<%= JSON.stringify(String(_id)) %>)"<% } else { %>onclick="closeDropdownMenu(<%= JSON.stringify(String(_id)) %>)"<% } %>
class="<%= itemCls %>"
>
<% if (item.icon) { %><span aria-hidden="true"><%- item.icon %></span><% } %>
<% if (reasonId) { %>
<span class="flex min-w-0 flex-col">
<span><%= item.label %></span>
<span id="<%= reasonId %>" class="text-xs text-text-secondary"><%= item.disabledReason %></span>
</span>
<% } else { %>
<%= item.label %>
<% } %>
</button>
<% } %>
<% } %>
<% }); %>
</div>
</div>
<script>
(function () {
function getEls(id) {
return {
root: document.getElementById(id),
trigger: document.getElementById(id + '-trigger'),
menu: document.getElementById(id + '-menu'),
};
}
// A portalled menu lives in document.body, fixed under its trigger while open.
function placePortal(id) {
var e = getEls(id);
if (!e.root || !e.menu) return;
var align = e.menu.getAttribute('data-dropdown-portal');
if (!align) return;
if (e.menu.parentNode !== document.body) document.body.appendChild(e.menu);
var r = e.root.getBoundingClientRect();
e.menu.classList.remove('absolute', 'mt-1', 'left-0', 'right-0');
e.menu.classList.add('fixed');
e.menu.style.top = (r.bottom + 4) + 'px';
if (align === 'right') { e.menu.style.right = (document.documentElement.clientWidth - r.right) + 'px'; e.menu.style.left = ''; }
else { e.menu.style.left = r.left + 'px'; e.menu.style.right = ''; }
}
window.__placeDropdownPortal = window.__placeDropdownPortal || placePortal;
function openDropdownMenu(id) {
var e = getEls(id);
if (!e.root || !e.menu || !e.trigger) return;
window.__placeDropdownPortal(id);
e.menu.hidden = false;
e.trigger.setAttribute('aria-expanded', 'true');
if (window.__overlayFocusTrap) window.__overlayFocusTrap.activate(id, e.menu);
}
function closeDropdownMenu(id) {
var e = getEls(id);
if (!e.root || !e.menu || !e.trigger) return;
e.menu.hidden = true;
e.trigger.setAttribute('aria-expanded', 'false');
if (window.__overlayFocusTrap) window.__overlayFocusTrap.deactivate(id);
}
function toggleDropdownMenu(id) {
var e = getEls(id);
if (!e.menu) return;
if (e.menu.hidden) openDropdownMenu(id); else closeDropdownMenu(id);
}
window.openDropdownMenu = window.openDropdownMenu || openDropdownMenu;
window.closeDropdownMenu = window.closeDropdownMenu || closeDropdownMenu;
window.toggleDropdownMenu = window.toggleDropdownMenu || toggleDropdownMenu;
var dropdownId = <%- include('./_script-json', { value: String(_id) }) %>;
var root = document.getElementById(dropdownId);
if (!root) return;
// The trigger prop is caller-supplied HTML (usually a real <button>) —
// wire the widget's ARIA/id onto that real element instead of the
// wrapper div, so aria-haspopup/aria-expanded land on something with
// a role that actually allows them.
var triggerWrap = root.querySelector('[data-dropdown-trigger-wrap]');
var triggerEl = triggerWrap && triggerWrap.firstElementChild;
if (triggerEl) {
triggerEl.id = dropdownId + '-trigger';
triggerEl.setAttribute('aria-haspopup', 'menu');
triggerEl.setAttribute('aria-expanded', 'false');
triggerEl.setAttribute('aria-controls', dropdownId + '-menu');
triggerEl.addEventListener('click', function () { toggleDropdownMenu(dropdownId); });
}
document.addEventListener('mousedown', function (ev) {
var menu = document.getElementById(dropdownId + '-menu');
if (!menu || menu.hidden) return;
if (!root.contains(ev.target) && !menu.contains(ev.target)) closeDropdownMenu(dropdownId);
});
var portalMenu = document.getElementById(dropdownId + '-menu');
if (portalMenu && portalMenu.hasAttribute('data-dropdown-portal')) {
var replace = function () { if (!portalMenu.hidden) window.__placeDropdownPortal(dropdownId); };
window.addEventListener('resize', replace);
window.addEventListener('scroll', replace, true);
}
document.addEventListener('keydown', function (ev) {
var menu = document.getElementById(dropdownId + '-menu');
if (!menu || menu.hidden) return;
var ft = window.__overlayFocusTrap;
if (ft && !ft.isTop(dropdownId)) return;
if (ev.key === 'Escape') { closeDropdownMenu(dropdownId); return; }
if (ft) ft.handleKey(dropdownId, menu, ev);
if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {
var items = Array.prototype.slice.call(menu.querySelectorAll('[role="menuitem"]:not([disabled])'));
if (!items.length) return;
ev.preventDefault();
var idx = items.indexOf(document.activeElement);
var next = ev.key === 'ArrowDown'
? (idx + 1) % items.length
: (idx <= 0 ? items.length - 1 : idx - 1);
items[next].focus();
}
});
})();
</script>