Skip to content

Commit

Permalink
Move MenuBar index check to an overridable method
Browse files Browse the repository at this point in the history
Added a protected isValidIndex method to the MenuBar class to handle
index validation before setting an index.

This enables adopters to customize the validation logic, e.g., for
supporting dynamic menus that may initially be empty.

Resolves #729
  • Loading branch information
sdirix committed Dec 20, 2024
1 parent e696f5d commit 6ef156b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
19 changes: 12 additions & 7 deletions packages/widgets/src/menubar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,13 +140,8 @@ export class MenuBar extends Widget {
* If the menu cannot be activated, the index will be set to `-1`.
*/
set activeIndex(value: number) {
// Adjust the value for an out of range index.
if (value < 0 || value >= this._menus.length) {
value = -1;
}

// An empty menu cannot be active
if (value > -1 && this._menus[value].items.length === 0) {
// Adjust the value for an invalid index.
if (!this.isValidIndex(value)) {
value = -1;
}

Expand All @@ -162,6 +157,16 @@ export class MenuBar extends Widget {
this.update();
}

/**
* Before setting a new index, this method is used to validate it.
*
* By default it checks whether the index is within menu range
* and whether the corresponding menu has at least one item.
*/
protected isValidIndex(index: number): boolean {
return index >= 0 && index < this._menus.length && this._menus[index].items.length > 0;
}

/**
* A read-only array of the menus in the menu bar.
*/
Expand Down
23 changes: 23 additions & 0 deletions packages/widgets/tests/src/menubar.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,29 @@ describe('@lumino/widgets', () => {
expect(bar.activeIndex).to.equal(-1);
bar.dispose();
});

it('should allow adopting the validation check', () => {
class AllowEmptyMenusBar extends MenuBar {
protected override isValidIndex(index: number): boolean {
return index >= 0 && index < this.menus.length;
}
}
const bar = new AllowEmptyMenusBar();
let emptyMenu = new Menu({ commands });
bar.insertMenu(1, emptyMenu);

// check that empty menu can be active
bar.activeIndex = 1;
expect(bar.activeIndex).to.equal(1);

// other indices should still be disallowed
bar.activeIndex = -1;
expect(bar.activeIndex).to.equal(-1);
bar.activeIndex = 2;
expect(bar.activeIndex).to.equal(-1);

bar.dispose();
});
});

describe('#menus', () => {
Expand Down

0 comments on commit 6ef156b

Please sign in to comment.