<commit_before>var _ = require('underscore');
var BaseAnalysisFormModel = require('./base-analysis-form-model');
var template = require('./aggregate-intersection-form.tpl');
var ColumnOptions = require('../column-options');
var AGGREGATE_FORMAT_FIELDS_NAMES = [
  'type',
  'aggregate_column',
  'aggregate_function'
];

/**
 * Form model for the aggregate intersection analysis
 */
module.exports = BaseAnalysisFormModel.extend({
  parse: function (attrs) {
    if (!attrs.aggregate_column) {
      attrs.aggregate_column = 'cartodb_id';
    }
    if (!attrs.aggregate_function) {
      attrs.aggregate_function = 'count';
    }
    attrs.aggregate = {
      operator: attrs.aggregate_function,
      attribute: attrs.aggregate_function === 'count' ? '' : attrs.aggregate_column
    };
    return attrs;
  },

  initialize: function () {
    BaseAnalysisFormModel.prototype.initialize.apply(this, arguments);

    this._columnOptions = new ColumnOptions({}, {
      configModel: this._configModel
    });

    this.listenTo(this._analysisSourceOptionsModel, 'change:fetching', this._setSchema);
    this.listenTo(this._columnOptions, 'columnsFetched', this._setSchema);

    this.on('change:aggregate', this._onChangeAggregate, this);
    this.on('change:target', this._onChangeTarget, this);

    this._setSchema();
    this._fetchColumns();
  },

  _formatAttrs: function (formAttrs) {
    var customFormattedFormAttrs = _.pick(formAttrs, ['id', 'source', 'target'].concat(AGGREGATE_FORMAT_FIELDS_NAMES));
    return BaseAnalysisFormModel.prototype._formatAttrs.call(this, customFormattedFormAttrs);
  },

  getTemplate: function () {
    return template;
  },

  getTemplateData: function () {
    return {
      dataFields: 'aggregate'
    };
  },

  _filterSchemaFieldsByType: function (schema) {
    // Always include the source and target fields in addition to the type-specific fields
    return _.pick(schema, ['source', 'target', 'aggregate']);
  },

  /**
   * @override {BaseAnalysisFormModel._setSchema}
   */
  _setSchema: function () {
    BaseAnalysisFormModel.prototype._setSchema.call(this, this._filterSchemaFieldsByType({
      source: this._primarySourceSchemaItem(),
      target: {
        type: 'NodeDataset',
        title: _t('editor.layers.analysis-form.target'),
        options: this._getSourceOptionsForSource('target'),
        validators: ['required'],
        editorAttrs: {
          disabled: this._isSourceDisabled('target')
        }
      },
      aggregate: {
        type: 'Operators',
        title: _t('editor.layers.analysis-form.operation'),
        options: this._columnOptions.filterByType('number')
      }
    }));
  },

  _onChangeAggregate: function () {
    var aggregate = this.get('aggregate');
    this.set({
      aggregate_column: aggregate.attribute || 'cartodb_id',
      aggregate_function: aggregate.operator
    });
  },

  _onChangeTarget: function () {
    this.set('aggregate', {
      operator: 'count',
      attribute: ''
    });
    this._analysisSourceOptionsModel.createSourceNodeUnlessExisting(this.get('target'));
    this._fetchColumns();
  },

  _fetchColumns: function () {
    var target = this.get('target');
    var nodeDefModel = this._layerDefinitionModel.findAnalysisDefinitionNodeModel(target);

    if (nodeDefModel) {
      this._columnOptions.setNode(nodeDefModel);
    } else if (target) {
      this._columnOptions.setDataset(target);
    }
  },

  _isSourceDisabled: function (sourceAttrName) {
    return this._isPrimarySource(sourceAttrName) || this._isFetchingOptions();
  },

  _isPrimarySource: function (sourceAttrName) {
    return sourceAttrName === this.get('primary_source_name');
  },

  _isFetchingOptions: function () {
    return this._analysisSourceOptionsModel.get('fetching');
  },

  _getSourceOptionsForSource: function (sourceAttrName) {
    var currentSource = this.get(sourceAttrName);

    if (this._isPrimarySource(sourceAttrName)) {
      return [currentSource];
    } else if (this._isFetchingOptions()) {
      return [{
        val: currentSource,
        label: _t('editor.layers.analysis-form.loading'),
        isLoading: true
      }];
    } else {
      // fetched
      var sourceId = this._layerDefinitionModel.get('source');
      return this._analysisSourceOptionsModel
        .filter(function (d) {
          // Can't select own layer as source, so exclude it
          return d.val !== sourceId;
        });
    }
  }
});
<commit_msg>Fixing problem with aggregate-intersection-form<commit_after>var _ = require('underscore');
var BaseAnalysisFormModel = require('./base-analysis-form-model');
var template = require('./aggregate-intersection-form.tpl');
var ColumnOptions = require('../column-options');
var AGGREGATE_FORMAT_FIELDS_NAMES = [
  'type',
  'aggregate_column',
  'aggregate_function'
];

/**
 * Form model for the aggregate intersection analysis
 */
module.exports = BaseAnalysisFormModel.extend({
  parse: function (attrs) {
    if (!attrs.aggregate_column) {
      attrs.aggregate_column = 'cartodb_id';
    }
    if (!attrs.aggregate_function) {
      attrs.aggregate_function = 'count';
    }
    attrs.aggregate = {
      operator: attrs.aggregate_function,
      attribute: attrs.aggregate_function === 'count' ? '' : attrs.aggregate_column
    };
    return attrs;
  },

  initialize: function () {
    BaseAnalysisFormModel.prototype.initialize.apply(this, arguments);

    this._columnOptions = new ColumnOptions({}, {
      configModel: this._configModel
    });

    this.listenTo(this._analysisSourceOptionsModel, 'change:fetching', this._setSchema);
    this.listenTo(this._columnOptions, 'columnsFetched', this._setSchema);

    this.on('change:aggregate', this._onChangeAggregate, this);
    this.on('change:target', this._onChangeTarget, this);

    this._setSchema();
    this._fetchColumns();
  },

  _formatAttrs: function (formAttrs) {
    var customFormattedFormAttrs = _.pick(formAttrs, ['id', 'source', 'target'].concat(AGGREGATE_FORMAT_FIELDS_NAMES));
    return BaseAnalysisFormModel.prototype._formatAttrs.call(this, customFormattedFormAttrs);
  },

  getTemplate: function () {
    return template;
  },

  getTemplateData: function () {
    return {
      dataFields: 'aggregate'
    };
  },

  _filterSchemaFieldsByType: function (schema) {
    // Always include the source and target fields in addition to the type-specific fields
    return _.pick(schema, ['source', 'target', 'aggregate']);
  },

  /**
   * @override {BaseAnalysisFormModel._setSchema}
   */
  _setSchema: function () {
    BaseAnalysisFormModel.prototype._setSchema.call(this, this._filterSchemaFieldsByType({
      source: this._primarySourceSchemaItem(),
      target: {
        type: 'NodeDataset',
        title: _t('editor.layers.analysis-form.target'),
        options: this._getSourceOptionsForSource('target', ['point', 'line', 'polygon']),
        validators: ['required'],
        editorAttrs: {
          disabled: this._isSourceDisabled('target')
        }
      },
      aggregate: {
        type: 'Operators',
        title: _t('editor.layers.analysis-form.operation'),
        options: this._columnOptions.filterByType('number')
      }
    }));
  },

  _onChangeAggregate: function () {
    var aggregate = this.get('aggregate');
    this.set({
      aggregate_column: aggregate.attribute || 'cartodb_id',
      aggregate_function: aggregate.operator
    });
  },

  _onChangeTarget: function () {
    this.set('aggregate', {
      operator: 'count',
      attribute: ''
    });
    this._analysisSourceOptionsModel.createSourceNodeUnlessExisting(this.get('target'));
    this._fetchColumns();
  },

  _fetchColumns: function () {
    var target = this.get('target');
    var nodeDefModel = this._layerDefinitionModel.findAnalysisDefinitionNodeModel(target);

    if (nodeDefModel) {
      this._columnOptions.setNode(nodeDefModel);
    } else if (target) {
      this._columnOptions.setDataset(target);
    }
  },

  _isSourceDisabled: function (sourceAttrName) {
    return this._isPrimarySource(sourceAttrName) || this._isFetchingOptions();
  },

  _isPrimarySource: function (sourceAttrName) {
    return sourceAttrName === this.get('primary_source_name');
  },

  _isFetchingOptions: function () {
    return this._analysisSourceOptionsModel.get('fetching');
  },

  _getSourceOptionsForSource: function (sourceAttrName, requiredSimpleGeometryType) {
    var currentSource = this.get(sourceAttrName);

    if (this._isPrimarySource(sourceAttrName)) {
      return [currentSource];
    } else if (this._isFetchingOptions()) {
      return [{
        val: currentSource,
        label: _t('editor.layers.analysis-form.loading'),
        isLoading: true
      }];
    } else {
      // fetched
      var sourceId = this._layerDefinitionModel.get('source');
      return this._analysisSourceOptionsModel
        .getSelectOptions(requiredSimpleGeometryType)
        .filter(function (d) {
          // Can't select own layer as source, so exclude it
          return d.val !== sourceId;
        });
    }
  }
});
<|endoftext|>


