<commit_before>Highcharts.setOptions({
    lang: {
        thousandsSep: ','
    },
    chart: {
        style: {
            fontFamily: '"ColaborateThinRegular", sans-serif'
        }
    }
});

var ChartHelper = ChartHelper || {};
var ChartHelper = {

    cleaned_data: [],
    categories: [],

    get_colors: function(num_series){

      if (num_series == 7){
        // age groups
        return ['#547bb6', '#6e83a5', '#878b94', '#a19383', '#ba9b72', '#d4a361', '#edab50']
        // return ['#e0ecf4', '#bfd3e6', '#9ebcda', '#8c96c6', '#8c6bb1', '#88419d', '#6e016b']
      }
      if (num_series == 6){
        // income groups
        return ['#ce603b', '#cc893d', '#cab040', '#AAA646', '#74722F', '#48471E']
      }

      if (num_series == 5){
        // income groups
        return ['#ce603b', '#cc893d', '#cab040', '#AAA646', '#48471E']
      }

      if (num_series == 4){
        // building types
        return ['#8DA7CE', '#547BB6', '#375481', '#1F2F47']
        //return ['#BDD9FF', '#82AFF1', '#1769D6', '#395A88'];
      }

      if (num_series == 3){
        return ['#375481', '#8DA7CE', '#CE603B'];
      }

      if (num_series == 2){
        return ['#375481', '#8DA7CE'];
      }

      return ['#547BB6'];
    },

    prep_chart_data: function(data, primary_dimension, number_type){
      // preps a matrix-esque csv w/ labels for rows & columns
      if(primary_dimension == 'row'){
        var csv_arrays = this.transpose($.csv.toArrays(data))
      } else{
        var csv_arrays = $.csv.toArrays(data);
      }

      var series_data = []
      var col_names = csv_arrays[0].slice(1)

      // loop through rows after first row
      var series_count = 0;
      var num_series = csv_arrays.length - 1;

      $.each(csv_arrays.slice(1), function(row_id, row){
        // first element is row name, rest is data
        var row_name = row[0]
        var row_data = []
        // format numbers
        $.each(row.slice(1), function(i, val){
          if(number_type == 'count'){
            // get rid of commas, parse int
            row_data.push(parseInt(val.replace(/,/g,'')));
          } else if (number_type == 'percentage'){
            row_data.push(parseFloat(val)*100);
          } else if (number_type == 'rate'){
            row_data.push(parseFloat(val));
          } else{
            // do nothing
            row_data.push(val);
          }
        });

        series_data.push({
          name: row_name,
          data: row_data,
          color: ChartHelper.get_colors(num_series)[series_count]
        });

        series_count = series_count + 1;
      });

      return [series_data, col_names]

    },

    transpose: function(a){
      return Object.keys(a[0]).map(
        function (c) { return a.map(function (r) { return r[c]; }); }
      );
    },

    make_bar_chart: function(el, series_data, categories, chart_title, yaxis_title, plotOptions, tooltip){

      $(el).highcharts({
        chart: {
          type: 'column',
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 40
        },
        plotOptions: plotOptions,
        credits: { enabled: false },
        title: {
          text: chart_title[0]
        },
        subtitle: {
          text: chart_title[1]
        },
        xAxis: {
          categories: categories,
          tickmarkPlacement: 'on',
          title: {
              enabled: false
          }
        },
        yAxis: {
          title: {
              text: yaxis_title
          },
          endOnTick: false,
          min: 0
        },
        tooltip: tooltip,
        series: series_data
      });

    },

    make_negative_bar_chart: function(el, series_data, categories, chart_title, yaxis_title, plotOptions, tooltip){

      $(el).highcharts({
        chart: {
          type: 'column',
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 40
        },
        plotOptions: plotOptions,
        credits: { enabled: false },
        title: {
          text: chart_title[0]
        },
        subtitle: {
          text: chart_title[1]
        },
        xAxis: {
          categories: categories,
          tickmarkPlacement: 'on',
          title: {
              enabled: false
          }
        },
        yAxis: {
          title: {
              text: yaxis_title
          },
          endOnTick: false
        },
        tooltip: tooltip,
        series: series_data
      });

    },

    make_composition_chart: function(el, series_data, categories, chart_title, xaxis_title, yaxis_title){

      // flipping data so that most recent year comes first
      categories = categories.reverse()
      $.each(series_data, function(i, group_data){
        group_data['data'] = group_data['data'].reverse()
      });

      $(el).highcharts({
        chart: {
          type: 'bar',
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 40
        },
        plotOptions: {
          series: {
            stacking: 'percent',
            dataLabels: {
              enabled: true,
              format: '{y:,.1f}%',
              color: '#fff',
              style: {
                textShadow: 'none',
                opacity: .8,
                fontWeight: 'bold'
              }
            },
            states: {
              hover: {
                enabled: false
              }
            }
          }
        },
        credits: { enabled: false },
        title: {
          text: chart_title[0]
        },
        subtitle: {
          text: chart_title[1]
        },
        xAxis: {
          categories: categories,
          tickmarkPlacement: 'on',
          title: {
              enabled: false
          }
        },
        yAxis: {
          title: {
              text: yaxis_title
          },
          min: 0,
          tickInterval: 100,
          reversedStacks: false
        },
        tooltip: {
          enabled: false
        },
        legend: {
          symbolPadding: 3,
          itemDistance: 12

        },
        series: series_data
      });

    },

    make_small_bar_chart: function(el, series_data, chart_title, y_range, data_type){

      if (data_type == 'percent') {
        num_format = '{point.y:,.1f}%'
        y_labels = {
              formatter: function () {
                  return this.value + '%';
              }
            }
      } else {
        num_format = '{point.y:,.0f}'
        y_labels = {}
      }

      $(el).highcharts({
        chart: {
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 30,
          spacingBottom: 30,
          type: 'column'
        },
        plotOptions: {
          series: {
            groupPadding: 0
          }
        },
        credits: { enabled: false },
        title: {
          text: chart_title,
          style: {
                fontSize: '16px'
            }
        },
        legend: {
            enabled: false
        },
        xAxis: {
          categories: [chart_title],
          lineWidth: 0,
          tickLength: 0,
          title: {
            enabled: false
          },
          labels: {
            enabled: false
          }
        },
        yAxis: {
          title: {
              enabled: false
          },
          min: y_range[0],
          max: y_range[1],
          endOnTick: false,
          labels: y_labels
        },
        tooltip: {
          borderColor: '#eee',
          shadow: false,
          headerFormat: '',
          pointFormat: num_format,
        },
        series: series_data
      });

    },

    make_small_line_chart: function(el, series_data, categories, chart_title, y_range, data_type){

      if (data_type=='percent'){
        num_format = '{point.y:,.1f}%'
        y_labels = {
          formatter: function () {
            return this.value + '%';
          }
        }
      } else {
        num_format = '{point.y:,.0f}'
        y_labels = {}
      }

      $(el).highcharts({
        chart: {
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 15,
          spacingBottom: 15,
          type: 'area'
        },
        plotOptions: {
          area: {
            fillOpacity: 0.25
          }
        },
        credits: { enabled: false },
        title: {
          text: chart_title,
          style: {
                fontSize: '16px'
            }
        },
        legend: {
            enabled: false
        },
        xAxis: {
          categories: categories,
          lineWidth: 0,
          tickLength: 0,
          title: {
            enabled: false
          },
        },
        yAxis: {
          title: {
              enabled: false
          },
          min: y_range[0],
          max: y_range[1],
          endOnTick: false,
          labels: y_labels
        },
        tooltip: {
          borderColor: '#eee',
          shadow: false,
          headerFormat: '',
          pointFormat: num_format,
        },
        series: series_data
      });

    },

    make_small_composition_chart: function(el, series_data, categories, chart_title, data_type){

      if (data_type=='percent'){
        num_format = '{point.y:,.1f}%';
      } else {
        num_format = '{point.y:,.0f}';
      }

      $(el).highcharts({
        chart: {
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 30,
          spacingBottom: 30,
          type: 'area'
        },
        plotOptions: {
          area: {
            marker: {
              symbol: 'circle',
              radius: 2
            },
            stacking: 'percent',
            fillOpacity: 0.7
          },
          series: {
            pointPadding: 0
          }
        },
        credits: { enabled: false },
        title: {
          text: chart_title,
          style: {
                fontSize: '16px'
            }
        },
        legend: {
            enabled: false
        },
        xAxis: {
          categories: categories,
          lineWidth: 0,
          tickLength: 0,
          title: {
            enabled: false
          },
          min: 0.5,
          max: 4.5
        },
        yAxis: {
          title: {
              enabled: false
          },
          min: 0,
          max: 100,
          endOnTick: false,
          labels: {
            formatter: function () {
              return this.value + '%';
            }
          }
        },
        tooltip: {
          shared: true,
          borderColor: '#eee',
          shadow: false,
          headerFormat: '',
          pointFormat: '\u25CF {series.name}: ' + num_format + '
.'
        },
        series: series_data
      });

    },

    make_line_chart: function(el, series_data, categories, chart_title, yaxis_title, data_type){
      if (data_type == 'percent'){
        y_min = null
        y_labels = {
              formatter: function () {
                  return this.value + '%';
              }
            }
        data_labels = {
                    enabled: true,
                    format: "{point.y:.1f}%"
                }
        states = {
                hover: {
                  enabled: false
                }
              }
        tooltip = {
            enabled: false
        }
      } else {
        y_min = 0
        y_labels = {}
        data_labels = {
          enabled: false
        }
        states = {}
        tooltip = {
          borderColor: '#eee',
          shadow: false,
          headerFormat: '',
          pointFormat: '{point.y:,.0f}',
        }

      }

      $(el).highcharts({
        chart: {
          type: 'line',
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 40
        },
        credits: { enabled: false },
        title: {
            text: chart_title[0]
        },
        subtitle: {
            text: chart_title[1]
        },
        xAxis: {
            categories: categories,
            tickmarkPlacement: 'on',
            title: {
                enabled: false
            }
        },
        yAxis: {
            title: {
                text: yaxis_title
            },
            labels: y_labels,
            min: y_min
        },
        tooltip: tooltip,
        plotOptions: {
            line: {
                marker: {
                    lineWidth: 1,
                    lineColor: '#ffffff',
                    symbol: 'square'
                },
                dataLabels: data_labels
            },
            series: {
              states: states
            }
        },
        series: series_data
      });

    },

    formatAmount: function(value) {
      if (value >= 1000000000)
        return Math.round(value / 1000000000) + "B";
      else if (value >= 1000000)
        return Math.round(value / 1000000) + "M";
      else if (value >= 1000)
        return Math.round(value / 1000) + "K";
      else
        return value;
    }

}<commit_msg>condensing small multiples<commit_after>Highcharts.setOptions({
    lang: {
        thousandsSep: ','
    },
    chart: {
        style: {
            fontFamily: '"ColaborateThinRegular", sans-serif'
        }
    }
});

