<commit_before>/**
 * impress.js
 *
 * impress.js is a presentation tool based on the power of CSS3 transforms and transitions
 * in modern browsers and inspired by the idea behind prezi.com.
 *
 *
 * Copyright 2011-2012 Bartek Szopka (@bartaz)
 *
 * Released under the MIT and GPL Licenses.
 *
 * ------------------------------------------------
 *  author:  Bartek Szopka
 *  version: 0.5.3
 *  url:     http://bartaz.github.com/impress.js/
 *  source:  http://github.com/bartaz/impress.js/
 */

/*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, latedef:true, newcap:true,
         noarg:true, noempty:true, undef:true, strict:true, browser:true */

// You are one of those who like to know how things work inside?
// Let me show you the cogs that make impress.js run...
(function ( document, window ) {
    'use strict';

    // HELPER FUNCTIONS

    // `pfx` is a function that takes a standard CSS property name as a parameter
    // and returns it's prefixed version valid for current browser it runs in.
    // The code is heavily inspired by Modernizr http://www.modernizr.com/
    var pfx = (function () {

        var style = document.createElement('dummy').style,
            prefixes = 'Webkit Moz O ms Khtml'.split(' '),
            memory = {};

        return function ( prop ) {
            if ( typeof memory[ prop ] === "undefined" ) {

                var ucProp  = prop.charAt(0).toUpperCase() + prop.substr(1),
                    props   = (prop + ' ' + prefixes.join(ucProp + ' ') + ucProp).split(' ');

                memory[ prop ] = null;
                for ( var i in props ) {
                    if ( style[ props[i] ] !== undefined ) {
                        memory[ prop ] = props[i];
                        break;
                    }
                }

            }

            return memory[ prop ];
        };

    })();

    // `arraify` takes an array-like object and turns it into real Array
    // to make all the Array.prototype goodness available.
    var arrayify = function ( a ) {
        return [].slice.call( a );
    };

    // `css` function applies the styles given in `props` object to the element
    // given as `el`. It runs all property names through `pfx` function to make
    // sure proper prefixed version of the property is used.
    var css = function ( el, props ) {
        var key, pkey;
        for ( key in props ) {
            if ( props.hasOwnProperty(key) ) {
                pkey = pfx(key);
                if ( pkey !== null ) {
                    el.style[pkey] = props[key];
                }
            }
        }
        return el;
    };

    // `toNumber` takes a value given as `numeric` parameter and tries to turn
    // it into a number. If it is not possible it returns 0 (or other value
    // given as `fallback`).
    var toNumber = function (numeric, fallback) {
        return isNaN(numeric) ? (fallback || 0) : Number(numeric);
    };

    // `byId` returns element with given `id` - you probably have guessed that ;)
    var byId = function ( id ) {
        return document.getElementById(id);
    };

    // `$` returns first element for given CSS `selector` in the `context` of
    // the given element or whole document.
    var $ = function ( selector, context ) {
        context = context || document;
        return context.querySelector(selector);
    };

    // `$$` return an array of elements for given CSS `selector` in the `context` of
    // the given element or whole document.
    var $$ = function ( selector, context ) {
        context = context || document;
        return arrayify( context.querySelectorAll(selector) );
    };

    // `triggerEvent` builds a custom DOM event with given `eventName` and `detail` data
    // and triggers it on element given as `el`.
    var triggerEvent = function (el, eventName, detail) {
        var event = document.createEvent("CustomEvent");
        event.initCustomEvent(eventName, true, true, detail);
        el.dispatchEvent(event);
    };

    // `translate` builds a translate transform string for given data.
    var translate = function ( t ) {
        return " translate3d(" + t.x + "px," + t.y + "px," + t.z + "px) ";
    };

    // `rotate` builds a rotate transform string for given data.
    // By default the rotations are in X Y Z order that can be reverted by passing `true`
    // as second parameter.
    var rotate = function ( r, revert ) {
        var rX = " rotateX(" + r.x + "deg) ",
            rY = " rotateY(" + r.y + "deg) ",
            rZ = " rotateZ(" + r.z + "deg) ";

        return revert ? rZ+rY+rX : rX+rY+rZ;
    };

    // `scale` builds a scale transform string for given data.
    var scale = function ( s ) {
        return " scale(" + s + ") ";
    };

    // `perspective` builds a perspective transform string for given data.
    var perspective = function ( p ) {
        return " perspective(" + p + "px) ";
    };

    // `getElementFromHash` returns an element located by id from hash part of
    // window location.
    var getElementFromHash = function () {
        // get id from url # by removing `#` or `#/` from the beginning,
        // so both "fallback" `#slide-id` and "enhanced" `#/slide-id` will work
        return byId( window.location.hash.replace(/^#\/?/,"") );
    };

    // `computeWindowScale` counts the scale factor between window size and size
    // defined for the presentation in the config.
    var computeWindowScale = function ( config ) {
        var hScale = window.innerHeight / config.height,
            wScale = window.innerWidth / config.width,
            scale = hScale > wScale ? wScale : hScale;

        if (config.maxScale && scale > config.maxScale) {
            scale = config.maxScale;
        }

        if (config.minScale && scale < config.minScale) {
            scale = config.minScale;
        }

        return scale;
    };

    // CHECK SUPPORT
    var body = document.body;

    var ua = navigator.userAgent.toLowerCase();
    var impressSupported =
                          // browser should support CSS 3D transtorms
                           ( pfx("perspective") !== null ) &&

                          // and `classList` and `dataset` APIs
                           ( body.classList ) &&
                           ( body.dataset ) &&

                          // but some mobile devices need to be blacklisted,
                          // because their CSS 3D support or hardware is not
                          // good enough to run impress.js properly, sorry...
                           ( ua.search(/(iphone)|(ipod)|(android)/) === -1 );

    if (!impressSupported) {
        // we can't be sure that `classList` is supported
        body.className += " impress-not-supported ";
    } else {
        body.classList.remove("impress-not-supported");
        body.classList.add("impress-supported");
    }

    // GLOBALS AND DEFAULTS

    // This is where the root elements of all impress.js instances will be kept.
    // Yes, this means you can have more than one instance on a page, but I'm not
    // sure if it makes any sense in practice ;)
    var roots = {};

    // some default config values.
    var defaults = {
        width: 1024,
        height: 768,
        maxScale: 1,
        minScale: 0,

        perspective: 1000,

        transitionDuration: 1000
    };

    // it's just an empty function ... and a useless comment.
    var empty = function () { return false; };

    // IMPRESS.JS API

    // And that's where interesting things will start to happen.
    // It's the core `impress` function that returns the impress.js API
    // for a presentation based on the element with given id ('impress'
    // by default).
    var impress = window.impress = function ( rootId ) {

        // If impress.js is not supported by the browser return a dummy API
        // it may not be a perfect solution but we return early and avoid
        // running code that may use features not implemented in the browser.
        if (!impressSupported) {
            return {
                init: empty,
                goto: empty,
                prev: empty,
                next: empty
            };
        }

        rootId = rootId || "impress";

        // if given root is already initialized just return the API
        if (roots["impress-root-" + rootId]) {
            return roots["impress-root-" + rootId];
        }

        // data of all presentation steps
        var stepsData = {};

        // element of currently active step
        var activeStep = null;

        // current state (position, rotation and scale) of the presentation
        var currentState = null;

        // array of step elements
        var steps = null;

        // configuration options
        var config = null;

        // scale factor of the browser window
        var windowScale = null;

        // root presentation elements
        var root = byId( rootId );
        var canvas = document.createElement("div");

        var initialized = false;

        // STEP EVENTS
        //
        // There are currently two step events triggered by impress.js
        // `impress:stepenter` is triggered when the step is shown on the
        // screen (the transition from the previous one is finished) and
        // `impress:stepleave` is triggered when the step is left (the
        // transition to next step just starts).

        // reference to last entered step
        var lastEntered = null;

        // `onStepEnter` is called whenever the step element is entered
        // but the event is triggered only if the step is different than
        // last entered step.
        var onStepEnter = function (step) {
            if (lastEntered !== step) {
                triggerEvent(step, "impress:stepenter");
                lastEntered = step;
            }
        };

        // `onStepLeave` is called whenever the step element is left
        // but the event is triggered only if the step is the same as
        // last entered step.
        var onStepLeave = function (step) {
            if (lastEntered === step) {
                triggerEvent(step, "impress:stepleave");
                lastEntered = null;
            }
        };

        // `initStep` initializes given step element by reading data from its
        // data attributes and setting correct styles.
        var initStep = function ( el, idx ) {
            var data = el.dataset,
                step = {
                    translate: {
                        x: toNumber(data.x),
                        y: toNumber(data.y),
                        z: toNumber(data.z)
                    },
                    rotate: {
                        x: toNumber(data.rotateX),
                        y: toNumber(data.rotateY),
                        z: toNumber(data.rotateZ || data.rotate)
                    },
                    scale: toNumber(data.scale, 1),
                    el: el
                };

            if ( !el.id ) {
                el.id = "step-" + (idx + 1);
            }

            stepsData["impress-" + el.id] = step;

            css(el, {
                position: "absolute",
                transform: "translate(-50%,-50%)" +
                           translate(step.translate) +
                           rotate(step.rotate) +
                           scale(step.scale),
                transformStyle: "preserve-3d"
            });
        };

        // `init` API function that initializes (and runs) the presentation.
        var init = function () {
            if (initialized) { return; }

            // First we set up the viewport for mobile devices.
            // For some reason iPad goes nuts when it is not done properly.
            var meta = $("meta[name='viewport']") || document.createElement("meta");
            meta.content = "width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no";
            if (meta.parentNode !== document.head) {
                meta.name = 'viewport';
                document.head.appendChild(meta);
            }

            // initialize configuration object
            var rootData = root.dataset;
            config = {
                width: toNumber( rootData.width, defaults.width ),
                height: toNumber( rootData.height, defaults.height ),
                maxScale: toNumber( rootData.maxScale, defaults.maxScale ),
                minScale: toNumber( rootData.minScale, defaults.minScale ),
                perspective: toNumber( rootData.perspective, defaults.perspective ),
                transitionDuration: toNumber( rootData.transitionDuration, defaults.transitionDuration )
            };

            windowScale = computeWindowScale( config );

            // wrap steps with "canvas" element
            arrayify( root.childNodes ).forEach(function ( el ) {
                canvas.appendChild( el );
            });
            root.appendChild(canvas);

            // set initial styles
            document.documentElement.style.height = "100%";

            css(body, {
                height: "100%",
                overflow: "hidden"
            });

            var rootStyles = {
                position: "absolute",
                transformOrigin: "top left",
                transition: "all 0s ease-in-out",
                transformStyle: "preserve-3d"
            };

            css(root, rootStyles);
            css(root, {
                top: "50%",
                left: "50%",
                transform: perspective( config.perspective/windowScale ) + scale( windowScale )
            });
            css(canvas, rootStyles);

            body.classList.remove("impress-disabled");
            body.classList.add("impress-enabled");

            // get and init steps
            steps = $$(".step", root);
            steps.forEach( initStep );

            // set a default initial state of the canvas
            currentState = {
                translate: { x: 0, y: 0, z: 0 },
                rotate:    { x: 0, y: 0, z: 0 },
                scale:     1
            };

            initialized = true;

            triggerEvent(root, "impress:init", { api: roots[ "impress-root-" + rootId ] });
        };

        // `getStep` is a helper function that returns a step element defined by parameter.
        // If a number is given, step with index given by the number is returned, if a string
        // is given step element with such id is returned, if DOM element is given it is returned
        // if it is a correct step element.
        var getStep = function ( step ) {
            if (typeof step === "number") {
                step = step < 0 ? steps[ steps.length + step] : steps[ step ];
            } else if (typeof step === "string") {
                step = byId(step);
            }
            return (step && step.id && stepsData["impress-" + step.id]) ? step : null;
        };

        // used to reset timeout for `impress:stepenter` event
        var stepEnterTimeout = null;

        // `goto` API function that moves to step given with `el` parameter (by index, id or element),
        // with a transition `duration` optionally given as second parameter.
        var goto = function ( el, duration ) {

            if ( !initialized || !(el = getStep(el)) ) {
                // presentation not initialized or given element is not a step
                return false;
            }

            // Sometimes it's possible to trigger focus on first link with some keyboard action.
            // Browser in such a case tries to scroll the page to make this element visible
            // (even that body overflow is set to hidden) and it breaks our careful positioning.
            //
            // So, as a lousy (and lazy) workaround we will make the page scroll back to the top
            // whenever slide is selected
            //
            // If you are reading this and know any better way to handle it, I'll be glad to hear about it!
            window.scrollTo(0, 0);

            var step = stepsData["impress-" + el.id];

            if ( activeStep ) {
                activeStep.classList.remove("active");
                body.classList.remove("impress-on-" + activeStep.id);
            }
            el.classList.add("active");

            body.classList.add("impress-on-" + el.id);

            // compute target state of the canvas based on given step
            var target = {
                rotate: {
                    x: -step.rotate.x,
                    y: -step.rotate.y,
                    z: -step.rotate.z
                },
                translate: {
                    x: -step.translate.x,
                    y: -step.translate.y,
                    z: -step.translate.z
                },
                scale: 1 / step.scale
            };

            // Check if the transition is zooming in or not.
            //
            // This information is used to alter the transition style:
            // when we are zooming in - we start with move and rotate transition
            // and the scaling is delayed, but when we are zooming out we start
            // with scaling down and move and rotation are delayed.
            var zoomin = target.scale >= currentState.scale;

            duration = toNumber(duration, config.transitionDuration);
            var delay = (duration / 2);

            // if the same step is re-selected, force computing window scaling,
            // because it is likely to be caused by window resize
            if (el === activeStep) {
                windowScale = computeWindowScale(config);
            }

            var targetScale = target.scale * windowScale;

            // trigger leave of currently active element (if it's not the same step again)
            if (activeStep && activeStep !== el) {
                onStepLeave(activeStep);
            }

            // Now we alter transforms of `root` and `canvas` to trigger transitions.
            //
            // And here is why there are two elements: `root` and `canvas` - they are
            // being animated separately:
            // `root` is used for scaling and `canvas` for translate and rotations.
            // Transitions on them are triggered with different delays (to make
            // visually nice and 'natural' looking transitions), so we need to know
            // that both of them are finished.
            css(root, {
                // to keep the perspective look similar for different scales
                // we need to 'scale' the perspective, too
                transform: perspective( config.perspective / targetScale ) + scale( targetScale ),
                transitionDuration: duration + "ms",
                transitionDelay: (zoomin ? delay : 0) + "ms"
            });

            css(canvas, {
                transform: rotate(target.rotate, true) + translate(target.translate),
                transitionDuration: duration + "ms",
                transitionDelay: (zoomin ? 0 : delay) + "ms"
            });

            // Here is a tricky part...
            //
            // If there is no change in scale or no change in rotation and translation, it means there was actually
            // no delay - because there was no transition on `root` or `canvas` elements.
            // We want to trigger `impress:stepenter` event in the correct moment, so here we compare the current
            // and target values to check if delay should be taken into account.
            //
            // I know that this `if` statement looks scary, but it's pretty simple when you know what is going on
            // - it's simply comparing all the values.
            if ( currentState.scale === target.scale ||
                (currentState.rotate.x === target.rotate.x && currentState.rotate.y === target.rotate.y &&
                 currentState.rotate.z === target.rotate.z && currentState.translate.x === target.translate.x &&
                 currentState.translate.y === target.translate.y && currentState.translate.z === target.translate.z) ) {
                delay = 0;
            }

            // store current state
            currentState = target;
            activeStep = el;

            // And here is where we trigger `impress:stepenter` event.
            // We simply set up a timeout to fire it taking transition duration (and possible delay) into account.
            //
            // I really wanted to make it in more elegant way. The `transitionend` event seemed to be the best way
            // to do it, but the fact that I'm using transitions on two separate elements and that the `transitionend`
            // event is only triggered when there was a transition (change in the values) caused some bugs and
            // made the code really complicated, cause I had to handle all the conditions separately. And it still
            // needed a `setTimeout` fallback for the situations when there is no transition at all.
            // So I decided that I'd rather make the code simpler than use shiny new `transitionend`.
            //
            // If you want learn something interesting and see how it was done with `transitionend` go back to
            // version 0.5.2 of impress.js: http://github.com/bartaz/impress.js/blob/0.5.2/js/impress.js
            window.clearTimeout(stepEnterTimeout);
            stepEnterTimeout = window.setTimeout(function() {
                onStepEnter(activeStep);
            }, duration + delay);

            return el;
        };

        // `prev` API function goes to previous step (in document order)
        var prev = function () {
            var prev = steps.indexOf( activeStep ) - 1;
            prev = prev >= 0 ? steps[ prev ] : steps[ steps.length-1 ];

            return goto(prev);
        };

        // `next` API function goes to next step (in document order)
        var next = function () {
            var next = steps.indexOf( activeStep ) + 1;
            next = next < steps.length ? steps[ next ] : steps[ 0 ];

            return goto(next);
        };

        // Adding some useful classes to step elements.
        //
        // All the steps that have not been shown yet are given `future` class.
        // When the step is entered the `future` class is removed and the `present`
        // class is given. When the step is left `present` class is replaced with
        // `past` class.
        //
        // So every step element is always in one of three possible states:
        // `future`, `present` and `past`.
        //
        // There classes can be used in CSS to style different types of steps.
        // For example the `present` class can be used to trigger some custom
        // animations when step is shown.
        root.addEventListener("impress:init", function(){
            // STEP CLASSES
            steps.forEach(function (step) {
                step.classList.add("future");
            });

            root.addEventListener("impress:stepenter", function (event) {
                event.target.classList.remove("past");
                event.target.classList.remove("future");
                event.target.classList.add("present");
            }, false);

            root.addEventListener("impress:stepleave", function (event) {
                event.target.classList.remove("present");
                event.target.classList.add("past");
            }, false);

        }, false);

        // Adding hash change support.
        root.addEventListener("impress:init", function(){

            // last hash detected
            var lastHash = "";

            // `#/step-id` is used instead of `#step-id` to prevent default browser
            // scrolling to element in hash.
            //
            // And it has to be set after animation finishes, because in Chrome it
            // makes transtion laggy.
            // BUG: http://code.google.com/p/chromium/issues/detail?id=62820
            root.addEventListener("impress:stepenter", function (event) {
                window.location.hash = lastHash = "#/" + event.target.id;
            }, false);

            window.addEventListener("hashchange", function () {
                // When the step is entered hash in the location is updated
                // (just few lines above from here), so the hash change is
                // triggered and we would call `goto` again on the same element.
                //
                // To avoid this we store last entered hash and compare.
                if (window.location.hash !== lastHash) {
                    goto( getElementFromHash() );
                }
            }, false);

            // START
            // by selecting step defined in url or first step of the presentation
            goto(getElementFromHash() || steps[0], 0);
        }, false);

        body.classList.add("impress-disabled");

        // store and return API for given impress.js root element
        return (roots[ "impress-root-" + rootId ] = {
            init: init,
            goto: goto,
            next: next,
            prev: prev
        });

    };

    // flag that can be used in JS to check if browser have passed the support test
    impress.supported = impressSupported;

})(document, window);

// NAVIGATION EVENTS

// As you can see this part is separate from the impress.js core code.
// It's because these navigation actions only need what impress.js provides with
// its simple API.
//
// In future I think about moving it to make them optional, move to separate files
// and treat more like a 'plugins'.
(function ( document, window ) {
    'use strict';

    // throttling function calls, by Remy Sharp
    // http://remysharp.com/2010/07/21/throttling-function-calls/
    var throttle = function (fn, delay) {
        var timer = null;
        return function () {
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        };
    };

    // wait for impress.js to be initialized
    document.addEventListener("impress:init", function (event) {
        // Getting API from event data.
        // So you don't event need to know what is the id of the root element
        // or anything. `impress:init` event data gives you everything you
        // need to control the presentation that was just initialized.
        var api = event.detail.api;

        // KEYBOARD NAVIGATION HANDLERS

        // Prevent default keydown action when one of supported key is pressed.
        document.addEventListener("keydown", function ( event ) {
            if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
                event.preventDefault();
            }
        }, false);

        // Trigger impress action (next or prev) on keyup.

        // Supported keys are:
        // [space] - quite common in presentation software to move forward
        // [up] [right] / [down] [left] - again common and natural addition,
        // [pgdown] / [pgup] - often triggered by remote controllers,
        // [tab] - this one is quite controversial, but the reason it ended up on
        //   this list is quite an interesting story... Remember that strange part
        //   in the impress.js code where window is scrolled to 0,0 on every presentation
        //   step, because sometimes browser scrolls viewport because of the focused element?
        //   Well, the [tab] key by default navigates around focusable elements, so clicking
        //   it very often caused scrolling to focused element and breaking impress.js
        //   positioning. I didn't want to just prevent this default action, so I used [tab]
        //   as another way to moving to next step... And yes, I know that for the sake of
        //   consistency I should add [shift+tab] as opposite action...
        document.addEventListener("keyup", function ( event ) {
            if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
                switch( event.keyCode ) {
                    case 33: // pg up
                    case 37: // left
                    case 38: // up
                             api.prev();
                             break;
                    case 9:  // tab
                    case 32: // space
                    case 34: // pg down
                    case 39: // right
                    case 40: // down
                             api.next();
                             break;
                }

                event.preventDefault();
            }
        }, false);

        // delegated handler for clicking on the links to presentation steps
        document.addEventListener("click", function ( event ) {
            // event delegation with "bubbling"
            // check if event target (or any of its parents is a link)
            var target = event.target;
            while ( (target.tagName !== "A") &&
                    (target !== document.documentElement) ) {
                target = target.parentNode;
            }

            if ( target.tagName === "A" ) {
                var href = target.getAttribute("href");

                // if it's a link to presentation step, target this step
                if ( href && href[0] === '#' ) {
                    target = document.getElementById( href.slice(1) );
                }
            }

            if ( api.goto(target) ) {
                event.stopImmediatePropagation();
                event.preventDefault();
            }
        }, false);

        // delegated handler for clicking on step elements
        document.addEventListener("click", function ( event ) {
            var target = event.target;
            // find closest step element that is not active
            while ( !(target.classList.contains("step") && !target.classList.contains("active")) &&
                    (target !== document.documentElement) ) {
                target = target.parentNode;
            }

            if ( api.goto(target) ) {
                event.preventDefault();
            }
        }, false);

        // touch handler to detect taps on the left and right side of the screen
        // based on awesome work of @hakimel: https://github.com/hakimel/reveal.js
        document.addEventListener("touchstart", function ( event ) {
            if (event.touches.length === 1) {
                var x = event.touches[0].clientX,
                    width = window.innerWidth * 0.3,
                    result = null;

                if ( x < width ) {
                    result = api.prev();
                } else if ( x > window.innerWidth - width ) {
                    result = api.next();
                }

                if (result) {
                    event.preventDefault();
                }
            }
        }, false);

        // rescale presentation when window is resized
        window.addEventListener("resize", throttle(function () {
            // force going to active step again, to trigger rescaling
            api.goto( document.querySelector(".step.active"), 500 );
        }, 250), false);

    }, false);

})(document, window);