<commit_before>Ui.Element.extend('Ui.Label',
/**@lends Ui.Label#*/
{
	text: '',
	orientation: 'horizontal',
	fontSize: undefined,
	fontFamily: undefined,
	fontWeight: undefined,
	color: undefined,
	labelDrawing: undefined,
	textMeasureValid: false,
	textWidth: 0,
	textHeight: 0,

    /**
     * @constructs
	 * @class A label is a graphical element that display a Text and which will take all the place it could to display it on one row.
     * @extends Ui.Element
     * @param {String} [config.text] Label's text
     * @param {Number} [config.fontSize]
     * @param {String} [config.fontFamily]
     * @param {String} [config.fontWeight] CSS fontWeight property ['normal', 'bold', Number]
     * @param {String} [config.color]
     * @param {String} [config.orientation]
	 * @param {mixed} [config] see {@link Ui.Element} constructor for more options.
     */
	constructor: function(config) {
		this.setSelectable(false);
	},

	getText: function() {
		return this.text;
	},

	setText: function(text) {
		if(this.text != text) {
			this.text = text;
			if('textContent' in this.labelDrawing)
				this.labelDrawing.textContent = this.text;
			else
				this.labelDrawing.innerText = this.text;
			this.textMeasureValid = false;
			this.invalidateMeasure();
		}
	},

	setFontSize: function(fontSize) {
		if(this.fontSize !== fontSize) {
			this.fontSize = fontSize;
			this.labelDrawing.style.fontSize = this.getFontSize()+'px';
			this.textMeasureValid = false;
			this.invalidateMeasure();
		}
	},

	getFontSize: function() {
		if(this.fontSize !== undefined)
			return this.fontSize;
		else
			return this.getStyleProperty('fontSize');
	},

	setFontFamily: function(fontFamily) {
		if(this.fontFamily !== fontFamily) {
			this.fontFamily = fontFamily;
			this.labelDrawing.style.fontFamily = this.getFontFamily();
			this.textMeasureValid = false;
			this.invalidateMeasure();
		}
	},

	getFontFamily: function() {
		if(this.fontFamily !== undefined)
			return this.fontFamily;
		else
			return this.getStyleProperty('fontFamily');
	},

	setFontWeight: function(fontWeight) {
		if(this.fontWeight !== fontWeight) {
			this.fontWeight = fontWeight;
			this.labelDrawing.style.fontWeight = this.getFontWeight();
			this.textMeasureValid = false;
			this.invalidateMeasure();
		}
	},

	getFontWeight: function() {
		if(this.fontWeight !== undefined)
			return this.fontWeight;
		else
			return this.getStyleProperty('fontWeight');
	},

	setColor: function(color) {
		if(this.color !== color) {
			this.color = Ui.Color.create(color);
			if(navigator.supportRgba)
				this.labelDrawing.style.color = this.getColor().getCssRgba();
			else
				this.labelDrawing.style.color = this.getColor().getCssHtml();
		}
	},

	getColor: function() {
		if(this.color !== undefined)
			return this.color;
		else
			return Ui.Color.create(this.getStyleProperty('color'));
	},

	getOrientation: function() {
		return this.orientation;
	},

	setOrientation: function(orientation) {
		if(this.orientation != orientation) {
			this.orientation = orientation;
			this.invalidateMeasure();
		}
	}
},
/**@lends Ui.Label#*/
{
	verticalAlign: 'center',
	horizontalAlign: 'center',

	onStyleChange: function() {
		this.labelDrawing.style.fontSize = this.getFontSize()+'px';
		this.labelDrawing.style.fontFamily = this.getFontFamily();
		this.labelDrawing.style.fontWeight = this.getFontWeight();
		if(navigator.supportRgba)
			this.labelDrawing.style.color = this.getColor().getCssRgba();
		else
			this.labelDrawing.style.color = this.getColor().getCssHtml();
		this.textMeasureValid = false;
		this.invalidateMeasure();
	},

	renderDrawing: function() {
		/**#nocode+ Avoid Jsdoc warnings...*/
		this.labelDrawing = document.createElement('div');
		this.labelDrawing.style.whiteSpace = 'nowrap';
		this.labelDrawing.style.display = 'inline';
		this.labelDrawing.style.position = 'absolute';
		this.labelDrawing.style.left = '0px';
		this.labelDrawing.style.top = '0px';
		return this.labelDrawing;
		/**#nocode- Avoid Jsdoc warnings...*/
	},

	measureCore: function(width, height) {
		if(!this.textMeasureValid) {
			this.textMeasureValid = true;
			var size = Ui.Label.measureText(this.text, this.getFontSize(), this.getFontFamily(), this.getFontWeight());
			this.textWidth = size.width;
			this.textHeight = size.height;
		}
		if(this.orientation == 'vertical')
			return { width: this.textHeight, height: this.textWidth };
		else
			return { width: this.textWidth, height: this.textHeight };
	},

	arrangeCore: function(width, height) {
		var matrix;
		if(this.orientation == 'vertical') {
			matrix = Ui.Matrix.createTranslate(this.labelDrawing.offsetHeight, 0);
			matrix.rotate(90);
			if(navigator.isIE) {
				this.labelDrawing.style.msTransform = matrix.toString();
				this.labelDrawing.style.msTransformOrigin = '0% 0%';
			}
			else if(navigator.isGecko) {
				this.labelDrawing.style.MozTransform = 'matrix('+matrix.svgMatrix.a.toFixed(4)+', '+matrix.svgMatrix.b.toFixed(4)+', '+matrix.svgMatrix.c.toFixed(4)+', '+matrix.svgMatrix.d.toFixed(4)+', '+matrix.svgMatrix.e.toFixed(0)+'px, '+matrix.svgMatrix.f.toFixed(0)+'px)';
				this.labelDrawing.style.MozTransformOrigin = '0% 0%';
			}
			else if(navigator.isWebkit) {
				this.labelDrawing.style.webkitTransform = matrix.toString();
				this.labelDrawing.style.webkitTransformOrigin = '0% 0%';
			}
			else if(navigator.isOpera) {
				this.labelDrawing.style.OTransform = matrix.toString();
				this.labelDrawing.style.OTransformOrigin = '0% 0%';
			}
		}
		else {
			if(navigator.isIE && ('removeProperty' in this.labelDrawing))
				this.labelDrawing.style.removeProperty('-ms-transform');
			else if(navigator.isGecko)
				this.labelDrawing.style.removeProperty('-moz-transform');
			else if(navigator.isWebkit)
				this.labelDrawing.style.removeProperty('-webkit-transform');
			else if(navigator.isOpera)
				this.labelDrawing.style.removeProperty('-o-transform');
		}
	}
},
/**@lends Ui.Label*/
{
	measureBox: undefined,
	measureContext: undefined,

	measureTextCanvas: function(text, fontSize, fontFamily, fontWeight) {
		if(Ui.Label.measureBox === undefined)
			this.createMeasureCanvas();
		Ui.Label.measureContext.font = 'normal '+fontWeight+' '+fontSize+'px '+fontFamily;
		var res = Ui.Label.measureContext.measureText(text);
		res.height = fontSize;
		return res;
	},

	createMeasureCanvas: function() {
		var measureWindow = window;
		if(navigator.isIE || navigator.isGecko)
			measureWindow = Ui.App.getRootWindow();

		if(measureWindow.document.body === undefined) {
			var body = measureWindow.document.createElement('body');
			measureWindow.document.body = body;
		}
		Ui.Label.measureBox = measureWindow.document.createElement('canvas');
		Ui.Label.measureBox.style.visibility = 'hidden';
		Ui.Label.measureBox.style.position = 'absolute';
		Ui.Label.measureBox.style.left = '0px';
		Ui.Label.measureBox.style.top = '0px';
		Ui.Label.measureBox.style.outline = 'none';
		Ui.Label.measureBox.setAttribute('width', 10, null);
		Ui.Label.measureBox.setAttribute('height', 10, null);
		measureWindow.document.body.appendChild(Ui.Label.measureBox);
		Ui.Label.measureContext = Ui.Label.measureBox.getContext('2d');
	},

	isFontAvailable: function(fontFamily, fontWeight) {
		var i;
		if(!navigator.supportCanvas)
			return true;
		if(Ui.Label.measureBox === undefined)
			Ui.Label.createMeasureCanvas();
		var ctx = Ui.Label.measureContext;
		ctx.fillStyle = 'rgba(0,0,0,0)';
		ctx.clearRect(0, 0, 10, 10);
		ctx.textBaseline = 'top';
		//console.log('isFontAvailable('+fontFamily+','+fontWeight+')');
		// draw with the wanted font
		ctx.font = 'normal '+fontWeight+' 10px '+fontFamily;
		ctx.fillStyle = 'rgba(255,255,255,1)';
		ctx.fillText('@', 0, 0);
		var wantedImageData = ctx.getImageData(0,0,10,10);
		var empty = true;
		for(i = 0; empty && (i < wantedImageData.data.length); i += 4) {
			if(wantedImageData.data[i+3] !== 0)
				empty = false;
		}
		if(empty)
			return false;
		// draw with a local font
		ctx.fillStyle = 'rgba(0,0,0,0)';
		ctx.clearRect(0, 0, 10, 10);
		ctx.fillStyle = 'rgba(255,255,255,1)';
		ctx.font = 'normal '+fontWeight+' 10px Sans-Serif';
		ctx.fillText('@', 0, 0);
		var refImageData = ctx.getImageData(0,0,10,10);
		// draw with wanted font fallback local font
		ctx.fillStyle = 'rgba(0,0,0,0)';
		ctx.clearRect(0, 0, 10, 10);
		ctx.fillStyle = 'rgba(255,255,255,1)';
		ctx.font = 'normal '+fontWeight+' 10px '+fontFamily+',Sans-Serif';
		ctx.fillText('@', 0, 0);
		// test if images are differents
		var imageData = ctx.getImageData(0,0,10,10);
		for(i = 0; i < imageData.data.length; i += 4) {
			if(imageData.data[i+3] !== refImageData.data[i+3])
				return true;
		}
		return false;
	},

	measureTextHtml: function(text, fontSize, fontFamily, fontWeight) {
		if(Ui.Label.measureBox === undefined)
			this.createMeasureHtml();
		Ui.Label.measureBox.style.fontSize = fontSize+'px';
		Ui.Label.measureBox.style.fontFamily = fontFamily;
		Ui.Label.measureBox.style.fontWeight = fontWeight;
		if('textContent' in Ui.Label.measureBox)
			Ui.Label.measureBox.textContent = text;
		else
			Ui.Label.measureBox.innerText = text;
		return { width: Ui.Label.measureBox.offsetWidth, height: Ui.Label.measureBox.offsetHeight };
	},

	createMeasureHtml: function() {
		var measureWindow = window;
		if(navigator.isIE || navigator.isGecko)
			measureWindow = Ui.App.getRootWindow();

		if(measureWindow.document.body === undefined) {
			var body = measureWindow.document.createElement('body');
			measureWindow.document.body = body;
		}
		Ui.Label.measureBox = measureWindow.document.createElement('div');
		Ui.Label.measureBox.style.whiteSpace = 'nowrap';
		Ui.Label.measureBox.style.position = 'absolute';
		Ui.Label.measureBox.style.left = '0px';
		Ui.Label.measureBox.style.top = '0px';
		Ui.Label.measureBox.style.position = 'absolute';
		Ui.Label.measureBox.style.display = 'inline';
		Ui.Label.measureBox.style.visibility = 'hidden';
		measureWindow.document.body.appendChild(Ui.Label.measureBox);
	},

	measureText: function(text, fontSize, fontFamily, fontWeight) {
		if((text === '') || (text === undefined))
			return { width: 0, height: 0 };
		if(navigator.supportCanvas)
			return Ui.Label.measureTextCanvas(text, fontSize, fontFamily, fontWeight);
		else
			return Ui.Label.measureTextHtml(text, fontSize, fontFamily, fontWeight);
	},

	style: {
		color: new Ui.Color({ r: 0, g: 0, b: 0 }),
		fontSize: 16,
		fontFamily: 'Sans-serif',
		fontWeight: 'normal'
	}
});

