choojs / nanomorph

🚅 - Hyper fast diffing algorithm for real DOM nodes
MIT License
726 stars 58 forks source link

Fix morph from text node to comment node #122

Open bennlich opened 3 years ago

bennlich commented 3 years ago

I'm not entirely sure what all the ramifications of this change are, but they fix a bug I was running into with HTML comments.

The bug was that occasionally my comment text would wind up getting rendered as DOM text after a morph. Sometimes during a walk morph would try to morph a text node into a comment node, which was no good.

I think my change prevents morph from ever trying to go from text node to comment node. tagName is undefined for both text and comment nodes, but nodeName is meaningful. And I think nodeName has the same value as tagName in most other cases, but I'm not too sure about this. See: https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName.

Here's some code that repro's the bug. When you click, you'll see the number 1 show up in the DOM, even though it's supposed to be in a comment.

test.html

<div id="test"></div>

<script type="module">

  import morph from './nanomorph.es6.js'
  import html from './nanohtml.es6.js'

  let parent = document.querySelector('#test')

  let fragment = () => html`
    <!-- 1 -->
    <!-- 2 -->
  `

  morph(parent, html`
    <div id="test">
      ${ fragment() }
    </div>
  `)

  document.addEventListener('click', () => {
    morph(parent, html`
      <div id="test">
        <div>Hello</div>
        ${ fragment() }
      </div>
    `)
  })

</script>