Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New discord.js-react utility bridge library #44

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/discord.js/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/LICENSE
Empty file added packages/discord.js/README.md
Empty file.
1 change: 1 addition & 0 deletions packages/discord.js/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="@total-typescript/ts-reset" />
2 changes: 2 additions & 0 deletions packages/discord.js/library/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./use-message"
export * from "./use-reactions"
5 changes: 5 additions & 0 deletions packages/discord.js/library/use-message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { Message } from "discord.js";

export function useMessage(): Message {
return {} as Message;
}
Comment on lines +3 to +5
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To make this work, the DJS adapter could render its own context provider with whatever content the user passes:

// reacord-discord-js.tsx
export const MessageContext = createContext<Message | undefined>(undefined)

export class ReacordDiscordJs extends Reacord {
	// ...

	protected createInstance(renderer: Renderer): ReacordInstance {
		const { render, ...instance } = super.createInstance(renderer)
		return {
			...instance,
			render(content) {
				return render(
					// renderer.message needs to be public now
					<MessageContext.Provider value={renderer.message}>
						{content}
					</MessageContext.Provider>,
				)
			},
		}
	}

	// ...
}

Although 🤔 since this is a separate package, that means MessageContext has to become a public export of the library... not great.

I guess we could just mark it as @private in JSDoc, but the "real" solution would be to move ReacordDiscordJs to this new package, so it can use that context without having to export it publicly

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I was thinking about a similar solution, this is why I left it empty. I will investigate the problem further. Thank you for an example

50 changes: 50 additions & 0 deletions packages/discord.js/library/use-reactions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {
Collection,
type Message,
type MessageReaction,
type ReactionCollector,
} from "discord.js"
import { useEffect, useState } from "react"
import { useMessage } from "./use-message"

export interface UseReactionsOptions {
message?: Message
}

type Reactions = Collection<string, MessageReaction>

