gutenbergdocs/docs/reference-guides/block-api/block-annotations.md
2025-10-22 01:40:18 +08:00

61 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 标注功能
<div class="callout callout-alert">
<strong>注意:</strong> 此 API 为实验性功能,这意味着在未来的任何版本中可能会发生不向后兼容的变更或被移除。
</div>
标注是一种高亮区块编辑器中创建的文章特定片段的方式。典型应用包括文本批注与拼写检查,两者均可通过标注 API 对文本片段进行标记。
## API
要直观了解 API最简便的方式是创建一个至少包含 200 个无格式字符的区块,并在控制台中执行以下代码:
```js
wp.data.dispatch( 'core/annotations' ).addAnnotation( {
source: 'my-annotations-plugin',
blockClientId: wp.data.select( 'core/block-editor' ).getBlockOrder()[ 0 ],
richTextIdentifier: 'content',
range: {
start: 50,
end: 100,
},
} );
```
范围起始点与结束点的计算应仅基于相应 `RichText` 的纯文本内容。例如在以下 HTML 中,位置 0 将指向大写字母 S 之前的位置:
```html
<strong>加粗文本</strong>
```
为帮助确定正确位置,可使用 `wp.richText.create` 方法。该方法会将 HTML 片段拆分为文本内容与格式标记。
所有可用属性均可在 `addAnnotation` 操作的 API 文档中查阅。
`richTextIdentifier` 属性用于指定标注所应用的富文本实例标识符。由于区块可能包含多个用于管理不同属性数据的富文本实例,必须传入此参数才能确保在正确的实例中高亮文本。
例如段落区块仅包含单个标识符为 `content` 的富文本实例。引述区块类型则拥有 2 个富文本实例,若需在引注部分高亮文本,添加标注时需将 `citation` 作为 `richTextIdentifier` 传入;若需定位引述内容,则需使用标识符 `value`。具体标识符请参考区块类型的源代码。
## 区块标注
也可对完整区块进行标注。此时只需提供值为 `block``selector` 属性。默认的 `selector``range`,适用于文本标注场景。
```js
wp.data.dispatch( 'core/annotations' ).addAnnotation( {
source: 'my-annotations-plugin',
blockClientId: wp.data.select( 'core/block-editor' ).getBlockOrder()[ 0 ],
selector: 'block',
} );
```
此操作不会自动提供样式支持,因此需要额外添加 CSS 以确保标注可见:
```css
.is-annotated-by-my-annotations-plugin {
outline: 1px solid black;
}
```
## 文本标注
文本标注通过 `start``end` 属性进行控制。由于简单的起止位置属性无法直接适用于 HTML 环境,这两个属性被设计为 `rich-text` 内部结构中的偏移量。为简化理解,可将其视为去除所有 HTML 标记后,在纯文本环境中计算的标注起止位置。