183 Commits

Author SHA1 Message Date
Darius
82b3575f2d Merge pull request #37 from itsMapleLeaf/changeset-release/main 2023-10-10 10:53:03 -05:00
github-actions[bot]
82b811c98b Version Packages 2023-10-10 15:51:06 +00:00
itsMapleLeaf
3a786310b1 upgrades 2023-10-10 10:50:15 -05:00
itsMapleLeaf
ced48a3ecb distribute .d.ts files 2023-10-10 10:47:31 -05:00
itsMapleLeaf
37b75a99e2 use type:module in helpers 2023-10-10 10:45:50 -05:00
itsMapleLeaf
f2f215d6b9 fix banner in readme 2023-09-28 12:47:39 -05:00
Darius
1f67e7c263 Merge pull request #35 from itsMapleLeaf/changeset-release/main 2023-09-28 12:33:08 -05:00
github-actions[bot]
d4f1bb4d4b Version Packages 2023-09-28 17:23:24 +00:00
Darius
47c9b75940 Merge pull request #34 from itsMapleLeaf/fix-type-definitions 2023-09-28 12:22:52 -05:00
itsMapleLeaf
41c87e3dcc fix typedefs 2023-09-28 12:20:58 -05:00
Darius
b210670b2a Merge pull request #31 from itsMapleLeaf/changeset-release/main 2023-09-27 23:21:57 -05:00
github-actions[bot]
2b9110bf2c Version Packages 2023-09-28 04:20:36 +00:00
Darius
5d4dde4e0c Merge pull request #30 from itsMapleLeaf/renderer-bug-fixes 2023-09-27 23:20:04 -05:00
itsMapleLeaf
31baa23076 format astro files 2023-09-27 23:18:36 -05:00
itsMapleLeaf
d76f316bb7 ensure action rows handle child interactions 2023-09-27 23:15:24 -05:00
itsMapleLeaf
47b0645a90 fix linter warnings 2023-09-27 23:09:21 -05:00
itsMapleLeaf
0bab505994 fix deprecated method 2023-09-27 23:09:21 -05:00
itsMapleLeaf
104b175931 edit if deferred or replied 2023-09-27 23:08:41 -05:00
itsMapleLeaf
156cf90919 set component interaction in loop
...only when an interaction was handled
2023-09-27 23:08:35 -05:00
Darius
b463ce3cf4 Merge pull request #27 from itsMapleLeaf/update-lint 2023-09-27 13:32:49 -05:00
itsMapleLeaf
576dd2e35e manual fixes, disable some errors 2023-09-27 13:29:20 -05:00
itsMapleLeaf
0d4294ee8c upgrade deps + remove unneeded 2023-09-27 12:33:40 -05:00
itsMapleLeaf
25fcc53d91 only list formatted files 2023-09-27 12:26:07 -05:00
itsMapleLeaf
34bc293df5 Merge branch 'update-lint' of https://github.com/itsMapleLeaf/reacord into update-lint 2023-09-27 12:24:00 -05:00
itsMapleLeaf
b7b237f2f5 less wordy name 2023-09-27 12:23:56 -05:00
itsMapleLeaf
e2c3de4fae Apply automatic changes 2023-09-27 17:23:41 +00:00
itsMapleLeaf
ffe0a86a33 merge and rename workflows 2023-09-27 12:23:24 -05:00
itsMapleLeaf
6ce9241080 run other scripts + fix always run 2023-09-27 12:22:09 -05:00
itsMapleLeaf
5d96d517df add cache and autocommit 2023-09-27 12:10:05 -05:00
itsMapleLeaf
2c706f6791 update lint configs and scripts 2023-09-27 12:07:32 -05:00
itsMapleLeaf
2abb61493e Merge branch 'rewrite' 2023-08-16 20:44:42 -05:00
itsMapleLeaf
3db1013b74 also sync before lint 2023-08-16 20:44:35 -05:00
itsMapleLeaf
3e2c6ba5d6 rename test job 2023-08-16 20:43:10 -05:00
itsMapleLeaf
0172534d13 actually remove tailwind typography 2023-08-16 20:41:59 -05:00
itsMapleLeaf
1a49423beb run astro sync before typecheck 2023-08-16 20:41:06 -05:00
itsMapleLeaf
3824859352 add github profile link 2023-08-16 20:34:35 -05:00
itsMapleLeaf
0dad3c9ecd style fixes and improvements 2023-08-16 20:33:53 -05:00
itsMapleLeaf
eea1a7ee9d solve some weird inclusion errors 2023-08-16 20:02:58 -05:00
itsMapleLeaf
e9e5a1617b tooling overhaul 2023-08-16 19:32:28 -05:00
itsMapleLeaf
7ac1a9cdce improve typecheck setup 2023-03-12 19:44:59 -05:00
itsMapleLeaf
33841a0c84 remove some extra scripts 2023-03-12 19:31:33 -05:00
itsMapleLeaf
69b3112d32 account for trailing slashes 2023-03-12 16:50:11 -05:00
itsMapleLeaf
b4fb6bc47c website cleanup 2023-03-12 16:38:32 -05:00
itsMapleLeaf
7aaef5f85f lint fixe 2023-03-12 16:38:26 -05:00
itsMapleLeaf
b755290569 skip website test for now 2023-03-12 16:29:46 -05:00
itsMapleLeaf
f0ad743080 menu improvements 2023-03-12 16:28:51 -05:00
itsMapleLeaf
af3d1c5058 add start script 2023-03-12 16:26:47 -05:00
itsMapleLeaf
bdee9454f2 disable ligatures 2023-03-12 16:19:52 -05:00
itsMapleLeaf
84348d287f active link style 2023-03-12 16:14:46 -05:00
itsMapleLeaf
6da6008d2c guide pages (why was that so easy wtf) 2023-03-12 15:58:47 -05:00
itsMapleLeaf
bece6c42fc ignore .vercel 2023-03-12 15:12:41 -05:00
itsMapleLeaf
abc809c9fb always run typedoc before build 2023-03-12 15:08:57 -05:00
itsMapleLeaf
d35659f6f6 fix website build 2023-03-12 15:01:12 -05:00
itsMapleLeaf
3969e6471f finished landing 2023-03-12 14:43:53 -05:00
itsMapleLeaf
95041acfd4 root layout 2023-03-12 13:36:03 -05:00
itsMapleLeaf
eb0409f1a2 add astro and configure some things 2023-03-12 13:20:49 -05:00
itsMapleLeaf
fbab145f39 fix dev script 2023-03-12 12:53:37 -05:00
itsMapleLeaf
f59323f245 remove node dep 2022-10-15 00:27:33 -05:00
itsMapleLeaf
1c37d37c28 vercel must be stopped 2022-10-14 14:01:58 -05:00
itsMapleLeaf
408ab4ce89 add version to helpers package 2022-10-14 13:59:27 -05:00
itsMapleLeaf
a8a64e601a pnpm lock 2022-10-14 13:56:45 -05:00
itsMapleLeaf
d88b982830 remove old release script 2022-10-14 13:55:16 -05:00
itsMapleLeaf
d87c27183a upgrades 2022-10-14 13:42:50 -05:00
itsMapleLeaf
b141ca1868 Merge branch 'main' of https://github.com/itsMapleLeaf/reacord 2022-10-14 13:35:14 -05:00
itsMapleLeaf
dfa7f8090c update github workflows 2022-10-14 13:35:12 -05:00
Darius
82068d2d83 Merge pull request #22 from itsMapleLeaf/changeset-release/main
Version Packages
2022-10-14 13:28:30 -05:00
github-actions[bot]
216ae7a29a Version Packages 2022-10-14 18:25:32 +00:00
itsMapleLeaf
9813a01a19 import react-reconciler/constants.js for esm 2022-10-14 13:24:12 -05:00
itsMapleLeaf
0be321b64e move helpers to new workspace folder 2022-10-14 13:22:55 -05:00
itsMapleLeaf
acbf21842f deploy to vercel 2022-10-02 18:04:15 -05:00
itsMapleLeaf
65be2ef201 Merge branch 'main' of https://github.com/itsMapleLeaf/reacord 2022-10-02 17:59:37 -05:00
Darius
c244124f6f Merge pull request #20 from kentcdodds/patch-1
Update sending-messages.md
2022-09-10 11:04:41 -05:00
Kent C. Dodds
4db8db0f2d Update sending-messages.md 2022-09-10 09:42:40 -06:00
github-actions[bot]
1fa4bc800b Version Packages 2022-08-04 10:39:56 -05:00
itsMapleLeaf
e3351654ea changeset 2022-08-04 10:38:08 -05:00
itsMapleLeaf
d1ca002939 fix links, closes #17 2022-08-04 10:38:08 -05:00
itsMapleLeaf
38a86bb783 fix links, closes #17 2022-08-04 10:34:19 -05:00
itsMapleLeaf
72f4a4afff changeset 2022-07-23 14:42:12 -05:00
itsMapleLeaf
eed5715f1f update website with new remix typings 2022-07-23 14:24:12 -05:00
itsMapleLeaf
e486da0881 migrate to cypress 10 2022-07-23 14:24:12 -05:00
itsMapleLeaf
b275d9b330 update reconciler 2022-07-23 14:24:12 -05:00
itsMapleLeaf
bab134d697 remove vite
was only used for viest config types, don't need it now
2022-07-23 14:24:12 -05:00
itsMapleLeaf
df9bdfaf77 remove nanoid, use crypto.randomUUID()
removes a dependency, and resolves an ESM require error
2022-07-23 14:24:12 -05:00
itsMapleLeaf
35d7f0b33f fix linter warnings 2022-07-23 14:24:12 -05:00
itsMapleLeaf
4f9fb4310f upgrade dependencies 2022-07-23 14:24:12 -05:00
itsMapleLeaf
7b74628732 add link to template + other tweaks 2022-07-23 00:16:27 -05:00
itsMapleLeaf
7536bdee43 changeset 2022-07-22 23:17:03 -05:00
itsMapleLeaf
ef8d915e3b add types field in exports to work with TS NodeNext 2022-07-22 23:15:57 -05:00
github-actions[bot]
3f078c91d2 Version Packages 2022-07-22 22:28:53 -05:00
itsMapleLeaf
8df7bc9baa back to the old script 2022-07-22 22:19:48 -05:00
itsMapleLeaf
52e587e70f add back changelog config 2022-07-22 22:12:53 -05:00
itsMapleLeaf
3152b1b79e add version to website 2022-07-22 22:11:43 -05:00
itsMapleLeaf
d20afb094c fix pnpm-workspace.yaml to work with changesets 2022-07-22 22:10:25 -05:00
itsMapleLeaf
118f567e8d add publish config 2022-07-22 21:46:11 -05:00
itsMapleLeaf
a447fefc7b fix changeset 2022-07-22 21:45:20 -05:00
itsMapleLeaf
9efc61d8eb update release workflow for pnpm 2022-07-22 21:44:48 -05:00
itsMapleLeaf
aa65da59df changeset 2022-07-22 21:35:54 -05:00
itsMapleLeaf
bc91080eca allow JSX for text in more places 2022-07-22 21:35:54 -05:00
itsMapleLeaf
9afe6fe0fa use changeset publish 2022-07-22 17:31:34 -05:00
itsMapleLeaf
abc60528d5 set access public 2022-07-22 17:29:04 -05:00
itsMapleLeaf
413f88c7b8 remove ignore config 2022-07-22 17:28:45 -05:00
itsMapleLeaf
b482f07788 ignore package by folder 2022-07-22 17:23:04 -05:00
itsMapleLeaf
3b191d274e always cancel in progress 2022-07-22 17:20:10 -05:00
itsMapleLeaf
be5ec7c545 install pnpm in release workflow 2022-07-22 17:17:51 -05:00
itsMapleLeaf
c93815b9f9 setup releasing in CI 2022-07-22 17:16:01 -05:00
itsMapleLeaf
1e527993e5 only publish reacord 2022-07-22 17:16:01 -05:00
itsMapleLeaf
f4eae8da75 consume changeset 2022-07-22 17:16:01 -05:00
itsMapleLeaf
62505ca98c test changeset 2022-07-22 17:16:01 -05:00
itsMapleLeaf
cc1bc0932f init changesets 2022-07-22 17:16:01 -05:00
itsMapleLeaf
c08f5621ef space 2022-07-22 13:51:02 -05:00
itsMapleLeaf
b6d2aac7a3 update release script 2022-07-22 13:51:02 -05:00
itsMapleLeaf
51ac0c89da add a manual tester in favor of playground 2022-07-22 13:51:02 -05:00
itsMapleLeaf
f4985b1d87 run one workflow at a time 2022-07-22 13:51:02 -05:00
itsMapleLeaf
96affac979 release v0.4.0 2022-07-21 16:23:15 -05:00
Crawron
93b321dc36 clean imports 2022-07-21 16:20:14 -05:00
Crawron
e313399a5a fix type guards 2022-07-21 16:20:14 -05:00
Crawron
90744ebe47 tweak and infer return type 2022-07-21 16:20:14 -05:00
Crawron
33bb2ee196 use enums instead of strings for component type 2022-07-21 16:20:14 -05:00
Crawron
eb97b2d23d Add helper to convert button style to enum 2022-07-21 16:20:14 -05:00
Crawron
5aaaffbda9 Update playground for djs v14 2022-07-21 16:20:14 -05:00
Crawron
43029019f4 gitignore pnpm debug log 2022-07-21 16:20:14 -05:00
Crawron
8c481f18c6 Update Discord.js version 2022-07-21 16:20:14 -05:00
itsMapleLeaf
87ecb20f7a fix pnpm scripts & lock pnpm version 2022-07-09 15:13:44 -05:00
itsMapleLeaf
2324f3c89f release v0.3.7 2022-07-09 14:55:00 -05:00
itsMapleLeaf
c35c32bddd fix cjs require 2022-07-09 14:54:27 -05:00
itsMapleLeaf
6eb36b44f3 move scripts to root for deployment 2022-07-07 12:20:00 -05:00
itsMapleLeaf
a1fc0287fc remove engines config 2022-07-07 12:02:13 -05:00
itsMapleLeaf
02dd763e63 install node 16 for website 2022-07-07 12:01:06 -05:00
itsMapleLeaf
a4024394e3 remove dockerfile 2022-07-07 11:56:13 -05:00
itsMapleLeaf
c72096058a fix umami script 2022-07-07 11:49:14 -05:00
itsMapleLeaf
672fcd5bc4 release v0.3.6 2022-04-27 22:39:35 -05:00
itsMapleLeaf
25f34b3715 alias release script 2022-04-27 22:36:32 -05:00
itsMapleLeaf
8a7557f0eb lint/typecheck fixes 2022-04-25 19:58:47 -05:00
itsMapleLeaf
fc3025baaf update configs 2022-04-25 14:52:04 -05:00
itsMapleLeaf
81f32794b4 fix import aliases 2022-04-24 19:52:21 -05:00
itsMapleLeaf
dbf9640b16 lockfile 2022-04-24 19:41:53 -05:00
itsMapleLeaf
a485ebaf74 improve pruneNullishValues + test 2022-04-24 16:05:00 -05:00
itsMapleLeaf
7ef5a7ac9d remove disableComponents function 2022-04-23 03:47:50 -05:00
itsMapleLeaf
6715756c2b fix deactivate overwriting edits 2022-04-23 03:44:50 -05:00
itsMapleLeaf
6851c5419a test improvements 2022-04-23 01:54:52 -05:00
itsMapleLeaf
1ba75492e5 reconciler fix 2022-04-23 00:44:31 -05:00
itsMapleLeaf
aced338d72 use require.resolve for eslint config 2022-04-23 00:37:11 -05:00
itsMapleLeaf
512c0649d8 ignore workspace files 2022-04-23 00:37:00 -05:00
itsMapleLeaf
91b82ca41f fix vitest fn usage 2022-04-22 23:58:05 -05:00
itsMapleLeaf
752ccc080d update remix imports + format 2022-04-22 23:50:01 -05:00
itsMapleLeaf
3c2d3b4683 upgrades 2022-04-22 23:45:30 -05:00
itsMapleLeaf
ad57674d6e 0.3.5 2022-04-22 23:27:43 -05:00
itsMapleLeaf
065bec9a37 Merge branches 'main' and 'main' of github.com:itsMapleLeaf/reacord 2022-04-22 23:23:35 -05:00
itsMapleLeaf
d3ccafc6d5 update website links 2022-04-22 23:22:28 -05:00
Darius
c71d70bbb4 remove domain redirect 2022-03-27 13:34:09 -05:00
itsMapleLeaf
5ba12af699 this should be call uncontrolled modal 2022-01-16 18:18:44 -06:00
itsMapleLeaf
ff39ef753f add accessible text to header logo 2022-01-16 14:09:53 -06:00
itsMapleLeaf
2288c27e1e fix style preload 2022-01-16 13:46:08 -06:00
MapleLeaf
c86648f44e deploy domain redirect to fly 2022-01-15 13:56:15 -06:00
MapleLeaf
0edf702b5f change umami url 2022-01-15 11:36:10 -06:00
MapleLeaf
05bda71ad6 fix action row example 2022-01-14 15:55:49 -06:00
MapleLeaf
0217fb8533 adjust prose style 2022-01-14 15:55:37 -06:00
MapleLeaf
b59dcc0ae7 active nav link style 2022-01-13 17:05:46 -06:00
Darius
3efaef162b update npm badge to link to npm 2022-01-13 12:54:42 -06:00
Darius
4c2aafe185 add npm badge 2022-01-13 12:52:55 -06:00
MapleLeaf
d3d1f473ae release v0.3.4 2022-01-13 11:42:36 -06:00
MapleLeaf
116e606db1 more package.json metadata fields 2022-01-13 11:41:16 -06:00
MapleLeaf
490bf2cefa reduce initial animation delay 2022-01-13 11:26:29 -06:00
MapleLeaf
e06bfa490f new main nav menu, remove alpine 2022-01-13 11:16:09 -06:00
MapleLeaf
2765b4fda4 extract and clean up buttonClass 2022-01-12 22:07:43 -06:00
MapleLeaf
5660297588 ignore /public/api 2022-01-12 22:07:19 -06:00
MapleLeaf
2cdd324495 un-proxy the api docs 2022-01-12 21:14:05 -06:00
MapleLeaf
7a09e8fdca add back get started button 2022-01-12 21:13:09 -06:00
MapleLeaf
8111931183 add meta theme-color 2022-01-12 20:32:50 -06:00
MapleLeaf
fd64132e58 seo stuff 2022-01-12 20:24:11 -06:00
MapleLeaf
1ba0da6c86 update header logo 2022-01-12 20:14:12 -06:00
MapleLeaf
fdd6a3a3cc add modal to show code 2022-01-12 20:10:09 -06:00
MapleLeaf
8ce3834cf4 fun landing animation 2022-01-12 19:29:20 -06:00
MapleLeaf
1bfbe9608c add neat tilted background 2022-01-12 17:55:36 -06:00
MapleLeaf
0695bbc6bd add favicon 2022-01-12 17:42:31 -06:00
MapleLeaf
569e5c7473 add new banner to readme 💖 thanks @Crawron 2022-01-12 17:12:40 -06:00
MapleLeaf
62300d23ca remove log in test script 2022-01-12 13:31:58 -06:00
MapleLeaf
cda69a0c85 load api files through a remix route 2022-01-12 13:31:50 -06:00
MapleLeaf
785384286b add analytics + notice 2022-01-12 13:15:09 -06:00
MapleLeaf
50961e888e prebuild tailwindcss for caching
need to figure out how to do this with remix-tailwind lol
2022-01-12 11:01:38 -06:00
MapleLeaf
8c3304144e add more package.json fields 2022-01-12 10:25:06 -06:00
MapleLeaf
b6b05232f7 release v0.3.3 2022-01-12 10:22:41 -06:00
MapleLeaf
33a170a4fb use bash release script 2022-01-12 10:21:54 -06:00
184 changed files with 9107 additions and 10236 deletions

