简体   繁体   中英

How to get current line on change in slate.js

How does one get the current line, or the currently edited node, within the onChange or onKeyDown methods in Slate.js ?

I'm trying to add an updatedAt or createdAt parameter in the data attribute for a particular line.

Here's a proof of concept for what I'm trying to do:

onChange = ({ value }) => {
  return value.document.nodes.reduce((change, node) => {
    return change.setNodeByKey(node.get("key"), {
      data: {
        createdAt: new Date(),
        ...node.get("data").toJS(),
      },
    });
  }, value.change()).value;
}

This loops through every node and adds a createdAt attribute in data if one is not already present. This is obviously not great code since it's looping through every node and has to unserialize the Immutable data object for each node, but it hopefully illustrates what I'm looking to do.

How do I set the data attribute for just the current node?

A few things I've learned:

  • anchorkey gets you the current key of the selection
  • Value has a useful shortcut, startKey

Using the currently selected key, you can then loop through the nodes on a document to get the current node.

I'm not sure if Slatejs provides a way to grab a node by key; if so I can't find it, but the above gets me to where I want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM