<commit_before>// iVisDesigner - scripts/editor/ui.js
// Author: Donghao Ren
//
// LICENSE
//
// Copyright (c) 2014, The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
//    may be used to endorse or promote products derived from this software without
//    specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

IV.addListener("command:panels.reset", function() {
    $("#panel-schema").IVPanel({ left: 10, top: 10, width: 180, height: 400 }).IVPanel("show");
    $("#panel-objects").IVPanel({ left: 10, top: 420, width: 180, bottom: 10 }).IVPanel("show");
    $("#panel-tools").IVPanel({ left: 200, top: 10, right: 220, height: 38, min_height: 38 }).IVPanel("show");
    $("#panel-log").IVPanel({ left: 10, bottom: 10, right: 10, height: 100 }).IVPanel("hide");
    $("#panel-page").IVPanel({ vcenter: 0, bottom: 200, top: 60, width: 600 }).IVPanel("hide");
    $("#panel-style").IVPanel({ right: 10, top: 10, width: 200, height: 300 }).IVPanel("show");
    $("#panel-property").IVPanel({ right: 10, top: 320, width: 200, bottom: 10 }).IVPanel("show");
    $("#panel-inspector").IVPanel({ right: 220, bottom: 10, width: 200, height: 200 }).IVPanel("hide");
    $("#panel-pose").IVPanel({ right: 220, bottom: 10, width: 200, height: 200 }).IVPanel("hide");
    $("#panel-code-editor").IVPanel({ left: 200, bottom: 10, right: 220, height: 200 }).IVPanel("hide");
});
IV.raiseEvent("command:panels.reset");

IV.add("status", "string");
IV.listen("status", function(s) {
    $(".status-text").text(s);
});

(function() {
    // Mouse events.
    var mouse_state = false;

    IV.isTrackingMouse = function() { return mouse_state; }

    $(window).contextmenu(function(e) {
        if(e.target.tagName == "INPUT") return;
        e.preventDefault();
    });

    $("#view").mousedown(function(e) {
        var offsetX = e.pageX - $("#view").offset().left;
        var offsetY = e.pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: e.shiftKey };
        mouse_state = true;
        Editor.raise("view:mousedown", o);
        Editor.renderer.render();
    });
    $(window).mousemove(function(e) {
        var offsetX = e.pageX - $("#view").offset().left;
        var offsetY = e.pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: e.shiftKey };
        var w = $("#view").width();
        var h = $("#view").height();
        var insideView = offsetX >= 0 && offsetX < w && offsetY >= 0 && offsetY < h;
        if(mouse_state || insideView) {
            Editor.raise("view:mousemove", o);
            Editor.renderer.render();
        }
        return true;
    });
    $(window).mouseup(function(e) {
        var offsetX = e.pageX - $("#view").offset().left;
        var offsetY = e.pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: e.shiftKey };
        mouse_state = false;
        Editor.raise("view:mouseup", o);
        Editor.renderer.render();
        return true;
    });
    // For iPad like platforms:
    // attach the touchstart, touchmove, touchend event listeners.
    var view_elem = document.getElementById("view");
    var touch_state = false;
    view_elem.addEventListener('touchstart',function(e) {
        //if(e.target != view_elem && e.target != canvas_front) return;
        e.preventDefault();
        touch_state = true;
        var offsetX = e.touches[0].pageX - $("#view").offset().left;
        var offsetY = e.touches[0].pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: false };
        Editor.raise("view:mousedown", o);
        Editor.renderer.render();
    });
    view_elem.addEventListener('touchmove',function(e) {
        var offsetX = e.touches[0].pageX - $("#view").offset().left;
        var offsetY = e.touches[0].pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: false };
        Editor.raise("view:mousemove", o);
        Editor.renderer.render();
    });
    view_elem.addEventListener('touchend', function(e) {
        var offsetX = e.changedTouches[0].pageX - $("#view").offset().left;
        var offsetY = e.changedTouches[0].pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: false };
        Editor.raise("view:mouseup", o);
        Editor.renderer.render();
    });

    IV.log = function(str) {
        var s;
        if(typeof(str) == "string") s = str;
        else s = JSON.stringify(str, null, " ");
        $("#log-container > ul").prepend($("

").append($("

").text(s)));
    };

    Editor.status = {
        start: function() {
            $(".status-text").html("");
            return this;
        },
        add: function(info) {
            this.append(info);
            return this;
        },
        append: function(info) { // append will return a descriptor, while add return the obj.
            var sp = $("").text(info);
            $(".status-text").append(sp);
            var ctx = {
                set: function(info) {
                    sp.text(info);
                }
            };
            return ctx;
        },
        end: function() {
            $(".status-text").html("");
            return this;
        }
    };

    var editor_messages = {};

    Editor.showMessage = function(str) {
        var s;
        if(editor_messages[str]) {
            s = editor_messages[str];
            clearTimeout(s.data().timeout);
        } else {
            s = IV._E("div").append(IV._E("span", type ? "msg-" + type : "message", str));
            editor_messages[str] = s;
            $("#editor-messages").append(s);
        }
        s.data().timeout = setTimeout(function() {
            s.remove();
            delete editor_messages[str];
        }, 2000);
    };

    $(window).keydown(function(e) {
        if(e.keyCode == 8 && e.target == document.body) {
            e.preventDefault();
        }
    });
    $(document).bind('touchmove', function(e) {
        e.preventDefault();
    });

    var codemirror = CodeMirror(document.getElementById("code-editor-container"), {
        value: "// Input Javascript code here.\n",
        lineNumbers: true,
        indentUnit: 4,
        tabSize: 4,
        keyMap: "sublime",
        theme: "monokai",
        lineNumbers: true,
        matchBrackets: true,
        showCursorWhenSelecting: true,
        mode: "javascript"
    });
    $("#code-editor-remote-run").click(function() {
        var code = codemirror.getSelection();
        IV.allosphere.postMessage({
            type: "eval",
            script: code
        });
    });
    $("#code-editor-local-run").click(function() {
        var code = codemirror.getSelection();
        eval(code);
    });
    var predefined_codes = { };
    predefined_codes["sample"] = { name: "Sample", code: "alert('Hello World!');" };
    predefined_codes["launch-test"] = { name: "Launch Test", code: IV.multiline(function() {/*
        IV.allosphere.postMessage({
            type: "viewport.launch",
            name: "test",
            command: "java",
            options: {
                cwd: "/Users/donghao/Documents/Projects/iVisDesigner/nodejs/allosphere/jni"
            },
            arguments: ["Test"],
            textures: [
              { key: "test", width: 100, height: 100 }
            ]
        });

        IV.editor.actions.add(new IV.actions.SetDirectly(IV.editor.workspace, "viewport_poses", [
          {
            name: "test",
            key: "test",
            pose: {
              center: new IV.Vector3(5, 0, 0),
              normal: new IV.Vector3(-1, 0, 0),
              up: new IV.Vector3(0, 0, 1),
              width: 4
            }
          }
        ])); IV.editor.actions.commit();
    */}) };
    predefined_codes["CyberViz"] = { name: "CyberViz Launch", code: IV.multiline(function() {/*
        IV.allosphere.postMessage({
            type: "viewport.launch",
            name: "cybaviz",
            command: "/alloshare/donghao/nodejs/ivisdesigner/java/cyberviz.sh",
            options: {
                cwd: "/alloshare/donghao/nodejs/ivisdesigner/java"
            },
            arguments: [],
            textures: [
              { key: "services", width: 2000, height: 2000 },
              { key: "missions", width: 2000, height: 2000 }
            ]
        });

        IV.editor.actions.add(new IV.actions.SetDirectly(IV.editor.workspace, "viewport_poses", [
          {
            name: "cybaviz",
            key: "services",
            pose: {
              center: new IV.Vector3(5, 0, 0),
              normal: new IV.Vector3(-1, 0, 0),
              up: new IV.Vector3(0, 0, 1),
              width: 4
            }
          },
          {
            name: "cybaviz",
            key: "missions",
            pose: {
              center: new IV.Vector3(-5, 0, 0),
              normal: new IV.Vector3(1, 0, 0),
              up: new IV.Vector3(0, 0, 1),
              width: 4
            }
          }
        ])); IV.editor.actions.commit();
    */}); }
    for(var id in predefined_codes) {
        var name = predefined_codes[id].name;
        $("#code-editor-predefined").append(IV._E("option").attr("value", id).text(name));
    }
    $("#code-editor-predefined").change(function() {
        codemirror.setValue(predefined_codes[$(this).val()].code);
        codemirror.execCommand("selectAll");
    });
})();
<commit_msg>Bug fix.<commit_after>// iVisDesigner - scripts/editor/ui.js
// Author: Donghao Ren
//
// LICENSE
//
// Copyright (c) 2014, The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
//    may be used to endorse or promote products derived from this software without
//    specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