8
.changeset/README.md Normal file
View File

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

11
.changeset/config.json Normal file
View File

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

View File

@@ -1,26 +0,0 @@
{
"extends": ["./node_modules/@itsmapleleaf/configs/eslint"],
"ignorePatterns": [
"**/node_modules/**",
"**/.cache/**",
"**/build/**",
"**/dist/**",
"**/coverage/**",
"**/public/**"
],
"parserOptions": {
"project": "./tsconfig.base.json"
},
"rules": {
"import/no-unused-modules": "off",
"unicorn/prevent-abbreviations": "off"
},
"overrides": [
{
"files": ["packages/website/cypress/**"],
"parserOptions": {
"project": "./packages/website/cypress/tsconfig.json"
}
}
]
}

View File

@@ -1,17 +0,0 @@
name: deploy website
on:
push:
branches: [main]
paths:
- "packages/website/**"
- "reacord/library/**/*.{ts,tsx}"
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: superfly/flyctl-actions@master
env:
FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
with:
args: "deploy"

View File

@@ -1,41 +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 }}
jobs:
run-commands:
strategy:
fail-fast: false
matrix:
command:
# if these run in the same process, it dies,
# so we test them separate
- name: test reacord
run: pnpm test -C packages/reacord
- name: test website
run: pnpm test -C packages/website
- name: build
run: pnpm build --recursive
- name: lint
run: pnpm lint
- name: typecheck
run: pnpm typecheck --parallel
name: ${{ matrix.command.name }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
# https://github.com/actions/setup-node#supported-version-syntax
node-version: "16"
- run: npm i -g pnpm
- run: pnpm install --frozen-lockfile
- run: ${{ matrix.command.run }}

33
.github/workflows/release.yml vendored Normal file
View File

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

44
.github/workflows/tests.yml vendored Normal file
View 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()

7
.gitignore vendored
View File

@@ -3,4 +3,9 @@ node_modules
.vscode
coverage
.env
*.code-workspace
.pnpm-debug.log
build
.cache
.vercel
*.tsbuildinfo

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
ignore-workspace-root-check = true

View File

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

View File

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

View File

@@ -1,7 +1,9 @@
# reacord
Create interactive Discord messages using React!
<center>
<img src="packages/website/src/assets/banner.png" alt="Reacord: Create interactive Discord messages using React">
</center>
## Installation ∙ [![npm](https://img.shields.io/npm/v/reacord?color=blue&style=flat-square)](https://www.npmjs.com/package/reacord)
## Installation
```console
# npm
npm install reacord react discord.js
@@ -15,9 +17,11 @@ pnpm add reacord react discord.js
```
## Get Started
[Visit the docs to get started.](https://reacord.fly.dev/guides/getting-started)
[Visit the docs to get started.](https://reacord.mapleleaf.dev/guides/getting-started)
## Example
<!-- prettier-ignore -->
```tsx
import * as React from "react"

View File

@@ -1,40 +0,0 @@
# fly.toml file generated for reacord on 2021-12-29T14:06:41-06:00
app = "reacord"
kill_signal = "SIGINT"
kill_timeout = 5
processes = []
[env]
PORT = 8080
[experimental]
allowed_public_ports = []
auto_rollback = true
[[services]]
http_checks = []
internal_port = 8080
processes = ["app"]
protocol = "tcp"
script_checks = []
[services.concurrency]
hard_limit = 25
soft_limit = 20
type = "connections"
[[services.ports]]
handlers = ["http"]
port = 80
[[services.ports]]
handlers = ["tls", "http"]
port = 443
[[services.tcp_checks]]
grace_period = "1s"
interval = "15s"
restart_limit = 0
timeout = "2s"

View File

@@ -1,29 +1,47 @@
{
"name": "reacord-monorepo",
"private": true,
"scripts": {
"lint": "eslint --ext js,ts,tsx .",
"lint-fix": "pnpm lint -- --fix",
"format": "prettier --write ."
},
"dependencies": {
"@itsmapleleaf/configs": "^1.1.2"
"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": {
"@typescript-eslint/eslint-plugin": "^5.9.1",
"@typescript-eslint/parser": "^5.9.1",
"eslint": "^8.6.0",
"eslint-config-prettier": "^8.3.0",
"eslint-import-resolver-typescript": "^2.5.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-react": "^7.28.0",
"eslint-plugin-react-hooks": "^4.3.0",
"eslint-plugin-unicorn": "^40.0.0",
"prettier": "^2.5.1",
"typescript": "^4.5.4"
"@changesets/cli": "^2.26.2",
"@itsmapleleaf/configs": "github:itsMapleLeaf/configs",
"eslint": "^8.51.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.6"
},
"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"
}
}
}

View 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)
})

View 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)
}

View 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

View 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
View File

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

View File

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

View File

@@ -0,0 +1,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 })
})

View 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
View 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
}

View File

@@ -0,0 +1,15 @@
{
"name": "@reacord/helpers",
"type": "module",
"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.4.0",
"vitest": "^0.34.6"
}
}

11
packages/helpers/pick.ts Normal file
View 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>
}

View 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)
})

View 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]

View File

@@ -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,

View File

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

View File

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

View File

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

View 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
View 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")

View 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")
}

View File

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

View File

@@ -1 +1,2 @@
/README.md
/LICENSE

View File

@@ -0,0 +1,50 @@
# reacord
## 0.5.5
### Patch Changes
- ced48a3: distribute d.ts files again instead of the source
distributing the source causes typecheck errors when the modules it imports from (in this case, `@reacord/helpers`) don't exist in the end users' projects, so we'll just distribute d.ts files instead like normal. failed experiment :(
## 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
- aa65da5: allow JSX in more places

1
packages/reacord/env.d.ts vendored Normal file
View File

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

View File

@@ -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)
})

View File

@@ -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)
}

View File

@@ -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

View File

@@ -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

View File

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

View File

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

View File

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

View File

@@ -1,27 +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
}
type PruneNullishValues<Input> = Input extends ReadonlyArray<infer Value>
? ReadonlyArray<NonNullable<Value>>
: Input extends object
? {
[Key in keyof Input]: NonNullable<Input[Key]>
}
: Input

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,52 +1,49 @@
import type { ReactNode } from "react"
import type { ReacordInstance } from "./instance"
/** @category Component Event */
export interface ComponentEvent {
/**
* @category Component Event
*/
export type ComponentEvent = {
/**
* The message associated with this event.
* For example: with a button click,
* The message associated with this event. For example: with a button click,
* this is the message that the button is on.
*
* @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
}

View File

@@ -1,29 +1,30 @@
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
* <ActionRow>
* <Button onClick={handleFirst}>First</Button>
* <Button label="First" onClick={handleFirst} />
* </ActionRow>
* <Button onClick={handleSecond}>Second</Button>
* <Button label="Second" onClick={handleSecond} />
* ```
*
* @category Action Row
@@ -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
}
}

View File

@@ -1,22 +1,24 @@
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?: string
label?: ReactNode
/** When true, the button will be slightly faded, and cannot be clicked. */
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
}

