Exemplo n.º 1
0
 unassignedStudentsProxy: computed('unassignedStudents', function(){
   let ap = ArrayProxy.extend(PromiseProxyMixin);
   return ap.create({
     promise: this.unassignedStudents
   });
 }),
Exemplo n.º 2
0
export default ArrayProxy.extend({
  fromJSON(json) {
    if (json && typeOf(json) !== 'object') {
      throw new Error('Vault expects data to be formatted as an JSON object.');
    }
    let contents = Object.keys(json || []).map(key => {
      let obj = {
        name: key,
        value: json[key],
      };
      guidFor(obj);
      return obj;
    });
    this.setObjects(
      contents.sort((a, b) => {
        if (a.name === '') {
          return 1;
        }
        if (b.name === '') {
          return -1;
        }
        return a.name.localeCompare(b.name);
      })
    );
    return this;
  },

  fromJSONString(jsonString) {
    return this.fromJSON(JSON.parse(jsonString));
  },

  toJSON(includeBlanks = false) {
    return this.reduce((obj, item) => {
      if (!includeBlanks && item.value === '' && item.name === '') {
        return obj;
      }
      let val = typeof item.value === 'undefined' ? '' : item.value;
      obj[item.name || ''] = val;
      return obj;
    }, {});
  },

  toJSONString(includeBlanks) {
    return JSON.stringify(this.toJSON(includeBlanks), null, 2);
  },

  isAdvanced() {
    return this.any(item => typeof item.value !== 'string');
  },
});
Exemplo n.º 3
0
/**
 * @module ember-paper
 */
import { Promise } from 'rsvp';

import ArrayProxy from '@ember/array/proxy';
import ObjectProxy from '@ember/object/proxy';
import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';

// See http://emberjs.com/api/data/classes/DS.PromiseArray.html
export const PromiseArray = ArrayProxy.extend(PromiseProxyMixin);
// See http://emberjs.com/api/data/classes/DS.PromiseObject.html
export const PromiseObject = ObjectProxy.extend(PromiseProxyMixin);

export function promiseObject(promise, label) {
  return PromiseObject.create({
    promise: Promise.resolve(promise, label)
  });
}

