avocado-old/packages/math/vector/mixin.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-03-21 23:13:46 -05:00
import {compose} from '@avocado/core';
import {Mixin, Property} from '@avocado/mixins'
2019-03-28 12:50:40 -05:00
import * as Vector from './index'
2019-03-21 23:13:46 -05:00
export function VectorMixin(
2019-03-21 23:39:09 -05:00
vectorKey = 'vector',
2019-03-21 23:13:46 -05:00
x = 'x',
y = 'y',
meta = {},
) {
meta = {
default: [0, 0],
eq: function(l, r) {
return Vector.equals(l, r);
},
...meta,
};
2019-04-12 16:30:22 -05:00
let transformedProperty;
if (meta.transformProperty) {
transformedProperty = meta.transformProperty(vectorKey);
}
else {
transformedProperty = `$$avocado_property_${vectorKey}`;
}
meta.initialize = function() {
this[transformedProperty] = Vector.copy(meta.default);
};
let bypassUpdates = false;
2019-03-21 23:13:46 -05:00
meta.set = meta.set || function(vector) {
2019-04-12 16:30:22 -05:00
this[transformedProperty] = Vector.copy(this[transformedProperty]);
if (bypassUpdates) {
this[transformedProperty][0] = vector[0];
this[transformedProperty][1] = vector[1];
2019-03-21 23:13:46 -05:00
}
2019-04-12 16:30:22 -05:00
else {
this[x] = vector[0];
this[y] = vector[1];
}
};
2019-03-21 23:13:46 -05:00
const decorate = compose(
2019-04-12 16:30:22 -05:00
Property(x, {
get: function() {
return this[transformedProperty][0];
},
set: function(value) {
bypassUpdates = true;
this[vectorKey] = [value, this[y]];
bypassUpdates = false;
},
track: meta.track,
}),
Property(y, {
get: function() {
return this[transformedProperty][1];
},
set: function(value) {
bypassUpdates = true;
this[vectorKey] = [this[x], value];
bypassUpdates = false;
},
track: meta.track,
}),
2019-03-21 23:39:09 -05:00
Property(vectorKey, meta),
2019-03-21 23:13:46 -05:00
);
return (Superclass) => {
2019-04-12 16:30:22 -05:00
return class Vector extends decorate(Superclass) {}
2019-03-21 23:13:46 -05:00
};
}