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

View File

@@ -1,40 +0,0 @@
{
"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 src/main.ts --clean --target node16 --format cjs,esm --dts --sourcemap"
},
"keywords": [],
"author": "itsMapleLeaf",
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/react": "*",
"@types/react-reconciler": "^0.26.4",
"immer": "^9.0.7",
"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.6",
"nanoid": "^3.1.30",
"reacord-helpers": "workspace:*",
"react": "^17.0.2",
"tsup": "^5.11.6"
}
}

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

@@ -1,109 +0,0 @@
/* eslint-disable unicorn/no-null */
import { inspect } from "node:util"
import { raise } from "reacord-helpers/raise.js"
import ReactReconciler from "react-reconciler"
import { BaseInstance } from "./base-instance.js"
import { ContainerInstance } from "./container-instance.js"
import type { ReacordContainer } from "./container.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"),
})

View File

@@ -1,25 +0,0 @@
/* 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()
},
}
}

View File

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

View File

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