silphius/app/ecs-components/inventory.js
2024-06-24 06:18:58 -05:00

87 lines
2.3 KiB
JavaScript

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});
delete slots[slot];
}
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'},
},
},
},
},
});
}
}