<commit_before>define(['d3'],
    function (d3) {
      return function () {
        var width = 300,
            height = 300;

        function heatmap_axes(selection) {
          selection.each(function (matrix, i) {
            var columns = matrix.columns.slice(1); // Skip ID column

            var x_scale = d3.scaleOrdinal(
                d3.range(columns.length)
                    .map(function (i) {
                      return i * width / columns.length
                    })
            ).domain(columns);

            var labels = d3.select(this).append("svg")
                .attr("width", width)
                .attr("height", 50)
                .append("g")
                .attr("transform", "translate(0,50)");

            labels.append("g")
                .call(d3.axisTop().scale(x_scale))
                .attr('text-anchor', 'end');

            labels.selectAll('text').style('transform', 'rotate(90deg)');
            labels.selectAll('line').remove();
            labels.selectAll('path').remove();
          });
        }

        function heatmap_body(selection) {
          selection.each(function (matrix, i) {
            var dx = matrix.columns.length - 1,
                dy = matrix.length;

            var canvas_pixel_width = dx;
            var canvas_pixel_height = d3.min([height, dy]);

            d3.select(this).append("canvas")
                .attr("width", canvas_pixel_width)
                .attr("height", canvas_pixel_height)
                .style("width", width + "px")
                .style("height", height + "px")
                .style("image-rendering",
                    (window.navigator.userAgent && window.navigator.userAgent.match('WebKit'))
                        ? "pixelated" : "-moz-crisp-edges") // TODO: works for my particular browser set
                .call(draw_heatmap);

            function draw_heatmap(canvas) {
              var context = canvas.node().getContext("2d"),
                  image = context.createImageData(dx, height);
              // One canvas pixel for data horizontally,
              // but combine data rows into a single canvas pixel row.

              var data_rows_per_pixel_row = dy / height;
              //console.log('data rows / pixel row', data_rows_per_pixel_row);

              var color = d3.scaleLinear()
                  .domain([-20, 0, 20]) // TODO: Set from data
                  .range(['blue', 'white', 'red']);

              for (var y = 0, p = -1; y < canvas_pixel_height; ++y) {
                for (var x = 1; x <= dx; ++x) { // 0-column is row ID
                  var mean = d3.mean(d3.range(data_rows_per_pixel_row).map(
                      function (i) {
                        return matrix[y + i][matrix.columns[x]];
                        // TODO: If data_rows_per_pixel_row is not an integer, rows may be double counted
                        // --> Use histogram machinery.
                      }
                  ));
                  var c = d3.rgb(color(mean));
                  image.data[++p] = c.r;
                  image.data[++p] = c.g;
                  image.data[++p] = c.b;
                  image.data[++p] = 255;
                }
              }

              context.putImageData(image, 0, 0);
            }
          });
        }

        function scatterplot_scales(matrix) {
          // TODO: only run this once
          // column-0 is ID
          var x_axis_column = matrix.columns[1];
          var y_axis_column = matrix.columns[2];

          var x_extent = d3.extent(matrix, function (row) {
            return +row[x_axis_column]
          });
          var y_extent = d3.extent(matrix, function (row) {
            return +row[y_axis_column]
          });

          var x_scale = d3.scaleLinear()
              .domain(x_extent).nice()
              .range([0, width]);
          var y_scale = d3.scaleLinear()
              .domain(y_extent).nice()
              .range([height, 0]);
          return {
            x: x_scale,
            y: y_scale,
            x_column: x_axis_column,
            y_column: y_axis_column
          }
        }

        function scatterplot_axes(selection) {
          selection.each(function (matrix, i) {
            var scales = scatterplot_scales(matrix);

            var x_axis = d3.axisBottom().scale(scales.x);
            var y_axis = d3.axisLeft().scale(scales.y);

            var svg_axes = d3.select(this).append("svg")
                .attr("width", width + 50)
                .attr("height", height + 50)
                .style("position", "absolute")
                .append("g")
                .attr("transform", "translate(30,10)");
            svg_axes.append("g")
                .attr("transform", "translate(0," + height + ")")
                .call(x_axis);
            svg_axes.append("g")
                .call(y_axis);
          });
        }

        function scatterplot_body(selection) {
          selection.each(function (matrix, i) {
            var scales = scatterplot_scales(matrix);
            d3.select(this).append("canvas")
                .attr("width", width)
                .attr("height", height)
                .style("position", "relative")
                .style("left", "30px")
                .style("top", "10px")
                .style("width", width + "px")
                .style("height", height + "px")
                .style("image-rendering", "-moz-crisp-edges")
                .call(draw_scatterplot);

            function draw_scatterplot(canvas) {
              var context = canvas.node().getContext("2d");
              context.fillStyle = "rgba(0,0,0,1)";
              matrix.forEach(function (row) {
                var x = scales.x(+row[scales.x_column]);
                var y = scales.y(+row[scales.y_column]);
                context.fillRect(x, y, 1, 1);
              })
            }
          });
        }

        function chart(selection) {
          selection.each(function (matrix, i) {
            d3.select(this).append("div")
                .style("width", width + 'px')
                .style("float", "left")
                .call(heatmap_axes)
                .call(heatmap_body);
            d3.select(this).append("div")
                .style("width", width + 'px')
                .style("float", "left")
                .call(scatterplot_axes)
                .call(scatterplot_body);
          });
        }

        return chart;
      };
    }
);

<commit_msg>Tidy up alignments<commit_after>define(['d3'],
    function (d3) {
      return function () {
        var chart_width = 300,
            chart_height = 300,
            gutter_width = 50,
            header_height = 50;

        function crisp() {
          // TODO: browser sniffing is bad, but this works for my particular browser set
          if (window.navigator.userAgent && window.navigator.userAgent.match('WebKit')) {
            return "pixelated"
          } else {
            return "-moz-crisp-edges"
          }
        }

        function heatmap_axes(selection) {
          selection.each(function (matrix, i) {
            var columns = matrix.columns.slice(1); // Skip ID column

            var x_scale = d3.scaleOrdinal(
                d3.range(columns.length)
                    .map(function (i) {
                      return i * chart_width / columns.length
                    })
            ).domain(columns);

            var labels = d3.select(this).append("svg")
                .attr("width", chart_width)
                .attr("height", header_height)
                .append("g")
                .attr("transform", "translate(0," + header_height + ")");

            labels.append("g")
                .call(d3.axisTop().scale(x_scale))
                .attr('text-anchor', 'end');

            labels.selectAll('text').style('transform', 'rotate(90deg)');
            labels.selectAll('line').remove();
            labels.selectAll('path').remove();
          });
        }

        function heatmap_body(selection) {
          selection.each(function (matrix, i) {
            var dx = matrix.columns.length - 1,
                dy = matrix.length;

            var canvas_pixel_width = dx;
            var canvas_pixel_height = d3.min([chart_height, dy]);

            d3.select(this).append("canvas")
                .attr("width", canvas_pixel_width)
                .attr("height", canvas_pixel_height)
                .style("width", chart_width + "px")
                .style("height", chart_height + "px")
                .style("image-rendering", crisp())
                .call(draw_heatmap);

            function draw_heatmap(canvas) {
              var context = canvas.node().getContext("2d"),
                  image = context.createImageData(dx, chart_height);
              // One canvas pixel for data horizontally,
              // but combine data rows into a single canvas pixel row.

              var data_rows_per_pixel_row = dy / chart_height;
              //console.log('data rows / pixel row', data_rows_per_pixel_row);

              var color = d3.scaleLinear()
                  .domain([-20, 0, 20]) // TODO: Set from data
                  .range(['blue', 'white', 'red']);

              for (var y = 0, p = -1; y < canvas_pixel_height; ++y) {
                for (var x = 1; x <= dx; ++x) { // 0-column is row ID
                  var mean = d3.mean(d3.range(data_rows_per_pixel_row).map(
                      function (i) {
                        return matrix[y + i][matrix.columns[x]];
                        // TODO: If data_rows_per_pixel_row is not an integer, rows may be double counted
                        // --> Use histogram machinery.
                      }
                  ));
                  var c = d3.rgb(color(mean));
                  image.data[++p] = c.r;
                  image.data[++p] = c.g;
                  image.data[++p] = c.b;
                  image.data[++p] = 255;
                }
              }

              context.putImageData(image, 0, 0);
            }
          });
        }

        function scatterplot_scales(matrix) {
          // TODO: only run this once
          // column-0 is ID
          var x_axis_column = matrix.columns[1];
          var y_axis_column = matrix.columns[2];

          var x_extent = d3.extent(matrix, function (row) {
            return +row[x_axis_column]
          });
          var y_extent = d3.extent(matrix, function (row) {
            return +row[y_axis_column]
          });

          var x_scale = d3.scaleLinear()
              .domain(x_extent).nice()
              .range([0, chart_width]);
          var y_scale = d3.scaleLinear()
              .domain(y_extent).nice()
              .range([chart_height, 0]);
          return {
            x: x_scale,
            y: y_scale,
            x_column: x_axis_column,
            y_column: y_axis_column
          }
        }

        function scatterplot_axes(selection) {
          selection.each(function (matrix, i) {
            var scales = scatterplot_scales(matrix);

            var x_axis = d3.axisBottom().scale(scales.x);
            var y_axis = d3.axisLeft().scale(scales.y);

            var svg_axes = d3.select(this).append("svg")
                .attr("width", chart_width + gutter_width)
                .attr("height", chart_height + 2 * header_height)
                .style("position", "absolute")
                .append("g")
                .attr("transform", "translate(" + gutter_width + "," + header_height + ")");
            svg_axes.append("g")
                .attr("transform", "translate(0," + chart_height + ")")
                .call(x_axis);
            svg_axes.append("g")
                .call(y_axis);
          });
        }

        function scatterplot_body(selection) {
          selection.each(function (matrix, i) {
            var scales = scatterplot_scales(matrix);
            d3.select(this).append("canvas")
                .attr("width", chart_width)
                .attr("height", chart_height)
                .style("position", "relative")
                .style("left", gutter_width + "px")
                .style("top", header_height + "px")
                .style("width", chart_width + "px")
                .style("height", chart_height + "px")
                .style("image-rendering", crisp())
                .call(draw_scatterplot);

            function draw_scatterplot(canvas) {
              var context = canvas.node().getContext("2d");
              context.fillStyle = "rgba(0,0,0,1)";
              matrix.forEach(function (row) {
                var x = scales.x(+row[scales.x_column]);
                var y = scales.y(+row[scales.y_column]);
                context.fillRect(x, y, 1, 1);
              })
            }
          });
        }

        function chart(selection) {
          selection.each(function (matrix, i) {
            d3.select(this).append("div")
                .style("width", chart_width + 'px')
                .style("float", "left")
                .call(heatmap_axes)
                .call(heatmap_body);
            d3.select(this).append("div")
                .style("width", chart_width + 'px')
                .style("float", "left")
                .call(scatterplot_axes)
                .call(scatterplot_body);
          });
        }

        return chart;
      };
    }
);

<|endoftext|>


<commit_before>/**
 * @overview ccm component for rendering component informations
 * @author André Kless <andre.kless@web.de> 2017
 * @author Tea Kless <tea.kless@web.de> 2017
 * @license The MIT License (MIT)
 */

