reblock
Version:
Build interactive Slack surfaces with React
83 lines (82 loc) • 2.08 kB
JavaScript
import { createContainer, render, Root } from '../renderer'
import { jsxToBlocks } from '../jsx/blocks'
import { activeRoots, activeAppHomes, ensureEventRegistered } from '../events'
import { blocks } from './blocks'
export class AppHomeRoot extends Root {
client
userID
resolve
reject
constructor(client, userID, resolve, reject) {
super()
this.client = client
this.userID = userID
this.resolve = resolve
this.reject = reject
}
async publish() {
try {
activeRoots.add(this)
activeAppHomes.set(this.userID, this)
const children = this.getChildren()
const [blocks] = jsxToBlocks(children)
await this.client.views.publish({
user_id: this.userID,
view: {
type: 'home',
blocks: blocks,
},
})
if (this.resolve) {
this.resolve()
}
} catch (error) {
if (this.reject) {
this.reject(error)
}
console.error(error)
}
}
handle = new AppHomeHandle(this)
}
export class AppHomeHandle {
root
constructor(root) {
this.root = root
}
get rendering() {
return this.root.rendering
}
async stop(behavior = 'clear') {
this.root.stopRendering()
activeRoots.delete(this.root)
activeAppHomes.delete(this.root.userID)
if (behavior === 'keep') return
const finalBlocks = behavior === 'clear' ? [] : blocks(behavior)
await this.root.client.views.publish({
user_id: this.root.userID,
view: {
type: 'home',
blocks: finalBlocks,
},
})
}
}
export async function userAppHome(app, userID, element) {
ensureEventRegistered(app)
const existing = activeAppHomes.get(userID)
if (existing) {
await existing.handle.stop('keep')
}
let resolve = undefined
let reject = undefined
const promise = new Promise((res, rej) => {
resolve = res
reject = rej
})
const root = new AppHomeRoot(app.client, userID, resolve, reject)
const container = createContainer(root)
render(element, container)
await promise
return root.handle
}