<commit_before>$(window).resize(function () {
    var h = $(window).height(),
      offsetTop = 105; // Calculate the top offset

    $('#map').css('height', (h - offsetTop));
}).resize();

(function(){
    var grid_layer = new L.FeatureGroup();
    var jenks_cutoffs;
    var map = L.map('map').fitBounds([[41.644286009999995, -87.94010087999999], [42.023134979999995, -87.52366115999999]]);
    L.tileLayer('https://{s}.tiles.mapbox.com/v3/datamade.hn83a654/{z}/{x}/{y}.png', {
        attribution: 'Terms & Feedback'
    }).addTo(map);
    var start_date = moment().subtract('days', 372);
    var end_date = moment().subtract('days', 7);
    var min_date = moment().subtract('years', 5);
    var max_date = moment().subtract('days', 7);
    var grid_data = {
        dataset: 'chicago_crimes_all',
        human_name: 'Crimes - 2001 to present',
        resolution: 1000, //in meters
        obs_from: start_date.format('YYYY-MM-DD'),
        obs_to: end_date.format('YYYY-MM-DD')
    }
    var legend = L.control({position: 'bottomright'});
    legend.onAdd = function(map){
        var div = L.DomUtil.create('div', 'legend')
        var labels = [];
        var from;
        var to;
        $.each(jenks_cutoffs, function(i, grade){
            from = grade
            to = jenks_cutoffs[i + 1];
            labels.push('' +
                       from + (to ? '–' + to : '+'));
        });
        div.innerHTML = '
' + grid_data['human_name'] + '
' + labels.join('
') + '
';
        return div
    }
    var drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);
    var drawControl = new L.Control.Draw({
        edit: {
            featureGroup: drawnItems
        },
        draw: {
            circle: false,
            marker: false,
            polygon: {
                shapeOptions: {
                    'color': '#123456',
                    'opacity': 0.4,
                    'fillOpacity': 0
                }
            },
            rectangle: {
                shapeOptions: {
                    'color': '#123456',
                    'opacity': 0.4,
                    'fillOpacity': 0
                }
            }
        }
    });
    map.addControl(drawControl);
    var d = new L.Control.Distance(); map.addControl(d);
    map.addControl(new L.Control.Scale());
    map.on('draw:created', draw_create);
    map.on('draw:edited', draw_edit);
    map.on('draw:deleted', draw_delete);
    map.on('draw:drawstart', draw_delete);
    var map_colors = [
        '#deebf7',
        '#c6dbef',
        '#9ecae1',
        '#6baed6',
        '#4292c6',
        '#2171b5',
        '#084594'
    ]
    var date_range_opts = {
        format: 'M/D/YYYY',
        showDropdowns: true,
        startDate: start_date,
        endDate: end_date,
        minDate: min_date,
        maxDate: max_date
    }
    $('#date_range').daterangepicker(
      date_range_opts,
      date_range_callback
    )
    update_date_range();
    $('#dataset-picker').on('change', function(e){
        var name = $(this).val();
        grid_data['dataset'] = name;
        grid_data['human_name'] = $('#dataset-picker').find(':selected').first().text().trim();
        $('.yearpicker').hide();
        $('#' + name + '-yearpicker').show();
        loadLayer(grid_data);
    });
    $('#resolution-picker').on('change', function(e){
        grid_data['resolution'] = parseFloat($(this).val());
        loadLayer(grid_data);
    });
    $('#buffer-picker').on('change', function(e){
        grid_data['buffer'] = parseFloat($(this).val());
        loadLayer(grid_data);
    })
    loadLayer(grid_data);
    $('.showmore').on('click', function(){
        var add_height = $('#dataset-description').height();
        $('.showmore-content').height(add_height);
        $(this).hide()
        $('.showless').show()
    });
    $('.showless').on('click', function(){
        $('.showmore-content').height(165);
        $(this).hide()
        $('.showmore').show()
    })
    function date_range_callback(start, end, label){
        start_date = start;
        end_date = end;
    }
    function draw_create(e){
        if(e.layerType == 'polyline'){
            $('#buffer').show();
        } else {
            $('#buffer').hide();
        }
        drawnItems.addLayer(e.layer);
        grid_data['location_geom__within'] = JSON.stringify(e.layer.toGeoJSON());
        loadLayer(grid_data)
    }
    function draw_edit(e){
        var layers = e.layers;
        layers.eachLayer(function(layer){
            drawnItems.addLayer(layer);
            grid_data['location_geom__within'] = JSON.stringify(layer.toGeoJSON());
        });
    }
    function draw_delete(e){
        grid_layer.clearLayers();
        drawnItems.clearLayers();
    }
    function loadLayer(grid_data){
        $('#map').spin('large');
        grid_data['center'] = [map.getCenter().lat, map.getCenter().lng]
        var url ='/api/grid/'
        $.when(getGrid(url, grid_data), $.getJSON('/api/', {'dataset_name': grid_data['dataset']})).then(
            function(grid, meta){
                grid = grid[0];
                meta = meta[0][0];
                $('#map').spin(false);
                var values = [];
                $.each(grid['features'], function(i, val){
                    values.push(val['properties']['count']);
                });
                try{legend.removeFrom(map);}catch(e){};
                grid_layer.clearLayers();
                if (typeof grid_layer !== 'undefined'){
                    map.removeLayer(grid_layer);
                }
                // Should probably do something here to let users know
                // that there are no results
                if (values.length > 0){
                    jenks_cutoffs = jenks(values, 6);
                    jenks_cutoffs[0] = 0;
                    jenks_cutoffs.pop();
                    grid_layer.addLayer(L.geoJson(grid, {
                        style: styleGrid,
                        onEachFeature: function(feature, layer){
                            var content = '
Count: ' + feature.properties.count + '
';
                            layer.bindLabel(content);
                        }
                    })).addTo(map);
                    legend.addTo(map);
                    map.fitBounds(grid_layer.getBounds());
                }
                if (meta.obs_from){
                    min_date = moment(meta['obs_from'], 'YYYY-MM-DD');
                } else {
                    min_date = moment().subtract('years', 5);
                }
                if (meta.obs_to){
                    max_date = moment(meta['obs_to'], 'YYYY-MM-DD');
                } else {
                    max_date = moment();
                }
                if (end_date.isAfter(max_date)){
                    end_date = max_date;
                }
                if (start_date.isBefore(min_date)){
                    start_state = min_date;
                }
                date_range_opts['minDate'] = min_date
                date_range_opts['maxDate'] = max_date
                date_range_opts['startDate'] = start_date
                date_range_opts['endDate'] = end_date
                $('#date_range').daterangepicker(date_range_opts, date_range_callback);
                $('#date_range').on('apply.daterangepicker', function(ev, picker) {
                    start_date = picker.startDate
                    end_date = picker.endDate
                    grid_data['obs_from'] = start_date.format('YYYY-MM-DD')
                    grid_data['obs_to'] = end_date.format('YYYY-MM-DD')
                    loadLayer(grid_data);
                });
                update_date_range();
                $('#dataset-name').html(meta['human_name']);
                $('#dataset-description').html(meta['description']);
            }
        );
    }

    function getColor(d){
        return d >= jenks_cutoffs[5] ? map_colors[6] :
               d >= jenks_cutoffs[4] ? map_colors[5] :
               d >= jenks_cutoffs[3] ? map_colors[4] :
               d >= jenks_cutoffs[2] ? map_colors[3] :
               d >= jenks_cutoffs[1] ? map_colors[2] :
               d >= jenks_cutoffs[0] ? map_colors[1] :
                                       map_colors[0];
    }

    function styleGrid(feature){
        return {
            fillColor: getColor(feature.properties.count),
            weight: 0.3,
            opacity: 1,
            color: 'white',
            fillOpacity: 0.7
        };
    }

    function getFieldDefs(dataset_name){
        $.when($.getJSON('/api/fields/' + dataset_name + '/')).then(
            function(fields){
                $('#fielddefs').show();
                $('#fielddefs-list').val()
            }
        )
    }

    function getGrid(url, grid){
        var data = {
            dataset_name: grid['dataset'],
            resolution: grid['resolution'],
            center: grid['center'],
            obs_date__ge: grid['obs_from'],
            obs_date__le: grid['obs_to']
        }
        if (typeof grid['location_geom__within'] !== 'undefined'){
            data['location_geom__within'] = grid['location_geom__within']
        }
        if (typeof grid['buffer'] !== 'undefined'){
            data['buffer'] = grid['buffer']
        }
        return $.getJSON(url, data)
    }
    function update_date_range(){
        $('#date_range').val(start_date.format('M/D/YYYY') + " - " + end_date.format('M/D/YYYY'));
    }
})()
<commit_msg>refactored distance controls<commit_after>$(window).resize(function () {
    var h = $(window).height(),
      offsetTop = 105; // Calculate the top offset

    $('#map').css('height', (h - offsetTop));
}).resize();

