<commit_before>/*global define*/
define([
        './equals',
        'Core/Cartesian2',
        'Core/defined',
        'Core/DeveloperError',
        'Core/RuntimeError'
    ], function(
        equals,
        Cartesian2,
        defined,
        DeveloperError,
        RuntimeError) {
    'use strict';

    var webglStub = !!window.webglStub;

    function createMissingFunctionMessageFunction(item, actualPrototype, expectedInterfacePrototype) {
        return function() {
            return 'Expected function \'' + item + '\' to exist on ' + actualPrototype.constructor.name + ' because it should implement interface ' + expectedInterfacePrototype.constructor.name + '.';
        };
    }

    function makeThrowFunction(debug, Type, name) {
        if (debug) {
            return function(util, customEqualityTesters) {
                return {
                    compare : function(actual, expected) {
                        // based on the built-in Jasmine toThrow matcher
                        var result = false;
                        var exception;

                        if (typeof actual !== 'function') {
                            throw new Error('Actual is not a function');
                        }

                        try {
                            actual();
                        } catch (e) {
                            exception = e;
                        }

                        if (exception) {
                            result = exception instanceof Type;
                        }

                        var message;
                        if (result) {
                            message = ['Expected function not to throw ' + name + ' , but it threw', exception.message || exception].join(' ');
                        } else {
                            message = 'Expected function to throw ' + name + '.';
                        }

                        return {
                            pass : result,
                            message : message
                        };
                    }
                };
            };
        }

        return function() {
            return {
                compare : function(actual, expected) {
                    return { pass : true  };
                },
                negativeCompare : function(actual, expected) {
                    return { pass : true };
                }
            };
        };
    }

    function createDefaultMatchers(debug) {
        return {
            toBeGreaterThanOrEqualTo : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : actual >= expected };
                    }
                };
            },

            toBeLessThanOrEqualTo : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : actual <= expected };
                    }
                };
            },

            toBeBetween : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, lower, upper) {
                        if (lower > upper) {
                            var tmp = upper;
                            upper = lower;
                            lower = tmp;
                        }
                        return { pass : actual >= lower && actual <= upper };
                    }
                };
            },

            toStartWith : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : actual.slice(0, expected.length) === expected };
                    }
                };
            },

            toEndWith : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : actual.slice(-expected.length) === expected };
                    }
                };
            },

            toEqual : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : equals(util, customEqualityTesters, actual, expected) };
                    }
                };
            },

            toEqualEpsilon : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected, epsilon) {
                        function equalityTester(a, b) {
                            if (Array.isArray(a) && Array.isArray(b)) {
                                if (a.length !== b.length) {
                                    return false;
                                }

                                for (var i = 0; i < a.length; ++i) {
                                    if (!equalityTester(a[i], b[i])) {
                                        return false;
                                    }
                                }

                                return true;
                            }

                            var to_run;
                            if (defined(a)) {
                                if (typeof a.equalsEpsilon === 'function') {
                                    return a.equalsEpsilon(b, epsilon);
                                } else if (a instanceof Object) {
                                    // Check if the current object has a static function named 'equalsEpsilon'
                                    to_run = Object.getPrototypeOf(a).constructor.equalsEpsilon;
                                    if (typeof to_run === 'function') {
                                        return to_run(a, b, epsilon);
                                    }
                                }
                            }

                            if (defined(b)) {
                                if (typeof b.equalsEpsilon === 'function') {
                                    return b.equalsEpsilon(a, epsilon);
                                } else if (b instanceof Object) {
                                    // Check if the current object has a static function named 'equalsEpsilon'
                                    to_run = Object.getPrototypeOf(b).constructor.equalsEpsilon;
                                    if (typeof to_run === 'function') {
                                        return to_run(b, a, epsilon);
                                    }
                                }
                            }

                            if (typeof a === 'number' || typeof b === 'number') {
                                return Math.abs(a - b) <= epsilon;
                            }

                            return undefined;
                        }

                        var result = equals(util, [equalityTester], actual, expected);

                        return { pass : result };
                    }
                };
            },

            toConformToInterface : function(util, customEqualityTesters) {
                return {
                    compare : function(actual, expectedInterface) {
                        // All function properties on the prototype should also exist on the actual's prototype.
                        var actualPrototype = actual.prototype;
                        var expectedInterfacePrototype = expectedInterface.prototype;

                        for ( var item in expectedInterfacePrototype) {
                            if (expectedInterfacePrototype.hasOwnProperty(item) && typeof expectedInterfacePrototype[item] === 'function' && !actualPrototype.hasOwnProperty(item)) {
                                return { pass : false, message : createMissingFunctionMessageFunction(item, actualPrototype, expectedInterfacePrototype) };
                            }
                        }

                        return { pass : true };
                    }
                };
            },

            toBeInstanceOf : function(util, customEqualityTesters) {
                return {
                    compare : function(actual, expectedConstructor) {
                        return { pass : actual instanceof expectedConstructor };
                    }
                };
            },

            toRender : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return renderEquals(util, customEqualityTesters, actual, expected, true);
                    }
                };
            },

            notToRender : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return renderEquals(util, customEqualityTesters, actual, expected, false);
                    }
                };
            },

            toRenderAndCall : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        if (!webglStub) {
                            var scene = actual;
                            scene.initializeFrame();
                            scene.render();
                            var actualRgba = scene.context.readPixels();

                            // The callback may have expectations that fail, which still makes the
                            // spec fail, as we desired, even though this matcher sets pass to true.
                            var callback = expected;
                            callback(actualRgba);
                        }

                        return {
                            pass : true
                        };
                    }
                };
            },

            toPickAndCall : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        if (!webglStub) {
                            var scene = actual;
                            var result = scene.pick(new Cartesian2(0, 0));

                            // The callback may have expectations that fail, which still makes the
                            // spec fail, as we desired, even though this matcher sets pass to true.
                            var callback = expected;
                            callback(result);
                        }

                        return {
                            pass : true
                        };
                    }
                };
            },

            toThrow : function(expectedConstructor) {
                throw new Error('Do not use toThrow.  Use toThrowDeveloperError or toThrowRuntimeError instead.');
            },

            toThrowDeveloperError : makeThrowFunction(debug, DeveloperError, 'DeveloperError'),

            toThrowRuntimeError : makeThrowFunction(true, RuntimeError, 'RuntimeError')
        };
    }

    function renderEquals(util, customEqualityTesters, actual, expected, expectEqual) {
        var scene;

        if (defined(actual.scene) && defined(actual.time)) {
            // options were passed to render the scene at a given time
            var options = actual;
            scene = actual.scene;
            scene.initializeFrame();
            scene.render(options.time);
        } else {
            scene = actual;
            scene.initializeFrame();
            scene.render();
        }

        var actualRgba = scene.context.readPixels();

        // When the WebGL stub is used, all WebGL function calls are noops so
        // the expectation is not verified.  This allows running all the WebGL
        // tests, to exercise as much Cesium code as possible, even if the system
        // doesn't have a WebGL implementation or a reliable one.
        if (webglStub) {
            return {
                pass : true
            };
        }

        var eq = equals(util, customEqualityTesters, actualRgba, expected);
        var pass = expectEqual ? eq : !eq;

        var message;
        if (!pass) {
            message = 'Expected to render [' + expected + '], but actually rendered [' + actualRgba + '].';
        }

        return {
            pass : pass,
            message : message
        };
    }

    return function(debug) {
        return function() {
            this.addMatchers(createDefaultMatchers(debug));
        };
    };
});
<commit_msg>Make toRender and toRenderAndCall consistent<commit_after>/*global define*/
define([
        './equals',
        'Core/Cartesian2',
        'Core/defined',
        'Core/DeveloperError',
        'Core/RuntimeError'
    ], function(
        equals,
        Cartesian2,
        defined,
        DeveloperError,
        RuntimeError) {
    'use strict';

    var webglStub = !!window.webglStub;

    function createMissingFunctionMessageFunction(item, actualPrototype, expectedInterfacePrototype) {
        return function() {
            return 'Expected function \'' + item + '\' to exist on ' + actualPrototype.constructor.name + ' because it should implement interface ' + expectedInterfacePrototype.constructor.name + '.';
        };
    }

    function makeThrowFunction(debug, Type, name) {
        if (debug) {
            return function(util, customEqualityTesters) {
                return {
                    compare : function(actual, expected) {
                        // based on the built-in Jasmine toThrow matcher
                        var result = false;
                        var exception;

                        if (typeof actual !== 'function') {
                            throw new Error('Actual is not a function');
                        }

                        try {
                            actual();
                        } catch (e) {
                            exception = e;
                        }

                        if (exception) {
                            result = exception instanceof Type;
                        }

                        var message;
                        if (result) {
                            message = ['Expected function not to throw ' + name + ' , but it threw', exception.message || exception].join(' ');
                        } else {
                            message = 'Expected function to throw ' + name + '.';
                        }

                        return {
                            pass : result,
                            message : message
                        };
                    }
                };
            };
        }

        return function() {
            return {
                compare : function(actual, expected) {
                    return { pass : true  };
                },
                negativeCompare : function(actual, expected) {
                    return { pass : true };
                }
            };
        };
    }

    function createDefaultMatchers(debug) {
        return {
            toBeGreaterThanOrEqualTo : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : actual >= expected };
                    }
                };
            },

            toBeLessThanOrEqualTo : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : actual <= expected };
                    }
                };
            },

            toBeBetween : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, lower, upper) {
                        if (lower > upper) {
                            var tmp = upper;
                            upper = lower;
                            lower = tmp;
                        }
                        return { pass : actual >= lower && actual <= upper };
                    }
                };
            },

            toStartWith : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : actual.slice(0, expected.length) === expected };
                    }
                };
            },

            toEndWith : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : actual.slice(-expected.length) === expected };
                    }
                };
            },

            toEqual : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return { pass : equals(util, customEqualityTesters, actual, expected) };
                    }
                };
            },

            toEqualEpsilon : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected, epsilon) {
                        function equalityTester(a, b) {
                            if (Array.isArray(a) && Array.isArray(b)) {
                                if (a.length !== b.length) {
                                    return false;
                                }

                                for (var i = 0; i < a.length; ++i) {
                                    if (!equalityTester(a[i], b[i])) {
                                        return false;
                                    }
                                }

                                return true;
                            }

                            var to_run;
                            if (defined(a)) {
                                if (typeof a.equalsEpsilon === 'function') {
                                    return a.equalsEpsilon(b, epsilon);
                                } else if (a instanceof Object) {
                                    // Check if the current object has a static function named 'equalsEpsilon'
                                    to_run = Object.getPrototypeOf(a).constructor.equalsEpsilon;
                                    if (typeof to_run === 'function') {
                                        return to_run(a, b, epsilon);
                                    }
                                }
                            }

                            if (defined(b)) {
                                if (typeof b.equalsEpsilon === 'function') {
                                    return b.equalsEpsilon(a, epsilon);
                                } else if (b instanceof Object) {
                                    // Check if the current object has a static function named 'equalsEpsilon'
                                    to_run = Object.getPrototypeOf(b).constructor.equalsEpsilon;
                                    if (typeof to_run === 'function') {
                                        return to_run(b, a, epsilon);
                                    }
                                }
                            }

                            if (typeof a === 'number' || typeof b === 'number') {
                                return Math.abs(a - b) <= epsilon;
                            }

                            return undefined;
                        }

                        var result = equals(util, [equalityTester], actual, expected);

                        return { pass : result };
                    }
                };
            },

            toConformToInterface : function(util, customEqualityTesters) {
                return {
                    compare : function(actual, expectedInterface) {
                        // All function properties on the prototype should also exist on the actual's prototype.
                        var actualPrototype = actual.prototype;
                        var expectedInterfacePrototype = expectedInterface.prototype;

                        for ( var item in expectedInterfacePrototype) {
                            if (expectedInterfacePrototype.hasOwnProperty(item) && typeof expectedInterfacePrototype[item] === 'function' && !actualPrototype.hasOwnProperty(item)) {
                                return { pass : false, message : createMissingFunctionMessageFunction(item, actualPrototype, expectedInterfacePrototype) };
                            }
                        }

                        return { pass : true };
                    }
                };
            },

            toBeInstanceOf : function(util, customEqualityTesters) {
                return {
                    compare : function(actual, expectedConstructor) {
                        return { pass : actual instanceof expectedConstructor };
                    }
                };
            },

            toRender : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return renderEquals(util, customEqualityTesters, actual, expected, true);
                    }
                };
            },

            notToRender : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        return renderEquals(util, customEqualityTesters, actual, expected, false);
                    }
                };
            },

            toRenderAndCall : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        if (!webglStub) {
                            var actualRgba = renderAndReadPixels(actual);

                            // The callback may have expectations that fail, which still makes the
                            // spec fail, as we desired, even though this matcher sets pass to true.
                            var callback = expected;
                            callback(actualRgba);
                        }

                        return {
                            pass : true
                        };
                    }
                };
            },

            toPickAndCall : function(util, customEqualityTesters) {
                return {
                    compare: function(actual, expected) {
                        if (!webglStub) {
                            var scene = actual;
                            var result = scene.pick(new Cartesian2(0, 0));

                            // The callback may have expectations that fail, which still makes the
                            // spec fail, as we desired, even though this matcher sets pass to true.
                            var callback = expected;
                            callback(result);
                        }

                        return {
                            pass : true
                        };
                    }
                };
            },

            toThrow : function(expectedConstructor) {
                throw new Error('Do not use toThrow.  Use toThrowDeveloperError or toThrowRuntimeError instead.');
            },

            toThrowDeveloperError : makeThrowFunction(debug, DeveloperError, 'DeveloperError'),

            toThrowRuntimeError : makeThrowFunction(true, RuntimeError, 'RuntimeError')
        };
    }

    function renderAndReadPixels(options) {
        var scene;

        if (defined(options.scene)) {
            // options were passed to render the scene at a given time or prime shadow map
            scene = options.scene;
            var time = options.time;

            scene.initializeFrame();
            if (defined(options.primeShadowMap)) {
                scene.render(time); // Computes shadow near/far for next frame
            }
            scene.render(time);
        } else {
            scene = options;
            scene.initializeFrame();
            scene.render();
        }

        return scene.context.readPixels();
    }

    function renderEquals(util, customEqualityTesters, actual, expected, expectEqual) {
        var actualRgba = renderAndReadPixels(actual);

        // When the WebGL stub is used, all WebGL function calls are noops so
        // the expectation is not verified.  This allows running all the WebGL
        // tests, to exercise as much Cesium code as possible, even if the system
        // doesn't have a WebGL implementation or a reliable one.
        if (webglStub) {
            return {
                pass : true
            };
        }

        var eq = equals(util, customEqualityTesters, actualRgba, expected);
        var pass = expectEqual ? eq : !eq;

        var message;
        if (!pass) {
            message = 'Expected to render [' + expected + '], but actually rendered [' + actualRgba + '].';
        }

        return {
            pass : pass,
            message : message
        };
    }

    return function(debug) {
        return function() {
            this.addMatchers(createDefaultMatchers(debug));
        };
    };
});
<|endoftext|>


