pomber/didact

keys implementation?

brainkim opened this issue · 6 comments

Hi. I’m wondering if you considered implementing the react key prop? Wondering what that looks like under the hood and haven’t found an approachable resource for it yet.

Thanks for the blog posts/implementation!

Hey, I haven't. Let me know if you find something or if you try to do it yourself, I'd like to add a link to it.

yisar commented

I implemented this in fre. It has the same performance as react, but it's super simple.
https://github.com/yisar/fre/blob/master/src/reconciler.js#L270

@yisar can you explain the general algorithm you use? I can’t seem to figure out from the code itself sorry :)

yisar commented

@brainkim Well, I can explain it, it is similar to React.

A B => B A
  1. insertPoint
    first, save the insertPoint(Usually the previous fiber), when traversing B, its insertPoint is A, and insertPoint of A is null
  2. insertBefore
    If there is insertPoint, it will insert before it, so B will insert before A
    if insertPoint is null, it will insert before null, same to appendChild
  3. reused
    Only reused fiber have insertPoint, others have not
    if there is no insertPoint, it will insert befroe first child
  4. key and index
    React use not only key but also index to reused fibers, I simplify this.
    I use hash to mark them meanwhile.

Generally speaking, it is actually the processing of insertpoint and reuse. In React, it distinguishes a variety of situations, and Fre super simplifies it.

You can try to debug them by yourself!

Hi @yisar Did you change the implementation of reconciliation in fre? I'm confused after reading the explanation and the code. Thanks

yisar commented

@Combo819 In Fre2 version, I refactor the reconciliation algorithm. The new algorithm uses Collision pointer for preprocessing, which is better implemented and easier to understand.

I can reinterpret the new algorithm implementation in Fre2:

1 2 3 4
1 3 2 4

We traverse from both ends to the middle, and find that 1 and 4 are exactly the same, then we skip them, and then it becomes:

2 3
3 2

The remaining nodes can be reused. We save their DOM references. Finally, we just need to change the position, that is, 3 is inserted in front of 2.

Of course, if you are interested in the old algorithm, you can look up the code of fre1, but I think fre2 will be better.