var ChartHelper = ChartHelper || {};
var ChartHelper = {

    cleaned_data: [],
    categories: [],

    get_colors: function(num_series){

      if (num_series == 7){
        // age groups
        return ['#547bb6', '#6e83a5', '#878b94', '#a19383', '#ba9b72', '#d4a361', '#edab50']
        // return ['#e0ecf4', '#bfd3e6', '#9ebcda', '#8c96c6', '#8c6bb1', '#88419d', '#6e016b']
      }
      if (num_series == 6){
        // income groups
        return ['#ce603b', '#cc893d', '#cab040', '#AAA646', '#74722F', '#48471E']
      }

      if (num_series == 5){
        // income groups
        return ['#ce603b', '#cc893d', '#cab040', '#AAA646', '#48471E']
      }

      if (num_series == 4){
        // building types
        return ['#8DA7CE', '#547BB6', '#375481', '#1F2F47']
        //return ['#BDD9FF', '#82AFF1', '#1769D6', '#395A88'];
      }

      if (num_series == 3){
        return ['#375481', '#8DA7CE', '#CE603B'];
      }

      if (num_series == 2){
        return ['#375481', '#8DA7CE'];
      }

      return ['#547BB6'];
    },

    prep_chart_data: function(data, primary_dimension, number_type){
      // preps a matrix-esque csv w/ labels for rows & columns
      if(primary_dimension == 'row'){
        var csv_arrays = this.transpose($.csv.toArrays(data))
      } else{
        var csv_arrays = $.csv.toArrays(data);
      }

      var series_data = []
      var col_names = csv_arrays[0].slice(1)

      // loop through rows after first row
      var series_count = 0;
      var num_series = csv_arrays.length - 1;

      $.each(csv_arrays.slice(1), function(row_id, row){
        // first element is row name, rest is data
        var row_name = row[0]
        var row_data = []
        // format numbers
        $.each(row.slice(1), function(i, val){
          if(number_type == 'count'){
            // get rid of commas, parse int
            row_data.push(parseInt(val.replace(/,/g,'')));
          } else if (number_type == 'percentage'){
            row_data.push(parseFloat(val)*100);
          } else if (number_type == 'rate'){
            row_data.push(parseFloat(val));
          } else{
            // do nothing
            row_data.push(val);
          }
        });

        series_data.push({
          name: row_name,
          data: row_data,
          color: ChartHelper.get_colors(num_series)[series_count]
        });

        series_count = series_count + 1;
      });

      return [series_data, col_names]

    },

    transpose: function(a){
      return Object.keys(a[0]).map(
        function (c) { return a.map(function (r) { return r[c]; }); }
      );
    },

    make_bar_chart: function(el, series_data, categories, chart_title, yaxis_title, plotOptions, tooltip){

      $(el).highcharts({
        chart: {
          type: 'column',
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 40
        },
        plotOptions: plotOptions,
        credits: { enabled: false },
        title: {
          text: chart_title[0]
        },
        subtitle: {
          text: chart_title[1]
        },
        xAxis: {
          categories: categories,
          tickmarkPlacement: 'on',
          title: {
              enabled: false
          }
        },
        yAxis: {
          title: {
              text: yaxis_title
          },
          endOnTick: false,
          min: 0
        },
        tooltip: tooltip,
        series: series_data
      });

    },

    make_negative_bar_chart: function(el, series_data, categories, chart_title, yaxis_title, plotOptions, tooltip){

      $(el).highcharts({
        chart: {
          type: 'column',
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 40
        },
        plotOptions: plotOptions,
        credits: { enabled: false },
        title: {
          text: chart_title[0]
        },
        subtitle: {
          text: chart_title[1]
        },
        xAxis: {
          categories: categories,
          tickmarkPlacement: 'on',
          title: {
              enabled: false
          }
        },
        yAxis: {
          title: {
              text: yaxis_title
          },
          endOnTick: false
        },
        tooltip: tooltip,
        series: series_data
      });

    },

    make_composition_chart: function(el, series_data, categories, chart_title, xaxis_title, yaxis_title){

      // flipping data so that most recent year comes first
      categories = categories.reverse()
      $.each(series_data, function(i, group_data){
        group_data['data'] = group_data['data'].reverse()
      });

      $(el).highcharts({
        chart: {
          type: 'bar',
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 40
        },
        plotOptions: {
          series: {
            stacking: 'percent',
            dataLabels: {
              enabled: true,
              format: '{y:,.1f}%',
              color: '#fff',
              style: {
                textShadow: 'none',
                opacity: .8,
                fontWeight: 'bold'
              }
            },
            states: {
              hover: {
                enabled: false
              }
            }
          }
        },
        credits: { enabled: false },
        title: {
          text: chart_title[0]
        },
        subtitle: {
          text: chart_title[1]
        },
        xAxis: {
          categories: categories,
          tickmarkPlacement: 'on',
          title: {
              enabled: false
          }
        },
        yAxis: {
          title: {
              text: yaxis_title
          },
          min: 0,
          tickInterval: 100,
          reversedStacks: false
        },
        tooltip: {
          enabled: false
        },
        legend: {
          symbolPadding: 3,
          itemDistance: 12

        },
        series: series_data
      });

    },

    make_small_bar_chart: function(el, series_data, chart_title, y_range, data_type){

      if (data_type == 'percent') {
        num_format = '{point.y:,.1f}%'
        y_labels = {
              formatter: function () {
                  return this.value + '%';
              }
            }
      } else {
        num_format = '{point.y:,.0f}'
        y_labels = {}
      }

      $(el).highcharts({
        chart: {
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 30,
          spacingBottom: 30,
          type: 'column'
        },
        plotOptions: {
          series: {
            groupPadding: 0
          }
        },
        credits: { enabled: false },
        title: {
          text: chart_title,
          style: {
                fontSize: '16px'
            }
        },
        legend: {
            enabled: false
        },
        xAxis: {
          categories: [chart_title],
          lineWidth: 0,
          tickLength: 0,
          title: {
            enabled: false
          },
          labels: {
            enabled: false
          }
        },
        yAxis: {
          title: {
              enabled: false
          },
          min: y_range[0],
          max: y_range[1],
          endOnTick: false,
          labels: y_labels
        },
        tooltip: {
          borderColor: '#eee',
          shadow: false,
          headerFormat: '',
          pointFormat: num_format,
        },
        series: series_data
      });

    },

    make_small_line_chart: function(el, series_data, categories, chart_title, y_range, data_type){

      if (data_type=='percent'){
        num_format = '{point.y:,.1f}%'
        y_labels = {
          formatter: function () {
            return this.value + '%';
          }
        }
      } else {
        num_format = '{point.y:,.0f}'
        y_labels = {}
      }

      $(el).highcharts({
        chart: {
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 15,
          spacingBottom: 30,
          type: 'area'
        },
        plotOptions: {
          area: {
            fillOpacity: 0.25
          }
        },
        credits: { enabled: false },
        title: {
          text: chart_title,
          style: {
                fontSize: '16px'
            }
        },
        legend: {
            enabled: false
        },
        xAxis: {
          categories: categories,
          lineWidth: 0,
          tickLength: 0,
          title: {
            enabled: false
          },
        },
        yAxis: {
          title: {
              enabled: false
          },
          min: y_range[0],
          max: y_range[1],
          endOnTick: false,
          labels: y_labels
        },
        tooltip: {
          borderColor: '#eee',
          shadow: false,
          headerFormat: '',
          pointFormat: num_format,
        },
        series: series_data
      });

    },

    make_small_composition_chart: function(el, series_data, categories, chart_title, data_type){

      if (data_type=='percent'){
        num_format = '{point.y:,.1f}%';
      } else {
        num_format = '{point.y:,.0f}';
      }

      $(el).highcharts({
        chart: {
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 30,
          spacingBottom: 30,
          type: 'area'
        },
        plotOptions: {
          area: {
            marker: {
              symbol: 'circle',
              radius: 2
            },
            stacking: 'percent',
            fillOpacity: 0.7
          },
          series: {
            pointPadding: 0
          }
        },
        credits: { enabled: false },
        title: {
          text: chart_title,
          style: {
                fontSize: '16px'
            }
        },
        legend: {
            enabled: false
        },
        xAxis: {
          categories: categories,
          lineWidth: 0,
          tickLength: 0,
          title: {
            enabled: false
          },
          min: 0.5,
          max: 4.5
        },
        yAxis: {
          title: {
              enabled: false
          },
          min: 0,
          max: 100,
          endOnTick: false,
          labels: {
            formatter: function () {
              return this.value + '%';
            }
          }
        },
        tooltip: {
          shared: true,
          borderColor: '#eee',
          shadow: false,
          headerFormat: '',
          pointFormat: '\u25CF {series.name}: ' + num_format + '
.'
        },
        series: series_data
      });

    },

    make_line_chart: function(el, series_data, categories, chart_title, yaxis_title, data_type){
      if (data_type == 'percent'){
        y_min = null
        y_labels = {
              formatter: function () {
                  return this.value + '%';
              }
            }
        data_labels = {
                    enabled: true,
                    format: "{point.y:.1f}%"
                }
        states = {
                hover: {
                  enabled: false
                }
              }
        tooltip = {
            enabled: false
        }
      } else {
        y_min = 0
        y_labels = {}
        data_labels = {
          enabled: false
        }
        states = {}
        tooltip = {
          borderColor: '#eee',
          shadow: false,
          headerFormat: '',
          pointFormat: '{point.y:,.0f}',
        }

      }

      $(el).highcharts({
        chart: {
          type: 'line',
          backgroundColor:"rgba(255, 255, 255, 0)",
          spacingTop: 40
        },
        credits: { enabled: false },
        title: {
            text: chart_title[0]
        },
        subtitle: {
            text: chart_title[1]
        },
        xAxis: {
            categories: categories,
            tickmarkPlacement: 'on',
            title: {
                enabled: false
            }
        },
        yAxis: {
            title: {
                text: yaxis_title
            },
            labels: y_labels,
            min: y_min
        },
        tooltip: tooltip,
        plotOptions: {
            line: {
                marker: {
                    lineWidth: 1,
                    lineColor: '#ffffff',
                    symbol: 'square'
                },
                dataLabels: data_labels
            },
            series: {
              states: states
            }
        },
        series: series_data
      });

    },

    formatAmount: function(value) {
      if (value >= 1000000000)
        return Math.round(value / 1000000000) + "B";
      else if (value >= 1000000)
        return Math.round(value / 1000000) + "M";
      else if (value >= 1000)
        return Math.round(value / 1000) + "K";
      else
        return value;
    }

}<|endoftext|>


