1 Commits

Author SHA1 Message Date
itsMapleLeaf
12ec45ccd4 first attempt at files api 2022-04-25 14:52:29 -05:00
24 changed files with 1117 additions and 1381 deletions

View File

@@ -19,15 +19,15 @@ jobs:
# if these run in the same process, it dies,
# so we test them separate
- name: test reacord
run: pnpm -C packages/reacord test
run: pnpm test -C packages/reacord
- name: test website
run: pnpm -C packages/website test
run: pnpm test -C packages/website
- name: build
run: pnpm --recursive run build
run: pnpm build --recursive
- name: lint
run: pnpm run lint
run: pnpm lint
- name: typecheck
run: pnpm --recursive run typecheck
run: pnpm typecheck --parallel
name: ${{ matrix.command.name }}
runs-on: ubuntu-latest
steps:
@@ -36,6 +36,6 @@ jobs:
with:
# https://github.com/actions/setup-node#supported-version-syntax
node-version: "16"
- run: npm i -g pnpm@7.5.0
- run: npm i -g pnpm
- run: pnpm install --frozen-lockfile
- run: ${{ matrix.command.run }}

1
.gitignore vendored
View File

@@ -4,7 +4,6 @@ node_modules
coverage
.env
*.code-workspace
.pnpm-debug.log
build
.cache

15
Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
FROM node:lts-slim
ENV CYPRESS_INSTALL_BINARY=0
WORKDIR /app
COPY / ./
RUN ls -R
RUN npm install -g pnpm
RUN pnpm install --unsafe-perm --frozen-lockfile
RUN pnpm run build -C packages/website
ENV NODE_ENV=production
CMD [ "pnpm", "-C", "packages/website", "start" ]

View File

@@ -3,10 +3,7 @@
"scripts": {
"lint": "eslint --ext js,ts,tsx .",
"lint-fix": "pnpm lint -- --fix",
"format": "prettier --write .",
"release": "pnpm -C packages/reacord run release",
"build": "pnpm -C packages/website run build",
"start": "pnpm -C packages/website run start"
"format": "prettier --write ."
},
"devDependencies": {
"@itsmapleleaf/configs": "^1.1.3",
@@ -14,8 +11,7 @@
"@types/eslint": "^8.4.1",
"eslint": "^8.14.0",
"prettier": "^2.6.2",
"typescript": "^4.6.3",
"node": "^16"
"typescript": "^4.6.3"
},
"resolutions": {
"esbuild": "latest"

View File

@@ -1,6 +1,5 @@
import { expect, test } from "vitest"
import type { PruneNullishValues } from "./prune-nullish-values"
import { pruneNullishValues } from "./prune-nullish-values"
import { PruneNullishValues, pruneNullishValues } from "./prune-nullish-values"
test("pruneNullishValues", () => {
type InputType = {
@@ -15,7 +14,6 @@ test("pruneNullishValues", () => {
const input: InputType = {
a: "a",
// eslint-disable-next-line unicorn/no-null
b: null,
c: undefined,
d: {

View File

@@ -1,3 +1,4 @@
/* eslint-disable import/no-unused-modules */
export type MaybePromise<T> = T | Promise<T>
export type ValueOf<Type> = Type extends ReadonlyArray<infer Value>

View File

@@ -1,4 +1,4 @@
import { setTimeout } from "node:timers/promises"
import { setTimeout } from "timers/promises"
const maxTime = 1000

View File

@@ -0,0 +1,7 @@
import { Readable } from "node:stream"
export type ReacordFile = {
name?: string
description?: string
data: Buffer | Readable | string
}

View File

@@ -1,4 +1,5 @@
import type { ReactNode } from "react"
import { ReacordFile } from "./file"
/**
* Represents an interactive message, which can later be replaced or deleted.
@@ -16,4 +17,7 @@ export type ReacordInstance = {
* This prevents it from listening to user interactions.
*/
deactivate: () => void
/** Attach a file to the message for this instance */
attach: (file: ReacordFile) => void
}

View File

@@ -5,12 +5,9 @@ import type { Except } from "type-fest"
import { pick } from "../../helpers/pick"
import { pruneNullishValues } from "../../helpers/prune-nullish-values"
import { raise } from "../../helpers/raise"
import { toUpper } from "../../helpers/to-upper"
import type { ComponentInteraction } from "../internal/interaction"
import type {
Message,
MessageButtonOptions,
MessageOptions,
} from "../internal/message"
import type { Message, MessageOptions } from "../internal/message"
import { ChannelMessageRenderer } from "../internal/renderers/channel-message-renderer"
import { InteractionReplyRenderer } from "../internal/renderers/interaction-reply-renderer"
import type {
@@ -33,7 +30,7 @@ export class ReacordDiscordJs extends Reacord {
super(config)
client.on("interactionCreate", (interaction) => {
if (interaction.isButton() || interaction.isSelectMenu()) {
if (interaction.isMessageComponent()) {
this.handleComponentInteraction(
this.createReacordComponentInteraction(interaction),
)
@@ -91,7 +88,7 @@ export class ReacordDiscordJs extends Reacord {
(await this.client.channels.fetch(channelId)) ??
raise(`Channel ${channelId} not found`)
if (!channel.isTextBased()) {
if (!channel.isText()) {
raise(`Channel ${channelId} is not a text channel`)
}
@@ -304,6 +301,15 @@ function createReacordMessage(message: Discord.Message): Message {
delete: async () => {
await message.delete()
},
updateFiles: async (files) => {
await message.edit({
files: files.map(({ name, description, data }) => ({
name,
description,
attachment: data,
})),
})
},
}
}
@@ -313,6 +319,10 @@ function createEphemeralReacordMessage(): Message {
console.warn("Ephemeral messages can't be edited")
return Promise.resolve()
},
updateFiles: () => {
console.warn("Ephemeral messages can't be edited")
return Promise.resolve()
},
delete: () => {
console.warn("Ephemeral messages can't be deleted")
return Promise.resolve()
@@ -320,34 +330,25 @@ function createEphemeralReacordMessage(): Message {
}
}
function convertButtonStyleToEnum(style: MessageButtonOptions["style"]) {
const styleMap = {
primary: Discord.ButtonStyle.Primary,
secondary: Discord.ButtonStyle.Secondary,
success: Discord.ButtonStyle.Success,
danger: Discord.ButtonStyle.Danger,
} as const
return styleMap[style ?? "secondary"]
}
// TODO: this could be a part of the core library,
// and also handle some edge cases, e.g. empty messages
function getDiscordMessageOptions(reacordOptions: MessageOptions) {
const options = {
function getDiscordMessageOptions(
reacordOptions: MessageOptions,
): Discord.MessageOptions {
const options: Discord.MessageOptions = {
// eslint-disable-next-line unicorn/no-null
content: reacordOptions.content || null,
embeds: reacordOptions.embeds,
components: reacordOptions.actionRows.map((row) => ({
type: Discord.ComponentType.ActionRow,
type: "ACTION_ROW",
components: row.map(
(component): Discord.MessageActionRowComponentData => {
(component): Discord.MessageActionRowComponentOptions => {
if (component.type === "button") {
return {
type: Discord.ComponentType.Button,
type: "BUTTON",
customId: component.customId,
label: component.label ?? "",
style: convertButtonStyleToEnum(component.style),
style: toUpper(component.style ?? "secondary"),
disabled: component.disabled,
emoji: component.emoji,
}
@@ -356,7 +357,7 @@ function getDiscordMessageOptions(reacordOptions: MessageOptions) {
if (component.type === "select") {
return {
...component,
type: Discord.ComponentType.SelectMenu,
type: "SELECT_MENU",
options: component.options.map((option) => ({
...option,
default: component.values?.includes(option.value),
@@ -370,7 +371,10 @@ function getDiscordMessageOptions(reacordOptions: MessageOptions) {
})),
}
if (!options.content && !options.embeds?.length) {
const hasContent =
options.content || options.embeds?.length || options.files?.length
if (!hasContent) {
options.content = "_ _"
}

View File

@@ -63,6 +63,9 @@ export abstract class Reacord {
this.renderers = this.renderers.filter((it) => it !== renderer)
renderer.destroy()
},
attach: (file) => {
renderer.attach(file)
},
}
if (initialContent !== undefined) {

View File

@@ -1,5 +1,7 @@
import { ReacordFile } from "../core/file"
import type { Message, MessageOptions } from "./message"
export type Channel = {
send(message: MessageOptions): Promise<Message>
sendFiles(files: readonly ReacordFile[]): Promise<Message>
}

View File

@@ -2,6 +2,7 @@ import type { Except } from "type-fest"
import { last } from "../../helpers/last"
import type { EmbedOptions } from "../core/components/embed-options"
import type { SelectProps } from "../core/components/select"
import { ReacordFile } from "../main"
export type MessageOptions = {
content: string
@@ -49,6 +50,7 @@ export type MessageSelectOptionOptions = {
export type Message = {
edit(options: MessageOptions): Promise<void>
delete(): Promise<void>
updateFiles(files: readonly ReacordFile[]): Promise<void>
}
export function getNextActionRow(options: MessageOptions): ActionRow {

View File

@@ -1,3 +1,4 @@
import { ReacordFile } from "../../core/file"
import type { Channel } from "../channel"
import type { Message, MessageOptions } from "../message"
import { Renderer } from "./renderer"
@@ -10,4 +11,10 @@ export class ChannelMessageRenderer extends Renderer {
protected createMessage(options: MessageOptions): Promise<Message> {
return this.channel.send(options)
}
protected createMessageFromFiles(
files: readonly ReacordFile[],
): Promise<Message> {
return this.channel.sendFiles(files)
}
}

View File

@@ -1,5 +1,6 @@
import { Subject } from "rxjs"
import { concatMap } from "rxjs/operators"
import { ReacordFile } from "../../core/file"
import { Container } from "../container.js"
import type { ComponentInteraction } from "../interaction"
import type { Message, MessageOptions } from "../message"
@@ -7,15 +8,21 @@ import type { Node } from "../node.js"
type UpdatePayload =
| { action: "update" | "deactivate"; options: MessageOptions }
| { action: "files"; files: readonly ReacordFile[] }
| { action: "deferUpdate"; interaction: ComponentInteraction }
| { action: "destroy" }
type NewMessagePayload =
| { source: "content"; messageOptions?: MessageOptions }
| { source: "files"; files?: readonly ReacordFile[] }
export abstract class Renderer {
readonly nodes = new Container<Node<unknown>>()
private componentInteraction?: ComponentInteraction
private message?: Message
private active = true
private updates = new Subject<UpdatePayload>()
private files: readonly ReacordFile[] = []
private updateSubscription = this.updates
.pipe(concatMap((payload) => this.updateMessage(payload)))
@@ -46,6 +53,11 @@ export abstract class Renderer {
this.updates.next({ action: "destroy" })
}
attach(file: ReacordFile) {
const newFiles = (this.files = [...this.files, file])
this.updates.next({ action: "files", files: newFiles })
}
handleComponentInteraction(interaction: ComponentInteraction) {
this.componentInteraction = interaction
@@ -60,7 +72,7 @@ export abstract class Renderer {
}
}
protected abstract createMessage(options: MessageOptions): Promise<Message>
protected abstract createMessage(options: NewMessagePayload): Promise<Message>
private getMessageOptions(): MessageOptions {
const options: MessageOptions = {
@@ -102,6 +114,15 @@ export abstract class Renderer {
return
}
if (payload.action === "files") {
if (this.message) {
await this.message?.updateFiles(payload.files)
} else {
this.message = await this.createMessageFromFiles(payload.files)
}
return
}
if (this.componentInteraction) {
const promise = this.componentInteraction.update(payload.options)
this.componentInteraction = undefined

View File

@@ -12,6 +12,7 @@ export * from "./core/components/embed-title"
export * from "./core/components/link"
export * from "./core/components/option"
export * from "./core/components/select"
export * from "./core/file"
export * from "./core/instance"
export { useInstance } from "./core/instance-context"
export * from "./core/reacord"

View File

@@ -2,7 +2,7 @@
"name": "reacord",
"type": "module",
"description": "Create interactive Discord messages using React.",
"version": "0.4.0",
"version": "0.3.5",
"types": "./dist/main.d.ts",
"homepage": "https://reacord.mapleleaf.dev",
"repository": "https://github.com/itsMapleLeaf/reacord.git",
@@ -35,7 +35,7 @@
}
},
"scripts": {
"build": "tsup library/main.ts --target node16 --format cjs,esm --dts --sourcemap",
"build": "tsup-node library/main.ts --target node16 --format cjs,esm --dts --sourcemap",
"build-watch": "pnpm build -- --watch",
"test": "vitest --coverage --no-watch",
"test-dev": "vitest",
@@ -52,7 +52,7 @@
"rxjs": "^7.5.5"
},
"peerDependencies": {
"discord.js": "^14",
"discord.js": "^13.3",
"react": ">=17"
},
"peerDependenciesMeta": {
@@ -63,7 +63,7 @@
"devDependencies": {
"@types/lodash-es": "^4.17.6",
"c8": "^7.11.2",
"discord.js": "^14.0.3",
"discord.js": "^13.6.0",
"dotenv": "^16.0.0",
"esbuild": "latest",
"esbuild-jest": "^0.5.0",
@@ -78,7 +78,7 @@
"type-fest": "^2.12.2",
"typescript": "^4.6.3",
"vite": "^2.9.5",
"vitest": "^0.10.0"
"vitest": "^0.9.4"
},
"resolutions": {
"esbuild": "latest"

Binary file not shown.

After

Width:  |  Height:  |  Size: 954 KiB

View File

@@ -8,21 +8,19 @@ type Command = {
export function createCommandHandler(client: Client, commands: Command[]) {
client.on("ready", async () => {
for (const command of commands) {
for (const guild of client.guilds.cache.values()) {
await client.application?.commands.create(
{
name: command.name,
description: command.description,
},
guild.id,
)
}
for (const guild of client.guilds.cache.values()) {
client.application!.commands.set(
commands.map(({ name, description }) => ({
name,
description,
})),
guild.id,
)
}
})
client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand()) return
if (!interaction.isCommand()) return
const command = commands.find(
(command) => command.name === interaction.commandName,

View File

@@ -1,13 +1,16 @@
import { Client, IntentsBitField } from "discord.js"
import { Client } from "discord.js"
import "dotenv/config"
import { readFile } from "fs/promises"
import { join } from "path"
import React from "react"
import { fileURLToPath } from "url"
import { Button, ReacordDiscordJs, useInstance } from "../library/main"
import { createCommandHandler } from "./command-handler"
import { Counter } from "./counter"
import { FruitSelect } from "./fruit-select"
const client = new Client({
intents: IntentsBitField.Flags.Guilds,
intents: ["GUILDS"],
})
const reacord = new ReacordDiscordJs(client)
@@ -104,6 +107,19 @@ createCommandHandler(client, [
reacord.reply(interaction, <DeleteThis />)
},
},
{
name: "anime",
description: "shows an anime image",
run: async (interaction) => {
const reply = reacord.reply(interaction)
const image = await readFile(
join(fileURLToPath(import.meta.url), "../anime.jpg"),
)
reply.attach({ name: "anime.jpg", data: image })
// reply.render("anime")
},
},
])
await client.login(process.env.TEST_BOT_TOKEN)

View File

@@ -1,12 +0,0 @@
import { spawnSync } from "node:child_process"
import { createRequire } from "node:module"
import { beforeAll, expect, test } from "vitest"
beforeAll(() => {
spawnSync("pnpm", ["run", "build"])
})
test("can require commonjs", () => {
const require = createRequire(import.meta.url)
expect(() => require("../dist/main.cjs")).not.toThrow()
})

View File

@@ -1,3 +1,4 @@
import packageJson from "reacord/package.json"
import type {
LinksFunction,
LoaderFunction,
@@ -12,7 +13,6 @@ import {
ScrollRestoration,
useLoaderData,
} from "@remix-run/react"
import packageJson from "reacord/package.json"
import bannerUrl from "~/assets/banner.png"
import faviconUrl from "~/assets/favicon.png"
import { GuideLinksProvider } from "~/modules/navigation/guide-links-context"
@@ -77,7 +77,6 @@ export default function App() {
return (
<html lang="en" className="bg-slate-900 text-slate-100">
<head>
{/* eslint-disable-next-line unicorn/text-encoding-identifier-case */}
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<Meta />
@@ -85,10 +84,9 @@ export default function App() {
{process.env.NODE_ENV === "production" && (
<script
async
defer
data-website-id="e3ce3a50-720e-4489-be37-cc091c1b7029"
src="https://umami-production-72bc.up.railway.app/umami.js"
></script>
data-website-id="49c69ade-5593-4853-9686-c9ca9d519a18"
src="https://umami-production-265f.up.railway.app/umami.js"
/>
)}
</head>
<body>

View File

@@ -11,7 +11,7 @@
"typecheck": "tsc --noEmit && tsc --project cypress/tsconfig.json --noEmit"
},
"dependencies": {
"@headlessui/react": "^1.6.0",
"@headlessui/react": "^1.5.0",
"@heroicons/react": "^1.0.6",
"@reach/rect": "^0.17.0",
"@remix-run/node": "^1.4.1",
@@ -33,13 +33,13 @@
"@remix-run/node": "^1.4.1",
"@testing-library/cypress": "^8.0.2",
"@types/node": "*",
"@types/react": "^18.0.7",
"@types/react": "^18.0.6",
"@types/react-dom": "^18.0.2",
"@types/tailwindcss": "^3.0.10",
"@types/wait-on": "^5.3.1",
"autoprefixer": "^10.4.5",
"autoprefixer": "^10.4.4",
"concurrently": "^7.1.0",
"cypress": "^9.6.0",
"cypress": "^9.5.4",
"execa": "^6.1.0",
"postcss": "^8.4.12",
"rehype-prism-plus": "^1.3.2",
@@ -48,5 +48,8 @@
"typescript": "^4.6.3",
"wait-on": "^6.0.1"
},
"engines": {
"node": ">=14"
},
"sideEffects": false
}

2267
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff