fix: some build & linter warnings

This commit is contained in:
ZavaruKitsu
2022-10-08 19:15:51 +03:00
parent 3f0d109fe2
commit a731e2a8d0
159 changed files with 2738 additions and 3742 deletions
+140 -171
View File
@@ -1,50 +1,43 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Datasources;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid
{
public class ButtonGrid : Base.ControlBase
public class ButtonGrid : ControlBase
{
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"];
public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; } = "";
public string ConfirmationText { get; set; } = "";
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object();
private static readonly object EvButtonClicked = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
/// <summary>
///
///
/// </summary>
[Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm
{
get
{
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
get => DataSource.ButtonForm;
set => DataSource = new ButtonFormDataSource(value);
}
/// <summary>
@@ -88,23 +81,23 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public bool EnableSearch { get; set; } = false;
public String SearchQuery { get; set; }
public string SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always;
public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary>
/// Index of the current page
/// </summary>
public int CurrentPageIndex { get; set; } = 0;
public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"];
public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"];
public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"];
public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"];
public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
/// <summary>
/// Layout of the buttons which should be displayed always on top.
@@ -119,89 +112,80 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Defines which type of Button Keyboard should be rendered.
/// </summary>
public eKeyboardType KeyboardType
public EKeyboardType KeyboardType
{
get
{
return m_eKeyboardType;
}
get => _mEKeyboardType;
set
{
if (m_eKeyboardType != value)
if (_mEKeyboardType != value)
{
this.RenderNecessary = true;
_renderNecessary = true;
Cleanup().Wait();
m_eKeyboardType = value;
_mEKeyboardType = value;
}
}
}
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard;
private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public ButtonGrid()
{
this.DataSource = new ButtonFormDataSource();
DataSource = new ButtonFormDataSource();
}
public ButtonGrid(eKeyboardType type) : this()
public ButtonGrid(EKeyboardType type) : this()
{
m_eKeyboardType = type;
_mEKeyboardType = type;
}
public ButtonGrid(ButtonForm form)
{
this.DataSource = new ButtonFormDataSource(form);
DataSource = new ButtonFormDataSource(form);
}
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
add => _events.AddHandler(EvButtonClicked, value);
remove => _events.RemoveHandler(EvButtonClicked, value);
}
public async Task OnButtonClicked(ButtonClickedEventArgs e)
{
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public override void Init()
{
this.Device.MessageDeleted += Device_MessageDeleted;
Device.MessageDeleted += Device_MessageDeleted;
}
private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
{
if (this.MessageId == null)
if (MessageId == null)
return;
if (e.MessageId != this.MessageId)
if (e.MessageId != MessageId)
return;
this.MessageId = null;
MessageId = null;
}
public async override Task Load(MessageResult result)
public override async Task Load(MessageResult result)
{
if (this.KeyboardType != eKeyboardType.ReplyKeyboard)
if (KeyboardType != EKeyboardType.ReplyKeyboard)
return;
if (!result.IsFirstHandler)
@@ -212,7 +196,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>();
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{
@@ -244,7 +228,7 @@ namespace TelegramBotBase.Controls.Hybrid
check:
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (match != null)
@@ -258,39 +242,39 @@ namespace TelegramBotBase.Controls.Hybrid
if (result.MessageText == PreviousPageLabel)
{
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
}
else if (this.EnableSearch)
else if (EnableSearch)
{
if (result.MessageText.StartsWith("🔍"))
{
//Sent note about searching
if (this.SearchQuery == null)
if (SearchQuery == null)
{
await this.Device.Send(this.SearchLabel);
await Device.Send(SearchLabel);
}
this.SearchQuery = null;
this.Updated();
SearchQuery = null;
Updated();
return;
}
this.SearchQuery = result.MessageText;
SearchQuery = result.MessageText;
if (this.SearchQuery != null && this.SearchQuery != "")
if (SearchQuery != null && SearchQuery != "")
{
this.CurrentPageIndex = 0;
this.Updated();
CurrentPageIndex = 0;
Updated();
}
}
@@ -299,7 +283,7 @@ namespace TelegramBotBase.Controls.Hybrid
}
public async override Task Action(MessageResult result, string value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
@@ -308,13 +292,13 @@ namespace TelegramBotBase.Controls.Hybrid
return;
//Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard)
if (KeyboardType != EKeyboardType.InlineKeyBoard)
return;
await result.ConfirmAction(this.ConfirmationText ?? "");
await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{
@@ -358,18 +342,18 @@ namespace TelegramBotBase.Controls.Hybrid
{
case "$previous$":
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
break;
case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
break;
}
@@ -381,49 +365,49 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
private void CheckGrid()
{
switch (m_eKeyboardType)
switch (_mEKeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
}
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
}
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!_renderNecessary)
return;
//Check for rows and column limits
CheckGrid();
this.RenderNecessary = false;
_renderNecessary = false;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null));
var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null));
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
@@ -435,42 +419,42 @@ namespace TelegramBotBase.Controls.Hybrid
// form = form.Duplicate();
//}
if (this.EnablePaging)
if (EnablePaging)
{
IntegratePagingView(form);
}
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{
form.InsertButtonRow(0, this.HeadLayoutButtonRow);
form.InsertButtonRow(0, HeadLayoutButtonRow);
}
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow);
form.InsertButtonRow(2, SubHeadLayoutButtonRow);
}
else
{
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow);
form.InsertButtonRow(1, SubHeadLayoutButtonRow);
}
}
Message m = null;
switch (this.KeyboardType)
switch (KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (form.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
@@ -491,39 +475,39 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
break;
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
//Try to edit message if message id is available
//When the returned message is null then the message has been already deleted, resend it
if (this.MessageId != null)
if (MessageId != null)
{
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form);
m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
return;
}
}
//When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
break;
}
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
@@ -531,23 +515,23 @@ namespace TelegramBotBase.Controls.Hybrid
private void IntegratePagingView(ButtonForm dataForm)
{
//No Items
//No Items
if (dataForm.Rows == 0)
{
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
}
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
//🔍
ButtonRow row = new ButtonRow();
var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"));
row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
row.Add(new ButtonBase(NextPageLabel, "$next$"));
if (this.EnableSearch)
if (EnableSearch)
{
row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$"));
row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$"));
}
dataForm.InsertButtonRow(0, row);
@@ -560,12 +544,12 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
return true;
}
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
return true;
}
@@ -578,7 +562,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary))
if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{
return true;
}
@@ -594,30 +578,19 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
switch (this.KeyboardType)
return KeyboardType switch
{
case eKeyboardType.InlineKeyBoard:
return Constants.Telegram.MaxInlineKeyBoardRows;
case eKeyboardType.ReplyKeyboard:
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
};
}
}
/// <summary>
/// Returns the number of all rows (layout + navigation + content);
/// </summary>
public int TotalRows
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
public int TotalRows => LayoutRows + DataSource.RowCount;
/// <summary>
@@ -627,15 +600,15 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
int layoutRows = 0;
var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto)
if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++;
return layoutRows;
@@ -645,13 +618,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Returns the number of item rows per page.
/// </summary>
public int ItemRowsPerPage
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int ItemRowsPerPage => MaximumRow - LayoutRows;
/// <summary>
/// Return the number of pages.
@@ -665,7 +632,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null);
var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -675,22 +642,24 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0)
return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage));
return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
}
}
public override async Task Hidden(bool FormClose)
public override Task Hidden(bool formClose)
{
//Prepare for opening Modal, and comming back
if (!FormClose)
if (!formClose)
{
this.Updated();
Updated();
}
else
{
//Remove event handler
this.Device.MessageDeleted -= Device_MessageDeleted;
Device.MessageDeleted -= Device_MessageDeleted;
}
return Task.CompletedTask;
}
/// <summary>
@@ -698,31 +667,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void Updated()
{
this.RenderNecessary = true;
_renderNecessary = true;
}
public async override Task Cleanup()
public override async Task Cleanup()
{
if (this.MessageId == null)
if (MessageId == null)
return;
switch (this.KeyboardType)
switch (KeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
this.MessageId = null;
MessageId = null;
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup)
if (HideKeyboardOnCleanup)
{
await this.Device.HideReplyKeyboard();
await Device.HideReplyKeyboard();
}
this.MessageId = null;
MessageId = null;
break;
}
+15 -31
View File
@@ -1,10 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using TelegramBotBase.Form;
namespace TelegramBotBase.Controls.Hybrid
@@ -12,8 +9,7 @@ namespace TelegramBotBase.Controls.Hybrid
[DebuggerDisplay("{Count} columns")]
public class ButtonRow
{
List<ButtonBase> __buttons = new List<ButtonBase>();
private List<ButtonBase> _buttons = new List<ButtonBase>();
public ButtonRow()
{
@@ -23,59 +19,47 @@ namespace TelegramBotBase.Controls.Hybrid
public ButtonRow(params ButtonBase[] buttons)
{
__buttons = buttons.ToList();
_buttons = buttons.ToList();
}
public ButtonBase this[int index]
{
get
{
return __buttons[index];
}
}
public ButtonBase this[int index] => _buttons[index];
public int Count
{
get
{
return __buttons.Count;
}
}
public int Count => _buttons.Count;
public void Add(ButtonBase button)
{
__buttons.Add(button);
_buttons.Add(button);
}
public void AddRange(ButtonBase button)
{
__buttons.Add(button);
_buttons.Add(button);
}
public void Insert(int index, ButtonBase button)
{
__buttons.Insert(index, button);
_buttons.Insert(index, button);
}
public IEnumerator<ButtonBase> GetEnumerator()
{
return __buttons.GetEnumerator();
return _buttons.GetEnumerator();
}
public ButtonBase[] ToArray()
{
return __buttons.ToArray();
return _buttons.ToArray();
}
public List<ButtonBase> ToList()
{
return __buttons.ToList();
return _buttons.ToList();
}
public bool Matches(String text, bool useText = true)
public bool Matches(string text, bool useText = true)
{
foreach (var b in __buttons)
foreach (var b in _buttons)
{
if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase))
return true;
@@ -92,9 +76,9 @@ namespace TelegramBotBase.Controls.Hybrid
/// <param name="text"></param>
/// <param name="useText"></param>
/// <returns></returns>
public ButtonBase GetButtonMatch(String text, bool useText = true)
public ButtonBase GetButtonMatch(string text, bool useText = true)
{
foreach (var b in __buttons)
foreach (var b in _buttons)
{
if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase))
return b;
@@ -106,7 +90,7 @@ namespace TelegramBotBase.Controls.Hybrid
public static implicit operator ButtonRow(List<ButtonBase> list)
{
return new ButtonRow() { __buttons = list };
return new ButtonRow { _buttons = list };
}
}
}
@@ -1,49 +1,42 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Datasources;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid
{
public class CheckedButtonList : Base.ControlBase
public class CheckedButtonList : ControlBase
{
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"];
public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; } = "";
public string ConfirmationText { get; set; } = "";
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object();
private static readonly object EvButtonClicked = new object();
private static readonly object __evCheckedChanged = new object();
private static readonly object EvCheckedChanged = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
[Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm
{
get
{
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
get => DataSource.ButtonForm;
set => DataSource = new ButtonFormDataSource(value);
}
/// <summary>
@@ -51,7 +44,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public ButtonFormDataSource DataSource { get; set; }
List<int> CheckedRows { get; set; } = new List<int>();
private List<int> CheckedRows { get; set; } = new List<int>();
public int? MessageId { get; set; }
@@ -91,25 +84,25 @@ namespace TelegramBotBase.Controls.Hybrid
//public String SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always;
public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary>
/// Index of the current page
/// </summary>
public int CurrentPageIndex { get; set; } = 0;
public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"];
public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"];
public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"];
public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
//public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"];
public String CheckedIconLabel { get; set; } = "✅";
public string CheckedIconLabel { get; set; } = "✅";
public String UncheckedIconLabel { get; set; } = "◻️";
public string UncheckedIconLabel { get; set; } = "◻️";
/// <summary>
/// Layout of the buttons which should be displayed always on top.
@@ -124,97 +117,82 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Defines which type of Button Keyboard should be rendered.
/// </summary>
public eKeyboardType KeyboardType
public EKeyboardType KeyboardType
{
get
{
return m_eKeyboardType;
}
get => _mEKeyboardType;
set
{
if (m_eKeyboardType != value)
if (_mEKeyboardType != value)
{
this.RenderNecessary = true;
_renderNecessary = true;
Cleanup().Wait();
m_eKeyboardType = value;
_mEKeyboardType = value;
}
}
}
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard;
private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public CheckedButtonList()
{
this.DataSource = new ButtonFormDataSource();
DataSource = new ButtonFormDataSource();
}
public CheckedButtonList(eKeyboardType type) : this()
public CheckedButtonList(EKeyboardType type) : this()
{
m_eKeyboardType = type;
_mEKeyboardType = type;
}
public CheckedButtonList(ButtonForm form)
{
this.DataSource = new ButtonFormDataSource(form);
DataSource = new ButtonFormDataSource(form);
}
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
add => _events.AddHandler(EvButtonClicked, value);
remove => _events.RemoveHandler(EvButtonClicked, value);
}
public async Task OnButtonClicked(ButtonClickedEventArgs e)
{
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public event AsyncEventHandler<CheckedChangedEventArgs> CheckedChanged
{
add
{
this.Events.AddHandler(__evCheckedChanged, value);
}
remove
{
this.Events.RemoveHandler(__evCheckedChanged, value);
}
add => _events.AddHandler(EvCheckedChanged, value);
remove => _events.RemoveHandler(EvCheckedChanged, value);
}
public async Task OnCheckedChanged(CheckedChangedEventArgs e)
{
var handler = this.Events[__evCheckedChanged]?.GetInvocationList().Cast<AsyncEventHandler<CheckedChangedEventArgs>>();
var handler = _events[EvCheckedChanged]?.GetInvocationList().Cast<AsyncEventHandler<CheckedChangedEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<CheckedChangedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public async override Task Load(MessageResult result)
public override async Task Load(MessageResult result)
{
if (this.KeyboardType != eKeyboardType.ReplyKeyboard)
if (KeyboardType != EKeyboardType.ReplyKeyboard)
return;
if (!result.IsFirstHandler)
@@ -225,7 +203,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>();
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{
@@ -260,36 +238,36 @@ namespace TelegramBotBase.Controls.Hybrid
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (match == null)
{
if (result.MessageText == PreviousPageLabel)
{
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
}
else if (result.MessageText.EndsWith(CheckedIconLabel))
{
var s = result.MessageText.Split(' ', '.');
index = int.Parse(s[0]) - 1;
if (!this.CheckedRows.Contains(index))
if (!CheckedRows.Contains(index))
return;
this.CheckedRows.Remove(index);
CheckedRows.Remove(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false));
@@ -299,13 +277,13 @@ namespace TelegramBotBase.Controls.Hybrid
var s = result.MessageText.Split(' ', '.');
index = int.Parse(s[0]) - 1;
if (this.CheckedRows.Contains(index))
if (CheckedRows.Contains(index))
return;
this.CheckedRows.Add(index);
CheckedRows.Add(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true));
@@ -355,7 +333,7 @@ namespace TelegramBotBase.Controls.Hybrid
}
public async override Task Action(MessageResult result, string value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
@@ -364,13 +342,13 @@ namespace TelegramBotBase.Controls.Hybrid
return;
//Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard)
if (KeyboardType != EKeyboardType.InlineKeyBoard)
return;
await result.ConfirmAction(this.ConfirmationText ?? "");
await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{
@@ -422,18 +400,18 @@ namespace TelegramBotBase.Controls.Hybrid
{
case "$previous$":
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
break;
case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
break;
@@ -448,11 +426,11 @@ namespace TelegramBotBase.Controls.Hybrid
index = int.Parse(s[1]);
if (!this.CheckedRows.Contains(index))
if (!CheckedRows.Contains(index))
{
this.CheckedRows.Add(index);
CheckedRows.Add(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true));
}
@@ -463,11 +441,11 @@ namespace TelegramBotBase.Controls.Hybrid
index = int.Parse(s[1]);
if (this.CheckedRows.Contains(index))
if (CheckedRows.Contains(index))
{
this.CheckedRows.Remove(index);
CheckedRows.Remove(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false));
}
@@ -487,51 +465,51 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
private void CheckGrid()
{
switch (m_eKeyboardType)
switch (_mEKeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
}
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
}
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!_renderNecessary)
return;
//Check for rows and column limits
CheckGrid();
this.RenderNecessary = false;
_renderNecessary = false;
Message m = null;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, null);
var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -542,7 +520,7 @@ namespace TelegramBotBase.Controls.Hybrid
//form = form.Duplicate();
//}
if (this.EnablePaging)
if (EnablePaging)
{
IntegratePagingView(form);
}
@@ -551,34 +529,34 @@ namespace TelegramBotBase.Controls.Hybrid
form = PrepareCheckableLayout(form);
}
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{
form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray());
form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray());
}
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray());
form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray());
}
else
{
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray());
form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray());
}
}
switch (this.KeyboardType)
switch (KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (form.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
@@ -589,25 +567,25 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
break;
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (this.MessageId != null)
if (MessageId != null)
{
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form);
m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
}
else
{
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
}
break;
@@ -615,7 +593,7 @@ namespace TelegramBotBase.Controls.Hybrid
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
@@ -623,23 +601,23 @@ namespace TelegramBotBase.Controls.Hybrid
private void IntegratePagingView(ButtonForm dataForm)
{
//No Items
//No Items
if (dataForm.Rows == 0)
{
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
}
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
bf = PrepareCheckableLayout(dataForm);
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
//🔍
ButtonRow row = new ButtonRow();
var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"));
row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
row.Add(new ButtonBase(NextPageLabel, "$next$"));
@@ -652,30 +630,30 @@ namespace TelegramBotBase.Controls.Hybrid
private ButtonForm PrepareCheckableLayout(ButtonForm dataForm)
{
var bf = new ButtonForm();
for (int i = 0; i < dataForm.Rows; i++)
for (var i = 0; i < dataForm.Rows; i++)
{
int it = (this.CurrentPageIndex * (this.MaximumRow - LayoutRows)) + i;
var it = (CurrentPageIndex * (MaximumRow - LayoutRows)) + i;
//if (it > dataForm.Rows - 1)
// break;
var r = dataForm[i];
String s = CheckedRows.Contains(it) ? this.CheckedIconLabel : this.UncheckedIconLabel;
var s = CheckedRows.Contains(it) ? CheckedIconLabel : UncheckedIconLabel;
//On reply keyboards we need a unique text.
if (this.KeyboardType == eKeyboardType.ReplyKeyboard)
if (KeyboardType == EKeyboardType.ReplyKeyboard)
{
s = $"{it + 1}. " + s;
}
if (CheckedRows.Contains(it))
{
r.Insert(0, new ButtonBase(s, "uncheck$" + it.ToString()));
r.Insert(0, new ButtonBase(s, "uncheck$" + it));
}
else
{
r.Insert(0, new ButtonBase(s, "check$" + it.ToString()));
r.Insert(0, new ButtonBase(s, "check$" + it));
}
bf.AddButtonRow(r);
@@ -688,12 +666,12 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
return true;
}
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
return true;
}
@@ -706,7 +684,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary))
if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{
return true;
}
@@ -722,30 +700,19 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
switch (this.KeyboardType)
return KeyboardType switch
{
case eKeyboardType.InlineKeyBoard:
return Constants.Telegram.MaxInlineKeyBoardRows;
case eKeyboardType.ReplyKeyboard:
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
};
}
}
/// <summary>
/// Returns the number of all rows (layout + navigation + content);
/// </summary>
public int TotalRows
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
public int TotalRows => LayoutRows + DataSource.RowCount;
/// <summary>
@@ -755,15 +722,15 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
int layoutRows = 0;
var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto)
if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++;
return layoutRows;
@@ -773,13 +740,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Returns the number of item rows per page.
/// </summary>
public int ItemRowsPerPage
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int ItemRowsPerPage => MaximumRow - LayoutRows;
public int PageCount
{
@@ -790,7 +751,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.RowCount;
var max = DataSource.RowCount;
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -800,28 +761,30 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0)
return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage));
return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
}
}
public override async Task Hidden(bool FormClose)
public override Task Hidden(bool formClose)
{
//Prepare for opening Modal, and comming back
if (!FormClose)
if (!formClose)
{
this.Updated();
Updated();
}
return Task.CompletedTask;
}
public List<ButtonBase> CheckedItems
{
get
{
List<ButtonBase> lst = new List<ButtonBase>();
var lst = new List<ButtonBase>();
foreach (var c in CheckedRows)
{
lst.Add(this.ButtonsForm[c][0]);
lst.Add(ButtonsForm[c][0]);
}
return lst;
@@ -834,31 +797,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void Updated()
{
this.RenderNecessary = true;
_renderNecessary = true;
}
public async override Task Cleanup()
public override async Task Cleanup()
{
if (this.MessageId == null)
if (MessageId == null)
return;
switch (this.KeyboardType)
switch (KeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
this.MessageId = null;
MessageId = null;
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup)
if (HideKeyboardOnCleanup)
{
await this.Device.HideReplyKeyboard();
await Device.HideReplyKeyboard();
}
this.MessageId = null;
MessageId = null;
break;
}
+25 -31
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
@@ -13,33 +9,30 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// This Control is for having a basic form content switching control.
/// </summary>
public abstract class MultiView : Base.ControlBase
public abstract class MultiView : ControlBase
{
/// <summary>
/// Index of the current View.
/// </summary>
public int SelectedViewIndex
{
get
{
return m_iSelectedViewIndex;
}
get => _mISelectedViewIndex;
set
{
m_iSelectedViewIndex = value;
_mISelectedViewIndex = value;
//Already rendered? Re-Render
if (_Rendered)
if (_rendered)
ForceRender().Wait();
}
}
private int m_iSelectedViewIndex = 0;
private int _mISelectedViewIndex;
/// <summary>
/// Hold if the View has been rendered already.
/// </summary>
private bool _Rendered = false;
private bool _rendered;
private List<int> Messages { get; set; }
@@ -50,12 +43,13 @@ namespace TelegramBotBase.Controls.Hybrid
}
private async Task Device_MessageSent(object sender, MessageSentEventArgs e)
private Task Device_MessageSent(object sender, MessageSentEventArgs e)
{
if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView)))
return;
return Task.CompletedTask;
this.Messages.Add(e.MessageId);
Messages.Add(e.MessageId);
return Task.CompletedTask;
}
public override void Init()
@@ -63,23 +57,24 @@ namespace TelegramBotBase.Controls.Hybrid
Device.MessageSent += Device_MessageSent;
}
public override async Task Load(MessageResult result)
public override Task Load(MessageResult result)
{
_Rendered = false;
_rendered = false;
return Task.CompletedTask;
}
public override async Task Render(MessageResult result)
{
//When already rendered, skip rendering
if (_Rendered)
if (_rendered)
return;
await CleanUpView();
await RenderView(new RenderViewEventArgs(this.SelectedViewIndex));
await RenderView(new RenderViewEventArgs(SelectedViewIndex));
_Rendered = true;
_rendered = true;
}
@@ -87,25 +82,24 @@ namespace TelegramBotBase.Controls.Hybrid
/// Will get invoked on rendering the current controls view.
/// </summary>
/// <param name="e"></param>
public virtual async Task RenderView(RenderViewEventArgs e)
public virtual Task RenderView(RenderViewEventArgs e)
{
return Task.CompletedTask;
}
async Task CleanUpView()
private async Task CleanUpView()
{
var tasks = new List<Task>();
foreach (var msg in this.Messages)
foreach (var msg in Messages)
{
tasks.Add(this.Device.DeleteMessage(msg));
tasks.Add(Device.DeleteMessage(msg));
}
await Task.WhenAll(tasks);
this.Messages.Clear();
Messages.Clear();
}
@@ -116,9 +110,9 @@ namespace TelegramBotBase.Controls.Hybrid
{
await CleanUpView();
await RenderView(new RenderViewEventArgs(this.SelectedViewIndex));
await RenderView(new RenderViewEventArgs(SelectedViewIndex));
_Rendered = true;
_rendered = true;
}
public override async Task Cleanup()
@@ -1,20 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InlineQueryResults;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Datasources;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid
@@ -22,27 +20,21 @@ namespace TelegramBotBase.Controls.Hybrid
public class TaggedButtonGrid : MultiView
{
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"];
public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; }
public string ConfirmationText { get; set; }
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object();
private static readonly object EvButtonClicked = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
[Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm
{
get
{
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
get => DataSource.ButtonForm;
set => DataSource = new ButtonFormDataSource(value);
}
/// <summary>
@@ -90,29 +82,29 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public bool EnableSearch { get; set; } = false;
public String SearchQuery { get; set; }
public string SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always;
public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary>
/// Index of the current page
/// </summary>
public int CurrentPageIndex { get; set; } = 0;
public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"];
public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"];
public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"];
public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"];
public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
public String BackLabel = Localizations.Default.Language["ButtonGrid_Back"];
public string BackLabel = Default.Language["ButtonGrid_Back"];
public String CheckAllLabel = Localizations.Default.Language["ButtonGrid_CheckAll"];
public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"];
public String UncheckAllLabel = Localizations.Default.Language["ButtonGrid_UncheckAll"];
public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"];
/// <summary>
/// Layout of the buttons which should be displayed always on top.
@@ -132,100 +124,91 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// List of Tags which will be allowed to filter by.
/// </summary>
public List<String> Tags { get; set; }
public List<string> Tags { get; set; }
/// <summary>
/// List of Tags selected by the User.
/// </summary>
public List<String> SelectedTags { get; set; }
public List<string> SelectedTags { get; set; }
/// <summary>
/// Defines which type of Button Keyboard should be rendered.
/// </summary>
public eKeyboardType KeyboardType
public EKeyboardType KeyboardType
{
get
{
return m_eKeyboardType;
}
get => _mEKeyboardType;
set
{
if (m_eKeyboardType != value)
if (_mEKeyboardType != value)
{
this.RenderNecessary = true;
_renderNecessary = true;
Cleanup().Wait();
m_eKeyboardType = value;
_mEKeyboardType = value;
}
}
}
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard;
private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public TaggedButtonGrid()
{
this.DataSource = new ButtonFormDataSource();
DataSource = new ButtonFormDataSource();
this.SelectedViewIndex = 0;
SelectedViewIndex = 0;
}
public TaggedButtonGrid(eKeyboardType type) : this()
public TaggedButtonGrid(EKeyboardType type) : this()
{
m_eKeyboardType = type;
_mEKeyboardType = type;
}
public TaggedButtonGrid(ButtonForm form)
{
this.DataSource = new ButtonFormDataSource(form);
DataSource = new ButtonFormDataSource(form);
}
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
add => _events.AddHandler(EvButtonClicked, value);
remove => _events.RemoveHandler(EvButtonClicked, value);
}
public async Task OnButtonClicked(ButtonClickedEventArgs e)
{
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public override void Init()
{
this.Device.MessageDeleted += Device_MessageDeleted;
Device.MessageDeleted += Device_MessageDeleted;
}
private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
{
if (this.MessageId == null)
if (MessageId == null)
return;
if (e.MessageId != this.MessageId)
if (e.MessageId != MessageId)
return;
this.MessageId = null;
MessageId = null;
}
public async override Task Load(MessageResult result)
public override async Task Load(MessageResult result)
{
if (this.KeyboardType != eKeyboardType.ReplyKeyboard)
if (KeyboardType != EKeyboardType.ReplyKeyboard)
return;
if (!result.IsFirstHandler)
@@ -236,7 +219,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>();
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{
@@ -275,12 +258,12 @@ namespace TelegramBotBase.Controls.Hybrid
switch (this.SelectedViewIndex)
switch (SelectedViewIndex)
{
case 0:
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (match != null)
@@ -293,59 +276,57 @@ namespace TelegramBotBase.Controls.Hybrid
if (result.MessageText == PreviousPageLabel)
{
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
result.Handled = true;
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
result.Handled = true;
}
else if (this.EnableSearch)
else if (EnableSearch)
{
if (result.MessageText.StartsWith("🔍"))
{
//Sent note about searching
if (this.SearchQuery == null)
if (SearchQuery == null)
{
await this.Device.Send(this.SearchLabel);
await Device.Send(SearchLabel);
}
this.SearchQuery = null;
this.Updated();
SearchQuery = null;
Updated();
result.Handled = true;
return;
}
this.SearchQuery = result.MessageText;
SearchQuery = result.MessageText;
if (this.SearchQuery != null && this.SearchQuery != "")
if (SearchQuery != null && SearchQuery != "")
{
this.CurrentPageIndex = 0;
this.Updated();
CurrentPageIndex = 0;
Updated();
result.Handled = true;
return;
}
}
else if (this.Tags != null)
else if (Tags != null)
{
if (result.MessageText == "📁")
{
//Remove button click message
if (this.DeletePreviousMessage)
if (DeletePreviousMessage)
await Device.DeleteMessage(result.MessageId);
this.SelectedViewIndex = 1;
this.Updated();
SelectedViewIndex = 1;
Updated();
result.Handled = true;
return;
}
}
@@ -353,23 +334,24 @@ namespace TelegramBotBase.Controls.Hybrid
case 1:
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (result.MessageText == this.BackLabel)
if (result.MessageText == BackLabel)
{
this.SelectedViewIndex = 0;
this.Updated();
SelectedViewIndex = 0;
Updated();
result.Handled = true;
return;
}
else if (result.MessageText == this.CheckAllLabel)
if (result.MessageText == CheckAllLabel)
{
this.CheckAllTags();
CheckAllTags();
}
else if (result.MessageText == this.UncheckAllLabel)
else if (result.MessageText == UncheckAllLabel)
{
this.UncheckAllTags();
UncheckAllTags();
}
var i = result.MessageText.LastIndexOf(" ");
@@ -378,16 +360,16 @@ namespace TelegramBotBase.Controls.Hybrid
var t = result.MessageText.Substring(0, i);
if (this.SelectedTags.Contains(t))
if (SelectedTags.Contains(t))
{
this.SelectedTags.Remove(t);
SelectedTags.Remove(t);
}
else
{
this.SelectedTags.Add(t);
SelectedTags.Add(t);
}
this.Updated();
Updated();
result.Handled = true;
@@ -399,7 +381,7 @@ namespace TelegramBotBase.Controls.Hybrid
}
public async override Task Action(MessageResult result, string value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
@@ -408,13 +390,13 @@ namespace TelegramBotBase.Controls.Hybrid
return;
//Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard)
if (KeyboardType != EKeyboardType.InlineKeyBoard)
return;
await result.ConfirmAction(this.ConfirmationText ?? "");
await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{
@@ -464,45 +446,45 @@ namespace TelegramBotBase.Controls.Hybrid
{
case "$previous$":
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
break;
case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
break;
case "$filter$":
this.SelectedViewIndex = 1;
this.Updated();
SelectedViewIndex = 1;
Updated();
break;
case "$back$":
this.SelectedViewIndex = 0;
this.Updated();
SelectedViewIndex = 0;
Updated();
break;
case "$checkall$":
this.CheckAllTags();
CheckAllTags();
break;
case "$uncheckall$":
this.UncheckAllTags();
UncheckAllTags();
break;
}
@@ -514,49 +496,49 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
private void CheckGrid()
{
switch (m_eKeyboardType)
switch (_mEKeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
}
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
}
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!_renderNecessary)
return;
//Check for rows and column limits
CheckGrid();
this.RenderNecessary = false;
_renderNecessary = false;
switch (this.SelectedViewIndex)
switch (SelectedViewIndex)
{
case 0:
@@ -586,7 +568,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
Message m = null;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null));
var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null));
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -597,111 +579,111 @@ namespace TelegramBotBase.Controls.Hybrid
// form = form.Duplicate();
//}
if (this.Tags != null && this.SelectedTags != null)
if (Tags != null && SelectedTags != null)
{
form = form.TagDuplicate(this.SelectedTags);
form = form.TagDuplicate(SelectedTags);
}
if (this.EnablePaging)
if (EnablePaging)
{
IntegratePagingView(form);
}
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{
form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray());
form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray());
}
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray());
form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray());
}
else
{
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray());
form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray());
}
}
switch (this.KeyboardType)
switch (KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (form.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
}
var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
break;
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
//Try to edit message if message id is available
//When the returned message is null then the message has been already deleted, resend it
if (this.MessageId != null)
if (MessageId != null)
{
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form);
m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
return;
}
}
//When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
break;
}
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
}
private void IntegratePagingView(ButtonForm dataForm)
{
//No Items
//No Items
if (dataForm.Rows == 0)
{
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
}
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
//🔍
ButtonRow row = new ButtonRow();
var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"));
row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
if (this.Tags != null && this.Tags.Count > 0)
if (Tags != null && Tags.Count > 0)
{
row.Add(new ButtonBase("📁", "$filter$"));
}
row.Add(new ButtonBase(NextPageLabel, "$next$"));
if (this.EnableSearch)
if (EnableSearch)
{
row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$"));
row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$"));
}
dataForm.InsertButtonRow(0, row);
@@ -719,22 +701,22 @@ namespace TelegramBotBase.Controls.Hybrid
private async Task RenderTagView()
{
Message m = null;
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
bf.AddButtonRow(this.BackLabel, "$back$");
bf.AddButtonRow(BackLabel, "$back$");
if (EnableCheckAllTools)
{
this.TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$"));
TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$"));
bf.AddButtonRow(TagsSubHeadLayoutButtonRow);
}
foreach (var t in this.Tags)
foreach (var t in Tags)
{
String s = t;
var s = t;
if (this.SelectedTags?.Contains(t) ?? false)
if (SelectedTags?.Contains(t) ?? false)
{
s += " ✅";
}
@@ -743,17 +725,17 @@ namespace TelegramBotBase.Controls.Hybrid
}
switch (this.KeyboardType)
switch (KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (bf.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
}
@@ -763,25 +745,25 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)bf;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
break;
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (this.MessageId != null)
if (MessageId != null)
{
m = await this.Device.Edit(this.MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf);
m = await Device.Edit(MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf);
}
else
{
m = await this.Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
m = await Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
}
break;
@@ -790,7 +772,7 @@ namespace TelegramBotBase.Controls.Hybrid
if (m != null)
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
@@ -802,12 +784,12 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
return true;
}
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
return true;
}
@@ -820,7 +802,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary))
if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{
return true;
}
@@ -836,30 +818,19 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
switch (this.KeyboardType)
return KeyboardType switch
{
case eKeyboardType.InlineKeyBoard:
return Constants.Telegram.MaxInlineKeyBoardRows;
case eKeyboardType.ReplyKeyboard:
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
};
}
}
/// <summary>
/// Returns the number of all rows (layout + navigation + content);
/// </summary>
public int TotalRows
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
public int TotalRows => LayoutRows + DataSource.RowCount;
/// <summary>
@@ -869,18 +840,18 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
int layoutRows = 0;
var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto)
if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++;
if (EnableCheckAllTools && this.SelectedViewIndex == 1)
if (EnableCheckAllTools && SelectedViewIndex == 1)
{
layoutRows++;
}
@@ -892,13 +863,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Returns the number of item rows per page.
/// </summary>
public int ItemRowsPerPage
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int ItemRowsPerPage => MaximumRow - LayoutRows;
public int PageCount
{
@@ -909,7 +874,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null);
var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -919,22 +884,24 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0)
return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage));
return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
}
}
public override async Task Hidden(bool FormClose)
public override Task Hidden(bool formClose)
{
//Prepare for opening Modal, and comming back
if (!FormClose)
if (!formClose)
{
this.Updated();
Updated();
}
else
{
//Remove event handler
this.Device.MessageDeleted -= Device_MessageDeleted;
Device.MessageDeleted -= Device_MessageDeleted;
}
return Task.CompletedTask;
}
/// <summary>
@@ -942,31 +909,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void Updated()
{
this.RenderNecessary = true;
_renderNecessary = true;
}
public async override Task Cleanup()
public override async Task Cleanup()
{
if (this.MessageId == null)
if (MessageId == null)
return;
switch (this.KeyboardType)
switch (KeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
this.MessageId = null;
MessageId = null;
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup)
if (HideKeyboardOnCleanup)
{
await this.Device.HideReplyKeyboard();
await Device.HideReplyKeyboard();
}
this.MessageId = null;
MessageId = null;
break;
}
@@ -979,11 +946,11 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void CheckAllTags()
{
this.SelectedTags.Clear();
SelectedTags.Clear();
this.SelectedTags = this.Tags.Select(a => a).ToList();
SelectedTags = Tags.Select(a => a).ToList();
this.Updated();
Updated();
}
@@ -992,9 +959,9 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void UncheckAllTags()
{
this.SelectedTags.Clear();
SelectedTags.Clear();
this.Updated();
Updated();
}
}
@@ -2,18 +2,17 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
using TelegramBotBase.Tools;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Tools.Arrays;
using static TelegramBotBase.Tools.Time;
namespace TelegramBotBase.Controls.Inline
{
public class CalendarPicker : Base.ControlBase
public class CalendarPicker : ControlBase
{
public DateTime SelectedDate { get; set; }
@@ -27,31 +26,31 @@ namespace TelegramBotBase.Controls.Inline
private int? MessageId { get; set; }
public String Title { get; set; } = Localizations.Default.Language["CalendarPicker_Title"];
public string Title { get; set; } = Default.Language["CalendarPicker_Title"];
public eMonthPickerMode PickerMode { get; set; }
public EMonthPickerMode PickerMode { get; set; }
public bool EnableDayView { get; set; } = true;
public bool EnableMonthView { get; set; } = true;
public bool EnableYearView { get; set; } = true;
public CalendarPicker(CultureInfo culture)
{
this.SelectedDate = DateTime.Today;
this.VisibleMonth = DateTime.Today;
this.FirstDayOfWeek = DayOfWeek.Monday;
this.Culture = culture;
this.PickerMode = eMonthPickerMode.day;
SelectedDate = DateTime.Today;
VisibleMonth = DateTime.Today;
FirstDayOfWeek = DayOfWeek.Monday;
Culture = culture;
PickerMode = EMonthPickerMode.day;
}
public CalendarPicker() : this(new CultureInfo("en-en")) { }
public override async Task Action(MessageResult result, String value = null)
public override async Task Action(MessageResult result, string value = null)
{
await result.ConfirmAction();
@@ -59,99 +58,84 @@ namespace TelegramBotBase.Controls.Inline
{
case "$next$":
switch (this.PickerMode)
VisibleMonth = PickerMode switch
{
case eMonthPickerMode.day:
this.VisibleMonth = this.VisibleMonth.AddMonths(1);
break;
case eMonthPickerMode.month:
this.VisibleMonth = this.VisibleMonth.AddYears(1);
break;
case eMonthPickerMode.year:
this.VisibleMonth = this.VisibleMonth.AddYears(10);
break;
}
EMonthPickerMode.day => VisibleMonth.AddMonths(1),
EMonthPickerMode.month => VisibleMonth.AddYears(1),
EMonthPickerMode.year => VisibleMonth.AddYears(10),
_ => VisibleMonth
};
break;
case "$prev$":
switch (this.PickerMode)
VisibleMonth = PickerMode switch
{
case eMonthPickerMode.day:
this.VisibleMonth = this.VisibleMonth.AddMonths(-1);
break;
case eMonthPickerMode.month:
this.VisibleMonth = this.VisibleMonth.AddYears(-1);
break;
case eMonthPickerMode.year:
this.VisibleMonth = this.VisibleMonth.AddYears(-10);
break;
}
EMonthPickerMode.day => VisibleMonth.AddMonths(-1),
EMonthPickerMode.month => VisibleMonth.AddYears(-1),
EMonthPickerMode.year => VisibleMonth.AddYears(-10),
_ => VisibleMonth
};
break;
case "$monthtitle$":
if (this.EnableMonthView)
if (EnableMonthView)
{
this.PickerMode = eMonthPickerMode.month;
PickerMode = EMonthPickerMode.month;
}
break;
case "$yeartitle$":
if (this.EnableYearView)
if (EnableYearView)
{
this.PickerMode = eMonthPickerMode.year;
PickerMode = EMonthPickerMode.year;
}
break;
case "$yearstitle$":
if (this.EnableMonthView)
if (EnableMonthView)
{
this.PickerMode = eMonthPickerMode.month;
PickerMode = EMonthPickerMode.month;
}
this.VisibleMonth = this.SelectedDate;
VisibleMonth = SelectedDate;
break;
default:
int day = 0;
if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], this.SelectedDate, out day))
var day = 0;
if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], SelectedDate, out day))
{
this.SelectedDate = new DateTime(this.VisibleMonth.Year, this.VisibleMonth.Month, day);
SelectedDate = new DateTime(VisibleMonth.Year, VisibleMonth.Month, day);
}
int month = 0;
var month = 0;
if (result.RawData.StartsWith("m-") && TryParseMonth(result.RawData.Split('-')[1], out month))
{
this.SelectedDate = new DateTime(this.VisibleMonth.Year, month, 1);
this.VisibleMonth = this.SelectedDate;
SelectedDate = new DateTime(VisibleMonth.Year, month, 1);
VisibleMonth = SelectedDate;
if (this.EnableDayView)
if (EnableDayView)
{
this.PickerMode = eMonthPickerMode.day;
PickerMode = EMonthPickerMode.day;
}
}
int year = 0;
var year = 0;
if (result.RawData.StartsWith("y-") && TryParseYear(result.RawData.Split('-')[1], out year))
{
this.SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day);
this.VisibleMonth = this.SelectedDate;
SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day);
VisibleMonth = SelectedDate;
if (this.EnableMonthView)
if (EnableMonthView)
{
this.PickerMode = eMonthPickerMode.month;
PickerMode = EMonthPickerMode.month;
}
}
@@ -170,18 +154,18 @@ namespace TelegramBotBase.Controls.Inline
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
switch (this.PickerMode)
switch (PickerMode)
{
case eMonthPickerMode.day:
case EMonthPickerMode.day:
var month = this.VisibleMonth;
var month = VisibleMonth;
string[] dayNamesNormal = this.Culture.DateTimeFormat.ShortestDayNames;
string[] dayNamesShifted = Shift(dayNamesNormal, (int)this.FirstDayOfWeek);
var dayNamesNormal = Culture.DateTimeFormat.ShortestDayNames;
var dayNamesShifted = Shift(dayNamesNormal, (int)FirstDayOfWeek);
bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(this.Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year.ToString(), "$monthtitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$"));
bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year, "$monthtitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$"));
bf.AddButtonRow(dayNamesShifted.Select(a => new ButtonBase(a, a)).ToList());
@@ -192,20 +176,20 @@ namespace TelegramBotBase.Controls.Inline
var lastDay = firstDay.LastDayOfMonth();
//Start of Week where first day of month is (left border)
var start = firstDay.StartOfWeek(this.FirstDayOfWeek);
var start = firstDay.StartOfWeek(FirstDayOfWeek);
//End of week where last day of month is (right border)
var end = lastDay.EndOfWeek(this.FirstDayOfWeek);
var end = lastDay.EndOfWeek(FirstDayOfWeek);
for (int i = 0; i <= ((end - start).Days / 7); i++)
for (var i = 0; i <= ((end - start).Days / 7); i++)
{
var lst = new List<ButtonBase>();
for (int id = 0; id < 7; id++)
for (var id = 0; id < 7; id++)
{
var d = start.AddDays((i * 7) + id);
if (d < firstDay | d > lastDay)
{
lst.Add(new ButtonBase("-", "m-" + d.Day.ToString()));
lst.Add(new ButtonBase("-", "m-" + d.Day));
continue;
}
@@ -216,35 +200,35 @@ namespace TelegramBotBase.Controls.Inline
day = "(" + day + ")";
}
lst.Add(new ButtonBase((this.SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day.ToString()));
lst.Add(new ButtonBase((SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day));
}
bf.AddButtonRow(lst);
}
break;
case eMonthPickerMode.month:
case EMonthPickerMode.month:
bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(this.VisibleMonth.Year.ToString("0000"), "$yeartitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$"));
bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(VisibleMonth.Year.ToString("0000"), "$yeartitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$"));
var months = this.Culture.DateTimeFormat.MonthNames;
var months = Culture.DateTimeFormat.MonthNames;
var buttons = months.Select((a, b) => new ButtonBase((b == this.SelectedDate.Month - 1 && this.SelectedDate.Year == this.VisibleMonth.Year ? "[ " + a + " ]" : a), "m-" + (b + 1).ToString()));
var buttons = months.Select((a, b) => new ButtonBase((b == SelectedDate.Month - 1 && SelectedDate.Year == VisibleMonth.Year ? "[ " + a + " ]" : a), "m-" + (b + 1)));
bf.AddSplitted(buttons, 2);
bf.AddSplitted(buttons);
break;
case eMonthPickerMode.year:
case EMonthPickerMode.year:
bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase("Year", "$yearstitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$"));
bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase("Year", "$yearstitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$"));
var starti = Math.Floor(this.VisibleMonth.Year / 10f) * 10;
var starti = Math.Floor(VisibleMonth.Year / 10f) * 10;
for (int i = 0; i < 10; i++)
for (var i = 0; i < 10; i++)
{
var m = starti + (i * 2);
bf.AddButtonRow(new ButtonBase((this.SelectedDate.Year == m ? "[ " + m.ToString() + " ]" : m.ToString()), "y-" + m.ToString()), new ButtonBase((this.SelectedDate.Year == (m + 1) ? "[ " + (m + 1).ToString() + " ]" : (m + 1).ToString()), "y-" + (m + 1).ToString()));
bf.AddButtonRow(new ButtonBase((SelectedDate.Year == m ? "[ " + m + " ]" : m.ToString()), "y-" + m), new ButtonBase((SelectedDate.Year == (m + 1) ? "[ " + (m + 1) + " ]" : (m + 1).ToString()), "y-" + (m + 1)));
}
break;
@@ -252,14 +236,14 @@ namespace TelegramBotBase.Controls.Inline
}
if (this.MessageId != null)
if (MessageId != null)
{
var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf);
var m = await Device.Edit(MessageId.Value, Title, bf);
}
else
{
var m = await this.Device.Send(this.Title, bf);
this.MessageId = m.MessageId;
var m = await Device.Send(Title, bf);
MessageId = m.MessageId;
}
}
@@ -268,9 +252,9 @@ namespace TelegramBotBase.Controls.Inline
public override async Task Cleanup()
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
}
}
+3 -11
View File
@@ -1,12 +1,4 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
using TelegramBotBase.Enums;
namespace TelegramBotBase.Controls.Inline
{
@@ -17,8 +9,8 @@ namespace TelegramBotBase.Controls.Inline
public MonthPicker()
{
this.PickerMode = eMonthPickerMode.month;
this.EnableDayView = false;
PickerMode = EMonthPickerMode.month;
EnableDayView = false;
}
@@ -1,11 +1,10 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Controls.Inline
{
@@ -14,25 +13,25 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// This contains the selected icon.
/// </summary>
public String SelectedIcon { get; set; } = Localizations.Default.Language["MultiToggleButton_SelectedIcon"];
public string SelectedIcon { get; set; } = Default.Language["MultiToggleButton_SelectedIcon"];
/// <summary>
/// This will appear on the ConfirmAction message (if not empty)
/// </summary>
public String ChangedString { get; set; } = Localizations.Default.Language["MultiToggleButton_Changed"];
public string ChangedString { get; set; } = Default.Language["MultiToggleButton_Changed"];
/// <summary>
/// This holds the title of the control.
/// </summary>
public String Title { get; set; } = Localizations.Default.Language["MultiToggleButton_Title"];
public string Title { get; set; } = Default.Language["MultiToggleButton_Title"];
public int? MessageId { get; set; }
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evToggled = new object();
private static readonly object EvToggled = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
/// <summary>
/// This will hold all options available.
@@ -52,27 +51,21 @@ namespace TelegramBotBase.Controls.Inline
public event EventHandler Toggled
{
add
{
this.Events.AddHandler(__evToggled, value);
}
remove
{
this.Events.RemoveHandler(__evToggled, value);
}
add => _events.AddHandler(EvToggled, value);
remove => _events.RemoveHandler(EvToggled, value);
}
public void OnToggled(EventArgs e)
{
(this.Events[__evToggled] as EventHandler)?.Invoke(this, e);
(_events[EvToggled] as EventHandler)?.Invoke(this, e);
}
public override async Task Action(MessageResult result, String value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
await result.ConfirmAction(this.ChangedString);
await result.ConfirmAction(ChangedString);
switch (value ?? "unknown")
{
@@ -82,30 +75,30 @@ namespace TelegramBotBase.Controls.Inline
if (s[0] == "check" && s.Length > 1)
{
int index = 0;
var index = 0;
if (!int.TryParse(s[1], out index))
{
return;
}
if(SelectedOption== null || SelectedOption != this.Options[index])
if(SelectedOption== null || SelectedOption != Options[index])
{
this.SelectedOption = this.Options[index];
OnToggled(new EventArgs());
SelectedOption = Options[index];
OnToggled(EventArgs.Empty);
}
else if(this.AllowEmptySelection)
else if(AllowEmptySelection)
{
this.SelectedOption = null;
OnToggled(new EventArgs());
SelectedOption = null;
OnToggled(EventArgs.Empty);
}
RenderNecessary = true;
_renderNecessary = true;
return;
}
RenderNecessary = false;
_renderNecessary = false;
break;
@@ -117,16 +110,16 @@ namespace TelegramBotBase.Controls.Inline
public override async Task Render(MessageResult result)
{
if (!RenderNecessary)
if (!_renderNecessary)
return;
var bf = new ButtonForm(this);
var lst = new List<ButtonBase>();
foreach (var o in this.Options)
foreach (var o in Options)
{
var index = this.Options.IndexOf(o);
if (o == this.SelectedOption)
var index = Options.IndexOf(o);
if (o == SelectedOption)
{
lst.Add(new ButtonBase(SelectedIcon + " " + o.Text, "check$" + index));
continue;
@@ -137,20 +130,20 @@ namespace TelegramBotBase.Controls.Inline
bf.AddButtonRow(lst);
if (this.MessageId != null)
if (MessageId != null)
{
var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf);
var m = await Device.Edit(MessageId.Value, Title, bf);
}
else
{
var m = await this.Device.Send(this.Title, bf, disableNotification: true);
var m = await Device.Send(Title, bf, disableNotification: true);
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
}
this.RenderNecessary = false;
_renderNecessary = false;
}
+90 -119
View File
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
@@ -10,9 +7,9 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// A simple control for show and managing progress.
/// </summary>
public class ProgressBar : Base.ControlBase
public class ProgressBar : ControlBase
{
public enum eProgressStyle
public enum EProgressStyle
{
standard = 0,
squares = 1,
@@ -22,104 +19,78 @@ namespace TelegramBotBase.Controls.Inline
custom = 10
}
public eProgressStyle ProgressStyle
public EProgressStyle ProgressStyle
{
get
{
return m_eStyle;
}
get => _mEStyle;
set
{
m_eStyle = value;
_mEStyle = value;
LoadStyle();
}
}
private eProgressStyle m_eStyle = eProgressStyle.standard;
private EProgressStyle _mEStyle = EProgressStyle.standard;
public int Value
{
get
{
return this.m_iValue;
}
get => _mIValue;
set
{
if (value > this.Max)
if (value > Max)
{
return;
}
if (this.m_iValue != value)
if (_mIValue != value)
{
this.RenderNecessary = true;
RenderNecessary = true;
}
this.m_iValue = value;
_mIValue = value;
}
}
private int m_iValue = 0;
private int _mIValue;
public int Max
{
get
{
return this.m_iMax;
}
get => _mIMax;
set
{
if (this.m_iMax != value)
if (_mIMax != value)
{
this.RenderNecessary = true;
RenderNecessary = true;
}
this.m_iMax = value;
_mIMax = value;
}
}
private int m_iMax = 100;
private int _mIMax = 100;
public int? MessageId { get; set; }
private bool RenderNecessary { get; set; } = false;
private bool RenderNecessary { get; set; }
public int Steps
{
get
{
switch (this.ProgressStyle)
return ProgressStyle switch
{
case eProgressStyle.standard:
return 1;
case eProgressStyle.squares:
return 10;
case eProgressStyle.circles:
return 10;
case eProgressStyle.lines:
return 5;
case eProgressStyle.squaredLines:
return 5;
default:
return 1;
}
EProgressStyle.standard => 1,
EProgressStyle.squares => 10,
EProgressStyle.circles => 10,
EProgressStyle.lines => 5,
EProgressStyle.squaredLines => 5,
_ => 1
};
}
}
/// <summary>
/// Filled block (reached percentage)
/// </summary>
public String BlockChar
public string BlockChar
{
get; set;
}
@@ -127,7 +98,7 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// Unfilled block (not reached yet)
/// </summary>
public String EmptyBlockChar
public string EmptyBlockChar
{
get; set;
}
@@ -135,7 +106,7 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// String at the beginning of the progress bar
/// </summary>
public String StartChar
public string StartChar
{
get; set;
}
@@ -143,133 +114,133 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// String at the end of the progress bar
/// </summary>
public String EndChar
public string EndChar
{
get; set;
}
public ProgressBar()
{
this.ProgressStyle = eProgressStyle.standard;
ProgressStyle = EProgressStyle.standard;
this.Value = 0;
this.Max = 100;
Value = 0;
Max = 100;
this.RenderNecessary = true;
RenderNecessary = true;
}
public ProgressBar(int Value, int Max, eProgressStyle Style)
public ProgressBar(int value, int max, EProgressStyle style)
{
this.Value = Value;
this.Max = Max;
this.ProgressStyle = Style;
this.Value = value;
this.Max = max;
ProgressStyle = style;
this.RenderNecessary = true;
RenderNecessary = true;
}
public override async Task Cleanup()
{
if (this.MessageId == null || this.MessageId == -1)
if (MessageId == null || MessageId == -1)
return;
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
}
public void LoadStyle()
{
this.StartChar = "";
this.EndChar = "";
StartChar = "";
EndChar = "";
switch (this.ProgressStyle)
switch (ProgressStyle)
{
case eProgressStyle.circles:
case EProgressStyle.circles:
this.BlockChar = "⚫️ ";
this.EmptyBlockChar = "⚪️ ";
BlockChar = "⚫️ ";
EmptyBlockChar = "⚪️ ";
break;
case eProgressStyle.squares:
case EProgressStyle.squares:
this.BlockChar = "⬛️ ";
this.EmptyBlockChar = "⬜️ ";
BlockChar = "⬛️ ";
EmptyBlockChar = "⬜️ ";
break;
case eProgressStyle.lines:
case EProgressStyle.lines:
this.BlockChar = "█";
this.EmptyBlockChar = "▁";
BlockChar = "█";
EmptyBlockChar = "▁";
break;
case eProgressStyle.squaredLines:
case EProgressStyle.squaredLines:
this.BlockChar = "▇";
this.EmptyBlockChar = "—";
BlockChar = "▇";
EmptyBlockChar = "—";
this.StartChar = "[";
this.EndChar = "]";
StartChar = "[";
EndChar = "]";
break;
case eProgressStyle.standard:
case eProgressStyle.custom:
case EProgressStyle.standard:
case EProgressStyle.custom:
this.BlockChar = "";
this.EmptyBlockChar = "";
BlockChar = "";
EmptyBlockChar = "";
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!RenderNecessary)
{
return;
}
if (this.Device == null)
if (Device == null)
{
return;
}
String message = "";
int blocks = 0;
int maxBlocks = 0;
var message = "";
var blocks = 0;
var maxBlocks = 0;
switch (this.ProgressStyle)
switch (ProgressStyle)
{
case eProgressStyle.standard:
case EProgressStyle.standard:
message = this.Value.ToString("0") + "%";
message = Value.ToString("0") + "%";
break;
case eProgressStyle.squares:
case eProgressStyle.circles:
case eProgressStyle.lines:
case eProgressStyle.squaredLines:
case eProgressStyle.custom:
case EProgressStyle.squares:
case EProgressStyle.circles:
case EProgressStyle.lines:
case EProgressStyle.squaredLines:
case EProgressStyle.custom:
blocks = (int)Math.Floor((decimal)this.Value / this.Steps);
blocks = (int)Math.Floor((decimal)Value / Steps);
maxBlocks = (this.Max / this.Steps);
maxBlocks = (Max / Steps);
message += this.StartChar;
message += StartChar;
for (int i = 0; i < blocks; i++)
for (var i = 0; i < blocks; i++)
{
message += this.BlockChar;
message += BlockChar;
}
for (int i = 0; i < (maxBlocks - blocks); i++)
for (var i = 0; i < (maxBlocks - blocks); i++)
{
message += this.EmptyBlockChar;
message += EmptyBlockChar;
}
message += this.EndChar;
message += EndChar;
message += " " + this.Value.ToString("0") + "%";
message += " " + Value.ToString("0") + "%";
break;
@@ -278,18 +249,18 @@ namespace TelegramBotBase.Controls.Inline
return;
}
if (this.MessageId == null)
if (MessageId == null)
{
var m = await this.Device.Send(message);
var m = await Device.Send(message);
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
else
{
await this.Device.Edit(this.MessageId.Value, message);
await Device.Edit(MessageId.Value, message);
}
this.RenderNecessary = false;
RenderNecessary = false;
}
}
+35 -43
View File
@@ -1,38 +1,36 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Controls.Inline
{
public class ToggleButton : ControlBase
{
public String UncheckedIcon { get; set; } = Localizations.Default.Language["ToggleButton_OffIcon"];
public string UncheckedIcon { get; set; } = Default.Language["ToggleButton_OffIcon"];
public String CheckedIcon { get; set; } = Localizations.Default.Language["ToggleButton_OnIcon"];
public string CheckedIcon { get; set; } = Default.Language["ToggleButton_OnIcon"];
public String CheckedString { get; set; } = Localizations.Default.Language["ToggleButton_On"];
public string CheckedString { get; set; } = Default.Language["ToggleButton_On"];
public String UncheckedString { get; set; } = Localizations.Default.Language["ToggleButton_Off"];
public string UncheckedString { get; set; } = Default.Language["ToggleButton_Off"];
public String ChangedString { get; set; } = Localizations.Default.Language["ToggleButton_Changed"];
public string ChangedString { get; set; } = Default.Language["ToggleButton_Changed"];
public String Title { get; set; } = Localizations.Default.Language["ToggleButton_Title"];
public string Title { get; set; } = Default.Language["ToggleButton_Title"];
public int? MessageId { get; set; }
public bool Checked { get; set; }
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evToggled = new object();
private static readonly object EvToggled = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
public ToggleButton()
@@ -41,68 +39,62 @@ namespace TelegramBotBase.Controls.Inline
}
public ToggleButton(String CheckedString, String UncheckedString)
public ToggleButton(string checkedString, string uncheckedString)
{
this.CheckedString = CheckedString;
this.UncheckedString = UncheckedString;
this.CheckedString = checkedString;
this.UncheckedString = uncheckedString;
}
public event EventHandler Toggled
{
add
{
this.Events.AddHandler(__evToggled, value);
}
remove
{
this.Events.RemoveHandler(__evToggled, value);
}
add => _events.AddHandler(EvToggled, value);
remove => _events.RemoveHandler(EvToggled, value);
}
public void OnToggled(EventArgs e)
{
(this.Events[__evToggled] as EventHandler)?.Invoke(this, e);
(_events[EvToggled] as EventHandler)?.Invoke(this, e);
}
public override async Task Action(MessageResult result, String value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
await result.ConfirmAction(this.ChangedString);
await result.ConfirmAction(ChangedString);
switch (value ?? "unknown")
{
case "on":
if (this.Checked)
if (Checked)
return;
RenderNecessary = true;
_renderNecessary = true;
this.Checked = true;
Checked = true;
OnToggled(new EventArgs());
OnToggled(EventArgs.Empty);
break;
case "off":
if (!this.Checked)
if (!Checked)
return;
RenderNecessary = true;
_renderNecessary = true;
this.Checked = false;
Checked = false;
OnToggled(new EventArgs());
OnToggled(EventArgs.Empty);
break;
default:
RenderNecessary = false;
_renderNecessary = false;
break;
@@ -114,31 +106,31 @@ namespace TelegramBotBase.Controls.Inline
public override async Task Render(MessageResult result)
{
if (!RenderNecessary)
if (!_renderNecessary)
return;
var bf = new ButtonForm(this);
ButtonBase bOn = new ButtonBase((this.Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on");
var bOn = new ButtonBase((Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on");
ButtonBase bOff = new ButtonBase((!this.Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off");
var bOff = new ButtonBase((!Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off");
bf.AddButtonRow(bOn, bOff);
if (this.MessageId != null)
if (MessageId != null)
{
var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf);
var m = await Device.Edit(MessageId.Value, Title, bf);
}
else
{
var m = await this.Device.Send(this.Title, bf, disableNotification: true);
var m = await Device.Send(Title, bf, disableNotification: true);
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
}
this.RenderNecessary = false;
_renderNecessary = false;
}
+22 -23
View File
@@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Controls.Inline
{
@@ -16,20 +15,20 @@ namespace TelegramBotBase.Controls.Inline
public TreeViewNode VisibleNode { get; set; }
public String Title { get; set; }
public string Title { get; set; }
private int? MessageId { get; set; }
public String MoveUpIcon { get; set; } = Localizations.Default.Language["TreeView_LevelUp"];
public string MoveUpIcon { get; set; } = Default.Language["TreeView_LevelUp"];
public TreeView()
{
this.Nodes = new List<TreeViewNode>();
this.Title = Localizations.Default.Language["TreeView_Title"];
Nodes = new List<TreeViewNode>();
Title = Default.Language["TreeView_Title"];
}
public override async Task Action(MessageResult result, String value = null)
public override async Task Action(MessageResult result, string value = null)
{
await result.ConfirmAction();
@@ -43,14 +42,14 @@ namespace TelegramBotBase.Controls.Inline
case "up":
case "parent":
this.VisibleNode = (this.VisibleNode?.ParentNode);
VisibleNode = (VisibleNode?.ParentNode);
result.Handled = true;
break;
default:
var n = (this.VisibleNode != null ? this.VisibleNode.FindNodeByValue(val) : this.Nodes.FirstOrDefault(a => a.Value == val));
var n = (VisibleNode != null ? VisibleNode.FindNodeByValue(val) : Nodes.FirstOrDefault(a => a.Value == val));
if (n == null)
return;
@@ -58,11 +57,11 @@ namespace TelegramBotBase.Controls.Inline
if (n.ChildNodes.Count > 0)
{
this.VisibleNode = n;
VisibleNode = n;
}
else
{
this.SelectedNode = (this.SelectedNode != n ? n : null);
SelectedNode = (SelectedNode != n ? n : null);
}
result.Handled = true;
@@ -77,21 +76,21 @@ namespace TelegramBotBase.Controls.Inline
public override async Task Render(MessageResult result)
{
var startnode = this.VisibleNode;
var startnode = VisibleNode;
var nodes = (startnode?.ChildNodes ?? this.Nodes);
var nodes = (startnode?.ChildNodes ?? Nodes);
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
if (startnode != null)
{
bf.AddButtonRow(new ButtonBase(this.MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent"));
bf.AddButtonRow(new ButtonBase(MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent"));
}
foreach (var n in nodes)
{
var s = n.Text;
if (this.SelectedNode == n)
if (SelectedNode == n)
{
s = "[ " + s + " ]";
}
@@ -101,20 +100,20 @@ namespace TelegramBotBase.Controls.Inline
if (this.MessageId != null)
if (MessageId != null)
{
var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf);
var m = await Device.Edit(MessageId.Value, Title, bf);
}
else
{
var m = await this.Device.Send(this.Title, bf);
this.MessageId = m.MessageId;
var m = await Device.Send(Title, bf);
MessageId = m.MessageId;
}
}
public String GetPath()
public string GetPath()
{
return (this.VisibleNode?.GetPath() ?? "\\");
return (VisibleNode?.GetPath() ?? "\\");
}
+14 -17
View File
@@ -1,35 +1,32 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Controls.Inline
{
public class TreeViewNode
{
public String Text { get; set; }
public string Text { get; set; }
public String Value { get; set; }
public string Value { get; set; }
public String Url { get; set; }
public string Url { get; set; }
public List<TreeViewNode> ChildNodes { get; set; } = new List<TreeViewNode>();
public TreeViewNode ParentNode { get; set; }
public TreeViewNode(String Text, String Value)
public TreeViewNode(string text, string value)
{
this.Text = Text;
this.Value = Value;
this.Text = text;
this.Value = value;
}
public TreeViewNode(String Text, String Value, String Url) : this(Text, Value)
public TreeViewNode(string text, string value, string url) : this(text, value)
{
this.Url = Url;
this.Url = url;
}
public TreeViewNode(String Text, String Value, params TreeViewNode[] childnodes) : this(Text, Value)
public TreeViewNode(string text, string value, params TreeViewNode[] childnodes) : this(text, value)
{
foreach(var c in childnodes)
{
@@ -44,14 +41,14 @@ namespace TelegramBotBase.Controls.Inline
ChildNodes.Add(node);
}
public TreeViewNode FindNodeByValue(String Value)
public TreeViewNode FindNodeByValue(string value)
{
return this.ChildNodes.FirstOrDefault(a => a.Value == Value);
return ChildNodes.FirstOrDefault(a => a.Value == value);
}
public String GetPath()
public string GetPath()
{
String s = "\\" + this.Value;
var s = "\\" + Value;
var p = this;
while (p.ParentNode != null)
{