1 Commits

Author SHA1 Message Date
itsMapleLeaf
12ec45ccd4 first attempt at files api 2022-04-25 14:52:29 -05:00
191 changed files with 12118 additions and 8773 deletions

View File

@@ -1,8 +0,0 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)

View File

@@ -1,11 +0,0 @@
{
"$schema": "https://unpkg.com/@changesets/config@2.1.0/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}

25
.eslintrc.cjs Normal file
View File

@@ -0,0 +1,25 @@
require("@rushstack/eslint-patch/modern-module-resolution")
/** @type {import('eslint').Linter.Config} */
module.exports = {
extends: [require.resolve("@itsmapleleaf/configs/eslint")],
ignorePatterns: [
"**/node_modules/**",
"**/.cache/**",
"**/build/**",
"**/dist/**",
"**/coverage/**",
"**/public/**",
],
parserOptions: {
project: require.resolve("./tsconfig.base.json"),
},
overrides: [
{
files: ["packages/website/cypress/**"],
parserOptions: {
project: require.resolve("./packages/website/cypress/tsconfig.json"),
},
},
],
}

41
.github/workflows/main.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: main
on:
push:
branches: [main]
pull_request:
env:
TEST_BOT_TOKEN: ${{ secrets.TEST_BOT_TOKEN }}
TEST_CHANNEL_ID: ${{ secrets.TEST_CHANNEL_ID }}
TEST_GUILD_ID: ${{ secrets.TEST_GUILD_ID }}
jobs:
run-commands:
strategy:
fail-fast: false
matrix:
command:
# if these run in the same process, it dies,
# so we test them separate
- name: test reacord
run: pnpm test -C packages/reacord
- name: test website
run: pnpm test -C packages/website
- name: build
run: pnpm build --recursive
- name: lint
run: pnpm lint
- name: typecheck
run: pnpm typecheck --parallel
name: ${{ matrix.command.name }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
# https://github.com/actions/setup-node#supported-version-syntax
node-version: "16"
- run: npm i -g pnpm
- run: pnpm install --frozen-lockfile
- run: ${{ matrix.command.run }}

View File

@@ -1,33 +0,0 @@
# https://pnpm.io/using-changesets
name: release
on:
push:
branches:
- main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
release:
name: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 8
- uses: actions/setup-node@v3
with:
node-version: 18
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: changesets release
id: changesets
uses: changesets/action@v1
with:
publish: pnpm run release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@@ -1,44 +0,0 @@
name: tests
on:
push:
branches: [main]
pull_request:
env:
TEST_BOT_TOKEN: ${{ secrets.TEST_BOT_TOKEN }}
TEST_CHANNEL_ID: ${{ secrets.TEST_CHANNEL_ID }}
TEST_GUILD_ID: ${{ secrets.TEST_GUILD_ID }}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
tests:
name: ${{ matrix.script }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
script:
- lint
- build
- test
steps:
- uses: actions/checkout@v3
- uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/pnpm-lock.yaml') }}
- uses: pnpm/action-setup@v2
with:
version: 8
- uses: actions/setup-node@v3
with:
node-version: 18
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm run ${{ matrix.script }}
- uses: stefanzweifel/git-auto-commit-action@v4
if: always()

4
.gitignore vendored
View File

@@ -4,8 +4,6 @@ node_modules
coverage coverage
.env .env
*.code-workspace *.code-workspace
.pnpm-debug.log
build build
.cache .cache
.vercel
*.tsbuildinfo

View File

@@ -1,3 +1,7 @@
node_modules
dist
coverage
pnpm-lock.yaml pnpm-lock.yaml
/packages/website/public/api build
.astro .cache
packages/website/public/api

15
Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
FROM node:lts-slim
ENV CYPRESS_INSTALL_BINARY=0
WORKDIR /app
COPY / ./
RUN ls -R
RUN npm install -g pnpm
RUN pnpm install --unsafe-perm --frozen-lockfile
RUN pnpm run build -C packages/website
ENV NODE_ENV=production
CMD [ "pnpm", "-C", "packages/website", "start" ]

View File

@@ -1,47 +1,20 @@
{ {
"name": "reacord-monorepo",
"private": true, "private": true,
"scripts": { "scripts": {
"lint": "run-s --continue-on-error lint:*", "lint": "eslint --ext js,ts,tsx .",
"lint:eslint": "eslint . --fix --cache --cache-file=node_modules/.cache/.eslintcache --report-unused-disable-directives", "lint-fix": "pnpm lint -- --fix",
"lint:prettier": "prettier . --write --cache --list-different", "format": "prettier --write ."
"lint:types": "tsc -b & pnpm -r --parallel run typecheck",
"astro-sync": "pnpm --filter website exec astro sync",
"format": "run-s --continue-on-error format:*",
"format:eslint": "eslint . --report-unused-disable-directives --fix",
"format:prettier": "prettier --cache --write . \"**/*.astro\"",
"test": "vitest",
"build": "pnpm -r run build",
"build:website": "pnpm --filter website... run build",
"start": "pnpm -C packages/website run start",
"start:website": "pnpm -C packages/website run start",
"release": "pnpm -r run build && changeset publish"
}, },
"devDependencies": { "devDependencies": {
"@changesets/cli": "^2.26.2", "@itsmapleleaf/configs": "^1.1.3",
"@itsmapleleaf/configs": "github:itsMapleLeaf/configs", "@rushstack/eslint-patch": "^1.1.3",
"eslint": "^8.50.0", "@types/eslint": "^8.4.1",
"npm-run-all": "^4.1.5", "eslint": "^8.14.0",
"prettier": "^3.0.3", "prettier": "^2.6.2",
"react": "^18.2.0", "typescript": "^4.6.3"
"tailwindcss": "^3.3.3",
"typescript": "^5.2.2",
"vitest": "^0.34.5"
}, },
"prettier": "@itsmapleleaf/configs/prettier", "resolutions": {
"eslintConfig": { "esbuild": "latest"
"extends": [ },
"./node_modules/@itsmapleleaf/configs/eslint.config.cjs", "prettier": "@itsmapleleaf/configs/prettier"
"./node_modules/@itsmapleleaf/configs/eslint.config.react.cjs"
],
"ignorePatterns": [
"node_modules",
"dist",
"packages/website/public/api"
],
"rules": {
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/require-await": "off"
}
}
} }

View File

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

View File

@@ -1,35 +0,0 @@
import { camelCase, isObject, snakeCase } from "lodash-es"
import type {
CamelCasedPropertiesDeep,
SnakeCasedPropertiesDeep,
UnknownRecord,
} 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 = {} as UnknownRecord
for (const [key, value] of Object.entries(input)) {
output[convertKey(key)] = convertKeyCaseDeep(value, convertKey)
}
return output as 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

@@ -1,7 +0,0 @@
/** For narrowing instance types with array.filter */
export const isInstanceOf =
<Instance, Args extends unknown[]>(
constructor: new (...args: Args) => Instance,
) =>
(value: unknown): value is Instance =>
value instanceof constructor

View File

@@ -1,3 +0,0 @@
export function isObject(value: unknown): value is object {
return typeof value === "object" && value !== null
}

View File

@@ -1,7 +0,0 @@
export function safeJsonStringify(value: unknown): string {
try {
return JSON.stringify(value)
} catch {
return String(value)
}
}

View File

@@ -1,11 +0,0 @@
import { inspect } from "node:util"
export function logPretty(value: unknown) {
console.info(
inspect(value, {
// depth: Number.POSITIVE_INFINITY,
depth: 10,
colors: true,
}),
)
}

View File

@@ -1,7 +0,0 @@
import { expect, test } from "vitest"
import { omit } from "./omit.ts"
test("omit", () => {
const subject = { a: 1, b: true }
expect(omit(subject, ["a"])).toStrictEqual({ b: true })
})

View File

@@ -1,3 +0,0 @@
import { omit } from "./omit.ts"
omit({ a: 1, b: true }, ["a"]) satisfies { b: boolean }

View File

@@ -1,10 +0,0 @@
export function omit<Subject extends object, Key extends PropertyKey>(
subject: Subject,
keys: Key[],
) {
const keySet = new Set<PropertyKey>(keys)
return Object.fromEntries(
Object.entries(subject).filter(([key]) => !keySet.has(key)),
// hack: conditional type preserves unions
) as Subject extends unknown ? Omit<Subject, Key> : never
}

View File

@@ -1,14 +0,0 @@
{
"name": "@reacord/helpers",
"version": "0.0.0",
"private": true,
"scripts": {
"typecheck": "tsc -b"
},
"dependencies": {
"@types/lodash-es": "^4.17.9",
"lodash-es": "^4.17.21",
"type-fest": "^4.3.2",
"vitest": "^0.34.5"
}
}

View File

@@ -1,11 +0,0 @@
import type { LoosePick } from "./types"
export function pick<T extends object, K extends keyof T | PropertyKey>(
object: T,
keys: K[],
) {
const keySet = new Set<PropertyKey>(keys)
return Object.fromEntries(
Object.entries(object).filter(([key]) => keySet.has(key)),
) as LoosePick<T, K>
}

View File

@@ -1,34 +0,0 @@
import { expect, test } from "vitest"
import type { PruneNullishValues } from "./prune-nullish-values"
import { pruneNullishValues } from "./prune-nullish-values"
test("pruneNullishValues", () => {
interface InputType {
a: string
b: string | null | undefined
c?: string
d: {
a: string
b: string | undefined
}
}
const input: InputType = {
a: "a",
b: null,
c: undefined,
d: {
a: "a",
b: undefined,
},
}
const output: PruneNullishValues<InputType> = {
a: "a",
d: {
a: "a",
},
}
expect(pruneNullishValues(input)).toEqual(output)
})

View File

@@ -1,46 +0,0 @@
import { isObject } from "./is-object"
export function pruneNullishValues<T>(input: T): PruneNullishValues<T> {
if (!isObject(input)) {
return input as PruneNullishValues<T>
}
if (Array.isArray(input)) {
return input
.filter(Boolean)
.map(
(item) => pruneNullishValues(item) as unknown,
) as PruneNullishValues<T>
}
const result: Record<string, unknown> = {}
for (const [key, value] of Object.entries(input)) {
if (value != undefined) {
result[key] = pruneNullishValues(value)
}
}
return result as PruneNullishValues<T>
}
export type PruneNullishValues<Input> = Input extends object
? OptionalKeys<
{ [Key in keyof Input]: NonNullable<PruneNullishValues<Input[Key]>> },
KeysWithNullishValues<Input>
>
: Input
type OptionalKeys<Input, Keys extends keyof Input> = Omit<Input, Keys> & {
[Key in Keys]?: Input[Key]
}
type KeysWithNullishValues<Input> = NonNullable<
Values<{
[Key in keyof Input]: null extends Input[Key]
? Key
: undefined extends Input[Key]
? Key
: never
}>
>
type Values<Input> = Input[keyof Input]

View File

@@ -1,21 +0,0 @@
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, @typescript-eslint/no-unnecessary-condition
while (true) {
try {
return await callback()
} catch (error) {
if (Date.now() - startTime > maxTime) {
throw error
}
await setTimeout(waitPeriod)
}
}
}

View File

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

View File

@@ -1,3 +0,0 @@
{
"extends": "../../tsconfig.base.json"
}

View File

@@ -1,4 +0,0 @@
import { type LooseOmit, type LoosePick, typeEquals } from "./types.ts"
typeEquals<LoosePick<{ a: 1; b: 2 }, "a">, { a: 1 }>(true)
typeEquals<LooseOmit<{ a: 1; b: 2 }, "a">, { b: 2 }>(true)

View File

@@ -1,21 +0,0 @@
import { raise } from "./raise.ts"
export type MaybePromise<T> = T | PromiseLike<T>
export type ValueOf<Type> = Type extends ReadonlyArray<infer Value>
? Value
: Type[keyof Type]
export type LoosePick<Shape, Keys extends PropertyKey> = Simplify<{
[Key in Extract<Keys, keyof Shape>]: Shape[Key]
}>
export type LooseOmit<Shape, Keys extends PropertyKey> = Simplify<{
[Key in Exclude<keyof Shape, Keys>]: Shape[Key]
}>
export type Simplify<T> = { [Key in keyof T]: T[Key] } & NonNullable<unknown>
export const typeEquals = <A, B>(
_result: A extends B ? (B extends A ? true : false) : false,
) => raise("typeEquals() should not be called at runtime")

View File

@@ -1,23 +0,0 @@
import { setTimeout } from "node:timers/promises"
import type { MaybePromise } from "./types.ts"
const maxTime = 1000
export async function waitFor<Result>(
predicate: () => MaybePromise<Result>,
): Promise<Awaited<Result>> {
const startTime = Date.now()
let lastError: unknown
while (Date.now() - startTime < maxTime) {
try {
return await predicate()
} catch (error) {
lastError = error
await setTimeout(50)
}
}
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw lastError ?? new Error("Timeout")
}

View File

@@ -1,24 +0,0 @@
import { inspect } from "node:util"
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: unknown[]) => {
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 unknown
}
},
}) as T
}

