baja/tag/ComponentRelations.js

/**
 * @copyright 2015 Tridium, Inc. All Rights Reserved.
 * @author Gareth Johnson
 */

/**
 * @module baja/tag/ComponentRelations
 */
define([ "bajaScript/sys",
        "bajaScript/baja/ord/SlotPath",
        "bajaScript/baja/comp/Flags",
        "bajaScript/baja/tag/Id",
        "bajaScript/baja/tag/Relation",
        "bajaScript/baja/tag/ComponentTags" ], function (
        baja,
        SlotPath,
        Flags,
        Id,
        Relation,
        ComponentTags) {
  
  "use strict";
     
  /**
   * Relations is used to access the direct relations on a Component instance.
   *
   * @class
   * @alias module:baja/tag/ComponentRelations
   *
   * @param {baja.Component} owner The Component instance owner.
   */  
  var ComponentRelations = function ComponentRelations(owner) {
    this.$owner = owner;
  };

  /**
   * @returns {Boolean} Returns true if there are no relation objects.
   */
  ComponentRelations.prototype.isEmpty = function () {
    return this.getAll().length === 0;
  };

  /**
   * Find the specified relation object via its Id and return it.
   * If the relation can't be found then return null.
   * 
   * @param  {String|module:baja/tag/Id} id The Id
   * used for the search. This can be an Id or a qname for an Id.
   * @returns {module:baja/tag/BRelation} The Relation object
   * or null if nothing can be found.
   */
  ComponentRelations.prototype.get = function (id) {
    var slotName = ComponentTags.idToSlotName(id);
    return this.isRelationSlot(slotName) ? this.$owner.get(slotName) : null;
  };

  /**
   * Returns a copy of the contained Relations array.
   * 
   * @returns {Array<module:baja/tag/BRelation>} An array of Relation objects.
   */
  ComponentRelations.prototype.getAll = function () {
    var that = this;

    return that.$owner
      .getSlots()
      .filter(function (slot) {
        // Filter to all relation Slots
        return that.isRelationSlot(slot);
      })
      .toValueArray();
  };

  /**
   * Returns true if the specified Slot is a relation.
   * 
   * @param {baja.Slot|String} slot The Slot (or slot name) that's tested
   * to see if it's a relation Slot.
   * @returns {Boolean} Returns true if the Slot is a Relation.
   */
  ComponentRelations.prototype.isRelationSlot = function (slot) {
    var owner = this.$owner;

    slot = owner.getSlot(slot);

    return slot && 
      slot.isProperty() && 
      (owner.getFlags(slot) & Flags.TRANSIENT) !== Flags.TRANSIENT &&
      owner.get(slot).getType().is("baja:Relation");
  };

  return ComponentRelations;
});