<commit_before>import Vue from 'vue';
import Vuex from 'vuex';
import undoRedo from '../plugins/undo-redo';
import shareMutations from '../plugins/share-mutations';
import shareTimeTravel from '../plugins/share-time-travel';
import page from './modules/page';
import definition from './modules/definition';
import Config from 'classes/Config';

/* global process */

Vue.use(Vuex);

let store = new Vuex.Store({

	state: {
		over: {
			x: 0,
			y: 0
		},
		preview: {
			visible: false,
			url: ''
		},
		wrapperStyles: {},
		showIframeOverlay: false,
		errors: [],
		undoRedo: {
			canUndo: false,
			canRedo: false
		}
	},

	getters: {},

	mutations: {

		updateOver(state, position) {
			state.over = position;
		},

		changePreview(state, value) {
			state.preview = value;
		},

		updateWrapperStyle(state, { prop, value }) {
			state.wrapperStyles = { ...state.wrapperStyles, [prop]: value };
		},

		showIframeOverlay(state, yes) {
			state.showIframeOverlay = yes;
		},

		updateErrors(state, errors) {
			state.errors = errors;
		},

		updateUndoRedo(state, canUndoRedo) {
			state.undoRedo = canUndoRedo;
		}
	},

	actions: {},

	modules: {
		page,
		definition
	},

	plugins: [
		shareMutations,
		undoRedo,
		...(Config.get('debug', false) ? [shareTimeTravel] : [])
	],

	strict: process.env.NODE_ENV !== 'production'

});

export default store;
<commit_msg>Slight name change for clarity so the "showIframeOverlay" mutation and data don't share the same name.<commit_after>import Vue from 'vue';
import Vuex from 'vuex';
import undoRedo from '../plugins/undo-redo';
import shareMutations from '../plugins/share-mutations';
import shareTimeTravel from '../plugins/share-time-travel';
import page from './modules/page';
import definition from './modules/definition';
import Config from 'classes/Config';

/* global process */

Vue.use(Vuex);

let store = new Vuex.Store({

	state: {
		over: {
			x: 0,
			y: 0
		},
		preview: {
			visible: false,
			url: ''
		},
		wrapperStyles: {},
		displayIframeOverlay: false,
		errors: [],
		undoRedo: {
			canUndo: false,
			canRedo: false
		}
	},

	getters: {},

	mutations: {

		updateOver(state, position) {
			state.over = position;
		},

		changePreview(state, value) {
			state.preview = value;
		},

		updateWrapperStyle(state, { prop, value }) {
			state.wrapperStyles = { ...state.wrapperStyles, [prop]: value };
		},

		showIframeOverlay(state, show = true) {
			state.displayIframeOverlay = show;
		},

		updateErrors(state, errors) {
			state.errors = errors;
		},

		updateUndoRedo(state, canUndoRedo) {
			state.undoRedo = canUndoRedo;
		}
	},

	actions: {},

	modules: {
		page,
		definition
	},

	plugins: [
		shareMutations,
		undoRedo,
		...(Config.get('debug', false) ? [shareTimeTravel] : [])
	],

	strict: process.env.NODE_ENV !== 'production'

});

export default store;
<|endoftext|>


<commit_before>// ==UserScript==
// @name           Google personal blocklist
// @namespace      curipha
// @description    Obscure annoying sites from search result
// @include        http://www.google.tld/search?*
// @include        https://www.google.tld/search?*
// @version        0.2.3
// @grant          none
// @noframes
// ==/UserScript==

(function(){
  var block = [
    // General doorways
    'ceron.jp/', 'page2rss.com/', 'zenback.itmedia.co.jp/', 'hatebu-graph.com/',
    'b.hatena.ne.jp/entrylist/',
    '[^/]+.s.hatena.ne.jp/',

    // Application doorways
    'www.altech-ads.com/', 'www.freewarelovers.com/', 'www.appbrain.com/',
    'download.cnet.com/',
    'www.vector.co.jp/soft/',
    '([^/]+.)?filehippo.com/',
    '[^/]+.soft(onic|pedia).(com|jp)/', '[^/]+.uptodown.com/',

    // SNS doorways
    '([^/]+.)?favstar.fm/',
    '([^/]+.)?tw(eet|tr|i(?!tter))[^/.]+.(com|org|jp|cc)/', // genocide...

    // Knowledge communities
    'questionbox.jp.msn.com/', 'ziddy.japan.zdnet.com/', 'soudan1.biglobe.ne.jp/', 'qanda.rakuten.ne.jp/',
    'www.itmedia.co.jp/qa/',
    'oshiete1?.(nifty.com|goo.ne.jp)/',
    '([^/]+.)?okwave.jp/', '([^/]+.)?chiebukuro(.travel)?.yahoo.co.jp/',

    // EC
    '(e?search|item).rakuten.co.jp/',
    '([^/]+.)?.animate-onlineshop.jp/',

    // Anime leakers
    'anime.dougasouko.com/',
    '([^/]+.)?anitube.se/',
    '([^/]*(anime|youtube)[^/]*|mvnavian).blog[0-9]*.(fc2.com|fc2blog.us)/',

    // Torrents
    '([^/]+.)?nyaa.se/',

    // Dll listing
    'systemexplorer.net/', '[^/]+.dll-files.com/',

    // Mobile pages
    'www.amazon.co.jp/gp/aw/', 'mobile.twitter.com/'
  ];

  var opacity = 0.2;
  var pattern = new RegExp('^https?:\/\/(?:' + block.join('|').replace(/([.\/])/g, '\\$1') + ')', 'i');
  var googler = /^https?:\/\/www\.google\.com\/url\?/i;
  var t = 0;

  var blocker = function() {
    var result = document.getElementsByClassName('g');
    for (var li of result) {
      var a = li.querySelector('h3 > a[href]');
      if (!a) continue;

      if (googler.test(a.href)) {
        var alturi = li.querySelector('cite._Rm').textContent;
        if (typeof(alturi) !== 'string') continue;

        alturi = alturi.replace(/\s+\u203A\s+/g, '/');
        var uri = /^https?:\/\//.test(uri) ? alturi : 'http://' + alturi;
      }
      else {
        var uri = a.href;
      }

      if (pattern.test(uri)) li.style.opacity = opacity;
    }
  };
  var blocker_wrap = function() {
    if (t) return;
    ｔ = setTimeout(function() {
      blocker();
      t = 0;
    }, 120);
  };

  blocker();

  var mo = new MutationObserver(blocker_wrap);
  mo.observe(document.body, { childList: true, subtree: true });
})();
<commit_msg>Update block list<commit_after>// ==UserScript==
// @name           Google personal blocklist
// @namespace      curipha
// @description    Obscure annoying sites from search result
// @include        http://www.google.tld/search?*
// @include        https://www.google.tld/search?*
// @version        0.2.3
// @grant          none
// @noframes
// ==/UserScript==