IV.addListener("command:panels.reset", function() {
    $("#panel-schema").IVPanel({ left: 10, top: 10, width: 180, height: 400 }).IVPanel("show");
    $("#panel-objects").IVPanel({ left: 10, top: 420, width: 180, bottom: 10 }).IVPanel("show");
    $("#panel-tools").IVPanel({ left: 200, top: 10, right: 220, height: 38, min_height: 38 }).IVPanel("show");
    $("#panel-log").IVPanel({ left: 10, bottom: 10, right: 10, height: 100 }).IVPanel("hide");
    $("#panel-page").IVPanel({ vcenter: 0, bottom: 200, top: 60, width: 600 }).IVPanel("hide");
    $("#panel-style").IVPanel({ right: 10, top: 10, width: 200, height: 300 }).IVPanel("show");
    $("#panel-property").IVPanel({ right: 10, top: 320, width: 200, bottom: 10 }).IVPanel("show");
    $("#panel-inspector").IVPanel({ right: 220, bottom: 10, width: 200, height: 200 }).IVPanel("hide");
    $("#panel-pose").IVPanel({ right: 220, bottom: 10, width: 200, height: 200 }).IVPanel("hide");
    $("#panel-code-editor").IVPanel({ left: 200, bottom: 10, right: 220, height: 200 }).IVPanel("hide");
});
IV.raiseEvent("command:panels.reset");

IV.add("status", "string");
IV.listen("status", function(s) {
    $(".status-text").text(s);
});

(function() {
    // Mouse events.
    var mouse_state = false;

    IV.isTrackingMouse = function() { return mouse_state; }

    $(window).contextmenu(function(e) {
        if(e.target.tagName == "INPUT") return;
        e.preventDefault();
    });

    $("#view").mousedown(function(e) {
        var offsetX = e.pageX - $("#view").offset().left;
        var offsetY = e.pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: e.shiftKey };
        mouse_state = true;
        Editor.raise("view:mousedown", o);
        Editor.renderer.render();
    });
    $(window).mousemove(function(e) {
        var offsetX = e.pageX - $("#view").offset().left;
        var offsetY = e.pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: e.shiftKey };
        var w = $("#view").width();
        var h = $("#view").height();
        var insideView = offsetX >= 0 && offsetX < w && offsetY >= 0 && offsetY < h;
        if(mouse_state || insideView) {
            Editor.raise("view:mousemove", o);
            Editor.renderer.render();
        }
        return true;
    });
    $(window).mouseup(function(e) {
        var offsetX = e.pageX - $("#view").offset().left;
        var offsetY = e.pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: e.shiftKey };
        mouse_state = false;
        Editor.raise("view:mouseup", o);
        Editor.renderer.render();
        return true;
    });
    // For iPad like platforms:
    // attach the touchstart, touchmove, touchend event listeners.
    var view_elem = document.getElementById("view");
    var touch_state = false;
    view_elem.addEventListener('touchstart',function(e) {
        //if(e.target != view_elem && e.target != canvas_front) return;
        e.preventDefault();
        touch_state = true;
        var offsetX = e.touches[0].pageX - $("#view").offset().left;
        var offsetY = e.touches[0].pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: false };
        Editor.raise("view:mousedown", o);
        Editor.renderer.render();
    });
    view_elem.addEventListener('touchmove',function(e) {
        var offsetX = e.touches[0].pageX - $("#view").offset().left;
        var offsetY = e.touches[0].pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: false };
        Editor.raise("view:mousemove", o);
        Editor.renderer.render();
    });
    view_elem.addEventListener('touchend', function(e) {
        var offsetX = e.changedTouches[0].pageX - $("#view").offset().left;
        var offsetY = e.changedTouches[0].pageY - $("#view").offset().top;
        var pt = new IV.Vector(offsetX, offsetY);
        pt = Editor.renderer.getOffsetFromScreen(pt);
        var o = { offset: pt,
                  page: new IV.Vector(e.pageX, e.pageY),
                  shift: false };
        Editor.raise("view:mouseup", o);
        Editor.renderer.render();
    });

    IV.log = function(str) {
        var s;
        if(typeof(str) == "string") s = str;
        else s = JSON.stringify(str, null, " ");
        $("#log-container > ul").prepend($("

").append($("

").text(s)));
    };

    Editor.status = {
        start: function() {
            $(".status-text").html("");
            return this;
        },
        add: function(info) {
            this.append(info);
            return this;
        },
        append: function(info) { // append will return a descriptor, while add return the obj.
            var sp = $("").text(info);
            $(".status-text").append(sp);
            var ctx = {
                set: function(info) {
                    sp.text(info);
                }
            };
            return ctx;
        },
        end: function() {
            $(".status-text").html("");
            return this;
        }
    };

    var editor_messages = {};

    Editor.showMessage = function(str) {
        var s;
        if(editor_messages[str]) {
            s = editor_messages[str];
            clearTimeout(s.data().timeout);
        } else {
            s = IV._E("div").append(IV._E("span", type ? "msg-" + type : "message", str));
            editor_messages[str] = s;
            $("#editor-messages").append(s);
        }
        s.data().timeout = setTimeout(function() {
            s.remove();
            delete editor_messages[str];
        }, 2000);
    };

    $(window).keydown(function(e) {
        if(e.keyCode == 8 && e.target == document.body) {
            e.preventDefault();
        }
    });
    $(document).bind('touchmove', function(e) {
        e.preventDefault();
    });

    var codemirror = CodeMirror(document.getElementById("code-editor-container"), {
        value: "// Input Javascript code here.\n",
        lineNumbers: true,
        indentUnit: 4,
        tabSize: 4,
        keyMap: "sublime",
        theme: "monokai",
        lineNumbers: true,
        matchBrackets: true,
        showCursorWhenSelecting: true,
        mode: "javascript"
    });
    $("#code-editor-remote-run").click(function() {
        var code = codemirror.getSelection();
        IV.allosphere.postMessage({
            type: "eval",
            script: code
        });
    });
    $("#code-editor-local-run").click(function() {
        var code = codemirror.getSelection();
        eval(code);
    });
    var predefined_codes = { };
    predefined_codes["sample"] = { name: "Sample", code: "alert('Hello World!');" };
    predefined_codes["launch-test"] = { name: "Launch Test", code: IV.multiline(function() {/*
        IV.allosphere.postMessage({
            type: "viewport.launch",
            name: "test",
            command: "java",
            options: {
                cwd: "/Users/donghao/Documents/Projects/iVisDesigner/nodejs/allosphere/jni"
            },
            arguments: ["Test"],
            textures: [
              { key: "test", width: 100, height: 100 }
            ]
        });

        IV.editor.actions.add(new IV.actions.SetDirectly(IV.editor.workspace, "viewport_poses", [
          {
            name: "test",
            key: "test",
            pose: {
              center: new IV.Vector3(5, 0, 0),
              normal: new IV.Vector3(-1, 0, 0),
              up: new IV.Vector3(0, 0, 1),
              width: 4
            }
          }
        ])); IV.editor.actions.commit();
    */}) };
    predefined_codes["CyberViz"] = { name: "CyberViz Launch", code: IV.multiline(function() {/*
        IV.allosphere.postMessage({
            type: "viewport.launch",
            name: "cybaviz",
            command: "/alloshare/donghao/nodejs/ivisdesigner/java/cyberviz.sh",
            options: {
                cwd: "/alloshare/donghao/nodejs/ivisdesigner/java"
            },
            arguments: [],
            textures: [
              { key: "services", width: 2000, height: 2000 },
              { key: "missions", width: 2000, height: 2000 }
            ]
        });

        IV.editor.actions.add(new IV.actions.SetDirectly(IV.editor.workspace, "viewport_poses", [
          {
            name: "cybaviz",
            key: "services",
            pose: {
              center: new IV.Vector3(5, 0, 0),
              normal: new IV.Vector3(-1, 0, 0),
              up: new IV.Vector3(0, 0, 1),
              width: 4
            }
          },
          {
            name: "cybaviz",
            key: "missions",
            pose: {
              center: new IV.Vector3(-5, 0, 0),
              normal: new IV.Vector3(1, 0, 0),
              up: new IV.Vector3(0, 0, 1),
              width: 4
            }
          }
        ])); IV.editor.actions.commit();
    */}) };
    for(var id in predefined_codes) {
        var name = predefined_codes[id].name;
        $("#code-editor-predefined").append(IV._E("option").attr("value", id).text(name));
    }
    $("#code-editor-predefined").change(function() {
        codemirror.setValue(predefined_codes[$(this).val()].code);
        codemirror.execCommand("selectAll");
    });
})();
<|endoftext|>


<commit_before><!DOCTYPE html>

   <meta charset="utf-8">
   <title>Modernizr</title>

   <meta name="description" content="Modernizr is an open-source JavaScript library that helps you build the next generation of HTML5 and CSS3-powered websites.">
   <meta name="author" content="Faruk Ateş, Paul Irish, Alex Sexton">

   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
   <meta name="viewport" content="width=device-width">
   <link rel="Shortcut Icon" href="/favicon.ico" type="image/x-icon" />
   <link rel="alternate" href="http://feeds.feedburner.com/Modernizr" type="application/rss+xml" title="RSS" />

   <link rel="stylesheet" href="/i/css/modernizr-2.0.4.css" type="text/css" media="screen">

Download

Documentation

Resources

News

         <hgroup>

Modernizr