<commit_msg>change the default color<commit_after>Ui.Element.extend('Ui.Label',
/**@lends Ui.Label#*/
{
	text: '',
	orientation: 'horizontal',
	fontSize: undefined,
	fontFamily: undefined,
	fontWeight: undefined,
	color: undefined,
	labelDrawing: undefined,
	textMeasureValid: false,
	textWidth: 0,
	textHeight: 0,

    /**
     * @constructs
	 * @class A label is a graphical element that display a Text and which will take all the place it could to display it on one row.
     * @extends Ui.Element
     * @param {String} [config.text] Label's text
     * @param {Number} [config.fontSize]
     * @param {String} [config.fontFamily]
     * @param {String} [config.fontWeight] CSS fontWeight property ['normal', 'bold', Number]
     * @param {String} [config.color]
     * @param {String} [config.orientation]
	 * @param {mixed} [config] see {@link Ui.Element} constructor for more options.
     */
	constructor: function(config) {
		this.setSelectable(false);
	},

	getText: function() {
		return this.text;
	},

	setText: function(text) {
		if(this.text != text) {
			this.text = text;
			if('textContent' in this.labelDrawing)
				this.labelDrawing.textContent = this.text;
			else
				this.labelDrawing.innerText = this.text;
			this.textMeasureValid = false;
			this.invalidateMeasure();
		}
	},

	setFontSize: function(fontSize) {
		if(this.fontSize !== fontSize) {
			this.fontSize = fontSize;
			this.labelDrawing.style.fontSize = this.getFontSize()+'px';
			this.textMeasureValid = false;
			this.invalidateMeasure();
		}
	},

	getFontSize: function() {
		if(this.fontSize !== undefined)
			return this.fontSize;
		else
			return this.getStyleProperty('fontSize');
	},

	setFontFamily: function(fontFamily) {
		if(this.fontFamily !== fontFamily) {
			this.fontFamily = fontFamily;
			this.labelDrawing.style.fontFamily = this.getFontFamily();
			this.textMeasureValid = false;
			this.invalidateMeasure();
		}
	},

	getFontFamily: function() {
		if(this.fontFamily !== undefined)
			return this.fontFamily;
		else
			return this.getStyleProperty('fontFamily');
	},

	setFontWeight: function(fontWeight) {
		if(this.fontWeight !== fontWeight) {
			this.fontWeight = fontWeight;
			this.labelDrawing.style.fontWeight = this.getFontWeight();
			this.textMeasureValid = false;
			this.invalidateMeasure();
		}
	},

	getFontWeight: function() {
		if(this.fontWeight !== undefined)
			return this.fontWeight;
		else
			return this.getStyleProperty('fontWeight');
	},

	setColor: function(color) {
		if(this.color !== color) {
			this.color = Ui.Color.create(color);
			if(navigator.supportRgba)
				this.labelDrawing.style.color = this.getColor().getCssRgba();
			else
				this.labelDrawing.style.color = this.getColor().getCssHtml();
		}
	},

	getColor: function() {
		if(this.color !== undefined)
			return this.color;
		else
			return Ui.Color.create(this.getStyleProperty('color'));
	},

	getOrientation: function() {
		return this.orientation;
	},

	setOrientation: function(orientation) {
		if(this.orientation != orientation) {
			this.orientation = orientation;
			this.invalidateMeasure();
		}
	}
},
/**@lends Ui.Label#*/
{
	verticalAlign: 'center',
	horizontalAlign: 'center',

	onStyleChange: function() {
		this.labelDrawing.style.fontSize = this.getFontSize()+'px';
		this.labelDrawing.style.fontFamily = this.getFontFamily();
		this.labelDrawing.style.fontWeight = this.getFontWeight();
		if(navigator.supportRgba)
			this.labelDrawing.style.color = this.getColor().getCssRgba();
		else
			this.labelDrawing.style.color = this.getColor().getCssHtml();
		this.textMeasureValid = false;
		this.invalidateMeasure();
	},

	renderDrawing: function() {
		/**#nocode+ Avoid Jsdoc warnings...*/
		this.labelDrawing = document.createElement('div');
		this.labelDrawing.style.whiteSpace = 'nowrap';
		this.labelDrawing.style.display = 'inline';
		this.labelDrawing.style.position = 'absolute';
		this.labelDrawing.style.left = '0px';
		this.labelDrawing.style.top = '0px';
		return this.labelDrawing;
		/**#nocode- Avoid Jsdoc warnings...*/
	},

	measureCore: function(width, height) {
		if(!this.textMeasureValid) {
			this.textMeasureValid = true;
			var size = Ui.Label.measureText(this.text, this.getFontSize(), this.getFontFamily(), this.getFontWeight());
			this.textWidth = size.width;
			this.textHeight = size.height;
		}
		if(this.orientation == 'vertical')
			return { width: this.textHeight, height: this.textWidth };
		else
			return { width: this.textWidth, height: this.textHeight };
	},

	arrangeCore: function(width, height) {
		var matrix;
		if(this.orientation == 'vertical') {
			matrix = Ui.Matrix.createTranslate(this.labelDrawing.offsetHeight, 0);
			matrix.rotate(90);
			if(navigator.isIE) {
				this.labelDrawing.style.msTransform = matrix.toString();
				this.labelDrawing.style.msTransformOrigin = '0% 0%';
			}
			else if(navigator.isGecko) {
				this.labelDrawing.style.MozTransform = 'matrix('+matrix.svgMatrix.a.toFixed(4)+', '+matrix.svgMatrix.b.toFixed(4)+', '+matrix.svgMatrix.c.toFixed(4)+', '+matrix.svgMatrix.d.toFixed(4)+', '+matrix.svgMatrix.e.toFixed(0)+'px, '+matrix.svgMatrix.f.toFixed(0)+'px)';
				this.labelDrawing.style.MozTransformOrigin = '0% 0%';
			}
			else if(navigator.isWebkit) {
				this.labelDrawing.style.webkitTransform = matrix.toString();
				this.labelDrawing.style.webkitTransformOrigin = '0% 0%';
			}
			else if(navigator.isOpera) {
				this.labelDrawing.style.OTransform = matrix.toString();
				this.labelDrawing.style.OTransformOrigin = '0% 0%';
			}
		}
		else {
			if(navigator.isIE && ('removeProperty' in this.labelDrawing))
				this.labelDrawing.style.removeProperty('-ms-transform');
			else if(navigator.isGecko)
				this.labelDrawing.style.removeProperty('-moz-transform');
			else if(navigator.isWebkit)
				this.labelDrawing.style.removeProperty('-webkit-transform');
			else if(navigator.isOpera)
				this.labelDrawing.style.removeProperty('-o-transform');
		}
	}
},
/**@lends Ui.Label*/
{
	measureBox: undefined,
	measureContext: undefined,

	measureTextCanvas: function(text, fontSize, fontFamily, fontWeight) {
		if(Ui.Label.measureBox === undefined)
			this.createMeasureCanvas();
		Ui.Label.measureContext.font = 'normal '+fontWeight+' '+fontSize+'px '+fontFamily;
		var res = Ui.Label.measureContext.measureText(text);
		res.height = fontSize;
		return res;
	},

	createMeasureCanvas: function() {
		var measureWindow = window;
		if(navigator.isIE || navigator.isGecko)
			measureWindow = Ui.App.getRootWindow();

		if(measureWindow.document.body === undefined) {
			var body = measureWindow.document.createElement('body');
			measureWindow.document.body = body;
		}
		Ui.Label.measureBox = measureWindow.document.createElement('canvas');
		Ui.Label.measureBox.style.visibility = 'hidden';
		Ui.Label.measureBox.style.position = 'absolute';
		Ui.Label.measureBox.style.left = '0px';
		Ui.Label.measureBox.style.top = '0px';
		Ui.Label.measureBox.style.outline = 'none';
		Ui.Label.measureBox.setAttribute('width', 10, null);
		Ui.Label.measureBox.setAttribute('height', 10, null);
		measureWindow.document.body.appendChild(Ui.Label.measureBox);
		Ui.Label.measureContext = Ui.Label.measureBox.getContext('2d');
	},

	isFontAvailable: function(fontFamily, fontWeight) {
		var i;
		if(!navigator.supportCanvas)
			return true;
		if(Ui.Label.measureBox === undefined)
			Ui.Label.createMeasureCanvas();
		var ctx = Ui.Label.measureContext;
		ctx.fillStyle = 'rgba(0,0,0,0)';
		ctx.clearRect(0, 0, 10, 10);
		ctx.textBaseline = 'top';
		//console.log('isFontAvailable('+fontFamily+','+fontWeight+')');
		// draw with the wanted font
		ctx.font = 'normal '+fontWeight+' 10px '+fontFamily;
		ctx.fillStyle = 'rgba(255,255,255,1)';
		ctx.fillText('@', 0, 0);
		var wantedImageData = ctx.getImageData(0,0,10,10);
		var empty = true;
		for(i = 0; empty && (i < wantedImageData.data.length); i += 4) {
			if(wantedImageData.data[i+3] !== 0)
				empty = false;
		}
		if(empty)
			return false;
		// draw with a local font
		ctx.fillStyle = 'rgba(0,0,0,0)';
		ctx.clearRect(0, 0, 10, 10);
		ctx.fillStyle = 'rgba(255,255,255,1)';
		ctx.font = 'normal '+fontWeight+' 10px Sans-Serif';
		ctx.fillText('@', 0, 0);
		var refImageData = ctx.getImageData(0,0,10,10);
		// draw with wanted font fallback local font
		ctx.fillStyle = 'rgba(0,0,0,0)';
		ctx.clearRect(0, 0, 10, 10);
		ctx.fillStyle = 'rgba(255,255,255,1)';
		ctx.font = 'normal '+fontWeight+' 10px '+fontFamily+',Sans-Serif';
		ctx.fillText('@', 0, 0);
		// test if images are differents
		var imageData = ctx.getImageData(0,0,10,10);
		for(i = 0; i < imageData.data.length; i += 4) {
			if(imageData.data[i+3] !== refImageData.data[i+3])
				return true;
		}
		return false;
	},

	measureTextHtml: function(text, fontSize, fontFamily, fontWeight) {
		if(Ui.Label.measureBox === undefined)
			this.createMeasureHtml();
		Ui.Label.measureBox.style.fontSize = fontSize+'px';
		Ui.Label.measureBox.style.fontFamily = fontFamily;
		Ui.Label.measureBox.style.fontWeight = fontWeight;
		if('textContent' in Ui.Label.measureBox)
			Ui.Label.measureBox.textContent = text;
		else
			Ui.Label.measureBox.innerText = text;
		return { width: Ui.Label.measureBox.offsetWidth, height: Ui.Label.measureBox.offsetHeight };
	},

	createMeasureHtml: function() {
		var measureWindow = window;
		if(navigator.isIE || navigator.isGecko)
			measureWindow = Ui.App.getRootWindow();

		if(measureWindow.document.body === undefined) {
			var body = measureWindow.document.createElement('body');
			measureWindow.document.body = body;
		}
		Ui.Label.measureBox = measureWindow.document.createElement('div');
		Ui.Label.measureBox.style.whiteSpace = 'nowrap';
		Ui.Label.measureBox.style.position = 'absolute';
		Ui.Label.measureBox.style.left = '0px';
		Ui.Label.measureBox.style.top = '0px';
		Ui.Label.measureBox.style.position = 'absolute';
		Ui.Label.measureBox.style.display = 'inline';
		Ui.Label.measureBox.style.visibility = 'hidden';
		measureWindow.document.body.appendChild(Ui.Label.measureBox);
	},

	measureText: function(text, fontSize, fontFamily, fontWeight) {
		if((text === '') || (text === undefined))
			return { width: 0, height: 0 };
		if(navigator.supportCanvas)
			return Ui.Label.measureTextCanvas(text, fontSize, fontFamily, fontWeight);
		else
			return Ui.Label.measureTextHtml(text, fontSize, fontFamily, fontWeight);
	},

	style: {
		color: '#444444',
		fontSize: 16,
		fontFamily: 'Sans-serif',
		fontWeight: 'normal'
	}
});

