我正在研究一个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在内部使用@ wordpress / rich-text包的applyFormat方法,但是我无法弄清楚如何直接使用applyFormat。该文档不足,缺少代码示例。
如果您使用过此方法,则可以使用示例工作代码(ES5或ES6)来以正确的方式使用applyFormat。
我终于弄明白了。如果有人需要这样做,只需将其发布在此处,因为Gutenberg文档缺少代码示例。
参考下面的代码,blockIndex
是您正在处理的块;和startIndex
和endIndex
是要在块上下文中进行注释的范围:
// 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
})
}
} );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句