Front-end Development Done Right

         </hgroup>

         <q>Modernizr is an essential part of my toolkit of files.</q>
         Andy Clarke, Stuff & Nonsense

Modernizr is an open-source JavaScript library that helps you build the next generation of HTML5 and CSS3-powered websites.

Why use Modernizr?

Taking advantage of the new capabilities of HTML5 and CSS3 can mean sacrificing control over the experience in older browsers. Modernizr 2 is your starting point for making the best websites and applications that work exactly right no matter what browser or device your visitors use.

Thanks to the new Media Query tests and built-in YepNope.js micro-library as Modernizr.load(), you can now combine feature detection with media queries and conditional resource loading. That gives you the power and flexibility to optimize for every circumstance.

Check out the full list of features that Modernizr detects, or learn more about conditional resource loading with Modernizr.

Download Modernizr 2.5.1

Use the commented, uncompressed Development version to develop with and learn from.

Then, dive into the Production build tool and pick just the tests you need!

View documentation

                  Development Uncompressed, 42 Kb

Production Configure your build

Get started with Modernizr

While Modernizr gives you finer control over the experience through JavaScript-driven feature detection, it is important to continue to use best practices throughout your development process. Use progressive enhancement wherever you can, and don’t sacrifice accessibility for convenience or performance.

Documentation: Getting started

Taking Advantage of HTML5 and CSS3 with Modernizr, Faruk Ateş

How to use Modernizr, Inayaili de León

Modernizr: front-end development done right, Ryan Seddon

[wiki] The Undetectables: features that cannot be detected

[wiki] Cross-browser Polyfills

Also check out our Resources section.

Tip: check our Modernizr test suite to quickly test your current browser’s features.

               <form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="donateForm"><input type="hidden" name="cmd" value="_s-xclick"><input type="hidden" name="hosted_button_id" value="T3SNE26ADDVX6">

Community links

Follow us on Twitter

Contribute on github

Subscribe with RSS

Donate to Modernizr

<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif" name="submit" alt="Love Modernizr? Donate to help the project!">

					</form>

Latest news

                  <time datetime="2012-02-06T20:20:20">February 6th, 2012</time>

Modernizr 2.5: Supercharged for 2012

Our biggest release yet!

Previous

                  <time datetime="2011-11-07T10:48:00">November 7th, 2011</time>

How Does Modernizr’s Test Suite Work?

                  <time datetime="2011-09-01T00:00:00">September 1st, 2011</time>

Modernizr and CDNs

                  <time datetime="2011-05-16T15:50:09">June 1st, 2011</time>

Modernizr 2

Used by

Twitter

Google

Microsoft

The Economist

About.com

The Knot

GOOD Magazine

Posterous

Created by

Faruk Ateş Creator & Lead @KuraFire

Paul Irish Lead Developer @paul_irish

Alex Sexton Developer @SlexAxton

Ryan Seddon Developer @ryanseddon

Alexander Farkas Developer

               Modernizr is the right micro-library to get you up and running with HTML5 & CSS3 today.

Proudly sponsored by: Typekit

Copyright © 2009—2012. Modernizr is available under the MIT & BSD licenses.

<commit_msg>removed copy of modernizr.com masquerading as modernizr.js<commit_after><|endoftext|>


<commit_before>
/* Test code to generate valley surrounded by mountains.
*/

const RG = require('../client/src/battles');

const OverWorld = RG.OverWorld;
const createOverWorld = OverWorld.createOverWorld;

const mult = 1;

const conf = {
    yFirst: false,
    topToBottom: false,
    // stopOnWall: 'random',
    stopOnWall: true,
    // nHWalls: 2,
    nVWalls: [0.8],
    highX: mult * 80,
    highY: mult * 40,
    worldX: mult * 800,
    worldY: mult * 400
};

const startTime = new Date().getTime();
createOverWorld(conf);
const endTime = new Date().getTime();

const dur = endTime - startTime;
console.log('Creating overworld took ' + dur + 'ms');
<commit_msg>Added setSeed().<commit_after>
/* Test code to generate valley surrounded by mountains.
*/

const RG = require('../client/src/battles');

RG.RAND.setSeed(new Date().getTime());

const OverWorld = RG.OverWorld;
const createOverWorld = OverWorld.createOverWorld;

const mult = 1;

const conf = {
    yFirst: false,
    topToBottom: false,
    // stopOnWall: 'random',
    stopOnWall: true,
    // nHWalls: 2,
    nVWalls: [0.8],
    highX: mult * 80,
    highY: mult * 40,
    worldX: mult * 800,
    worldY: mult * 400
};

const startTime = new Date().getTime();
createOverWorld(conf);
const endTime = new Date().getTime();

const dur = endTime - startTime;
console.log('Creating overworld took ' + dur + 'ms');
<|endoftext|>


<commit_before>var apiData = function (longname) {
  var root = DocsData;

  _.each(longname.split("."), function (pathSegment) {
    root = root[pathSegment];
  });

  if (! root) {
    console.log("API Data not found: " + longname);
  }

  return root;
};

var typeLink = function (displayName, id) {
  return "" + displayName + "";
};

var toOrSentence = function (array) {
  if (array.length === 1) {
    return array[0];
  } else if (array.length === 2) {
    return array.join(" or ");
  }

  return _.initial(array).join(", ") + ", or " + _.last(array);
};

Template.autoApiBox.helpers({
  apiData: apiData,
  typeNames: function (nameList) {
    // change names if necessary
    nameList = _.map(nameList, function (name) {
      if (name === "function") {
        return "Function";
      } else if (name === "EJSONable" || name === "EJSON") {
        return typeLink("EJSON-able Object", "ejson");
      } else if (name === "Tracker.Computation") {
        return typeLink("Tracker.Computation", "tracker_computation");
      } else if (name === "MongoSelector") {
        return [
          typeLink("Mongo Selector", "selectors"),
          typeLink("Object ID", "mongo_object_id"),
          "String"
        ];
      } else if (name === "MongoModifier") {
        return typeLink("Mongo Modifier", "modifiers");
      } else if (name === "MongoSortSpecifier") {
        return typeLink("Mongo Sort Specifier", "sortspecifiers");
      } else if (name === "MongoFieldSpecifier") {
        return typeLink("Mongo Field Specifier", "fieldspecifiers");
      } else if (name === "JSONCompatible") {
        return "JSON-compatible Object";
      } else if (name === "EventMap") {
        return typeLink("Event Map", "eventmaps");
      } else if (name === "DOMNode") {
        return "DOM Node";
      }

      // decode the "Array.<Type>" syntax
      if (name.slice(0, 7) === "Array.<") {
        return "Array of " + name.match(/<([^>]+)>/)[1] + "s";
      }

      return name;
    });

    nameList = _.flatten(nameList);

    return toOrSentence(nameList);
  },
  signature: function () {
    var signature;

    var beforeParens;
    if (this.scope === "instance") {
      beforeParens = "" + apiData(this.memberof).instancename + "." + this.name;
    } else if (this.kind === "class") {
      beforeParens = "new " + this.longname;
    } else {
      beforeParens = this.longname;
    }

    signature = beforeParens;

    // if it is a function, and therefore has arguments
    if (_.contains(["function", "class"], this.kind)) {
      var params = this.params;

      var paramNames = _.map(params, function (param) {
        if (param.optional) {
          return "[" + param.name + "]";
        }

        return param.name;
      });

      signature += "(" + paramNames.join(", ") + ")";
    }

    return signature;
  },
  link: function () {
    if (nameToId[this.longname]) {
      return nameToId[this.longname];
    }

    // fallback
    return this.longname.replace(".", "-");
  },
  paramsNoOptions: function () {
    return _.reject(this.params, function (param) {
      return param.name === "options";
    });
  }
});
<commit_msg>Improve type link generation in autoApiBox<commit_after>var apiData = function (longname) {
  var root = DocsData;

  _.each(longname.split("."), function (pathSegment) {
    root = root[pathSegment];
  });

  if (! root) {
    console.log("API Data not found: " + longname);
  }

  return root;
};

var typeLink = function (displayName, id) {
  return "" + displayName + "";
};

var toOrSentence = function (array) {
  if (array.length === 1) {
    return array[0];
  } else if (array.length === 2) {
    return array.join(" or ");
  }

  return _.initial(array).join(", ") + ", or " + _.last(array);
};

var typeNameTranslation = {
  "function": "Function",
  EJSON: typeLink("EJSON-able Object", "ejson"),
  EJSONable: typeLink("EJSON-able Object", "ejson"),
  "Tracker.Computation": typeLink("Tracker.Computation", "tracker_computation"),
  MongoSelector: [
    typeLink("Mongo Selector", "selectors"),
    typeLink("Object ID", "mongo_object_id"),
    "String"
  ],
  MongoModifier: typeLink("Mongo Modifier", "modifiers"),
  MongoSortSpecifier: typeLink("Mongo Sort Specifier", "sortspecifiers"),
  MongoFieldSpecifier: typeLink("Mongo Field Specifier", "fieldspecifiers"),
  JSONCompatible: "JSON-compatible Object",
  EventMap: typeLink("Event Map", "eventmaps"),
  DOMNode: "DOM Node",
  "Blaze.View": typeLink("Blaze.View", "blaze_view"),
  Template: typeLink("Blaze.Template", "blaze_template")
};