// THAT'S ALL FOLKS!
//
// Thanks for reading it all.
// Or thanks for scrolling down and reading the last part.
//
// I've learnt a lot when building impress.js and I hope this code and comments
// will help somebody learn at least some part of it.
<commit_msg>removed impressjs<commit_after><|endoftext|>


<commit_before>var Bounds = require('../util/Bounds'),
    canvas = require('../util/canvas'),
    svg = require('../util/svg'),
    font = require('./font'),
    paths = require('../path'),
    parse = paths.parse,
    boundPath = paths.bounds,
    areaPath = svg.path.area,
    linePath = svg.path.line,
    halfpi = Math.PI / 2,
    sqrt3 = Math.sqrt(3),
    tan30 = Math.tan(30 * Math.PI / 180),
    g2D = null;

function context() {
  return g2D || (g2D = canvas.instance(1,1).getContext('2d'));
}

function strokeBounds(o, bounds) {
  if (o.stroke && o.opacity !== 0 && o.stokeOpacity !== 0) {
    bounds.expand(o.strokeWidth != null ? o.strokeWidth : 1);
  }
  return bounds;
}

function pathBounds(o, path, bounds) {
  if (path == null) {
    bounds.set(0, 0, 0, 0);
  } else {
    boundPath(path, bounds);
    strokeBounds(o, bounds);
  }
  return bounds;
}