<|endoftext|>


<commit_before>(function($){

    function getWidth(max, count, min){
        if (count < 1) {
            return max;
        } else if ((max/count) > min ) {
            return max/count;
        }
        return getWidth(max, count-1, min);
    }

    function updateSizes($elements){
        var width = $('#isotope-container').width();
        var boxWidth =  getWidth(width, 5, 250);
        $elements.css('width', boxWidth + 'px');
        var imageWidth = boxWidth - 10 ;
        var imageHeight = imageWidth * 0.75;
        var $images = $elements.find('img');
        $images.css('width', imageWidth  + 'px');
        $images.css('height', imageHeight + 'px');
    }

    $(document).ready(function(){

        // Isotope
        var isotope = $('#isotope-container').isotope({
            itemSelector: '.isotope-item'
        });
        $('.pagination').hide();

        // Infinite Scroll
        $('#isotope-container').infinitescroll({
            navSelector  : ".pagination",
            nextSelector : ".pagination .next",
            itemSelector : ".blog-article",
            loading: {
                selector: '#infinite-scrolling-loading',
                finishedMsg: '',
                img: 'wp-content/themes/apperclass/assets/images/loader3.gif',
                msgText: ''
            }
        },function(elements){
            updateSizes($(elements));
            isotope.isotope( 'appended', elements );
        });

        // Switch category menu
        $('.category-list-menu').hide();
        $('.category-switch').change(function(e){
            window.location = $(this).val();
        });

        $(window).resize(function(){
            updateSizes($('.isotope-item'));
            setTimeout(function(){
                $('#isotope-container').data('isotope').layout();
            },150);
        });

        $(window).trigger('resize');
    });
})(jQuery);

<commit_msg>[TEST] try effect with opacity<commit_after>(function($){

    function getWidth(max, count, min){
        if (count < 1) {
            return max;
        } else if ((max/count) > min ) {
            return max/count;
        }
        return getWidth(max, count-1, min);
    }

    function updateSizes($elements){
        var width = $('#isotope-container').width();
        var boxWidth =  getWidth(width, 5, 250);
        $elements.css('width', boxWidth + 'px');
        var imageWidth = boxWidth - 10 ;
        var imageHeight = imageWidth * 0.75;
        var $images = $elements.find('img');
        $images.css('width', imageWidth  + 'px');
        $images.css('height', imageHeight + 'px');
    }

    $(document).ready(function(){
        $('#isotope-container').css('opacity',0);
        // Isotope
        var isotope = $('#isotope-container').isotope({
            itemSelector: '.isotope-item'
        });
        $('.pagination').hide();

        // Infinite Scroll
        $('#isotope-container').infinitescroll({
            navSelector  : ".pagination",
            nextSelector : ".pagination .next",
            itemSelector : ".blog-article",
            loading: {
                selector: '#infinite-scrolling-loading',
                finishedMsg: '',
                img: 'wp-content/themes/apperclass/assets/images/loader3.gif',
                msgText: ''
            }
        },function(elements){
            updateSizes($(elements));
            isotope.isotope( 'appended', elements );
        });

        // Switch category menu
        $('.category-list-menu').hide();
        $('.category-switch').change(function(e){
            window.location = $(this).val();
        });

        $(window).resize(function(){
            updateSizes($('.isotope-item'));
            setTimeout(function(){
                $('#isotope-container').data('isotope').layout();
            },50);
        });

        setTimeout(function(){
            $(window).trigger('resize');
            $('#isotope-container').css('opacity', 1);
        }, 200);

    });
})(jQuery);

<|endoftext|>