View File

@@ -1,32 +0,0 @@
# reacord
## 0.5.3
### Patch Changes
- 104b175: ensure message is edited from arbitrary component updates
- 156cf90: fix interaction handling
- 0bab505: fix DJS deprecation warning on isStringSelectMenu
- d76f316: ensure action rows handle child interactions
## 0.5.2
### Patch Changes
- 9813a01: import react-reconciler/constants.js for esm
ESM projects which tried to import reacord would fail due to the lack of .js on this import
## 0.5.1
### Patch Changes
- 72f4a4a: upgrade dependencies and remove some unneeded
- 7536bde: add types in exports to work with TS nodenext
- e335165: fix links
## 0.5.0
### Minor Changes
- aa65da5: allow JSX in more places

View File

@@ -1 +0,0 @@
/// <reference types="@total-typescript/ts-reset" />

View File

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

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,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,7 @@
export function isObject<T>(
value: T,
): value is Exclude<T, Primitive | AnyFunction> {
return typeof value === "object" && value !== null
}
type Primitive = string | number | boolean | undefined | null
type AnyFunction = (...args: any[]) => any

View File

@@ -0,0 +1,11 @@
import { inspect } from "node:util"
export function logPretty(value: unknown) {
console.info(
inspect(value, {
// depth: Number.POSITIVE_INFINITY,
depth: 10,
colors: true,
}),
)
}

View File

@@ -0,0 +1,13 @@
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,15 @@
import type { LoosePick, UnknownRecord } from "./types"
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,33 @@
import { expect, test } from "vitest"
import { PruneNullishValues, pruneNullishValues } from "./prune-nullish-values"
test("pruneNullishValues", () => {
type InputType = {
a: string
b: string | null | undefined
c?: string
d: {
a: string
b: string | undefined
}
}
const input: InputType = {
a: "a",
b: null,
c: undefined,
d: {
a: "a",
b: undefined,
},
}
const output: PruneNullishValues<InputType> = {
a: "a",
d: {
a: "a",
},
}
expect(pruneNullishValues(input)).toEqual(output)
})

View File

@@ -0,0 +1,42 @@
import { isObject } from "./is-object"
export function pruneNullishValues<T>(input: T): PruneNullishValues<T> {
if (Array.isArray(input)) {
return input.filter(Boolean).map((item) => pruneNullishValues(item)) as any
}
if (!isObject(input)) {
return input as any
}
const result: any = {}
for (const [key, value] of Object.entries(input)) {
if (value != undefined) {
result[key] = pruneNullishValues(value)
}
}
return result
}
export type PruneNullishValues<Input> = Input extends object
? OptionalKeys<
{ [Key in keyof Input]: NonNullable<PruneNullishValues<Input[Key]>> },
KeysWithNullishValues<Input>
>
: Input
type OptionalKeys<Input, Keys extends keyof Input> = Omit<Input, Keys> & {
[Key in Keys]?: Input[Key]
}
type KeysWithNullishValues<Input> = NonNullable<
Values<{
[Key in keyof Input]: null extends Input[Key]
? Key
: undefined extends Input[Key]
? Key
: never
}>
>
type Values<Input> = Input[keyof Input]

View File

@@ -1,5 +1,5 @@
import { toError } from "./to-error.js"
import { setTimeout } from "node:timers/promises" import { setTimeout } from "node:timers/promises"
import { toError } from "./to-error.js"
export async function rejectAfter( export async function rejectAfter(
timeMs: number, timeMs: number,

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,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,21 @@
import { setTimeout } from "timers/promises"
const maxTime = 1000
export async function waitFor<Result>(
predicate: () => Result,
): Promise<Awaited<Result>> {
const startTime = Date.now()
let lastError: unknown
while (Date.now() - startTime < maxTime) {
try {
return await predicate()
} catch (error) {
lastError = error
await setTimeout(50)
}
}
throw lastError ?? new Error("Timeout")
}

View File

@@ -0,0 +1,24 @@
import { inspect } from "node:util"
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

@@ -1,49 +1,52 @@
import type { ReactNode } from "react" import type { ReactNode } from "react"
import type { ReacordInstance } from "./instance" import type { ReacordInstance } from "./instance"
/** @category Component Event */ /**
export interface ComponentEvent { * @category Component Event
*/
export type ComponentEvent = {
/** /**
* The message associated with this event. For example: with a button click, * The message associated with this event.
* For example: with a button click,
* this is the message that the button is on. * this is the message that the button is on.
*
* @see https://discord.com/developers/docs/resources/channel#message-object * @see https://discord.com/developers/docs/resources/channel#message-object
*/ */
message: MessageInfo message: MessageInfo
/** /**
* The channel that this event occurred in. * The channel that this event occurred in.
*
* @see https://discord.com/developers/docs/resources/channel#channel-object * @see https://discord.com/developers/docs/resources/channel#channel-object
*/ */
channel: ChannelInfo channel: ChannelInfo
/** /**
* The user that triggered this event. * The user that triggered this event.
*
* @see https://discord.com/developers/docs/resources/user#user-object * @see https://discord.com/developers/docs/resources/user#user-object
*/ */
user: UserInfo user: UserInfo
/** /**
* The guild that this event occurred in. * The guild that this event occurred in.
*
* @see https://discord.com/developers/docs/resources/guild#guild-object * @see https://discord.com/developers/docs/resources/guild#guild-object
*/ */
guild?: GuildInfo guild?: GuildInfo
/** Create a new reply to this event. */ /**
* Create a new reply to this event.
*/
reply(content?: ReactNode): ReacordInstance reply(content?: ReactNode): ReacordInstance
/** /**
* Create an ephemeral reply to this event, shown only to the user who * Create an ephemeral reply to this event,
* triggered it. * shown only to the user who triggered it.
*/ */
ephemeralReply(content?: ReactNode): ReacordInstance ephemeralReply(content?: ReactNode): ReacordInstance
} }
/** @category Component Event */ /**
export interface ChannelInfo { * @category Component Event
*/
export type ChannelInfo = {
id: string id: string
name?: string name?: string
topic?: string topic?: string
@@ -54,11 +57,13 @@ export interface ChannelInfo {
rateLimitPerUser?: number rateLimitPerUser?: number
} }
/** @category Component Event */ /**
export interface MessageInfo { * @category Component Event
*/
export type MessageInfo = {
id: string id: string
channelId: string channelId: string
authorId: string authorId: UserInfo
member?: GuildMemberInfo member?: GuildMemberInfo
content: string content: string
timestamp: string timestamp: string
@@ -69,15 +74,19 @@ export interface MessageInfo {
mentions: string[] mentions: string[]
} }
/** @category Component Event */ /**
export interface GuildInfo { * @category Component Event
*/
export type GuildInfo = {
id: string id: string
name: string name: string
member: GuildMemberInfo member: GuildMemberInfo
} }
/** @category Component Event */ /**
export interface GuildMemberInfo { * @category Component Event
*/
export type GuildMemberInfo = {
id: string id: string
nick?: string nick?: string
displayName: string displayName: string
@@ -91,12 +100,14 @@ export interface GuildMemberInfo {
communicationDisabledUntil?: string communicationDisabledUntil?: string
} }
/** @category Component Event */ /**
export interface UserInfo { * @category Component Event
*/
export type UserInfo = {
id: string id: string
username: string username: string
discriminator: string discriminator: string
tag: string tag: string
avatarUrl: string | null avatarUrl: string
accentColor?: number accentColor?: number
} }

View File

@@ -1,23 +1,22 @@
import type { ReactNode } from "react" import type { ReactNode } from "react"
import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import type { MessageOptions } from "../../internal/message" import type { MessageOptions } from "../../internal/message"
import { Node } from "../../internal/node.js" import { Node } from "../../internal/node.js"
import type { ComponentInteraction } from "../../internal/interaction.js"
/** /**
* Props for an action row * Props for an action row
*
* @category Action Row * @category Action Row
*/ */
export interface ActionRowProps { export type ActionRowProps = {
children?: ReactNode children?: ReactNode
} }
/** /**
* An action row is a top-level container for message components. * 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 don't need to use this; Reacord automatically creates action rows for you.
* you. But this can be useful if you want a specific layout. * But this can be useful if you want a specific layout.
* *
* ```tsx * ```tsx
* // put buttons on two separate rows * // put buttons on two separate rows
@@ -38,19 +37,11 @@ export function ActionRow(props: ActionRowProps) {
) )
} }
class ActionRowNode extends Node<ActionRowProps> { class ActionRowNode extends Node<{}> {
override modifyMessageOptions(options: MessageOptions): void { override modifyMessageOptions(options: MessageOptions): void {
options.actionRows.push([]) options.actionRows.push([])
for (const child of this.children) { for (const child of this.children) {
child.modifyMessageOptions(options) child.modifyMessageOptions(options)
} }
} }
handleComponentInteraction(interaction: ComponentInteraction) {
for (const child of this.children) {
if (child.handleComponentInteraction(interaction)) {
return true
}
}
return false
}
} }

View File

@@ -1,24 +1,22 @@
import type { ReactNode } from "react"
/** /**
* Common props between button-like components * Common props between button-like components
*
* @category Button * @category Button
*/ */
export interface ButtonSharedProps { export type ButtonSharedProps = {
/** The text on the button. Rich formatting (markdown) is not supported here. */ /** The text on the button. Rich formatting (markdown) is not supported here. */
label?: ReactNode label?: string
/** When true, the button will be slightly faded, and cannot be clicked. */ /** When true, the button will be slightly faded, and cannot be clicked. */
disabled?: boolean disabled?: boolean
/** /**
* Renders an emoji to the left of the text. Has to be a literal emoji * Renders an emoji to the left of the text.
* character (e.g. 🍍), or an emoji code, like * Has to be a literal emoji character (e.g. 🍍),
* `<:plus_one:778531744860602388>`. * or an emoji code, like `<:plus_one:778531744860602388>`.
* *
* To get an emoji code, type your emoji in Discord chat with a backslash `\` * To get an emoji code, type your emoji in Discord chat
* in front. The bot has to be in the emoji's guild to use it. * with a backslash `\` in front.
* The bot has to be in the emoji's guild to use it.
*/ */
emoji?: string emoji?: string
} }

View File