function path(o, bounds) {
  var p = o.path ? o.pathCache || (o.pathCache = parse(o.path)) : null;
  return pathBounds(o, p, bounds).translate(o.x || 0, o.y || 0);
}

function area(mark, bounds) {
  var items = mark.items,
      item = items[0],
      p = item.pathCache || (item.pathCache = parse(areaPath(items)));
  return pathBounds(item, p, bounds);
}

function line(mark, bounds) {
  var items = mark.items,
      item = items[0],
      p = item.pathCache || (item.pathCache = parse(linePath(items)));
  return pathBounds(item, p, bounds);
}

function rect(o, bounds) {
  var x, y;
  return strokeBounds(o, bounds.set(
    x = o.x || 0,
    y = o.y || 0,
    (x + o.width) || 0,
    (y + o.height) || 0
  ));
}

function image(o, bounds) {
  var x = o.x || 0,
      y = o.y || 0,
      w = o.width || 0,
      h = o.height || 0;
  x = x - (o.align === 'center' ? w/2 : (o.align === 'right' ? w : 0));
  y = y - (o.baseline === 'middle' ? h/2 : (o.baseline === 'bottom' ? h : 0));
  return bounds.set(x, y, x+w, y+h);
}

function rule(o, bounds) {
  var x1, y1;
  return strokeBounds(o, bounds.set(
    x1 = o.x || 0,
    y1 = o.y || 0,
    o.x2 != null ? o.x2 : x1,
    o.y2 != null ? o.y2 : y1
  ));
}

function arc(o, bounds) {
  var cx = o.x || 0,
      cy = o.y || 0,
      ir = o.innerRadius || 0,
      or = o.outerRadius || 0,
      sa = (o.startAngle || 0) - halfpi,
      ea = (o.endAngle || 0) - halfpi,
      xmin = Infinity, xmax = -Infinity,
      ymin = Infinity, ymax = -Infinity,
      a, i, n, x, y, ix, iy, ox, oy;

  var angles = [sa, ea],
      s = sa - (sa % halfpi);
  for (i=0; i<4 && s<ea; ++i, s+=halfpi) {
    angles.push(s);
  }

  for (i=0, n=angles.length; i<n; ++i) {
    a = angles[i];
    x = Math.cos(a); ix = ir*x; ox = or*x;
    y = Math.sin(a); iy = ir*y; oy = or*y;
    xmin = Math.min(xmin, ix, ox);
    xmax = Math.max(xmax, ix, ox);
    ymin = Math.min(ymin, iy, oy);
    ymax = Math.max(ymax, iy, oy);
  }

  return strokeBounds(o, bounds.set(
    cx + xmin,
    cy + ymin,
    cx + xmax,
    cy + ymax
  ));
}

function symbol(o, bounds) {
  var size = o.size != null ? o.size : 100,
      x = o.x || 0,
      y = o.y || 0,
      r, t, rx, ry;

  switch (o.shape) {
    case 'cross':
      r = Math.sqrt(size / 5) / 2;
      t = 3*r;
      bounds.set(x-t, y-r, x+t, y+r);
      break;

    case 'diamond':
      ry = Math.sqrt(size / (2 * tan30));
      rx = ry * tan30;
      bounds.set(x-rx, y-ry, x+rx, y+ry);
      break;

    case 'square':
      t = Math.sqrt(size);
      r = t / 2;
      bounds.set(x-r, y-r, x+r, y+r);
      break;

    case 'triangle-down':
      rx = Math.sqrt(size / sqrt3);
      ry = rx * sqrt3 / 2;
      bounds.set(x-rx, y-ry, x+rx, y+ry);
      break;

    case 'triangle-up':
      rx = Math.sqrt(size / sqrt3);
      ry = rx * sqrt3 / 2;
      bounds.set(x-rx, y-ry, x+rx, y+ry);
      break;

    default:
      r = Math.sqrt(size/Math.PI);
      bounds.set(x-r, y-r, x+r, y+r);
  }

  return strokeBounds(o, bounds);
}

function text(o, bounds, noRotate) {
  var x = (o.x || 0) + (o.dx || 0),
      y = (o.y || 0) + (o.dy || 0),
      h = font.size(o),
      a = o.align,
      r = o.radius || 0,
      g = context(), w, t;

  g.font = font.string(o);
  w = g.measureText(o.text || '').width;

  if (r) {
    t = (o.theta || 0) - Math.PI/2;
    x += r * Math.cos(t);
    y += r * Math.sin(t);
  }

  // horizontal
  if (a === 'center') {
    x = x - (w / 2);
  } else if (a === 'right') {
    x = x - w;
  } else {
    // left by default, do nothing
  }

  // vertical
  y += font.offset(o) - Math.round(0.8*h);

  bounds.set(x, y, x+w, y+h);
  if (o.angle && !noRotate) {
    bounds.rotate(o.angle*Math.PI/180, o.x||0, o.y||0);
  }
  return bounds.expand(noRotate ? 0 : 1);
}

function group(g, bounds, includeLegends) {
  var axes = g.axisItems || [],
      items = g.items || [],
      legends = g.legendItems || [],
      j, m;

  for (j=0, m=axes.length; j<m; ++j) {
    bounds.union(axes[j].bounds);
  }
  for (j=0, m=items.length; j<m; ++j) {
    bounds.union(items[j].bounds);
  }
  if (includeLegends) {
    for (j=0, m=legends.length; j<m; ++j) {
      bounds.union(legends[j].bounds);
    }
  }
  if (g.width != null && g.height != null) {
    bounds.add(g.width, g.height);
  }
  if (g.x != null && g.y != null) {
    bounds.add(0, 0);
  }
  return bounds.translate(g.x || 0, g.y || 0);
}

var methods = {
  group:  group,
  symbol: symbol,
  image:  image,
  rect:   rect,
  rule:   rule,
  arc:    arc,
  text:   text,
  path:   path,
  area:   area,
  line:   line
};
methods.area.nest = true;
methods.line.nest = true;

function itemBounds(item, func, opt) {
  var type = item.mark.marktype;
  func = func || methods[type];
  if (func.nest) item = item.mark;

  var curr = item.bounds,
      prev = item['bounds:prev'] || (item['bounds:prev'] = new Bounds());

  if (curr) {
    prev.clear().union(curr);
    curr.clear();
  } else {
    item.bounds = new Bounds();
  }
  func(item, item.bounds, opt);
  if (!curr) prev.clear().union(item.bounds);
  return item.bounds;
}

