From a2c0ea56fda7878c599e58d527666d7017cbcccb Mon Sep 17 00:00:00 2001 From: Edgar To Date: Sun, 16 Sep 2018 23:30:36 +0200 Subject: [PATCH] fix: only run action handler.hide when its an action --- action-code.js | 17 +++++++++++++++++ action-code.test.js | 18 ++++++++++++++++++ inline-menu.js | 18 ++++++++++++++++-- 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/action-code.js b/action-code.js index 18eb432..e16c237 100644 --- a/action-code.js +++ b/action-code.js @@ -25,6 +25,23 @@ class ActionCode { return this.code } + getRegex() { + if (this.code instanceof RegExp) { + const {source, flags} = this.code + const newSource = `^${source}$` + return new RegExp(newSource, flags) + } + return new RegExp(`^${this.code}$`) + } + + exec(value = '') { + return this.getRegex().exec(value) + } + + test(value = '') { + return this.getRegex().test(value) + } + concat(action) { return ActionCode.concat(this.code, action) } diff --git a/action-code.test.js b/action-code.test.js index 8e78468..1a9ed14 100644 --- a/action-code.test.js +++ b/action-code.test.js @@ -72,3 +72,21 @@ test('regex fail anchors', t => { t.throws(() => new ActionCode(/^42/), /anchor/) t.throws(() => new ActionCode(/42$/), /anchor/) }) + +test('getRegex from regex', t => { + t.deepEqual(new ActionCode(/b/).getRegex(), /^b$/) +}) + +test('getRegex from non regex', t => { + t.deepEqual(new ActionCode('b').getRegex(), /^b$/) +}) + +test('exec', t => { + t.deepEqual(new ActionCode('b').exec('c'), null) + t.truthy(new ActionCode('b').exec('b')) +}) + +test('test', t => { + t.false(new ActionCode('b').test('c')) + t.true(new ActionCode('b').test('b')) +}) diff --git a/inline-menu.js b/inline-menu.js index 722ac59..a7910ff 100644 --- a/inline-menu.js +++ b/inline-menu.js @@ -127,13 +127,27 @@ class TelegrafInlineMenu { if (handler.submenu) { middleware = handler.submenu.middleware(childActionCode.get(), subOptions) } else { + middlewareOptions.only = async ctx => { + if (ctx.updateType !== 'callback_query') { + return false + } + ctx.match = childActionCode.exec(ctx.callbackQuery.data) + if (!ctx.match) { + return false + } + if (handler.only && !(await handler.only(ctx))) { + return false + } + return true + } + options.log('add action reaction', childActionCode.get(), handler.middleware) - middleware = Composer.action(childActionCode.get(), async (ctx, next) => { + middleware = async (ctx, next) => { await handler.middleware(ctx, next) if (handler.setMenuAfter) { await setMenuFunc(ctx, 'after handler action' + childActionCode.get()) } - }) + } } } else { middleware = handler.middleware