workspace

This commit is contained in:
MapleLeaf
2021-12-29 13:19:46 -06:00
parent 3fa99f9ee2
commit 88e9919c8f
74 changed files with 237 additions and 2217 deletions

View File

@@ -0,0 +1,18 @@
{
"extends": ["./node_modules/@itsmapleleaf/configs/eslint"],
"ignorePatterns": [
"**/node_modules/**",
"**/coverage/**",
"**/dist/**",
"**/.vscode/**",
"**/docs/**"
],
"parserOptions": {
"project": "./tsconfig.json"
},
"rules": {
// this rule causes a bunch of error notifications to pop up when moving files around
// disabling this for now
"import/no-unused-modules": "off"
}
}

View File

@@ -0,0 +1,4 @@
node_modules
dist
coverage
pnpm-lock.yaml

View File

@@ -0,0 +1,37 @@
import type {
CamelCasedPropertiesDeep,
SnakeCasedPropertiesDeep,
} from "type-fest"
import { camelCaseDeep, snakeCaseDeep } from "./convert-object-property-case"
test("camelCaseDeep", () => {
const input = {
some_prop: {
some_deep_prop: "some_deep_value",
},
someOtherProp: "someOtherValue",
}
expect(camelCaseDeep(input)).toEqual<CamelCasedPropertiesDeep<typeof input>>({
someProp: {
someDeepProp: "some_deep_value",
},
someOtherProp: "someOtherValue",
})
})
test("snakeCaseDeep", () => {
const input = {
someProp: {
someDeepProp: "someDeepValue",
},
some_other_prop: "someOtherValue",
}
expect(snakeCaseDeep(input)).toEqual<SnakeCasedPropertiesDeep<typeof input>>({
some_prop: {
some_deep_prop: "someDeepValue",
},
some_other_prop: "someOtherValue",
})
})

View File

@@ -0,0 +1,34 @@
import { camelCase, isObject, snakeCase } from "lodash-es"
import type {
CamelCasedPropertiesDeep,
SnakeCasedPropertiesDeep,
} from "type-fest"
function convertKeyCaseDeep<Input, Output>(
input: Input,
convertKey: (key: string) => string,
): Output {
if (!isObject(input)) {
return input as unknown as Output
}
if (Array.isArray(input)) {
return input.map((item) =>
convertKeyCaseDeep(item, convertKey),
) as unknown as Output
}
const output: any = {}
for (const [key, value] of Object.entries(input)) {
output[convertKey(key)] = convertKeyCaseDeep(value, convertKey)
}
return output
}
export function camelCaseDeep<T>(input: T): CamelCasedPropertiesDeep<T> {
return convertKeyCaseDeep(input, camelCase)
}
export function snakeCaseDeep<T>(input: T): SnakeCasedPropertiesDeep<T> {
return convertKeyCaseDeep(input, snakeCase)
}

View File

@@ -0,0 +1,5 @@
import { raise } from "./raise.js"
export function getEnvironmentValue(name: string) {
return process.env[name] ?? raise(`Missing environment variable: ${name}`)
}

View File

@@ -0,0 +1,7 @@
/**
* for narrowing instance types with array.filter
*/
export const isInstanceOf =
<T>(Constructor: new (...args: any[]) => T) =>
(value: unknown): value is T =>
value instanceof Constructor

View File

@@ -0,0 +1,3 @@
export function last<T>(array: T[]): T | undefined {
return array[array.length - 1]
}

View File

@@ -0,0 +1,12 @@
import { inspect } from "node:util"
// eslint-disable-next-line import/no-unused-modules
export function logPretty(value: unknown) {
console.info(
inspect(value, {
// depth: Number.POSITIVE_INFINITY,
depth: 10,
colors: true,
}),
)
}

View File

@@ -0,0 +1,14 @@
// eslint-disable-next-line import/no-unused-modules
export function omit<Subject extends object, Key extends PropertyKey>(
subject: Subject,
keys: Key[],
// hack: using a conditional type preserves union types
): Subject extends any ? Omit<Subject, Key> : never {
const result: any = {}
for (const key in subject) {
if (!keys.includes(key as unknown as Key)) {
result[key] = subject[key]
}
}
return result
}

View File

@@ -0,0 +1,16 @@
import type { LoosePick, UnknownRecord } from "./types"
// eslint-disable-next-line import/no-unused-modules
export function pick<T, K extends keyof T | PropertyKey>(
object: T,
keys: K[],
): LoosePick<T, K> {
const result: any = {}
for (const key of keys) {
const value = (object as UnknownRecord)[key]
if (value !== undefined) {
result[key] = value
}
}
return result
}

View File

@@ -0,0 +1,15 @@
export function pruneNullishValues<T extends object>(
object: T,
): PruneNullishValues<T> {
const result: any = {}
for (const [key, value] of Object.entries(object)) {
if (value != undefined) {
result[key] = value
}
}
return result
}
type PruneNullishValues<T> = {
[Key in keyof T]: NonNullable<T[Key]>
}

View File

@@ -0,0 +1,5 @@
import { toError } from "./to-error.js"
export function raise(error: unknown): never {
throw toError(error)
}

View File

@@ -0,0 +1,10 @@
import { setTimeout } from "node:timers/promises"
import { toError } from "./to-error.js"
export async function rejectAfter(
timeMs: number,
error: unknown = `rejected after ${timeMs}ms`,
): Promise<never> {
await setTimeout(timeMs)
return Promise.reject(toError(error))
}

View File

@@ -0,0 +1,21 @@
import { setTimeout } from "node:timers/promises"
const maxTime = 500
const waitPeriod = 50
export async function retryWithTimeout<T>(
callback: () => Promise<T> | T,
): Promise<T> {
const startTime = Date.now()
// eslint-disable-next-line no-constant-condition
while (true) {
try {
return await callback()
} catch (error) {
if (Date.now() - startTime > maxTime) {
throw error
}
await setTimeout(waitPeriod)
}
}
}

View File

@@ -0,0 +1,3 @@
export function toError(value: unknown) {
return value instanceof Error ? value : new Error(String(value))
}

View File

@@ -0,0 +1,4 @@
/** A typesafe version of toUpperCase */
export function toUpper<S extends string>(string: S) {
return string.toUpperCase() as Uppercase<S>
}

View File

@@ -0,0 +1,12 @@
/* eslint-disable import/no-unused-modules */
export type MaybePromise<T> = T | Promise<T>
export type ValueOf<Type> = Type extends ReadonlyArray<infer Value>
? Value
: Type[keyof Type]
export type UnknownRecord = Record<PropertyKey, unknown>
export type LoosePick<Shape, Keys extends PropertyKey> = {
[Key in Keys]: Shape extends Record<Key, infer Value> ? Value : never
}

View File

@@ -0,0 +1,25 @@
import { inspect } from "node:util"
// eslint-disable-next-line import/no-unused-modules
export function withLoggedMethodCalls<T extends object>(value: T) {
return new Proxy(value as Record<string | symbol, unknown>, {
get(target, property) {
const value = target[property]
if (typeof value !== "function") {
return value
}
return (...values: any[]) => {
console.info(
`${String(property)}(${values
.map((value) =>
typeof value === "object" && value !== null
? value.constructor.name
: inspect(value, { colors: true }),
)
.join(", ")})`,
)
return value.apply(target, values)
}
},
}) as T
}

View File

