monorepon't

This commit is contained in:
MapleLeaf
2021-12-20 20:18:18 -06:00
parent 628c4b23d7
commit e2ea46a18f
32 changed files with 66 additions and 91 deletions

17
src/base-instance.ts Normal file
View File

@@ -0,0 +1,17 @@
import type { MessageEmbedOptions, MessageOptions } from "discord.js"
export abstract class BaseInstance {
/** The name of the JSX element represented by this instance */
abstract readonly name: string
/** If the element represents text, the text for this element */
getText?(): string
/** If this element can be a child of a message,
* the function to modify the message options */
renderToMessage?(options: MessageOptions): void
/** If this element can be a child of an embed,
* the function to modify the embed options */
renderToEmbed?(options: MessageEmbedOptions): void
}

40
src/container-instance.ts Normal file
View File

@@ -0,0 +1,40 @@
import { BaseInstance } from "./base-instance.js"
// eslint-disable-next-line import/no-unused-modules
export type ContainerInstanceOptions = {
/**
* Whether or not to log a warning when calling getChildrenText() with non-text children
*
* Regardless of what this is set to, non-text children will always be skipped */
warnOnNonTextChildren: boolean
}
export abstract class ContainerInstance extends BaseInstance {
readonly children: BaseInstance[] = []
constructor(private readonly options: ContainerInstanceOptions) {
super()
}
add(child: BaseInstance) {
this.children.push(child)
}
clear() {
this.children.splice(0)
}
protected getChildrenText(): string {
let text = ""
for (const child of this.children) {
if (!child.getText) {
if (this.options.warnOnNonTextChildren) {
console.warn(`${child.name} is not a valid child of ${this.name}`)
}
continue
}
text += child.getText()
}
return text
}
}

94
src/container.ts Normal file
View File

@@ -0,0 +1,94 @@
import type { Message, MessageOptions, TextBasedChannels } from "discord.js"
import type { BaseInstance } from "./base-instance.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(children: BaseInstance[]) {
const options: MessageOptions = {}
for (const child of children) {
if (!child.renderToMessage) {
console.warn(`${child.name} is not a valid message child`)
continue
}
child.renderToMessage(options)
}
// can't render an empty message
if (!options?.content && !options.embeds?.length) {
options.content = "_ _"
}
this.addAction({ type: "updateMessage", options })
}
destroy() {
this.actions = []
this.addAction({ 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,
// need to ensure that, if there's no text, it's erased
// eslint-disable-next-line unicorn/no-null
content: action.options.content ?? null,
})
: this.channel.send(action.options))
}
if (action.type === "deleteMessage") {
await this.message?.delete()
this.message = undefined
}
}
}

80
src/embed.tsx Normal file
View File

@@ -0,0 +1,80 @@
import type {
ColorResolvable,
MessageEmbedOptions,
MessageOptions,
} from "discord.js"
import type { ReactNode } from "react"
import React from "react"
import { ContainerInstance } from "./container-instance.js"
export type EmbedProps = {
title?: string
color?: ColorResolvable
url?: string
timestamp?: Date | number | string
thumbnailUrl?: string
author?: {
name?: string
url?: string
iconUrl?: string
}
footer?: {
text?: string
iconUrl?: string
}
children?: ReactNode
}
export function Embed(props: EmbedProps) {
return (
<reacord-element createInstance={() => new EmbedInstance(props)}>
{props.children}
</reacord-element>
)
}
class EmbedInstance extends ContainerInstance {
readonly name = "Embed"
constructor(readonly props: EmbedProps) {
super({ warnOnNonTextChildren: false })
}
override renderToMessage(message: MessageOptions) {
message.embeds ??= []
message.embeds.push(this.getEmbedOptions())
}
getEmbedOptions(): MessageEmbedOptions {
const options: MessageEmbedOptions = {
...this.props,
author: {
...this.props.author,
iconURL: this.props.author?.iconUrl,
},
footer: {
text: "",
...this.props.footer,
iconURL: this.props.footer?.iconUrl,
},
timestamp: this.props.timestamp
? new Date(this.props.timestamp) // this _may_ need date-fns to parse this
: undefined,
}
for (const child of this.children) {
if (!child.renderToEmbed) {
console.warn(`${child.name} is not a valid child of ${this.name}`)
continue
}
child.renderToEmbed(options)
}
// can't render an empty embed
if (!options.description) {
options.description = "_ _"
}
return options
}
}

View File

@@ -0,0 +1,16 @@
import { expect, test } from "vitest"
import { createDeferred } from "./deferred.js"
test("resolve", async () => {
const deferred = createDeferred<string>()
setTimeout(() => deferred.resolve("hi"))
expect(await deferred).toBe("hi")
})
test("reject", async () => {
const deferred = createDeferred()
const error = new Error("oops")
setTimeout(() => deferred.reject(error))
const caught = await Promise.resolve(deferred).catch((error) => error)
expect(caught).toBe(error)
})

21
src/helpers/deferred.ts Normal file
View 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),
}
}

13
src/helpers/pick.ts Normal file
View File

