All files / addon/components/modals ember-model.js

5.88% Statements 2/34
6.67% Branches 2/30
14.29% Functions 1/7
6.67% Lines 2/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79                                                                                                              1x 1x                                            
import Component from '@ember/component';
import layout from '../../templates/components/modals/ember-model';
import { alias, or } from '@ember/object/computed';
import { task, didCancel } from 'ember-concurrency';
import { inject as service } from '@ember/service';
import { isPresent, isBlank } from '@ember/utils';
 
 
export default Component.extend({
  layout,
  isSaving: alias('saveTask.isRunning'),
  isCanceling: alias('cancelTask.isRunning'),
  isRunningAsync: or('isSaving', 'isCanceling'),
  disableForm: or('isRunningAsync', 'disabled'),
  isNewModel: alias('model.isNew'),
 
  saveTask: task(function * (beforeSave, afterSave) {
    if (isPresent(beforeSave)) {
      const beforeSaveResponse = yield beforeSave();
      if (!beforeSaveResponse) {
        return false;
      }
    }
    const model = yield this.get('model');
    if (isBlank(model)) { return yield this.set('isOpen', false); }
    yield model.save();
    yield this.set('isOpen', false);
 
    if (isPresent(afterSave)) {
      return yield afterSave();
    } else {
      return true;
    }
  }),
 
  cancelTask: task(function * (afterCancel) {
    const model = yield this.get('model');
    if (isBlank(model)) { return yield this.set('isOpen', false); }
    const modelHasChanges = model.get('isDirty') || model.get('hasDirtyAttributes');
    if (!modelHasChanges || window.confirm('You have unsaved changes. Discard them?')) {
      if (typeof model.rollback === "function") {
        model.rollback();
      } else if (typeof model.rollbackAttributes === "function") {
        model.rollbackAttributes();
      }
      yield this.set('isOpen', false);
      if (isPresent(afterCancel)) {
        return yield afterCancel();
      } else {
        return true;
      }
    }
  }),
 
  didReceiveAttrs() {
    const model = this.get('model');
    Iif(isPresent(model) && typeof model.startTrack === "function") {
      model.startTrack();
    }
  },
 
  actions: {
    save() {
      return this.get('saveTask').perform(
        this.get('beforeSave'),
        this.get('afterSave')
      ).catch(e => {
        if (!didCancel(e)) { throw e; }
      });
    },
 
    close() {
      return this.get('cancelTask').perform(this.get('afterCancel')).catch(e => {
        if (!didCancel(e)) { throw e; }
      });
    },
  },
});