<commit_before>/**
 * Given a DOM subtree, wraps it in a list, and puts each line into its own
 * list item.
 *
 * @param {Node} node modified in place.  Its content is pulled into an
 *     HTMLOListElement, and each line is moved into a separate list item.
 *     This requires cloning elements, so the input might not have unique
 *     IDs after numbering.
 */
function numberLines(node, opt_startLineNum) {
  var nocode = /(?:^|\s)nocode(?:\s|$)/;
  var lineBreak = /\r\n?|\n/;

  var document = node.ownerDocument;

  var whitespace;
  if (node.currentStyle) {
    whitespace = node.currentStyle.whiteSpace;
  } else if (window.getComputedStyle) {
    whitespace = document.defaultView.getComputedStyle(node, null)
        .getPropertyValue('white-space');
  }
  // If it's preformatted, then we need to split lines on line breaks
  // in addition to
s.
  var isPreformatted = whitespace && 'pre' === whitespace.substring(0, 3);

  var li = document.createElement('LI');
  while (node.firstChild) {
    li.appendChild(node.firstChild);
  }
  // An array of lines.  We split below, so this is initialized to one
  // un-split line.
  var listItems = [li];

  function walk(node) {
    switch (node.nodeType) {
      case 1:  // Element
        if (nocode.test(node.className)) { console.log('nocode'); break; }
console.log('  el=' + node.nodeName);
        if ('BR' === node.nodeName) {
          breakAfter(node);
          // Discard the
 since it is now flush against a
.
          if (node.parentNode) {
            node.parentNode.removeChild(node);
          }
        } else {
          for (var child = node.firstChild; child; child = child.nextSibling) {
            walk(child);
          }
        }
        break;
      case 3: case 4:  // Text
        if (isPreformatted) {
          var text = node.nodeValue;
          var match = text.match(lineBreak);
          if (match) {
            var firstLine = text.substring(0, match.index);
            node.nodeValue = firstLine;
            var tail = text.substring(match.index + match[0].length);
console.log('split "' + text.replace(/\r\n?|\n/g, '\\n') + '" into "' + firstLine + '" and "' + tail.replace(/\r\n?|\n/g, '\\n') + '"');
            if (tail) {
              var parent = node.parentNode;
              parent.insertBefore(
                  document.createTextNode(tail), node.nextSibling);
            }
            breakAfter(node);
            if (!firstLine) {
              // Don't leave blank text nodes in the DOM.
              node.parentNode.removeChild(node);
            }
          }
        }
        break;
    }
  }

  // Split a line after the given node.
  function breakAfter(lineEndNode) {
    // If there's nothing to the right, then we can skip ending the line
    // here, and move root-wards since splitting just before an end-tag
    // would require us to create a bunch of empty copies.
    while (!lineEndNode.nextSibling) {
      lineEndNode = lineEndNode.parentNode;
      if (!lineEndNode) { return; }
    }

    function breakLeftOf(limit, copy) {
      // Clone shallowly if this node needs to be on both sides of the break.
      var rightSide = copy ? limit.cloneNode(false) : limit;
      var parent = limit.parentNode;
      if (parent) {
        // We clone the parent chain.
        // This helps us resurrect important styling elements that cross lines.
        // E.g. in Foo
Bar
        // should be rewritten to
Foo

Bar
.
        var parentClone = breakLeftOf(parent, 1);
        // Move the clone and everything to the right of the original
        // onto the cloned parent.
        var next = limit.nextSibling;
        parentClone.appendChild(rightSide);
        for (var sibling = next; sibling; sibling = next) {
          next = sibling.nextSibling;
          parentClone.appendChild(sibling);
        }
      }
      return rightSide;
    }

    var split = breakLeftOf(lineEndNode.nextSibling, 0);

    // Walk the parent chain until we reach an unattached LI.
    for (var parent; (parent = split.parentNode);) { split = parent; }
    // Put it on the list of lines for later processing.
    listItems.push(split);
console.log('pushing listItem length=' + listItems.length);
  }

  // Split lines while there are lines left to split.
  for (var i = 0;  // Number of lines that have been split so far.
       i < listItems.length;  // length updated by breakAfter calls.
       ++i) {
console.log('walking list item ' + i + ' : ' + listItems[i].innerHTML.replace(/[\r\n]+/, '\\n'));
    walk(listItems[i]);
  }

  // Make sure numeric indices show correctly.
  if (opt_startLineNum === (opt_startLineNum|0)) {
    listItems[0].setAttribute('value', opt_startLineNum);
  }

  var ol = document.createElement('OL');
  ol.className = 'linenums';
  var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
  for (var i = 0, n = listItems.length; i < n; ++i) {
    li = listItems[i];
    // Stick a class on the LIs so that stylesheets can
    // color odd/even rows, or any other row pattern that
    // is co-prime with 10.
    li.className = 'L' + ((i + offset) % 10);
    if (!li.firstChild) {
      li.appendChild(document.createTextNode('\xA0'));
    }
    ol.appendChild(li);
  }

  node.appendChild(ol);
}<commit_msg>logging for IE<commit_after>/**
 * Given a DOM subtree, wraps it in a list, and puts each line into its own
 * list item.
 *
 * @param {Node} node modified in place.  Its content is pulled into an
 *     HTMLOListElement, and each line is moved into a separate list item.
 *     This requires cloning elements, so the input might not have unique
 *     IDs after numbering.
 */
