import Schema from '@/ecs/schema.js'; export default function(Component) { return class Inventory extends Component { insertMany(entities) { for (const [id, {slotChange}] of entities) { if (slotChange) { const {slots} = this.get(id); for (const slotIndex in slotChange) { if (false === slotChange[slotIndex]) { delete slots[slotIndex]; } else { slots[slotIndex] = { ...slots[slotIndex], ...slotChange[slotIndex], }; } } } } return super.insertMany(entities); } mergeDiff(original, update) { if (!update.slotChange) { return super.mergeDiff(original, update); } const slotChange = { ...original.slotChange, }; for (const index in update.slotChange) { if (false === update.slotChange[index]) { slotChange[index] = false; } else { slotChange[index] = { ...slotChange[index], ...update.slotChange[index], }; } } return {slotChange}; } instanceFromSchema() { const Instance = super.instanceFromSchema(); const Component = this; Instance.prototype.item = function (slot) { const {slots} = this; if (!(slot in slots)) { return undefined; } const instance = this; const proxy = new Proxy(slots[slot], { set(target, property, value) { target[property] = value; if ('qty' === property && value <= 0) { Component.markChange(instance.entity, 'slotChange', {[slot]: false}); } else { Component.markChange(instance.entity, 'slotChange', {[slot]: {[property]: value}}); } return true; }, }); return proxy; }; return Instance; } static schema = new Schema({ type: 'object', properties: { slots: { type: 'map', value: { type: 'object', properties: { quantity: {type: 'uint16'}, source: {type: 'string'}, }, }, }, }, }); } }