@@ -0,0 +1,15 @@
/** @type {import('@jest/types').Config.InitialOptions} */
const config = {
transform: {
"^.+\\.[jt]sx?$": ["esbuild-jest", { format: "esm", sourcemap: true }],
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
moduleNameMapper: {
"^(\\.\\.?/.+)\\.jsx?$": "$1",
},
verbose: true,
cache: false,
coverageReporters: ["text", "text-summary", "html"],
coveragePathIgnorePatterns: ["discord-js-adapter", "test/setup-testing"],
}
export default config

View File

@@ -0,0 +1,65 @@
import type { ReactNode } from "react"
import type { ReacordInstance } from "./instance"
export type ComponentEvent = {
message: MessageInfo
channel: ChannelInfo
user: UserInfo
guild?: GuildInfo
reply(content?: ReactNode): ReacordInstance
ephemeralReply(content?: ReactNode): ReacordInstance
}
export type ChannelInfo = {
id: string
name?: string
topic?: string
nsfw?: boolean
lastMessageId?: string
ownerId?: string
parentId?: string
rateLimitPerUser?: number
}
export type MessageInfo = {
id: string
channelId: string
authorId: UserInfo
member?: GuildMemberInfo
content: string
timestamp: string
editedTimestamp?: string
tts: boolean
mentionEveryone: boolean
/** The IDs of mentioned users */
mentions: string[]
}
export type GuildInfo = {
id: string
name: string
member: GuildMemberInfo
}
export type GuildMemberInfo = {
id: string
nick?: string
displayName: string
avatarUrl?: string
displayAvatarUrl: string
roles: string[]
color: number
joinedAt?: string
premiumSince?: string
pending?: boolean
communicationDisabledUntil?: string
}
export type UserInfo = {
id: string
username: string
discriminator: string
tag: string
avatarUrl: string
accentColor?: number
}

View File

@@ -0,0 +1,47 @@
import type { ReactNode } from "react"
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import type { MessageOptions } from "../../internal/message"
import { Node } from "../../internal/node.js"
/**
* Props for an action row
* @category Components
*/
export type ActionRowProps = {
children?: ReactNode
}
/**
* An action row is a top-level container for message components.
*
* You don't need to use this; Reacord automatically creates action rows for you.
* But this can be useful if you want a specific layout.
*
* ```tsx
* // put buttons on two separate rows
* <ActionRow>
* <Button onClick={handleFirst}>First</Button>
* </ActionRow>
* <Button onClick={handleSecond}>Second</Button>
* ```
*
* @category Components
* @see https://discord.com/developers/docs/interactions/message-components#action-rows
*/
export function ActionRow(props: ActionRowProps) {
return (
<ReacordElement props={props} createNode={() => new ActionRowNode(props)}>
{props.children}
</ReacordElement>
)
}
class ActionRowNode extends Node<{}> {
override modifyMessageOptions(options: MessageOptions): void {
options.actionRows.push([])
for (const child of this.children) {
child.modifyMessageOptions(options)
}
}
}

View File

@@ -0,0 +1,50 @@
import { nanoid } from "nanoid"
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import type { ComponentInteraction } from "../../internal/interaction"
import type { MessageOptions } from "../../internal/message"
import { getNextActionRow } from "../../internal/message"
import { Node } from "../../internal/node.js"
import type { ComponentEvent } from "../component-event"
export type ButtonProps = {
label?: string
style?: "primary" | "secondary" | "success" | "danger"
disabled?: boolean
emoji?: string
onClick: (event: ButtonClickEvent) => void
}
export type ButtonClickEvent = ComponentEvent
export function Button(props: ButtonProps) {
return (
<ReacordElement props={props} createNode={() => new ButtonNode(props)} />
)
}
class ButtonNode extends Node<ButtonProps> {
private customId = nanoid()
override modifyMessageOptions(options: MessageOptions): void {
getNextActionRow(options).push({
type: "button",
customId: this.customId,
style: this.props.style ?? "secondary",
disabled: this.props.disabled,
emoji: this.props.emoji,
label: this.props.label,
})
}
override handleComponentInteraction(interaction: ComponentInteraction) {
if (
interaction.type === "button" &&
interaction.customId === this.customId
) {
this.props.onClick(interaction.event)
return true
}
return false
}
}

View File

@@ -0,0 +1,30 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options"
export type EmbedAuthorProps = {
name?: string
children?: string
url?: string
iconUrl?: string
}
export function EmbedAuthor(props: EmbedAuthorProps) {
return (
<ReacordElement
props={props}
createNode={() => new EmbedAuthorNode(props)}
/>
)
}
class EmbedAuthorNode extends EmbedChildNode<EmbedAuthorProps> {
override modifyEmbedOptions(options: EmbedOptions): void {
options.author = {
name: this.props.name ?? this.props.children ?? "",
url: this.props.url,
icon_url: this.props.iconUrl,
}
}
}

View File

@@ -0,0 +1,6 @@
import { Node } from "../../internal/node.js"
import type { EmbedOptions } from "./embed-options"
export abstract class EmbedChildNode<Props> extends Node<Props> {
abstract modifyEmbedOptions(options: EmbedOptions): void
}

View File

@@ -0,0 +1,31 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options"
export type EmbedFieldProps = {
name: string
value?: string
inline?: boolean
children?: string
}
export function EmbedField(props: EmbedFieldProps) {
return (
<ReacordElement
props={props}
createNode={() => new EmbedFieldNode(props)}
/>
)
}
class EmbedFieldNode extends EmbedChildNode<EmbedFieldProps> {
override modifyEmbedOptions(options: EmbedOptions): void {
options.fields ??= []
options.fields.push({
name: this.props.name,
value: this.props.value ?? this.props.children ?? "",
inline: this.props.inline,
})
}
}

View File

@@ -0,0 +1,32 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options"
export type EmbedFooterProps = {
text?: string
children?: string
iconUrl?: string
timestamp?: string | number | Date
}
export function EmbedFooter(props: EmbedFooterProps) {
return (
<ReacordElement
props={props}
createNode={() => new EmbedFooterNode(props)}
/>
)
}
class EmbedFooterNode extends EmbedChildNode<EmbedFooterProps> {
override modifyEmbedOptions(options: EmbedOptions): void {
options.footer = {
text: this.props.text ?? this.props.children ?? "",
icon_url: this.props.iconUrl,
}
options.timestamp = this.props.timestamp
? new Date(this.props.timestamp).toISOString()
: undefined
}
}

View File

@@ -0,0 +1,23 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options"
export type EmbedImageProps = {
url: string
}
export function EmbedImage(props: EmbedImageProps) {
return (
<ReacordElement
props={props}
createNode={() => new EmbedImageNode(props)}
/>
)
}
class EmbedImageNode extends EmbedChildNode<EmbedImageProps> {
override modifyEmbedOptions(options: EmbedOptions): void {
options.image = { url: this.props.url }
}
}

View File

@@ -0,0 +1,8 @@
import type { Except, SnakeCasedPropertiesDeep } from "type-fest"
import type { EmbedProps } from "./embed"
export type EmbedOptions = SnakeCasedPropertiesDeep<
Except<EmbedProps, "timestamp" | "children"> & {
timestamp?: string
}
>

View File

@@ -0,0 +1,23 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options"
export type EmbedThumbnailProps = {
url: string
}
export function EmbedThumbnail(props: EmbedThumbnailProps) {
return (
<ReacordElement
props={props}
createNode={() => new EmbedThumbnailNode(props)}
/>
)
}
class EmbedThumbnailNode extends EmbedChildNode<EmbedThumbnailProps> {
override modifyEmbedOptions(options: EmbedOptions): void {
options.thumbnail = { url: this.props.url }
}
}

View File

@@ -0,0 +1,25 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options"
export type EmbedTitleProps = {
children: string
url?: string
}
export function EmbedTitle(props: EmbedTitleProps) {
return (
<ReacordElement
props={props}
createNode={() => new EmbedTitleNode(props)}
/>
)
}
class EmbedTitleNode extends EmbedChildNode<EmbedTitleProps> {
override modifyEmbedOptions(options: EmbedOptions): void {
options.title = this.props.children
options.url = this.props.url
}
}

View File

@@ -0,0 +1,54 @@
import React from "react"
import { snakeCaseDeep } from "../../../helpers/convert-object-property-case"
import { omit } from "../../../helpers/omit"
import { ReacordElement } from "../../internal/element.js"
import type { MessageOptions } from "../../internal/message"
import { Node } from "../../internal/node.js"
import { TextNode } from "../../internal/text-node"
import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options"
export type EmbedProps = {
title?: string
description?: string
url?: string
color?: number
fields?: Array<{ name: string; value: string; inline?: boolean }>
author?: { name: string; url?: string; iconUrl?: string }
thumbnail?: { url: string }
image?: { url: string }
video?: { url: string }
footer?: { text: string; iconUrl?: string }
timestamp?: string | number | Date
children?: React.ReactNode
}
export function Embed(props: EmbedProps) {
return (
<ReacordElement props={props} createNode={() => new EmbedNode(props)}>
{props.children}
</ReacordElement>
)
}
class EmbedNode extends Node<EmbedProps> {
override modifyMessageOptions(options: MessageOptions): void {
const embed: EmbedOptions = {
...snakeCaseDeep(omit(this.props, ["children", "timestamp"])),
timestamp: this.props.timestamp
? new Date(this.props.timestamp).toISOString()
: undefined,
}
for (const child of this.children) {
if (child instanceof EmbedChildNode) {
child.modifyEmbedOptions(embed)
}
if (child instanceof TextNode) {
embed.description = (embed.description || "") + child.props
}
}
options.embeds.push(embed)
}
}

View File

@@ -0,0 +1,29 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js"
import type { MessageOptions } from "../../internal/message"
import { getNextActionRow } from "../../internal/message"
import { Node } from "../../internal/node.js"
export type LinkProps = {
label?: string
children?: string
emoji?: string
disabled?: boolean
url: string
}
export function Link(props: LinkProps) {
return <ReacordElement props={props} createNode={() => new LinkNode(props)} />
}
class LinkNode extends Node<LinkProps> {
override modifyMessageOptions(options: MessageOptions): void {
getNextActionRow(options).push({
type: "link",
disabled: this.props.disabled,
emoji: this.props.emoji,
label: this.props.label || this.props.children,
url: this.props.url,
})
}
}

View File

@@ -0,0 +1,14 @@
import type { MessageSelectOptionOptions } from "../../internal/message"
import { Node } from "../../internal/node"
import type { OptionProps } from "./option"
export class OptionNode extends Node<OptionProps> {
get options(): MessageSelectOptionOptions {
return {
label: this.props.children || this.props.label || this.props.value,
value: this.props.value,
description: this.props.description,
emoji: this.props.emoji,
}
}
}

View File

@@ -0,0 +1,17 @@
import React from "react"
import { ReacordElement } from "../../internal/element"
import { OptionNode } from "./option-node"
export type OptionProps = {
label?: string
children?: string
value: string
description?: string
emoji?: string
}
export function Option(props: OptionProps) {
return (
<ReacordElement props={props} createNode={() => new OptionNode(props)} />
)
}

View File

@@ -0,0 +1,90 @@
import { nanoid } from "nanoid"
import type { ReactNode } from "react"
import React from "react"
import { isInstanceOf } from "../../../helpers/is-instance-of"
import { ReacordElement } from "../../internal/element.js"
import type { ComponentInteraction } from "../../internal/interaction"
import type { ActionRow, MessageOptions } from "../../internal/message"
import { Node } from "../../internal/node.js"
import type { ComponentEvent } from "../component-event"
import { OptionNode } from "./option-node"
export type SelectProps = {
children?: ReactNode
value?: string
values?: string[]
placeholder?: string
multiple?: boolean
minValues?: number
maxValues?: number
disabled?: boolean
onChange?: (event: SelectChangeEvent) => void
onChangeValue?: (value: string, event: SelectChangeEvent) => void
onChangeMultiple?: (values: string[], event: SelectChangeEvent) => void
}
export type SelectChangeEvent = ComponentEvent & {
values: string[]
}
export function Select(props: SelectProps) {
return (
<ReacordElement props={props} createNode={() => new SelectNode(props)}>
{props.children}
</ReacordElement>
)
}
class SelectNode extends Node<SelectProps> {
readonly customId = nanoid()
override modifyMessageOptions(message: MessageOptions): void {
const actionRow: ActionRow = []
message.actionRows.push(actionRow)
const options = [...this.children]
.filter(isInstanceOf(OptionNode))
.map((node) => node.options)
const {
multiple,
value,
values,
minValues = 0,
maxValues = 25,
children,
onChange,
onChangeValue,
onChangeMultiple,
...props
} = this.props
actionRow.push({
...props,
type: "select",
customId: this.customId,
options,
values: [...(values || []), ...(value ? [value] : [])],
minValues: multiple ? minValues : undefined,
maxValues: multiple ? Math.max(minValues, maxValues) : undefined,
})
}
override handleComponentInteraction(
interaction: ComponentInteraction,
): boolean {
const isSelectInteraction =
interaction.type === "select" &&
interaction.customId === this.customId &&
!this.props.disabled
if (!isSelectInteraction) return false
this.props.onChange?.(interaction.event)
this.props.onChangeMultiple?.(interaction.event.values, interaction.event)
if (interaction.event.values[0]) {
this.props.onChangeValue?.(interaction.event.values[0], interaction.event)
}
return true
}
}

View File

@@ -0,0 +1,7 @@
import type { ReactNode } from "react"
export type ReacordInstance = {
render: (content: ReactNode) => void
deactivate: () => void
destroy: () => void
}

View File

@@ -0,0 +1,364 @@
/* eslint-disable class-methods-use-this */
import * as Discord from "discord.js"
import type { ReactNode } from "react"
import type { Except } from "type-fest"
import { pick } from "../../helpers/pick"
import { pruneNullishValues } from "../../helpers/prune-null-values"
import { raise } from "../../helpers/raise"
import { toUpper } from "../../helpers/to-upper"
import type { ComponentInteraction } from "../internal/interaction"
import type { Message, MessageOptions } from "../internal/message"
import { ChannelMessageRenderer } from "../internal/renderers/channel-message-renderer"
import { InteractionReplyRenderer } from "../internal/renderers/interaction-reply-renderer"
import type {
ChannelInfo,
GuildInfo,
GuildMemberInfo,
MessageInfo,
UserInfo,
} from "./component-event"
import type { ReacordInstance } from "./instance"
import type { ReacordConfig } from "./reacord"
import { Reacord } from "./reacord"
export class ReacordDiscordJs extends Reacord {
constructor(private client: Discord.Client, config: ReacordConfig = {}) {
super(config)
client.on("interactionCreate", (interaction) => {
if (interaction.isMessageComponent()) {
this.handleComponentInteraction(
this.createReacordComponentInteraction(interaction),
)
}
})
}
override send(
channelId: string,
initialContent?: React.ReactNode,
): ReacordInstance {
return this.createInstance(
this.createChannelRenderer(channelId),
initialContent,
)
}
override reply(
interaction: Discord.CommandInteraction,
initialContent?: React.ReactNode,
): ReacordInstance {
return this.createInstance(
this.createInteractionReplyRenderer(interaction),
initialContent,
)
}
override ephemeralReply(
interaction: Discord.CommandInteraction,
initialContent?: React.ReactNode,
): ReacordInstance {
return this.createInstance(
this.createEphemeralInteractionReplyRenderer(interaction),
initialContent,
)
}
private createChannelRenderer(channelId: string) {
return new ChannelMessageRenderer({
send: async (options) => {
const channel =
this.client.channels.cache.get(channelId) ??
(await this.client.channels.fetch(channelId)) ??
raise(`Channel ${channelId} not found`)
if (!channel.isText()) {
raise(`Channel ${channelId} is not a text channel`)
}
const message = await channel.send(getDiscordMessageOptions(options))
return createReacordMessage(message)
},
})
}
private createInteractionReplyRenderer(
interaction:
| Discord.CommandInteraction
| Discord.MessageComponentInteraction,
) {
return new InteractionReplyRenderer({
type: "command",
id: interaction.id,
reply: async (options) => {
const message = await interaction.reply({
...getDiscordMessageOptions(options),
fetchReply: true,
})
return createReacordMessage(message as Discord.Message)
},
followUp: async (options) => {
const message = await interaction.followUp({
...getDiscordMessageOptions(options),
fetchReply: true,
})
return createReacordMessage(message as Discord.Message)
},
})
}
private createEphemeralInteractionReplyRenderer(
interaction:
| Discord.CommandInteraction
| Discord.MessageComponentInteraction,
) {
return new InteractionReplyRenderer({
type: "command",
id: interaction.id,
reply: async (options) => {
await interaction.reply({
...getDiscordMessageOptions(options),
ephemeral: true,
})
return createEphemeralReacordMessage()
},
followUp: async (options) => {
await interaction.followUp({
...getDiscordMessageOptions(options),
ephemeral: true,
})
return createEphemeralReacordMessage()
},
})
}
private createReacordComponentInteraction(
interaction: Discord.MessageComponentInteraction,
): ComponentInteraction {
// todo please dear god clean this up
const channel: ChannelInfo = interaction.channel
? {
...pick(pruneNullishValues(interaction.channel), [
"topic",
"nsfw",
"lastMessageId",
"ownerId",
"parentId",
"rateLimitPerUser",
]),
id: interaction.channelId,
}
: raise("Non-channel interactions are not supported")
const message: MessageInfo =
interaction.message instanceof Discord.Message
? {
...pick(interaction.message, [
"id",
"channelId",
"authorId",
"content",
"tts",
"mentionEveryone",
]),
timestamp: new Date(
interaction.message.createdTimestamp,
).toISOString(),
editedTimestamp: interaction.message.editedTimestamp
? new Date(interaction.message.editedTimestamp).toISOString()
: undefined,
mentions: interaction.message.mentions.users.map((u) => u.id),
}
: raise("Message not found")
const member: GuildMemberInfo | undefined =
interaction.member instanceof Discord.GuildMember
? {
...pick(pruneNullishValues(interaction.member), [
"id",
"nick",
"displayName",
"avatarUrl",
"displayAvatarUrl",
"color",
"pending",
]),
displayName: interaction.member.displayName,
roles: [...interaction.member.roles.cache.map((role) => role.id)],
joinedAt: interaction.member.joinedAt?.toISOString(),
premiumSince: interaction.member.premiumSince?.toISOString(),
communicationDisabledUntil:
interaction.member.communicationDisabledUntil?.toISOString(),
}
: undefined
const guild: GuildInfo | undefined = interaction.guild
? {
...pick(pruneNullishValues(interaction.guild), ["id", "name"]),
member: member ?? raise("unexpected: member is undefined"),
}
: undefined
const user: UserInfo = {
...pick(pruneNullishValues(interaction.user), [
"id",
"username",
"discriminator",
"tag",
]),
avatarUrl: interaction.user.avatarURL()!,
accentColor: interaction.user.accentColor ?? undefined,
}
const baseProps: Except<ComponentInteraction, "type"> = {
id: interaction.id,
customId: interaction.customId,
update: async (options: MessageOptions) => {
await interaction.update(getDiscordMessageOptions(options))
},
deferUpdate: async () => {
if (interaction.replied || interaction.deferred) return
await interaction.deferUpdate()
},
reply: async (options) => {
const message = await interaction.reply({
...getDiscordMessageOptions(options),
fetchReply: true,
})
return createReacordMessage(message as Discord.Message)
},
followUp: async (options) => {
const message = await interaction.followUp({
...getDiscordMessageOptions(options),
fetchReply: true,
})
return createReacordMessage(message as Discord.Message)
},
event: {
channel,
message,
user,
guild,
reply: (content?: ReactNode) =>
this.createInstance(
this.createInteractionReplyRenderer(interaction),
content,
),
ephemeralReply: (content: ReactNode) =>
this.createInstance(
this.createEphemeralInteractionReplyRenderer(interaction),
content,
),
},
}
if (interaction.isButton()) {
return {
...baseProps,
type: "button",
}
}
if (interaction.isSelectMenu()) {
return {
...baseProps,
type: "select",
event: {
...baseProps.event,
values: interaction.values,
},
}
}
raise(`Unsupported component interaction type: ${interaction.type}`)
}
}
function createReacordMessage(message: Discord.Message): Message {
return {
edit: async (options) => {
await message.edit(getDiscordMessageOptions(options))
},
disableComponents: async () => {
for (const actionRow of message.components) {
for (const component of actionRow.components) {
component.setDisabled(true)
}
}
await message.edit({
components: message.components,
})
},
delete: async () => {
await message.delete()
},
}
}
function createEphemeralReacordMessage(): Message {
return {
edit: () => {
console.warn("Ephemeral messages can't be edited")
return Promise.resolve()
},
disableComponents: () => {
console.warn("Ephemeral messages can't be edited")
return Promise.resolve()
},
delete: () => {
console.warn("Ephemeral messages can't be deleted")
return Promise.resolve()
},
}
}
// TODO: this could be a part of the core library,
// and also handle some edge cases, e.g. empty messages
function getDiscordMessageOptions(
reacordOptions: MessageOptions,
): Discord.MessageOptions {
const options: Discord.MessageOptions = {
// eslint-disable-next-line unicorn/no-null
content: reacordOptions.content || null,
embeds: reacordOptions.embeds,
components: reacordOptions.actionRows.map((row) => ({
type: "ACTION_ROW",
components: row.map(
(component): Discord.MessageActionRowComponentOptions => {
if (component.type === "button") {
return {
type: "BUTTON",
customId: component.customId,
label: component.label ?? "",
style: toUpper(component.style ?? "secondary"),
disabled: component.disabled,
emoji: component.emoji,
}
}
if (component.type === "select") {
return {
...component,
type: "SELECT_MENU",
options: component.options.map((option) => ({
...option,
default: component.values?.includes(option.value),
})),
}
}
raise(`Unsupported component type: ${component.type}`)
},
),
})),
}
if (!options.content && !options.embeds?.length) {
options.content = "_ _"
}
return options
}

View File

@@ -0,0 +1,292 @@
/* eslint-disable class-methods-use-this */
/* eslint-disable require-await */
import { nanoid } from "nanoid"
import { nextTick } from "node:process"
import { promisify } from "node:util"
import type { ReactNode } from "react"
import { logPretty } from "../../helpers/log-pretty"
import { omit } from "../../helpers/omit"
import { raise } from "../../helpers/raise"
import type { Channel } from "../internal/channel"
import { Container } from "../internal/container"
import type {
ButtonInteraction,
CommandInteraction,
SelectInteraction,
} from "../internal/interaction"
import type {
Message,
MessageButtonOptions,
MessageOptions,
MessageSelectOptions,
} from "../internal/message"
import { ChannelMessageRenderer } from "../internal/renderers/channel-message-renderer"
import { InteractionReplyRenderer } from "../internal/renderers/interaction-reply-renderer"
import type {
ChannelInfo,
GuildInfo,
MessageInfo,
UserInfo,
} from "./component-event"
import type { ButtonClickEvent } from "./components/button"
import type { SelectChangeEvent } from "./components/select"
import type { ReacordInstance } from "./instance"
import { Reacord } from "./reacord"
const nextTickPromise = promisify(nextTick)
export class ReacordTester extends Reacord {
private messageContainer = new Container<TestMessage>()
constructor() {
super({ maxInstances: 2 })
}
get messages(): readonly TestMessage[] {
return [...this.messageContainer]
}
override send(): ReacordInstance {
return this.createInstance(
new ChannelMessageRenderer(new TestChannel(this.messageContainer)),
)
}
override reply(): ReacordInstance {
return this.createInstance(
new InteractionReplyRenderer(
new TestCommandInteraction(this.messageContainer),
),
)
}
override ephemeralReply(): ReacordInstance {
return this.reply()
}
async assertMessages(expected: ReturnType<this["sampleMessages"]>) {
await nextTickPromise()
expect(this.sampleMessages()).toEqual(expected)
}
async assertRender(
content: ReactNode,
expected: ReturnType<this["sampleMessages"]>,
) {
const instance = this.reply()
instance.render(content)
await this.assertMessages(expected)
instance.destroy()
}
logMessages() {
logPretty(this.sampleMessages())
}
sampleMessages() {
return this.messages.map((message) => ({
...message.options,
actionRows: message.options.actionRows.map((row) =>
row.map((component) =>
omit(component, ["customId", "onClick", "onSelect", "onSelectValue"]),
),
),
}))
}
findButtonByLabel(label: string) {
for (const message of this.messageContainer) {
for (const component of message.options.actionRows.flat()) {
if (component.type === "button" && component.label === label) {
return this.createButtonActions(component, message)
}
}
}
raise(`Couldn't find button with label "${label}"`)
}
findSelectByPlaceholder(placeholder: string) {
for (const message of this.messageContainer) {
for (const component of message.options.actionRows.flat()) {
if (
component.type === "select" &&
component.placeholder === placeholder
) {
return this.createSelectActions(component, message)
}
}
}
raise(`Couldn't find select with placeholder "${placeholder}"`)
}
createMessage(options: MessageOptions) {
return new TestMessage(options, this.messageContainer)
}
private createButtonActions(
button: MessageButtonOptions,
message: TestMessage,
) {
return {
click: () => {
this.handleComponentInteraction(
new TestButtonInteraction(button.customId, message, this),
)
},
}
}
private createSelectActions(
component: MessageSelectOptions,
message: TestMessage,
) {
return {
select: (...values: string[]) => {
this.handleComponentInteraction(
new TestSelectInteraction(component.customId, message, values, this),
)
},
}
}
}
class TestMessage implements Message {
constructor(
public options: MessageOptions,
private container: Container<TestMessage>,
) {
container.add(this)
}
async edit(options: MessageOptions): Promise<void> {
this.options = options
}
async disableComponents(): Promise<void> {
for (const row of this.options.actionRows) {
for (const action of row) {
if (action.type === "button") {
action.disabled = true
}
}
}
}
async delete(): Promise<void> {
this.container.remove(this)
}
}
class TestCommandInteraction implements CommandInteraction {
readonly type = "command"
readonly id = "test-command-interaction"
readonly channelId = "test-channel-id"
constructor(private messageContainer: Container<TestMessage>) {}
reply(messageOptions: MessageOptions): Promise<Message> {
return Promise.resolve(
new TestMessage(messageOptions, this.messageContainer),
)
}
followUp(messageOptions: MessageOptions): Promise<Message> {
return Promise.resolve(
new TestMessage(messageOptions, this.messageContainer),
)
}
}
class TestInteraction {
readonly id = nanoid()
readonly channelId = "test-channel-id"
constructor(
readonly customId: string,
readonly message: TestMessage,
private tester: ReacordTester,
) {}
async update(options: MessageOptions): Promise<void> {
this.message.options = options
}
async deferUpdate(): Promise<void> {}
async reply(messageOptions: MessageOptions): Promise<Message> {
return this.tester.createMessage(messageOptions)
}
async followUp(messageOptions: MessageOptions): Promise<Message> {
return this.tester.createMessage(messageOptions)
}
}
class TestButtonInteraction
extends TestInteraction
implements ButtonInteraction
{
readonly type = "button"
readonly event: ButtonClickEvent
constructor(customId: string, message: TestMessage, tester: ReacordTester) {
super(customId, message, tester)
this.event = new TestButtonClickEvent(tester)
}
}
class TestSelectInteraction
extends TestInteraction
implements SelectInteraction
{
readonly type = "select"
readonly event: SelectChangeEvent
constructor(
customId: string,
message: TestMessage,
readonly values: string[],
tester: ReacordTester,
) {
super(customId, message, tester)
this.event = new TestSelectChangeEvent(values, tester)
}
}
class TestComponentEvent {
constructor(private tester: ReacordTester) {}
message: MessageInfo = {} as any // todo
channel: ChannelInfo = {} as any // todo
user: UserInfo = {} as any // todo
guild: GuildInfo = {} as any // todo
reply(content?: ReactNode): ReacordInstance {
return this.tester.reply()
}
ephemeralReply(content?: ReactNode): ReacordInstance {
return this.tester.ephemeralReply()
}
}
class TestButtonClickEvent
extends TestComponentEvent
implements ButtonClickEvent {}
class TestSelectChangeEvent
extends TestComponentEvent
implements SelectChangeEvent
{
constructor(readonly values: string[], tester: ReacordTester) {
super(tester)
}
}
class TestChannel implements Channel {
constructor(private messageContainer: Container<TestMessage>) {}
async send(messageOptions: MessageOptions): Promise<Message> {
return new TestMessage(messageOptions, this.messageContainer)
}
}

View File

@@ -0,0 +1,69 @@
import type { ReactNode } from "react"
import type { ComponentInteraction } from "../internal/interaction"
import { reconciler } from "../internal/reconciler.js"
import type { Renderer } from "../internal/renderers/renderer"
import type { ReacordInstance } from "./instance"
export type ReacordConfig = {
/**
* The max number of active instances.
* When this limit is exceeded, the oldest instances will be disabled.
*/
maxInstances?: number
}
export type ComponentInteractionListener = (
interaction: ComponentInteraction,
) => void
export abstract class Reacord {
private renderers: Renderer[] = []
constructor(private readonly config: ReacordConfig = {}) {}
abstract send(...args: unknown[]): ReacordInstance
abstract reply(...args: unknown[]): ReacordInstance
abstract ephemeralReply(...args: unknown[]): ReacordInstance
protected handleComponentInteraction(interaction: ComponentInteraction) {
for (const renderer of this.renderers) {
if (renderer.handleComponentInteraction(interaction)) return
}
}
private get maxInstances() {
return this.config.maxInstances ?? 50
}
protected createInstance(renderer: Renderer, initialContent?: ReactNode) {
if (this.renderers.length > this.maxInstances) {
this.deactivate(this.renderers[0]!)
}
this.renderers.push(renderer)
const container = reconciler.createContainer(renderer, 0, false, {})
if (initialContent !== undefined) {
reconciler.updateContainer(initialContent, container)
}
return {
render: (content: ReactNode) => {
reconciler.updateContainer(content, container)
},
deactivate: () => {
this.deactivate(renderer)
},
destroy: () => {
this.renderers = this.renderers.filter((it) => it !== renderer)
renderer.destroy()
},
}
}
private deactivate(renderer: Renderer) {
this.renderers = this.renderers.filter((it) => it !== renderer)
renderer.deactivate()
}
}

View File

@@ -0,0 +1,5 @@
import type { Message, MessageOptions } from "./message"
export type Channel = {
send(message: MessageOptions): Promise<Message>
}

View File

@@ -0,0 +1,27 @@
export class Container<T> {
private items: T[] = []
add(...items: T[]) {
this.items.push(...items)
}
addBefore(item: T, before: T) {
let index = this.items.indexOf(before)
if (index === -1) {
index = this.items.length
}
this.items.splice(index, 0, item)
}
remove(toRemove: T) {
this.items = this.items.filter((item) => item !== toRemove)
}
clear() {
this.items = []
}
[Symbol.iterator]() {
return this.items[Symbol.iterator]()
}
}

View File

@@ -0,0 +1,11 @@
import type { ReactNode } from "react"
import React from "react"
import type { Node } from "./node"
export function ReacordElement<Props>(props: {
props: Props
createNode: () => Node<Props>
children?: ReactNode
}) {
return React.createElement("reacord-element", props)
}

View File

@@ -0,0 +1,35 @@
import type { ComponentEvent } from "../core/component-event"
import type { ButtonClickEvent, SelectChangeEvent } from "../main"
import type { Message, MessageOptions } from "./message"
export type Interaction = CommandInteraction | ComponentInteraction
export type ComponentInteraction = ButtonInteraction | SelectInteraction
export type CommandInteraction = BaseInteraction<"command">
export type ButtonInteraction = BaseComponentInteraction<
"button",
ButtonClickEvent
>
export type SelectInteraction = BaseComponentInteraction<
"select",
SelectChangeEvent
>
export type BaseInteraction<Type extends string> = {
type: Type
id: string
reply(messageOptions: MessageOptions): Promise<Message>
followUp(messageOptions: MessageOptions): Promise<Message>
}
export type BaseComponentInteraction<
Type extends string,
Event extends ComponentEvent,
> = BaseInteraction<Type> & {
event: Event
customId: string
update(options: MessageOptions): Promise<void>
deferUpdate(): Promise<void>
}

View File

@@ -0,0 +1,24 @@
export class LimitedCollection<T> {
private items: T[] = []
constructor(private readonly size: number) {}
add(item: T) {
if (this.items.length >= this.size) {
this.items.shift()
}
this.items.push(item)
}
has(item: T) {
return this.items.includes(item)
}
values(): readonly T[] {
return this.items
}
[Symbol.iterator]() {
return this.items[Symbol.iterator]()
}
}

View File

@@ -0,0 +1,63 @@
import type { Except } from "type-fest"
import { last } from "../../helpers/last"
import type { EmbedOptions } from "../core/components/embed-options"
import type { SelectProps } from "../core/components/select"
export type MessageOptions = {
content: string
embeds: EmbedOptions[]
actionRows: ActionRow[]
}
export type ActionRow = Array<
MessageButtonOptions | MessageLinkOptions | MessageSelectOptions
>
export type MessageButtonOptions = {
type: "button"
customId: string
label?: string
style?: "primary" | "secondary" | "success" | "danger"
disabled?: boolean
emoji?: string
}
export type MessageLinkOptions = {
type: "link"
url: string
label?: string
emoji?: string
disabled?: boolean
}
export type MessageSelectOptions = Except<SelectProps, "children" | "value"> & {
type: "select"
customId: string
options: MessageSelectOptionOptions[]
}
export type MessageSelectOptionOptions = {
label: string
value: string
description?: string
emoji?: string
}
export type Message = {
edit(options: MessageOptions): Promise<void>
delete(): Promise<void>
disableComponents(): Promise<void>
}
export function getNextActionRow(options: MessageOptions): ActionRow {
let actionRow = last(options.actionRows)
if (
actionRow == undefined ||
actionRow.length >= 5 ||
actionRow[0]?.type === "select"
) {
actionRow = []
options.actionRows.push(actionRow)
}
return actionRow
}

View File

@@ -0,0 +1,16 @@
/* eslint-disable class-methods-use-this */
import { Container } from "./container.js"
import type { ComponentInteraction } from "./interaction"
import type { MessageOptions } from "./message"
export abstract class Node<Props> {
readonly children = new Container<Node<unknown>>()
constructor(public props: Props) {}
modifyMessageOptions(options: MessageOptions) {}
handleComponentInteraction(interaction: ComponentInteraction): boolean {
return false
}
}

View File

@@ -0,0 +1,102 @@
import type { HostConfig } from "react-reconciler"
import ReactReconciler from "react-reconciler"
import { raise } from "../../helpers/raise.js"
import { Node } from "./node.js"
import type { Renderer } from "./renderers/renderer"
import { TextNode } from "./text-node.js"
const config: HostConfig<
string, // Type,
Record<string, unknown>, // Props,
Renderer, // Container,
Node<unknown>, // Instance,
TextNode, // TextInstance,
never, // SuspenseInstance,
never, // HydratableInstance,
never, // PublicInstance,
never, // HostContext,
true, // UpdatePayload,
never, // ChildSet,
number, // TimeoutHandle,
number // NoTimeout,
> = {
// config
now: Date.now,
supportsMutation: true,
supportsPersistence: false,
supportsHydration: false,
isPrimaryRenderer: true,
scheduleTimeout: global.setTimeout,
cancelTimeout: global.clearTimeout,
noTimeout: -1,
// eslint-disable-next-line unicorn/no-null
getRootHostContext: () => null,
getChildHostContext: (parentContext) => parentContext,
createInstance: (type, props) => {
if (type !== "reacord-element") {
raise(`Unknown element type: ${type}`)
}
if (typeof props.createNode !== "function") {
raise(`Missing createNode function`)
}
const node = props.createNode(props.props)
if (!(node instanceof Node)) {
raise(`createNode function did not return a Node`)
}
return node
},
createTextInstance: (text) => new TextNode(text),
shouldSetTextContent: () => false,
clearContainer: (renderer) => {
renderer.nodes.clear()
},
appendChildToContainer: (renderer, child) => {
renderer.nodes.add(child)
},
removeChildFromContainer: (renderer, child) => {
renderer.nodes.remove(child)
},
insertInContainerBefore: (renderer, child, before) => {
renderer.nodes.addBefore(child, before)
},
appendInitialChild: (parent, child) => {
parent.children.add(child)
},
appendChild: (parent, child) => {
parent.children.add(child)
},
removeChild: (parent, child) => {
parent.children.remove(child)
},
insertBefore: (parent, child, before) => {
parent.children.addBefore(child, before)
},
prepareUpdate: () => true,
commitUpdate: (node, payload, type, oldProps, newProps) => {
node.props = newProps.props
},
commitTextUpdate: (node, oldText, newText) => {
node.props = newText
},
// eslint-disable-next-line unicorn/no-null
prepareForCommit: () => null,
resetAfterCommit: (renderer) => {
renderer.render()
},
preparePortalMount: () => raise("Portals are not supported"),
getPublicInstance: () => raise("Refs are currently not supported"),
finalizeInitialChildren: () => false,
}
export const reconciler = ReactReconciler(config)

View File

@@ -0,0 +1,13 @@
import type { Channel } from "../channel"
import type { Message, MessageOptions } from "../message"
import { Renderer } from "./renderer"
export class ChannelMessageRenderer extends Renderer {
constructor(private channel: Channel) {
super()
}
protected createMessage(options: MessageOptions): Promise<Message> {
return this.channel.send(options)
}
}

View File

@@ -0,0 +1,22 @@
import type { Interaction } from "../interaction"
import type { Message, MessageOptions } from "../message"
import { Renderer } from "./renderer"
// keep track of interaction ids which have replies,
// so we know whether to call reply() or followUp()
const repliedInteractionIds = new Set<string>()
export class InteractionReplyRenderer extends Renderer {
constructor(private interaction: Interaction) {
super()
}
protected createMessage(options: MessageOptions): Promise<Message> {
if (repliedInteractionIds.has(this.interaction.id)) {
return this.interaction.followUp(options)
}
repliedInteractionIds.add(this.interaction.id)
return this.interaction.reply(options)
}
}

View File

@@ -0,0 +1,109 @@
import { Subject } from "rxjs"
import { concatMap } from "rxjs/operators"
import { Container } from "../container.js"
import type { ComponentInteraction } from "../interaction"
import type { Message, MessageOptions } from "../message"
import type { Node } from "../node.js"
type UpdatePayload =
| { action: "update" | "deactivate"; options: MessageOptions }
| { action: "deferUpdate"; interaction: ComponentInteraction }
| { action: "destroy" }
export abstract class Renderer {
readonly nodes = new Container<Node<unknown>>()
private componentInteraction?: ComponentInteraction
private message?: Message
private active = true
private updates = new Subject<UpdatePayload>()
private updateSubscription = this.updates
.pipe(concatMap((payload) => this.updateMessage(payload)))
.subscribe({ error: console.error })
render() {
if (!this.active) {
console.warn("Attempted to update a deactivated message")
return
}
this.updates.next({
options: this.getMessageOptions(),
action: "update",
})
}
deactivate() {
this.active = false
this.updates.next({
options: this.getMessageOptions(),
action: "deactivate",
})
}
destroy() {
this.active = false
this.updates.next({ action: "destroy" })
}
handleComponentInteraction(interaction: ComponentInteraction) {
this.componentInteraction = interaction
setTimeout(() => {
this.updates.next({ action: "deferUpdate", interaction })
}, 500)
for (const node of this.nodes) {
if (node.handleComponentInteraction(interaction)) {
return true
}
}
}
protected abstract createMessage(options: MessageOptions): Promise<Message>
private getMessageOptions(): MessageOptions {
const options: MessageOptions = {
content: "",
embeds: [],
actionRows: [],
}
for (const node of this.nodes) {
node.modifyMessageOptions(options)
}
return options
}
private async updateMessage(payload: UpdatePayload) {
if (payload.action === "destroy") {
this.updateSubscription.unsubscribe()
await this.message?.delete()
return
}
if (payload.action === "deactivate") {
this.updateSubscription.unsubscribe()
await this.message?.disableComponents()
return
}
if (payload.action === "deferUpdate") {
await payload.interaction.deferUpdate()
return
}
if (this.componentInteraction) {
const promise = this.componentInteraction.update(payload.options)
this.componentInteraction = undefined
await promise
return
}
if (this.message) {
await this.message.edit(payload.options)
return
}
this.message = await this.createMessage(payload.options)
}
}

View File

@@ -0,0 +1,8 @@
import type { MessageOptions } from "./message"
import { Node } from "./node.js"
export class TextNode extends Node<string> {
override modifyMessageOptions(options: MessageOptions) {
options.content = options.content + this.props
}
}

View File

@@ -0,0 +1,20 @@
export class Timeout {
private timeoutId?: NodeJS.Timeout
constructor(
private readonly time: number,
private readonly callback: () => void,
) {}
run() {
this.cancel()
this.timeoutId = setTimeout(this.callback, this.time)
}
cancel() {
if (this.timeoutId) {
clearTimeout(this.timeoutId)
this.timeoutId = undefined
}
}
}

View File

@@ -0,0 +1,17 @@
export * from "./core/component-event"
export * from "./core/components/action-row"
export * from "./core/components/button"
export * from "./core/components/embed"
export * from "./core/components/embed-author"
export * from "./core/components/embed-field"
export * from "./core/components/embed-footer"
export * from "./core/components/embed-image"
export * from "./core/components/embed-thumbnail"
export * from "./core/components/embed-title"
export * from "./core/components/link"
export * from "./core/components/option"
export * from "./core/components/select"
export * from "./core/instance"
export * from "./core/reacord"
export * from "./core/reacord-discord-js"
export * from "./core/reacord-tester"

View File

@@ -0,0 +1,78 @@
{
"name": "reacord",
"type": "module",
"description": "send reactive discord messages using react components ⚛",
"version": "0.0.0",
"types": "./dist/main.d.ts",
"files": [
"dist"
],
"exports": {
"import": "./dist/main.js",
"require": "./dist/main.cjs"
},
"scripts": {
"build": "tsup-node library/main.ts --target node16 --format cjs,esm --dts --sourcemap",
"build-watch": "pnpm build -- --watch",
"lint": "eslint --ext js,ts,tsx .",
"lint-fix": "pnpm lint -- --fix",
"format": "prettier --write .",
"test": "node --experimental-vm-modules --no-warnings ./node_modules/jest/bin/jest.js --colors",
"test-watch": "pnpm test -- --watch",
"coverage": "pnpm test -- --coverage",
"typecheck": "tsc --noEmit",
"playground": "nodemon --exec esmo --ext ts,tsx ./playground/main.tsx"
},
"dependencies": {
"@types/node": "*",
"@types/react": "*",
"@types/react-reconciler": "^0.26.4",
"nanoid": "^3.1.30",
"react-reconciler": "^0.26.2",
"rxjs": "^7.5.1"
},
"peerDependencies": {
"discord.js": "^13.3",
"react": ">=17"
},
"peerDependenciesMeta": {
"discord.js": {
"optional": true
}
},
"devDependencies": {
"@itsmapleleaf/configs": "^1.1.2",
"@jest/globals": "^27.4.4",
"@types/jest": "^27.0.3",
"@types/lodash-es": "^4.17.5",
"@typescript-eslint/eslint-plugin": "^5.8.1",
"@typescript-eslint/parser": "^5.8.1",
"c8": "^7.10.0",
"discord.js": "^13.4.0",
"dotenv": "^10.0.0",
"esbuild": "latest",
"esbuild-jest": "^0.5.0",
"eslint": "^8.5.0",
"eslint-config-prettier": "^8.3.0",
"eslint-import-resolver-typescript": "^2.5.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-react": "^7.28.0",
"eslint-plugin-react-hooks": "^4.3.0",
"eslint-plugin-unicorn": "^39.0.0",
"esmo": "^0.13.0",
"jest": "^27.4.5",
"lodash-es": "^4.17.21",
"nodemon": "^2.0.15",
"prettier": "^2.5.1",
"pretty-ms": "^7.0.1",
"react": "^17.0.2",
"tsup": "^5.11.9",
"type-fest": "^2.8.0",
"typescript": "^4.5.4"
},
"resolutions": {
"esbuild": "latest"
},
"prettier": "@itsmapleleaf/configs/prettier"
}

View File

@@ -0,0 +1,38 @@
import type { Client, CommandInteraction } from "discord.js"
type Command = {
name: string
description: string
run: (interaction: CommandInteraction) => unknown
}
export function createCommandHandler(client: Client, commands: Command[]) {
client.on("ready", async () => {
for (const command of commands) {
for (const guild of client.guilds.cache.values()) {
await client.application?.commands.create(
{
name: command.name,
description: command.description,
},
guild.id,
)
}
}
})
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return
const command = commands.find(
(command) => command.name === interaction.commandName,
)
if (command) {
try {
await command.run(interaction)
} catch (error) {
console.error(error)
}
}
})
}