function numberLines(node, opt_startLineNum) {
  var nocode = /(?:^|\s)nocode(?:\s|$)/;
  var lineBreak = /\r\n?|\n/;

  var document = node.ownerDocument;

  var whitespace;
  if (node.currentStyle) {
    whitespace = node.currentStyle.whiteSpace;
  } else if (window.getComputedStyle) {
    whitespace = document.defaultView.getComputedStyle(node, null)
        .getPropertyValue('white-space');
  }
  // If it's preformatted, then we need to split lines on line breaks
  // in addition to
s.
  var isPreformatted = whitespace && 'pre' === whitespace.substring(0, 3);

  var li = document.createElement('LI');
  while (node.firstChild) {
    li.appendChild(node.firstChild);
  }
  // An array of lines.  We split below, so this is initialized to one
  // un-split line.
  var listItems = [li];

  function walk(node) {
    switch (node.nodeType) {
      case 1:  // Element
        if (nocode.test(node.className)) { console.log('nocode'); break; }
console.log('  el=' + node.nodeName);
        if ('BR' === node.nodeName) {
          breakAfter(node);
          // Discard the
 since it is now flush against a
.
          if (node.parentNode) {
            node.parentNode.removeChild(node);
          }
        } else {
          for (var child = node.firstChild; child; child = child.nextSibling) {
            walk(child);
          }
        }
        break;
      case 3: case 4:  // Text
        if (isPreformatted) {
          var text = node.nodeValue;
          var match = text.match(lineBreak);
          if (match) {
            var firstLine = text.substring(0, match.index);
            node.nodeValue = firstLine;
            var tail = text.substring(match.index + match[0].length);
console.log('split "' + text.replace(/\r\n?|\n/g, '\\n') + '" into "' + firstLine + '" and "' + tail.replace(/\r\n?|\n/g, '\\n') + '"');
            if (tail) {
              var parent = node.parentNode;
              parent.insertBefore(
                  document.createTextNode(tail), node.nextSibling);
            }
            breakAfter(node);
            if (!firstLine) {
              // Don't leave blank text nodes in the DOM.
              node.parentNode.removeChild(node);
            }
          }
        }
        break;
    }
  }

  // Split a line after the given node.
  function breakAfter(lineEndNode) {
    // If there's nothing to the right, then we can skip ending the line
    // here, and move root-wards since splitting just before an end-tag
    // would require us to create a bunch of empty copies.
    while (!lineEndNode.nextSibling) {
      lineEndNode = lineEndNode.parentNode;
      if (!lineEndNode) { return; }
    }

    function breakLeftOf(limit, copy) {
      // Clone shallowly if this node needs to be on both sides of the break.
      var rightSide = copy ? limit.cloneNode(false) : limit;
      var parent = limit.parentNode;
      if (parent) {
        // We clone the parent chain.
        // This helps us resurrect important styling elements that cross lines.
        // E.g. in Foo
Bar
        // should be rewritten to
Foo

Bar
.
        var parentClone = breakLeftOf(parent, 1);
        // Move the clone and everything to the right of the original
        // onto the cloned parent.
        var next = limit.nextSibling;
        parentClone.appendChild(rightSide);
        for (var sibling = next; sibling; sibling = next) {
          next = sibling.nextSibling;
          parentClone.appendChild(sibling);
        }
      }
      return rightSide;
    }

    var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);

    // Walk the parent chain until we reach an unattached LI.
    for (var parent; (parent = copiedListItem.parentNode);) { copiedListItem = parent; }
    // Put it on the list of lines for later processing.
    listItems.push(copiedListItem);
console.log('pushing listItem length=' + listItems.length + ', copy=' + copiedListItem.nodeName);
  }

  // Split lines while there are lines left to split.
  for (var i = 0;  // Number of lines that have been split so far.
       i < listItems.length;  // length updated by breakAfter calls.
       ++i) {
console.log('walking list item ' + i + ' : ' + listItems[i].innerHTML.replace(/[\r\n]+/, '\\n'));
    walk(listItems[i]);
  }

  // Make sure numeric indices show correctly.
  if (opt_startLineNum === (opt_startLineNum|0)) {
    listItems[0].setAttribute('value', opt_startLineNum);
  }

  var ol = document.createElement('OL');
  ol.className = 'linenums';
  var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
  for (var i = 0, n = listItems.length; i < n; ++i) {
    li = listItems[i];
    // Stick a class on the LIs so that stylesheets can
    // color odd/even rows, or any other row pattern that
    // is co-prime with 10.
    li.className = 'L' + ((i + offset) % 10);
    if (!li.firstChild) {
      li.appendChild(document.createTextNode('\xA0'));
    }
    ol.appendChild(li);
  }

  node.appendChild(ol);
}<|endoftext|>


<commit_before>var ipc = window.require('ipc');
var _ = require('underscore');

var Reflux = require('reflux');
var Actions = require('../actions/actions');
var apiRequests = require('../utils/api-requests');

var NotificationsStore = Reflux.createStore({
  listenables: Actions,

  init: function () {
    this._notifications = [];
  },

  updateTrayIcon: function (notifications) {
    if (notifications.length > 0) {
      ipc.sendChannel('update-icon', 'TrayActive');
    } else {
      ipc.sendChannel('update-icon', 'TrayIdle');
    }
  },

  onGetNotifications: function () {
    var self = this;

    apiRequests
      .getAuth('https://api.github.com/notifications')
      .end(function (err, response) {
        if (response && response.ok) {
          // Success - Do Something.
          Actions.getNotifications.completed(response.body);
          self.updateTrayIcon(response.body);
        } else {
          // Error - Show messages.
          Actions.getNotifications.failed(err);
        }
      });
  },

  onGetNotificationsCompleted: function (notifications) {
    var groupedNotifications = _.groupBy(notifications, function (object) {
      return object.repository.full_name;
    });

    var array = [];
    _.map(groupedNotifications, function (obj) {
      array.push(obj);
    });

    this._notifications = array;
    this.trigger(this._notifications);
  },

  onGetNotificationsFailed: function () {
    this._notifications = [];
    this.trigger(this._notifications);
  }

});

module.exports = NotificationsStore;
<commit_msg>Parameter for notifications requests<commit_after>var ipc = window.require('ipc');
var _ = require('underscore');

var Reflux = require('reflux');
var Actions = require('../actions/actions');
var apiRequests = require('../utils/api-requests');
var SettingsStore = require('../stores/settings');

var NotificationsStore = Reflux.createStore({
  listenables: Actions,

  init: function () {
    this._notifications = [];
  },

  updateTrayIcon: function (notifications) {
    if (notifications.length > 0) {
      ipc.sendChannel('update-icon', 'TrayActive');
    } else {
      ipc.sendChannel('update-icon', 'TrayIdle');
    }
  },

  onGetNotifications: function () {
    var self = this;
    var participating = SettingsStore.getSettings().participating;

    apiRequests
      .getAuth('https://api.github.com/notifications?participating=' + participating)
      .end(function (err, response) {
        if (response && response.ok) {
          // Success - Do Something.
          Actions.getNotifications.completed(response.body);
          self.updateTrayIcon(response.body);
        } else {
          // Error - Show messages.
          Actions.getNotifications.failed(err);
        }
      });
  },

  onGetNotificationsCompleted: function (notifications) {
    var groupedNotifications = _.groupBy(notifications, function (object) {
      return object.repository.full_name;
    });

    var array = [];
    _.map(groupedNotifications, function (obj) {
      array.push(obj);
    });

    this._notifications = array;
    this.trigger(this._notifications);
  },

  onGetNotificationsFailed: function () {
    this._notifications = [];
    this.trigger(this._notifications);
  }

});

module.exports = NotificationsStore;
<|endoftext|>


<commit_before>var injector = require('../');
var path = require('path');
var q = require('q');
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
var bodyParser = require('body-parser');

var app = injector();

app.value('secret', 'Secret Cookie Signature');

app.value('port', 3000);

app.singleton('single', function(port) {
    return 'port: ' + port;
});

app.provide('randString', function(single) {
    return single + ' ' + Math.random();
});

app.provide('delay', function() {
    var deferred = q.defer();
    /* istanbul ignore next */
    setTimeout(function() {
        deferred.resolve('done delaying');
    }, 1000);
    return deferred.promise;
});

app.provide('promiseError', function() {
    return q.fcall(function() {
        throw Error('Should catch this');
    });
});

app.provide('callNext', function(next) {
    next();
});

app.use(serveStatic(__dirname));
app.use(bodyParser.json());

app.get('/greet/:name/:age', function(params, send) {
    send('hello ' + params.name +
        ' age ' + params.age);
});

app.get(/^\/foo\/bar(.*)$/, function(params, send) {
    send(params[0]);
});

app.get('/status/:status', function(params, send) {
    send(parseInt(params.status), params.status);
});

app.get('/send-buffer', function(send) {
    send(new Buffer('hello buffer', 'utf8'));
});

app.get('/send-json', function(send) {
    send({success:true});
});

app.get('/json', function(req, sendJson) {
    sendJson({here:'is',some:'json'});
});

app.post('/json', function(req, sendJson) {
    sendJson(req.body);
});

app.get('/port', function(sendJson, port) {
    sendJson(port);
});

app.get('/single', function(send, single) {
    send(single);
});

app.get('/rand', function(send, randString) {
    send(randString);
});

app.get('/randOptional', function(send, randString_, optional_) {
    send(optional_);
});

app.get('/randOptionalDefault', function(send, optional_) {
    var optional = optional_ || 'sam';
    send(optional);
});

app.get('/accepts', function(res, send, accepts, acceptsEncodings, acceptsCharsets, acceptsLanguages, contentType) {
    var stats =
        'favored content type: ' + accepts('txt','html','xml') + '\n' +
        'favored encoding: ' + acceptsEncodings('gzip') + '\n' +
        'favored charset: ' + acceptsCharsets('utf8') + '\n' +
        'favored language: ' + acceptsLanguages('en', 'es');
    contentType('txt');
    send(stats);
});