console.log(typeNameTranslation);

Template.autoApiBox.helpers({
  apiData: apiData,
  typeNames: function (nameList) {
    // change names if necessary
    nameList = _.map(nameList, function (name) {

      // decode the "Array.<Type>" syntax
      if (name.slice(0, 7) === "Array.<") {
        // get the part inside angle brackets like in Array<String>
        name = name.match(/<([^>]+)>/)[1];

        if (name && typeNameTranslation.hasOwnProperty(name)) {
          return "Array of " + typeNameTranslation[name] + "s";
        }

        if (name) {
          return "Array of " + name + "s";
        }

        console.log("no array type defined");
        return "Array";
      }

      if (typeNameTranslation.hasOwnProperty(name)) {
        return typeNameTranslation[name];
      }

      return name;
    });

    nameList = _.flatten(nameList);

    return toOrSentence(nameList);
  },
  signature: function () {
    var signature;

    var beforeParens;
    if (this.scope === "instance") {
      beforeParens = "" + apiData(this.memberof).instancename + "." + this.name;
    } else if (this.kind === "class") {
      beforeParens = "new " + this.longname;
    } else {
      beforeParens = this.longname;
    }

    signature = beforeParens;

    // if it is a function, and therefore has arguments
    if (_.contains(["function", "class"], this.kind)) {
      var params = this.params;

      var paramNames = _.map(params, function (param) {
        if (param.optional) {
          return "[" + param.name + "]";
        }

        return param.name;
      });

      signature += "(" + paramNames.join(", ") + ")";
    }

    return signature;
  },
  link: function () {
    if (nameToId[this.longname]) {
      return nameToId[this.longname];
    }

    // fallback
    return this.longname.replace(".", "-");
  },
  paramsNoOptions: function () {
    return _.reject(this.params, function (param) {
      return param.name === "options";
    });
  }
});
<|endoftext|>


<commit_before>release = Meteor.release ? "1.0.4.2" : "(checkout)";

Template.registerHelper("release", release);

Template.registerHelper("fullApi", function () {
  return Session.get("fullApi");
});

Template.registerHelper('dstache', function() {
  return '{{';
});

Template.registerHelper('tstache', function() {
  return '{{{';
});

Template.registerHelper('lt', function () {
  return '<';
});
<commit_msg>Update release number in the docs<commit_after>release = Meteor.release ? "1.0.5" : "(checkout)";

Template.registerHelper("release", release);

Template.registerHelper("fullApi", function () {
  return Session.get("fullApi");
});

Template.registerHelper('dstache', function() {
  return '{{';
});

Template.registerHelper('tstache', function() {
  return '{{{';
});

Template.registerHelper('lt', function () {
  return '<';
});
<|endoftext|>


<commit_before>angular.module("HtmlImageEditor", [])
    .directive("imageEditorDirective", function() {
        return {
            templateUrl: '/HtmlImageEditor/directives/imageEditor.html',
            link: function(scope, element) {
                var imageElem = element[0].getElementsByClassName('imageEditorImageArea')[0];
                scope.canvas = document.createElement("canvas");
                scope.canvas.style.display = 'block';
                imageElem.appendChild(scope.canvas);
                var histElem = element[0].getElementsByClassName('imageEditorHistogramArea')[0];
                scope.histogramCanvas = document.createElement("canvas");
                scope.histogramCanvas.className = "imageEditorHistogramCanvas";
                histElem.appendChild(scope.histogramCanvas);
            }
        };
    })
    .service("imageEditorService", function () {
        this.optimizeData = function (data, whitePoint) {
            var grayVal;
            for (var i = 0; i < data.length; i += 4) {
                grayVal = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
                if (grayVal > whitePoint) {
                    // red
                    data[i] = 255;
                    // green
                    data[i + 1] = 255;
                    // blue
                    data[i + 2] = 255;
                }
            }
            return data;
        };

        this.getHistogramDotData = function (data) {
            var grayVal;
            var histogramDotData = [];
            for (var i = 0; i < data.length; i += 4) {
                grayVal = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
                if (histogramDotData[grayVal] === undefined) {
                    histogramDotData[grayVal] = ".";
                } else {
                    histogramDotData[grayVal] += ".";
                }
            }

            return histogramDotData;
        };

        this.flipCanvas = function (originalImage, canvas, bVertical, bHorizontal) {
            var context = canvas.getContext("2d");
            var x = 0;
            var y = 0;
            context.save();

            if (bVertical && bHorizontal){
                context.scale(-1, -1);
                x = -canvas.width;
                y = -canvas.height;
            } else if (bVertical) {
                context.scale(1, -1);
                y = -canvas.height;
            }  else if (bHorizontal) {
                context.scale(-1, 1);
                x = -canvas.width;
            }

            context.drawImage(originalImage, x, y, canvas.width, canvas.height);
            context.restore();
            return canvas;
        };
    })
    .controller("imageEditorCtrl", function ($scope, imageEditorService){
        var imgObj = new Image();

        $scope.drawImage = function (imageObj) {
            var dimension = parseInt(document.documentElement.clientHeight - 100);
            var maxWidth = parseInt(document.documentElement.clientWidth - 622);
            var x = 0;
            var y = 0;
            var tempHeight = dimension;
            var tempWidth = dimension;
            var context;
            var imageData;

            if (imageObj.width > imageObj.height) {
                tempHeight = (imageObj.height / imageObj.width) * tempWidth;
            } else {
                tempWidth = (imageObj.width / imageObj.height) * tempHeight;
            }

            if(tempWidth > maxWidth) {
                tempHeight = tempHeight * (maxWidth / tempWidth);
                tempWidth = maxWidth;
            }

            $scope.canvas.height = tempHeight;
            $scope.canvas.width = tempWidth;
            context = $scope.canvas.getContext('2d');
            context.drawImage(imageObj, x, y, tempWidth, tempHeight);
            imageData = context.getImageData(x, y, tempWidth, tempHeight);
            this.drawHistogram(imageData.data);

            //reset values
            $scope.white = 180;
            $scope.optm = false;
            $scope.bwm = false;
            $scope.brightness = 0;
            $scope.shadow = 0;
            $scope.highlight = 0;
            $scope.black = 0;
            $scope.vFlipM = 0;
            $scope.hFlipM = 0;
        };

        $scope.adjustImage = function (imageObj, imageData, context) {
            var whitePoint = _.parseInt($scope.white);

            if ($scope.optm === true) {
                imageEditorService.optimizeData(imageData.data, whitePoint);
            } else {
                this.processSliderChanges(imageData.data);
            }

            this.drawHistogram(imageData.data);
            // overwrite original image
            context.putImageData(imageData, 0, 0);
        };

        $scope.createDisplayImage = function (imageObj) {
            var context = $scope.canvas.getContext('2d');
            imageEditorService.flipCanvas(imageObj, $scope.canvas, $scope.vFlipM, $scope.hFlipM);
            var imageData = context.getImageData(0, 0, $scope.canvas.width, $scope.canvas.height);

            $scope.adjustImage(imageObj, imageData, context);
        };

        $scope.createSaveImage = function () {
            var canvas = document.createElement("canvas");
            canvas.width = imgObj.width;
            canvas.height = imgObj.height;
            canvas.style.display = 'block';
            var context = canvas.getContext('2d');
            imageEditorService.flipCanvas(imgObj, canvas, $scope.vFlipM, $scope.hFlipM);
            var imageData = context.getImageData(0, 0, canvas.width, canvas.height);

            $scope.adjustImage(imgObj, imageData, context);

            var fullQualityImage = canvas.toDataURL("image/jpeg", 1.0);

            window.open(fullQualityImage,'Image','width=canvas.width,height=canvas.height,resizable=1');
        };

        $scope.processSliderChanges = function (data) {
            var brighter = _.parseInt($scope.brightness);
            var shadows = _.parseInt($scope.shadow);
            var highlights = _.parseInt($scope.highlight);
            var blacks = _.parseInt($scope.black);
            var bwVal, shadowFactor, highlightFactor, blackFactor, combinedFactors;

            for (var i = 0; i < data.length; i += 4) {
                bwVal = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
                shadowFactor = shadows * ((255 - bwVal) / 255);
                highlightFactor = highlights * (bwVal / 255);

                if (bwVal < 25) {
                    blackFactor = blacks * (bwVal / 255);
                } else if (bwVal < 50) {
                    blackFactor = blacks * ((bwVal * 0.95) / 255);//5
                } else if (bwVal < 75) {
                    blackFactor = blacks * ((bwVal * 0.88) / 255);//7 + 2
                } else if (bwVal < 100) {
                    blackFactor = blacks * ((bwVal * 0.77) / 255);//11 + 4
                } else if (bwVal < 125) {
                    blackFactor = blacks * ((bwVal * 0.60) / 255);//17 + 8
                } else if (bwVal < 150) {
                    blackFactor = blacks * ((bwVal * 0.44) / 255);// 25 +12
                } else if (bwVal < 175) {
                    blackFactor = blacks * ((bwVal * 0.3) / 255);// 37+16
                } else if (bwVal < 200) {
                    blackFactor = blacks * ((bwVal * 0.2) / 255);// 53 + 20
                } else if (bwVal < 225) {
                    blackFactor = blacks * ((bwVal * 0.1) / 255);// 73 + 24
                } else if (bwVal < 250) {
                    blackFactor = blacks * ((bwVal * 0.05) / 255);// 97
                } else {
                    blackFactor = 0;
                }

                combinedFactors = shadowFactor + highlightFactor + blackFactor + brighter;

                if ($scope.bwm === true) {
                    // red
                    data[i] = bwVal + combinedFactors;
                    // green
                    data[i + 1] = bwVal + combinedFactors;
                    // blue
                    data[i + 2] = bwVal + combinedFactors;
                } else {
                    // red
                    data[i] += combinedFactors;
                    // green
                    data[i + 1] += combinedFactors;
                    // blue
                    data[i + 2] += combinedFactors;
                }
            }
        };

        $scope.drawHistogram = function (data) {
            var height = parseInt(document.documentElement.clientHeight - 111);
            var context = $scope.histogramCanvas.getContext('2d');
            var histogramData = [], maxVal = 0, grayVal, imageData, pixelGroupCounter, i, j;

            for (i = 0; i < data.length; i += 4) {
                grayVal = parseInt(0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]);
                if (isNaN(histogramData[grayVal])) {
                    histogramData[grayVal] = 1;
                } else {
                    histogramData[grayVal]++;
                }

                if (histogramData[grayVal] > maxVal) {
                    maxVal = histogramData[grayVal];
                }
            }

            $scope.histogramCanvas.height = height;
            $scope.histogramCanvas.width = histogramData.length;

            imageData = context.getImageData(0, 0, $scope.histogramCanvas.width, height);
            data = imageData.data;
            pixelGroupCounter = 0;

            for (i = 0; i < height; i++) {
                for (j = 0; j < histogramData.length; j++) {
                    if ((histogramData[j] / maxVal) * height <= (height - i) || histogramData[j] === undefined) {
                        data[pixelGroupCounter] = 240;
                        data[pixelGroupCounter + 1] = 240;
                        data[pixelGroupCounter + 2] = 240;
                        data[pixelGroupCounter + 3] = 255;
                    } else {
                        data[pixelGroupCounter] = 0;
                        data[pixelGroupCounter + 1] = 0;
                        data[pixelGroupCounter + 2] = 0;
                        data[pixelGroupCounter + 3] = 255;
                    }
                    pixelGroupCounter += 4;
                }
            }

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

        $scope.printHistogramDotData = function (data) {
            var dotData = imageEditorService.getHistogramDotData(data);

            dotData.forEach(function (elem) {
                console.log(elem);
            });
        };

        $scope.redraw = function () {
            $scope.createDisplayImage(imgObj);
        };

        function handleFileSelect(event) {
            var files = event.target.files;
            var reader = new FileReader();

            if(event.target && event.target.files) {
                // process all File objects
                for(var i = 0; i < files.length; i++){
                    reader.onload = fileOnLoad;
                    reader.readAsDataURL(files[i]);
                }
            }
        }

        function fileOnLoad (event) {
            if(event.target.result) {
                imgObj.onload = function () {
                    $scope.drawImage(imgObj);
                };

                imgObj.src = event.target.result;
            }
        }

        document.getElementById('imageInputMasterButton').addEventListener('change', handleFileSelect, false);
    });<commit_msg>Adding comments<commit_after>/**
 * Html Image Editor Directive
 *
 * Author: Nicholas Arent
 * Date: 2016
 */