<commit_before>/*
Copyright 2013 - $Date $ by PeopleWare n.v.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

define(["dojo/_base/declare", "ppwcode-vernacular-semantics/Value",
        "ppwcode-util-collections/ArraySet", "ppwcode-util-oddsAndEnds/js", "dojo/number", "dojo/_base/lang",
        "ppwcode-vernacular-semantics/ParseException",
        "module"],
    function(declare, Value,
             Set, js, number, lang,
             ParseException,
             module) {

      var ScalarQuantitativeValue = declare([Value], {

        _c_invar: [
          function() {return this._c_prop_mandatory("scalarValue");},
          function() {return this._c_prop_number("scalarValue");},
          function() {return this._c_prop_mandatory("unit");},
          function() {return this._c_prop_string("unit");},
          function() {return this.getSupportedUnits().contains(this.unit);}
        ],

        // scalarValue: Number
        //   The scalar value of this value. Mandatory.
        scalarValue: null,

        // unit: String
        //   The string representing the unit of this value. Mandatory.
        unit: null,

        constructor: function(/*Object*/ props) {
          this._c_pre(function() {return props /* exists and not null */;});
          this._c_pre(function() {return js.typeOf(props) === "object";});
          this._c_pre(function() {return this._c_prop_mandatory(props, "scalarValue");});
          this._c_pre(function() {return this._c_prop_number(props, "scalarValue");});
          this._c_pre(function() {return this._c_prop_mandatory(props, "unit");});
          this._c_pre(function() {return this._c_prop_string(props, "unit");});
          this._c_pre(function() {return this.getSupportedUnits().contains(props.unit);});

          this.scalarValue = props.scalarValue;
          this.unit = props.unit;
        },

        getExtraSupportedUnits: function() {
          // summary:
          //   The extra units this class adds to the supported units
          //   defined in superclasses.
          //   Concrete subclasses can define the extra supported units
          //   in a Constructor property "extraSupportedUnits".
          // description:
          //   If a class defines no extra supported units,
          //   this returns undefined.

          return this.constructor.extraSupportedUnits;
        },

        getSupportedUnits: function() {
          // summary:
          //   Returns Set of all supported units.
          // description:
          //   Subtypes list the extra units they support, next to the ones their super types support,
          //   in a Set property `extraSupportedUnits` of the constructor. This function returns
          //   the union of those Sets of all super types of the instance.

          return getSupportedUnits(this.constructor);
        },

        getScalarValueAs: function(/*String*/ unit) {
          // summary:
          //   Return the scalarValue in the given unit.
          // description:
          //   Must be overridden if the class supports more then 1 unit.
          this._c_pre(function() {return unit;});
          this._c_pre(function() {return this.getSupportedUnits().contains(unit);});

          return this.scalarValue; // return Number - works only if there is only 1 unit supported
        },

        compare: function(/*ScalarQuantitativeValue*/ other) {
          this._c_pre(function() {return !other || (other.isInstanceOf && other.isInstanceOf(ScalarQuantitativeValue));});

          if (!other) {
            return +1;
          }
          var otherScalar = other.getScalarValueAs(this.unit);
          return this.scalarValue < otherScalar ? -1 : (this.scalarValue === otherScalar ? 0 : +1);
        },

        equals: function(/*ScalarQuantitativeValue*/ other) {
          return this.inherited(arguments) && (this.scalarValue === other.getScalarValueAs(this.unit));
        },

        add: function(/*ScalarQuantitativeValue*/ other) {
          // summary:
          //   Returns a new object, of the same concrete type as this, with the unit of this,
          //   and a scalarValue that represents the sum of other with this.
          //   Other must be compatible, in that it must be able to return a scalar value
          //   in the unit of this.
          //   If no other is given, we return this.
          // description:
          //   The kwargs argument offered to the constructor of this type is the result of
          //   this.toJSON, with an altered scalarValue. This means all other properties that
          //   the subclass provides are copied to the new object.
          this._c_pre(function() {return !other || other.getSupportedUnits().contains(this.unit);});

          if (!other) {
            return this;
          }
          var sum = this.scalarValue + other.getScalarValueAs(this.unit);
          var kwargs = this.toJSON();
          kwargs.scalarValue = sum;
          return new (this.constructor)(kwargs);
        },

        getValue: function() {
          return this.scalarValue + " " + this.unit;
        },

        _extendJsonObject: function(/*Object*/ json) {
          json.scalarValue = this.scalarValue;
          json.unit = this.unit;
        },

        _stateToString: function(/*Array of String*/ toStrings) {
          toStrings.push("scalarValue: " + this.scalarValue);
          toStrings.push("unit: " + this.unit);
        }
      });

      //noinspection ParameterNamingConventionJS
      function getSupportedUnits(ScalarQuantitativeValueConstructor) {
        if (!ScalarQuantitativeValueConstructor.prototype.isInstanceOf(ScalarQuantitativeValue)) {
          throw "ERROR: precondition violation: constructor is not a subtype of ScalarQuantitativeValue";
        }

        if (!ScalarQuantitativeValueConstructor._supportedUnits) {
          var parents = ScalarQuantitativeValueConstructor._meta.parents;
          ScalarQuantitativeValueConstructor._supportedUnits = parents.reduce(
            function(acc, parent) {
              if (parent.prototype.isInstanceOf(ScalarQuantitativeValue)) {
                acc.addAll(getSupportedUnits(parent));
              }
              return acc;
            },
            ScalarQuantitativeValueConstructor.prototype.getExtraSupportedUnits() ||
              new Set({elementType: "string"})
          );
        }
        return ScalarQuantitativeValueConstructor._supportedUnits;
      }

      ScalarQuantitativeValue.format = function(sqv, options) {
        // summary:
        //   options.unit can be filled out; if not, the unit of the value is used.
        //   options.na can be filled out; this string is used to represent null or undefined `fraction`.
        //   If options.mantisseOptional is true, the output does not show a decimal point, or a mantisse,
        //   if the mantisse is 0.
        //   If options.showNoUnit is true, the unit is not shown.

        if (!sqv) {
          return (options && (options.na || options.na === "")) ? options.na : "N/A";
        }
        else {
          var displayUnit = (options && options.unit) || sqv.unit;
          if (! sqv.getSupportedUnits().contains(displayUnit)) {
            throw "ERROR: cannot format " + sqv.toString() + " as '" + displayUnit + "' (unit not supported)";
          }
          var scalarValue = sqv.getScalarValueAs(displayUnit);
          var opt = options ? lang.clone(options) : {};
          if (opt.mantisseOptional) {
            var mantisse = scalarValue - Math.floor(scalarValue);
            if (mantisse === 0) {
              opt.places = 0;
            }
          }
          return number.format(scalarValue, opt) + (opt.showNoUnit ? "" : " " + displayUnit);
        }
      };

      ScalarQuantitativeValue.parse = function(defaultDefaultUnit, SqvConstructor, str, options) {
        // summary:
        //   Not a parse function. To get a parse function, do
        //  lang.partial(ScalarQuantitativeValue.parse, ConcreteConstructor, "defaultDefaultUnit")

        if (!(lang.isFunction(SqvConstructor) &&
              SqvConstructor.prototype &&
              SqvConstructor.prototype.isInstanceOf &&
              SqvConstructor.prototype.isInstanceOf(ScalarQuantitativeValue))) {
          throw "ERROR: SqvConstructor is not a subtype of ScalarQuantitativeValue";
        }

        if (!str || str === (options && options.na ? options.na : "N/A")) {
          return null;
        }
        else {
          var unitStartPosition = -1;
          var unit = (options && (options.defaultUnit || options.unit)) || defaultDefaultUnit; // default
          var supportedUnits = SqvConstructor.prototype.getSupportedUnits().toArray().sort(function(one, other) { // sort: longest first
            return (other.length - one.length) || (one < other ? -1 : +1); // == is impossible: it is a set
          });
          for(var i = 0; i < supportedUnits.length; i++) {
            unitStartPosition = str.indexOf(supportedUnits[i]);
            if (unitStartPosition >= 0) {
              unit = supportedUnits[i];
              //noinspection BreakStatementJS
              break; // because sorted from longest to shortest, first hit is it
            }
          }
          // we certainly have a unit; now we also either have a unitStartPosition >= 0, or not
          // the scalar value must come before the unit
          var strScalar = unitStartPosition >= 0 ? str.substring(0, unitStartPosition) : str;
          strScalar = strScalar.trim();
          // if there is nothing left, we take that as a null (empty, or unit without a number)
          if (strScalar === "") {
            return null;
          }
          // now, parse the number part, with i18n
          // with options.places, we need to supply str with this exact decimal places!!! 0's aren't added, number isn't truncated
          // we don't want that, so remove the places
          var opt = options ? lang.clone(options) : {};
          delete opt.places;
          var d = number.parse(strScalar, opt);
          // now d is a number, or NaN if strScalar was not a str that represented a number; that is a problem
          if (!d) {
            throw new ParseException({targetType: SqvConstructor, str: str, options: opt});
          }
          // we now have a number and a unit; we can create the Value
          return new SqvConstructor({scalarValue: d, unit: unit});
        }
      };

      ScalarQuantitativeValue._supportedUnits = new Set({elementType: "string"});
      ScalarQuantitativeValue.extraSupportedUnits = null;

      ScalarQuantitativeValue.mid = module.id;

      return ScalarQuantitativeValue;
    }
);
<commit_msg>Code inspection. TODO for warning: function too complex.<commit_after>/*
Copyright 2013 - $Date $ by PeopleWare n.v.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

define(["dojo/_base/declare", "ppwcode-vernacular-semantics/Value",
        "ppwcode-util-collections/ArraySet", "ppwcode-util-oddsAndEnds/js", "dojo/number", "dojo/_base/lang",
        "ppwcode-vernacular-semantics/ParseException",
        "module"],
    function(declare, Value,
             Set, js, number, lang,
             ParseException,
             module) {

      var ScalarQuantitativeValue = declare([Value], {

        _c_invar: [
          function() {return this._c_prop_mandatory("scalarValue");},
          function() {return this._c_prop_number("scalarValue");},
          function() {return this._c_prop_mandatory("unit");},
          function() {return this._c_prop_string("unit");},
          function() {return this.getSupportedUnits().contains(this.unit);}
        ],

        // scalarValue: Number
        //   The scalar value of this value. Mandatory.
        scalarValue: null,

        // unit: String
        //   The string representing the unit of this value. Mandatory.
        unit: null,

        constructor: function(/*Object*/ props) {
          this._c_pre(function() {return props /* exists and not null */;});
          this._c_pre(function() {return js.typeOf(props) === "object";});
          this._c_pre(function() {return this._c_prop_mandatory(props, "scalarValue");});
          this._c_pre(function() {return this._c_prop_number(props, "scalarValue");});
          this._c_pre(function() {return this._c_prop_mandatory(props, "unit");});
          this._c_pre(function() {return this._c_prop_string(props, "unit");});
          this._c_pre(function() {return this.getSupportedUnits().contains(props.unit);});

          this.scalarValue = props.scalarValue;
          this.unit = props.unit;
        },

        getExtraSupportedUnits: function() {
          // summary:
          //   The extra units this class adds to the supported units
          //   defined in superclasses.
          //   Concrete subclasses can define the extra supported units
          //   in a Constructor property "extraSupportedUnits".
          // description:
          //   If a class defines no extra supported units,
          //   this returns undefined.

          return this.constructor.extraSupportedUnits;
        },

        getSupportedUnits: function() {
          // summary:
          //   Returns Set of all supported units.
          // description:
          //   Subtypes list the extra units they support, next to the ones their super types support,
          //   in a Set property `extraSupportedUnits` of the constructor. This function returns
          //   the union of those Sets of all super types of the instance.

          return getSupportedUnits(this.constructor);
        },

        getScalarValueAs: function(/*String*/ unit) {
          // summary:
          //   Return the scalarValue in the given unit.
          // description:
          //   Must be overridden if the class supports more then 1 unit.
          this._c_pre(function() {return unit;});
          this._c_pre(function() {return this.getSupportedUnits().contains(unit);});

          return this.scalarValue; // return Number - works only if there is only 1 unit supported
        },

        compare: function(/*ScalarQuantitativeValue*/ other) {
          this._c_pre(function() {return !other || (other.isInstanceOf && other.isInstanceOf(ScalarQuantitativeValue));});

          if (!other) {
            return +1;
          }
          var otherScalar = other.getScalarValueAs(this.unit);
          return this.scalarValue < otherScalar ? -1 : (this.scalarValue === otherScalar ? 0 : +1);
        },

        equals: function(/*ScalarQuantitativeValue*/ other) {
          return this.inherited(arguments) && (this.scalarValue === other.getScalarValueAs(this.unit));
        },

        add: function(/*ScalarQuantitativeValue*/ other) {
          // summary:
          //   Returns a new object, of the same concrete type as this, with the unit of this,
          //   and a scalarValue that represents the sum of other with this.
          //   Other must be compatible, in that it must be able to return a scalar value
          //   in the unit of this.
          //   If no other is given, we return this.
          // description:
          //   The kwargs argument offered to the constructor of this type is the result of
          //   this.toJSON, with an altered scalarValue. This means all other properties that
          //   the subclass provides are copied to the new object.
          this._c_pre(function() {return !other || other.getSupportedUnits().contains(this.unit);});

          if (!other) {
            return this;
          }
          var sum = this.scalarValue + other.getScalarValueAs(this.unit);
          var kwargs = this.toJSON();
          kwargs.scalarValue = sum;
          return new (this.constructor)(kwargs);
        },

        getValue: function() {
          return this.scalarValue + " " + this.unit;
        },

        _extendJsonObject: function(/*Object*/ json) {
          json.scalarValue = this.scalarValue;
          json.unit = this.unit;
        },

        _stateToString: function(/*Array of String*/ toStrings) {
          toStrings.push("scalarValue: " + this.scalarValue);
          toStrings.push("unit: " + this.unit);
        }
      });

      //noinspection ParameterNamingConventionJS
      function getSupportedUnits(ScalarQuantitativeValueConstructor) {
        if (!ScalarQuantitativeValueConstructor.prototype.isInstanceOf(ScalarQuantitativeValue)) {
          throw "ERROR: precondition violation: constructor is not a subtype of ScalarQuantitativeValue";
        }

        if (!ScalarQuantitativeValueConstructor._supportedUnits) {
          var parents = ScalarQuantitativeValueConstructor._meta.parents;
          ScalarQuantitativeValueConstructor._supportedUnits = parents.reduce(
            function(acc, parent) {
              if (parent.prototype.isInstanceOf(ScalarQuantitativeValue)) {
                acc.addAll(getSupportedUnits(parent));
              }
              return acc;
            },
            ScalarQuantitativeValueConstructor.prototype.getExtraSupportedUnits() ||
              new Set({elementType: "string"})
          );
        }
        return ScalarQuantitativeValueConstructor._supportedUnits;
      }

      ScalarQuantitativeValue.format = function(sqv, options) {
        // summary:
        //   options.unit can be filled out; if not, the unit of the value is used.
        //   options.na can be filled out; this string is used to represent null or undefined `fraction`.
        //   If options.mantisseOptional is true, the output does not show a decimal point, or a mantisse,
        //   if the mantisse is 0.
        //   If options.showNoUnit is true, the unit is not shown.

        if (!sqv) {
          return (options && (options.na || options.na === "")) ? options.na : "N/A";
        }
        else {
          var displayUnit = (options && options.unit) || sqv.unit;
          if (! sqv.getSupportedUnits().contains(displayUnit)) {
            throw "ERROR: cannot format " + sqv.toString() + " as '" + displayUnit + "' (unit not supported)";
          }
          var scalarValue = sqv.getScalarValueAs(displayUnit);
          var opt = options ? lang.clone(options) : {};
          if (opt.mantisseOptional) {
            var mantisse = scalarValue - Math.floor(scalarValue);
            if (mantisse === 0) {
              opt.places = 0;
            }
          }
          return number.format(scalarValue, opt) + (opt.showNoUnit ? "" : " " + displayUnit);
        }
      };

      ScalarQuantitativeValue.parse = function(defaultDefaultUnit, SqvConstructor, str, options) {
        // summary:
        //   Not a parse function. To get a parse function, do
        //  lang.partial(ScalarQuantitativeValue.parse, ConcreteConstructor, "defaultDefaultUnit")

        // TODO too complex. refactor.

        if (!(lang.isFunction(SqvConstructor) &&
              SqvConstructor.prototype &&
              SqvConstructor.prototype.isInstanceOf &&
              SqvConstructor.prototype.isInstanceOf(ScalarQuantitativeValue))) {
          throw "ERROR: SqvConstructor is not a subtype of ScalarQuantitativeValue";
        }

        if (!str || str === (options && options.na ? options.na : "N/A")) {
          return null;
        }
        else {
          var unitStartPosition = -1;
          var unit = (options && (options.defaultUnit || options.unit)) || defaultDefaultUnit; // default
          var supportedUnits = SqvConstructor.prototype.getSupportedUnits().toArray().sort(function(one, other) { // sort: longest first
            return (other.length - one.length) || (one < other ? -1 : +1); // == is impossible: it is a set
          });
          for(var i = 0; i < supportedUnits.length; i++) {
            unitStartPosition = str.indexOf(supportedUnits[i]);
            if (unitStartPosition >= 0) {
              unit = supportedUnits[i];
              //noinspection BreakStatementJS
              break; // because sorted from longest to shortest, first hit is it
            }
          }
          // we certainly have a unit; now we also either have a unitStartPosition >= 0, or not
          // the scalar value must come before the unit
          var strScalar = unitStartPosition >= 0 ? str.substring(0, unitStartPosition) : str;
          strScalar = strScalar.trim();
          // if there is nothing left, we take that as a null (empty, or unit without a number)
          if (strScalar === "") {
            return null;
          }
          // now, parse the number part, with i18n
          // with options.places, we need to supply str with this exact decimal places!!! 0's aren't added, number isn't truncated
          // we don't want that, so remove the places
          var opt = options ? lang.clone(options) : {};
          delete opt.places;
          var d = number.parse(strScalar, opt);
          // now d is a number, or NaN if strScalar was not a str that represented a number; that is a problem
          if (!d) {
            throw new ParseException({targetType: SqvConstructor, str: str, options: opt});
          }
          // we now have a number and a unit; we can create the Value
          return new SqvConstructor({scalarValue: d, unit: unit});
        }
      };

      ScalarQuantitativeValue._supportedUnits = new Set({elementType: "string"});
      ScalarQuantitativeValue.extraSupportedUnits = null;

      ScalarQuantitativeValue.mid = module.id;

      return ScalarQuantitativeValue;
    }
);
<|endoftext|>