/* istanbul ignore next */
app.get('/delay', function(delay, send) {
    send('delayed ' + delay);
});

/* istanbul ignore next */
app.get('/error', function(promiseError, send) {
    send("Shouldn't get here");
});

app.get('/file', function(sendFile) {
    sendFile(path.join(__dirname, 'file.txt'));
});

app.get('/file-alt', function(sendFile) {
    sendFile(path.join(__dirname, 'file.txt'), function(){});
});

app.get('/file404', function(sendFile) {
    // This file shouldn't exist
    sendFile(path.join(__dirname, 'file404.txt'));
});

app.get('/download', function(download) {
    download(path.join(__dirname, 'file.txt'), 'file123.txt');
});

app.get('/download-alt', function(res, download) {
    download(path.join(__dirname, 'file.txt'), function() {});
});

/* istanbul ignore next */
app.get('/next', function(callNext, send) {
    send("Shouldn't get here");
});

app.get('/next', function(send) {
    send('Should get here');
});

app.get('/format', function(format, contentType, send, sendJson) {
    format({
        'text/plain': function() {
            contentType('txt');
            send('Here is some text');
        },
        'text/html': function() {
            send('Here is some html');
        },
        'application/json': function() {
            sendJson({message: 'Here is some json'});
        }
    });
});

app.get('/vary', function(vary, send) {
    vary('Accept');
    send('Added Vary header');
})

app.get('/location', function(res, location) {
    location('/location2');
    res.end();
});

app.get('/location-back', function(res, location) {
    location('back');
    res.end();
});

/* istanbul ignore next */
app.get('/location2', function(send) {
    send('Hello from location2');
});

app.get('/cookie/:name', function(params, send, cookie) {
    cookie('name', params.name);
    send('Set a cookie');
});

app.get('/signed-cookie/:name', function(params, send, cookie) {
    cookie('name', params.name, {signed: true});
    send('Set a signed cookie');
});

app.get('/clear-cookie', function(send, clearCookie) {
    clearCookie('name');
    send('Cleared cookie');
});

// TODO: more cookie examples

app.get('/error-pass', function(next) {
    next(new Error('pass'));
});

app.error(function(err, res, send, next) {
    if ('pass' === err.message) {
        next(err);
    }
    res.statusCode = err.status || 500;
    send(err.message);
});

app.use(serveIndex(__dirname));

/* istanbul ignore else */
if (module.parent) {
    module.exports = app;
} else {
    app.listen(app.value('port'));
}
<commit_msg>Return when calling next() in kitchen sink error handler<commit_after>var injector = require('../');
var path = require('path');
var q = require('q');
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
var bodyParser = require('body-parser');

var app = injector();

app.value('secret', 'Secret Cookie Signature');

app.value('port', 3000);

app.singleton('single', function(port) {
    return 'port: ' + port;
});

app.provide('randString', function(single) {
    return single + ' ' + Math.random();
});

app.provide('delay', function() {
    var deferred = q.defer();
    /* istanbul ignore next */
    setTimeout(function() {
        deferred.resolve('done delaying');
    }, 1000);
    return deferred.promise;
});

app.provide('promiseError', function() {
    return q.fcall(function() {
        throw Error('Should catch this');
    });
});

app.provide('callNext', function(next) {
    next();
});

app.use(serveStatic(__dirname));
app.use(bodyParser.json());

app.get('/greet/:name/:age', function(params, send) {
    send('hello ' + params.name +
        ' age ' + params.age);
});

app.get(/^\/foo\/bar(.*)$/, function(params, send) {
    send(params[0]);
});

app.get('/status/:status', function(params, send) {
    send(parseInt(params.status), params.status);
});

app.get('/send-buffer', function(send) {
    send(new Buffer('hello buffer', 'utf8'));
});

app.get('/send-json', function(send) {
    send({success:true});
});

app.get('/json', function(req, sendJson) {
    sendJson({here:'is',some:'json'});
});

app.post('/json', function(req, sendJson) {
    sendJson(req.body);
});

app.get('/port', function(sendJson, port) {
    sendJson(port);
});

app.get('/single', function(send, single) {
    send(single);
});

app.get('/rand', function(send, randString) {
    send(randString);
});

app.get('/randOptional', function(send, randString_, optional_) {
    send(optional_);
});

app.get('/randOptionalDefault', function(send, optional_) {
    var optional = optional_ || 'sam';
    send(optional);
});

app.get('/accepts', function(res, send, accepts, acceptsEncodings, acceptsCharsets, acceptsLanguages, contentType) {
    var stats =
        'favored content type: ' + accepts('txt','html','xml') + '\n' +
        'favored encoding: ' + acceptsEncodings('gzip') + '\n' +
        'favored charset: ' + acceptsCharsets('utf8') + '\n' +
        'favored language: ' + acceptsLanguages('en', 'es');
    contentType('txt');
    send(stats);
});

/* istanbul ignore next */
app.get('/delay', function(delay, send) {
    send('delayed ' + delay);
});

/* istanbul ignore next */
app.get('/error', function(promiseError, send) {
    send("Shouldn't get here");
});

app.get('/file', function(sendFile) {
    sendFile(path.join(__dirname, 'file.txt'));
});

app.get('/file-alt', function(sendFile) {
    sendFile(path.join(__dirname, 'file.txt'), function(){});
});

app.get('/file404', function(sendFile) {
    // This file shouldn't exist
    sendFile(path.join(__dirname, 'file404.txt'));
});

app.get('/download', function(download) {
    download(path.join(__dirname, 'file.txt'), 'file123.txt');
});

app.get('/download-alt', function(res, download) {
    download(path.join(__dirname, 'file.txt'), function() {});
});

/* istanbul ignore next */
app.get('/next', function(callNext, send) {
    send("Shouldn't get here");
});

app.get('/next', function(send) {
    send('Should get here');
});

app.get('/format', function(format, contentType, send, sendJson) {
    format({
        'text/plain': function() {
            contentType('txt');
            send('Here is some text');
        },
        'text/html': function() {
            send('Here is some html');
        },
        'application/json': function() {
            sendJson({message: 'Here is some json'});
        }
    });
});

app.get('/vary', function(vary, send) {
    vary('Accept');
    send('Added Vary header');
})

app.get('/location', function(res, location) {
    location('/location2');
    res.end();
});

app.get('/location-back', function(res, location) {
    location('back');
    res.end();
});

/* istanbul ignore next */
app.get('/location2', function(send) {
    send('Hello from location2');
});

app.get('/cookie/:name', function(params, send, cookie) {
    cookie('name', params.name);
    send('Set a cookie');
});

app.get('/signed-cookie/:name', function(params, send, cookie) {
    cookie('name', params.name, {signed: true});
    send('Set a signed cookie');
});

app.get('/clear-cookie', function(send, clearCookie) {
    clearCookie('name');
    send('Cleared cookie');
});

// TODO: more cookie examples

app.get('/error-pass', function(next) {
    next(new Error('pass'));
});

app.error(function(err, res, send, next) {
    if ('pass' === err.message) {
        return next(err);
    }
    res.statusCode = err.status || 500;
    send(err.message);
});

app.use(serveIndex(__dirname));

/* istanbul ignore else */
if (module.parent) {
    module.exports = app;
} else {
    app.listen(app.value('port'));
}
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { red500, grey50 } from 'material-ui/styles/colors';

import RaisedButton from 'material-ui/RaisedButton';
import DatePicker from 'material-ui/DatePicker';
import Paper from 'material-ui/Paper';
import { List, ListItem } from 'material-ui/List';
import CircularProgress from 'material-ui/CircularProgress';

import './ShowPicker.css';

class ShowPicker extends React.Component {

    static propTypes = {
        /**
         * Fired when a show has been selected.
         * @signature (show) => void
         */
        onChange: PropTypes.func.isRequired,
    };

    state = {
        open: false,

        availableDates: null,
        minDate: null,
        maxDate: null,

        selectedDate: null,
        showsOnSelectedDate: null,
    };

    componentDidMount() {
        if (this.state.availableDates) {
            return;
        }

        fetch('/api/shows/dates', {
            accept: 'application/json',
        }).then((response) => {
            return response.json();
        }).then((dates) => {
            const l = dates.length;
            const minDate = (dates && dates[0]) ? moment(dates[0], 'YYYY-MM-DD').toDate() : null;
            const maxDate = (dates && dates[l-1]) ? moment(dates[l-1], 'YYYY-MM-DD').toDate() : null;

            this.setState({
                availableDates: dates,
                minDate: minDate,
                maxDate: maxDate,
            });
        });
    };

    onGetStartedTapped = () => {
        this.setState({ open: true });
    };

    onDateSelected = (_, date) => {
        this.setState({ selectedDate: date });

        fetch('/api/shows/' + moment(date).format('YYYY/MM/DD'), {
            accept: 'application/json',
        }).then((response) => {
            return response.json();
        }).then((shows) => {
            this.setState({ showsOnSelectedDate: shows });
        });
    };

    shouldDisableDate = (date) => {
        const { availableDates } = this.state;
        if (!availableDates) {
            return false;
        }

        return !availableDates.includes(moment(date).format('YYYY-MM-DD'));
    };

    onShowSelected = (show) => {
        this.props.onChange(show);
    };

    formatDate = (date) => {
        return moment(date).locale('de').format('dddd, DD.MM.YYYY');
    };

    // TODO FIXME Deal with various absent information.
    renderItem(show) {
        const formattedLocation = show.location + ', ' + show.theater;

        return (
            <ListItem
                key={show.id}
                primaryText={show.type}
                secondaryText={formattedLocation}
                onTouchTap={() => this.onShowSelected(show)}
            />
        );
    };

    renderItems() {
        const { showsOnSelectedDate } = this.state;
        if (!showsOnSelectedDate) {
            return (
);
        }

        if (showsOnSelectedDate.length === 0) {
            return (

Für diesen Tag gibt es aktuell leider keine Informationen.

            );
        }

        return showsOnSelectedDate.map((show) => {
            return this.renderItem(show);
        });
    };

