<commit_before>import { setUp, tearDown } from '../../../../test/helpers/fixture.js';
import { capture3x } from '../../../../test/helpers/capture.js';

const SPACING = 6;

const black = {
    r: 0,
    g: 0,
    b: 0
};

const shadow = (alphas) => {
    return alphas.map(alpha => ({...black, a: alpha}));
};

// shadows
const noShadow = new Array(18).fill({ a: 0 });
const sideShadow2 = shadow([0, 0, 0, 0, [0, 4], [0, 4], [0, 4], [0, 4], [0, 4], [0, 4], [4, 8], [4, 8], [4, 8], [8, 12], [12, 16], [16, 20], [20, 28], [24, 32]]);
const sideShadow4 = shadow([[0, 4], [0, 4], [0, 4], [0, 8], [0, 8], [4, 8], [4, 12], [4, 12], [4, 12], [8, 16], [8, 20], [12, 20], [12, 24], [16, 28], [20, 32], [24, 36], [28, 40], [32, 44]]);
const sideShadow8 = shadow([[8, 16], [8, 16], [8, 16], [12, 20], [12, 20], [12, 20], [16, 24], [16, 24], [20, 24], [20, 28], [20, 28], [24, 32], [24, 32], [24, 36], [28, 36], [28, 40], [32, 44], [32, 48]]);

