@blockprotocol/hook

中文文档
0.1.8发布于 2024/03/19MITTypeScriptES Module近 30 天下载 2.4万

Implementation of the Block Protocol Hook module specification for blocks and embedding applications

原始使用文档
文档目录6 节
  1. Block Protocol – Hook Module
  2. Blocks
  3. React example
  4. Custom element example
  5. Embedding applications
  6. React

Block Protocol – Hook Module

This package implements the Block Protocol Hook module for blocks and embedding applications.

To get started:

  1. yarn add @blockprotocol/hook or npm install @blockprotocol/hook
  2. Follow the instructions to use the hook module as a block or an embedding application

Blocks

To create a HookBlockHandler, pass the constructor an element in your block, along with any callbacks you wish to register to handle incoming messages.

To send a hook message, you call the hook function.

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
  },
});

React example

For React, we provide a useHookBlockModule hook, which accepts a ref to an element. This will return an object with the shape of { hookModule: HookBlockHandler | null } which you can use to send hook messages.

We also provide a useHook hook to make sending hook messages easier.

import { useHook } from "@blockprotocol/hook/react";

useHook(
  hookModule,
  nodeRef,
  "text",
  ["http://example.com/property-type/text/"],
  (node) => {
    node.innerText = "hook fallback";

    return () => {
      node.innerText = "";
    };
  },
);

Where nodeRef is a RefObject containing the DOM node you'd like to pass to the embedding application.

Custom element example

You can use the firstUpdate Lit lifecycle hook to request that the embedding application take over control of a DOM node.

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>
    `;
  }

Embedding applications

To create a HookEmbedderHandler, pass the constructor:

  1. An element wrapping your block
  2. callbacks to respond to messages from the block
  3. The starting values for any of the following messages you implement:
  • 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,
});

React

For React embedding applications, we provide a useHookEmbedderModule hook, which accepts a ref to an element, and optionally any additional constructor arguments you wish to pass.

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>
  );
};

版本与发布记录

@blockprotocol/hook 共发布 83 个版本,首次发布于 2022/08/01;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.1.8latest2024/03/192 年前
0.1.8-canary-20240314113521canary2024/03/142 年前
0.1.8-canary-202403131914382024/03/142 年前
0.1.8-canary-202403131225332024/03/132 年前
0.1.8-canary-202403121912272024/03/132 年前
0.1.8-canary-202403041547262024/03/042 年前

关于 @blockprotocol/hook 的常见问题

@blockprotocol/hook 是什么?

Implementation of the Block Protocol Hook module specification for blocks and embedding applications

如何安装 @blockprotocol/hook?

在项目目录运行 npm install @blockprotocol/hook,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@blockprotocol/hook 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@blockprotocol/hook 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@blockprotocol/hook 可以商用吗?

@blockprotocol/hook 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@blockprotocol/hook 的下载量有多少?

根据 npm 官方下载统计,@blockprotocol/hook 在 2026/10/09 – 2026/11/07 这 30 天内被下载 24,391 次,日均约 813 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@blockprotocol/hook 还在维护吗?

最新版本 0.1.8 发布于 2024/03/19(2 年前);至今共发布 83 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/08/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。