(function(){
  var block = [
    // General doorways
    'ceron.jp/', 'page2rss.com/', 'zenback.itmedia.co.jp/', 'hatebu-graph.com/',
    'b.hatena.ne.jp/entrylist/',
    '[^/]+.s.hatena.ne.jp/',

    // Application doorways
    'www.altech-ads.com/', 'www.freewarelovers.com/', 'www.appbrain.com/',
    'download.cnet.com/',
    'www.vector.co.jp/soft/',
    '([^/]+.)?filehippo.com/',
    '[^/]+.soft(onic|pedia).(com|jp)/', '[^/]+.uptodown.com/',

    // SNS doorways
    '([^/]+.)?favstar.fm/',
    '([^/]+.)?tw(eet|tr|i(?!tter))[^/.]+.(com|org|jp|cc)/', // genocide...

    // Knowledge communities
    'questionbox.jp.msn.com/', 'ziddy.japan.zdnet.com/', 'soudan1.biglobe.ne.jp/', 'qanda.rakuten.ne.jp/',
    'www.itmedia.co.jp/qa/',
    'oshiete1?.(nifty.com|goo.ne.jp)/',
    '([^/]+.)?okwave.jp/', '([^/]+.)?chiebukuro(.travel)?.yahoo.co.jp/',

    // EC
    '(e?search|item).rakuten.co.jp/',
    '([^/]+.)?.animate-onlineshop.jp/',

    // Anime leakers
    'anime.dougasouko.com/',
    '([^/]+.)?anitube.se/',
    '([^/]*(anime|youtube)[^/]*|mvnavian).blog[0-9]*.(fc2.com|fc2blog.us)/',

    // Torrents
    '([^/]+.)?nyaa.se/',

    // Dll listing
    'systemexplorer.net/', '[^/]+.dll-files.com/',

    // Linux package listing
    'packages.(debian|ubuntu).org/',

    // Mirror
    'wpedia.goo.ne.jp/',

    // Mobile pages
    'www.amazon.co.jp/gp/aw/', 'mobile.twitter.com/'
  ];

  var opacity = 0.2;
  var pattern = new RegExp('^https?:\/\/(?:' + block.join('|').replace(/([.\/])/g, '\\$1') + ')', 'i');
  var googler = /^https?:\/\/www\.google\.com\/url\?/i;
  var t = 0;

  var blocker = function() {
    var result = document.getElementsByClassName('g');
    for (var li of result) {
      var a = li.querySelector('h3 > a[href]');
      if (!a) continue;

      if (googler.test(a.href)) {
        var alturi = li.querySelector('cite._Rm').textContent;
        if (typeof(alturi) !== 'string') continue;

        alturi = alturi.replace(/\s+\u203A\s+/g, '/');
        var uri = /^https?:\/\//.test(uri) ? alturi : 'http://' + alturi;
      }
      else {
        var uri = a.href;
      }

      if (pattern.test(uri)) li.style.opacity = opacity;
    }
  };
  var blocker_wrap = function() {
    if (t) return;
    ｔ = setTimeout(function() {
      blocker();
      t = 0;
    }, 120);
  };

  blocker();

  var mo = new MutationObserver(blocker_wrap);
  mo.observe(document.body, { childList: true, subtree: true });
})();
<|endoftext|>


<commit_before>var remixLib = require('remix-lib')
var EventManager = remixLib.EventManager
var util = remixLib.util
var executionContext = require('./execution-context')
var async = require('async')

/**
  * Record transaction as long as the user create them.
  *
  *
  */
class Recorder {
  constructor (opts = {}) {
    var self = this
    self._api = opts.api
    self.event = new EventManager()
    self.data = { _listen: true, _replay: false, journal: [], _pendingTxs: {}, _createdContracts: {}, _createdContractsReverse: {}, _usedAccounts: {}, _abis: {} }
    opts.events.executioncontext.register('contextChanged', () => {
      self.clearAll()
    })

    opts.events.udapp.register('initiatingTransaction', (timestamp, tx) => {
      var { from, to, value, data, useCall } = tx
      var record = { value, data, useCall }

      this.data._pendingTxs[timestamp] = tx

      // convert to and from to tokens
      if (this.data._listen) {
        if (!to) {
          var selectedContract = self._api.getSelectedContract()
          if (selectedContract) {
            var abi = selectedContract.contract.object.abi
            var sha3 = util.sha3_256(JSON.stringify(abi))
            record.abi = sha3
            record.contractName = selectedContract.name
            self.data._abis[sha3] = abi
          }
        } else {
          record.to = `created-contract{${this.data._createdContracts[to]}}`
        }

        self._api.getAccounts((error, accounts) => {
          if (error) return console.log(error)
          record.from = `account{${accounts.indexOf(from)}}`
          self.data._usedAccounts[record.from] = from
          self.append(timestamp, record)
        })
      }
    })

    opts.events.udapp.register('transactionExecuted', (error, from, to, data, call, txResult, timestamp) => {
      if (error) return console.log(error)
      var tx = this.data._pendingTxs[timestamp]

      var address = executionContext.isVM() ? txResult.result.createdAddress : tx.result.contractAddress
      if (!address) return // not a contract creation
      address = '0x' + address.toString('hex')
      // save back created addresses for the convertion from tokens to real adresses
      this.data._createdContracts[address] = timestamp
      this.data._createdContractsReverse[timestamp] = address
    })
  }

  /**
    * stop/start saving txs. If not listenning, is basically in replay mode
    *
    * @param {Bool} listen
    */
  setListen (listen) {
    this.data._listen = listen
    this.data._replay = !listen
  }

  /**
    * convert back from/to from tokens to real addresses
    *
    * @param {Object} record
    * @param {Object} accounts
    * @param {Object} options
    *
    */
  resolveAddress (record, accounts, options) {
    if (record.to) {
      var timestamp = /created-contract{(.*)}/g.exec(record.to)
      record.to = this.data._createdContractsReverse[timestamp[1]]
    }
    record.from = accounts[record.from]
    // @TODO: writing browser test
    return record
  }

  /**
    * save the given @arg record
    *
    * @param {Number/String} timestamp
    * @param {Object} record
    *
    */
  append (timestamp, record) {
    var self = this
    self.data.journal.push({ timestamp, record })
  }

  /**
    * basically return the records + associate values (like abis / accounts)
    *
    */
  getAll () {
    var self = this
    var records = [].concat(self.data.journal)
    return {
      accounts: self.data._usedAccounts,
      options: {
        useAccountList: true
      },
      transactions: records.sort((A, B) => {
        var stampA = A.timestamp
        var stampB = B.timestamp
        return stampA - stampB
      }),
      abis: self.data._abis
    }
  }

  /**
    * delete the seen transactions
    *
    */
  clearAll () {
    var self = this
    self.data.journal = []
    self.data._pendingTxs = {}
    self.data._createdContracts = {}
    self.data._createdContractsReverse = {}
    self.data._usedAccounts = {}
    self.data._abis = {}
  }

  /**
    * run the list of records
    *
    * @param {Object} accounts
    * @param {Object} options
    * @param {Object} abis
    * @param {Function} newContractFn
    *
    */
  run (records, accounts, options, abis, newContractFn) {
    var self = this
    self.setListen(false)
    async.eachSeries(records, function (tx, cb) {
      var record = self.resolveAddress(tx.record, accounts, options)
      self._api.udapp().rerunTx(record, function (err, txResult) {
        if (err) {
          console.error(err)
        } else {
          var address = executionContext.isVM() ? txResult.result.createdAddress : tx.result.contractAddress
          if (!address) return // not a contract creation
          address = '0x' + address.toString('hex')
          // save back created addresses for the convertion from tokens to real adresses
          self.data._createdContracts[address] = tx.timestamp
          self.data._createdContractsReverse[tx.timestamp] = address
          var abi = abis[tx.record.abi]
          if (abi) {
            newContractFn(abi, address, record.contractName)
          }
        }
        cb()
      })
    }, () => { self.setListen(true) })
  }
}

module.exports = Recorder
<commit_msg>don't save calls<commit_after>var remixLib = require('remix-lib')
var EventManager = remixLib.EventManager
var util = remixLib.util
var executionContext = require('./execution-context')
var async = require('async')

/**
  * Record transaction as long as the user create them.
  *
  *
  */
class Recorder {
  constructor (opts = {}) {
    var self = this
    self._api = opts.api
    self.event = new EventManager()
    self.data = { _listen: true, _replay: false, journal: [], _pendingTxs: {}, _createdContracts: {}, _createdContractsReverse: {}, _usedAccounts: {}, _abis: {} }
    opts.events.executioncontext.register('contextChanged', () => {
      self.clearAll()
    })

    opts.events.udapp.register('initiatingTransaction', (timestamp, tx) => {
      if (tx.useCall) return
      var { from, to, value, data } = tx
      var record = { value, data }

      this.data._pendingTxs[timestamp] = tx

      // convert to and from to tokens
      if (this.data._listen) {
        if (!to) {
          var selectedContract = self._api.getSelectedContract()
          if (selectedContract) {
            var abi = selectedContract.contract.object.abi
            var sha3 = util.sha3_256(JSON.stringify(abi))
            record.abi = sha3
            record.contractName = selectedContract.name
            self.data._abis[sha3] = abi
          }
        } else {
          record.to = `created-contract{${this.data._createdContracts[to]}}`
        }

        self._api.getAccounts((error, accounts) => {
          if (error) return console.log(error)
          record.from = `account{${accounts.indexOf(from)}}`
          self.data._usedAccounts[record.from] = from
          self.append(timestamp, record)
        })
      }
    })

    opts.events.udapp.register('transactionExecuted', (error, from, to, data, call, txResult, timestamp) => {
      if (error) return console.log(error)
      if (call) return
      var tx = this.data._pendingTxs[timestamp]

      var address = executionContext.isVM() ? txResult.result.createdAddress : tx.result.contractAddress
      if (!address) return // not a contract creation
      address = '0x' + address.toString('hex')
      // save back created addresses for the convertion from tokens to real adresses
      this.data._createdContracts[address] = timestamp
      this.data._createdContractsReverse[timestamp] = address
    })
  }

  /**
    * stop/start saving txs. If not listenning, is basically in replay mode
    *
    * @param {Bool} listen
    */
  setListen (listen) {
    this.data._listen = listen
    this.data._replay = !listen
  }

  /**
    * convert back from/to from tokens to real addresses
    *
    * @param {Object} record
    * @param {Object} accounts
    * @param {Object} options
    *
    */
  resolveAddress (record, accounts, options) {
    if (record.to) {
      var timestamp = /created-contract{(.*)}/g.exec(record.to)
      record.to = this.data._createdContractsReverse[timestamp[1]]
    }
    record.from = accounts[record.from]
    // @TODO: writing browser test
    return record
  }