( function () {

  var ccm_version = '9.0.0';
  var ccm_url     = 'https://akless.github.io/ccm/ccm.min.js';

  var component_name = 'comp_info';
  var component_obj  = {

    name: component_name,

    config: {

      html_templates: {
        "main": {
          "id": "main",
          "class": "container",
          "inner": [
            {
              "tag": "header",
              "class": "media",
              "inner": [
                {
                  "class": "media-left",
                  "tag": "section",
                  "id": "logo",
                  "inner":
                    {
                      "tag": "a",
                      "inner":
                        {
                          "tag": "img",
                          "src": "%logo%"
                        }
                    }
                },
                {
                  "class": "media-body",
                  "tag": "section",
                  "id": "trailer",
                  "inner": [
                    {
                      "tag": "h4",
                      "id": "title",
                      "class": "media-heading",
                      "inner": "%title%"
                    },
                    {
                      "tag": "a",
                      "href": "%link_to_developer%",
                      "id": "developer",
                      "inner": [
                          "%developer%",
                        {
                          "tag":"span",
                          "class": "glyphicon glyphicon-chevron-right"
                        }
                      ]

                    }
                  ]
                }
              ]
            },
            {
              "tag": "hr"
            },
            {
              "class": "navigation text-center",
              "inner": {
                "class": "btn-group",
                "inner":[
                  {
                    "tag": "button",
                    "typ": "button",
                    "class": "btn btn-primary",
                    "inner": "Information",
                    "onclick": "%info%"
                  },
                  {
                    "tag": "button",
                    "typ": "button",
                    "class": "btn btn-primary",
                    "inner": "Preview",
                    "onclick": "%preview%"
                  },
                  {
                    "tag": "button",
                    "typ": "button",
                    "class": "btn btn-primary",
                    "inner": "Demo",
                    "onclick": "%demo%"
                  }
                ]
              }
            },
            {
              "id": "info",
              "inner": [
                {
                  "tag": "h2",
                  "inner": "Information"
                },
                {
                  "tag": "hr"
                },
                {
                  "tag": "p",
                  "class": "lead",
                  "inner": "%abstract%"
                },
                {
                  "tag": "h4",
                  "inner": "Description"
                },
                {
                  "tag": "p",
                  "inner": "%description%"
                },
                {
                  "tag": "h4",
                  "inner": "Details"
                },
                {
                  "tag": "table",
                  "class": "table table-striped",
                  "inner": {
                    "tag": "tbody",
                    "class": "col-md-12",
                    "inner": [
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "Component name"
                          },
                          {
                            "tag": "td",
                            "inner": "%name%"
                          }
                        ]
                      },
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "Version"
                          },
                          {
                            "tag": "td",
                            "inner": "%version%"
                          }
                        ]
                      },
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "URL"
                          },
                          {
                            "tag": "td",
                            "inner": {
                              "tag": "a",
                              "href": "%url%",
                              "inner": "%u%"
                            }
                          }
                        ]
                      },
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "Developer"
                          },
                          {
                            "tag": "td",
                            "inner": "%developer%"
                          }
                        ]
                      },
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "LICENSE"
                          },
                          {
                            "tag": "td",
                            "inner": "%license%"
                          }
                        ]
                      }
                    ]
                  }
                },
                {
                  "class": "text-right",
                  "inner": {
                    "tag": "a",
                    "href": "#main",
                    "inner": {
                      "tag": "span",
                      "class": "label label-default",
                      "inner": "back to top",
                      "onclick": "%top%"
                    }
                  }
                }
              ]
            },
            {
              "id": "prev",
              "inner": [
                {
                  "tag": "h3",
                  "inner": "Preview"
                },
                {
                  "tag": "hr"
                },
                {
                  "class": "row",
                  "inner": [
                    {
                      "class": "col-xs-6 col-md-3",
                      "inner":{
                        "class": "thumbnail",
                        "inner":{
                          "tag": "img",
                          "src": "%placeholder1%"
                        }
                      }
                    },
                    {
                      "class": "col-xs-6 col-md-3",
                      "inner":{
                        "class": "thumbnail",
                        "inner":{
                          "tag": "img",
                          "src": "%placeholder2%"
                        }
                      }
                    },
                    {
                      "class": "col-xs-6 col-md-3",
                      "inner":{
                        "class": "thumbnail",
                        "inner":{
                          "tag": "img",
                          "src": "%placeholder3%"
                        }
                      }
                    }
                  ]

                },
                {
                  "class": "text-right",
                  "inner": {
                    "tag": "a",
                    "href": "#main",
                    "inner": {
                      "tag": "span",
                      "class": "label label-default",
                      "inner": "back to top",
                      "onclick": "%to%"
                    }
                  }
                }
              ]
            },
            {
              "id": "demo",
              "inner":[
                {
                  "tag": "h3",
                  "inner": "Live demo with demo data"
                },
                {
                  "tag": "hr"
                },
                {
                  "id": "demo_section"
                },
                {
                  "class": "text-right",
                  "inner": {
                    "tag": "a",
                    "href": "#main",
                    "inner": {
                      "tag": "span",
                      "class": "label label-default",
                      "inner": "back to top",
                      "onclick": "%t%"
                    }
                  }
                }
              ]
            }
          ]
        }
      },
      data: { store: [ 'ccm.store' ] },
      placeholder: {
        name: 'Name',
        url: 'URL',
        developer: 'Developer',
        licence: 'Licence'
      },
      bootstrap: [ 'ccm.load', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css', { context: 'head', url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css' } ]

  //  compact: true

    },

    Instance: function () {

      var self = this;

      this.start = function ( callback ) {

        self.ccm.helper.dataset( self.data, function ( dataset ) {

          var main_templ = self.ccm.helper.clone( self.html_templates.main );

          var main_elem = self.ccm.helper.html( main_templ, {
            logo: dataset.logo,
            title: dataset.title,
            link_to_developer: dataset.link,
            developer: dataset.developer,
            abstract: dataset.abstract,
            description: dataset.description,
            name: dataset.name,
            version: dataset.version,
            url: dataset.url,
            u: dataset.url,
            license: dataset.license,
            placeholder1: Array.isArray( dataset.previews ) && dataset.previews[ 0 ] ? dataset.previews[ 0 ] : 'none',
            placeholder2: Array.isArray( dataset.previews ) && dataset.previews[ 1 ] ? dataset.previews[ 1 ] : 'none',
            placeholder3: Array.isArray( dataset.previews ) && dataset.previews[ 2 ] ? dataset.previews[ 2 ] : 'none',
            info: function () {
              self.element.querySelector( '#info' ).scrollIntoView();
            },
            preview: function () {
              self.element.querySelector( '#prev' ).scrollIntoView();
            },
            demo: function () {
              self.element.querySelector( '#demo' ).scrollIntoView();
            },
            top: function () {
              self.element.querySelector( '#main' ).scrollIntoView();
            },
            to: function () {
              self.element.querySelector( '#main' ).scrollIntoView();
            },
            t: function () {
              self.element.querySelector( '#main' ).scrollIntoView();
            }

          } );
          self.ccm.helper.makeIterable( main_elem.querySelector( 'img[src="none"]' ) ).map( function ( node ) {
            node.parentNode.parentNode.style.display = 'none';
          } );

          self.ccm.start( dataset.url, dataset.demo, function ( instance ) {

            self.ccm.helper.setContent( main_elem.querySelector( '#demo_section' ), instance.root );

            self.ccm.helper.setContent( self.element, main_elem );

            if ( callback ) callback();

          } );

        } );

      };

    }

  };

  var namespace = window.ccm && ccm.components[ component_name ]; if ( namespace ) { if ( namespace.ccm_version ) ccm_version = namespace.ccm_version; if ( namespace.ccm_url ) ccm_url = namespace.ccm_url; }
  if ( !window.ccm || !ccm[ ccm_version ] ) { var tag = document.createElement( 'script' ); document.head.appendChild( tag ); tag.onload = register; tag.src = ccm_url; } else register();
  function register() { ccm[ ccm_version ].component( component_obj ); }
}() );<commit_msg>update info component<commit_after>/**
 * @overview ccm component for rendering component informations
 * @author André Kless <andre.kless@web.de> 2017
 * @author Tea Kless <tea.kless@web.de> 2017
 * @license The MIT License (MIT)
 */

( function () {

  var ccm_version = '9.0.0';
  var ccm_url     = 'https://akless.github.io/ccm/ccm.min.js';

  var component_name = 'comp_info';
  var component_obj  = {

    name: component_name,

    config: {

      html_templates: {
        "main": {
          "id": "main",
          "class": "container",
          "inner": [
            {
              "tag": "header",
              "class": "media",
              "inner": [
                {
                  "class": "media-left",
                  "tag": "section",
                  "id": "logo",
                  "inner":
                    {
                      "tag": "a",
                      "inner":
                        {
                          "tag": "img",
                          "src": "%logo%"
                        }
                    }
                },
                {
                  "class": "media-body",
                  "tag": "section",
                  "id": "trailer",
                  "inner": [
                    {
                      "tag": "h4",
                      "id": "title",
                      "class": "media-heading",
                      "inner": "%title%"
                    },
                    {
                      "tag": "a",
                      "href": "%link_to_developer%",
                      "id": "developer",
                      "inner": [
                          "%developer%",
                        {
                          "tag":"span",
                          "class": "glyphicon glyphicon-chevron-right"
                        }
                      ]

                    }
                  ]
                }
              ]
            },
            {
              "tag": "hr"
            },
            {
              "class": "navigation text-center",
              "inner": {
                "class": "btn-group",
                "inner":[
                  {
                    "tag": "button",
                    "typ": "button",
                    "class": "btn btn-primary",
                    "inner": "Information",
                    "onclick": "%info%"
                  },
                  {
                    "tag": "button",
                    "typ": "button",
                    "class": "btn btn-primary",
                    "inner": "Preview",
                    "onclick": "%preview%"
                  },
                  {
                    "tag": "button",
                    "typ": "button",
                    "class": "btn btn-primary",
                    "inner": "Demo",
                    "onclick": "%demo%"
                  }
                ]
              }
            },
            {
              "id": "info",
              "inner": [
                {
                  "tag": "h2",
                  "inner": "Information"
                },
                {
                  "tag": "hr"
                },
                {
                  "tag": "p",
                  "class": "lead",
                  "inner": "%abstract%"
                },
                {
                  "tag": "h4",
                  "inner": "Description"
                },
                {
                  "tag": "p",
                  "inner": "%description%"
                },
                {
                  "tag": "h4",
                  "inner": "Details"
                },
                {
                  "tag": "table",
                  "class": "table table-striped",
                  "inner": {
                    "tag": "tbody",
                    "class": "col-md-12",
                    "inner": [
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "Component name"
                          },
                          {
                            "tag": "td",
                            "inner": "%name%"
                          }
                        ]
                      },
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "Version"
                          },
                          {
                            "tag": "td",
                            "inner": "%version%"
                          }
                        ]
                      },
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "URL"
                          },
                          {
                            "tag": "td",
                            "inner": {
                              "tag": "a",
                              "href": "%url%",
                              "inner": "%u%"
                            }
                          }
                        ]
                      },
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "Developer"
                          },
                          {
                            "tag": "td",
                            "inner": "%developer%"
                          }
                        ]
                      },
                      {
                        "tag": "tr",
                        "inner": [
                          {
                            "tag": "th",
                            "inner": "LICENSE"
                          },
                          {
                            "tag": "td",
                            "inner": "%license%"
                          }
                        ]
                      }
                    ]
                  }
                },
                {
                  "class": "text-right",
                  "inner": {
                    "tag": "a",
                    "href": "#main",
                    "inner": {
                      "tag": "span",
                      "class": "label label-default",
                      "inner": "back to top",
                      "onclick": "%top%"
                    }
                  }
                }
              ]
            },
            {
              "id": "prev",
              "inner": [
                {
                  "tag": "h3",
                  "inner": "Preview"
                },
                {
                  "tag": "hr"
                },
                {
                  "class": "row",
                  "inner": [
                    {
                      "class": "col-xs-6 col-md-3",
                      "inner":{
                        "class": "thumbnail",
                        "inner":{
                          "tag": "img",
                          "src": "%placeholder1%"
                        }
                      }
                    },
                    {
                      "class": "col-xs-6 col-md-3",
                      "inner":{
                        "class": "thumbnail",
                        "inner":{
                          "tag": "img",
                          "src": "%placeholder2%"
                        }
                      }
                    },
                    {
                      "class": "col-xs-6 col-md-3",
                      "inner":{
                        "class": "thumbnail",
                        "inner":{
                          "tag": "img",
                          "src": "%placeholder3%"
                        }
                      }
                    }
                  ]

                },
                {
                  "class": "text-right",
                  "inner": {
                    "tag": "a",
                    "href": "#main",
                    "inner": {
                      "tag": "span",
                      "class": "label label-default",
                      "inner": "back to top",
                      "onclick": "%to%"
                    }
                  }
                }
              ]
            },
            {
              "id": "demo",
              "inner":[
                {
                  "tag": "h3",
                  "inner": "Live demo with demo data"
                },
                {
                  "tag": "hr"
                },
                {
                  "id": "demo_section"
                },
                {
                  "class": "text-right",
                  "inner": {
                    "tag": "a",
                    "href": "#main",
                    "inner": {
                      "tag": "span",
                      "class": "label label-default",
                      "inner": "back to top",
                      "onclick": "%t%"
                    }
                  }
                }
              ]
            }
          ]
        }
      },
      data: { store: [ 'ccm.store' ] },
      placeholder: {
        name: 'Name',
        url: 'URL',
        developer: 'Developer',
        licence: 'Licence'
      },
      bootstrap: [ 'ccm.load', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css', { context: 'head', url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css' } ]

  //  compact: true

    },

    Instance: function () {

      var self = this;

      this.start = function ( callback ) {

        self.ccm.helper.dataset( self.data, function ( dataset ) {

          var main_templ = self.ccm.helper.clone( self.html_templates.main );

          var main_elem = self.ccm.helper.html( main_templ, {
            logo: dataset.logo,
            title: dataset.title,
            link_to_developer: dataset.link,
            developer: dataset.developer,
            abstract: dataset.abstract,
            description: dataset.description,
            name: dataset.name,
            version: dataset.version,
            url: dataset.url,
            u: dataset.url,
            license: dataset.license,
            placeholder1: Array.isArray( dataset.previews ) && dataset.previews[ 0 ] ? dataset.previews[ 0 ] : 'none',
            placeholder2: Array.isArray( dataset.previews ) && dataset.previews[ 1 ] ? dataset.previews[ 1 ] : 'none',
            placeholder3: Array.isArray( dataset.previews ) && dataset.previews[ 2 ] ? dataset.previews[ 2 ] : 'none',
            info: function () {
              self.element.querySelector( '#info' ).scrollIntoView();
            },
            preview: function () {
              self.element.querySelector( '#prev' ).scrollIntoView();
            },
            demo: function () {
              self.element.querySelector( '#demo' ).scrollIntoView();
            },
            top: function () {
              self.element.querySelector( '#main' ).scrollIntoView();
            },
            to: function () {
              self.element.querySelector( '#main' ).scrollIntoView();
            },
            t: function () {
              self.element.querySelector( '#main' ).scrollIntoView();
            }

          } );
          self.ccm.helper.makeIterable( main_elem.querySelectorAll( 'img[src="none"]' ) ).map( function ( node ) {
            node.parentNode.parentNode.style.display = 'none';
          } );

          self.ccm.start( dataset.url, dataset.demo, function ( instance ) {

            self.ccm.helper.setContent( main_elem.querySelector( '#demo_section' ), instance.root );

            self.ccm.helper.setContent( self.element, main_elem );

            if ( callback ) callback();

          } );

        } );

      };

    }

  };

  var namespace = window.ccm && ccm.components[ component_name ]; if ( namespace ) { if ( namespace.ccm_version ) ccm_version = namespace.ccm_version; if ( namespace.ccm_url ) ccm_url = namespace.ccm_url; }
  if ( !window.ccm || !ccm[ ccm_version ] ) { var tag = document.createElement( 'script' ); document.head.appendChild( tag ); tag.onload = register; tag.src = ccm_url; } else register();
  function register() { ccm[ ccm_version ].component( component_obj ); }
}() );<|endoftext|>


