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