  /**
    * save the given @arg record
    *
    * @param {Number/String} timestamp
    * @param {Object} record
    *
    */
  append (timestamp, record) {
    var self = this
    self.data.journal.push({ timestamp, record })
  }

  /**
    * basically return the records + associate values (like abis / accounts)
    *
    */
  getAll () {
    var self = this
    var records = [].concat(self.data.journal)
    return {
      accounts: self.data._usedAccounts,
      options: {
        useAccountList: true
      },
      transactions: records.sort((A, B) => {
        var stampA = A.timestamp
        var stampB = B.timestamp
        return stampA - stampB
      }),
      abis: self.data._abis
    }
  }

  /**
    * delete the seen transactions
    *
    */
  clearAll () {
    var self = this
    self.data.journal = []
    self.data._pendingTxs = {}
    self.data._createdContracts = {}
    self.data._createdContractsReverse = {}
    self.data._usedAccounts = {}
    self.data._abis = {}
  }

  /**
    * run the list of records
    *
    * @param {Object} accounts
    * @param {Object} options
    * @param {Object} abis
    * @param {Function} newContractFn
    *
    */
  run (records, accounts, options, abis, newContractFn) {
    var self = this
    self.setListen(false)
    async.eachSeries(records, function (tx, cb) {
      var record = self.resolveAddress(tx.record, accounts, options)
      self._api.udapp().rerunTx(record, function (err, txResult) {
        if (err) {
          console.error(err)
        } else {
          var address = executionContext.isVM() ? txResult.result.createdAddress : tx.result.contractAddress
          if (!address) return // not a contract creation
          address = '0x' + address.toString('hex')
          // save back created addresses for the convertion from tokens to real adresses
          self.data._createdContracts[address] = tx.timestamp
          self.data._createdContractsReverse[tx.timestamp] = address
          var abi = abis[tx.record.abi]
          if (abi) {
            newContractFn(abi, address, record.contractName)
          }
        }
        cb()
      })
    }, () => { self.setListen(true) })
  }
}

module.exports = Recorder
<|endoftext|>


<commit_before>/*
    R E D S H I F T
    ----------------------------------------

*/
"use strict";

var KEY = require('./opts/keys.js'),
	ActionManager = require('./bobs/actionManager.js'),
	InputManager = require('./bobs/inputManager.js'),
	Chronos = require('./bobs/chronos.js'),
	Easing = require('./utils/easingFunctions.js'),
	calc = require('./utils/calc.js'),
	utils = require('./utils/utils.js'),
	shims = require('./utils/shims.js'),
	rQuery = require('./utils/rQuery.js'),
	Redshift = function () {
    	this.init();
	},
    redshift,
    Instance = function (token) {
        this.token = token;
    };

Instance.prototype = {

	/*
    	Read or bind data to this Redshift object

    	Read
    	    @param [string]: Key of data value to read
    	    @return [any]: The data stored under that key

        Write syntax A
            @param [string]: Key of data value to write
            @param [any]: The data to store under that key

        Write syntax B
            @param [object]: Object of key/value pairs to attach to this object
	*/
	data: function () {
	    var returnValue = this,
	        arg0 = arguments[0],
	        arg0IsString = utils.isString(arg0),
	        dataToSet = {};

	    // If this is a get request
	    if (arg0IsString && !arguments[1]) {
    	    returnValue = ActionManager.getData(this.token, arg0);

	    // Else this is a set request
	    } else {
	        if (arg0IsString) {
    	        dataToSet[arg0] = arguments[1];
	        } else {
    	        dataToSet = arg0;
	        }

    	    ActionManager.setData(this.token, dataToSet);
	    }

	    return returnValue;
	},

	/*
    	Play the provided actions as animations

    	@param [string || array]: Space deliminated string or array of defined action keys in order of execution
    	@param [object]: Override action defaults with those defined here
	*/
	play: function (defs, override) {
	    return redshift.ignite(this.token, KEY.RUBIX.TIME, ActionManager.createBase(defs, override));
	},

	/*
    	Run the provided action based on property speed

    	@param [string]: Key of the action to process
    	@param [object]: Override action defaults with those defined here
	*/
	move: function (defs, override) {
	    return redshift.ignite(this.token, KEY.RUBIX.SPEED, ActionManager.createBase(defs, override));
	},

    /*
        Track pointer

    	@param [string]: Key of the action to process
        @param [event]: Initiating pointer event
    */
	track: function (defs) {
	    var hasAllArgs = (arguments[2] !== undefined),
	        toTrack = hasAllArgs ? arguments[2] : arguments[1],
	        override = hasAllArgs ? arguments[3] : {},
	        rubix = (utils.isNum(toTrack.token)) ? KEY.RUBIX.ACTION : KEY.RUBIX.POINTER;

	    return redshift.ignite(this.token, rubix, ActionManager.createBase(defs, override), toTrack);
	},

    /*
        Start specified action

        Activate the action and fire up Chronos animation loop
    */
    start: function () {
        redshift.start(this.token);
        return this;
    },

    /*
        Stop specified action
    */
    stop: function () {
        redshift.stop(this.token);
        return this;
    },

    getToken: function () {
        return this.token;
    },

    isActive: function () {
        return ActionManager.isActive(this.token);
    }

};

Redshift.prototype = {

    newAction: function () {
        return this.get();
    },

    newInput: function () {
	    return InputManager.create();
    },

    /*
        Create a Instance with the specified token
    */
    get: function (token) {
        var action = ActionManager.get(token) || ActionManager.create();

        return new Instance(action.token);
    },

    define: function (actions) {
	    ActionManager.define(actions);
	    return this;
    },

	start: function (token) {
        ActionManager.activate(token);
        Chronos.start();
	},

	stop: function (token) {
    	ActionManager.deactivate(token);
	},

	/*
    	Ignite Redshift

    	Get the specified action (or create if none), update its properties
    	and then start

        @param [object]: Properties to manipulate
        @param [object]: Options for track
        @param [event]: Initiating pointer event
        @return [int]: ID token for action
	*/
	ignite: function (token, rubix, changes, e) {
		var action = ActionManager.get(token);

		changes.rubix = rubix;

		ActionManager.change(token, changes, e);

		this.start(token);

		return token;
	},

	/*
    	Add bezier curve function

    	Add the specified bezier curve the EasingFunction's available easings
    	My favourite bezier curve generator is Lea Verou's excellent http://cubic-bezier.com/

    	@param [string]: Name of the new easing function
    	@param [number]: x coordinate of point 1
    	@param [number]: y coordinate of point 1
    	@param [number]: x coordinate of point 2
    	@param [number]: y coordinate of point 2
	*/
	addBezier: function (name, x1, y1, x2, y2) {
		Easing.addBezier(name, x1, y1, x2, y2);
	},

    Calc: calc,

	run: function () {

	},

	updatePointer: function (x, y, z) {

	},

	/*
    	Init Redshift

    	Check if we need shims and load if necessary
	*/
	init: function () {
    	shims.featureCheck();
    	rQuery.check();
	}
};

redshift = new Redshift();

window.Redshift = redshift;
module.exports = redshift;<commit_msg>passing through input rubix value<commit_after>/*
    R E D S H I F T
    ----------------------------------------

*/
"use strict";

var KEY = require('./opts/keys.js'),
	ActionManager = require('./bobs/actionManager.js'),
	InputManager = require('./bobs/inputManager.js'),
	Chronos = require('./bobs/chronos.js'),
	Easing = require('./utils/easingFunctions.js'),
	calc = require('./utils/calc.js'),
	utils = require('./utils/utils.js'),
	shims = require('./utils/shims.js'),
	rQuery = require('./utils/rQuery.js'),
	Redshift = function () {
    	this.init();
	},
    redshift,
    Instance = function (token) {
        this.token = token;
    };

Instance.prototype = {

	/*
    	Read or bind data to this Redshift object

    	Read
    	    @param [string]: Key of data value to read
    	    @return [any]: The data stored under that key

        Write syntax A
            @param [string]: Key of data value to write
            @param [any]: The data to store under that key

        Write syntax B
            @param [object]: Object of key/value pairs to attach to this object
	*/
	data: function () {
	    var returnValue = this,
	        arg0 = arguments[0],
	        arg0IsString = utils.isString(arg0),
	        dataToSet = {};

	    // If this is a get request
	    if (arg0IsString && !arguments[1]) {
    	    returnValue = ActionManager.getData(this.token, arg0);

	    // Else this is a set request
	    } else {
	        if (arg0IsString) {
    	        dataToSet[arg0] = arguments[1];
	        } else {
    	        dataToSet = arg0;
	        }

    	    ActionManager.setData(this.token, dataToSet);
	    }

	    return returnValue;
	},

	/*
    	Play the provided actions as animations

    	@param [string || array]: Space deliminated string or array of defined action keys in order of execution
    	@param [object]: Override action defaults with those defined here
	*/
	play: function (defs, override) {
	    return redshift.ignite(this.token, KEY.RUBIX.TIME, ActionManager.createBase(defs, override));
	},

	/*
    	Run the provided action based on property speed

    	@param [string]: Key of the action to process
    	@param [object]: Override action defaults with those defined here
	*/
	move: function (defs, override) {
	    return redshift.ignite(this.token, KEY.RUBIX.SPEED, ActionManager.createBase(defs, override));
	},

    /*
        Track pointer

    	@param [string]: Key of the action to process
        @param [event]: Initiating pointer event
    */
	track: function (defs) {
	    var hasAllArgs = (arguments[2] !== undefined),
	        toTrack = hasAllArgs ? arguments[2] : arguments[1],
	        override = hasAllArgs ? arguments[3] : {};

	    return redshift.ignite(this.token, KEY.RUBIX.INPUT, ActionManager.createBase(defs, override), toTrack);
	},

    /*
        Start specified action

        Activate the action and fire up Chronos animation loop
    */
    start: function () {
        redshift.start(this.token);
        return this;
    },

    /*
        Stop specified action
    */
    stop: function () {
        redshift.stop(this.token);
        return this;
    },

    getToken: function () {
        return this.token;
    },

    isActive: function () {
        return ActionManager.isActive(this.token);
    }

};