View File

@@ -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,38 +7,41 @@ 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)} />
<ReacordElement props={props} createNode={() => new ButtonNode(props)}>
<ReacordElement props={{}} createNode={() => new ButtonLabelNode({})}>
{props.label}
</ReacordElement>
</ReacordElement>
)
}
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 @typescript-eslint/class-literal-property-style
override get text() {
return ""
}
override modifyMessageOptions(options: MessageOptions): void {
getNextActionRow(options).push({
@@ -48,7 +50,7 @@ class ButtonNode extends Node<ButtonProps> {
style: this.props.style ?? "secondary",
disabled: this.props.disabled,
emoji: this.props.emoji,
label: this.props.label,
label: this.children.findType(ButtonLabelNode)?.text,
})
}
@@ -63,3 +65,5 @@ class ButtonNode extends Node<ButtonProps> {
return false
}
}
class ButtonLabelNode extends Node<Record<string, never>> {}

View File

@@ -1,36 +1,36 @@
import React from "react"
import type { ReactNode } 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 = {
name?: string
children?: string
/** @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)}
/>
<ReacordElement props={props} createNode={() => new EmbedAuthorNode(props)}>
<ReacordElement props={{}} createNode={() => new AuthorTextNode({})}>
{props.name ?? props.children}
</ReacordElement>
</ReacordElement>
)
}
class EmbedAuthorNode extends EmbedChildNode<EmbedAuthorProps> {
override modifyEmbedOptions(options: EmbedOptions): void {
options.author = {
name: this.props.name ?? this.props.children ?? "",
name: this.children.findType(AuthorTextNode)?.text ?? "",
url: this.props.url,
icon_url: this.props.iconUrl,
}
}
}
class AuthorTextNode extends Node<Record<string, never>> {}

View File

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

View File

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

View File

@@ -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

View File

@@ -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"> & {

View File

@@ -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

View File

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

View File

@@ -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
}
}

View File

@@ -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,21 +12,27 @@ export type LinkProps = ButtonSharedProps & {
children?: string
}
/**
* @category Link
*/
export function Link(props: LinkProps) {
return <ReacordElement props={props} createNode={() => new LinkNode(props)} />
/** @category Link */
export function Link({ label, children, ...props }: LinkProps) {
return (
<ReacordElement props={props} createNode={() => new LinkNode(props)}>
<ReacordElement props={{}} createNode={() => new LinkTextNode({})}>
{label ?? children}
</ReacordElement>
</ReacordElement>
)
}
class LinkNode extends Node<LinkProps> {
class LinkNode extends Node<Omit<LinkProps, "label" | "children">> {
override modifyMessageOptions(options: MessageOptions): void {
getNextActionRow(options).push({
type: "link",
disabled: this.props.disabled,
emoji: this.props.emoji,
label: this.props.label || this.props.children,
label: this.children.findType(LinkTextNode)?.text,
url: this.props.url,
})
}
}
class LinkTextNode extends Node<Record<string, never>> {}

View File

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

View File

@@ -1,38 +1,56 @@
import React from "react"
import type { ReactNode } from "react"
import { ReacordElement } from "../../internal/element"
import { OptionNode } from "./option-node"
import {
OptionDescriptionNode,
OptionLabelNode,
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` */
label?: string
label?: ReactNode
/** The text shown to the user */
children?: string
children?: ReactNode
/** Description for the option, shown to the user */
description?: string
description?: ReactNode
/**
* 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
*/
export function Option(props: OptionProps) {
/** @category Select */
export function Option({
label,
children,
description,
...props
}: OptionProps) {
return (
<ReacordElement props={props} createNode={() => new OptionNode(props)} />
<ReacordElement props={props} createNode={() => new OptionNode(props)}>
{(label !== undefined || children !== undefined) && (
<ReacordElement props={{}} createNode={() => new OptionLabelNode({})}>
{label ?? children}
</ReacordElement>
)}
{description !== undefined && (
<ReacordElement
props={{}}
createNode={() => new OptionDescriptionNode({})}
>
{description}
</ReacordElement>
)}
</ReacordElement>
)
}

View File

@@ -1,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,

View File

@@ -1,6 +1,6 @@
import type { ReacordInstance } from "./instance.js"
import { raise } from "@reacord/helpers/raise.js"
import * as React from "react"
import { raise } from "../../helpers/raise"
import type { ReacordInstance } from "./instance"
const Context = React.createContext<ReacordInstance | undefined>(undefined)
@@ -10,7 +10,7 @@ export const InstanceProvider = Context.Provider
* Get the associated instance for the current component.
*
* @category Core
* @see https://reacord.fly.dev/guides/use-instance
* @see https://reacord.mapleleaf.dev/guides/use-instance
*/
export function useInstance(): ReacordInstance {
return (

View File

@@ -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

View File

@@ -1,13 +1,16 @@
/* 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 { toUpper } from "../../helpers/to-upper"
import type { ComponentInteraction } from "../internal/interaction"
import type { Message, MessageOptions } from "../internal/message"
import type {
Message,
MessageButtonOptions,
MessageOptions,
} from "../internal/message"
import { ChannelMessageRenderer } from "../internal/renderers/channel-message-renderer"
import { InteractionReplyRenderer } from "../internal/renderers/interaction-reply-renderer"
import type {
@@ -23,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.isMessageComponent()) {
if (interaction.isButton() || interaction.isStringSelectMenu()) {
this.handleComponentInteraction(
this.createReacordComponentInteraction(interaction),
)
@@ -40,7 +47,8 @@ export class ReacordDiscordJs extends Reacord {
/**
* Sends a message to a channel.
* @see https://reacord.fly.dev/guides/sending-messages
*
* @see https://reacord.mapleleaf.dev/guides/sending-messages
*/
override send(
channelId: string,
@@ -54,7 +62,8 @@ export class ReacordDiscordJs extends Reacord {
/**
* Sends a message as a reply to a command interaction.
* @see https://reacord.fly.dev/guides/sending-messages
*
* @see https://reacord.mapleleaf.dev/guides/sending-messages
*/
override reply(
interaction: Discord.CommandInteraction,
@@ -68,7 +77,8 @@ export class ReacordDiscordJs extends Reacord {
/**
* Sends an ephemeral message as a reply to a command interaction.
* @see https://reacord.fly.dev/guides/sending-messages
*
* @see https://reacord.mapleleaf.dev/guides/sending-messages
*/
override ephemeralReply(
interaction: Discord.CommandInteraction,
@@ -88,7 +98,7 @@ export class ReacordDiscordJs extends Reacord {
(await this.client.channels.fetch(channelId)) ??
raise(`Channel ${channelId} not found`)
if (!channel.isText()) {
if (!channel.isTextBased()) {
raise(`Channel ${channelId} is not a text channel`)
}
@@ -111,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)
},
})
}
@@ -186,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")
@@ -204,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
@@ -223,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,
}
@@ -231,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
@@ -242,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,
@@ -278,7 +296,7 @@ export class ReacordDiscordJs extends Reacord {
}
}
if (interaction.isSelectMenu()) {
if (interaction.isStringSelectMenu()) {
return {
...baseProps,
type: "select",
@@ -298,17 +316,6 @@ function createReacordMessage(message: Discord.Message): Message {
edit: async (options) => {
await message.edit(getDiscordMessageOptions(options))
},
disableComponents: async () => {
for (const actionRow of message.components) {
for (const component of actionRow.components) {
component.setDisabled(true)
}
}
await message.edit({
components: message.components,
})
},
delete: async () => {
await message.delete()
},
@@ -321,10 +328,6 @@ function createEphemeralReacordMessage(): Message {
console.warn("Ephemeral messages can't be edited")
return Promise.resolve()
},
disableComponents: () => {
console.warn("Ephemeral messages can't be edited")
return Promise.resolve()
},
delete: () => {
console.warn("Ephemeral messages can't be deleted")
return Promise.resolve()
@@ -332,34 +335,55 @@ function createEphemeralReacordMessage(): Message {
}
}
function convertButtonStyleToEnum(style: MessageButtonOptions["style"]) {
const styleMap = {
primary: Discord.ButtonStyle.Primary,
secondary: Discord.ButtonStyle.Secondary,
success: Discord.ButtonStyle.Success,
danger: Discord.ButtonStyle.Danger,
} as const
return styleMap[style ?? "secondary"]
}
// TODO: this could be a part of the core library,
// and also handle some edge cases, e.g. empty messages
function getDiscordMessageOptions(
reacordOptions: MessageOptions,
): Discord.MessageOptions {
const options: Discord.MessageOptions = {
// eslint-disable-next-line unicorn/no-null
content: reacordOptions.content || null,
function getDiscordMessageOptions(reacordOptions: MessageOptions) {
const options = {
content: reacordOptions.content || undefined,
embeds: reacordOptions.embeds,
components: reacordOptions.actionRows.map((row) => ({
type: "ACTION_ROW",
type: Discord.ComponentType.ActionRow,
components: row.map(
(component): Discord.MessageActionRowComponentOptions => {
(component): Discord.MessageActionRowComponentData => {
if (component.type === "button") {
return {
type: "BUTTON",
type: Discord.ComponentType.Button,
customId: component.customId,
label: component.label ?? "",
style: toUpper(component.style ?? "secondary"),
style: convertButtonStyleToEnum(component.style),
disabled: component.disabled,
emoji: component.emoji,
}
}
if (component.type === "link") {
return {
type: Discord.ComponentType.Button,
url: component.url,
label: component.label ?? "",
style: Discord.ButtonStyle.Link,
disabled: component.disabled,
emoji: component.emoji,
}
}
// future proofing
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (component.type === "select") {
return {
...component,
type: "SELECT_MENU",
type: Discord.ComponentType.SelectMenu,
options: component.options.map((option) => ({
...option,
default: component.values?.includes(option.value),
@@ -367,13 +391,16 @@ function getDiscordMessageOptions(
}
}
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 = "_ _"
}

View File

@@ -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 interface ReacordConfig {
/**
* @category Core
*/
export type 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) => {

View File

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

View File

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

View File

@@ -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

View File

@@ -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>

View File

@@ -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,17 +39,16 @@ 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>
disableComponents(): Promise<void>
}
export function getNextActionRow(options: MessageOptions): ActionRow {

View File

@@ -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,15 @@ 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
}
get text(): string {
return [...this.children].map((child) => child.text).join("")
}
}

View File

@@ -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,6 +50,11 @@ const config: HostConfig<
},
createTextInstance: (text) => new TextNode(text),
shouldSetTextContent: () => false,
detachDeletedInstance: (_instance) => {},
beforeActiveInstanceBlur: () => {},
afterActiveInstanceBlur: () => {},
getInstanceFromNode: (_node: unknown) => null,
getInstanceFromScope: (_scopeInstance: unknown) => null,
clearContainer: (renderer) => {
renderer.nodes.clear()
@@ -87,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)

View File

@@ -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
}
}
@@ -83,7 +81,17 @@ export abstract class Renderer {
if (payload.action === "deactivate") {
this.updateSubscription.unsubscribe()
await this.message?.disableComponents()
await this.message?.edit({
...payload.options,
actionRows: payload.options.actionRows.map((row) =>
row.map((component) => ({
...component,
disabled: true,
})),
),
})
return
}

View File

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

View File

@@ -2,15 +2,33 @@
"name": "reacord",
"type": "module",
"description": "Create interactive Discord messages using React.",
"version": "0.3.1",
"types": "./dist/main.d.ts",
"files": [
"dist"
"version": "0.5.5",
"homepage": "https://reacord.mapleleaf.dev",
"repository": "https://github.com/itsMapleLeaf/reacord.git",
"changelog": "https://github.com/itsMapleLeaf/reacord/releases",
"license": "MIT",
"keywords": [
"discord",
"discord-js",
"react",
"react-js",
"react-renderer",
"interaction",
"message",
"embed",
"reacord"
],
"files": [
"dist",
"README.md",
"LICENSE"
],
"types": "./dist/main.d.ts",
"exports": {
".": {
"import": "./dist/main.js",
"require": "./dist/main.cjs"
"require": "./dist/main.cjs",
"types": "./dist/main.d.ts"
},
"./package.json": {
"import": "./package.json",
@@ -18,24 +36,22 @@
}
},
"scripts": {
"build": "tsup-node 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 --dts --dts-resolve",
"build-watch": "pnpm build -- --watch",
"test": "vitest --coverage --no-watch",
"test-dev": "vitest",
"typecheck": "tsc --noEmit",
"playground": "nodemon --exec esmo --ext ts,tsx --inspect=5858 --enable-source-maps ./playground/main.tsx",
"release": "pnpm build && cp ../../README.md . && release-it"
"test-manual": "nodemon --exec tsx --ext ts,tsx ./scripts/discordjs-manual-test.tsx",
"typecheck": "tsc -b"
},
"dependencies": {
"@types/node": "*",
"@types/react": "*",
"@types/react-reconciler": "^0.26.4",
"nanoid": "^3.1.31",
"react-reconciler": "^0.26.2",
"rxjs": "^7.5.2"
"@types/node": "^20.8.4",
"@types/react": "^18.2.27",
"@types/react-reconciler": "^0.28.5",
"react-reconciler": "^0.29.0",
"rxjs": "^7.8.1"
},
"peerDependencies": {
"discord.js": "^13.3",
"discord.js": "^14",
"react": ">=17"
},
"peerDependenciesMeta": {
@@ -44,27 +60,20 @@
}
},
"devDependencies": {
"@types/lodash-es": "^4.17.5",
"c8": "^7.11.0",
"discord.js": "^13.5.1",
"dotenv": "^11.0.0",
"esbuild": "latest",
"esbuild-jest": "^0.5.0",
"esmo": "^0.13.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.5.1",
"pretty-ms": "^7.0.1",
"react": "^17.0.2",
"release-it": "^14.12.1",
"tsup": "^5.11.11",
"type-fest": "^2.9.0",
"typescript": "^4.5.4",
"vite": "^2.7.10",
"vitest": "^0.0.141"
},
"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.4.0"
},
"release-it": {
"git": {
@@ -74,5 +83,8 @@
"release": true,
"web": true
}
},
"publishConfig": {
"access": "public"
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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",

View File

@@ -1,11 +1,11 @@
import React, { useState } from "react"
import { expect, fn, test } from "vitest"
import { useState } from "react"
import { expect, test, vi } from "vitest"
import { Button, Option, Select } from "../library/main"
import { ReacordTester } from "./test-adapter"
test("single select", async () => {
const tester = new ReacordTester()
const onSelect = fn()
const onSelect = vi.fn()
function TestSelect() {
const [value, setValue] = useState<string>()
@@ -59,23 +59,23 @@ 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)
})
test("multiple select", async () => {
const tester = new ReacordTester()
const onSelect = fn()
const onSelect = vi.fn()
function TestSelect() {
const [values, setValues] = useState<string[]>([])
@@ -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: "",

View File

@@ -1,14 +1,12 @@
/* eslint-disable class-methods-use-this */
/* eslint-disable require-await */
import { nanoid } from "nanoid"
import { nextTick } from "node:process"
import { promisify } from "node:util"
import { 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 type {
ChannelInfo,
GuildInfo,
@@ -26,22 +24,13 @@ import type {
CommandInteraction,
SelectInteraction,
} from "../library/internal/interaction"
import type {
Message,
MessageButtonOptions,
MessageOptions,
MessageSelectOptions,
} from "../library/internal/message"
import type { Message, MessageOptions } from "../library/internal/message"
import { ChannelMessageRenderer } from "../library/internal/renderers/channel-message-renderer"
import { InteractionReplyRenderer } from "../library/internal/renderers/interaction-reply-renderer"
const nextTickPromise = promisify(nextTick)
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>()
@@ -73,9 +62,10 @@ export class ReacordTester extends Reacord {
return this.reply(initialContent)
}
async assertMessages(expected: MessageSample[]) {
await nextTickPromise()
assertMessages(expected: MessageSample[]) {
return waitFor(() => {
expect(this.sampleMessages()).toEqual(expected)
})
}
async assertRender(content: ReactNode, expected: MessageSample[]) {
@@ -108,58 +98,59 @@ export class ReacordTester extends Reacord {
}
findButtonByLabel(label: string) {
for (const message of this.messageContainer) {
for (const component of message.options.actionRows.flat()) {
return {
click: () => {
return waitFor(() => {
for (const [component, message] of this.eachComponent()) {
if (component.type === "button" && component.label === label) {
return this.createButtonActions(component, message)
}
this.handleComponentInteraction(
new TestButtonInteraction(component.customId, message, this),
)
return
}
}
raise(`Couldn't find button with label "${label}"`)
})
},
}
}
findSelectByPlaceholder(placeholder: string) {
for (const message of this.messageContainer) {
for (const component of message.options.actionRows.flat()) {
return {
select: (...values: string[]) => {
return waitFor(() => {
for (const [component, message] of this.eachComponent()) {
if (
component.type === "select" &&
component.placeholder === placeholder
) {
return this.createSelectActions(component, message)
}
this.handleComponentInteraction(
new TestSelectInteraction(
component.customId,
message,
values,
this,
),
)
return
}
}
raise(`Couldn't find select with placeholder "${placeholder}"`)
})
},
}
}
createMessage(options: MessageOptions) {
return new TestMessage(options, this.messageContainer)
}
private createButtonActions(
button: MessageButtonOptions,
message: TestMessage,
) {
return {
click: () => {
this.handleComponentInteraction(
new TestButtonInteraction(button.customId, message, this),
)
},
private *eachComponent() {
for (const message of this.messageContainer) {
for (const component of message.options.actionRows.flat()) {
yield [component, message] as const
}
}
private createSelectActions(
component: MessageSelectOptions,
message: TestMessage,
) {
return {
select: (...values: string[]) => {
this.handleComponentInteraction(
new TestSelectInteraction(component.customId, message, values, this),
)
},
}
}
}
@@ -175,16 +166,6 @@ class TestMessage implements Message {
this.options = options
}
async disableComponents(): Promise<void> {
for (const row of this.options.actionRows) {
for (const action of row) {
if (action.type === "button") {
action.disabled = true
}
}
}
}
async delete(): Promise<void> {
this.container.remove(this)
}
@@ -197,21 +178,19 @@ class TestCommandInteraction implements CommandInteraction {
constructor(private messageContainer: Container<TestMessage>) {}
reply(messageOptions: MessageOptions): Promise<Message> {
return Promise.resolve(
new TestMessage(messageOptions, this.messageContainer),
)
async reply(messageOptions: MessageOptions): Promise<Message> {
await setTimeout()
return new TestMessage(messageOptions, this.messageContainer)
}
followUp(messageOptions: MessageOptions): Promise<Message> {
return Promise.resolve(
new TestMessage(messageOptions, this.messageContainer),
)
async followUp(messageOptions: MessageOptions): Promise<Message> {
await setTimeout()
return new TestMessage(messageOptions, this.messageContainer)
}
}
class TestInteraction {
readonly id = nanoid()
readonly id = randomUUID()
readonly channelId = "test-channel-id"
constructor(
@@ -269,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)
@@ -291,7 +270,10 @@ class TestSelectChangeEvent
extends TestComponentEvent
implements SelectChangeEvent
{
constructor(readonly values: string[], tester: ReacordTester) {
constructor(
readonly values: string[],
tester: ReacordTester,
) {
super(tester)
}
}

View File

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

View File

@@ -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 () => {
@@ -55,7 +54,7 @@ describe("useInstance", () => {
await tester.assertMessages([messageOutput("parent")])
expect(instanceFromHook).toBe(instance)
tester.findButtonByLabel("create parent").click()
await tester.findButtonByLabel("create parent").click()
await tester.assertMessages([
messageOutput("parent"),
messageOutput("child"),
@@ -63,10 +62,10 @@ describe("useInstance", () => {
// this test ensures that the only the child instance is destroyed,
// and not the parent instance
tester.findButtonByLabel("destroy child").click()
await tester.findButtonByLabel("destroy child").click()
await tester.assertMessages([messageOutput("parent")])
tester.findButtonByLabel("destroy parent").click()
await tester.findButtonByLabel("destroy parent").click()
await tester.assertMessages([])
})
})

View File

@@ -1,3 +1,7 @@
{
"extends": "../../tsconfig.base.json"
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "react-jsx"
},
"exclude": ["node_modules", "dist"]
}

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