function markBounds(mark, bounds, opt) {
  bounds = bounds || mark.bounds && mark.bounds.clear() || new Bounds();

  var type  = mark.marktype,
      func  = methods[type],
      items = mark.items,
      i, n;

  if (items && items.length) {
    if (func.nest) {
      bounds = itemBounds(items[0], func, opt);
    } else {
      for (i=0, n=items.length; i<n; ++i) {
        bounds.union(itemBounds(items[i], func, opt));
      }
    }
  }
  return (mark.bounds = bounds);
}

module.exports = {
  mark:  markBounds,
  item:  itemBounds,
  text:  text,
  group: group
};
<commit_msg>Fix mark bounds calculation.<commit_after>var Bounds = require('../util/Bounds'),
    canvas = require('../util/canvas'),
    svg = require('../util/svg'),
    font = require('./font'),
    paths = require('../path'),
    parse = paths.parse,
    boundPath = paths.bounds,
    areaPath = svg.path.area,
    linePath = svg.path.line,
    halfpi = Math.PI / 2,
    sqrt3 = Math.sqrt(3),
    tan30 = Math.tan(30 * Math.PI / 180),
    g2D = null;

function context() {
  return g2D || (g2D = canvas.instance(1,1).getContext('2d'));
}

function strokeBounds(o, bounds) {
  if (o.stroke && o.opacity !== 0 && o.stokeOpacity !== 0) {
    bounds.expand(o.strokeWidth != null ? o.strokeWidth : 1);
  }
  return bounds;
}

function pathBounds(o, path, bounds) {
  if (path == null) {
    bounds.set(0, 0, 0, 0);
  } else {
    boundPath(path, bounds);
    strokeBounds(o, bounds);
  }
  return bounds;
}

function path(o, bounds) {
  var p = o.path ? o.pathCache || (o.pathCache = parse(o.path)) : null;
  return pathBounds(o, p, bounds).translate(o.x || 0, o.y || 0);
}

function area(mark, bounds) {
  if (mark.items.length === 0) return bounds;
  var items = mark.items,
      item = items[0],
      p = item.pathCache || (item.pathCache = parse(areaPath(items)));
  return pathBounds(item, p, bounds);
}

function line(mark, bounds) {
  if (mark.items.length === 0) return bounds;
  var items = mark.items,
      item = items[0],
      p = item.pathCache || (item.pathCache = parse(linePath(items)));
  return pathBounds(item, p, bounds);
}

function rect(o, bounds) {
  var x, y;
  return strokeBounds(o, bounds.set(
    x = o.x || 0,
    y = o.y || 0,
    (x + o.width) || 0,
    (y + o.height) || 0
  ));
}

function image(o, bounds) {
  var x = o.x || 0,
      y = o.y || 0,
      w = o.width || 0,
      h = o.height || 0;
  x = x - (o.align === 'center' ? w/2 : (o.align === 'right' ? w : 0));
  y = y - (o.baseline === 'middle' ? h/2 : (o.baseline === 'bottom' ? h : 0));
  return bounds.set(x, y, x+w, y+h);
}

function rule(o, bounds) {
  var x1, y1;
  return strokeBounds(o, bounds.set(
    x1 = o.x || 0,
    y1 = o.y || 0,
    o.x2 != null ? o.x2 : x1,
    o.y2 != null ? o.y2 : y1
  ));
}

function arc(o, bounds) {
  var cx = o.x || 0,
      cy = o.y || 0,
      ir = o.innerRadius || 0,
      or = o.outerRadius || 0,
      sa = (o.startAngle || 0) - halfpi,
      ea = (o.endAngle || 0) - halfpi,
      xmin = Infinity, xmax = -Infinity,
      ymin = Infinity, ymax = -Infinity,
      a, i, n, x, y, ix, iy, ox, oy;

  var angles = [sa, ea],
      s = sa - (sa % halfpi);
  for (i=0; i<4 && s<ea; ++i, s+=halfpi) {
    angles.push(s);
  }

  for (i=0, n=angles.length; i<n; ++i) {
    a = angles[i];
    x = Math.cos(a); ix = ir*x; ox = or*x;
    y = Math.sin(a); iy = ir*y; oy = or*y;
    xmin = Math.min(xmin, ix, ox);
    xmax = Math.max(xmax, ix, ox);
    ymin = Math.min(ymin, iy, oy);
    ymax = Math.max(ymax, iy, oy);
  }

  return strokeBounds(o, bounds.set(
    cx + xmin,
    cy + ymin,
    cx + xmax,
    cy + ymax
  ));
}

function symbol(o, bounds) {
  var size = o.size != null ? o.size : 100,
      x = o.x || 0,
      y = o.y || 0,
      r, t, rx, ry;

  switch (o.shape) {
    case 'cross':
      r = Math.sqrt(size / 5) / 2;
      t = 3*r;
      bounds.set(x-t, y-r, x+t, y+r);
      break;

    case 'diamond':
      ry = Math.sqrt(size / (2 * tan30));
      rx = ry * tan30;
      bounds.set(x-rx, y-ry, x+rx, y+ry);
      break;

    case 'square':
      t = Math.sqrt(size);
      r = t / 2;
      bounds.set(x-r, y-r, x+r, y+r);
      break;

    case 'triangle-down':
      rx = Math.sqrt(size / sqrt3);
      ry = rx * sqrt3 / 2;
      bounds.set(x-rx, y-ry, x+rx, y+ry);
      break;

    case 'triangle-up':
      rx = Math.sqrt(size / sqrt3);
      ry = rx * sqrt3 / 2;
      bounds.set(x-rx, y-ry, x+rx, y+ry);
      break;

    default:
      r = Math.sqrt(size/Math.PI);
      bounds.set(x-r, y-r, x+r, y+r);
  }

  return strokeBounds(o, bounds);
}

function text(o, bounds, noRotate) {
  var x = (o.x || 0) + (o.dx || 0),
      y = (o.y || 0) + (o.dy || 0),
      h = font.size(o),
      a = o.align,
      r = o.radius || 0,
      g = context(), w, t;

  g.font = font.string(o);
  w = g.measureText(o.text || '').width;

  if (r) {
    t = (o.theta || 0) - Math.PI/2;
    x += r * Math.cos(t);
    y += r * Math.sin(t);
  }

  // horizontal
  if (a === 'center') {
    x = x - (w / 2);
  } else if (a === 'right') {
    x = x - w;
  } else {
    // left by default, do nothing
  }

  // vertical
  y += font.offset(o) - Math.round(0.8*h);

  bounds.set(x, y, x+w, y+h);
  if (o.angle && !noRotate) {
    bounds.rotate(o.angle*Math.PI/180, o.x||0, o.y||0);
  }
  return bounds.expand(noRotate ? 0 : 1);
}

function group(g, bounds, includeLegends) {
  var axes = g.axisItems || [],
      items = g.items || [],
      legends = g.legendItems || [],
      j, m;

  for (j=0, m=axes.length; j<m; ++j) {
    bounds.union(axes[j].bounds);
  }
  for (j=0, m=items.length; j<m; ++j) {
    bounds.union(items[j].bounds);
  }
  if (includeLegends) {
    for (j=0, m=legends.length; j<m; ++j) {
      bounds.union(legends[j].bounds);
    }
  }
  if (g.width != null && g.height != null) {
    bounds.add(g.width, g.height);
  }
  if (g.x != null && g.y != null) {
    bounds.add(0, 0);
  }
  return bounds.translate(g.x || 0, g.y || 0);
}

var methods = {
  group:  group,
  symbol: symbol,
  image:  image,
  rect:   rect,
  rule:   rule,
  arc:    arc,
  text:   text,
  path:   path,
  area:   area,
  line:   line
};
methods.area.nest = true;
methods.line.nest = true;

function itemBounds(item, func, opt) {
  var type = item.mark.marktype;
  func = func || methods[type];
  if (func.nest) item = item.mark;

  var curr = item.bounds,
      prev = item['bounds:prev'] || (item['bounds:prev'] = new Bounds());

  if (curr) {
    prev.clear().union(curr);
    curr.clear();
  } else {
    item.bounds = new Bounds();
  }
  func(item, item.bounds, opt);
  if (!curr) prev.clear().union(item.bounds);
  return item.bounds;
}

var DUMMY_ITEM = {mark: null};

function markBounds(mark, bounds, opt) {
  var type  = mark.marktype,
      func  = methods[type],
      items = mark.items,
      hasi  = items && items.length,
      i, n, o, b;

  if (func.nest) {
    o = hasi ? items[0]
      : (DUMMY_ITEM.mark = mark, DUMMY_ITEM); // no items, so fake it
    b = itemBounds(o, func, opt);
    bounds = bounds && bounds.union(b) || b;
    return bounds;
  }

  bounds = bounds || mark.bounds && mark.bounds.clear() || new Bounds();
  if (hasi) {
    for (i=0, n=items.length; i<n; ++i) {
      bounds.union(itemBounds(items[i], func, opt));
    }
  }
  return (mark.bounds = bounds);
}

module.exports = {
  mark:  markBounds,
  item:  itemBounds,
  text:  text,
  group: group
};
<|endoftext|>