export function useReactions(options: UseReactionsOptions) {
// Hooks should not be called conditionally
domin-mnd marked this conversation as resolved.
Show resolved Hide resolved
const messageInstance = useMessage()
// Ref will persist the value across renders
const message = options.message ?? messageInstance
const [collector, setCollector] = useState<ReactionCollector | null>(null)
const [alive, setAlive] = useState<boolean>(true)

// Reactions collection
const [reactions, setReactions] = useState<Reactions>(
() => new Collection(),
)

useEffect(() => {
const collector = message.createReactionCollector({
dispose: true,
})

const update = () => {
setReactions(() => collector.collected)
}

setCollector(collector)
collector.on("collect", update)
collector.on("remove", update)
collector.on("end", () => {
update()
setAlive(false)
})

return () => collector.stop()
}, [message])

return { reactions, alive, collector }
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is exposing the collector useful here? That feels like an implementation detail that could change over time. If the use case is wanting to be able to control the behavior, I'd expose wrapped callbacks or additional options instead (like an active option)

I also don't see a use case for alive - I feel most usages of this hook only care about the current reactions

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The alive use case should've been an addition for watching the effect. Yes, I should definitely wrap callbacks. I will look into the implementation later once I solve the message context problem.

}
84 changes: 84 additions & 0 deletions packages/discord.js/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
{
"name": "@reacord/discord.js",
"type": "module",
"description": "Utility bridge between discord.js and react.",
"version": "0.0.1",
"homepage": "https://reacord.mapleleaf.dev",
"repository": "https://github.com/itsMapleLeaf/reacord.git",
"changelog": "https://github.com/itsMapleLeaf/reacord/releases",
"license": "MIT",
"keywords": [
"discord",
"discord-js",
"react",
"react-js",
"react-renderer",
"interaction",
"message",
"embed",
"reacord",
"bridge"
],
"files": [
"dist",
"README.md",
"LICENSE"
],
"types": "./dist/main.d.ts",
"exports": {
".": {
"import": "./dist/main.js",
"require": "./dist/main.cjs",
"types": "./dist/main.d.ts"
},
"./package.json": {
"import": "./package.json",
"require": "./package.json"
}
},
"scripts": {
"build": "cpy ../../LICENSE . && tsup library/main.ts --target node18 --format cjs,esm --sourcemap --dts --dts-resolve",
"build-watch": "pnpm build -- --watch",
"test": "vitest --coverage --no-watch",
"test-dev": "vitest",
"typecheck": "tsc -b"
},
"dependencies": {
"@types/node": "^20.8.4",
"@types/react": "^18.2.27",
"@types/react-reconciler": "^0.28.5",
"react-reconciler": "^0.29.0",
"rxjs": "^7.8.1"
},
"peerDependencies": {
"discord.js": "^14",
"reacord": ">=0.6.0",
"react": ">=17"
},
"devDependencies": {
"@reacord/helpers": "workspace:*",
"@types/lodash-es": "^4.17.9",
"c8": "^8.0.1",
"cpy-cli": "^5.0.0",
"discord.js": "^14.13.0",
"dotenv": "^16.3.1",
"lodash-es": "^4.17.21",
"nodemon": "^3.0.1",
"prettier": "^3.0.3",
"react": "^18.2.0",
"tsup": "^7.2.0",
"type-fest": "^4.4.0"
},
"release-it": {
"git": {
"commitMessage": "release v${version}"
},
"github": {
"release": true,
"web": true
}
},
"publishConfig": {
"access": "public"
}
}
7 changes: 7 additions & 0 deletions packages/discord.js/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "react-jsx"
},
"exclude": ["node_modules", "dist"]
}
59 changes: 56 additions & 3 deletions packages/reacord/scripts/discordjs-manual-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import {
Select,
useInstance,
} from "../library/main.js"
import type { TextChannel } from "discord.js"
import { ChannelType, Client, IntentsBitField } from "discord.js"
import type { CommandInteraction, TextChannel } from "discord.js"
import { ChannelType, Client, Events, IntentsBitField } from "discord.js"
import "dotenv/config"
import { kebabCase } from "lodash-es"
import { useState } from "react"
import { useEffect, useState } from "react"

const client = new Client({ intents: IntentsBitField.Flags.Guilds })
const reacord = new ReacordDiscordJs(client)
Expand Down Expand Up @@ -50,6 +50,29 @@ const createTest = async (
await block(channel)
}

const executables: Record<
string,
(interaction: CommandInteraction) => unknown
> = {}
const createInteractionTest = async (
name: string,
block: (interaction: CommandInteraction) => unknown,
) => {
const slashName = kebabCase(name)

await client.application?.commands.create({
name: slashName,
description: "Test command",
})
executables[slashName] = block
}

client.on(Events.InteractionCreate, (interaction) => {
if (interaction.isCommand()) {
executables[interaction.commandName]?.(interaction)
}
})

await createTest("basic", (channel) => {
reacord.createChannelMessage(channel).render("Hello, world!")
})
Expand Down Expand Up @@ -125,6 +148,36 @@ await createTest("counter", (channel) => {
reacord.createChannelMessage(channel).render(<Counter />)
})

await createInteractionTest("bounce counter", (interaction) => {
function Counter() {
const [count, setCount] = useState(0)

useEffect(() => {
// This will reply once the count is updated to track useEffect usage.
// Not creating instances.
void interaction.followUp(`Updated the count to ${count}`)
}, [count])

return (
<>
count: {count}
<Button
style="primary"
emoji="➕"
onClick={() => setCount(count + 1)}
/>
<Button
style="primary"
emoji="➖"
onClick={() => setCount(count - 1)}
/>
<Button label="reset" onClick={() => setCount(0)} />
</>
)
}
reacord.createInteractionReply(interaction).render(<Counter />)
})

await createTest("select", (channel) => {
function FruitSelect({ onConfirm }: { onConfirm: (choice: string) => void }) {
const [value, setValue] = useState<string>()
Expand Down
58 changes: 58 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading