grammy-inline-menu icon indicating copy to clipboard operation
grammy-inline-menu copied to clipboard

Lifecycle hook(s) for menus

Open phils-hub opened this issue 5 years ago • 1 comments

It would be interesting to have a sort of menu lifecycle hook that is triggered before this menu and any of its components (such as menu.select) are rendered. A subset of hooks such as the lifecycle hooks of Vue could be provided.

An example - assuming we had a beforeRendered hook the following would then be possible:

const menuOfTeams = new MenuTemplate(ctx => `You have ${ctx.state.teams.length} teams. Here they are:`)

menuOfTeams.chooseIntoSubmenu('details', ctx => ctx.state.teams.map(team => team.name), teamDetailsMenu)

menuOfTeams.beforeRendered(ctx => ctx.state.teams = restApi.getTeams())

The hook could easily be used to execute API calls to populate shared state, after which menu components can then access that state during rendering.

This would be more intuitive and simpler to use than configuring separate middleware. The non-lifecycle hook approach (as of today) would require something like:

bot.action(/^\/my\/relevant\/path\//, (ctx, next) => {
  ctx.state.something = 'hello world!'
  return next()
})

const menuTemplate = new MenuTemplate(ctx => ctx.state.something)

phils-hub avatar Jun 11 '20 12:06 phils-hub

Hooks do not seem as easy as I have hoped for. I think for now this is a bit annoying to implement. Personally I can work without them so I think they are not a high priority currently.

When the menu is generated the first thing done is always the body so you can preload stuff at the body. For functions like do or set this is not the case as they are independent of the resulting visible menu. As interactions for example might change things the menu has to load the same stuff again to have everything up to date what changed with the interaction. That might be the same with preloading via a hook.

I would like 2 different hooks: one for going into the path and one only for the exact menu. Implementing this would requiring a different internal approach for MenuMiddleware. The good thing here is that this will probably not be a breaking change as it only changes within the MenuMiddleware. Because of this I think I will not continue to think about this until v5 stable is released.

EdJoPaTo avatar Jun 24 '20 16:06 EdJoPaTo