angular.module("HtmlImageEditor", [])
    .directive("imageEditorDirective", function() {
        return {
            templateUrl: '/HtmlImageEditor/directives/imageEditor.html',
            link: function(scope, element) {
                var imageElem = element[0].getElementsByClassName('imageEditorImageArea')[0];
                scope.canvas = document.createElement("canvas");
                scope.canvas.style.display = 'block';
                imageElem.appendChild(scope.canvas);
                var histElem = element[0].getElementsByClassName('imageEditorHistogramArea')[0];
                scope.histogramCanvas = document.createElement("canvas");
                scope.histogramCanvas.className = "imageEditorHistogramCanvas";
                histElem.appendChild(scope.histogramCanvas);
            }
        };
    })
    .service("imageEditorService", function () {
        /**
         * This is mostly used for simple images like snapshots of a whiteboard. It willincrease the
         * contrast of the image to make whiteboard snapshots less "muddy" looking.
         *
         * Data is canvas.getContext('2d').getImageData
         *
         * Whitepoint should be a value less than 255. Any pixel values above whitepoint will be
         * set to white.
         *
         * @param data
         * @param whitePoint
         * @returns {*}
         */
        this.optimizeData = function (data, whitePoint) {
            var grayVal;
            for (var i = 0; i < data.length; i += 4) {
                grayVal = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
                if (grayVal > whitePoint) {
                    // red
                    data[i] = 255;
                    // green
                    data[i + 1] = 255;
                    // blue
                    data[i + 2] = 255;
                }
            }
            return data;
        };

        /**
         * Returns a dot representation of the image's histogram.
         * Data is canvas.getContext('2d').getImageData
         *
         * @param data
         * @returns {Array}
         */
        this.getHistogramDotData = function (data) {
            var grayVal;
            var histogramDotData = [];
            for (var i = 0; i < data.length; i += 4) {
                grayVal = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
                if (histogramDotData[grayVal] === undefined) {
                    histogramDotData[grayVal] = ".";
                } else {
                    histogramDotData[grayVal] += ".";
                }
            }

            return histogramDotData;
        };

        /**
         * Flips the canvas vertically or horizontally depending on the boolean values of
         * bVertical and bHorizontal.
         *
         * originalImage is of type Image
         *
         * canvas is an HTML5 Canvas object
         *
         * bVertical is boolean true to flip image on the vertical axis
         *
         * bHorizontal is boolean true to flip image on the horizontal axis
         *
         * @param originalImage
         * @param canvas
         * @param bVertical
         * @param bHorizontal
         * @returns {*}
         */
        this.flipCanvas = function (originalImage, canvas, bVertical, bHorizontal) {
            var context = canvas.getContext("2d");
            var x = 0;
            var y = 0;
            context.save();

            if (bVertical && bHorizontal){
                context.scale(-1, -1);
                x = -canvas.width;
                y = -canvas.height;
            } else if (bVertical) {
                context.scale(1, -1);
                y = -canvas.height;
            }  else if (bHorizontal) {
                context.scale(-1, 1);
                x = -canvas.width;
            }

            context.drawImage(originalImage, x, y, canvas.width, canvas.height);
            context.restore();
            return canvas;
        };
    })
    .controller("imageEditorCtrl", function ($scope, imageEditorService){
        var imgObj = new Image();

        /**
         * Initial draw of the target image to the screen with default set values. Also
         * draws the histogram for the image data.
         *
         * imageObj is of type Image
         *
         * @param imageObj
         */
        $scope.drawImage = function (imageObj) {
            var dimension = parseInt(document.documentElement.clientHeight - 100);
            var maxWidth = parseInt(document.documentElement.clientWidth - 622);
            var x = 0;
            var y = 0;
            var tempHeight = dimension;
            var tempWidth = dimension;
            var context;
            var imageData;

            if (imageObj.width > imageObj.height) {
                tempHeight = (imageObj.height / imageObj.width) * tempWidth;
            } else {
                tempWidth = (imageObj.width / imageObj.height) * tempHeight;
            }

            if(tempWidth > maxWidth) {
                tempHeight = tempHeight * (maxWidth / tempWidth);
                tempWidth = maxWidth;
            }

            $scope.canvas.height = tempHeight;
            $scope.canvas.width = tempWidth;
            context = $scope.canvas.getContext('2d');
            context.drawImage(imageObj, x, y, tempWidth, tempHeight);
            imageData = context.getImageData(x, y, tempWidth, tempHeight);
            this.drawHistogram(imageData.data);

            //reset values
            $scope.white = 180;
            $scope.optm = false;
            $scope.bwm = false;
            $scope.brightness = 0;
            $scope.shadow = 0;
            $scope.highlight = 0;
            $scope.black = 0;
            $scope.vFlipM = 0;
            $scope.hFlipM = 0;
        };

        /**
         * Is responsible for adjusting the target image based on the image edit slider values.
         *
         * imageObj is of type Image
         *
         * imageData is canvas.getContext('2d').getImageData
         *
         * context is canvas.getContext('2d')
         *
         * @param imageObj
         * @param imageData
         * @param context
         */
        $scope.adjustImage = function (imageObj, imageData, context) {
            var whitePoint = _.parseInt($scope.white);

            if ($scope.optm === true) {
                imageEditorService.optimizeData(imageData.data, whitePoint);
            } else {
                this.processSliderChanges(imageData.data);
            }

            this.drawHistogram(imageData.data);
            // overwrite original image
            context.putImageData(imageData, 0, 0);
        };

        /**
         * Creates the low resolution preview image displayed in the editor based on
         * the editor slider values.
         *
         * imageObj is of type Image
         *
         * @param imageObj
         */
        $scope.createDisplayImage = function (imageObj) {
            var context = $scope.canvas.getContext('2d');
            imageEditorService.flipCanvas(imageObj, $scope.canvas, $scope.vFlipM, $scope.hFlipM);
            var imageData = context.getImageData(0, 0, $scope.canvas.width, $scope.canvas.height);

            $scope.adjustImage(imageObj, imageData, context);
        };

        /**
         * Creates the original resolution image for saving based on
         * the editor slider values.
         */
        $scope.createSaveImage = function () {
            var canvas = document.createElement("canvas");
            canvas.width = imgObj.width;
            canvas.height = imgObj.height;
            canvas.style.display = 'block';
            var context = canvas.getContext('2d');
            imageEditorService.flipCanvas(imgObj, canvas, $scope.vFlipM, $scope.hFlipM);
            var imageData = context.getImageData(0, 0, canvas.width, canvas.height);

            $scope.adjustImage(imgObj, imageData, context);

            var fullQualityImage = canvas.toDataURL("image/jpeg", 1.0);

            window.open(fullQualityImage,'Image','width=canvas.width,height=canvas.height,resizable=1');
        };

        /**
         * Modifies the raw image data based on the editor slider values.
         * This will iterate through every pixel of the image to make the adjustments.
         *
         * data is canvas.getContext('2d').getImageData
         *
         * @param data
         */
        $scope.processSliderChanges = function (data) {
            var brighter = _.parseInt($scope.brightness);
            var shadows = _.parseInt($scope.shadow);
            var highlights = _.parseInt($scope.highlight);
            var blacks = _.parseInt($scope.black);
            var bwVal, shadowFactor, highlightFactor, blackFactor, combinedFactors;

            for (var i = 0; i < data.length; i += 4) {
                bwVal = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
                shadowFactor = shadows * ((255 - bwVal) / 255);
                highlightFactor = highlights * (bwVal / 255);

                if (bwVal < 25) {
                    blackFactor = blacks * (bwVal / 255);
                } else if (bwVal < 50) {
                    blackFactor = blacks * ((bwVal * 0.95) / 255);//5
                } else if (bwVal < 75) {
                    blackFactor = blacks * ((bwVal * 0.88) / 255);//7 + 2
                } else if (bwVal < 100) {
                    blackFactor = blacks * ((bwVal * 0.77) / 255);//11 + 4
                } else if (bwVal < 125) {
                    blackFactor = blacks * ((bwVal * 0.60) / 255);//17 + 8
                } else if (bwVal < 150) {
                    blackFactor = blacks * ((bwVal * 0.44) / 255);// 25 +12
                } else if (bwVal < 175) {
                    blackFactor = blacks * ((bwVal * 0.3) / 255);// 37+16
                } else if (bwVal < 200) {
                    blackFactor = blacks * ((bwVal * 0.2) / 255);// 53 + 20
                } else if (bwVal < 225) {
                    blackFactor = blacks * ((bwVal * 0.1) / 255);// 73 + 24
                } else if (bwVal < 250) {
                    blackFactor = blacks * ((bwVal * 0.05) / 255);// 97
                } else {
                    blackFactor = 0;
                }

                combinedFactors = shadowFactor + highlightFactor + blackFactor + brighter;

                if ($scope.bwm === true) {
                    // red
                    data[i] = bwVal + combinedFactors;
                    // green
                    data[i + 1] = bwVal + combinedFactors;
                    // blue
                    data[i + 2] = bwVal + combinedFactors;
                } else {
                    // red
                    data[i] += combinedFactors;
                    // green
                    data[i + 1] += combinedFactors;
                    // blue
                    data[i + 2] += combinedFactors;
                }
            }
        };

        /**
         * Calculates histogram values from the image data and creates a canvas drawn graph representation
         * of the histogram data.
         *
         * data is canvas.getContext('2d').getImageData
         *
         * @param data
         */
        $scope.drawHistogram = function (data) {
            var height = parseInt(document.documentElement.clientHeight - 111);
            var context = $scope.histogramCanvas.getContext('2d');
            var histogramData = [], maxVal = 0, grayVal, imageData, pixelGroupCounter, i, j;

            for (i = 0; i < data.length; i += 4) {
                grayVal = parseInt(0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]);
                if (isNaN(histogramData[grayVal])) {
                    histogramData[grayVal] = 1;
                } else {
                    histogramData[grayVal]++;
                }

                if (histogramData[grayVal] > maxVal) {
                    maxVal = histogramData[grayVal];
                }
            }

            $scope.histogramCanvas.height = height;
            $scope.histogramCanvas.width = histogramData.length;

            imageData = context.getImageData(0, 0, $scope.histogramCanvas.width, height);
            data = imageData.data;
            pixelGroupCounter = 0;

            for (i = 0; i < height; i++) {
                for (j = 0; j < histogramData.length; j++) {
                    if ((histogramData[j] / maxVal) * height <= (height - i) || histogramData[j] === undefined) {
                        data[pixelGroupCounter] = 240;
                        data[pixelGroupCounter + 1] = 240;
                        data[pixelGroupCounter + 2] = 240;
                        data[pixelGroupCounter + 3] = 255;
                    } else {
                        data[pixelGroupCounter] = 0;
                        data[pixelGroupCounter + 1] = 0;
                        data[pixelGroupCounter + 2] = 0;
                        data[pixelGroupCounter + 3] = 255;
                    }
                    pixelGroupCounter += 4;
                }
            }

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

        /**
         * Calculates the images histogram data and prints it to the console as
         * a dot graph.
         *
         * data is canvas.getContext('2d').getImageData
         *
         * @param data
         */
        $scope.printHistogramDotData = function (data) {
            var dotData = imageEditorService.getHistogramDotData(data);

            dotData.forEach(function (elem) {
                console.log(elem);
            });
        };

        /**
         * Called after each slider change. Updates the preview image and histogram based on
         * slider changes.
         *
         */
        $scope.redraw = function () {
            $scope.createDisplayImage(imgObj);
        };

        /**
         * Handler for file selection button.
         *
         * @param event
         */
        function handleFileSelect(event) {
            var files = event.target.files;
            var reader = new FileReader();

            if(event.target && event.target.files) {
                // process all File objects
                for(var i = 0; i < files.length; i++){
                    reader.onload = fileOnLoad;
                    reader.readAsDataURL(files[i]);
                }
            }
        }

        /**
         * Handler for FileReader object when image is selected and read in.
         *
         * @param event
         */
        function fileOnLoad (event) {
            if(event.target.result) {
                imgObj.onload = function () {
                    $scope.drawImage(imgObj);
                };

                imgObj.src = event.target.result;
            }
        }

        //Attach handler to file select button
        document.getElementById('imageInputMasterButton').addEventListener('change', handleFileSelect, false);
    });<|endoftext|>


