272 Commits

Author SHA1 Message Date
Darius
a00fbc0631 Merge pull request #42 from itsMapleLeaf/changeset-release/main 2023-10-28 14:53:10 -05:00
github-actions[bot]
a713f17a5c Version Packages 2023-10-28 19:49:36 +00:00
Darius
44795cd7cc Merge pull request #41 from itsMapleLeaf/dev 2023-10-28 14:49:01 -05:00
itsMapleLeaf
17978a5252 node 16 is EOL 2023-10-28 14:47:01 -05:00
itsMapleLeaf
95fb342183 remove format and fix lint:prettier 2023-10-28 14:46:25 -05:00
itsMapleLeaf
0772ca4502 fix test command interaction 2023-10-28 14:45:03 -05:00
itsMapleLeaf
11153dfe0f breaking: more descriptive component event types 2023-10-28 14:39:16 -05:00
itsMapleLeaf
fb0a997855 changeset 2023-10-28 14:34:13 -05:00
itsMapleLeaf
da1c62f2f0 public interface tweaks and such 2023-10-28 14:34:09 -05:00
Darius
cdc22b7916 Merge pull request #40 from domin-mnd/main 2023-10-28 13:04:33 -05:00
Domin-MND
7fee69c8ae fix select-menu guide 2023-10-27 16:09:18 +03:00
Domin-MND
c2e5dc04dd fix api guides 2023-10-27 16:06:00 +03:00
Domin-MND
390da4cab6 remove initial content for create methods 2023-10-24 19:58:48 +03:00
Domin-MND
def0c46f13 fix monorepo formatting 2023-10-23 23:25:44 +03:00
Domin-MND
8b6e283810 update guides 2023-10-23 23:22:25 +03:00
Domin-MND
13fcf7ddc9 match test adapter syntax 2023-10-23 22:25:06 +03:00
Domin-MND
ce12351a24 fix formatting 2023-10-23 22:08:08 +03:00
Domin-MND
73bb098774 add options for component event 2023-10-23 22:05:05 +03:00
Domin-MND
4ee4d4ab91 add options for component event 2023-10-23 22:02:33 +03:00
Domin-MND
f998a0e09a fix djs manual test 2023-10-23 12:24:24 +03:00
Domin-MND
453192cc96 cleanup 2023-10-23 11:51:59 +03:00
Domin-MND
d387f669ab more descriptive djs adapter methods 2023-10-21 11:16:58 +03:00
Darius
9aec87ae9f Merge pull request #39 from domin-mnd/main 2023-10-19 13:05:01 -05:00
Domin-MND
65d1d68bb0 fix id raising 2023-10-19 16:37:51 +03:00
Domin-MND
dfb7562c97 use reply renderer for ephermalReply 2023-10-18 21:48:38 +03:00
Domin-MND
9e2be6c2e0 add opts argument support 2023-10-18 21:39:17 +03:00
Domin-MND
d078995516 deprecate ephemeralReply in adapters 2023-10-18 20:59:14 +03:00
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
MapleLeaf
9a6f85a726 copy readme before publish 2022-01-12 09:57:02 -06:00
MapleLeaf
a79649048f fix version 2022-01-12 09:55:46 -06:00
MapleLeaf
e7196e686c build before release 2022-01-12 09:55:04 -06:00
Darius
26eb8bedb0 Add useInstance (#6) 2022-01-12 09:55:03 -06:00
MapleLeaf
2851d4b787 update todo 2022-01-12 09:55:03 -06:00
MapleLeaf
46d3c64133 release v0.2.0 2022-01-12 09:55:03 -06:00
MapleLeaf
6b77971ed5 docs -> website 2022-01-11 00:28:41 -06:00
MapleLeaf
effd16ed97 run reacord and docs test in separate processes 2022-01-11 00:25:13 -06:00
MapleLeaf
989ab330b3 just test reacord 2022-01-11 00:25:13 -06:00
MapleLeaf
0aafc66ce1 debug log 2022-01-11 00:25:13 -06:00
MapleLeaf
ff8347b52a try just running parallel test 2022-01-11 00:25:13 -06:00
MapleLeaf
c436500b3a try running test in packages/docs 2022-01-11 00:25:13 -06:00
MapleLeaf
e93506409f no esmo 2022-01-11 00:25:13 -06:00
MapleLeaf
8482f6e91a simplify workflow again 2022-01-11 00:25:13 -06:00
MapleLeaf
c5e11b4417 run scripts in parallel 2022-01-11 00:25:13 -06:00
MapleLeaf
2e4ff0f524 remove detached flag 2022-01-11 00:25:13 -06:00
MapleLeaf
d0c940c693 exit 2022-01-11 00:25:13 -06:00
MapleLeaf
01f245c2e2 kill detached process with sigkill 2022-01-11 00:25:13 -06:00
MapleLeaf
b65004dd75 try to kill detached process 2022-01-11 00:25:12 -06:00
MapleLeaf
d9dd4d5307 test: kill app with sigkill 2022-01-11 00:25:12 -06:00
MapleLeaf
2b3b8953d0 don't test in parallel??? 2022-01-11 00:25:12 -06:00
MapleLeaf
a6b706a3de add wait-on types??? 2022-01-11 00:25:12 -06:00
MapleLeaf
d3f6c8af4d write test script for cypress
to properly kill the process
2022-01-11 00:25:12 -06:00
MapleLeaf
b0e937f896 exit after test 2022-01-11 00:25:12 -06:00
MapleLeaf
8b371cd1cf separate test and test dev scripts 2022-01-11 00:25:12 -06:00
MapleLeaf
ba155226f1 run test scripts in parallel 2022-01-11 00:25:12 -06:00
MapleLeaf
a1424f4607 linter lol 2022-01-11 00:25:12 -06:00
MapleLeaf
42461c7ec8 upgrades 2022-01-11 00:25:12 -06:00
MapleLeaf
27f793b1db print coverage from test script 2022-01-11 00:25:12 -06:00
MapleLeaf
97a5526d9d run test in main workflow 2022-01-11 00:25:12 -06:00
MapleLeaf
99eebef9a9 turn off watch in coverage 2022-01-11 00:25:12 -06:00
MapleLeaf
1b97f9256f deeply prune defined undefined values in test adapter 2022-01-11 00:25:12 -06:00
MapleLeaf
1a04e6093d clearer select option resolution 2022-01-11 00:25:12 -06:00
MapleLeaf
4803cb8478 remove reacord-tester from core 2022-01-11 00:25:12 -06:00
MapleLeaf
4201f45cc9 use export default in cypress plugin file 2022-01-11 00:25:12 -06:00
MapleLeaf
52b83522de ignore cypress videos and screenshots 2022-01-11 00:25:12 -06:00
MapleLeaf
017a417773 add vitest in project 2022-01-11 00:25:12 -06:00
MapleLeaf
661a253d8c update todo 2022-01-10 17:15:50 -06:00
MapleLeaf
5b68a1f0ea yaml is bad 2022-01-10 17:07:24 -06:00
MapleLeaf
8c4a450bfb update paths on deploy workflow 2022-01-10 17:06:45 -06:00
MapleLeaf
14b74a0a3f remove readme in docs 2022-01-10 17:05:33 -06:00
MapleLeaf
f2d309b2a7 add eslint override for cypress 2022-01-10 16:52:31 -06:00
MapleLeaf
adeb0fb0d9 fix type checking for cypress 2022-01-10 16:04:09 -06:00
Sami Ibrahim
4f8308dc73 Update README.md (#5) 2022-01-10 15:33:29 -06:00
MapleLeaf
f5d8fa5271 docker: set node env after install 2022-01-10 15:11:38 -06:00
MapleLeaf
ac759412b3 lint fix 2022-01-10 15:10:50 -06:00
MapleLeaf
608b008659 fix typress type error 2022-01-10 15:10:23 -06:00
MapleLeaf
87cbf1b74d docs: add cypress test 2022-01-10 15:06:55 -06:00
MapleLeaf
4f463bfa23 link directly to alpine dist js
just to reduce network round trips
2022-01-10 14:44:19 -06:00
MapleLeaf
2e65218083 release v0.1.1 2022-01-09 20:35:54 -06:00
MapleLeaf
1e4a2bd006 configure release-it 2022-01-09 20:34:44 -06:00
MapleLeaf
76bd0b0b98 add doc comments 2022-01-09 20:31:31 -06:00
MapleLeaf
021afc154f more helpful reference links 2022-01-09 19:41:48 -06:00
MapleLeaf
fe39859b68 add links doc 2022-01-09 19:34:24 -06:00
MapleLeaf
c55fb22a8f lower framerate gif 2022-01-09 17:40:15 -06:00
MapleLeaf
7d8336c7a7 migrate docs back to remix oops 2022-01-09 17:36:42 -06:00
Darius
c6ea101330 Add demo gif (#3) 2022-01-09 16:39:08 -06:00
MapleLeaf
4e9b358731 run serve script directly from docker container 2022-01-09 13:41:43 -06:00
MapleLeaf
a66520829a remove cross-env 2022-01-09 13:09:17 -06:00
MapleLeaf
e2b150bbe2 docs: disable source maps in prod 2022-01-09 13:01:00 -06:00
MapleLeaf
be42042552 upgrades 2022-01-09 12:55:37 -06:00
MapleLeaf
3bfc5f4977 try to fix deploy issues 2022-01-09 12:46:51 -06:00
197 changed files with 9851 additions and 11413 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,17 +0,0 @@
{
"extends": ["./node_modules/@itsmapleleaf/configs/eslint"],
"ignorePatterns": [
"**/node_modules/**",
"**/.cache/**",
"**/build/**",
"**/dist/**",
"**/coverage/**"
],
"parserOptions": {
"project": "./tsconfig.base.json"
},
"rules": {
"import/no-unused-modules": "off",
"unicorn/prevent-abbreviations": "off"
}
}

View File

@@ -1,16 +0,0 @@
name: deploy docs
on:
push:
branches: [main]
paths: [packages/docs/**, reacord/library/**/*.ts]
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,37 +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-scripts:
strategy:
matrix:
scripts:
- name: test
script: coverage
- name: lint
script: lint
- name: typecheck
script: typecheck
- name: build
script: build
fail-fast: false
name: ${{ matrix.scripts.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: pnpm run --recursive ${{ matrix.scripts.script }}

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,13 +0,0 @@
FROM node:lts-slim
WORKDIR /app
COPY / ./
RUN ls -R
RUN npm install -g pnpm
RUN pnpm install --unsafe-perm --frozen-lockfile
RUN pnpm build -C packages/docs
RUN pnpm install --prod --unsafe-perm --frozen-lockfile
CMD [ "pnpm", "start", "-C", "packages/docs" ]

View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2022 itsMapleLeaf
Copyright (c) 2022 itsMapleLeaf
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,6 +1,26 @@
# reacord
<center>
<img src="packages/website/src/assets/banner.png" alt="Reacord: Create interactive Discord messages using React">
</center>
Create interactive Discord messages using React! [Visit the docs to get started.](https://reacord.fly.dev/guides/getting-started)
## Installation ∙ [![npm](https://img.shields.io/npm/v/reacord?color=blue&style=flat-square)](https://www.npmjs.com/package/reacord)
```console
# npm
npm install reacord react discord.js
# yarn
yarn add reacord react discord.js
# pnpm
pnpm add reacord react discord.js
```
## Get Started
[Visit the docs to get started.](https://reacord.mapleleaf.dev/guides/getting-started)
## Example
<!-- prettier-ignore -->
```tsx
@@ -21,3 +41,5 @@ function Counter() {
)
}
```
![Counter demo](./reacord-counter-demo.gif)

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,44 @@
{
"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 . \"**/*.astro\" --write --cache --list-different",
"lint:types": "tsc -b & pnpm -r --parallel run typecheck",
"astro-sync": "pnpm --filter website exec astro sync",
"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.8.1",
"@typescript-eslint/parser": "^5.8.1",
"eslint": "^8.5.0",
"eslint-config-prettier": "^8.3.0",
"eslint-import-resolver-typescript": "^2.5.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-react": "^7.28.0",
"eslint-plugin-react-hooks": "^4.3.0",
"eslint-plugin-unicorn": "^39.0.0",
"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

@@ -1,3 +0,0 @@
.asset-cache
node_modules
/api

View File

@@ -1,65 +0,0 @@
{
"name": "reacord-docs-new",
"type": "module",
"private": true,
"scripts": {
"prepare": "node ./scripts/fix-heroicons.js",
"serve": "esmo --experimental-import-meta-resolve --experimental-json-modules --no-warnings --enable-source-maps src/main.tsx | pino-colada",
"dev": "npm-run-all --parallel --print-label --race dev-*",
"dev-server": "nodemon --inspect --exec \"pnpm serve\" --watch src --ext ts,tsx,md,css",
"dev-docs": "typedoc --watch",
"build": "typedoc",
"start": "cross-env NODE_ENV=production pnpm serve",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@heroicons/react": "^1.0.5",
"@tailwindcss/typography": "^0.5.0",
"alpinejs": "^3.7.1",
"autoprefixer": "^10.4.1",
"clsx": "^1.1.1",
"compression": "^1.7.4",
"cross-env": "^7.0.3",
"cssnano": "^5.0.15",
"esbuild": "^0.14.10",
"esno": "^0.13.0",
"express": "^4.17.2",
"express-promise-router": "^4.1.1",
"fast-glob": "^3.2.7",
"gray-matter": "^4.0.3",
"http-terminator": "^3.0.4",
"markdown-it": "^12.3.0",
"markdown-it-prism": "^2.2.1",
"pino": "^7.6.2",
"pino-colada": "^2.2.2",
"pino-http": "^6.5.0",
"postcss": "^8.4.5",
"reacord": "workspace:*",
"react": "^18.0.0-rc.0",
"react-dom": "^18.0.0-rc.0",
"react-ssr-prepass": "^1.5.0",
"tailwindcss": "^3.0.8"
},
"devDependencies": {
"@types/browser-sync": "^2.26.3",
"@types/compression": "^1.7.2",
"@types/cssnano": "^5.0.0",
"@types/express": "^4.17.13",
"@types/markdown-it": "^12.2.3",
"@types/node": "*",
"@types/react": "^17.0.38",
"@types/react-dom": "^17.0.9",
"@types/tailwindcss": "^3.0.0",
"@types/wait-on": "^5.3.1",
"browser-sync": "^2.27.7",
"execa": "^6.0.0",
"nodemon": "^2.0.15",
"npm-run-all": "^4.1.5",
"rxjs": "^7.5.1",
"tsup": "^5.11.10",
"type-fest": "^2.8.0",
"typedoc": "^0.22.10",
"typescript": "^4.5.4",
"wait-on": "^6.0.0"
}
}

View File

@@ -1,6 +0,0 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@@ -1,15 +0,0 @@
// heroicons doesn't have "sideEffects": false in it's package json,
// which causes esbuild to bundle in 460+ imports of react for some reason,
// which causes memory issues
import glob from "fast-glob"
import { readFile, writeFile } from "node:fs/promises"
const files = await glob("node_modules/@heroicons/react/**/*.json", {
absolute: true,
})
for (const file of files) {
const data = JSON.parse(await readFile(file, "utf8"))
data.sideEffects = false
await writeFile(file, JSON.stringify(data, undefined, 2))
}

View File

@@ -1,10 +0,0 @@
import { createContext, useContext } from "react"
import type { AssetBuilder } from "../asset-builder/asset-builder.js"
import { raise } from "../helpers/raise.js"
const Context = createContext<AssetBuilder>()
export const AssetBuilderProvider = Context.Provider
export const useAssetBuilder = () =>
useContext(Context) ?? raise("AssetBuilderProvider not found")

View File

@@ -1,96 +0,0 @@
import type { RequestHandler } from "express"
import express from "express"
import { createHash } from "node:crypto"
import { mkdir, rm } from "node:fs/promises"
import { join, parse } from "node:path"
import React from "react"
import { renderToStaticMarkup } from "react-dom/server"
import ssrPrepass from "react-ssr-prepass"
import type { Promisable } from "type-fest"
import { ensureWrite, normalizeAsFilePath } from "../helpers/filesystem.js"
import { AssetBuilderProvider } from "./asset-builder-context.js"
export type AssetTransformer<Asset> = {
transform: (context: AssetTransformContext) => Promise<Asset>
}
export class AssetBuilder {
private constructor(private cacheFolder: string) {}
static async create(cacheFolder: string) {
if (process.env.NODE_ENV !== "production") {
await rm(cacheFolder, { recursive: true }).catch(() => {})
}
await mkdir(cacheFolder, { recursive: true })
return new AssetBuilder(cacheFolder)
}
async build<Asset>(
input: Promisable<string | URL>,
transformer: AssetTransformer<Asset>,
alias?: string,
): Promise<Asset> {
const inputFile = normalizeAsFilePath(await input)
// TODO: cache assets by inputFile in production
return transformer.transform(
new AssetTransformContext({
inputFile,
cacheFolder: this.cacheFolder,
alias: alias || parse(inputFile).name,
}),
)
}
async render(element: React.ReactElement) {
element = (
<AssetBuilderProvider value={this}>
<React.Suspense fallback={<></>}>{element}</React.Suspense>
</AssetBuilderProvider>
)
await ssrPrepass(element)
return `<!DOCTYPE html>\n${renderToStaticMarkup(element)}`
}
middleware(): RequestHandler {
return express.static(this.cacheFolder, {
immutable: true,
maxAge: "1y",
})
}
}
export type AssetTransformOptions = {
inputFile: string
cacheFolder: string
alias: string
}
export class AssetTransformContext {
constructor(private options: AssetTransformOptions) {}
get inputFile() {
return this.options.inputFile
}
get cacheFolder() {
return this.options.cacheFolder
}
get alias() {
return this.options.alias
}
getOutputFileName(content: string) {
const { ext } = parse(this.inputFile)
const hash = createHash("sha256").update(content).digest("hex").slice(0, 8)
return `${this.alias}.${hash}${ext}`
}
async writeOutputFile(content: string) {
const outputFileName = this.getOutputFileName(content)
const outputFile = join(this.cacheFolder, outputFileName)
await ensureWrite(outputFile, content)
return { outputFileName, outputFile }
}
}

View File

@@ -1,75 +0,0 @@
import type { ReactNode } from "react";
import React from "react"
import { normalizeAsFilePath } from "../helpers/filesystem.js"
import { useAssetBuilder } from "./asset-builder-context.js"
import type { AssetBuilder, AssetTransformer } from "./asset-builder.js"
type AssetState =
| { status: "building"; promise: Promise<unknown> }
| { status: "built"; asset: unknown }
const cache = new Map<string, AssetState>()
function useAssetBuild<Asset>(
cacheKey: string,
build: (builder: AssetBuilder) => Promise<Asset>,
) {
const builder = useAssetBuilder()
const state = cache.get(cacheKey)
if (!state) {
const promise = build(builder).then((asset) => {
cache.set(cacheKey, { status: "built", asset })
})
cache.set(cacheKey, { status: "building", promise })
throw promise
}
if (state.status === "building") {
throw state.promise
}
return state.asset as Asset
}
export function LocalFileAsset<Asset>({
from,
using: transformer,
as: alias,
children,
}: {
from: string | URL
using: AssetTransformer<Asset>
as?: string
children: (url: Asset) => ReactNode
}) {
const inputFile = normalizeAsFilePath(from)
const asset = useAssetBuild(inputFile, (builder) => {
return builder.build(inputFile, transformer, alias)
})
return <>{children(asset)}</>
}
export function ModuleAsset<Asset>({
from,
using: transformer,
as: name,
children,
}: {
from: string
using: AssetTransformer<Asset>
as?: string
children: (url: Asset) => ReactNode
}) {
const cacheKey = `node:${from}`
const asset = useAssetBuild(cacheKey, async (builder) => {
const inputFile = await import.meta.resolve!(from)
return await builder.build(inputFile, transformer, name)
})
return <>{children(asset)}</>
}

View File

@@ -1,29 +0,0 @@
import grayMatter from "gray-matter"
import MarkdownIt from "markdown-it"
import prism from "markdown-it-prism"
import { readFile } from "node:fs/promises"
import type { AssetTransformer } from "./asset-builder.jsx"
const renderer = new MarkdownIt({
html: true,
linkify: true,
}).use(prism)
export type MarkdownAsset = {
content: { __html: string }
data: Record<string, any>
}
export const markdownTransformer: AssetTransformer<MarkdownAsset> = {
async transform(context) {
const { data, content } = grayMatter(
await readFile(context.inputFile, "utf8"),
)
const html = renderer.render(content)
return {
content: { __html: html },
data,
}
},
}

View File

@@ -1,26 +0,0 @@
import { build } from "esbuild"
import type { AssetTransformer } from "./asset-builder.jsx"
type ScriptAsset = {
url: string
}
export const scriptTransformer: AssetTransformer<ScriptAsset> = {
async transform(context) {
const scriptBuild = await build({
entryPoints: [context.inputFile],
bundle: true,
target: ["chrome89", "firefox89"],
format: "esm",
write: false,
minify: process.env.NODE_ENV === "production",
})
const content = scriptBuild.outputFiles[0]!.text
const { outputFileName } = await context.writeOutputFile(content)
return {
url: "/" + outputFileName,
}
},
}

View File

@@ -1,26 +0,0 @@
import autoprefixer from "autoprefixer"
import cssnano from "cssnano"
import { readFile } from "node:fs/promises"
import type { AcceptedPlugin } from "postcss"
import postcss from "postcss"
import tailwindcss from "tailwindcss"
import type { AssetTransformer } from "./asset-builder.jsx"
export type StylesheetAsset = { url: string }
export const stylesheetTransformer: AssetTransformer<StylesheetAsset> = {
async transform(context) {
const plugins: AcceptedPlugin[] = [tailwindcss, autoprefixer]
if (process.env.NODE_ENV === "production") {
plugins.push(cssnano)
}
const result = await postcss(plugins).process(
await readFile(context.inputFile),
{ from: context.inputFile },
)
const { outputFileName } = await context.writeOutputFile(result.css)
return { url: "/" + outputFileName }
},
}

View File

@@ -1,7 +0,0 @@
import { join } from "node:path"
const projectRoot = new URL("../", import.meta.url).pathname
export function fromProjectRoot(...subPaths: string[]) {
return join(projectRoot, ...subPaths)
}

View File

@@ -1,10 +0,0 @@
import type { ComponentPropsWithoutRef } from "react"
import React from "react"
export function ExternalLink(props: ComponentPropsWithoutRef<"a">) {
return (
<a target="_blank" rel="noopener noreferrer" {...props}>
{props.children}
</a>
)
}

View File

@@ -1,46 +0,0 @@
---
order: 3
title: Buttons
description: Using button components
---
# Buttons
Use the `<Button />` component to create a message with a button, and use the `onClick` callback to respond to button clicks.
```jsx
import { Button } from "reacord"
function Counter() {
const [count, setCount] = useState(0)
return (
<>
You've clicked the button {count} times.
<Button label="+1" onClick={() => setCount(count + 1)} />
</>
)
}
```
The `onClick` callback receives an `event` object. It includes some information, such as the user who clicked the button, and functions for creating new replies in response. These functions return message instances.
```jsx
import { Button } from "reacord"
function TheButton() {
function handleClick(event) {
const name = event.guild.member.displayName || event.user.username
const publicReply = event.reply(`${name} clicked the button. wow`)
setTimeout(() => publicReply.destroy(), 3000)
const privateReply = event.ephemeralReply("good job, you clicked it")
privateReply.deactivate() // we don't need to listen to updates on this
}
return <Button label="click me i dare you" onClick={handleClick} />
}
```
See the [API reference](/api) for more information.

View File

@@ -1,63 +0,0 @@
---
order: 2
title: Embeds
description: Using embed components
---
# Embeds
Reacord comes with an `<Embed />` component for sending rich embeds.
```jsx
import { Embed } from "reacord"
function FancyMessage({ title, description }) {
return (
<Embed
title={title}
description={description}
color={0x00ff00}
timestamp={Date.now()}
/>
)
}
```
```jsx
reacord.send(channelId, <FancyMessage title="Hello" description="World" />)
```
Reacord also comes with multiple embed components, for defining embeds on a piece-by-piece basis. This enables composition:
```jsx
import { Embed, EmbedTitle } from "reacord"
function FancyDetails({ title, description }) {
return (
<>
<EmbedTitle>{title}</EmbedTitle>
{/* embed descriptions are just text */}
{description}
</>
)
}
function FancyMessage({ children }) {
return (
<Embed color={0x00ff00} timestamp={Date.now()}>
{children}
</Embed>
)
}
```
```jsx
reacord.send(
channelId,
<FancyMessage>
<FancyDetails title="Hello" description="World" />
</FancyMessage>,
)
```
See the [API Reference](/api) for the full list of embed components.

View File

@@ -1,43 +0,0 @@
---
order: 0
title: Getting Started
description: Learn how to get started with Reacord.
---
# Getting Started
This guide assumes some familiarity with JavaScript, [React](https://reactjs.org), [Discord.js](https://discord.js.org) and the [Discord API](https://discord.dev). Keep these pages as reference if you need it.
**Note:** Ensure your project has support for running code with JSX. I recommend using [esno](https://npm.im/esno).
## Install
```bash
# npm
npm install reacord react discord.js
# yarn
yarn add reacord react discord.js
# pnpm
pnpm add reacord react discord.js
```
## Setup
Create a Discord.js client and a Reacord instance:
```js
// main.js
import { Client } from "discord.js"
import { ReacordDiscordJs } from "reacord"
const client = new Client()
const reacord = new ReacordDiscordJs(client)
client.on("ready", () => {
console.log("Ready!")
})
await client.login(process.env.BOT_TOKEN)
```

View File

@@ -1,56 +0,0 @@
import clsx from "clsx"
import React from "react"
import { LocalFileAsset } from "../asset-builder/asset.js"
import { markdownTransformer } from "../asset-builder/markdown-transformer.js"
import { Html } from "../html.js"
import { AppLink } from "../navigation/app-link"
import { guideLinks } from "../navigation/guide-links"
import { MainNavigation } from "../navigation/main-navigation"
import { docsProseClass, linkClass, maxWidthContainer } from "../ui/components"
export function GuidePage({ url }: { url: string }) {
return (
<LocalFileAsset
from={new URL(`${url}.md`, import.meta.url)}
using={markdownTransformer}
>
{(asset) => (
<Html title={asset.data.title} description={asset.data.description}>
<Header />
<Body content={asset.content} />
</Html>
)}
</LocalFileAsset>
)
}
function Header() {
return (
<header className="bg-slate-700/30 shadow sticky top-0 backdrop-blur-sm transition z-10 flex">
<div className={maxWidthContainer}>
<MainNavigation />
</div>
</header>
)
}
function Body({ content }: { content: { __html: string } }) {
return (
<main className={clsx(maxWidthContainer, "mt-8 flex items-start gap-4")}>
<nav className="w-48 sticky top-24 hidden md:block">
<h2 className="text-2xl">Guides</h2>
<ul className="mt-3 flex flex-col gap-2 items-start">
{guideLinks.map((link) => (
<li key={link.to}>
<AppLink {...link} className={linkClass} />
</li>
))}
</ul>
</nav>
<section
className={clsx(docsProseClass, "pb-8 flex-1 min-w-0")}
dangerouslySetInnerHTML={content}
/>
</main>
)
}

View File

@@ -1,70 +0,0 @@
---
order: 4
title: Select Menus
description: Using select menu components
---
# Select Menus
To create a select menu, use the `Select` component, and pass a list of `Option` components as children. Use the `value` prop to set a currently selected value. You can respond to changes in the value via `onChangeValue`.
```jsx
export function FruitSelect({ onConfirm }) {
const [value, setValue] = useState()
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)
}}
/>
</>
)
}
```
```jsx
const instance = reacord.send(
channelId,
<FruitSelect
onConfirm={(value) => {
instance.render(`you chose ${value}`)
instance.deactivate()
}}
/>,
)
```
For a multi-select, use the `multiple` prop, then you can use `values` and `onChangeMultiple` to handle multiple values.
```tsx
export function FruitSelect({ onConfirm }) {
const [values, setValues] = useState([])
return (
<Select
placeholder="choose a fruit"
values={values}
onChangeMultiple={setValues}
>
<Option value="🍎" />
<Option value="🍌" />
<Option value="🍒" />
</Select>
)
}
```
The Select component accepts a variety of props beyond what's shown here. See the [API reference](/api) for more information.

View File

@@ -1,166 +0,0 @@
---
order: 1
title: Sending Messages
description: Sending messages by creating Reacord instances
---
# Sending Messages with Instances
You can send messages via Reacord to a channel like so.
```jsx
const channelId = "abc123deadbeef"
client.on("ready", () => {
reacord.send(channelId, "Hello, world!")
})
```
The `.send()` function creates a **Reacord instance**. You can pass strings, numbers, or anything that can be rendered by React, such as JSX!
Components rendered through this instance can include state and effects, and the message on Discord will update automatically.
```jsx
function Uptime() {
const [startTime] = useState(Date.now())
const [currentTime, setCurrentTime] = useState(Date.now())
useEffect(() => {
const interval = setInterval(() => {
currentTime(Date.now())
}, 3000)
return () => clearInterval(interval)
}, [])
return <>this message has been shown for {currentTime - startTime}ms</>
}
client.on("ready", () => {
reacord.send(channelId, <Uptime />)
})
```
The instance can be rendered to multiple times, which will update the message each time.
```jsx
const Hello = ({ subject }) => <>Hello, {subject}!</>
client.on("ready", () => {
const instance = reacord.send(channel)
instance.render(<Hello subject="World" />)
instance.render(<Hello subject="Moon" />)
})
```
## Cleaning Up Instances
If you no longer want to use the instance, you can clean it up in a few ways:
- `instance.destroy()` - This will remove the message.
- `instance.deactivate()` - This will keep the message, but it will disable the components on the message, and no longer listen to user interactions.
By default, Reacord has a max limit on the number of active instances, and deactivates older instances to conserve memory. This can be configured through the Reacord options:
```js
const reacord = new ReacordDiscordJs(client, {
// after sending four messages,
// the first one will be deactivated
maxInstances: 3,
})
```
## Discord Slash Commands
<aside>
This section also applies to other kinds of application commands, such as context menu commands.
</aside>
To reply to a command interaction, use the `.reply()` function. This function returns an instance that works the same way as the one from `.send()`. Here's an example:
```jsx
import { Client } from "discord.js"
import * as React from "react"
import { Button, ReacordDiscordJs } from "reacord"
const client = new Client({ intents: [] })
const reacord = new ReacordDiscordJs(client)
client.on("ready", () => {
client.application?.commands.create({
name: "ping",
description: "pong!",
})
})
client.on("interactionCreate", (interaction) => {
if (interaction.isCommand() && interaction.commandName === "ping") {
// Use the reply() function instead of send
reacord.reply(interaction, <>pong!</>)
}
})
client.login(process.env.DISCORD_TOKEN)
```
<aside>
This example uses <a href="https://discord.com/developers/docs/interactions/application-commands#registering-a-command">global commands</a>, so the command might take a while to show up 😅
</aside>
However, the process of creating commands can get really repetitive and error-prone. A command framework could help with this, or you could make a small helper:
```jsx
function handleCommands(client, commands) {
client.on("ready", () => {
for (const { name, description } of commands) {
client.application?.commands.create({ name, description })
}
})
client.on("interactionCreate", (interaction) => {
if (interaction.isCommand()) {
for (const command of commands) {
if (interaction.commandName === command.name) {
command.run(interaction)
}
}
}
})
}
```
```jsx
handleCommands(client, [
{
name: "ping",
description: "pong!",
run: (interaction) => {
reacord.reply(interaction, <>pong!</>)
},
},
{
name: "hi",
description: "say hi",
run: (interaction) => {
reacord.reply(interaction, <>hi</>)
},
},
])
```
## Ephemeral Command Replies
Ephemeral replies are replies that only appear for one user. To create them, use the `.ephemeralReply()` function.
```tsx
handleCommands(client, [
{
name: "pong",
description: "pong, but in secret",
run: (interaction) => {
reacord.ephemeralReply(interaction, <>(pong)</>)
},
},
])
```
The `ephemeralReply` function also returns an instance, but ephemeral replies cannot be updated via `instance.render()`. You can `.deactivate()` them, but `.destroy()` will not delete the message; only the user can hide it from view.

View File

@@ -1,11 +0,0 @@
import { mkdir, writeFile } from "node:fs/promises"
import { dirname } from "node:path"
export async function ensureWrite(file: string, content: string) {
await mkdir(dirname(file), { recursive: true })
await writeFile(file, content)
}
export function normalizeAsFilePath(file: string | URL) {
return new URL(file, "file:").pathname
}

View File

@@ -1,15 +0,0 @@
import grayMatter from "gray-matter"
import MarkdownIt from "markdown-it"
import prism from "markdown-it-prism"
import { readFile } from "node:fs/promises"
const renderer = new MarkdownIt({
html: true,
linkify: true,
}).use(prism)
export async function renderMarkdownFile(filePath: string) {
const { data, content } = grayMatter(await readFile(filePath, "utf8"))
const html = renderer.render(content)
return { html, data }
}

View File

@@ -1,3 +0,0 @@
export function raise(error: unknown): never {
throw error instanceof Error ? error : new Error(String(error))
}

View File

@@ -1,70 +0,0 @@
import packageJson from "reacord/package.json"
import type { ReactNode } from "react"
import React from "react"
import { LocalFileAsset, ModuleAsset } from "./asset-builder/asset.js"
import { scriptTransformer } from "./asset-builder/script-transformer.js"
import { stylesheetTransformer } from "./asset-builder/stylesheet-transformer.js"
export function Html({
title: titleProp,
description = packageJson.description,
children,
}: {
title?: string
description?: string
children: ReactNode
}) {
const title = [titleProp, "Reacord"].filter(Boolean).join(" | ")
return (
<html lang="en" className="bg-slate-900 text-slate-100">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="description" content={description} />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin=""
/>
<link
rel="preload"
as="style"
href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500&family=Rubik:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap"
/>
<ModuleAsset
from="tailwindcss/tailwind.css"
using={stylesheetTransformer}
>
{(asset) => <link rel="stylesheet" href={asset.url} />}
</ModuleAsset>
<LocalFileAsset
from={new URL("ui/prism-theme.css", import.meta.url)}
using={stylesheetTransformer}
>
{(asset) => <link rel="stylesheet" href={asset.url} />}
</LocalFileAsset>
<LocalFileAsset
from={new URL("ui/markdown.css", import.meta.url)}
using={stylesheetTransformer}
>
{(asset) => <link rel="stylesheet" href={asset.url} />}
</LocalFileAsset>
<title>{title}</title>
<ModuleAsset
from="alpinejs/dist/cdn.js"
as="alpine"
using={scriptTransformer}
>
{(asset) => <script defer src={asset.url} />}
</ModuleAsset>
</head>
<body>{children}</body>
</html>
)
}

View File

@@ -1,19 +0,0 @@
<!-- prettier-ignore -->
```tsx
import * as React from "react"
import { Embed, Button } from "reacord"
function Counter() {
const [count, setCount] = React.useState(0)
return (
<>
<Embed title="Counter">
This button has been clicked {count} times.
</Embed>
<Button onClick={() => setCount(count + 1)}>
+1
</Button>
</>
)
}
```

View File

@@ -1,42 +0,0 @@
import packageJson from "reacord/package.json"
import React from "react"
import { LocalFileAsset } from "../asset-builder/asset.js"
import { markdownTransformer } from "../asset-builder/markdown-transformer.js"
import { Html } from "../html.js"
import { MainNavigation } from "../navigation/main-navigation"
import { maxWidthContainer } from "../ui/components"
export function Landing() {
return (
<Html>
<div className="flex flex-col min-w-0 min-h-screen text-center">
<header className={maxWidthContainer}>
<MainNavigation />
</header>
<div className="px-4 pb-8 flex flex-1">
<main className="px-4 py-6 rounded-lg shadow bg-slate-800 space-y-5 m-auto w-full max-w-xl">
<h1 className="text-6xl font-light">reacord</h1>
<LocalFileAsset
from={new URL("landing-example.md", import.meta.url)}
using={markdownTransformer}
>
{(asset) => (
<section
className="mx-auto text-sm sm:text-base"
dangerouslySetInnerHTML={asset.content}
/>
)}
</LocalFileAsset>
<p className="text-2xl font-light">{packageJson.description}</p>
<a
href="/guides/getting-started"
className="inline-block px-4 py-3 text-xl transition rounded-lg bg-emerald-700 hover:translate-y-[-2px] hover:bg-emerald-800 hover:shadow"
>
Get Started
</a>
</main>
</div>
</div>
</Html>
)
}

View File

@@ -1,61 +0,0 @@
import compression from "compression"
import type { ErrorRequestHandler, Request } from "express"
import express from "express"
import PromiseRouter from "express-promise-router"
import httpTerminator from "http-terminator"
import pino from "pino"
import pinoHttp from "pino-http"
import * as React from "react"
import { AssetBuilder } from "./asset-builder/asset-builder.js"
import { fromProjectRoot } from "./constants"
import { GuidePage } from "./guides/guide-page"
import { Landing } from "./landing/landing"
const port = process.env.PORT || 3000
const builder = await AssetBuilder.create(fromProjectRoot(".asset-cache"))
const logger = pino()
const errorHandler: ErrorRequestHandler = (error, request, response, next) => {
response.status(500).send(error.message)
logger.error(error)
}
const router = PromiseRouter()
.use(pinoHttp({ logger }))
.use(compression())
.use(builder.middleware())
.use("/api", express.static("dist/api"))
.get("/guides/*", async (req: Request<{ 0: string }>, res) => {
res
.type("html")
.send(await builder.render(<GuidePage url={req.params[0]} />))
})
.get("/", async (req, res) => {
res.type("html").send(await builder.render(<Landing />))
})
.use(errorHandler)
const server = express()
.use(router)
.listen(port, () => {
logger.info(`Server is running on http://localhost:${port}`)
})
const terminator = httpTerminator.createHttpTerminator({ server })
process.on("SIGINT", () => {
terminator
.terminate()
.then(() => {
logger.info("Server terminated")
})
.catch((error) => {
logger.error(error)
})
.finally(() => {
process.exit()
})
})

View File

@@ -1,27 +0,0 @@
import React from "react"
import { ExternalLink } from "../dom/external-link"
export type AppLinkProps = {
type: "internal" | "external"
label: React.ReactNode
to: string
className?: string
}
export function AppLink(props: AppLinkProps) {
switch (props.type) {
case "internal":
return (
<a className={props.className} href={props.to}>
{props.label}
</a>
)
case "external":
return (
<ExternalLink className={props.className} href={props.to}>
{props.label}
</ExternalLink>
)
}
}

View File

@@ -1,34 +0,0 @@
import glob from "fast-glob"
import grayMatter from "gray-matter"
import { readFile } from "node:fs/promises"
import { join } from "node:path"
import type { AppLinkProps } from "./app-link"
const docsFolder = new URL("../guides", import.meta.url).pathname
const guideFiles = await glob("**/*.md", { cwd: docsFolder })
const entries = await Promise.all(
guideFiles.map(async (file) => {
const content = await readFile(join(docsFolder, file), "utf-8")
const { data } = grayMatter(content)
let order = Number(data.order)
if (!Number.isFinite(order)) {
order = Number.POSITIVE_INFINITY
}
return {
route: `/guides/${file.replace(/\.mdx?$/, "")}`,
title: String(data.title || ""),
order,
}
}),
)
export const guideLinks: AppLinkProps[] = entries
.sort((a, b) => a.order - b.order)
.map((item) => ({
type: "internal",
label: item.title,
to: item.route,
}))

View File

@@ -1,38 +0,0 @@
import {
CodeIcon,
DocumentTextIcon,
ExternalLinkIcon,
} from "@heroicons/react/solid/esm"
import React from "react"
import { inlineIconClass } from "../ui/components"
import type { AppLinkProps } from "./app-link"
export const mainLinks: AppLinkProps[] = [
{
type: "internal",
to: "/guides/getting-started",
label: (
<>
<DocumentTextIcon className={inlineIconClass} /> Guides
</>
),
},
{
type: "internal",
to: "/api",
label: (
<>
<CodeIcon className={inlineIconClass} /> API Reference
</>
),
},
{
type: "external",
to: "https://github.com/itsMapleLeaf/reacord",
label: (
<>
<ExternalLinkIcon className={inlineIconClass} /> GitHub
</>
),
},
]

View File

@@ -1,40 +0,0 @@
import React from "react"
import { linkClass } from "../ui/components"
import { PopoverMenu } from "../ui/popover-menu"
import { AppLink } from "./app-link"
import { guideLinks } from "./guide-links"
import { mainLinks } from "./main-links"
export function MainNavigation() {
return (
<nav className="flex justify-between items-center h-16">
<a href="/">
<h1 className="text-3xl font-light">reacord</h1>
</a>
<div className="hidden md:flex gap-4">
{mainLinks.map((link) => (
<AppLink {...link} key={link.to} className={linkClass} />
))}
</div>
<div className="md:hidden" id="main-navigation-popover">
<PopoverMenu>
{mainLinks.map((link) => (
<AppLink
{...link}
key={link.to}
className={PopoverMenu.itemClass}
/>
))}
<hr className="border-0 h-[2px] bg-black/50" />
{guideLinks.map((link) => (
<AppLink
{...link}
key={link.to}
className={PopoverMenu.itemClass}
/>
))}
</PopoverMenu>
</div>
</nav>
)
}

View File

@@ -1,10 +0,0 @@
import "react"
declare module "react" {
export function createContext<Value>(): Context<Value | undefined>
}
declare module "react-dom" {
export function createRoot(element: Element): {
render(element: React.ReactNode): void
}
}

View File

@@ -1,24 +0,0 @@
import clsx from "clsx"
export const maxWidthContainer = clsx`mx-auto w-full max-w-screen-lg px-4`
export const inlineIconClass = clsx`inline w-5 align-sub`
export const linkClass = clsx`
font-medium inline-block relative
opacity-60 hover:opacity-100 transition-opacity
after:absolute after:block after:w-full after:h-px after:bg-white/50 after:translate-y-[3px] after:opacity-0 after:transition
hover:after:translate-y-[-1px] hover:after:opacity-100
`
export const docsProseClass = clsx`
prose prose-invert
prose-h1:font-light prose-h1:mb-4 prose-h1:text-3xl lg:prose-h1:text-4xl
prose-h2:font-light
prose-h3:font-light
prose-p:my-4
prose-a:font-medium prose-a:text-emerald-400 hover:prose-a:no-underline
prose-strong:font-medium prose-strong:text-emerald-400
prose-pre:font-monospace prose-pre:overflow-x-auto
max-w-none
`

View File

@@ -1,3 +0,0 @@
.prose aside {
@apply opacity-75 italic border-l-4 pl-3 border-white/50;
}

View File

@@ -1,38 +0,0 @@
import clsx from "clsx"
const menus = document.querySelectorAll("[data-popover]")
for (const menu of menus) {
const button = menu.querySelector<HTMLButtonElement>("[data-popover-button]")!
const panel = menu.querySelector<HTMLDivElement>("[data-popover-panel]")!
const panelClasses = clsx`${panel.className} transition-all`
const visibleClass = clsx`${panelClasses} visible opacity-100 translate-y-0`
const hiddenClass = clsx`${panelClasses} invisible opacity-0 translate-y-2`
let visible = false
const setVisible = (newVisible: boolean) => {
visible = newVisible
panel.className = visible ? visibleClass : hiddenClass
if (!visible) return
requestAnimationFrame(() => {
const handleClose = (event: MouseEvent) => {
if (panel.contains(event.target as Node)) return
setVisible(false)
window.removeEventListener("click", handleClose)
}
window.addEventListener("click", handleClose)
})
}
const toggleVisible = () => setVisible(!visible)
button.addEventListener("click", toggleVisible)
setVisible(false)
panel.hidden = false
}

View File

@@ -1,31 +0,0 @@
import { MenuAlt4Icon } from "@heroicons/react/outline/esm"
import clsx from "clsx"
import React from "react"
import { linkClass } from "./components"
export function PopoverMenu({ children }: { children: React.ReactNode }) {
return (
<div className="relative" x-data="{ open: false }">
<button title="Menu" className={linkClass} x-on:click="open = !open">
<MenuAlt4Icon className="w-6" />
</button>
<div
className={`
w-48 max-h-[calc(100vh-4rem)]
absolute right-0 top-[calc(100%+8px)]
bg-slate-800 shadow rounded-lg
overflow-hidden overflow-y-auto
transition-all
`}
x-bind:class="open ? 'visible opacity-100' : 'invisible opacity-0 translate-y-3'"
>
{children}
</div>
</div>
)
}
PopoverMenu.itemClass = clsx`
px-3 py-2 transition text-left font-medium block
opacity-50 hover:opacity-100 hover:bg-black/30
`

View File

@@ -1,133 +0,0 @@
/**
* Nord Theme Originally by Arctic Ice Studio
* https://nordtheme.com
*
* Ported for PrismJS by Zane Hitchcoxc (@zwhitchcox) and Gabriel Ramos (@gabrieluizramos)
*/
code[class*="language-"],
pre[class*="language-"] {
color: #f8f8f2;
background: none;
/* font-family: "Fira Code", Consolas, Monaco, "Andale Mono", "Ubuntu Mono",
monospace; */
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.7;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: 0.5em 0;
overflow: auto;
border-radius: 0.3em;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
/* background: #2e3440; */
background: rgba(0, 0, 0, 0.3);
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: 0.1em;
border-radius: 0.3em;
white-space: normal;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: #636f88;
}
.token.punctuation {
color: #81a1c1;
}
.namespace {
opacity: 0.7;
}
.token.property,
.token.tag,
.token.constant,
.token.symbol,
.token.deleted {
color: #81a1c1;
}
.token.number {
color: #b48ead;
}
.token.boolean {
color: #81a1c1;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #a3be8c;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string,
.token.variable {
color: #81a1c1;
}
.token.atrule,
.token.attr-value,
.token.function,
.token.class-name {
color: #88c0d0;
}
.token.keyword {
color: #81a1c1;
}
.token.regex,
.token.important {
color: #ebcb8b;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
.code-line.highlight-line {
background-color: rgba(255, 255, 255, 0.08);
padding: 0 1rem;
margin: 0 -1rem;
display: block;
}

View File

@@ -1,15 +0,0 @@
// @ts-nocheck
module.exports = {
content: ["./src/**/*.{ts,tsx,md}"],
theme: {
fontFamily: {
sans: ["Rubik", "sans-serif"],
monospace: ["'JetBrains Mono'", "monospace"],
},
boxShadow: {
DEFAULT: "0 2px 9px 0 rgb(0 0 0 / 0.3), 0 2px 4px -2px rgb(0 0 0 / 0.3)",
},
extend: {},
},
plugins: [require("@tailwindcss/typography")],
}

View File

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

View File

@@ -1,22 +0,0 @@
{
"entryPoints": ["../reacord/library/main.ts"],
"out": ["dist/api"],
"tsconfig": "../reacord/tsconfig.json",
"excludeInternal": true,
"excludePrivate": true,
"excludeProtected": true,
"categorizeByGroup": false,
"preserveWatchOutput": true,
"githubPages": false,
"readme": "none",
"categoryOrder": [
"Core",
"Embed",
"Button",
"Link",
"Select",
"Action Row",
"Component Event",
"*"
]
}

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

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

View File

@@ -0,0 +1,7 @@
/** For narrowing instance types with array.filter */
export const isInstanceOf =
<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

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

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 { toError } from "./to-error.js"
export function raise(error: unknown): never {
throw toError(error)
throw toError(error)
}

View File

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

View File

@@ -0,0 +1,21 @@
import { setTimeout } from "node:timers/promises"
const maxTime = 500
const waitPeriod = 50
export async function retryWithTimeout<T>(
callback: () => Promise<T> | T,
): Promise<T> {
const startTime = Date.now()
// eslint-disable-next-line no-constant-condition, @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

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

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
}

2
packages/reacord/.gitignore vendored Normal file
View File

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

View File

@@ -0,0 +1,85 @@
# reacord
## 0.6.0
### Minor Changes
- 11153df: breaking: more descriptive component event types
- fb0a997: add new descriptive adapter methods
The reacord instance names have been updated, and the old names are now deprecated.
- `send` -> `createChannelMessage`
- `reply` -> `createInteractionReply`
These new methods also accept discord JS options. Usage example:
```ts
// can accept either a channel object or a channel ID
reacord.createChannelMessage(channel)
reacord.createChannelMessage(channel, {
tts: true,
})
reacord.createChannelMessage(channel, {
reply: {
messageReference: "123456789012345678",
failIfNotExists: false,
},
})
reacord.createInteractionReply(interaction)
reacord.createInteractionReply(interaction, {
ephemeral: true,
})
```
These new methods replace the old ones, which are now deprecated.
## 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,37 +0,0 @@
import type {
CamelCasedPropertiesDeep,
SnakeCasedPropertiesDeep,
} from "type-fest"
import { camelCaseDeep, snakeCaseDeep } from "./convert-object-property-case"
test("camelCaseDeep", () => {
const input = {
some_prop: {
some_deep_prop: "some_deep_value",
},
someOtherProp: "someOtherValue",
}
expect(camelCaseDeep(input)).toEqual<CamelCasedPropertiesDeep<typeof input>>({
someProp: {
someDeepProp: "some_deep_value",
},
someOtherProp: "someOtherValue",
})
})
test("snakeCaseDeep", () => {
const input = {
someProp: {
someDeepProp: "someDeepValue",
},
some_other_prop: "someOtherValue",
}
expect(snakeCaseDeep(input)).toEqual<SnakeCasedPropertiesDeep<typeof input>>({
some_prop: {
some_deep_prop: "someDeepValue",
},
some_other_prop: "someOtherValue",
})
})

View File

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

View File

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

View File

@@ -1,83 +1,113 @@
import type { ReactNode } from "react"
import type { ReacordInstance } from "./instance"
/**
* @category Component Event
*/
export type ComponentEvent = {
message: MessageInfo
channel: ChannelInfo
user: UserInfo
guild?: GuildInfo
reply(content?: ReactNode): ReacordInstance
ephemeralReply(content?: ReactNode): ReacordInstance
/** @category Component Event */
export interface ComponentEvent {
/**
* 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: ComponentEventMessage
/**
* The channel that this event occurred in.
*
* @see https://discord.com/developers/docs/resources/channel#channel-object
*/
channel: ComponentEventChannel
/**
* The user that triggered this event.
*
* @see https://discord.com/developers/docs/resources/user#user-object
*/
user: ComponentEventUser
/**
* The guild that this event occurred in.
*
* @see https://discord.com/developers/docs/resources/guild#guild-object
*/
guild?: ComponentEventGuild
/** Create a new reply to this event. */
reply(
content?: ReactNode,
options?: ComponentEventReplyOptions,
): ReacordInstance
/**
* Create an ephemeral reply to this event, shown only to the user who
* triggered it.
*
* @deprecated Use event.reply(content, { ephemeral: true })
*/
ephemeralReply(content?: ReactNode): ReacordInstance
}
/**
* @category Component Event
*/
export type ChannelInfo = {
id: string
name?: string
topic?: string
nsfw?: boolean
lastMessageId?: string
ownerId?: string
parentId?: string
rateLimitPerUser?: number
/** @category Component Event */
export interface ComponentEventReplyOptions {
ephemeral?: boolean
tts?: boolean
}
/**
* @category Component Event
*/
export type MessageInfo = {
id: string
channelId: string
authorId: UserInfo
member?: GuildMemberInfo
content: string
timestamp: string
editedTimestamp?: string
tts: boolean
mentionEveryone: boolean
/** The IDs of mentioned users */
mentions: string[]
/** @category Component Event */
export interface ComponentEventChannel {
id: string
name?: string
topic?: string
nsfw?: boolean
lastMessageId?: string
ownerId?: string
parentId?: string
rateLimitPerUser?: number
}
/**
* @category Component Event
*/
export type GuildInfo = {
id: string
name: string
member: GuildMemberInfo
/** @category Component Event */
export interface ComponentEventMessage {
id: string
channelId: string
authorId: string
member?: ComponentEventGuildMember
content: string
timestamp: string
editedTimestamp?: string
tts: boolean
mentionEveryone: boolean
/** The IDs of mentioned users */
mentions: string[]
}
/**
* @category Component Event
*/
export type GuildMemberInfo = {
id: string
nick?: string
displayName: string
avatarUrl?: string
displayAvatarUrl: string
roles: string[]
color: number
joinedAt?: string
premiumSince?: string
pending?: boolean
communicationDisabledUntil?: string
/** @category Component Event */
export interface ComponentEventGuild {
id: string
name: string
member: ComponentEventGuildMember
}
/**
* @category Component Event
*/
export type UserInfo = {
id: string
username: string
discriminator: string
tag: string
avatarUrl: string
accentColor?: number
/** @category Component Event */
export interface ComponentEventGuildMember {
id: string
nick?: string
displayName: string
avatarUrl?: string
displayAvatarUrl: string
roles: string[]
color: number
joinedAt?: string
premiumSince?: string
pending?: boolean
communicationDisabledUntil?: string
}
/** @category Component Event */
export interface ComponentEventUser {
id: string
username: string
discriminator: string
tag: string
avatarUrl: string | null
accentColor?: number
}

View File

@@ -1,47 +1,56 @@
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 = {
children?: ReactNode
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
* @see https://discord.com/developers/docs/interactions/message-components#action-rows
*/
export function ActionRow(props: ActionRowProps) {
return (
<ReacordElement props={props} createNode={() => new ActionRowNode(props)}>
{props.children}
</ReacordElement>
)
return (
<ReacordElement props={props} createNode={() => new ActionRowNode(props)}>
{props.children}
</ReacordElement>
)
}
class ActionRowNode extends Node<{}> {
override modifyMessageOptions(options: MessageOptions): void {
options.actionRows.push([])
for (const child of this.children) {
child.modifyMessageOptions(options)
}
}
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

@@ -0,0 +1,24 @@
import type { ReactNode } from "react"
/**
* Common props between button-like components
*
* @category Button
*/
export interface ButtonSharedProps {
/** The text on the button. Rich formatting (markdown) is not supported here. */
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>`.
*
* 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,58 +1,69 @@
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"
import { getNextActionRow } from "../../internal/message"
import { Node } from "../../internal/node.js"
import type { ComponentEvent } from "../component-event"
import type { ButtonSharedProps } from "./button-shared-props"
/**
* @category Button
*/
export type ButtonProps = {
label?: string
style?: "primary" | "secondary" | "success" | "danger"
disabled?: boolean
emoji?: string
onClick: (event: ButtonClickEvent) => void
/** @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. */
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)} />
)
return (
<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()
override modifyMessageOptions(options: MessageOptions): void {
getNextActionRow(options).push({
type: "button",
customId: this.customId,
style: this.props.style ?? "secondary",
disabled: this.props.disabled,
emoji: this.props.emoji,
label: this.props.label,
})
}
// 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 handleComponentInteraction(interaction: ComponentInteraction) {
if (
interaction.type === "button" &&
interaction.customId === this.customId
) {
this.props.onClick(interaction.event)
return true
}
return false
}
override modifyMessageOptions(options: MessageOptions): void {
getNextActionRow(options).push({
type: "button",
customId: this.customId,
style: this.props.style ?? "secondary",
disabled: this.props.disabled,
emoji: this.props.emoji,
label: this.children.findType(ButtonLabelNode)?.text,
})
}
override handleComponentInteraction(interaction: ComponentInteraction) {
if (
interaction.type === "button" &&
interaction.customId === this.customId
) {
this.props.onClick(interaction.event)
return true
}
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
url?: string
iconUrl?: 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)}
/>
)
return (
<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 ?? "",
url: this.props.url,
icon_url: this.props.iconUrl,
}
}
override modifyEmbedOptions(options: EmbedOptions): void {
options.author = {
name: this.children.findType(AuthorTextNode)?.text ?? "",
url: this.props.url,
icon_url: this.props.iconUrl,
}
}
}
class AuthorTextNode extends Node<Record<string, never>> {}

View File

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

View File

@@ -1,37 +1,41 @@
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
inline?: boolean
children?: string
/** @category Embed */
export interface EmbedFieldProps {
name: ReactNode
value?: ReactNode
inline?: boolean
children?: ReactNode
}
/**
* @category Embed
*/
/** @category Embed */
export function EmbedField(props: EmbedFieldProps) {
return (
<ReacordElement
props={props}
createNode={() => new EmbedFieldNode(props)}
/>
)
return (
<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>
)
}
class EmbedFieldNode extends EmbedChildNode<EmbedFieldProps> {
override modifyEmbedOptions(options: EmbedOptions): void {
options.fields ??= []
options.fields.push({
name: this.props.name,
value: this.props.value ?? this.props.children ?? "",
inline: this.props.inline,
})
}
override modifyEmbedOptions(options: EmbedOptions): void {
options.fields ??= []
options.fields.push({
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>> {}

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