import * as React from "react"; import { first } from "rxjs/operators"; import { Plugin as BaseEntity, IPluginState as BaseData, } from "@daostack/arc.js"; import { Arc as Protocol, ArcConfig as ProtocolConfig, Component, ComponentProps, ComponentLogs, } from "../../"; import { CreateContextFeed } from "../../runtime/ContextFeed"; abstract class Entity extends BaseEntity {} type Data = BaseData; interface RequiredProps extends ComponentProps { // Plugin ID id: Entity | string; } interface InferredProps extends RequiredProps { config: ProtocolConfig; } class InferredPlugin extends Component { protected async createEntity(): Promise { const { config, id } = this.props; if (!config) { throw Error( "Arc Config Missing: Please provide this field as a prop, or use the inference component." ); } if (!id) { throw Error( "ID Missing: Please provide this field as a prop, or use the inference component" ); } if (typeof id === "string") { const plugin = await Entity.search(config.connection, { where: { id } }) .pipe(first()) .toPromise(); if (!plugin || plugin.length === 0) { throw Error("Plugin not found"); } return plugin[0]; } else { return id; } } public static get Entity() { return CreateContextFeed( this.EntityContext.Consumer, this.LogsContext.Consumer, "Plugin" ); } public static get Data() { return CreateContextFeed( this.DataContext.Consumer, this.LogsContext.Consumer, "Plugin" ); } public static get Logs() { return CreateContextFeed( this.LogsContext.Consumer, this.LogsContext.Consumer, "Plugin" ); } public static EntityContext = React.createContext( undefined ); public static DataContext = React.createContext(undefined); public static LogsContext = React.createContext( undefined ); } function usePlugin(): [Data | undefined, Entity | undefined] { const data = React.useContext(InferredPlugin.DataContext); const entity = React.useContext( InferredPlugin.EntityContext ); return [data, entity]; } class Plugin extends React.Component { public render() { const { id, children } = this.props; return ( {(config: ProtocolConfig) => ( {children} )} ); } public static get Entity() { return InferredPlugin.Entity; } public static get Data() { return InferredPlugin.Data; } public static get Logs() { return InferredPlugin.Logs; } } export default Plugin; export { Plugin, InferredPlugin, Entity as PluginEntity, Data as PluginData, usePlugin, };