@@ -1,4 +1,5 @@
import { randomUUID } from "node:crypto" import { nanoid } from "nanoid"
import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import type { ComponentInteraction } from "../../internal/interaction" import type { ComponentInteraction } from "../../internal/interaction"
import type { MessageOptions } from "../../internal/message" import type { MessageOptions } from "../../internal/message"
@@ -7,41 +8,38 @@ import { Node } from "../../internal/node.js"
import type { ComponentEvent } from "../component-event" import type { ComponentEvent } from "../component-event"
import type { ButtonSharedProps } from "./button-shared-props" import type { ButtonSharedProps } from "./button-shared-props"
/** @category Button */ /**
* @category Button
*/
export type ButtonProps = ButtonSharedProps & { export type ButtonProps = ButtonSharedProps & {
/** /**
* The style determines the color of the button and signals intent. * The style determines the color of the button and signals intent.
*
* @see https://discord.com/developers/docs/interactions/message-components#button-object-button-styles * @see https://discord.com/developers/docs/interactions/message-components#button-object-button-styles
*/ */
style?: "primary" | "secondary" | "success" | "danger" style?: "primary" | "secondary" | "success" | "danger"
/** Happens when a user clicks the button. */ /**
* Happens when a user clicks the button.
*/
onClick: (event: ButtonClickEvent) => void onClick: (event: ButtonClickEvent) => void
} }
/** @category Button */ /**
* @category Button
*/
export type ButtonClickEvent = ComponentEvent export type ButtonClickEvent = ComponentEvent
/** @category Button */ /**
* @category Button
*/
export function Button(props: ButtonProps) { export function Button(props: ButtonProps) {
return ( return (
<ReacordElement props={props} createNode={() => new ButtonNode(props)}> <ReacordElement props={props} createNode={() => new ButtonNode(props)} />
<ReacordElement props={{}} createNode={() => new ButtonLabelNode({})}>
{props.label}
</ReacordElement>
</ReacordElement>
) )
} }
class ButtonNode extends Node<ButtonProps> { class ButtonNode extends Node<ButtonProps> {
private customId = randomUUID() private customId = nanoid()
// this has text children, but buttons themselves shouldn't yield text
// eslint-disable-next-line @typescript-eslint/class-literal-property-style
override get text() {
return ""
}
override modifyMessageOptions(options: MessageOptions): void { override modifyMessageOptions(options: MessageOptions): void {
getNextActionRow(options).push({ getNextActionRow(options).push({
@@ -50,7 +48,7 @@ class ButtonNode extends Node<ButtonProps> {
style: this.props.style ?? "secondary", style: this.props.style ?? "secondary",
disabled: this.props.disabled, disabled: this.props.disabled,
emoji: this.props.emoji, emoji: this.props.emoji,
label: this.children.findType(ButtonLabelNode)?.text, label: this.props.label,
}) })
} }
@@ -65,5 +63,3 @@ class ButtonNode extends Node<ButtonProps> {
return false return false
} }
} }
class ButtonLabelNode extends Node<Record<string, never>> {}

View File

@@ -1,36 +1,36 @@
import type { ReactNode } from "react" import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import { Node } from "../../internal/node.js"
import { EmbedChildNode } from "./embed-child.js" import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options" import type { EmbedOptions } from "./embed-options"
/** @category Embed */ /**
export interface EmbedAuthorProps { * @category Embed
name?: ReactNode */
children?: ReactNode export type EmbedAuthorProps = {
name?: string
children?: string
url?: string url?: string
iconUrl?: string iconUrl?: string
} }
/** @category Embed */ /**
* @category Embed
*/
export function EmbedAuthor(props: EmbedAuthorProps) { export function EmbedAuthor(props: EmbedAuthorProps) {
return ( return (
<ReacordElement props={props} createNode={() => new EmbedAuthorNode(props)}> <ReacordElement
<ReacordElement props={{}} createNode={() => new AuthorTextNode({})}> props={props}
{props.name ?? props.children} createNode={() => new EmbedAuthorNode(props)}
</ReacordElement> />
</ReacordElement>
) )
} }
class EmbedAuthorNode extends EmbedChildNode<EmbedAuthorProps> { class EmbedAuthorNode extends EmbedChildNode<EmbedAuthorProps> {
override modifyEmbedOptions(options: EmbedOptions): void { override modifyEmbedOptions(options: EmbedOptions): void {
options.author = { options.author = {
name: this.children.findType(AuthorTextNode)?.text ?? "", name: this.props.name ?? this.props.children ?? "",
url: this.props.url, url: this.props.url,
icon_url: this.props.iconUrl, icon_url: this.props.iconUrl,
} }
} }
} }
class AuthorTextNode extends Node<Record<string, never>> {}

View File

@@ -1,28 +1,27 @@
import type { ReactNode } from "react" import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import { Node } from "../../internal/node.js"
import { EmbedChildNode } from "./embed-child.js" import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options" import type { EmbedOptions } from "./embed-options"
/** @category Embed */ /**
export interface EmbedFieldProps { * @category Embed
name: ReactNode */
value?: ReactNode export type EmbedFieldProps = {
name: string
value?: string
inline?: boolean inline?: boolean
children?: ReactNode children?: string
} }
/** @category Embed */ /**
* @category Embed
*/
export function EmbedField(props: EmbedFieldProps) { export function EmbedField(props: EmbedFieldProps) {
return ( return (
<ReacordElement props={props} createNode={() => new EmbedFieldNode(props)}> <ReacordElement
<ReacordElement props={{}} createNode={() => new FieldNameNode({})}> props={props}
{props.name} createNode={() => new EmbedFieldNode(props)}
</ReacordElement> />
<ReacordElement props={{}} createNode={() => new FieldValueNode({})}>
{props.value ?? props.children}
</ReacordElement>
</ReacordElement>
) )
} }
@@ -30,12 +29,9 @@ class EmbedFieldNode extends EmbedChildNode<EmbedFieldProps> {
override modifyEmbedOptions(options: EmbedOptions): void { override modifyEmbedOptions(options: EmbedOptions): void {
options.fields ??= [] options.fields ??= []
options.fields.push({ options.fields.push({
name: this.children.findType(FieldNameNode)?.text ?? "", name: this.props.name,
value: this.children.findType(FieldValueNode)?.text ?? "", value: this.props.value ?? this.props.children ?? "",
inline: this.props.inline, inline: this.props.inline,
}) })
} }
} }
class FieldNameNode extends Node<Record<string, never>> {}
class FieldValueNode extends Node<Record<string, never>> {}

View File

@@ -1,34 +1,34 @@
import type { ReactNode } from "react" import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import { Node } from "../../internal/node.js"
import { EmbedChildNode } from "./embed-child.js" import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options" import type { EmbedOptions } from "./embed-options"
/** @category Embed */ /**
export interface EmbedFooterProps { * @category Embed
text?: ReactNode */
children?: ReactNode export type EmbedFooterProps = {
text?: string
children?: string
iconUrl?: string iconUrl?: string
timestamp?: string | number | Date timestamp?: string | number | Date
} }
/** @category Embed */ /**
export function EmbedFooter({ text, children, ...props }: EmbedFooterProps) { * @category Embed
*/
export function EmbedFooter(props: EmbedFooterProps) {
return ( return (
<ReacordElement props={props} createNode={() => new EmbedFooterNode(props)}> <ReacordElement
<ReacordElement props={{}} createNode={() => new FooterTextNode({})}> props={props}
{text ?? children} createNode={() => new EmbedFooterNode(props)}
</ReacordElement> />
</ReacordElement>
) )
} }
class EmbedFooterNode extends EmbedChildNode< class EmbedFooterNode extends EmbedChildNode<EmbedFooterProps> {
Omit<EmbedFooterProps, "text" | "children">
> {
override modifyEmbedOptions(options: EmbedOptions): void { override modifyEmbedOptions(options: EmbedOptions): void {
options.footer = { options.footer = {
text: this.children.findType(FooterTextNode)?.text ?? "", text: this.props.text ?? this.props.children ?? "",
icon_url: this.props.iconUrl, icon_url: this.props.iconUrl,
} }
options.timestamp = this.props.timestamp options.timestamp = this.props.timestamp
@@ -36,5 +36,3 @@ class EmbedFooterNode extends EmbedChildNode<
: undefined : undefined
} }
} }
class FooterTextNode extends Node<Record<string, never>> {}

View File

