Skip to content

Commit

Permalink
feat(database): add global menu open listener (#9032)
Browse files Browse the repository at this point in the history
  • Loading branch information
zzj3720 authored Dec 19, 2024
1 parent 08a9d51 commit 2213c04
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 6 deletions.
14 changes: 8 additions & 6 deletions packages/affine/components/src/context-menu/menu-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -502,11 +502,12 @@ const popMobileMenu = (options: MenuOptions): MenuHandler => {
};
return {
close: () => {
closePopup();
menu.close();
},
menu,
reopen: () => {
options.onClose?.();
menu.close();
popMobileMenu(options);
},
};
};
Expand All @@ -526,15 +527,16 @@ export const popMenu = (
const onClose = () => {
props.options.onClose?.();
popupEnd();
closePopup();
};
const menu = new Menu({
...props.options,
onClose: () => {
closePopup();
},
onClose: onClose,
});
const closePopup = createPopup(target, menu.menuElement, {
onClose: onClose,
onClose: () => {
menu.close();
},
middleware: props.middleware ?? [
autoPlacement({
allowedPlacements: [
Expand Down
35 changes: 35 additions & 0 deletions packages/affine/components/src/context-menu/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,30 @@ export type MenuOptions = {
items: MenuConfig[];
};

// Global menu open listener type
type MenuOpenListener = (menu: Menu) => (() => void) | void;

// Global menu open listeners
const menuOpenListeners = new Set<MenuOpenListener>();

// Add global menu open listener
export function onMenuOpen(listener: MenuOpenListener) {
menuOpenListeners.add(listener);
// Return cleanup function
return () => {
menuOpenListeners.delete(listener);
};
}

export class Menu {
private _cleanupFns: Array<() => void> = [];

private _currentFocused$ = signal<MenuFocusable>();

private _subMenu$ = signal<Menu>();

closed = false;

readonly currentFocused$ = computed(() => this._currentFocused$.value);

menuElement: MenuComponentInterface;
Expand All @@ -68,9 +87,25 @@ export class Menu {
? new MobileMenuComponent()
: new MenuComponent();
this.menuElement.menu = this;

// Call global menu open listeners
menuOpenListeners.forEach(listener => {
const cleanup = listener(this);
if (cleanup) {
this._cleanupFns.push(cleanup);
}
});
}

close() {
if (this.closed) {
return;
}
this.closed = true;
// Execute cleanup functions
this._cleanupFns.forEach(cleanup => cleanup());
this._cleanupFns = [];

this.menuElement.remove();
this.options.onClose?.();
}
Expand Down

0 comments on commit 2213c04

Please sign in to comment.