Пагинация
Конечно! Пагинация - ценный прием в пользовательских интерфейсах, позволяющий отображать большие объемы информации в структурированном и удобном виде. При работе с обширными данными, такими как результаты поиска, статьи или списки товаров, показ всего сразу может перегрузить пользователей и ухудшить их восприятие. Пагинация разбивает информацию на более мелкие, упорядоченные разделы, повышая вовлеченность пользователей и удобство навигации. Этот модуль позволяет реализовать пагинацию с помощью всего нескольких строк кода.
Использование
После завершения процесса установки мы можем импортировать NestCordPaginationModule
вместе с вашим NestCordModule
в корневой AppModule
:
import { NestCordModule } from '@globalart/nestcord';
import { Module } from '@nestjs/common';
import { NestCordPaginationModule } from '@globalart/nestcord';
import { AppService } from './app.service';
@Module({
imports: [
NestCordModule.forRoot({
token: 'DISCORD_BOT_TOKEN',
intents: ['Guilds', 'GuildMessages', 'DirectMessages']
}),
NestCordPaginationModule.forRoot()
],
providers: [AppService]
})
export class AppModule {}
Затем мы можем внедрить PaginationService
в наш сервис и зарегистрировать обработчик пагинации:
Кнопки пагинации
import { OnModuleInit, Injectable } from '@nestjs/common';
import { NestCordPaginationService, PageBuilder } from '@globalart/nestcord/pagination';
import { Context, SlashCommand, PaginatorTypeEnum, SlashCommandContext } from '@globalart/nestcord';
@Injectable()
export class AppService implements OnModuleInit {
public constructor(private readonly paginationService: NestCordPaginationService) {
}
public onModuleInit(): void {
this.paginationService.register(PaginatorTypeEnum.BUTTONS, (builder) =>
builder
.setCustomId('test')
);
}
@SlashCommand({ name: 'pagination', description: 'Test pagination' })
public async onPagination(@Context() [interaction]: SlashCommandContext) {
const pagination = this.paginationService.get<PaginatorTypeEnum.BUTTONS>('test');
pagination.setButtons([
[
{
customId: 'page1',
label: 'Page 1',
style: ButtonStyle.Secondary,
},
{
customId: 'page2',
label: 'Page 2',
style: ButtonStyle.Secondary,
}
]
]);
pagination.setPages([
new PageBuilder().setContent('Page 1'),
new PageBuilder().setContent('Page 2')
]);
const page = await pagination.build(1);
return interaction.reply(page);
}
}
Пагинация меню выбора
import { OnModuleInit, Injectable } from '@nestjs/common';
import { NestCordPaginationService, PageBuilder } from '@globalart/nestcord/pagination';
import { Context, SlashCommand, PaginatorTypeEnum, SlashCommandContext } from '@globalart/nestcord';
@Injectable()
export class AppService implements OnModuleInit {
public constructor(private readonly paginationService: NestCordPaginationService) {
}
public onModuleInit(): void {
this.paginationService.register(PaginatorTypeEnum.SELECT_MENU, (builder) =>
builder
.setCustomId('test')
);
}
@SlashCommand({ name: 'pagination', description: 'Test pagination' })
public async onPagination(@Context() [interaction]: SlashCommandContext) {
const pagination = this.paginationService.get<PaginatorTypeEnum.SELECT_MENU>('test');
pagination.setSelectMenuItems(this.setMenuItems());
pagination.setPages(this.setMenuPages());
const page = await pagination.build('page1');
return interaction.reply(page);
}
@StringSelect('nestcord-pagination/test')
async MenusInteraction(@Context() [interaction]: ButtonContext, @SelectedStrings() selected: string[]) {
const selectedPage = selected?.[0] || null;
const pagination = this.paginationService.get<PaginatorTypeEnum.SELECT_MENU>('menus');
pagination.setSelectMenuItems(this.setMenuItems());
pagination.setPages(this.setMenuPages());
const page = await pagination.build(selectedPage);
await interaction.update(page);
}
private readonly setMenuPages() {
return [
{
pageId: 'page1',
builder: new PageBuilder().setContent('Page 1'),
},
{
pageId: 'page2',
builder: new PageBuilder().setContent('Page 2'),
},
];
}
private readonly setMenuItems() {
return [
{
label: 'Page 1',
value: 'page1',
},
{
label: 'Page 2',
value: 'page2',
},
]
}
}
Поздравляем! Вы успешно создали свою первую пагинацию!
Просто используйте команду pagination
, и вы увидите свою пагинацию!