2022-03-05 00:04:40 +08:00
|
|
|
import EmberObject, { computed, get } from "@ember/object";
|
2020-04-28 22:14:49 +08:00
|
|
|
import extractValue from "./extract-value";
|
|
|
|
|
|
|
|
export default function handleDescriptor(target, key, desc, params = []) {
|
2022-03-05 00:04:40 +08:00
|
|
|
const val = extractValue(desc);
|
2020-04-28 22:14:49 +08:00
|
|
|
|
2022-03-05 00:04:40 +08:00
|
|
|
if (typeof val === "function" && target instanceof EmberObject) {
|
|
|
|
// We're in a native class, so convert the method to a getter first
|
|
|
|
desc.writable = false;
|
|
|
|
desc.initializer = undefined;
|
|
|
|
desc.value = undefined;
|
|
|
|
desc.get = callUserSuppliedGet(params, val);
|
|
|
|
|
|
|
|
return computed(target, key, desc);
|
|
|
|
} else {
|
|
|
|
return {
|
|
|
|
enumerable: desc.enumerable,
|
|
|
|
configurable: desc.configurable,
|
|
|
|
writable: desc.writable,
|
|
|
|
initializer() {
|
|
|
|
let computedDescriptor;
|
|
|
|
|
|
|
|
if (desc.writable) {
|
|
|
|
if (typeof val === "object") {
|
|
|
|
let value = {};
|
|
|
|
if (val.get) {
|
|
|
|
value.get = callUserSuppliedGet(params, val.get);
|
|
|
|
}
|
|
|
|
if (val.set) {
|
|
|
|
value.set = callUserSuppliedSet(params, val.set);
|
|
|
|
}
|
|
|
|
computedDescriptor = value;
|
|
|
|
} else {
|
|
|
|
computedDescriptor = callUserSuppliedGet(params, val);
|
2020-04-28 22:14:49 +08:00
|
|
|
}
|
|
|
|
} else {
|
2022-03-05 00:04:40 +08:00
|
|
|
throw new Error(
|
|
|
|
"ember-computed-decorators does not support using getters and setters"
|
|
|
|
);
|
2020-04-28 22:14:49 +08:00
|
|
|
}
|
|
|
|
|
2022-03-05 00:04:40 +08:00
|
|
|
return computed.apply(null, params.concat(computedDescriptor));
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
2020-04-28 22:14:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
function niceAttr(attr) {
|
|
|
|
const parts = attr.split(".");
|
|
|
|
let i;
|
|
|
|
|
|
|
|
for (i = 0; i < parts.length; i++) {
|
|
|
|
if (
|
|
|
|
parts[i] === "@each" ||
|
|
|
|
parts[i] === "[]" ||
|
|
|
|
parts[i].indexOf("{") !== -1
|
|
|
|
) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return parts.slice(0, i).join(".");
|
|
|
|
}
|
|
|
|
|
|
|
|
function callUserSuppliedGet(params, func) {
|
|
|
|
params = params.map(niceAttr);
|
|
|
|
return function () {
|
|
|
|
let paramValues = params.map((p) => get(this, p));
|
|
|
|
|
|
|
|
return func.apply(this, paramValues);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function callUserSuppliedSet(params, func) {
|
|
|
|
params = params.map(niceAttr);
|
|
|
|
return function (key, value) {
|
|
|
|
let paramValues = params.map((p) => get(this, p));
|
|
|
|
paramValues.unshift(value);
|
|
|
|
|
|
|
|
return func.apply(this, paramValues);
|
|
|
|
};
|
|
|
|
}
|