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

68 lines
1.5 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],
emit: function (...args) {
if (this.emit) {
this.emit(...args);
}
},
eq: function(l, r) {
return Vector.equals(l, r);
},
get: function() {
2019-03-21 23:39:09 -05:00
const vector = this[meta.transformProperty(vectorKey)];
if (!vector) {
return [0, 0];
}
return [vector[0], vector[1]];
2019-03-21 23:13:46 -05:00
},
2019-04-07 12:00:24 -05:00
transformProperty: (key) => `$$avocado_property_${key}`,
2019-03-21 23:13:46 -05:00
...meta,
};
meta.set = meta.set || function(vector) {
if (meta.track && meta.emit) {
2019-03-22 11:23:12 -05:00
if (this[vectorKey][0] !== vector[0]) {
meta.emit.call(this, `${x}Changed`, this[vectorKey][0], vector[0]);
2019-03-21 23:13:46 -05:00
}
2019-03-22 11:23:12 -05:00
if (this[vectorKey][1] !== vector[1]) {
meta.emit.call(this, `${y}Changed`, this[vectorKey][1], vector[1]);
2019-03-21 23:13:46 -05:00
}
}
2019-03-21 23:39:09 -05:00
this[meta.transformProperty(vectorKey)] = [vector[0], vector[1]];
2019-03-21 23:13:46 -05:00
}
const decorate = compose(
2019-03-21 23:39:09 -05:00
Property(vectorKey, meta),
2019-03-21 23:13:46 -05:00
);
return (Superclass) => {
return class Vector extends decorate(Superclass) {
get [x]() {
2019-03-21 23:39:09 -05:00
return this[vectorKey][0];
2019-03-21 23:13:46 -05:00
}
set [x](x) {
2019-03-21 23:39:09 -05:00
this[vectorKey] = [x, this[vectorKey][1]];
2019-03-21 23:13:46 -05:00
}
get [y]() {
2019-03-21 23:39:09 -05:00
return this[vectorKey][1];
2019-03-21 23:13:46 -05:00
}
set [y](y) {
2019-03-21 23:39:09 -05:00
this[vectorKey] = [this[vectorKey][0], y];
2019-03-21 23:13:46 -05:00
}
}
};
}