@@ -0,0 +1,13 @@
export function pick<T, K extends keyof T>(
object: T,
...keys: K[]
): Pick<T, K> {
const result: any = {}
for (const key of keys) {
const value = object[key]
if (value !== undefined) {
result[key] = value
}
}
return result
}

5
src/helpers/raise.ts Normal file
View File

@@ -0,0 +1,5 @@
import { toError } from "./to-error.js"
export function raise(error: unknown): never {
throw toError(error)
}

View 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
src/helpers/to-error.ts Normal file
View File

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

5
src/helpers/types.ts Normal file
View File

@@ -0,0 +1,5 @@
export type MaybePromise<T> = T | Promise<T>
export type ValueOf<Type> = Type extends ReadonlyArray<infer Value>
? Value
: Type[keyof Type]

View 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
src/helpers/wait-for.ts Normal file
View 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)
}
}

View File

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

11
src/jsx.d.ts vendored Normal file
View File

@@ -0,0 +1,11 @@
declare namespace JSX {
import type { ReactNode } from "react"
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
interface IntrinsicElements {
"reacord-element": {
createInstance: () => unknown
children?: ReactNode
}
}
}

3
src/main.ts Normal file
View File

@@ -0,0 +1,3 @@
export * from "./embed"
export * from "./root"
export * from "./text"

109
src/reconciler.ts Normal file
View File

@@ -0,0 +1,109 @@
/* eslint-disable unicorn/no-null */
import { inspect } from "node:util"
import ReactReconciler from "react-reconciler"
import { BaseInstance } from "./base-instance.js"
import { ContainerInstance } from "./container-instance.js"
import type { ReacordContainer } from "./container.js"
import { raise } from "./helpers/raise.js"
import { TextInstance } from "./text-instance.js"
type ElementTag = string
type Props = Record<string, unknown>
const createInstance = (type: string, props: Props): BaseInstance => {
if (type !== "reacord-element") {
raise(`createInstance: unknown type: ${type}`)
}
if (typeof props.createInstance !== "function") {
const actual = inspect(props.createInstance)
raise(`invalid createInstance function, received: ${actual}`)
}
const instance = props.createInstance()
if (!(instance instanceof BaseInstance)) {
raise(`invalid instance: ${inspect(instance)}`)
}
return instance
}
export const reconciler = ReactReconciler<
string, // Type (jsx tag),
Props, // Props,
ReacordContainer, // Container,
BaseInstance, // Instance,
TextInstance, // TextInstance,
never, // SuspenseInstance,
never, // HydratableInstance,
never, // PublicInstance,
null, // HostContext,
never, // UpdatePayload,
BaseInstance[], // ChildSet,
unknown, // TimeoutHandle,
unknown // NoTimeout
>({
now: Date.now,
isPrimaryRenderer: true,
supportsMutation: false,
supportsPersistence: true,
supportsHydration: false,
scheduleTimeout: setTimeout,
cancelTimeout: clearTimeout,
noTimeout: -1,
getRootHostContext: () => null,
getChildHostContext: (parentContext) => parentContext,
shouldSetTextContent: () => false,
createInstance,
createTextInstance: (text) => new TextInstance(text),
createContainerChildSet: () => [],
appendChildToContainerChildSet: (
childSet: BaseInstance[],
child: BaseInstance,
) => {
childSet.push(child)
},
finalizeContainerChildren: (
container: ReacordContainer,
children: BaseInstance[],
) => false,
replaceContainerChildren: (
container: ReacordContainer,
children: BaseInstance[],
) => {
container.render(children)
},
appendInitialChild: (parent, child) => {
if (parent instanceof ContainerInstance) {
parent.add(child)
} else {
raise(
`Cannot append child of type ${child.constructor.name} to ${parent.constructor.name}`,
)
}
},
cloneInstance: (
instance: BaseInstance,
_: unknown,
type: ElementTag,
oldProps: Props,
newProps: Props,
) => createInstance(type, newProps),
finalizeInitialChildren: () => false,
prepareForCommit: (container) => null,
resetAfterCommit: () => null,
prepareUpdate: () => null,
getPublicInstance: () => raise("Not implemented"),
preparePortalMount: () => raise("Not implemented"),
})

176
src/rendering.test.tsx Normal file
View File

@@ -0,0 +1,176 @@
/* eslint-disable unicorn/no-null */
import type { Message } from "discord.js"
import { Client, TextChannel } from "discord.js"
import { deepEqual } from "node:assert"
import React from "react"
import { afterAll, beforeAll, test } from "vitest"
import { pick } from "./helpers/pick.js"
import { raise } from "./helpers/raise.js"
import type { ReacordRoot } from "./main"
import { createRoot, Embed, Text } from "./main"
import { testBotToken, testChannelId } from "./test-environment.js"
const client = new Client({
intents: ["GUILDS"],
})
let channel: TextChannel
let root: ReacordRoot
beforeAll(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
for (const [, message] of await channel.messages.fetch()) {
await message.delete()
}
root = createRoot(channel)
})
afterAll(() => {
client.destroy()
})
test("rapid updates", async () => {
// rapid updates
void root.render("hi world")
void root.render("hi the")
await root.render("hi moon")
await assertMessages([{ content: "hi moon" }])
})
test("nested text", async () => {
await root.render(
<Text>
<Text>hi world</Text>{" "}
<Text>
hi moon <Text>hi sun</Text>
</Text>
</Text>,
)
await assertMessages([{ content: "hi world hi moon hi sun" }])
})
test.only("empty embed fallback", async () => {
await root.render(<Embed />)
await assertMessages([{ embeds: [{ description: "_ _" }] }])
})
test.only("embed with only author", async () => {
await root.render(<Embed author={{ name: "only author" }} />)
await assertMessages([
{ embeds: [{ description: "_ _", author: { name: "only author" } }] },
])
})
test("empty embed author", async () => {
await root.render(<Embed author={{}} />)
await assertMessages([{ embeds: [{ description: "_ _" }] }])
})
test("kitchen sink", async () => {
await root.render(
<>
message <Text>content</Text>
no space
<Embed
color="#feeeef"
title="the embed"
url="https://example.com"
timestamp={new Date().toISOString()}
thumbnailUrl="https://cdn.discordapp.com/avatars/109677308410875904/3e53fcb70760a08fa63f73376ede5d1f.png?size=1024"
author={{
name: "hi craw",
url: "https://example.com",
iconUrl:
"https://cdn.discordapp.com/avatars/109677308410875904/3e53fcb70760a08fa63f73376ede5d1f.png?size=1024",
}}
footer={{
text: "the footer",
iconUrl:
"https://cdn.discordapp.com/avatars/109677308410875904/3e53fcb70760a08fa63f73376ede5d1f.png?size=1024",
}}
>
description <Text>more description</Text>
</Embed>
<Embed>
another <Text>hi</Text>
</Embed>
</>,
)
await assertMessages([
{
content: "message contentno space",
embeds: [
{
color: 0xfe_ee_ef,
description: "description more description",
author: {
name: "hi craw",
url: "https://example.com",
iconURL:
"https://cdn.discordapp.com/avatars/109677308410875904/3e53fcb70760a08fa63f73376ede5d1f.png?size=1024",
},
},
{ author: {}, color: null, description: "another hi" },
],
},
])
})
test("destroy", async () => {
await root.destroy()
await assertMessages([])
})
type MessageData = ReturnType<typeof extractMessageData>
function extractMessageData(message: Message) {
return {
content: message.content,
embeds: message.embeds.map((embed) => ({
...pick(embed, "color", "description"),
author: embed.author
? pick(embed.author, "name", "url", "iconURL")
: { name: "" },
})),
}
}
async function assertMessages(expected: Array<DeepPartial<MessageData>>) {
const messages = await channel.messages.fetch()
deepEqual(
messages.map((message) => extractMessageData(message)),
expected.map((message) => ({
content: "",
...message,
embeds:
message.embeds?.map((embed) => ({
color: null,
description: "",
...embed,
author: {
name: "",
...embed?.author,
},
})) ?? [],
})),
)
}
type DeepPartial<Subject> = Subject extends object
? {
[Key in keyof Subject]?: DeepPartial<Subject[Key]>
}
: Subject

25
src/root.ts Normal file
View File

@@ -0,0 +1,25 @@
/* 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 type ReacordRoot = ReturnType<typeof createRoot>
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)
container.destroy()
return container.completion()
},
}
}

10
src/test-environment.ts Normal file
View File

@@ -0,0 +1,10 @@
import "dotenv/config.js"
import { raise } from "./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")

23
src/text-instance.ts Normal file
View File

@@ -0,0 +1,23 @@
import type { MessageEmbedOptions, MessageOptions } from "discord.js"
import { BaseInstance } from "./base-instance.js"
/** Represents raw strings in JSX */
export class TextInstance extends BaseInstance {
readonly name = "Text"
constructor(private readonly text: string) {
super()
}
override getText() {
return this.text
}
override renderToMessage(options: MessageOptions) {
options.content = (options.content ?? "") + this.getText()
}
override renderToEmbed(options: MessageEmbedOptions) {
options.description = (options.description ?? "") + this.getText()
}
}

36
src/text.tsx Normal file
View File

@@ -0,0 +1,36 @@
import type { MessageEmbedOptions, MessageOptions } from "discord.js"
import type { ReactNode } from "react"
import React from "react"
import { ContainerInstance } from "./container-instance.js"
export type TextProps = {
children?: ReactNode
}
export function Text(props: TextProps) {
return (
<reacord-element createInstance={() => new TextElementInstance()}>
{props.children}
</reacord-element>
)
}
class TextElementInstance extends ContainerInstance {
readonly name = "Text"
constructor() {
super({ warnOnNonTextChildren: true })
}
override getText() {
return this.getChildrenText()
}
override renderToMessage(options: MessageOptions) {
options.content = (options.content ?? "") + this.getText()
}
override renderToEmbed(options: MessageEmbedOptions) {
options.description = (options.description ?? "") + this.getText()
}
}