    renderList() {
        const { selectedDate, showsOnSelectedDate } = this.state;
        if (!selectedDate) {
            return (
);
        }

        if (!showsOnSelectedDate) {
            return (
                <CircularProgress
                    color={red500}
                />
            );
        }

        const styles = {
            showList: {
                textAlign: 'left',
            },
        };

        return (
            <Paper>
            <List style={styles.showList}>
                {this.renderItems()}
            </List>
            </Paper>
        );
    };

    // TODO FIXME shouldDisableDate
    render() {
        const { open, minDate, maxDate } = this.state;

        if (!open) {
            return (
                <RaisedButton
                    label="Suchen"
                    onTouchTap={this.onGetStartedTapped}
                    backgroundColor={red500}
                    labelColor={grey50}
                />
            );
        }

        const styles = {
            root: {
                maxWidth: 400,
                margin: '0 auto',
            },
        };

        return (

                <DatePicker
                    mode="landscape"
                    okLabel="OK"
                    cancelLabel="Abbrechen"
                    hintText="Wähle das Datum der Vorstellung"
                    autoOk={true}
                    formatDate={this.formatDate}
                    DateTimeFormat={global.Intl.DateTimeFormat}
                    locale="de-DE"
                    minDate={minDate}
                    maxDate={maxDate}
                    onChange={this.onDateSelected}
                    shouldDisableDate={this.shouldDisableDate}
                />
                {this.renderList()}

        );
    };

}

export default ShowPicker;<commit_msg>Deal with more absent information<commit_after>// @flow

import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { red500, grey50 } from 'material-ui/styles/colors';

import RaisedButton from 'material-ui/RaisedButton';
import DatePicker from 'material-ui/DatePicker';
import Paper from 'material-ui/Paper';
import { List, ListItem } from 'material-ui/List';
import CircularProgress from 'material-ui/CircularProgress';

import './ShowPicker.css';

class ShowPicker extends React.Component {

    static propTypes = {
        /**
         * Fired when a show has been selected.
         * @signature (show) => void
         */
        onChange: PropTypes.func.isRequired,
    };

    state = {
        open: false,

        availableDates: null,
        minDate: null,
        maxDate: null,

        selectedDate: null,
        showsOnSelectedDate: null,
    };

    componentDidMount() {
        if (this.state.availableDates) {
            return;
        }

        fetch('/api/shows/dates', {
            accept: 'application/json',
        }).then((response) => {
            return response.json();
        }).then((dates) => {
            const l = dates.length;
            const minDate = (dates && dates[0]) ? moment(dates[0], 'YYYY-MM-DD').toDate() : null;
            const maxDate = (dates && dates[l-1]) ? moment(dates[l-1], 'YYYY-MM-DD').toDate() : null;

            this.setState({
                availableDates: dates,
                minDate: minDate,
                maxDate: maxDate,
            });
        });
    };

    onGetStartedTapped = () => {
        this.setState({ open: true });
    };

    onDateSelected = (_, date) => {
        this.setState({ selectedDate: date });

        fetch('/api/shows/' + moment(date).format('YYYY/MM/DD'), {
            accept: 'application/json',
        }).then((response) => {
            return response.json();
        }).then((shows) => {
            this.setState({ showsOnSelectedDate: shows });
        });
    };

    shouldDisableDate = (date) => {
        const { availableDates } = this.state;
        if (!availableDates) {
            return false;
        }

        return !availableDates.includes(moment(date).format('YYYY-MM-DD'));
    };

    onShowSelected = (show) => {
        this.props.onChange(show);
    };

    formatDate = (date) => {
        return moment(date).locale('de').format('dddd, DD.MM.YYYY');
    };

    renderItem(show) {
        let formattedTitle = show.type;
        if (show.time) {
            formattedTitle += ', ' + show.time;
        }

        let formattedLocation = show.location;
        if (show.theater) {
            formattedLocation += + ', ' + show.theater;
        }

        return (
            <ListItem
                key={show.id}
                primaryText={formattedTitle}
                secondaryText={formattedLocation}
                onTouchTap={() => this.onShowSelected(show)}
            />
        );
    };

    renderItems() {
        const { showsOnSelectedDate } = this.state;
        if (!showsOnSelectedDate) {
            return (
);
        }

        if (showsOnSelectedDate.length === 0) {
            return (

Für diesen Tag gibt es aktuell leider keine Informationen.

            );
        }

        return showsOnSelectedDate.map((show) => {
            return this.renderItem(show);
        });
    };

    renderList() {
        const { selectedDate, showsOnSelectedDate } = this.state;
        if (!selectedDate) {
            return (
);
        }

        if (!showsOnSelectedDate) {
            return (
                <CircularProgress
                    color={red500}
                />
            );
        }

        const styles = {
            showList: {
                textAlign: 'left',
            },
        };

        return (
            <Paper>
            <List style={styles.showList}>
                {this.renderItems()}
            </List>
            </Paper>
        );
    };

    render() {
        const { open, minDate, maxDate } = this.state;

        if (!open) {
            return (
                <RaisedButton
                    label="Suchen"
                    onTouchTap={this.onGetStartedTapped}
                    backgroundColor={red500}
                    labelColor={grey50}
                />
            );
        }

        const styles = {
            root: {
                maxWidth: 400,
                margin: '0 auto',
            },
        };

        return (

                <DatePicker
                    mode="landscape"
                    okLabel="OK"
                    cancelLabel="Abbrechen"
                    hintText="Wähle das Datum der Vorstellung"
                    autoOk={true}
                    formatDate={this.formatDate}
                    DateTimeFormat={global.Intl.DateTimeFormat}
                    locale="de-DE"
                    minDate={minDate}
                    maxDate={maxDate}
                    onChange={this.onDateSelected}
                    shouldDisableDate={this.shouldDisableDate}
                />
                {this.renderList()}

        );
    };

}

export default ShowPicker;<|endoftext|>


<commit_before>'use babel';

import { createFormattingOptions, createFormattingOptionsFromStylint, format } from 'stylus-supremacy'

import AtomStylusSupremacyView from './atom-stylus-supremacy-view';
import { CompositeDisposable } from 'atom';
import fs from 'fs'
import path from 'path'

function isStylus (textEditor) {
  const { scopes } = textEditor.getRootScopeDescriptor()
  return /.stylus$/.test(scopes[0])
}

function getStylintOptionsFromFile (textEditor) {
  const [ projectPath, filePath ] = atom.project
                                      .relativizePath(textEditor.getPath())
  const pathArray = (path.sep + filePath)
                      .split(path.sep)
                      .slice(0, -1)
  const rulesPath = pathArray.reduce(result => {
    const currentPath = path.join(projectPath, ...result, '.stylintrc')
    if (fs.existsSync(currentPath)) {
      return [...result, '.stylintrc']
    }
    return result.slice(0, -1)
  }, pathArray).join(path.sep)
  if (!rulesPath) {
    atom.notifications.addError('Stylus supremacy: Can\'t find .stylintrc file.')
    throw new Error('Can\'t find .stylintrc file.')
  }
  const rules = JSON.parse(
    fs.readFileSync(path.join(projectPath, rulesPath), 'utf8')
  )
  return createFormattingOptionsFromStylint(rules)
}
function getFormattedStylusText (textEditor) {
  const formattingOptions = getStylintOptionsFromFile(textEditor)
  console.log(formattingOptions);
  const content = textEditor.getText()
  return format(content, formattingOptions)
}

export default {

  atomStylusSupremacyView: null,
  modalPanel: null,
  subscriptions: null,

  config: {
    fixOnSave: {
      type: 'boolean',
      default: false,
      description: 'Let this package fix your stylus file on save.'
    }
  },

  activate(state) {
    this.atomStylusSupremacyView = new AtomStylusSupremacyView(state.atomStylusSupremacyViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.atomStylusSupremacyView.getElement(),
      visible: true
    });

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'atom-stylus-supremacy:fix-file': async () => {
        const textEditor = atom.workspace.getActiveTextEditor()
        if (!textEditor || textEditor.isModified()) {
          atom.notifications.addError('Stylus supremacy: Please save before fixing this file.')
          return
        }
        if (!isStylus(textEditor)) {
          atom.notifications.addError('Stylus supremacy: This is not a stylus file.')
          return
        }
        const cursorPosition = textEditor.getCursorBufferPosition()
        const formattedText = getFormattedStylusText(textEditor)
        textEditor.setText(formattedText)
        textEditor.setCursorBufferPosition(cursorPosition)
      }
    }));

    // Register text editor events
    this.subscriptions.add(atom.workspace.observeTextEditors((textEditor) => {
      textEditor.onDidSave(async ({ path }) => {
        if (atom.config.get('atom-stylus-supremacy.fixOnSave') && isStylus(textEditor)) {
          // When a stylus file is saved, we will replace the file with a formatted one.
          const formattedText = getFormattedStylusText(textEditor)
          fs.writeFileSync(path, formattedText)
        }
      })
    }))
  },

  deactivate() {
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.atomStylusSupremacyView.destroy();
  },

  serialize() {
    return {
      atomStylusSupremacyViewState: this.atomStylusSupremacyView.serialize()
    };
  }
};
<commit_msg>edited rulesPath for non-stylintrc<commit_after>'use babel';

import { createFormattingOptions, createFormattingOptionsFromStylint, format } from 'stylus-supremacy'

import AtomStylusSupremacyView from './atom-stylus-supremacy-view';
import { CompositeDisposable } from 'atom';
import fs from 'fs'
import path from 'path'

function isStylus (textEditor) {
  const { scopes } = textEditor.getRootScopeDescriptor()
  return /.stylus$/.test(scopes[0])
}

function getStylintOptionsFromFile (textEditor) {
  const [ projectPath, filePath ] = atom.project
                                      .relativizePath(textEditor.getPath())
  const pathArray = (path.sep + filePath)
                      .split(path.sep)
                      .slice(0, -1)
  const rulesPath = pathArray.reduce(result => {
    const currentPath = path.join(projectPath, ...result, '.stylintrc')
    if (fs.existsSync(currentPath)) {
      return [...result, '.stylintrc']
    }
    return result.slice(0, -1)
  }, pathArray).join(path.sep)
  if (!rulesPath) return
  const rules = JSON.parse(
    fs.readFileSync(path.join(projectPath, rulesPath), 'utf8')
  )
  return createFormattingOptionsFromStylint(rules)
}
function getFormattedStylusText (textEditor) {
  const formattingOptions = getStylintOptionsFromFile(textEditor)
  const content = textEditor.getText()
  return format(content, formattingOptions)
}