<commit_before>var reducer = require('../../src/reducers/slides');
import addSlideAction from '../../src/actions/addSlide.js';
import editSlideAction from '../../src/actions/editSlide.js';
import deleteSlideAction from '../../src/actions/deleteSlide.js';

describe.only('slides', () => {

  it('should return the initial state', () => {
    expect(
      reducer(undefined, {})
    ).to.deep.equal([])
  })

  it('should not change the passed state', (done) => {

    const state = Object.freeze({});
    reducer(state, {type: 'INVALID'});

    done();
  });

  describe('action handling', () => {
    it('should handle ADD_SLIDE', () => {
      const reducerStateAfterHandlingAddSlide = reducer(undefined, addSlideAction({
        url: 'http://www.example.com',
        duration: 5000
      }))
      expect(reducerStateAfterHandlingAddSlide.length).to.equal(1);
      expect(reducerStateAfterHandlingAddSlide[0].url).to.equal('http://www.example.com');
      expect(reducerStateAfterHandlingAddSlide[0].duration).to.equal(5000);
    })

    it('should handle EDIT_SLIDE', () => {
      const reducerStateAfterHandlingAddSlide = reducer(
        [
          {
            _id: '1234567',
            url: 'http://www.exmaple.com',
            duration: 5000
          }
        ], editSlideAction('1234567',
          {
            url: 'http://smash.cologne',
            duration: 7500
          }
        )
      )
      expect(reducerStateAfterHandlingAddSlide.length).to.equal(1);
      expect(reducerStateAfterHandlingAddSlide[0].url).to.equal('http://smash.cologne');
      expect(reducerStateAfterHandlingAddSlide[0].duration).to.equal(7500);
    })

    it('should handle DELETE_SLIDE', () => {
      const reducerStateAfterHandlingAddSlide = reducer(
        [
          {
            _id: '1234567',
            url: 'http://www.exmaple.com',
            duration: 5000
          }
        ], deleteSlideAction('1234567')
      )
      expect(reducerStateAfterHandlingAddSlide.length).to.equal(0);
    })
  })
});
<commit_msg>Adds the spec for the INSERT_SLIDE action<commit_after>var reducer = require('../../src/reducers/slides');
import addSlideAction from '../../src/actions/addSlide.js';
import editSlideAction from '../../src/actions/editSlide.js';
import deleteSlideAction from '../../src/actions/deleteSlide.js';

describe.only('slides', () => {

  it('should return the initial state', () => {
    expect(
      reducer(undefined, {})
    ).to.deep.equal([])
  })

  it('should not change the passed state', (done) => {

    const state = Object.freeze({});
    reducer(state, {type: 'INVALID'});

    done();
  });

  describe('action handling', () => {
    it('should handle ADD_SLIDE', () => {
      const reducerStateAfterHandlingAddSlide = reducer(undefined, addSlideAction({
        url: 'http://www.example.com',
        duration: 5000
      }))
      expect(reducerStateAfterHandlingAddSlide.length).to.equal(1);
      expect(reducerStateAfterHandlingAddSlide[0].url).to.equal('http://www.example.com');
      expect(reducerStateAfterHandlingAddSlide[0].duration).to.equal(5000);
    })

    it('should handle EDIT_SLIDE', () => {
      const reducerStateAfterHandlingAddSlide = reducer(
        [
          {
            _id: '1234567',
            url: 'http://www.exmaple.com',
            duration: 5000
          }
        ], editSlideAction('1234567',
          {
            url: 'http://smash.cologne',
            duration: 7500
          }
        )
      )
      expect(reducerStateAfterHandlingAddSlide.length).to.equal(1);
      expect(reducerStateAfterHandlingAddSlide[0].url).to.equal('http://smash.cologne');
      expect(reducerStateAfterHandlingAddSlide[0].duration).to.equal(7500);
    })

    it('should handle DELETE_SLIDE', () => {
      const reducerStateAfterHandlingAddSlide = reducer(
        [
          {
            _id: '1234567',
            url: 'http://www.exmaple.com',
            duration: 5000
          }
        ], deleteSlideAction('1234567')
      )
      expect(reducerStateAfterHandlingAddSlide.length).to.equal(0);
    })
  })

  describe('pouch db middleware action handling', () => {
    it('should handle INSERT_SLIDE', () => {
      const reducerStateAfterHandlingAddSlide = reducer(
        [],
        {
          type: 'INSERT_SLIDE',
          slide: {
            _id: '1234567',
            url: 'http://www.exmaple.com',
            duration: 5000
          }
        }
      )
      expect(reducerStateAfterHandlingAddSlide).to.deep.equal([
        {
          _id: '1234567',
          url: 'http://www.exmaple.com',
          duration: 5000
        }
      ]);
    })
  })
});
<|endoftext|>


<commit_before>import {base64} from '@ciscospark/common';

/**
 * Tests if a string is a UUID
 * @param {String} string
 * @returns {Boolean}
 */
export function isUuid(string) {
  const uuidRegExp = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

  return uuidRegExp.test(string);
}

/**
 * Takes a Conversation URL and returns the Uuid
 * @param {String} convoUrl
 * @returns {String|Boolean}
 */
export function getConvoIdFromUrl(convoUrl) {
  const id = convoUrl.split('/').pop();
  if (isUuid(id)) {
    return id;
  }
  return false;
}

/**
 * Validates a string as a UUID or a hydra encoded UUID
 * @param {String} string
 * @returns {Boolean|String}
 */
export function validateAndDecodeId(string) {
  let resultId = false;
  if (isUuid(string)) {
    resultId = string;
  }
  else {
    let isEncodedUUID = false;
    let base64uuid;
    // Check for base 64 encoding
    try {
      base64uuid = atob(string).split('/').pop();
      isEncodedUUID = isUuid(base64uuid);
    }
    catch (e) {
      if (e.name !== 'InvalidCharacterError') {
        throw e;
      }
    }
    if (isEncodedUUID) {
      resultId = base64uuid;
    }
  }
  return resultId;
}

/**
 * Constructs a hydra id for a given uuid and type
 *
 * @export
 * @param {string} type one of PEOPLE, TEAM, ROOM
 * @param {any} id
 * @returns {string}
 */
export function constructHydraId(type, id) {
  return base64.encode(`ciscospark://us/${type.toUpperCase()}/${id}`);
}

/**
 * Deconstructs a hydra id and provides the uuid
 *
 * @export
 * @param {String} id
 * @returns {String}
 */
export function deconstructHydraId(id) {
  const payload = base64.decode(id).split('/');
  return {
    id: payload.pop(),
    type: payload.pop()
  };
}
<commit_msg>feat(react-component-utils): add hydraTypes object<commit_after>import {base64} from '@ciscospark/common';

/**
 * Tests if a string is a UUID
 * @param {String} string
 * @returns {Boolean}
 */
export function isUuid(string) {
  const uuidRegExp = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

  return uuidRegExp.test(string);
}

/**
 * Takes a Conversation URL and returns the Uuid
 * @param {String} convoUrl
 * @returns {String|Boolean}
 */
export function getConvoIdFromUrl(convoUrl) {
  const id = convoUrl.split('/').pop();
  if (isUuid(id)) {
    return id;
  }
  return false;
}

/**
 * Validates a string as a UUID or a hydra encoded UUID
 * @param {String} string
 * @returns {Boolean|String}
 */
export function validateAndDecodeId(string) {
  let resultId = false;
  if (isUuid(string)) {
    resultId = string;
  }
  else {
    let isEncodedUUID = false;
    let base64uuid;
    // Check for base 64 encoding
    try {
      base64uuid = atob(string).split('/').pop();
      isEncodedUUID = isUuid(base64uuid);
    }
    catch (e) {
      if (e.name !== 'InvalidCharacterError') {
        throw e;
      }
    }
    if (isEncodedUUID) {
      resultId = base64uuid;
    }
  }
  return resultId;
}

/**
 * Constructs a hydra id for a given uuid and type
 *
 * @export
 * @param {string} type one of PEOPLE, TEAM, ROOM
 * @param {any} id
 * @returns {string}
 */
export function constructHydraId(type, id) {
  return base64.encode(`ciscospark://us/${type.toUpperCase()}/${id}`);
}

/**
 * Deconstructs a hydra id and provides the uuid
 *
 * @export
 * @param {String} id
 * @returns {String}
 */