Redshift.prototype = {

    newAction: function () {
        return this.get();
    },

    newInput: function () {
	    return InputManager.create();
    },

    /*
        Create a Instance with the specified token
    */
    get: function (token) {
        var action = ActionManager.get(token) || ActionManager.create();

        return new Instance(action.token);
    },

    define: function (actions) {
	    ActionManager.define(actions);
	    return this;
    },

	start: function (token) {
        ActionManager.activate(token);
        Chronos.start();
	},

	stop: function (token) {
    	ActionManager.deactivate(token);
	},

	/*
    	Ignite Redshift

    	Get the specified action (or create if none), update its properties
    	and then start

        @param [object]: Properties to manipulate
        @param [object]: Options for track
        @param [event]: Initiating pointer event
        @return [int]: ID token for action
	*/
	ignite: function (token, rubix, changes, e) {
		var action = ActionManager.get(token);

		changes.rubix = rubix;

		ActionManager.change(token, changes, e);

		this.start(token);

		return token;
	},

	/*
    	Add bezier curve function

    	Add the specified bezier curve the EasingFunction's available easings
    	My favourite bezier curve generator is Lea Verou's excellent http://cubic-bezier.com/

    	@param [string]: Name of the new easing function
    	@param [number]: x coordinate of point 1
    	@param [number]: y coordinate of point 1
    	@param [number]: x coordinate of point 2
    	@param [number]: y coordinate of point 2
	*/
	addBezier: function (name, x1, y1, x2, y2) {
		Easing.addBezier(name, x1, y1, x2, y2);
	},

    Calc: calc,

	run: function () {

	},

	updatePointer: function (x, y, z) {

	},

	/*
    	Init Redshift

    	Check if we need shims and load if necessary
	*/
	init: function () {
    	shims.featureCheck();
    	rQuery.check();
	}
};

redshift = new Redshift();

window.Redshift = redshift;
module.exports = redshift;<|endoftext|>


<commit_before>'use strict';

import store from './store';
import PouchDB from 'pouchdb';
import { receiveConfig } from './actions/config';
import { receiveDoc } from './actions/docs';

export const regex = /[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3})?Z/;

// then replicate this to a pouch instance
// then use the pouch instance to keep couchdb clean
let remote = new PouchDB('http://localhost:5984/work');
let db = new PouchDB('work_test');
remote.replicate.to(db);

export function format(doc) {
  return Object.assign({}, {
    date: new Date(doc._id),
    ticket: '',
    product: '',
    company: '',
    desc: '',
    type: '',
    lang: []
  }, doc);
}

remote.changes({
  live: true,
  include_docs: true, // eslint-disable-line camelcase
  since: 'now'
}).on('change', callback)
  .on('error', console.log.bind(console));

function callback(change) {
  // change.id contains the id
  // change.doc contains the doc (assuming include_docs: true)

  if (regex.test(change.id)) {
    store.dispatch(receiveDoc(change));
  } else {
    store.dispatch(receiveConfig(change.doc));
  }
}

export default db;
<commit_msg>reworked the db API functions<commit_after>'use strict';

import store from './store';
import PouchDB from 'pouchdb';
import { receiveConfig } from './actions/config';
import { receiveDoc } from './actions/docs';

export const regex = /[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3})?Z/;

let db = new PouchDB('http://localhost:5984/work_test');

export function format(doc) {
  return Object.assign({}, {
    date: new Date(doc._id),
    ticket: '',
    product: '',
    company: '',
    desc: '',
    type: '',
    lang: []
  }, doc);
}

db.changes({
  live: true,
  include_docs: true, // eslint-disable-line camelcase
  since: 'now'
}).on('change', callback)
  .on('error', console.log.bind(console));

function callback(change) {
  // change.id contains the id
  // change.doc contains the doc (assuming include_docs: true)

  if (regex.test(change.id)) {
    store.dispatch(receiveDoc(change));
  } else {
    store.dispatch(receiveConfig(change.doc));
  }
}

export default {
  get: (id) => db.get(id).catch(err => {
    throw err;
  }),
  put: (doc) => db.put(doc).then(r => {
    return {
      ...doc, _rev: r.rev
    };
  }),
  allDocs: (args) => db.allDocs({...args, include_docs: true}) // eslint-disable-line camelcase
    .then(result => result.rows || [])
};
<|endoftext|>


<commit_before>import * as THREE from 'three';
import Terrain from './terrain';

var scene, camera, renderer;

const init = function() {
  let width = window.innerWidth;
  let height = window.innerHeight;

  scene = new THREE.Scene();

  camera = new THREE.OrthographicCamera(width / - 2, width / 2, height / 2, height / - 2, 0.1, 1000);
  camera.position.set(200, 200, 200);
  camera.lookAt(scene.position);

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(width, height);

  let ambientLight = new THREE.AmbientLight(0x999999);
  scene.add(ambientLight);

  let directionalLight = new THREE.DirectionalLight(0x777777);
  directionalLight.position.set(3, 7, 6);
  directionalLight.position.normalize();
  scene.add(directionalLight);

  document.body.appendChild(renderer.domElement);
};

const render = function() {
  renderer.render(scene, camera);
};

const setBackgroundColor = function(color) {
  scene.background = new THREE.Color(color);
};

/**
 * Expose functionality
 */
export default {
  render,
  init,
  setBackgroundColor
};
<commit_msg>Render some random terrain to the view<commit_after>import * as THREE from 'three';
import Terrain from './terrain';

var scene, camera, renderer;

const init = function() {
  let width = window.innerWidth;
  let height = window.innerHeight;

  scene = new THREE.Scene();

  camera = new THREE.OrthographicCamera(width / - 2, width / 2, height / 2, height / - 2, 0.1, 1000);
  camera.position.set(200, 300, 200);
  camera.lookAt(scene.position);

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(width, height);

  // Create some random terrain
  const maxX = 100;
  const maxY = 100;
  let heightMap = Terrain.generate(maxX, maxY);
  heightMap[1][1] = 0.2;

  let geometry = new THREE.PlaneGeometry(2500, 2500, maxX-1, maxY-1);
  geometry.rotateX(-Math.PI / 2);

  let vertices = geometry.vertices;
  for (let x = 0; x < maxX; x++) {
    for (let y = 0; y < maxY; y++) {
      vertices[x + y * maxY].y = heightMap[x][y]*30;
    }
  }
  geometry.computeFlatVertexNormals();
  // geometry.computeVertexNormals();

  let material = new THREE.MeshLambertMaterial({ color: 0xdd8888, shading: THREE.SmoothShading });
  let mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  let ambientLight = new THREE.AmbientLight(0x999999);
  scene.add(ambientLight);

  let directionalLight = new THREE.DirectionalLight(0x777777);
  directionalLight.position.set(3, 7, 6);
  directionalLight.position.normalize();
  scene.add(directionalLight);

  document.body.appendChild(renderer.domElement);
};

const render = function() {
  renderer.render(scene, camera);
};

const setBackgroundColor = function(color) {
  scene.background = new THREE.Color(color);
};

/**
 * Expose functionality
 */
export default {
  render,
  init,
  setBackgroundColor
};
<|endoftext|>


<commit_before>'use strict'

const util = require('./util')
const cidForHash = require('./common').cidForHash

exports = module.exports

exports.multicodec = 'eth-block'

/*
 * resolve: receives a path and a block and returns the value on path,
 * throw if not possible. `block` is an IPFS Block instance (contains data + key)
 */
exports.resolve = (block, path) => {
  let node = util.deserialize(block.data)

  // root

  if (!path || path === '/') {
    return { value: node, remainderPath: '' }
  }

  // check tree results

  let pathParts = path.split('/')
  let firstPart = pathParts.unshift()
  let remainderPath = pathParts.join('/')

  let lookupResult = exports.tree(block).find(key => key === firstPart)

  if (!lookupResult) {
    throw new Error('Path not found.')
  }

  return {
    value: lookupResult,
    remainderPath: remainderPath,
  }

}

/*
 * tree: returns a flattened array with paths: values of the project. options
 * are option (i.e. nestness)
 */

exports.tree = (block, options) => {
  if (!options) {
    options = {}
  }

  const blockHeader = util.deserialize(block.data)
  const paths = []

  // external links
  paths.push({
    path: 'parent',
    value: { '/': cidForHash('eth-block', blockHeader.parentHash) },
  })
  paths.push({
    path: 'uncles',
    value: { '/': cidForHash('eth-block-list', blockHeader.uncleHash) },
  })
  paths.push({
    path: 'transactions',
    value: { '/': cidForHash('eth-tx-trie', blockHeader.transactionsTrie) },
  })
  paths.push({
    path: 'transactionReceipts',
    value: { '/': cidForHash('eth-tx-receipt-trie', blockHeader.receiptTrie) },
  })
  paths.push({
    path: 'state',
    value: { '/': cidForHash('eth-state-trie', blockHeader.stateRoot) },
  })

  // external links as data
  paths.push({
    path: 'parentHash',
    value: blockHeader.parentHash,
  })
  paths.push({
    path: 'uncleHash',
    value: blockHeader.uncleHash,
  })
  paths.push({
    path: 'transactionTrieRoot',
    value: blockHeader.transactionsTrie,
  })
  paths.push({
    path: 'transactionReceiptTrieRoot',
    value: blockHeader.receiptTrie,
  })
  paths.push({
    path: 'stateRoot',
    value: blockHeader.stateRoot,
  })

  // internal data
  paths.push({
    path: 'authorAddress',
    value: blockHeader.coinbase,
  })
  paths.push({
    path: 'bloom',
    value: blockHeader.bloom,
  })
  paths.push({
    path: 'difficulty',
    value: blockHeader.difficulty,
  })
  paths.push({
    path: 'number',
    value: blockHeader.number,
  })
  paths.push({
    path: 'gasLimit',
    value: blockHeader.gasLimit,
  })
  paths.push({
    path: 'gasUsed',
    value: blockHeader.gasUsed,
  })
  paths.push({
    path: 'timestamp',
    value: blockHeader.timestamp,
  })
  paths.push({
    path: 'extraData',
    value: blockHeader.extraData,
  })
  paths.push({
    path: 'mixHash',
    value: blockHeader.mixHash,
  })
  paths.push({
    path: 'nonce',
    value: blockHeader.nonce,
  })

  return paths

}<commit_msg>use asexual terminology<commit_after>'use strict'