<commit_before>(function () {

    Sudoku.GameBoard = function (n) {

        Utils.EventDispatcher.call(this);

        this._n = n || 3;

        this._nSqrd = n * n;

        this._emptyCellCount = this._nSqrd * this._nSqrd;

        this._startingConfiguration = []; // { i, j, value }

        this._cells = new Utils.MultiArray(this._nSqrd, this._nSqrd);

        for (var i = 0; i < this._nSqrd; i++) {
            for (var j = 0; j < this._nSqrd; j++) {
                this._cells[i][j] = {value:0, isStarting:false};
            }
        }

    };

    Sudoku.GameBoard.prototype = {

        constructor:Sudoku.GameBoard,

        getGameSize:function () {

            return this._n;

        },

        isComplete:function(){

            return this._emptyCellCount === 0;

        },

        enterValue:function (i, j, value) {

            if (canEnterValue.call(this, i, j, value)) {
                this._cells[i][j].value = value;
                decrementEmptyCellCount.call(this);
                this.dispatchEvent({
                    type:"valueEntered",
                    i:i,
                    j:j,
                    value:value
                });
            }

            return this;

        },

        clearValue:function (i, j) {

            var oldValue = this._cells[i][j].value;

            if (canClearValue.call(this, i, j)) {
                this._cells[i][j].value = 0;
                incrementEmptyCellCount.call(this);
                this.dispatchEvent({
                    type:"valueCleared",
                    i:i,
                    j:j,
                    value:oldValue
                });
            }

            return this;

        },

        batchEnterValue:function (batch) {

            var entered = [];

            batch.forEach(
                function (el, idx, arr) {
                    if (canEnterValue.call(this, el.i, el.j, el.value)) {
                        this._cells[el.i][el.j].value = el.value;
                        decrementEmptyCellCount.call(this);
                        entered.push({i:el.i, j:el.j, value:el.value});
                    }
                },
                this
            );

            this.dispatchEvent({
                type:'batchValueEntered',
                batch:entered
            });

        },

        batchClearValue:function (batch) {

            var cleared = []
                , oldValue
                ;

            if (batch === "all") {
                batch = [];
                for (var i = 0; i < this._nSqrd; i++) {
                    for (var j = 0; j < this._nSqrd; j++) {
                        batch.push({
                            i:i,
                            j:j
                        });
                    }
                }
            }

            batch.forEach(
                function (el, idx, arr) {
                    if (canClearValue.call(this, el.i, el.j)) {
                        oldValue = this._cells[el.i][el.j].value;
                        this._cells[el.i][el.j].value = 0;
                        incrementEmptyCellCount.call(this);
                        cleared.push({i:el.i, j:el.j,value:oldValue});
                    }
                },
                this
            );

            this.dispatchEvent({
                type:'batchValueCleared',
                batch:cleared
            });

        },

        getValue:function (i, j) {

            return this._cells[i][j].value;

        },

        setToStartingConfiguration:function () {

            if (this._startingConfiguration.length === 0) {
                return this;
            }

            this.batchClearValue("all");

            this.batchEnterValue(this._startingConfiguration);

            return this;

        },

        saveStartingConfiguration:function () {

            this.discardStartingConfiguration();

            for (var i = 0; i < this._nSqrd; i++) {
                for (var j = 0; j < this._nSqrd; j++) {
                    if (this._cells[i][j].value !== 0) {
                        this._cells[i][j].isStarting = true;
                        this._startingConfiguration.push({
                            i:i,
                            j:j,
                            value:this._cells[i][j].value
                        })
                    }
                }
            }

            if (this._startingConfiguration.length > 0) {

                this.dispatchEvent({
                    type:'startingConfigurationSaved',
                    startingConfiguration:this.getStartingConfiguration()
                });

            }

            return this;

        },

        loadStartingConfiguration:function (startingConfiguration) {

            var batch = [];

            this.wipeClean();

            for (var i = 0; i < this._nSqrd; i++) {
                for (var j = 0; j < this._nSqrd; j++) {
                    if (startingConfiguration[i][j] !== 0) {
                        batch.push({i:i, j:j, value:startingConfiguration[i][j]})
                    }
                }
            }

            this.batchEnterValue(batch);

            this.saveStartingConfiguration();

            return this;

        },

        getStartingConfiguration:function () {

            var arr = [];

            for (var i = 0, l = this._startingConfiguration.length; i < l; i++) {
                arr.push({
                    i:this._startingConfiguration[i].i,
                    j:this._startingConfiguration[i].j,
                    value:this._startingConfiguration[i].value
                });
            }

            return arr;

        },

        discardStartingConfiguration:function () {

            if (this._startingConfiguration.length > 0) {

                var arr = this.getStartingConfiguration();

                for (var i = 0, l = this._startingConfiguration.length; i < l; i++) {
                    this._cells[this._startingConfiguration[i].i][this._startingConfiguration[i].j].isStarting = false;
                }

                this._startingConfiguration = [];

                this.dispatchEvent({
                    type:'startingConfigurationDiscarded',
                    startingConfiguration:arr
                });

            }

            return this;

        },

        wipeClean:function () {

            this.discardStartingConfiguration();

            this.batchClearValue("all");

            return this;

        },

        isStarting:function (i, j) {

            return this._cells[i][j].isStarting;

        },

        getSubGridBoundsContainingCell:function (i, j) {

            var iLower = Math.floor(i / this._n) * this._n
                , iUpper = iLower + this._n - 1
                , iSubGrid = iLower / this._n
                , jLower = Math.floor(j / this._n) * this._n
                , jUpper = jLower + this._n - 1
                , jSubGrid = jLower / this._n
                ;

            return {
                iLower:iLower,
                iUpper:iUpper,
                iSubGrid:iSubGrid,
                jLower:jLower,
                jUpper:jUpper,
                jSubGrid:jSubGrid
            };
        }

    };

    function entryClash(i, j, value) {

        var subGridBounds = this.getSubGridBoundsContainingCell(i, j)
            , subGridClashFound = false
            , clashOccurred = false
            ;

        for (var k = 0; k < this._nSqrd; k++) {
            if (k >= subGridBounds.jLower && k <= subGridBounds.jUpper) {
                continue;
            }
            if (this._cells[i][k].value === value) {
                this.dispatchEvent({
                    type:"clash",
                    subType:"row",
                    i:i,
                    j:k
                });
                clashOccurred = true;
                break;
            }
        }
        for (var k = 0; k < this._nSqrd; k++) {
            if (k >= subGridBounds.iLower && k <= subGridBounds.iUpper) {
                continue;
            }
            if (this._cells[k][j].value === value) {
                this.dispatchEvent({
                    type:"clash",
                    subType:"column",
                    i:k,
                    j:j
                });
                clashOccurred = true;
                break;
            }
        }

        for (var k = subGridBounds.iLower; k <= subGridBounds.iUpper; k++) {
            for (var l = subGridBounds.jLower; l <= subGridBounds.jUpper; l++) {
                if (this._cells[k][l].value === value) {
                    this.dispatchEvent({
                        type:"clash",
                        subType:"subGrid",
                        i:k,
                        j:l
                    });
                    clashOccurred = true;
                    subGridClashFound = true;
                    break;
                }
            }
            if (subGridClashFound) {
                break;
            }
        }
        return clashOccurred;
    }

    function decrementEmptyCellCount() {

        if (this._emptyCellCount === 0) {
            throw new Utils.Error('Can\'t decrement _emptyCellCount below zero');
            return;
        }

        this._emptyCellCount--;

        if (this._emptyCellCount === 0) {

            this.dispatchEvent({
                type:"gameComplete"
            });

        }

    }

    function incrementEmptyCellCount() {

        if (this._emptyCellCount === this._nSqrd * this._nSqrd) {
            throw new Utils.Error('Can\'t increment _emptyCellCount above ' + this._emptyCellCount);
            return;
        }

        this._emptyCellCount++;

    }

    function canEnterValue(i, j, value) {

        if (this._cells[i][j].value === 0 && !entryClash.call(this, i, j, value) &&
            value <= this._nSqrd &&
            value > 0 &&
            value % 1 === 0) {
            return true;
        } else {
            return false;
        }

    }

    function canClearValue(i, j) {

        if (this._cells[i][j].value !== 0 && !this._cells[i][j].isStarting) {
            return true;
        } else {
            return false;
        }

    }

})();
<commit_msg>made canEnterValue and canClearValue public<commit_after>(function () {

    Sudoku.GameBoard = function (n) {

        Utils.EventDispatcher.call(this);

        this._n = n || 3;

        this._nSqrd = n * n;

        this._emptyCellCount = this._nSqrd * this._nSqrd;

        this._startingConfiguration = []; // { i, j, value }

        this._cells = new Utils.MultiArray(this._nSqrd, this._nSqrd);

        for (var i = 0; i < this._nSqrd; i++) {
            for (var j = 0; j < this._nSqrd; j++) {
                this._cells[i][j] = {value:0, isStarting:false};
            }
        }

    };

    Sudoku.GameBoard.prototype = {

        constructor:Sudoku.GameBoard,

        getGameSize:function () {

            return this._n;

        },

        isComplete:function () {

            return this._emptyCellCount === 0;

        },

        enterValue:function (i, j, value) {

            if (this.canEnterValue( i, j, value)) {
                this._cells[i][j].value = value;
                decrementEmptyCellCount.call(this);
                this.dispatchEvent({
                    type:"valueEntered",
                    i:i,
                    j:j,
                    value:value
                });
            }

            return this;

        },

        clearValue:function (i, j) {

            var oldValue = this._cells[i][j].value;

            if (this.canClearValue( i, j)) {
                this._cells[i][j].value = 0;
                incrementEmptyCellCount.call(this);
                this.dispatchEvent({
                    type:"valueCleared",
                    i:i,
                    j:j,
                    value:oldValue
                });
            }

            return this;

        },

        batchEnterValue:function (batch) {

            var entered = [];

            batch.forEach(
                function (el, idx, arr) {
                    if (this.canEnterValue( el.i, el.j, el.value)) {
                        this._cells[el.i][el.j].value = el.value;
                        decrementEmptyCellCount.call(this);
                        entered.push({i:el.i, j:el.j, value:el.value});
                    }
                },
                this
            );

            this.dispatchEvent({
                type:'batchValueEntered',
                batch:entered
            });

        },

        batchClearValue:function (batch) {

            var cleared = []
                , oldValue
                ;

            if (batch === "all") {
                batch = [];
                for (var i = 0; i < this._nSqrd; i++) {
                    for (var j = 0; j < this._nSqrd; j++) {
                        batch.push({
                            i:i,
                            j:j
                        });
                    }
                }
            }

            batch.forEach(
                function (el, idx, arr) {
                    if (this.canClearValue( el.i, el.j)) {
                        oldValue = this._cells[el.i][el.j].value;
                        this._cells[el.i][el.j].value = 0;
                        incrementEmptyCellCount.call(this);
                        cleared.push({i:el.i, j:el.j, value:oldValue});
                    }
                },
                this
            );

            this.dispatchEvent({
                type:'batchValueCleared',
                batch:cleared
            });

        },

        getValue:function (i, j) {

            return this._cells[i][j].value;

        },

        setToStartingConfiguration:function () {

            if (this._startingConfiguration.length === 0) {
                return this;
            }

            this.batchClearValue("all");

            this.batchEnterValue(this._startingConfiguration);

            return this;

        },

        saveStartingConfiguration:function () {

            this.discardStartingConfiguration();

            for (var i = 0; i < this._nSqrd; i++) {
                for (var j = 0; j < this._nSqrd; j++) {
                    if (this._cells[i][j].value !== 0) {
                        this._cells[i][j].isStarting = true;
                        this._startingConfiguration.push({
                            i:i,
                            j:j,
                            value:this._cells[i][j].value
                        })
                    }
                }
            }

            if (this._startingConfiguration.length > 0) {

                this.dispatchEvent({
                    type:'startingConfigurationSaved',
                    startingConfiguration:this.getStartingConfiguration()
                });

            }

            return this;

        },

        loadStartingConfiguration:function (startingConfiguration) {

            var batch = [];

            this.wipeClean();

            for (var i = 0; i < this._nSqrd; i++) {
                for (var j = 0; j < this._nSqrd; j++) {
                    if (startingConfiguration[i][j] !== 0) {
                        batch.push({i:i, j:j, value:startingConfiguration[i][j]})
                    }
                }
            }

            this.batchEnterValue(batch);

            this.saveStartingConfiguration();

            return this;

        },

        getStartingConfiguration:function () {

            var arr = [];

            for (var i = 0, l = this._startingConfiguration.length; i < l; i++) {
                arr.push({
                    i:this._startingConfiguration[i].i,
                    j:this._startingConfiguration[i].j,
                    value:this._startingConfiguration[i].value
                });
            }

            return arr;

        },

        discardStartingConfiguration:function () {

            if (this._startingConfiguration.length > 0) {

                var arr = this.getStartingConfiguration();

                for (var i = 0, l = this._startingConfiguration.length; i < l; i++) {
                    this._cells[this._startingConfiguration[i].i][this._startingConfiguration[i].j].isStarting = false;
                }

                this._startingConfiguration = [];

                this.dispatchEvent({
                    type:'startingConfigurationDiscarded',
                    startingConfiguration:arr
                });

            }

            return this;

        },

        wipeClean:function () {

            this.discardStartingConfiguration();

            this.batchClearValue("all");

            return this;

        },

        isStarting:function (i, j) {

            return this._cells[i][j].isStarting;

        },

        getSubGridBoundsContainingCell:function (i, j) {

            var iLower = Math.floor(i / this._n) * this._n
                , iUpper = iLower + this._n - 1
                , iSubGrid = iLower / this._n
                , jLower = Math.floor(j / this._n) * this._n
                , jUpper = jLower + this._n - 1
                , jSubGrid = jLower / this._n
                ;

            return {
                iLower:iLower,
                iUpper:iUpper,
                iSubGrid:iSubGrid,
                jLower:jLower,
                jUpper:jUpper,
                jSubGrid:jSubGrid
            };
        },

        canEnterValue:function (i, j, value) {

            if (this._cells[i][j].value === 0 && !entryClash.call(this, i, j, value) &&
                value <= this._nSqrd &&
                value > 0 &&
                value % 1 === 0) {
                return true;
            } else {
                return false;
            }

        },

        canClearValue:function (i, j) {

            if (this._cells[i][j].value !== 0 && !this._cells[i][j].isStarting) {
                return true;
            } else {
                return false;
            }

        }

    };

    function entryClash(i, j, value) {

        var subGridBounds = this.getSubGridBoundsContainingCell(i, j)
            , subGridClashFound = false
            , clashOccurred = false
            ;

        for (var k = 0; k < this._nSqrd; k++) {
            if (k >= subGridBounds.jLower && k <= subGridBounds.jUpper) {
                continue;
            }
            if (this._cells[i][k].value === value) {
                this.dispatchEvent({
                    type:"clash",
                    subType:"row",
                    i:i,
                    j:k
                });
                clashOccurred = true;
                break;
            }
        }
        for (var k = 0; k < this._nSqrd; k++) {
            if (k >= subGridBounds.iLower && k <= subGridBounds.iUpper) {
                continue;
            }
            if (this._cells[k][j].value === value) {
                this.dispatchEvent({
                    type:"clash",
                    subType:"column",
                    i:k,
                    j:j
                });
                clashOccurred = true;
                break;
            }
        }

        for (var k = subGridBounds.iLower; k <= subGridBounds.iUpper; k++) {
            for (var l = subGridBounds.jLower; l <= subGridBounds.jUpper; l++) {
                if (this._cells[k][l].value === value) {
                    this.dispatchEvent({
                        type:"clash",
                        subType:"subGrid",
                        i:k,
                        j:l
                    });
                    clashOccurred = true;
                    subGridClashFound = true;
                    break;
                }
            }
            if (subGridClashFound) {
                break;
            }
        }
        return clashOccurred;
    }

    function decrementEmptyCellCount() {

        if (this._emptyCellCount === 0) {
            throw new Utils.Error('Can\'t decrement _emptyCellCount below zero');
            return;
        }

        this._emptyCellCount--;

        if (this._emptyCellCount === 0) {

            this.dispatchEvent({
                type:"gameComplete"
            });

        }

    }

    function incrementEmptyCellCount() {

        if (this._emptyCellCount === this._nSqrd * this._nSqrd) {
            throw new Utils.Error('Can\'t increment _emptyCellCount above ' + this._emptyCellCount);
            return;
        }

        this._emptyCellCount++;

    }

    function canEnterValue(i, j, value) {

        if (this._cells[i][j].value === 0 && !entryClash.call(this, i, j, value) &&
            value <= this._nSqrd &&
            value > 0 &&
            value % 1 === 0) {
            return true;
        } else {
            return false;
        }

    }

    function canClearValue(i, j) {

        if (this._cells[i][j].value !== 0 && !this._cells[i][j].isStarting) {
            return true;
        } else {
            return false;
        }

    }

})
    ();
