Skip to content

Commit

Permalink
Fix durabilityUsed for items with components
Browse files Browse the repository at this point in the history
Fixes #121

Update `durabilityUsed` getter to support items with components.

* Modify `durabilityUsed` getter in `index.js` to check the `components` array for the `damage` component.
* Use the `damage` component value for `durabilityUsed` if found.
* Fall back to checking the `Damage` field in `nbt` or `metadata` if the `damage` component is not found.
* Add test cases in `test/basic.test.js` to verify `durabilityUsed` returns the correct value for items with and without the `damage` component.

---

For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/PrismarineJS/prismarine-item/issues/121?shareId=XXXX-XXXX-XXXX-XXXX).
  • Loading branch information
rom1504 committed Jan 11, 2025
1 parent 7d4cd63 commit f01a6eb
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
17 changes: 14 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -330,9 +330,20 @@ function loader (registryOrVersion) {
get durabilityUsed () {
const where = registry.supportFeature('whereDurabilityIsSerialized')
let ret
if (where === 'Damage') ret = this.nbt?.value?.Damage?.value
else if (where === 'metadata') ret = this.metadata
else throw new Error('unknown durability location')

if (this.components && this.components.length > 0) {
const damageComponent = this.components.find(component => component.type === 'damage')
if (damageComponent) {
ret = damageComponent.data
}
}

if (ret === undefined) {
if (where === 'Damage') ret = this.nbt?.value?.Damage?.value
else if (where === 'metadata') ret = this.metadata
else throw new Error('unknown durability location')
}

return ret ?? (this.maxDurability ? 0 : null)
}

Expand Down
38 changes: 38 additions & 0 deletions test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -447,3 +447,41 @@ describe('use Item.equal', () => {
expect(Item.equal(itemOne, itemTwo)).toStrictEqual(false)
})
})

describe('durabilityUsed with damage component', () => {
const Item = require('prismarine-item')('1.20.5')

it('should return correct durabilityUsed for item with damage component', () => {
const item = new Item(830, 1, 0, {
type: 'compound',
name: '',
value: {
Damage: {
type: 'int',
value: 0
}
}
})
item.components = [
{
type: 'damage',
data: 15
}
]
expect(item.durabilityUsed).toBe(15)
})

it('should return correct durabilityUsed for item without damage component', () => {
const item = new Item(830, 1, 0, {
type: 'compound',
name: '',
value: {
Damage: {
type: 'int',
value: 10
}
}
})
expect(item.durabilityUsed).toBe(10)
})
})

0 comments on commit f01a6eb

Please sign in to comment.