块状协议-虎克模块
这个软件包为块和嵌入应用执行"块协议钩"模块.
要开始 :
块
创建 HookBlockHandler中,将构造器传递到您块中的元素,以及您想要注册的用于处理来信的任何调用.
为了发出一个钩子信息,你叫 hook 函数.
import { HookBlockHandler } from "@blockprotocol/hook";
const handler = new HookBlockHandler({ element });
handler.hook({
data: {
hookId: null, // the embedding application will provide a hookId in response to use in future messages
node, // a reference to the DOM node to render into
type: "text", // the type of hook
entityId: "entity1", // the id of the entity this hook will show/edit data for
path: ["http://example.com/property-type/text/"], // the path in the entity's properties data will be taken from/saved to
},
});
反应示例
对于反应,我们提供 useHookBlockModule 钩子,它接受 ref 到一个元素。 这将返回对象的形状为 { hookModule: HookBlockHandler | null } 用于发送钩状信息.
我们还提供 useHook 钩子可以让发送钩子信息更容易.
import { useHook } from "@blockprotocol/hook/react";
useHook(
hookModule,
nodeRef,
"text",
["http://example.com/property-type/text/"],
(node) => {
node.innerText = "hook fallback";
return () => {
node.innerText = "";
};
},
);
何处 nodeRef 是一个 RefObject 包含您想要传递到嵌入应用程序的 DOM 节点 .
自定义元素示例
你可以用这个 firstUpdate 升 生命周期钩 请求嵌入应用程序接管DOM节点的控制.
export class MyBlock extends BlockElementBase {
private hookModule?: HookBlockHandler;
firstUpdated() {
if (!this.hookModule || this.hookModule.destroyed) {
this.hookModule = new HookBlockHandler({
element: this,
});
}
const paragraph = this.renderRoot.querySelector(`#my-hook-paragraph`);
if (!paragraph || !(paragraph instanceof HTMLParagraphElement)) {
throw new Error("No paragraph element for hook module found in element DOM");
}
void this.hookModule.hook({
data: {
node: paragraph,
entityId: this.getBlockEntity()?.metadata.recordId.entityId,
hookId: null,
path: [extractBaseUrl(propertyTypes.description.$id)],
type: "text",
},
});
}
render() {
return html`
<p id="my-hook-paragraph"></p>
`;
}
嵌入应用程序
创建 HookEmbedderHandler,通过构造器:
- 一个
element包装您的块 callbacks以响应块中的信息- 您执行的以下信件的起始值 :
hook
import { HookEmbedderHandler } from "@blockprotocol/hook";
const hookIds = new WeakMap<HTMLElement, string>();
const nodes = new Map<string, HTMLElement>();
const generateId = () => (Math.random() + 1).toString(36).substring(7);
const hookModule = new HookEmbedderHandler({
callbacks: {
hook({ data }) {
if (data.hookId) {
const node = nodes.get(data.hookId);
if (node) node.innerText = "";
nodes.delete(data.hookId);
}
const hookId = data.hookId ?? generateId();
if (data.node) {
nodes.set(hookId, data.node);
data.node.innerText = `Hook of type ${data.type} for path ${data.path}`;
}
return { hookId };
},
},
element: elementWrappingTheBlock,
});
反应
对于反应嵌入应用程序,我们提供一个 useHookEmbedderModule 钩子,它接受 ref ,以及您想要通过的任何附加构造参数.
import { useHookEmbedderModule } from "@blockprotocol/hook/react";
import { useRef } from "react";
export const App = () => {
const wrappingRef = useRef<HTMLDivElement>(null);
useHookEmbedderModule(blockRef, {
hook({ data }) {
// As above
},
});
return (
<div ref={wrappingRef}>
<Block />
</div>
);
};