<commit_before>/**
 * @since 0.0.1
 * @copyright 2015 Spatial Vision, Inc. http://spatialvision.com.au
 * @license The MIT License
 * @author Spatial Vision
 * @version 0.1.0
 */

'use strict';

/**
 * soilSampleImporter
 * @module soilSampleImporter
 */
angular.module('farmbuild.soilSampleImporter', ['farmbuild.core','farmbuild.farmdata'])
	.factory('soilSampleImporter',
  function (soilSampleImporterSession,
            soilSampleConverter,
            importField,
            soilSampleValidator,
            soilClassification,
            paddockSoilSampleRetriever,
            mangementZones,
            farmdata,
            validations,
            googleAnalyticsImporter,
            $log) {
		var soilSampleImporter = {
        farmdata:farmdata
      },
			_isPositiveNumber = validations.isPositiveNumber,
			_isDefined = validations.isDefined;

    soilSampleImporter.version = '0.1.0';
    soilSampleImporter.ga = googleAnalyticsImporter;
    soilSampleImporter.session = soilSampleImporterSession;

		$log.info('Welcome to Soil Sample Importer... ' +
      'this should only be initialised once! why we see twice in the example?');

    /**
     * Finds the farmData from the session.
     * @method find
     * @returns {object} the farmData stored in session, undefined if the farmData is found in session
     * @public
     * @static
     */
    soilSampleImporter.find = function () {
      return soilSampleImporterSession.find();
    };

		/**
		 * Loads the farmData into the session.
     * If the farmData has no soilSampleImporter section, then append one
		 * @method load
		 * @param {!object} farmData -
		 * @returns {object} the farmData stored in session, undefined if the farmData is invalid
		 * @public
		 * @static
		 */
		soilSampleImporter.load = function (inputFarmData) {
      var loaded = farmdata.load(inputFarmData);
      $log.info('loaded '+JSON.stringify(loaded,null,"  "));
			if (!_isDefined(loaded)) {
				return undefined;
			}

      if(!loaded.hasOwnProperty('soils')){
        loaded.soils = {};
      }
      if(!loaded.soils.hasOwnProperty('sampleResults')){
          loaded.soils.sampleResults =  soilSampleImporter.createDefault();
          loaded = farmdata.update(loaded);

      }
			return loaded;
		};

    soilSampleImporter.export = soilSampleImporterSession.export;
    soilSampleImporter.toFarmData = soilSampleConverter.toFarmData;
    soilSampleImporter.createDefault = soilSampleConverter.createDefault;
    soilSampleImporter.isValidFarmDataWithSoilSample = soilSampleValidator.isValidFarmDataWithSoilSample;
    soilSampleImporter.classifyResult = soilClassification.classifyResult;
    soilSampleImporter.hasAverage = importField.hasAverage;
    soilSampleImporter.hasClassification = importField.hasClassification;
    soilSampleImporter.averageForPaddocks = paddockSoilSampleRetriever.soilSamplesInPaddock;
    soilSampleImporter.averageForManagementZone = mangementZones.averageForManagementZone;

		if (typeof window.farmbuild === 'undefined') {
			window.farmbuild = {
        soilSampleImporter: soilSampleImporter
			};
		} else {
			window.farmbuild.soilSampleImporter = soilSampleImporter;
		}

		return soilSampleImporter;
	});<commit_msg>Average for soil samples<commit_after>/**
 * @since 0.0.1
 * @copyright 2015 Spatial Vision, Inc. http://spatialvision.com.au
 * @license The MIT License
 * @author Spatial Vision
 * @version 0.1.0
 */

'use strict';

/**
 * soilSampleImporter
 * @module soilSampleImporter
 */
angular.module('farmbuild.soilSampleImporter', ['farmbuild.core','farmbuild.farmdata'])
	.factory('soilSampleImporter',
  function (soilSampleImporterSession,
            soilSampleConverter,
            importField,
            soilSampleValidator,
            soilClassification,
            paddockSoilSampleRetriever,
            mangementZones,
            farmdata,
            validations,
            googleAnalyticsImporter,
            $log) {
		var soilSampleImporter = {
        farmdata:farmdata
      },
			_isPositiveNumber = validations.isPositiveNumber,
			_isDefined = validations.isDefined;

    soilSampleImporter.version = '0.1.0';
    soilSampleImporter.ga = googleAnalyticsImporter;
    soilSampleImporter.session = soilSampleImporterSession;

		$log.info('Welcome to Soil Sample Importer... ' +
      'this should only be initialised once! why we see twice in the example?');

    /**
     * Finds the farmData from the session.
     * @method find
     * @returns {object} the farmData stored in session, undefined if the farmData is found in session
     * @public
     * @static
     */
    soilSampleImporter.find = function () {
      return soilSampleImporterSession.find();
    };

		/**
		 * Loads the farmData into the session.
     * If the farmData has no soilSampleImporter section, then append one
		 * @method load
		 * @param {!object} farmData -
		 * @returns {object} the farmData stored in session, undefined if the farmData is invalid
		 * @public
		 * @static
		 */
		soilSampleImporter.load = function (inputFarmData) {
      var loaded = farmdata.load(inputFarmData);
      $log.info('loaded '+JSON.stringify(loaded,null,"  "));
			if (!_isDefined(loaded)) {
				return undefined;
			}

      if(!loaded.hasOwnProperty('soils')){
        loaded.soils = {};
      }
      if(!loaded.soils.hasOwnProperty('sampleResults')){
          loaded.soils.sampleResults =  soilSampleImporter.createDefault();
          loaded = farmdata.update(loaded);

      }
			return loaded;
		};

    soilSampleImporter.export = soilSampleImporterSession.export;
    soilSampleImporter.toFarmData = soilSampleConverter.toFarmData;
    soilSampleImporter.createDefault = soilSampleConverter.createDefault;
    soilSampleImporter.isValidFarmDataWithSoilSample = soilSampleValidator.isValidFarmDataWithSoilSample;
    soilSampleImporter.classifyResult = soilClassification.classifyResult;
    soilSampleImporter.hasAverage = importField.hasAverage;
    soilSampleImporter.hasClassification = importField.hasClassification;
    soilSampleImporter.averageForPaddocks = paddockSoilSampleRetriever.averagesForSoilSamples;
    soilSampleImporter.averageForManagementZone = mangementZones.averageForManagementZone;

		if (typeof window.farmbuild === 'undefined') {
			window.farmbuild = {
        soilSampleImporter: soilSampleImporter
			};
		} else {
			window.farmbuild.soilSampleImporter = soilSampleImporter;
		}

		return soilSampleImporter;
	});<|endoftext|>


<commit_before>import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import callApiMiddleware from './callAPIMiddleware';
import rootReducer from './Reducers';

