-
Notifications
You must be signed in to change notification settings - Fork 1
/
operators.ts
94 lines (83 loc) · 2.65 KB
/
operators.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
import {
ActionRow,
ApplicationCommandInteractionDataOption,
Component,
} from "droff/types";
import { pipe } from "fp-ts/lib/function";
import { Map } from "immutable";
import { Observable } from "rxjs";
import * as Rx from "rxjs";
import * as RxO from "rxjs/operators";
import { InteractionContext } from "./factory";
import * as O from "fp-ts/lib/Option";
import { Interactions as H } from "droff-helpers";
export const filterByName = (name: string) =>
RxO.filter(({ interaction }: InteractionContext) =>
pipe(
H.getCommandOrAutocompleteData(interaction),
O.filter((d) => d.name === name),
O.isSome,
),
);
export type InteractionContextWithSubCommand = readonly [
InteractionContext,
ApplicationCommandInteractionDataOption,
];
export const withSubCommand = (name: string) => {
const find = H.findSubCommand(name);
return RxO.flatMap((ctx: InteractionContext) =>
pipe(
find(ctx.interaction),
O.fold(
() => Rx.EMPTY,
(subCommand) =>
Rx.of([ctx, subCommand] as InteractionContextWithSubCommand),
),
),
);
};
export const filterBySelector =
(selector: (data: InteractionContext) => string | undefined) =>
(matcher: string | RegExp) =>
matcher instanceof RegExp
? RxO.filter((ctx: InteractionContext) =>
matcher.test(selector(ctx) ?? ""),
)
: RxO.filter((ctx: InteractionContext) => selector(ctx) === matcher);
export const selectorStartsWith =
(selector: (data: InteractionContext) => string | undefined) =>
(prefix: string) =>
RxO.filter((ctx: InteractionContext) =>
(selector(ctx) ?? "").startsWith(prefix),
);
export const filterByCustomId = filterBySelector(
({ interaction }) => (interaction.data as any)?.custom_id,
);
export const customIdStartsWith = selectorStartsWith(
({ interaction }) => (interaction.data as any)?.custom_id,
);
export const filterByFocusedOption = filterBySelector(
({ focusedOption }) => focusedOption?.name,
);
export const focusedOptionStartsWith = selectorStartsWith(
({ focusedOption }) => focusedOption?.name,
);
export const filterByComponents =
(components: Exclude<Component, ActionRow>[]) =>
(source$: Observable<InteractionContext>) => {
const map = components
.filter(({ custom_id }) => !!custom_id)
.reduce((map, c) => map.set(c.custom_id!, c), Map<string, Component>());
return source$.pipe(
RxO.filter(({ interaction }) =>
map.has((interaction.data as any).custom_id || ""),
),
RxO.map(
(ctx) =>
[
ctx,
map.get((ctx.interaction.data as any).custom_id || "")!,
] as const,
),
);
};