[英]Twitter style (stock) mention with Slate.js
I am building a note taking app and for text I use the Slate.js editor.我正在构建一个笔记应用程序,对于文本,我使用 Slate.js 编辑器。 Twitter mention also works with stocks like this
Twitter 提及也适用于这样的股票
It basically turns into a mention if /\$[a-zA-Z]{1,6}/
is true.如果
/\$[a-zA-Z]{1,6}/
是真的,它基本上会变成一个提及。 What I have tried is to use the normalizeNode
callback to change if the regex matches, by deleting the text and inserting a new node at that location but so far I've been unsuccessful.我尝试的是使用
normalizeNode
回调来更改正则表达式是否匹配,方法是删除文本并在该位置插入一个新节点,但到目前为止我一直没有成功。
Slate.js also has a nice set of examples but unfortunately haven't found any of them to demonstrate what I'm trying to do. Slate.js 也有一组很好的示例,但遗憾的是没有找到任何示例来演示我正在尝试做的事情。 What would be a good way to go about implementing this feature?
go 关于实现此功能的好方法是什么? Am I wrong to assume it's through using
normalizeNode
?我错误地认为它是通过使用
normalizeNode
吗?
I solved this question when working on typed in emojis.我在输入表情符号时解决了这个问题。 For example, when a person typed
:smile:
we wanted the emoji to appear (a la Slack).例如,当一个人输入
:smile:
时,我们希望表情符号出现(a la Slack)。 The only differences with stock symbols and emojis would be the stock lookup and the usage of Transforms.insertNodes
instead of Transforms.insertText
.股票符号和表情符号的唯一区别是股票查找和使用
Transforms.insertNodes
而不是Transforms.insertText
。
The code below should be enough to help someone solve their use case.下面的代码应该足以帮助某人解决他们的用例。 The key is
startIndex
and endIndex
which targets the replacement.关键是针对替换的
startIndex
和endIndex
。
Here's my solution:这是我的解决方案:
editor.normalizeNode = entry => {
const [node, path] = entry;
if (!Text.isText(node)) {
return normalizeNode([node, path]);
}
const emojiMatch = node.text.match(EMOJI_REGEX);
if (!emojiMatch) {
return normalizeNode([node, path]);
}
const [searchMatch, colonMatch] = emojiMatch;
const { index: startIndex } = emojiMatch;
const endIndex = startIndex + searchMatch.length;
const [matchedEmoji] = emojiIndex.search(colonMatch).map(emoji => emoji) as BaseEmoji[];
if (!matchedEmoji) {
return normalizeNode([node, path]);
}
Transforms.insertText(editor, matchedEmoji.native, {
at: {
anchor: { path, offset: startIndex },
focus: { path, offset: endIndex },
}
})
normalizeNode([node, path]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.