const util = require('./util')
const cidForHash = require('./common').cidForHash

exports = module.exports

exports.multicodec = 'eth-block'

/*
 * resolve: receives a path and a block and returns the value on path,
 * throw if not possible. `block` is an IPFS Block instance (contains data + key)
 */
exports.resolve = (block, path) => {
  let node = util.deserialize(block.data)

  // root

  if (!path || path === '/') {
    return { value: node, remainderPath: '' }
  }

  // check tree results

  let pathParts = path.split('/')
  let firstPart = pathParts.unshift()
  let remainderPath = pathParts.join('/')

  let lookupResult = exports.tree(block).find(key => key === firstPart)

  if (!lookupResult) {
    throw new Error('Path not found.')
  }

  return {
    value: lookupResult,
    remainderPath: remainderPath,
  }

}

/*
 * tree: returns a flattened array with paths: values of the project. options
 * are option (i.e. nestness)
 */

exports.tree = (block, options) => {
  if (!options) {
    options = {}
  }

  const blockHeader = util.deserialize(block.data)
  const paths = []

  // external links
  paths.push({
    path: 'parent',
    value: { '/': cidForHash('eth-block', blockHeader.parentHash) },
  })
  paths.push({
    path: 'ommers',
    value: { '/': cidForHash('eth-block-list', blockHeader.uncleHash) },
  })
  paths.push({
    path: 'transactions',
    value: { '/': cidForHash('eth-tx-trie', blockHeader.transactionsTrie) },
  })
  paths.push({
    path: 'transactionReceipts',
    value: { '/': cidForHash('eth-tx-receipt-trie', blockHeader.receiptTrie) },
  })
  paths.push({
    path: 'state',
    value: { '/': cidForHash('eth-state-trie', blockHeader.stateRoot) },
  })

  // external links as data
  paths.push({
    path: 'parentHash',
    value: blockHeader.parentHash,
  })
  paths.push({
    path: 'ommerHash',
    value: blockHeader.uncleHash,
  })
  paths.push({
    path: 'transactionTrieRoot',
    value: blockHeader.transactionsTrie,
  })
  paths.push({
    path: 'transactionReceiptTrieRoot',
    value: blockHeader.receiptTrie,
  })
  paths.push({
    path: 'stateRoot',
    value: blockHeader.stateRoot,
  })

  // internal data
  paths.push({
    path: 'authorAddress',
    value: blockHeader.coinbase,
  })
  paths.push({
    path: 'bloom',
    value: blockHeader.bloom,
  })
  paths.push({
    path: 'difficulty',
    value: blockHeader.difficulty,
  })
  paths.push({
    path: 'number',
    value: blockHeader.number,
  })
  paths.push({
    path: 'gasLimit',
    value: blockHeader.gasLimit,
  })
  paths.push({
    path: 'gasUsed',
    value: blockHeader.gasUsed,
  })
  paths.push({
    path: 'timestamp',
    value: blockHeader.timestamp,
  })
  paths.push({
    path: 'extraData',
    value: blockHeader.extraData,
  })
  paths.push({
    path: 'mixHash',
    value: blockHeader.mixHash,
  })
  paths.push({
    path: 'nonce',
    value: blockHeader.nonce,
  })

  return paths

}<|endoftext|>


<commit_before>import _ from "lodash"
import path from "path"
// import sql from "sql-bricks-postgres"
import {db} from "bardo"
import route from "./route"
import validate from "./validate"

export function mount(path) {
  function decorator(path, cls) {
    cls.mount(path)
    return cls
  }

  if (_.isString(path)) {
    return decorator.bind(undefined, path)
  }

  return decorator("/", path)
}

// TODO: Split up `Resource` and `ModelResource`
export class Resource {
  static mount(base="/") {
    // Dasherize the name of this class
    let name = _.kebabCase(_.camelCase(this.name, true))
    let url = path.join(base, name)

    // NOTE: It'd be nice if resitfy supported a way to bind a handler to
    //       all methods
    let dispatch = this.dispatch.bind(this)
    let methods = ["head", "get", "post", "put", "patch", "del"]
    for (let method of methods) {
      route[method](url, dispatch)
      route[method](path.join(url, ":id"), dispatch)
    }

    // Collect `before` and `after` methods
    // NOTE: It'd be nice if there was to do metaclass-style initialization
    this._before = []
    this._after = []

    // Add the local `after` first
    if (this.prototype.after != null) {
      this._after.push(this.prototype.after)
    }

    // TODO: Collect `before` and `after` from mixins
    for (let mix of (this.mixins || [])) {
      if (mix.prototype != null) {
        mix = mix.prototype
      }

      if (mix.before != null) {
        this._before.push(mix.before)
      }

      if (mix.after != null) {
        this._after.push(mix.after)
      }
    }

    // Add the local `before` last
    if (this.prototype.before != null) {
      this._before.push(this.prototype.before)
    }
  }

  static dispatch(req, res, next) {
    let resource = new this()

    // Determine an appropriate handler method
    let handler = resource[req.method.toLowerCase()]
    if (handler == null) {
      // No handler found: Method not allowed
      // TODO: Should return allowed methods
      res.send(405)
      return next(false)
    }

    let cls = this
    let beforeIndex = 0
    let afterIndex = 0
    let routed = false
    let cleanup = false

    function finalize() {
      process.nextTick(function() {
        next()
      })
    }

    let nextFn = req.domain.bind((function(err) {
      let method = null

      // Determine what method to call next
      if (err === false) {
        // `next(false)` should stop the handler chain
        method = finalize
        cleanup = false
      } else if (beforeIndex < cls._before.length) {
        method = cls._before[beforeIndex]
        beforeIndex += 1
      } else if (!routed) {
        method = handler
        routed = true
      } else if (afterIndex < cls._after.length) {
        method = cls._after[afterIndex]
        afterIndex += 1
      } else if (!cleanup) {
        method = finalize
        cleanup = false
      }

      // Bind the method to the request domain
      method = req.domain.bind(method)

      // Call the method
      Promise.resolve(method.call(this, req, res, nextFn)).catch(function(err) {
        // Raise the error upwards (if this was an async method)
        throw err
      })
    }).bind(resource))
    nextFn()
  }

  constructor() {
    // NOTE: Does nothing (for the moment)
  }

  prepare(req, row) {
    // NOTE: If only one parameter is passed; assume it to be `row`
    if (row == null) row = req

    // NOTE: Could be overridden by a derived class
    return row
  }

  clean(req, item) {
    // NOTE: If only one parameter is passed; assume it to be `item`
    if (item == null) item = req

    // NOTE: Could be overridden by a derived class
    return item
  }

  validate(item, schema=null) {
    // Use the schema provided on the instance if one is not provided
    schema = schema != null ? schema : (this.schema || this.constructor.schema)
    return validate(item, schema)
  }
}

export default {
  Resource,
  mount
}
<commit_msg>:bug:<commit_after>import _ from "lodash"
import path from "path"
// import sql from "sql-bricks-postgres"
import {db} from "bardo"
import route from "./route"
import validate from "./validate"

export function mount(path) {
  function decorator(path, cls) {
    cls.mount(path)
    return cls
  }

  if (_.isString(path)) {
    return decorator.bind(undefined, path)
  }

  return decorator("/", path)
}

// TODO: Split up `Resource` and `ModelResource`
export class Resource {
  static mount(base="/") {
    // Dasherize the name of this class
    let name = _.kebabCase(_.camelCase(this.name, true))
    let url = path.join(base, name)

    // NOTE: It'd be nice if resitfy supported a way to bind a handler to
    //       all methods
    let dispatch = this.dispatch.bind(this)
    let methods = ["head", "get", "post", "put", "patch", "del"]
    for (let method of methods) {
      route[method](url, dispatch)
      route[method](path.join(url, ":id"), dispatch)
    }

    // Collect `before` and `after` methods
    // NOTE: It'd be nice if there was to do metaclass-style initialization
    this._before = []
    this._after = []

    // Add the local `after` first
    if (this.prototype.after != null) {
      this._after.push(this.prototype.after)
    }

    // TODO: Collect `before` and `after` from mixins
    for (let mix of (this.mixins || [])) {
      if (mix.prototype != null) {
        mix = mix.prototype
      }

      if (mix.before != null) {
        this._before.push(mix.before)
      }

      if (mix.after != null) {
        this._after.push(mix.after)
      }
    }

    // Add the local `before` last
    if (this.prototype.before != null) {
      this._before.push(this.prototype.before)
    }
  }

