Skip to content

Commit 6ef156b

Browse files
committed
Move MenuBar index check to an overridable method
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 jupyterlab#729
1 parent e696f5d commit 6ef156b

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

Diff for: packages/widgets/src/menubar.ts

+12-7
Original file line numberDiff line numberDiff line change
@@ -140,13 +140,8 @@ export class MenuBar extends Widget {
140140
* If the menu cannot be activated, the index will be set to `-1`.
141141
*/
142142
set activeIndex(value: number) {
143-
// Adjust the value for an out of range index.
144-
if (value < 0 || value >= this._menus.length) {
145-
value = -1;
146-
}
147-
148-
// An empty menu cannot be active
149-
if (value > -1 && this._menus[value].items.length === 0) {
143+
// Adjust the value for an invalid index.
144+
if (!this.isValidIndex(value)) {
150145
value = -1;
151146
}
152147

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

160+
/**
161+
* Before setting a new index, this method is used to validate it.
162+
*
163+
* By default it checks whether the index is within menu range
164+
* and whether the corresponding menu has at least one item.
165+
*/
166+
protected isValidIndex(index: number): boolean {
167+
return index >= 0 && index < this._menus.length && this._menus[index].items.length > 0;
168+
}
169+
165170
/**
166171
* A read-only array of the menus in the menu bar.
167172
*/

Diff for: packages/widgets/tests/src/menubar.spec.ts

+23
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,29 @@ describe('@lumino/widgets', () => {
294294
expect(bar.activeIndex).to.equal(-1);
295295
bar.dispose();
296296
});
297+
298+
it('should allow adopting the validation check', () => {
299+
class AllowEmptyMenusBar extends MenuBar {
300+
protected override isValidIndex(index: number): boolean {
301+
return index >= 0 && index < this.menus.length;
302+
}
303+
}
304+
const bar = new AllowEmptyMenusBar();
305+
let emptyMenu = new Menu({ commands });
306+
bar.insertMenu(1, emptyMenu);
307+
308+
// check that empty menu can be active
309+
bar.activeIndex = 1;
310+
expect(bar.activeIndex).to.equal(1);
311+
312+
// other indices should still be disallowed
313+
bar.activeIndex = -1;
314+
expect(bar.activeIndex).to.equal(-1);
315+
bar.activeIndex = 2;
316+
expect(bar.activeIndex).to.equal(-1);
317+
318+
bar.dispose();
319+
});
297320
});
298321

299322
describe('#menus', () => {

0 commit comments

Comments
 (0)