Skip to content

Commit

Permalink
fix $id caching mechanism
Browse files Browse the repository at this point in the history
  • Loading branch information
calebporzio committed Dec 12, 2023
1 parent 9c3d527 commit 5887109
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
43 changes: 27 additions & 16 deletions packages/alpinejs/src/magics/$id.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,19 @@ import { closestIdRoot, findAndIncrementId } from '../ids'
import { interceptClone } from '../clone'

magic('id', (el, { cleanup }) => (name, key = null) => {
// We only want $id to run once per an element's lifecycle...
if (el._x_id) return el._x_id
let cacheKey = `${name}${key ? `-${key}` : ''}`

let root = closestIdRoot(el, name)
return cacheIdByNameOnElement(el, cacheKey, cleanup, ()=> {
let root = closestIdRoot(el, name)

let id = root
? root._x_ids[name]
: findAndIncrementId(name)
let id = root
? root._x_ids[name]
: findAndIncrementId(name)

let output = key
? `${name}-${id}-${key}`
: `${name}-${id}`

el._x_id = output

cleanup(() => {
delete el._x_id
return key
? `${name}-${id}-${key}`
: `${name}-${id}`
})

return output
})

interceptClone((from, to) => {
Expand All @@ -33,3 +26,21 @@ interceptClone((from, to) => {
to._x_id = from._x_id
}
})

function cacheIdByNameOnElement(el, cacheKey, cleanup, callback)
{
if (! el._x_id) el._x_id = {}

// // We only want $id to run once per an element's lifecycle...
if (el._x_id[cacheKey]) return e._x_id[cacheKey]

let output = callback()

el._x_id[cacheKey] = output

cleanup(() => {
delete el._x_id[cacheKey]
})

return output
}
2 changes: 1 addition & 1 deletion tests/cypress/integration/plugins/ui/dialog.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ test('x-dialog:title',
},
)

test('x-dialog:description',
test.only('x-dialog:description',
[html`
<article x-data x-dialog>
<p x-dialog:description>Dialog Title</p>
Expand Down

0 comments on commit 5887109

Please sign in to comment.