(function(){
    var grid_layer = new L.FeatureGroup();
    var jenks_cutoffs;
    var map = L.map('map').fitBounds([[41.644286009999995, -87.94010087999999], [42.023134979999995, -87.52366115999999]]);
    L.tileLayer('https://{s}.tiles.mapbox.com/v3/datamade.hn83a654/{z}/{x}/{y}.png', {
        attribution: 'Terms & Feedback'
    }).addTo(map);
    var start_date = moment().subtract('days', 372);
    var end_date = moment().subtract('days', 7);
    var min_date = moment().subtract('years', 5);
    var max_date = moment().subtract('days', 7);
    var grid_data = {
        dataset: 'chicago_crimes_all',
        human_name: 'Crimes - 2001 to present',
        resolution: 1000, //in meters
        obs_from: start_date.format('YYYY-MM-DD'),
        obs_to: end_date.format('YYYY-MM-DD')
    }
    var legend = L.control({position: 'bottomright'});
    legend.onAdd = function(map){
        var div = L.DomUtil.create('div', 'legend')
        var labels = [];
        var from;
        var to;
        $.each(jenks_cutoffs, function(i, grade){
            from = grade
            to = jenks_cutoffs[i + 1];
            labels.push('' +
                       from + (to ? '–' + to : '+'));
        });
        div.innerHTML = '
' + grid_data['human_name'] + '
' + labels.join('
') + '
';
        return div
    }
    var drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);
    var drawControl = new L.Control.Draw({
        edit: {
            featureGroup: drawnItems
        },
        draw: {
            circle: false,
            marker: false,
            polygon: {
                shapeOptions: {
                    'color': '#123456',
                    'opacity': 0.4,
                    'fillOpacity': 0
                }
            },
            rectangle: {
                shapeOptions: {
                    'color': '#123456',
                    'opacity': 0.4,
                    'fillOpacity': 0
                }
            }
        }
    });
    map.addControl(drawControl);
    map.addControl(new L.Control.Distance()); //distance plugin when drawing lines
    map.addControl(new L.Control.Scale()); //show distance scale in lower left
    map.on('draw:created', draw_create);
    map.on('draw:edited', draw_edit);
    map.on('draw:deleted', draw_delete);
    map.on('draw:drawstart', draw_delete);
    var map_colors = [
        '#deebf7',
        '#c6dbef',
        '#9ecae1',
        '#6baed6',
        '#4292c6',
        '#2171b5',
        '#084594'
    ]
    var date_range_opts = {
        format: 'M/D/YYYY',
        showDropdowns: true,
        startDate: start_date,
        endDate: end_date,
        minDate: min_date,
        maxDate: max_date
    }
    $('#date_range').daterangepicker(
      date_range_opts,
      date_range_callback
    )
    update_date_range();
    $('#dataset-picker').on('change', function(e){
        var name = $(this).val();
        grid_data['dataset'] = name;
        grid_data['human_name'] = $('#dataset-picker').find(':selected').first().text().trim();
        $('.yearpicker').hide();
        $('#' + name + '-yearpicker').show();
        loadLayer(grid_data);
    });
    $('#resolution-picker').on('change', function(e){
        grid_data['resolution'] = parseFloat($(this).val());
        loadLayer(grid_data);
    });
    $('#buffer-picker').on('change', function(e){
        grid_data['buffer'] = parseFloat($(this).val());
        loadLayer(grid_data);
    })
    loadLayer(grid_data);
    $('.showmore').on('click', function(){
        var add_height = $('#dataset-description').height();
        $('.showmore-content').height(add_height);
        $(this).hide()
        $('.showless').show()
    });
    $('.showless').on('click', function(){
        $('.showmore-content').height(165);
        $(this).hide()
        $('.showmore').show()
    })
    function date_range_callback(start, end, label){
        start_date = start;
        end_date = end;
    }
    function draw_create(e){
        if(e.layerType == 'polyline'){
            $('#buffer').show();
        } else {
            $('#buffer').hide();
        }
        drawnItems.addLayer(e.layer);
        grid_data['location_geom__within'] = JSON.stringify(e.layer.toGeoJSON());
        loadLayer(grid_data)
    }
    function draw_edit(e){
        var layers = e.layers;
        layers.eachLayer(function(layer){
            drawnItems.addLayer(layer);
            grid_data['location_geom__within'] = JSON.stringify(layer.toGeoJSON());
        });
    }
    function draw_delete(e){
        grid_layer.clearLayers();
        drawnItems.clearLayers();
    }
    function loadLayer(grid_data){
        $('#map').spin('large');
        grid_data['center'] = [map.getCenter().lat, map.getCenter().lng]
        var url ='/api/grid/'
        $.when(getGrid(url, grid_data), $.getJSON('/api/', {'dataset_name': grid_data['dataset']})).then(
            function(grid, meta){
                grid = grid[0];
                meta = meta[0][0];
                $('#map').spin(false);
                var values = [];
                $.each(grid['features'], function(i, val){
                    values.push(val['properties']['count']);
                });
                try{legend.removeFrom(map);}catch(e){};
                grid_layer.clearLayers();
                if (typeof grid_layer !== 'undefined'){
                    map.removeLayer(grid_layer);
                }
                // Should probably do something here to let users know
                // that there are no results
                if (values.length > 0){
                    jenks_cutoffs = jenks(values, 6);
                    jenks_cutoffs[0] = 0;
                    jenks_cutoffs.pop();
                    grid_layer.addLayer(L.geoJson(grid, {
                        style: styleGrid,
                        onEachFeature: function(feature, layer){
                            var content = '
Count: ' + feature.properties.count + '
';
                            layer.bindLabel(content);
                        }
                    })).addTo(map);
                    legend.addTo(map);
                    map.fitBounds(grid_layer.getBounds());
                }
                if (meta.obs_from){
                    min_date = moment(meta['obs_from'], 'YYYY-MM-DD');
                } else {
                    min_date = moment().subtract('years', 5);
                }
                if (meta.obs_to){
                    max_date = moment(meta['obs_to'], 'YYYY-MM-DD');
                } else {
                    max_date = moment();
                }
                if (end_date.isAfter(max_date)){
                    end_date = max_date;
                }
                if (start_date.isBefore(min_date)){
                    start_state = min_date;
                }
                date_range_opts['minDate'] = min_date
                date_range_opts['maxDate'] = max_date
                date_range_opts['startDate'] = start_date
                date_range_opts['endDate'] = end_date
                $('#date_range').daterangepicker(date_range_opts, date_range_callback);
                $('#date_range').on('apply.daterangepicker', function(ev, picker) {
                    start_date = picker.startDate
                    end_date = picker.endDate
                    grid_data['obs_from'] = start_date.format('YYYY-MM-DD')
                    grid_data['obs_to'] = end_date.format('YYYY-MM-DD')
                    loadLayer(grid_data);
                });
                update_date_range();
                $('#dataset-name').html(meta['human_name']);
                $('#dataset-description').html(meta['description']);
            }
        );
    }

    function getColor(d){
        return d >= jenks_cutoffs[5] ? map_colors[6] :
               d >= jenks_cutoffs[4] ? map_colors[5] :
               d >= jenks_cutoffs[3] ? map_colors[4] :
               d >= jenks_cutoffs[2] ? map_colors[3] :
               d >= jenks_cutoffs[1] ? map_colors[2] :
               d >= jenks_cutoffs[0] ? map_colors[1] :
                                       map_colors[0];
    }

    function styleGrid(feature){
        return {
            fillColor: getColor(feature.properties.count),
            weight: 0.3,
            opacity: 1,
            color: 'white',
            fillOpacity: 0.7
        };
    }

    function getFieldDefs(dataset_name){
        $.when($.getJSON('/api/fields/' + dataset_name + '/')).then(
            function(fields){
                $('#fielddefs').show();
                $('#fielddefs-list').val()
            }
        )
    }

    function getGrid(url, grid){
        var data = {
            dataset_name: grid['dataset'],
            resolution: grid['resolution'],
            center: grid['center'],
            obs_date__ge: grid['obs_from'],
            obs_date__le: grid['obs_to']
        }
        if (typeof grid['location_geom__within'] !== 'undefined'){
            data['location_geom__within'] = grid['location_geom__within']
        }
        if (typeof grid['buffer'] !== 'undefined'){
            data['buffer'] = grid['buffer']
        }
        return $.getJSON(url, data)
    }
    function update_date_range(){
        $('#date_range').val(start_date.format('M/D/YYYY') + " - " + end_date.format('M/D/YYYY'));
    }
})()
<|endoftext|>


<commit_before>/* This file is only loaded on Cordova-bundled apps and is used only in case
 * autoupdate package is used.
 * It checks if File plugin is installed and a newer version of the app code can
 * be found on persistent storage. In that case those files are dynamically
 * added to the page.
 * Otherwise a normal app code is loaded (shipped with the app initially).
 */

(function () {

  var evt = new Event("meteor-cordova-loaded");

  var readFile = function (url, cb) {
    window.resolveLocalFileSystemURL(url,
      function (fileEntry) {
        var success = function (file) {
          var reader = new FileReader();
          reader.onloadend = function (evt) {
            var result = evt.target.result;
            cb(null, result);
          };
          reader.onerror = fail;
          reader.readAsText(file);
        };
        var fail = function (evt) {
          cb(new Error("Failed to load entry"), null);
        };
        fileEntry.file(success, fail);
      },
      // error callback
      function (err) { cb(new Error("Failed to load entry"), null); }
    );
  };

  var each = function (array, f) {
    for (var i = 0; i < array.length; i++)
      f(array[i], i, array);
  };

  // To ensure that all our <script> tags are loaded in the correct order we add
  // them to DOM one by one.
  // The assumption here is that every element in the queue is a function that
  // calls loadScript only once. Because loadScript makes sure to call
  // launchNext after the async operation is done, it works as intended. We
  // allow the last function to be something different (like trigger the
  // document event).
  var queue = [];
  var launchNext = function () {
    if (! queue.length)
      return;
    var fun = queue.shift();
    fun();
  };

  var loadScript = function (url) {
    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.src = url;
    scriptTag.onload = launchNext;

    document.getElementsByTagName('head')[0].appendChild(scriptTag);
  };

  var loadStyle = function (url) {
    var styleTag = document.createElement('link');
    styleTag.rel = "stylesheet";
    styleTag.type = "text/css";
    styleTag.href = url;
    document.getElementsByTagName('head')[0].appendChild(styleTag);
  };

  var loadAssetsFromManifest = function (manifest, urlPrefix) {
    each(manifest, function (item) {
      var url = urlPrefix + (item.url ? item.url.substring(1) : '');
      if (item.type === 'js')
        queue.push(function () {
          loadScript(url);
        });
      else if (item.type === 'css')
        loadStyle(url);
    });

    queue.push(function () {
      document.dispatchEvent(evt);
    });

    launchNext();
  };

  // Fallback to the bundled assets from the disk. If an error is passed as an
  // argument, then there was a problem reading from the manifest files. If
  // no error is passed, then we simply do not have any new versions.
  var fallback = function (err) {
    if (err) {
      console.log('Couldn\'t load from the manifest, ' +
                  'falling back to the bundled assets.');
    } else {
      console.log('No new versions saved to disk.');
    }

    loadAssetsFromManifest(__meteor_manifest__, '');
  };

  var cleanCache = function (url, cb) {
    var fail = function (err) {
      console.log("Clearing cache failed: ");
      console.log(err);
      cb();
    };
    window.resolveLocalFileSystemURL(url, function(entry) {
      entry.removeRecursively(function() {
        console.log("Cleared cache successfully.");
        cb();
      }, fail);
    }, fail);
  };

  var loadApp = function (localPathPrefix) {

    readFile(localPathPrefix + 'version',
      function (err, version) {
        if (err) {
          fallback();
          return;
        }

        var versionPrefix = localPathPrefix + version + '/';

        // We have a version string, now read the new version
        readFile(versionPrefix + 'manifest.json',
            function (err, res) {
          if (err) {
            fallback(err);
            return;
          }

          var program = JSON.parse(res);
          // update the version we are loading
          __meteor_runtime_config__.autoupdateVersionCordova = version;
          // update the public settings
          __meteor_runtime_config__.PUBLIC_SETTINGS = program.PUBLIC_SETTINGS;

          loadAssetsFromManifest(program.manifest, versionPrefix);
        });
    });
  };

  document.addEventListener("deviceready", function () {
    var localPathPrefix = cordova.file.applicationStorageDirectory +
                          'Documents/meteor/';
    if (__meteor_runtime_config__.cleanCache) {
      // If cleanCache is enabled, clean the cache and then load the app.
      cleanCache(localPathPrefix, function () {
        loadApp(localPathPrefix);
      });
    } else {
      loadApp(localPathPrefix);
    }
  }, false);
})();

<commit_msg>Push history state '/' on load<commit_after>/* This file is only loaded on Cordova-bundled apps and is used only in case
 * autoupdate package is used.
 * It checks if File plugin is installed and a newer version of the app code can
 * be found on persistent storage. In that case those files are dynamically
 * added to the page.
 * Otherwise a normal app code is loaded (shipped with the app initially).
 */