View File

@@ -0,0 +1,35 @@
import * as React from "react"
import { Button, Embed, EmbedField, EmbedTitle } from "../library/main"
export function Counter(props: { onDeactivate: () => void }) {
const [count, setCount] = React.useState(0)
const [embedVisible, setEmbedVisible] = React.useState(false)
return (
<>
this button was clicked {count} times
{embedVisible && (
<Embed>
<EmbedTitle>the counter</EmbedTitle>
{count > 0 && (
<EmbedField name="is it even?">
{count % 2 === 0 ? "yes" : "no"}
</EmbedField>
)}
</Embed>
)}
{embedVisible && (
<Button label="hide embed" onClick={() => setEmbedVisible(false)} />
)}
<Button
style="primary"
label="clicc"
onClick={() => setCount(count + 1)}
/>
{!embedVisible && (
<Button label="show embed" onClick={() => setEmbedVisible(true)} />
)}
<Button style="danger" label="deactivate" onClick={props.onDeactivate} />
</>
)
}

View File

@@ -0,0 +1,31 @@
import React, { useState } from "react"
import { Button, Option, Select } from "../library/main"
export function FruitSelect() {
const [value, setValue] = useState<string>()
const [finalChoice, setFinalChoice] = useState<string>()
if (finalChoice) {
return <>you chose {finalChoice}</>
}
return (
<>
{"_ _"}
<Select
placeholder="choose a fruit"
value={value}
onChangeValue={setValue}
>
<Option value="🍎" />
<Option value="🍌" />
<Option value="🍒" />
</Select>
<Button
label="confirm"
disabled={value == undefined}
onClick={() => setFinalChoice(value)}
/>
</>
)
}

View File

@@ -0,0 +1,90 @@
import { Client } from "discord.js"
import "dotenv/config"
import React from "react"
import { Button, ReacordDiscordJs } from "../library/main"
import { createCommandHandler } from "./command-handler"
import { Counter } from "./counter"
import { FruitSelect } from "./fruit-select"
const client = new Client({
intents: ["GUILDS"],
})
const reacord = new ReacordDiscordJs(client)
client.on("ready", () => {
console.info("ready 💖")
// const now = new Date()
// function UptimeCounter() {
// const [uptime, setUptime] = React.useState(0)
// React.useEffect(() => {
// const interval = setInterval(() => {
// setUptime(Date.now() - now.getTime())
// }, 5000)
// return () => clearInterval(interval)
// }, [])
// return (
// <Embed>this bot has been running for {prettyMilliseconds(uptime)}</Embed>
// )
// }
// reacord.send("671787605624487941", <UptimeCounter />)
})
createCommandHandler(client, [
{
name: "button",
description: "it's a button",
run: (interaction) => {
reacord.reply(
interaction,
<Button label="clic" onClick={() => console.info("was clic")} />,
)
},
},
{
name: "counter",
description: "shows a counter button",
run: (interaction) => {
const reply = reacord.reply(interaction)
reply.render(<Counter onDeactivate={() => reply.destroy()} />)
},
},
{
name: "select",
description: "shows a select",
run: (interaction) => {
reacord.reply(interaction, <FruitSelect />)
},
},
{
name: "ephemeral-button",
description: "button which shows ephemeral messages",
run: (interaction) => {
reacord.reply(
interaction,
<>
<Button
label="public clic"
onClick={(event) =>
reacord.reply(
interaction,
`${event.guild?.member.displayName} clic`,
)
}
/>
<Button
label="clic"
onClick={(event) => event.ephemeralReply("you clic")}
/>
</>,
)
},
},
])
await client.login(process.env.TEST_BOT_TOKEN)

View File

@@ -0,0 +1,40 @@
import React from "react"
import { ReacordTester } from "../library/core/reacord-tester"
import { ActionRow, Button, Select } from "../library/main"
const testing = new ReacordTester()
test("action row", async () => {
await testing.assertRender(
<>
<Button label="outside button" onClick={() => {}} />
<ActionRow>
<Button label="button inside action row" onClick={() => {}} />
</ActionRow>
<Select />
<Button label="last row 1" onClick={() => {}} />
<Button label="last row 2" onClick={() => {}} />
</>,
[
{
content: "",
embeds: [],
actionRows: [
[{ type: "button", style: "secondary", label: "outside button" }],
[
{
type: "button",
style: "secondary",
label: "button inside action row",
},
],
[{ type: "select", options: [], values: [] }],
[
{ type: "button", style: "secondary", label: "last row 1" },
{ type: "button", style: "secondary", label: "last row 2" },
],
],
},
],
)
})

View File

@@ -0,0 +1,2 @@
test.todo("channel message renderer")
export {}

View File

@@ -0,0 +1,2 @@
test.todo("discord js integration")
export {}

View File

@@ -0,0 +1,274 @@
import React from "react"
import { ReacordTester } from "../library/core/reacord-tester"
import {
Embed,
EmbedAuthor,
EmbedField,
EmbedFooter,
EmbedImage,
EmbedThumbnail,
EmbedTitle,
} from "../library/main"
const testing = new ReacordTester()
test("kitchen sink", async () => {
const now = new Date()
await testing.assertRender(
<>
<Embed color={0xfe_ee_ef}>
<EmbedAuthor name="author" iconUrl="https://example.com/author.png" />
<EmbedTitle>title text</EmbedTitle>
description text
<EmbedThumbnail url="https://example.com/thumbnail.png" />
<EmbedImage url="https://example.com/image.png" />
<EmbedField name="field name" value="field value" inline />
<EmbedField name="block field" value="block field value" />
<EmbedFooter
text="footer text"
iconUrl="https://example.com/footer.png"
timestamp={now}
/>
</Embed>
</>,
[
{
actionRows: [],
content: "",
embeds: [
{
description: "description text",
author: {
icon_url: "https://example.com/author.png",
name: "author",
},
color: 0xfe_ee_ef,
fields: [
{
inline: true,
name: "field name",
value: "field value",
},
{
name: "block field",
value: "block field value",
},
],
footer: {
icon_url: "https://example.com/footer.png",
text: "footer text",
},
image: {
url: "https://example.com/image.png",
},
thumbnail: {
url: "https://example.com/thumbnail.png",
},
timestamp: now.toISOString(),
title: "title text",
},
],
},
],
)
})
test("author variants", async () => {
await testing.assertRender(
<>
<Embed>
<EmbedAuthor iconUrl="https://example.com/author.png">
author name
</EmbedAuthor>
</Embed>
<Embed>
<EmbedAuthor iconUrl="https://example.com/author.png" />
</Embed>
</>,
[
{
content: "",
actionRows: [],
embeds: [
{
author: {
icon_url: "https://example.com/author.png",
name: "author name",
},
},
{
author: {
icon_url: "https://example.com/author.png",
name: "",
},
},
],
},
],
)
})
test("field variants", async () => {
await testing.assertRender(
<>
<Embed>
<EmbedField name="field name" value="field value" />
<EmbedField name="field name" value="field value" inline />
<EmbedField name="field name" inline>
field value
</EmbedField>
<EmbedField name="field name" />
</Embed>
</>,
[
{
content: "",
actionRows: [],
embeds: [
{
fields: [
{
name: "field name",
value: "field value",
},
{
inline: true,
name: "field name",
value: "field value",
},
{
inline: true,
name: "field name",
value: "field value",
},
{
name: "field name",
value: "",
},
],
},
],
},
],
)
})
test("footer variants", async () => {
const now = new Date()
await testing.assertRender(
<>
<Embed>
<EmbedFooter text="footer text" />
</Embed>
<Embed>
<EmbedFooter
text="footer text"
iconUrl="https://example.com/footer.png"
/>
</Embed>
<Embed>
<EmbedFooter timestamp={now}>footer text</EmbedFooter>
</Embed>
<Embed>
<EmbedFooter iconUrl="https://example.com/footer.png" timestamp={now} />
</Embed>
</>,
[
{
content: "",
actionRows: [],
embeds: [
{
footer: {
text: "footer text",
},
},
{
footer: {
icon_url: "https://example.com/footer.png",
text: "footer text",
},
},
{
footer: {
text: "footer text",
},
timestamp: now.toISOString(),
},
{
footer: {
icon_url: "https://example.com/footer.png",
text: "",
},
timestamp: now.toISOString(),
},
],
},
],
)
})
test("embed props", async () => {
const now = new Date()
await testing.assertRender(
<Embed
title="title text"
description="description text"
url="https://example.com/"
color={0xfe_ee_ef}
timestamp={now}
author={{
name: "author name",
url: "https://example.com/author",
iconUrl: "https://example.com/author.png",
}}
thumbnail={{
url: "https://example.com/thumbnail.png",
}}
image={{
url: "https://example.com/image.png",
}}
footer={{
text: "footer text",
iconUrl: "https://example.com/footer.png",
}}
fields={[
{ name: "field name", value: "field value", inline: true },
{ name: "block field", value: "block field value" },
]}
/>,
[
{
content: "",
actionRows: [],
embeds: [
{
title: "title text",
description: "description text",
url: "https://example.com/",
color: 0xfe_ee_ef,
timestamp: now.toISOString(),
author: {
name: "author name",
url: "https://example.com/author",
icon_url: "https://example.com/author.png",
},
thumbnail: { url: "https://example.com/thumbnail.png" },
image: { url: "https://example.com/image.png" },
footer: {
text: "footer text",
icon_url: "https://example.com/footer.png",
},
fields: [
{ name: "field name", value: "field value", inline: true },
{ name: "block field", value: "block field value" },
],
},
],
},
],
)
})

