<commit_before>define([
    "jquery",
    "pat-parser",
    "pat-registry",
    "pat-utils",
    "pat-inject"
], function($, Parser, registry, utils, inject) {
    var parser = new Parser("modal");

    parser.add_argument("class");

    var modal = {
        name: "modal",
        jquery_plugin: true,
        // div's are turned into modals
        // links and forms inject modals
        trigger: "div.pat-modal, a.pat-modal, form.pat-modal",
        init: function($el, opts) {
            if ($el.length > 1) {
                // We enforce a one-to-one mapping between modal objects and
                // DOM elements, so here we recurse and instantiate a new modal
                // for each $el
                $el.each(function() {
                    modal.init($(this));
                });
            } else if ($el.length === 1) {
                var cfg = parser.parse($el, opts);
                this.$el = $el;
                if ($el.is("div"))
                    modal._init_div1($el, cfg);
                else
                    modal._init_inject1($el, cfg);
            }
        },

        _init_inject1: function($el, cfg) {
            var opts = {
                target: "#pat-modal",
                "class": "pat-modal" + (cfg["class"] ? " " + cfg["class"] : "")
            };
            // if $el is already inside a modal, do not detach #pat-modal,
            // because this would unnecessarily close the modal itself
            if (!$el.closest("#pat-modal")) {
                $("#pat-modal").detach();
            }
            inject.init($el, opts);
        },

        _init_div1: function($el) {
            var $header = $("
"),
                activeElement = document.activeElement;

            $("<button type='button' class='close-panel'>Close</button>").appendTo($header);

            // We cannot handle text nodes here
            $el.children(":last, :not(:first)")
                .wrapAll("
");
            $(".panel-content", $el).before($header);
            $el.children(":first:not(.header)").prependTo($header);

            // Restore focus in case the active element was a child of $el and
            // the focus was lost during the wrapping.
            activeElement.focus();

            // event handlers remove modal - first arg to bind is ``this``
            $(document).on("click.pat-modal", ".close-panel",
                           modal.destroy.bind($el, $el));
            // remove on ESC
            $(document).on("keyup.pat-modal",
                           modal.destroy.bind($el, $el));

            modal.setPosition();
        },

        setPosition: function() {
            if ((this.$el === undefined) || (this.$el.length === 0)) {
                return;
            }

            var $oldClone = $("#pat-modal-clone");
            if ($oldClone.length > 0) {
                $oldClone.remove();
            }
            var true_height = this.$el.outerHeight(); // the height of the highest element (after the function runs)
            $(".panel-content", this.$el).each(function () {
                if ($(this).outerHeight() > true_height) {
                    true_height = $(this).outerHeight();
                }
            });
            var $clone = this.$el.clone();
            $clone
                .attr("id", "pat-modal-clone")
                .css({
                    "visibility": "hidden",
                    "position": "absolute",
                    "height": true_height
                }).appendTo("body");

            modal.callWhenReady(
                '#pat-modal-clone',
                $.proxy(modal.measure, this),
                this);
        },

        callWhenReady: function (selector, callback, scope) {
            // Call the callback only once we're certain the element identified
            // by "selector" is attached to the DOM.
            var self = this;
            if ($(selector).closest('body').length) {
                callback.call(scope);
            } else {
                setTimeout(function () {
                    self.callWhenReady(selector, callback, scope);
                }, 1);
            }
        },

        measure: function() {
            var $clone = $("#pat-modal-clone");
            if ($clone.length === 0) {
                return;
            }

            var maxHeight = $(window).innerHeight() - $clone.outerHeight(true) +
                            $clone.outerHeight(),
                height = $clone.outerHeight();

            $clone.remove();

            if (maxHeight - height < 0) {
                this.$el.addClass("max-height").css("height", maxHeight);
            } else {
                this.$el.removeClass("max-height").css("height", height);
            }

            var top = ($(window).innerHeight() - this.$el.outerHeight(true)) / 2;
            this.$el.css("top", top);
        },

        destroy: function($el, ev) {
            if (ev && ev.type === "keyup" && ev.which !== 27)
                return;
            $(document).off(".pat-modal");
            $el.remove();
        }
    };

    $(window).on("resize.pat-modal-position",
        $.proxy(modal.setPosition, modal));
    $(document).on("patterns-injected.pat-modal-position", "#pat-modal,div.pat-modal",
        $.proxy(modal.setPosition, modal));

    registry.register(modal);
    return modal;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Slight refactor. Read below pls.<commit_after>define([
    "jquery",
    "pat-parser",
    "pat-registry",
    "pat-utils",
    "pat-inject"
], function($, Parser, registry, utils, inject) {
    var parser = new Parser("modal");

    parser.add_argument("class");

    var modal = {
        name: "modal",
        jquery_plugin: true,
        // div's are turned into modals
        // links and forms inject modals
        trigger: "div.pat-modal, a.pat-modal, form.pat-modal",
        init: function($el, opts) {
            if ($el.length > 1) {
                // We enforce a one-to-one mapping between modal objects and
                // DOM elements, so here we recurse and instantiate a new modal
                // for each $el
                $el.each(function() {
                    modal.init($(this));
                });
            } else if ($el.length === 1) {
                var cfg = parser.parse($el, opts);
                this.$el = $el;
                if ($el.is("div"))
                    modal._init_div1($el, cfg);
                else
                    modal._init_inject1($el, cfg);
            }
        },

        _init_inject1: function($el, cfg) {
            var opts = {
                target: "#pat-modal",
                "class": "pat-modal" + (cfg["class"] ? " " + cfg["class"] : "")
            };
            // if $el is already inside a modal, do not detach #pat-modal,
            // because this would unnecessarily close the modal itself
            if (!$el.closest("#pat-modal")) {
                $("#pat-modal").detach();
            }
            inject.init($el, opts);
        },

        _init_div1: function($el) {
            var $header = $("
"),
                activeElement = document.activeElement;

            $("<button type='button' class='close-panel'>Close</button>").appendTo($header);

            // We cannot handle text nodes here
            $el.children(":last, :not(:first)")
                .wrapAll("
");
            $(".panel-content", $el).before($header);
            $el.children(":first:not(.header)").prependTo($header);

            // Restore focus in case the active element was a child of $el and
            // the focus was lost during the wrapping.
            activeElement.focus();
            modal._init_handlers($el);
            modal.setPosition($el);
        },

        _init_handlers: function($el) {
            // event handlers remove modal - first arg to bind is ``this``
            $(document).on("click.pat-modal", ".close-panel", modal.destroy.bind($el, $el));
            // remove on ESC
            $(document).on("keyup.pat-modal", modal.destroy.bind($el, $el));

            $(document).on('resize.pat-modal-position', modal.setPosition.bind(modal, $el));
            $(document).on('pat-inject-content-loaded.pat-modal-position', '#pat-modal',
                modal.setPosition.bind(modal, $el));
            $(document).on('patterns-injected.pat-modal-position', '#pat-modal,div.pat-modal',
                modal.setPosition.bind(modal, $el));
        },

        setPosition: function($el) {
            var $oldClone = $("#pat-modal-clone");
            if ($oldClone.length > 0) {
                $oldClone.remove();
            }
            var true_height = $el.outerHeight(); // the height of the highest element (after the function runs)
            $(".panel-content", $el).each(function () {
                if ($(this).outerHeight() > true_height) {
                    true_height = $(this).outerHeight();
                }
            });
            var $clone = $el.clone();
            $clone
                .attr("id", "pat-modal-clone")
                .css({
                    "visibility": "hidden",
                    "position": "absolute",
                    "height": true_height
                }).appendTo("body");

            modal.callWhenReady(
                '#pat-modal-clone',
                modal.measure.bind(this, $el),
                this);
        },

        callWhenReady: function (selector, callback, scope) {
            // Call the callback only once we're certain the element identified
            // by "selector" is attached to the DOM.
            var self = this;
            if ($(selector).closest('body').length) {
                callback.call(scope);
            } else {
                setTimeout(function () {
                    self.callWhenReady(selector, callback, scope);
                }, 1);
            }
        },

        measure: function($el) {
            var $clone = $("#pat-modal-clone");
            if ($clone.length === 0) {
                return;
            }
            var maxHeight = $(window).innerHeight() - $clone.outerHeight(true) +
                            $clone.outerHeight(),
                height = $clone.outerHeight();

            $clone.remove();

            if (maxHeight - height < 0) {
                $el.addClass("max-height").css("height", maxHeight);
            } else {
                $el.removeClass("max-height").css("height", height);
            }
            $el.css("top", ($(window).innerHeight() - $el.outerHeight(true)) / 2);
        },

        destroy: function($el, ev) {
            if (ev && ev.type === "keyup" && ev.which !== 27)
                return;
            $(document).off(".pat-modal");
            $el.remove();
        }
    };

    registry.register(modal);
    return modal;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|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'));

    var isDev = /Apple_Terminal|iterm\.app/i.test(process.env.TERM_PROGRAM);

    // 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);
    }

    function randomColor(params, maxLightness) {
        let k = math.randomInt(params.xy.length);
        let yy = params.xy[k].y;
        let xx = params.xy[k].x;

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

        let color = `0x${num2hex(math.floor(rgb.r * maxLightness))}${num2hex(math.floor(rgb.g * maxLightness))}${num2hex(math.floor(rgb.b * maxLightness))}`;

        return color;
    }

    //------------- shapes

    let shapeLine = {
      fn: "ln",
      sample: (isDev ? 0.2 : 0.4)
    };

    let shapeCylinder = {
      fn: "cyl",
      sample: 1
    };

    // ------------ 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;

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

            let outputWidth = inputWidth;
            let outputHeight = inputHeight;

            let dimensions = {
                inputWidth,
                inputHeight,
                outputWidth,
                outputHeight
            };

            let maxz = 100 + Rp.bandomInt(outputHeight - 100, 3);

            let maxRadius = 1 + Rp.bandomInt(128, 2);
            let maxRadius2 = (maxRadius < 10 ? 10 + Rp.bandomInt(128, 2) : (math.random() < 0.5 ? maxRadius : 1 + Rp.bandomInt(128, 2)));

            let maxShininess = math.randomInt(0, 256);

            let spotLights = Rp.bandomInt(4, 1);
            let pointLights = (spotLights === 0 ? 1 : 0) + Rp.bandomInt(4, 1);

            let segments = math.randomInt(1, 65);

            let wireframe = (maxRadius > 12) &&  (math.random() < 0.25);

            let minOpacity = math.round(100 * math.random()) / 100;
            let maxOpacity = 1;

            if (wireframe) {
              maxOpacity = math.round(100 * math.random(minOpacity, 1)) / 100;
            }

            let openEnded = (math.random() < 0.5);

            let arc = (math.random() < 0.75) ? 2 * Math.PI : math.round(100 * math.random(0, 2 * Math.PI)) / 100;

            let rotation = {
              x: math.random(0, 2 * Math.PI),
              y: math.random(0, 2 * Math.PI),
              z: math.random(0, 2 * Math.PI)
            };

          let fieldOfView = 60 + Rp.bandom(30, 2) ;

            let params = {
                maxz,
                maxRadius,
                maxRadius2,
                maxShininess,
                spotLights,
                pointLights,
                segments,
                wireframe,
                minOpacity,
                maxOpacity,
                openEnded,
                arc,
                rotation,
                fieldOfView
            };

            console.log('params ', JSON.stringify(params, null, 2));

            params.dimensions = dimensions;

            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`);

                outf.write(`<script>\n`);

                // add line
                outf.write(`
                function ln(scene, options) {
                  var geometry = new THREE.Geometry();

                  geometry.vertices.push(
                    new THREE.Vector3( options.x, options.y, 0 ),
                    new THREE.Vector3( options.x, options.y, options.z )
                  );

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

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

                  scene.add(line);
                }
                \n`);

                // add cylinder

                outf.write(`
                function cyl(scene, options) {

                  var geometry = new THREE.CylinderGeometry(options.radius, options.radius2, options.z, ${params.segments}, 1, ${params.openEnded}, 0, ${params.arc});

                  var materials = [
                  new THREE.MeshPhongMaterial( {
                    color: options.color,
                    opacity: options.opacity,
                    transparent: true,
                    shininess: options.shininess
                  } )
                ];
                \n`);

                if (params.wireframe) {
                  outf.write(`
                    materials.push(

                      new THREE.MeshBasicMaterial( {
                        color: options.color,
                        wireframe: true
                      } )

                    );
                  \n`);
                }

                outf.write(`
                  var cylinder = new THREE.SceneUtils.createMultiMaterialObject( geometry, materials );

                  cylinder.rotation.x = ${params.rotation.x};
                  cylinder.rotation.y = ${params.rotation.y};
                  cylinder.rotation.z = ${params.rotation.z};

                  cylinder.position.x = options.x;
                  cylinder.position.y = options.y;
                  cylinder.position.z = options.z / 2;

                  scene.add(cylinder);
                }
                \n`);

                outf.write(`
                  draw();

                  function draw() {

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

                      var scene = new THREE.Scene();
                      var s = scene;
                \n`);

                let xy = [];

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

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

                // use a small % of points otherwise too big to render

                let shape = shapeLine;

                // let maxRadius = Math.max(params.maxRadius, params.maxRadius2);

                // sample = sample / (maxRadius * maxRadius);

                xy = R.sortBy(() => math.random(), xy);
                xy = R.take(xy.length * shape.sample, xy);

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

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

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

                    let hsl = clr.rgb2hsl(rgb);

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

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

                    let radius = params.maxRadius;
                    let radius2 = params.maxRadius2;

                    let opacity = params.minOpacity + (params.maxOpacity - params.minOpacity) * hsl.l;

                    let shininess = params.maxShininess;

                    outf.write(`${shape.fn}(s, {
                      x: ${x3},
                      y: ${y3},
                      z: ${z3},
                      color: 0x${num2hex(rgb.r)}${num2hex(rgb.g)}${num2hex(rgb.b)},
                      radius: ${radius},
                      radius2: ${radius2},
                      opacity: ${opacity},
                      shininess: ${shininess}
                    });
                    \n`);
                }

                // end

                let backgroundColor = '0x000000';

                params.xy = xy;
                params.data = data;

                params.ambientLight = randomColor(params, 0.5);
                console.log('params.ambientLight ' , params.ambientLight);

                let cameraPositionZ = 1000;

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

                  var camera = new THREE.PerspectiveCamera( ${params.fieldOfView}, width / height, 0.1, 1000 );

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

                  camera.lookAt(scene.position);
                  \n`);

                // spotlights

                for (let i = 0; i < spotLights; i++) {

                  let spotLightColor = randomColor(params, 1);
                  console.log(`spotLightColor${i} `, spotLightColor);

                    outf.write(`
                  var spotLight${i} = new THREE.SpotLight(${spotLightColor});
                  spotLight${i}.position.set(${Rp.bandomInt(dimensions.outputWidth / 2, 2) * Rp.randomSign()}, ${Rp.bandomInt(dimensions.outputHeight / 2, 2) * Rp.randomSign()}, ${ Rp.bandomInt(1000, -2)});
                  spotLight${i}.angle = ${math.random(Math.PI)};
                  spotLight${i}.distance = ${Rp.bandom(1000, -3)};
                  spotLight${i}.exponent = ${math.random(20)};
                  scene.add(spotLight${i});
                  \n`);
                }

                // pointlights

                for (let i = 0; i < pointLights; i++) {

                  let pointLightColor = randomColor(params, 1);
                  console.log(`pointLightColor${i} `, pointLightColor);

                    outf.write(`
                  var pointLight${i} = new THREE.PointLight(${pointLightColor});
                  pointLight${i}.position.set(${Rp.bandomInt(dimensions.outputWidth / 2, 2) * Rp.randomSign()}, ${Rp.bandomInt(dimensions.outputHeight / 2, 2) * Rp.randomSign()}, ${ math.randomInt(-100, 1000)});
                  pointLight${i}.intensity = ${math.random(0, 3)};
                  pointLight${i}.distance = ${Rp.bandom(1000, -3)};
                  scene.add(pointLight${i});
                  \n`);
                }

                // ambient light
                outf.write(`
                  var ambientLight = new THREE.AmbientLight(${params.ambientLight});
                  scene.add(ambientLight);

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

                  renderer.setSize( width, height );

                  document.body.appendChild( renderer.domElement );

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

                outf.write(`}\n`); // end draw()

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

                outf.write(`
                  </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>mix lines & cylinders<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'));

    var isDev = /Apple_Terminal|iterm\.app/i.test(process.env.TERM_PROGRAM);

    // 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);
    }

    function randomColor(params, maxLightness) {
        let k = math.randomInt(params.xy.length);
        let yy = params.xy[k].y;
        let xx = params.xy[k].x;

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

        let color = `0x${num2hex(math.floor(rgb.r * maxLightness))}${num2hex(math.floor(rgb.g * maxLightness))}${num2hex(math.floor(rgb.b * maxLightness))}`;

        return color;
    }

    //------------- shapes

    let shapeLine = {
        fn: "ln",
        sample: (isDev ? 0.2 : 0.4)
    };

    let shapeCylinder = {
        fn: "cyl",
        sample: 1
    };

    let shapes = [
        {
            shape: shapeLine,
            weight: 100
        },
        {
            shape: shapeCylinder,
            weight: 100
        }
    ];

    // ------------ 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;

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

            let outputWidth = inputWidth;
            let outputHeight = inputHeight;

            let dimensions = {
                inputWidth,
                inputHeight,
                outputWidth,
                outputHeight
            };

            let maxz = 100 + Rp.bandomInt(outputHeight - 100, 3);

            let maxRadius = 1 + Rp.bandomInt(128, 2);
            let maxRadius2 = (maxRadius < 10 ? 10 + Rp.bandomInt(128, 2) : (math.random() < 0.5 ? maxRadius : 1 + Rp.bandomInt(128, 2)));

            let maxShininess = math.randomInt(0, 256);

            let spotLights = Rp.bandomInt(4, 1);
            let pointLights = (spotLights === 0 ? 1 : 0) + Rp.bandomInt(4, 1);

            let segments = math.randomInt(1, 65);

            let wireframe = (maxRadius > 12) && (math.random() < 0.25);

            let minOpacity = math.round(100 * math.random()) / 100;
            let maxOpacity = 1;

            if (wireframe) {
                maxOpacity = math.round(100 * math.random(minOpacity, 1)) / 100;
            }

            let openEnded = (math.random() < 0.5);

            let arc = (math.random() < 0.75) ? 2 * Math.PI : math.round(100 * math.random(0, 2 * Math.PI)) / 100;

            let rotation = {
                x: math.random(0, 2 * Math.PI),
                y: math.random(0, 2 * Math.PI),
                z: math.random(0, 2 * Math.PI)
            };

            let fieldOfView = 60 + Rp.bandom(30, 2);

            let params = {
                maxz,
                maxRadius,
                maxRadius2,
                maxShininess,
                spotLights,
                pointLights,
                segments,
                wireframe,
                minOpacity,
                maxOpacity,
                openEnded,
                arc,
                rotation,
                fieldOfView
            };

            console.log('params ', JSON.stringify(params, null, 2));

            params.dimensions = dimensions;

            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`);

                outf.write(`<script>\n`);

                // add line
                outf.write(`
                function ln(scene, options) {
                  var geometry = new THREE.Geometry();

                  geometry.vertices.push(
                    new THREE.Vector3( options.x, options.y, 0 ),
                    new THREE.Vector3( options.x, options.y, options.z )
                  );

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

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

                  scene.add(line);
                }
                \n`);

                // add cylinder

                outf.write(`
                function cyl(scene, options) {

                  var geometry = new THREE.CylinderGeometry(options.radius, options.radius2, options.z, ${params.segments}, 1, ${params.openEnded}, 0, ${params.arc});

                  var materials = [
                  new THREE.MeshPhongMaterial( {
                    color: options.color,
                    opacity: options.opacity,
                    transparent: true,
                    shininess: options.shininess
                  } )
                ];
                \n`);

                if (params.wireframe) {
                    outf.write(`
                    materials.push(

                      new THREE.MeshBasicMaterial( {
                        color: options.color,
                        wireframe: true
                      } )

                    );
                  \n`);
                }

                outf.write(`
                  var cylinder = new THREE.SceneUtils.createMultiMaterialObject( geometry, materials );

                  cylinder.rotation.x = ${params.rotation.x};
                  cylinder.rotation.y = ${params.rotation.y};
                  cylinder.rotation.z = ${params.rotation.z};

                  cylinder.position.x = options.x;
                  cylinder.position.y = options.y;
                  cylinder.position.z = options.z / 2;

                  scene.add(cylinder);
                }
                \n`);

                outf.write(`
                  draw();

                  function draw() {

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

                      var scene = new THREE.Scene();
                      var s = scene;
                \n`);

                let xy = [];

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

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

                // use a small % of points otherwise too big to render

                let shape = Rp.wandom(shapes).shape;

                // let maxRadius = Math.max(params.maxRadius, params.maxRadius2);

                // sample = sample / (maxRadius * maxRadius);

                xy = R.sortBy(() => math.random(), xy);
                xy = R.take(xy.length * shape.sample, xy);

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

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

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

                    let hsl = clr.rgb2hsl(rgb);

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

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

                    let radius = params.maxRadius;
                    let radius2 = params.maxRadius2;

                    let opacity = params.minOpacity + (params.maxOpacity - params.minOpacity) * hsl.l;

                    let shininess = params.maxShininess;

                    outf.write(`${shape.fn}(s, {
                      x: ${x3},
                      y: ${y3},
                      z: ${z3},
                      color: 0x${num2hex(rgb.r)}${num2hex(rgb.g)}${num2hex(rgb.b)},
                      radius: ${radius},
                      radius2: ${radius2},
                      opacity: ${opacity},
                      shininess: ${shininess}
                    });
                    \n`);
                }

                // end

                let backgroundColor = '0x000000';

                params.xy = xy;
                params.data = data;

                params.ambientLight = randomColor(params, 0.5);
                console.log('params.ambientLight ', params.ambientLight);

                let cameraPositionZ = 1000;

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

                  var camera = new THREE.PerspectiveCamera( ${params.fieldOfView}, width / height, 0.1, 1000 );

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

                  camera.lookAt(scene.position);
                  \n`);

                // spotlights

                for (let i = 0; i < spotLights; i++) {

                    let spotLightColor = randomColor(params, 1);
                    console.log(`spotLightColor${i} `, spotLightColor);

                    outf.write(`
                  var spotLight${i} = new THREE.SpotLight(${spotLightColor});
                  spotLight${i}.position.set(${Rp.bandomInt(dimensions.outputWidth / 2, 2) * Rp.randomSign()}, ${Rp.bandomInt(dimensions.outputHeight / 2, 2) * Rp.randomSign()}, ${ Rp.bandomInt(1000, -2)});
                  spotLight${i}.angle = ${math.random(Math.PI)};
                  spotLight${i}.distance = ${Rp.bandom(1000, -3)};
                  spotLight${i}.exponent = ${math.random(20)};
                  scene.add(spotLight${i});
                  \n`);
                }

                // pointlights

                for (let i = 0; i < pointLights; i++) {

                    let pointLightColor = randomColor(params, 1);
                    console.log(`pointLightColor${i} `, pointLightColor);

                    outf.write(`
                  var pointLight${i} = new THREE.PointLight(${pointLightColor});
                  pointLight${i}.position.set(${Rp.bandomInt(dimensions.outputWidth / 2, 2) * Rp.randomSign()}, ${Rp.bandomInt(dimensions.outputHeight / 2, 2) * Rp.randomSign()}, ${ math.randomInt(-100, 1000)});
                  pointLight${i}.intensity = ${math.random(0, 3)};
                  pointLight${i}.distance = ${Rp.bandom(1000, -3)};
                  scene.add(pointLight${i});
                  \n`);
                }

                // ambient light
                outf.write(`
                  var ambientLight = new THREE.AmbientLight(${params.ambientLight});
                  scene.add(ambientLight);

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

                  renderer.setSize( width, height );

                  document.body.appendChild( renderer.domElement );

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

                outf.write(`}\n`); // end draw()

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

                outf.write(`
                  </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>require('./proof')(8, function (step, once, deepEqual, ok) {
    var stream = require('stream')
    step(function () {
        var input = new stream.PassThrough()
        input.end('a=1', 'utf8')
        once(step, 'fixtures//verb', ['put'], input)
    }, function (response) {
        deepEqual(response.headers['content-type'], 'text/plain', 'content type')
        deepEqual(JSON.parse(response.body), { method: "PUT" }, 'body')
        var input = new stream.PassThrough()
        input.end('_method=put', 'utf8')
        once(step, 'fixtures//verb', ['post'], input)
    }, function (response) {
        deepEqual(response.headers['content-type'], 'text/plain', 'content type')
        deepEqual(JSON.parse(response.body), { method: 'POST' }, 'body')
        var input = new stream.PassThrough()
        input.end('a=1', 'utf8')
        once(step, 'fixtures//verb', ['delete'], input)
    }, function (response) {
        deepEqual(response.headers['content-type'], 'text/plain', 'content type')
        deepEqual(JSON.parse(response.body), { method: 'DELETE' }, 'body')
        var input = new stream.PassThrough()
        input.end('a=1', 'utf8')
        once(step, 'fixtures//verb', ['patch'], input)
    }, function (response) {
        deepEqual(response.headers['content-type'], 'text/plain', 'content type')
        deepEqual(JSON.parse(response.body), { method: 'PATCH' }, 'body')
    })
})
<commit_msg>Remove `ok` parameter from verb test.<commit_after>require('./proof')(8, function (step, once, deepEqual) {
    var stream = require('stream')
    step(function () {
        var input = new stream.PassThrough()
        input.end('a=1', 'utf8')
        once(step, 'fixtures//verb', ['put'], input)
    }, function (response) {
        deepEqual(response.headers['content-type'], 'text/plain', 'content type')
        deepEqual(JSON.parse(response.body), { method: "PUT" }, 'body')
        var input = new stream.PassThrough()
        input.end('_method=put', 'utf8')
        once(step, 'fixtures//verb', ['post'], input)
    }, function (response) {
        deepEqual(response.headers['content-type'], 'text/plain', 'content type')
        deepEqual(JSON.parse(response.body), { method: 'POST' }, 'body')
        var input = new stream.PassThrough()
        input.end('a=1', 'utf8')
        once(step, 'fixtures//verb', ['delete'], input)
    }, function (response) {
        deepEqual(response.headers['content-type'], 'text/plain', 'content type')
        deepEqual(JSON.parse(response.body), { method: 'DELETE' }, 'body')
        var input = new stream.PassThrough()
        input.end('a=1', 'utf8')
        once(step, 'fixtures//verb', ['patch'], input)
    }, function (response) {
        deepEqual(response.headers['content-type'], 'text/plain', 'content type')
        deepEqual(JSON.parse(response.body), { method: 'PATCH' }, 'body')
    })
})
<|endoftext|>


<commit_before>/* Base view */

var dust = require('dustjs-linkedin'),
	Promise = require('./util/promise'),
	tagPattern = /<(\w+)[^>]*>/,
	attrPattern = /\s+(\S+)\s*=\s*("[^"]*"|'[^']*')/g;

/* Extract wrapping element, attributes and contents */
function parseElement(html, callback) {
	var m = html.match(tagPattern);    // match first start tag

	if (m) {
		var tag = m[0], tagName = m[1],
			endTag = '</' + tagName + '>',
			endIndex = html.lastIndexOf('</');

		// check that the last end matches the start tag
		// and that there is no content after it

		if (html.slice(endIndex).replace(/\s+/g, '') == endTag)
			return callback(html.slice(m.index + tag.length, endIndex), tag, endTag, tagName);
	}

	return callback(html);
}

function attributes(tag) {    // extract attributes from tag string
	var attrs = {}, m;

	while (m = attrPattern.exec(tag))
		attrs[m[1]] = m[2].slice(1, -1);

	return attrs;
}

function updateElement(html, tag, endTag, tagName) {
	if (tag && !this.rendered) {
		if (this.$el.is(tagName)) {
			this.$el.attr(attributes(tag));
		} else {
			var $oldEl = this.$el;
			var attrs = _.object(_.map($oldEl[0].attributes, function(attr) {
				return [ attr.name, attr.value ];
			}));
			var queue = $oldEl.queue();
			this.$el.clearQueue();
			this.setElement(tag + endTag);
			this.$el.attr(attrs);
			$oldEl.replaceWith(this.el);
			this.$el.queue(queue);
		}
	}
	this.el.innerHTML = html;
	this.rendered = true;
}

var View = Backbone.View.extend({
	// Promise factory function using view as the context with callbacks
	Promise: function(resolver) {
		return Promise(resolver, this);
	},

	constructor: function(options) {
		_.extend(this, _.pick(options, 'template', 'parent'));

		// we clone to prevent views referencing the same object
		this.data = options && options.data ? _.clone(options.data) : {};

		this.elements = {};

		Backbone.View.apply(this, arguments);

		if(_.isString(this.model))
			this.model = new this.app.models[this.model]();

		if(_.isString(this.collection))
			this.collection = new this.app.collections[this.collection]();

		this.rendered = (this.el && this.el.firstChild) != null;

		if (!this.rendered) this.render();
		else if (this.attach) this.attach();

		// this.ready(callbacks)
		//

		this.ready = this.ready || $.Callbacks('once memory').fireWith(this).add;
	},

	convertElements: function() {
		var view = this;
		_.each(this.elements, function(element, key) {
			if(/^\$/.test(key)) view.elements[key.slice(1)] = element[0];
		});
	},

	initializeViews: function() {
		var _view = this;

		_view.$('[data-view]').each(function() {
			var viewName = $(this).data('view');

			var View = _view.app.views[viewName];

			// TODO destroy/remove all nested views when a PageView is removed.
			if (View) new View({ el: this, data: _view.data });
		});
	},

	render: function() {
		var _view = this;

		var data = _.result(_view, 'data');

		var args = arguments[0] === true ? _.rest(arguments) : null;

		if(_view.app.user)
			data.user = _view.app.user.toJSON();

		if (_view.model) {
			var modelData = _view.model.toJSON();

			if(args)
				data[_view.model.name.toCamelCase()] = modelData;
			else
				_.extend(data, modelData);
		}

		_view.renderTemplate(data).ready(args || arguments);

		return _view;
	},

	// Render Dust template and update element, using the fx queue

	renderTemplate: function(data) {
		var templateName = this.template,
			rendering = this.Promise(function(resolve, reject) {
			this.$el.queue(function(next, hooks) {
				// hooks.stop() is called if queue is stopped using $el.stop() or $el.finish()
				hooks.stop = function() {
					reject();
				};

				dust.render(templateName, data || {}, function(err, out) {
					if (err)
						reject(err);
					else
						parseElement(out, resolve);
				});
			});
		}).then(updateElement.bind(this))
			.done(this.attach, function() { this.$el.dequeue(); })
			.fail(function(err) {
				if (err) console.error(err);
			});

		this.ready = rendering.done;
		this.rendering = rendering;

		return this;
	},

	// animated enter
	enter: function() {
		this.$el.enter.apply(this.$el, arguments);
		return this;
	},

	alternate: function() {
		this.$el.alternate();
	},

	// animated remove
	remove: function() {
		this.$el.leave();
		return this.stopListening();
	}
});

View.prototype._remove = View.prototype.remove;
View.prototype._render = View.prototype.render;

module.exports = View;
<commit_msg>Return instance (this) in alternate()<commit_after>/* Base view */

var dust = require('dustjs-linkedin'),
	Promise = require('./util/promise'),
	tagPattern = /<(\w+)[^>]*>/,
	attrPattern = /\s+(\S+)\s*=\s*("[^"]*"|'[^']*')/g;

/* Extract wrapping element, attributes and contents */
function parseElement(html, callback) {
	var m = html.match(tagPattern);    // match first start tag

	if (m) {
		var tag = m[0], tagName = m[1],
			endTag = '</' + tagName + '>',
			endIndex = html.lastIndexOf('</');

		// check that the last end matches the start tag
		// and that there is no content after it

		if (html.slice(endIndex).replace(/\s+/g, '') == endTag)
			return callback(html.slice(m.index + tag.length, endIndex), tag, endTag, tagName);
	}

	return callback(html);
}

function attributes(tag) {    // extract attributes from tag string
	var attrs = {}, m;

	while (m = attrPattern.exec(tag))
		attrs[m[1]] = m[2].slice(1, -1);

	return attrs;
}

function updateElement(html, tag, endTag, tagName) {
	if (tag && !this.rendered) {
		if (this.$el.is(tagName)) {
			this.$el.attr(attributes(tag));
		} else {
			var $oldEl = this.$el;
			var attrs = _.object(_.map($oldEl[0].attributes, function(attr) {
				return [ attr.name, attr.value ];
			}));
			var queue = $oldEl.queue();
			this.$el.clearQueue();
			this.setElement(tag + endTag);
			this.$el.attr(attrs);
			$oldEl.replaceWith(this.el);
			this.$el.queue(queue);
		}
	}
	this.el.innerHTML = html;
	this.rendered = true;
}

var View = Backbone.View.extend({
	// Promise factory function using view as the context with callbacks
	Promise: function(resolver) {
		return Promise(resolver, this);
	},

	constructor: function(options) {
		_.extend(this, _.pick(options, 'template', 'parent'));

		// we clone to prevent views referencing the same object
		this.data = options && options.data ? _.clone(options.data) : {};

		this.elements = {};

		Backbone.View.apply(this, arguments);

		if(_.isString(this.model))
			this.model = new this.app.models[this.model]();

		if(_.isString(this.collection))
			this.collection = new this.app.collections[this.collection]();

		this.rendered = (this.el && this.el.firstChild) != null;

		if (!this.rendered) this.render();
		else if (this.attach) this.attach();

		// this.ready(callbacks)
		//

		this.ready = this.ready || $.Callbacks('once memory').fireWith(this).add;
	},

	convertElements: function() {
		var view = this;
		_.each(this.elements, function(element, key) {
			if(/^\$/.test(key)) view.elements[key.slice(1)] = element[0];
		});
	},

	initializeViews: function() {
		var _view = this;

		_view.$('[data-view]').each(function() {
			var viewName = $(this).data('view');

			var View = _view.app.views[viewName];

			// TODO destroy/remove all nested views when a PageView is removed.
			if (View) new View({ el: this, data: _view.data });
		});
	},

	render: function() {
		var _view = this;

		var data = _.result(_view, 'data');

		var args = arguments[0] === true ? _.rest(arguments) : null;

		if(_view.app.user)
			data.user = _view.app.user.toJSON();

		if (_view.model) {
			var modelData = _view.model.toJSON();

			if(args)
				data[_view.model.name.toCamelCase()] = modelData;
			else
				_.extend(data, modelData);
		}

		_view.renderTemplate(data).ready(args || arguments);

		return _view;
	},

	// Render Dust template and update element, using the fx queue

	renderTemplate: function(data) {
		var templateName = this.template,
			rendering = this.Promise(function(resolve, reject) {
			this.$el.queue(function(next, hooks) {
				// hooks.stop() is called if queue is stopped using $el.stop() or $el.finish()
				hooks.stop = function() {
					reject();
				};

				dust.render(templateName, data || {}, function(err, out) {
					if (err)
						reject(err);
					else
						parseElement(out, resolve);
				});
			});
		}).then(updateElement.bind(this))
			.done(this.attach, function() { this.$el.dequeue(); })
			.fail(function(err) {
				if (err) console.error(err);
			});

		this.ready = rendering.done;
		this.rendering = rendering;

		return this;
	},

	// animated enter
	enter: function() {
		this.$el.enter.apply(this.$el, arguments);
		return this;
	},

	alternate: function() {
		this.$el.alternate();
		return this;
	},

	// animated remove
	remove: function() {
		this.$el.leave();
		return this.stopListening();
	}
});

View.prototype._remove = View.prototype.remove;
View.prototype._render = View.prototype.render;

module.exports = View;
<|endoftext|>


<commit_before>/*
 *	Copyright 2015 Calixto Jorge calixto.jorge@gmail.com
 *
 *	Licensed under the Apache License, Version 2.0 (the "License");
 *	you may not use this file except in compliance with the License.
 *	You may obtain a copy of the License at
 *
 *	    http://www.apache.org/licenses/LICENSE-2.0
 *
 *	Unless required by applicable law or agreed to in writing, software
 *	distributed under the License is distributed on an "AS IS" BASIS,
 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	See the License for the specific language governing permissions and
 *	limitations under the License.
 */

/**
 * A router method of this plugin
 * @param {String} method
 * @param {Json} params
 * @returns {Json}
 */
$.fn.view = function(method,params, callbackDebug){
    switch(method){
        case 'assign':
            return $(this).assign(params, callbackDebug);
            break;
        case 'extract':
            return $(this).extract(params, callbackDebug);
        case 'iterate':
            var options = $.extend({
                'template':$(),
                'collection':[],
                'callbackItem':false,
                'cleanBeforeInit':false
            },params);
            return $(this).iterate(options.template, options.collection, options.callbackItem, options.cleanBeforeInit);
            break;
        case 'extractCollection':
            var options = $.extend({
                'valueObject':{},
                'selector':''
            },params);
            return $(this).extractCollection(options.valueObject, options.selector, callbackDebug);
    }
};

/**
 * Default find and add $(this) too if selector found
 * @param {type} selector
 * @returns {jQuery}
 */
$.fn.findMeToo = function(selector){
    if($(this).is(selector)){
        return $(this).add($(this).find(selector));
    }else{
        return $(this).find(selector);
    }
};
/**
 * Method used to set css
 * @param {String} property
 * @param {String} value
 * @returns {jQuery}
 */
$.fn.viewDataCss = function(property, value) {
    var $this = $(this);
    if (!$(this)[0])
        return $(this);
    $.each($(this), function() {
        var attr = $this.attr('data-css-' + property);
        if (!attr) {
            console.error(this, 'not found value of: ' + 'data-css-' + attr);
            return true;
        }
        var attrs = attr.split('|');
        for (var j in attrs) {
            $(this).css(attrs[j], value);
        }
    });
    return $(this);
};

/**
 * Method used to set property
 * @param string property
 * @param string value
 * @returns void
 */
$.fn.viewDataProp = function(property, valor) {
    var $this = $(this);
    if (!$this[0])
        return;
    $.each($this, function() {
        var attr = $this.attr('data-prop-' + property);
        if(!attr){
            console.warning($this, 'not found value of: ' + 'data-prop-' + property);
            return true;
        }
        var attrs = attr.split('|');
        if(attrs.length < 2){
            console.warning($this, 'not found value of: ' + 'data-prop-' + property + ' expected something like "checked|functionValidateCheck"');
            return true;
        };
        try{
            var fn = eval(attrs[1]);
            $this.prop(attrs[0],fn(valor, $this));
        }catch (e){
            console.warning($this, 'it was not possible to apply in ' + 'data-prop-' + property + ' property ' + attrs[0] + ' or function ' + attrs[1] + ' not exists.');
        }
    });
};
/**
 * method to create property
 * @param string property
 * @param string value
 * @returns void
 */
$.fn.viewDataAttr = function(property, valor) {
    var $this = $(this);
    if (!$this[0])
        return;
    $.each($this, function() {
        var attr = $this.attr('data-attr-' + property);
        if(!attr){
            console.warning($this, 'value of ' + 'data-attr-' + property + ' is not found.');
            return true;
        }
        var attrs = attr.split('|');
        for (var j in attrs) {
            $this.attr(attrs[j], valor);
        }
    });
};
/**
 * Assign values of json object in to jquery object
 * <element  data-val-{index} to execute jquery "val" method in element
 * <element data-html-{index} to execute jquery "html" method in element
 * <element data-attr-{index}="{new-attribute-name}" adds the element of the index value in the attribute-related
 * <element data-attr-{index}="{new-attribute-name|[callback-for-value-in]}" adds the element of the index value in the attribute related, with callback for value
 * <element data-prop-{index}="{property-name}" set element property
 * <element data-prop-{index}="{property-name|callback-for-value-in}" set element property, with callback for value
 *      Samples:
 *
 *

 *
 *          <input type="text" data-val-ID_PESSOA />
 *

 *      will be executed on  tag:
 *          $(this).find('[data-attr-ST_LINK_PAGINA="href"]').attr('href',ST_LINK_PAGINA);
 *          $(this).find('[data-html-DS_TEXTO]').html(DS_TEXTO);
 *      will be executed on <input> tag:
 *          $(this).find('[data-val-ID_PESSOA]').val(ID_PESSOA);
 * @param Object json
 * @param function to debug
 * @returns jQuery
 */
$.fn.assign = function(obj, fnDebug) {
    var $this = $(this);
    fnDebug = fnDebug || function() {
    };
    if (!$this.length)
        return;
    if (fnDebug) {
        for (var i in obj) {
            var $html = $this.findMeToo('[data-html-' + i + ']');
            $html.html(obj[i]);
            fnDebug($html, obj[i], 'html', i);
            var $css = $this.findMeToo('[data-css-' + i + ']');
            $css.viewDataCss(i, obj[i]);
            fnDebug($css, obj[i], 'css', i);
            var $val = $this.findMeToo('[data-val-' + i + ']');
            $val.val(obj[i]);
            fnDebug($val, obj[i], 'val', i);
            var $attr = $this.findMeToo('[data-attr-' + i + ']');
            $attr.viewDataAttr(i, obj[i]);
            fnDebug($attr, obj[i], 'attr', i);
            var $prop = $this.findMeToo('[data-prop-' + i + ']');
            $prop.viewDataProp(i, obj[i]);
            fnDebug($prop, obj[i], 'prop', i);
        }
    } else {
        for (var i in obj) {
            $this.findMeToo('[data-html-' + i + ']').html(obj[i]);
            $this.findMeToo('[data-val-' + i + ']').val(obj[i]);
            $this.findMeToo('[data-attr-' + i + ']').viewDataAttr(i, obj[i]);
            $this.findMeToo('[data-pro-' + i + ']').viewDataProp(i, obj[i]);
            $this.findMeToo('[data-css-' + i + ']').viewDataCss(i, obj[i]);
        }
    }
    return $this;
};
/**
 * returns a result set for each item found
 * @param json attributes for search
 * @param string selector for item
 * @param function to debug
 * @returns Array with json objects
 */
$.fn.extractCollection = function(obj, seletor, fn) {
    var res = [];
    $.each($(this).find(seletor), function() {
        res.push($(this).extract($.extend(true, {}, obj), fn));
    });
    return res;
};
/**
 * returns a json completed for element
 * @param Object json
 * @param function to debug
 * @returns Object json
 */
$.fn.extract = function(objeto, fn) {
    fn = fn || function() {
    };
    var $this = $(this);
    if (!$this[0])
        return objeto;
    if (fn) {
        for (var i in objeto) {
            var attr = $this.findMeToo('[data-' + i + ']').attr('data-' + i);
            var val = $this.findMeToo('[data-val-' + i + ']').val();
            var html = $this.findMeToo('[data-html-' + i + ']').html();
            objeto[i] = attr ? attr : (val ? val : (html ? html : null));
            fn(i, objeto[i], attr, val, html);
        }
    } else {
        for (var i in objeto) {
            var attr = $this.findMeToo('[data-' + i + ']').attr('data-' + i);
            var val = $this.findMeToo('[data-val-' + i + ']').val();
            var html = $this.findMeToo('[data-html-' + i + ']').html();
            objeto[i] = attr ? attr : (val ? val : (html ? html : null));
        }
    }
    return objeto;
};
/**
 * Fills the element with several templates filled with the collection object
 * @param jQuery template for to cloning in loop
 * @param Array collection of json for assign in template
 * @param function for callback in item loop
 * @param boolean to clean before init operation
 * @returns jQuery
 */
$.fn.iterate = function($tpl, collection, callbackItem, cleanBeforeInit, callbackDebug) {
    cleanBeforeInit = cleanBeforeInit || false;
    if (cleanBeforeInit) {
        $(this).html('');
    }
    if (callbackItem) {
        for (i in collection) {
            var $clone = $tpl.clone(true);
            $(this).append($clone.assign(collection[i]), callbackDebug)
            callbackItem($clone, collection[i]);
        }
    } else {
        for (i in collection) {
            $(this).append($tpl.clone(true).assign(collection[i]))
        }
    }
    return $(this);
};
<commit_msg>Adicionando método replace<commit_after>/*
 *	Copyright 2015 Calixto Jorge calixto.jorge@gmail.com
 *
 *	Licensed under the Apache License, Version 2.0 (the "License");
 *	you may not use this file except in compliance with the License.
 *	You may obtain a copy of the License at
 *
 *	    http://www.apache.org/licenses/LICENSE-2.0
 *
 *	Unless required by applicable law or agreed to in writing, software
 *	distributed under the License is distributed on an "AS IS" BASIS,
 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	See the License for the specific language governing permissions and
 *	limitations under the License.
 */

/**
 * A router method of this plugin
 * @param {String} method
 * @param {Json} params
 * @returns {Json}
 */
$.fn.view = function(method,params, callbackDebug){
    switch(method){
        case 'assign':
            return $(this).assign(params, callbackDebug);
            break;
        case 'unreplace':
            return $(this).viewDataUnreplace();
            break;
        case 'extract':
            return $(this).extract(params, callbackDebug);
        case 'iterate':
            var options = $.extend({
                'template':$(),
                'collection':[],
                'callbackItem':false,
                'cleanBeforeInit':false
            },params);
            return $(this).iterate(options.template, options.collection, options.callbackItem, options.cleanBeforeInit);
            break;
        case 'extractCollection':
            var options = $.extend({
                'valueObject':{},
                'selector':''
            },params);
            return $(this).extractCollection(options.valueObject, options.selector, callbackDebug);
    }
};

/**
 * Default find and add $(this) too if selector found
 * @param {type} selector
 * @returns {jQuery}
 */
$.fn.findMeToo = function(selector){
    if($(this).is(selector)){
        return $(this).add($(this).find(selector));
    }else{
        return $(this).find(selector);
    }
};
/**
 * Method used to set css
 * @param {String} property
 * @param {String} value
 * @returns {jQuery}
 */
$.fn.viewDataCss = function(property, value) {
    var $this = $(this);
    if (!$(this)[0])
        return $(this);
    $.each($this, function() {
        var attr = $this.attr('data-css-' + property);
        if(!attr){
            console.log($this, 'value of ' + 'data-css-' + property + ' is not found.');
            return true;
        }
        var attrs = attr.split('|');
        $.each(attrs,function(j,v){
            $this.css(attrs[j], value);
        });
    });
    return $(this);
};

/**
 * Method used to set property
 * @param string property
 * @param string value
 * @returns void
 */
$.fn.viewDataProp = function(property, valor) {
    var $this = $(this);
    if (!$this[0])
        return;
    $.each($this, function() {
        var attr = $this.attr('data-prop-' + property);
        if(!attr){
            console.log($this, 'not found value of: ' + 'data-prop-' + property);
            return true;
        }
        var attrs = attr.split('|');
        if(attrs.length < 2){
            console.log($this, 'not found value of: ' + 'data-prop-' + property + ' expected something like "checked|functionValidateCheck"');
            return true;
        };
        try{
            var fn = eval(attrs[1]);
            $this.prop(attrs[0],fn(valor, $this));
        }catch (e){
            console.log($this, 'it was not possible to apply in ' + 'data-prop-' + property + ' property ' + attrs[0] + ' or function ' + attrs[1] + ' not exists.');
        }
    });
};
/**
 * method to create property
 * @param string property
 * @param string value
 * @returns void
 */
$.fn.viewDataAttr = function(property, valor) {
    var $this = $(this);
    if (!$this[0])
        return;
    $.each($this, function() {
        var attr = $this.attr('data-attr-' + property);
        if(!attr){
            console.log($this, 'value of ' + 'data-attr-' + property + ' is not found.');
            return true;
        }
        var attrs = attr.split('|');
        $.each(attrs,function(j,v){
            $this.attr(attrs[j], valor);
        });
    });
};
$.fn.viewDataUnreplace = function(){
    $.each($(this),function(){
        var $this = $(this);
        $.each($this.findMeToo('[data-view-replaced="true"]'),function(){
            $el = $(this);
            $.each($el.data('data-view-attrs-replaced'),function(attribute, value){
                $el.attr(attribute, value);
            });
        });
    });
    return $(this);
};
$.fn.viewStoreBeforeReplace = function () {
    $.each($(this),function(){
        var $this = $(this);
        if(!$this.attr('data-view-replaced')){
            var replace = {};
            var reg = /^data-replace/;
            $.each($this,function(){
                $.each(this.attributes,function(){
                    var attribute = this;
                    if(reg.test(attribute.name)){
                        $.each($this.attr(attribute.name).split('|'), function(i,configured){
                            replace[configured] = $this.attr(configured);
                        });
                    }
                });
            });
            $this.data('data-view-attrs-replaced',replace);
            $this.attr('data-view-replaced','true');
        }

    });
};
/**
 * method to replace of property
 * @param string property
 * @param string value
 * @returns void
 */
$.fn.viewDataReplace = function(property, valor) {
    var $this = $(this);
    if (!$this[0])
        return;
    $.each($this, function() {
        var $el = $(this);
        var attr = $el.attr('data-replace-' + property);
        if(!attr){
            console.log($el, 'value of ' + 'data-attr-' + property + ' is not found.');
            return true;
        }
        var attrs = attr.split('|');
        $.each(attrs,function(j,attr){
            $el.attr(attr, $el.attr(attr).replaceAll('{' + property + '}', valor));
        });
    });
};
/**
 * Assign values of json object in to jquery object
 * <element  data-val-{index} to execute jquery "val" method in element
 * <element data-html-{index} to execute jquery "html" method in element
 * <element data-attr-{index}="{new-attribute-name}" adds the element of the index value in the attribute-related
 * <element data-attr-{index}="{new-attribute-name|[callback-for-value-in]}" adds the element of the index value in the attribute related, with callback for value
 * <element data-prop-{index}="{property-name}" set element property
 * <element data-prop-{index}="{property-name|callback-for-value-in}" set element property, with callback for value
 *      Samples:
 *
 *

 *
 *          <input type="text" data-val-ID_PESSOA />
 *

 *      will be executed on  tag:
 *          $(this).find('[data-attr-ST_LINK_PAGINA="href"]').attr('href',ST_LINK_PAGINA);
 *          $(this).find('[data-html-DS_TEXTO]').html(DS_TEXTO);
 *      will be executed on <input> tag:
 *          $(this).find('[data-val-ID_PESSOA]').val(ID_PESSOA);
 * @param Object json
 * @param function to debug
 * @returns jQuery
 */
$.fn.assign = function(obj, fnDebug) {
    var $this = $(this);
    fnDebug = fnDebug || function() {
    };
    if (!$this.length)
        return;
    if (fnDebug) {
        for (var i in obj) {
            var $html = $this.findMeToo('[data-html-' + i + ']');
            $html.html(obj[i]);
            fnDebug($html, obj[i], 'html', i);
            var $val = $this.findMeToo('[data-val-' + i + ']');
            $val.val(obj[i]);
            fnDebug($val, obj[i], 'val', i);
            var $attr = $this.findMeToo('[data-attr-' + i + ']');
            $attr.viewDataAttr(i, obj[i]);
            fnDebug($attr, obj[i], 'attr', i);
            var $prop = $this.findMeToo('[data-prop-' + i + ']');
            $prop.viewDataProp(i, obj[i]);
            fnDebug($prop, obj[i], 'prop', i);
            var $css = $this.findMeToo('[data-css-' + i + ']');
            $css.viewDataCss(i, obj[i]);
            fnDebug($css, obj[i], 'css', i);
            var $replace = $this.findMeToo('[data-replace-' + i + ']');
            $replace.viewStoreBeforeReplace();
            $replace.viewDataReplace(i, obj[i]);
            fnDebug($replace, obj[i], 'replace', i);
        }
    } else {
        for (var i in obj) {
            $this.findMeToo('[data-html-' + i + ']').html(obj[i]);
            $this.findMeToo('[data-val-' + i + ']').val(obj[i]);
            $this.findMeToo('[data-attr-' + i + ']').viewDataAttr(i, obj[i]);
            $this.findMeToo('[data-prop-' + i + ']').viewDataProp(i, obj[i]);
            $this.findMeToo('[data-css-' + i + ']').viewDataCss(i, obj[i]);
            $this.findMeToo('[data-replace-' + i + ']').viewStoreBeforeReplace();
            $this.findMeToo('[data-replace-' + i + ']').viewDataReplace(i, obj[i]);
        }
    }
    return $this;
};
/**
 * returns a result set for each item found
 * @param json attributes for search
 * @param string selector for item
 * @param function to debug
 * @returns Array with json objects
 */
$.fn.extractCollection = function(obj, seletor, fn) {
    var res = [];
    $.each($(this).find(seletor), function() {
        res.push($(this).extract($.extend(true, {}, obj), fn));
    });
    return res;
};
/**
 * returns a json completed for element
 * @param Object json
 * @param function to debug
 * @returns Object json
 */
$.fn.extract = function(objeto, fn) {
    fn = fn || function() {
    };
    var $this = $(this);
    if (!$this[0])
        return objeto;
    if (fn) {
        for (var i in objeto) {
            var attr = $this.findMeToo('[data-' + i + ']').attr('data-' + i);
            var val = $this.findMeToo('[data-val-' + i + ']').val();
            var html = $this.findMeToo('[data-html-' + i + ']').html();
            objeto[i] = attr ? attr : (val ? val : (html ? html : null));
            fn(i, objeto[i], attr, val, html);
        }
    } else {
        for (var i in objeto) {
            var attr = $this.findMeToo('[data-' + i + ']').attr('data-' + i);
            var val = $this.findMeToo('[data-val-' + i + ']').val();
            var html = $this.findMeToo('[data-html-' + i + ']').html();
            objeto[i] = attr ? attr : (val ? val : (html ? html : null));
        }
    }
    return objeto;
};
/**
 * Fills the element with several templates filled with the collection object
 * @param jQuery template for to cloning in loop
 * @param Array collection of json for assign in template
 * @param function for callback in item loop
 * @param boolean to clean before init operation
 * @returns jQuery
 */
$.fn.iterate = function($tpl, collection, callbackItem, cleanBeforeInit, callbackDebug) {
    var $this = this;
    cleanBeforeInit = cleanBeforeInit || false;
    if (cleanBeforeInit) {
        $this.html('');
    }
    if (callbackItem) {
        $.each(collection,function(i,v){
            var $clone = $tpl.clone(true);
            $this.append($clone.assign(collection[i]), callbackDebug)
            callbackItem($clone, collection[i]);
        });
    } else {
        $.each(collection,function(i,v){
            $this.append($tpl.clone(true).assign(collection[i]))
        });
    }
    return $this;
};

/**
 * Replace all occurrences of a string
 * @param string search
 * @param string replacement
 * @returns {String}
 */
String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};
<|endoftext|>