(function () {

  var evt = new Event("meteor-cordova-loaded");

  var readFile = function (url, cb) {
    window.resolveLocalFileSystemURL(url,
      function (fileEntry) {
        var success = function (file) {
          var reader = new FileReader();
          reader.onloadend = function (evt) {
            var result = evt.target.result;
            cb(null, result);
          };
          reader.onerror = fail;
          reader.readAsText(file);
        };
        var fail = function (evt) {
          cb(new Error("Failed to load entry"), null);
        };
        fileEntry.file(success, fail);
      },
      // error callback
      function (err) { cb(new Error("Failed to load entry"), null); }
    );
  };

  var each = function (array, f) {
    for (var i = 0; i < array.length; i++)
      f(array[i], i, array);
  };

  // To ensure that all our <script> tags are loaded in the correct order we add
  // them to DOM one by one.
  // The assumption here is that every element in the queue is a function that
  // calls loadScript only once. Because loadScript makes sure to call
  // launchNext after the async operation is done, it works as intended. We
  // allow the last function to be something different (like trigger the
  // document event).
  var queue = [];
  var launchNext = function () {
    if (! queue.length)
      return;
    var fun = queue.shift();
    fun();
  };

  var loadScript = function (url) {
    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.src = url;
    scriptTag.onload = launchNext;

    document.getElementsByTagName('head')[0].appendChild(scriptTag);
  };

  var loadStyle = function (url) {
    var styleTag = document.createElement('link');
    styleTag.rel = "stylesheet";
    styleTag.type = "text/css";
    styleTag.href = url;
    document.getElementsByTagName('head')[0].appendChild(styleTag);
  };

  var loadAssetsFromManifest = function (manifest, urlPrefix) {
    each(manifest, function (item) {
      var url = urlPrefix + (item.url ? item.url.substring(1) : '');
      if (item.type === 'js')
        queue.push(function () {
          loadScript(url);
        });
      else if (item.type === 'css')
        loadStyle(url);
    });

    queue.push(function () {
      document.dispatchEvent(evt);
    });

    launchNext();
  };

  // Fallback to the bundled assets from the disk. If an error is passed as an
  // argument, then there was a problem reading from the manifest files. If
  // no error is passed, then we simply do not have any new versions.
  var fallback = function (err) {
    if (err) {
      console.log('Couldn\'t load from the manifest, ' +
                  'falling back to the bundled assets.');
    } else {
      console.log('No new versions saved to disk.');
    }

    loadAssetsFromManifest(__meteor_manifest__, '');
  };

  var cleanCache = function (url, cb) {
    var fail = function (err) {
      console.log("Clearing cache failed: ");
      console.log(err);
      cb();
    };
    window.resolveLocalFileSystemURL(url, function(entry) {
      entry.removeRecursively(function() {
        console.log("Cleared cache successfully.");
        cb();
      }, fail);
    }, fail);
  };

  var loadApp = function (localPathPrefix) {

    readFile(localPathPrefix + 'version',
      function (err, version) {
        if (err) {
          fallback();
          return;
        }

        var versionPrefix = localPathPrefix + version + '/';

        // We have a version string, now read the new version
        readFile(versionPrefix + 'manifest.json',
            function (err, res) {
          if (err) {
            fallback(err);
            return;
          }

          var program = JSON.parse(res);
          // update the version we are loading
          __meteor_runtime_config__.autoupdateVersionCordova = version;
          // update the public settings
          __meteor_runtime_config__.PUBLIC_SETTINGS = program.PUBLIC_SETTINGS;

          loadAssetsFromManifest(program.manifest, versionPrefix);
        });
    });
  };

  document.addEventListener("deviceready", function () {
    // set the url to /
    if (history) {
      history.pushState({}, "Application", "/");
    }
    var localPathPrefix = cordova.file.applicationStorageDirectory +
                          'Documents/meteor/';
    if (__meteor_runtime_config__.cleanCache) {
      // If cleanCache is enabled, clean the cache and then load the app.
      cleanCache(localPathPrefix, function () {
        loadApp(localPathPrefix);
      });
    } else {
      loadApp(localPathPrefix);
    }
  }, false);
})();

<|endoftext|>


<commit_before>
	// style
	// stroke, fill,

	// attributes
	// x1, x2, y1, y2, r, cx, cy, d, x, y
	// stroke, stroke-width, fill, stroke-dash-array

	// CURRENT THINGS TO CONSIDER

	// if animation is running, should new function call take over or work "on top"/"side-by-side"
	// css transitions take over

	u.a.getInitialValue = function(node, attribute) {

		var value = (node.getAttribute(attribute) ? node.getAttribute(attribute) : u.gcs(node, attribute)).replace(node._unit[attribute], "")
		return Number(value.replace(/auto/, 0));
	}

	u.a.to = function(node, transition, attributes) {

		// get duration
		var duration = transition.match(/[0-9.]+[ms]+/g);
		if(duration) {
	//		u.bug(duration[0]);
			node.duration = duration[0].match("ms") ? parseFloat(duration[0]) : (parseFloat(duration[0]) * 1000);
		}

		// TODO: get delay

		node._start = {};
		node._end = {};
		node._unit = {};

		for(attribute in attributes) {

			node._unit[attribute] = attributes[attribute].toString().match(/\%|px/);

			node._start[attribute] = Number(this.getInitialValue(node, attribute));
			 //(node.getAttribute(attribute) ? node.getAttribute(attribute) : u.gcs(node, attribute)).replace(node._unit[attribute], "");
			node._end[attribute] = attributes[attribute].toString().replace(node._unit[attribute], "");

//			u.bug("attributes["+attribute+"] = "+attributes[attribute] + "::"+ node._start[attribute] + " -> " + node._end[attribute]);

		}
//		u.bug("duration:" + node.duration);

		node.transitionTo = function(progress) {

			for(attribute in attributes) {
				if(attribute.match(/translate|rotate|scale/)) {

					if(attribute == "translate") {
						u.a.translate(this, Math.round((this._end_x - this._start_x) * progress), Math.round((this._end_y - this._start_y) * progress))
					}
					else if(attribute == "rotate") {

					}

				}
				else if(attribute.match(/x1|y1|x2|y2|r|cx|cy/)) {

					var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]
//					u.bug("update:" + attribute + ":" + new_value);

					this.setAttribute(attribute, new_value);

				}
				else {

					//u.bug("update:" + this._end[attribute] + "-" + this._start[attribute] + " * " + progress + " " + this._unit[attribute])
					var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]

//					u.bug("update:" + attribute + ":" + new_value);

					u.as(node, attribute, new_value, false);

				}

			}

		}

//			u.bug(u.nodeId(this) + ":progress:" + progress + " ("+(this._end_x - this._start_x) * progress+","+(this._end_y - this._start_y) * progress+")")

		u.a.requestAnimationFrame(node, "transitionTo", node.duration);

	}

// this.animationFrame = function(node, callback) {
//
// 	if(!window._animationframe) {
// 		window._animationframe = window[this.vendor("requestAnimationFrame")]
//
// 	}
//
// }
//
//
// window.cancelRequestAnimFrame = ( function() {
// 	return window.cancelAnimationFrame 						||
//       window.webkitCancelRequestAnimationFrame 	||
//       window.mozCancelRequestAnimationFrame 		||
//       window.oCancelRequestAnimationFrame 			||
//       window.msCancelRequestAnimationFrame			||
//       clearTimeout
// } )();
//
// window.requestAnimFrame = (function() {
//   return  window.requestAnimationFrame     ||
//         window.webkitRequestAnimationFrame ||
//         window.mozRequestAnimationFrame    ||
//         window.oRequestAnimationFrame      ||
//         window.msRequestAnimationFrame     ||
//         function(callback, element){
//             return window.setTimeout(callback, 1000 / 60);
//         };
// })();
//
// (function() {
//     var lastTime = 0;
//     var vendors = ['ms', 'moz', 'webkit', 'o'];
//     for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
//         window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
//         window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
//                                    || window[vendors[x]+'CancelRequestAnimationFrame'];
//     }
//
//     if (!window.requestAnimationFrame)
//         window.requestAnimationFrame = function(callback, element) {
//             var currTime = new Date().getTime();
//             var timeToCall = Math.max(0, 16 - (currTime - lastTime));
//             var id = window.setTimeout(function() { callback(currTime + timeToCall); },
//               timeToCall);
//             lastTime = currTime + timeToCall;
//             return id;
//         };
//
//     if (!window.cancelAnimationFrame)
//         window.cancelAnimationFrame = function(id) {
//             clearTimeout(id);
//         };
// }());
<commit_msg>Enabled stroke-width animation<commit_after>
	// style
	// stroke, fill,

	// attributes
	// x1, x2, y1, y2, r, cx, cy, d, x, y
	// stroke, stroke-width, fill, stroke-dash-array

	// CURRENT THINGS TO CONSIDER

	// if animation is running, should new function call take over or work "on top"/"side-by-side"
	// css transitions take over

	u.a.getInitialValue = function(node, attribute) {

		var value = (node.getAttribute(attribute) ? node.getAttribute(attribute) : u.gcs(node, attribute)).replace(node._unit[attribute], "")
		return Number(value.replace(/auto/, 0));
	}

	u.a.to = function(node, transition, attributes) {

		// get duration
		var duration = transition.match(/[0-9.]+[ms]+/g);
		if(duration) {
	//		u.bug(duration[0]);
			node.duration = duration[0].match("ms") ? parseFloat(duration[0]) : (parseFloat(duration[0]) * 1000);
		}

		// TODO: get delay

		node._start = {};
		node._end = {};
		node._unit = {};

		for(attribute in attributes) {

			node._unit[attribute] = attributes[attribute].toString().match(/\%|px/);

			node._start[attribute] = Number(this.getInitialValue(node, attribute));
			 //(node.getAttribute(attribute) ? node.getAttribute(attribute) : u.gcs(node, attribute)).replace(node._unit[attribute], "");
			node._end[attribute] = attributes[attribute].toString().replace(node._unit[attribute], "");

//			u.bug("attributes["+attribute+"] = "+attributes[attribute] + "::"+ node._start[attribute] + " -> " + node._end[attribute]);

		}
//		u.bug("duration:" + node.duration);

		node.transitionTo = function(progress) {

			for(attribute in attributes) {
				if(attribute.match(/translate|rotate|scale/)) {

					if(attribute == "translate") {
						u.a.translate(this, Math.round((this._end_x - this._start_x) * progress), Math.round((this._end_y - this._start_y) * progress))
					}
					else if(attribute == "rotate") {

					}

				}
				else if(attribute.match(/x1|y1|x2|y2|r|cx|cy|stroke-width/)) {

					var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]
//					u.bug("update:" + attribute + ":" + new_value);

					this.setAttribute(attribute, new_value);

				}
				else {

					//u.bug("update:" + this._end[attribute] + "-" + this._start[attribute] + " * " + progress + " " + this._unit[attribute])
					var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]

//					u.bug("update:" + attribute + ":" + new_value);

					u.as(node, attribute, new_value, false);

				}

			}

		}

//			u.bug(u.nodeId(this) + ":progress:" + progress + " ("+(this._end_x - this._start_x) * progress+","+(this._end_y - this._start_y) * progress+")")

		u.a.requestAnimationFrame(node, "transitionTo", node.duration);

	}

// this.animationFrame = function(node, callback) {
//
// 	if(!window._animationframe) {
// 		window._animationframe = window[this.vendor("requestAnimationFrame")]
//
// 	}
//
// }
//
//
// window.cancelRequestAnimFrame = ( function() {
// 	return window.cancelAnimationFrame 						||
//       window.webkitCancelRequestAnimationFrame 	||
//       window.mozCancelRequestAnimationFrame 		||
//       window.oCancelRequestAnimationFrame 			||
//       window.msCancelRequestAnimationFrame			||
//       clearTimeout
// } )();
//
// window.requestAnimFrame = (function() {
//   return  window.requestAnimationFrame     ||
//         window.webkitRequestAnimationFrame ||
//         window.mozRequestAnimationFrame    ||
//         window.oRequestAnimationFrame      ||
//         window.msRequestAnimationFrame     ||
//         function(callback, element){
//             return window.setTimeout(callback, 1000 / 60);
//         };
// })();
//
// (function() {
//     var lastTime = 0;
//     var vendors = ['ms', 'moz', 'webkit', 'o'];
//     for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
//         window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
//         window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
//                                    || window[vendors[x]+'CancelRequestAnimationFrame'];
//     }
//
//     if (!window.requestAnimationFrame)
//         window.requestAnimationFrame = function(callback, element) {
//             var currTime = new Date().getTime();
//             var timeToCall = Math.max(0, 16 - (currTime - lastTime));
//             var id = window.setTimeout(function() { callback(currTime + timeToCall); },
//               timeToCall);
//             lastTime = currTime + timeToCall;
//             return id;
//         };
//
//     if (!window.cancelAnimationFrame)
//         window.cancelAnimationFrame = function(id) {
//             clearTimeout(id);
//         };
// }());
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name reviveComplex128
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/reviver-float64}
*/
setReadOnly( ns, 'reviveComplex128', require( '@stdlib/types/complex/reviver-float64' ) );

/**
* @name reviveComplex64
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/reviver-float32}
*/
setReadOnly( ns, 'reviveComplex64', require( '@stdlib/types/complex/reviver-float32' ) );

/**
* @name conj
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/conj}
*/
setReadOnly( ns, 'conj', require( '@stdlib/types/complex/conj' ) );

/**
* @name complex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/factory}
*/
setReadOnly( ns, 'complex', require( '@stdlib/types/complex/factory' ) );

