monorepo
This commit is contained in:
14
packages/helpers/deferred.test.ts
Normal file
14
packages/helpers/deferred.test.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import test from "ava"
|
||||
import { createDeferred } from "./deferred.js"
|
||||
|
||||
test("resolve", async (t) => {
|
||||
const deferred = createDeferred<string>()
|
||||
setTimeout(() => deferred.resolve("hi"))
|
||||
t.is(await deferred, "hi")
|
||||
})
|
||||
|
||||
test("reject", async (t) => {
|
||||
const deferred = createDeferred()
|
||||
setTimeout(() => deferred.reject(new Error("oops")))
|
||||
await t.throwsAsync(() => deferred, { instanceOf: Error, message: "oops" })
|
||||
})
|
||||
21
packages/helpers/deferred.ts
Normal file
21
packages/helpers/deferred.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
// eslint-disable-next-line import/no-unused-modules
|
||||
export type Deferred<T> = PromiseLike<T> & {
|
||||
resolve: (value: T | PromiseLike<T>) => void
|
||||
reject: (reason?: unknown) => void
|
||||
}
|
||||
|
||||
export function createDeferred<T = void>(): Deferred<T> {
|
||||
let resolve: (value: T | PromiseLike<T>) => void
|
||||
let reject: (reason?: unknown) => void
|
||||
|
||||
const promise = new Promise<T>((_resolve, _reject) => {
|
||||
resolve = _resolve
|
||||
reject = _reject
|
||||
})
|
||||
|
||||
return {
|
||||
then: promise.then.bind(promise),
|
||||
resolve: (value) => resolve(value),
|
||||
reject: (reason) => reject(reason),
|
||||
}
|
||||
}
|
||||
7
packages/helpers/package.json
Normal file
7
packages/helpers/package.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "reacord-helpers",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"@types/node": "^16.11.14"
|
||||
}
|
||||
}
|
||||
5
packages/helpers/raise.ts
Normal file
5
packages/helpers/raise.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { toError } from "./to-error.js"
|
||||
|
||||
export function raise(error: unknown): never {
|
||||
throw toError(error)
|
||||
}
|
||||
10
packages/helpers/reject-after.ts
Normal file
10
packages/helpers/reject-after.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { setTimeout } from "node:timers/promises"
|
||||
import { toError } from "./to-error.js"
|
||||
|
||||
export async function rejectAfter(
|
||||
timeMs: number,
|
||||
error: unknown = `rejected after ${timeMs}ms`,
|
||||
): Promise<never> {
|
||||
await setTimeout(timeMs)
|
||||
return Promise.reject(toError(error))
|
||||
}
|
||||
3
packages/helpers/to-error.ts
Normal file
3
packages/helpers/to-error.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export function toError(value: unknown) {
|
||||
return value instanceof Error ? value : new Error(String(value))
|
||||
}
|
||||
3
packages/helpers/tsconfig.json
Normal file
3
packages/helpers/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json"
|
||||
}
|
||||
1
packages/helpers/types.ts
Normal file
1
packages/helpers/types.ts
Normal file
@@ -0,0 +1 @@
|
||||
export type MaybePromise<T> = T | Promise<T>
|
||||
11
packages/helpers/wait-for-with-timeout.ts
Normal file
11
packages/helpers/wait-for-with-timeout.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { rejectAfter } from "./reject-after.js"
|
||||
import type { MaybePromise } from "./types.js"
|
||||
import { waitFor } from "./wait-for.js"
|
||||
|
||||
export function waitForWithTimeout(
|
||||
condition: () => MaybePromise<boolean>,
|
||||
timeout = 1000,
|
||||
errorMessage = `timed out after ${timeout}ms`,
|
||||
) {
|
||||
return Promise.race([waitFor(condition), rejectAfter(timeout, errorMessage)])
|
||||
}
|
||||
8
packages/helpers/wait-for.ts
Normal file
8
packages/helpers/wait-for.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { setTimeout } from "node:timers/promises"
|
||||
import type { MaybePromise } from "./types.js"
|
||||
|
||||
export async function waitFor(condition: () => MaybePromise<boolean>) {
|
||||
while (!(await condition())) {
|
||||
await setTimeout(100)
|
||||
}
|
||||
}
|
||||
66
packages/integration-tests/package.json
Normal file
66
packages/integration-tests/package.json
Normal file
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"name": "reacord-integration-tests",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"lint": "eslint --ext js,ts,tsx .",
|
||||
"lint-fix": "pnpm lint -- --fix",
|
||||
"format": "prettier --write .",
|
||||
"test": "c8 ava",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@itsmapleleaf/configs": "^1.1.0",
|
||||
"@types/node": "*",
|
||||
"@types/react": "*",
|
||||
"@typescript-eslint/eslint-plugin": "^5.6.0",
|
||||
"@typescript-eslint/parser": "^5.6.0",
|
||||
"ava": "^4.0.0-rc.1",
|
||||
"c8": "^7.10.0",
|
||||
"discord.js": "^13.3.1",
|
||||
"dotenv": "^10.0.0",
|
||||
"esbuild": "^0.14.2",
|
||||
"esbuild-node-loader": "^0.6.3",
|
||||
"eslint": "^8.4.1",
|
||||
"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.27.1",
|
||||
"eslint-plugin-react-hooks": "^4.3.0",
|
||||
"eslint-plugin-unicorn": "^39.0.0",
|
||||
"nanoid": "^3.1.30",
|
||||
"prettier": "^2.5.1",
|
||||
"reacord": "workspace:*",
|
||||
"reacord-helpers": "workspace:*",
|
||||
"react": "^17.0.2",
|
||||
"typescript": "^4.5.4"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"./node_modules/@itsmapleleaf/configs/eslint"
|
||||
],
|
||||
"ignorePatterns": [
|
||||
"**/node_modules/**",
|
||||
"**/coverage/**",
|
||||
"**/.vscode/**"
|
||||
],
|
||||
"parserOptions": {
|
||||
"project": "./tsconfig.json"
|
||||
}
|
||||
},
|
||||
"prettier": "@itsmapleleaf/configs/prettier",
|
||||
"ava": {
|
||||
"files": [
|
||||
"**/*.test.{ts,tsx}"
|
||||
],
|
||||
"nodeArguments": [
|
||||
"--loader=esbuild-node-loader",
|
||||
"--experimental-specifier-resolution=node",
|
||||
"--no-warnings"
|
||||
],
|
||||
"extensions": {
|
||||
"ts": "module",
|
||||
"tsx": "module"
|
||||
}
|
||||
}
|
||||
}
|
||||
119
packages/integration-tests/tests/rendering.test.tsx
Normal file
119
packages/integration-tests/tests/rendering.test.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
import type { ExecutionContext } from "ava"
|
||||
import test from "ava"
|
||||
import { Client, TextChannel } from "discord.js"
|
||||
import { nanoid } from "nanoid"
|
||||
import { createRoot, Embed } from "reacord"
|
||||
import { raise } from "reacord-helpers/raise.js"
|
||||
import React, { useState } from "react"
|
||||
import { testBotToken, testChannelId } from "./test-environment.js"
|
||||
|
||||
const client = new Client({
|
||||
intents: ["GUILDS"],
|
||||
})
|
||||
|
||||
let channel: TextChannel
|
||||
|
||||
test.before(async () => {
|
||||
await client.login(testBotToken)
|
||||
|
||||
const result =
|
||||
client.channels.cache.get(testChannelId) ??
|
||||
(await client.channels.fetch(testChannelId)) ??
|
||||
raise("Channel not found")
|
||||
|
||||
if (!(result instanceof TextChannel)) {
|
||||
throw new TypeError("Channel must be a text channel")
|
||||
}
|
||||
|
||||
channel = result
|
||||
})
|
||||
|
||||
test.after(() => {
|
||||
client.destroy()
|
||||
})
|
||||
|
||||
test.only("test", async (t) => {
|
||||
const root = createRoot(channel)
|
||||
await root.render(
|
||||
<>
|
||||
<Embed color="BLUE">
|
||||
<Embed color="DARKER_GREY" />
|
||||
</Embed>
|
||||
<Embed color="DARKER_GREY" />
|
||||
</>,
|
||||
)
|
||||
t.pass()
|
||||
})
|
||||
|
||||
test("kitchen sink", async (t) => {
|
||||
const root = createRoot(channel)
|
||||
|
||||
const content = nanoid()
|
||||
await root.render(content)
|
||||
|
||||
await assertSomeMessageHasContent(t, content)
|
||||
|
||||
const newContent = nanoid()
|
||||
await root.render(newContent)
|
||||
|
||||
await assertSomeMessageHasContent(t, newContent)
|
||||
|
||||
await root.render(false)
|
||||
|
||||
await assertNoMessageHasContent(t, newContent)
|
||||
})
|
||||
|
||||
test("kitchen sink, rapid updates", async (t) => {
|
||||
const root = createRoot(channel)
|
||||
|
||||
const content = nanoid()
|
||||
const newContent = nanoid()
|
||||
|
||||
void root.render(content)
|
||||
await root.render(newContent)
|
||||
|
||||
await assertSomeMessageHasContent(t, newContent)
|
||||
|
||||
void root.render(content)
|
||||
await root.render(false)
|
||||
|
||||
await assertNoMessageHasContent(t, newContent)
|
||||
})
|
||||
|
||||
test("state", async (t) => {
|
||||
let setMessage: (message: string) => void
|
||||
|
||||
const initialMessage = nanoid()
|
||||
const newMessage = nanoid()
|
||||
|
||||
function Counter() {
|
||||
const [message, setMessage_] = useState(initialMessage)
|
||||
setMessage = setMessage_
|
||||
return `state: ${message}` as any
|
||||
}
|
||||
|
||||
const root = createRoot(channel)
|
||||
await root.render(<Counter />)
|
||||
|
||||
await assertSomeMessageHasContent(t, initialMessage)
|
||||
|
||||
setMessage!(newMessage)
|
||||
await root.completion()
|
||||
|
||||
await assertSomeMessageHasContent(t, newMessage)
|
||||
|
||||
await root.destroy()
|
||||
})
|
||||
|
||||
async function assertSomeMessageHasContent(
|
||||
t: ExecutionContext,
|
||||
content: string,
|
||||
) {
|
||||
const messages = await channel.messages.fetch()
|
||||
t.true(messages.some((m) => m.content.includes(content)))
|
||||
}
|
||||
|
||||
async function assertNoMessageHasContent(t: ExecutionContext, content: string) {
|
||||
const messages = await channel.messages.fetch()
|
||||
t.true(messages.every((m) => !m.content.includes(content)))
|
||||
}
|
||||
10
packages/integration-tests/tests/test-environment.ts
Normal file
10
packages/integration-tests/tests/test-environment.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import "dotenv/config.js"
|
||||
import { raise } from "reacord-helpers/raise.js"
|
||||
|
||||
function getEnvironmentValue(name: string) {
|
||||
return process.env[name] ?? raise(`Missing environment variable: ${name}`)
|
||||
}
|
||||
|
||||
export const testBotToken = getEnvironmentValue("TEST_BOT_TOKEN")
|
||||
// export const testGuildId = getEnvironmentValue("TEST_GUILD_ID")
|
||||
export const testChannelId = getEnvironmentValue("TEST_CHANNEL_ID")
|
||||
3
packages/integration-tests/tsconfig.json
Normal file
3
packages/integration-tests/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json"
|
||||
}
|
||||
39
packages/reacord/package.json
Normal file
39
packages/reacord/package.json
Normal file
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "reacord",
|
||||
"type": "module",
|
||||
"description": "send reactive discord messages using react components ⚛",
|
||||
"version": "0.0.0",
|
||||
"types": "./dist/main.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"exports": {
|
||||
"import": "./dist/main.js",
|
||||
"require": "./dist/main.cjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsup-node src/main.ts --clean --target node16 --format cjs,esm --dts"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "itsMapleLeaf",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*",
|
||||
"@types/react": "*",
|
||||
"@types/react-reconciler": "^0.26.4",
|
||||
"react-reconciler": "^0.26.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"discord.js": "^13.3",
|
||||
"react": "^17.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"discord.js": "^13.3.1",
|
||||
"dotenv": "^10.0.0",
|
||||
"esbuild": "^0.14.2",
|
||||
"nanoid": "^3.1.30",
|
||||
"reacord-helpers": "workspace:*",
|
||||
"react": "^17.0.2",
|
||||
"tsup": "^5.10.3"
|
||||
}
|
||||
}
|
||||
19
packages/reacord/src/components/embed.tsx
Normal file
19
packages/reacord/src/components/embed.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { ColorResolvable } from "discord.js"
|
||||
import type { ReactNode } from "react"
|
||||
import * as React from "react"
|
||||
|
||||
export type EmbedProps = {
|
||||
color?: ColorResolvable
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
export function Embed(props: EmbedProps) {
|
||||
return (
|
||||
<reacord-element
|
||||
modifyOptions={(options) => {
|
||||
options.embeds ??= []
|
||||
options.embeds.push({ color: props.color })
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
79
packages/reacord/src/container.ts
Normal file
79
packages/reacord/src/container.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import type { Message, MessageOptions, TextBasedChannels } from "discord.js"
|
||||
import type { ReacordElement } from "./element.js"
|
||||
|
||||
type Action =
|
||||
| { type: "updateMessage"; options: MessageOptions }
|
||||
| { type: "deleteMessage" }
|
||||
|
||||
export class ReacordContainer {
|
||||
private channel: TextBasedChannels
|
||||
private message?: Message
|
||||
private actions: Action[] = []
|
||||
private runningPromise?: Promise<void>
|
||||
|
||||
constructor(channel: TextBasedChannels) {
|
||||
this.channel = channel
|
||||
}
|
||||
|
||||
render(instances: ReacordElement[]) {
|
||||
const messageOptions: MessageOptions = {
|
||||
content: instances.join("") || undefined, // empty strings are not allowed
|
||||
}
|
||||
|
||||
const hasContent = messageOptions.content !== undefined
|
||||
|
||||
this.addAction(
|
||||
hasContent
|
||||
? { type: "updateMessage", options: messageOptions }
|
||||
: { type: "deleteMessage" },
|
||||
)
|
||||
}
|
||||
|
||||
completion() {
|
||||
return this.runningPromise ?? Promise.resolve()
|
||||
}
|
||||
|
||||
private addAction(action: Action) {
|
||||
const lastAction = this.actions[this.actions.length - 1]
|
||||
if (lastAction?.type === action.type) {
|
||||
this.actions[this.actions.length - 1] = action
|
||||
} else {
|
||||
this.actions.push(action)
|
||||
}
|
||||
this.runActions()
|
||||
}
|
||||
|
||||
private runActions() {
|
||||
if (this.runningPromise) return
|
||||
|
||||
this.runningPromise = new Promise((resolve) => {
|
||||
// using a microtask to allow multiple actions to be added synchronously
|
||||
queueMicrotask(async () => {
|
||||
let action: Action | undefined
|
||||
while ((action = this.actions.shift())) {
|
||||
try {
|
||||
await this.runAction(action)
|
||||
} catch (error) {
|
||||
console.error(`Failed to run action:`, action)
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
resolve()
|
||||
this.runningPromise = undefined
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
private async runAction(action: Action) {
|
||||
if (action.type === "updateMessage") {
|
||||
this.message = await (this.message
|
||||
? this.message.edit(action.options)
|
||||
: this.channel.send(action.options))
|
||||
}
|
||||
|
||||
if (action.type === "deleteMessage") {
|
||||
await this.message?.delete()
|
||||
this.message = undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
15
packages/reacord/src/element.ts
Normal file
15
packages/reacord/src/element.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { MessageOptions } from "discord.js"
|
||||
|
||||
export type ReacordElementJsxTag = "reacord-element"
|
||||
|
||||
export type ReacordElement = {
|
||||
modifyOptions: (options: MessageOptions) => void
|
||||
}
|
||||
|
||||
declare global {
|
||||
namespace JSX {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
||||
interface IntrinsicElements
|
||||
extends Record<ReacordElementJsxTag, ReacordElement> {}
|
||||
}
|
||||
}
|
||||
25
packages/reacord/src/instance.ts
Normal file
25
packages/reacord/src/instance.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import type { Message, TextBasedChannels } from "discord.js"
|
||||
|
||||
export class ReacordInstance {
|
||||
message?: Message
|
||||
content: string
|
||||
|
||||
constructor(content: string) {
|
||||
this.content = content
|
||||
}
|
||||
|
||||
render(channel: TextBasedChannels) {
|
||||
if (this.message) {
|
||||
this.message.edit(this.content).catch(console.error)
|
||||
} else {
|
||||
channel.send(this.content).then((message) => {
|
||||
this.message = message
|
||||
}, console.error)
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.message?.delete().catch(console.error)
|
||||
this.message?.channel.messages.cache.delete(this.message?.id)
|
||||
}
|
||||
}
|
||||
2
packages/reacord/src/main.ts
Normal file
2
packages/reacord/src/main.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./components/embed.js"
|
||||
export * from "./root.js"
|
||||
94
packages/reacord/src/reconciler.ts
Normal file
94
packages/reacord/src/reconciler.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
/* eslint-disable unicorn/no-null */
|
||||
import { raise } from "reacord-helpers/raise.js"
|
||||
import ReactReconciler from "react-reconciler"
|
||||
import type { ReacordContainer } from "./container.js"
|
||||
import type { ReacordElement, ReacordElementJsxTag } from "./element.js"
|
||||
|
||||
export const reconciler = ReactReconciler<
|
||||
ReacordElementJsxTag,
|
||||
ReacordElement,
|
||||
ReacordContainer,
|
||||
ReacordElement,
|
||||
string,
|
||||
unknown,
|
||||
unknown,
|
||||
unknown,
|
||||
unknown,
|
||||
unknown,
|
||||
unknown,
|
||||
unknown,
|
||||
unknown
|
||||
>({
|
||||
now: Date.now,
|
||||
isPrimaryRenderer: true,
|
||||
supportsMutation: false,
|
||||
supportsPersistence: true,
|
||||
supportsHydration: false,
|
||||
scheduleTimeout: setTimeout,
|
||||
cancelTimeout: clearTimeout,
|
||||
noTimeout: -1,
|
||||
|
||||
getRootHostContext: () => ({}),
|
||||
getChildHostContext: () => ({}),
|
||||
shouldSetTextContent: () => false,
|
||||
|
||||
createInstance: (
|
||||
type,
|
||||
props,
|
||||
rootContainerInstance,
|
||||
hostContext,
|
||||
internalInstanceHandle,
|
||||
) => {
|
||||
return props
|
||||
},
|
||||
|
||||
createTextInstance: (
|
||||
text,
|
||||
rootContainerInstance,
|
||||
hostContext,
|
||||
internalInstanceHandle,
|
||||
) => {
|
||||
return text
|
||||
},
|
||||
|
||||
prepareForCommit: () => null,
|
||||
resetAfterCommit: () => null,
|
||||
|
||||
appendInitialChild: (parent, child) => raise("Not implemented"),
|
||||
finalizeInitialChildren: (...args) => {
|
||||
console.log("finalizeInitialChildren", args)
|
||||
return false
|
||||
},
|
||||
getPublicInstance: () => raise("Not implemented"),
|
||||
prepareUpdate: () => raise("Not implemented"),
|
||||
preparePortalMount: () => raise("Not implemented"),
|
||||
|
||||
createContainerChildSet: (): ReacordElement[] => {
|
||||
// console.log("createContainerChildSet", [container])
|
||||
return []
|
||||
},
|
||||
|
||||
appendChildToContainerChildSet: (
|
||||
children: ReacordElement[],
|
||||
child: ReacordElement,
|
||||
) => {
|
||||
// console.log("appendChildToContainerChildSet", [children, child])
|
||||
children.push(child)
|
||||
},
|
||||
|
||||
finalizeContainerChildren: (
|
||||
container: ReacordContainer,
|
||||
children: ReacordElement[],
|
||||
) => {
|
||||
// console.log("finalizeContainerChildren", [container, children])
|
||||
return false
|
||||
},
|
||||
|
||||
replaceContainerChildren: (
|
||||
container: ReacordContainer,
|
||||
children: ReacordElement[],
|
||||
) => {
|
||||
console.log("replaceContainerChildren", [container, children])
|
||||
container.render(children)
|
||||
},
|
||||
})
|
||||
23
packages/reacord/src/root.ts
Normal file
23
packages/reacord/src/root.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
/* eslint-disable unicorn/no-null */
|
||||
import type { TextBasedChannels } from "discord.js"
|
||||
import type { ReactNode } from "react"
|
||||
import { ReacordContainer } from "./container"
|
||||
import { reconciler } from "./reconciler"
|
||||
|
||||
export type ReacordRenderTarget = TextBasedChannels
|
||||
|
||||
export function createRoot(target: ReacordRenderTarget) {
|
||||
const container = new ReacordContainer(target)
|
||||
const containerId = reconciler.createContainer(container, 0, false, null)
|
||||
return {
|
||||
render: (content: ReactNode) => {
|
||||
reconciler.updateContainer(content, containerId)
|
||||
return container.completion()
|
||||
},
|
||||
destroy: () => {
|
||||
reconciler.updateContainer(null, containerId)
|
||||
return container.completion()
|
||||
},
|
||||
completion: () => container.completion(),
|
||||
}
|
||||
}
|
||||
3
packages/reacord/tsconfig.json
Normal file
3
packages/reacord/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json"
|
||||
}
|
||||
Reference in New Issue
Block a user