View File

@@ -0,0 +1,2 @@
test.todo("ephemeral reply")
export {}

View File

@@ -0,0 +1,3 @@
test.todo("button onClick")
test.todo("select onChange")
export {}

View File

@@ -0,0 +1,41 @@
import React from "react"
import { ReacordTester } from "../library/core/reacord-tester"
import { Link } from "../library/main"
const tester = new ReacordTester()
test("link", async () => {
await tester.assertRender(
<>
<Link url="https://example.com/">link text</Link>
<Link label="link text" url="https://example.com/" />
<Link label="link text" url="https://example.com/" disabled />
</>,
[
{
content: "",
embeds: [],
actionRows: [
[
{
type: "link",
url: "https://example.com/",
label: "link text",
},
{
type: "link",
url: "https://example.com/",
label: "link text",
},
{
type: "link",
url: "https://example.com/",
label: "link text",
disabled: true,
},
],
],
},
],
)
})

View File

@@ -0,0 +1,309 @@
import * as React from "react"
import {
Button,
Embed,
EmbedField,
EmbedTitle,
ReacordTester,
} from "../library/main"
test("rendering behavior", async () => {
const tester = new ReacordTester()
const reply = tester.reply()
reply.render(<KitchenSinkCounter onDeactivate={() => reply.deactivate()} />)
await tester.assertMessages([
{
content: "count: 0",
embeds: [],
actionRows: [
[
{
type: "button",
style: "primary",
label: "clicc",
},
{
type: "button",
style: "secondary",
label: "show embed",
},
{
type: "button",
style: "danger",
label: "deactivate",
},
],
],
},
])
tester.findButtonByLabel("show embed").click()
await tester.assertMessages([
{
content: "count: 0",
embeds: [{ title: "the counter" }],
actionRows: [
[
{
type: "button",
style: "secondary",
label: "hide embed",
},
{
type: "button",
style: "primary",
label: "clicc",
},
{
type: "button",
style: "danger",
label: "deactivate",
},
],
],
},
])
tester.findButtonByLabel("clicc").click()
await tester.assertMessages([
{
content: "count: 1",
embeds: [
{
title: "the counter",
fields: [{ name: "is it even?", value: "no" }],
},
],
actionRows: [
[
{
type: "button",
style: "secondary",
label: "hide embed",
},
{
type: "button",
style: "primary",
label: "clicc",
},
{
type: "button",
style: "danger",
label: "deactivate",
},
],
],
},
])
tester.findButtonByLabel("clicc").click()
await tester.assertMessages([
{
content: "count: 2",
embeds: [
{
title: "the counter",
fields: [{ name: "is it even?", value: "yes" }],
},
],
actionRows: [
[
{
type: "button",
style: "secondary",
label: "hide embed",
},
{
type: "button",
style: "primary",
label: "clicc",
},
{
type: "button",
style: "danger",
label: "deactivate",
},
],
],
},
])
tester.findButtonByLabel("hide embed").click()
await tester.assertMessages([
{
content: "count: 2",
embeds: [],
actionRows: [
[
{
type: "button",
style: "primary",
label: "clicc",
},
{
type: "button",
style: "secondary",
label: "show embed",
},
{
type: "button",
style: "danger",
label: "deactivate",
},
],
],
},
])
tester.findButtonByLabel("clicc").click()
await tester.assertMessages([
{
content: "count: 3",
embeds: [],
actionRows: [
[
{
type: "button",
style: "primary",
label: "clicc",
},
{
type: "button",
style: "secondary",
label: "show embed",
},
{
type: "button",
style: "danger",
label: "deactivate",
},
],
],
},
])
tester.findButtonByLabel("deactivate").click()
await tester.assertMessages([
{
content: "count: 3",
embeds: [],
actionRows: [
[
{
type: "button",
style: "primary",
label: "clicc",
disabled: true,
},
{
type: "button",
style: "secondary",
label: "show embed",
disabled: true,
},
{
type: "button",
style: "danger",
label: "deactivate",
disabled: true,
},
],
],
},
])
tester.findButtonByLabel("clicc").click()
await tester.assertMessages([
{
content: "count: 3",
embeds: [],
actionRows: [
[
{
type: "button",
style: "primary",
label: "clicc",
disabled: true,
},
{
type: "button",
style: "secondary",
label: "show embed",
disabled: true,
},
{
type: "button",
style: "danger",
label: "deactivate",
disabled: true,
},
],
],
},
])
})
test("delete", async () => {
const tester = new ReacordTester()
const reply = tester.reply()
reply.render(
<>
some text
<Embed>some embed</Embed>
<Button label="some button" onClick={() => {}} />
</>,
)
await tester.assertMessages([
{
content: "some text",
embeds: [{ description: "some embed" }],
actionRows: [
[{ type: "button", style: "secondary", label: "some button" }],
],
},
])
reply.destroy()
await tester.assertMessages([])
})
// test multiple instances that can be updated independently,
// + old instances getting deactivated once the limit is reached
test.todo("multiple instances")
function KitchenSinkCounter(props: { onDeactivate: () => void }) {
const [count, setCount] = React.useState(0)
const [embedVisible, setEmbedVisible] = React.useState(false)
return (
<>
count: {count}
{embedVisible && (
<Embed>
<EmbedTitle>the counter</EmbedTitle>
{count > 0 && (
<EmbedField name="is it even?">
{count % 2 === 0 ? "yes" : "no"}
</EmbedField>
)}
</Embed>
)}
{embedVisible && (
<Button label="hide embed" onClick={() => setEmbedVisible(false)} />
)}
<Button
style="primary"
label="clicc"
onClick={() => setCount(count + 1)}
/>
{!embedVisible && (
<Button label="show embed" onClick={() => setEmbedVisible(true)} />
)}
<Button style="danger" label="deactivate" onClick={props.onDeactivate} />
</>
)
}