/**
* @name Complex64
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/complex/float32}
*/
setReadOnly( ns, 'Complex64', require( '@stdlib/types/complex/float32' ) );

/**
* @name Complex128
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/complex/float64}
*/
setReadOnly( ns, 'Complex128', require( '@stdlib/types/complex/float64' ) );

/**
* @name imag
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/imag}
*/
setReadOnly( ns, 'imag', require( '@stdlib/types/complex/imag' ) );

/**
* @name real
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/real}
*/
setReadOnly( ns, 'real', require( '@stdlib/types/complex/real' ) );

/**
* @name reim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/reim}
*/
setReadOnly( ns, 'reim', require( '@stdlib/types/complex/reim' ) );

/**
* @name reviveComplex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/reviver}
*/
setReadOnly( ns, 'reviveComplex', require( '@stdlib/types/complex/reviver' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Reorder properties<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name conj
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/conj}
*/
setReadOnly( ns, 'conj', require( '@stdlib/types/complex/conj' ) );

/**
* @name complex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/factory}
*/
setReadOnly( ns, 'complex', require( '@stdlib/types/complex/factory' ) );

/**
* @name Complex64
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/complex/float32}
*/
setReadOnly( ns, 'Complex64', require( '@stdlib/types/complex/float32' ) );

/**
* @name Complex128
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/complex/float64}
*/
setReadOnly( ns, 'Complex128', require( '@stdlib/types/complex/float64' ) );

/**
* @name imag
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/imag}
*/
setReadOnly( ns, 'imag', require( '@stdlib/types/complex/imag' ) );

/**
* @name real
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/real}
*/
setReadOnly( ns, 'real', require( '@stdlib/types/complex/real' ) );

/**
* @name reim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/reim}
*/
setReadOnly( ns, 'reim', require( '@stdlib/types/complex/reim' ) );

/**
* @name reviveComplex
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/reviver}
*/
setReadOnly( ns, 'reviveComplex', require( '@stdlib/types/complex/reviver' ) );

/**
* @name reviveComplex64
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/reviver-float32}
*/
setReadOnly( ns, 'reviveComplex64', require( '@stdlib/types/complex/reviver-float32' ) );

/**
* @name reviveComplex128
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/complex/reviver-float64}
*/
setReadOnly( ns, 'reviveComplex128', require( '@stdlib/types/complex/reviver-float64' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>/* gamesys.settings */
define ([
], function (
) {

///////////////////////////////////////////////////////////////////////////////
/**	MASTER SETTINGS *********************************************************\

	Contains global settings, properties, constants

	The actual global values are stored in an inaccessible object called
	PROP, which the Property() method checks.

///////////////////////////////////////////////////////////////////////////////
/** PUBLIC API **************************************************************/

	var SETTINGS;

///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/*/	This checks if a property actually exists
/*/	SETTINGS = function ( propName ) {
		var value = PROP[propName];
		console.assert(value,"Requested property '"+propName+"' exists");
		return value;
	};

///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.Set = function ( key, value ) {
		if (PROP[key]) console.log ('overwriting',key.bracket(),'with new value');
		PROP[key]=value;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.SetMasterTime = function ( current_time_ms ) {
		if (current_time_ms!==undefined) {
			CURRENT_TIME_MS = current_time_ms;
		}
		return CURRENT_TIME_MS;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.SetGamePath = function ( path ) {
		if (path!==undefined) {
			CURRENT_GAME_PATH = path;
		}
		return CURRENT_GAME_PATH;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.SetSystemPath = function ( path ) {
		if (path!==undefined) {
			SYSTEM_PATH = path;
		}
		return SYSTEM_PATH;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.MasterTime = function () {
		if (CURRENT_TIME_MS===undefined) console.error("Use of MasterTime before Start() is invalid!");
		return CURRENT_TIME_MS;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.GamePath = function ( extra ) {
		extra = extra || '';
		if (CURRENT_GAME_PATH===undefined) console.error("Use of GamePath before Start() is invalid!");
		return CURRENT_GAME_PATH+extra;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.SystemPath = function ( extra ) {
		extra = extra || '';
		if (SYSTEM_PATH===undefined) console.error("Use of SystemPath before Start() is invalid!");
		return SYSTEM_PATH+extra;
	};

///////////////////////////////////////////////////////////////////////////////
/** MODULE PRIVATE VARIABLES ************************************************/

	var CURRENT_TIME_MS;
	var CURRENT_GAME_PATH;
	var SYSTEM_PATH;

	var PROP = {};

///	IMPORTANT PATHS ///////////////////////////////////////////////////////////

	PROP.PATH_GAMES = '/javascripts/1401-games';	// this should be set in main.js
	PROP.PATH_RUNFILE = 'game-main.js';				// the default entry point
	PROP.PATH_SYSTEM = '/javascripts/1401';			// default system path

///	MASTER TIME //////////////////////////////////////////////////////////////
///	The timestep established in master.js uses these variables

	PROP.FPS = 30;
	PROP.TIMESTEP = 1000 / PROP.FPS;

//////////////////////////////////////////////////////////////////////////////
/** RETURN MODULE DEFINITION FOR REQUIREJS ***********************************/
	// settings is a FUNCTION that can be invoked. weird, right?
	return SETTINGS;

});
<commit_msg>MasterTime() now returns 0 if no current time<commit_after>/* gamesys.settings */
define ([
], function (
) {

///////////////////////////////////////////////////////////////////////////////
/**	MASTER SETTINGS *********************************************************\

	Contains global settings, properties, constants

	The actual global values are stored in an inaccessible object called
	PROP, which the Property() method checks.

///////////////////////////////////////////////////////////////////////////////
/** PUBLIC API **************************************************************/

	var SETTINGS;

///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/*/	This checks if a property actually exists
/*/	SETTINGS = function ( propName ) {
		var value = PROP[propName];
		console.assert(value,"Requested property '"+propName+"' exists");
		return value;
	};

///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.Set = function ( key, value ) {
		if (PROP[key]) console.log ('overwriting',key.bracket(),'with new value');
		PROP[key]=value;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.SetMasterTime = function ( current_time_ms ) {
		if (current_time_ms!==undefined) {
			CURRENT_TIME_MS = current_time_ms;
		}
		return CURRENT_TIME_MS;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.SetGamePath = function ( path ) {
		if (path!==undefined) {
			CURRENT_GAME_PATH = path;
		}
		return CURRENT_GAME_PATH;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.SetSystemPath = function ( path ) {
		if (path!==undefined) {
			SYSTEM_PATH = path;
		}
		return SYSTEM_PATH;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.MasterTime = function () {
		if (CURRENT_TIME_MS===undefined) {
			console.warn("Settings.MasterTime() before MasterStart always returns 0ms");
			return 0;
		}
		return CURRENT_TIME_MS;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.GamePath = function ( extra ) {
		extra = extra || '';
		if (CURRENT_GAME_PATH===undefined) console.warn("GamePath is invalid before Game Load");
		return CURRENT_GAME_PATH+extra;
	};
///	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	SETTINGS.SystemPath = function ( extra ) {
		extra = extra || '';
		if (SYSTEM_PATH===undefined) console.error("SystemPath is invalid before Game Load");
		return SYSTEM_PATH+extra;
	};

///////////////////////////////////////////////////////////////////////////////
/** MODULE PRIVATE VARIABLES ************************************************/

	var CURRENT_TIME_MS;
	var CURRENT_GAME_PATH;
	var SYSTEM_PATH;

	var PROP = {};

///	IMPORTANT PATHS ///////////////////////////////////////////////////////////

	PROP.PATH_GAMES = '/javascripts/1401-games';	// this should be set in main.js
	PROP.PATH_RUNFILE = 'game-main.js';				// the default entry point
	PROP.PATH_SYSTEM = '/javascripts/1401';			// default system path

///	MASTER TIME //////////////////////////////////////////////////////////////
///	The timestep established in master.js uses these variables

	PROP.FPS = 30;
	PROP.TIMESTEP = 1000 / PROP.FPS;

//////////////////////////////////////////////////////////////////////////////
/** RETURN MODULE DEFINITION FOR REQUIREJS ***********************************/
	// settings is a FUNCTION that can be invoked. weird, right?
	return SETTINGS;

});
<|endoftext|>


<commit_before>import resettableGroupModule from '../../../../source/iml/resettable-group/resettable-group-module.js';

describe('resettable group', () => {
  var $scope, qs, el, entry1, entry2, month, yourName, yourEmail, resetButton;

  beforeEach(module(resettableGroupModule));

  beforeEach(inject(($rootScope, $compile) => {
    const template = `<form name="testForm">
  <resettable-group>
    <ng-form name="subForm1">
      Entry 1
      <input type="text" name="entry1" ng-model="entry1" placeholder="entry1" />
    </ng-form>
    <ng-form name="subForm2">
      Entry 2
      <input type="text" name="entry2" ng-model="entry2" placeholder="entry2" />
      <select name="month" ng-model="month">
        <option value="january">January</option>
        <option value="february">February</option>
        <option value="march">March</option>
        <option value="april">April</option>
        <option value="may" selected>May</option>
        <option value="june">June</option>
        <option value="july">July</option>
        <option value="august">August</option>
        <option value="september">September</option>
        <option value="october">October</option>
        <option value="november">November</option>
        <option value="december">December</option>
      </select>
    </ng-form>
    Name
    <input type="text" name="yourName" ng-model="yourName" placeholder="Name" />
    Email
    <input type="text" name="yourEmail" ng-model="yourEmail" placeholder="Email" />
    <button type="submit">Submit</button>
    <button type="button" resetter>Reset</button>
  </resettable-group>
</form>`;

    $scope = $rootScope.$new();
    $scope.entry1 = 'entry 1';
    $scope.entry2 = 'entry 2';
    $scope.month = 'may';
    $scope.yourName = 'John Doe';
    $scope.yourEmail = 'someone@someplace.com';

    el = $compile(template)($scope)[0];

    $scope.$digest();

    qs = el.querySelector.bind(el);
    entry1 = qs('[name="entry1"]');
    entry2 = qs('[name="entry2"]');
    month = qs('[name="month"]');
    yourName = qs('[name="yourName"]');
    yourEmail = qs('[name="yourEmail"]');
    resetButton = qs('button[resetter]');
  }));

  describe('initial form values', () => {
    it('should have default entry 1', () => {
      expect(entry1.value).toEqual('entry 1');
    });

    it('should have default entry 2', () => {
      expect(entry2.value).toEqual('entry 2');
    });

    it('should have default month of may', () => {
      expect(month.value).toEqual('may');
    });

    it('should have default name', () => {
      expect(yourName.value).toEqual('John Doe');
    });

    it('should have default email', () => {
      expect(yourEmail.value).toEqual('someone@someplace.com');
    });
  });

  describe('setting new values on all forms and their elements', () => {
    beforeEach(() => {
      entry1.value = 'new entry 1';
      entry1.dispatchEvent(new Event('input'));
      entry2.value = 'new entry 2';
      entry2.dispatchEvent(new Event('input'));
      month.value = 'september';
      month.dispatchEvent(new Event('input'));
      yourName.value = 'Jane Doe';
      yourName.dispatchEvent(new Event('input'));
      yourEmail.value = 'newguy@newplace.com';
      yourEmail.dispatchEvent(new Event('input'));
    });

    it('should have the new entry 1 value', () => {
      expect(entry1.value).toEqual('new entry 1');
    });

    it('should have the new entry 2 value', () => {
      expect(entry2.value).toEqual('new entry 2');
    });

    it('should have the new month value', () => {
      expect(month.value).toEqual('september');
    });

    it('should have the new name value', () => {
      expect(yourName.value).toEqual('Jane Doe');
    });

    it('should have the new email value', () => {
      expect(yourEmail.value).toEqual('newguy@newplace.com');
    });

    describe('resetting the top level form', () => {
      beforeEach(() => {
        resetButton.click();
      });

      it('should have the original entry 1 value', () => {
        expect(entry1.value).toEqual('entry 1');
      });

      it('should have the original entry 2 value', () => {
        expect(entry2.value).toEqual('entry 2');
      });

      it('should have the original month value', () => {
        expect(month.value).toEqual('may');
      });

      it('should have the original name value', () => {
        expect(yourName.value).toEqual('John Doe');
      });

      it('should have the original email value', () => {
        expect(yourEmail.value).toEqual('someone@someplace.com');
      });

      it('should put entry1 in pristine state', () => {
        expect(entry1.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should put entry2 in pristine state', () => {
        expect(entry2.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should put month in pristine state', () => {
        expect(month.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should put yourName in pristine state', () => {
        expect(yourName.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should put yourEmail in pristine state', () => {
        expect(yourEmail.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should indicate entry1 is not touched', () => {
        expect(entry1.classList.contains('ng-touched')).toEqual(false);
      });

      it('should indicate entry2 is not touched', () => {
        expect(entry2.classList.contains('ng-touched')).toEqual(false);
      });

      it('should indicate month is not touched', () => {
        expect(month.classList.contains('ng-touched')).toEqual(false);
      });

      it('should indicate yourName is not touched', () => {
        expect(yourName.classList.contains('ng-touched')).toEqual(false);
      });

      it('should indicate yourEmail is not touched', () => {
        expect(yourEmail.classList.contains('ng-touched')).toEqual(false);
      });
    });
  });
});
<commit_msg>- Check property on scope instead of on element after changing the value<commit_after>import resettableGroupModule from '../../../../source/iml/resettable-group/resettable-group-module.js';

describe('resettable group', () => {
  var $scope, qs, el, entry1, entry2, month, yourName, yourEmail, resetButton;

  beforeEach(module(resettableGroupModule));

  beforeEach(inject(($rootScope, $compile) => {
    const template = `<form name="testForm">
  <resettable-group>
    <ng-form name="subForm1">
      Entry 1
      <input type="text" name="entry1" ng-model="entry1" placeholder="entry1" />
    </ng-form>
    <ng-form name="subForm2">
      Entry 2
      <input type="text" name="entry2" ng-model="entry2" placeholder="entry2" />
      <select name="month" ng-model="month">
        <option value="january">January</option>
        <option value="february">February</option>
        <option value="march">March</option>
        <option value="april">April</option>
        <option value="may" selected>May</option>
        <option value="june">June</option>
        <option value="july">July</option>
        <option value="august">August</option>
        <option value="september">September</option>
        <option value="october">October</option>
        <option value="november">November</option>
        <option value="december">December</option>
      </select>
    </ng-form>
    Name
    <input type="text" name="yourName" ng-model="yourName" placeholder="Name" />
    Email
    <input type="text" name="yourEmail" ng-model="yourEmail" placeholder="Email" />
    <button type="submit">Submit</button>
    <button type="button" resetter>Reset</button>
  </resettable-group>
</form>`;

    $scope = $rootScope.$new();
    $scope.entry1 = 'entry 1';
    $scope.entry2 = 'entry 2';
    $scope.month = 'may';
    $scope.yourName = 'John Doe';
    $scope.yourEmail = 'someone@someplace.com';

    el = $compile(template)($scope)[0];

    $scope.$digest();

    qs = el.querySelector.bind(el);
    entry1 = qs('[name="entry1"]');
    entry2 = qs('[name="entry2"]');
    month = qs('[name="month"]');
    yourName = qs('[name="yourName"]');
    yourEmail = qs('[name="yourEmail"]');
    resetButton = qs('button[resetter]');
  }));

  describe('initial form values', () => {
    it('should have default entry 1', () => {
      expect(entry1.value).toEqual('entry 1');
    });

    it('should have default entry 2', () => {
      expect(entry2.value).toEqual('entry 2');
    });

    it('should have default month of may', () => {
      expect(month.value).toEqual('may');
    });

    it('should have default name', () => {
      expect(yourName.value).toEqual('John Doe');
    });

    it('should have default email', () => {
      expect(yourEmail.value).toEqual('someone@someplace.com');
    });
  });

  describe('setting new values on all forms and their elements', () => {
    beforeEach(() => {
      entry1.value = 'new entry 1';
      entry1.dispatchEvent(new Event('input'));
      entry2.value = 'new entry 2';
      entry2.dispatchEvent(new Event('input'));
      month.value = 'september';
      month.dispatchEvent(new Event('change'));
      yourName.value = 'Jane Doe';
      yourName.dispatchEvent(new Event('input'));
      yourEmail.value = 'newguy@newplace.com';
      yourEmail.dispatchEvent(new Event('input'));
    });

    it('should have the new entry 1 value', () => {
      expect($scope.entry1).toEqual('new entry 1');
    });

    it('should have the new entry 2 value', () => {
      expect($scope.entry2).toEqual('new entry 2');
    });

    it('should have the new month value', () => {
      expect($scope.month).toEqual('september');
    });

    it('should have the new name value', () => {
      expect($scope.yourName).toEqual('Jane Doe');
    });

    it('should have the new email value', () => {
      expect($scope.yourEmail).toEqual('newguy@newplace.com');
    });

    describe('resetting the top level form', () => {
      beforeEach(() => {
        resetButton.click();
      });

      it('should have the original entry 1 value', () => {
        expect(entry1.value).toEqual('entry 1');
      });

      it('should have the original entry 2 value', () => {
        expect(entry2.value).toEqual('entry 2');
      });

      it('should have the original month value', () => {
        expect(month.value).toEqual('may');
      });

      it('should have the original name value', () => {
        expect(yourName.value).toEqual('John Doe');
      });

      it('should have the original email value', () => {
        expect(yourEmail.value).toEqual('someone@someplace.com');
      });

      it('should put entry1 in pristine state', () => {
        expect(entry1.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should put entry2 in pristine state', () => {
        expect(entry2.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should put month in pristine state', () => {
        expect(month.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should put yourName in pristine state', () => {
        expect(yourName.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should put yourEmail in pristine state', () => {
        expect(yourEmail.classList.contains('ng-pristine')).toEqual(true);
      });

      it('should indicate entry1 is not touched', () => {
        expect(entry1.classList.contains('ng-touched')).toEqual(false);
      });

      it('should indicate entry2 is not touched', () => {
        expect(entry2.classList.contains('ng-touched')).toEqual(false);
      });

      it('should indicate month is not touched', () => {
        expect(month.classList.contains('ng-touched')).toEqual(false);
      });

      it('should indicate yourName is not touched', () => {
        expect(yourName.classList.contains('ng-touched')).toEqual(false);
      });

      it('should indicate yourEmail is not touched', () => {
        expect(yourEmail.classList.contains('ng-touched')).toEqual(false);
      });
    });
  });
});
<|endoftext|>


<commit_before>export default function shallowEqual (obj1, obj2) {
  if (obj1 === null || obj2 === null) {
    return false
  }
  if (Object.is(obj1, obj2)) {
    return true
  }
  const obj1Keys = Object.keys(obj1)
  const obj2Keys = Object.keys(obj2)
  if (obj1Keys.length !== obj2Keys.length) {
    return false
  }

  for (let i = 0; i < obj1Keys.length; i++) {
    const obj1KeyItem = obj1Keys[i]
    if (!obj2.hasOwnProperty(obj1KeyItem) || !Object.is(obj1[obj1KeyItem], obj2[obj1KeyItem])) {
      return false
    }
  }

  return true
}
<commit_msg>fix:shallowEqual with null or undefined<commit_after>export default function shallowEqual (obj1, obj2) {
  if (obj1 === null || obj2 === null) {
    return false
  }
  if (Object.is(obj1, obj2)) {
    return true
  }
  const obj1Keys = obj1 ? Object.keys(obj1) : []
  const obj2Keys = obj2 ? Object.keys(obj2) : []
  if (obj1Keys.length !== obj2Keys.length) {
    return false
  }

  for (let i = 0; i < obj1Keys.length; i++) {
    const obj1KeyItem = obj1Keys[i]
    if (!obj2.hasOwnProperty(obj1KeyItem) || !Object.is(obj1[obj1KeyItem], obj2[obj1KeyItem])) {
      return false
    }
  }

  return true
}
<|endoftext|>


<commit_before>/*
Mag.JS AddOns v0.22.1
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
!function(e,t,a,n){function r(e,t){for(var a=Object.keys(e),n=0,r=a.length;r>n;++n){var i=a[n];t(i,e[i])}}e.noop=function(){},e.copy=e.utils.copy,e.merge=e.utils.merge,e.show=function(t,a){var n=typeof t;return"object"!==n?(n={_config:function(e){e.style.display=t?"block":"none"}},"object"==typeof a&&e.merge(a,n),n):void("object"==n?t.willload=function(e,t){t.style.display="block"}:t.willupdate=function(e,t,n){t.style.display=n[a]?"block":"none"})},e.deferred=function(){var e={};return e.promise=new Promise(function(t,a){e.resolve=t,e.reject=a}),e},e.when=function(e,t){return Promise.all(e).then(t)},e.request=function(t){var a=e.deferred();t.initialValue&&(a.promise.initialValue=t.initialValue);var n=JSON.stringify(t);if(t.cache){var r=e.cache(n);if(r)return a.resolve(r),a.promise}if(e.request.queue[n])return e.request.queue[n];e.request.queue[n]=a.promise;var i=new XMLHttpRequest,u=(t.method||"GET").toUpperCase(),r="GET"!==u&&t.data?t.data:"";if(i.onload=function(r){var u=i.getResponseHeader("content-type")||"";r=r.target.responseText,-1<u.indexOf("json")&&(r=JSON.parse(r)),t.cache&&e.cache(n,r,t.cacheTime,t.cacheType),delete e.request.queue[n],u=i.getAllResponseHeaders(),a.resolve(r,u)},i.onerror=function(e){a.reject(e)},i.open(u,t.url),t.headers)for(u=0;u<t.headers.length;u++){var o,c=t.headers[u];for(o in c)i.setRequestHeader(o,c[o])}return i.send(r),a.promise},e.request.queue={},e.cache=function(a,n,r,i){var u=t[i||"sessionStorage"];if(1==arguments.length){if(e.cache.data[a])return e.cache.data[a].data;var o=u.getItem(a);return o?(e.cache.data[a]=JSON.parse(o),e.cache.data[a].data):0}e.cache.data[a]&&e.cache.data[a].id&&clearTimeout(e.cache.data[a].id),o=setTimeout(function(t){u.removeItem(t),delete e.cache.data[t]}.bind({},a),r||6e5),e.cache.data[a]={id:o,data:n},u.setItem(a,JSON.stringify(e.cache.data[a]))},e.cache.data={},e.requestWithFeedback=function(t){var n=JSON.stringify(t);if(!e.requestWithFeedback.cache[n]){for(var r,i=a.querySelectorAll(".loader"),u=0;r=i[u];u++)r.style.display="block";var o=function(t){if(delete e.requestWithFeedback.cache[n],0==Object.keys(e.requestWithFeedback.cache).length)for(var a,r=0;a=i[r];r++)a.style.display="none";return t};e.requestWithFeedback.cache[n]=e.request(t),e.requestWithFeedback.cache[n].then(o,function(e){throw o(e),e})}return e.requestWithFeedback.cache[n]},e.requestWithFeedback.cache={},e.disable=function(t,a){var n=a&&a._config?a._config:function(){},r={_config:function(e){n.apply(this,arguments),t()?e.setAttribute("disabled","disabled"):e.removeAttribute("disabled")}};return a&&e.merge(a,r),r},e.find=function(t,n){var r=a.getElementById(t);return e.fill.find(r,n)},e.toMenu=function(e,t){return e.map(function(e,a){return{_text:e,_value:a,_selected:t===a||t===e?!0:null}})},e.namespace=function(t,a){var n=t.split("."),r=n.shift();return a=a||this,a[r]=a[r]||{},n.length?e.namespace(n.join("."),a[r]):a[r]},e.route=function(e){function t(){for(var t=e.location.hash.substr(1).split("/"),r=t.length,i=0;i<a.length;i++){var u=a[i];if(u.parts.length===r){for(var o=[],c=0;r>c;c++)if(":"===u.parts[c].substr(0,1))o.push(t[c]);else if(u.parts[c]!==t[c])break;if(c===r)return u.handler.apply(n,o),n}}}var a=[];return e.onhashchange=t,{addRoute:function(e,t){a.push({parts:e.split("/"),handler:t})},load:function(t){e.location.hash=t},start:t}}(t),e.hookin("attributes","key",function(e){e.value=null}),e.hookin("attributes","style",function(e){if("object"==typeof e.value){var t=e.node.getAttribute("style")||"",a="";r(e.value,function(e,t){a+=e+":"+(isNaN(t)?t:t+"px")+";"}),e.value=t&&~t.indexOf(a)?t:t+a}}),e.hookin("attributes","className",function(e){e.key="class";var t=e.value;if("string"==typeof e.value)t=e.value.split(" ");else if("object"==typeof e.value){for(var a in t)e.node.classList.toggle(a,t[a]);return e.value=e.node.classList+"",n}e.value=e.node.classList+"";for(a in t){var r=t[a];r.trim()&&0<e.node.classList.length&&!e.node.classList.contains(r.trim())?e.value=e.node.classList+" "+r:r.trim()&&0==e.node.classList.length&&(e.value+=r+" ")}e.value=e.value.trim()}),e.hookin("values","*",function(t){var a=typeof t.value;if(null!=t.value)if("function"===a&&t.value.toJSON)t.change=1,t.value=t.value();else if("object"==a&&"function"==typeof t.value.then){var n=e.utils.items.getItem(e.fill.id);t.value.then(function(a){e.mod.getState(n)[t.key]=a}),t.value.initialValue&&(t.change=1,t.value=t.value.initialValue)}}),e.getId=function(t){return e.utils.items.getItemVal(t)},e.prop=function(e){var t=function(){return arguments.length&&(e=arguments[0]),e};return t.toJSON=function(){return e},t.type="fun",t},e.withProp=function(e,t){return function(a){a=a||event,a=a.currentTarget||this,t(e in a?a[e]:a.getAttribute(e))}}}(mag,window||global||this,document);
<commit_msg>Update mag.addons.0.22.min.js<commit_after>/*
Mag.JS AddOns v0.22.2
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
!function(e,t,a,n){function r(e,t){for(var a=Object.keys(e),n=0,r=a.length;r>n;++n){var i=a[n];t(i,e[i])}}e.noop=function(){},e.copy=e.utils.copy,e.merge=e.utils.merge,e.show=function(t,a){var n=typeof t;return"object"!==n?(n={_config:function(e){e.style.display=t?"block":"none"}},"object"==typeof a&&e.merge(a,n),n):void("object"==n?t.willload=function(e,t){t.style.display="block"}:t.willupdate=function(e,t,n){t.style.display=n[a]?"block":"none"})},e.deferred=function(){var e={};return e.promise=new Promise(function(t,a){e.resolve=t,e.reject=a}),e},e.when=function(e,t){return Promise.all(e).then(t)},e.request=function(t){var a=e.deferred();t.initialValue&&(a.promise.initialValue=t.initialValue);var n=JSON.stringify(t);if(t.cache){var r=e.cache(n);if(r)return a.resolve(r),a.promise}if(e.request.queue[n])return e.request.queue[n];e.request.queue[n]=a.promise;var i=new XMLHttpRequest,u=(t.method||"GET").toUpperCase(),r="GET"!==u&&t.data?t.data:"";if(i.onload=function(r){var u=i.getResponseHeader("content-type")||"";r=r.target.responseText,-1<u.indexOf("json")&&(r=JSON.parse(r)),t.cache&&e.cache(n,r,t.cacheTime,t.cacheType),delete e.request.queue[n],u=i.getAllResponseHeaders(),a.resolve(r,u)},i.onerror=function(e){a.reject(e)},i.open(u,t.url),t.headers)for(u=0;u<t.headers.length;u++){var o,c=t.headers[u];for(o in c)i.setRequestHeader(o,c[o])}return i.send(r),a.promise},e.request.queue={},e.cache=function(a,n,r,i){var u=t[i||"sessionStorage"];if(1==arguments.length){if(e.cache.data[a])return e.cache.data[a].data;var o=u.getItem(a);return o?(e.cache.data[a]=JSON.parse(o),e.cache.data[a].data):0}e.cache.data[a]&&e.cache.data[a].id&&clearTimeout(e.cache.data[a].id),o=setTimeout(function(t){u.removeItem(t),delete e.cache.data[t]}.bind({},a),r||6e5),e.cache.data[a]={id:o,data:n},u.setItem(a,JSON.stringify(e.cache.data[a]))},e.cache.data={},e.requestWithFeedback=function(t){var n=JSON.stringify(t);if(!e.requestWithFeedback.cache[n]){for(var r,i=a.querySelectorAll(".loader"),u=0;r=i[u];u++)r.style.display="block";var o=function(t){if(delete e.requestWithFeedback.cache[n],0==Object.keys(e.requestWithFeedback.cache).length)for(var a,r=0;a=i[r];r++)a.style.display="none";return t};e.requestWithFeedback.cache[n]=e.request(t),e.requestWithFeedback.cache[n].then(o,function(e){throw o(e),e})}return e.requestWithFeedback.cache[n]},e.requestWithFeedback.cache={},e.disable=function(t,a){var n=a&&a._config?a._config:function(){},r={_config:function(e){n.apply(this,arguments),t()?e.setAttribute("disabled","disabled"):e.removeAttribute("disabled")}};return a&&e.merge(a,r),r},e.find=function(t,n){var r=a.getElementById(t);return e.fill.find(r,n)},e.toMenu=function(e,t){return e.map(function(e,a){return{_text:e,_value:a,_selected:t===a||t===e?!0:null}})},e.namespace=function(t,a){var n=t.split("."),r=n.shift();return a=a||this,a[r]=a[r]||{},n.length?e.namespace(n.join("."),a[r]):a[r]},e.route=function(e){function t(){for(var t=e.location.hash.substr(1).split("/"),r=t.length,i=0;i<a.length;i++){var u=a[i];if(u.parts.length===r){for(var o=[],c=0;r>c;c++)if(":"===u.parts[c].substr(0,1))o.push(t[c]);else if(u.parts[c]!==t[c])break;if(c===r)return u.handler.apply(n,o),n}}}var a=[];return e.onhashchange=t,{addRoute:function(e,t){a.push({parts:e.split("/"),handler:t})},load:function(t){e.location.hash=t},start:t}}(t),e.hookin("attributes","key",function(e){e.value=null}),e.hookin("attributes","style",function(e){if("object"==typeof e.value){var t=e.node.getAttribute("style")||"",a="";r(e.value,function(e,t){a+=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()+":"+(isNaN(t)?t:t+"px")+";"}),e.value=t&&~t.indexOf(a)?t:t+a}}),e.hookin("attributes","className",function(e){e.key="class";var t=e.value;if("string"==typeof e.value)t=e.value.split(" ");else if("object"==typeof e.value){for(var a in t)e.node.classList.toggle(a,t[a]);return e.value=e.node.classList+"",n}e.value=e.node.classList+"";for(a in t){var r=t[a];r.trim()&&0<e.node.classList.length&&!e.node.classList.contains(r.trim())?e.value=e.node.classList+" "+r:r.trim()&&0==e.node.classList.length&&(e.value+=r+" ")}e.value=e.value.trim()}),e.hookin("values","*",function(t){var a=typeof t.value;if(null!=t.value)if("function"===a&&t.value.toJSON)t.change=1,t.value=t.value();else if("object"==a&&"function"==typeof t.value.then){var n=e.utils.items.getItem(e.fill.id);t.value.then(function(a){e.mod.getState(n)[t.key]=a}),t.value.initialValue&&(t.change=1,t.value=t.value.initialValue)}}),e.getId=function(t){return e.utils.items.getItemVal(t)},e.prop=function(e){var t=function(){return arguments.length&&(e=arguments[0]),e};return t.toJSON=function(){return e},t},e.withProp=function(e,t){return function(a){a=a||event,a=a.currentTarget||this,t(e in a?a[e]:a.getAttribute(e))}}}(mag,window||global||this,document);
<|endoftext|>


<commit_before>'use strict';

const conf = global.conf;
const pubDir = global.conf.ui.paths.public;
const srcDir = global.conf.ui.paths.source;

const gulp = require('gulp');
const plugins = require('gulp-load-plugins')();

const utils = require('../core/lib/utils');

gulp.task('tcp-ip-reload:listen', function () {
  plugins.refresh.listen({port: conf.livereload_port});
});

gulp.task('tcp-ip-reload:assetsScripts', function () {
  return gulp.src(utils.pathResolve(pubDir.root) + '/!(_styles|patterns|styleguide)/**')
    .pipe(plugins.refresh());
});

gulp.task('tcp-ip-reload:index', function () {
  return gulp.src(utils.pathResolve(pubDir.root) + '/index.html')
    .pipe(plugins.refresh());
});

gulp.task('tcp-ip-reload:injectStyles', function () {
  return gulp.src(utils.pathResolve(pubDir.css) + '/**/*.css')
    .pipe(plugins.refresh());
});

gulp.task('tcp-ip-reload:watch', function () {
  // Need delay in order for launch to succeed consistently.
  setTimeout(function () {
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.images)}, ['patternlab:copy']);
    gulp.watch('_data.json', {cwd: utils.pathResolve(srcDir.data)}, ['data']);
    gulp.watch('listitems.json', {cwd: utils.pathResolve(srcDir.data)}, ['patternlab:build']);
    gulp.watch('annotations.json', {cwd: utils.pathResolve(srcDir.annotations)}, ['patternlab:build']);
    gulp.watch('**/*.mustache', {cwd: utils.pathResolve(srcDir.meta)}, ['patternlab:build']);
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.patterns)}, ['data']);
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.js)}, ['patternlab:copy']);
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.css)}, ['patternlab:copy-styles']);
    gulp.watch('static/**', {cwd: utils.pathResolve(srcDir.root)}, ['patternlab:copy']);
    gulp.watch('!(_styles|patterns|styleguide)/**', {cwd: utils.pathResolve(pubDir.root)}, ['tcp-ip-reload:assetsScripts']);
    gulp.watch('**/*.css', {cwd: utils.pathResolve(pubDir.css)}, ['tcp-ip-reload:injectStyles']);
    gulp.watch('index.html', {cwd: utils.pathResolve(pubDir.root)}, ['tcp-ip-reload:index']);
  }, conf.timeout_main);
});
<commit_msg>more general gulp.watch<commit_after>'use strict';

const conf = global.conf;
const pubDir = global.conf.ui.paths.public;
const srcDir = global.conf.ui.paths.source;

const gulp = require('gulp');
const plugins = require('gulp-load-plugins')();

const utils = require('../core/lib/utils');

gulp.task('tcp-ip-reload:listen', function () {
  plugins.refresh.listen({port: conf.livereload_port});
});

gulp.task('tcp-ip-reload:assetsScripts', function () {
  return gulp.src(utils.pathResolve(pubDir.root) + '/!(_styles|patterns|styleguide)/**')
    .pipe(plugins.refresh());
});

gulp.task('tcp-ip-reload:index', function () {
  return gulp.src(utils.pathResolve(pubDir.root) + '/index.html')
    .pipe(plugins.refresh());
});

gulp.task('tcp-ip-reload:injectStyles', function () {
  return gulp.src(utils.pathResolve(pubDir.css) + '/**/*.css')
    .pipe(plugins.refresh());
});

gulp.task('tcp-ip-reload:watch', function () {
  // Need delay in order for launch to succeed consistently.
  setTimeout(function () {
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.images)}, ['patternlab:copy']);
    gulp.watch('_data.json', {cwd: utils.pathResolve(srcDir.data)}, ['data']);
    gulp.watch('listitems.json', {cwd: utils.pathResolve(srcDir.data)}, ['patternlab:build']);
    gulp.watch('annotations.json', {cwd: utils.pathResolve(srcDir.annotations)}, ['patternlab:build']);
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.meta)}, ['patternlab:build']);
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.patterns)}, ['data']);
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.js)}, ['patternlab:copy']);
    gulp.watch('**', {cwd: utils.pathResolve(srcDir.css)}, ['patternlab:copy-styles']);
    gulp.watch('static/**', {cwd: utils.pathResolve(srcDir.root)}, ['patternlab:copy']);
    gulp.watch('!(_styles|patterns|styleguide)/**', {cwd: utils.pathResolve(pubDir.root)}, ['tcp-ip-reload:assetsScripts']);
    gulp.watch('**', {cwd: utils.pathResolve(pubDir.css)}, ['tcp-ip-reload:injectStyles']);
    gulp.watch('index.html', {cwd: utils.pathResolve(pubDir.root)}, ['tcp-ip-reload:index']);
  }, conf.timeout_main);
});
<|endoftext|>


<commit_before>
	// style
	// stroke, fill,

	// attributes
	// x1, x2, y1, y2, r, cx, cy, d, x, y
	// stroke, stroke-width, fill, stroke-dash-array

	// CURRENT THINGS TO CONSIDER

	// if animation is running, should new function call take over or work "on top"/"side-by-side"
	// css transitions take over

	u.a.getInitialValue = function(node, attribute) {

		var value = (node.getAttribute(attribute) ? node.getAttribute(attribute) : u.gcs(node, attribute)).replace(node._unit[attribute], "")
		return Number(value.replace(/auto/, 0));
	}

	u.a.to = function(node, transition, attributes) {

		// get duration
		var duration = transition.match(/[0-9.]+[ms]+/g);
		if(duration) {
	//		u.bug(duration[0]);
			node.duration = duration[0].match("ms") ? parseFloat(duration[0]) : (parseFloat(duration[0]) * 1000);
		}

		// TODO: get delay

		node._start = {};
		node._end = {};
		node._unit = {};

		for(attribute in attributes) {

			node._unit[attribute] = attributes[attribute].toString().match(/\%|px/);

			node._start[attribute] = Number(this.getInitialValue(node, attribute));
			 //(node.getAttribute(attribute) ? node.getAttribute(attribute) : u.gcs(node, attribute)).replace(node._unit[attribute], "");
			node._end[attribute] = attributes[attribute].toString().replace(node._unit[attribute], "");

//			u.bug("attributes["+attribute+"] = "+attributes[attribute] + "::"+ node._start[attribute] + " -> " + node._end[attribute]);

		}
//		u.bug("duration:" + node.duration);

		node.transitionTo = function(progress) {

			for(attribute in attributes) {
				if(attribute.match(/translate|rotate|scale/)) {

					if(attribute == "translate") {
						u.a.translate(this, Math.round((this._end_x - this._start_x) * progress), Math.round((this._end_y - this._start_y) * progress))
					}
					else if(attribute == "rotate") {

					}

				}
				else if(attribute.match(/x1|y1|x2|y2|r|cx|cy|stroke-width/)) {

					var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]
//					u.bug("update:" + attribute + ":" + new_value);

					this.setAttribute(attribute, new_value);

				}
				else {

					//u.bug("update:" + this._end[attribute] + "-" + this._start[attribute] + " * " + progress + " " + this._unit[attribute])
					var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]

//					u.bug("update:" + attribute + ":" + new_value);

					u.as(node, attribute, new_value, false);

				}

			}

		}

