Skip to content

Commit f01a6eb

Browse files
committed
Fix durabilityUsed for items with components
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).
1 parent 7d4cd63 commit f01a6eb

File tree

2 files changed

+52
-3
lines changed

2 files changed

+52
-3
lines changed

index.js

+14-3
Original file line numberDiff line numberDiff line change
@@ -330,9 +330,20 @@ function loader (registryOrVersion) {
330330
get durabilityUsed () {
331331
const where = registry.supportFeature('whereDurabilityIsSerialized')
332332
let ret
333-
if (where === 'Damage') ret = this.nbt?.value?.Damage?.value
334-
else if (where === 'metadata') ret = this.metadata
335-
else throw new Error('unknown durability location')
333+
334+
if (this.components && this.components.length > 0) {
335+
const damageComponent = this.components.find(component => component.type === 'damage')
336+
if (damageComponent) {
337+
ret = damageComponent.data
338+
}
339+
}
340+
341+
if (ret === undefined) {
342+
if (where === 'Damage') ret = this.nbt?.value?.Damage?.value
343+
else if (where === 'metadata') ret = this.metadata
344+
else throw new Error('unknown durability location')
345+
}
346+
336347
return ret ?? (this.maxDurability ? 0 : null)
337348
}
338349

test/basic.test.js

+38
Original file line numberDiff line numberDiff line change
@@ -447,3 +447,41 @@ describe('use Item.equal', () => {
447447
expect(Item.equal(itemOne, itemTwo)).toStrictEqual(false)
448448
})
449449
})
450+
451+
describe('durabilityUsed with damage component', () => {
452+
const Item = require('prismarine-item')('1.20.5')
453+
454+
it('should return correct durabilityUsed for item with damage component', () => {
455+
const item = new Item(830, 1, 0, {
456+
type: 'compound',
457+
name: '',
458+
value: {
459+
Damage: {
460+
type: 'int',
461+
value: 0
462+
}
463+
}
464+
})
465+
item.components = [
466+
{
467+
type: 'damage',
468+
data: 15
469+
}
470+
]
471+
expect(item.durabilityUsed).toBe(15)
472+
})
473+
474+
it('should return correct durabilityUsed for item without damage component', () => {
475+
const item = new Item(830, 1, 0, {
476+
type: 'compound',
477+
name: '',
478+
value: {
479+
Damage: {
480+
type: 'int',
481+
value: 10
482+
}
483+
}
484+
})
485+
expect(item.durabilityUsed).toBe(10)
486+
})
487+
})

0 commit comments

Comments
 (0)