2021-12-08 19:26:25 +00:00
|
|
|
import { action } from '@ember/object';
|
|
|
|
import Component from '@glimmer/component';
|
|
|
|
import { tracked } from '@glimmer/tracking';
|
|
|
|
import { task } from 'ember-concurrency';
|
|
|
|
|
|
|
|
const noOp = () => undefined;
|
|
|
|
|
|
|
|
export default class Trigger extends Component {
|
|
|
|
@tracked error = null;
|
|
|
|
@tracked result = null;
|
|
|
|
|
|
|
|
get isBusy() {
|
|
|
|
return this.triggerTask.isRunning;
|
|
|
|
}
|
|
|
|
|
|
|
|
get isIdle() {
|
|
|
|
return this.triggerTask.isIdle;
|
|
|
|
}
|
|
|
|
|
|
|
|
get isSuccess() {
|
2021-12-14 17:56:03 +00:00
|
|
|
return this.triggerTask.last?.isSuccessful;
|
2021-12-08 19:26:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
get isError() {
|
2021-12-14 17:56:03 +00:00
|
|
|
return !!this.error;
|
2021-12-08 19:26:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
get fns() {
|
|
|
|
return {
|
|
|
|
do: this.onTrigger,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
get onError() {
|
|
|
|
return this.args.onError ?? noOp;
|
|
|
|
}
|
|
|
|
|
|
|
|
get onSuccess() {
|
|
|
|
return this.args.onSuccess ?? noOp;
|
|
|
|
}
|
|
|
|
|
|
|
|
get data() {
|
|
|
|
const { isBusy, isIdle, isSuccess, isError, result } = this;
|
|
|
|
return { isBusy, isIdle, isSuccess, isError, result };
|
|
|
|
}
|
|
|
|
|
2021-12-14 17:56:03 +00:00
|
|
|
_reset() {
|
|
|
|
this.result = null;
|
|
|
|
this.error = null;
|
|
|
|
}
|
|
|
|
|
2021-12-08 19:26:25 +00:00
|
|
|
@task(function*() {
|
2021-12-14 17:56:03 +00:00
|
|
|
this._reset();
|
2021-12-08 19:26:25 +00:00
|
|
|
try {
|
|
|
|
this.result = yield this.args.do();
|
|
|
|
this.onSuccess(this.result);
|
|
|
|
} catch (e) {
|
2021-12-14 17:56:03 +00:00
|
|
|
this.error = { Error: e };
|
2021-12-08 19:26:25 +00:00
|
|
|
this.onError(this.error);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
triggerTask;
|
|
|
|
|
|
|
|
@action
|
|
|
|
onTrigger() {
|
|
|
|
this.triggerTask.perform();
|
|
|
|
}
|
|
|
|
}
|