export default {

  atomStylusSupremacyView: null,
  modalPanel: null,
  subscriptions: null,

  config: {
    fixOnSave: {
      type: 'boolean',
      default: false,
      description: 'Let this package fix your stylus file on save.'
    }
  },

  activate(state) {
    this.atomStylusSupremacyView = new AtomStylusSupremacyView(state.atomStylusSupremacyViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.atomStylusSupremacyView.getElement(),
      visible: true
    });

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'atom-stylus-supremacy:fix-file': async () => {
        const textEditor = atom.workspace.getActiveTextEditor()
        if (!textEditor || textEditor.isModified()) {
          atom.notifications.addError('Stylus supremacy: Please save before fixing this file.')
          return
        }
        if (!isStylus(textEditor)) {
          atom.notifications.addError('Stylus supremacy: This is not a stylus file.')
          return
        }
        const cursorPosition = textEditor.getCursorBufferPosition()
        const formattedText = getFormattedStylusText(textEditor)
        textEditor.setText(formattedText)
        textEditor.setCursorBufferPosition(cursorPosition)
      }
    }));

    // Register text editor events
    this.subscriptions.add(atom.workspace.observeTextEditors((textEditor) => {
      textEditor.onDidSave(async ({ path }) => {
        if (atom.config.get('atom-stylus-supremacy.fixOnSave') && isStylus(textEditor)) {
          // When a stylus file is saved, we will replace the file with a formatted one.
          const formattedText = getFormattedStylusText(textEditor)
          fs.writeFileSync(path, formattedText)
        }
      })
    }))
  },

  deactivate() {
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.atomStylusSupremacyView.destroy();
  },

  serialize() {
    return {
      atomStylusSupremacyViewState: this.atomStylusSupremacyView.serialize()
    };
  }
};
<|endoftext|>


<commit_before>"use strict";
var Config = (function () {
    function Config() {
    }
    // VERSION is filled in by the build script.
    Config.VERSION = '12fc3c7';
    Config.URL_BASE = 'services/rest/';
    Config.URL_CONTENTS = '/list';
    Config.URL_ELEMENT = '/details';
    Config.URL_DELETE = '/delete';
    Config.CEG_NODE_WIDTH = 150;
    Config.CEG_NODE_HEIGHT = 57;
    Config.CEG_NODE_ARC_DIST = 17 + Math.sqrt((Config.CEG_NODE_WIDTH / 2.0) * (Config.CEG_NODE_WIDTH / 2.0) + (Config.CEG_NODE_HEIGHT / 2.0) * (Config.CEG_NODE_HEIGHT / 2.0));
    Config.CEG_MODEL_BASE_ID = 'model';
    Config.CEG_NEW_MODEL_NAME = 'New Model';
    Config.CEG_NEW_MODEL_DESCRIPTION = '';
    Config.CEG_NODE_BASE_ID = 'node';
    Config.CEG_NEW_NODE_NAME = 'New Node';
    Config.CEG_NEW_NODE_DESCRIPTION = '';
    Config.CEG_NEW_NODE_X = 100;
    Config.CEG_NEW_NODE_Y = 100;
    Config.CEG_NODE_NEW_TYPE = 'AND';
    Config.CEG_NODE_NEW_VARIABLE = 'variable';
    Config.CEG_NODE_NEW_OPERATOR = '=';
    Config.CEG_NODE_NEW_VALUE = '0';
    Config.CEG_CONNECTION_BASE_ID = 'conn';
    Config.CEG_NEW_CONNECTION_NAME = 'New Connection';
    Config.CEG_NEW_CONNECTION_DESCRIPTION = '';
    Config.CEG_EDITOR_HEIGHT = (isNaN(window.innerHeight) ? window['clientHeight'] : window.innerHeight) * 0.75;
    Config.CEG_EDITOR_WIDTH = 1000;
    Config.CEG_EDITOR_DESCRIPTION_ROWS = 9;
    Config.TESTSPEC_BASE_ID = 'testspec';
    Config.TESTSPEC_NAME = 'New Test Specification';
    Config.TESTSPEC_DESCRIPTION = '';
    // The separator to separate strings from id-numbers. Must not be included in the allowed chars.
    Config.ID_SEP = '-';
    Config.ID_ALLOWED_CHARS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', '_'];
    Config.ID_FORBIDDEN_REPLACEMENT = '_';
    Config.ID_MIN = 1;
    return Config;
}());
exports.Config = Config;
//# sourceMappingURL=config.js.map
<commit_msg>Updating version number<commit_after>"use strict";
var Config = (function () {
    function Config() {
    }
    // VERSION is filled in by the build script.
    Config.VERSION = 'cda6c95';
    Config.URL_BASE = 'services/rest/';
    Config.URL_CONTENTS = '/list';
    Config.URL_ELEMENT = '/details';
    Config.URL_DELETE = '/delete';
    Config.CEG_NODE_WIDTH = 150;
    Config.CEG_NODE_HEIGHT = 57;
    Config.CEG_NODE_ARC_DIST = 17 + Math.sqrt((Config.CEG_NODE_WIDTH / 2.0) * (Config.CEG_NODE_WIDTH / 2.0) + (Config.CEG_NODE_HEIGHT / 2.0) * (Config.CEG_NODE_HEIGHT / 2.0));
    Config.CEG_MODEL_BASE_ID = 'model';
    Config.CEG_NEW_MODEL_NAME = 'New Model';
    Config.CEG_NEW_MODEL_DESCRIPTION = '';
    Config.CEG_NODE_BASE_ID = 'node';
    Config.CEG_NEW_NODE_NAME = 'New Node';
    Config.CEG_NEW_NODE_DESCRIPTION = '';
    Config.CEG_NEW_NODE_X = 100;
    Config.CEG_NEW_NODE_Y = 100;
    Config.CEG_NODE_NEW_TYPE = 'AND';
    Config.CEG_NODE_NEW_VARIABLE = 'variable';
    Config.CEG_NODE_NEW_OPERATOR = '=';
    Config.CEG_NODE_NEW_VALUE = '0';
    Config.CEG_CONNECTION_BASE_ID = 'conn';
    Config.CEG_NEW_CONNECTION_NAME = 'New Connection';
    Config.CEG_NEW_CONNECTION_DESCRIPTION = '';
    Config.CEG_EDITOR_HEIGHT = (isNaN(window.innerHeight) ? window['clientHeight'] : window.innerHeight) * 0.75;
    Config.CEG_EDITOR_WIDTH = 1000;
    Config.CEG_EDITOR_DESCRIPTION_ROWS = 9;
    Config.TESTSPEC_BASE_ID = 'testspec';
    Config.TESTSPEC_NAME = 'New Test Specification';
    Config.TESTSPEC_DESCRIPTION = '';
    // The separator to separate strings from id-numbers. Must not be included in the allowed chars.
    Config.ID_SEP = '-';
    Config.ID_ALLOWED_CHARS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', '_'];
    Config.ID_FORBIDDEN_REPLACEMENT = '_';
    Config.ID_MIN = 1;
    return Config;
}());
exports.Config = Config;
//# sourceMappingURL=config.js.map
<|endoftext|>


<commit_before>import React, { Component } from 'react'

import { propTypes, defaultProps } from './props'
import { isEqual } from './utils'

const SEEK_ON_PLAY_EXPIRY = 5000