export function deconstructHydraId(id) {
  const payload = base64.decode(id).split('/');
  return {
    id: payload.pop(),
    type: payload.pop()
  };
}

export const hydraTypes = {
  MESSAGE: 'MESSAGE',
  PEOPLE: 'PEOPLE',
  ROOM: 'ROOM',
  TEAM: 'TEAM'
};
<|endoftext|>


<commit_before>import React from 'react';
import Logo from './Logo';
import LogInOut from './LogInOut';
import AppBar from 'material-ui/lib/app-bar';
<<<<<<< 04bc5a597a8dd39407c00fbd42a7b9af8e80217f
import ActionFlightTakeoff from 'material-ui/lib/svg-icons/action/flight-takeoff';

const REDBORDERSTYLE = {borderStyle: 'dotted', borderColor: 'red'};
=======

>>>>>>> Changed logobar and navbar to material ui components

class LogoBar extends React.Component {
  render() {
    return (

        <AppBar
          style={{ backgroundColor: 'WHITE' }}
          title={PICDROP}
          iconElementRight={<LogInOut history={this.props.history} />}
          zDepth={0}
        />

    );
  }
}

export default LogoBar;
<commit_msg>Changed logobar and navbar to material ui components<commit_after>import React from 'react';
import Logo from './Logo';
import LogInOut from './LogInOut';
import AppBar from 'material-ui/lib/app-bar';
import ActionFlightTakeoff from 'material-ui/lib/svg-icons/action/flight-takeoff';

const REDBORDERSTYLE = {borderStyle: 'dotted', borderColor: 'red'};

class LogoBar extends React.Component {
  render() {
    return (

      <AppBar
        style={{ backgroundColor: 'WHITE' }}
        title={PICDROP}
        iconElementRight={<LogInOut />}
        zDepth={0}
      />

    );
  }
}

export default LogoBar;
<|endoftext|>


<commit_before>steal('can/util/can.js', 'mootools', 'can/util/event.js','can/util/fragment.js', 'can/util/deferred.js',
'can/util/array/each.js', 'can/util/object/isplain', 'can/util/object/extend', function(can) {
	// mootools.js
	// ---------
	// _MooTools node list._
	//
	// Map string helpers.
	can.trim = function(s){
		return s && s.trim()
	}

	// Map array helpers.
	can.makeArray = function(item) {
		// All other libraries return a copy if item is an array.
		// The original Mootools Array.from returned the same item so we need to slightly modify it
		if (item == null) return [];
		try {
			return (Type.isEnumerable(item) && typeof item != 'string') ? Array.prototype.slice.call(item) : [item];
		} catch(ex) {
			// some things like DOMNodeChildCollections don't slice so good.
			// This pains me, but it has to be done.
			var arr = [],
				i;
			for( i = 0; i < item.length; ++i) {
				arr.push(item[i]);
			}
			return arr;
		}
	}

	can.isArray = function(arr) {
		return typeOf(arr) === 'array'
	};
	can.inArray = function(item,arr) {
		if(!arr) {
			return -1;
		}
		return Array.prototype.indexOf.call(arr, item);
	}
	can.map = function(arr, fn){
		return Array.from(arr||[]).map(fn);
	}

	// Map object helpers.
	can.param = function(object){
		return Object.toQueryString(object)
	}
	can.isEmptyObject = function(object){
		return Object.keys(object).length === 0;
	}
	// Map function helpers.
	can.proxy = function(func){
		var args = can.makeArray(arguments),
			func = args.shift();

		return func.bind.apply(func, args)
	}
	can.isFunction = function(f){
		return typeOf(f) == 'function'
	}
	// Make this object so you can bind on it.
	can.bind = function( ev, cb){
		// If we can bind to it...
		if(this.bind && this.bind !== can.bind){
			this.bind(ev, cb)
		} else if(this.addEvent) {
			this.addEvent(ev, cb)
		} else {
			// Make it bind-able...
			can.addEvent.call(this, ev, cb)
		}
		return this;
	}
	can.unbind = function(ev, cb){
		// If we can bind to it...
		if(this.unbind && this.unbind !== can.unbind){
			this.unbind(ev, cb)
		} else if(this.removeEvent) {
			this.removeEvent(ev, cb)
		} else {
			// Make it bind-able...
			can.removeEvent.call(this, ev, cb)
		}
		return this;
	}
	can.trigger = function(item, event, args, bubble){
		// Defaults to `true`.
		bubble = (bubble === undefined ? true : bubble);
		args = args || []
		if(item.fireEvent){
			item = item[0] || item;
			// walk up parents to simulate bubbling .
			while(item) {
			// Handle walking yourself.
				if(!event.type){
					event = {
						type : event,
						target : item
					}
				}
				var events = (item !== window ?
					can.$(item).retrieve('events')[0] :
					item.retrieve('events') );
				if (events && events[event.type]) {
					events[event.type].keys.each(function(fn){
						fn.apply(this, [event].concat(args));
					}, this);
				}
				// If we are bubbling, get parent node.
				if(bubble && item.parentNode){
					item = item.parentNode
				} else {
					item = null;
				}

			}

		} else {
			if(typeof event === 'string'){
				event = {type: event}
			}
			event.target = event.target || item;
			event.data = args
			can.dispatch.call(item, event)
		}
	}
	can.delegate = function(selector, ev , cb){
		if(this.delegate) {
			this.delegate(selector, ev , cb)
		}
		 else if(this.addEvent) {
			this.addEvent(ev+":relay("+selector+")", cb)
		} else {
			// make it bind-able ...
		}
		return this;
	}
	can.undelegate = function(selector, ev , cb){
		if(this.undelegate) {
			this.undelegate(selector, ev , cb)
		}
		 else if(this.removeEvent) {
			this.removeEvent(ev+":relay("+selector+")", cb)
		} else {
			// make it bind-able ...

		}
		return this;
	}
	var optionsMap = {
		type:"method",
		success : undefined,
		error: undefined
	}
	var updateDeferred = function(xhr, d){
		for(var prop in xhr){
			if(typeof d[prop] == 'function'){
				d[prop] = function(){
					xhr[prop].apply(xhr, arguments)
				}
			} else {
				d[prop] = prop[xhr]
			}
		}
	}
	can.ajax = function(options){
		var d = can.Deferred(),
			requestOptions = can.extend({}, options);
		// Map jQuery options to MooTools options.

		for(var option in optionsMap){
			if(requestOptions[option] !== undefined){
				requestOptions[optionsMap[option]] = requestOptions[option];
				delete requestOptions[option]
			}
		}
		// Mootools defaults to 'post', but Can expects a default of 'get'
		requestOptions.method = requestOptions.method || 'get';

		var success = options.success,
			error = options.error;

		requestOptions.onSuccess = function(responseText, xml){
			var data = responseText;
			if(options.dataType ==='json'){
				data = eval("("+data+")")
			}
			updateDeferred(request.xhr, d);
			d.resolve(data,"success",request.xhr);
			success && success(data,"success",request.xhr);
		}
		requestOptions.onError = function(){
			updateDeferred(request.xhr, d);
			d.reject(request.xhr,"error");
			error(request.xhr,"error");
		}

		var request = new Request(requestOptions);
		request.send();
		updateDeferred(request.xhr, d);
		return d;

	}
	// Element -- get the wrapped helper.
	can.$ = function(selector){
		if(selector === window){
			return window;
		}
		return $$(selector)
	}

	// Add `document` fragment support.
	var old = document.id;
	document.id =  function(el){
		if(el && el.nodeType === 11){
			return el
		} else{
			return old.apply(document, arguments);
		}
	};
	can.append = function(wrapped, html){
		if(typeof html === 'string'){
			html = can.buildFragment(html)
		}
		return wrapped.grab(html)
	}
	can.filter = function(wrapped, filter){
		return wrapped.filter(filter);
	}
	can.data = function(wrapped, key, value){
		if(value === undefined){
			return wrapped[0].retrieve(key)
		} else {
			return wrapped.store(key, value)
		}
	}
	can.addClass = function(wrapped, className){
		return wrapped.addClass(className);
	}
	can.remove = function(wrapped){
		// We need to remove text nodes ourselves.
		var filtered = wrapped.filter(function(node){
			if(node.nodeType !== 1){
				node.parentNode.removeChild(node);
			} else {
				return true;
			}
		})
		filtered.destroy();
		return filtered;
	}

	// Destroyed method.
	var destroy = Element.prototype.destroy;
	Element.implement({
		destroy : function(){
			can.trigger(this,"destroyed",[],false)
			var elems = this.getElementsByTagName("*");
			for ( var i = 0, elem; (elem = elems[i]) !== undefined; i++ ) {
				can.trigger(elem,"destroyed",[],false);
			}
			destroy.apply(this, arguments)
		}
	});
	can.get = function(wrapped, index){
		return wrapped[index];
	}

	// Overwrite to handle IE not having an id.
	// IE barfs if text node.
	var idOf = Slick.uidOf;
	Slick.uidOf = function(node){
		if(node.nodeType === 1 || node === window){
			return idOf(node);
		} else {
			return Math.random();
		}

	}

	return can;
});
<commit_msg>can.ajax in Mootools works properly if a window.location object is used as a URL<commit_after>steal('can/util/can.js', 'mootools', 'can/util/event.js','can/util/fragment.js', 'can/util/deferred.js',
'can/util/array/each.js', 'can/util/object/isplain', 'can/util/object/extend', function(can) {
	// mootools.js
	// ---------
	// _MooTools node list._
	//
	// Map string helpers.
	can.trim = function(s){
		return s && s.trim()
	}

	// Map array helpers.
	can.makeArray = function(item) {
		// All other libraries return a copy if item is an array.
		// The original Mootools Array.from returned the same item so we need to slightly modify it
		if (item == null) return [];
		try {
			return (Type.isEnumerable(item) && typeof item != 'string') ? Array.prototype.slice.call(item) : [item];
		} catch(ex) {
			// some things like DOMNodeChildCollections don't slice so good.
			// This pains me, but it has to be done.
			var arr = [],
				i;
			for( i = 0; i < item.length; ++i) {
				arr.push(item[i]);
			}
			return arr;
		}
	}

	can.isArray = function(arr) {
		return typeOf(arr) === 'array'
	};
	can.inArray = function(item,arr) {
		if(!arr) {
			return -1;
		}
		return Array.prototype.indexOf.call(arr, item);
	}
	can.map = function(arr, fn){
		return Array.from(arr||[]).map(fn);
	}

	// Map object helpers.
	can.param = function(object){
		return Object.toQueryString(object)
	}
	can.isEmptyObject = function(object){
		return Object.keys(object).length === 0;
	}
	// Map function helpers.
	can.proxy = function(func){
		var args = can.makeArray(arguments),
			func = args.shift();

		return func.bind.apply(func, args)
	}
	can.isFunction = function(f){
		return typeOf(f) == 'function'
	}
	// Make this object so you can bind on it.
	can.bind = function( ev, cb){
		// If we can bind to it...
		if(this.bind && this.bind !== can.bind){
			this.bind(ev, cb)
		} else if(this.addEvent) {
			this.addEvent(ev, cb)
		} else {
			// Make it bind-able...
			can.addEvent.call(this, ev, cb)
		}
		return this;
	}
	can.unbind = function(ev, cb){
		// If we can bind to it...
		if(this.unbind && this.unbind !== can.unbind){
			this.unbind(ev, cb)
		} else if(this.removeEvent) {
			this.removeEvent(ev, cb)
		} else {
			// Make it bind-able...
			can.removeEvent.call(this, ev, cb)
		}
		return this;
	}
	can.trigger = function(item, event, args, bubble){
		// Defaults to `true`.
		bubble = (bubble === undefined ? true : bubble);
		args = args || []
		if(item.fireEvent){
			item = item[0] || item;
			// walk up parents to simulate bubbling .
			while(item) {
			// Handle walking yourself.
				if(!event.type){
					event = {
						type : event,
						target : item
					}
				}
				var events = (item !== window ?
					can.$(item).retrieve('events')[0] :
					item.retrieve('events') );
				if (events && events[event.type]) {
					events[event.type].keys.each(function(fn){
						fn.apply(this, [event].concat(args));
					}, this);
				}
				// If we are bubbling, get parent node.
				if(bubble && item.parentNode){
					item = item.parentNode
				} else {
					item = null;
				}

			}

		} else {
			if(typeof event === 'string'){
				event = {type: event}
			}
			event.target = event.target || item;
			event.data = args
			can.dispatch.call(item, event)
		}
	}
	can.delegate = function(selector, ev , cb){
		if(this.delegate) {
			this.delegate(selector, ev , cb)
		}
		 else if(this.addEvent) {
			this.addEvent(ev+":relay("+selector+")", cb)
		} else {
			// make it bind-able ...
		}
		return this;
	}
	can.undelegate = function(selector, ev , cb){
		if(this.undelegate) {
			this.undelegate(selector, ev , cb)
		}
		 else if(this.removeEvent) {
			this.removeEvent(ev+":relay("+selector+")", cb)
		} else {
			// make it bind-able ...

		}
		return this;
	}
	var optionsMap = {
		type:"method",
		success : undefined,
		error: undefined
	}
	var updateDeferred = function(xhr, d){
		for(var prop in xhr){
			if(typeof d[prop] == 'function'){
				d[prop] = function(){
					xhr[prop].apply(xhr, arguments)
				}
			} else {
				d[prop] = prop[xhr]
			}
		}
	}
	can.ajax = function(options){
		var d = can.Deferred(),
			requestOptions = can.extend({}, options);
		// Map jQuery options to MooTools options.

		for(var option in optionsMap){
			if(requestOptions[option] !== undefined){
				requestOptions[optionsMap[option]] = requestOptions[option];
				delete requestOptions[option]
			}
		}
		// Mootools defaults to 'post', but Can expects a default of 'get'
		requestOptions.method = requestOptions.method || 'get';
		requestOptions.url = requestOptions.url.toString();

		var success = options.success,
			error = options.error;

		requestOptions.onSuccess = function(responseText, xml){
			var data = responseText;
			if(options.dataType ==='json'){
				data = eval("("+data+")")
			}
			updateDeferred(request.xhr, d);
			d.resolve(data,"success",request.xhr);
			success && success(data,"success",request.xhr);
		}
		requestOptions.onError = function(){
			updateDeferred(request.xhr, d);
			d.reject(request.xhr,"error");
			error(request.xhr,"error");
		}

		var request = new Request(requestOptions);
		request.send();
		updateDeferred(request.xhr, d);
		return d;

	}
	// Element -- get the wrapped helper.
	can.$ = function(selector){
		if(selector === window){
			return window;
		}
		return $$(selector)
	}

	// Add `document` fragment support.
	var old = document.id;
	document.id =  function(el){
		if(el && el.nodeType === 11){
			return el
		} else{
			return old.apply(document, arguments);
		}
	};
	can.append = function(wrapped, html){
		if(typeof html === 'string'){
			html = can.buildFragment(html)
		}
		return wrapped.grab(html)
	}
	can.filter = function(wrapped, filter){
		return wrapped.filter(filter);
	}
	can.data = function(wrapped, key, value){
		if(value === undefined){
			return wrapped[0].retrieve(key)
		} else {
			return wrapped.store(key, value)
		}
	}
	can.addClass = function(wrapped, className){
		return wrapped.addClass(className);
	}
	can.remove = function(wrapped){
		// We need to remove text nodes ourselves.
		var filtered = wrapped.filter(function(node){
			if(node.nodeType !== 1){
				node.parentNode.removeChild(node);
			} else {
				return true;
			}
		})
		filtered.destroy();
		return filtered;
	}

	// Destroyed method.
	var destroy = Element.prototype.destroy;
	Element.implement({
		destroy : function(){
			can.trigger(this,"destroyed",[],false)
			var elems = this.getElementsByTagName("*");
			for ( var i = 0, elem; (elem = elems[i]) !== undefined; i++ ) {
				can.trigger(elem,"destroyed",[],false);
			}
			destroy.apply(this, arguments)
		}
	});
	can.get = function(wrapped, index){
		return wrapped[index];
	}

	// Overwrite to handle IE not having an id.
	// IE barfs if text node.
	var idOf = Slick.uidOf;
	Slick.uidOf = function(node){
		if(node.nodeType === 1 || node === window){
			return idOf(node);
		} else {
			return Math.random();
		}

	}

	return can;
});
<|endoftext|>