//			u.bug(u.nodeId(this) + ":progress:" + progress + " ("+(this._end_x - this._start_x) * progress+","+(this._end_y - this._start_y) * progress+")")

		u.a.requestAnimationFrame(node, "transitionTo", node.duration);

	}

// this.animationFrame = function(node, callback) {
//
// 	if(!window._animationframe) {
// 		window._animationframe = window[this.vendor("requestAnimationFrame")]
//
// 	}
//
// }
//
//
// window.cancelRequestAnimFrame = ( function() {
// 	return window.cancelAnimationFrame 						||
//       window.webkitCancelRequestAnimationFrame 	||
//       window.mozCancelRequestAnimationFrame 		||
//       window.oCancelRequestAnimationFrame 			||
//       window.msCancelRequestAnimationFrame			||
//       clearTimeout
// } )();
//
// window.requestAnimFrame = (function() {
//   return  window.requestAnimationFrame     ||
//         window.webkitRequestAnimationFrame ||
//         window.mozRequestAnimationFrame    ||
//         window.oRequestAnimationFrame      ||
//         window.msRequestAnimationFrame     ||
//         function(callback, element){
//             return window.setTimeout(callback, 1000 / 60);
//         };
// })();
//
// (function() {
//     var lastTime = 0;
//     var vendors = ['ms', 'moz', 'webkit', 'o'];
//     for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
//         window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
//         window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
//                                    || window[vendors[x]+'CancelRequestAnimationFrame'];
//     }
//
//     if (!window.requestAnimationFrame)
//         window.requestAnimationFrame = function(callback, element) {
//             var currTime = new Date().getTime();
//             var timeToCall = Math.max(0, 16 - (currTime - lastTime));
//             var id = window.setTimeout(function() { callback(currTime + timeToCall); },
//               timeToCall);
//             lastTime = currTime + timeToCall;
//             return id;
//         };
//
//     if (!window.cancelAnimationFrame)
//         window.cancelAnimationFrame = function(id) {
//             clearTimeout(id);
//         };
// }());
<commit_msg>Animating paths<commit_after>
	// style
	// stroke, fill,

	// attributes
	// x1, x2, y1, y2, r, cx, cy, d, x, y
	// stroke, stroke-width, fill, stroke-dash-array

	// CURRENT THINGS TO CONSIDER

	// if animation is running, should new function call take over or work "on top"/"side-by-side"
	// css transitions take over

	u.a.parseSVGPath = function(value) {

		// values required for each type
		var pairs = {"m":2, "l":2, "a":7, "c":6, "s":4, "q":4, "z":0};

		// add structure to string for parsability
		value = value.replace(/-/g, " -");
		value = value.replace(/,/g, " ");
		value = value.replace(/(m|l|a|c|s|q|M|L|A|C|S|Q)/g, " $1 ");
		value = value.replace(/  /g, " ");

		// check values
		sets = value.match(/(m|l|a|c|s|q|M|L|A|C|S|Q)([0-9 \-\.]+)/g);

		for(x in sets) {
			parts = sets[x].trim().split(" ");

			sets[x] = parts;

			if(parts && pairs[parts[0].toLowerCase()] == parts.length-1) {
//				u.bug("valid set:" + parts);
			}
			else {
//				u.bug("invalid set - could be 'dual' set with only one identifier")
			}

		}

		// u.bug("values:" + sets);
		// u.bug("value:" + value);
		return sets;

	}

	u.a.getInitialValue = function(node, attribute) {

		var value = (node.getAttribute(attribute) ? node.getAttribute(attribute) : u.gcs(node, attribute)).replace(node._unit[attribute], "")
		if(attribute.match(/^(d)$/)) {
			return value;
//			value.split("m|l|a|c|s|M|L|A|C|S");

		}
		else {
			return Number(value.replace(/auto/, 0));
		}
	}

	u.a.to = function(node, transition, attributes) {

		// get duration
		var duration = transition.match(/[0-9.]+[ms]+/g);
		if(duration) {
	//		u.bug(duration[0]);
			node.duration = duration[0].match("ms") ? parseFloat(duration[0]) : (parseFloat(duration[0]) * 1000);
		}

		var value, d;

		// TODO: get delay

		node._start = {};
		node._end = {};
		node._unit = {};

		for(attribute in attributes) {

			// path definitions are
			if(attribute.match(/^(d)$/)) {

				node._start[attribute] = this.parseSVGPath(this.getInitialValue(node, attribute));
				node._end[attribute] = this.parseSVGPath(attributes[attribute]);

//				u.bug("start:" + node._start[attribute].join("#"))
//				u.bug("end:" + node._end[attribute])

				// d_parts = this.getInitialValue(node, attribute);
				//
				// u.bug("d_parts:" + d_parts)
				//
				//
				// node._start[attribute] = d_parts.split("m|l|a|c|s|M|L|A|C|S");
				//
				// u.bug("node._start:" + node._start[attribute])

			}
			// plain number svg shapes
			else {

				node._unit[attribute] = attributes[attribute].toString().match(/\%|px/);
				node._start[attribute] = this.getInitialValue(node, attribute);
				 //(node.getAttribute(attribute) ? node.getAttribute(attribute) : u.gcs(node, attribute)).replace(node._unit[attribute], "");
				node._end[attribute] = attributes[attribute].toString().replace(node._unit[attribute], "");

			}

//			u.bug("attributes["+attribute+"] = "+attributes[attribute] + "::"+ node._start[attribute] + " -> " + node._end[attribute]);

		}
//		u.bug("duration:" + node.duration);

		node.transitionTo = function(progress) {

			for(attribute in attributes) {

				// transform value
				if(attribute.match(/^(translate|rotate|scale)$/)) {

					if(attribute == "translate") {

						u.a.translate(this, Math.round((this._end_x - this._start_x) * progress), Math.round((this._end_y - this._start_y) * progress))
					}
					else if(attribute == "rotate") {

					}

				}

				// plain svg value
				else if(attribute.match(/^(x1|y1|x2|y2|r|cx|cy|stroke-width)$/)) {

					var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]
//					u.bug("update:" + attribute + ":" + new_value);

					this.setAttribute(attribute, new_value);

				}

				// path d attribute
				else if(attribute.match(/^(d)$/)) {
//					u.bug("path")
//					var d_parts = this._start[attribute].split("m|l|a|c|s|M|L|A|C|S");
//					u.bug("d_parts:" + d_parts)
					var new_value = "";
					for(x in this._start[attribute]) {

						for(y in this._start[attribute][x]) {
//							u.bug("pf:" + this._start[attribute][x][y] + " :: " + parseFloat(this._start[attribute][x][y]) + ", " + typeof(this._start[attribute][x][y]))

							if(parseFloat(this._start[attribute][x][y]) == this._start[attribute][x][y]) {
								new_value += (Number(this._start[attribute][x][y]) + ((Number(this._end[attribute][x][y]) - Number(this._start[attribute][x][y])) * progress)) + " ";
							}
							else {
								new_value += this._end[attribute][x][y] + " ";
							}
						}
					}
					// var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]
//
//					u.bug("set new:" + new_value);
					this.setAttribute(attribute, new_value);

				}
				// regular attribute
				else {

					//u.bug("update:" + this._end[attribute] + "-" + this._start[attribute] + " * " + progress + " " + this._unit[attribute])
					var new_value = (this._start[attribute] + ((this._end[attribute] - this._start[attribute]) * progress)) +  this._unit[attribute]

//					u.bug("update:" + attribute + ":" + new_value);

					u.as(node, attribute, new_value, false);

				}

			}

		}

//			u.bug(u.nodeId(this) + ":progress:" + progress + " ("+(this._end_x - this._start_x) * progress+","+(this._end_y - this._start_y) * progress+")")

		u.a.requestAnimationFrame(node, "transitionTo", node.duration);

	}