export default class Player extends Component {
  static displayName = 'Player'
  static propTypes = propTypes
  static defaultProps = defaultProps
  mounted = false
  isReady = false
  isPlaying = false // Track playing state internally to prevent bugs
  isLoading = true // Use isLoading to prevent onPause when switching URL
  loadOnReady = null
  startOnPlay = true
  seekOnPlay = null
  onDurationCalled = false
  componentDidMount () {
    this.mounted = true
    this.player.load(this.props.url)
    this.progress()
  }
  componentWillUnmount () {
    clearTimeout(this.progressTimeout)
    clearTimeout(this.durationCheckTimeout)
    if (this.isReady) {
      this.player.stop()
    }
    if (this.player.disablePIP) {
      this.player.disablePIP()
    }
    this.mounted = false
  }
  componentWillReceiveProps (nextProps) {
    // Invoke player methods based on incoming props
    const { url, playing, volume, muted, playbackRate, pip, loop } = this.props
    if (!isEqual(url, nextProps.url)) {
      if (this.isLoading) {
        console.warn(`ReactPlayer: the attempt to load ${nextProps.url} is being deferred until the player has loaded`)
        this.loadOnReady = nextProps.url
        return
      }
      this.isLoading = true
      this.startOnPlay = true
      this.onDurationCalled = false
      this.player.load(nextProps.url, this.isReady)
    }
    if (!playing && nextProps.playing && !this.isPlaying) {
      this.player.play()
    }
    if (playing && !nextProps.playing && this.isPlaying) {
      this.player.pause()
    }
    if (!pip && nextProps.pip && this.player.enablePIP) {
      this.player.enablePIP()
    } else if (pip && !nextProps.pip && this.player.disablePIP) {
      this.player.disablePIP()
    }
    if (volume !== nextProps.volume && nextProps.volume !== null) {
      this.player.setVolume(nextProps.volume)
    }
    if (muted !== nextProps.muted) {
      if (nextProps.muted) {
        this.player.mute()
      } else {
        this.player.unmute()
        if (nextProps.volume !== null) {
          // Set volume next tick to fix a bug with DailyMotion
          setTimeout(() => this.player.setVolume(nextProps.volume))
        }
      }
    }
    if (playbackRate !== nextProps.playbackRate && this.player.setPlaybackRate) {
      this.player.setPlaybackRate(nextProps.playbackRate)
    }
    if (loop !== nextProps.loop && this.player.setLoop) {
      this.player.setLoop(nextProps.loop)
    }
  }
  getDuration () {
    if (!this.isReady) return null
    return this.player.getDuration()
  }
  getCurrentTime () {
    if (!this.isReady) return null
    return this.player.getCurrentTime()
  }
  getSecondsLoaded () {
    if (!this.isReady) return null
    return this.player.getSecondsLoaded()
  }
  getInternalPlayer = (key) => {
    if (!this.player) return null
    return this.player[key]
  }
  progress = () => {
    if (this.props.url && this.player && this.isReady) {
      const playedSeconds = this.getCurrentTime() || 0
      const loadedSeconds = this.getSecondsLoaded()
      const duration = this.getDuration()
      if (duration) {
        const progress = {
          playedSeconds,
          played: playedSeconds / duration
        }
        if (loadedSeconds !== null) {
          progress.loadedSeconds = loadedSeconds
          progress.loaded = loadedSeconds / duration
        }
        // Only call onProgress if values have changed
        if (progress.played !== this.prevPlayed || progress.loaded !== this.prevLoaded) {
          this.props.onProgress(progress)
        }
        this.prevPlayed = progress.played
        this.prevLoaded = progress.loaded
      }
    }
    this.progressTimeout = setTimeout(this.progress, this.props.progressFrequency || this.props.progressInterval)
  }
  seekTo (amount, type) {
    // When seeking before player is ready, store value and seek later
    if (!this.isReady && amount !== 0) {
      this.seekOnPlay = amount
      setTimeout(() => { this.seekOnPlay = null }, SEEK_ON_PLAY_EXPIRY)
      return
    }
    const isFraction = !type ? (amount > 0 && amount < 1) : type === 'fraction'
    if (isFraction) {
      // Convert fraction to seconds based on duration
      const duration = this.player.getDuration()
      if (!duration) {
        console.warn('ReactPlayer: could not seek using fraction – duration not yet available')
        return
      }
      this.player.seekTo(duration * amount)
      return
    }
    this.player.seekTo(amount)
  }
  onReady = () => {
    if (!this.mounted) return
    this.isReady = true
    this.isLoading = false
    const { onReady, playing, volume, muted } = this.props
    onReady()
    if (!muted && volume !== null) {
      this.player.setVolume(volume)
    }
    if (this.loadOnReady) {
      this.player.load(this.loadOnReady, true)
      this.loadOnReady = null
    } else if (playing) {
      this.player.play()
    }
    this.onDurationCheck()
  }
  onPlay = () => {
    this.isPlaying = true
    this.isLoading = false
    const { onStart, onPlay, playbackRate } = this.props
    if (this.startOnPlay) {
      if (this.player.setPlaybackRate) {
        this.player.setPlaybackRate(playbackRate)
      }
      onStart()
      this.startOnPlay = false
    }
    onPlay()
    if (this.seekOnPlay) {
      this.seekTo(this.seekOnPlay)
      this.seekOnPlay = null
    }
    this.onDurationCheck()
  }
  onPause = (e) => {
    this.isPlaying = false
    if (!this.isLoading) {
      this.props.onPause(e)
    }
  }
  onEnded = () => {
    const { activePlayer, loop, onEnded } = this.props
    if (activePlayer.loopOnEnded && loop) {
      this.seekTo(0)
    }
    if (!loop) {
      this.isPlaying = false
      onEnded()
    }
  }
  onError = (...args) => {
    this.isLoading = false
    this.props.onError(...args)
  }
  onDurationCheck = () => {
    clearTimeout(this.durationCheckTimeout)
    const duration = this.getDuration()
    if (duration) {
      if (!this.onDurationCalled) {
        this.props.onDuration(duration)
        this.onDurationCalled = true
      }
    } else {
      this.durationCheckTimeout = setTimeout(this.onDurationCheck, 100)
    }
  }
  onLoaded = () => {
    // Sometimes we know loading has stopped but onReady/onPlay are never called
    // so this provides a way for players to avoid getting stuck
    this.isLoading = false
  }
  ref = player => {
    if (player) {
      this.player = player
    }
  }
  render () {
    const Player = this.props.activePlayer
    if (!Player) {
      return null
    }
    return (
      <Player
        {...this.props}
        ref={this.ref}
        onReady={this.onReady}
        onPlay={this.onPlay}
        onPause={this.onPause}
        onEnded={this.onEnded}
        onLoaded={this.onLoaded}
        onError={this.onError}
      />
    )
  }
}
<commit_msg>Fix onProgress for infinite duration streams<commit_after>import React, { Component } from 'react'

import { propTypes, defaultProps } from './props'
import { isEqual } from './utils'

const SEEK_ON_PLAY_EXPIRY = 5000

export default class Player extends Component {
  static displayName = 'Player'
  static propTypes = propTypes
  static defaultProps = defaultProps
  mounted = false
  isReady = false
  isPlaying = false // Track playing state internally to prevent bugs
  isLoading = true // Use isLoading to prevent onPause when switching URL
  loadOnReady = null
  startOnPlay = true
  seekOnPlay = null
  onDurationCalled = false
  componentDidMount () {
    this.mounted = true
    this.player.load(this.props.url)
    this.progress()
  }
  componentWillUnmount () {
    clearTimeout(this.progressTimeout)
    clearTimeout(this.durationCheckTimeout)
    if (this.isReady) {
      this.player.stop()
    }
    if (this.player.disablePIP) {
      this.player.disablePIP()
    }
    this.mounted = false
  }
  componentWillReceiveProps (nextProps) {
    // Invoke player methods based on incoming props
    const { url, playing, volume, muted, playbackRate, pip, loop } = this.props
    if (!isEqual(url, nextProps.url)) {
      if (this.isLoading) {
        console.warn(`ReactPlayer: the attempt to load ${nextProps.url} is being deferred until the player has loaded`)
        this.loadOnReady = nextProps.url
        return
      }
      this.isLoading = true
      this.startOnPlay = true
      this.onDurationCalled = false
      this.player.load(nextProps.url, this.isReady)
    }
    if (!playing && nextProps.playing && !this.isPlaying) {
      this.player.play()
    }
    if (playing && !nextProps.playing && this.isPlaying) {
      this.player.pause()
    }
    if (!pip && nextProps.pip && this.player.enablePIP) {
      this.player.enablePIP()
    } else if (pip && !nextProps.pip && this.player.disablePIP) {
      this.player.disablePIP()
    }
    if (volume !== nextProps.volume && nextProps.volume !== null) {
      this.player.setVolume(nextProps.volume)
    }
    if (muted !== nextProps.muted) {
      if (nextProps.muted) {
        this.player.mute()
      } else {
        this.player.unmute()
        if (nextProps.volume !== null) {
          // Set volume next tick to fix a bug with DailyMotion
          setTimeout(() => this.player.setVolume(nextProps.volume))
        }
      }
    }
    if (playbackRate !== nextProps.playbackRate && this.player.setPlaybackRate) {
      this.player.setPlaybackRate(nextProps.playbackRate)
    }
    if (loop !== nextProps.loop && this.player.setLoop) {
      this.player.setLoop(nextProps.loop)
    }
  }
  getDuration () {
    if (!this.isReady) return null
    return this.player.getDuration()
  }
  getCurrentTime () {
    if (!this.isReady) return null
    return this.player.getCurrentTime()
  }
  getSecondsLoaded () {
    if (!this.isReady) return null
    return this.player.getSecondsLoaded()
  }
  getInternalPlayer = (key) => {
    if (!this.player) return null
    return this.player[key]
  }
  progress = () => {
    if (this.props.url && this.player && this.isReady) {
      const playedSeconds = this.getCurrentTime() || 0
      const loadedSeconds = this.getSecondsLoaded()
      const duration = this.getDuration()
      if (duration) {
        const progress = {
          playedSeconds,
          played: playedSeconds / duration
        }
        if (loadedSeconds !== null) {
          progress.loadedSeconds = loadedSeconds
          progress.loaded = loadedSeconds / duration
        }
        // Only call onProgress if values have changed
        if (progress.playedSeconds !== this.prevPlayed || progress.loadedSeconds !== this.prevLoaded) {
          this.props.onProgress(progress)
        }
        this.prevPlayed = progress.playedSeconds
        this.prevLoaded = progress.loadedSeconds
      }
    }
    this.progressTimeout = setTimeout(this.progress, this.props.progressFrequency || this.props.progressInterval)
  }
  seekTo (amount, type) {
    // When seeking before player is ready, store value and seek later
    if (!this.isReady && amount !== 0) {
      this.seekOnPlay = amount
      setTimeout(() => { this.seekOnPlay = null }, SEEK_ON_PLAY_EXPIRY)
      return
    }
    const isFraction = !type ? (amount > 0 && amount < 1) : type === 'fraction'
    if (isFraction) {
      // Convert fraction to seconds based on duration
      const duration = this.player.getDuration()
      if (!duration) {
        console.warn('ReactPlayer: could not seek using fraction – duration not yet available')
        return
      }
      this.player.seekTo(duration * amount)
      return
    }
    this.player.seekTo(amount)
  }
  onReady = () => {
    if (!this.mounted) return
    this.isReady = true
    this.isLoading = false
    const { onReady, playing, volume, muted } = this.props
    onReady()
    if (!muted && volume !== null) {
      this.player.setVolume(volume)
    }
    if (this.loadOnReady) {
      this.player.load(this.loadOnReady, true)
      this.loadOnReady = null
    } else if (playing) {
      this.player.play()
    }
    this.onDurationCheck()
  }
  onPlay = () => {
    this.isPlaying = true
    this.isLoading = false
    const { onStart, onPlay, playbackRate } = this.props
    if (this.startOnPlay) {
      if (this.player.setPlaybackRate) {
        this.player.setPlaybackRate(playbackRate)
      }
      onStart()
      this.startOnPlay = false
    }
    onPlay()
    if (this.seekOnPlay) {
      this.seekTo(this.seekOnPlay)
      this.seekOnPlay = null
    }
    this.onDurationCheck()
  }
  onPause = (e) => {
    this.isPlaying = false
    if (!this.isLoading) {
      this.props.onPause(e)
    }
  }
  onEnded = () => {
    const { activePlayer, loop, onEnded } = this.props
    if (activePlayer.loopOnEnded && loop) {
      this.seekTo(0)
    }
    if (!loop) {
      this.isPlaying = false
      onEnded()
    }
  }
  onError = (...args) => {
    this.isLoading = false
    this.props.onError(...args)
  }
  onDurationCheck = () => {
    clearTimeout(this.durationCheckTimeout)
    const duration = this.getDuration()
    if (duration) {
      if (!this.onDurationCalled) {
        this.props.onDuration(duration)
        this.onDurationCalled = true
      }
    } else {
      this.durationCheckTimeout = setTimeout(this.onDurationCheck, 100)
    }
  }
  onLoaded = () => {
    // Sometimes we know loading has stopped but onReady/onPlay are never called
    // so this provides a way for players to avoid getting stuck
    this.isLoading = false
  }
  ref = player => {
    if (player) {
      this.player = player
    }
  }
  render () {
    const Player = this.props.activePlayer
    if (!Player) {
      return null
    }
    return (
      <Player
        {...this.props}
        ref={this.ref}
        onReady={this.onReady}
        onPlay={this.onPlay}
        onPause={this.onPause}
        onEnded={this.onEnded}
        onLoaded={this.onLoaded}
        onError={this.onError}
      />
    )
  }
}
<|endoftext|>


