Skip to content

Commit

Permalink
Add fix and test (#3658)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshhanley authored Jul 24, 2023
1 parent 03e9337 commit c3c8f26
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/morph/src/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,18 @@ export let dom = {
replace(children, old, replacement) {
let index = children.indexOf(old)

let replacementIndex = children.indexOf(old)

if (index === -1) throw 'Cant find element in children'

old.replaceWith(replacement)

children[index] = replacement

if (replacementIndex) {
children.splice(replacementIndex, 1)
}

return children
},
before(children, reference, subject) {
Expand Down
2 changes: 1 addition & 1 deletion packages/morph/src/morph.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export function morph(from, toHtml, options) {

function patchChildren(fromChildren, toChildren, appendFn) {
// I think I can get rid of this for now:
let fromKeyDomNodeMap = {} // keyToMap(fromChildren)
let fromKeyDomNodeMap = keyToMap(fromChildren)
let fromKeyHoldovers = {}

let currentTo = dom.first(toChildren)
Expand Down
29 changes: 29 additions & 0 deletions tests/cypress/integration/plugins/morph.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,35 @@ test('can morph using a custom key function',
},
)

test('can morph using keys with existing key to be moved up',
[html`
<ul>
<li key="1">foo<input></li>
<li key="2">bar<input></li>
<li key="3">baz<input></li>
</ul>
`],
({ get }, reload, window, document) => {
let toHtml = html`
<ul>
<li key="1">foo<input></li>
<li key="3">baz<input></li>
</ul>
`

get('li:nth-of-type(1) input').type('foo')
get('li:nth-of-type(3) input').type('baz')

get('ul').then(([el]) => window.Alpine.morph(el, toHtml))

get('li').should(haveLength(2))
get('li:nth-of-type(1)').should(haveText('foo'))
get('li:nth-of-type(2)').should(haveText('baz'))
get('li:nth-of-type(1) input').should(haveValue('foo'))
get('li:nth-of-type(2) input').should(haveValue('baz'))
},
)

test('can morph text nodes',
[html`<h2>Foo <br> Bar</h2>`],
({ get }, reload, window, document) => {
Expand Down

0 comments on commit c3c8f26

Please sign in to comment.