<|endoftext|>


<commit_before>import dotenv from 'dotenv'
dotenv.config()

const rethinkdbConfig = (() => {
  let config = {
    host: process.env.RETHINKDB_HOST,
    port: process.env.RETHINKDB_PORT,
    db: 'quill_lessons'
  }

  if (process.env.RETHINKDB_AUTH_KEY) {
    config['authKey'] = process.env.RETHINKDB_AUTH_KEY
  }

  if (process.env.RETHINKDB_SSL_CERT) {
    config['ssl'] = { ca: Buffer(process.env.RETHINKDB_SSL_CERT) }
  }

  return config
})()

export default rethinkdbConfig
<commit_msg>Revert rethinkdb config file commit<commit_after>import dotenv from 'dotenv'
import fs from 'fs'
import path from 'path'

dotenv.config()

const rethinkdbConfig = (() => {
  const pathToCert = path.resolve(__dirname + '/..') + '/public-key.crt'

  let config = {
    host: process.env.RETHINKDB_HOST,
    port: process.env.RETHINKDB_PORT,
    db: 'quill_lessons'
  }

  if (process.env.RETHINKDB_AUTH_KEY) {
    config['authKey'] = process.env.RETHINKDB_AUTH_KEY
  }

  if (process.env.RETHINKDB_USE_SSL === 'true') {
    const caCert = fs.readFileSync(pathToCert)
    config['ssl'] = { ca: caCert }
  }

  return config
})()

export default rethinkdbConfig
<|endoftext|>


<commit_before>define([
  'jquery'
], function ($) {
  var Fullscreen = function (context) {
    var $editor = context.layoutInfo.editor;
    var $toolbar = context.layoutInfo.toolbar;
    var $editable = context.layoutInfo.editable;
    var $codable = context.layoutInfo.codable;

    var $window = $(window);
    var $scrollbar = $('html, body');

    /**
     * toggle fullscreen
     */
    this.toggle = function () {
      var resize = function (size) {
        $editable.css('height', size.h);
        $codable.css('height', size.h);
        if ($codable.data('cmeditor')) {
          $codable.data('cmeditor').setsize(null, size.h);
        }
      };
      var fullscreenResize = function () {
        resize({
          h: $window.height() - $toolbar.outerHeight()
        });
      }

      $editor.toggleClass('fullscreen');
      if (this.isFullscreen()) {
        $editable.data('orgHeight', $editable.css('height'));

        $window.on('resize', fullscreenResize).trigger('resize');

        $scrollbar.css('overflow', 'hidden');
      } else {
        $window.off('resize', fullscreenResize);
        resize({
          h: $editable.data('orgHeight')
        });
        $scrollbar.css('overflow', 'visible');
      }

      context.invoke('toolbar.updateFullscreen', this.isFullscreen());
    };

    this.isFullscreen = function () {
      return $editor.hasClass('fullscreen');
    };
  };

  return Fullscreen;
});
<commit_msg>Update Fullscreen.js<commit_after>define([
  'jquery'
], function ($) {
  var Fullscreen = function (context) {
    var $editor = context.layoutInfo.editor;
    var $toolbar = context.layoutInfo.toolbar;
    var $editable = context.layoutInfo.editable;
    var $codable = context.layoutInfo.codable;

    var $window = $(window);
    var $scrollbar = $('html, body');

    /**
     * toggle fullscreen
     */
    this.toggle = function () {
      var resize = function (size) {
        $editable.css('height', size.h);
        $codable.css('height', size.h);
        if ($codable.data('cmeditor')) {
          $codable.data('cmeditor').setsize(null, size.h);
        }
      };
      var fullscreenResize = function () {
        resize({
          h: $window.height() - $toolbar.outerHeight()
        });
      };

      $editor.toggleClass('fullscreen');
      if (this.isFullscreen()) {
        $editable.data('orgHeight', $editable.css('height'));

        $window.on('resize', fullscreenResize).trigger('resize');

        $scrollbar.css('overflow', 'hidden');
      } else {
        $window.off('resize', fullscreenResize);
        resize({
          h: $editable.data('orgHeight')
        });
        $scrollbar.css('overflow', 'visible');
      }

      context.invoke('toolbar.updateFullscreen', this.isFullscreen());
    };

    this.isFullscreen = function () {
      return $editor.hasClass('fullscreen');
    };
  };

  return Fullscreen;
});
<|endoftext|>


<commit_before>// (C) Copyright 2016 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import CSSClassnames from '../../utils/CSSClassnames';
import DragIcon from '../icons/base/Drag';
import { padding } from './utils';

const CLASS_ROOT = CSSClassnames.CHART_RANGE;

// Allows selecting a region.
// Click to select one.
// Press and Drag to select multiple.
// Drag edges to adjust.

export default class Range extends Component {

  constructor(props, context) {
    super(props, context);
    this._onMouseMove = this._onMouseMove.bind(this);
    this._onMouseUp = this._onMouseUp.bind(this);
    this.state = {};
  }

  componentWillUnmount () {
    const { mouseDown } = this.state;
    if (mouseDown) {
      window.removeEventListener('mouseup', this._onMouseUp);
    }
  }

  _valueToIndex (value) {
    const { count, vertical } = this.props;
    const rect = this.rangeRef.getBoundingClientRect();
    const total = vertical ? rect.height : rect.width;
    return Math.round((value / total) * (count - 1));
  }

  _percentForIndex (index) {
    const { count } = this.props;
    return (100 / (count - 1)) * Math.min(index, count - 1);
  }

  _mouseIndex (event) {
    const { active, count, vertical } = this.props;
    const { mouseDown, mouseDownIndex } = this.state;
    const rect = this.rangeRef.getBoundingClientRect();
    const value = (vertical ? (event.clientY - rect.top) :
      (event.clientX - rect.left));
    let index = this._valueToIndex(value);

    // constrain index to keep it within range as needed
    if ('active' === mouseDown && mouseDownIndex >= 0) {
      if (index > mouseDownIndex) {
        // moving right/down
        index = Math.min(mouseDownIndex + count - 1 - active.end, index);
      } else if (index < mouseDownIndex) {
        // moving up/left
        index = Math.max(mouseDownIndex - active.start, index);
      }
    } else if ('start' === mouseDown) {
      index = Math.min(active.end, index);
    } else if ('end' === mouseDown) {
      index = Math.max(active.start, index);
    }

    return index;
  }

  _mouseDown (source) {
    return (event) => {
      event.stopPropagation(); // so start and end don't trigger range
      const index = this._mouseIndex(event);
      this.setState({
        mouseDown: source,
        mouseDownIndex: index
      });
      window.addEventListener('mouseup', this._onMouseUp);
    };
  }

  _onMouseUp (event) {
    window.removeEventListener('mouseup', this._onMouseUp);
    const { active, onActive, count } = this.props;
    const { mouseDown, mouseDownIndex, moved } = this.state;
    let mouseUpIndex = this._mouseIndex(event);

    if (mouseUpIndex < 0) {
      mouseUpIndex = 0;
    } else if (mouseUpIndex > count) {
      mouseUpIndex = count;
    }

    this.setState({
      mouseDown: false,
      mouseDownIndex: undefined,
      mouseMoveIndex: undefined,
      moved: false
    });

    if (onActive) {
      let nextActive;

      if ('range' === mouseDown) {
        if (moved) {
          nextActive = {
            start: Math.min(mouseDownIndex, mouseUpIndex),
            end: Math.max(mouseDownIndex, mouseUpIndex)
          };
        }

      } else if ('active' === mouseDown) {
        const delta = mouseUpIndex - mouseDownIndex;
        nextActive = {
          start: active.start + delta,
          end: active.end + delta
        };

      } else if ('start' === mouseDown) {
        nextActive = {
          start: mouseUpIndex,
          end: active.end
        };

      } else if ('end' === mouseDown) {
        nextActive = {
          start: active.start,
          end: mouseUpIndex
        };
      }

      onActive(nextActive);
    }
  }

  _onMouseMove (event) {
    const { mouseMoveIndex } = this.state;
    const index = this._mouseIndex(event);
    if (index !== mouseMoveIndex) {
      this.setState({ mouseMoveIndex: index, moved: true });
    }
  }

  render () {
    const {
      active, className, count, onActive, vertical, ...props
    } = this.props;
    const { mouseDown, mouseDownIndex, mouseMoveIndex } = this.state;

    const classes = classnames(
      CLASS_ROOT, {
        [`${CLASS_ROOT}--vertical`]: vertical,
        [`${CLASS_ROOT}--dragging`]: mouseDown
      },
      className
    );

    let layers;
    if (active || mouseDown) {

      let start, end;
      if ('range' === mouseDown) {
        start = Math.min(mouseDownIndex, mouseMoveIndex);
        end = Math.max(mouseDownIndex, mouseMoveIndex);
      } else if ('active' === mouseDown && mouseMoveIndex >= 0) {
        const delta = mouseMoveIndex - mouseDownIndex;
        start = active.start + delta;
        end = active.end + delta;
      } else if ('start' === mouseDown && mouseMoveIndex >= 0) {
        start = mouseMoveIndex;
        end = active.end;
      } else if ('end' === mouseDown && mouseMoveIndex >= 0) {
        start = active.start;
        end = mouseMoveIndex;
      } else {
        start = active.start;
        end = active.end;
      }
      // in case the user resizes the window
      start = Math.max(0, Math.min(count - 1, start));
      end = Math.max(0, Math.min(count - 1, end));

      layers = [
        <div key='before' className={`${CLASS_ROOT}__inactive`}
          style={{ flexBasis: `${this._percentForIndex(start)}%` }} />,
        <div key='active' {...props} className={`${CLASS_ROOT}__active`}
          style={{ flexBasis: `${this._percentForIndex(end - start)}%` }}
          onMouseDown={this._mouseDown('active')}>
          <div className={`${CLASS_ROOT}__active-start`}
            onMouseDown={onActive ? this._mouseDown('start') : undefined}>
            <DragIcon />

          <div className={`${CLASS_ROOT}__active-end`}
            onMouseDown={onActive ? this._mouseDown('end') : undefined}>
            <DragIcon />

,
        <div key='after' className={`${CLASS_ROOT}__inactive`}
          style={{
            flexBasis: `${this._percentForIndex((count - 1) - end)}%`
          }} />
      ];
    }

    let onMouseMove;
    if (onActive && mouseDown) {
      onMouseMove = this._onMouseMove;
    }

    return (

 this.rangeRef = ref} className={classes}
        style={{ padding: padding }} onMouseMove={onMouseMove}
        onMouseDown={onActive ? this._mouseDown('range') : undefined}>
        {layers}

    );
  }

};

Range.propTypes = {
  active: PropTypes.shape({
    end: PropTypes.number.isRequired,
    start: PropTypes.number.isRequired
  }),
  count: PropTypes.number.isRequired,
  onActive: PropTypes.func, // (start, end)
  vertical: PropTypes.bool
};
<commit_msg>Changed Chart Range to constrain active indexes within bounds. Fixes GitHub issue #1207.<commit_after>// (C) Copyright 2016 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import CSSClassnames from '../../utils/CSSClassnames';
import DragIcon from '../icons/base/Drag';
import { padding } from './utils';

const CLASS_ROOT = CSSClassnames.CHART_RANGE;

// Allows selecting a region.
// Click to select one.
// Press and Drag to select multiple.
// Drag edges to adjust.

export default class Range extends Component {

  constructor(props, context) {
    super(props, context);
    this._onMouseMove = this._onMouseMove.bind(this);
    this._onMouseUp = this._onMouseUp.bind(this);
    this.state = {};
  }

  componentWillUnmount () {
    const { mouseDown } = this.state;
    if (mouseDown) {
      window.removeEventListener('mouseup', this._onMouseUp);
    }
  }

  _valueToIndex (value) {
    const { count, vertical } = this.props;
    const rect = this.rangeRef.getBoundingClientRect();
    const total = vertical ? rect.height : rect.width;
    return Math.round((value / total) * (count - 1));
  }

  _percentForIndex (index) {
    const { count } = this.props;
    return (100 / (count - 1)) * Math.min(index, count - 1);
  }

  _mouseIndex (event) {
    const { active, count, vertical } = this.props;
    const { mouseDown, mouseDownIndex } = this.state;
    const rect = this.rangeRef.getBoundingClientRect();
    const value = (vertical ? (event.clientY - rect.top) :
      (event.clientX - rect.left));
    let index = this._valueToIndex(value);

    // constrain index to keep it within range as needed
    if ('active' === mouseDown && mouseDownIndex >= 0) {
      if (index > mouseDownIndex) {
        // moving right/down
        index = Math.min(mouseDownIndex + count - 1 - active.end, index);
      } else if (index < mouseDownIndex) {
        // moving up/left
        index = Math.max(mouseDownIndex - active.start, index);
      }
    } else if ('start' === mouseDown) {
      index = Math.min(active.end, index);
    } else if ('end' === mouseDown) {
      index = Math.max(active.start, index);
    }

    return index;
  }

  _mouseDown (source) {
    return (event) => {
      event.stopPropagation(); // so start and end don't trigger range
      const index = this._mouseIndex(event);
      this.setState({
        mouseDown: source,
        mouseDownIndex: index
      });
      window.addEventListener('mouseup', this._onMouseUp);
    };
  }

  _onMouseUp (event) {
    window.removeEventListener('mouseup', this._onMouseUp);
    const { active, onActive, count } = this.props;
    const { mouseDown, mouseDownIndex, moved } = this.state;
    let mouseUpIndex = this._mouseIndex(event);

    if (mouseUpIndex < 0) {
      mouseUpIndex = 0;
    } else if (mouseUpIndex > count) {
      mouseUpIndex = count;
    }

    this.setState({
      mouseDown: false,
      mouseDownIndex: undefined,
      mouseMoveIndex: undefined,
      moved: false
    });

    if (onActive) {
      let nextActive;

      if ('range' === mouseDown) {
        if (moved) {
          nextActive = {
            start: Math.min(mouseDownIndex, mouseUpIndex),
            end: Math.max(mouseDownIndex, mouseUpIndex)
          };
        }

      } else if ('active' === mouseDown) {
        const delta = mouseUpIndex - mouseDownIndex;
        nextActive = {
          start: active.start + delta,
          end: active.end + delta
        };

      } else if ('start' === mouseDown) {
        nextActive = {
          start: Math.min(mouseUpIndex, active.end - 1),
          end: active.end
        };

      } else if ('end' === mouseDown) {
        nextActive = {
          start: active.start,
          end: Math.max(mouseUpIndex, active.start + 1)
        };
      }

      onActive(nextActive);
    }
  }

  _onMouseMove (event) {
    const { mouseMoveIndex } = this.state;
    const index = this._mouseIndex(event);
    if (index !== mouseMoveIndex) {
      this.setState({ mouseMoveIndex: index, moved: true });
    }
  }