@@ -1,13 +1,18 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import { EmbedChildNode } from "./embed-child.js" import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options" import type { EmbedOptions } from "./embed-options"
/** @category Embed */ /**
export interface EmbedImageProps { * @category Embed
*/
export type EmbedImageProps = {
url: string url: string
} }
/** @category Embed */ /**
* @category Embed
*/
export function EmbedImage(props: EmbedImageProps) { export function EmbedImage(props: EmbedImageProps) {
return ( return (
<ReacordElement <ReacordElement

View File

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

View File

@@ -1,13 +1,18 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import { EmbedChildNode } from "./embed-child.js" import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options" import type { EmbedOptions } from "./embed-options"
/** @category Embed */ /**
export interface EmbedThumbnailProps { * @category Embed
*/
export type EmbedThumbnailProps = {
url: string url: string
} }
/** @category Embed */ /**
* @category Embed
*/
export function EmbedThumbnail(props: EmbedThumbnailProps) { export function EmbedThumbnail(props: EmbedThumbnailProps) {
return ( return (
<ReacordElement <ReacordElement

View File

@@ -1,31 +1,31 @@
import type { ReactNode } from "react" import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import { Node } from "../../internal/node.js"
import { EmbedChildNode } from "./embed-child.js" import { EmbedChildNode } from "./embed-child.js"
import type { EmbedOptions } from "./embed-options" import type { EmbedOptions } from "./embed-options"
/** @category Embed */ /**
export interface EmbedTitleProps { * @category Embed
children: ReactNode */
export type EmbedTitleProps = {
children: string
url?: string url?: string
} }
/** @category Embed */ /**
export function EmbedTitle({ children, ...props }: EmbedTitleProps) { * @category Embed
*/
export function EmbedTitle(props: EmbedTitleProps) {
return ( return (
<ReacordElement props={props} createNode={() => new EmbedTitleNode(props)}> <ReacordElement
<ReacordElement props={{}} createNode={() => new TitleTextNode({})}> props={props}
{children} createNode={() => new EmbedTitleNode(props)}
</ReacordElement> />
</ReacordElement>
) )
} }
class EmbedTitleNode extends EmbedChildNode<Omit<EmbedTitleProps, "children">> { class EmbedTitleNode extends EmbedChildNode<EmbedTitleProps> {
override modifyEmbedOptions(options: EmbedOptions): void { override modifyEmbedOptions(options: EmbedOptions): void {
options.title = this.children.findType(TitleTextNode)?.text ?? "" options.title = this.props.children
options.url = this.props.url options.url = this.props.url
} }
} }
class TitleTextNode extends Node<Record<string, never>> {}

View File

@@ -1,6 +1,6 @@
import { snakeCaseDeep } from "@reacord/helpers/convert-object-property-case" import React from "react"
import { omit } from "@reacord/helpers/omit" import { snakeCaseDeep } from "../../../helpers/convert-object-property-case"
import type React from "react" import { omit } from "../../../helpers/omit"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import type { MessageOptions } from "../../internal/message" import type { MessageOptions } from "../../internal/message"
import { Node } from "../../internal/node.js" import { Node } from "../../internal/node.js"
@@ -12,7 +12,7 @@ import type { EmbedOptions } from "./embed-options"
* @category Embed * @category Embed
* @see https://discord.com/developers/docs/resources/channel#embed-object * @see https://discord.com/developers/docs/resources/channel#embed-object
*/ */
export interface EmbedProps { export type EmbedProps = {
title?: string title?: string
description?: string description?: string
url?: string url?: string
@@ -53,7 +53,7 @@ class EmbedNode extends Node<EmbedProps> {
child.modifyEmbedOptions(embed) child.modifyEmbedOptions(embed)
} }
if (child instanceof TextNode) { if (child instanceof TextNode) {
embed.description = (embed.description ?? "") + child.props embed.description = (embed.description || "") + child.props
} }
} }

View File

@@ -1,10 +1,13 @@
import React from "react"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import type { MessageOptions } from "../../internal/message" import type { MessageOptions } from "../../internal/message"
import { getNextActionRow } from "../../internal/message" import { getNextActionRow } from "../../internal/message"
import { Node } from "../../internal/node.js" import { Node } from "../../internal/node.js"
import type { ButtonSharedProps } from "./button-shared-props" import type { ButtonSharedProps } from "./button-shared-props"
/** @category Link */ /**
* @category Link
*/
export type LinkProps = ButtonSharedProps & { export type LinkProps = ButtonSharedProps & {
/** The URL the link should lead to */ /** The URL the link should lead to */
url: string url: string
@@ -12,27 +15,21 @@ export type LinkProps = ButtonSharedProps & {
children?: string children?: string
} }
/** @category Link */ /**
export function Link({ label, children, ...props }: LinkProps) { * @category Link
return ( */
<ReacordElement props={props} createNode={() => new LinkNode(props)}> export function Link(props: LinkProps) {
<ReacordElement props={{}} createNode={() => new LinkTextNode({})}> return <ReacordElement props={props} createNode={() => new LinkNode(props)} />
{label ?? children}
</ReacordElement>
</ReacordElement>
)
} }
class LinkNode extends Node<Omit<LinkProps, "label" | "children">> { class LinkNode extends Node<LinkProps> {
override modifyMessageOptions(options: MessageOptions): void { override modifyMessageOptions(options: MessageOptions): void {
getNextActionRow(options).push({ getNextActionRow(options).push({
type: "link", type: "link",
disabled: this.props.disabled, disabled: this.props.disabled,
emoji: this.props.emoji, emoji: this.props.emoji,
label: this.children.findType(LinkTextNode)?.text, label: this.props.label || this.props.children,
url: this.props.url, url: this.props.url,
}) })
} }
} }
class LinkTextNode extends Node<Record<string, never>> {}

View File

@@ -2,18 +2,13 @@ import type { MessageSelectOptionOptions } from "../../internal/message"
import { Node } from "../../internal/node" import { Node } from "../../internal/node"
import type { OptionProps } from "./option" import type { OptionProps } from "./option"
export class OptionNode extends Node< export class OptionNode extends Node<OptionProps> {
Omit<OptionProps, "children" | "label" | "description">
> {
get options(): MessageSelectOptionOptions { get options(): MessageSelectOptionOptions {
return { return {
label: this.children.findType(OptionLabelNode)?.text ?? this.props.value, label: this.props.children || this.props.label || this.props.value,
value: this.props.value, value: this.props.value,
description: this.children.findType(OptionDescriptionNode)?.text, description: this.props.description,
emoji: this.props.emoji, emoji: this.props.emoji,
} }
} }
} }
export class OptionLabelNode extends Node<Record<string, never>> {}
export class OptionDescriptionNode extends Node<Record<string, never>> {}

View File

@@ -1,56 +1,38 @@
import type { ReactNode } from "react" import React from "react"
import { ReacordElement } from "../../internal/element" import { ReacordElement } from "../../internal/element"
import { import { OptionNode } from "./option-node"
OptionDescriptionNode,
OptionLabelNode,
OptionNode,
} from "./option-node"
/** @category Select */ /**
export interface OptionProps { * @category Select
*/
export type OptionProps = {
/** The internal value of this option */ /** The internal value of this option */
value: string value: string
/** The text shown to the user. This takes priority over `children` */ /** The text shown to the user. This takes priority over `children` */
label?: ReactNode label?: string
/** The text shown to the user */ /** The text shown to the user */
children?: ReactNode children?: string
/** Description for the option, shown to the user */ /** Description for the option, shown to the user */
description?: ReactNode description?: string
/** /**
* Renders an emoji to the left of the text. * Renders an emoji to the left of the text.
* *
* Has to be a literal emoji character (e.g. 🍍), or an emoji code, like * Has to be a literal emoji character (e.g. 🍍),
* `<:plus_one:778531744860602388>`. * or an emoji code, like `<:plus_one:778531744860602388>`.
* *
* To get an emoji code, type your emoji in Discord chat with a backslash `\` * To get an emoji code, type your emoji in Discord chat
* in front. The bot has to be in the emoji's guild to use it. * with a backslash `\` in front.
* The bot has to be in the emoji's guild to use it.
*/ */
emoji?: string emoji?: string
} }
/** @category Select */ /**
export function Option({ * @category Select
label, */
children, export function Option(props: OptionProps) {
description,
...props
}: OptionProps) {
return ( return (
<ReacordElement props={props} createNode={() => new OptionNode(props)}> <ReacordElement props={props} createNode={() => new OptionNode(props)} />
{(label !== undefined || children !== undefined) && (
<ReacordElement props={{}} createNode={() => new OptionLabelNode({})}>
{label ?? children}
</ReacordElement>
)}
{description !== undefined && (
<ReacordElement
props={{}}
createNode={() => new OptionDescriptionNode({})}
>
{description}
</ReacordElement>
)}
</ReacordElement>
) )
} }

View File