View File

@@ -0,0 +1,6 @@
// test that the interaction update is _eventually_ deferred if there's no component update,
// and that update isn't called after the fact
// ...somehow
test.todo("defer update timeout")
export {}

View File

@@ -0,0 +1,159 @@
import { jest } from "@jest/globals"
import React, { useState } from "react"
import { Button, Option, ReacordTester, Select } from "../library/main"
test("single select", async () => {
const tester = new ReacordTester()
const onSelect = jest.fn()
function TestSelect() {
const [value, setValue] = useState<string>()
const [disabled, setDisabled] = useState(false)
return (
<>
<Select
placeholder="choose one"
value={value}
onChange={onSelect}
onChangeValue={setValue}
disabled={disabled}
>
<Option value="1" />
<Option value="2" label="two" />
<Option value="3">three</Option>
</Select>
<Button label="disable" onClick={() => setDisabled(true)} />
</>
)
}
async function assertSelect(values: string[], disabled = false) {
await tester.assertMessages([
{
content: "",
embeds: [],
actionRows: [
[
{
type: "select",
placeholder: "choose one",
values,
disabled,
options: [
{ label: "1", value: "1" },
{ label: "two", value: "2" },
{ label: "three", value: "3" },
],
},
],
[{ type: "button", style: "secondary", label: "disable" }],
],
},
])
}
const reply = tester.reply()
reply.render(<TestSelect />)
await assertSelect([])
expect(onSelect).toHaveBeenCalledTimes(0)
tester.findSelectByPlaceholder("choose one").select("2")
await assertSelect(["2"])
expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({ values: ["2"] }),
)
tester.findButtonByLabel("disable").click()
await assertSelect(["2"], true)
tester.findSelectByPlaceholder("choose one").select("1")
await assertSelect(["2"], true)
expect(onSelect).toHaveBeenCalledTimes(1)
})
test("multiple select", async () => {
const tester = new ReacordTester()
const onSelect = jest.fn()
function TestSelect() {
const [values, setValues] = useState<string[]>([])
return (
<Select
placeholder="select"
multiple
values={values}
onChange={onSelect}
onChangeMultiple={setValues}
>
<Option value="1">one</Option>
<Option value="2">two</Option>
<Option value="3">three</Option>
</Select>
)
}
async function assertSelect(values: string[]) {
await tester.assertMessages([
{
content: "",
embeds: [],
actionRows: [
[
{
type: "select",
placeholder: "select",
values,
minValues: 0,
maxValues: 25,
options: [
{ label: "one", value: "1" },
{ label: "two", value: "2" },
{ label: "three", value: "3" },
],
},
],
],
},
])
}
const reply = tester.reply()
reply.render(<TestSelect />)
await assertSelect([])
expect(onSelect).toHaveBeenCalledTimes(0)
tester.findSelectByPlaceholder("select").select("1", "3")
await assertSelect(expect.arrayContaining(["1", "3"]))
expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({ values: expect.arrayContaining(["1", "3"]) }),
)
tester.findSelectByPlaceholder("select").select("2")
await assertSelect(expect.arrayContaining(["2"]))
expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({ values: expect.arrayContaining(["2"]) }),
)
tester.findSelectByPlaceholder("select").select()
await assertSelect([])
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ values: [] }))
})
test("optional onSelect + unknown value", async () => {
const tester = new ReacordTester()
tester.reply().render(<Select placeholder="select" />)
tester.findSelectByPlaceholder("select").select("something")
await tester.assertMessages([
{
content: "",
embeds: [],
actionRows: [
[{ type: "select", placeholder: "select", options: [], values: [] }],
],
},
])
})
test.todo("select minValues and maxValues")

View File

@@ -0,0 +1,14 @@
{
"extends": "@itsmapleleaf/configs/tsconfig.base",
"compilerOptions": {
"noImplicitOverride": true
},
"exclude": [
"**/node_modules/**",
"**/coverage/**",
"**/dist/**",
"**/.cache/**",
"**/api/_build/**",
"**/public/**"
]
}

View File

@@ -0,0 +1,10 @@
{
"entryPoints": ["../library/main.ts"],
"json": "./app/docs.json",
"excludeInternal": true,
"excludePrivate": true,
"excludeProtected": true,
"categoryOrder": ["Classes", "Functions", "*"],
"categorizeByGroup": false,
"preserveWatchOutput": true
}