Compare commits
82 Commits
reacord@0.
...
reacord@0.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f67e7c263 | ||
|
|
d4f1bb4d4b | ||
|
|
47c9b75940 | ||
|
|
41c87e3dcc | ||
|
|
b210670b2a | ||
|
|
2b9110bf2c | ||
|
|
5d4dde4e0c | ||
|
|
31baa23076 | ||
|
|
d76f316bb7 | ||
|
|
47b0645a90 | ||
|
|
0bab505994 | ||
|
|
104b175931 | ||
|
|
156cf90919 | ||
|
|
b463ce3cf4 | ||
|
|
576dd2e35e | ||
|
|
0d4294ee8c | ||
|
|
25fcc53d91 | ||
|
|
34bc293df5 | ||
|
|
b7b237f2f5 | ||
|
|
e2c3de4fae | ||
|
|
ffe0a86a33 | ||
|
|
6ce9241080 | ||
|
|
5d96d517df | ||
|
|
2c706f6791 | ||
|
|
2abb61493e | ||
|
|
3db1013b74 | ||
|
|
3e2c6ba5d6 | ||
|
|
0172534d13 | ||
|
|
1a49423beb | ||
|
|
3824859352 | ||
|
|
0dad3c9ecd | ||
|
|
eea1a7ee9d | ||
|
|
e9e5a1617b | ||
|
|
7ac1a9cdce | ||
|
|
33841a0c84 | ||
|
|
69b3112d32 | ||
|
|
b4fb6bc47c | ||
|
|
7aaef5f85f | ||
|
|
b755290569 | ||
|
|
f0ad743080 | ||
|
|
af3d1c5058 | ||
|
|
bdee9454f2 | ||
|
|
84348d287f | ||
|
|
6da6008d2c | ||
|
|
bece6c42fc | ||
|
|
abc809c9fb | ||
|
|
d35659f6f6 | ||
|
|
3969e6471f | ||
|
|
95041acfd4 | ||
|
|
eb0409f1a2 | ||
|
|
fbab145f39 | ||
|
|
f59323f245 | ||
|
|
1c37d37c28 | ||
|
|
408ab4ce89 | ||
|
|
a8a64e601a | ||
|
|
d88b982830 | ||
|
|
d87c27183a | ||
|
|
b141ca1868 | ||
|
|
dfa7f8090c | ||
|
|
82068d2d83 | ||
|
|
216ae7a29a | ||
|
|
9813a01a19 | ||
|
|
0be321b64e | ||
|
|
acbf21842f | ||
|
|
65be2ef201 | ||
|
|
c244124f6f | ||
|
|
4db8db0f2d | ||
|
|
1fa4bc800b | ||
|
|
e3351654ea | ||
|
|
d1ca002939 | ||
|
|
38a86bb783 | ||
|
|
72f4a4afff | ||
|
|
eed5715f1f | ||
|
|
e486da0881 | ||
|
|
b275d9b330 | ||
|
|
bab134d697 | ||
|
|
df9bdfaf77 | ||
|
|
35d7f0b33f | ||
|
|
4f9fb4310f | ||
|
|
7b74628732 | ||
|
|
7536bdee43 | ||
|
|
ef8d915e3b |
@@ -1,25 +0,0 @@
|
||||
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"),
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
45
.github/workflows/main.yml
vendored
45
.github/workflows/main.yml
vendored
@@ -1,45 +0,0 @@
|
||||
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 }}
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
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 -C packages/reacord test
|
||||
- name: test website
|
||||
run: pnpm -C packages/website test
|
||||
- name: build
|
||||
run: pnpm --recursive run build
|
||||
- name: lint
|
||||
run: pnpm run lint
|
||||
- name: typecheck
|
||||
run: pnpm --recursive run typecheck
|
||||
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@7.5.0
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: ${{ matrix.command.run }}
|
||||
20
.github/workflows/release.yml
vendored
20
.github/workflows/release.yml
vendored
@@ -13,19 +13,15 @@ jobs:
|
||||
name: release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: setup node
|
||||
uses: actions/setup-node@v2
|
||||
- uses: actions/checkout@v3
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
node-version: 16
|
||||
|
||||
- name: install pnpm
|
||||
run: npm install -g pnpm
|
||||
|
||||
- name: install deps
|
||||
run: pnpm install --frozen-lockfile
|
||||
version: 8
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: changesets release
|
||||
id: changesets
|
||||
|
||||
44
.github/workflows/tests.yml
vendored
Normal file
44
.github/workflows/tests.yml
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
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()
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -5,6 +5,7 @@ coverage
|
||||
.env
|
||||
*.code-workspace
|
||||
.pnpm-debug.log
|
||||
|
||||
build
|
||||
.cache
|
||||
.vercel
|
||||
*.tsbuildinfo
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
pnpm-lock.yaml
|
||||
build
|
||||
.cache
|
||||
packages/website/public/api
|
||||
/packages/website/public/api
|
||||
.astro
|
||||
|
||||
51
package.json
51
package.json
@@ -2,25 +2,46 @@
|
||||
"name": "reacord-monorepo",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"lint": "eslint --ext js,ts,tsx .",
|
||||
"lint-fix": "pnpm lint -- --fix",
|
||||
"format": "prettier --write .",
|
||||
"lint": "run-s --continue-on-error lint:*",
|
||||
"lint:eslint": "eslint . --fix --cache --cache-file=node_modules/.cache/.eslintcache --report-unused-disable-directives",
|
||||
"lint:prettier": "prettier . --write --cache --list-different",
|
||||
"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": {
|
||||
"@changesets/cli": "^2.24.0",
|
||||
"@itsmapleleaf/configs": "^1.1.3",
|
||||
"@rushstack/eslint-patch": "^1.1.3",
|
||||
"@types/eslint": "^8.4.1",
|
||||
"eslint": "^8.14.0",
|
||||
"node": "^16",
|
||||
"prettier": "^2.6.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@changesets/cli": "^2.26.2",
|
||||
"@itsmapleleaf/configs": "github:itsMapleLeaf/configs",
|
||||
"eslint": "^8.50.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prettier": "^3.0.3",
|
||||
"react": "^18.2.0",
|
||||
"tailwindcss": "^3.3.3",
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^0.34.5"
|
||||
},
|
||||
"resolutions": {
|
||||
"esbuild": "latest"
|
||||
},
|
||||
"prettier": "@itsmapleleaf/configs/prettier"
|
||||
"prettier": "@itsmapleleaf/configs/prettier",
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"./node_modules/@itsmapleleaf/configs/eslint.config.cjs",
|
||||
"./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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
42
packages/helpers/convert-object-property-case.test.ts
Normal file
42
packages/helpers/convert-object-property-case.test.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
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)
|
||||
})
|
||||
35
packages/helpers/convert-object-property-case.ts
Normal file
35
packages/helpers/convert-object-property-case.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
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)
|
||||
}
|
||||
7
packages/helpers/is-instance-of.ts
Normal file
7
packages/helpers/is-instance-of.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
/** 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
|
||||
3
packages/helpers/is-object.ts
Normal file
3
packages/helpers/is-object.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export function isObject(value: unknown): value is object {
|
||||
return typeof value === "object" && value !== null
|
||||
}
|
||||
7
packages/helpers/json.ts
Normal file
7
packages/helpers/json.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export function safeJsonStringify(value: unknown): string {
|
||||
try {
|
||||
return JSON.stringify(value)
|
||||
} catch {
|
||||
return String(value)
|
||||
}
|
||||
}
|
||||
11
packages/helpers/log-pretty.ts
Normal file
11
packages/helpers/log-pretty.ts
Normal 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,
|
||||
}),
|
||||
)
|
||||
}
|
||||
7
packages/helpers/omit.test.ts
Normal file
7
packages/helpers/omit.test.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
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 })
|
||||
})
|
||||
3
packages/helpers/omit.test.types.ts
Normal file
3
packages/helpers/omit.test.types.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { omit } from "./omit.ts"
|
||||
|
||||
omit({ a: 1, b: true }, ["a"]) satisfies { b: boolean }
|
||||
10
packages/helpers/omit.ts
Normal file
10
packages/helpers/omit.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
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
|
||||
}
|
||||
14
packages/helpers/package.json
Normal file
14
packages/helpers/package.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
11
packages/helpers/pick.ts
Normal file
11
packages/helpers/pick.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
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>
|
||||
}
|
||||
34
packages/helpers/prune-nullish-values.test.ts
Normal file
34
packages/helpers/prune-nullish-values.test.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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)
|
||||
})
|
||||
46
packages/helpers/prune-nullish-values.ts
Normal file
46
packages/helpers/prune-nullish-values.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
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]
|
||||
@@ -1,5 +1,5 @@
|
||||
import { setTimeout } from "node:timers/promises"
|
||||
import { toError } from "./to-error.js"
|
||||
import { setTimeout } from "node:timers/promises"
|
||||
|
||||
export async function rejectAfter(
|
||||
timeMs: number,
|
||||
21
packages/helpers/retry-with-timeout.ts
Normal file
21
packages/helpers/retry-with-timeout.ts
Normal 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, @typescript-eslint/no-unnecessary-condition
|
||||
while (true) {
|
||||
try {
|
||||
return await callback()
|
||||
} catch (error) {
|
||||
if (Date.now() - startTime > maxTime) {
|
||||
throw error
|
||||
}
|
||||
await setTimeout(waitPeriod)
|
||||
}
|
||||
}
|
||||
}
|
||||
3
packages/helpers/to-error.ts
Normal file
3
packages/helpers/to-error.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export function toError(value: unknown) {
|
||||
return value instanceof Error ? value : new Error(String(value))
|
||||
}
|
||||
3
packages/helpers/tsconfig.json
Normal file
3
packages/helpers/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json"
|
||||
}
|
||||
4
packages/helpers/types.test.types.ts
Normal file
4
packages/helpers/types.test.types.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
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)
|
||||
21
packages/helpers/types.ts
Normal file
21
packages/helpers/types.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
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")
|
||||
23
packages/helpers/wait-for.ts
Normal file
23
packages/helpers/wait-for.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
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")
|
||||
}
|
||||
24
packages/helpers/with-logged-method-calls.ts
Normal file
24
packages/helpers/with-logged-method-calls.ts
Normal 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: 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
|
||||
}
|
||||
@@ -1,5 +1,40 @@
|
||||
# reacord
|
||||
|
||||
## 0.5.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 41c87e3: fix type definitions
|
||||
|
||||
`"types"` wasn't updated, oops!
|
||||
|
||||
technically the typedefs were already correctly defined via `"exports"`, but this may not be picked up depending on the tsconfig, so I'll ensure both are used for compatibility purposes. but this might be worth a note in the docs; pretty much every modern TS Node project should be using a tsconfig that doesn't require setting `"types"`
|
||||
|
||||
## 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
|
||||
|
||||
1
packages/reacord/env.d.ts
vendored
Normal file
1
packages/reacord/env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="@total-typescript/ts-reset" />
|
||||
@@ -1,42 +0,0 @@
|
||||
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)
|
||||
})
|
||||
@@ -1,34 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
/**
|
||||
* for narrowing instance types with array.filter
|
||||
*/
|
||||
export const isInstanceOf =
|
||||
<T>(Constructor: new (...args: any[]) => T) =>
|
||||
(value: unknown): value is T =>
|
||||
value instanceof Constructor
|
||||
@@ -1,7 +0,0 @@
|
||||
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
|
||||
@@ -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,
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { expect, test } from "vitest"
|
||||
import type { PruneNullishValues } from "./prune-nullish-values"
|
||||
import { 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",
|
||||
// eslint-disable-next-line unicorn/no-null
|
||||
b: null,
|
||||
c: undefined,
|
||||
d: {
|
||||
a: "a",
|
||||
b: undefined,
|
||||
},
|
||||
}
|
||||
|
||||
const output: PruneNullishValues<InputType> = {
|
||||
a: "a",
|
||||
d: {
|
||||
a: "a",
|
||||
},
|
||||
}
|
||||
|
||||
expect(pruneNullishValues(input)).toEqual(output)
|
||||
})
|
||||
@@ -1,42 +0,0 @@
|
||||
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]
|
||||
@@ -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
|
||||
while (true) {
|
||||
try {
|
||||
return await callback()
|
||||
} catch (error) {
|
||||
if (Date.now() - startTime > maxTime) {
|
||||
throw error
|
||||
}
|
||||
await setTimeout(waitPeriod)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export function toError(value: unknown) {
|
||||
return value instanceof Error ? value : new Error(String(value))
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { setTimeout } from "node: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")
|
||||
}
|
||||
@@ -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: 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
|
||||
}
|
||||
@@ -1,52 +1,49 @@
|
||||
import type { ReactNode } from "react"
|
||||
import type { ReacordInstance } from "./instance"
|
||||
|
||||
/**
|
||||
* @category Component Event
|
||||
*/
|
||||
export type ComponentEvent = {
|
||||
/** @category Component Event */
|
||||
export interface 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.
|
||||
*
|
||||
* @see https://discord.com/developers/docs/resources/channel#message-object
|
||||
*/
|
||||
message: MessageInfo
|
||||
|
||||
/**
|
||||
* The channel that this event occurred in.
|
||||
*
|
||||
* @see https://discord.com/developers/docs/resources/channel#channel-object
|
||||
*/
|
||||
channel: ChannelInfo
|
||||
|
||||
/**
|
||||
* The user that triggered this event.
|
||||
*
|
||||
* @see https://discord.com/developers/docs/resources/user#user-object
|
||||
*/
|
||||
user: UserInfo
|
||||
|
||||
/**
|
||||
* The guild that this event occurred in.
|
||||
*
|
||||
* @see https://discord.com/developers/docs/resources/guild#guild-object
|
||||
*/
|
||||
guild?: GuildInfo
|
||||
|
||||
/**
|
||||
* Create a new reply to this event.
|
||||
*/
|
||||
/** Create a new reply to this event. */
|
||||
reply(content?: ReactNode): ReacordInstance
|
||||
|
||||
/**
|
||||
* Create an ephemeral reply to this event,
|
||||
* shown only to the user who triggered it.
|
||||
* Create an ephemeral reply to this event, shown only to the user who
|
||||
* triggered it.
|
||||
*/
|
||||
ephemeralReply(content?: ReactNode): ReacordInstance
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Component Event
|
||||
*/
|
||||
export type ChannelInfo = {
|
||||
/** @category Component Event */
|
||||
export interface ChannelInfo {
|
||||
id: string
|
||||
name?: string
|
||||
topic?: string
|
||||
@@ -57,13 +54,11 @@ export type ChannelInfo = {
|
||||
rateLimitPerUser?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Component Event
|
||||
*/
|
||||
export type MessageInfo = {
|
||||
/** @category Component Event */
|
||||
export interface MessageInfo {
|
||||
id: string
|
||||
channelId: string
|
||||
authorId: UserInfo
|
||||
authorId: string
|
||||
member?: GuildMemberInfo
|
||||
content: string
|
||||
timestamp: string
|
||||
@@ -74,19 +69,15 @@ export type MessageInfo = {
|
||||
mentions: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Component Event
|
||||
*/
|
||||
export type GuildInfo = {
|
||||
/** @category Component Event */
|
||||
export interface GuildInfo {
|
||||
id: string
|
||||
name: string
|
||||
member: GuildMemberInfo
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Component Event
|
||||
*/
|
||||
export type GuildMemberInfo = {
|
||||
/** @category Component Event */
|
||||
export interface GuildMemberInfo {
|
||||
id: string
|
||||
nick?: string
|
||||
displayName: string
|
||||
@@ -100,14 +91,12 @@ export type GuildMemberInfo = {
|
||||
communicationDisabledUntil?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Component Event
|
||||
*/
|
||||
export type UserInfo = {
|
||||
/** @category Component Event */
|
||||
export interface UserInfo {
|
||||
id: string
|
||||
username: string
|
||||
discriminator: string
|
||||
tag: string
|
||||
avatarUrl: string
|
||||
avatarUrl: string | null
|
||||
accentColor?: number
|
||||
}
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import type { MessageOptions } from "../../internal/message"
|
||||
import { Node } from "../../internal/node.js"
|
||||
import type { ComponentInteraction } from "../../internal/interaction.js"
|
||||
|
||||
/**
|
||||
* Props for an action row
|
||||
*
|
||||
* @category Action Row
|
||||
*/
|
||||
export type ActionRowProps = {
|
||||
export interface ActionRowProps {
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* An action row is a top-level container for message components.
|
||||
*
|
||||
* You don't need to use this; Reacord automatically creates action rows for you.
|
||||
* But this can be useful if you want a specific layout.
|
||||
* You don't need to use this; Reacord automatically creates action rows for
|
||||
* you. But this can be useful if you want a specific layout.
|
||||
*
|
||||
* ```tsx
|
||||
* // put buttons on two separate rows
|
||||
@@ -37,11 +38,19 @@ export function ActionRow(props: ActionRowProps) {
|
||||
)
|
||||
}
|
||||
|
||||
class ActionRowNode extends Node<{}> {
|
||||
class ActionRowNode extends Node<ActionRowProps> {
|
||||
override modifyMessageOptions(options: MessageOptions): void {
|
||||
options.actionRows.push([])
|
||||
for (const child of this.children) {
|
||||
child.modifyMessageOptions(options)
|
||||
}
|
||||
}
|
||||
handleComponentInteraction(interaction: ComponentInteraction) {
|
||||
for (const child of this.children) {
|
||||
if (child.handleComponentInteraction(interaction)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@ import type { ReactNode } from "react"
|
||||
|
||||
/**
|
||||
* Common props between button-like components
|
||||
*
|
||||
* @category Button
|
||||
*/
|
||||
export type ButtonSharedProps = {
|
||||
export interface ButtonSharedProps {
|
||||
/** The text on the button. Rich formatting (markdown) is not supported here. */
|
||||
label?: ReactNode
|
||||
|
||||
@@ -12,13 +13,12 @@ export type ButtonSharedProps = {
|
||||
disabled?: boolean
|
||||
|
||||
/**
|
||||
* Renders an emoji to the left of the text.
|
||||
* Has to be a literal emoji character (e.g. 🍍),
|
||||
* or an emoji code, like `<:plus_one:778531744860602388>`.
|
||||
* Renders an emoji to the left of the text. Has to be a literal emoji
|
||||
* character (e.g. 🍍), or an emoji code, like
|
||||
* `<:plus_one:778531744860602388>`.
|
||||
*
|
||||
* To get an emoji code, type your emoji in Discord chat
|
||||
* with a backslash `\` in front.
|
||||
* The bot has to be in the emoji's guild to use it.
|
||||
* To get an emoji code, type your emoji in Discord chat with a backslash `\`
|
||||
* in front. The bot has to be in the emoji's guild to use it.
|
||||
*/
|
||||
emoji?: string
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { nanoid } from "nanoid"
|
||||
import React from "react"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import type { ComponentInteraction } from "../../internal/interaction"
|
||||
import type { MessageOptions } from "../../internal/message"
|
||||
@@ -8,30 +7,23 @@ import { Node } from "../../internal/node.js"
|
||||
import type { ComponentEvent } from "../component-event"
|
||||
import type { ButtonSharedProps } from "./button-shared-props"
|
||||
|
||||
/**
|
||||
* @category Button
|
||||
*/
|
||||
/** @category Button */
|
||||
export type ButtonProps = ButtonSharedProps & {
|
||||
/**
|
||||
* The style determines the color of the button and signals intent.
|
||||
*
|
||||
* @see https://discord.com/developers/docs/interactions/message-components#button-object-button-styles
|
||||
*/
|
||||
style?: "primary" | "secondary" | "success" | "danger"
|
||||
|
||||
/**
|
||||
* Happens when a user clicks the button.
|
||||
*/
|
||||
/** Happens when a user clicks the button. */
|
||||
onClick: (event: ButtonClickEvent) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Button
|
||||
*/
|
||||
/** @category Button */
|
||||
export type ButtonClickEvent = ComponentEvent
|
||||
|
||||
/**
|
||||
* @category Button
|
||||
*/
|
||||
/** @category Button */
|
||||
export function Button(props: ButtonProps) {
|
||||
return (
|
||||
<ReacordElement props={props} createNode={() => new ButtonNode(props)}>
|
||||
@@ -43,10 +35,10 @@ export function Button(props: ButtonProps) {
|
||||
}
|
||||
|
||||
class ButtonNode extends Node<ButtonProps> {
|
||||
private customId = nanoid()
|
||||
private customId = randomUUID()
|
||||
|
||||
// this has text children, but buttons themselves shouldn't yield text
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
// eslint-disable-next-line @typescript-eslint/class-literal-property-style
|
||||
override get text() {
|
||||
return ""
|
||||
}
|
||||
@@ -74,4 +66,4 @@ class ButtonNode extends Node<ButtonProps> {
|
||||
}
|
||||
}
|
||||
|
||||
class ButtonLabelNode extends Node<{}> {}
|
||||
class ButtonLabelNode extends Node<Record<string, never>> {}
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import { Node } from "../../internal/node.js"
|
||||
import { EmbedChildNode } from "./embed-child.js"
|
||||
import type { EmbedOptions } from "./embed-options"
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
export type EmbedAuthorProps = {
|
||||
/** @category Embed */
|
||||
export interface EmbedAuthorProps {
|
||||
name?: ReactNode
|
||||
children?: ReactNode
|
||||
url?: string
|
||||
iconUrl?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
/** @category Embed */
|
||||
export function EmbedAuthor(props: EmbedAuthorProps) {
|
||||
return (
|
||||
<ReacordElement props={props} createNode={() => new EmbedAuthorNode(props)}>
|
||||
@@ -38,4 +33,4 @@ class EmbedAuthorNode extends EmbedChildNode<EmbedAuthorProps> {
|
||||
}
|
||||
}
|
||||
|
||||
class AuthorTextNode extends Node<{}> {}
|
||||
class AuthorTextNode extends Node<Record<string, never>> {}
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import { Node } from "../../internal/node.js"
|
||||
import { EmbedChildNode } from "./embed-child.js"
|
||||
import type { EmbedOptions } from "./embed-options"
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
export type EmbedFieldProps = {
|
||||
/** @category Embed */
|
||||
export interface EmbedFieldProps {
|
||||
name: ReactNode
|
||||
value?: ReactNode
|
||||
inline?: boolean
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
/** @category Embed */
|
||||
export function EmbedField(props: EmbedFieldProps) {
|
||||
return (
|
||||
<ReacordElement props={props} createNode={() => new EmbedFieldNode(props)}>
|
||||
@@ -25,7 +20,7 @@ export function EmbedField(props: EmbedFieldProps) {
|
||||
{props.name}
|
||||
</ReacordElement>
|
||||
<ReacordElement props={{}} createNode={() => new FieldValueNode({})}>
|
||||
{props.value || props.children}
|
||||
{props.value ?? props.children}
|
||||
</ReacordElement>
|
||||
</ReacordElement>
|
||||
)
|
||||
@@ -42,5 +37,5 @@ class EmbedFieldNode extends EmbedChildNode<EmbedFieldProps> {
|
||||
}
|
||||
}
|
||||
|
||||
class FieldNameNode extends Node<{}> {}
|
||||
class FieldValueNode extends Node<{}> {}
|
||||
class FieldNameNode extends Node<Record<string, never>> {}
|
||||
class FieldValueNode extends Node<Record<string, never>> {}
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import { Node } from "../../internal/node.js"
|
||||
import { EmbedChildNode } from "./embed-child.js"
|
||||
import type { EmbedOptions } from "./embed-options"
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
export type EmbedFooterProps = {
|
||||
/** @category Embed */
|
||||
export interface EmbedFooterProps {
|
||||
text?: ReactNode
|
||||
children?: ReactNode
|
||||
iconUrl?: string
|
||||
timestamp?: string | number | Date
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
/** @category Embed */
|
||||
export function EmbedFooter({ text, children, ...props }: EmbedFooterProps) {
|
||||
return (
|
||||
<ReacordElement props={props} createNode={() => new EmbedFooterNode(props)}>
|
||||
@@ -42,4 +37,4 @@ class EmbedFooterNode extends EmbedChildNode<
|
||||
}
|
||||
}
|
||||
|
||||
class FooterTextNode extends Node<{}> {}
|
||||
class FooterTextNode extends Node<Record<string, never>> {}
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import { EmbedChildNode } from "./embed-child.js"
|
||||
import type { EmbedOptions } from "./embed-options"
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
export type EmbedImageProps = {
|
||||
/** @category Embed */
|
||||
export interface EmbedImageProps {
|
||||
url: string
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
/** @category Embed */
|
||||
export function EmbedImage(props: EmbedImageProps) {
|
||||
return (
|
||||
<ReacordElement
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Except, SnakeCasedPropertiesDeep } from "type-fest"
|
||||
import type { EmbedProps } from "./embed"
|
||||
import type { Except, SnakeCasedPropertiesDeep } from "type-fest"
|
||||
|
||||
export type EmbedOptions = SnakeCasedPropertiesDeep<
|
||||
Except<EmbedProps, "timestamp" | "children"> & {
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import { EmbedChildNode } from "./embed-child.js"
|
||||
import type { EmbedOptions } from "./embed-options"
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
export type EmbedThumbnailProps = {
|
||||
/** @category Embed */
|
||||
export interface EmbedThumbnailProps {
|
||||
url: string
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
/** @category Embed */
|
||||
export function EmbedThumbnail(props: EmbedThumbnailProps) {
|
||||
return (
|
||||
<ReacordElement
|
||||
|
||||
@@ -1,21 +1,16 @@
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import { Node } from "../../internal/node.js"
|
||||
import { EmbedChildNode } from "./embed-child.js"
|
||||
import type { EmbedOptions } from "./embed-options"
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
export type EmbedTitleProps = {
|
||||
/** @category Embed */
|
||||
export interface EmbedTitleProps {
|
||||
children: ReactNode
|
||||
url?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Embed
|
||||
*/
|
||||
/** @category Embed */
|
||||
export function EmbedTitle({ children, ...props }: EmbedTitleProps) {
|
||||
return (
|
||||
<ReacordElement props={props} createNode={() => new EmbedTitleNode(props)}>
|
||||
@@ -33,4 +28,4 @@ class EmbedTitleNode extends EmbedChildNode<Omit<EmbedTitleProps, "children">> {
|
||||
}
|
||||
}
|
||||
|
||||
class TitleTextNode extends Node<{}> {}
|
||||
class TitleTextNode extends Node<Record<string, never>> {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from "react"
|
||||
import { snakeCaseDeep } from "../../../helpers/convert-object-property-case"
|
||||
import { omit } from "../../../helpers/omit"
|
||||
import { snakeCaseDeep } from "@reacord/helpers/convert-object-property-case"
|
||||
import { omit } from "@reacord/helpers/omit"
|
||||
import type React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import type { MessageOptions } from "../../internal/message"
|
||||
import { Node } from "../../internal/node.js"
|
||||
@@ -12,7 +12,7 @@ import type { EmbedOptions } from "./embed-options"
|
||||
* @category Embed
|
||||
* @see https://discord.com/developers/docs/resources/channel#embed-object
|
||||
*/
|
||||
export type EmbedProps = {
|
||||
export interface EmbedProps {
|
||||
title?: string
|
||||
description?: string
|
||||
url?: string
|
||||
@@ -53,7 +53,7 @@ class EmbedNode extends Node<EmbedProps> {
|
||||
child.modifyEmbedOptions(embed)
|
||||
}
|
||||
if (child instanceof TextNode) {
|
||||
embed.description = (embed.description || "") + child.props
|
||||
embed.description = (embed.description ?? "") + child.props
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import type { MessageOptions } from "../../internal/message"
|
||||
import { getNextActionRow } from "../../internal/message"
|
||||
import { Node } from "../../internal/node.js"
|
||||
import type { ButtonSharedProps } from "./button-shared-props"
|
||||
|
||||
/**
|
||||
* @category Link
|
||||
*/
|
||||
/** @category Link */
|
||||
export type LinkProps = ButtonSharedProps & {
|
||||
/** The URL the link should lead to */
|
||||
url: string
|
||||
@@ -15,14 +12,12 @@ export type LinkProps = ButtonSharedProps & {
|
||||
children?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Link
|
||||
*/
|
||||
/** @category Link */
|
||||
export function Link({ label, children, ...props }: LinkProps) {
|
||||
return (
|
||||
<ReacordElement props={props} createNode={() => new LinkNode(props)}>
|
||||
<ReacordElement props={{}} createNode={() => new LinkTextNode({})}>
|
||||
{label || children}
|
||||
{label ?? children}
|
||||
</ReacordElement>
|
||||
</ReacordElement>
|
||||
)
|
||||
@@ -40,4 +35,4 @@ class LinkNode extends Node<Omit<LinkProps, "label" | "children">> {
|
||||
}
|
||||
}
|
||||
|
||||
class LinkTextNode extends Node<{}> {}
|
||||
class LinkTextNode extends Node<Record<string, never>> {}
|
||||
|
||||
@@ -15,5 +15,5 @@ export class OptionNode extends Node<
|
||||
}
|
||||
}
|
||||
|
||||
export class OptionLabelNode extends Node<{}> {}
|
||||
export class OptionDescriptionNode extends Node<{}> {}
|
||||
export class OptionLabelNode extends Node<Record<string, never>> {}
|
||||
export class OptionDescriptionNode extends Node<Record<string, never>> {}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import { ReacordElement } from "../../internal/element"
|
||||
import {
|
||||
OptionDescriptionNode,
|
||||
@@ -7,10 +6,8 @@ import {
|
||||
OptionNode,
|
||||
} from "./option-node"
|
||||
|
||||
/**
|
||||
* @category Select
|
||||
*/
|
||||
export type OptionProps = {
|
||||
/** @category Select */
|
||||
export interface OptionProps {
|
||||
/** The internal value of this option */
|
||||
value: string
|
||||
/** The text shown to the user. This takes priority over `children` */
|
||||
@@ -23,19 +20,16 @@ export type OptionProps = {
|
||||
/**
|
||||
* Renders an emoji to the left of the text.
|
||||
*
|
||||
* Has to be a literal emoji character (e.g. 🍍),
|
||||
* or an emoji code, like `<:plus_one:778531744860602388>`.
|
||||
* Has to be a literal emoji character (e.g. 🍍), or an emoji code, like
|
||||
* `<:plus_one:778531744860602388>`.
|
||||
*
|
||||
* To get an emoji code, type your emoji in Discord chat
|
||||
* with a backslash `\` in front.
|
||||
* The bot has to be in the emoji's guild to use it.
|
||||
* To get an emoji code, type your emoji in Discord chat with a backslash `\`
|
||||
* in front. The bot has to be in the emoji's guild to use it.
|
||||
*/
|
||||
emoji?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Select
|
||||
*/
|
||||
/** @category Select */
|
||||
export function Option({
|
||||
label,
|
||||
children,
|
||||
@@ -46,7 +40,7 @@ export function Option({
|
||||
<ReacordElement props={props} createNode={() => new OptionNode(props)}>
|
||||
{(label !== undefined || children !== undefined) && (
|
||||
<ReacordElement props={{}} createNode={() => new OptionLabelNode({})}>
|
||||
{label || children}
|
||||
{label ?? children}
|
||||
</ReacordElement>
|
||||
)}
|
||||
{description !== undefined && (
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { nanoid } from "nanoid"
|
||||
import { isInstanceOf } from "@reacord/helpers/is-instance-of"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import { isInstanceOf } from "../../../helpers/is-instance-of"
|
||||
import { ReacordElement } from "../../internal/element.js"
|
||||
import type { ComponentInteraction } from "../../internal/interaction"
|
||||
import type {
|
||||
@@ -12,11 +11,10 @@ import type {
|
||||
import { Node } from "../../internal/node.js"
|
||||
import type { ComponentEvent } from "../component-event"
|
||||
import { OptionNode } from "./option-node"
|
||||
import { omit } from "@reacord/helpers/omit.js"
|
||||
|
||||
/**
|
||||
* @category Select
|
||||
*/
|
||||
export type SelectProps = {
|
||||
/** @category Select */
|
||||
export interface SelectProps {
|
||||
children?: ReactNode
|
||||
/** Sets the currently selected value */
|
||||
value?: string
|
||||
@@ -31,8 +29,8 @@ export type SelectProps = {
|
||||
multiple?: boolean
|
||||
|
||||
/**
|
||||
* With `multiple`, the minimum number of values that can be selected.
|
||||
* When `multiple` is false or not defined, this is always 1.
|
||||
* With `multiple`, the minimum number of values that can be selected. 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 does not limit the number of values that can be displayed by you.
|
||||
@@ -40,44 +38,44 @@ export type SelectProps = {
|
||||
minValues?: number
|
||||
|
||||
/**
|
||||
* With `multiple`, the maximum number of values that can be selected.
|
||||
* When `multiple` is false or not defined, this is always 1.
|
||||
* With `multiple`, the maximum number of values that can be selected. 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 does not limit the number of values that can be displayed by you.
|
||||
*/
|
||||
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
|
||||
|
||||
/**
|
||||
* Called when the user inputs a selection.
|
||||
* Receives the entire select change event,
|
||||
* which can be used to create new replies, etc.
|
||||
* Called when the user inputs a selection. Receives the entire select change
|
||||
* event, which can be used to create new replies, etc.
|
||||
*/
|
||||
onChange?: (event: SelectChangeEvent) => void
|
||||
|
||||
/**
|
||||
* Convenience shorthand for `onChange`, which receives the first selected value.
|
||||
* Convenience shorthand for `onChange`, which receives the first selected
|
||||
* value.
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* @category Select
|
||||
*/
|
||||
/** @category Select */
|
||||
export type SelectChangeEvent = ComponentEvent & {
|
||||
values: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* See [the select menu guide](/guides/select-menu) for a usage example.
|
||||
*
|
||||
* @category Select
|
||||
*/
|
||||
export function Select(props: SelectProps) {
|
||||
@@ -89,7 +87,7 @@ export function Select(props: SelectProps) {
|
||||
}
|
||||
|
||||
class SelectNode extends Node<SelectProps> {
|
||||
readonly customId = nanoid()
|
||||
readonly customId = randomUUID()
|
||||
|
||||
override modifyMessageOptions(message: MessageOptions): void {
|
||||
const actionRow: ActionRow = []
|
||||
@@ -105,12 +103,13 @@ class SelectNode extends Node<SelectProps> {
|
||||
values,
|
||||
minValues = 0,
|
||||
maxValues = 25,
|
||||
children,
|
||||
onChange,
|
||||
onChangeValue,
|
||||
onChangeMultiple,
|
||||
...props
|
||||
} = this.props
|
||||
} = omit(this.props, [
|
||||
"children",
|
||||
"onChange",
|
||||
"onChangeValue",
|
||||
"onChangeMultiple",
|
||||
])
|
||||
|
||||
const item: ActionRowItem = {
|
||||
...props,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ReacordInstance } from "./instance.js"
|
||||
import { raise } from "@reacord/helpers/raise.js"
|
||||
import * as React from "react"
|
||||
import { raise } from "../../helpers/raise"
|
||||
import type { ReacordInstance } from "./instance"
|
||||
|
||||
const Context = React.createContext<ReacordInstance | undefined>(undefined)
|
||||
|
||||
|
||||
@@ -2,9 +2,10 @@ import type { ReactNode } from "react"
|
||||
|
||||
/**
|
||||
* Represents an interactive message, which can later be replaced or deleted.
|
||||
*
|
||||
* @category Core
|
||||
*/
|
||||
export type ReacordInstance = {
|
||||
export interface ReacordInstance {
|
||||
/** Render some JSX to this instance (edits the message) */
|
||||
render: (content: ReactNode) => void
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/* eslint-disable class-methods-use-this */
|
||||
import { safeJsonStringify } from "@reacord/helpers/json"
|
||||
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 type { ReactNode } from "react"
|
||||
import type { Except } from "type-fest"
|
||||
import { pick } from "../../helpers/pick"
|
||||
import { pruneNullishValues } from "../../helpers/prune-nullish-values"
|
||||
import { raise } from "../../helpers/raise"
|
||||
import type { ComponentInteraction } from "../internal/interaction"
|
||||
import type {
|
||||
Message,
|
||||
@@ -26,14 +26,18 @@ import { Reacord } from "./reacord"
|
||||
|
||||
/**
|
||||
* The Reacord adapter for Discord.js.
|
||||
*
|
||||
* @category Core
|
||||
*/
|
||||
export class ReacordDiscordJs extends Reacord {
|
||||
constructor(private client: Discord.Client, config: ReacordConfig = {}) {
|
||||
constructor(
|
||||
private client: Discord.Client,
|
||||
config: ReacordConfig = {},
|
||||
) {
|
||||
super(config)
|
||||
|
||||
client.on("interactionCreate", (interaction) => {
|
||||
if (interaction.isButton() || interaction.isSelectMenu()) {
|
||||
if (interaction.isButton() || interaction.isStringSelectMenu()) {
|
||||
this.handleComponentInteraction(
|
||||
this.createReacordComponentInteraction(interaction),
|
||||
)
|
||||
@@ -43,6 +47,7 @@ export class ReacordDiscordJs extends Reacord {
|
||||
|
||||
/**
|
||||
* Sends a message to a channel.
|
||||
*
|
||||
* @see https://reacord.mapleleaf.dev/guides/sending-messages
|
||||
*/
|
||||
override send(
|
||||
@@ -57,6 +62,7 @@ export class ReacordDiscordJs extends Reacord {
|
||||
|
||||
/**
|
||||
* Sends a message as a reply to a command interaction.
|
||||
*
|
||||
* @see https://reacord.mapleleaf.dev/guides/sending-messages
|
||||
*/
|
||||
override reply(
|
||||
@@ -71,6 +77,7 @@ export class ReacordDiscordJs extends Reacord {
|
||||
|
||||
/**
|
||||
* Sends an ephemeral message as a reply to a command interaction.
|
||||
*
|
||||
* @see https://reacord.mapleleaf.dev/guides/sending-messages
|
||||
*/
|
||||
override ephemeralReply(
|
||||
@@ -114,14 +121,14 @@ export class ReacordDiscordJs extends Reacord {
|
||||
...getDiscordMessageOptions(options),
|
||||
fetchReply: true,
|
||||
})
|
||||
return createReacordMessage(message as Discord.Message)
|
||||
return createReacordMessage(message)
|
||||
},
|
||||
followUp: async (options) => {
|
||||
const message = await interaction.followUp({
|
||||
...getDiscordMessageOptions(options),
|
||||
fetchReply: true,
|
||||
})
|
||||
return createReacordMessage(message as Discord.Message)
|
||||
return createReacordMessage(message)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -189,6 +196,8 @@ export class ReacordDiscordJs extends Reacord {
|
||||
? new Date(interaction.message.editedTimestamp).toISOString()
|
||||
: undefined,
|
||||
mentions: interaction.message.mentions.users.map((u) => u.id),
|
||||
authorId: interaction.message.author.id,
|
||||
mentionEveryone: interaction.message.mentions.everyone,
|
||||
}
|
||||
: raise("Message not found")
|
||||
|
||||
@@ -207,11 +216,13 @@ export class ReacordDiscordJs extends Reacord {
|
||||
]),
|
||||
),
|
||||
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(),
|
||||
premiumSince: interaction.member.premiumSince?.toISOString(),
|
||||
communicationDisabledUntil:
|
||||
interaction.member.communicationDisabledUntil?.toISOString(),
|
||||
color: interaction.member.displayColor,
|
||||
displayAvatarUrl: interaction.member.displayAvatarURL(),
|
||||
}
|
||||
: undefined
|
||||
|
||||
@@ -226,7 +237,7 @@ export class ReacordDiscordJs extends Reacord {
|
||||
...pruneNullishValues(
|
||||
pick(interaction.user, ["id", "username", "discriminator", "tag"]),
|
||||
),
|
||||
avatarUrl: interaction.user.avatarURL()!,
|
||||
avatarUrl: interaction.user.avatarURL(),
|
||||
accentColor: interaction.user.accentColor ?? undefined,
|
||||
}
|
||||
|
||||
@@ -234,7 +245,11 @@ export class ReacordDiscordJs extends Reacord {
|
||||
id: interaction.id,
|
||||
customId: interaction.customId,
|
||||
update: async (options: MessageOptions) => {
|
||||
if (interaction.deferred || interaction.replied) {
|
||||
await interaction.message.edit(getDiscordMessageOptions(options))
|
||||
} else {
|
||||
await interaction.update(getDiscordMessageOptions(options))
|
||||
}
|
||||
},
|
||||
deferUpdate: async () => {
|
||||
if (interaction.replied || interaction.deferred) return
|
||||
@@ -245,14 +260,14 @@ export class ReacordDiscordJs extends Reacord {
|
||||
...getDiscordMessageOptions(options),
|
||||
fetchReply: true,
|
||||
})
|
||||
return createReacordMessage(message as Discord.Message)
|
||||
return createReacordMessage(message)
|
||||
},
|
||||
followUp: async (options) => {
|
||||
const message = await interaction.followUp({
|
||||
...getDiscordMessageOptions(options),
|
||||
fetchReply: true,
|
||||
})
|
||||
return createReacordMessage(message as Discord.Message)
|
||||
return createReacordMessage(message)
|
||||
},
|
||||
event: {
|
||||
channel,
|
||||
@@ -281,7 +296,7 @@ export class ReacordDiscordJs extends Reacord {
|
||||
}
|
||||
}
|
||||
|
||||
if (interaction.isSelectMenu()) {
|
||||
if (interaction.isStringSelectMenu()) {
|
||||
return {
|
||||
...baseProps,
|
||||
type: "select",
|
||||
@@ -335,8 +350,7 @@ function convertButtonStyleToEnum(style: MessageButtonOptions["style"]) {
|
||||
// and also handle some edge cases, e.g. empty messages
|
||||
function getDiscordMessageOptions(reacordOptions: MessageOptions) {
|
||||
const options = {
|
||||
// eslint-disable-next-line unicorn/no-null
|
||||
content: reacordOptions.content || null,
|
||||
content: reacordOptions.content || undefined,
|
||||
embeds: reacordOptions.embeds,
|
||||
components: reacordOptions.actionRows.map((row) => ({
|
||||
type: Discord.ComponentType.ActionRow,
|
||||
@@ -353,6 +367,19 @@ function getDiscordMessageOptions(reacordOptions: MessageOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
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") {
|
||||
return {
|
||||
...component,
|
||||
@@ -364,13 +391,16 @@ function getDiscordMessageOptions(reacordOptions: MessageOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
raise(`Unsupported component type: ${component.type}`)
|
||||
component satisfies never
|
||||
throw new Error(
|
||||
`Invalid component type ${safeJsonStringify(component)}}`,
|
||||
)
|
||||
},
|
||||
),
|
||||
})),
|
||||
}
|
||||
|
||||
if (!options.content && !options.embeds?.length) {
|
||||
if (!options.content && !options.embeds.length) {
|
||||
options.content = "_ _"
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,22 @@
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import type { ComponentInteraction } from "../internal/interaction"
|
||||
import type { ComponentInteraction } from "../internal/interaction.js"
|
||||
import { reconciler } from "../internal/reconciler.js"
|
||||
import type { Renderer } from "../internal/renderers/renderer"
|
||||
import type { ReacordInstance } from "./instance"
|
||||
import { InstanceProvider } from "./instance-context"
|
||||
import type { Renderer } from "../internal/renderers/renderer.js"
|
||||
import { InstanceProvider } from "./instance-context.js"
|
||||
import type { ReacordInstance } from "./instance.js"
|
||||
|
||||
/**
|
||||
* @category Core
|
||||
*/
|
||||
export type ReacordConfig = {
|
||||
/** @category Core */
|
||||
export interface ReacordConfig {
|
||||
/**
|
||||
* The max number of active instances.
|
||||
* When this limit is exceeded, the oldest instances will be disabled.
|
||||
* The max number of active instances. When this limit is exceeded, the oldest
|
||||
* instances will be disabled.
|
||||
*/
|
||||
maxInstances?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The main Reacord class that other Reacord adapters should extend.
|
||||
* Only use this directly if you're making [a custom adapter](/guides/custom-adapters).
|
||||
* The main Reacord class that other Reacord adapters should extend. Only use
|
||||
* this directly if you're making [a custom adapter](/guides/custom-adapters).
|
||||
*/
|
||||
export abstract class Reacord {
|
||||
private renderers: Renderer[] = []
|
||||
@@ -41,13 +38,22 @@ export abstract class Reacord {
|
||||
}
|
||||
|
||||
protected createInstance(renderer: Renderer, initialContent?: ReactNode) {
|
||||
if (this.renderers.length > this.maxInstances) {
|
||||
this.deactivate(this.renderers[0]!)
|
||||
if (this.renderers.length > this.maxInstances && this.renderers[0]) {
|
||||
this.deactivate(this.renderers[0])
|
||||
}
|
||||
|
||||
this.renderers.push(renderer)
|
||||
|
||||
const container = reconciler.createContainer(renderer, 0, false, {})
|
||||
const container: unknown = reconciler.createContainer(
|
||||
renderer,
|
||||
0,
|
||||
null,
|
||||
false,
|
||||
null,
|
||||
"reacord",
|
||||
() => {},
|
||||
null,
|
||||
)
|
||||
|
||||
const instance: ReacordInstance = {
|
||||
render: (content: ReactNode) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Message, MessageOptions } from "./message"
|
||||
|
||||
export type Channel = {
|
||||
export interface Channel {
|
||||
send(message: MessageOptions): Promise<Message>
|
||||
}
|
||||
|
||||
@@ -25,7 +25,9 @@ export class Container<T> {
|
||||
return this.items.find(predicate)
|
||||
}
|
||||
|
||||
findType<U extends T>(type: new (...args: any[]) => U): U | undefined {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Node } from "./node"
|
||||
import type { ReactNode } from "react"
|
||||
import React from "react"
|
||||
import type { Node } from "./node"
|
||||
|
||||
export function ReacordElement<Props>(props: {
|
||||
props: Props
|
||||
|
||||
@@ -17,7 +17,7 @@ export type SelectInteraction = BaseComponentInteraction<
|
||||
SelectChangeEvent
|
||||
>
|
||||
|
||||
export type BaseInteraction<Type extends string> = {
|
||||
export interface BaseInteraction<Type extends string> {
|
||||
type: Type
|
||||
id: string
|
||||
reply(messageOptions: MessageOptions): Promise<Message>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { Except } from "type-fest"
|
||||
import { last } from "../../helpers/last"
|
||||
import type { EmbedOptions } from "../core/components/embed-options"
|
||||
import type { SelectProps } from "../core/components/select"
|
||||
import { last } from "@reacord/helpers/last"
|
||||
import type { Except } from "type-fest"
|
||||
|
||||
export type MessageOptions = {
|
||||
export interface MessageOptions {
|
||||
content: string
|
||||
embeds: EmbedOptions[]
|
||||
actionRows: ActionRow[]
|
||||
@@ -16,7 +16,7 @@ export type ActionRowItem =
|
||||
| MessageLinkOptions
|
||||
| MessageSelectOptions
|
||||
|
||||
export type MessageButtonOptions = {
|
||||
export interface MessageButtonOptions {
|
||||
type: "button"
|
||||
customId: string
|
||||
label?: string
|
||||
@@ -25,7 +25,7 @@ export type MessageButtonOptions = {
|
||||
emoji?: string
|
||||
}
|
||||
|
||||
export type MessageLinkOptions = {
|
||||
export interface MessageLinkOptions {
|
||||
type: "link"
|
||||
url: string
|
||||
label?: string
|
||||
@@ -39,14 +39,14 @@ export type MessageSelectOptions = Except<SelectProps, "children" | "value"> & {
|
||||
options: MessageSelectOptionOptions[]
|
||||
}
|
||||
|
||||
export type MessageSelectOptionOptions = {
|
||||
export interface MessageSelectOptionOptions {
|
||||
label: string
|
||||
value: string
|
||||
description?: string
|
||||
emoji?: string
|
||||
}
|
||||
|
||||
export type Message = {
|
||||
export interface Message {
|
||||
edit(options: MessageOptions): Promise<void>
|
||||
delete(): Promise<void>
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/* eslint-disable class-methods-use-this */
|
||||
import { Container } from "./container.js"
|
||||
import type { ComponentInteraction } from "./interaction"
|
||||
import type { MessageOptions } from "./message"
|
||||
@@ -8,9 +7,11 @@ export abstract class Node<Props> {
|
||||
|
||||
constructor(public props: Props) {}
|
||||
|
||||
modifyMessageOptions(options: MessageOptions) {}
|
||||
modifyMessageOptions(_options: MessageOptions) {
|
||||
// noop
|
||||
}
|
||||
|
||||
handleComponentInteraction(interaction: ComponentInteraction): boolean {
|
||||
handleComponentInteraction(_interaction: ComponentInteraction): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { raise } from "@reacord/helpers/raise.js"
|
||||
import type { HostConfig } from "react-reconciler"
|
||||
import ReactReconciler from "react-reconciler"
|
||||
import { raise } from "../../helpers/raise.js"
|
||||
import { DefaultEventPriority } from "react-reconciler/constants.js"
|
||||
import { Node } from "./node.js"
|
||||
import type { Renderer } from "./renderers/renderer"
|
||||
import { TextNode } from "./text-node.js"
|
||||
@@ -20,8 +21,6 @@ const config: HostConfig<
|
||||
number, // TimeoutHandle,
|
||||
number // NoTimeout,
|
||||
> = {
|
||||
// config
|
||||
now: Date.now,
|
||||
supportsMutation: true,
|
||||
supportsPersistence: false,
|
||||
supportsHydration: false,
|
||||
@@ -30,7 +29,6 @@ const config: HostConfig<
|
||||
cancelTimeout: global.clearTimeout,
|
||||
noTimeout: -1,
|
||||
|
||||
// eslint-disable-next-line unicorn/no-null
|
||||
getRootHostContext: () => null,
|
||||
getChildHostContext: (parentContext) => parentContext,
|
||||
|
||||
@@ -43,7 +41,7 @@ const config: HostConfig<
|
||||
raise(`Missing createNode function`)
|
||||
}
|
||||
|
||||
const node = props.createNode(props.props)
|
||||
const node: unknown = props.createNode(props.props)
|
||||
if (!(node instanceof Node)) {
|
||||
raise(`createNode function did not return a Node`)
|
||||
}
|
||||
@@ -52,8 +50,11 @@ const config: HostConfig<
|
||||
},
|
||||
createTextInstance: (text) => new TextNode(text),
|
||||
shouldSetTextContent: () => false,
|
||||
// @ts-expect-error
|
||||
detachDeletedInstance: (instance) => {},
|
||||
detachDeletedInstance: (_instance) => {},
|
||||
beforeActiveInstanceBlur: () => {},
|
||||
afterActiveInstanceBlur: () => {},
|
||||
getInstanceFromNode: (_node: unknown) => null,
|
||||
getInstanceFromScope: (_scopeInstance: unknown) => null,
|
||||
|
||||
clearContainer: (renderer) => {
|
||||
renderer.nodes.clear()
|
||||
@@ -89,16 +90,18 @@ const config: HostConfig<
|
||||
node.props = newText
|
||||
},
|
||||
|
||||
// eslint-disable-next-line unicorn/no-null
|
||||
prepareForCommit: () => null,
|
||||
resetAfterCommit: (renderer) => {
|
||||
renderer.render()
|
||||
},
|
||||
prepareScopeUpdate: (_scopeInstance: unknown, _instance: unknown) => {},
|
||||
|
||||
preparePortalMount: () => raise("Portals are not supported"),
|
||||
getPublicInstance: () => raise("Refs are currently not supported"),
|
||||
|
||||
finalizeInitialChildren: () => false,
|
||||
|
||||
getCurrentEventPriority: () => DefaultEventPriority,
|
||||
}
|
||||
|
||||
export const reconciler = ReactReconciler(config)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Subject } from "rxjs"
|
||||
import { concatMap } from "rxjs/operators"
|
||||
import { Container } from "../container.js"
|
||||
import type { ComponentInteraction } from "../interaction"
|
||||
import type { Message, MessageOptions } from "../message"
|
||||
import type { Node } from "../node.js"
|
||||
import { Subject } from "rxjs"
|
||||
import { concatMap } from "rxjs/operators"
|
||||
|
||||
type UpdatePayload =
|
||||
| { action: "update" | "deactivate"; options: MessageOptions }
|
||||
@@ -47,14 +47,12 @@ export abstract class Renderer {
|
||||
}
|
||||
|
||||
handleComponentInteraction(interaction: ComponentInteraction) {
|
||||
for (const node of this.nodes) {
|
||||
if (node.handleComponentInteraction(interaction)) {
|
||||
this.componentInteraction = interaction
|
||||
|
||||
setTimeout(() => {
|
||||
this.updates.next({ action: "deferUpdate", interaction })
|
||||
}, 500)
|
||||
|
||||
for (const node of this.nodes) {
|
||||
if (node.handleComponentInteraction(interaction)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
"name": "reacord",
|
||||
"type": "module",
|
||||
"description": "Create interactive Discord messages using React.",
|
||||
"version": "0.5.0",
|
||||
"types": "./dist/main.d.ts",
|
||||
"version": "0.5.4",
|
||||
"homepage": "https://reacord.mapleleaf.dev",
|
||||
"repository": "https://github.com/itsMapleLeaf/reacord.git",
|
||||
"changelog": "https://github.com/itsMapleLeaf/reacord/releases",
|
||||
@@ -20,14 +19,17 @@
|
||||
"reacord"
|
||||
],
|
||||
"files": [
|
||||
"library",
|
||||
"dist",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"types": "./library/main.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/main.js",
|
||||
"require": "./dist/main.cjs"
|
||||
"require": "./dist/main.cjs",
|
||||
"types": "./library/main.ts"
|
||||
},
|
||||
"./package.json": {
|
||||
"import": "./package.json",
|
||||
@@ -35,21 +37,19 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "cp ../../README.md . && cp ../../LICENSE . && tsup library/main.ts --target node16 --format cjs,esm --dts --sourcemap",
|
||||
"build": "cpy ../../README.md ../../LICENSE . && tsup library/main.ts --target node16 --format cjs,esm --sourcemap",
|
||||
"build-watch": "pnpm build -- --watch",
|
||||
"test": "vitest --coverage --no-watch",
|
||||
"test-dev": "vitest",
|
||||
"test-manual": "nodemon --exec tsx --ext ts,tsx ./scripts/discordjs-manual-test.tsx",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"release": "bash scripts/release.sh"
|
||||
"typecheck": "tsc -b"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/node": "*",
|
||||
"@types/react": "*",
|
||||
"@types/react-reconciler": "^0.26.6",
|
||||
"nanoid": "^3.3.3",
|
||||
"react-reconciler": "^0.27.0",
|
||||
"rxjs": "^7.5.5"
|
||||
"@types/node": "^20.7.0",
|
||||
"@types/react": "^18.2.23",
|
||||
"@types/react-reconciler": "^0.28.5",
|
||||
"react-reconciler": "^0.29.0",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"discord.js": "^14",
|
||||
@@ -61,25 +61,20 @@
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/lodash-es": "^4.17.6",
|
||||
"c8": "^7.11.2",
|
||||
"discord.js": "^14.0.3",
|
||||
"dotenv": "^16.0.0",
|
||||
"@reacord/helpers": "workspace:*",
|
||||
"@types/lodash-es": "^4.17.9",
|
||||
"c8": "^8.0.1",
|
||||
"cpy-cli": "^5.0.0",
|
||||
"discord.js": "^14.13.0",
|
||||
"dotenv": "^16.3.1",
|
||||
"lodash-es": "^4.17.21",
|
||||
"nodemon": "^2.0.15",
|
||||
"prettier": "^2.6.2",
|
||||
"pretty-ms": "^7.0.1",
|
||||
"react": "^18.0.0",
|
||||
"release-it": "^14.14.2",
|
||||
"tsup": "^5.12.6",
|
||||
"tsx": "^3.8.0",
|
||||
"type-fest": "^2.12.2",
|
||||
"typescript": "^4.6.3",
|
||||
"vite": "^2.9.5",
|
||||
"vitest": "^0.10.0"
|
||||
},
|
||||
"resolutions": {
|
||||
"esbuild": "latest"
|
||||
"nodemon": "^3.0.1",
|
||||
"prettier": "^3.0.3",
|
||||
"pretty-ms": "^8.0.0",
|
||||
"react": "^18.2.0",
|
||||
"tsup": "^7.2.0",
|
||||
"tsx": "^3.13.0",
|
||||
"type-fest": "^4.3.2"
|
||||
},
|
||||
"release-it": {
|
||||
"git": {
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
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"
|
||||
import {
|
||||
Button,
|
||||
Option,
|
||||
ReacordDiscordJs,
|
||||
Select,
|
||||
useInstance,
|
||||
} from "../library/main"
|
||||
|
||||
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!)
|
||||
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!)
|
||||
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}`,
|
||||
@@ -33,7 +39,7 @@ for (const [, channel] of category.children.cache) {
|
||||
let prefix = 0
|
||||
const createTest = async (
|
||||
name: string,
|
||||
block: (channel: TextChannel) => void | Promise<unknown>,
|
||||
block: (channel: TextChannel) => unknown,
|
||||
) => {
|
||||
prefix += 1
|
||||
const channel = await category.children.create({
|
||||
@@ -132,3 +138,7 @@ await createTest("delete this", (channel) => {
|
||||
}
|
||||
reacord.send(channel.id, <DeleteThis />)
|
||||
})
|
||||
|
||||
await createTest("link", (channel) => {
|
||||
reacord.send(channel.id, <Link label="hi" url="https://mapleleaf.dev" />)
|
||||
})
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from "react"
|
||||
import { test } from "vitest"
|
||||
import { ActionRow, Button, Select } from "../library/main"
|
||||
import { ReacordTester } from "./test-adapter"
|
||||
|
||||
@@ -8,5 +8,5 @@ beforeAll(() => {
|
||||
|
||||
test("can require commonjs", () => {
|
||||
const require = createRequire(import.meta.url)
|
||||
expect(() => require("../dist/main.cjs")).not.toThrow()
|
||||
expect(() => require("../dist/main.cjs") as unknown).not.toThrow()
|
||||
})
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from "react"
|
||||
import { test } from "vitest"
|
||||
import {
|
||||
Embed,
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
import { test } from "vitest"
|
||||
|
||||
test.todo("ephemeral reply")
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from "react"
|
||||
import { test } from "vitest"
|
||||
import { Link } from "../library/main"
|
||||
import { ReacordTester } from "./test-adapter"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as React from "react"
|
||||
import { test } from "vitest"
|
||||
import { Button, Embed, EmbedField, EmbedTitle } from "../library/main"
|
||||
import { ReacordTester } from "./test-adapter"
|
||||
import * as React from "react"
|
||||
import { test } from "vitest"
|
||||
|
||||
test("rendering behavior", async () => {
|
||||
const tester = new ReacordTester()
|
||||
@@ -35,7 +35,7 @@ test("rendering behavior", async () => {
|
||||
},
|
||||
])
|
||||
|
||||
tester.findButtonByLabel("show embed").click()
|
||||
await tester.findButtonByLabel("show embed").click()
|
||||
await tester.assertMessages([
|
||||
{
|
||||
content: "count: 0",
|
||||
@@ -62,7 +62,7 @@ test("rendering behavior", async () => {
|
||||
},
|
||||
])
|
||||
|
||||
tester.findButtonByLabel("clicc").click()
|
||||
await tester.findButtonByLabel("clicc").click()
|
||||
await tester.assertMessages([
|
||||
{
|
||||
content: "count: 1",
|
||||
@@ -94,7 +94,7 @@ test("rendering behavior", async () => {
|
||||
},
|
||||
])
|
||||
|
||||
tester.findButtonByLabel("clicc").click()
|
||||
await tester.findButtonByLabel("clicc").click()
|
||||
await tester.assertMessages([
|
||||
{
|
||||
content: "count: 2",
|
||||
@@ -126,7 +126,7 @@ test("rendering behavior", async () => {
|
||||
},
|
||||
])
|
||||
|
||||
tester.findButtonByLabel("hide embed").click()
|
||||
await tester.findButtonByLabel("hide embed").click()
|
||||
await tester.assertMessages([
|
||||
{
|
||||
content: "count: 2",
|
||||
@@ -153,7 +153,7 @@ test("rendering behavior", async () => {
|
||||
},
|
||||
])
|
||||
|
||||
tester.findButtonByLabel("clicc").click()
|
||||
await tester.findButtonByLabel("clicc").click()
|
||||
await tester.assertMessages([
|
||||
{
|
||||
content: "count: 3",
|
||||
@@ -180,7 +180,7 @@ test("rendering behavior", async () => {
|
||||
},
|
||||
])
|
||||
|
||||
tester.findButtonByLabel("deactivate").click()
|
||||
await tester.findButtonByLabel("deactivate").click()
|
||||
await tester.assertMessages([
|
||||
{
|
||||
content: "count: 3",
|
||||
@@ -210,7 +210,7 @@ test("rendering behavior", async () => {
|
||||
},
|
||||
])
|
||||
|
||||
tester.findButtonByLabel("clicc").click()
|
||||
await tester.findButtonByLabel("clicc").click()
|
||||
await tester.assertMessages([
|
||||
{
|
||||
content: "count: 3",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react"
|
||||
import { useState } from "react"
|
||||
import { expect, test, vi } from "vitest"
|
||||
import { Button, Option, Select } from "../library/main"
|
||||
import { ReacordTester } from "./test-adapter"
|
||||
@@ -59,16 +59,16 @@ test("single select", async () => {
|
||||
await assertSelect([])
|
||||
expect(onSelect).toHaveBeenCalledTimes(0)
|
||||
|
||||
tester.findSelectByPlaceholder("choose one").select("2")
|
||||
await tester.findSelectByPlaceholder("choose one").select("2")
|
||||
await assertSelect(["2"])
|
||||
expect(onSelect).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ values: ["2"] }),
|
||||
)
|
||||
|
||||
tester.findButtonByLabel("disable").click()
|
||||
await tester.findButtonByLabel("disable").click()
|
||||
await assertSelect(["2"], true)
|
||||
|
||||
tester.findSelectByPlaceholder("choose one").select("1")
|
||||
await tester.findSelectByPlaceholder("choose one").select("1")
|
||||
await assertSelect(["2"], true)
|
||||
expect(onSelect).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
@@ -125,19 +125,23 @@ test("multiple select", async () => {
|
||||
await assertSelect([])
|
||||
expect(onSelect).toHaveBeenCalledTimes(0)
|
||||
|
||||
tester.findSelectByPlaceholder("select").select("1", "3")
|
||||
await tester.findSelectByPlaceholder("select").select("1", "3")
|
||||
await assertSelect(expect.arrayContaining(["1", "3"]) as unknown as string[])
|
||||
expect(onSelect).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ values: expect.arrayContaining(["1", "3"]) }),
|
||||
expect.objectContaining({
|
||||
values: expect.arrayContaining(["1", "3"]) as unknown,
|
||||
}),
|
||||
)
|
||||
|
||||
tester.findSelectByPlaceholder("select").select("2")
|
||||
await tester.findSelectByPlaceholder("select").select("2")
|
||||
await assertSelect(expect.arrayContaining(["2"]) as unknown as string[])
|
||||
expect(onSelect).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ values: expect.arrayContaining(["2"]) }),
|
||||
expect.objectContaining({
|
||||
values: expect.arrayContaining(["2"]) as unknown,
|
||||
}),
|
||||
)
|
||||
|
||||
tester.findSelectByPlaceholder("select").select()
|
||||
await tester.findSelectByPlaceholder("select").select()
|
||||
await assertSelect([])
|
||||
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ values: [] }))
|
||||
})
|
||||
@@ -145,7 +149,7 @@ test("multiple select", async () => {
|
||||
test("optional onSelect + unknown value", async () => {
|
||||
const tester = new ReacordTester()
|
||||
tester.reply().render(<Select placeholder="select" />)
|
||||
tester.findSelectByPlaceholder("select").select("something")
|
||||
await tester.findSelectByPlaceholder("select").select("something")
|
||||
await tester.assertMessages([
|
||||
{
|
||||
content: "",
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
/* eslint-disable class-methods-use-this */
|
||||
/* eslint-disable require-await */
|
||||
import { nanoid } from "nanoid"
|
||||
import { logPretty } from "@reacord/helpers/log-pretty"
|
||||
import { omit } from "@reacord/helpers/omit"
|
||||
import { pruneNullishValues } from "@reacord/helpers/prune-nullish-values"
|
||||
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 type { ReactNode } from "react"
|
||||
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 {
|
||||
ChannelInfo,
|
||||
GuildInfo,
|
||||
@@ -32,9 +30,7 @@ import { InteractionReplyRenderer } from "../library/internal/renderers/interact
|
||||
|
||||
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 {
|
||||
private messageContainer = new Container<TestMessage>()
|
||||
|
||||
@@ -194,7 +190,7 @@ class TestCommandInteraction implements CommandInteraction {
|
||||
}
|
||||
|
||||
class TestInteraction {
|
||||
readonly id = nanoid()
|
||||
readonly id = randomUUID()
|
||||
readonly channelId = "test-channel-id"
|
||||
|
||||
constructor(
|
||||
@@ -252,10 +248,10 @@ class TestSelectInteraction
|
||||
class TestComponentEvent {
|
||||
constructor(private tester: ReacordTester) {}
|
||||
|
||||
message: MessageInfo = {} as any // todo
|
||||
channel: ChannelInfo = {} as any // todo
|
||||
user: UserInfo = {} as any // todo
|
||||
guild: GuildInfo = {} as any // todo
|
||||
message: MessageInfo = {} as MessageInfo // todo
|
||||
channel: ChannelInfo = {} as ChannelInfo // todo
|
||||
user: UserInfo = {} as UserInfo // todo
|
||||
guild: GuildInfo = {} as GuildInfo // todo
|
||||
|
||||
reply(content?: ReactNode): ReacordInstance {
|
||||
return this.tester.reply(content)
|
||||
@@ -274,7 +270,10 @@ class TestSelectChangeEvent
|
||||
extends TestComponentEvent
|
||||
implements SelectChangeEvent
|
||||
{
|
||||
constructor(readonly values: string[], tester: ReacordTester) {
|
||||
constructor(
|
||||
readonly values: string[],
|
||||
tester: ReacordTester,
|
||||
) {
|
||||
super(tester)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as React from "react"
|
||||
import { test } from "vitest"
|
||||
import {
|
||||
Button,
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import React from "react"
|
||||
import { describe, expect, it } from "vitest"
|
||||
import type { ReacordInstance } from "../library/main"
|
||||
import { Button, useInstance } from "../library/main"
|
||||
import type { MessageSample } from "./test-adapter"
|
||||
import { ReacordTester } from "./test-adapter"
|
||||
import { describe, expect, it } from "vitest"
|
||||
|
||||
describe("useInstance", () => {
|
||||
it("returns the instance of itself", async () => {
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json"
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
/// <reference types="vitest" />
|
||||
import { defineConfig } from "vite"
|
||||
|
||||
export default defineConfig({
|
||||
build: {
|
||||
sourcemap: true,
|
||||
},
|
||||
})
|
||||
3
packages/website/.gitignore
vendored
3
packages/website/.gitignore
vendored
@@ -1,5 +1,4 @@
|
||||
node_modules
|
||||
|
||||
/.cache
|
||||
/build
|
||||
/public/build
|
||||
@@ -8,3 +7,5 @@ node_modules
|
||||
cypress/videos
|
||||
cypress/screenshots
|
||||
*.out.css
|
||||
/api
|
||||
.astro
|
||||
|
||||
@@ -1,5 +1,38 @@
|
||||
# website
|
||||
|
||||
## 0.4.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [41c87e3]
|
||||
- reacord@0.5.4
|
||||
|
||||
## 0.4.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [104b175]
|
||||
- Updated dependencies [156cf90]
|
||||
- Updated dependencies [0bab505]
|
||||
- Updated dependencies [d76f316]
|
||||
- reacord@0.5.3
|
||||
|
||||
## 0.4.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [9813a01]
|
||||
- reacord@0.5.2
|
||||
|
||||
## 0.4.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [72f4a4a]
|
||||
- Updated dependencies [7536bde]
|
||||
- Updated dependencies [e335165]
|
||||
- reacord@0.5.1
|
||||
|
||||
## 0.4.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
import { hydrate } from "react-dom"
|
||||
import { RemixBrowser } from "@remix-run/react"
|
||||
|
||||
hydrate(<RemixBrowser />, document)
|
||||
@@ -1,21 +0,0 @@
|
||||
import { renderToString } from "react-dom/server"
|
||||
import type { EntryContext } from "@remix-run/node"
|
||||
import { RemixServer } from "@remix-run/react"
|
||||
|
||||
export default function handleRequest(
|
||||
request: Request,
|
||||
responseStatusCode: number,
|
||||
responseHeaders: Headers,
|
||||
remixContext: EntryContext,
|
||||
) {
|
||||
const markup = renderToString(
|
||||
<RemixServer context={remixContext} url={request.url} />,
|
||||
)
|
||||
|
||||
responseHeaders.set("Content-Type", "text/html")
|
||||
|
||||
return new Response("<!DOCTYPE html>" + markup, {
|
||||
status: responseStatusCode,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import { HeartIcon } from "@heroicons/react/solid"
|
||||
import clsx from "clsx"
|
||||
import { ExternalLink } from "~/modules/dom/external-link"
|
||||
import { linkClass, maxWidthContainer } from "~/modules/ui/components"
|
||||
|
||||
export function AppFooter() {
|
||||
return (
|
||||
<footer className={clsx(maxWidthContainer, "text-xs opacity-75")}>
|
||||
<address className="not-italic">
|
||||
© {new Date().getFullYear()} itsMapleLeaf
|
||||
</address>
|
||||
<p>
|
||||
Coded with <HeartIcon className="inline w-4 align-sub" /> using{" "}
|
||||
<ExternalLink className={linkClass()} href="https://remix.run">
|
||||
Remix
|
||||
</ExternalLink>
|
||||
</p>
|
||||
<p>
|
||||
Uses{" "}
|
||||
<ExternalLink className={linkClass()} href="https://umami.is/">
|
||||
umami
|
||||
</ExternalLink>{" "}
|
||||
for simple, non-identifying analytics.
|
||||
</p>
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,12 +0,0 @@
|
||||
import type { ComponentPropsWithoutRef } from "react"
|
||||
|
||||
export function ExternalLink({
|
||||
children,
|
||||
...props
|
||||
}: ComponentPropsWithoutRef<"a">) {
|
||||
return (
|
||||
<a target="_blank" rel="noopener noreferrer" {...props}>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { ReactNode } from "react"
|
||||
import { useEffect, useRef } from "react"
|
||||
import { createPortal } from "react-dom"
|
||||
|
||||
export function Portal({ children }: { children: ReactNode }) {
|
||||
const containerRef = useRef<Element>()
|
||||
|
||||
if (!containerRef.current && typeof document !== "undefined") {
|
||||
containerRef.current = document.createElement("react-portal")
|
||||
document.body.append(containerRef.current)
|
||||
}
|
||||
|
||||
useEffect(() => () => containerRef.current!.remove(), [])
|
||||
|
||||
return containerRef.current ? (
|
||||
createPortal(children, containerRef.current)
|
||||
) : (
|
||||
<>{children}</>
|
||||
)
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export function raise(error: unknown): never {
|
||||
throw error instanceof Error ? error : new Error(String(error))
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
import clsx from "clsx"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import blobComfyUrl from "~/assets/blob-comfy.png"
|
||||
import cursorIbeamUrl from "~/assets/cursor-ibeam.png"
|
||||
import cursorUrl from "~/assets/cursor.png"
|
||||
|
||||
const defaultState = {
|
||||
chatInputText: "",
|
||||
chatInputCursorVisible: true,
|
||||
messageVisible: false,
|
||||
count: 0,
|
||||
cursorLeft: "25%",
|
||||
cursorBottom: "-15px",
|
||||
}
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
const animationFrame = () =>
|
||||
new Promise((resolve) => requestAnimationFrame(resolve))
|
||||
|
||||
export function LandingAnimation() {
|
||||
const [state, setState] = useState(defaultState)
|
||||
const chatInputRef = useRef<HTMLDivElement>(null)
|
||||
const addRef = useRef<HTMLDivElement>(null)
|
||||
const deleteRef = useRef<HTMLDivElement>(null)
|
||||
const cursorRef = useRef<HTMLImageElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const animateClick = (element: HTMLElement) =>
|
||||
element.animate(
|
||||
[{ transform: `translateY(2px)` }, { transform: `translateY(0px)` }],
|
||||
300,
|
||||
)
|
||||
|
||||
let running = true
|
||||
|
||||
void (async () => {
|
||||
while (running) {
|
||||
setState(defaultState)
|
||||
await delay(700)
|
||||
|
||||
for (const letter of "/counter") {
|
||||
setState((state) => ({
|
||||
...state,
|
||||
chatInputText: state.chatInputText + letter,
|
||||
}))
|
||||
await delay(100)
|
||||
}
|
||||
|
||||
await delay(1000)
|
||||
|
||||
setState((state) => ({
|
||||
...state,
|
||||
messageVisible: true,
|
||||
chatInputText: "",
|
||||
}))
|
||||
await delay(1000)
|
||||
|
||||
setState((state) => ({
|
||||
...state,
|
||||
cursorLeft: "70px",
|
||||
cursorBottom: "40px",
|
||||
}))
|
||||
await delay(1500)
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
setState((state) => ({
|
||||
...state,
|
||||
count: state.count + 1,
|
||||
chatInputCursorVisible: false,
|
||||
}))
|
||||
animateClick(addRef.current!)
|
||||
await delay(700)
|
||||
}
|
||||
|
||||
await delay(500)
|
||||
|
||||
setState((state) => ({
|
||||
...state,
|
||||
cursorLeft: "140px",
|
||||
}))
|
||||
await delay(1000)
|
||||
|
||||
animateClick(deleteRef.current!)
|
||||
setState((state) => ({ ...state, messageVisible: false }))
|
||||
await delay(1000)
|
||||
|
||||
setState(() => ({
|
||||
...defaultState,
|
||||
chatInputCursorVisible: false,
|
||||
}))
|
||||
await delay(500)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
running = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let running = true
|
||||
|
||||
void (async () => {
|
||||
while (running) {
|
||||
// check if the cursor is in the input
|
||||
const cursorRect = cursorRef.current!.getBoundingClientRect()
|
||||
const chatInputRect = chatInputRef.current!.getBoundingClientRect()
|
||||
|
||||
const isOverInput =
|
||||
cursorRef.current &&
|
||||
chatInputRef.current &&
|
||||
cursorRect.top + cursorRect.height / 2 > chatInputRect.top
|
||||
|
||||
cursorRef.current!.src = isOverInput ? cursorIbeamUrl : cursorUrl
|
||||
|
||||
await animationFrame()
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
running = false
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
className="grid gap-2 relative pointer-events-none select-none"
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
className={clsx(
|
||||
"bg-slate-800 p-4 rounded-lg shadow transition",
|
||||
state.messageVisible ? "opacity-100" : "opacity-0 -translate-y-2",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-12 h-12 p-2 rounded-full bg-no-repeat bg-contain bg-black/25">
|
||||
<img
|
||||
src={blobComfyUrl}
|
||||
alt=""
|
||||
className="object-contain scale-90 w-full h-full"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-bold">comfybot</p>
|
||||
<p>this button was clicked {state.count} times</p>
|
||||
<div className="mt-2 flex flex-row gap-3">
|
||||
<div
|
||||
ref={addRef}
|
||||
className="bg-emerald-700 text-white py-1.5 px-3 text-sm rounded"
|
||||
>
|
||||
+1
|
||||
</div>
|
||||
<div
|
||||
ref={deleteRef}
|
||||
className="bg-red-700 text-white py-1.5 px-3 text-sm rounded"
|
||||
>
|
||||
🗑 delete
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="bg-slate-700 pb-2 pt-1.5 px-4 rounded-lg shadow"
|
||||
ref={chatInputRef}
|
||||
>
|
||||
<span
|
||||
className={clsx(
|
||||
"text-sm after:content-[attr(data-after)] after:relative after:-top-px after:-left-[2px]",
|
||||
state.chatInputCursorVisible
|
||||
? "after:opacity-100"
|
||||
: "after:opacity-0",
|
||||
)}
|
||||
data-after="|"
|
||||
>
|
||||
{state.chatInputText || (
|
||||
<span className="opacity-50 block absolute translate-y-1">
|
||||
Message #showing-off-reacord
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<img
|
||||
src={cursorUrl}
|
||||
alt=""
|
||||
className="transition-all duration-500 absolute scale-75"
|
||||
style={{ left: state.cursorLeft, bottom: state.cursorBottom }}
|
||||
ref={cursorRef}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user