-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpagination.ts
263 lines (241 loc) · 8.2 KB
/
pagination.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import process from 'node:process';
import {
ActionRowBuilder,
APIEmbed,
ButtonBuilder,
ButtonStyle,
EmbedBuilder,
InteractionReplyOptions,
StringSelectMenuBuilder,
} from 'discord.js';
import { COLORS, createId, Logger, Namespace } from 'utils';
import { PaginationContext, PaginationData } from 'types';
export class Paginator {
name: string;
/**
* The embed data to use for the pagination embed.
* The fields and footer are automatically set by the paginator.
*/
embedData?:
| Omit<APIEmbed, 'fields' | 'footer'>
| ((ctx: PaginationContext) => Omit<APIEmbed, 'fields' | 'footer'>);
/**
* The reply to which the pagination embed and its controls are added.
* If not specified, the reply is ephemeral by default.
*/
replyOptions?:
| InteractionReplyOptions
| ((ctx: PaginationContext) => InteractionReplyOptions);
/** The number of fields to display on a single page (max 25). */
pageLength: number;
/** Asynchronous function to fetch the data for the paginator */
getData: (ctx: PaginationContext) => PaginationData | Promise<PaginationData>;
// #region Cache
/** Whether or not to cache the fetched data */
cacheData = false;
/** The cached data */
protected cachedData: Map<string, PaginationData> = new Map();
/** Function to get the cache key for the paginator */
getCacheKey: (ctx: PaginationContext) => string;
// #endregion
private logger: Logger;
constructor(
/** Name of the paginator */
name: string,
{
embedData,
replyOptions,
pageLength,
getData,
cacheData,
getCacheKey,
}: {
/**
* The embed data to use for the pagination embed.
* The fields and footer are automatically set by the paginator.
*/
embedData?: typeof Paginator.prototype.embedData;
/**
* The reply to which the pagination embed and its controls are added.
* If not specified, the reply is ephemeral by default.
*/
replyOptions?: typeof Paginator.prototype.replyOptions;
/** The number of fields to display on a single page (max 25). */
pageLength: typeof Paginator.prototype.pageLength;
getData: typeof Paginator.prototype.getData;
/** Whether or not to cache the fetched data */
cacheData?: boolean;
/**
* Function to get the cache key for the paginator based on the given context.
* This can be used to make the cache key unique to the user and/or guild.
* @example
* (ctx) => `${ctx.interaction.user.id}-${ctx.interaction.guildId}`
*/
getCacheKey?: typeof Paginator.prototype.getCacheKey;
},
) {
this.logger = new Logger(`paginators/${name}`);
// Page length can be at most 25 due to limit of 25 fields per embed
if (pageLength > 25) {
this.logger.error(
`Paginator "${name}" has a page length greater than 25`,
);
process.exit(1);
}
// Components can have at most 3 rows, because of the 5 component limit on embeds
// (2 are already being used for back/next buttons and page selector)
if (
replyOptions &&
typeof replyOptions !== 'function' &&
replyOptions.components &&
replyOptions.components.length > 3
) {
this.logger.error(`Paginator "${name}" has more than 3 components`);
process.exit(1);
}
// The replyOptions can have at most 4 embeds, because of the 5 embed limit on replies
// (1 is already being used for the pagination embed)
if (
replyOptions &&
typeof replyOptions !== 'function' &&
replyOptions.embeds &&
replyOptions.embeds.length > 4
) {
this.logger.error(`Paginator "${name}" has more than 4 embeds`);
process.exit(1);
}
// If caching is enabled, the cache key function must be specified
if (cacheData && !getCacheKey) {
this.logger.error(
`Paginator "${name}" has caching enabled but no cache key function specified`,
);
process.exit(1);
}
this.name = name;
this.embedData = embedData;
this.replyOptions = replyOptions;
this.pageLength = pageLength;
this.getData = getData;
this.cacheData = cacheData ?? false;
this.getCacheKey = getCacheKey ?? (() => name);
}
/**
* Get a page of the paginator at a given offset
* @param offset The offset to get the page at
* @returns The interaction reply options for the page at the given offset
*/
public async getPage(
offset: number,
ctx: PaginationContext,
): Promise<InteractionReplyOptions> {
// If caching is enabled, try to get the data from the cache and fetch otherwise
const cacheKey = this.getCacheKey(ctx);
if (this.cacheData && this.cachedData.has(cacheKey)) {
return this.formatPage(offset, this.cachedData.get(cacheKey)!, ctx);
}
const data = await this.getData(ctx);
if (this.cacheData) this.cachedData.set(cacheKey, data);
return this.formatPage(offset, data, ctx);
}
/**
* Invalidate the cache for the paginator at the cache key retrieved from the given context
*/
public invalidateCache(ctx: PaginationContext) {
if (!this.cacheData) return;
const cacheKey = this.getCacheKey(ctx);
this.cachedData.delete(cacheKey);
}
/**
* Format a page of the paginator at a given offset
* @param offset The offset to get the page at
* @param data The data to format
* @returns The interaction reply options for the page at the given offset
*/
protected formatPage(
offset: number,
data: PaginationData,
ctx: PaginationContext,
): InteractionReplyOptions {
const fields = data.slice(offset, offset + this.pageLength);
const currentPage = Math.floor(offset / this.pageLength) + 1;
const pageCount = Math.ceil(data.length / this.pageLength);
const embedData = this.embedData
? typeof this.embedData === 'function'
? this.embedData(ctx)
: this.embedData
: undefined;
const embed = new EmbedBuilder(embedData)
.setFields(fields)
.setColor(embedData?.color ?? COLORS.embed);
if (fields.length === 0) embed.setDescription('No results found!');
else {
embed.setFooter({
text: `Page ${currentPage} / ${pageCount}`,
});
}
// Back button
const backId = createId(
Namespace.Pagination,
this.name,
offset - this.pageLength,
);
const backButton = new ButtonBuilder()
.setCustomId(backId)
.setLabel('Back')
.setStyle(ButtonStyle.Primary)
.setDisabled(offset <= 0);
// Next button
const nextId = createId(
Namespace.Pagination,
this.name,
offset + this.pageLength,
);
const nextButton = new ButtonBuilder()
.setCustomId(nextId)
.setLabel('Next')
.setStyle(ButtonStyle.Primary)
.setDisabled(currentPage >= pageCount);
const selectId = createId(Namespace.Pagination, this.name);
const pageSelector = new StringSelectMenuBuilder()
.setCustomId(selectId)
.setPlaceholder('Select a page...')
.setMaxValues(1)
.setOptions(
Array.from(Array(pageCount).keys()).map((i) => ({
label: `Page ${i + 1}`,
value: i.toString(),
})),
);
const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
backButton,
nextButton,
);
const selectMenu = new ActionRowBuilder<StringSelectMenuBuilder>()
.addComponents(
pageSelector,
);
const replyOptions = this.replyOptions
? typeof this.replyOptions === 'function'
? this.replyOptions(ctx)
: this.replyOptions
: undefined;
if (replyOptions?.components && replyOptions.components.length > 3) {
throw new Error(`Paginator "${this.name}" has more than 3 components`);
}
if (replyOptions?.embeds && replyOptions.embeds.length > 4) {
throw new Error(`Paginator "${this.name}" has more than 4 embeds`);
}
return {
...this.replyOptions,
embeds: [embed, ...(replyOptions?.embeds ?? [])],
components: [
buttons,
// Only show page selection menu if there are multiple pages
...(pageCount > 1 ? [selectMenu] : []),
...(replyOptions?.components ?? []),
],
// Ephemeral by default
ephemeral: replyOptions?.ephemeral ?? true,
};
}
}