@@ -1,6 +1,7 @@
import { isInstanceOf } from "@reacord/helpers/is-instance-of" import { nanoid } from "nanoid"
import { randomUUID } from "node:crypto"
import type { ReactNode } from "react" import type { ReactNode } from "react"
import React from "react"
import { isInstanceOf } from "../../../helpers/is-instance-of"
import { ReacordElement } from "../../internal/element.js" import { ReacordElement } from "../../internal/element.js"
import type { ComponentInteraction } from "../../internal/interaction" import type { ComponentInteraction } from "../../internal/interaction"
import type { import type {
@@ -11,10 +12,11 @@ import type {
import { Node } from "../../internal/node.js" import { Node } from "../../internal/node.js"
import type { ComponentEvent } from "../component-event" import type { ComponentEvent } from "../component-event"
import { OptionNode } from "./option-node" import { OptionNode } from "./option-node"
import { omit } from "@reacord/helpers/omit.js"
/** @category Select */ /**
export interface SelectProps { * @category Select
*/
export type SelectProps = {
children?: ReactNode children?: ReactNode
/** Sets the currently selected value */ /** Sets the currently selected value */
value?: string value?: string
@@ -29,8 +31,8 @@ export interface SelectProps {
multiple?: boolean multiple?: boolean
/** /**
* With `multiple`, the minimum number of values that can be selected. When * With `multiple`, the minimum number of values that can be selected.
* `multiple` is false or not defined, this is always 1. * When `multiple` is false or not defined, this is always 1.
* *
* This only limits the number of values that can be received by the user. * This only limits the number of values that can be received by the user.
* This does not limit the number of values that can be displayed by you. * This does not limit the number of values that can be displayed by you.
@@ -38,44 +40,44 @@ export interface SelectProps {
minValues?: number minValues?: number
/** /**
* With `multiple`, the maximum number of values that can be selected. When * With `multiple`, the maximum number of values that can be selected.
* `multiple` is false or not defined, this is always 1. * When `multiple` is false or not defined, this is always 1.
* *
* This only limits the number of values that can be received by the user. * This only limits the number of values that can be received by the user.
* This does not limit the number of values that can be displayed by you. * This does not limit the number of values that can be displayed by you.
*/ */
maxValues?: number maxValues?: number
/** /** When true, the select will be slightly faded, and cannot be interacted with. */
* When true, the select will be slightly faded, and cannot be interacted
* with.
*/
disabled?: boolean disabled?: boolean
/** /**
* Called when the user inputs a selection. Receives the entire select change * Called when the user inputs a selection.
* event, which can be used to create new replies, etc. * Receives the entire select change event,
* which can be used to create new replies, etc.
*/ */
onChange?: (event: SelectChangeEvent) => void onChange?: (event: SelectChangeEvent) => void
/** /**
* Convenience shorthand for `onChange`, which receives the first selected * Convenience shorthand for `onChange`, which receives the first selected value.
* value.
*/ */
onChangeValue?: (value: string, event: SelectChangeEvent) => void onChangeValue?: (value: string, event: SelectChangeEvent) => void
/** Convenience shorthand for `onChange`, which receives all selected values. */ /**
* Convenience shorthand for `onChange`, which receives all selected values.
*/
onChangeMultiple?: (values: string[], event: SelectChangeEvent) => void onChangeMultiple?: (values: string[], event: SelectChangeEvent) => void
} }
/** @category Select */ /**
* @category Select
*/
export type SelectChangeEvent = ComponentEvent & { export type SelectChangeEvent = ComponentEvent & {
values: string[] values: string[]
} }
/** /**
* See [the select menu guide](/guides/select-menu) for a usage example. * See [the select menu guide](/guides/select-menu) for a usage example.
*
* @category Select * @category Select
*/ */
export function Select(props: SelectProps) { export function Select(props: SelectProps) {
@@ -87,7 +89,7 @@ export function Select(props: SelectProps) {
} }
class SelectNode extends Node<SelectProps> { class SelectNode extends Node<SelectProps> {
readonly customId = randomUUID() readonly customId = nanoid()
override modifyMessageOptions(message: MessageOptions): void { override modifyMessageOptions(message: MessageOptions): void {
const actionRow: ActionRow = [] const actionRow: ActionRow = []
@@ -103,13 +105,12 @@ class SelectNode extends Node<SelectProps> {
values, values,
minValues = 0, minValues = 0,
maxValues = 25, maxValues = 25,
children,
onChange,
onChangeValue,
onChangeMultiple,
...props ...props
} = omit(this.props, [ } = this.props
"children",
"onChange",
"onChangeValue",
"onChangeMultiple",
])
const item: ActionRowItem = { const item: ActionRowItem = {
...props, ...props,

View File

@@ -0,0 +1,7 @@
import { Readable } from "node:stream"
export type ReacordFile = {
name?: string
description?: string
data: Buffer | Readable | string
}

View File

@@ -1,6 +1,6 @@
import type { ReacordInstance } from "./instance.js"
import { raise } from "@reacord/helpers/raise.js"
import * as React from "react" import * as React from "react"
import { raise } from "../../helpers/raise"
import type { ReacordInstance } from "./instance"
const Context = React.createContext<ReacordInstance | undefined>(undefined) const Context = React.createContext<ReacordInstance | undefined>(undefined)

View File

@@ -1,11 +1,11 @@
import type { ReactNode } from "react" import type { ReactNode } from "react"
import { ReacordFile } from "./file"
/** /**
* Represents an interactive message, which can later be replaced or deleted. * Represents an interactive message, which can later be replaced or deleted.
*
* @category Core * @category Core
*/ */
export interface ReacordInstance { export type ReacordInstance = {
/** Render some JSX to this instance (edits the message) */ /** Render some JSX to this instance (edits the message) */
render: (content: ReactNode) => void render: (content: ReactNode) => void
@@ -17,4 +17,7 @@ export interface ReacordInstance {
* This prevents it from listening to user interactions. * This prevents it from listening to user interactions.
*/ */
deactivate: () => void deactivate: () => void
/** Attach a file to the message for this instance */
attach: (file: ReacordFile) => void
} }

View File

@@ -1,16 +1,13 @@
import { safeJsonStringify } from "@reacord/helpers/json" /* eslint-disable class-methods-use-this */
import { pick } from "@reacord/helpers/pick"
import { pruneNullishValues } from "@reacord/helpers/prune-nullish-values"
import { raise } from "@reacord/helpers/raise"
import * as Discord from "discord.js" import * as Discord from "discord.js"
import type { ReactNode } from "react" import type { ReactNode } from "react"
import type { Except } from "type-fest" import type { Except } from "type-fest"
import { pick } from "../../helpers/pick"
import { pruneNullishValues } from "../../helpers/prune-nullish-values"
import { raise } from "../../helpers/raise"
import { toUpper } from "../../helpers/to-upper"
import type { ComponentInteraction } from "../internal/interaction" import type { ComponentInteraction } from "../internal/interaction"
import type { import type { Message, MessageOptions } from "../internal/message"
Message,
MessageButtonOptions,
MessageOptions,
} from "../internal/message"
import { ChannelMessageRenderer } from "../internal/renderers/channel-message-renderer" import { ChannelMessageRenderer } from "../internal/renderers/channel-message-renderer"
import { InteractionReplyRenderer } from "../internal/renderers/interaction-reply-renderer" import { InteractionReplyRenderer } from "../internal/renderers/interaction-reply-renderer"
import type { import type {
@@ -26,18 +23,14 @@ import { Reacord } from "./reacord"
/** /**
* The Reacord adapter for Discord.js. * The Reacord adapter for Discord.js.
*
* @category Core * @category Core
*/ */
export class ReacordDiscordJs extends Reacord { export class ReacordDiscordJs extends Reacord {
constructor( constructor(private client: Discord.Client, config: ReacordConfig = {}) {
private client: Discord.Client,
config: ReacordConfig = {},
) {
super(config) super(config)
client.on("interactionCreate", (interaction) => { client.on("interactionCreate", (interaction) => {
if (interaction.isButton() || interaction.isStringSelectMenu()) { if (interaction.isMessageComponent()) {
this.handleComponentInteraction( this.handleComponentInteraction(
this.createReacordComponentInteraction(interaction), this.createReacordComponentInteraction(interaction),
) )
@@ -47,7 +40,6 @@ export class ReacordDiscordJs extends Reacord {
/** /**
* Sends a message to a channel. * Sends a message to a channel.
*
* @see https://reacord.mapleleaf.dev/guides/sending-messages * @see https://reacord.mapleleaf.dev/guides/sending-messages
*/ */
override send( override send(
@@ -62,7 +54,6 @@ export class ReacordDiscordJs extends Reacord {
/** /**
* Sends a message as a reply to a command interaction. * Sends a message as a reply to a command interaction.
*
* @see https://reacord.mapleleaf.dev/guides/sending-messages * @see https://reacord.mapleleaf.dev/guides/sending-messages
*/ */
override reply( override reply(
@@ -77,7 +68,6 @@ export class ReacordDiscordJs extends Reacord {
/** /**
* Sends an ephemeral message as a reply to a command interaction. * Sends an ephemeral message as a reply to a command interaction.
*
* @see https://reacord.mapleleaf.dev/guides/sending-messages * @see https://reacord.mapleleaf.dev/guides/sending-messages
*/ */
override ephemeralReply( override ephemeralReply(
@@ -98,7 +88,7 @@ export class ReacordDiscordJs extends Reacord {
(await this.client.channels.fetch(channelId)) ?? (await this.client.channels.fetch(channelId)) ??
raise(`Channel ${channelId} not found`) raise(`Channel ${channelId} not found`)
if (!channel.isTextBased()) { if (!channel.isText()) {
raise(`Channel ${channelId} is not a text channel`) raise(`Channel ${channelId} is not a text channel`)
} }
@@ -121,14 +111,14 @@ export class ReacordDiscordJs extends Reacord {
...getDiscordMessageOptions(options), ...getDiscordMessageOptions(options),
fetchReply: true, fetchReply: true,
}) })
return createReacordMessage(message) return createReacordMessage(message as Discord.Message)
}, },
followUp: async (options) => { followUp: async (options) => {
const message = await interaction.followUp({ const message = await interaction.followUp({
...getDiscordMessageOptions(options), ...getDiscordMessageOptions(options),
fetchReply: true, fetchReply: true,
}) })
return createReacordMessage(message) return createReacordMessage(message as Discord.Message)
}, },
}) })
} }
@@ -196,8 +186,6 @@ export class ReacordDiscordJs extends Reacord {
? new Date(interaction.message.editedTimestamp).toISOString() ? new Date(interaction.message.editedTimestamp).toISOString()
: undefined, : undefined,
mentions: interaction.message.mentions.users.map((u) => u.id), mentions: interaction.message.mentions.users.map((u) => u.id),
authorId: interaction.message.author.id,
mentionEveryone: interaction.message.mentions.everyone,
} }
: raise("Message not found") : raise("Message not found")
@@ -216,13 +204,11 @@ export class ReacordDiscordJs extends Reacord {
]), ]),
), ),
displayName: interaction.member.displayName, displayName: interaction.member.displayName,
roles: interaction.member.roles.cache.map((role) => role.id), roles: [...interaction.member.roles.cache.map((role) => role.id)],
joinedAt: interaction.member.joinedAt?.toISOString(), joinedAt: interaction.member.joinedAt?.toISOString(),
premiumSince: interaction.member.premiumSince?.toISOString(), premiumSince: interaction.member.premiumSince?.toISOString(),
communicationDisabledUntil: communicationDisabledUntil:
interaction.member.communicationDisabledUntil?.toISOString(), interaction.member.communicationDisabledUntil?.toISOString(),
color: interaction.member.displayColor,
displayAvatarUrl: interaction.member.displayAvatarURL(),
} }
: undefined : undefined
@@ -237,7 +223,7 @@ export class ReacordDiscordJs extends Reacord {
...pruneNullishValues( ...pruneNullishValues(
pick(interaction.user, ["id", "username", "discriminator", "tag"]), pick(interaction.user, ["id", "username", "discriminator", "tag"]),
), ),
avatarUrl: interaction.user.avatarURL(), avatarUrl: interaction.user.avatarURL()!,
accentColor: interaction.user.accentColor ?? undefined, accentColor: interaction.user.accentColor ?? undefined,
} }
@@ -245,11 +231,7 @@ export class ReacordDiscordJs extends Reacord {
id: interaction.id, id: interaction.id,
customId: interaction.customId, customId: interaction.customId,
update: async (options: MessageOptions) => { update: async (options: MessageOptions) => {
if (interaction.deferred || interaction.replied) {
await interaction.message.edit(getDiscordMessageOptions(options))
} else {
await interaction.update(getDiscordMessageOptions(options)) await interaction.update(getDiscordMessageOptions(options))
}
}, },
deferUpdate: async () => { deferUpdate: async () => {
if (interaction.replied || interaction.deferred) return if (interaction.replied || interaction.deferred) return
@@ -260,14 +242,14 @@ export class ReacordDiscordJs extends Reacord {
...getDiscordMessageOptions(options), ...getDiscordMessageOptions(options),
fetchReply: true, fetchReply: true,
}) })
return createReacordMessage(message) return createReacordMessage(message as Discord.Message)
}, },
followUp: async (options) => { followUp: async (options) => {
const message = await interaction.followUp({ const message = await interaction.followUp({
...getDiscordMessageOptions(options), ...getDiscordMessageOptions(options),
fetchReply: true, fetchReply: true,
}) })
return createReacordMessage(message) return createReacordMessage(message as Discord.Message)
}, },
event: { event: {
channel, channel,
@@ -296,7 +278,7 @@ export class ReacordDiscordJs extends Reacord {
} }
} }
if (interaction.isStringSelectMenu()) { if (interaction.isSelectMenu()) {
return { return {
...baseProps, ...baseProps,
type: "select", type: "select",
@@ -319,6 +301,15 @@ function createReacordMessage(message: Discord.Message): Message {
delete: async () => { delete: async () => {
await message.delete() await message.delete()
}, },
updateFiles: async (files) => {
await message.edit({
files: files.map(({ name, description, data }) => ({
name,
description,
attachment: data,
})),
})
},
} }
} }
@@ -328,6 +319,10 @@ function createEphemeralReacordMessage(): Message {
console.warn("Ephemeral messages can't be edited") console.warn("Ephemeral messages can't be edited")
return Promise.resolve() return Promise.resolve()
}, },
updateFiles: () => {
console.warn("Ephemeral messages can't be edited")
return Promise.resolve()
},
delete: () => { delete: () => {
console.warn("Ephemeral messages can't be deleted") console.warn("Ephemeral messages can't be deleted")
return Promise.resolve() return Promise.resolve()
@@ -335,55 +330,34 @@ function createEphemeralReacordMessage(): Message {
} }
} }
function convertButtonStyleToEnum(style: MessageButtonOptions["style"]) {
const styleMap = {
primary: Discord.ButtonStyle.Primary,
secondary: Discord.ButtonStyle.Secondary,
success: Discord.ButtonStyle.Success,
danger: Discord.ButtonStyle.Danger,
} as const
return styleMap[style ?? "secondary"]
}
// TODO: this could be a part of the core library, // TODO: this could be a part of the core library,
// and also handle some edge cases, e.g. empty messages // and also handle some edge cases, e.g. empty messages
function getDiscordMessageOptions(reacordOptions: MessageOptions) { function getDiscordMessageOptions(
const options = { reacordOptions: MessageOptions,
content: reacordOptions.content || undefined, ): Discord.MessageOptions {
const options: Discord.MessageOptions = {
// eslint-disable-next-line unicorn/no-null
content: reacordOptions.content || null,
embeds: reacordOptions.embeds, embeds: reacordOptions.embeds,
components: reacordOptions.actionRows.map((row) => ({ components: reacordOptions.actionRows.map((row) => ({
type: Discord.ComponentType.ActionRow, type: "ACTION_ROW",
components: row.map( components: row.map(
(component): Discord.MessageActionRowComponentData => { (component): Discord.MessageActionRowComponentOptions => {
if (component.type === "button") { if (component.type === "button") {
return { return {
type: Discord.ComponentType.Button, type: "BUTTON",
customId: component.customId, customId: component.customId,
label: component.label ?? "", label: component.label ?? "",
style: convertButtonStyleToEnum(component.style), style: toUpper(component.style ?? "secondary"),
disabled: component.disabled, disabled: component.disabled,
emoji: component.emoji, emoji: component.emoji,
} }
} }
if (component.type === "link") {
return {
type: Discord.ComponentType.Button,
url: component.url,
label: component.label ?? "",
style: Discord.ButtonStyle.Link,
disabled: component.disabled,
emoji: component.emoji,
}
}
// future proofing
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (component.type === "select") { if (component.type === "select") {
return { return {
...component, ...component,
type: Discord.ComponentType.SelectMenu, type: "SELECT_MENU",
options: component.options.map((option) => ({ options: component.options.map((option) => ({
...option, ...option,
default: component.values?.includes(option.value), default: component.values?.includes(option.value),
@@ -391,16 +365,16 @@ function getDiscordMessageOptions(reacordOptions: MessageOptions) {
} }
} }
component satisfies never raise(`Unsupported component type: ${component.type}`)
throw new Error(
`Invalid component type ${safeJsonStringify(component)}}`,
)
}, },
), ),
})), })),
} }
if (!options.content && !options.embeds.length) { const hasContent =
options.content || options.embeds?.length || options.files?.length
if (!hasContent) {
options.content = "_ _" options.content = "_ _"
} }

View File

@@ -1,22 +1,25 @@
import type { ReactNode } from "react" import type { ReactNode } from "react"
import type { ComponentInteraction } from "../internal/interaction.js" import React from "react"
import type { ComponentInteraction } from "../internal/interaction"
import { reconciler } from "../internal/reconciler.js" import { reconciler } from "../internal/reconciler.js"
import type { Renderer } from "../internal/renderers/renderer.js" import type { Renderer } from "../internal/renderers/renderer"
import { InstanceProvider } from "./instance-context.js" import type { ReacordInstance } from "./instance"
import type { ReacordInstance } from "./instance.js" import { InstanceProvider } from "./instance-context"
/** @category Core */ /**
export interface ReacordConfig { * @category Core
*/
export type ReacordConfig = {
/** /**
* The max number of active instances. When this limit is exceeded, the oldest * The max number of active instances.
* instances will be disabled. * When this limit is exceeded, the oldest instances will be disabled.
*/ */
maxInstances?: number maxInstances?: number
} }
/** /**
* The main Reacord class that other Reacord adapters should extend. Only use * The main Reacord class that other Reacord adapters should extend.
* this directly if you're making [a custom adapter](/guides/custom-adapters). * Only use this directly if you're making [a custom adapter](/guides/custom-adapters).
*/ */
export abstract class Reacord { export abstract class Reacord {
private renderers: Renderer[] = [] private renderers: Renderer[] = []
@@ -38,22 +41,13 @@ export abstract class Reacord {
} }
protected createInstance(renderer: Renderer, initialContent?: ReactNode) { protected createInstance(renderer: Renderer, initialContent?: ReactNode) {
if (this.renderers.length > this.maxInstances && this.renderers[0]) { if (this.renderers.length > this.maxInstances) {
this.deactivate(this.renderers[0]) this.deactivate(this.renderers[0]!)
} }
this.renderers.push(renderer) this.renderers.push(renderer)
const container: unknown = reconciler.createContainer( const container = reconciler.createContainer(renderer, 0, false, {})
renderer,
0,
null,
false,
null,
"reacord",
() => {},
null,
)
const instance: ReacordInstance = { const instance: ReacordInstance = {
render: (content: ReactNode) => { render: (content: ReactNode) => {
@@ -69,6 +63,9 @@ export abstract class Reacord {
this.renderers = this.renderers.filter((it) => it !== renderer) this.renderers = this.renderers.filter((it) => it !== renderer)
renderer.destroy() renderer.destroy()
}, },
attach: (file) => {
renderer.attach(file)
},
} }
if (initialContent !== undefined) { if (initialContent !== undefined) {

View File

@@ -1,5 +1,7 @@
import { ReacordFile } from "../core/file"
import type { Message, MessageOptions } from "./message" import type { Message, MessageOptions } from "./message"
export interface Channel { export type Channel = {
send(message: MessageOptions): Promise<Message> send(message: MessageOptions): Promise<Message>
sendFiles(files: readonly ReacordFile[]): Promise<Message>
} }

View File

@@ -21,18 +21,6 @@ export class Container<T> {
this.items = [] this.items = []
} }
find(predicate: (item: T) => boolean): T | undefined {
return this.items.find(predicate)
}
findType<U extends T>(
type: new (...args: Array<NonNullable<unknown>>) => U,
): U | undefined {
for (const item of this.items) {
if (item instanceof type) return item
}
}
[Symbol.iterator]() { [Symbol.iterator]() {
return this.items[Symbol.iterator]() return this.items[Symbol.iterator]()
} }

View File

@@ -1,6 +1,6 @@
import type { Node } from "./node"
import type { ReactNode } from "react" import type { ReactNode } from "react"
import React from "react" import React from "react"
import type { Node } from "./node"
export function ReacordElement<Props>(props: { export function ReacordElement<Props>(props: {
props: Props props: Props

View File

@@ -17,7 +17,7 @@ export type SelectInteraction = BaseComponentInteraction<
SelectChangeEvent SelectChangeEvent
> >
export interface BaseInteraction<Type extends string> { export type BaseInteraction<Type extends string> = {
type: Type type: Type
id: string id: string
reply(messageOptions: MessageOptions): Promise<Message> reply(messageOptions: MessageOptions): Promise<Message>

View File

@@ -1,9 +1,10 @@
import type { Except } from "type-fest"
import { last } from "../../helpers/last"
import type { EmbedOptions } from "../core/components/embed-options" import type { EmbedOptions } from "../core/components/embed-options"
import type { SelectProps } from "../core/components/select" import type { SelectProps } from "../core/components/select"
import { last } from "@reacord/helpers/last" import { ReacordFile } from "../main"
import type { Except } from "type-fest"
export interface MessageOptions { export type MessageOptions = {
content: string content: string
embeds: EmbedOptions[] embeds: EmbedOptions[]
actionRows: ActionRow[] actionRows: ActionRow[]
@@ -16,7 +17,7 @@ export type ActionRowItem =
| MessageLinkOptions | MessageLinkOptions
| MessageSelectOptions | MessageSelectOptions
export interface MessageButtonOptions { export type MessageButtonOptions = {
type: "button" type: "button"
customId: string customId: string
label?: string label?: string
@@ -25,7 +26,7 @@ export interface MessageButtonOptions {
emoji?: string emoji?: string
} }
export interface MessageLinkOptions { export type MessageLinkOptions = {
type: "link" type: "link"
url: string url: string
label?: string label?: string
@@ -39,16 +40,17 @@ export type MessageSelectOptions = Except<SelectProps, "children" | "value"> & {
options: MessageSelectOptionOptions[] options: MessageSelectOptionOptions[]
} }
export interface MessageSelectOptionOptions { export type MessageSelectOptionOptions = {
label: string label: string
value: string value: string
description?: string description?: string
emoji?: string emoji?: string
} }
export interface Message { export type Message = {
edit(options: MessageOptions): Promise<void> edit(options: MessageOptions): Promise<void>
delete(): Promise<void> delete(): Promise<void>
updateFiles(files: readonly ReacordFile[]): Promise<void>
} }
export function getNextActionRow(options: MessageOptions): ActionRow { export function getNextActionRow(options: MessageOptions): ActionRow {

View File

@@ -1,3 +1,4 @@
/* eslint-disable class-methods-use-this */
import { Container } from "./container.js" import { Container } from "./container.js"
import type { ComponentInteraction } from "./interaction" import type { ComponentInteraction } from "./interaction"
import type { MessageOptions } from "./message" import type { MessageOptions } from "./message"
@@ -7,15 +8,9 @@ export abstract class Node<Props> {
constructor(public props: Props) {} constructor(public props: Props) {}
modifyMessageOptions(_options: MessageOptions) { modifyMessageOptions(options: MessageOptions) {}
// noop
}
handleComponentInteraction(_interaction: ComponentInteraction): boolean { handleComponentInteraction(interaction: ComponentInteraction): boolean {
return false return false
} }
get text(): string {
return [...this.children].map((child) => child.text).join("")
}
} }

View File

@@ -1,7 +1,6 @@
import { raise } from "@reacord/helpers/raise.js"
import type { HostConfig } from "react-reconciler" import type { HostConfig } from "react-reconciler"
import ReactReconciler from "react-reconciler" import ReactReconciler from "react-reconciler"
import { DefaultEventPriority } from "react-reconciler/constants.js" import { raise } from "../../helpers/raise.js"
import { Node } from "./node.js" import { Node } from "./node.js"
import type { Renderer } from "./renderers/renderer" import type { Renderer } from "./renderers/renderer"
import { TextNode } from "./text-node.js" import { TextNode } from "./text-node.js"
@@ -21,6 +20,8 @@ const config: HostConfig<
number, // TimeoutHandle, number, // TimeoutHandle,
number // NoTimeout, number // NoTimeout,
> = { > = {
// config
now: Date.now,
supportsMutation: true, supportsMutation: true,
supportsPersistence: false, supportsPersistence: false,
supportsHydration: false, supportsHydration: false,
@@ -29,6 +30,7 @@ const config: HostConfig<
cancelTimeout: global.clearTimeout, cancelTimeout: global.clearTimeout,
noTimeout: -1, noTimeout: -1,
// eslint-disable-next-line unicorn/no-null
getRootHostContext: () => null, getRootHostContext: () => null,
getChildHostContext: (parentContext) => parentContext, getChildHostContext: (parentContext) => parentContext,
@@ -41,7 +43,7 @@ const config: HostConfig<
raise(`Missing createNode function`) raise(`Missing createNode function`)
} }
const node: unknown = props.createNode(props.props) const node = props.createNode(props.props)
if (!(node instanceof Node)) { if (!(node instanceof Node)) {
raise(`createNode function did not return a Node`) raise(`createNode function did not return a Node`)
} }
@@ -50,11 +52,8 @@ const config: HostConfig<
}, },
createTextInstance: (text) => new TextNode(text), createTextInstance: (text) => new TextNode(text),
shouldSetTextContent: () => false, shouldSetTextContent: () => false,
detachDeletedInstance: (_instance) => {}, // @ts-expect-error
beforeActiveInstanceBlur: () => {}, detachDeletedInstance: (instance) => {},
afterActiveInstanceBlur: () => {},
getInstanceFromNode: (_node: unknown) => null,
getInstanceFromScope: (_scopeInstance: unknown) => null,
clearContainer: (renderer) => { clearContainer: (renderer) => {
renderer.nodes.clear() renderer.nodes.clear()
@@ -90,18 +89,16 @@ const config: HostConfig<
node.props = newText node.props = newText
}, },
// eslint-disable-next-line unicorn/no-null
prepareForCommit: () => null, prepareForCommit: () => null,
resetAfterCommit: (renderer) => { resetAfterCommit: (renderer) => {
renderer.render() renderer.render()
}, },
prepareScopeUpdate: (_scopeInstance: unknown, _instance: unknown) => {},
preparePortalMount: () => raise("Portals are not supported"), preparePortalMount: () => raise("Portals are not supported"),
getPublicInstance: () => raise("Refs are currently not supported"), getPublicInstance: () => raise("Refs are currently not supported"),
finalizeInitialChildren: () => false, finalizeInitialChildren: () => false,
getCurrentEventPriority: () => DefaultEventPriority,
} }
export const reconciler = ReactReconciler(config) export const reconciler = ReactReconciler(config)

View File

@@ -1,3 +1,4 @@
import { ReacordFile } from "../../core/file"
import type { Channel } from "../channel" import type { Channel } from "../channel"
import type { Message, MessageOptions } from "../message" import type { Message, MessageOptions } from "../message"
import { Renderer } from "./renderer" import { Renderer } from "./renderer"
@@ -10,4 +11,10 @@ export class ChannelMessageRenderer extends Renderer {
protected createMessage(options: MessageOptions): Promise<Message> { protected createMessage(options: MessageOptions): Promise<Message> {
return this.channel.send(options) return this.channel.send(options)
} }
protected createMessageFromFiles(
files: readonly ReacordFile[],
): Promise<Message> {
return this.channel.sendFiles(files)
}
} }

View File

@@ -1,21 +1,28 @@
import { Subject } from "rxjs"
import { concatMap } from "rxjs/operators"
import { ReacordFile } from "../../core/file"
import { Container } from "../container.js" import { Container } from "../container.js"
import type { ComponentInteraction } from "../interaction" import type { ComponentInteraction } from "../interaction"
import type { Message, MessageOptions } from "../message" import type { Message, MessageOptions } from "../message"
import type { Node } from "../node.js" import type { Node } from "../node.js"
import { Subject } from "rxjs"
import { concatMap } from "rxjs/operators"
type UpdatePayload = type UpdatePayload =
| { action: "update" | "deactivate"; options: MessageOptions } | { action: "update" | "deactivate"; options: MessageOptions }
| { action: "files"; files: readonly ReacordFile[] }
| { action: "deferUpdate"; interaction: ComponentInteraction } | { action: "deferUpdate"; interaction: ComponentInteraction }
| { action: "destroy" } | { action: "destroy" }
type NewMessagePayload =
| { source: "content"; messageOptions?: MessageOptions }
| { source: "files"; files?: readonly ReacordFile[] }
export abstract class Renderer { export abstract class Renderer {
readonly nodes = new Container<Node<unknown>>() readonly nodes = new Container<Node<unknown>>()
private componentInteraction?: ComponentInteraction private componentInteraction?: ComponentInteraction
private message?: Message private message?: Message
private active = true private active = true
private updates = new Subject<UpdatePayload>() private updates = new Subject<UpdatePayload>()
private files: readonly ReacordFile[] = []
private updateSubscription = this.updates private updateSubscription = this.updates
.pipe(concatMap((payload) => this.updateMessage(payload))) .pipe(concatMap((payload) => this.updateMessage(payload)))
@@ -46,19 +53,26 @@ export abstract class Renderer {
this.updates.next({ action: "destroy" }) this.updates.next({ action: "destroy" })
} }
attach(file: ReacordFile) {
const newFiles = (this.files = [...this.files, file])
this.updates.next({ action: "files", files: newFiles })
}
handleComponentInteraction(interaction: ComponentInteraction) { handleComponentInteraction(interaction: ComponentInteraction) {
for (const node of this.nodes) {
if (node.handleComponentInteraction(interaction)) {
this.componentInteraction = interaction this.componentInteraction = interaction
setTimeout(() => { setTimeout(() => {
this.updates.next({ action: "deferUpdate", interaction }) this.updates.next({ action: "deferUpdate", interaction })
}, 500) }, 500)
for (const node of this.nodes) {
if (node.handleComponentInteraction(interaction)) {
return true return true
} }
} }
} }
protected abstract createMessage(options: MessageOptions): Promise<Message> protected abstract createMessage(options: NewMessagePayload): Promise<Message>
private getMessageOptions(): MessageOptions { private getMessageOptions(): MessageOptions {
const options: MessageOptions = { const options: MessageOptions = {
@@ -100,6 +114,15 @@ export abstract class Renderer {
return return
} }
if (payload.action === "files") {
if (this.message) {
await this.message?.updateFiles(payload.files)
} else {
this.message = await this.createMessageFromFiles(payload.files)
}
return
}
if (this.componentInteraction) { if (this.componentInteraction) {
const promise = this.componentInteraction.update(payload.options) const promise = this.componentInteraction.update(payload.options)
this.componentInteraction = undefined this.componentInteraction = undefined

View File

@@ -5,8 +5,4 @@ export class TextNode extends Node<string> {
override modifyMessageOptions(options: MessageOptions) { override modifyMessageOptions(options: MessageOptions) {
options.content = options.content + this.props options.content = options.content + this.props
} }
override get text() {
return this.props
}
} }

View File

@@ -12,6 +12,7 @@ export * from "./core/components/embed-title"
export * from "./core/components/link" export * from "./core/components/link"
export * from "./core/components/option" export * from "./core/components/option"
export * from "./core/components/select" export * from "./core/components/select"
export * from "./core/file"
export * from "./core/instance" export * from "./core/instance"
export { useInstance } from "./core/instance-context" export { useInstance } from "./core/instance-context"
export * from "./core/reacord" export * from "./core/reacord"

View File

@@ -2,7 +2,7 @@
"name": "reacord", "name": "reacord",
"type": "module", "type": "module",
"description": "Create interactive Discord messages using React.", "description": "Create interactive Discord messages using React.",
"version": "0.5.3", "version": "0.3.5",
"types": "./dist/main.d.ts", "types": "./dist/main.d.ts",
"homepage": "https://reacord.mapleleaf.dev", "homepage": "https://reacord.mapleleaf.dev",
"repository": "https://github.com/itsMapleLeaf/reacord.git", "repository": "https://github.com/itsMapleLeaf/reacord.git",
@@ -20,7 +20,6 @@
"reacord" "reacord"
], ],
"files": [ "files": [
"library",
"dist", "dist",
"README.md", "README.md",
"LICENSE" "LICENSE"
@@ -28,8 +27,7 @@
"exports": { "exports": {
".": { ".": {
"import": "./dist/main.js", "import": "./dist/main.js",
"require": "./dist/main.cjs", "require": "./dist/main.cjs"
"types": "./library/main.ts"
}, },
"./package.json": { "./package.json": {
"import": "./package.json", "import": "./package.json",
@@ -37,22 +35,24 @@
} }
}, },
"scripts": { "scripts": {
"build": "cpy ../../README.md ../../LICENSE . && tsup library/main.ts --target node16 --format cjs,esm --sourcemap", "build": "tsup-node library/main.ts --target node16 --format cjs,esm --dts --sourcemap",
"build-watch": "pnpm build -- --watch", "build-watch": "pnpm build -- --watch",
"test": "vitest --coverage --no-watch", "test": "vitest --coverage --no-watch",
"test-dev": "vitest", "test-dev": "vitest",
"test-manual": "nodemon --exec tsx --ext ts,tsx ./scripts/discordjs-manual-test.tsx", "typecheck": "tsc --noEmit",
"typecheck": "tsc -b" "playground": "nodemon --exec esmo --ext ts,tsx --inspect=5858 --enable-source-maps ./playground/main.tsx",
"release": "bash scripts/release.sh"
}, },
"dependencies": { "dependencies": {
"@types/node": "^20.7.0", "@types/node": "*",
"@types/react": "^18.2.23", "@types/react": "*",
"@types/react-reconciler": "^0.28.5", "@types/react-reconciler": "^0.26.6",
"react-reconciler": "^0.29.0", "nanoid": "^3.3.3",
"rxjs": "^7.8.1" "react-reconciler": "^0.27.0",
"rxjs": "^7.5.5"
}, },
"peerDependencies": { "peerDependencies": {
"discord.js": "^14", "discord.js": "^13.3",
"react": ">=17" "react": ">=17"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
@@ -61,20 +61,27 @@
} }
}, },
"devDependencies": { "devDependencies": {
"@reacord/helpers": "workspace:*", "@types/lodash-es": "^4.17.6",
"@types/lodash-es": "^4.17.9", "c8": "^7.11.2",
"c8": "^8.0.1", "discord.js": "^13.6.0",
"cpy-cli": "^5.0.0", "dotenv": "^16.0.0",
"discord.js": "^14.13.0", "esbuild": "latest",
"dotenv": "^16.3.1", "esbuild-jest": "^0.5.0",
"esmo": "^0.14.1",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"nodemon": "^3.0.1", "nodemon": "^2.0.15",
"prettier": "^3.0.3", "prettier": "^2.6.2",
"pretty-ms": "^8.0.0", "pretty-ms": "^7.0.1",
"react": "^18.2.0", "react": "^18.0.0",
"tsup": "^7.2.0", "release-it": "^14.14.2",
"tsx": "^3.13.0", "tsup": "^5.12.6",
"type-fest": "^4.3.2" "type-fest": "^2.12.2",
"typescript": "^4.6.3",
"vite": "^2.9.5",
"vitest": "^0.9.4"
},
"resolutions": {
"esbuild": "latest"
}, },
"release-it": { "release-it": {
"git": { "git": {
@@ -84,8 +91,5 @@
"release": true, "release": true,
"web": true "web": true
} }
},
"publishConfig": {
"access": "public"
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 954 KiB

View File

@@ -0,0 +1,36 @@
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 guild of client.guilds.cache.values()) {
client.application!.commands.set(
commands.map(({ name, description }) => ({
name,
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,36 @@
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"
emoji="<:plus_one:778531744860602388>"
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({
onConfirm,
}: {
onConfirm: (choice: string) => void
}) {
const [value, setValue] = useState<string>()
return (
<>
<Select
placeholder="choose a fruit"
value={value}
onChangeValue={setValue}
>
<Option value="🍎" />
<Option value="🍌" />
<Option value="🍒" />
</Select>
<Button
label="confirm"
disabled={value == undefined}
onClick={() => {
if (value) onConfirm(value)
}}
/>
</>
)
}

View File

@@ -0,0 +1,125 @@
import { Client } from "discord.js"
import "dotenv/config"
import { readFile } from "fs/promises"
import { join } from "path"
import React from "react"
import { fileURLToPath } from "url"
import { Button, ReacordDiscordJs, useInstance } 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) => {
const instance = reacord.reply(
interaction,
<FruitSelect
onConfirm={(value) => {
instance.render(`you chose ${value}`)
instance.deactivate()
}}
/>,
)
},
},
{
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")}
/>
</>,
)
},
},
{
name: "delete-this",
description: "delete this",
run: (interaction) => {
function DeleteThis() {
const instance = useInstance()
return <Button label="delete this" onClick={() => instance.destroy()} />
}
reacord.reply(interaction, <DeleteThis />)
},
},
{
name: "anime",
description: "shows an anime image",
run: async (interaction) => {
const reply = reacord.reply(interaction)
const image = await readFile(
join(fileURLToPath(import.meta.url), "../anime.jpg"),
)
reply.attach({ name: "anime.jpg", data: image })
// reply.render("anime")
},
},
])
await client.login(process.env.TEST_BOT_TOKEN)

View File

@@ -1,144 +0,0 @@
import { raise } from "@reacord/helpers/raise.js"
import {
Button,
Link,
Option,
ReacordDiscordJs,
Select,
useInstance,
} from "../library/main.js"
import type { TextChannel } from "discord.js"
import { ChannelType, Client, IntentsBitField } from "discord.js"
import "dotenv/config"
import { kebabCase } from "lodash-es"
import * as React from "react"
import { useState } from "react"
const client = new Client({ intents: IntentsBitField.Flags.Guilds })
const reacord = new ReacordDiscordJs(client)
await client.login(process.env.TEST_BOT_TOKEN)
const guild = await client.guilds.fetch(
process.env.TEST_GUILD_ID ?? raise("TEST_GUILD_ID not defined"),
)
const category = await guild.channels.fetch(
process.env.TEST_CATEGORY_ID ?? raise("TEST_CATEGORY_ID not defined"),
)
if (category?.type !== ChannelType.GuildCategory) {
throw new Error(
`channel ${process.env.TEST_CATEGORY_ID} is not a guild category. received ${category?.type}`,
)
}
for (const [, channel] of category.children.cache) {
await channel.delete()
}
let prefix = 0
const createTest = async (
name: string,
block: (channel: TextChannel) => unknown,
) => {
prefix += 1
const channel = await category.children.create({
type: ChannelType.GuildText,
name: `${String(prefix).padStart(3, "0")}-${kebabCase(name)}`,
})
await block(channel)
}
await createTest("basic", (channel) => {
reacord.send(channel.id, "Hello, world!")
})
await createTest("counter", (channel) => {
const Counter = () => {
const [count, setCount] = React.useState(0)
return (
<>
count: {count}
<Button
style="primary"
emoji=""
onClick={() => setCount(count + 1)}
/>
<Button
style="primary"
emoji=""
onClick={() => setCount(count - 1)}
/>
<Button label="reset" onClick={() => setCount(0)} />
</>
)
}
reacord.send(channel.id, <Counter />)
})
await createTest("select", (channel) => {
function FruitSelect({ onConfirm }: { onConfirm: (choice: string) => void }) {
const [value, setValue] = useState<string>()
return (
<>
<Select
placeholder="choose a fruit"
value={value}
onChangeValue={setValue}
>
<Option value="🍎" emoji="🍎" label="apple" description="it red" />
<Option value="🍌" emoji="🍌" label="banana" description="bnanbna" />
<Option value="🍒" emoji="🍒" label="cherry" description="heh" />
</Select>
<Button
label="confirm"
disabled={value == undefined}
onClick={() => {
if (value) onConfirm(value)
}}
/>
</>
)
}
const instance = reacord.send(
channel.id,
<FruitSelect
onConfirm={(value) => {
instance.render(`you chose ${value}`)
instance.deactivate()
}}
/>,
)
})
await createTest("ephemeral button", (channel) => {
reacord.send(
channel.id,
<>
<Button
label="public clic"
onClick={(event) =>
event.reply(`${event.guild?.member.displayName} clic`)
}
/>
<Button
label="clic"
onClick={(event) => event.ephemeralReply("you clic")}
/>
</>,
)
})
await createTest("delete this", (channel) => {
function DeleteThis() {
const instance = useInstance()
return <Button label="delete this" onClick={() => instance.destroy()} />
}
reacord.send(channel.id, <DeleteThis />)
})
await createTest("link", (channel) => {
reacord.send(channel.id, <Link label="hi" url="https://mapleleaf.dev" />)
})

View File

@@ -0,0 +1,4 @@
pnpm build
cp ../../README.md .
cp ../../LICENSE .
pnpx release-it

View File

@@ -1,3 +1,4 @@
import React from "react"
import { test } from "vitest" import { test } from "vitest"
import { ActionRow, Button, Select } from "../library/main" import { ActionRow, Button, Select } from "../library/main"
import { ReacordTester } from "./test-adapter" import { ReacordTester } from "./test-adapter"

View File

@@ -1,12 +0,0 @@
import { spawnSync } from "node:child_process"
import { createRequire } from "node:module"
import { beforeAll, expect, test } from "vitest"
beforeAll(() => {
spawnSync("pnpm", ["run", "build"])
})
test("can require commonjs", () => {
const require = createRequire(import.meta.url)
expect(() => require("../dist/main.cjs") as unknown).not.toThrow()
})

View File

@@ -1,3 +1,4 @@
import React from "react"
import { test } from "vitest" import { test } from "vitest"
import { import {
Embed, Embed,

View File

@@ -1,3 +1,2 @@
import { test } from "vitest" import { test } from "vitest"
test.todo("ephemeral reply") test.todo("ephemeral reply")

View File

@@ -1,3 +1,4 @@
import React from "react"
import { test } from "vitest" import { test } from "vitest"
import { Link } from "../library/main" import { Link } from "../library/main"
import { ReacordTester } from "./test-adapter" import { ReacordTester } from "./test-adapter"

View File

@@ -1,7 +1,7 @@
import { Button, Embed, EmbedField, EmbedTitle } from "../library/main"
import { ReacordTester } from "./test-adapter"
import * as React from "react" import * as React from "react"
import { test } from "vitest" import { test } from "vitest"
import { Button, Embed, EmbedField, EmbedTitle } from "../library/main"
import { ReacordTester } from "./test-adapter"
test("rendering behavior", async () => { test("rendering behavior", async () => {
const tester = new ReacordTester() const tester = new ReacordTester()
@@ -35,7 +35,7 @@ test("rendering behavior", async () => {
}, },
]) ])
await tester.findButtonByLabel("show embed").click() tester.findButtonByLabel("show embed").click()
await tester.assertMessages([ await tester.assertMessages([
{ {
content: "count: 0", content: "count: 0",
@@ -62,7 +62,7 @@ test("rendering behavior", async () => {
}, },
]) ])
await tester.findButtonByLabel("clicc").click() tester.findButtonByLabel("clicc").click()
await tester.assertMessages([ await tester.assertMessages([
{ {
content: "count: 1", content: "count: 1",
@@ -94,7 +94,7 @@ test("rendering behavior", async () => {
}, },
]) ])
await tester.findButtonByLabel("clicc").click() tester.findButtonByLabel("clicc").click()
await tester.assertMessages([ await tester.assertMessages([
{ {
content: "count: 2", content: "count: 2",
@@ -126,7 +126,7 @@ test("rendering behavior", async () => {
}, },
]) ])
await tester.findButtonByLabel("hide embed").click() tester.findButtonByLabel("hide embed").click()
await tester.assertMessages([ await tester.assertMessages([
{ {
content: "count: 2", content: "count: 2",
@@ -153,7 +153,7 @@ test("rendering behavior", async () => {
}, },
]) ])
await tester.findButtonByLabel("clicc").click() tester.findButtonByLabel("clicc").click()
await tester.assertMessages([ await tester.assertMessages([
{ {
content: "count: 3", content: "count: 3",
@@ -180,7 +180,7 @@ test("rendering behavior", async () => {
}, },
]) ])
await tester.findButtonByLabel("deactivate").click() tester.findButtonByLabel("deactivate").click()
await tester.assertMessages([ await tester.assertMessages([
{ {
content: "count: 3", content: "count: 3",
@@ -210,7 +210,7 @@ test("rendering behavior", async () => {
}, },
]) ])
await tester.findButtonByLabel("clicc").click() tester.findButtonByLabel("clicc").click()
await tester.assertMessages([ await tester.assertMessages([
{ {
content: "count: 3", content: "count: 3",

View File

@@ -1,4 +1,4 @@
import { useState } from "react" import React, { useState } from "react"
import { expect, test, vi } from "vitest" import { expect, test, vi } from "vitest"
import { Button, Option, Select } from "../library/main" import { Button, Option, Select } from "../library/main"
import { ReacordTester } from "./test-adapter" import { ReacordTester } from "./test-adapter"
@@ -59,16 +59,16 @@ test("single select", async () => {
await assertSelect([]) await assertSelect([])
expect(onSelect).toHaveBeenCalledTimes(0) expect(onSelect).toHaveBeenCalledTimes(0)
await tester.findSelectByPlaceholder("choose one").select("2") tester.findSelectByPlaceholder("choose one").select("2")
await assertSelect(["2"]) await assertSelect(["2"])
expect(onSelect).toHaveBeenCalledWith( expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({ values: ["2"] }), expect.objectContaining({ values: ["2"] }),
) )
await tester.findButtonByLabel("disable").click() tester.findButtonByLabel("disable").click()
await assertSelect(["2"], true) await assertSelect(["2"], true)
await tester.findSelectByPlaceholder("choose one").select("1") tester.findSelectByPlaceholder("choose one").select("1")
await assertSelect(["2"], true) await assertSelect(["2"], true)
expect(onSelect).toHaveBeenCalledTimes(1) expect(onSelect).toHaveBeenCalledTimes(1)
}) })
@@ -125,23 +125,19 @@ test("multiple select", async () => {
await assertSelect([]) await assertSelect([])
expect(onSelect).toHaveBeenCalledTimes(0) expect(onSelect).toHaveBeenCalledTimes(0)
await tester.findSelectByPlaceholder("select").select("1", "3") tester.findSelectByPlaceholder("select").select("1", "3")
await assertSelect(expect.arrayContaining(["1", "3"]) as unknown as string[]) await assertSelect(expect.arrayContaining(["1", "3"]) as unknown as string[])
expect(onSelect).toHaveBeenCalledWith( expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({ values: expect.arrayContaining(["1", "3"]) }),
values: expect.arrayContaining(["1", "3"]) as unknown,
}),
) )
await tester.findSelectByPlaceholder("select").select("2") tester.findSelectByPlaceholder("select").select("2")
await assertSelect(expect.arrayContaining(["2"]) as unknown as string[]) await assertSelect(expect.arrayContaining(["2"]) as unknown as string[])
expect(onSelect).toHaveBeenCalledWith( expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({ values: expect.arrayContaining(["2"]) }),
values: expect.arrayContaining(["2"]) as unknown,
}),
) )
await tester.findSelectByPlaceholder("select").select() tester.findSelectByPlaceholder("select").select()
await assertSelect([]) await assertSelect([])
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ values: [] })) expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ values: [] }))
}) })
@@ -149,7 +145,7 @@ test("multiple select", async () => {
test("optional onSelect + unknown value", async () => { test("optional onSelect + unknown value", async () => {
const tester = new ReacordTester() const tester = new ReacordTester()
tester.reply().render(<Select placeholder="select" />) tester.reply().render(<Select placeholder="select" />)
await tester.findSelectByPlaceholder("select").select("something") tester.findSelectByPlaceholder("select").select("something")
await tester.assertMessages([ await tester.assertMessages([
{ {
content: "", content: "",

View File

@@ -1,12 +1,14 @@
import { logPretty } from "@reacord/helpers/log-pretty" /* eslint-disable class-methods-use-this */
import { omit } from "@reacord/helpers/omit" /* eslint-disable require-await */
import { pruneNullishValues } from "@reacord/helpers/prune-nullish-values" import { nanoid } from "nanoid"
import { raise } from "@reacord/helpers/raise"
import { waitFor } from "@reacord/helpers/wait-for"
import { randomUUID } from "node:crypto"
import { setTimeout } from "node:timers/promises" import { setTimeout } from "node:timers/promises"
import type { ReactNode } from "react" import type { ReactNode } from "react"
import { expect } from "vitest" import { expect } from "vitest"
import { logPretty } from "../helpers/log-pretty"
import { omit } from "../helpers/omit"
import { pruneNullishValues } from "../helpers/prune-nullish-values"
import { raise } from "../helpers/raise"
import { waitFor } from "../helpers/wait-for"
import type { import type {
ChannelInfo, ChannelInfo,
GuildInfo, GuildInfo,
@@ -30,7 +32,9 @@ import { InteractionReplyRenderer } from "../library/internal/renderers/interact
export type MessageSample = ReturnType<ReacordTester["sampleMessages"]>[0] export type MessageSample = ReturnType<ReacordTester["sampleMessages"]>[0]
/** A Record adapter for automated tests. WIP */ /**
* A Record adapter for automated tests. WIP
*/
export class ReacordTester extends Reacord { export class ReacordTester extends Reacord {
private messageContainer = new Container<TestMessage>() private messageContainer = new Container<TestMessage>()
@@ -190,7 +194,7 @@ class TestCommandInteraction implements CommandInteraction {
} }
class TestInteraction { class TestInteraction {
readonly id = randomUUID() readonly id = nanoid()
readonly channelId = "test-channel-id" readonly channelId = "test-channel-id"
constructor( constructor(
@@ -248,10 +252,10 @@ class TestSelectInteraction
class TestComponentEvent { class TestComponentEvent {
constructor(private tester: ReacordTester) {} constructor(private tester: ReacordTester) {}
message: MessageInfo = {} as MessageInfo // todo message: MessageInfo = {} as any // todo
channel: ChannelInfo = {} as ChannelInfo // todo channel: ChannelInfo = {} as any // todo
user: UserInfo = {} as UserInfo // todo user: UserInfo = {} as any // todo
guild: GuildInfo = {} as GuildInfo // todo guild: GuildInfo = {} as any // todo
reply(content?: ReactNode): ReacordInstance { reply(content?: ReactNode): ReacordInstance {
return this.tester.reply(content) return this.tester.reply(content)
@@ -270,10 +274,7 @@ class TestSelectChangeEvent
extends TestComponentEvent extends TestComponentEvent
implements SelectChangeEvent implements SelectChangeEvent
{ {
constructor( constructor(readonly values: string[], tester: ReacordTester) {
readonly values: string[],
tester: ReacordTester,
) {
super(tester) super(tester)
} }
} }

View File

@@ -1,88 +0,0 @@
import { test } from "vitest"
import {
Button,
Embed,
EmbedAuthor,
EmbedField,
EmbedFooter,
EmbedTitle,
Link,
Option,
Select,
} from "../library/main"
import { ReacordTester } from "./test-adapter"
test("text children in other components", async () => {
const tester = new ReacordTester()
const SomeText = () => <>some text</>
await tester.assertRender(
<>
<Embed>
<EmbedTitle>
<SomeText />
</EmbedTitle>
<EmbedAuthor>
<SomeText />
</EmbedAuthor>
<EmbedField name={<SomeText />}>
<SomeText /> <Button label="ignore this" onClick={() => {}} />
nailed it
</EmbedField>
<EmbedFooter>
<SomeText />
</EmbedFooter>
</Embed>
<Button label={<SomeText />} onClick={() => {}} />
<Link url="https://discord.com" label={<SomeText />} />
<Select>
<Option value="1">
<SomeText />
</Option>
<Option value="2" label={<SomeText />} description={<SomeText />} />
</Select>
</>,
[
{
content: "",
embeds: [
{
title: "some text",
author: {
name: "some text",
},
fields: [{ name: "some text", value: "some text nailed it" }],
footer: {
text: "some text",
},
},
],
actionRows: [
[
{
type: "button",
label: "some text",
style: "secondary",
},
{
type: "link",
url: "https://discord.com",
label: "some text",
},
],
[
{
type: "select",
values: [],
options: [
{ value: "1", label: "some text" },
{ value: "2", label: "some text", description: "some text" },
],
},
],
],
},
],
)
})

Some files were not shown because too many files have changed in this diff Show More