// this.animationFrame = function(node, callback) {
//
// 	if(!window._animationframe) {
// 		window._animationframe = window[this.vendor("requestAnimationFrame")]
//
// 	}
//
// }
//
//
// window.cancelRequestAnimFrame = ( function() {
// 	return window.cancelAnimationFrame 						||
//       window.webkitCancelRequestAnimationFrame 	||
//       window.mozCancelRequestAnimationFrame 		||
//       window.oCancelRequestAnimationFrame 			||
//       window.msCancelRequestAnimationFrame			||
//       clearTimeout
// } )();
//
// window.requestAnimFrame = (function() {
//   return  window.requestAnimationFrame     ||
//         window.webkitRequestAnimationFrame ||
//         window.mozRequestAnimationFrame    ||
//         window.oRequestAnimationFrame      ||
//         window.msRequestAnimationFrame     ||
//         function(callback, element){
//             return window.setTimeout(callback, 1000 / 60);
//         };
// })();
//
// (function() {
//     var lastTime = 0;
//     var vendors = ['ms', 'moz', 'webkit', 'o'];
//     for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
//         window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
//         window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
//                                    || window[vendors[x]+'CancelRequestAnimationFrame'];
//     }
//
//     if (!window.requestAnimationFrame)
//         window.requestAnimationFrame = function(callback, element) {
//             var currTime = new Date().getTime();
//             var timeToCall = Math.max(0, 16 - (currTime - lastTime));
//             var id = window.setTimeout(function() { callback(currTime + timeToCall); },
//               timeToCall);
//             lastTime = currTime + timeToCall;
//             return id;
//         };
//
//     if (!window.cancelAnimationFrame)
//         window.cancelAnimationFrame = function(id) {
//             clearTimeout(id);
//         };
// }());
<|endoftext|>


<commit_before>'use strict';

const babel = require('broccoli-babel-transpiler');
const stripGlimmerUtils = require('babel-plugin-strip-glimmer-utils');
const debugMacros = require('babel-plugin-debug-macros').default;
const nuke = require('babel-plugin-nukable-import');
const nameResolver = require('amd-name-resolver').moduleResolve;

/**
 * Optimizes out Glimmer utility functions and strips debug code with a set of
 * Babel plugins.
 */
module.exports = function(jsTree) {
  let RETAIN_FLAGS = process.env.RETAIN_FLAGS;
  let glimmerUtils = [];
  if (!RETAIN_FLAGS) {
    glimmerUtils.push([debugMacros, {
      envFlags: {
        source: '@glimmer/local-debug-flags',
        flags: {
          DEBUG: process.env.EMBER_ENV !== 'production',
          DEVMODE: process.env.EMBER_ENV !== 'production'
        }
      },
      debugTools: {
        source: '@glimmer/debug'
      },
      externalizeHelpers: {
        module: true
      }
    }])

    glimmerUtils.push([nuke, { source: '@glimmer/debug' }])
    glimmerUtils.push([nuke, { source: '@glimmer/vm/lib/-debug-strip' }]);
    glimmerUtils.push([nuke, {
      source: '@glimmer/vm',
      delegate: removeMetaData
    }]);
  }

  function removeMetaData(bindingName, path, t) {
    if (bindingName === 'METADATA') {
      path.parentPath.replaceWith(t.nullLiteral());
    }
  }

  removeMetaData.baseDir = nuke.baseDir;

  return babel(jsTree, {
    annotation: 'Babel - Strip Glimmer Utilities',
    sourceMaps: 'inline',
    moduleIds: true,
    getModuleId: nameResolver,
    plugins: [
      ...glimmerUtils,
      [stripGlimmerUtils, { bindings: ['expect', 'unwrap'], source: '@glimmer/util' }]
    ]
  });
}
<commit_msg>Nuke the debugging imports from opcode-compiler<commit_after>'use strict';

const babel = require('broccoli-babel-transpiler');
const stripGlimmerUtils = require('babel-plugin-strip-glimmer-utils');
const debugMacros = require('babel-plugin-debug-macros').default;
const nuke = require('babel-plugin-nukable-import');
const nameResolver = require('amd-name-resolver').moduleResolve;

/**
 * Optimizes out Glimmer utility functions and strips debug code with a set of
 * Babel plugins.
 */
module.exports = function(jsTree) {
  let RETAIN_FLAGS = process.env.RETAIN_FLAGS;
  let glimmerUtils = [];
  if (!RETAIN_FLAGS) {
    glimmerUtils.push([debugMacros, {
      envFlags: {
        source: '@glimmer/local-debug-flags',
        flags: {
          DEBUG: process.env.EMBER_ENV !== 'production',
          DEVMODE: process.env.EMBER_ENV !== 'production'
        }
      },
      debugTools: {
        source: '@glimmer/debug'
      },
      externalizeHelpers: {
        module: true
      }
    }])

    glimmerUtils.push([nuke, { source: '@glimmer/debug' }])
    glimmerUtils.push([nuke, { source: '@glimmer/vm/lib/-debug-strip' }]);
    glimmerUtils.push([nuke, {
      source: '@glimmer/vm',
      delegate: removeMetaData
    }]);
    glimmerUtils.push([nuke, {
      source: '@glimmer/opcode-compiler',
      delegate: removeLogging
    }]);
  }

  return babel(jsTree, {
    annotation: 'Babel - Strip Glimmer Utilities',
    sourceMaps: 'inline',
    moduleIds: true,
    getModuleId: nameResolver,
    plugins: [
      ...glimmerUtils,
      [stripGlimmerUtils, { bindings: ['expect', 'unwrap'], source: '@glimmer/util' }]
    ]
  });
}

function removeMetaData(bindingName, path, t) {
  if (bindingName === 'METADATA') {
    path.parentPath.replaceWith(t.nullLiteral());
  }
}

function removeLogging(bindingName, path, t) {
  if (bindingName === 'debugSlice') {
    path.parentPath.remove();
  }

  if (bindingName === 'debug') {
    path.parentPath.replaceWith(t.arrayExpression());
  }

  if (bindingName === 'logOpcode') {
    path.parentPath.replaceWith(t.stringLiteral(''));
  }
}

removeLogging.baseDir = nuke.baseDir;
removeMetaData.baseDir = nuke.baseDir;
<|endoftext|>


<commit_before>!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.VueInputAutowidth={})}(this,function(e){"use strict";function t(e,t){if(void 0===e||null===e)throw new TypeError("Cannot convert first argument to object");for(var n=Object(e),o=1;o<arguments.length;o++){var r=arguments[o];if(void 0!==r&&null!==r)for(var i=Object.keys(Object(r)),a=0,u=i.length;a<u;a++){var d=i[a],l=Object.getOwnPropertyDescriptor(r,d);void 0!==l&&l.enumerable&&(n[d]=r[d])}}return n}function n(e,t){e.directive("autowidth",r)}({assign:t,polyfill:function(){Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:t})}}).polyfill();var o=function(e,t){var n=document.querySelector(".vue-input-autowidth-mirror-"+e.dataset.uuid),o=Object.assign({},{maxWidth:"none",minWidth:"none",comfortZone:0},t.value);e.style.maxWidth=o.maxWidth,e.style.minWidth=o.minWidth;var r=e.value;for(r||(r=e.placeholder||"");n.childNodes.length;)n.removeChild(n.childNodes[0]);n.appendChild(document.createTextNode(r));var i=n.getBoundingClientRect().width+o.comfortZone;i!=e.getBoundingClientRect().width&&(e.style.width=i+"px")},r={bind:function(e){if("INPUT"!==e.tagName.toLocaleUpperCase())throw new Error("v-input-autowidth can only be used on input elements.");e.dataset.uuid=Math.random().toString(36).slice(-5)},inserted:function(e,t){e.mirror=document.createElement("span"),e.mirror.classList.add("vue-input-autowidth-mirror-"+e.dataset.uuid);var n=window.getComputedStyle(e);Object.assign(e.mirror.style,{position:"absolute",top:"-9999px",left:"-9999px",width:"auto",whiteSpace:"pre",opacity:0,border:n.getPropertyValue("border"),fontSize:n.getPropertyValue("font-size"),fontFamily:n.getPropertyValue("font-family"),fontWeight:n.getPropertyValue("font-weight"),fontStyle:n.getPropertyValue("font-style"),fontFeatureSettings:n.getPropertyValue("font-feature-settings"),fontKerning:n.getPropertyValue("font-kerning"),fontStretch:n.getPropertyValue("font-stretch"),fontVariant:n.getPropertyValue("font-variant"),fontVariantCaps:n.getPropertyValue("font-variant-caps"),fontVariantLigatures:n.getPropertyValue("font-variant-ligatures"),fontVariantNumeric:n.getPropertyValue("font-variant-numeric"),letterSpacing:n.getPropertyValue("letter-spacing"),padding:n.getPropertyValue("padding"),textTransform:n.getPropertyValue("text-transform"),ariaHidden:!0}),document.body.appendChild(e.mirror),o(e,t)},componentUpdated:function(e,t){o(e,t)},unbind:function(e){document.body.removeChild(e.mirror)}};"undefined"!=typeof window&&window.Vue&&window.Vue.use(n),e.default=n,e.VueInputAutoWidth=r,Object.defineProperty(e,"__esModule",{value:!0})});
<commit_msg>actually build the changes from 1.0.4 (#14)<commit_after>!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.VueInputAutowidth={})}(this,function(t){"use strict";function e(t,e){if(null==t)throw new TypeError("Cannot convert first argument to object");for(var n=Object(t),r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o)for(var i=Object.keys(Object(o)),a=0,u=i.length;a<u;a++){var d=i[a],l=Object.getOwnPropertyDescriptor(o,d);void 0!==l&&l.enumerable&&(n[d]=o[d])}}return n}({assign:e,polyfill:function(){Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:e})}}).polyfill();var r=function(t,e){var n=document.querySelector(".vue-input-autowidth-mirror-"+t.dataset.uuid),r=Object.assign({},{maxWidth:"none",minWidth:"none",comfortZone:0},e.value);t.style.maxWidth=r.maxWidth,t.style.minWidth=r.minWidth;var o=t.value;for(o||(o=t.placeholder||"");n.childNodes.length;)n.removeChild(n.childNodes[0]);n.appendChild(document.createTextNode(o));var i=n.getBoundingClientRect().width+r.comfortZone;i!=t.getBoundingClientRect().width&&(t.style.width=i+"px")},n={bind:function(t){if("INPUT"!==t.tagName.toLocaleUpperCase())throw new Error("v-input-autowidth can only be used on input elements.");t.dataset.uuid=Math.random().toString(36).slice(-5)},inserted:function(t,e){t.mirror=document.createElement("span"),t.mirror.classList.add("vue-input-autowidth-mirror-"+t.dataset.uuid);var n=window.getComputedStyle(t);Object.assign(t.mirror.style,{position:"absolute",top:"-9999px",left:"-9999px",width:"auto",whiteSpace:"pre",opacity:0,border:n.getPropertyValue("border"),fontSize:n.getPropertyValue("font-size"),fontFamily:n.getPropertyValue("font-family"),fontWeight:n.getPropertyValue("font-weight"),fontStyle:n.getPropertyValue("font-style"),fontFeatureSettings:n.getPropertyValue("font-feature-settings"),fontKerning:n.getPropertyValue("font-kerning"),fontStretch:n.getPropertyValue("font-stretch"),fontVariant:n.getPropertyValue("font-variant"),fontVariantCaps:n.getPropertyValue("font-variant-caps"),fontVariantLigatures:n.getPropertyValue("font-variant-ligatures"),fontVariantNumeric:n.getPropertyValue("font-variant-numeric"),letterSpacing:n.getPropertyValue("letter-spacing"),padding:n.getPropertyValue("padding"),textTransform:n.getPropertyValue("text-transform")}),t.mirror.setAttribute("aria-hidden","true"),document.body.appendChild(t.mirror),r(t,e)},componentUpdated:function(t,e){r(t,e)},unbind:function(t){document.body.removeChild(t.mirror)}};function o(t,e){t.directive("autowidth",n)}"undefined"!=typeof window&&window.Vue&&window.Vue.use(o),t.default=o,t.VueInputAutoWidth=n,Object.defineProperty(t,"__esModule",{value:!0})});
<|endoftext|>