Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rowSize doesn't work with isButtonsMode #10

Open
Viiprogrammer opened this issue Dec 16, 2022 · 4 comments
Open

rowSize doesn't work with isButtonsMode #10

Viiprogrammer opened this issue Dec 16, 2022 · 4 comments

Comments

@Viiprogrammer
Copy link

I think can be resolved by replacing

if (0 === i % 1 && row.length) {

to

if (0 === i % this.rowSize && row.length) {
@Viiprogrammer Viiprogrammer changed the title rowSize dose't work with isButtonsMode rowSize doesn't work with isButtonsMode Dec 16, 2022
@sergey608
Copy link

class Pagination {
defaultMessages = {
firstPage: "❗️ That's the first page",
lastPage: "❗️ That's the last page",
prev: "⬅️",
next: "➡️",
delete: "❌",
indexKey: "order",
};

constructor({
data = [],
lazy = false,
total,
pageSize = 10,
rowSize = 5,
currentPage = 1,
isButtonsMode = false,
buttonModeOptions = {
isSimpleArray: true,
title: "",
},
isEnabledDeleteButton = true,
inlineCustomButtons = null,
onSelect = () => {},
format = (item, index) => ${index + 1}. ${item},
header = (currentPage, pageSize, total) =>
Items ${(currentPage - 1) * pageSize + 1}-${ currentPage * pageSize <= total ? currentPage * pageSize : total } of ${total},
messages = {},
}) {
this.lazy = lazy;
if (!this.lazy && Array.isArray(data)) {
this.data = data;
} else if (this.lazy && typeof data === "function") {
this.data = data;
} else {
throw new TypeError(
data must be function or array depending on value of lazy
);
}
this.pageSize = pageSize;
this.rowSize = rowSize;
this.currentPage = currentPage;
this.onSelect = onSelect;
this.format = format;
this.header = header;
this.messages = { ...this.defaultMessages, ...messages };
this.total = this.lazy ? total ?? Infinity : this.data.length;
this.totalPages = Math.ceil(this.total / this.pageSize);
this.currentPage =
currentPage && (this.lazy || currentPage < this.totalPages)
? currentPage
: 1;
this.isButtonsMode = isButtonsMode;
this.isEnabledDeleteButton = isEnabledDeleteButton;
this.inlineCustomButtons = inlineCustomButtons;
this.buttonModeOptions = {
isSimpleArray: false,
title: "",
...buttonModeOptions,
};

this._callbackStr = Math.random().toString(36).slice(2);

this.currentItems = [];

}

async text() {
let items = [];

if (!this.isButtonsMode) {
  if (this.lazy) {
    this.currentItems = await this.data(this.currentPage, this.pageSize);
  } else {
    this.currentItems = getPageData(
      this.data,
      this.currentPage,
      this.pageSize
    );
  }

  items = this.currentItems;
}

const header = this.header(this.currentPage, this.pageSize, this.total);
const itemsText = items.map(this.format).join("\n");

return `${header}\n${itemsText}`;

}

async keyboard() {
const keyboard = [];

if (this.lazy) {
  this.currentItems = await this.data(this.currentPage, this.pageSize);
} else {
  this.currentItems = getPageData(
    this.data,
    this.currentPage,
    this.pageSize
  );
}
const items = this.currentItems;

let row = [];

if (!this.isButtonsMode) {
  // Pagination buttons
  for (let i = 0; i < items.length; i++) {
    if (i % this.rowSize === 0 && row.length) {
      keyboard.push(row);
      row = [];
    }
    let item = items[i];
    if (this.messages.indexKey === "order") {
      item.order = i + 1;
    }
    let button = getButton(
      item[this.messages.indexKey],
      `${this._callbackStr}-${i}`
    );
    row.push(button);
  }
} else {
  // Need to display the title from an associative array?...
  let { isSimpleArray, title } = this.buttonModeOptions;

  if (isSimpleArray) {
    title = 0;
  }

  // Pagination buttons
  for (let i = 0; i < items.length; i++) {
    if (i % this.rowSize === 0 && row.length) {
      keyboard.push(row);
      row = [];
    }

    let currentItem = items[i];
    let buttonText;
    if (typeof title === "function") {
      buttonText = title(currentItem, i);
    } else {
      buttonText =
        typeof currentItem[title] !== "undefined" &&
        (currentItem[title] !== ""
          ? currentItem[title]
          : `Element #${i + 1}`);
    }

    let button = getButton(buttonText, `${this._callbackStr}-${i}`);
    row.push(button);
  }
}

keyboard.push(row);
row = [];

// Pagination Controls
if (this.totalPages > 1) {
  row.push(getButton(this.messages.prev, `${this._callbackStr}-prev`));
  if (this.isEnabledDeleteButton) {
    row.push(
      getButton(this.messages.delete, `${this._callbackStr}-delete`)
    );
  }
  row.push(getButton(this.messages.next, `${this._callbackStr}-next`));
  keyboard.push(row);
}

// If needed add custom buttons
if (
  this.inlineCustomButtons &&
  typeof this.inlineCustomButtons === "object"
) {
  keyboard.push(...this.inlineCustomButtons);
}

// Give ready-to-use Telegra Markup object
return {
  reply_markup: { inline_keyboard: keyboard },
};

}

handleActions(composer) {
composer.action(new RegExp(this._callbackStr + "-(.+)"), async (ctx) => {
let data = ctx.match[1];
let text;
let keyboard;
switch (data) {
case "prev":
if (this.currentPage <= 1) {
return await ctx.answerCbQuery(this.messages.firstPage);
}
this.currentPage = this.currentPage - 1;
text = await this.text();
keyboard = await this.keyboard();
await ctx.editMessageText(text, {
...keyboard,
parse_mode: "HTML",
});
break;
case "next":
if (this.currentPage >= this.totalPages) {
return await ctx.answerCbQuery(this.messages.lastPage);
}
this.currentPage = this.currentPage + 1;
text = await this.text();
keyboard = await this.keyboard();
await ctx.editMessageText(text, {
...keyboard,
parse_mode: "HTML",
});
break;
case "delete":
await ctx.deleteMessage();
break;
default:
this.onSelect(this.currentItems[data], parseInt(data) + 1, ctx);
}
return await ctx.answerCbQuery();
});
}
}

const getPageData = (data, page, pageSize) =>
data.slice((page - 1) * pageSize, page * pageSize);

const getButton = (text, callback_data) => ({ text, callback_data });

module.exports = { Pagination };

@sergey608
Copy link

еще минимально еще поработал

@Viiprogrammer
Copy link
Author

еще минимально еще поработал

Ну и треш чувак, ты бы хоть в блок кода обернул

@sergey608
Copy link

sergey608 commented Dec 22, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants