back to immutable mode

This commit is contained in:
MapleLeaf
2021-12-16 20:58:48 -06:00
parent e67abe0b9b
commit 174bc22c18
10 changed files with 110 additions and 104 deletions

View File

@@ -6,7 +6,8 @@
"lint": "eslint --ext js,ts,tsx .", "lint": "eslint --ext js,ts,tsx .",
"lint-fix": "pnpm lint -- --fix", "lint-fix": "pnpm lint -- --fix",
"format": "prettier --write .", "format": "prettier --write .",
"test": "c8 ava", "test": "ava",
"test-coverage": "c8 ava",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"devDependencies": { "devDependencies": {
@@ -40,7 +41,7 @@
"**/.vscode/**" "**/.vscode/**"
], ],
"parserOptions": { "parserOptions": {
"project": "./tsconfig.base.json" "project": "./tsconfig.json"
} }
}, },
"prettier": "@itsmapleleaf/configs/prettier", "prettier": "@itsmapleleaf/configs/prettier",

View File

@@ -10,7 +10,7 @@ export function withLoggedMethodCalls<T extends object>(value: T) {
return (...values: any[]) => { return (...values: any[]) => {
console.log( console.log(
`${String(property)}(${values `${String(property)}(${values
.map((value: any) => inspect(value, { depth: 1 })) .map((value) => inspect(value, { depth: 1 }))
.join(", ")})`, .join(", ")})`,
) )
return value.apply(target, values) return value.apply(target, values)

View File

@@ -38,7 +38,7 @@ test.beforeEach(async () => {
await Promise.all(messages.map((message) => message.delete())) await Promise.all(messages.map((message) => message.delete()))
}) })
test("rendering", async (t) => { test.serial("basic text & content updates", async (t) => {
const root = createRoot(channel) const root = createRoot(channel)
await root.render("hi world") await root.render("hi world")
@@ -55,12 +55,32 @@ test("rendering", async (t) => {
await assertMessages(t, [{ content: "hi world" }]) await assertMessages(t, [{ content: "hi world" }])
await root.render(<Text></Text>) await root.render(<Text></Text>)
await assertMessages(t, []) await assertMessages(t, [{ content: "_ _" }])
await root.render(<Text>hi world</Text>)
await assertMessages(t, [{ content: "hi world" }])
await root.render([]) await root.render([])
await assertMessages(t, [{ content: "_ _" }])
await root.destroy()
await assertMessages(t, []) await assertMessages(t, [])
}) })
test.serial("nested text", async (t) => {
const root = createRoot(channel)
await root.render(
<Text>
<Text>hi world</Text>{" "}
<Text>
hi moon <Text>hi sun</Text>
</Text>
</Text>,
)
await assertMessages(t, [{ content: "hi world hi moon hi sun" }])
})
type MessageData = ReturnType<typeof extractMessageData> type MessageData = ReturnType<typeof extractMessageData>
function extractMessageData(message: Message) { function extractMessageData(message: Message) {
return pick(message, "content", "embeds", "components") return pick(message, "content", "embeds", "components")

View File

@@ -1,7 +1,8 @@
import type { ReactNode } from "react"
import React from "react" import React from "react"
export type TextProps = { export type TextProps = {
children?: string children?: ReactNode
} }
export function Text(props: TextProps) { export function Text(props: TextProps) {

View File

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

View File

@@ -1,5 +1,4 @@
/* eslint-disable unicorn/no-null */ /* eslint-disable unicorn/no-null */
import { raise } from "reacord-helpers/raise.js" import { raise } from "reacord-helpers/raise.js"
import ReactReconciler from "react-reconciler" import ReactReconciler from "react-reconciler"
import type { ReacordElementMap } from "./elements.js" import type { ReacordElementMap } from "./elements.js"
@@ -7,25 +6,47 @@ import type { ReacordContainer } from "./renderer/container.js"
import { TextElementInstance } from "./renderer/text-element-instance.js" import { TextElementInstance } from "./renderer/text-element-instance.js"
import { TextInstance } from "./renderer/text-instance.js" import { TextInstance } from "./renderer/text-instance.js"
// instances that represent an element
type ElementInstance = TextElementInstance
// any instance
type Instance = ElementInstance | TextInstance
type ElementTag =
| keyof ReacordElementMap
| (string & { __autocompleteHack__?: never })
type Props = Record<string, unknown>
const createInstance = (
type: ElementTag,
props: Props,
): TextElementInstance => {
if (type === "reacord-text") {
return new TextElementInstance()
}
raise(`Unknown element type "${type}"`)
}
export const reconciler = ReactReconciler< export const reconciler = ReactReconciler<
keyof ReacordElementMap | (string & { __autocompleteHack__?: never }), // Type, ElementTag, // Type,
Record<string, unknown>, // Props, Props, // Props,
ReacordContainer, // Container, ReacordContainer, // Container,
TextElementInstance, // Instance, ElementInstance, // Instance,
TextInstance, // TextInstance, TextInstance, // TextInstance,
never, // SuspenseInstance, never, // SuspenseInstance,
never, // HydratableInstance, never, // HydratableInstance,
never, // PublicInstance, never, // PublicInstance,
null, // HostContext, null, // HostContext,
never, // UpdatePayload, never, // UpdatePayload,
never, // ChildSet, Instance[], // ChildSet,
unknown, // TimeoutHandle, unknown, // TimeoutHandle,
unknown // NoTimeout unknown // NoTimeout
>({ >({
now: Date.now, now: Date.now,
isPrimaryRenderer: true, isPrimaryRenderer: true,
supportsMutation: true, supportsMutation: false,
supportsPersistence: false, supportsPersistence: true,
supportsHydration: false, supportsHydration: false,
scheduleTimeout: setTimeout, scheduleTimeout: setTimeout,
cancelTimeout: clearTimeout, cancelTimeout: clearTimeout,
@@ -35,42 +56,44 @@ export const reconciler = ReactReconciler<
getChildHostContext: (parentContext) => parentContext, getChildHostContext: (parentContext) => parentContext,
shouldSetTextContent: () => false, shouldSetTextContent: () => false,
createInstance: (type, props) => { createInstance,
if (type === "reacord-text") {
return new TextElementInstance() createTextInstance: (text) => new TextInstance(text),
}
raise(`Unknown element type "${type}"`) createContainerChildSet: () => [],
appendChildToContainerChildSet: (childSet: Instance[], child: Instance) => {
childSet.push(child)
}, },
createTextInstance: (text) => { finalizeContainerChildren: (
return new TextInstance(text) container: ReacordContainer,
}, children: Instance[],
) => false,
clearContainer: (container) => { replaceContainerChildren: (
container.clear() container: ReacordContainer,
}, children: Instance[],
) => {
appendChildToContainer: (container, child) => { container.render(children)
container.add(child)
},
removeChildFromContainer: (container, child) => {
container.remove(child)
}, },
appendInitialChild: (parent, child) => { appendInitialChild: (parent, child) => {
parent.add(child) parent.add(child)
}, },
removeChild: (parent, child) => { cloneInstance: (
parent.remove(child) instance: Instance,
}, _: unknown,
type: ElementTag,
oldProps: Props,
newProps: Props,
) => createInstance(type, newProps),
finalizeInitialChildren: () => false, finalizeInitialChildren: () => false,
prepareForCommit: (container) => null, prepareForCommit: (container) => null,
resetAfterCommit: () => null, resetAfterCommit: () => null,
prepareUpdate: () => null, prepareUpdate: () => null,
getPublicInstance: () => raise("Not implemented"), getPublicInstance: () => raise("Not implemented"),
preparePortalMount: () => raise("Not implemented"), preparePortalMount: () => raise("Not implemented"),
}) })

View File

@@ -6,46 +6,35 @@ type Action =
| { type: "updateMessage"; options: MessageOptions } | { type: "updateMessage"; options: MessageOptions }
| { type: "deleteMessage" } | { type: "deleteMessage" }
type ReacordContainerChild = TextElementInstance | TextInstance type ContainerChild = TextInstance | TextElementInstance
export class ReacordContainer { export class ReacordContainer {
private channel: TextBasedChannels private channel: TextBasedChannels
private message?: Message private message?: Message
private actions: Action[] = [] private actions: Action[] = []
private runningPromise?: Promise<void> private runningPromise?: Promise<void>
private instances = new Set<ReacordContainerChild>()
constructor(channel: TextBasedChannels) { constructor(channel: TextBasedChannels) {
this.channel = channel this.channel = channel
} }
add(instance: ReacordContainerChild) { render(children: ContainerChild[]) {
this.instances.add(instance)
this.render()
}
remove(instance: ReacordContainerChild) {
this.instances.delete(instance)
this.render()
}
clear() {
this.instances.clear()
this.render()
}
render() {
const messageOptions: MessageOptions = {} const messageOptions: MessageOptions = {}
for (const instance of this.instances) { for (const child of children) {
instance.render(messageOptions) child.renderToMessage(messageOptions)
} }
// can't render an empty message // can't render an empty message
if (!messageOptions.content) { if (!messageOptions?.content) {
this.addAction({ type: "deleteMessage" }) messageOptions.content = "_ _"
} else {
this.addAction({ type: "updateMessage", options: messageOptions })
} }
this.addAction({ type: "updateMessage", options: messageOptions })
}
destroy() {
this.actions = []
this.addAction({ type: "deleteMessage" })
} }
completion() { completion() {

View File

@@ -1,26 +1,22 @@
import type { MessageOptions } from "discord.js" import type { MessageOptions } from "discord.js"
import type { TextInstance } from "./text-instance.js" import type { TextInstance } from "./text-instance.js"
type TextElementInstanceChild = TextElementInstance | TextInstance type TextElementChild = TextElementInstance | TextInstance
export class TextElementInstance { export class TextElementInstance {
children = new Set<TextElementInstanceChild>() children = new Set<TextElementChild>()
add(child: TextElementInstanceChild) { add(child: TextElementChild) {
this.children.add(child) this.children.add(child)
} }
remove(child: TextElementInstanceChild) { renderToMessage(options: MessageOptions) {
this.children.delete(child)
}
clear() {
this.children.clear()
}
render(options: MessageOptions) {
for (const child of this.children) { for (const child of this.children) {
child.render(options) options.content = `${options.content ?? ""}${child.text}`
} }
} }
get text(): string {
return [...this.children].map((child) => child.text).join("")
}
} }

View File

@@ -1,13 +1,9 @@
import type { MessageOptions } from "discord.js" import type { MessageOptions } from "discord.js"
export class TextInstance { export class TextInstance {
text: string constructor(readonly text: string) {}
constructor(text: string) { renderToMessage(options: MessageOptions) {
this.text = text
}
render(options: MessageOptions) {
options.content = `${options.content ?? ""}${this.text}` options.content = `${options.content ?? ""}${this.text}`
} }
} }

View File

@@ -1,3 +1,4 @@
/* eslint-disable unicorn/no-null */
import type { TextBasedChannels } from "discord.js" import type { TextBasedChannels } from "discord.js"
import type { ReactNode } from "react" import type { ReactNode } from "react"
import { reconciler } from "./reconciler" import { reconciler } from "./reconciler"
@@ -7,12 +8,16 @@ export type ReacordRenderTarget = TextBasedChannels
export function createRoot(target: ReacordRenderTarget) { export function createRoot(target: ReacordRenderTarget) {
const container = new ReacordContainer(target) const container = new ReacordContainer(target)
// eslint-disable-next-line unicorn/no-null
const containerId = reconciler.createContainer(container, 0, false, null) const containerId = reconciler.createContainer(container, 0, false, null)
return { return {
render: (content: ReactNode) => { render: (content: ReactNode) => {
reconciler.updateContainer(content, containerId) reconciler.updateContainer(content, containerId)
return container.completion() return container.completion()
}, },
destroy: () => {
reconciler.updateContainer(null, containerId)
container.destroy()
return container.completion()
},
} }
} }