<commit_before>angular.module('MyApp')
  .directive('passwordStrength', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        var indicator = element.children();
        var dots = Array.prototype.slice.call(indicator.children());
        var weakest = dots.slice(-1)[0];
        var weak = dots.slice(-2);
        var strong = dots.slice(-3);
        var strongest = dots.slice(-4);

        element.after(indicator);

        element.bind('keyup', function() {
          angular.forEach(dots, function(el) { el.style.backgroundColor = '#ebeef1'; });
          if (ngModel.$modelValue.length > 8) {
            angular.forEach(strongest, function(el) { el.style.backgroundColor = '#008cdd'; });
          } else if (ngModel.$modelValue.length > 5) {
            angular.forEach(strong, function(el) { el.style.backgroundColor = '#6ead09'; });
          } else if (ngModel.$modelValue.length > 3) {
            angular.forEach(weak, function(el) { el.style.backgroundColor = '#e09115'; });
          } else {
            weakest.style.backgroundColor = '#e01414';
          }
        });
      },
      template: ''
    };
  });<commit_msg>added if-statement to check if $modelValue is present<commit_after>angular.module('MyApp')
  .directive('passwordStrength', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        var indicator = element.children();
        var dots = Array.prototype.slice.call(indicator.children());
        var weakest = dots.slice(-1)[0];
        var weak = dots.slice(-2);
        var strong = dots.slice(-3);
        var strongest = dots.slice(-4);

        element.after(indicator);

        element.bind('keyup', function() {
          angular.forEach(dots, function(el) { el.style.backgroundColor = '#ebeef1'; });
          if (ngModel.$modelValue) {
            if (ngModel.$modelValue.length > 8) {
              angular.forEach(strongest, function(el) { el.style.backgroundColor = '#008cdd'; });
            } else if (ngModel.$modelValue.length > 5) {
              angular.forEach(strong, function(el) { el.style.backgroundColor = '#6ead09'; });
            } else if (ngModel.$modelValue.length > 3) {
              angular.forEach(weak, function(el) { el.style.backgroundColor = '#e09115'; });
            } else {
              weakest.style.backgroundColor = '#e01414';
            }
          }
        });
      },
      template: ''
    };
  });<|endoftext|>


<commit_before>//
// NOTE: this code relies on prototype and scriptaclulous...
//

//
// make sure a file is selected before submission
//

function submitUploadForm(form, controller, uuid) {
  if (/\w/.exec($('data').value)) {
    UploadProgress.monitor(controller, uuid) ;
		$(form).submit() ;
	} else {
  	alert('You must choose a file to upload!') ;
	}
}

//
// Prototype extensions
//

PeriodicalExecuter.prototype.registerCallback = function() {
  this.intervalID = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
}

PeriodicalExecuter.prototype.stop = function() {
  clearInterval(this.intervalID);
}

//
// Upload Progress class (for use with mongrel_upload_progress & DRb)
//

var UploadProgress = {
  uploading: false,

  monitor: function(controller, uuid) {
    this.setAsStarting() ;
    this.watcher = new PeriodicalExecuter(function() {
      if (!UploadProgress.uploading) { return ; }
      new Ajax.Request('/' + controller + '/upload_progress?upload_id=' + uuid) ;
    }, 3) ;
  },

  update: function(total, current) {
    if (!this.uploading) { return ; }
    var progress = current / total ;
		var maxWidth = $('ProgressBarShell').offsetWidth ;
    var newWidth = Math.floor(progress * maxWidth) ;
		$('ProgressBar').setAttribute('width', newWidth + 'px') ;
    $('ProgressBar').style.width = newWidth + 'px' ;
    $('ProgressBarText').innerHTML = total.toHumanSize() + ': ' + progress.toPercentage() ;
  },

  setAsStarting: function() {
    this.uploading = true ;
    this.processing = false ;
	  $('ProgressBar').style.width = '0%' ;
	  $('ProgressBar').className = 'Uploading' ;
		$('ProgressBarText').innerHTML  = '...' ;
	  Effect.Appear('ProgressBarShell') ;
  },

  setAsProcessing: function() {
    this.uploading = false ;
    this.watcher.stop() ;
    $('ProgressBar').style.width = 'auto' ;
    $('ProgressBar').className   = 'Processing' ;
		$('ProgressBarText').innerHTML  = '100%' ;
  },

  setAsFinished: function() {
    this.uploading = false ;
    this.watcher.stop() ;
    $('ProgressBar').style.width = 'auto' ;
    $('ProgressBar').className   = 'Finished' ;
		$('ProgressBarText').innerHTML  = '100%' ;
	  Effect.Fade('ProgressBarShell', { duration: 1.5 });
	}
}

//
// Number convenience methods
//

Number.prototype.bytes     = function() { return this; };
Number.prototype.kilobytes = function() { return this *  1024; };
Number.prototype.megabytes = function() { return this * (1024).kilobytes(); };
Number.prototype.gigabytes = function() { return this * (1024).megabytes(); };
Number.prototype.terabytes = function() { return this * (1024).gigabytes(); };
Number.prototype.petabytes = function() { return this * (1024).terabytes(); };
Number.prototype.exabytes =  function() { return this * (1024).petabytes(); };

['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte', 'exabyte'].each(function(meth) {
  Number.prototype[meth] = Number.prototype[meth+'s'];
});

Number.prototype.toPrecision = function() {
  var precision = arguments[0] || 2 ;
  var s         = Math.round(this * Math.pow(10, precision)).toString();
  var pos       = s.length - precision;
  var last      = s.substr(pos, precision);
  return s.substr(0, pos) + (last.match("^0{" + precision + "}$") ? '' : '.' + last);
}

Number.prototype.toPercentage = function() {
  return Math.floor(this * 100) + '%';
}

Number.prototype.toHumanSize = function() {
  if(this < (1).kilobyte())  return this + " Bytes";
  if(this < (1).megabyte())  return (this / (1).kilobyte()).toPrecision()  + ' KB';
  if(this < (1).gigabytes()) return (this / (1).megabyte()).toPrecision()  + ' MB';
  if(this < (1).terabytes()) return (this / (1).gigabytes()).toPrecision() + ' GB';
  if(this < (1).petabytes()) return (this / (1).terabytes()).toPrecision() + ' TB';
  if(this < (1).exabytes())  return (this / (1).petabytes()).toPrecision() + ' PB';
                             return (this / (1).exabytes()).toPrecision()  + ' EB';
}
<commit_msg><commit_after>//
// NOTE: this code relies on prototype and scriptaclulous...
//

//
// make sure a file is selected before submission
//

function submitUploadForm(form, controller, uuid) {
  if (/\w/.exec($('data').value)) {
    UploadProgress.monitor(controller, uuid) ;
		$(form).submit() ;
	} else {
  	alert('You must choose a file to upload!') ;
	}
}

//
// Prototype extensions
//

PeriodicalExecuter.prototype.registerCallback = function() {
  this.intervalID = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
}

PeriodicalExecuter.prototype.stop = function() {
  clearInterval(this.intervalID);
}

//
// Upload Progress class (for use with mongrel_upload_progress & DRb)
//

var UploadProgress = {
  uploading: false,

  monitor: function(controller, uuid) {
    this.setAsStarting() ;
    this.watcher = new PeriodicalExecuter(function() {
      if (!UploadProgress.uploading) { return ; }
      new Ajax.Request('/' + controller + '/upload_progress?upload_id=' + uuid) ;
    }, 2) ;
  },

  update: function(total, current) {
    if (!this.uploading) { return ; }
    var progress = current / total ;
		var maxWidth = $('ProgressBarShell').offsetWidth ;
    var newWidth = Math.floor(progress * maxWidth) ;
		$('ProgressBar').setAttribute('width', newWidth + 'px') ;
    $('ProgressBar').style.width = newWidth + 'px' ;
    $('ProgressBarText').innerHTML = total.toHumanSize() + ': ' + progress.toPercentage() ;
  },

  setAsStarting: function() {
    this.uploading = true ;
    this.processing = false ;
	  $('ProgressBar').style.width = '0%' ;
	  $('ProgressBar').className = 'Uploading' ;
		$('ProgressBarText').innerHTML  = '...' ;
	  Effect.Appear('ProgressBarShell') ;
  },

  setAsProcessing: function() {
    this.uploading = false ;
    this.watcher.stop() ;
    $('ProgressBar').style.width = 'auto' ;
    $('ProgressBar').className   = 'Processing' ;
		$('ProgressBarText').innerHTML  = '100%' ;
  },

  setAsFinished: function() {
    this.uploading = false ;
    this.watcher.stop() ;
    $('ProgressBar').style.width = 'auto' ;
    $('ProgressBar').className   = 'Finished' ;
		$('ProgressBarText').innerHTML  = '100%' ;
	  Effect.Fade('ProgressBarShell', { duration: 1.5 });
	}
}

//
// Number convenience methods
//

Number.prototype.bytes     = function() { return this; };
Number.prototype.kilobytes = function() { return this *  1024; };
Number.prototype.megabytes = function() { return this * (1024).kilobytes(); };
Number.prototype.gigabytes = function() { return this * (1024).megabytes(); };
Number.prototype.terabytes = function() { return this * (1024).gigabytes(); };
Number.prototype.petabytes = function() { return this * (1024).terabytes(); };
Number.prototype.exabytes =  function() { return this * (1024).petabytes(); };

['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte', 'exabyte'].each(function(meth) {
  Number.prototype[meth] = Number.prototype[meth+'s'];
});

Number.prototype.toPrecision = function() {
  var precision = arguments[0] || 2 ;
  var s         = Math.round(this * Math.pow(10, precision)).toString();
  var pos       = s.length - precision;
  var last      = s.substr(pos, precision);
  return s.substr(0, pos) + (last.match("^0{" + precision + "}$") ? '' : '.' + last);
}

Number.prototype.toPercentage = function() {
  return Math.floor(this * 100) + '%';
}

Number.prototype.toHumanSize = function() {
  if(this < (1).kilobyte())  return this + " Bytes";
  if(this < (1).megabyte())  return (this / (1).kilobyte()).toPrecision()  + ' KB';
  if(this < (1).gigabytes()) return (this / (1).megabyte()).toPrecision()  + ' MB';
  if(this < (1).terabytes()) return (this / (1).gigabytes()).toPrecision() + ' GB';
  if(this < (1).petabytes()) return (this / (1).terabytes()).toPrecision() + ' TB';
  if(this < (1).exabytes())  return (this / (1).petabytes()).toPrecision() + ' PB';
                             return (this / (1).exabytes()).toPrecision()  + ' EB';
}
<|endoftext|>


<commit_before>// A modal for force-exporting a group of docs
// to other locales. Acts as a dataSource for
// the force-export batch operation, does not
// invoke the force export API on its own

apos.define('apostrophe-workflow-batch-force-export-modal', {

  extend: 'apostrophe-workflow-export-modal',

  source: 'batch-force-export-modal',

  construct: function(self, options) {

    var superBeforeShow = self.beforeShow;
    var relatedByType;

    self.beforeShow = function(callback) {
      return superBeforeShow(function(err) {
        if (err) {
          return callback(err);
        }
        self.$el.on('change', '[name="related"]', function() {
          if (!relatedByType) {
            apos.ui.globalBusy(true);
            self.api('count-related-by-type', {
              ids: self.options.body.ids
            }, function(data) {
              apos.ui.globalBusy(false);
              if (data.status !== 'ok') {
                return callback(data.status);
              }
              self.$el.find('[data-related-types]').html(data.html);
            }, function(err) {
              apos.ui.globalBusy(false);
              return callback(err);
            });
          }
        });
        return callback(null);
      });
    };

    self.saveContent = function(callback) {
      var locales = self.getLocales();
      if (!locales.length) {
        apos.notify('Select at least one locale to export to.', { type: 'error' });
        return callback('user');
      }
      var related = self.$el.findByName('related').prop('checked');
      // Modifying the `body` object passed to us
      // by batchForceExportGetLocales allows that
      // method to see the locales that were chosen
      self.options.body.locales = locales;
      self.options.body.related = related;
      self.options.body.relatedTypes = [];
      self.$el.find('[name="relatedTypes"]:checked').each(function() {
        self.options.body.relatedTypes.push($(this).attr('value'));
      });
      console.log(self.options.body.relatedTypes);
      return callback(null);
    };

  }
});
<commit_msg>no console.log<commit_after>// A modal for force-exporting a group of docs
// to other locales. Acts as a dataSource for
// the force-export batch operation, does not
// invoke the force export API on its own

apos.define('apostrophe-workflow-batch-force-export-modal', {

  extend: 'apostrophe-workflow-export-modal',

  source: 'batch-force-export-modal',

  construct: function(self, options) {

    var superBeforeShow = self.beforeShow;
    var relatedByType;

    self.beforeShow = function(callback) {
      return superBeforeShow(function(err) {
        if (err) {
          return callback(err);
        }
        self.$el.on('change', '[name="related"]', function() {
          if (!relatedByType) {
            apos.ui.globalBusy(true);
            self.api('count-related-by-type', {
              ids: self.options.body.ids
            }, function(data) {
              apos.ui.globalBusy(false);
              if (data.status !== 'ok') {
                return callback(data.status);
              }
              self.$el.find('[data-related-types]').html(data.html);
            }, function(err) {
              apos.ui.globalBusy(false);
              return callback(err);
            });
          }
        });
        return callback(null);
      });
    };

    self.saveContent = function(callback) {
      var locales = self.getLocales();
      if (!locales.length) {
        apos.notify('Select at least one locale to export to.', { type: 'error' });
        return callback('user');
      }
      var related = self.$el.findByName('related').prop('checked');
      // Modifying the `body` object passed to us
      // by batchForceExportGetLocales allows that
      // method to see the locales that were chosen
      self.options.body.locales = locales;
      self.options.body.related = related;
      self.options.body.relatedTypes = [];
      self.$el.find('[name="relatedTypes"]:checked').each(function() {
        self.options.body.relatedTypes.push($(this).attr('value'));
      });
      return callback(null);
    };

  }
});
<|endoftext|>


<commit_before>
/**
 * models for cartodb admin
 */

(function() {

  /**
   * current user running app
   */
  cdb.admin.User = Backbone.Model.extend({});

  /**
   * contains table meta information like name
   * rows and so on
   */
  cdb.admin.Table = cdb.ui.common.TableProperties.extend({
    idAttribute: 'name'
  });

  /**
   * tables available for given user
   * usage:
   * var tables = new cbd.admin.Tables()
   */
  cdb.admin.Tables = Backbone.Collection.extend({

    model: cdb.admin.Table,

    url: function() {
      //TODO: use current host
      //var name = this.options.user.get('name');
      return '/api/v1/tables';
    },

    initialize: function() {
    }
  });

})();
<commit_msg>table doc<commit_after>
/**
 * models for cartodb admin
 */

(function() {

  /**
   * current user running app
   */
  cdb.admin.User = Backbone.Model.extend({});

  /**
   * contains table meta information like name
   * rows and so on
   */
  cdb.admin.Table = cdb.ui.common.TableProperties.extend({
    idAttribute: 'name'
  });

  /**
   * tables available for given user
   * usage:
   * var tables = new cbd.admin.Tables()
   * tables.fetch();
   */
  cdb.admin.Tables = Backbone.Collection.extend({

    model: cdb.admin.Table,

    url: function() {
      //TODO: use current host
      //var name = this.options.user.get('name');
      return '/api/v1/tables';
    },

    initialize: function() {
    }
  });

})();
<|endoftext|>


<commit_before>'use strict';

var app = app || {};

(function (module){

  const genView= {};

  genView.appendSocial = function(){
    app.words.checkInst()
    app.words.checkGit()
    app.words.checkTwit()
  }

  genView.init = function (){
  $('.generator').show().siblings().hide();
  genView.populateSlots();
  };

  //  This function will repopulate slots when user clicks re-roll button
  $("#re-roll").click(function(){
    console.log("wokrs")
    app.genView.populateSlots()
  });

  // append our app.words.slotArray to the DOM
  genView.appendWords = function () {
    app.words.slotArray.forEach( function ( arrayEle, currentIndex, array) {
      let idName = '#slot' + (currentIndex+1);

      //TODO: move concatType to global
      let concatType = 'none';

      //If data-saved isn't true, append to DOM
      if ( $(idName).attr('data-saved') !== 'true' ) {
        switch (concatType) {
          case 'camelCase':
            if (currentIndex > 0) {
              let newElement = arrayEle.split('');
              newElement[0] = newElement[0].toUpperCase();
              $(idName).text(newElement.join(''));
              break;
            }
          case 'hyphenated':
            if (currentIndex > 0) {
              $(idName).text('-' + arrayEle);
              break;
            }
          case 'snakeCase':
            if (currentIndex > 0) {
              $(idName).text('_' + arrayEle);
              break;
            }
          case 'none':
              $(idName).text(arrayEle);
        }
      }

      //Update currentHandle variable
      genView.updateCurrentHandle();

      //Add event listener to toggle "data-saved" status
      $(idName).off('click');
      $(idName).on('click',function(){
        $(idName).attr('data-saved') === 'true' ? $(idName).attr('data-saved', false) : $(idName).attr('data-saved', true);
        console.log(idName,'is clicked. data-saved value is',$(idName).attr('data-saved'))
        })

    });
  }

  //Update currentHandle with current displayed handle
  genView.updateCurrentHandle = function () {
    app.words.currentHandle = '';
    for (let i = 0; i < $('.slots').children().length; i++){
      app.words.currentHandle += $('.slots').children().eq(i).text();
      //TODO: refactor to accomodate concationation options
    }
    //TODO: append currentHandle to DOM
    console.log('currentHandle is now',app.words.currentHandle);
  }

  // populates our slots.
  genView.populateSlots = function() {
    app.words.randomizeAll()
    genView.appendWords()
  }

module.genView = genView

})(app);<commit_msg>commit before integrating switch<commit_after>'use strict';

var app = app || {};

(function (module){

  const genView= {};

  genView.appendSocial = function(){
    app.words.checkInst()
    app.words.checkGit()
    app.words.checkTwit()
  }

  genView.init = function (){
    $('.generator').show().siblings().hide();
    genView.populateSlots();
  };

  //  This function will repopulate slots when user clicks re-roll button
  $("#re-roll").click(function(){
    console.log("wokrs")
    app.genView.populateSlots()
  });

  //TODO: add switch function to currentHandle process
        // //If data-saved isn't true, append to DOM
        // if ( $(idName).attr('data-saved') !== 'true' ) {
        //   switch (concatType) {
        //     case 'camelCase':
        //       if (currentIndex > 0) {
        //         let newElement = arrayEle.split('');
        //         newElement[0] = newElement[0].toUpperCase();
        //         $(idName).text(newElement.join(''));
        //         break;
        //       }
        //     case 'hyphenated':
        //       if (currentIndex > 0) {
        //         $(idName).text('-' + arrayEle);
        //         break;
        //       }
        //     case 'snakeCase':
        //       if (currentIndex > 0) {
        //         $(idName).text('_' + arrayEle);
        //         break;
        //       }
        //     case 'none':
        //         $(idName).text(arrayEle);
        //   }
        // }

    // append our app.words.slotArray to the DOM
  genView.appendWords = function () {
    app.words.slotArray.forEach( function ( arrayEle, currentIndex, array) {
      let idName = '#slot' + (currentIndex+1);

      //If data-saved
      if ( $(idName).attr('data-saved') !== 'true' ) { $(idName).text(arrayEle); }

      //Update currentHandle variable
      genView.updateCurrentHandle();

      //Add event listener to toggle "data-saved" status
      $(idName).off('click');
      $(idName).on('click',function(){
        $(idName).attr('data-saved') === 'true' ? $(idName).attr('data-saved', false) : $(idName).attr('data-saved', true);
        console.log(idName,'is clicked. data-saved value is',$(idName).attr('data-saved'))
        })

    });
  }

  //Update currentHandle with current displayed handle
  genView.updateCurrentHandle = function () {
    app.words.currentHandle = '';
    for (let i = 0; i < $('.slots').children().length; i++){
      app.words.currentHandle += $('.slots').children().eq(i).text();
      //TODO: refactor to accomodate concationation options
    }
    //TODO: append currentHandle to DOM
    console.log('currentHandle is now',app.words.currentHandle);
  }

  // populates our slots.
  genView.populateSlots = function() {
    app.words.randomizeAll()
    genView.appendWords()
  }

module.genView = genView

})(app);<|endoftext|>