describe('Contained Button', () => {

    [
        {
            label: 'normal',
            states: {},
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: 33, g: 150, b: 243, a: 255 },
            shadow: { side: sideShadow2 }
        },
        {
            label: 'hover',
            states: {
                '#xmas.matter-button-contained': [ 'hover' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: 50, g: 158, b: [243, 244], a: 255 },
            shadow: { side: sideShadow4 }
        },
        {
            label: 'focus',
            states: {
                '#xmas.matter-button-contained': [ 'focus' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: [85, 86], g: 175, b: [245, 246], a: 255 },
            shadow: { side: sideShadow4 }
        },
        {
            label: 'active',
            states: {
                '#xmas.matter-button-contained': [ 'active' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: 33, g: 150, b: 243, a: 255 },
            shadow: { side: sideShadow8 }
        },
        {
            label: 'hover & focus',
            states: {
                '#xmas.matter-button-contained': [ 'hover', 'focus' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: [99, 104], g: [181, 184], b: [246, 247], a: 255 },
            shadow: { side: sideShadow4 }
        },
        {
            label: 'hover & active',
            states: {
                '#xmas.matter-button-contained': [ 'hover', 'active' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: 50, g: 158, b: [243, 244], a: 255 },
            shadow: { side: sideShadow8 }
        },
        {
            label: 'focus & active',
            states: {
                '#xmas.matter-button-contained': [ 'focus', 'active' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: [85, 86], g: 175, b: [245, 246], a: 255 },
            shadow: { side: sideShadow8 }
        },
        {
            label: 'hover, focus & active',
            states: {
                '#xmas.matter-button-contained': [ 'hover', 'focus', 'active' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: [99, 104], g: [181, 184], b: [246, 247], a: 255 },
            shadow: { side: sideShadow8 }
        },
        {
            label: 'disabled',
            states: {
                '#xmas.matter-button-contained': [ 'disabled' ]
            },
            textColor: { r: 0, g: 0, b: 0, a: 116 },
            bodyColor: { r: 0, g: 0, b: 0, a: [30, 31] },
            shadow: { side: noShadow }
        },
        {
            label: 'customized',
            states: {
                '#xmas.matter-button-contained': {
                    style: '--matter-primary-rgb: 255, 0, 0;--matter-onprimary-rgb: 0, 0, 0;width: 120px'
                }
            },
            textColor: { r: 0, g: 0, b: 0, a: 255 },
            bodyColor: { r: 255, g: 0, b: 0, a: 255 },
            shadow: { side: sideShadow2 }
        }
    ].forEach((suite) => {

        describe(`in ${suite.label} state`, () => {

            let style;
            let button;
            let width;
            let height;
            let context;

            beforeAll(async () => {
                style = setUp('src/components/buttons/contained/button-contained', suite.states);

                button = document.querySelector('#xmas');
                const rect = button.getBoundingClientRect();
                width = rect.width;
                height = rect.height;
                context = await capture3x(button, style, SPACING);
            });

            afterAll(() => {
                tearDown();
            });

            it(`should have dominant ${JSON.stringify(suite.bodyColor).replace(/"/g, '')} color`, () => {
                const component = context.getImageData3x(0, 0, width, height);

                expect(component).toResembleColor(suite.bodyColor);
            });

            it('should have uppercase caption text', () => {
                const caption = context.getImageData3x(4, 4, width - 8, height - 8);

                expect(button.innerText).toBe('XMAS TREE');
                expect(caption).toResembleText('XMAS TREE', suite.textColor, suite.bodyColor);
            });

            it(`should have 4px round corners`, () => {
                // shadow
                const sh = {a: [0, 98]};

                // intermediate
                const im = {};

                // body
                const bd = suite.bodyColor;

                const corner = [
                    [ sh, sh, sh, sh, sh, sh, sh, im, im, im, im, im],
                    [ sh, sh, sh, sh, sh, im, im, im, bd, bd, bd, bd],
                    [ sh, sh, sh, sh, im, im, bd, bd, bd, bd, bd, bd],
                    [ sh, sh, sh, im, im, bd, bd, bd, bd, bd, bd, bd],
                    [ sh, sh, im, im, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ sh, im, im, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ sh, im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd]
                ];

                const topLeft = context.getImageData3x(0, 0, 4, 4);
                const topRight = context.getImageData3x(width - 4, 0, 4, 4);
                const bottomRight = context.getImageData3x(width - 4, height - 4, 4, 4);
                const bottomLeft = context.getImageData3x(0, height - 4, 4, 4);

                expect(topLeft).toResembleShape(corner, 0);
                expect(topRight).toResembleShape(corner, 90);
                expect(bottomRight).toResembleShape(corner, 180);
                expect(bottomLeft).toResembleShape(corner, 270);
            });

            it('should have no outline', () => {
                // body
                const bd = suite.bodyColor;

                const edge = [ bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd ];

                const top = context.getImageData3x(4, 0, width - 8, 4);
                const right = context.getImageData3x(width - 4, 4, 4, height - 8);
                const bottom = context.getImageData3x(4, height - 4, width - 8, 4);
                const left = context.getImageData3x(0, 4, 4, height - 8);

                expect(top).toResembleOblongShape(edge, 0);
                expect(right).toResembleOblongShape(edge, 90);
                expect(bottom).toResembleOblongShape(edge, 180);
                expect(left).toResembleOblongShape(edge, 270);
            });

            it('should have shadow', () => {
                const top = context.getImageData3x(SPACING, -SPACING, width - 2 * SPACING, SPACING);
                const right = context.getImageData3x(width, 12, SPACING, height - 24);
                const bottom = context.getImageData3x(0, height, width + SPACING, SPACING);
                const left = context.getImageData3x(-SPACING, 12, SPACING, height - 24);

                // expect(top).toResembleOblongShape(suite.shadow.top, 0);
                expect(right).toResembleOblongShape(suite.shadow.side, 90);
                // expect(bottom).toResembleOblongShape(suite.shadow.bottom, 180);
                expect(left).toResembleOblongShape(suite.shadow.side, 270);
            });

        });

    });

    describe('in normal state', () => {

        beforeAll(() => {
            setUp('src/components/buttons/contained/button-contained');
        });

        afterAll(() => {
            tearDown();
        });

        it('should have a height of 36px', () => {
            const { height } = document.querySelector('#normal').getBoundingClientRect();

            expect(height).toBe(36);
        });

        it('should have a minimum width of 64px', () => {
            const { width } = document.querySelector('#min').getBoundingClientRect();

            expect(width).toBe(64);
        });

        it('should have variable-width', () => {
            const { width } = document.querySelector('#sized').getBoundingClientRect();

            expect(width).toBe(120);
        });

    });

});
<commit_msg>Fix and Improve testing shadows<commit_after>import { setUp, tearDown } from '../../../../test/helpers/fixture.js';
import { capture3x } from '../../../../test/helpers/capture.js';
import { isBrowserNot } from '../../../../test/helpers/browser.js';

const SPACING = 6;

const black = {
    r: 0,
    g: 0,
    b: 0
};

const shadow = (alphas) => {
    return alphas.map(alpha => ({...black, a: alpha}));
};

// shadows
const noShadow = new Array(18).fill({ a: 0 });
const topShadow2 = shadow([[0, 0], [0, 0], [0, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [1, 2], [1, 2], [2, 3], [3, 4], [3, 4], [4, 5], [5, 6], [7, 8], [8, 10], [9, 11]]);
const topShadow4 = shadow([[2, 3], [2, 3], [2, 4], [2, 4], [2, 4], [3, 5], [3, 5], [4, 6], [5, 7], [5, 7], [6, 8], [7, 9], [7, 10], [8, 12], [9, 13], [9, 14], [10, 15], [13, 18]]);
const topShadow8 = shadow([[4, 5], [4, 6], [4, 6], [5, 7], [5, 8], [5, 8], [6, 9], [6, 9], [7, 10], [7, 10], [8, 11], [8, 11], [9, 13], [9, 14], [9, 14], [10, 15], [11, 16], [12, 17]]);
const sideShadow2 = shadow([[0, 1], [0, 1], [0, 1], [0, 1], [0, 4], [0, 4], [0, 4], [0, 4], [0, 4], [0, 4], [4, 8], [4, 8], [6, 10], [8, 12], [12, 16], [16, 21], [20, 28], [24, 32]]);
const sideShadow4 = shadow([[0, 5], [0, 5], [0, 6], [0, 8], [0, 8], [4, 9], [4, 12], [4, 12], [4, 14], [8, 16], [8, 20], [12, 21], [12, 25], [16, 28], [20, 32], [24, 36], [28, 41], [32, 46]]);
const sideShadow8 = shadow([[8, 16], [8, 17], [8, 18], [12, 20], [12, 21], [12, 22], [16, 24], [16, 24], [20, 26], [20, 28], [20, 30], [24, 32], [24, 32], [24, 36], [28, 36], [28, 40], [32, 44], [32, 48]]);
const bottomShadow2 = shadow([[0, 1], [0, 1], [1, 2], [1, 2], [2, 4], [3, 5], [4, 6], [6, 8], [9, 11], [14, 17], [18, 21], [23, 26], [31, 34], [42, 45], [54, 57], [68, 73], [80, 86], [87, 93]]);
const bottomShadow4 = shadow([[11, 14], [12, 17], [15, 20], [17, 22], [20, 26], [24, 30], [26, 32], [30, 36], [33, 39], [38, 44], [42, 48], [46, 52], [51, 57], [55, 63], [60, 66], [63, 70], [67, 74], [71, 78]]);
const bottomShadow8 = shadow([[35, 43], [36, 46], [37, 47], [40, 50], [42, 52], [45, 55], [47, 57], [51, 61], [52, 63], [56, 67], [58, 69], [62, 73], [63, 75], [65, 77], [68, 80], [70, 83], [73, 85], [76, 88]]);

describe('Contained Button', () => {

    [
        {
            label: 'normal',
            states: {},
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: 33, g: 150, b: 243, a: 255 },
            shadow: {
                top: topShadow2,
                side: sideShadow2,
                bottom: bottomShadow2
            }
        },
        {
            label: 'hover',
            states: {
                '#xmas.matter-button-contained': [ 'hover' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: 50, g: 158, b: [243, 244], a: 255 },
            shadow: {
                top: topShadow4,
                side: sideShadow4,
                bottom: bottomShadow4
            }
        },
        {
            label: 'focus',
            states: {
                '#xmas.matter-button-contained': [ 'focus' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: [85, 86], g: 175, b: [245, 246], a: 255 },
            shadow: {
                top: topShadow4,
                side: sideShadow4,
                bottom: bottomShadow4
            }
        },
        {
            label: 'active',
            states: {
                '#xmas.matter-button-contained': [ 'active' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: 33, g: 150, b: 243, a: 255 },
            shadow: {
                top: topShadow8,
                side: sideShadow8,
                bottom: bottomShadow8,
            }
        },
        {
            label: 'hover & focus',
            states: {
                '#xmas.matter-button-contained': [ 'hover', 'focus' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: [99, 104], g: [181, 184], b: [246, 247], a: 255 },
            shadow: {
                top: topShadow4,
                side: sideShadow4,
                bottom: bottomShadow4
            }
        },
        {
            label: 'hover & active',
            states: {
                '#xmas.matter-button-contained': [ 'hover', 'active' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: 50, g: 158, b: [243, 244], a: 255 },
            shadow: {
                top: topShadow8,
                side: sideShadow8,
                bottom: bottomShadow8,
            }
        },
        {
            label: 'focus & active',
            states: {
                '#xmas.matter-button-contained': [ 'focus', 'active' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: [85, 86], g: 175, b: [245, 246], a: 255 },
            shadow: {
                top: topShadow8,
                side: sideShadow8,
                bottom: bottomShadow8,
            }
        },
        {
            label: 'hover, focus & active',
            states: {
                '#xmas.matter-button-contained': [ 'hover', 'focus', 'active' ]
            },
            textColor: { r: 255, g: 255, b: 255, a: 255 },
            bodyColor: { r: [99, 104], g: [181, 184], b: [246, 247], a: 255 },
            shadow: {
                top: topShadow8,
                side: sideShadow8,
                bottom: bottomShadow8,
            }
        },
        {
            label: 'disabled',
            states: {
                '#xmas.matter-button-contained': [ 'disabled' ]
            },
            textColor: { r: 0, g: 0, b: 0, a: 116 },
            bodyColor: { r: 0, g: 0, b: 0, a: [30, 31] },
            shadow: {
                top: noShadow,
                side: noShadow,
                bottom: noShadow
            }
        },
        {
            label: 'customized',
            states: {
                '#xmas.matter-button-contained': {
                    style: '--matter-primary-rgb: 255, 0, 0;--matter-onprimary-rgb: 0, 0, 0;width: 120px'
                }
            },
            textColor: { r: 0, g: 0, b: 0, a: 255 },
            bodyColor: { r: 255, g: 0, b: 0, a: 255 },
            shadow: {
                top: topShadow2,
                side: sideShadow2,
                bottom: bottomShadow2
            }
        }
    ].forEach((suite) => {

        describe(`in ${suite.label} state`, () => {

            let style;
            let button;
            let width;
            let height;
            let context;

            beforeAll(async () => {
                style = setUp('src/components/buttons/contained/button-contained', suite.states);

                button = document.querySelector('#xmas');
                const rect = button.getBoundingClientRect();
                width = rect.width;
                height = rect.height;
                context = await capture3x(button, style, SPACING);
            });

            afterAll(() => {
                tearDown();
            });

            it(`should have dominant ${JSON.stringify(suite.bodyColor).replace(/"/g, '')} color`, () => {
                const component = context.getImageData3x(0, 0, width, height);

                expect(component).toResembleColor(suite.bodyColor);
            });

            it('should have uppercase caption text', () => {
                const caption = context.getImageData3x(4, 4, width - 8, height - 8);

                expect(button.innerText).toBe('XMAS TREE');
                expect(caption).toResembleText('XMAS TREE', suite.textColor, suite.bodyColor);
            });

            it(`should have 4px round corners`, () => {
                // shadow
                const sh = {a: [0, 98]};

                // intermediate
                const im = {};

                // body
                const bd = suite.bodyColor;

                const corner = [
                    [ sh, sh, sh, sh, sh, sh, sh, im, im, im, im, im],
                    [ sh, sh, sh, sh, sh, im, im, im, bd, bd, bd, bd],
                    [ sh, sh, sh, sh, im, im, bd, bd, bd, bd, bd, bd],
                    [ sh, sh, sh, im, im, bd, bd, bd, bd, bd, bd, bd],
                    [ sh, sh, im, im, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ sh, im, im, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ sh, im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd],
                    [ im, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd]
                ];

                const topLeft = context.getImageData3x(0, 0, 4, 4);
                const topRight = context.getImageData3x(width - 4, 0, 4, 4);
                const bottomRight = context.getImageData3x(width - 4, height - 4, 4, 4);
                const bottomLeft = context.getImageData3x(0, height - 4, 4, 4);

                expect(topLeft).toResembleShape(corner, 0);
                expect(topRight).toResembleShape(corner, 90);
                expect(bottomRight).toResembleShape(corner, 180);
                expect(bottomLeft).toResembleShape(corner, 270);
            });

            it('should have no outline', () => {
                // body
                const bd = suite.bodyColor;

                const edge = [ bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd, bd ];

                const top = context.getImageData3x(4, 0, width - 8, 4);
                const right = context.getImageData3x(width - 4, 4, 4, height - 8);
                const bottom = context.getImageData3x(4, height - 4, width - 8, 4);
                const left = context.getImageData3x(0, 4, 4, height - 8);

                expect(top).toResembleOblongShape(edge, 0);
                expect(right).toResembleOblongShape(edge, 90);
                expect(bottom).toResembleOblongShape(edge, 180);
                expect(left).toResembleOblongShape(edge, 270);
            });

            it('should have shadow', () => {
                const top = context.getImageData3x(SPACING, -SPACING, width - 2 * SPACING, SPACING);
                const right = context.getImageData3x(width, 12, SPACING, height - 24);
                const bottom = context.getImageData3x(SPACING, height, width - 2 * SPACING, SPACING);
                const left = context.getImageData3x(-SPACING, 12, SPACING, height - 24);

                isBrowserNot('Safari') && expect(top).toResembleOblongShape(suite.shadow.top, 0);
                expect(right).toResembleOblongShape(suite.shadow.side, 90);
                isBrowserNot('Safari') && expect(bottom).toResembleOblongShape(suite.shadow.bottom, 180);
                expect(left).toResembleOblongShape(suite.shadow.side, 270);
            });

        });

    });

    describe('in normal state', () => {

        beforeAll(() => {
            setUp('src/components/buttons/contained/button-contained');
        });

        afterAll(() => {
            tearDown();
        });

        it('should have a height of 36px', () => {
            const { height } = document.querySelector('#normal').getBoundingClientRect();

            expect(height).toBe(36);
        });

        it('should have a minimum width of 64px', () => {
            const { width } = document.querySelector('#min').getBoundingClientRect();

            expect(width).toBe(64);
        });

        it('should have variable-width', () => {
            const { width } = document.querySelector('#sized').getBoundingClientRect();

            expect(width).toBe(120);
        });

    });

});
<|endoftext|>


<commit_before>function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function getJSON(url) {
  return get(url).then(JSON.parse);
}

var pairwise = function(list) {
  if (list.length < 2) {
    return [];
  }
  var first = list[0],
        rest = list.slice(1),
      pairs = rest.map(function (x) { return [first, x]; });
  return pairs.concat(pairwise(rest));
};

var calculate_distance = function(p1, p2) {
  return Math.sqrt(Math.pow(p2.x - p1.x, 2) +
                   Math.pow(p2.y - p1.y, 2) +
                   Math.pow(p2.z - p1.z, 2));
};

var calculate_distances = function(p1, points) {
  return points.map(function(p) {
    return calculate_distance(p1, p.position);
  });
};

var calculate_midpoint = function(p1, p2) {
  return {
    x: (p1.x + p2.x) / 2,
    y: (p1.y + p2.y) / 2,
    z: (p1.z + p2.z) / 2
  };
};

var AU = 149597870700;

var systems_promise = new Promise(function(resolve, reject) {
  api_endpoint = 'https://public-crest.eveonline.com/solarsystems/';
  getJSON(api_endpoint).then(function(data) {
    var systems = {};
    var names = [];
    data.items.forEach(function(system) {
      systems[system.name] = system.href;
      names.push(system.name);
    });
    systems.order = names.sort();
    resolve(systems);
  });
});

systems_promise.then(function(systems) {
  var element = document.getElementById('system_selector');
  var options = ['<option>Please choose system</option>'];
  systems.order.forEach(function(name) {
    options.push("<option value='" + name + "'>" + name + "</option>");
  });
  element.innerHTML = options.join("\n");
  element.addEventListener('change', function() {
    var name = this.value;
    safe_points_for_system(name).then(function(safe_watch) {
      var data = new vis.DataSet();
      var numbers = [];
      var labels = {};
      safe_watch.planets.forEach(function(planet) {
        var point = planet.position;
        point.style = 1;
        var temp = point.y;
        point.y = point.z;
        point.z = temp;
        labels[point.x + '|' + point.y + '|' + point.z] = planet.name;
        data.add(point);
        numbers.push(Math.abs(point.x), Math.abs(point.y), Math.abs(point.z));
      });
      safe_watch.midpoints.forEach(function(midpoint) {
        var point = midpoint.midpoint;
        point.style = 2;
        var temp = point.y;
        point.y = point.z;
        point.z = temp;
        labels[point.x + '|' + point.y + '|' + point.z] = midpoint.name;
        data.add(point);
      });
      var max = Math.max.apply(null, numbers);
      draw(data, max, labels);
      window.location.hash = '#' + name
    });
  });
  name = window.location.hash.substr(1);
  if (name.length) {
    element.value = name;
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
  }
});

var safe_points_for_system = function(system_name) {
  return new Promise(function(resolve, reject) {
    systems_promise.then(function(systems) {
      return getJSON(systems[system_name]);
    }).then(function(system) {
      return Promise.all(
        system.planets.map(function(planet) {
          return planet.href;
        }).map(getJSON)
      );
    }).then(function(planets) {
      planets.push({
        position: { x: 0, y: 0, z: 0 },
        name: 'Sun'
      });
      var pairs = pairwise(planets);
      var midpoints = pairs.map(function(pair) {
        return {
          name: pair[0].name + ' to ' + pair[1].name,
          midpoint: calculate_midpoint(pair[0].position, pair[1].position),
          distance: calculate_distance(pair[0].position, pair[1].position)
        }
      });
      return {
        planets: planets,
        midpoints: midpoints.map(function(mid) {
          return planets.map(function(planet) {
            var midpoint = calculate_midpoint(mid.midpoint, planet.position);
            var distances = calculate_distances(midpoint, planets);
            return {
              name: '(' + mid.name + ') to ' + planet.name,
              midpoint: midpoint,
              distances: distances,
              safe: distances.every(function(d) { return d > 2147483647000 })
            }
          });
        })
      };
    }).then(function(data) {
      final_midpoints = Array.prototype.concat.apply([], data.midpoints);
      data.midpoints = final_midpoints.filter(function(m) {
        return m.safe;
      });
      resolve(data);
    });
  });
};

var draw, graph;

draw = function(data, max, labels) {
  var options = {
    width: '100%',
    height: '100%',
    style: 'dot-color',
    showPerspective: false,
    showGrid: true,
    keepAspectRatio: false,
    verticalRatio: 1.0,
    tooltip: function(point) {
      return labels[point.x + '|' + point.y + '|' + point.z];
    },
    dotSizeRatio: 0.005,
    xValueLabel: function(x) { return Math.round(x / AU) + ' AU'; },
    yValueLabel: function(y) { return Math.round(y / AU) + ' AU'; },
    zValueLabel: function(z) { return Math.round(z / AU) + ' AU'; },
    xMin: -max,
    xMax: max,
    xStep: 5 * AU,
    yMin: -max,
    yMax: max,
    yStep: 5 * AU,
    zMin: -max,
    zMax: max,
    zStep: 5 * AU,
    legendLabel: "Blue: sun and planets; Red: safe spots",
    cameraPosition: {
      horizontal: 0,
      vertical: 0.5 * Math.PI,
      distance: 2.2
    }
  };
  vis.Graph3d.prototype._redrawLegend = function(){};
  var container = document.getElementById('system');
  graph = new vis.Graph3d(container, data, options);
};
<commit_msg>Update main.js<commit_after>function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function getJSON(url) {
  return get(url).then(JSON.parse);
}

var pairwise = function(list) {
  if (list.length < 2) {
    return [];
  }
  var first = list[0],
        rest = list.slice(1),
      pairs = rest.map(function (x) { return [first, x]; });
  return pairs.concat(pairwise(rest));
};

var calculate_distance = function(p1, p2) {
  return Math.sqrt(Math.pow(p2.x - p1.x, 2) +
                   Math.pow(p2.y - p1.y, 2) +
                   Math.pow(p2.z - p1.z, 2));
};

var calculate_distances = function(p1, points) {
  return points.map(function(p) {
    return calculate_distance(p1, p.position);
  });
};

var calculate_midpoint = function(p1, p2) {
  return {
    x: (p1.x + p2.x) / 2,
    y: (p1.y + p2.y) / 2,
    z: (p1.z + p2.z) / 2
  };
};

var AU = 149597870700;

var systems_promise = new Promise(function(resolve, reject) {
  api_endpoint = 'https://esi.evetech.net/latest/universe/systems/';
  getJSON(api_endpoint).then(function(data) {
    var systems = {};
    var names = [];
    data.items.forEach(function(system) {
      systems[system.name] = system.href;
      names.push(system.name);
    });
    systems.order = names.sort();
    resolve(systems);
  });
});

systems_promise.then(function(systems) {
  var element = document.getElementById('system_selector');
  var options = ['<option>Please choose system</option>'];
  systems.order.forEach(function(name) {
    options.push("<option value='" + name + "'>" + name + "</option>");
  });
  element.innerHTML = options.join("\n");
  element.addEventListener('change', function() {
    var name = this.value;
    safe_points_for_system(name).then(function(safe_watch) {
      var data = new vis.DataSet();
      var numbers = [];
      var labels = {};
      safe_watch.planets.forEach(function(planet) {
        var point = planet.position;
        point.style = 1;
        var temp = point.y;
        point.y = point.z;
        point.z = temp;
        labels[point.x + '|' + point.y + '|' + point.z] = planet.name;
        data.add(point);
        numbers.push(Math.abs(point.x), Math.abs(point.y), Math.abs(point.z));
      });
      safe_watch.midpoints.forEach(function(midpoint) {
        var point = midpoint.midpoint;
        point.style = 2;
        var temp = point.y;
        point.y = point.z;
        point.z = temp;
        labels[point.x + '|' + point.y + '|' + point.z] = midpoint.name;
        data.add(point);
      });
      var max = Math.max.apply(null, numbers);
      draw(data, max, labels);
      window.location.hash = '#' + name
    });
  });
  name = window.location.hash.substr(1);
  if (name.length) {
    element.value = name;
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
  }
});

var safe_points_for_system = function(system_name) {
  return new Promise(function(resolve, reject) {
    systems_promise.then(function(systems) {
      return getJSON(systems[system_name]);
    }).then(function(system) {
      return Promise.all(
        system.planets.map(function(planet) {
          return planet.href;
        }).map(getJSON)
      );
    }).then(function(planets) {
      planets.push({
        position: { x: 0, y: 0, z: 0 },
        name: 'Sun'
      });
      var pairs = pairwise(planets);
      var midpoints = pairs.map(function(pair) {
        return {
          name: pair[0].name + ' to ' + pair[1].name,
          midpoint: calculate_midpoint(pair[0].position, pair[1].position),
          distance: calculate_distance(pair[0].position, pair[1].position)
        }
      });
      return {
        planets: planets,
        midpoints: midpoints.map(function(mid) {
          return planets.map(function(planet) {
            var midpoint = calculate_midpoint(mid.midpoint, planet.position);
            var distances = calculate_distances(midpoint, planets);
            return {
              name: '(' + mid.name + ') to ' + planet.name,
              midpoint: midpoint,
              distances: distances,
              safe: distances.every(function(d) { return d > 2147483647000 })
            }
          });
        })
      };
    }).then(function(data) {
      final_midpoints = Array.prototype.concat.apply([], data.midpoints);
      data.midpoints = final_midpoints.filter(function(m) {
        return m.safe;
      });
      resolve(data);
    });
  });
};

var draw, graph;

draw = function(data, max, labels) {
  var options = {
    width: '100%',
    height: '100%',
    style: 'dot-color',
    showPerspective: false,
    showGrid: true,
    keepAspectRatio: false,
    verticalRatio: 1.0,
    tooltip: function(point) {
      return labels[point.x + '|' + point.y + '|' + point.z];
    },
    dotSizeRatio: 0.005,
    xValueLabel: function(x) { return Math.round(x / AU) + ' AU'; },
    yValueLabel: function(y) { return Math.round(y / AU) + ' AU'; },
    zValueLabel: function(z) { return Math.round(z / AU) + ' AU'; },
    xMin: -max,
    xMax: max,
    xStep: 5 * AU,
    yMin: -max,
    yMax: max,
    yStep: 5 * AU,
    zMin: -max,
    zMax: max,
    zStep: 5 * AU,
    legendLabel: "Blue: sun and planets; Red: safe spots",
    cameraPosition: {
      horizontal: 0,
      vertical: 0.5 * Math.PI,
      distance: 2.2
    }
  };
  vis.Graph3d.prototype._redrawLegend = function(){};
  var container = document.getElementById('system');
  graph = new vis.Graph3d(container, data, options);
};
<|endoftext|>


<commit_before>"use strict"; // strict mode syntax
var hidden = [];
var oldData = [];
var loadChart = function(data, type, collection){
	/*
	Using Chart.js
	*/
	var data1 = data;
	data1[0].splice(0, 1);
	var chartdata = dataset(data1, collection);
	var data = {
		labels: data1[0],
		datasetFill: false,
		datasets: chartdata.data
	};

	var ctx = document.getElementById("myChart").getContext("2d");
	var myLineChart;
	if(type === "scatter")
		myLineChart = new Chart(ctx).ScatterPlot(data);
	else if(type === "bar")
		myLineChart = new Chart(ctx).Bar(data);
	else
	  myLineChart = new Chart(ctx).Line(data);
	document.getElementById("myChart").setAttribute("title","image of graph"); // by setting the attribute we can make the chart accessible
	for(var i =0; i<data.datasets.length;i++){
		//Setting input functions for each line in order to set new colors
		chartdata.inputboxes[i].oninput = function(){
			var index = chartdata.inputboxes.indexOf(this);
			var newcolor = this.value;
				//Regex check for correctly formatted RGB color value
				if(/^#[0-9A-F]{6}$/i.test(newcolor)){
					//If test passes, parse out red, green, and blue.
					var r = parseInt(newcolor.substring(1,3), 16);
					var g = parseInt(newcolor.substring(3,5), 16);
					var b = parseInt(newcolor.substring(5), 16);
					//Combine them to make a new color
					var color = [r, g, b].join(", ");
					lineColors[index] = "rgba("+ color +", 1)";
					if(this.nextSibling.checked){
						//Set necessary color values based on graph type
						if(type==="line" || type==="scatter")
							chart.datasets[index].strokeColor = "rgba("+ color +", 1)";
							chart.datasets[index].pointColor = "rgba("+ color +", 1)";
							chart.datasets[index].pointHighlightStroke = "rgba("+ color +", 1)";
						if(type==="line"|| type==="scatter"){
							for(var i = 0; i<chart.datasets[index].points.length;i++){
								chart.datasets[index].points[i].fillColor= "rgba("+ color +", 1)";
							}
						}
						else if(type==="bar"){
							for(var i = 0; i<chart.datasets[index].bars.length;i++){
								chart.datasets[index].bars[i].fillColor= "rgba("+ color +", 1)";
								chart.datasets[index].bars[i].strokeColor= "rgba("+ color +", 1)";
							}
						}
						//Redraw graph
						chart.update();
					}
					//Set Graph data color indication color to match new color
					if(type === "line" || type === "scatter")
						this.parentNode.firstChild.nextSibling.nextSibling.setAttribute("style", "color:rgb(" + color + "); display: inline; margine-right: 5px;");
					else if(type === "bar")
						this.parentNode.firstChild.nextSibling.nextSibling.firstChild.setAttribute("style", "background:rgb(" + color + "); display: inline; margine-right: 5px;");
				}
				//Check color list for name match
				else if(/^#[0-9A-F]{6}$/i.test(colors[newcolor.toLowerCase().split(' ').join('')])){
					//If there is a match, get red, green, and blue values from the corresponding color
					var rgb = colors[newcolor.toLowerCase().split(' ').join('')];
					var r = parseInt(rgb.substring(1,3), 16);
					var g = parseInt(rgb.substring(3,5), 16);
					var b = parseInt(rgb.substring(5), 16);
					//Using red, green, and blue values, make a new color.
					var color = [r, g, b].join(", ");
          			lineColors[index] = "rgba("+ color +", 1)";
					if(this.nextSibling.checked){
						//Set necessary colors based on graph type
            			if(type==="line")
            			chart.datasets[index].strokeColor = "rgba("+ color +", 1)";
						chart.datasets[index].pointColor = "rgba("+ color +", 1)";
						chart.datasets[index].pointHighlightStroke = "rgba("+ color +", 1)";
						if(type==="line" || type==="scatter"){
							for(var i = 0; i<chart.datasets[index].points.length;i++){
								chart.datasets[index].points[i].fillColor= "rgba("+ color +", 1)";
							}
						}
						else if(type==="bar"){
							for(var i = 0; i<chart.datasets[index].bars.length;i++){
								chart.datasets[index].bars[i].fillColor= "rgba("+ color +", 1)";
								chart.datasets[index].bars[i].strokeColor= "rgba("+ color +", 1)";
							}
						}
						//Redraw graph
						chart.update();
					}
					//Set graph data color indicator
					if(type === "line" || type==="scatter")
						this.parentNode.firstChild.nextSibling.nextSibling.setAttribute("style", "color:rgb(" + color + "); display: inline; margine-right: 5px;");
					else if(type === "bar")
						this.parentNode.firstChild.nextSibling.nextSibling.firstChild.setAttribute("style", "background:rgb(" + color + "); display: inline; margine-right: 5px;");
          }
			};
		//Setting behavior for all toggleboxes
		chartdata.inputboxes[i].nextSibling.onclick = function(){
			var index = chartdata.inputboxes.indexOf(this.previousSibling);
			//If not hidden, hide
			if(!this.checked){
				if(hidden[index]!= false){
					hidden[index] = false;
					var transparent = [0,0,0].join(", ");
					transparent = "rgba(" + transparent +", 0)";
					chart.datasets[index].strokeColor = transparent;
					chart.datasets[index].pointColor = transparent;
					chart.datasets[index].pointHighlightStroke = transparent;
					if(type==="line" || type === "scatter"){
						if(!oldData[index])
							oldData[index] = {};
	          			oldData[index].points = chart.datasets[index].points;
	          			chart.datasets[index].points = undefined;
					}
					else if(type === "bar"){
						if(!oldData[index])
							oldData[index] = {};
	          			oldData[index].bars = chart.datasets[index].bars;
	          			chart.datasets[index].bars = undefined;
					}
					chart.update();
					linkSlickTable(chart,player,overlay,summary);
				}
			}
			//If hidden, bring the line back
			else{
				if(hidden[index]!= true){
					hidden[index]= true;
					if(type === "bar")
						var color = this.previousSibling.previousSibling.firstChild.style.background;
					else
						var color = this.previousSibling.previousSibling.style.color;
					color = color.substring(0,3) + "a(" + color.substring(4,(color.indexOf(")"))) + ", 1)";
					chart.datasets[index].strokeColor = color;
					chart.datasets[index].pointColor = color;
					chart.datasets[index].pointHighlightStroke = color;
					if(type === "line" || type === "scatter"){
	          			chart.datasets[index].points = oldData[index].points;
	          			//oldData[index].points = undefined;
					}
					else if(type === "bar"){
	          			chart.datasets[index].bars = oldData[index].bars;
	          			//oldData[index].bars= undefined;
					}
					chart.update();
					linkSlickTable(chart,player,overlay,summary);
					}
			}
		};
	}
	return myLineChart;
}

// sets the data for the chart in a selection of generated colors
function dataset(data, collection) {
	var dataArray = [];
	var inputBoxArray = [];
	var red, green, blue;
	red = green = blue = 0;
	var colorIncrease = parseInt((255/ data.length).toFixed(0));
	document.getElementById('colors').innerHTML= "";
	for (var i = 1; i < data.length; i++) {
		var color = [red, green, blue].join(", ");
		data[i].splice(0, 1);
		var line =
		{
		fillColor: "rgba(220, 220, 220, 0)",
		strokeColor: "rgba("+ color +", 1)",
		pointColor: "rgba("+ color +", 1)",
		label: i,

      //pointStrokeColor: "#fff",
		pointHighlightFill: "#fff",
		pointHighlightStroke: "rgba("+ color +", 1)",
		data: data[i]
		}
    //Fill Bar Color
		if(type === "bar"){
			line.fillColor = line.strokeColor;
		}
    //Put line into data Array
    	//console.log(line);
    	if(hidden[i-1]===false){
    		oldData[i-1].data = line;
    		line.data = undefined;
    	}
		dataArray.push(line);
    //Chech if previous line color existed
    if(lineColors.length<i){
      //If not, add it
      lineColors.push(line.strokeColor);
    }
    else{
      //If so, inherit previous color
      line.strokeColor = lineColors[i-1];
      line.pointColor= lineColors[i-1];
      line.pointHighlightStroke = lineColors[i-1];
      if(type === "bar"){
        //Bar will inherit fill color as well
        line.fillColor = lineColors[i-1];
      }
    }
		// log color into color editor
    var newColor = lineColors[i-1];
		var entry = document.createElement('li');
		var textInput = document.createElement('input');
		var toggleBox = document.createElement('input');
		var keyValue = document.createElement('p');
		//var removeButton = document.createElement('button');
    if(type === "line")
		var keyLabel = document.createTextNode(shapes[(i-1)%6]);
	else if(type === "scatter"){
		var keyLabel = document.createTextNode(shapes[0]);
		}
    else if(type === "bar"){
		keyLabel = document.createElement('span');
		keyLabel.setAttribute("style", "background:"+newColor);
		keyLabel.setAttribute("class", "colorblock");
		}
		if(hidden.length<= i-1){
			hidden.push(true);
		}
		inputBoxArray.push(textInput);
		textInput.setAttribute("title", "Enter color");
		toggleBox.setAttribute("type", "checkbox");
		if(hidden[i-1]===true)
			toggleBox.setAttribute("checked", "checked");
		toggleBox.setAttribute("title", "Display Data Set " + i);
		keyValue.setAttribute('style', 'color:' + newColor +'; display: inline; margin-right: 5px;');
		keyValue.appendChild(keyLabel);
		entry.appendChild(keyValue);
		entry.appendChild(textInput);
		entry.appendChild(toggleBox);
		document.getElementById('colors').appendChild(entry);
		red += colorIncrease + 15;
		green += colorIncrease;
		blue += colorIncrease - 15;

	}
	var returndata = new Object();
	returndata.data = dataArray;
	returndata.inputboxes = inputBoxArray;
	return returndata;
}

// deques elements off the array
function deque(array) {
	var ele = array[0];
	array.splice(0,1);
	return ele;
}

function convertPointsToBars(){
	var datasetLen = chart.datasets.length;
	var chartBase = chart.scale.endPoint;

	for(var i = 0; i < chart.datasets.length; i ++){
		if(chart.datasets[i].points){
			chart.datasets[i].bars = [];
			for(var j = 0; j <chart.datasets[i].points.length; j++){
				var point = chart.datasets[i].points[j];
				var bar = new chart.BarClass();
				bar.base = chart.scale.endPoint;
				bar.datasetLabel = point.datasetLabel;
				bar.fillColor = point.fillColor;
				bar.highlightFill = point.fillColor;
				bar.highlightStroke = point.fillColor;
				bar.label = point.label;
				bar.strokeColor = point.fillColor;
				bar.value = point.value;
				bar.width = chart.scale.calculateBarWidth(chart.datasets.length);
				bar.x = chart.scale.calculateBarX(datasetLen,i,j);
				bar.y = point.y;
				chart.datasets[i].bars.push(bar);
			}
		}
		else{
			oldData[i].bars = [];
			for(var j = 0; j <oldData[i].points.length; j++){
				var point = oldData[i].points[j];
				var bar = new chart.BarClass();
				bar.base = chart.scale.endPoint;
				bar.datasetLabel = point.datasetLabel;
				bar.fillColor = point.fillColor;
				bar.highlightFill = point.fillColor;
				bar.highlightStroke = point.fillColor;
				bar.label = point.label;
				bar.strokeColor = point.fillColor;
				bar.value = point.value;
				bar.width = chart.scale.calculateBarWidth(chart.datasets.length);
				bar.x = chart.scale.calculateBarX(datasetLen,i,j);
				bar.y = point.y;
				oldData[i].bars.push(bar);
			}
		}
	}
}<commit_msg>Fixed overlay silliness<commit_after>"use strict"; // strict mode syntax
var hidden = [];
var oldData = [];
var loadChart = function(data, type, collection){
	/*
	Using Chart.js
	*/
	var data1 = data;
	data1[0].splice(0, 1);
	var chartdata = dataset(data1, collection);
	var data = {
		labels: data1[0],
		datasetFill: false,
		datasets: chartdata.data
	};

	var ctx = document.getElementById("myChart").getContext("2d");
	var myLineChart;
	if(type === "scatter")
		myLineChart = new Chart(ctx).ScatterPlot(data);
	else if(type === "bar")
		myLineChart = new Chart(ctx).Bar(data);
	else
	  myLineChart = new Chart(ctx).Line(data);
	document.getElementById("myChart").setAttribute("title","image of graph"); // by setting the attribute we can make the chart accessible
	for(var i =0; i<data.datasets.length;i++){
		//Setting input functions for each line in order to set new colors
		chartdata.inputboxes[i].oninput = function(){
			var index = chartdata.inputboxes.indexOf(this);
			var newcolor = this.value;
				//Regex check for correctly formatted RGB color value
				if(/^#[0-9A-F]{6}$/i.test(newcolor)){
					//If test passes, parse out red, green, and blue.
					var r = parseInt(newcolor.substring(1,3), 16);
					var g = parseInt(newcolor.substring(3,5), 16);
					var b = parseInt(newcolor.substring(5), 16);
					//Combine them to make a new color
					var color = [r, g, b].join(", ");
					lineColors[index] = "rgba("+ color +", 1)";
					if(this.nextSibling.checked){
						//Set necessary color values based on graph type
						if(type==="line" || type==="scatter")
							chart.datasets[index].strokeColor = "rgba("+ color +", 1)";
							chart.datasets[index].pointColor = "rgba("+ color +", 1)";
							chart.datasets[index].pointHighlightStroke = "rgba("+ color +", 1)";
						if(type==="line"|| type==="scatter"){
							for(var i = 0; i<chart.datasets[index].points.length;i++){
								chart.datasets[index].points[i].fillColor= "rgba("+ color +", 1)";
							}
						}
						else if(type==="bar"){
							for(var i = 0; i<chart.datasets[index].bars.length;i++){
								chart.datasets[index].bars[i].fillColor= "rgba("+ color +", 1)";
								chart.datasets[index].bars[i].strokeColor= "rgba("+ color +", 1)";
							}
						}
						//Redraw graph
						chart.update();
					}
					//Set Graph data color indication color to match new color
					if(type === "line" || type === "scatter")
						this.parentNode.firstChild.nextSibling.nextSibling.setAttribute("style", "color:rgb(" + color + "); display: inline; margine-right: 5px;");
					else if(type === "bar")
						this.parentNode.firstChild.nextSibling.nextSibling.firstChild.setAttribute("style", "background:rgb(" + color + "); display: inline; margine-right: 5px;");
				}
				//Check color list for name match
				else if(/^#[0-9A-F]{6}$/i.test(colors[newcolor.toLowerCase().split(' ').join('')])){
					//If there is a match, get red, green, and blue values from the corresponding color
					var rgb = colors[newcolor.toLowerCase().split(' ').join('')];
					var r = parseInt(rgb.substring(1,3), 16);
					var g = parseInt(rgb.substring(3,5), 16);
					var b = parseInt(rgb.substring(5), 16);
					//Using red, green, and blue values, make a new color.
					var color = [r, g, b].join(", ");
          			lineColors[index] = "rgba("+ color +", 1)";
					if(this.nextSibling.checked){
						//Set necessary colors based on graph type
            			if(type==="line")
            			chart.datasets[index].strokeColor = "rgba("+ color +", 1)";
						chart.datasets[index].pointColor = "rgba("+ color +", 1)";
						chart.datasets[index].pointHighlightStroke = "rgba("+ color +", 1)";
						if(type==="line" || type==="scatter"){
							for(var i = 0; i<chart.datasets[index].points.length;i++){
								chart.datasets[index].points[i].fillColor= "rgba("+ color +", 1)";
							}
						}
						else if(type==="bar"){
							for(var i = 0; i<chart.datasets[index].bars.length;i++){
								chart.datasets[index].bars[i].fillColor= "rgba("+ color +", 1)";
								chart.datasets[index].bars[i].strokeColor= "rgba("+ color +", 1)";
							}
						}
						//Redraw graph
						chart.update();
					}
					//Set graph data color indicator
					if(type === "line" || type==="scatter")
						this.parentNode.firstChild.nextSibling.nextSibling.setAttribute("style", "color:rgb(" + color + "); display: inline; margine-right: 5px;");
					else if(type === "bar")
						this.parentNode.firstChild.nextSibling.nextSibling.firstChild.setAttribute("style", "background:rgb(" + color + "); display: inline; margine-right: 5px;");
          }
			};
		//Setting behavior for all toggleboxes
		chartdata.inputboxes[i].nextSibling.onclick = function(){
			var index = chartdata.inputboxes.indexOf(this.previousSibling);
			//If not hidden, hide
			if(!this.checked){
				if(hidden[index]!= false){
					hidden[index] = false;
					var transparent = [0,0,0].join(", ");
					transparent = "rgba(" + transparent +", 0)";
					chart.datasets[index].strokeColor = transparent;
					chart.datasets[index].pointColor = transparent;
					chart.datasets[index].pointHighlightStroke = transparent;
					if(type==="line" || type === "scatter"){
						if(!oldData[index])
							oldData[index] = {};
	          			oldData[index].points = chart.datasets[index].points;
	          			chart.datasets[index].points = undefined;
					}
					else if(type === "bar"){
						if(!oldData[index])
							oldData[index] = {};
	          			oldData[index].bars = chart.datasets[index].bars;
	          			chart.datasets[index].bars = undefined;
					}
					chart.update();
					overlay.updateSize(chart);
					linkSlickTable(chart,player,overlay,summary);
				}
			}
			//If hidden, bring the line back
			else{
				if(hidden[index]!= true){
					hidden[index]= true;
					if(type === "bar")
						var color = this.previousSibling.previousSibling.firstChild.style.background;
					else
						var color = this.previousSibling.previousSibling.style.color;
					color = color.substring(0,3) + "a(" + color.substring(4,(color.indexOf(")"))) + ", 1)";
					chart.datasets[index].strokeColor = color;
					chart.datasets[index].pointColor = color;
					chart.datasets[index].pointHighlightStroke = color;
					if(type === "line" || type === "scatter"){
	          			chart.datasets[index].points = oldData[index].points;
	          			//oldData[index].points = undefined;
					}
					else if(type === "bar"){
	          			chart.datasets[index].bars = oldData[index].bars;
	          			//oldData[index].bars= undefined;
					}
					chart.update();
					overlay.updateSize(chart);
					linkSlickTable(chart,player,overlay,summary);
					}
			}
		};
	}
	return myLineChart;
}

// sets the data for the chart in a selection of generated colors
function dataset(data, collection) {
	var dataArray = [];
	var inputBoxArray = [];
	var red, green, blue;
	red = green = blue = 0;
	var colorIncrease = parseInt((255/ data.length).toFixed(0));
	document.getElementById('colors').innerHTML= "";
	for (var i = 1; i < data.length; i++) {
		var color = [red, green, blue].join(", ");
		data[i].splice(0, 1);
		var line =
		{
		fillColor: "rgba(220, 220, 220, 0)",
		strokeColor: "rgba("+ color +", 1)",
		pointColor: "rgba("+ color +", 1)",
		label: i,

      //pointStrokeColor: "#fff",
		pointHighlightFill: "#fff",
		pointHighlightStroke: "rgba("+ color +", 1)",
		data: data[i]
		}
    //Fill Bar Color
		if(type === "bar"){
			line.fillColor = line.strokeColor;
		}
    //Put line into data Array
    	//console.log(line);
    	if(hidden[i-1]===false){
    		oldData[i-1].data = line;
    		line.data = undefined;
    	}
		dataArray.push(line);
    //Chech if previous line color existed
    if(lineColors.length<i){
      //If not, add it
      lineColors.push(line.strokeColor);
    }
    else{
      //If so, inherit previous color
      line.strokeColor = lineColors[i-1];
      line.pointColor= lineColors[i-1];
      line.pointHighlightStroke = lineColors[i-1];
      if(type === "bar"){
        //Bar will inherit fill color as well
        line.fillColor = lineColors[i-1];
      }
    }
		// log color into color editor
    var newColor = lineColors[i-1];
		var entry = document.createElement('li');
		var textInput = document.createElement('input');
		var toggleBox = document.createElement('input');
		var keyValue = document.createElement('p');
		//var removeButton = document.createElement('button');
    if(type === "line")
		var keyLabel = document.createTextNode(shapes[(i-1)%6]);
	else if(type === "scatter"){
		var keyLabel = document.createTextNode(shapes[0]);
		}
    else if(type === "bar"){
		keyLabel = document.createElement('span');
		keyLabel.setAttribute("style", "background:"+newColor);
		keyLabel.setAttribute("class", "colorblock");
		}
		if(hidden.length<= i-1){
			hidden.push(true);
		}
		inputBoxArray.push(textInput);
		textInput.setAttribute("title", "Enter color");
		toggleBox.setAttribute("type", "checkbox");
		if(hidden[i-1]===true)
			toggleBox.setAttribute("checked", "checked");
		toggleBox.setAttribute("title", "Display Data Set " + i);
		keyValue.setAttribute('style', 'color:' + newColor +'; display: inline; margin-right: 5px;');
		keyValue.appendChild(keyLabel);
		entry.appendChild(keyValue);
		entry.appendChild(textInput);
		entry.appendChild(toggleBox);
		document.getElementById('colors').appendChild(entry);
		red += colorIncrease + 15;
		green += colorIncrease;
		blue += colorIncrease - 15;

	}
	var returndata = new Object();
	returndata.data = dataArray;
	returndata.inputboxes = inputBoxArray;
	return returndata;
}

// deques elements off the array
function deque(array) {
	var ele = array[0];
	array.splice(0,1);
	return ele;
}

function convertPointsToBars(){
	var datasetLen = chart.datasets.length;
	var chartBase = chart.scale.endPoint;

	for(var i = 0; i < chart.datasets.length; i ++){
		if(chart.datasets[i].points){
			chart.datasets[i].bars = [];
			for(var j = 0; j <chart.datasets[i].points.length; j++){
				var point = chart.datasets[i].points[j];
				var bar = new chart.BarClass();
				bar.base = chart.scale.endPoint;
				bar.datasetLabel = point.datasetLabel;
				bar.fillColor = point.fillColor;
				bar.highlightFill = point.fillColor;
				bar.highlightStroke = point.fillColor;
				bar.label = point.label;
				bar.strokeColor = point.fillColor;
				bar.value = point.value;
				bar.width = chart.scale.calculateBarWidth(chart.datasets.length);
				bar.x = chart.scale.calculateBarX(datasetLen,i,j);
				bar.y = point.y;
				chart.datasets[i].bars.push(bar);
			}
		}
		else{
			if(oldData[i]){
				oldData[i].bars = [];
				for(var j = 0; j <oldData[i].points.length; j++){
					var point = oldData[i].points[j];
					var bar = new chart.BarClass();
					bar.base = chart.scale.endPoint;
					bar.datasetLabel = point.datasetLabel;
					bar.fillColor = point.fillColor;
					bar.highlightFill = point.fillColor;
					bar.highlightStroke = point.fillColor;
					bar.label = point.label;
					bar.strokeColor = point.fillColor;
					bar.value = point.value;
					bar.width = chart.scale.calculateBarWidth(chart.datasets.length);
					bar.x = chart.scale.calculateBarX(datasetLen,i,j);
					bar.y = point.y;
					oldData[i].bars.push(bar);
				}
			}
		}
	}
}<|endoftext|>


<commit_before>"use strict";

describe("Factory: apEncodeService", function () {

    beforeEach(module("angularPoint"));

    var service,
        mockModel,
        mockXMLService,
        apUtilityService,
        utils;

    beforeEach(inject(function (_apEncodeService_, _mockXMLService_, _mockModel_, _apUtilityService_, apMockUtils) {
        service = _apEncodeService_;
        mockXMLService = _mockXMLService_;
        mockModel = _mockModel_;
        apUtilityService = _apUtilityService_;
        utils = apMockUtils;
    }));

    describe('Function: choiceMultiToString', function () {

        it('converts array of strings into delimited string', function () {
            var tempChoices = ['choice 1', 'choice 2'];
            expect(service.choiceMultiToString(tempChoices))
                .toEqual(';#choice 1;#choice 2;#');
        });

    });

    describe('Function: apEncodeService', function () {
        it('returns an empty value if an empty value is passed in', function () {
            expect(service.createValuePair(mockDefinition('Lookup'), ''))
                .toEqual(['Lookup', '']);
        });

        it('correctly handles a Lookup field', function () {
            var validLookup = {lookupId: 1, lookupValue: 'Test'};
            expect(service.createValuePair(mockDefinition('Lookup'), validLookup))
                .toEqual([ 'Lookup', '1;#Test' ]);
        });

        it('correctly handles a User field', function () {
            var validUser = {lookupId: 1100, lookupValue: 'Bill'};
            expect(service.createValuePair(mockDefinition('User'), validUser))
                .toEqual([ 'User', '1100;#Bill' ]);
        });

        it('correctly handles a UserMulti field', function () {
            var validUsers = [
                {lookupId: 1100, lookupValue: 'Bill'},
                {lookupId: 1101, lookupValue: 'Jane'}
            ];
            expect(service.createValuePair(mockDefinition('UserMulti'), validUsers))
                .toEqual([ 'UserMulti', '1100;#Bill;#1101;#Jane;#' ]);
        });

        it('correctly handles a LookupMulti field', function () {
            var validUsers = [
                {lookupId: 1, lookupValue: 'Cog'},
                {lookupId: 2, lookupValue: 'Widget'}
            ];
            expect(service.createValuePair(mockDefinition('LookupMulti'), validUsers))
                .toEqual([ 'LookupMulti', '1;#Cog;#2;#Widget;#' ]);
        });

        it('correctly handles a true Boolean field', function () {
            expect(service.createValuePair(mockDefinition('Boolean'), true))
                .toEqual([ 'Boolean', 1 ]);
        });

        it('correctly handles a false Boolean field', function () {
            expect(service.createValuePair(mockDefinition('Boolean'), false))
                .toEqual([ 'Boolean', 0 ]);
        });

        it('correctly handles a DateTime field', function () {
            var validDate = new Date(2014, 5, 10, 3, 25, 30);
            expect(service.createValuePair(mockDefinition('DateTime'), validDate))
                .toEqual([ 'DateTime', '2014-06-10T03:25:30Z-08:00']);
        });

        it('handles a DateTime value as a string', function () {
            expect(service.createValuePair(mockDefinition('DateTime'), '2014-05-06'))
                .toEqual([ 'DateTime', '2014-05-06T00:00:00Z-08:00' ]);
                //.toEqual([ 'DateTime', '2014-05-06T00:00:00Z-' + utils.getTimezoneOffsetString() ]);
        });

        it('doesn\'t save invalid DateTime field', function () {
            var invalidDate = 'This is a string and not a date!';
            expect(function(){service.createValuePair(mockDefinition('DateTime'), invalidDate)})
                .toThrow();
        });

        it('correctly handles a HTML field', function () {
            var validHTML = '
I like eggs & bacon @ breakfast!
';
            expect(service.createValuePair(mockDefinition('HTML'), validHTML))
                .toEqual([ 'HTML', '<div>I like eggs & bacon @ breakfast!</div>' ]);
        });

        it('correctly handles a Note field', function () {
            var validNote = 'This is a test area > 1 line!';
            expect(service.createValuePair(mockDefinition('Note'), validNote))
                .toEqual([ 'Note', 'This is a test area > 1 line!' ]);
        });

        it('correctly handles a JSON field', function () {
            var validObject = {
                test: 'cog',
                test2: 'sprocket'
            };
            expect(service.createValuePair(mockDefinition('JSON'), validObject))
                .toEqual([ 'JSON', '{"test":"cog","test2":"sprocket"}' ]);
        });

        it('correctly handles a plan text field', function () {
            expect(service.createValuePair(mockDefinition('Title'), 'Test String'))
                .toEqual(['Title', 'Test String']);
        });
    });

    function mockDefinition(type) {
        return _.find(mockModel.list.customFields, {staticName: type});
    }

});
<commit_msg>Remove daylight savings time.<commit_after>"use strict";

describe("Factory: apEncodeService", function () {

    beforeEach(module("angularPoint"));

    var service,
        mockModel,
        mockXMLService,
        apUtilityService,
        utils;

    beforeEach(inject(function (_apEncodeService_, _mockXMLService_, _mockModel_, _apUtilityService_, apMockUtils) {
        service = _apEncodeService_;
        mockXMLService = _mockXMLService_;
        mockModel = _mockModel_;
        apUtilityService = _apUtilityService_;
        utils = apMockUtils;
    }));

    describe('Function: choiceMultiToString', function () {

        it('converts array of strings into delimited string', function () {
            var tempChoices = ['choice 1', 'choice 2'];
            expect(service.choiceMultiToString(tempChoices))
                .toEqual(';#choice 1;#choice 2;#');
        });

    });

    describe('Function: apEncodeService', function () {
        it('returns an empty value if an empty value is passed in', function () {
            expect(service.createValuePair(mockDefinition('Lookup'), ''))
                .toEqual(['Lookup', '']);
        });

        it('correctly handles a Lookup field', function () {
            var validLookup = {lookupId: 1, lookupValue: 'Test'};
            expect(service.createValuePair(mockDefinition('Lookup'), validLookup))
                .toEqual([ 'Lookup', '1;#Test' ]);
        });

        it('correctly handles a User field', function () {
            var validUser = {lookupId: 1100, lookupValue: 'Bill'};
            expect(service.createValuePair(mockDefinition('User'), validUser))
                .toEqual([ 'User', '1100;#Bill' ]);
        });

        it('correctly handles a UserMulti field', function () {
            var validUsers = [
                {lookupId: 1100, lookupValue: 'Bill'},
                {lookupId: 1101, lookupValue: 'Jane'}
            ];
            expect(service.createValuePair(mockDefinition('UserMulti'), validUsers))
                .toEqual([ 'UserMulti', '1100;#Bill;#1101;#Jane;#' ]);
        });

        it('correctly handles a LookupMulti field', function () {
            var validUsers = [
                {lookupId: 1, lookupValue: 'Cog'},
                {lookupId: 2, lookupValue: 'Widget'}
            ];
            expect(service.createValuePair(mockDefinition('LookupMulti'), validUsers))
                .toEqual([ 'LookupMulti', '1;#Cog;#2;#Widget;#' ]);
        });

        it('correctly handles a true Boolean field', function () {
            expect(service.createValuePair(mockDefinition('Boolean'), true))
                .toEqual([ 'Boolean', 1 ]);
        });

        it('correctly handles a false Boolean field', function () {
            expect(service.createValuePair(mockDefinition('Boolean'), false))
                .toEqual([ 'Boolean', 0 ]);
        });

        it('correctly handles a DateTime field', function () {
            var validDate = new Date(2014, 5, 10, 3, 25, 30);
            expect(service.createValuePair(mockDefinition('DateTime'), validDate))
                .toEqual([ 'DateTime', '2014-06-10T03:25:30Z-07:00']);
        });

        it('handles a DateTime value as a string', function () {
            expect(service.createValuePair(mockDefinition('DateTime'), '2014-05-06'))
                .toEqual([ 'DateTime', '2014-05-06T00:00:00Z-07:00' ]);
                //.toEqual([ 'DateTime', '2014-05-06T00:00:00Z-' + utils.getTimezoneOffsetString() ]);
        });

        it('doesn\'t save invalid DateTime field', function () {
            var invalidDate = 'This is a string and not a date!';
            expect(function(){service.createValuePair(mockDefinition('DateTime'), invalidDate)})
                .toThrow();
        });

        it('correctly handles a HTML field', function () {
            var validHTML = '
I like eggs & bacon @ breakfast!
';
            expect(service.createValuePair(mockDefinition('HTML'), validHTML))
                .toEqual([ 'HTML', '<div>I like eggs & bacon @ breakfast!</div>' ]);
        });

        it('correctly handles a Note field', function () {
            var validNote = 'This is a test area > 1 line!';
            expect(service.createValuePair(mockDefinition('Note'), validNote))
                .toEqual([ 'Note', 'This is a test area > 1 line!' ]);
        });

        it('correctly handles a JSON field', function () {
            var validObject = {
                test: 'cog',
                test2: 'sprocket'
            };
            expect(service.createValuePair(mockDefinition('JSON'), validObject))
                .toEqual([ 'JSON', '{"test":"cog","test2":"sprocket"}' ]);
        });

        it('correctly handles a plan text field', function () {
            expect(service.createValuePair(mockDefinition('Title'), 'Test String'))
                .toEqual(['Title', 'Test String']);
        });
    });

    function mockDefinition(type) {
        return _.find(mockModel.list.customFields, {staticName: type});
    }

});
<|endoftext|>


<commit_before>jQuery.fn.extend({
  slideRightShow: function(duration) {
    return this.each(function() {
      $(this).show('slide', {direction: 'right'}, duration);
    });
  },
  slideLeftHide: function(duration) {
    return this.each(function() {
      $(this).hide('slide', {direction: 'left'}, duration);
    });
  },
  slideRightHide: function(duration) {
    return this.each(function() {
      $(this).hide('slide', {direction: 'right'}, duration);
    });
  },
  slideLeftShow: function(duration) {
    return this.each(function() {
      $(this).show('slide', {direction: 'left'}, duration);
    });
  }
});

$(document).on('page:fetch', function() {
  var turbolinkContent = $('.js-turbolink-content');
  turbolinkContent.each(function(index) {
    var animationType = $(this).data('animation')
    var duration = $(this).data('duration') || 300;
    switch (animationType) {
      case 'slide-right':
        $(this).slideRightHide(duration); break;
      case 'slide-left':
        $(this).slideLeftHide(duration); break;
      default:
        $(this).fadeOut('slow');
    }
  });
});

$(document).on('page:restore', function() {
  var turbolinkContent = $('.js-turbolink-content');
  turbolinkContent.each(function(index) {
    var animationType = $(this).data('animation')
    var duration = $(this).data('duration') || 300;
    switch (animationType) {
      case 'slide-right':
        $(this).slideLeftShow(duration); break;
      case 'slide-left':
        $(this).slideRightShow(duration); break;
      default:
        $(this).fadeIn('slow');
    }
  });
});
<commit_msg>parseInt duration<commit_after>jQuery.fn.extend({
  slideRightShow: function(duration) {
    return this.each(function() {
      $(this).show('slide', {direction: 'right'}, duration);
    });
  },
  slideLeftHide: function(duration) {
    return this.each(function() {
      $(this).hide('slide', {direction: 'left'}, duration);
    });
  },
  slideRightHide: function(duration) {
    return this.each(function() {
      $(this).hide('slide', {direction: 'right'}, duration);
    });
  },
  slideLeftShow: function(duration) {
    return this.each(function() {
      $(this).show('slide', {direction: 'left'}, duration);
    });
  }
});

$(document).on('page:fetch', function() {
  var turbolinkContent = $('.js-turbolink-content');
  turbolinkContent.each(function(index) {
    var animationType = $(this).data('animation')
    var duration = parseInt($(this).data('duration')) || 300;
    switch (animationType) {
      case 'slide-right':
        $(this).slideRightHide(duration); break;
      case 'slide-left':
        $(this).slideLeftHide(duration); break;
      default:
        $(this).fadeOut('slow');
    }
  });
});

$(document).on('page:restore', function() {
  var turbolinkContent = $('.js-turbolink-content');
  turbolinkContent.each(function(index) {
    var animationType = $(this).data('animation')
    var duration = parseInt($(this).data('duration')) || 300;
    switch (animationType) {
      case 'slide-right':
        $(this).slideLeftShow(duration); break;
      case 'slide-left':
        $(this).slideRightShow(duration); break;
      default:
        $(this).fadeIn('slow');
    }
  });
});
<|endoftext|>


<commit_before>/**
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

'use strict';

import * as utils from './utils'
import * as mutation from './logical-mutation'
import {ActiveElementAccessor, ShadowRootAccessor, patchAccessors} from './patch-accessors'
import {getProperty} from './logical-properties'
import {addEventListener, removeEventListener} from './patch-events'
import {attachShadow} from './attach-shadow'

function getAssignedSlot(node) {
  mutation.renderRootNode(node);
  return getProperty(node, 'assignedSlot') || null;
}

let nodeMixin = {

  addEventListener: addEventListener,

  removeEventListener: removeEventListener,

  appendChild(node) {
    return mutation.insertBefore(this, node);
  },

  insertBefore(node, ref_node) {
    return mutation.insertBefore(this, node, ref_node);
  },

  removeChild(node) {
    return mutation.removeChild(this, node);
  },

  replaceChild(node, ref_node) {
    this.insertBefore(node, ref_node);
    this.removeChild(ref_node);
    return node;
  },

  cloneNode(deep) {
    return mutation.cloneNode(this, deep);
  },

  getRootNode(options) {
    return mutation.getRootNode(this, options);
  },

  get isConnected() {
    return document.documentElement.contains(this)
  }

};

// NOTE: For some reason `Text` redefines `assignedSlot`
let textMixin = {
  get assignedSlot() {
    return getAssignedSlot(this);
  }
};

let fragmentMixin = {

  // TODO(sorvell): consider doing native QSA and filtering results.
  querySelector(selector) {
    // match selector and halt on first result.
    let result = mutation.query(this, function(n) {
      return utils.matchesSelector(n, selector);
    }, function(n) {
      return Boolean(n);
    })[0];
    return result || null;
  },

  querySelectorAll(selector) {
    return mutation.query(this, function(n) {
      return utils.matchesSelector(n, selector);
    });
  }

};

let slotMixin = {

  assignedNodes(options) {
    if (this.localName === 'slot') {
      mutation.renderRootNode(this);
      return this.__shady ?
        ((options && options.flatten ? this.__shady.distributedNodes :
        this.__shady.assignedNodes) || []) :
        [];
    }
  }

};

let elementMixin = utils.extendAll({

  setAttribute(name, value) {
    mutation.setAttribute(this, name, value);
  },

  removeAttribute(name) {
    mutation.removeAttribute(this, name);
  },

  attachShadow(options) {
    return attachShadow(this, options);
  },

  get slot() {
    return this.getAttribute('slot');
  },

  set slot(value) {
    this.setAttribute('slot', value);
  },

  get assignedSlot() {
    return getAssignedSlot(this);
  }

}, fragmentMixin, slotMixin);

Object.defineProperties(elementMixin, ShadowRootAccessor);

let documentMixin = utils.extendAll({

}, fragmentMixin);

Object.defineProperties(documentMixin, {
  _activeElement: ActiveElementAccessor.activeElement
});

function patchBuiltin(proto, obj) {
  let n$ = Object.getOwnPropertyNames(obj);
  for (let i=0; i < n$.length; i++) {
    let n = n$[i];
    let d = Object.getOwnPropertyDescriptor(obj, n);
    // NOTE: we prefer writing directly here because some browsers
    // have descriptors that are writable but not configurable (e.g.
    // `appendChild` on older browsers)
    if (d.value) {
      proto[n] = d.value;
    } else {
      Object.defineProperty(proto, n, d);
    }
  }
}

// Apply patches to builtins (e.g. Element.prototype). Some of these patches
// can be done unconditionally (mostly methods like
// `Element.prototype.appendChild`) and some can only be done when the browser
// has proper descriptors on the builtin prototype
// (e.g. `Element.prototype.firstChild`)`. When descriptors are not available,
// elements are individually patched when needed.
export function patchBuiltins() {
  // These patches can always be done, for all supported browsers.
  patchBuiltin(window.Node.prototype, nodeMixin);
  patchBuiltin(window.Text.prototype, textMixin);
  patchBuiltin(window.DocumentFragment.prototype, fragmentMixin);
  patchBuiltin(window.Element.prototype, elementMixin);
  patchBuiltin(window.Document.prototype, documentMixin);
  // patch this only on the instance because (1) main document is only
  // one we care about; (2) better compatibility with other polyfills
  // that may also patch the instance (e.g. CE)
  let previousImportNode = document.importNode;
  document.importNode = function(node, deep) {
    return mutation.importNode(node, deep, previousImportNode);
  }
  if (window.HTMLSlotElement) {
    patchBuiltin(window.HTMLSlotElement.prototype, slotMixin);
  }
  // These patches can *only* be done
  // on browsers that have proper property descriptors on builtin prototypes.
  // This includes: IE11, Edge, Chrome >= 4?; Safari >= 10, Firefox
  // On older browsers (Chrome <= 4?, Safari 9), a per element patching
  // strategy is used for patching accessors.
  if (utils.settings.hasDescriptors) {
    patchAccessors(window.Node.prototype);
    patchAccessors(window.Text.prototype);
    patchAccessors(window.DocumentFragment.prototype);
    patchAccessors(window.Element.prototype);
    let nativeHTMLElement =
      (window.customElements && customElements.nativeHTMLElement) ||
      HTMLElement;
    patchAccessors(nativeHTMLElement.prototype);
    patchAccessors(window.Document.prototype);
    if (window.HTMLSlotElement) {
      patchAccessors(window.HTMLSlotElement.prototype);
    }
  }
}<commit_msg>improve comment.<commit_after>/**
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

'use strict';

import * as utils from './utils'
import * as mutation from './logical-mutation'
import {ActiveElementAccessor, ShadowRootAccessor, patchAccessors} from './patch-accessors'
import {getProperty} from './logical-properties'
import {addEventListener, removeEventListener} from './patch-events'
import {attachShadow} from './attach-shadow'

function getAssignedSlot(node) {
  mutation.renderRootNode(node);
  return getProperty(node, 'assignedSlot') || null;
}

let nodeMixin = {

  addEventListener: addEventListener,

  removeEventListener: removeEventListener,

  appendChild(node) {
    return mutation.insertBefore(this, node);
  },

  insertBefore(node, ref_node) {
    return mutation.insertBefore(this, node, ref_node);
  },

  removeChild(node) {
    return mutation.removeChild(this, node);
  },

  replaceChild(node, ref_node) {
    this.insertBefore(node, ref_node);
    this.removeChild(ref_node);
    return node;
  },

  cloneNode(deep) {
    return mutation.cloneNode(this, deep);
  },

  getRootNode(options) {
    return mutation.getRootNode(this, options);
  },

  get isConnected() {
    return document.documentElement.contains(this)
  }

};

// NOTE: For some reason `Text` redefines `assignedSlot`
let textMixin = {
  get assignedSlot() {
    return getAssignedSlot(this);
  }
};

let fragmentMixin = {

  // TODO(sorvell): consider doing native QSA and filtering results.
  querySelector(selector) {
    // match selector and halt on first result.
    let result = mutation.query(this, function(n) {
      return utils.matchesSelector(n, selector);
    }, function(n) {
      return Boolean(n);
    })[0];
    return result || null;
  },

  querySelectorAll(selector) {
    return mutation.query(this, function(n) {
      return utils.matchesSelector(n, selector);
    });
  }

};

let slotMixin = {

  assignedNodes(options) {
    if (this.localName === 'slot') {
      mutation.renderRootNode(this);
      return this.__shady ?
        ((options && options.flatten ? this.__shady.distributedNodes :
        this.__shady.assignedNodes) || []) :
        [];
    }
  }

};

let elementMixin = utils.extendAll({

  setAttribute(name, value) {
    mutation.setAttribute(this, name, value);
  },

  removeAttribute(name) {
    mutation.removeAttribute(this, name);
  },

  attachShadow(options) {
    return attachShadow(this, options);
  },

  get slot() {
    return this.getAttribute('slot');
  },

  set slot(value) {
    this.setAttribute('slot', value);
  },

  get assignedSlot() {
    return getAssignedSlot(this);
  }

}, fragmentMixin, slotMixin);

Object.defineProperties(elementMixin, ShadowRootAccessor);

let documentMixin = utils.extendAll({

}, fragmentMixin);

Object.defineProperties(documentMixin, {
  _activeElement: ActiveElementAccessor.activeElement
});

function patchBuiltin(proto, obj) {
  let n$ = Object.getOwnPropertyNames(obj);
  for (let i=0; i < n$.length; i++) {
    let n = n$[i];
    let d = Object.getOwnPropertyDescriptor(obj, n);
    // NOTE: we prefer writing directly here because some browsers
    // have descriptors that are writable but not configurable (e.g.
    // `appendChild` on older browsers)
    if (d.value) {
      proto[n] = d.value;
    } else {
      Object.defineProperty(proto, n, d);
    }
  }
}

// Apply patches to builtins (e.g. Element.prototype). Some of these patches
// can be done unconditionally (mostly methods like
// `Element.prototype.appendChild`) and some can only be done when the browser
// has proper descriptors on the builtin prototype
// (e.g. `Element.prototype.firstChild`)`. When descriptors are not available,
// elements are individually patched when needed (see e.g.
// `patchInside/OutsideElementAccessors` in `patch-accessors.js`).
export function patchBuiltins() {
  // These patches can always be done, for all supported browsers.
  patchBuiltin(window.Node.prototype, nodeMixin);
  patchBuiltin(window.Text.prototype, textMixin);
  patchBuiltin(window.DocumentFragment.prototype, fragmentMixin);
  patchBuiltin(window.Element.prototype, elementMixin);
  patchBuiltin(window.Document.prototype, documentMixin);
  // patch this only on the instance because (1) main document is only
  // one we care about; (2) better compatibility with other polyfills
  // that may also patch the instance (e.g. CE)
  let previousImportNode = document.importNode;
  document.importNode = function(node, deep) {
    return mutation.importNode(node, deep, previousImportNode);
  }
  if (window.HTMLSlotElement) {
    patchBuiltin(window.HTMLSlotElement.prototype, slotMixin);
  }
  // These patches can *only* be done
  // on browsers that have proper property descriptors on builtin prototypes.
  // This includes: IE11, Edge, Chrome >= 4?; Safari >= 10, Firefox
  // On older browsers (Chrome <= 4?, Safari 9), a per element patching
  // strategy is used for patching accessors.
  if (utils.settings.hasDescriptors) {
    patchAccessors(window.Node.prototype);
    patchAccessors(window.Text.prototype);
    patchAccessors(window.DocumentFragment.prototype);
    patchAccessors(window.Element.prototype);
    let nativeHTMLElement =
      (window.customElements && customElements.nativeHTMLElement) ||
      HTMLElement;
    patchAccessors(nativeHTMLElement.prototype);
    patchAccessors(window.Document.prototype);
    if (window.HTMLSlotElement) {
      patchAccessors(window.HTMLSlotElement.prototype);
    }
  }
}<|endoftext|>


<commit_before>fb_app = {
  current_url: '',

  locales: {

  },

  config: {
    url_prefix: '',
    save_auth_url: '',
    show_login_url: '',

    init: function() {

    },

  },

  timeline: {
    app_id: '',
    //app_scope: 'publish_actions',
    app_scope: '',

    loading: function() {
      jQuery('#fb-app-connect-status').empty().addClass('loading').height(150)
    },

    connect: function() {
      this.loading();
      fb_app.fb.scope = this.app_scope
      //fb_app.fb.init(this.app_id, 'fb_app.fb.connect()')
      fb_app.fb.connect(function (response) {
        fb_app.auth.receive(response)
      });
    },

    disconnect: function() {
      this.loading();
      fb_app.auth.receive({status: 'not_authorized'})
    },

    connect_to_another: function() {
      this.disconnect();
      fb_app.fb.connect_to_another(this.connect)
    },
  },

  page_tab: {
    app_id: '',
    next_url: '',

    init: function() {
    },

    config: {

      init: function() {
        this.change_type($('select#page_tab_config_type'))

      },

      edit: function(button) {
        var page_tab = button.parents('.page-tab')
        page_tab.find('form').toggle(400)
      },

      remove: function(button, url) {
        var page_tab = button.parents('.page-tab')
        var name = page_tab.find('#page_tab_name').val()
        jQuery('.modal-button-yes')
          .attr('target_url',url)
          .attr('target_id','#'+page_tab.attr('id'))
        //jQuery('#fb-app-modal-catalog-name').text(name)
        noosfero.modal.html(jQuery('#fb-app-modal-wrap').html())
      },

      remove_confirmed: function(el) {
        el = jQuery(el)
        jQuery.post(el.attr('target_url'), function() {
          var page_tab = jQuery(el.attr('target_id'))
          page_tab.remove()
        })
      },

      close: function(evt) {
       if (evt != null && evt != void 0) { evt.preventDefault(); evt.stopPropagation();}
        noosfero.modal.close()
        jQuery('#content').html('').addClass('loading')
        window.location.href = fb_app.current_url
      },

      validate: function(form) {
        for (var i=0; tinymce.editors[i]; i++) {
          var editor = tinymce.editors[i]
          var textarea = editor.getElement()
          textarea.value = editor.getContent()
        }

        if (form.find('#page_tab_title').val().trim()=='') {
          noosfero.modal.html('
'+fb_app.locales.error_empty_title+'
')
          return false
        } else {
          var selected_type = form.find('#page_tab_config_type').val()
          var sub_option = form.find('.config-type-'+selected_type+' input')
          if (sub_option.length > 0 && sub_option.val().trim()=='') {
            noosfero.modal.html('
'+fb_app.locales.error_empty_settings+'
')
            return false
          }
        }
        return true
      },

      add: function (form) {
        if (!this.validate(form))
          return false
        // this checks if the user is using FB as a page and offer a switch
        FB.login(function(response) {
          if (response.status != 'connected') return
          var next_url = fb_app.page_tab.next_url + '?' + form.serialize()
          window.location.href = fb_app.fb.add_tab_url(fb_app.page_tab.app_id, next_url)
        })
        return false
      },

      save: function(form) {
        if (!this.validate(form))
          return false
        jQuery(form).ajaxSubmit({
          dataType: 'script',
        })
        return false
      },

      change_type: function(select) {
        select = jQuery(select)
        var page_tab = select.parents('.page-tab')
        var config_selector = '.config-type-'+select.val()
        var config = page_tab.find(config_selector)
        var to_show = config
        var to_hide = page_tab.find('.config-type:not('+config_selector+')')

        to_show.show().
          find('input').prop('disabled', false)
        to_show.find('.tokenfield').removeClass('disabled')
        to_hide.hide().
          find('input').prop('disabled', true)
      },

      profile: {

        onchange: function(input) {
          if (input.val())
            input.removeAttr('placeholder')
          else
            input.attr('placeholder', input.attr('data-placeholder'))
        },
      },
    },

  },

  auth: {
    status: 'not_authorized',

    load: function (html) {
      jQuery('#fb-app-settings').html(html)
    },
    loadLogin: function (html) {
      if (this.status == 'not_authorized')
        jQuery('#fb-app-connect').html(html).removeClass('loading')
      else
        jQuery('#fb-app-login').html(html)
    },

    receive: function(response) {
      fb_app.fb.authResponse = response
      fb_app.auth.save(response)
    },

    transformParams: function(response) {
      var authResponse = response.authResponse
      if (!authResponse)
        return {auth: {status: response.status}}
      else
        return {
          auth: {
            status: response.status,
            access_token: authResponse.accessToken,
            expires_in: authResponse.expiresIn,
            signed_request: authResponse.signedRequest,
            provider_user_id: authResponse.userID,
          }
        }
    },

    showLogin: function(response) {
      jQuery.get(fb_app.config.show_login_url, this.transformParams(response), this.loadLogin)
    },

    save: function(response) {
      jQuery.post(fb_app.config.save_auth_url, this.transformParams(response), this.load)
    },
  },

  fb: {
    id: '',
    scope: '',

    init: function(app_id, asyncInit) {

      window.fbAsyncInit = function() {
        FB.init({
          appId: app_id,
          status: true,
          cookie: true,
          xfbml: true
        })

        fb_app.fb.size_change()
        jQuery(document).on('DOMNodeInserted', fb_app.fb.size_change)

        if (asyncInit)
          jQuery.globalEval(asyncInit)
      }
    },

    size_change: function() {
      FB.Canvas.setSize({height: jQuery('body').height()+100})
    },

    redirect_to_tab: function(pageID) {
      FB.api('/'+pageID, function(response) {
        window.location.href = response.link + '?sk=app_' + fb_app.fb.id
      })
    },

    add_tab_url: function (app_id, next_url) {
      return 'https://www.facebook.com/dialog/pagetab?' + jQuery.param({app_id: app_id, next: next_url})
    },

    connect: function(callback) {
      FB.login(function(response) {
        if (callback) callback(response)
      }, {scope: fb_app.fb.scope})
    },

    connect_to_another: function(callback) {
      this.logout(this.connect(callback))
    },

    logout: function(callback) {
      // this checks if the user is using FB as a page and offer a switch
      FB.login(function(response) {
        FB.logout(function(response) {
          if (callback) callback(response)
        })
      })
    },

    // not to be used
    delete: function(callback) {
      FB.api("/me/permissions", "DELETE", function(response) {
        if (callback) callback(response)
      })
    },

    checkLoginStatus: function() {
      FB.getLoginStatus(function(response) {
        // don't do nothing, this is just to fetch auth after init
      })
    },

  },

}

<commit_msg>scroll to top...<commit_after>fb_app = {
  current_url: '',

  locales: {

  },

  config: {
    url_prefix: '',
    save_auth_url: '',
    show_login_url: '',

    init: function() {

    },

  },

  timeline: {
    app_id: '',
    //app_scope: 'publish_actions',
    app_scope: '',

    loading: function() {
      jQuery('#fb-app-connect-status').empty().addClass('loading').height(150)
    },

    connect: function() {
      this.loading();
      fb_app.fb.scope = this.app_scope
      //fb_app.fb.init(this.app_id, 'fb_app.fb.connect()')
      fb_app.fb.connect(function (response) {
        fb_app.auth.receive(response)
      });
    },

    disconnect: function() {
      this.loading();
      fb_app.auth.receive({status: 'not_authorized'})
    },

    connect_to_another: function() {
      this.disconnect();
      fb_app.fb.connect_to_another(this.connect)
    },
  },

  page_tab: {
    app_id: '',
    next_url: '',

    init: function() {
      jQuery('html').scrollTop();
    },

    config: {

      init: function() {
        this.change_type($('select#page_tab_config_type'))

      },

      edit: function(button) {
        var page_tab = button.parents('.page-tab')
        page_tab.find('form').toggle(400)
      },

      remove: function(button, url) {
        var page_tab = button.parents('.page-tab')
        var name = page_tab.find('#page_tab_name').val()
        jQuery('.modal-button-yes')
          .attr('target_url',url)
          .attr('target_id','#'+page_tab.attr('id'))
        //jQuery('#fb-app-modal-catalog-name').text(name)
        noosfero.modal.html(jQuery('#fb-app-modal-wrap').html())
      },

      remove_confirmed: function(el) {
        el = jQuery(el)
        jQuery.post(el.attr('target_url'), function() {
          var page_tab = jQuery(el.attr('target_id'))
          page_tab.remove()
        })
      },

      close: function(evt) {
       if (evt != null && evt != void 0) { evt.preventDefault(); evt.stopPropagation();}
        noosfero.modal.close()
        jQuery('#content').html('').addClass('loading')
        window.location.href = fb_app.current_url
      },

      validate: function(form) {
        for (var i=0; tinymce.editors[i]; i++) {
          var editor = tinymce.editors[i]
          var textarea = editor.getElement()
          textarea.value = editor.getContent()
        }

        if (form.find('#page_tab_title').val().trim()=='') {
          noosfero.modal.html('
'+fb_app.locales.error_empty_title+'
')
          return false
        } else {
          var selected_type = form.find('#page_tab_config_type').val()
          var sub_option = form.find('.config-type-'+selected_type+' input')
          if (sub_option.length > 0 && sub_option.val().trim()=='') {
            noosfero.modal.html('
'+fb_app.locales.error_empty_settings+'
')
            return false
          }
        }
        return true
      },

      add: function (form) {
        if (!this.validate(form))
          return false
        // this checks if the user is using FB as a page and offer a switch
        FB.login(function(response) {
          if (response.status != 'connected') return
          var next_url = fb_app.page_tab.next_url + '?' + form.serialize()
          window.location.href = fb_app.fb.add_tab_url(fb_app.page_tab.app_id, next_url)
        })
        return false
      },

      save: function(form) {
        if (!this.validate(form))
          return false
        jQuery(form).ajaxSubmit({
          dataType: 'script',
        })
        return false
      },

      change_type: function(select) {
        select = jQuery(select)
        var page_tab = select.parents('.page-tab')
        var config_selector = '.config-type-'+select.val()
        var config = page_tab.find(config_selector)
        var to_show = config
        var to_hide = page_tab.find('.config-type:not('+config_selector+')')

        to_show.show().
          find('input').prop('disabled', false)
        to_show.find('.tokenfield').removeClass('disabled')
        to_hide.hide().
          find('input').prop('disabled', true)
      },

      profile: {

        onchange: function(input) {
          if (input.val())
            input.removeAttr('placeholder')
          else
            input.attr('placeholder', input.attr('data-placeholder'))
        },
      },
    },

  },

  auth: {
    status: 'not_authorized',

    load: function (html) {
      jQuery('#fb-app-settings').html(html)
    },
    loadLogin: function (html) {
      if (this.status == 'not_authorized')
        jQuery('#fb-app-connect').html(html).removeClass('loading')
      else
        jQuery('#fb-app-login').html(html)
    },

    receive: function(response) {
      fb_app.fb.authResponse = response
      fb_app.auth.save(response)
    },

    transformParams: function(response) {
      var authResponse = response.authResponse
      if (!authResponse)
        return {auth: {status: response.status}}
      else
        return {
          auth: {
            status: response.status,
            access_token: authResponse.accessToken,
            expires_in: authResponse.expiresIn,
            signed_request: authResponse.signedRequest,
            provider_user_id: authResponse.userID,
          }
        }
    },

    showLogin: function(response) {
      jQuery.get(fb_app.config.show_login_url, this.transformParams(response), this.loadLogin)
    },

    save: function(response) {
      jQuery.post(fb_app.config.save_auth_url, this.transformParams(response), this.load)
    },
  },

  fb: {
    id: '',
    scope: '',

    init: function(app_id, asyncInit) {

      window.fbAsyncInit = function() {
        FB.init({
          appId: app_id,
          status: true,
          cookie: true,
          xfbml: true
        })

        fb_app.fb.size_change()
        jQuery(document).on('DOMNodeInserted', fb_app.fb.size_change)

        if (asyncInit)
          jQuery.globalEval(asyncInit)
      }
    },

    size_change: function() {
      FB.Canvas.setSize({height: jQuery('body').height()+100})
    },

    redirect_to_tab: function(pageID) {
      FB.api('/'+pageID, function(response) {
        window.location.href = response.link + '?sk=app_' + fb_app.fb.id
      })
    },

    add_tab_url: function (app_id, next_url) {
      return 'https://www.facebook.com/dialog/pagetab?' + jQuery.param({app_id: app_id, next: next_url})
    },

    connect: function(callback) {
      FB.login(function(response) {
        if (callback) callback(response)
      }, {scope: fb_app.fb.scope})
    },

    connect_to_another: function(callback) {
      this.logout(this.connect(callback))
    },

    logout: function(callback) {
      // this checks if the user is using FB as a page and offer a switch
      FB.login(function(response) {
        FB.logout(function(response) {
          if (callback) callback(response)
        })
      })
    },

    // not to be used
    delete: function(callback) {
      FB.api("/me/permissions", "DELETE", function(response) {
        if (callback) callback(response)
      })
    },

    checkLoginStatus: function() {
      FB.getLoginStatus(function(response) {
        // don't do nothing, this is just to fetch auth after init
      })
    },

  },

}

<|endoftext|>