export function promiseArray(promise, label) {
  return PromiseArray.create({
    promise: Promise.resolve(promise, label)
  });
}
Exemplo n.º 4
0
export default ArrayProxy.extend(Evented, {
  init() {
    this._super(...arguments);

    /**
      The array of client ids backing the record array. When a
      record is requested from the record array, the record
      for the client id at the same index is materialized, if
      necessary, by the store.

      @property content
      @private
      @type Ember.Array
      */
    this.set('content', this.content || null);

    /**
    The flag to signal a `RecordArray` is finished loading data.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isLoaded'); // true
    ```

    @property isLoaded
    @type Boolean
    */
    this.isLoaded = this.isLoaded || false;
      /**
    The flag to signal a `RecordArray` is currently loading data.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isUpdating'); // false
    people.update();
    people.get('isUpdating'); // true
    ```

    @property isUpdating
    @type Boolean
    */
    this.isUpdating = false;

      /**
    The store that created this record array.

    @property store
    @private
    @type DS.Store
    */
    this.store = this.store || null;
    this._updatingPromise = null;
  },

  replace() {
    throw new Error(`The result of a server query (for all ${this.modelName} types) is immutable. To modify contents, use toArray()`);
  },

  /**
   The modelClass represented by this record array.

   @property type
   @type DS.Model
   */
  type: computed('modelName', function() {
    if (!this.modelName) {
      return null;
    }
    return this.store.modelFor(this.modelName);
  }).readOnly(),

  /**
    Retrieves an object from the content by index.

    @method objectAtContent
    @private
    @param {Number} index
    @return {DS.Model} record
  */
  objectAtContent(index) {
    let internalModel = get(this, 'content').objectAt(index);
    return internalModel && internalModel.getRecord();
  },

  /**
    Used to get the latest version of all of the records in this array
    from the adapter.

    Example

    ```javascript
    var people = store.peekAll('person');
    people.get('isUpdating'); // false

    people.update().then(function() {
      people.get('isUpdating'); // false
    });

    people.get('isUpdating'); // true
    ```

    @method update
  */
  update() {
    if (get(this, 'isUpdating')) { return this._updatingPromise; }

    this.set('isUpdating', true);

    let updatingPromise = this._update().finally(() => {
      this._updatingPromise = null;
      if (this.get('isDestroying') || this.get('isDestroyed')) { return }
      this.set('isUpdating', false);
    });

    this._updatingPromise = updatingPromise;

    return updatingPromise;
  },

  /*
    Update this RecordArray and return a promise which resolves once the update
    is finished.
   */
  _update() {
    return this.store.findAll(this.modelName, { reload: true });
  },

  /**
    Adds an internal model to the `RecordArray` without duplicates

    @method _pushInternalModels
    @private
    @param {InternalModel} internalModel
  */
  _pushInternalModels(internalModels) {
    // pushObjects because the internalModels._recordArrays set was already
    // consulted for inclusion, so addObject and its on .contains call is not
    // required.
    get(this, 'content').pushObjects(internalModels);
  },

  /**
    Removes an internalModel to the `RecordArray`.

    @method removeInternalModel
    @private
    @param {InternalModel} internalModel
  */
  _removeInternalModels(internalModels) {
    get(this, 'content').removeObjects(internalModels);
  },

  /**
    Saves all of the records in the `RecordArray`.

    Example

    ```javascript
    var messages = store.peekAll('message');
    messages.forEach(function(message) {
      message.set('hasBeenSeen', true);
    });
    messages.save();
    ```

    @method save
    @return {DS.PromiseArray} promise
  */
  save() {
    let promiseLabel = `DS: RecordArray#save ${this.modelName}`;
    let promise = Promise.all(this.invoke('save'), promiseLabel)
      .then(() => this, null, 'DS: RecordArray#save return RecordArray');

    return PromiseArray.create({ promise });
  },

  _dissociateFromOwnRecords() {
    this.get('content').forEach(internalModel => {
      let recordArrays = internalModel.__recordArrays;

      if (recordArrays) {
        recordArrays.delete(this);
      }
    });
  },

  /**
    @method _unregisterFromManager
    @private
  */
  _unregisterFromManager() {
    this.manager.unregisterRecordArray(this);
  },

  willDestroy() {
    this._unregisterFromManager();
    this._dissociateFromOwnRecords();
    // TODO: we should not do work during destroy:
    //   * when objects are destroyed, they should simply be left to do
    //   * if logic errors do to this, that logic needs to be more careful during
    //    teardown (ember provides isDestroying/isDestroyed) for this reason
    //   * the exception being: if an dominator has a reference to this object,
    //     and must be informed to release e.g. e.g. removing itself from th
    //     recordArrayMananger
    set(this, 'content', null);
    set(this, 'length', 0);
    this._super(...arguments);
  },

  /*
    @method _createSnapshot
    @private
  */
  _createSnapshot(options) {
    // this is private for users, but public for ember-data internals
    return new SnapshotRecordArray(this, this.get('meta'), options);
  },

  /*
    @method _takeSnapshot
    @private
  */
  _takeSnapshot() {
    return get(this, 'content').map(internalModel => internalModel.createSnapshot());
  }
});
Exemplo n.º 5
0
const StatefulArray = ArrayProxy.extend(Copyable, {
  /**
    A reference to the array's owner record.

    @property owner
    @type {DS.Model}
  */
  owner: null,

  /**
    The array's property name on the owner record.

    @property name
    @private
    @type {String}
  */
  name: null,

  init() {
    this._super(...arguments);
    this._pendingData = undefined;
    set(this, '_originalState', []);
  },

  content: computed(function() {
    return A();
  }),

  /**
    Copies the array by calling copy on each of its members.

    @method copy
    @return {array} a new array
  */
  copy() {
    return this.map(copy);
  },

  /**
    @method setupData
    @private
    @param {Object} data
  */
  setupData(data) {
    // Since replacing the contents of the array can trigger changes to fragment
    // array properties, this method can get invoked recursively with the same
    // data, so short circuit here once it's been setup the first time
    if (this._pendingData === data) {
      return;
    }

    this._pendingData = data;

    let processedData = this._normalizeData(makeArray(data));
    let content = get(this, 'content');

    // This data is canonical, so create rollback point
    set(this, '_originalState', processedData);

    // Completely replace the contents with the new data
    content.replace(0, get(content, 'length'), processedData);

    this._pendingData = undefined;
  },

  /**
    @method _normalizeData
    @private
    @param {Object} data
  */
  _normalizeData(data) {
    return data;
  },

  /**
    @method _createSnapshot
    @private
  */
  _createSnapshot() {
    // Since elements are not models, a snapshot is simply a mapping of raw values
    return this.toArray();
  },

  /**
    @method _flushChangedAttributes
  */
  _flushChangedAttributes() {},

  /**
    @method _adapterDidCommit
    @private
  */
  _adapterDidCommit(data) {
    if (data) {
      this.setupData(data);
    } else {
      // Fragment array has been persisted; use the current state as the original state
      set(this, '_originalState', this.toArray());
    }
  },

  _adapterDidError(/* error */) {
    // No-Op
  },

  /**
    If this property is `true` the contents of the array do not match its
    original state. The array has local changes that have not yet been saved by
    the adapter. This includes additions, removals, and reordering of elements.

    Example

    ```javascript
    array.toArray(); // [ 'Tom', 'Yehuda' ]
    array.get('isDirty'); // false
    array.popObject(); // 'Yehuda'
    array.get('isDirty'); // true
    ```

    @property hasDirtyAttributes
    @type {Boolean}
    @readOnly
  */
  hasDirtyAttributes: computed('[]', '_originalState', function() {
    return compare(this.toArray(), get(this, '_originalState')) !== 0;
  }),

  /**
    This method reverts local changes of the array's contents to its original
    state.

    Example

    ```javascript
    array.toArray(); // [ 'Tom', 'Yehuda' ]
    array.popObject(); // 'Yehuda'
    array.toArray(); // [ 'Tom' ]
    array.rollbackAttributes();
    array.toArray(); // [ 'Tom', 'Yehuda' ]
    ```

    @method rollbackAttributes
  */
  rollbackAttributes() {
    this.setObjects(get(this, '_originalState'));
  },

  /**
    Method alias for `toArray`.

    @method serialize
    @return {Array}
  */
  serialize() {
    return this.toArray();
  },

  arrayContentDidChange() {
    this._super(...arguments);

    let record = get(this, 'owner');
    let key = get(this, 'name');

    // Any change to the size of the fragment array means a potential state change
    if (get(this, 'hasDirtyAttributes')) {
      fragmentDidDirty(record, key, this);
    } else {
      fragmentDidReset(record, key);
    }
  },

  toStringExtension() {
    let ownerId = get(this, 'owner.id');
    return `owner(${ownerId})`;
  }
});
Exemplo n.º 6
0
import ArrayProxy from '@ember/array/proxy';
import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';