  static dispatch(req, res, next) {
    let resource = new this()

    // Determine an appropriate handler method
    let handler = resource[req.method.toLowerCase()]
    if (handler == null) {
      // No handler found: Method not allowed
      // TODO: Should return allowed methods
      res.send(405)
      return next(false)
    }

    let cls = this
    let beforeIndex = 0
    let afterIndex = 0
    let routed = false
    let cleanup = false

    function finalize() {
      process.nextTick(function() {
        next()
      })
    }

    let nextFn = req.domain.bind((function(err) {
      let method = null

      // Determine what method to call next
      if (err === false) {
        // `next(false)` should stop the handler chain
        method = finalize
        cleanup = false
      } else if (beforeIndex < cls._before.length) {
        method = cls._before[beforeIndex]
        beforeIndex += 1
      } else if (!routed) {
        method = handler
        routed = true
      } else if (afterIndex < cls._after.length) {
        method = cls._after[afterIndex]
        afterIndex += 1
      } else if (!cleanup) {
        method = finalize
        cleanup = false
      }

      // Bind the method to the request domain
      method = req.domain.bind(method)

      // Call the method
      return Promise.resolve(method.call(this, req, res, nextFn)).catch(function(err) {
        // Raise the error upwards (if this was an async method)
        throw err
      })
    }).bind(resource))
    nextFn()
  }

  constructor() {
    // NOTE: Does nothing (for the moment)
  }

  prepare(req, row) {
    // NOTE: If only one parameter is passed; assume it to be `row`
    if (row == null) row = req

    // NOTE: Could be overridden by a derived class
    return row
  }

  clean(req, item) {
    // NOTE: If only one parameter is passed; assume it to be `item`
    if (item == null) item = req

    // NOTE: Could be overridden by a derived class
    return item
  }

  validate(item, schema=null) {
    // Use the schema provided on the instance if one is not provided
    schema = schema != null ? schema : (this.schema || this.constructor.schema)
    return validate(item, schema)
  }
}

export default {
  Resource,
  mount
}
<|endoftext|>


<commit_before>dojo.provide("dijit.Toaster");

dojo.require("dojo.fx");

dojo.require("dijit.base.Widget");
dojo.require("dijit.base.TemplatedWidget");
dojo.require("dijit.util.BackgroundIframe");
dojo.require("dijit.util.place");

// This is mostly taken from Jesse Kuhnert's MessageNotifier.
// Modified by Bryan Forbes to support topics and a variable delay.
// Modified by Karl Tiedt to support 0 duration messages that require user interaction and message stacking

dojo.declare(
	"dijit.Toaster",
	[dijit.base.Widget, dijit.base.TemplatedWidget],
	null,
	{
		// summary
		//		Message that slides in from the corner of the screen, used for notifications
		//		like "new email".
		templateString: '

',

		// messageTopic: String
		//		Name of topic; anything published to this topic will be displayed as a message.
		//		Message format is either String or an object like
		//		{message: "hello word", type: "error", duration: 500}
		messageTopic: "",

		// messageTypes: Enumeration
		//		Possible message types.
		messageTypes: {
			MESSAGE: "message",
			WARNING: "warning",
			ERROR: "error",
			FATAL: "fatal"
		},

		// defaultType: String
		//		If message type isn't specified (see "messageTopic" parameter),
		//		then display message as this type.
		//		Possible values in messageTypes enumeration ("message", "warning", "error", "fatal")
		defaultType: "message",

		// positionDirection: String
		//		Position from which message slides into screen, one of
		//		["br-up", "br-left", "bl-up", "bl-right", "tr-down", "tr-left", "tl-down", "tl-right"]
		positionDirection: "br-up",

		// positionDirectionTypes: Array
		//		Possible values for positionDirection parameter
		positionDirectionTypes: ["br-up", "br-left", "bl-up", "bl-right", "tr-down", "tr-left", "tl-down", "tl-right"],

		// duration: Integer
		//		Number of milliseconds to show message
		duration: "2000",

		//separator: String
		//		String used to separate messages if consecutive calls are made to setContent before previous messages go away
		separator: "

",

		postCreate: function(){
			dijit.Toaster.superclass.postCreate.apply(this);
			this.hide();

			this.clipNode.className = "dojoToasterClip";
			this.containerNode.className += " dojoToasterContainer";
			this.contentNode.className = "dojoToasterContent";
			if(this.messageTopic){
				dojo.subscribe(this.messageTopic, this, "_handleMessage");
			}
		},

		_handleMessage: function(/*String|Object*/message){
			if(dojo.isString(message)){
				this.setContent(message);
			}else{
				this.setContent(message.message, message.type, message.duration);
			}
		},

		setContent: function(/*String*/message, /*String*/messageType, /*int?*/duration){
			// summary
			//		sets and displays the given message and show duration
			// message:
			//		the message
			// messageType:
			//		type of message; possible values in messageTypes enumeration ("message", "warning", "error", "fatal")
			// duration:
			//		duration in milliseconds to display message before removing it. Widget has default value.
			duration = duration||this.duration;
			// sync animations so there are no ghosted fades and such
			if(this.slideAnim){
				if(this.slideAnim.status() != "playing"){
					this.slideAnim.stop();
				}
				if(this.slideAnim.status() == "playing" || (this.fadeAnim && this.fadeAnim.status() == "playing")){
					setTimeout(dojo.hitch(this, function(){
						this.setContent(message, messageType);
					}), 50);
					return;
				}
			}

			var capitalize = function(word){
				return word.substring(0,1).toUpperCase() + word.substring(1);
			};

			// determine type of content and apply appropriately
			for(var type in this.messageTypes){
				this._removeClass(this.containerNode, "dojoToaster" + capitalize(this.messageTypes[type]));
			}

			dojo.style(this.containerNode, "opacity", 1);

			if(message && this.isVisible){
				message = this.contentNode.innerHTML + this.separator + message;
			}
			this.contentNode.innerHTML = message;

			this._addClass(this.containerNode, "dojoToaster" + capitalize(messageType || this.defaultType));

			// now do funky animation of widget appearing from
			// bottom right of page and up
			this.show();
			var nodeSize = dojo.marginBox(this.containerNode);

			if(this.isVisible){
				this._placeClip();
			}else{
				var style = this.containerNode.style;
				var pd = this.positionDirection;
				// sets up initial position of container node and slide-out direction
				if(pd.indexOf("-up") >= 0){
					style.left=0+"px";
					style.top=nodeSize.h + 10 + "px";
				}else if(pd.indexOf("-left") >= 0){
					style.left=nodeSize.w + 10 +"px";
					style.top=0+"px";
				}else if(pd.indexOf("-right") >= 0){
					style.left = 0 - nodeSize.w - 10 + "px";
					style.top = 0+"px";
				}else if(pd.indexOf("-down") >= 0){
					style.left = 0+"px";
					style.top = 0 - nodeSize.h - 10 + "px";
				}else{
					throw new Error(this.id + ".positionDirection is an invalid value: " + pd);
				}

				this.slideAnim = dojo.fx.slideTo({
					node: this.containerNode,
					top: 0, left: 0,
					duration: 450});
				dojo.connect(this.slideAnim, "onEnd", this, function(nodes, anim){
						//we build the fadeAnim here so we dont have to duplicate it later
						// can't do a fadeHide because we're fading the
						// inner node rather than the clipping node
						this.fadeAnim = dojo.fadeOut({
							node: this.containerNode,
							duration: 1000});
						dojo.connect(this.fadeAnim, "onEnd", this, function(evt){
								this.isVisible = false;
								this.hide();
							});
						//if duration == 0 we keep the message displayed until clicked
						//TODO: fix so that if a duration > 0 is displayed when a duration==0 is appended to it, the fadeOut is canceled
						if(duration>0){
							setTimeout(dojo.hitch(this, function(evt){
								// we must hide the iframe in order to fade
								// TODO: figure out how to fade with a BackgroundIframe
								if(this.bgIframe){
									this.bgIframe.hide();
								}
								this.fadeAnim.play();
							}), duration);
						}else{
							dojo.connect(
								this,
								'onSelect',
								this,
								function(evt){
									this.fadeAnim.play();
								});
						}
						this.isVisible = true;
					});
				this.slideAnim.play();
			}
		},

		_placeClip: function(){
			var scroll = dijit.util.getScroll();
			var view = dijit.util.getViewport();

			var nodeSize = dojo.marginBox(this.containerNode);

			var style = this.clipNode.style;
			// sets up the size of the clipping node
			style.height = nodeSize.h+"px";
			style.width = nodeSize.w+"px";

			// sets up the position of the clipping node
			var pd = this.positionDirection;
			if(pd.match(/^t/)){
				style.top = scroll.top+"px";
			}else if(pd.match(/^b/)){
				style.top = (view.h - nodeSize.h - 2 + scroll.top)+"px";
			}
			if(pd.match(/^[tb]r-/)){
				style.left = (view.w - nodeSize.w - 1 - scroll.left)+"px";
			}else if(pd.match(/^[tb]l-/)){
				style.left = 0 + "px";
			}

			style.clip = "rect(0px, " + nodeSize.w + "px, " + nodeSize.h + "px, 0px)";
			if(dojo.isIE){
				if(!this.bgIframe){
					this.bgIframe = new dijit.util.BackgroundIframe(this.clipNode);
					this.bgIframe.setZIndex(this.clipNode);
				}
				this.bgIframe.onResized();
				this.bgIframe.show();
			}
		},

		onSelect: function(/*Event*/e){
			// summary: callback for when user clicks the message
		},

		show: function(){
			// summary: show the Toaster
			dojo.style(this.containerNode, 'display', '');

			this._placeClip();

			if(!this._scrollConnected){
				this._scrollConnected = true;
				this._scrollHandle = dojo.connect(window, "onscroll", this, this._placeClip);
			}
		},

		hide: function(){
			// summary: hide the Toaster

			//Q: ALP: I didn't port all the toggler stuff from d.w.HtmlWidget.  Is it needed? Ditto for show.
			dojo.style(this.containerNode, 'display', 'none');

			if(this._scrollConnected){
				this._scrollConnected = false;
				dojo.disconnect(window, "onscroll", this._scrollHandle);
			}

			dojo.style(this.containerNode, "opacity", 1);
		}
	}
);
<commit_msg>Refs #2824<commit_after><|endoftext|>