<commit_before>// modified from
// https://stackoverflow.com/questions/12150491/toc-list-with-all-classes-generated-by-automodule-in-sphinx-docs

$(function (){
  var createList = function(selected) {
    var ul = $('
');

    selected.each(function(i,e) {

      var fullname = e.id;
      var n = $(e).children('.descname').clone();
      if (fullname.startsWith('tensorpack.'))
        fullname = fullname.substr(11);
      n[0].innerText = fullname;
      var l = $(e).children('.headerlink');

      var a = $('');
      a.attr('href',l.attr('href')).attr('title', 'Link to this definition');

      a.append(n);

      var entry = $('
').append(a);
      ul.append(entry);
    });
    return ul;
  }

  var customIndex = $('.custom-index');
  customIndex.empty();

  var selected = $('div.section>dl>dt');
  if (selected.length === 0)
    return;

  var l = createList(selected);

  var c = $('
');
  var ul = c.clone()
    .append(l);
  customIndex.append(ul);

});
<commit_msg>Refactoring javascript to show class name (#385)<commit_after>// modified from
// https://stackoverflow.com/questions/12150491/toc-list-with-all-classes-generated-by-automodule-in-sphinx-docs

$(function (){
  var createList = function(selected) {
    var obj = {};
    var ul = $('
');

    selected.each(function(i,e) {

      var className = e.getElementsByTagName('a')[0].href;
      className = className.substr(className.lastIndexOf('/')+1);
      className = className.substr(0,className.lastIndexOf(".html"));

      var fullname = e.id;
      if (fullname.startsWith('tensorpack.'))
        fullname = fullname.substr(11);
      var n = $(e).children('.descname').clone();

      n[0].innerText = fullname;
      var l = $(e).children('.headerlink');

      var a = $('');
      a.attr('href',l.attr('href')).attr('title', 'Link to this definition');

      a.append(n);

      var entry = $('
').append(a);

      if(className in obj) {
        obj[className] = obj[className].append(entry);
      } else {
        var ul = $('
');
        ul.append(entry);
        obj[className] = ul;
      }

    });

    return obj;
  }

  var customIndex = $('.custom-index');
  customIndex.empty();

  var selected = $('div.section>dl>dt');
  if (selected.length === 0)
    return;

  var obj = createList(selected);
  for(var key in obj) {
    var c = $('
');
    var a = $('
');
    a.html(key);
    var u = c.clone().append(a);
    var ul = c.clone().append(obj[key]);
    customIndex.append(u);
    customIndex.append(ul);
  }

});
<|endoftext|>


<commit_before>(function() {

    "use strict";

    var seedrandom = require('seedrandom');
    var randomSeed = (new Date()).getTime();

    // must be first
    seedrandom(randomSeed, {
        global: true
    });

    var chalk = require('chalk');
    var math = require('mathjs');
    var jpeg = require('jpeg-js');
    var R = require('ramda');
    var Rp = require('./plus-fp/plus-fp');

    var clr = require('./color');

    var path = require('path');
    var promise = require("bluebird");
    var fs = promise.promisifyAll(require('fs'));

    // load jpeg

    function loadJpeg(filename) {

        var jpegData = fs.readFileSync(filename);

        var rawImageData = jpeg.decode(jpegData);

        var data = R.times(() => [], rawImageData.height);

        var rawData = rawImageData.data;
        var w = rawImageData.width;
        var h = rawImageData.height;

        for (var d = 0; d < rawImageData.width * rawImageData.height * 4; d += 4) {
            let rgb = {};

            rgb.r = rawData[d];
            rgb.g = rawData[d + 1];
            rgb.b = rawData[d + 2];

            let d1 = d / 4;

            let x = math.floor(d1 / w);
            let y = d1 - x * w;

            data[y][x] = {
                rgb: rgb
            };
        }

        return {
            data: data,
            width: w,
            height: h
        };
    }

    function num2hex(d) {
      return (d < 16 ? "0" : "") + d.toString(16);
    }

    // ------------ output to html+three.js

    var create3d = function(filename) {

        return new promise(function(resolve) {

            console.log(chalk.yellow(filename));

            var jpeg = loadJpeg(filename);

            let data = jpeg.data;
            let inputWidth = jpeg.width;
            let inputHeight = jpeg.height;

            var outputFilename = filename.replace(/\.jpg/, '.html');

            var outputWidth = inputWidth;
            var outputHeight = inputHeight;

            var maxz = 100 + Rp.bandomInt(outputHeight - 100, 3);
            console.log('maxz ' , maxz);

            try {
                var outf = fs.createWriteStream(`${outputFilename}`);

                outf.write(`<!DOCTYPE html>
                <html lang='en'>
                <head>
                    <meta charset='UTF-8'>
                    <title>${outputFilename}</title>
                    <script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/r73/three.min.js'></script>
                </head>
                <body style='margin:0; padding:0; overflow: hidden'>\n`);

                // add line
                outf.write(`<script>
                function al(scene, x3, y3, z3, color) {
                  var geometry = new THREE.Geometry();

                  geometry.vertices.push(
                    new THREE.Vector3( x3, y3, 0 ),
                    new THREE.Vector3( x3, y3, z3 )
                  );

                  var material = new THREE.LineBasicMaterial({
                    color: color
                  });

                  var line = new THREE.Line( geometry, material );

                  scene.add(line);
                }
                </script>\n`);

                outf.write(`<script>
                  draw();

                  function draw() {

                      var width = ${outputWidth};
                      var height = ${outputHeight};

                      var s = new THREE.Scene();

                      var planeGeometry = new THREE.PlaneGeometry(width, height);
                      var planeMaterial = new THREE.MeshBasicMaterial({color: 0xff6600});
                      var plane = new THREE.Mesh(planeGeometry, planeMaterial);
                \n`);

                // outf.write(`
                //       var planeGeometry = new THREE.PlaneGeometry(width, height);
                //       var planeMaterial = new THREE.MeshBasicMaterial({color: 0xff6600});
                //       var plane = new THREE.Mesh(planeGeometry, planeMaterial);

                //       // rotate and position the plane
                //       plane.rotation.x = -0.5 * Math.PI;
                //       plane.position.x = 15;
                //       plane.position.y = 0;
                //       plane.position.z = 0;

                //       s.add(plane);
                // \n`);

                let xy = [];

                for (let y = 0; y < outputHeight; y++) {

                    for (let x = 0; x < outputWidth; x++) {
                        xy.push({
                            x: x,
                            y: y
                        });
                    }
                }

                // use a small % of points otherwise too big to render
                xy = R.sortBy(() => math.random(), xy);
                xy = R.take(xy.length * 0.18, xy);
                // xy = R.take(1000, xy); // debug

                for (let k = 0; k < xy.length; k++) {

                    let yy = xy[k].y;
                    let xx = xy[k].x;

                    let x = xx + inputWidth / 2 - outputWidth / 2;
                    let y = yy + inputHeight / 2 - outputHeight / 2;
                    let rgb = data[x][y].rgb;

                    let hsl = clr.rgb2hsl(rgb);

                    // 3d coords
                    let x3 = (x / inputWidth) * outputWidth - outputWidth / 2;
                    let y3 = - ((y / inputHeight) * outputHeight - outputHeight / 2);

                    let z3 = math.round(hsl.l * maxz, 0); /// outputHeight;

                    outf.write(`al(s, ${x3}, ${y3}, ${z3}, 0x${num2hex(rgb.r)}${num2hex(rgb.g)}${num2hex(rgb.b)});\n`);
                }

                // end

                let backgroundColor = '0x000000';

                outf.write(`
                  var renderer = new THREE.WebGLRenderer();

                  var camera = new THREE.PerspectiveCamera( 75, width / height, 0.1, 1000 );

                  camera.position.x = ${ Rp.bandomInt(outputWidth / 2, 2) * Rp.randomSign()};
                  camera.position.y = ${ Rp.bandomInt(outputHeight / 2, 2) * Rp.randomSign()};
                  camera.position.z = ${ Rp.bandomInt(1000, -2)};

                  camera.lookAt(s.position);

                  renderer.setClearColor(new THREE.Color(${backgroundColor}));

                  renderer.setSize( width, height );

                  document.body.appendChild( renderer.domElement );

                  renderer.render( s, camera );
                \n`);

                outf.write(`}
                      </script>
                  </body>
                  </html>
                  \n`);

                data = null;
                jpeg.data = null;
                jpeg = null;
                xy = null;

                outf.end(function() {
                    outf = null;
                    resolve();
                });
            } catch (ex) {
                console.log(chalk.red('error'), ex);

                resolve();
            }

        });
    };

    // process file

    var processFiles = function() {

        if (process.argv.length > 2) {

            var files = R.tail(R.tail(process.argv));

            files = R.filter((f) => path.extname(f) === '.jpg', files);

            // console.log(files);

            promise.each(files, create3d).then(function() {});
        }
        else {
            console.log('usage: node 3d-image path ...');
        }

    };

    // kick off

    processFiles();

}());
<commit_msg>more points<commit_after>(function() {

    "use strict";

    var seedrandom = require('seedrandom');
    var randomSeed = (new Date()).getTime();

    // must be first
    seedrandom(randomSeed, {
        global: true
    });

    var chalk = require('chalk');
    var math = require('mathjs');
    var jpeg = require('jpeg-js');
    var R = require('ramda');
    var Rp = require('./plus-fp/plus-fp');

    var clr = require('./color');

    var path = require('path');
    var promise = require("bluebird");
    var fs = promise.promisifyAll(require('fs'));

    // load jpeg

    function loadJpeg(filename) {

        var jpegData = fs.readFileSync(filename);

        var rawImageData = jpeg.decode(jpegData);

        var data = R.times(() => [], rawImageData.height);

        var rawData = rawImageData.data;
        var w = rawImageData.width;
        var h = rawImageData.height;

        for (var d = 0; d < rawImageData.width * rawImageData.height * 4; d += 4) {
            let rgb = {};

            rgb.r = rawData[d];
            rgb.g = rawData[d + 1];
            rgb.b = rawData[d + 2];

            let d1 = d / 4;

            let x = math.floor(d1 / w);
            let y = d1 - x * w;

            data[y][x] = {
                rgb: rgb
            };
        }

        return {
            data: data,
            width: w,
            height: h
        };
    }

    function num2hex(d) {
      return (d < 16 ? "0" : "") + d.toString(16);
    }

    // ------------ output to html+three.js

    var create3d = function(filename) {

        return new promise(function(resolve) {

            console.log(chalk.yellow(filename));

            var jpeg = loadJpeg(filename);

            let data = jpeg.data;
            let inputWidth = jpeg.width;
            let inputHeight = jpeg.height;

            var outputFilename = filename.replace(/\.jpg/, '.html');

            var outputWidth = inputWidth;
            var outputHeight = inputHeight;

            var maxz = 100 + Rp.bandomInt(outputHeight - 100, 3);
            console.log('maxz ' , maxz);

            try {
                var outf = fs.createWriteStream(`${outputFilename}`);

                outf.write(`<!DOCTYPE html>
                <html lang='en'>
                <head>
                    <meta charset='UTF-8'>
                    <title>${outputFilename}</title>
                    <script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/r73/three.min.js'></script>
                </head>
                <body style='margin:0; padding:0; overflow: hidden'>\n`);

                // add line
                outf.write(`<script>
                function al(scene, x3, y3, z3, color) {
                  var geometry = new THREE.Geometry();

                  geometry.vertices.push(
                    new THREE.Vector3( x3, y3, 0 ),
                    new THREE.Vector3( x3, y3, z3 )
                  );

                  var material = new THREE.LineBasicMaterial({
                    color: color
                  });

                  var line = new THREE.Line( geometry, material );

                  scene.add(line);
                }
                </script>\n`);

                outf.write(`<script>
                  draw();

                  function draw() {

                      var width = ${outputWidth};
                      var height = ${outputHeight};

                      var s = new THREE.Scene();

                      var planeGeometry = new THREE.PlaneGeometry(width, height);
                      var planeMaterial = new THREE.MeshBasicMaterial({color: 0xff6600});
                      var plane = new THREE.Mesh(planeGeometry, planeMaterial);
                \n`);

                // outf.write(`
                //       var planeGeometry = new THREE.PlaneGeometry(width, height);
                //       var planeMaterial = new THREE.MeshBasicMaterial({color: 0xff6600});
                //       var plane = new THREE.Mesh(planeGeometry, planeMaterial);

                //       // rotate and position the plane
                //       plane.rotation.x = -0.5 * Math.PI;
                //       plane.position.x = 15;
                //       plane.position.y = 0;
                //       plane.position.z = 0;

                //       s.add(plane);
                // \n`);

                let xy = [];

                for (let y = 0; y < outputHeight; y++) {

                    for (let x = 0; x < outputWidth; x++) {
                        xy.push({
                            x: x,
                            y: y
                        });
                    }
                }

                // use a small % of points otherwise too big to render
                xy = R.sortBy(() => math.random(), xy);
                xy = R.take(xy.length * 0.75, xy);
                // xy = R.take(1000, xy); // debug

                for (let k = 0; k < xy.length; k++) {

                    let yy = xy[k].y;
                    let xx = xy[k].x;

                    let x = xx + inputWidth / 2 - outputWidth / 2;
                    let y = yy + inputHeight / 2 - outputHeight / 2;
                    let rgb = data[x][y].rgb;

                    let hsl = clr.rgb2hsl(rgb);

                    // 3d coords
                    let x3 = (x / inputWidth) * outputWidth - outputWidth / 2;
                    let y3 = - ((y / inputHeight) * outputHeight - outputHeight / 2);

                    let z3 = math.round(hsl.l * maxz, 0); /// outputHeight;

                    outf.write(`al(s, ${x3}, ${y3}, ${z3}, 0x${num2hex(rgb.r)}${num2hex(rgb.g)}${num2hex(rgb.b)});\n`);
                }

                // end

                let backgroundColor = '0x000000';

                outf.write(`
                  var renderer = new THREE.WebGLRenderer();

                  var camera = new THREE.PerspectiveCamera( 75, width / height, 0.1, 1000 );

                  camera.position.x = ${ Rp.bandomInt(outputWidth / 2, 2) * Rp.randomSign()};
                  camera.position.y = ${ Rp.bandomInt(outputHeight / 2, 2) * Rp.randomSign()};
                  camera.position.z = ${ Rp.bandomInt(1000, -2)};

                  camera.lookAt(s.position);

                  renderer.setClearColor(new THREE.Color(${backgroundColor}));

                  renderer.setSize( width, height );

                  document.body.appendChild( renderer.domElement );

                  renderer.render( s, camera );
                \n`);

                outf.write(`}
                      </script>
                  </body>
                  </html>
                  \n`);

                data = null;
                jpeg.data = null;
                jpeg = null;
                xy = null;

                outf.end(function() {
                    outf = null;
                    resolve();
                });
            } catch (ex) {
                console.log(chalk.red('error'), ex);

                resolve();
            }

        });
    };

    // process file

    var processFiles = function() {

        if (process.argv.length > 2) {

            var files = R.tail(R.tail(process.argv));

            files = R.filter((f) => path.extname(f) === '.jpg', files);

            // console.log(files);

            promise.each(files, create3d).then(function() {});
        }
        else {
            console.log('usage: node 3d-image path ...');
        }

    };

    // kick off

    processFiles();

}());
<|endoftext|>


<commit_before>/*jslint browser: true*/

( function( vui ) {

	'use strict';

	// Check if the provided vui global is defined, otherwise try to require it if
	// we're in a CommonJS environment; otherwise we'll just fail out
	if( vui === undefined ) {
		if( typeof require === 'function' ) {
			vui = require('../../core');
		} else {
			throw new Error('load vui first');
		}
	}

	// Export the vui object if we're in a CommonJS environment.
	// It will already be on the window otherwise
	if( typeof module === 'object' && typeof module.exports === 'object' ) {
		module.exports = vui;
	}

	var $ = vui.$;

	$.widget( 'vui.vui_changeTracker', {

		_create: function() {

			var $node = $( this.element );

			var changedItems = {};

			$node.on( 'vui-change', function( e, args ) {

				changedItems[args.id] = true;

				$node.addClass( 'vui-changed' );

			} ).on( 'vui-restore', function( e, args ) {

				if ( changedItems[args.id] !== undefined ) {
					delete changedItems[args.id];
				}

				if ( Object.keys( changedItems ).length === 0 ) {
					$node.removeClass( 'vui-changed' );
				}

			} );

		},

		_destroy: function () {

			$( this.element )
				.removeClass( 'vui-changed' )
				.off( 'vui-change vui-restore' );

		},

		hasChanged: function() {
			return $( this.element ).hasClass( 'vui-changed' );
		}

	} );

	vui.addClassInitializer(
			'vui-change-tracker',
			function( node ) {
				$( node ).vui_changeTracker();
			}
		);

} )( window.vui );<commit_msg>Changing hasChanged to containsChanges and isHighlightingChanges (separating tracking of changes from purplification.<commit_after>/*jslint browser: true*/

( function( vui ) {

	'use strict';

	// Check if the provided vui global is defined, otherwise try to require it if
	// we're in a CommonJS environment; otherwise we'll just fail out
	if( vui === undefined ) {
		if( typeof require === 'function' ) {
			vui = require('../../core');
		} else {
			throw new Error('load vui first');
		}
	}

	// Export the vui object if we're in a CommonJS environment.
	// It will already be on the window otherwise
	if( typeof module === 'object' && typeof module.exports === 'object' ) {
		module.exports = vui;
	}

	var $ = vui.$;

	$.widget( 'vui.vui_changeTracker', {

		_changedItems: {},

		_create: function() {

			var me = this;

			var $node = $( this.element );

			$node.on( 'vui-change', function( e, args ) {

				me._changedItems[args.id] = true;

				if ( !e.isChangeHighlighted ) {
					$node.addClass( 'vui-changed' );
					e.isChangeHighlighted = true;
				}

			} ).on( 'vui-restore', function( e, args ) {

				if ( me._changedItems[args.id] !== undefined ) {
					delete me._changedItems[args.id];
				}

				if ( Object.keys( me._changedItems ).length === 0 ) {
					$node.removeClass( 'vui-changed' );
				}

			} );

		},

		_destroy: function () {

			$( this.element )
				.removeClass( 'vui-changed' )
				.off( 'vui-change vui-restore' );

			this._changedItems = { };

		},

		containsChanges: function() {
			return ( Object.keys( this._changedItems ).length > 0 );
		},

		isHighlightingChanges: function () {
			return $( this.element ).hasClass( 'vui-changed' );
		}

	} );

	vui.addClassInitializer(
			'vui-change-tracker',
			function( node ) {
				$( node ).vui_changeTracker();
			}
		);

} )( window.vui );<|endoftext|>


<commit_before>var width = 960,
	height = 800,
	innerRadius = Math.min(width, height) * .41,
	outerRadius = innerRadius * 1.1;

var fill = d3.scale.ordinal().domain(d3.range(5)).range(
		[ "#000000", "#FFDD89", "#957244", "#F26223", "#00FF00" ]);

function fillByLength(length){
	if(length < 10000){
		return "#FF0000";
	}
	else if(length < 50000){
		return "#FFDD00";
	}
	else{
		return "#00FF00";
	}
}

function fillByIdy(identity){
	if(identity < 90){
		return "#FF0000";
	}
	else if(identity < 95){
		return "#FFDD00";
	}
	else{
		return "#00FF00";
	}
}

var svg = d3.select("body").append("svg").attr("width", width).attr("height",
		height).append("g").attr("transform",
		"translate(" + width / 2 + "," + height / 2 + ")");

function drawKaryo(karyo) {
	svg.append("g").selectAll("path").data(karyo).enter().append("path").style(
			"fill", function(d) {
				return fill(d.index);
			}).style("stroke", function(d) {
		return fill(d.index);
	})
			.attr(
					"d",
					d3.svg.arc().innerRadius(innerRadius).outerRadius(
							outerRadius)).on("mouseover", fade(.1)).on(
					"mouseout", fade(1));
	addTicks(karyo);
}

function addTicks(karyo) {
	var ticks = svg.append("g").selectAll("g").data(karyo).enter().append("g")
			.selectAll("g").data(groupTicks).enter().append("g").attr(
					"transform",
					function(d) {
						return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
								+ "translate(" + outerRadius + ",0)";
					});

	ticks.append("line").attr("x1", 1).attr("y1", 0).attr("x2", 5)
			.attr("y2", 0).style("stroke", "#000");

	ticks.append("text").attr("x", 8).attr("dy", ".35em").attr("transform",
			function(d) {
				return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
			}).style("text-anchor", function(d) {
		return d.angle > Math.PI ? "end" : null;
	}).text(function(d) {
		return d.label;
	});
}

function drawLinks(links) {
	svg.append("g").attr("class", "chord").selectAll("path").data(links)
			.enter().append("path").attr("d",
					d3.svg.chord().radius(innerRadius)).style("fill",
					function(d) {
					//	return fillByLength(Math.abs(d.target.end - d.target.start));
						return fillByIdy(Math.abs(d.identity));
					}).style("opacity", 1);
}

// Returns an array of tick angles and labels, given a group.
function groupTicks(d) {
	var k = (d.endAngle - d.startAngle) / d.value;
	return d3.range(0, d.value, 10000).map(function(v, i) {
		return {
			angle : v * k + d.startAngle,
			label : i % 5 ? null : v / 1000 + "k"
		};
	});
}

function loadKaryoFile(file) {
	$.getJSON(file, function(data) {
		karyo_to_coords(data);
	});
}

function karyo_to_coords(data) {
	var total = 0;
	var spacer = 10000;
	$.each(data, function(key, value) {
		total += value + spacer;
	});
	var current = 0;
	var index = 0;
	$.each(data, function(key, value) {
		data[key] = {
			"value" : value,
			"startAngle" : ((current + spacer) / total) * (2 * Math.PI),
			"index" : index++
		};
		current += value + spacer;
		data[key].endAngle = (current / total) * (2 * Math.PI);
	});
	var array = $.map(data, function(value, index) {
		return [ value ];
	});
	drawKaryo(array);
	loadLinkFile("test/link.json", data)
}

function loadLinkFile(file, karyo) {
	$.getJSON(file, function(data) {
		link_to_coords(data, karyo);
	});
}

function link_to_coords(links, karyo) {
	$.each(links, function(key, value) {
		var s = karyo[value.source.name];
		var s_totalAngle = s.endAngle - s.startAngle;
		links[key].source.startAngle = s.startAngle + s_totalAngle
				* (value.source.start / s.value);
		links[key].source.endAngle = s.startAngle + s_totalAngle
				* (value.source.end / s.value);
		links[key].source.index = s.index;
		links[key].source.value = Math.abs(value.source.end
				- value.source.start);
		var t = karyo[value.target.name];
		var t_totalAngle = t.endAngle - t.startAngle;
		links[key].target.endAngle = t.startAngle + t_totalAngle
				* (value.target.start / t.value);
		links[key].target.startAngle = t.startAngle + t_totalAngle
				* (value.target.end / t.value);
		links[key].target.index = t.index;
		links[key].target.value = Math.abs(value.target.end
				- value.target.start);
	});
        console.log(links);
	drawLinks(links);
}

// Returns an event handler for fading a given chord group.
function fade(opacity) {
	return function(g, i) {
		svg.selectAll(".chord path").filter(function(d) {
			return d.source.index != i && d.target.index != i;
		}).transition().style("opacity", opacity);
	};
}
<commit_msg>modified karyo function to call a callback if provided<commit_after>var width = 960,
	height = 800,
	innerRadius = Math.min(width, height) * .41,
	outerRadius = innerRadius * 1.1;

var fill = d3.scale.ordinal().domain(d3.range(5)).range(
		[ "#000000", "#FFDD89", "#957244", "#F26223", "#00FF00" ]);

function fillByLength(length){
	if(length < 10000){
		return "#FF0000";
	}
	else if(length < 50000){
		return "#FFDD00";
	}
	else{
		return "#00FF00";
	}
}

function fillByIdy(identity){
	if(identity < 90){
		return "#FF0000";
	}
	else if(identity < 95){
		return "#FFDD00";
	}
	else{
		return "#00FF00";
	}
}

var svg = d3.select("body").append("svg").attr("width", width).attr("height",
		height).append("g").attr("transform",
		"translate(" + width / 2 + "," + height / 2 + ")");

function drawKaryo(karyo) {
	svg.append("g").selectAll("path").data(karyo).enter().append("path").style(
			"fill", function(d) {
				return fill(d.index);
			}).style("stroke", function(d) {
		return fill(d.index);
	})
			.attr(
					"d",
					d3.svg.arc().innerRadius(innerRadius).outerRadius(
							outerRadius)).on("mouseover", fade(.1)).on(
					"mouseout", fade(1));
	addTicks(karyo);
}

function addTicks(karyo) {
	var ticks = svg.append("g").selectAll("g").data(karyo).enter().append("g")
			.selectAll("g").data(groupTicks).enter().append("g").attr(
					"transform",
					function(d) {
						return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
								+ "translate(" + outerRadius + ",0)";
					});

	ticks.append("line").attr("x1", 1).attr("y1", 0).attr("x2", 5)
			.attr("y2", 0).style("stroke", "#000");

	ticks.append("text").attr("x", 8).attr("dy", ".35em").attr("transform",
			function(d) {
				return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
			}).style("text-anchor", function(d) {
		return d.angle > Math.PI ? "end" : null;
	}).text(function(d) {
		return d.label;
	});
}

function drawLinks(links) {
	svg.append("g").attr("class", "chord").selectAll("path").data(links)
			.enter().append("path").attr("d",
					d3.svg.chord().radius(innerRadius)).style("fill",
					function(d) {
					//	return fillByLength(Math.abs(d.target.end - d.target.start));
						return fillByIdy(Math.abs(d.identity));
					}).style("opacity", 1);
}

// Returns an array of tick angles and labels, given a group.
function groupTicks(d) {
	var k = (d.endAngle - d.startAngle) / d.value;
	return d3.range(0, d.value, 10000).map(function(v, i) {
		return {
			angle : v * k + d.startAngle,
			label : i % 5 ? null : v / 1000 + "k"
		};
	});
}

function loadKaryoFile(file, callback) {
	$.getJSON(file, function(data) {
		karyo_to_coords(data);
	        if(typeof callback !== "undefined"){
		    callback(data);
		}
	});
}

function karyo_to_coords(data) {
	var total = 0;
	var spacer = 10000;
	$.each(data, function(key, value) {
		total += value + spacer;
	});
	var current = 0;
	var index = 0;
	$.each(data, function(key, value) {
		data[key] = {
			"value" : value,
			"startAngle" : ((current + spacer) / total) * (2 * Math.PI),
			"index" : index++
		};
		current += value + spacer;
		data[key].endAngle = (current / total) * (2 * Math.PI);
	});
	var array = $.map(data, function(value, index) {
		return [ value ];
	});
	drawKaryo(array);
	loadLinkFile("test/link.json", data)
}

function loadLinkFile(file, karyo) {
	$.getJSON(file, function(data) {
		link_to_coords(data, karyo);
	});
}

function link_to_coords(links, karyo) {
	$.each(links, function(key, value) {
		var s = karyo[value.source.name];
		var s_totalAngle = s.endAngle - s.startAngle;
		links[key].source.startAngle = s.startAngle + s_totalAngle
				* (value.source.start / s.value);
		links[key].source.endAngle = s.startAngle + s_totalAngle
				* (value.source.end / s.value);
		links[key].source.index = s.index;
		links[key].source.value = Math.abs(value.source.end
				- value.source.start);
		var t = karyo[value.target.name];
		var t_totalAngle = t.endAngle - t.startAngle;
		links[key].target.endAngle = t.startAngle + t_totalAngle
				* (value.target.start / t.value);
		links[key].target.startAngle = t.startAngle + t_totalAngle
				* (value.target.end / t.value);
		links[key].target.index = t.index;
		links[key].target.value = Math.abs(value.target.end
				- value.target.start);
	});
        console.log(links);
	drawLinks(links);
}

// Returns an event handler for fading a given chord group.
function fade(opacity) {
	return function(g, i) {
		svg.selectAll(".chord path").filter(function(d) {
			return d.source.index != i && d.target.index != i;
		}).transition().style("opacity", opacity);
	};
}
<|endoftext|>


<commit_before>/*
Mag.JS v0.10.2
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
!function(e,n,t,r){function o(e){return"[object Array]"===Object.prototype.toString.call(e)}function i(e){if(""!==e.id)return'id("'+e.id+'")';if(e===t.body)return e.tagName;var n=0;if(e.parentNode)for(var r=e.parentNode.childNodes,o=0;o<r.length;o++){var l=r[o];if(l===e)return i(e.parentNode)+"/"+e.tagName+"["+(n+1)+"]";1===l.nodeType&&l.tagName===e.tagName&&n++}}function l(e){var n=i(e);e.queryCache,e.parentNode.removeChild(e),w[n+"-config"]&&w[n+"-config"].configContext&&"function"==typeof w[n+"-config"].configContext.onunload&&w[n+"-config"].configContext.onunload(w[n+"-config"].configContext,e,n),delete w[n];for(var t in w)0===t.indexOf(n)&&delete w[t]}function a(e){return(e=e&&parseInt(e.split("[").pop().slice(0,-1)))?parseInt(e)-1:0}function c(e,n,t){var a,u,s;if(e){null==n&&(n={_text:""});var h=d(e);if(s=o(n)){if(x[t]=x[t]||0,b[t]&&0===h.length&&(b[t].parent.insertAdjacentHTML("beforeend",b[t].node),h=d(b[t].parent.children),"object"==typeof n[0]),0===h.length)return;for(u=h[0].parentNode,b[t]||(b[t]={node:h[0].cloneNode(!0).outerHTML,parent:u});h.length<n.length;)b[t]?(u.insertAdjacentHTML("beforeend",b[t].node),a=u.lastChild):a=h[0].cloneNode(!0),h.push(a),u&&u.appendChild(a);if(void 0===h[0].__key&&"object"==typeof n[0],a=n.map(function(e){return e[C]}),(h.length==n.length||-1!==a.indexOf(r))&&(n=n.map(function(e,n){return"object"==typeof e&&(e[C]||(e[C]="__magnum__"+x[t]++),h[n].__key=e[C]),e})),h.length>n.length)if(0===n.length||"object"!=typeof n[0])for(;h.length>n.length;)a=h.pop(),(u=a.parentNode)&&l(a);else var g=n.map(function(e){return e[C]}),h=(h.map(function(e){return e.__key}),h.filter(function(e){return-1===g.indexOf(e.__key)?(l(e),!1):!0}))}for(a=0;a<h.length;a++)u=i(h[a]),s?h[a]&&(w[u]&&w[u]===JSON.stringify(n[a]),c(h[a],n[a]),h[a].queryCache):(n&&"object"==typeof n&&-1!==Object.keys(n).indexOf(C)&&(h[a].isChildOfArray=!0,h[a]._dataPass=n),f(h[a],n));return e}}function u(e){return e.parentNode&&e.parentNode.isChildOfArray?e.parentNode:e.parentNode?u(e.parentNode):void 0}function f(e,n){var t;if("function"!=typeof n){if("object"!=typeof n)return f(e,{_text:n});for(var a in n){var u=n[a];u===r?u="":null===u&&-1===["onunload"].indexOf(a)&&v(e,a).forEach(function(e){l(e)}),"_"===a[0]&&(t=t||{},t[a.substr(1)]=u)}var d=i(e);t&&s(e,t);var h=0,g=["willupdate","didupdate","didload","willload"];for(a in n)if(-1===g.indexOf(a)&&(u=n[a],"_"!==a[0])){if(t=v(e,a),"function"==typeof u&&"fun"==u.type)try{u=u()}catch(p){}o(u)&&(t=v(e,"$"+a)),c(t,u,d+"/"+a),h++}}}function d(e){var n;if(null==e.length&&(e=[e]),!o(e)){n=[];for(var t=0;t<e.length;t+=1)e[t]&&n.push(e[t]);e=n}return e}function s(t,r){var o=i(t),l=a(o);w[o]&&w[o]===JSON.stringify(r),t._events=t._events||[];for(var c in r)if("text"!==c&&"html"!==c)if(0==c.indexOf("on")){if(-1===t._events.indexOf(c)||N){var f=function(n,t,r,o,i){try{return n.call(t,i,r,t,o)}finally{e.redraw()}}.bind(null,r[c],t,l,(u(t)||{})._dataPass);t[c]=f,t._events.push(c)}}else if("config"==c){f=!0,w[o+"-config"]?f=!1:w[o+"-config"]={};var d=w[o+"-config"].configContext=w[o+"-config"].configContext||{};n.push(function(e,n){return function(){return e.apply(e,n)}}(r[c],[t,f,d,l]))}else f={key:c,value:r[c],node:t},e.hook("attributes",c,f),f.change&&(c=f.key,r[c]=f.value),null===r[c]?t.removeAttribute(c):t.setAttribute(c,""+r[c]);h(t,r.text),p(t,r.html),t.queryCache}function h(e,n){var t,r;if(i(e),e&&null!=n){if(!r){r=[];for(var o=0;o<e.childNodes.length;o+=1)t=e.childNodes[o],t.nodeType===y&&r.push(t)}for(;e.firstChild;)e.removeChild(e.firstChild);for("input"===e.nodeName.toLowerCase()?e.setAttribute("value",""+n):e.appendChild(e.ownerDocument.createTextNode(""+n)),o=0;o<r.length;o+=1)e.appendChild(r[o])}}function g(e){e.cloner&&(e.id="__magnum__::"+e.id.split("__magnum__::").pop())}function p(e,n){if(e&&null!=n){for(;e.firstChild;)e.removeChild(e.firstChild);if("function"==typeof n&&1===n().nodeType){g(n());var r=t.createElement("span");e.appendChild(r);try{e.replaceChild(n(),r)}catch(o){console.log("FILL HTML ERROR",n().id,o)}}else 1===n.nodeType?(g(n),r=t.createElement("span"),e.appendChild(r),e.replaceChild(n,r)):e.innerHTML=n}}function v(n,t,r){for(var o=n.childNodes,i=[],l=0;l<o.length;l+=1)o[l].nodeType===y&&i.push(o[l]);var o=[],l=t,a="$"===t[0];"$"===l[0]&&(l=l.substr(1));for(var c=0;c<i.length;c+=1){var u=i[c],f=l,d=" "+u.className+" ";(u.id===f||-1<d.indexOf(" "+f+" ")||u.name===f||u.nodeName.toLowerCase()===f.toLowerCase()||u.getAttribute("data-bind")===f)&&o.push(i[c])}if(!o.length||a)for(c=0;c<i.length&&(o=o.concat(v(i[c],t,!0)),!o.length||a);c++);return r||o.length||(n={key:t,value:o,node:n},e.hook("elementMatcher",t,n),n.change),o}function m(e,n){if(n={tagName:e.tagName},e.firstChild||e.children[0]){var t=e.firstChild||e.childNodes[0];(t=t.nodeValue||t.value||t.innerText)&&(t=t.replace(/\u00a0/g,"x").trim()),t&&(n.tagValue=t)}for(t=0;t<e.attributes.length;t++)n[e.attributes[t].name]=e.attributes[t].value;var r=e.children;if(r.length)for(n.children=[],t=0;t<r.length;t++)n.children[t]=m(r[t],n.children);return n}var y=1,w=[],C="_key",b={},w=[],x={},N=!1;e.fill={fill:c,elementToObject:m,cached:w,find:v,clear:function(){N=!0},unclear:function(){N=!1},configs:n},window.mag=e}(window.mag||{},[],document),function(e){var n={modules:[],promises:[],deferreds:[],controllers:[],elements:[],getController:function(e,n,t){return"undefined"!=typeof Proxy?new Proxy(new e.controller,{get:function(e,r){if(void 0===e[r]&&-1===["watchers","toJSON","called","onload","onunload"].indexOf(r)){var o,i=t.find(n,r),l="$"===r[0],a=[];return i.forEach(function(e,n){i[n]&&(i[n].value&&0<i[n].value.length?(o=i[n].value,!i[n].type||"checkbox"!=i[n].type&&"radio"!=i[n].type||(o={_text:o,_checked:i[n].checked},a.push(o))):i[n].innerText&&0<i[n].innerText.length?o=i[n].innerText:i[0].innerHTML&&0<i[n].innerHTML.length&&(o=i[n].innerHTML))}),0<a.length&&l?a:o}return e[r]}}):new e.controller},submodule:function(e,n){var t=function(n){return(e.controller||function(){}).apply(this,n)}.bind({},n);return t.$original=e.controller,t.$$args=n,t={controller:t,view:function(t){if(1<arguments.length)var r=n.concat([].slice.call(arguments,1));r=e.view.apply(e,r?[t].concat(r):[t]),n[0]&&null!=n[0].key&&(r.attrs.key=n[0].key)}},n[0]&&null!=n[0].key&&(t.attrs={key:n[0].key}),t},getArgs:function(e){return n.modules[e].controller&&n.modules[e].controller.$$args?[n.controllers[e]].concat(n.modules[e].controller.$$args):[n.controllers[e]]}};e.mod=n}(window.mag||{}),function(e){function n(e,n,t){var o=n.getArgs(t),i=n.modules[t];n.controllers[t],n=r.contexts[t]=r.contexts[t]||{};try{i.view(o[0],e,n)}catch(l){console.log("Mag.JS",e.id,t,l)}}function t(e,n){e&&void 0!==Object.observe&&Object.observe(e,function(r){r.forEach(function(r){"object"==typeof e[r.name]&&t(e[r.name],n)}),n.apply(this,arguments)})}var r={roots:[],contexts:[],templates:{},cache:{},unloaders:[],callLCEvent:function(e,n,t,o){var i=!1,l={preventDefault:function(){i=!0}};if(n.controllers[t][e]&&(n.controllers[t][e].call({},l,n.elements[t]),o&&(n.controllers[t][e]=0)),i)for(o=0;e=r.unloaders[o];o++)e.controller.onunload&&(e.handler.call(e.controller,n.elements[t]),e.controller.onunload=0);return i},callConfigs:function(e){for(var n=0,t=e.length;t>n;n++)e[n]()}},o=[];r.redraw=function(e,n,t){e=e||r.module||{},t&&(o=[]),this.fun=this.fun||c(function(){n.configs.splice(0,n.configs.length),r.doLoop(e,n)}),this.fun()},r.doLoop=function(n,t){for(var o=0;r.roots[o];o++)if(e.running=!0,n.controllers[o]&&n.elements[o]){if(r.callLCEvent("willload",n,o,1))return;if(r.innerLoop(n,t,o)){n.deferreds[o][2]({_html:e.prop(n.elements[o])}),r.callLCEvent("didload",n,o,1),r.callConfigs(t.configs);var i=n,l=t,a=o,c=void 0;for(c in l.cached)-1!==c.indexOf('id("'+i.elements[a].id+'")/')&&l.cached[c].configContext&&r.unloaders.push({controller:l.cached[c].configContext,handler:l.cached[c].configContext.onunload});n.deferreds[o][0]&&(i=n.deferreds[o][1],delete n.elements[i],n.modules[i],n.controllers[i],n.promises[i],n.deferreds[i])}}t.unclear()},r.clear=function(e,n,t){-1!==e&&o[e]&&t.clear()},r.innerLoop=function(e,t,i){var l=e.elements[i],a=e.getArgs(i);return o[i]&&o[i]===JSON.stringify(a)?!1:(n(l,e,i),o[i]=JSON.stringify(a),r.setupWatch(a,t,l,i,e),t.fill(l,a[0]),!0)};var i;r.doWatch=function(t,l,a,c,u,f){if(f!=i){if(i=f,e.running=!0,r.callLCEvent("willupdate",c,a,1),u=c.getArgs(a),o[a]&&o[a]===JSON.stringify(u))return void r.callLCEvent("didupdate",c,a);n(l,c,a),o[a]=JSON.stringify(u),t.fill(l,u[0]),e.running=!1}},r.setupWatch=function(n,o,i,l,a){var u=e.runner=!1;t(n[0],function(t){t.forEach(function(e){return"add"==e.type||"update"==e.type?void(u=!0):void 0}),u&&!e.runner&&(e.runner=!0,a.controllers[l]=n[0],c(r.doWatch.bind({},o,i,l,a,t))())})};var l=window.cancelAnimationFrame||window.clearTimeout,a=window.requestAnimationFrame||window.setTimeout,c=function(e,n){var t,r,o=n||16;return function(){if(+new Date-t>o||a===window.requestAnimationFrame){r>0&&l(r);var n=arguments;r=a(function(){t=+new Date;var r=[].slice.call(arguments).concat([].slice.call(n));e.apply(this,r)},o)}else{t=+new Date;var i=[].slice.call(arguments).concat([].slice.call(n));e.apply(this,i),r=a(function(){r=null},o)}}};e.render=r}(window.mag||{}),function(e,n){function t(n){var t=function(){return arguments.length&&(n=arguments[0],e.redraw()),n};return t.type="fun",t.toJSON=function(){return n&&n.nodeType?l.elementToObject(n):n},t}function r(n,t){var o=e.prop(t);return n.then(o),o.then=function(e,o){return r(n.then(e,o),t)},o}var o=e.mod,i=e.render,l=e.fill,a={}.toString,c=e.running=!1;e.redraw=function(n){c||e.running||(c=!0,i.redraw(o||i.module||{},l,n),c=!1)},e.withProp=function(e,n){return function(t){t=t||event,t=t.currentTarget||this,n(e in t?t[e]:t.getAttribute(e))}},e.prop=function(e){return(null!=e&&"[object Object]"===a.call(e)||"function"==typeof e)&&"function"==typeof e.then?r(e):t(e)};var u={attributes:[],elementMatcher:[]};e.hookin=function(e,n,t){u[e].push({context:{},handler:t,key:n})},e.hook=function(e,n,t,r){for(var o in u[e])t.changed=!1,u[e][o].key==n&&(r=JSON.stringify({v:t.value,k:t.key}),u[e][o].handler.call(u[e][o].context,t),r!==JSON.stringify({v:t.value,k:t.key})&&(t.change=!0))},e.module=function(t,a,c,u){var f=i.roots.indexOf(t);c&&!c.retain&&i.clear(f,t,l),(0>f||u)&&(f=i.roots.length);var d=n.getElementById(t);if(!d)throw Error("Mag.JS Module - invalid node id: "+t);if(i.roots[f]=d.id,!a.view)throw Error("Mag.JS module - requires a view: "+JSON.stringify(a));return t=o.submodule(a,[Object.freeze(c||{})]),a=o.getController(t,d,l),o.controllers[f]=a,a.onunload&&i.unloaders.push({controller:a,handler:a.onunload}),o.modules[f]=t,o.elements[f]=u?d.cloneNode(!0):d,o.elements[f].cloner=u,o.promises[f]=new Promise(function(){o.deferreds[f]=arguments}.bind({},u,f)),e.redraw(),r(o.promises[f],{_html:e.prop(o.elements[f])})}}(window.mag||{},document);
<commit_msg>Delete mag.0.10.2.min.js<commit_after><|endoftext|>


<commit_before>/*
Mag.JS v0.22.1
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
!function(e,t,n){function i(e,n){if(c[e]&&!n)return c[e];var i=t.getElementById(e);return i&&(c[e]=i),i}var r={values:[],attributes:[],elementMatcher:[]};e.create=function(t,n,i){return function(r,o){return"string"!=typeof r&&(o=r,r=0),e.module(r||t,n,e.utils.merge(i||{},o||{}))}},e.module=function(t,n,r){r=r||{};var o;if(!(o=!e.utils.items.isItem(t))){o=e.utils.items.getItem(t);var a=i(t);o=!e.utils.callLCEvent("onreload",e.mod.getState(o),a,o)}return o&&(o=r.key&&e.utils.items.isItem(t+"."+r.key)?e.utils.items.getItem(t+"."+r.key):e.utils.getItemInstanceId(r.key?t+"."+r.key:t),r.retain||e.mod.clear(o),e.mod.submodule(t,o,n,r),a=i(t),l(o,t),!e.utils.callLCEvent("willload",e.mod.getState(o),a,o,1))?(t=e.mod.getState(o),e.utils.unloaders[o]=e.utils.unloaders[o]||[],t.onunload&&e.utils.unloaders[o].push({controller:t,handler:t.onunload}),e.redraw(a,o,1),e.utils.callLCEvent("didload",e.mod.getState(o),a,o,1),d(o,a,n,e.utils.copyFun(r))):void 0};var o=function(t,n){return 0>n||n!=e.utils.items.getItem(t)?t==e.mod.getId(n)?!0:!1:!0},a=[];e.begin=function(e){n===a[e]?a[e]=1:a[e]++},e.end=function(t){if(1<a[t])a[t]--;else{a[t]=0;var n=e.utils.items.getItemVal(t);e.redraw(i(n),t)}},e.redraw=function(t,i,r){if(!a[i]){if(!t||n===i)throw Error("Mag.JS - Id or node invalid: "+i);o(t.id,i)&&(r&&e.fill.configs.splice(0,e.fill.configs.length),r&&e.mod.clear(i),t=f(t,i,r),fastdom.clear(e.mod.getFrameId(i)),t=fastdom.write(t),e.mod.setFrameId(i,t))}},e.hookin=function(e,t,n){r[e].push({context:{},handler:n,key:t})},e.hook=function(t,n,i){for(var o=0,a=r[t].length;a>o;o++)e.utils.callHook(r,n,t,o,i)};var u={},d=function(t,n,i,r){return i=function(t,n,i,r,o){return t=n.id+(r.key?"."+r.key:"")+"."+o,o=u[t]||{},o.id=t,e.utils.items.isItem(t)||(u[t]=o=n.cloneNode(1),o.id=t),o instanceof HTMLElement?(t=e.utils.getItemInstanceId(o.id),e.mod.submodule(o.id,t,i,r),l(t,o.id),e.redraw(o,t,1),o):void 0}.bind({},t,n,i,r),i.getId=function(e){return e}.bind({},t),i.draw=function(t,n,i){e.redraw(t,n,i)}.bind({},n,t),i.getState=function(t){return e.mod.getState(t)}.bind({},t),i.getProps=function(t){return e.mod.getProps(t)}.bind({},t),i.toJSON=function(){return{id:this.getId(),props:this.getProps(),state:this.getState()}},i},c=[],l=function(t,n){var r=function(t,n){i(n)?e.redraw(i(n),t):e.utils.items.isItem(n)&&e.clear(t)}.bind({},t,n);e.props.setup(t,r)};e.clear=function(t){fastdom.clear(e.mod.getFrameId(t)),e.utils.items.removeItem(t),e.mod.clear(t),e.props.cached.splice(t,1),e.fill.clearCache(e.mod.getId(t))};var f=function(t,n,r){return function(t,n,r){if(i(t.id,1),o(t.id,n)&&t){var a=e.mod.getState(n);if(!e.utils.callLCEvent("isupdate",a,t,n)){var u=e.mod.getProps(n),u=e.utils.merge(e.utils.copy(u),e.utils.copy(a));if(e.mod.iscached(n,u)&&!r)return 0;if(r=!e.utils.callLCEvent("willupdate",a,t,n)){e.mod.callView(t,n),e.fill.setId(t.id),e.fill.run(t,a),r=t.id;var d,u=e.fill.configs;for(d in u)-1<d.indexOf('id("'+r+'")/')&&u[d]();d=t.id;for(var c in e.fill.cached)-1<c.indexOf('id("'+d+'")/')&&-1<c.indexOf("-config")&&e.fill.cached[c].configContext&&(e.utils.unloaders[n]=e.utils.unloaders[n]||[],e.utils.unloaders[n].push({controller:e.fill.cached[c].configContext,handler:e.fill.cached[c].configContext.onunload}));e.utils.callLCEvent("didupdate",a,t,n),r=t&&t.parentNode}r&&(t=s(t.parentNode))&&e.redraw(t,e.utils.items.getItem(t.id))}}}.bind({},t,n,r)},s=function(e){return e.id?e:e.parentNode?s(e.parentNode):n};e.getNode=i,window.mag=e}(window.mag||{},document),function(e){function t(t,n,i){var o=document.getElementById(i);return"undefined"!=typeof Proxy?new Proxy(new t,{get:function(t,n){if(void 0===t[n]&&!~r.indexOf(""+n)){var i,a=e.fill.find(o,n),u="$"===n[0],d=[];return a.reverse().forEach(function(e,t){a[t]&&(a[t].value&&0<a[t].value.length?(i=a[t].value,!a[t].type||"checkbox"!=a[t].type&&"radio"!=a[t].type||(i={_value:i,_checked:a[t].checked},d.push(i))):a[t].innerText&&0<a[t].innerText.length?i=a[t].innerText:a[0].innerHTML&&0<a[t].innerHTML.length&&(i=a[t].innerHTML))}),0<d.length&&u?d:i}return t[n]}}):new t}var n=[],i={cache:[],getState:function(e){return n[e][1]},setState:function(e,t){n[e][1]=t},getView:function(e){return n[e][0]},getProps:function(e){return n[e][2]},setProps:function(e,t){return n[e][2]=t},remove:function(e){n.splice(e,1)},getId:function(e){return n[e]&&n[e][3]},exists:function(e){return void 0!==n[e]?!0:!1},setFrameId:function(e,t){n[e][4]=t},getFrameId:function(e){return n[e][4]},submodule:function(e,r,o,a){return n[r]?(i.setProps(r,a),n[r]):(n[r]=[0,0,0,0,0],i.setProps(r,a),a=function(e,t,n){o.view.call(o,t,i.getProps(e),n)}.bind({},r),n[r][0]=a,n[r][1]=t(function(){return(o.controller||function(){}).call(this,i.getProps(r))||this},r,e),n[r][3]=e,n[r])}},r="Symbol(Symbol.toStringTag) nodeType toJSON onunload onreload willupdate didupdate didload willload isupdate".split(" ");i.iscached=function(e,t){return i.cache[e]&&i.cache[e]===JSON.stringify(t)?!0:void(i.cache[e]=JSON.stringify(t))},i.clear=function(e){e>-1&&i.cache[e]&&i.cache.splice(e,1)};var o=[];i.callView=function(t,n){var r=i.getView(n);o[n]||(e.props.attachToArgs(n,i.getState(n),t),o[n]=1),r(i.getState(n),t)},e.mod=i}(window.mag||{}),function(e,t){function n(t,n){var i=[];return new Proxy(t,{deleteProperty:function(e,t){return n(),delete e[t]},set:function(t,r,o){return JSON.stringify(o)!==JSON.stringify(t[r])&&(i[r]=t[r]&&e.utils.copyFun(t[r],1)),n({type:"update",name:r,object:t,oldValue:i[r]}),t[r]=o,!0}})}function i(e,t){for(var i in e)Array.isArray(e[i])&&(e[i]=n(e[i],t));return n(e,t)}function r(e,n){return e&&t.Proxy?i(e,function(e){"object"==typeof e.object[e.name]&&(e.object[e.name]=r(e.object[e.name],n)),n(e)}):void 0}function o(e){for(var t in e)if(e[t]&&-1!==["INPUT","SELECT","TEXTAREA"].indexOf(e[t].tagName))return e[t];return!1}var a={},u=[];a.setup=function(t,n){if(!u[t]){var i=e.mod.getState(t),o=e.mod.getProps(t),i=r(i,function(t){"update"==t.type&&t.oldValue&&"function"==typeof t.oldValue.draw&&t.object[t.name]&&!t.object[t.name].draw&&(t=t.oldValue.getId(),e.utils.callLCEvent("onunload",e.mod.getState(t),e.getNode(e.mod.getId(t)),t),e.clear(t)),n()}),a=r(o,n),a=r(o,n);e.mod.setState(t,i),e.mod.setProps(t,a),u[t]=1}};var d=function(t,n){for(var i=1;i<t.length;i+=2){var r=t[i+1];n=e.fill.find(n,t[i]),n=n[r]}return n},c=function(t,n,i,r){return i=(""+i).split("."),3>i.length?(i=parseInt(i.pop()),i=isNaN(i)?0:i,n=e.fill.find(r[i]?r[i]:r,n)):(r=d(i,r),n=e.fill.find(r,n)),(n=o(n))&&!n.eventOnFocus&&(i=-1<["radio","checkbox"].indexOf(n.type),r=function(n,i){this.__magnum__=this.__magnum__||{},this.__magnum__.dirty||(this.__magnum__.dirty=1),i&&(t._checked=this.checked,e.redraw(n,e.utils.items.getItem(n.id),1))}.bind(n,r,i),i?n.addEventListener("click",r,!1):n.addEventListener("focus",r,!1),n.eventOnFocus=1),n},l=function(t,n,i,r){var a=i[n];"_value"===n&&(n=t.split(".").pop());var u=e.fill.find(r,n),u=o(u);if("function"!=typeof a&&u){var d=c.bind({},i,n,t,r);d(),Object.defineProperty(i,n,{configurable:!0,get:function(){var n=d();return n&&"undefined"!==n.value&&n.__magnum__&&n.__magnum__.dirty&&n.value!==a?(a=n.value,e.redraw(r,t,1),n.value):a},set:function(e){var t=d();t&&"undefined"!==t.value&&t.value!==e&&e!==a&&(t.value=e,a=e)}})}},f=function(e,t,n){for(var i in t){var r=t[i];"object"==typeof r?f(e+"."+i,r,n):l.bind({},e,i,t,n)()}};a.attachToArgs=f,a.cached=u,e.props=a}(window.mag||{},window),function(e){var t={callHook:function(e,t,n,i,r,o){r.change=!1,e[n][i].key==t&&(o=JSON.stringify({v:r.value,k:r.key}),e[n][i].handler.call(e[n][i].context,r),o!==JSON.stringify({v:r.value,k:r.key})&&(r.change=!0))},unloaders:[],callLCEvent:function(n,i,r,o,a){var u=!1,d={preventDefault:function(){u=!0}};if(i&&i[n]&&(i[n].call(i,d,r,e.mod.getProps(o)),a&&(i[n]=0)),u)for(i=0;n=t.unloaders[o][i];i++)n.controller.onunload&&(n.handler.call(n.controller,r),n.controller.onunload=0);return u},copy:function(e){return JSON.parse(JSON.stringify(e))},copyFun:function(n,i){if("object"!=typeof n)return n;if(Object.assign&&!i)return Object.assign(n);if(Object.create&&i)return Object.create(n);var r,o,a;r=Array.isArray(n)?[]:{};for(a in n)o=n[a],r[a]="object"==typeof o?t.copy(o):"function"==typeof o&&"fun"==o.type?e.prop(o()):o;return r},merge:function(e,n){for(var i in n)n[i]&&n[i].constructor==Object&&n.hasOwnProperty(i)&&("object"!=typeof e[i]&&(e[i]={}),e[i])?t.merge(e[i],n[i]):e[i]=n[i];return e}},n={i:[],isItem:function(e){return-1<n.i.indexOf(e)},setItem:function(e){n.i[n.i.length]=e},getItem:function(e){return n.i.indexOf(e)},getItemVal:function(e){return n.i[e]},removeItem:function(e){n.i.splice(n.i.indexOf(e),1)}};t.items=n,t.getItemInstanceIdAll=function(){return n.i},t.getItemInstanceId=function(e){return n.isItem(e)?n.getItem(e):(n.setItem(e),n.getItem(e))},e.utils=t}(window.mag||{}),function(e,t,n,i){function r(e){return Array.isArray&&Array.isArray(e)||"[object Array]"==={}.toString.call(e)}function o(e,t){return e[O]=e[O]||{},(!e[O].uid||t)&&(e[O].uid=performance.now()),e[O].uid}function a(e,t){var n=o(e,t);if(T[n])n=T[n];else{var i,r=T,a="";i=d(e);var u=e.parentNode&&[].indexOf.call(e.parentNode.children,e);i&&(a+='id("'+i.id+'")'),i=a+("/"+e.tagName+"["+(u+1)+"]"),n=r[n]=i}return n}function u(e,t,n){return e=o(e,n),A[N.id]=A[N.id]||[],A[N.id][e]&&A[N.id][e]==t?1:(A[N.id][e]=t,i)}function d(e){return e.id?e:e.parentNode?d(e.parentNode):i}function c(e){if(""!==e.id)return'id("'+e.id+'")';if(e===n.body)return e.tagName;var t=0;if(e.parentNode)for(var i=e.parentNode.childNodes,r=0;r<i.length;r++){var o=i[r];if(o===e)return c(e.parentNode)+"/"+e.tagName+"["+(t+1)+"]";1===o.nodeType&&o.tagName===e.tagName&&t++}}function l(e){var t=c(e);e.parentNode.removeChild(e),k[t+"-config"]&&k[t+"-config"].configContext&&typeof k[t+"-config"].configContext.onunload===C&&k[t+"-config"].configContext.onunload(k[t+"-config"].configContext,e,t)}function f(e){return(e=e&&parseInt(e.split("[").pop().slice(0,-1)))?parseInt(e)-1:0}function s(e){return e&&e[O]&&e[O].isChildOfArray?e:e.parentNode?s(e.parentNode):i}function h(e,t,n){if(!u(e,t.outerHTML,n)){for(;e.lastChild;)e.removeChild(e.lastChild);e.appendChild(t)}}function p(t,n,o){var a,u=f(o);if(n&&n.nodeType==_)return h(t,n),i;if("function"==typeof n){var d=(a=s(t.parentNode))&&a.getAttribute("key");return a&&d&&(u=+d.split(O)[1]),(n=n(u))&&n.nodeType&&n.nodeType==_?(h(t,n),t[O]=t[O]||{},t[O].isChildOfArray=!0,t[O].dataPass={index:u},i):(d=/<[a-z][\s\S]*>/i.test(n)?"_html":"_text",u={},u[d]=n,p(t,u,o))}if("object"!=typeof n)return p(t,{_text:n},o);for(d in n)u=n[d],u===i?u="":null===u&&-1===["onunload"].indexOf(d)?(t[O].detached=t[O].detached||[],t[O].detached[d]=1,g(t,d)):t[O].detached&&t[O].detached[d]&&(m(t,d),t[O].detached[d]=0),"_"===d[0]&&(a=a||{},a[d.substr(1)]=u);a&&w(t,a,o);for(d in n)if(u=n[d],-1===S.indexOf(d)&&"_"!==d[0]){a=x(t,d);var c={key:d,value:u,node:t};e.hook("values","*",c),c.change&&(u=c.value),r(u)&&(a=x(t,"$"+d)),N.run(a,u,o+"/"+d)}}function m(e,t){x(e,t).forEach(function(e){var t=o(e);if(E[t]){for(var n in E[t])e.appendChild(E[t][n]);delete E[t]}})}function g(e,t){x(e,t).forEach(function(e){var t=o(e);for(e.children.length&&(E[t]=v(e.children));e.lastChild;)l(e.lastChild)})}function v(e){var t;if(null==e.length&&(e=[e]),!r(e)){t=[];for(var n=0;n<e.length;n+=1)e[n]&&t.push(e[n]);e=t}return e}function y(t,i,r){return function(t,i,r){var o=s(i),u=o&&c(o),d=f(u),l=a(i),h=f(l),o={path:u,data:((o||{})[O]||[]).dataPass,node:o,index:d},l=l&&-1<l.indexOf("id(")&&l.split('id("')[1].split('")')[0],u=n.getElementById(l);return t=t.call(i,r,h,i,o),e.redraw(u,e.utils.items.getItem(l),1),t}.bind({},i[r],t)}function w(n,i,r){var o,a=f(r);for(o in i)if("text"!==o&&"html"!==o)if(0==o.indexOf("on"))n[o.toLowerCase()]=y(n,i,o);else if("config"==o){r=c(n);var a=f(r),u=!0;k[r+"-config"]?u=!1:k[r+"-config"]={};var d=k[r+"-config"].configContext=k[r+"-config"].configContext||{};t[r]=function(e,t){return function(){return e.apply(e,t)}}(i[o],[n,u,d,a])}else r={key:o,value:i[o],node:n},e.hook("attributes",o,r),r.change&&(o=r.key,i[o]=r.value),null===i[o]?n.removeAttribute(o):(o in n&&(n[o]=i[o]),n.setAttribute(o,""+i[o]));b(n,i.text),I(n,i.html)}function b(e,t){var n,i;if(e&&null!=t&&!u(e,t)){if(!i){i=[];for(var r=0;r<e.childNodes.length;r+=1)n=e.childNodes[r],n.nodeType===_&&i.push(n)}for(;e.lastChild;)e.removeChild(e.lastChild);for("INPUT"===e.nodeName?e.value=""+t:e.appendChild(e.ownerDocument.createTextNode(""+t)),r=0;r<i.length;r+=1)e.appendChild(i[r]);"SELECT"===e.nodeName&&(e.value=""+t)}}function I(e,t){e&&null!=t&&!u(e,t)&&(e.innerHTML=t)}function x(t,n,i){var r=[];if(t){var o=t.childNodes;if(o)for(var a=0;a<o.length;a+=1)o[a].nodeType===_&&r.push(o[a])}var o=[],a=n,u="$"===n[0];"$"===a[0]&&(a=a.substr(1));for(var d=0;d<r.length;d+=1){var c=r[d],l=a,f=" "+c.className+" ";(c.id===l||-1<f.indexOf(" "+l+" ")||c.name===l||c.nodeName.toLowerCase()===l.toLowerCase()||c.getAttribute("data-bind")===l)&&o.push(r[d])}if(!o.length||u)for(d=0;d<r.length&&(o=o.concat(x(r[d],n,!0)),!o.length||u);d++);return i||o.length||(t={key:n,value:o,node:t},e.hook("elementMatcher",n,t),t.change&&(o=t.value)),o}var N={},_=1,k=[],O="__magnum__",C="function",S="onunload onreload willupdate didupdate didload willload isupdate".split(" "),T=[],A=[],j={};N.run=function(e,t,n){var o,u,d;if(e){null==t&&(t={_text:""});var c=v(e);if(d=r(t)){if(j[n]&&0===c.length&&(j[n].parent.insertAdjacentHTML("beforeend",j[n].node),c=v(j[n].parent.children)),0===c.length)return;for(u=c[0].parentNode,j[n]||(j[n]={node:c[0].cloneNode(!0).outerHTML,parent:u});c.length<t.length;)j[n]?(u.insertAdjacentHTML("beforeend",j[n].node),o=u.lastChild):o=c[0].cloneNode(!0),c.push(o),u&&u.appendChild(o);if(c.map(function(e){return e.__key}),n=t.map(function(e){return e._key}),(c.length==t.length||-1!==n.indexOf(i))&&(t=t.map(function(e,t){if("object"==typeof e){if(c[t].__key&&void 0===e._key)return e._key=c[t].__key,e;void 0===e._key&&(e._key=O+t),c[t].__key=e._key}return e})),c.length>t.length)if(0===t.length||"object"!=typeof t[0])for(;c.length>t.length;)o=c.pop(),(u=o.parentNode)&&l(o);else var f=[],s=t.map(function(e){return e._key}),c=(c.map(function(e){return e.__key}),c.filter(function(e){return-1===s.indexOf(e.__key)||-1!==f.indexOf(e.__key)?(f.push(e.__key),l(e),!1):(f.push(e.__key),!0)}))}for(n=0;n<c.length;n++)d?c[n]&&N.run(c[n],t[n]):(t&&"object"==typeof t&&-1!==Object.keys(t).indexOf("_key")&&(c[n][O]=c[n][O]||{},c[n][O].isChildOfArray=!0,c[n][O].dataPass=t),o=a(c[n]),p(c[n],t,o));return e}};var E=[];N.configs=t,N.find=x,N.setId=function(e){N.id=e},N.clearCache=function(e){A[e]&&delete A[e]},e.fill=N}(window.mag||{},[],document),function(e){function t(){this.frames=[],this.lastId=0,this.raf=n,this.batch={hash:{},read:[],write:[],mode:null}}var n=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||function(e){return window.setTimeout(e,1e3/60)};t.prototype.write=function(e,t){var n=this.add("write",e,t),i=this.batch.mode,r=n.id;return this.batch.write.push(n.id),"writing"===i||"reading"===i||this.batch.scheduled?r:(this.scheduleBatch(),r)},t.prototype.clear=function(e){if("function"==typeof e)return this.clearFrame(e);e=+e;var t=this.batch.hash[e];if(t){var t=this.batch[t.type],n=t.indexOf(e);delete this.batch.hash[e],~n&&t.splice(n,1)}},t.prototype.clearFrame=function(e){e=this.frames.indexOf(e),~e&&this.frames.splice(e,1)},t.prototype.scheduleBatch=function(){var e=this;this.schedule(0,function(){e.batch.scheduled=!1,e.runBatch()}),this.batch.scheduled=!0},t.prototype.uniqueId=function(){return++this.lastId},t.prototype.flush=function(e){for(var t;t=e.shift();)this.run(this.batch.hash[t])},t.prototype.runBatch=function(){this.batch.mode="reading",this.flush(this.batch.read),this.batch.mode="writing",this.flush(this.batch.write),this.batch.mode=null},t.prototype.add=function(e,t,n){var i=this.uniqueId();return this.batch.hash[i]={id:i,fn:t,ctx:n,type:e}},t.prototype.run=function(e){var t=e.ctx||this,n=e.fn;return delete this.batch.hash[e.id],this.onError?void n.call(t):n.call(t)},t.prototype.loop=function(){var e=this,t=this.raf;this.looping||(t(function n(){var i=e.frames.shift();e.frames.length?t(n):e.looping=!1,i&&i()}),this.looping=!0)},t.prototype.schedule=function(e,t){return this.frames[e]?this.schedule(e+1,t):(this.loop(),this.frames[e]=t)},e=e||new t,window.fastdom=e}(window.fastdom);
<commit_msg>Delete mag.0.22.1.min.js<commit_after><|endoftext|>