export default ArrayProxy.extend(PromiseProxyMixin);
export default ArrayProxy.extend({
  init() {
    this.set('content', []);
    this.set('source', new ol.source.Vector());

    this._super(...arguments);
  },

  /**
   * Calculates the bounds of all flights in the collection.
   * @return {ol.extent}
   */
  getBounds() {
    return this.source.getExtent();
  },

  /**
   * Returns the minimum and maximum fix time within the extent.
   * Code based on ol.render.canvas.Replay.prototype.appendFlatCoordinates.
   * @param {ol.extent} extent
   * @return {Object}
   */
  getMinMaxTimeInExtent(extent) {
    let min = Infinity;
    let max = -Infinity;

    let total_min = Infinity;
    let total_max = -Infinity;

    this.source.forEachFeatureInExtent(extent, feature => {
      let coordinates = feature.getGeometry().getCoordinates();

      let lastCoord = coordinates[0];
      let nextCoord = null;
      let end = coordinates.length;

      let lastRel = ol.extent.containsCoordinate(extent, lastCoord);

      total_min = Math.min(total_min, lastCoord[3]);

      if (lastRel === true) {
        min = Math.min(lastCoord[3], min);
      }

      for (let i = 1; i < end; i += 1) {
        nextCoord = coordinates[i];

        let nextRel = ol.extent.containsCoordinate(extent, nextCoord);

        // current vector completely within extent. do nothing.
        // current vector completely outside extent. do nothing.

        // last vertice was inside extent, next one is outside.
        if (lastRel && !nextRel) {
          max = Math.max(nextCoord[3], max);
          lastRel = nextRel;
        } else if (!lastRel && nextRel) {
          // last vertice was outside extent, next one is inside
          min = Math.min(lastCoord[3], min);
        }

        lastCoord = nextCoord;
        lastRel = nextRel;
      }

      if (lastRel === true) {
        max = Math.max(lastCoord[3], max);
      }

      total_max = Math.max(total_max, lastCoord[3]);
    });

    if (min === Infinity) {
      min = total_min;
    }
    if (max === -Infinity) {
      max = total_max;
    }

    return { min, max };
  },

  arrayContentWillChange(offset, removeCount) {
    this._super(...arguments);

    let flights = this.content;
    let removedFlights = flights.slice(offset, offset + removeCount);

    let source = this.source;
    removedFlights.forEach(flight => {
      let id = flight.get('id');

      this.source
        .getFeatures()
        .filter(feature => feature.get('sfid') === id)
        .forEach(feature => source.removeFeature(feature));
    });
  },

  arrayContentDidChange(offset, removeCount, addCount) {
    let flights = this.content;
    let addedFlights = flights.slice(offset, offset + addCount);

    let source = this.source;
    addedFlights.forEach(flight => {
      let feature = new ol.Feature({
        geometry: flight.get('geometry'),
        sfid: flight.get('id'),
        color: flight.get('color'),
        type: 'flight',
      });

      source.addFeature(feature);
    });

    this._super(...arguments);
  },
});