在 WordPress Gutenberg 块中使用(开始和结束索引)范围持久应用格式

Persistently apply format using (start and end index) range in WordPress Gutenberg block

我正在开发一个 Gutenberg 侧边栏插件,它可以进行一些文本分析,并基于此,它需要在段落块中注释文本。这是比较容易的部分,使用 Annotations API 通过像这样遍历每个块来实现:

wp.data.dispatch( 'core/annotations' ).__experimentalAddAnnotation( {
    source: "my-annotations-plugin",
    blockClientId: wp.data.select( 'core/editor' ).getBlockOrder()[0],
    richTextIdentifier: "content",
    range: {
        start: 50,
        end: 100,
    },
} );

现在,我面临的挑战是保留这些注释(因为这是插件的要求)。我发现 Annotations API 内部使用了 applyFormat method of @wordpress/rich-text 包,但我不知道如何直接使用 applyFormat。文档不充分且缺少代码示例。

如果您使用过它,那么使用示例工作(ES5 或 ES6)代码以正确的方式使用 applyFormat 会有所帮助。

我终于明白了。如果有人需要这样做,只需将其张贴在这里,因为古腾堡文档缺少代码示例。

参考下面的代码,blockIndex是你正在处理的块; startIndexendIndex 是要在块上下文中注释的范围:

// Get latest modified content of the block
let html = wp.data.select( "core/editor" ).getBlocks()[blockIndex].attributes.content;
// Get uuid of the block
let blockUid = wp.data.select( "core/editor" ).getBlocks()[blockIndex].clientId;
// Create a RichText value from HTML string of block content
let value = wp.richText.create({
  html
});
// Apply a format object to a Rich Text value from the given startIndex to the given endIndex
value = wp.richText.applyFormat(value, { type: 'strong' }, startIndex, endIndex);
// Update the block with new content
wp.data.dispatch( 'core/editor' ).updateBlock( blockUid, {
    attributes: {
      content: wp.richText.toHTMLString({
        value
      })
    }
  } );