From f01a6eb64acb47e9a8e9722ace2ed89e591befdf Mon Sep 17 00:00:00 2001 From: Romain Beaumont Date: Sat, 11 Jan 2025 18:52:13 +0100 Subject: [PATCH] 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). --- index.js | 17 ++++++++++++++--- test/basic.test.js | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index f224181..f1c72f8 100644 --- a/index.js +++ b/index.js @@ -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) } diff --git a/test/basic.test.js b/test/basic.test.js index e703588..9ba236d 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -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) + }) +})