2

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?

ottomeister
  • 5,415
  • 2
  • 23
  • 27
thekevinscott
  • 5,263
  • 10
  • 44
  • 57

1 Answers1

-1

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.

thekevinscott
  • 5,263
  • 10
  • 44
  • 57
  • 1
    Slate's Document implements Node and one can use this along with Node's traversing methods. E.g. to find a node by it's key: `this.state.value.document.getDescendant(nodeKey)` – Alexander Marinov Aug 27 '18 at 13:44