DEV: Allow `@discourseComputed` in native classes (#16097)

(also fixes `writeable` -> `writable` typo)
This commit is contained in:
Jarek Radosz 2022-03-04 17:04:40 +01:00 committed by GitHub
parent dfc19c62f8
commit 94ea1afc43
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 72 additions and 28 deletions

View File

@ -1,16 +1,26 @@
import { computed, get } from "@ember/object";
import EmberObject, { computed, get } from "@ember/object";
import extractValue from "./extract-value";
export default function handleDescriptor(target, key, desc, params = []) {
const val = extractValue(desc);
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,
writeable: desc.writeable,
writable: desc.writable,
initializer() {
let computedDescriptor;
if (desc.writable) {
let val = extractValue(desc);
if (typeof val === "object") {
let value = {};
if (val.get) {
@ -33,6 +43,7 @@ export default function handleDescriptor(target, key, desc, params = []) {
},
};
}
}
function niceAttr(attr) {
const parts = attr.split(".");

View File

@ -1,5 +1,7 @@
import Component from "@ember/component";
import { afterRender } from "discourse-common/utils/decorators";
import discourseComputed, {
afterRender,
} from "discourse-common/utils/decorators";
import componentTest, {
setupRenderingTest,
} from "discourse/tests/helpers/component-test";
@ -29,7 +31,16 @@ const fooComponent = Component.extend({
},
});
discourseModule("utils:decorators", function (hooks) {
class NativeComponent extends Component {
name = "";
@discourseComputed("name")
text(name) {
return `hello, ${name}`;
}
}
discourseModule("Unit | Utils | decorators", function (hooks) {
setupRenderingTest(hooks);
componentTest("afterRender", {
@ -50,4 +61,26 @@ discourseModule("utils:decorators", function (hooks) {
assert.strictEqual(this.baz, 1);
},
});
componentTest("discourseComputed works in native classes", {
template: hbs`<NativeComponent @name="Jarek" />`,
beforeEach() {
Ember.TEMPLATES[
"components/native-component"
] = hbs`<span class="native-component">{{this.text}}</span>`;
this.registry.register("component:native-component", NativeComponent);
},
afterEach() {
delete Ember.TEMPLATES["components/native-component"];
},
test(assert) {
assert.strictEqual(
document.querySelector(".native-component").textContent,
"hello, Jarek"
);
},
});
});