export default function storeCreator() {
  const middleWareTools = compose(
    applyMiddleware(thunkMiddleware, callApiMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  );

  return createStore(rootReducer, middleWareTools);
}
<commit_msg>Casing.<commit_after>import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import callAPIMiddleware from './callAPIMiddleware';
import rootReducer from './Reducers';

export default function storeCreator() {
  const middleWareTools = compose(
    applyMiddleware(thunkMiddleware, callAPIMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  );

  return createStore(rootReducer, middleWareTools);
}
<|endoftext|>


<commit_before>import { make } from 'vuex-pathify'
import { version } from '../../package.json'

const state = {
  version: '',
  platform: 'all', // either 'android', 'ios', or 'all'
  hardware: 'basalt',
  firmwareVersion: '',
  appVersion: '',
  inApp: false,
  devMode: false
}

export default {
  namespaced: true,
  state: state,
  mutations: {
    ...make.mutations(state),
    INIT (state) {
      if (localStorage.getItem('rebbleUserParameters')) {
        let cacheState = JSON.parse(localStorage.getItem('rebbleUserParameters'))
        if (cacheState.version === version) {
          Object.assign(state, cacheState)
        } else {
          state.version = version
        }
      } else {
        state.version = version
      }
    }
  }
}
<commit_msg>Remove firmware version as it's not provided<commit_after>import { make } from 'vuex-pathify'
import { version } from '../../package.json'

const state = {
  version: '',
  platform: 'all', // either 'android', 'ios', or 'all'
  hardware: 'basalt',
  appVersion: '',
  inApp: false,
  devMode: false
}

export default {
  namespaced: true,
  state: state,
  mutations: {
    ...make.mutations(state),
    INIT (state) {
      if (localStorage.getItem('rebbleUserParameters')) {
        let cacheState = JSON.parse(localStorage.getItem('rebbleUserParameters'))
        if (cacheState.version === version) {
          Object.assign(state, cacheState)
        } else {
          state.version = version
        }
      } else {
        state.version = version
      }
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Validate the given sourcePath property and attempt to
 * locate a repository with a helpful.json manifest file.
 */
export default function (ctx, next) {}<commit_msg>Started work on the validate source step<commit_after>import url from "url";
import http from "http";
import { someSeries } from "async";

/**
 * Validate the given sourcePath property and attempt to
 * locate a repository with a helpful.json manifest file.
 *
 * @param  {Object} ctx
 * @param  {Callback<Error>} next
 */
export default function (ctx, next) {
  process.stdout.write("\n\n\tOk, let's see if we can find this template... ");
  someSeries([
    isGithub
  ], function (test, next) {
    test(ctx.source.path, next);
  }, function (err, result) {
    if ( ! err && result) {
      Object.assign(ctx.source, result);
      process.stdout.write("Looks good!");
    } else if ( ! err && ! result) {
      err = new Error("The given template path could not be resolved.");
    }
    if (err) {
      process.stdout.write("Nope.");
    }
    next(err);
  });
}

/**
 * Provides a callback with a true or false response depending on if the
 * given URL has a valid 200-series response.
 *
 * @param  {String} testUrl
 * @param  {Callback<Boolean>} cb
 */
function checkUrl (testUrl, cb) {
  var req = http.request({
    method: 'HEAD',
    host: url.parse(testUrl).host,
    port: 80,
    path: url.parse(testUrl).pathname
  }, function (res) {
    cb(res.statusCode >= 200 && res.statusCode <= 299);
  });
}

/**
 * Takes a RegEx value and creates a URL using the given replacement
 * string value.
 *
 * @param  {RegExp} pattern
 * @param  {String} replacement
 * @return {Function}
 */
function testAndCreateUrl (pattern, replacement) {
  return function (source, next) {
    if ( ! pattern.test(source)) next();
    else {
      var url = source.replace(pattern, replacement);
      checkUrl(url, function (valid) {
        var out;
        if (valid) out = { url, type: "github" };
        next(null, out);
      });
    }
  };
}

/**
 * Checks to see if the given source references a GitHub hosted
 * repository.
 *
 * @param  {String} source
 * @param  {Callback<E, R>} next
 */
const isGithub = testAndCreateUrl(
  /^(?:https?\:\/\/)?(?:www\.)?(?:github\.com\/)?([\w\-]+\/[\w\-]+)/,
  "https://github.com/$1"
);<|endoftext|>


<commit_before>'use strict'
const Twitter = require('twitter')
var sentiment = require('sentiment')
var _ = require('underscore')
var apiKeys = require('../api-keys')

var client = new Twitter({
  consumer_key: apiKeys.twitter_consumer_key,
  consumer_secret: apiKeys.twitter_consumer_secret,
  access_token_key: apiKeys.twitter_acess_token_key,
  access_token_secret: apiKeys.twitter_access_token_secret
})

/**
 * Constructor for an object that manages a connection to the streaming API,
 * monitoring a provided list of trends and collecting information on them.
 *
 * @return {Object} A new TweetStream object
 */
function TweetStream () {
  var stream = null

  // Array mapping trend names to collected info on that trend
  var trendData = {}

  // Array of objects containing trend names and regexes to match for them
  var trendRegexes = []

  /**
   * Start collecting data for the trend names listed in the trends array.
   *
   * @param  {Array} trends List of trend names as strings to track
   */
  this.startTracking = function (trends) {
    // Close the stream (if one is open already)
    this.closeStream()

    // Build array of regexes to match trends against in tweet text
    trendRegexes = trends.map(trendName => {
      // Case insensitive search
      return {name: trendName, regex: new RegExp(trendName, 'i')}
    })

    // Fill the trendData object
    trendData = {}
    trends.forEach(trend => {
      trendData[trend] = {count: 0, sentiment_prelim: 0}
    })

    stream = client.stream('statuses/filter', {track: trends.join(',')})

    stream.on('data', event => {
      // Ignore all streaming API messages except tweets
      if (!event.text) {
        return
      }

      var sentimentScore = sentiment(event.text).score

      // Identify the trend and update trendData
      trendRegexes.forEach(trendRegex => {
        if (event.text.match(trendRegex.regex)) {
          // Add sentiment (Sentiment is averaged when data is returned)
          trendData[trendRegex.name].sentiment_prelim += sentimentScore
          trendData[trendRegex.name].count ++
        }
      })
    })

    stream.on('error', function (error) {
      throw error
    })
  }

  /**
   * Close the connection to the streaming API
   */
  this.closeStream = function () {
    if (stream) {
      stream.destroy()
    }
  }

  /**
   * Returns data collected so far for each trend from the streamin API.
   *
   * @return {type}  description
   */
  this.getData = function () {
    var returnTrendData = {}

    Object.keys(trendData).forEach(trend => {
      // Omit sentiment_prelim from the return
      returnTrendData[trend] = _.omit(trendData[trend], 'sentiment_prelim')

      // Average the sentiment (avoiding dividing by zero if count == 0)
      var avgSentiment = trendData[trend].count > 0
      ? trendData[trend].sentiment_prelim / trendData[trend].count : 0
      returnTrendData[trend].sentiment = avgSentiment
    })

    return returnTrendData
  }
}

module.exports = TweetStream
<commit_msg>Fix spelling error in tweet-stream.js and convert var to const<commit_after>'use strict'
const Twitter = require('twitter')
const sentiment = require('sentiment')
const _ = require('underscore')
const apiKeys = require('../api-keys')

var client = new Twitter({
  consumer_key: apiKeys.twitter_consumer_key,
  consumer_secret: apiKeys.twitter_consumer_secret,
  access_token_key: apiKeys.twitter_access_token_key,
  access_token_secret: apiKeys.twitter_access_token_secret
})

/**
 * Constructor for an object that manages a connection to the streaming API,
 * monitoring a provided list of trends and collecting information on them.
 *
 * @return {Object} A new TweetStream object
 */
function TweetStream () {
  var stream = null

  // Array mapping trend names to collected info on that trend
  var trendData = {}

  // Array of objects containing trend names and regexes to match for them
  var trendRegexes = []

  /**
   * Start collecting data for the trend names listed in the trends array.
   *
   * @param  {Array} trends List of trend names as strings to track
   */
  this.startTracking = function (trends) {
    // Close the stream (if one is open already)
    this.closeStream()

    // Build array of regexes to match trends against in tweet text
    trendRegexes = trends.map(trendName => {
      // Case insensitive search
      return {name: trendName, regex: new RegExp(trendName, 'i')}
    })

    // Fill the trendData object
    trendData = {}
    trends.forEach(trend => {
      trendData[trend] = {count: 0, sentiment_prelim: 0}
    })

    stream = client.stream('statuses/filter', {track: trends.join(',')})

    stream.on('data', event => {
      // Ignore all streaming API messages except tweets
      if (!event.text) {
        return
      }

      var sentimentScore = sentiment(event.text).score

      // Identify the trend and update trendData
      trendRegexes.forEach(trendRegex => {
        if (event.text.match(trendRegex.regex)) {
          // Add sentiment (Sentiment is averaged when data is returned)
          trendData[trendRegex.name].sentiment_prelim += sentimentScore
          trendData[trendRegex.name].count ++
        }
      })
    })

    stream.on('error', function (error) {
      console.error(error)
    })
  }

  /**
   * Close the connection to the streaming API
   */
  this.closeStream = function () {
    if (stream) {
      stream.destroy()
    }
  }

  /**
   * Returns data collected so far for each trend from the streamin API.
   *
   * @return {type}  description
   */
  this.getData = function () {
    var returnTrendData = {}

    Object.keys(trendData).forEach(trend => {
      // Omit sentiment_prelim from the return
      returnTrendData[trend] = _.omit(trendData[trend], 'sentiment_prelim')

      // Average the sentiment (avoiding dividing by zero if count == 0)
      var avgSentiment = trendData[trend].count > 0
      ? trendData[trend].sentiment_prelim / trendData[trend].count : 0
      returnTrendData[trend].sentiment = avgSentiment
    })

    return returnTrendData
  }
}

module.exports = TweetStream
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $ */

/**
 * ExtensionUtils defines utility methods for implementing extensions.
 */
define(function (require, exports, module) {
    "use strict";

    /**
     * Loads a style sheet relative to the extension module.
     *
     * @param {!module} module Module provided by RequireJS
     * @param {!string} path Relative path from the extension folder to a CSS file
     * @return {!$.Promise} A promise object that is resolved if the CSS file can be loaded.
     */
    function loadStyleSheet(module, path) {
        var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1),
            url = encodeURI(modulePath + path),
            result = new $.Deferred();

        // Make a request for the same file in order to record success or failure.
        // The link element's onload and onerror events are not consistently supported.
        $.get(url).done(function () {
            var $link = $("<link/>");

            $link.attr({
                type:       "text/css",
                rel:        "stylesheet",
                href:       url
            });

            $("head").append($link[0]);

            result.resolve($link[0]);
        }).fail(function (err) {
            result.reject(err);
        });

        return result;
    }

    exports.loadStyleSheet = loadStyleSheet;
});
<commit_msg>Prefix url with 'file:///' on windows.<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets */

/**
 * ExtensionUtils defines utility methods for implementing extensions.
 */
define(function (require, exports, module) {
    "use strict";

    /**
     * Loads a style sheet relative to the extension module.
     *
     * @param {!module} module Module provided by RequireJS
     * @param {!string} path Relative path from the extension folder to a CSS file
     * @return {!$.Promise} A promise object that is resolved if the CSS file can be loaded.
     */
    function loadStyleSheet(module, path) {
        var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1),
            url = encodeURI(modulePath + path),
            result = new $.Deferred();

        // Make a request for the same file in order to record success or failure.
        // The link element's onload and onerror events are not consistently supported.
        // On Windows, $.get() fails if the url is a full pathname. To work around this,
        // prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname,
        // but *doesn't* work if it is prepended with "file://". Go figure.
        $.get((brackets.platform === "win" ? "file:///" : "") + url).done(function () {
            var $link = $("<link/>");

            $link.attr({
                type:       "text/css",
                rel:        "stylesheet",
                href:       url
            });

            $("head").append($link[0]);

            result.resolve($link[0]);
        }).fail(function (err) {
            result.reject(err);
        });

        return result;
    }

    exports.loadStyleSheet = loadStyleSheet;
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, less */

/**
 * ExtensionUtils defines utility methods for implementing extensions.
 */
define(function (require, exports, module) {
    "use strict";

    /**
     * Appends a <style> tag to the document's head.
     *
     * @param {!string} css CSS code to use as the tag's content
     * @return {!HTMLStyleElement} The generated HTML node
     **/
    function addEmbeddedStyleSheet(css) {
        return $("<style>").text(css).appendTo("head")[0];
    }

    /**
     * Appends a <link> tag to the document's head.
     *
     * @param {!string} url URL to a style sheet
     * @param {$.Deferred=} deferred Optionally check for load and error events
     * @return {!HTMLLinkElement} The generated HTML node
     **/
    function addLinkedStyleSheet(url, deferred) {
        var attributes = {
            type: "text/css",
            rel:  "stylesheet",
            href: url
        };

        var $link = $("<link/>").attr(attributes);

        if (deferred) {
            $link.on('load', deferred.resolve).on('error', deferred.reject);
        }

        $link.appendTo("head");

        return $link[0];
    }

    /**
     * Parses LESS code and returns a promise that resolves with plain CSS code.
     *
     * Pass the {@link url} argument to resolve relative URLs contained in the code.
     * Make sure URLs in the code are wrapped in quotes, like so:
     *     background-image: url("image.png");
     *
     * @param {!string} code LESS code to parse
     * @param {?string} url URL to the file containing the code
     * @return {!$.Promise} A promise object that is resolved with CSS code if the LESS code can be parsed
     */
    function parseLessCode(code, url) {
        var result = new $.Deferred(),
            options;

        if (url) {
            var dir  = url.slice(0, url.lastIndexOf("/") + 1),
                file = url.slice(dir.length);

            options = {
                filename: file,
                paths:    [dir],
                rootpath: dir
            };
        }

        var parser = new less.Parser(options);
        parser.parse(code, function onParse(err, tree) {
            if (err) {
                result.reject(err);
            } else {
                result.resolve(tree.toCSS());
            }
        });

        return result.promise();
    }

    /**
     * Returns a path to an extension module.
     *
     * @param {!module} module Module provided by RequireJS
     * @param {?string} path Relative path from the extension folder to a file
     * @return {!string} The path to the module's folder
     **/
    function getModulePath(module, path) {
        var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1);
        if (path) {
            modulePath += path;
        }

        return modulePath;
    }

    /**
     * Returns a URL to an extension module.
     *
     * @param {!module} module Module provided by RequireJS
     * @param {?string} path Relative path from the extension folder to a file
     * @return {!string} The URL to the module's folder
     **/
    function getModuleUrl(module, path) {
        var url = encodeURI(getModulePath(module, path));

        // On Windows, $.get() fails if the url is a full pathname. To work around this,
        // prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname,
        // but *doesn't* work if it is prepended with "file://". Go figure.
        // However, the prefix "file://localhost" does work.
        if (brackets.platform === "win" && url.indexOf(":") !== -1) {
            url = "file:///" + url;
        }

        return url;
    }

    /**
     * Performs a GET request using a path relative to an extension module.
     *
     * The resulting URL can be retrieved in the resolve callback by accessing
     *
     * @param {!module} module Module provided by RequireJS
     * @param {!string} path Relative path from the extension folder to a file
     * @return {!$.Promise} A promise object that is resolved with the contents of the requested file
     **/
    function loadFile(module, path) {
        var url     = getModuleUrl(module, path),
            promise = $.get(url);

        return promise;
    }

    /**
     * Loads a style sheet (CSS or LESS) relative to the extension module.
     *
     * @param {!module} module Module provided by RequireJS
     * @param {!string} path Relative path from the extension folder to a CSS or LESS file
     * @return {!$.Promise} A promise object that is resolved with an HTML node if the file can be loaded.
     */
    function loadStyleSheet(module, path) {
        var result = new $.Deferred();

        loadFile(module, path)
            .done(function (content) {
                var url = this.url;

                if (url.slice(-5) === ".less") {
                    parseLessCode(content, url)
                        .done(function (css) {
                            result.resolve(addEmbeddedStyleSheet(css));
                        })
                        .fail(result.reject);
                } else {
                    var deferred = new $.Deferred(),
                        link = addLinkedStyleSheet(url, deferred);

                    deferred
                        .done(function () {
                            result.resolve(link);
                        })
                        .fail(result.reject);
                }
            })
            .fail(result.reject);

        return result.promise();
    }

    exports.addEmbeddedStyleSheet = addEmbeddedStyleSheet;
    exports.addLinkedStyleSheet   = addLinkedStyleSheet;
    exports.parseLessCode         = parseLessCode;
    exports.getModulePath         = getModulePath;
    exports.getModuleUrl          = getModuleUrl;
    exports.loadFile              = loadFile;
    exports.loadStyleSheet        = loadStyleSheet;
});
<commit_msg>Fix a case when extension less file is importing other less files<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, less */

/**
 * ExtensionUtils defines utility methods for implementing extensions.
 */
define(function (require, exports, module) {
    "use strict";

    /**
     * Appends a <style> tag to the document's head.
     *
     * @param {!string} css CSS code to use as the tag's content
     * @return {!HTMLStyleElement} The generated HTML node
     **/
    function addEmbeddedStyleSheet(css) {
        return $("<style>").text(css).appendTo("head")[0];
    }

    /**
     * Appends a <link> tag to the document's head.
     *
     * @param {!string} url URL to a style sheet
     * @param {$.Deferred=} deferred Optionally check for load and error events
     * @return {!HTMLLinkElement} The generated HTML node
     **/
    function addLinkedStyleSheet(url, deferred) {
        var attributes = {
            type: "text/css",
            rel:  "stylesheet",
            href: url
        };

        var $link = $("<link/>").attr(attributes);

        if (deferred) {
            $link.on('load', deferred.resolve).on('error', deferred.reject);
        }

        $link.appendTo("head");

        return $link[0];
    }

    /**
     * Parses LESS code and returns a promise that resolves with plain CSS code.
     *
     * Pass the {@link url} argument to resolve relative URLs contained in the code.
     * Make sure URLs in the code are wrapped in quotes, like so:
     *     background-image: url("image.png");
     *
     * @param {!string} code LESS code to parse
     * @param {?string} url URL to the file containing the code
     * @return {!$.Promise} A promise object that is resolved with CSS code if the LESS code can be parsed
     */
    function parseLessCode(code, url) {
        var result = new $.Deferred(),
            options;

        if (url) {
            var dir  = url.slice(0, url.lastIndexOf("/") + 1),
                file = url.slice(dir.length);

            options = {
                filename: file,
                paths:    [dir],
                rootpath: dir,
                currentFileInfo: {
                    currentDirectory: dir,
                    entryPath: dir,
                    filename: url,
                    rootFilename: url,
                    rootpath: dir
                }
            };
        }

        var parser = new less.Parser(options);
        parser.parse(code, function onParse(err, tree) {
            if (err) {
                result.reject(err);
            } else {
                result.resolve(tree.toCSS());
            }
        });

        return result.promise();
    }

    /**
     * Returns a path to an extension module.
     *
     * @param {!module} module Module provided by RequireJS
     * @param {?string} path Relative path from the extension folder to a file
     * @return {!string} The path to the module's folder
     **/
    function getModulePath(module, path) {
        var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1);
        if (path) {
            modulePath += path;
        }

        return modulePath;
    }

    /**
     * Returns a URL to an extension module.
     *
     * @param {!module} module Module provided by RequireJS
     * @param {?string} path Relative path from the extension folder to a file
     * @return {!string} The URL to the module's folder
     **/
    function getModuleUrl(module, path) {
        var url = encodeURI(getModulePath(module, path));

        // On Windows, $.get() fails if the url is a full pathname. To work around this,
        // prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname,
        // but *doesn't* work if it is prepended with "file://". Go figure.
        // However, the prefix "file://localhost" does work.
        if (brackets.platform === "win" && url.indexOf(":") !== -1) {
            url = "file:///" + url;
        }

        return url;
    }

    /**
     * Performs a GET request using a path relative to an extension module.
     *
     * The resulting URL can be retrieved in the resolve callback by accessing
     *
     * @param {!module} module Module provided by RequireJS
     * @param {!string} path Relative path from the extension folder to a file
     * @return {!$.Promise} A promise object that is resolved with the contents of the requested file
     **/
    function loadFile(module, path) {
        var url     = getModuleUrl(module, path),
            promise = $.get(url);

        return promise;
    }

    /**
     * Loads a style sheet (CSS or LESS) relative to the extension module.
     *
     * @param {!module} module Module provided by RequireJS
     * @param {!string} path Relative path from the extension folder to a CSS or LESS file
     * @return {!$.Promise} A promise object that is resolved with an HTML node if the file can be loaded.
     */
    function loadStyleSheet(module, path) {
        var result = new $.Deferred();

        loadFile(module, path)
            .done(function (content) {
                var url = this.url;

                if (url.slice(-5) === ".less") {
                    parseLessCode(content, url)
                        .done(function (css) {
                            result.resolve(addEmbeddedStyleSheet(css));
                        })
                        .fail(result.reject);
                } else {
                    var deferred = new $.Deferred(),
                        link = addLinkedStyleSheet(url, deferred);

                    deferred
                        .done(function () {
                            result.resolve(link);
                        })
                        .fail(result.reject);
                }
            })
            .fail(result.reject);

        return result.promise();
    }

    exports.addEmbeddedStyleSheet = addEmbeddedStyleSheet;
    exports.addLinkedStyleSheet   = addLinkedStyleSheet;
    exports.parseLessCode         = parseLessCode;
    exports.getModulePath         = getModulePath;
    exports.getModuleUrl          = getModuleUrl;
    exports.loadFile              = loadFile;
    exports.loadStyleSheet        = loadStyleSheet;
});
<|endoftext|>


<commit_before>"use strict";
/*
* Options:
* - title   ( string, optional, if value is "" not show.)
* - content ( string, required)
* - type    ( int, NORMAL/SUCCESS/WARING/ERROR)
*           ( optional, default is NORMAL )
*
* Param:
* - string：
*   - 1：content
*   - 2：type content or title content
*
* - object
*   - { type: xxx, title: xxx, content: xxx }
*
* Example:
* new Notify().Render( "Test" );
* new Notify().Render( 0, "Test 2" );
* new Notify().Render( 0, "Test title", "Test 3" );
* new Notify().Render( 0, "SimpTab has update.", "New version changlog here.", true );
* new Notify().Render( { title: "SimpTab has update.", content: "New version changlog here.", type: 0, closed: true } );
*
*/
var Notify = ( function () {
    var VERSION = "2.0.0",
        name    = "notify",
        root    = "notify-gp",
        roottmpl= "<" + root + ">",
        num     = 0,
        NORMAL  = 0,
        SUCCESS = 1,
        WARNING = 2,
        ERROR   = 3,
        options = {
            version : VERSION,
            title   : "",
            content : "",
            type    : NORMAL,
        },
        timer      = {},
        $container,
        TMPL       = '\
        <notify>\
            <notify-a href="javascript:;"><notify-span></notify-span></notify-a>\
            <notify-i></notify-i>\
            <notify-title></notify-title>\
            <notify-content></notify-content>\
            <notify-action></notify-action>\
        </notify>',
        prefix      = function( value ) {
            return name + "-" + value;
        },
        registyElement = function( name, elements ) {
            elements.forEach( function( item ) {
                document.createElement( prefix( item ));
            });
        },
        closeHandle = function( event ) {
            $container.undelegate( "." + event.data + " notify-a", "click", closeHandle );
            hidden( $(this).parent() );
        },
        delay = function( item ) {
            clearTimeout( timer[item] );
            delete timer[item];
            hidden( this );
        },
        hidden = function( target ) {
            target.addClass( "notify-hide" );
            target.slideUp( 500, function() {
                target.remove();
                if ($container.children().length === 0 ) $container.css( "z-index", 0 );
            });
        },
        render = function() {
            var $tmpl    = $( TMPL ),
                $title   = $tmpl.find(prefix( "title"   )),
                $content = $tmpl.find(prefix( "content" )),
                $close   = $tmpl.find(prefix( "a"       )),
                item     = "notify-item-" + num++;

            this.title   ? $title.text( this.title )     : $title.hide();
            this.content ? $content.html( this.content ) : $content.hide();

            /*if ( this.closed ) {
                $container.delegate( "." + item + " notify-a", "click", item, closeHandle );
            }
            else {
                $close.hide();
                timer[item] = setTimeout( delay.bind( $tmpl, item ), 1000 * 5 );
            }*/

            switch( this.type ) {
                case 1:
                    $content.addClass( "notify-success" );
                    break;
                case 2:
                    $content.addClass( "notify-warning" );
                    break;
                case 3:
                    $content.addClass( "notify-error" );
                    break;
            }

            $close.hide();
            timer[item] = setTimeout( delay.bind( $tmpl, item ), 1000 * 5 );

            $tmpl.addClass( item );
            $container.append( $tmpl ).css( "z-index", 2147483647 );
            setTimeout( function() { $tmpl.addClass( "notify-show" );}, 200 );
        };

    function Notify() {
        registyElement( name, [ "gp", "div", "a", "span", "title", "content", "i" ] );
        if ( $( "html" ).find ( root ).length == 0 ) {
            $( "html" ).append( roottmpl );
            $container = $( root );
        }
    }

    Notify.prototype.title   = options.title;
    Notify.prototype.content = options.content;
    Notify.prototype.type    = options.type;

    Notify.prototype.Render  = function () {

        var self = this;

        if ( arguments.length === 1 && typeof arguments[0] === "object" ) {
            options = arguments[0];

            Object.keys( options ).forEach( function( item ) {
                self[item] = options[item];
            });

            render.bind( self )();
        }
        else if ( typeof arguments[0] !== "object" && arguments.length > 0 && arguments.length < 5 ) {
            switch ( arguments.length ) {
                case 1:
                    this.content = arguments[0];
                    break;
                case 2:
                    if ( typeof arguments[0] == "number" ) {
                        this.type  = arguments[0];
                    } else {
                        this.title = arguments[0];
                    }
                    this.content = arguments[1];
                    break;
            }
            render.bind( self )();
        }
        else {
            console.error( "Arguments error", arguments );
        }
    };

    return Notify;

})();

module.exports = Notify;<commit_msg>Add new props: mode.<commit_after>"use strict";
/*
* Options:
* - title   ( string, optional, if value is "" not show.)
* - content ( string, required)
* - type    ( int, NORMAL/SUCCESS/WARING/ERROR)
*           ( optional, default is NORMAL )
* - mode    ( string, toast/modal/snackbar)
*           ( optional, default is toast )
*
* Param:
* - string：
*   - 1：content
*   - 2：type content or title content
*
* - object
*   - { type: xxx, title: xxx, content: xxx }
*
* Example:
* new Notify().Render( "Test" );
* new Notify().Render( 0, "Test 2" );
* new Notify().Render( 0, "Test title", "Test 3" );
* new Notify().Render( 0, "SimpTab has update.", "New version changlog here.", true );
* new Notify().Render( { title: "SimpTab has update.", content: "New version changlog here.", type: 0, closed: true } );
*
*/
var Notify = ( function () {
    var VERSION = "2.0.0",
        name    = "notify",
        root    = "notify-gp",
        roottmpl= "<" + root + ">",
        num     = 0,
        NORMAL  = 0,
        SUCCESS = 1,
        WARNING = 2,
        ERROR   = 3,
        MODE    = {
            toast    : "toast",
            modal    : "modal",
            snackbar : "snackbar",
        },
        options = {
            version : VERSION,
            title   : "",
            content : "",
            type    : NORMAL,
            mode    : MODE.toast,
        },
        timer      = {},
        $container,
        TMPL       = '\
        <notify>\
            <notify-a href="javascript:;"><notify-span></notify-span></notify-a>\
            <notify-i></notify-i>\
            <notify-title></notify-title>\
            <notify-content></notify-content>\
            <notify-action></notify-action>\
        </notify>',
        prefix      = function( value ) {
            return name + "-" + value;
        },
        registyElement = function( name, elements ) {
            elements.forEach( function( item ) {
                document.createElement( prefix( item ));
            });
        },
        closeHandle = function( event ) {
            $container.undelegate( "." + event.data + " notify-a", "click", closeHandle );
            hidden( $(this).parent() );
        },
        delay = function( item ) {
            clearTimeout( timer[item] );
            delete timer[item];
            hidden( this );
        },
        hidden = function( target ) {
            target.addClass( "notify-hide" );
            target.slideUp( 500, function() {
                target.remove();
                if ($container.children().length === 0 ) $container.css( "z-index", 0 );
            });
        },
        render = function() {
            var $tmpl    = $( TMPL ),
                $title   = $tmpl.find(prefix( "title"   )),
                $content = $tmpl.find(prefix( "content" )),
                $close   = $tmpl.find(prefix( "a"       )),
                item     = "notify-item-" + num++;

            this.title   ? $title.text( this.title )     : $title.hide();
            this.content ? $content.html( this.content ) : $content.hide();

            if ( this.mode === MODE.modal ) {
                $tmpl.addClass( "notify-modal" );
                $content.addClass( "notify-modal-content" );
                $container.delegate( "." + item + " notify-a", "click", item, closeHandle );
            } else {
                $close.hide();
                timer[item] = setTimeout( delay.bind( $tmpl, item ), 1000 * 5 );
                this.mode == MODE.snackbar && $tmpl.addClass( "notify-snackbar" );
            }

            switch( this.type ) {
                case 1:
                    $content.addClass( "notify-success" );
                    break;
                case 2:
                    $content.addClass( "notify-warning" );
                    break;
                case 3:
                    $content.addClass( "notify-error" );
                    break;
            }

            $tmpl.addClass( item );
            $container.append( $tmpl ).css( "z-index", 2147483647 );
            setTimeout( function() { $tmpl.addClass( "notify-show" );}, 200 );
        };

    function Notify() {
        registyElement( name, [ "gp", "div", "a", "span", "title", "content", "i" ] );
        if ( $( "html" ).find ( root ).length == 0 ) {
            $( "html" ).append( roottmpl );
            $container = $( root );
        }
    }

    Notify.prototype.title   = options.title;
    Notify.prototype.content = options.content;
    Notify.prototype.type    = options.type;

    Notify.prototype.Render  = function () {

        var self = this;

        if ( arguments.length === 1 && typeof arguments[0] === "object" ) {
            options = arguments[0];

            Object.keys( options ).forEach( function( item ) {
                self[item] = options[item];
            });

            render.bind( self )();
        }
        else if ( typeof arguments[0] !== "object" && arguments.length > 0 && arguments.length < 5 ) {
            switch ( arguments.length ) {
                case 1:
                    this.content = arguments[0];
                    break;
                case 2:
                    if ( typeof arguments[0] == "number" ) {
                        this.type  = arguments[0];
                    } else {
                        this.mode  = MODE.modal,
                        this.title = arguments[0];
                    }
                    this.content = arguments[1];
                    break;
            }
            render.bind( self )();
        }
        else {
            console.error( "Arguments error", arguments );
        }
    };

    return Notify;

})();

module.exports = Notify;<|endoftext|>


<commit_before>import { warnIfDebug } from 'utils/log';
import { COMPONENT, INTERPOLATOR } from 'config/types';
import Item from './shared/Item';
import construct from 'Ractive/construct';
import initialise from 'Ractive/initialise';
import { create } from 'utils/object';
import { removeFromArray } from 'utils/array';
import { isArray } from 'utils/is';
import resolve from '../resolvers/resolve';
import { cancel, unbind } from 'shared/methodCallers';
import Hook from 'events/Hook';
import Fragment from '../Fragment';
import parseJSON from 'utils/parseJSON';

function removeFromLiveComponentQueries ( component ) {
	let instance = component.ractive;

	while ( instance ) {
		const query = instance._liveComponentQueries[ `_${component.name}` ];
		if ( query ) query._remove( component );

		instance = instance.parent;
	}
}

const teardownHook = new Hook( 'teardown' );

export default class Component extends Item {
	constructor ( options, ComponentConstructor ) {
		super( options );
		this.type = COMPONENT; // override ELEMENT from super

		const instance = create( ComponentConstructor.prototype );

		this.instance = instance;
		this.name = options.template.e;
		this.parentFragment = options.parentFragment;
		this.resolvers = [];
		this.complexMappings = [];

		if ( instance.el ) {
			warnIfDebug( `The <${this.name}> component has a default 'el' property; it has been disregarded` );
		}

		let partials = options.template.p || {};
		if ( !( 'content' in partials ) ) partials.content = options.template.f || [];
		this._partials = partials; // TEMP

		this.yielders = {};

		construct( this.instance, { partials });

		// add component-instance-specific properties
		instance.parent = this.parentFragment.ractive;
		//instance.container = options.container || null; TODO...?
		instance.root = instance.parent.root;
		instance.component = this;

		// for hackability, this could be an open option
		// for any ractive instance, but for now, just
		// for components and just for ractive...
		// TODO is this still used?
		//instance._inlinePartials = options.inlinePartials;
	}

	bind () {
		const viewmodel = this.instance.viewmodel;
		const childData = viewmodel.value;

		let initialising = true;

		// determine mappings
		if ( this.template.a ) {
			Object.keys( this.template.a ).forEach( localKey => {
				const template = this.template.a[ localKey ];

				if ( template === 0 ) {
					// empty attributes are `true`
					viewmodel.joinKey( localKey ).set( true );
				}

				else if ( typeof template === 'string' ) {
					const parsed = parseJSON( template );
					viewmodel.joinKey( localKey ).set( parsed ? parsed.value : template );
				}

				else if ( isArray( template ) ) {
					if ( template.length === 1 && template[0].t === INTERPOLATOR ) {
						const model = resolve( this.parentFragment, template[0] );

						if ( model ) {
							viewmodel.map( localKey, model );

							if ( model.value === undefined && localKey in childData ) {
								model.set( childData[ localKey ] );
							}
						}

						else {
							const resolver = this.parentFragment.resolve( template[0].r, model => {
								viewmodel.map( localKey, model );
								viewmodel.clearUnresolveds( localKey );
							});

							// TODO is this necessary? or can the parentFragment handle cleanup?
							this.resolvers.push( resolver );
						}
					}

					else {
						const fragment = new Fragment({
							owner: this,
							template
						}).bind();

						const model = viewmodel.joinKey( localKey );
						model.set( fragment.valueOf() );

						// this is a *bit* of a hack
						fragment.bubble = () => {
							Fragment.prototype.bubble.call( fragment );
							model.set( fragment.valueOf() );
						};

						this.complexMappings.push( fragment );
					}
				}
			});
		}

		initialising = false;

		initialise( this.instance, {
			partials: this._partials
		}, {
			indexRefs: this.instance.isolated ? {} : this.parentFragment.indexRefs,
			keyRefs: this.instance.isolated ? {} : this.parentFragment.keyRefs,
			cssIds: this.parentFragment.cssIds
		});
	}

	bubble () {
		if ( !this.dirty ) {
			this.dirty = true;
			this.parentFragment.bubble();
		}
	}

	checkYielders () {
		Object.keys( this.yielders ).forEach( name => {
			if ( this.yielders[ name ].length > 1 ) {
				throw new Error( `A component template can only have one {{yield${name ? ' ' + name : ''}}} declaration at a time` );
			}
		});
	}

	detach () {
		return this.instance.detach();
	}

	find ( selector ) {
		return this.instance.fragment.find( selector );
	}

	findAll ( selector, queryResult ) {
		this.instance.fragment.findAll( selector, queryResult );
	}

	findComponent ( name ) {
		if ( this.name === name ) return this.instance;

		if ( this.instance.fragment ) {
			return this.instance.fragment.findComponent( name );
		}
	}

	findAllComponents ( name, queryResult ) {
		queryResult._test( this, true );
		this.instance.fragment.findAllComponents( name, queryResult );
	}

	firstNode () {
		return this.instance.fragment.firstNode();
	}

	// TODO can this be done in a less roundabout way?
	render () {
		var instance = this.instance;

		instance.render( this.parentFragment.findParentNode().cloneNode() );
		this.checkYielders();

		this.rendered = true;
		const docFrag = instance.fragment.detach();
		return docFrag;
	}

	toString () {
		return this.instance.toHTML();
	}

	unbind () {
		this.complexMappings.forEach( unbind );
		this.resolvers.forEach( unbind );

		const instance = this.instance;
		instance.viewmodel.teardown();
		instance.fragment.unbind();
		instance._observers.forEach( cancel );

		removeFromLiveComponentQueries( this );

		if ( instance.fragment.rendered && instance.el.__ractive_instances__ ) {
			removeFromArray( instance.el.__ractive_instances__, instance );
		}

		teardownHook.fire( instance );
	}

	unrender ( shouldDestroy ) {
		this.shouldDestroy = shouldDestroy;
		this.instance.unrender();
	}

	update () {
		this.instance.fragment.update();
		this.checkYielders();

		this.dirty = false;
	}
}
<commit_msg>component events<commit_after>import { warnIfDebug } from 'utils/log';
import { COMPONENT, INTERPOLATOR } from 'config/types';
import Item from './shared/Item';
import construct from 'Ractive/construct';
import initialise from 'Ractive/initialise';
import { create } from 'utils/object';
import { removeFromArray } from 'utils/array';
import { isArray } from 'utils/is';
import resolve from '../resolvers/resolve';
import { cancel, unbind } from 'shared/methodCallers';
import Hook from 'events/Hook';
import Fragment from '../Fragment';
import parseJSON from 'utils/parseJSON';
import fireEvent from 'events/fireEvent';

function removeFromLiveComponentQueries ( component ) {
	let instance = component.ractive;

	while ( instance ) {
		const query = instance._liveComponentQueries[ `_${component.name}` ];
		if ( query ) query._remove( component );

		instance = instance.parent;
	}
}

const teardownHook = new Hook( 'teardown' );

export default class Component extends Item {
	constructor ( options, ComponentConstructor ) {
		super( options );
		this.type = COMPONENT; // override ELEMENT from super

		const instance = create( ComponentConstructor.prototype );

		this.instance = instance;
		this.name = options.template.e;
		this.parentFragment = options.parentFragment;
		this.resolvers = [];
		this.complexMappings = [];

		if ( instance.el ) {
			warnIfDebug( `The <${this.name}> component has a default 'el' property; it has been disregarded` );
		}

		let partials = options.template.p || {};
		if ( !( 'content' in partials ) ) partials.content = options.template.f || [];
		this._partials = partials; // TEMP

		this.yielders = {};

		construct( this.instance, { partials });

		// add component-instance-specific properties
		instance.parent = this.parentFragment.ractive;
		//instance.container = options.container || null; TODO...?
		instance.root = instance.parent.root;
		instance.component = this;

		// for hackability, this could be an open option
		// for any ractive instance, but for now, just
		// for components and just for ractive...
		// TODO is this still used?
		//instance._inlinePartials = options.inlinePartials;

		if ( this.template.v ) this.setupEvents();
	}

	bind () {
		const viewmodel = this.instance.viewmodel;
		const childData = viewmodel.value;

		let initialising = true;

		// determine mappings
		if ( this.template.a ) {
			Object.keys( this.template.a ).forEach( localKey => {
				const template = this.template.a[ localKey ];

				if ( template === 0 ) {
					// empty attributes are `true`
					viewmodel.joinKey( localKey ).set( true );
				}

				else if ( typeof template === 'string' ) {
					const parsed = parseJSON( template );
					viewmodel.joinKey( localKey ).set( parsed ? parsed.value : template );
				}

				else if ( isArray( template ) ) {
					if ( template.length === 1 && template[0].t === INTERPOLATOR ) {
						const model = resolve( this.parentFragment, template[0] );

						if ( model ) {
							viewmodel.map( localKey, model );

							if ( model.value === undefined && localKey in childData ) {
								model.set( childData[ localKey ] );
							}
						}

						else {
							const resolver = this.parentFragment.resolve( template[0].r, model => {
								viewmodel.map( localKey, model );
								viewmodel.clearUnresolveds( localKey );
							});

							// TODO is this necessary? or can the parentFragment handle cleanup?
							this.resolvers.push( resolver );
						}
					}

					else {
						const fragment = new Fragment({
							owner: this,
							template
						}).bind();

						const model = viewmodel.joinKey( localKey );
						model.set( fragment.valueOf() );

						// this is a *bit* of a hack
						fragment.bubble = () => {
							Fragment.prototype.bubble.call( fragment );
							model.set( fragment.valueOf() );
						};

						this.complexMappings.push( fragment );
					}
				}
			});
		}

		initialising = false;

		initialise( this.instance, {
			partials: this._partials
		}, {
			indexRefs: this.instance.isolated ? {} : this.parentFragment.indexRefs,
			keyRefs: this.instance.isolated ? {} : this.parentFragment.keyRefs,
			cssIds: this.parentFragment.cssIds
		});
	}

	bubble () {
		if ( !this.dirty ) {
			this.dirty = true;
			this.parentFragment.bubble();
		}
	}

	checkYielders () {
		Object.keys( this.yielders ).forEach( name => {
			if ( this.yielders[ name ].length > 1 ) {
				throw new Error( `A component template can only have one {{yield${name ? ' ' + name : ''}}} declaration at a time` );
			}
		});
	}

	detach () {
		return this.instance.detach();
	}

	find ( selector ) {
		return this.instance.fragment.find( selector );
	}

	findAll ( selector, queryResult ) {
		this.instance.fragment.findAll( selector, queryResult );
	}

	findComponent ( name ) {
		if ( this.name === name ) return this.instance;

		if ( this.instance.fragment ) {
			return this.instance.fragment.findComponent( name );
		}
	}

	findAllComponents ( name, queryResult ) {
		queryResult._test( this, true );
		this.instance.fragment.findAllComponents( name, queryResult );
	}

	firstNode () {
		return this.instance.fragment.firstNode();
	}

	// TODO can this be done in a less roundabout way?
	render () {
		var instance = this.instance;

		instance.render( this.parentFragment.findParentNode().cloneNode() );
		this.checkYielders();

		this.rendered = true;
		const docFrag = instance.fragment.detach();
		return docFrag;
	}

	setupEvents () {
		Object.keys( this.template.v ).forEach( name => {
			const template = this.template.v[ name ];

			if ( typeof template !== 'string' ) {
				fatal( 'Components currently only support simple events - you cannot include arguments. Sorry!' );
			}

			const ractive = this.ractive;

			this.instance.on( name, function () {
				let event;

				// semi-weak test, but what else? tag the event obj ._isEvent ?
				if ( arguments.length && arguments[0] && arguments[0].node ) {
					event = Array.prototype.shift.call( arguments );
				}

				const args = Array.prototype.slice.call( arguments );

				fireEvent( ractive, template, { event, args });

				// cancel bubbling
				return false;
			});
		});
	}

	toString () {
		return this.instance.toHTML();
	}

	unbind () {
		this.complexMappings.forEach( unbind );
		this.resolvers.forEach( unbind );

		const instance = this.instance;
		instance.viewmodel.teardown();
		instance.fragment.unbind();
		instance._observers.forEach( cancel );

		removeFromLiveComponentQueries( this );

		if ( instance.fragment.rendered && instance.el.__ractive_instances__ ) {
			removeFromArray( instance.el.__ractive_instances__, instance );
		}

		teardownHook.fire( instance );
	}

	unrender ( shouldDestroy ) {
		this.shouldDestroy = shouldDestroy;
		this.instance.unrender();
	}

	update () {
		this.instance.fragment.update();
		this.checkYielders();

		this.dirty = false;
	}
}
<|endoftext|>


<commit_before>/// <reference path="../../../../ext/ext-core-debug.js"/>
/// <reference path="../../../../Simplate.js"/>
/// <reference path="../../../../sdata/SDataSingleResourceRequest.js"/>
/// <reference path="../../../../sdata/SDataService.js"/>
/// <reference path="../../../../platform/View.js"/>
/// <reference path="../../../../platform/Detail.js"/>
/// <reference path="../../Format.js"/>
/// <reference path="../../Template.js"/>

Ext.namespace("Mobile.SalesLogix.Contact");

Mobile.SalesLogix.Contact.Detail = Ext.extend(Sage.Platform.Mobile.Detail, {
    titleText: 'Contact',
    nameText: 'contact',
    accountText: 'account',
    workText: 'phone',
    homeText: 'home phone',
    mobileText: 'mobile',
    emailText: 'email',
    addressText: 'address',
    webText: 'web',
    acctMgrText: 'acct mgr',
    ownerText: 'owner',
    titlText: 'title',
    createUserText: 'create user',
    createDateText: 'create date',
    relatedItemsText: 'Related Items',
    relatedActivitiesText: 'Activities',
    relatedNotesText: 'Notes',
    faxText: 'fax',
    constructor: function(o) {
        Mobile.SalesLogix.Contact.Detail.superclass.constructor.call(this);

        Ext.apply(this, o, {
            id: 'contact_detail',
            title: this.titleText,
            editor: 'contact_edit',
            resourceKind: 'contacts'
        });

        this.layout = [
            {name: 'NameLF', label: this.nameText},
            {name: 'AccountName', descriptor: 'AccountName', label: this.accountText, view: 'account_detail', key: 'Account.$key', property: true},
            {name: 'WebAddress', label: this.webText, renderer: Mobile.SalesLogix.Format.link},
            {name: 'WorkPhone', label: this.workText, renderer: Mobile.SalesLogix.Format.phone},
            {name: 'Email', label: this.emailText, renderer: Mobile.SalesLogix.Format.mail},
            {name: 'Title', label: this.titlText},
            {name: 'Address', label: this.addressText, renderer: Mobile.SalesLogix.Format.address},
            {name: 'HomePhone', label: this.homeText, renderer: Mobile.SalesLogix.Format.phone},
            {name: 'Mobile', label: this.mobileText, renderer: Mobile.SalesLogix.Format.phone},
            {name: 'Fax', label: this.faxText, renderer: Mobile.SalesLogix.Format.phone},
            {name: 'AccountManager.UserInfo', label: this.acctMgrText, tpl: Mobile.SalesLogix.Template.nameLF},
            {name: 'Owner.OwnerDescription', label: this.ownerText},
            {options: {title: this.relatedItemsText, list: true}, as: [

                {
                    view: 'activity_related',
                    where: this.formatRelatedQuery.createDelegate(this, ['ContactId eq "{0}"'], true),
                    label: this.relatedActivitiesText,
                    icon: 'content/images/Task_List_3D_24x24.gif'
                },
                {
                    view: 'note_related',
                    where: this.formatRelatedQuery.createDelegate(this, ['ContactId eq "{0}" and Type eq "atNote"'], true),
                    label: this.relatedNotesText,
                    icon: 'content/images/note_24x24.gif'
                }

            ]}
        ];
    },

    init: function() {
        Mobile.SalesLogix.Contact.Detail.superclass.init.call(this);
    },
    createRequest: function() {
        var request = Mobile.SalesLogix.Contact.Detail.superclass.createRequest.call(this);

        request
            .setQueryArgs({
                'include': 'Account,Address,AccountManager,AccountManager/UserInfo,Owner',
                'select': [
                    'Account/AccountName',
                    'Name',
                    'NameLF',
                    'FirstName',
                    'LastName',
                    'AccountName',
                    'WorkPhone',
                    'Mobile',
                    'Email',
                    'Address/*',
                    'WebAddress',
                    'AccountManager/UserInfo/FirstName',
                    'AccountManager/UserInfo/LastName',
                    'Owner/OwnerDescription',
                    'CreateDate',
                    'CreateUser',
                    'Title',
                    'HomePhone',
                    'Mobile',
                    'Fax'

                ].join(',')
            });

        return request;
    }
});
<commit_msg>[#5074444] For Contact detail view, related items modified contact detail view<commit_after>/// <reference path="../../../../ext/ext-core-debug.js"/>
/// <reference path="../../../../Simplate.js"/>
/// <reference path="../../../../sdata/SDataSingleResourceRequest.js"/>
/// <reference path="../../../../sdata/SDataService.js"/>
/// <reference path="../../../../platform/View.js"/>
/// <reference path="../../../../platform/Detail.js"/>
/// <reference path="../../Format.js"/>
/// <reference path="../../Template.js"/>

Ext.namespace("Mobile.SalesLogix.Contact");

Mobile.SalesLogix.Contact.Detail = Ext.extend(Sage.Platform.Mobile.Detail, {
    titleText: 'Contact',
    nameText: 'contact',
    accountText: 'account',
    workText: 'phone',
    homeText: 'home phone',
    mobileText: 'mobile',
    emailText: 'email',
    addressText: 'address',
    webText: 'web',
    acctMgrText: 'acct mgr',
    ownerText: 'owner',
    titlText: 'title',
    createUserText: 'create user',
    createDateText: 'create date',
    relatedItemsText: 'Related Items',
    relatedActivitiesText: 'Activities',
    relatedNotesText: 'Notes',
    relatedAccountsText: 'Accounts',
    relatedOpportunitiesText: 'Opportunities',
    relatedTicketsText: 'Tickets',
    faxText: 'fax',
    constructor: function(o) {
        Mobile.SalesLogix.Contact.Detail.superclass.constructor.call(this);

        Ext.apply(this, o, {
            id: 'contact_detail',
            title: this.titleText,
            editor: 'contact_edit',
            resourceKind: 'contacts'
        });

        this.layout = [
            {name: 'NameLF', label: this.nameText},
            {name: 'AccountName', descriptor: 'AccountName', label: this.accountText, view: 'account_detail', key: 'Account.$key', property: true},
            {name: 'WebAddress', label: this.webText, renderer: Mobile.SalesLogix.Format.link},
            {name: 'WorkPhone', label: this.workText, renderer: Mobile.SalesLogix.Format.phone},
            {name: 'Email', label: this.emailText, renderer: Mobile.SalesLogix.Format.mail},
            {name: 'Title', label: this.titlText},
            {name: 'Address', label: this.addressText, renderer: Mobile.SalesLogix.Format.address},
            {name: 'HomePhone', label: this.homeText, renderer: Mobile.SalesLogix.Format.phone},
            {name: 'Mobile', label: this.mobileText, renderer: Mobile.SalesLogix.Format.phone},
            {name: 'Fax', label: this.faxText, renderer: Mobile.SalesLogix.Format.phone},
            {name: 'AccountManager.UserInfo', label: this.acctMgrText, tpl: Mobile.SalesLogix.Template.nameLF},
            {name: 'Owner.OwnerDescription', label: this.ownerText},
            {options: {title: this.relatedItemsText, list: true}, as: [

                {
                    view: 'activity_related',
                    where: this.formatRelatedQuery.createDelegate(this, ['ContactId eq "{0}"'], true),
                    label: this.relatedActivitiesText,
                    icon: 'content/images/Task_List_3D_24x24.gif'
                },
                {
                    view: 'note_related',
                    where: this.formatRelatedQuery.createDelegate(this, ['ContactId eq "{0}" and Type eq "atNote"'], true),
                    label: this.relatedNotesText,
                    icon: 'content/images/note_24x24.gif'
                },
                {
                    view: 'account_related',
                    where: this.formatRelatedQuery.createDelegate(this, ['Contact.Id eq "{0}"'], true),
                    label: this.relatedAccountsText,
                    icon: 'content/images/Accounts_24x24.gif'
                },
                {
                    view: 'opportunity_related',
                    where: this.formatRelatedQuery.createDelegate(this, ['ContactId eq "{0}"'], true),
                    label: this.relatedOpportunitiesText,
                    icon: 'content/images/Opportunity_List_24x24.gif'
                },
                {
                    view: 'ticket_related',
                    where: this.formatRelatedQuery.createDelegate(this, ['Contact.Id eq "{0}"'], true),
                    label: this.relatedTicketsText,
                    icon: 'content/images/Ticket_List_3D_32x32.gif'
                },
            ]}
        ];
    },

    init: function() {
        Mobile.SalesLogix.Contact.Detail.superclass.init.call(this);
    },
    createRequest: function() {
        var request = Mobile.SalesLogix.Contact.Detail.superclass.createRequest.call(this);

        request
            .setQueryArgs({
                'include': 'Account,Address,AccountManager,AccountManager/UserInfo,Owner',
                'select': [
                    'Account/AccountName',
                    'Name',
                    'NameLF',
                    'FirstName',
                    'LastName',
                    'AccountName',
                    'WorkPhone',
                    'Mobile',
                    'Email',
                    'Address/*',
                    'WebAddress',
                    'AccountManager/UserInfo/FirstName',
                    'AccountManager/UserInfo/LastName',
                    'Owner/OwnerDescription',
                    'CreateDate',
                    'CreateUser',
                    'Title',
                    'HomePhone',
                    'Mobile',
                    'Fax'

                ].join(',')
            });

        return request;
    }
});
<|endoftext|>


<commit_before>'use strict';
/*
 * This file was autogenerated
 * Any changes made here will be overriten!
 */

exports.EMOJI_PICKER_PATH = 'div#app-mount > div:eq(1)';

exports.SETTINGS_CLASSES = 5386;
exports.SWITCH_CLASSES = 5210;
exports.FLEX_CHILD_CLASSES = 2718;
exports.FLEX_CLASSES = 2719;
exports.HEADER_CLASSES = 2725;
exports.SWITCH_ITEM_CLASSES = 1239;
exports.DIVIDER_ITEM_CLASSES = 5211;
exports.LABEL_ITEM_CLASSES = 5209;
exports.FONT_SIZE_CLASSES = 2722;
exports.CARD_CLASSES = 2726;
exports.EMOJI_BUTTON_CLASS = 1322;
exports.LOCAL_STORAGE_MODULE = 2646;
exports.EMOJI_STORAGE_MODULE = 192;
exports.SERVERS_STORAGE_MODULE = 16;
exports.SERVERS_PERMISSIONS_MODULE = 43;
exports.TRANSLATION_MODULE = 3;
exports.CUSTOM_EMOJI_STORAGE_MODULE = 216;
exports.REACTION_EMOJI_CONVERTER = 338;
<commit_msg>Updated module numbers<commit_after>'use strict';
/*
 * This file was autogenerated
 * Any changes made here will be overriten!
 */

exports.EMOJI_PICKER_PATH = '.popouts';

exports.SETTINGS_CLASSES = 4830;
exports.SWITCH_CLASSES = 4526;
exports.FLEX_CHILD_CLASSES = 1103;
exports.FLEX_CLASSES = 1104;
exports.HEADER_CLASSES = 1205;
exports.SWITCH_ITEM_CLASSES = 1740;
exports.DIVIDER_ITEM_CLASSES = 4527;
exports.LABEL_ITEM_CLASSES = 4525;
exports.FONT_SIZE_CLASSES = 1159;
exports.CARD_CLASSES = 1170;
exports.EMOJI_BUTTON_CLASS = 5200;
exports.LOCAL_STORAGE_MODULE = 825;
exports.EMOJI_STORAGE_MODULE = 1305;
exports.SERVERS_STORAGE_MODULE = 45;
exports.SERVERS_PERMISSIONS_MODULE = 215;
exports.TRANSLATION_MODULE = 18;
exports.CUSTOM_EMOJI_STORAGE_MODULE = 1317;
exports.REACTION_EMOJI_CONVERTER = 1422;
<|endoftext|>


<commit_before>var _ = require('underscore');
var cdb = require('cartodb.js');
var AutoStylerFactory = require('./auto-style/factory');

/**
 * Default widget model
 *
 * Note: Currently all widgets have a dependency on a dataview, why it makes sense to have it here.
 * If you need a widget model that's backed up by a dataview model please implement your own model and adhere to the
 * public interface instead of extending/hacking this one.
 */
module.exports = cdb.core.Model.extend({
  defaults: {
    attrsNames: [],
    show_stats: false
  },

  defaultState: {
    'collapsed': false
  },

  initialize: function (attrs, models, opts) {
    opts = opts || {};
    this.dataviewModel = models.dataviewModel;
    this.defaults.autoStyleEnabled = opts.autoStyleEnabled;

    this.activeAutoStyler();
    this.bind('change:style', this.activeAutoStyler, this);
  },

  activeAutoStyler: function () {
    if (this.isAutoStyleEnabled() && !this.autoStyler) {
      this.autoStyler = AutoStylerFactory.get(this.dataviewModel, this.get('style'));
    }
  },

  /**
   * @public
   * @param {Object} attrs, not that it should be
   * @return {Boolean} true if at least one attribute was changed
   * @throws {Error} Should throw an error if the attrs are invalid or inconsistent
   */
  update: function (attrs) {
    var wAttrs = _.pick(attrs, this.get('attrsNames'));
    this.set(wAttrs);
    this.dataviewModel.update(attrs);
    this._triggerChangesInAutoStyle();
    return !!(this.changedAttributes() || this.dataviewModel.changedAttributes());
  },

  _triggerChangesInAutoStyle: function () {
    var changed = this.changed && this.changed.style && this.changed.style.auto_style && this.changed.style.auto_style.definition;
    var previous = this.previousAttributes();
    var former = previous.style && previous.style.auto_style && previous.style.auto_style.definition;

    if (!_.isEqual(changed, former)) {
      this.trigger('customAutoStyle', this);
    }
  },

  /**
   * @public
   */
  remove: function () {
    this.dataviewModel.remove();
    this.trigger('destroy', this);
    this.stopListening();
  },

  isAutoStyleEnabled: function () {
    if (!this.defaults.autoStyleEnabled) return false;

    var styles = this.get('style');

    if (this.get('type') === 'category' || this.get('type') === 'histogram') {
      if (!styles || !styles.auto_style) {
        return true;
      }
      return styles && styles.auto_style && styles.auto_style.allowed;
    } else {
      return false;
    }
  },

  getWidgetColor: function () {
    var styles = this.get('style');

    return styles && styles.widget_style &&
          styles.widget_style.definition &&
          styles.widget_style.definition.color &&
          styles.widget_style.definition.color.fixed;
  },

  getColor: function (name) {
    if (this.isAutoStyleEnabled() && this.isAutoStyle() && this.get('type') === 'category') {
      return this.autoStyler.colors.getColorByCategory(name);
    } else {
      return this.getWidgetColor();
    }
  },

  isAutoStyle: function () {
    return this.get('autoStyle');
  },

  autoStyle: function () {
    if (!this.isAutoStyleEnabled()) return;

    var layer = this.dataviewModel.layer;
    var initialStyle = layer.get('cartocss');
    if (!initialStyle && layer.get('meta')) {
      initialStyle = layer.get('meta').cartocss;
    }
    layer.set('initialStyle', initialStyle);

    var style = this.autoStyler.getStyle();
    layer.set('cartocss', style);
    this.set('autoStyle', true);
  },

  reapplyAutoStyle: function () {
    var style = this.autoStyler.getStyle();
    this.dataviewModel.layer.set('cartocss', style);
    this.set('autoStyle', true);
  },

  cancelAutoStyle: function (noRestore) {
    if (!noRestore) {
      this.dataviewModel.layer.restoreCartoCSS();
    }
    this.set('autoStyle', false);
  },

  getAutoStyle: function () {
    var style = this.get('style');
    var layerModel = this.dataviewModel.layer;
    var cartocss = layerModel.get('cartocss') || (layerModel.get('meta') && layerModel.get('meta').cartocss);

    if (style && style.auto_style && style.auto_style.definition) {
      var toRet = _.extend(style.auto_style, {cartocss: cartocss});
      return _.extend({}, toRet, {definition: this.autoStyler.getDef(cartocss)});
    } else {
      return {
        definition: this.autoStyler.getDef(cartocss),
        cartocss: cartocss
      };
    }
  },

  setInitialState: function (state) {
    this.initialState = state || {};
  },

  applyInitialState: function () {
    var attrs = _.extend(
      this.initialState,
      {hasInitialState: true}
    );

    this.setState(attrs);
  },

  setState: function (state) {
    this.set(state);
  },

  getState: function () {
    var state = {};
    for (var key in this.defaultState) {
      var attribute = this.get(key);
      var defaultValue = this.defaultState[key];
      if (typeof defaultValue !== 'undefined' && typeof attribute !== 'undefined' && !_.isEqual(attribute, defaultValue)) {
        state[key] = attribute;
      }
    }
    return state;
  }
});
<commit_msg>CR feedback applied<commit_after>var _ = require('underscore');
var cdb = require('cartodb.js');
var AutoStylerFactory = require('./auto-style/factory');

/**
 * Default widget model
 *
 * Note: Currently all widgets have a dependency on a dataview, why it makes sense to have it here.
 * If you need a widget model that's backed up by a dataview model please implement your own model and adhere to the
 * public interface instead of extending/hacking this one.
 */
module.exports = cdb.core.Model.extend({
  defaults: {
    attrsNames: [],
    show_stats: false
  },

  defaultState: {
    'collapsed': false
  },

  initialize: function (attrs, models, opts) {
    opts = opts || {};
    this.dataviewModel = models.dataviewModel;
    this.defaults.autoStyleEnabled = opts.autoStyleEnabled;

    this.activeAutoStyler();
    this.bind('change:style', this.activeAutoStyler, this);
  },

  activeAutoStyler: function () {
    if (this.isAutoStyleEnabled() && !this.autoStyler) {
      this.autoStyler = AutoStylerFactory.get(this.dataviewModel, this.get('style'));
    }
  },

  /**
   * @public
   * @param {Object} attrs, not that it should be
   * @return {Boolean} true if at least one attribute was changed
   * @throws {Error} Should throw an error if the attrs are invalid or inconsistent
   */
  update: function (attrs) {
    var wAttrs = _.pick(attrs, this.get('attrsNames'));
    this.set(wAttrs);
    this.dataviewModel.update(attrs);
    this._triggerChangesInAutoStyle();
    return !!(this.changedAttributes() || this.dataviewModel.changedAttributes());
  },

  _triggerChangesInAutoStyle: function () {
    var changed = this.changed && this.changed.style && this.changed.style.auto_style && this.changed.style.auto_style.definition;
    var previous = this.previousAttributes();
    var former = previous.style && previous.style.auto_style && previous.style.auto_style.definition;

    if (!_.isEqual(changed, former)) {
      this.trigger('customAutoStyle', this);
    }
  },

  /**
   * @public
   */
  remove: function () {
    this.dataviewModel.remove();
    this.trigger('destroy', this);
    this.stopListening();
  },

  isAutoStyleEnabled: function () {
    if (!this.defaults.autoStyleEnabled) return false;

    var styles = this.get('style');

    if (this.get('type') === 'category' || this.get('type') === 'histogram') {
      return (styles && styles.auto_style && styles.auto_style.allowed) || true;
    } else {
      return false;
    }
  },

  getWidgetColor: function () {
    var styles = this.get('style');

    return styles && styles.widget_style &&
          styles.widget_style.definition &&
          styles.widget_style.definition.color &&
          styles.widget_style.definition.color.fixed;
  },

  getColor: function (name) {
    if (this.isAutoStyleEnabled() && this.isAutoStyle() && this.get('type') === 'category') {
      return this.autoStyler.colors.getColorByCategory(name);
    } else {
      return this.getWidgetColor();
    }
  },

  isAutoStyle: function () {
    return this.get('autoStyle');
  },

  autoStyle: function () {
    if (!this.isAutoStyleEnabled()) return;

    var layer = this.dataviewModel.layer;
    var initialStyle = layer.get('cartocss');
    if (!initialStyle && layer.get('meta')) {
      initialStyle = layer.get('meta').cartocss;
    }
    layer.set('initialStyle', initialStyle);

    var style = this.autoStyler.getStyle();
    layer.set('cartocss', style);
    this.set('autoStyle', true);
  },

  reapplyAutoStyle: function () {
    var style = this.autoStyler.getStyle();
    this.dataviewModel.layer.set('cartocss', style);
    this.set('autoStyle', true);
  },

  cancelAutoStyle: function (noRestore) {
    if (!noRestore) {
      this.dataviewModel.layer.restoreCartoCSS();
    }
    this.set('autoStyle', false);
  },

  getAutoStyle: function () {
    var style = this.get('style');
    var layerModel = this.dataviewModel.layer;
    var cartocss = layerModel.get('cartocss') || (layerModel.get('meta') && layerModel.get('meta').cartocss);

    if (style && style.auto_style && style.auto_style.definition) {
      var toRet = _.extend(style.auto_style, {cartocss: cartocss});
      return _.extend({}, toRet, {definition: this.autoStyler.getDef(cartocss)});
    } else {
      return {
        definition: this.autoStyler.getDef(cartocss),
        cartocss: cartocss
      };
    }
  },

  setInitialState: function (state) {
    this.initialState = state || {};
  },

  applyInitialState: function () {
    var attrs = _.extend(
      this.initialState,
      {hasInitialState: true}
    );

    this.setState(attrs);
  },

  setState: function (state) {
    this.set(state);
  },

  getState: function () {
    var state = {};
    for (var key in this.defaultState) {
      var attribute = this.get(key);
      var defaultValue = this.defaultState[key];
      if (typeof defaultValue !== 'undefined' && typeof attribute !== 'undefined' && !_.isEqual(attribute, defaultValue)) {
        state[key] = attribute;
      }
    }
    return state;
  }
});
<|endoftext|>


<commit_before>'use strict'

/* var CPBAPI = require('cpasbien-api')
var CpasbienApi = new CPBAPI()
*/
var cloudscraper = require('cloudscraper')
var cheerio = require('cheerio')

/**
 * Search torrent.
 * @constructor
*/
function SearchTorrent () {
  this.url = new Buffer('aHR0cDovL3d3dy50b3JyZW50OS50b3AK', 'base64').toString()
}

/**
 * Search a torrent.
 * @param {string} query - Torrent name to search.
 * @param {function} callback - Return function with informations.
*/
SearchTorrent.prototype.search = function (query, callback) {
  var self = this
  var search = function () {
    var torrents = {
      tv: {
        items: [],
        type: 'films'
      },
      mv: {
        items: [],
        type: 'series'
      }
    }

    cloudscraper.get(`${self.url}/search_torrent/films/${query}.html`, function (err, res, body) {
      if (err) {
        console.error(err)
      }
      var $ = cheerio.load(body)
      torrents.mv.items = self.parse($, $('.table tbody tr'))
      cloudscraper.get(`${self.url}/search_torrent/series/${query}.html`, function (err, res, body) {
        if (err) {
          console.error(err)
        }
        var $ = cheerio.load(body)

        torrents.tv.items = self.parse($, $('.table tbody').children('tr'))
        callback(torrents)
      })
    })
  }

  setTimeout(search)
}

/**
 * Search the latest torrents.
 * @param {function} callback - Return function with informations.
*/
SearchTorrent.prototype.latest = function (callback) {
  var self = this
  var latest = function () {
    var torrents = {
      tv: {
        items: [],
        type: 'films'
      },
      mv: {
        items: [],
        type: 'series'
      }
    }

    cloudscraper.get(`${self.url}/torrents_films.html`, function (err, res, body) {
      if (err) {
        console.error(err)
      }
      var $ = cheerio.load(body)
      torrents.mv.items = self.parse($, $('.table-responsive tbody tr'))
      cloudscraper.get(`${self.url}/torrents_series.html`, function (err, res, body) {
        if (err) {
          console.error(err)
        }
        var $ = cheerio.load(body)

        torrents.tv.items = self.parse($, $('.table-responsive tbody').children('tr'))
        callback(torrents)
      })
    })
  }

  setTimeout(latest)
}

SearchTorrent.prototype.parse = function ($, tr) {
  var self = this
  var array = []
  for (var key in tr) {
    if (!isNaN(key)) {
      var $line = $(tr[key])
      var torrent = {}
      torrent.title = $($line.children()[0]).find('a').text()
      torrent.size = $($line.children()[1]).text()
      torrent.seeds = $($($line.children()[2]).find('span')).text()
      torrent.leechs = $($line.children()[3]).text()
      torrent.torrent = `${self.url}/get_torrent/${$($line.children()[0]).find('a').attr('href').split('/').pop()}.torrent`
      array.push(torrent)
    }
  }

  return array
}
module.exports = new SearchTorrent()
<commit_msg>fixing base64<commit_after>'use strict'

/* var CPBAPI = require('cpasbien-api')
var CpasbienApi = new CPBAPI()
*/
var cloudscraper = require('cloudscraper')
var cheerio = require('cheerio')

/**
 * Search torrent.
 * @constructor
*/
function SearchTorrent () {
  this.url = new Buffer('aHR0cDovL3d3dy50b3JyZW50OS50b3A=', 'base64').toString()
}

/**
 * Search a torrent.
 * @param {string} query - Torrent name to search.
 * @param {function} callback - Return function with informations.
*/
SearchTorrent.prototype.search = function (query, callback) {
  var self = this
  var search = function () {
    var torrents = {
      tv: {
        items: [],
        type: 'films'
      },
      mv: {
        items: [],
        type: 'series'
      }
    }

    cloudscraper.get(`${self.url}/search_torrent/films/${query}.html`, function (err, res, body) {
      if (err) {
        console.error(err)
      }
      var $ = cheerio.load(body)
      torrents.mv.items = self.parse($, $('.table tbody tr'))
      cloudscraper.get(`${self.url}/search_torrent/series/${query}.html`, function (err, res, body) {
        if (err) {
          console.error(err)
        }
        var $ = cheerio.load(body)

        torrents.tv.items = self.parse($, $('.table tbody').children('tr'))
        callback(torrents)
      })
    })
  }

  setTimeout(search)
}

/**
 * Search the latest torrents.
 * @param {function} callback - Return function with informations.
*/
SearchTorrent.prototype.latest = function (callback) {
  var self = this
  var latest = function () {
    var torrents = {
      tv: {
        items: [],
        type: 'films'
      },
      mv: {
        items: [],
        type: 'series'
      }
    }

    cloudscraper.get(`${self.url}/torrents_films.html`, function (err, res, body) {
      if (err) {
        console.error(err)
      }
      var $ = cheerio.load(body)
      torrents.mv.items = self.parse($, $('.table-responsive tbody tr'))
      cloudscraper.get(`${self.url}/torrents_series.html`, function (err, res, body) {
        if (err) {
          console.error(err)
        }
        var $ = cheerio.load(body)

        torrents.tv.items = self.parse($, $('.table-responsive tbody').children('tr'))
        callback(torrents)
      })
    })
  }

  setTimeout(latest)
}

SearchTorrent.prototype.parse = function ($, tr) {
  var self = this
  var array = []
  for (var key in tr) {
    if (!isNaN(key)) {
      var $line = $(tr[key])
      var torrent = {}
      torrent.title = $($line.children()[0]).find('a').text()
      torrent.size = $($line.children()[1]).text()
      torrent.seeds = $($($line.children()[2]).find('span')).text()
      torrent.leechs = $($line.children()[3]).text()
      torrent.torrent = `${self.url}/get_torrent/${$($line.children()[0]).find('a').attr('href').split('/').pop()}.torrent`
      array.push(torrent)
    }
  }

  return array
}
module.exports = new SearchTorrent()
<|endoftext|>


<commit_before>(global => {
    'use strict';

    const toolbox = global.toolbox;

    class StaticCache {
        constructor(baseUrl) {
            this.cacheName = toolbox.options.cache.name;
            this.baseUrl = baseUrl;
            toolbox.cache(baseUrl);
        }

        listen() {
            global.addEventListener('fetch', (event) => {
                if (event.request.method === 'GET') {
                    event.respondWith(
                        this.fetchBootstrap(event)
                    );
                }
            });
        }

        indexFallback(event, cache) {
            return cache.keys().then((keys) => {
                let key;
                keys.some((cacheValue) => {
                    if (cacheValue.url === this.baseUrl) {
                        key = cacheValue;
                        return true;
                    }
                    return false;
                });
                return cache.match(key).then((indexResponse) => {
                    if (indexResponse && indexResponse.ok) {
                        return Promise.resolve(indexResponse);
                    }
                    return Promise.reject();
                });
            });
        }

        cacheFallback(event) {
            return caches.open(this.cacheName).then((cache) =>
                cache.match(event.request)
                    .then((cacheResponse) => {
                        if (cacheResponse) {
                            return Promise.resolve(cacheResponse);
                        }
                        return this.indexFallback(event, cache);
                    })
                    .catch(() => this.indexFallback(event, cache))
            );
        }

        fetchBootstrap(event) {
            return Promise.resolve(
                fetch(event.request)
                    .then((response) => {
                        if (response && response.ok) {
                            return Promise.resolve(response);
                        }
                        return this.cacheFallback(event);
                    })
                    .catch(() => this.cacheFallback(event))
            );
        }
    }

    // export
    global.StaticCache = StaticCache;
})(self);
<commit_msg>fix: service worker static cache only for same origin<commit_after>(global => {
    'use strict';

    const toolbox = global.toolbox;

    class StaticCache {
        constructor(baseUrl) {
            this.cacheName = toolbox.options.cache.name;
            this.baseUrl = baseUrl;
            toolbox.cache(baseUrl);
        }

        listen() {
            global.addEventListener('fetch', (event) => {
                if (event.request.method === 'GET' &&
                    event.request.url.match(new RegExp(`^${global.location.origin}`))) {
                    event.respondWith(
                        this.fetchBootstrap(event)
                    );
                }
            });
        }

        indexFallback(event, cache) {
            return cache.keys().then((keys) => {
                let key;
                keys.some((cacheValue) => {
                    if (cacheValue.url === this.baseUrl) {
                        key = cacheValue;
                        return true;
                    }
                    return false;
                });
                return cache.match(key).then((indexResponse) => {
                    if (indexResponse && indexResponse.ok) {
                        return Promise.resolve(indexResponse);
                    }
                    return Promise.reject();
                });
            });
        }

        cacheFallback(event) {
            return caches.open(this.cacheName).then((cache) =>
                cache.match(event.request)
                    .then((cacheResponse) => {
                        if (cacheResponse) {
                            return Promise.resolve(cacheResponse);
                        }
                        return this.indexFallback(event, cache);
                    })
                    .catch(() => this.indexFallback(event, cache))
            );
        }

        fetchBootstrap(event) {
            return Promise.resolve(
                fetch(event.request)
                    .then((response) => {
                        if (response && response.ok) {
                            return Promise.resolve(response);
                        }
                        return this.cacheFallback(event);
                    })
                    .catch(() => this.cacheFallback(event))
            );
        }
    }

    // export
    global.StaticCache = StaticCache;
})(self);
<|endoftext|>


<commit_before><commit_msg>preliminary commit of date with dc js<commit_after><|endoftext|>


<commit_before>db.users.remove({});
db.users.insert({
    userId : 'kaidouji85@gmail.com',
    armdozerId : 'granBraver'
});
db.users.insert({
    userId : 'gbraver85001@gmail.com',
    armdozerId : 'landozer'
});

db.armdozers.remove({});
db.armdozers.insert({
    armdozerId : 'granBraver',
    name : 'グランブレイバー',
    pictName : 'GranBraver.PNG',
    hp : 3000,
    speed : 110,
    weapons : {
        1 : {
            name : 'バスターナックル',
            power : 1000
        },
        2 : {
            name : 'バスターナックル',
            power : 1000
        },
        3 : {
            name : 'バスターナックル',
            power : 1000
        },
        4 : {
            name : 'バスターナックル',
            power : 1000
        },
        5 : {
            name : 'バスターナックル',
            power : 1000
        }
    }
});

db.armdozers.insert({
    armdozerId : 'landozer',
    name : 'ランドーザ',
    pictName : 'Landozer.PNG',
    hp : 3100,
    speed : 95,
    weapons : {
        1 : {
            name : 'ブレイクパンチ',
            power : 1200
        },
        2 : {
            name : 'ブレイクパンチ',
            power : 1200
        },
        3 : {
            name : 'ブレイクパンチ',
            power : 1200
        },
        4 : {
            name : 'ブレイクパンチ',
            power : 1200
        },
        5 : {
            name : 'ブレイクパンチ',
            power : 1200
        }
    }
});

db.armdozers.insert({
    armdozerId : 'zeroBraver',
    name : 'ゼロブレイバー',
    pictName : 'ZeroBraver.PNG',
    hp : 2100,
    speed : 125,
    weapons : {
        1 : {
            name : 'バスターナックル',
            power : 1000
        },
        2 : {
            name : 'バスターナックル',
            power : 1000
        },
        3 : {
            name : 'バスターナックル',
            power : 1000
        },
        4 : {
            name : 'バスターナックル',
            power : 1000
        },
        5 : {
            name : 'バスターナックル',
            power : 1000
        }
    }
});<commit_msg>ランドーザ、ゼロブレイバーのステータスを調整した。<commit_after>db.users.remove({});
db.users.insert({
    userId : 'kaidouji85@gmail.com',
    armdozerId : 'granBraver'
});
db.users.insert({
    userId : 'gbraver85001@gmail.com',
    armdozerId : 'landozer'
});

db.armdozers.remove({});
db.armdozers.insert({
    armdozerId : 'granBraver',
    name : 'グランブレイバー',
    pictName : 'GranBraver.PNG',
    hp : 3000,
    speed : 110,
    weapons : {
        1 : {
            name : 'バスターナックル',
            power : 1000
        },
        2 : {
            name : 'バスターナックル',
            power : 1000
        },
        3 : {
            name : 'バスターナックル',
            power : 1000
        },
        4 : {
            name : 'バスターナックル',
            power : 1000
        },
        5 : {
            name : 'バスターナックル',
            power : 1000
        }
    }
});

db.armdozers.insert({
    armdozerId : 'landozer',
    name : 'ランドーザ',
    pictName : 'Landozer.PNG',
    hp : 3500,
    speed : 95,
    weapons : {
        1 : {
            name : 'ブレイクパンチ',
            power : 900
        },
        2 : {
            name : 'ブレイクパンチ',
            power : 900
        },
        3 : {
            name : 'ブレイクパンチ',
            power : 900
        },
        4 : {
            name : 'ブレイクパンチ',
            power : 900
        },
        5 : {
            name : 'ブレイクパンチ',
            power : 900
        }
    }
});

db.armdozers.insert({
    armdozerId : 'zeroBraver',
    name : 'ゼロブレイバー',
    pictName : 'ZeroBraver.PNG',
    hp : 2100,
    speed : 125,
    weapons : {
        1 : {
            name : 'バスターナックル',
            power : 1100
        },
        2 : {
            name : 'バスターナックル',
            power : 1100
        },
        3 : {
            name : 'バスターナックル',
            power : 1100
        },
        4 : {
            name : 'バスターナックル',
            power : 1100
        },
        5 : {
            name : 'バスターナックル',
            power : 1100
        }
    }
});<|endoftext|>