  render () {
    const {
      active, className, count, onActive, vertical, ...props
    } = this.props;
    const { mouseDown, mouseDownIndex, mouseMoveIndex } = this.state;

    const classes = classnames(
      CLASS_ROOT, {
        [`${CLASS_ROOT}--vertical`]: vertical,
        [`${CLASS_ROOT}--dragging`]: mouseDown
      },
      className
    );

    let layers;
    if (active || mouseDown) {

      let start, end;
      if ('range' === mouseDown) {
        start = Math.min(mouseDownIndex, mouseMoveIndex);
        end = Math.max(mouseDownIndex, mouseMoveIndex);
      } else if ('active' === mouseDown && mouseMoveIndex >= 0) {
        const delta = mouseMoveIndex - mouseDownIndex;
        start = active.start + delta;
        end = active.end + delta;
      } else if ('start' === mouseDown && mouseMoveIndex >= 0) {
        start = Math.min(mouseMoveIndex, active.end - 1);
        end = active.end;
      } else if ('end' === mouseDown && mouseMoveIndex >= 0) {
        start = active.start;
        end = Math.max(mouseMoveIndex, active.start + 1);
      } else {
        start = active.start;
        end = active.end;
      }
      // in case the user resizes the window
      start = Math.max(0, Math.min(count - 1, start));
      end = Math.max(0, Math.min(count - 1, end));

      layers = [
        <div key='before' className={`${CLASS_ROOT}__inactive`}
          style={{ flexBasis: `${this._percentForIndex(start)}%` }} />,
        <div key='active' {...props} className={`${CLASS_ROOT}__active`}
          style={{ flexBasis: `${this._percentForIndex(end - start)}%` }}
          onMouseDown={this._mouseDown('active')}>
          <div className={`${CLASS_ROOT}__active-start`}
            onMouseDown={onActive ? this._mouseDown('start') : undefined}>
            <DragIcon />

          <div className={`${CLASS_ROOT}__active-end`}
            onMouseDown={onActive ? this._mouseDown('end') : undefined}>
            <DragIcon />

,
        <div key='after' className={`${CLASS_ROOT}__inactive`}
          style={{
            flexBasis: `${this._percentForIndex((count - 1) - end)}%`
          }} />
      ];
    }

    let onMouseMove;
    if (onActive && mouseDown) {
      onMouseMove = this._onMouseMove;
    }

    return (

 this.rangeRef = ref} className={classes}
        style={{ padding: padding }} onMouseMove={onMouseMove}
        onMouseDown={onActive ? this._mouseDown('range') : undefined}>
        {layers}

    );
  }

};

Range.propTypes = {
  active: PropTypes.shape({
    end: PropTypes.number.isRequired,
    start: PropTypes.number.isRequired
  }),
  count: PropTypes.number.isRequired,
  onActive: PropTypes.func, // (start, end)
  vertical: PropTypes.bool
};
<|endoftext|>


<commit_before>/*!
 * jQuery UI Widget @VERSION
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function( $, undefined ) {

// jQuery 1.4+
if ( $.cleanData ) {
	var _cleanData = $.cleanData;
	$.cleanData = function( elems ) {
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			$( elem ).triggerHandler( "remove" );
		}
		_cleanData( elems );
	};
} else {
	var _remove = $.fn.remove;
	$.fn.remove = function( selector, keepData ) {
		return this.each(function() {
			if ( !keepData ) {
				if ( !selector || $.filter( selector, [ this ] ).length ) {
					$( "*", this ).add( [ this ] ).each(function() {
						$( this ).triggerHandler( "remove" );
					});
				}
			}
			return _remove.call( $(this), selector, keepData );
		});
	};
}

$.widget = function( name, base, prototype ) {
	var namespace = name.split( "." )[ 0 ],
		fullName;
	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName ] = function( elem ) {
		return !!$.data( elem, name );
	};

	$[ namespace ] = $[ namespace ] || {};
	$[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without initializing for simple inheritance
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	var basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
//	$.each( basePrototype, function( key, val ) {
//		if ( $.isPlainObject(val) ) {
//			basePrototype[ key ] = $.extend( {}, val );
//		}
//	});
	basePrototype.options = $.extend( true, {}, basePrototype.options );
	$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
		namespace: namespace,
		widgetName: name,
		widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
		widgetBaseClass: fullName
	}, prototype );

	$.widget.bridge( name, $[ namespace ][ name ] );
};

$.widget.bridge = function( name, object ) {
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = Array.prototype.slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.extend.apply( null, [ true, options ].concat(args) ) :
			options;

		// prevent calls to internal methods
		if ( isMethodCall && options.charAt( 0 ) === "_" ) {
			return returnValue;
		}

		if ( isMethodCall ) {
			this.each(function() {
				var instance = $.data( this, name );
				if ( !instance ) {
					throw "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'";
				}
				if ( !$.isFunction( instance[options] ) ) {
					throw "no such method '" + options + "' for " + name + " widget instance";
				}
				var methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, name );
				if ( instance ) {
					instance.option( options || {} )._init();
				} else {
					$.data( this, name, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( options, element ) {
	// allow instantiation without initializing for simple inheritance
	if ( arguments.length ) {
		this._createWidget( options, element );
	}
};

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	options: {
		disabled: false
	},
	_createWidget: function( options, element ) {
		// $.widget.bridge stores the plugin instance, but we do it anyway
		// so that it's stored even before the _create function runs
		$.data( element, this.widgetName, this );
		this.element = $( element );
		this.options = $.extend( true, {},
			this.options,
			this._getCreateOptions(),
			options );

		var self = this;
		this.element.bind( "remove." + this.widgetName, function() {
			self.destroy();
		});

		this._create();
		this._trigger( "create" );
		this._init();
	},
	_getCreateOptions: function() {
		return $.metadata && $.metadata.get( element )[ this.widgetName ];
	},
	_create: function() {},
	_init: function() {},

	destroy: function() {
		this.element
			.unbind( "." + this.widgetName )
			.removeData( this.widgetName );
		this.widget()
			.unbind( "." + this.widgetName )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetBaseClass + "-disabled " +
				"ui-state-disabled" );
	},

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.extend( {}, this.options );
		}

		if  (typeof key === "string" ) {
			if ( value === undefined ) {
				return this.options[ key ];
			}
			options = {};
			options[ key ] = value;
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var self = this;
		$.each( options, function( key, value ) {
			self._setOption( key, value );
		});

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				[ value ? "addClass" : "removeClass"](
					this.widgetBaseClass + "-disabled" + " " +
					"ui-state-disabled" )
				.attr( "aria-disabled", value );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_trigger: function( type, event, data ) {
		var callback = this.options[ type ];

		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		data = data || {};

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if ( event.originalEvent ) {
			for ( var i = $.event.props.length, prop; i; ) {
				prop = $.event.props[ --i ];
				event[ prop ] = event.originalEvent[ prop ];
			}
		}

		this.element.trigger( event, data );

		return !( $.isFunction(callback) &&
			callback.call( this.element[0], event, data ) === false ||
			event.isDefaultPrevented() );
	}
};

})( jQuery );
<commit_msg>Widget: Fixed reference to element in _getCreateOptions().<commit_after>/*!
 * jQuery UI Widget @VERSION
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function( $, undefined ) {

// jQuery 1.4+
if ( $.cleanData ) {
	var _cleanData = $.cleanData;
	$.cleanData = function( elems ) {
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			$( elem ).triggerHandler( "remove" );
		}
		_cleanData( elems );
	};
} else {
	var _remove = $.fn.remove;
	$.fn.remove = function( selector, keepData ) {
		return this.each(function() {
			if ( !keepData ) {
				if ( !selector || $.filter( selector, [ this ] ).length ) {
					$( "*", this ).add( [ this ] ).each(function() {
						$( this ).triggerHandler( "remove" );
					});
				}
			}
			return _remove.call( $(this), selector, keepData );
		});
	};
}

$.widget = function( name, base, prototype ) {
	var namespace = name.split( "." )[ 0 ],
		fullName;
	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName ] = function( elem ) {
		return !!$.data( elem, name );
	};

	$[ namespace ] = $[ namespace ] || {};
	$[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without initializing for simple inheritance
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	var basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
//	$.each( basePrototype, function( key, val ) {
//		if ( $.isPlainObject(val) ) {
//			basePrototype[ key ] = $.extend( {}, val );
//		}
//	});
	basePrototype.options = $.extend( true, {}, basePrototype.options );
	$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
		namespace: namespace,
		widgetName: name,
		widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
		widgetBaseClass: fullName
	}, prototype );

	$.widget.bridge( name, $[ namespace ][ name ] );
};

$.widget.bridge = function( name, object ) {
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = Array.prototype.slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.extend.apply( null, [ true, options ].concat(args) ) :
			options;

		// prevent calls to internal methods
		if ( isMethodCall && options.charAt( 0 ) === "_" ) {
			return returnValue;
		}

		if ( isMethodCall ) {
			this.each(function() {
				var instance = $.data( this, name );
				if ( !instance ) {
					throw "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'";
				}
				if ( !$.isFunction( instance[options] ) ) {
					throw "no such method '" + options + "' for " + name + " widget instance";
				}
				var methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, name );
				if ( instance ) {
					instance.option( options || {} )._init();
				} else {
					$.data( this, name, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( options, element ) {
	// allow instantiation without initializing for simple inheritance
	if ( arguments.length ) {
		this._createWidget( options, element );
	}
};

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	options: {
		disabled: false
	},
	_createWidget: function( options, element ) {
		// $.widget.bridge stores the plugin instance, but we do it anyway
		// so that it's stored even before the _create function runs
		$.data( element, this.widgetName, this );
		this.element = $( element );
		this.options = $.extend( true, {},
			this.options,
			this._getCreateOptions(),
			options );

		var self = this;
		this.element.bind( "remove." + this.widgetName, function() {
			self.destroy();
		});

		this._create();
		this._trigger( "create" );
		this._init();
	},
	_getCreateOptions: function() {
		return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ];
	},
	_create: function() {},
	_init: function() {},

	destroy: function() {
		this.element
			.unbind( "." + this.widgetName )
			.removeData( this.widgetName );
		this.widget()
			.unbind( "." + this.widgetName )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetBaseClass + "-disabled " +
				"ui-state-disabled" );
	},

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.extend( {}, this.options );
		}

		if  (typeof key === "string" ) {
			if ( value === undefined ) {
				return this.options[ key ];
			}
			options = {};
			options[ key ] = value;
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var self = this;
		$.each( options, function( key, value ) {
			self._setOption( key, value );
		});

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				[ value ? "addClass" : "removeClass"](
					this.widgetBaseClass + "-disabled" + " " +
					"ui-state-disabled" )
				.attr( "aria-disabled", value );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_trigger: function( type, event, data ) {
		var callback = this.options[ type ];

		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		data = data || {};

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if ( event.originalEvent ) {
			for ( var i = $.event.props.length, prop; i; ) {
				prop = $.event.props[ --i ];
				event[ prop ] = event.originalEvent[ prop ];
			}
		}

		this.element.trigger( event, data );

		return !( $.isFunction(callback) &&
			callback.call( this.element[0], event, data ) === false ||
			event.isDefaultPrevented() );
	}
};

})( jQuery );
<|endoftext|>