<commit_before>if (typeof audioplayer === "undefined") {
    throw "audioplayer is required";
} else {
    function updateSongs() {
        var songs = document.querySelectorAll(".hidden[data-type='audio']");
        for (var i = 0; i < songs.length; i++) {
            updateSong(songs[i]);
        }
    }

    function updateSong(song) {
        song.className = song.className.replace("hidden", "");
        song.className = song.className.replace("  ", " ");

        song.addEventListener("click", play, false);
        song.addEventListener("contextmenu", contextMenu, false);
    }

    function play() {
        var song = new Song(this, this.getAttribute("data-path"), {
            title: this.querySelector(".title"),
            artist: this.querySelector(".artist"),
            album: this.querySelector(".album"),
            duration: this.querySelector(".duration"),
            cover: this.getAttribute("data-cover-path"),
            moddate: this.getAttribute("data-moddate")
        });
        audioplayer.newSong(song);
    }

    function contextMenu() {
        swal(this.querySelector(".title").innerHTML, this.querySelector(".artist").innerHTML);
    }

    function clickPercent(element, e) {
        return (e.pageX - element.getBoundingClientRect().left) / element.offsetWidth;
    }

    function movePlayHead(element, e) {
        var timelintWidth = parseInt(element.offsetWidth);
        var newLeftMargin = e.pageX - element.getBoundingClientRect().left;
    }

    window.addEventListener("variablesLoaded", function() {
        audioplayer.elements.timeline.timeline.addEventListener("click", function() {
            if (audioplayer.audio.object.src) {
                movePlayHead(audioplayer.elements.timeline.timeline, event);
                audioplayer.audio.object.currentTime = audioplayer.audio.object.duration * clickPercent(audioplayer.elements.timeline.timeline, event);
            }
        }, false);

        audioplayer.elements.buttons.play.addEventListener("click", function() {
            audioplayer.play();
        }, false);

        audioplayer.elements.buttons.pause.addEventListener("click", function() {
            audioplayer.pause();
        }, false);

        audioplayer.elements.buttons.stop.addEventListener("click", function() {
            audioplayer.stop();
        }, false);

        audioplayer.elements.buttons.previousSong.addEventListener("click", function() {
            audioplayer.previousSong();
        }, false);

        audioplayer.elements.buttons.nextSong.addEventListener("click", function() {
            audioplayer.nextSong();
        }, false);

        for (var i=0; i < audioplayer.elements.buttons.repeat.length; i++) {
            audioplayer.elements.buttons.repeat[i].addEventListener("click", function() {
                audioplayer.repeat(this);
            }, false);
        }

        for (var i=0; i < audioplayer.elements.buttons.random.length; i++) {
            audioplayer.elements.buttons.random[i].addEventListener("click", function() {
                audioplayer.random();
            });
        }

        for (var i=0; i < audioplayer.elements.buttons.volumeIndicator.length; i++) {
            audioplayer.elements.buttons.volumeIndicator[i].addEventListener("click", function() {
                audioplayer.volumeMute();
            }, false);
        }

        var hotKeys;
        require("electron").ipcRenderer.on("keyPress", (event, action) => {

            switch (action) {
                case "volumeUp":
                    audioplayer.volumeUp();
                    break;

                case "volumeDown":
                    audioplayer.volumeDown();
                    break;

                case "toggleMute":
                    audioplayer.volumeMute();
                    break

                case "previousSong":
                    audioplayer.previousSong();
                    break;

                case "nextSong":
                    audioplayer.nextSong();
                    break;

                case "playPause":
                    if (audioplayer.audio.object.paused) {
                        audioplayer.play();
                    } else {
                        audioplayer.pause();
                    }
                    break;

                case "stop":
                    audioplayer.stop();
                    break;

                default:
                    console.log("Hotkey: " + action);
                    break;
            }

        });

        audioplayer.log("Controls loaded");
    });

}
<commit_msg>Start doing secondary click menu<commit_after>if (typeof audioplayer === "undefined") {
    throw "audioplayer is required";
} else {
    function updateSongs() {
        var songs = document.querySelectorAll(".hidden[data-type='audio']");
        for (var i = 0; i < songs.length; i++) {
            updateSong(songs[i]);
        }
    }

    function updateSong(song) {
        song.className = song.className.replace("hidden", "");
        song.className = song.className.replace("  ", " ");

        song.addEventListener("click", play, false);
        song.addEventListener("contextmenu", showContextMenu, false);
    }

    document.querySelector("*:not(#contextMenu)").addEventListener("click", hideContextMenu, false);
    document.querySelectorAll("#contextMenu li").forEach((element) => {
        element.addEventListener("click", () => {

            switch (element.getAttribute("data-target")) {
                case "toggle-theme":

                    var styles = document.head.querySelectorAll("[href$='.css']");

                    if (document.body.getAttribute("data-theme") == "dark") {
                        document.body.setAttribute("data-theme", "light");

                        styles.forEach((element) => {
                            if (element.getAttribute("href").indexOf("/dark/") > 0) {
                                element.setAttribute("href", element.getAttribute("href").replace("/dark/", "/light/"));
                            }
                        });

                    } else if(document.body.getAttribute("data-theme") == "light") {
                        document.body.setAttribute("data-theme", "dark");

                        styles.forEach((element) => {
                            if (element.getAttribute("href").indexOf("/light/") > 0) {
                                element.setAttribute("href", element.getAttribute("href").replace("/light/", "/dark/"));
                            }
                        });

                    }
                    break;

                default:
                    swal({
                        title: "WIP, selected:",
                        text: element.getAttribute("data-target"),
                        html: true,
                        timer: 750
                    });
                }
        }, false);
    });

    function play() {
        var song = new Song(this, this.getAttribute("data-path"), {
            title: this.querySelector(".title"),
            artist: this.querySelector(".artist"),
            album: this.querySelector(".album"),
            duration: this.querySelector(".duration"),
            cover: this.getAttribute("data-cover-path"),
            moddate: this.getAttribute("data-moddate")
        });
        audioplayer.newSong(song);
    }

    function hideContextMenu() {
        document.getElementById("contextMenu").style.display = "none";
    }

    function showContextMenu(e) {
        var posX = e.clientX;
        var posY = e.clientY;

        document.getElementById("contextMenu").style.display = "block";
        document.getElementById("contextMenu").style.left = posX + "px";
        document.getElementById("contextMenu").style.top = posY + "px";

        e.preventDefault();
    }

    function clickPercent(element, e) {
        return (e.pageX - element.getBoundingClientRect().left) / element.offsetWidth;
    }

    function movePlayHead(element, e) {
        var timelintWidth = parseInt(element.offsetWidth);
        var newLeftMargin = e.pageX - element.getBoundingClientRect().left;
    }

    window.addEventListener("variablesLoaded", function() {
        audioplayer.elements.timeline.timeline.addEventListener("click", function() {
            if (audioplayer.audio.object.src) {
                movePlayHead(audioplayer.elements.timeline.timeline, event);
                audioplayer.audio.object.currentTime = audioplayer.audio.object.duration * clickPercent(audioplayer.elements.timeline.timeline, event);
            }
        }, false);

        audioplayer.elements.buttons.play.addEventListener("click", function() {
            audioplayer.play();
        }, false);

        audioplayer.elements.buttons.pause.addEventListener("click", function() {
            audioplayer.pause();
        }, false);

        audioplayer.elements.buttons.stop.addEventListener("click", function() {
            audioplayer.stop();
        }, false);

        audioplayer.elements.buttons.previousSong.addEventListener("click", function() {
            audioplayer.previousSong();
        }, false);

        audioplayer.elements.buttons.nextSong.addEventListener("click", function() {
            audioplayer.nextSong();
        }, false);

        for (var i=0; i < audioplayer.elements.buttons.repeat.length; i++) {
            audioplayer.elements.buttons.repeat[i].addEventListener("click", function() {
                audioplayer.repeat(this);
            }, false);
        }

        for (var i=0; i < audioplayer.elements.buttons.random.length; i++) {
            audioplayer.elements.buttons.random[i].addEventListener("click", function() {
                audioplayer.random();
            });
        }

        for (var i=0; i < audioplayer.elements.buttons.volumeIndicator.length; i++) {
            audioplayer.elements.buttons.volumeIndicator[i].addEventListener("click", function() {
                audioplayer.volumeMute();
            }, false);
        }

        var hotKeys;
        require("electron").ipcRenderer.on("keyPress", (event, action) => {

            switch (action) {
                case "volumeUp":
                    audioplayer.volumeUp();
                    break;

                case "volumeDown":
                    audioplayer.volumeDown();
                    break;

                case "toggleMute":
                    audioplayer.volumeMute();
                    break

                case "previousSong":
                    audioplayer.previousSong();
                    break;

                case "nextSong":
                    audioplayer.nextSong();
                    break;

                case "playPause":
                    if (audioplayer.audio.object.paused) {
                        audioplayer.play();
                    } else {
                        audioplayer.pause();
                    }
                    break;

                case "stop":
                    audioplayer.stop();
                    break;

                default:
                    console.log("Hotkey: " + action);
                    break;
            }

        });

        audioplayer.log("Controls loaded");
    });

}
<|endoftext|>