<commit_before>import Ember from 'ember';

const { Controller, computed, observer } = Ember;

export default Controller.extend({
  creatingNewModel: false,

  // Contains only the user defined schemas (excluding "SpaceDog" models)
  items: Ember.computed('model.[]', function(){
    return this.get('model').filter(function(item){
      // Recomputing everything - very ineficient, but not time for fancy shit
      var isUserDefined = !item.get('id').match(/^tsygan@/i);
      // XXX double registration doesn't work obviously
      // console.warn('---', item.get('id'), isUserDefined);
      if(isUserDefined)
        SpaceDog.register(Ember.getOwner(this), item);
      return isUserDefined;
    }, this)
  }),

  // List of ids
  list: computed('items.[]', function(){
    return this.get('items').map(function(item){
      return item.id;
    });
  }),

  // Actions
  actions: {
    // Add a new model
    newModel(modelId) {
      // XXX This may fail here if record id already exist (for example)
      const model = this.store.createRecord('tsygan@spacedog-schema', {
        // XXX SpaceDog damnit! https://github.com/spacedog-io/services/issues/34
        id: modelId.toLowerCase().replace(/[\\/*?"<>|\s]/g, '')
      });

      // this.send('newField', model);
      model.save();
      this.set('model', this.store.peekAll('tsygan@spacedog-schema'));
      // this.model.pushObjects(model);
    },

    // Add a new field
    newField(model) {
      const currentFields = model.get('fields');

      currentFields.then((data) => {
        const newField = this.store.createRecord('tsygan@spacedog-schemafield', {
          parentModel: model,
          type: 'string',
          dirty: true
        });

        data.addObject(newField);
      });
    },

    // Remove a model
    removeModel(model) {
      const fields = model.get('fields');

      // iterate through fields and delete those records
      fields.forEach((field) => {
        if (field) {
          field.destroyRecord();
        }
      });

      model.destroyRecord();

    },

    saveModel(model) {
      model.save();
      model.set('dirty', false);
      const fields = model.get('fields');
      // iterate through fields and delete those records
      fields.forEach((field) => {
        field.set('dirty', false);
      });
    },

    // Triggered when fields are updated - change the state to not saved
    updateFields(modelId) {
      var model = this.store.peekRecord('tsygan@spacedog-schema', modelId);
      model.set('dirty', true);
      // model.save();
    }
  }
});
<commit_msg>Workaround https://github.com/spacedog-io/services/issues/34 and https://github.com/spacedog-io/services/issues/31<commit_after>import Ember from 'ember';

const { Controller, computed, observer } = Ember;

export default Controller.extend({
  creatingNewModel: false,

  // Contains only the user defined schemas (excluding "SpaceDog" models)
  items: Ember.computed('model.[]', function(){
    return this.get('model').filter(function(item){
      // Recomputing everything - very ineficient, but not time for fancy shit
      var isUserDefined = !item.get('id').match(/^tsygan@/i);
      // XXX double registration doesn't work obviously
      // console.warn('---', item.get('id'), isUserDefined);
      if(isUserDefined)
        SpaceDog.register(Ember.getOwner(this), item);
      return isUserDefined;
    }, this)
  }),

  // List of ids
  list: computed('items.[]', function(){
    return this.get('items').map(function(item){
      return item.id;
    });
  }),

  // Actions
  actions: {
    // Add a new model
    newModel(modelId) {
      // XXX This may fail here if record id already exist (for example)
      const model = this.store.createRecord('tsygan@spacedog-schema', {
        // XXX SpaceDog https://github.com/spacedog-io/services/issues/34
        // https://github.com/spacedog-io/services/issues/31
        // XXX should be expressed on id type / validated on input instead
        id: modelId.toLowerCase().replace(/[\\/*?"<>|\s]/g, '')
      });

      // this.send('newField', model);
      model.save();
      this.set('model', this.store.peekAll('tsygan@spacedog-schema'));
      // this.model.pushObjects(model);
    },

    // Add a new field
    newField(model) {
      const currentFields = model.get('fields');

      currentFields.then((data) => {
        const newField = this.store.createRecord('tsygan@spacedog-schemafield', {
          parentModel: model,
          type: 'string',
          dirty: true
        });

        data.addObject(newField);
      });
    },

    // Remove a model
    removeModel(model) {
      const fields = model.get('fields');

      // iterate through fields and delete those records
      fields.forEach((field) => {
        if (field) {
          field.destroyRecord();
        }
      });

      model.destroyRecord();

    },

    saveModel(model) {
      model.save();
      model.set('dirty', false);
      const fields = model.get('fields');
      // iterate through fields and delete those records
      fields.forEach((field) => {
        field.set('dirty', false);
      });
    },

    // Triggered when fields are updated - change the state to not saved
    updateFields(modelId) {
      var model = this.store.peekRecord('tsygan@spacedog-schema', modelId);
      model.set('dirty', true);
      // model.save();
    }
  }
});
<|endoftext|>