Skip to content

refactor: use Lit for rendering menu-bar buttons #8871

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 101 additions & 74 deletions packages/menu-bar/src/vaadin-menu-bar-mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
* Copyright (c) 2019 - 2025 Vaadin Ltd.
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
*/
import { html, noChange, nothing, render } from 'lit';
import { Directive, directive } from 'lit/directive.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { DisabledMixin } from '@vaadin/a11y-base/src/disabled-mixin.js';
import { FocusMixin } from '@vaadin/a11y-base/src/focus-mixin.js';
import { isElementFocused, isKeyboardActive } from '@vaadin/a11y-base/src/focus-utils.js';
Expand All @@ -12,6 +15,41 @@ import { I18nMixin } from '@vaadin/component-base/src/i18n-mixin.js';
import { ResizeMixin } from '@vaadin/component-base/src/resize-mixin.js';
import { SlotController } from '@vaadin/component-base/src/slot-controller.js';

/**
* Custom Lit directive for rendering item components
* inspired by the `flowComponentDirective` logic.
*/
class ItemComponentDirective extends Directive {
update(part, [{ component, text }]) {
const { parentNode, startNode } = part;

const newNode = component || (text ? document.createTextNode(text) : null);
const oldNode = this.getOldNode(part);

if (oldNode === newNode) {
return noChange;
} else if (oldNode && newNode) {
parentNode.replaceChild(newNode, oldNode);
} else if (oldNode) {
parentNode.removeChild(oldNode);
} else if (newNode) {
startNode.after(newNode);
}

return noChange;
}

getOldNode(part) {
const { startNode, endNode } = part;
if (startNode.nextSibling === endNode) {
return null;
}
return startNode.nextSibling;
}
}

const componentDirective = directive(ItemComponentDirective);

const DEFAULT_I18N = {
moreOptions: 'More options',
};
Expand Down Expand Up @@ -284,8 +322,11 @@ export const MenuBarMixin = (superClass) =>
dots.innerHTML = '·'.repeat(3);
btn.appendChild(dots);

btn.setAttribute('aria-haspopup', 'true');
btn.setAttribute('aria-expanded', 'false');
btn.setAttribute('role', this.tabNavigation ? 'button' : 'menuitem');

this._overflow = btn;
this._initButtonAttrs(btn);
},
});
this.addController(this._overflowController);
Expand Down Expand Up @@ -366,14 +407,16 @@ export const MenuBarMixin = (superClass) =>
*/
_themeChanged(theme, overflow, container) {
if (overflow && container) {
this._buttons.forEach((btn) => this._setButtonTheme(btn, theme));
this.__renderButtons(this.items);
this.__detectOverflow();
}

if (theme) {
this._subMenu.setAttribute('theme', theme);
} else {
this._subMenu.removeAttribute('theme');
if (theme) {
overflow.setAttribute('theme', theme);
this._subMenu.setAttribute('theme', theme);
} else {
overflow.removeAttribute('theme');
this._subMenu.removeAttribute('theme');
}
}
}

Expand Down Expand Up @@ -421,11 +464,18 @@ export const MenuBarMixin = (superClass) =>
if (items !== this._oldItems) {
this._oldItems = items;
this.__renderButtons(items);
this.__detectOverflow();
}

const subMenu = this._subMenu;
if (subMenu && subMenu.opened) {
subMenu.close();
const button = subMenu._overlayElement.positionTarget;

// Close sub-menu if the corresponding button is no longer in the DOM,
// or if the item on it has been changed to no longer have children.
if (!button.isConnected || !Array.isArray(button.item.children) || button.item.children.length === 0) {
subMenu.close();
}
}
}

Expand Down Expand Up @@ -561,66 +611,17 @@ export const MenuBarMixin = (superClass) =>
});
}

/** @protected */
_removeButtons() {
this._buttons.forEach((button) => {
if (button !== this._overflow) {
this.removeChild(button);
}
});
}

/** @protected */
_initButton(item) {
const button = document.createElement('vaadin-menu-bar-button');

const itemCopy = { ...item };
button.item = itemCopy;

if (item.component) {
const component = this.__getComponent(itemCopy);
itemCopy.component = component;
// Save item for overflow menu
component.item = itemCopy;
button.appendChild(component);
} else if (item.text) {
button.textContent = item.text;
}

if (item.className) {
button.className = item.className;
}

button.disabled = item.disabled;

return button;
}

/** @protected */
_initButtonAttrs(button) {
button.setAttribute('role', this.tabNavigation ? 'button' : 'menuitem');

if (button === this._overflow || (button.item && button.item.children)) {
button.setAttribute('aria-haspopup', 'true');
button.setAttribute('aria-expanded', 'false');
}
}

/** @protected */
_setButtonTheme(btn, hostTheme) {
/** @private */
__getButtonTheme(item, hostTheme) {
let theme = hostTheme;

// Item theme takes precedence over host theme even if it's empty, as long as it's not undefined or null
const itemTheme = btn.item && btn.item.theme;
const itemTheme = item && item.theme;
if (itemTheme != null) {
theme = Array.isArray(itemTheme) ? itemTheme.join(' ') : itemTheme;
}

if (theme) {
btn.setAttribute('theme', theme);
} else {
btn.removeAttribute('theme');
}
return theme;
}

/** @private */
Expand All @@ -645,21 +646,47 @@ export const MenuBarMixin = (superClass) =>

/** @private */
__renderButtons(items = []) {
this._removeButtons();

/* Empty array, do nothing */
if (items.length === 0) {
return;
}
render(
html`
${items.map((item) => {
const itemCopy = { ...item };
const hasChildren = Boolean(item && item.children);

if (itemCopy.component) {
const component = this.__getComponent(itemCopy);
itemCopy.component = component;
component.item = itemCopy;
}

items.forEach((item) => {
const button = this._initButton(item);
this.insertBefore(button, this._overflow);
this._initButtonAttrs(button);
this._setButtonTheme(button, this._theme);
});
return html`
<vaadin-menu-bar-button
.item="${itemCopy}"
.disabled="${item.disabled}"
role="${this.tabNavigation ? 'button' : 'menuitem'}"
aria-haspopup="${ifDefined(hasChildren ? 'true' : nothing)}"
aria-expanded="${ifDefined(hasChildren ? 'false' : nothing)}"
class="${ifDefined(item.className || nothing)}"
theme="${ifDefined(this.__getButtonTheme(item, this._theme) || nothing)}"
@click="${this.__onRootButtonClick}"
>${componentDirective(itemCopy)}</vaadin-menu-bar-button
>
`;
})}
`,
this,
{ renderBefore: this._overflow },
);
}

this.__detectOverflow();
/** @private */
__onRootButtonClick(event) {
const button = event.target;
// Propagate click event from button to the item component if it was outside
// it e.g. by calling `click()` on the button (used by the Flow counterpart).
if (button.item && button.item.component && !event.composedPath().includes(button.item.component)) {
event.stopPropagation();
button.item.component.click();
}
}

/**
Expand Down
Loading