<commit_before>/*
 * Copyright 2012 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is goverened by a BSD-style
 * license that can be found in the LICENSE file.
 */

suite('Shadow DOM rerender', function() {

  function getVisualInnerHtml(el) {
    return HTMLElement_prototype.innerHTML.get.call(el);
  }

  test('No <content> nor <shadow>', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.textContent = 'text';
    var textNode = shadowRoot.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('text');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalTextNodeWrapper = logical.getWrapper(textNode);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalTextNodeWrapper,
        lastChild: logicalTextNodeWrapper
      });

      expectStructure(logicalTextNodeWrapper, {
        parentNode: logicalShadowRootWrapper
      });
    }

    testRender();
    testRender();
  });

test('<content>', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.innerHTML = '<content></content>';
    var content = shadowRoot.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalContentWrapper = logical.getWrapper(content);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalContentWrapper,
        lastChild: logicalContentWrapper
      });

      expectStructure(logicalContentWrapper, {
        parentNode: logicalShadowRootWrapper
      });
    }

    testRender();
    testRender();
  });

  test('<content> with fallback', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.innerHTML = '<content select="b">fallback</content>';
    var content = shadowRoot.firstChild;
    var fallback = content.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalContentWrapper = logical.getWrapper(content);
      var logicalFallbackWrapper = logical.getWrapper(fallback);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalContentWrapper,
        lastChild: logicalContentWrapper
      });

      expectStructure(logicalContentWrapper, {
        parentNode: logicalShadowRootWrapper,
        firstChild: logicalFallbackWrapper,
        lastChild: logicalFallbackWrapper
      });

      expectStructure(logicalFallbackWrapper, {
        parentNode: logicalContentWrapper
      });
    }

    testRender();
    testRender();
  });

test('<shadow>', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.innerHTML = '<shadow></shadow>';
    var shadow = shadowRoot.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalShadowWrapper = logical.getWrapper(shadow);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalShadowWrapper,
        lastChild: logicalShadowWrapper
      });

      expectStructure(logicalShadowWrapper, {
        parentNode: logicalShadowRootWrapper
      });
    }

    testRender();
    testRender();
  });

  test('<shadow> with fallback', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.innerHTML = '<shadow>fallback</shadow>';
    var shadow = shadowRoot.firstChild;
    var fallback = shadow.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalShadowWrapper = logical.getWrapper(shadow);
      var logicalFallbackWrapper = logical.getWrapper(fallback);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalShadowWrapper,
        lastChild: logicalShadowWrapper
      });

      expectStructure(logicalShadowWrapper, {
        parentNode: logicalShadowRootWrapper,
        firstChild: logicalFallbackWrapper,
        lastChild: logicalFallbackWrapper
      });

      expectStructure(logicalFallbackWrapper, {
        parentNode: logicalShadowWrapper
      });
    }

    testRender();
    testRender();
  });

  test('<shadow> with nested shadow roots', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var oldestShadowRoot = new JsShadowRoot(host);
    oldestShadowRoot.textContent = 'text';
    var textNode = oldestShadowRoot.firstChild;

    var youngestShadowRoot = new JsShadowRoot(host);
    youngestShadowRoot.innerHTML = '<shadow></shadow>';
    var shadow = youngestShadowRoot.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('text');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalOldestShadowRootWrapper = logical.getWrapper(oldestShadowRoot);
      var logicalTextNodeWrapper = logical.getWrapper(textNode);
      var logicalYoungestShadowRootWrapper =
          logical.getWrapper(youngestShadowRoot);
      var logicalShadowWrapper = logical.getWrapper(shadow);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalOldestShadowRootWrapper, {
        firstChild: logicalTextNodeWrapper,
        lastChild: logicalTextNodeWrapper
      });

      expectStructure(logicalTextNodeWrapper, {
        parentNode: logicalOldestShadowRootWrapper
      });

      expectStructure(logicalYoungestShadowRootWrapper, {
        firstChild: logicalShadowWrapper,
        lastChild: logicalShadowWrapper
      });

      expectStructure(logicalShadowWrapper, {
        parentNode: logicalYoungestShadowRootWrapper
      });
    }

    testRender();
    testRender();
  });

  suite('Mutate logical DOM', function() {
    test('removeAllChildNodes - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content>fallback</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeAllChildNodes(logical.getFirstChild(host));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeAllChildNodes(host);
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');
    });

    test('removeAllChildNodes - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>after';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Helloafter');

      logical.removeAllChildNodes(logical.getLastChild(shadowRoot));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeAllChildNodes(shadowRoot);
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');
    });

    test('removeAllChildNodes - mutate shadow fallback', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content select="xxx">fallback</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');

      logical.removeAllChildNodes(logical.getFirstChild(logical.getFirstChild(shadowRoot)));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeAllChildNodes(logical.getFirstChild(shadowRoot));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeAllChildNodes(shadowRoot);
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');
    });

    test('removeChild - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content>fallback</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeChild(logical.getFirstChild(host),
          logical.getFirstChild(logical.getFirstChild(host)));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeChild(host, logical.getFirstChild(host));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');
    });

    test('removeChild - mutate host 2', function() {
      var host = document.createElement('div');
      host.innerHTML = '';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content>fallback</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeChild(host, logical.getLastChild(host));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeChild(host, logical.getFirstChild(host));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');
    });

    test('removeChild - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>after';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Helloafter');

      logical.removeChild(logical.getLastChild(shadowRoot),
        logical.getFirstChild(logical.getLastChild(shadowRoot)));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeChild(shadowRoot, logical.getLastChild(shadowRoot));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeChild(shadowRoot, logical.getFirstChild(shadowRoot));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');
    });

    test('setAttribute select', function() {
      // TODO(arv): DOM bindings for select.
      var host = document.createElement('div');
      host.innerHTML = 'HelloWorld';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content select="b">fallback b</content>' +
                             '<content select="a">fallback a</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('WorldHello');

      logical.getFirstChild(shadowRoot).setAttribute('select', 'xxx');

      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback bHello');

      logical.getFirstChild(shadowRoot).setAttribute('select', '');

      render(host);
      expect(getVisualInnerHtml(host)).to.be('HelloWorldfallback a');
    });

    test('appendChild - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.appendChild(host, b);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');
    });

    test('appendChild - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.appendChild(shadowRoot, b);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');
    });

    test('insertBefore - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';
      var a = host.firstChild;

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.insertBefore(host, b, a);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');
    });

    test('insertBefore - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';
      var content = shadowRoot.firstChild;

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.insertBefore(shadowRoot, b, content);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');
    });

    test('replaceChild - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';
      var a = host.firstChild;

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';

      render(host);
      expect(host.innerHTML).to.be('Hello');

      var b = document.createElement('b');
      logical.replaceChild(host, b, a);

      render(host);
      expect(host.innerHTML).to.be('');
    });

    test('replaceChild - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';
      var content = shadowRoot.firstChild;

      render(host);
      expect(host.innerHTML).to.be('Hello');

      var b = document.createElement('b');
      logical.replaceChild(shadowRoot, b, content);

      render(host);
      expect(host.innerHTML).to.be('');
    });

  });
});<commit_msg>Fix test to use getVisualInnerHtml<commit_after>/*
 * Copyright 2012 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is goverened by a BSD-style
 * license that can be found in the LICENSE file.
 */

suite('Shadow DOM rerender', function() {

  function getVisualInnerHtml(el) {
    return HTMLElement_prototype.innerHTML.get.call(el);
  }

  test('No <content> nor <shadow>', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.textContent = 'text';
    var textNode = shadowRoot.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('text');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalTextNodeWrapper = logical.getWrapper(textNode);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalTextNodeWrapper,
        lastChild: logicalTextNodeWrapper
      });

      expectStructure(logicalTextNodeWrapper, {
        parentNode: logicalShadowRootWrapper
      });
    }

    testRender();
    testRender();
  });

test('<content>', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.innerHTML = '<content></content>';
    var content = shadowRoot.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalContentWrapper = logical.getWrapper(content);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalContentWrapper,
        lastChild: logicalContentWrapper
      });

      expectStructure(logicalContentWrapper, {
        parentNode: logicalShadowRootWrapper
      });
    }

    testRender();
    testRender();
  });

  test('<content> with fallback', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.innerHTML = '<content select="b">fallback</content>';
    var content = shadowRoot.firstChild;
    var fallback = content.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalContentWrapper = logical.getWrapper(content);
      var logicalFallbackWrapper = logical.getWrapper(fallback);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalContentWrapper,
        lastChild: logicalContentWrapper
      });

      expectStructure(logicalContentWrapper, {
        parentNode: logicalShadowRootWrapper,
        firstChild: logicalFallbackWrapper,
        lastChild: logicalFallbackWrapper
      });

      expectStructure(logicalFallbackWrapper, {
        parentNode: logicalContentWrapper
      });
    }

    testRender();
    testRender();
  });

test('<shadow>', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.innerHTML = '<shadow></shadow>';
    var shadow = shadowRoot.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalShadowWrapper = logical.getWrapper(shadow);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalShadowWrapper,
        lastChild: logicalShadowWrapper
      });

      expectStructure(logicalShadowWrapper, {
        parentNode: logicalShadowRootWrapper
      });
    }

    testRender();
    testRender();
  });

  test('<shadow> with fallback', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var shadowRoot = new JsShadowRoot(host);
    shadowRoot.innerHTML = '<shadow>fallback</shadow>';
    var shadow = shadowRoot.firstChild;
    var fallback = shadow.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalShadowRootWrapper = logical.getWrapper(shadowRoot);
      var logicalShadowWrapper = logical.getWrapper(shadow);
      var logicalFallbackWrapper = logical.getWrapper(fallback);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalShadowRootWrapper, {
        firstChild: logicalShadowWrapper,
        lastChild: logicalShadowWrapper
      });

      expectStructure(logicalShadowWrapper, {
        parentNode: logicalShadowRootWrapper,
        firstChild: logicalFallbackWrapper,
        lastChild: logicalFallbackWrapper
      });

      expectStructure(logicalFallbackWrapper, {
        parentNode: logicalShadowWrapper
      });
    }

    testRender();
    testRender();
  });

  test('<shadow> with nested shadow roots', function() {
    var host = document.createElement('div');
    host.innerHTML = '';
    var a = host.firstChild;

    var oldestShadowRoot = new JsShadowRoot(host);
    oldestShadowRoot.textContent = 'text';
    var textNode = oldestShadowRoot.firstChild;

    var youngestShadowRoot = new JsShadowRoot(host);
    youngestShadowRoot.innerHTML = '<shadow></shadow>';
    var shadow = youngestShadowRoot.firstChild;

    function testRender() {
      render(host);
      expect(getVisualInnerHtml(host)).to.be('text');

      var logicalHostWrapper = logical.getWrapper(host);
      var logicalAWrapper = logical.getWrapper(a);
      var logicalOldestShadowRootWrapper = logical.getWrapper(oldestShadowRoot);
      var logicalTextNodeWrapper = logical.getWrapper(textNode);
      var logicalYoungestShadowRootWrapper =
          logical.getWrapper(youngestShadowRoot);
      var logicalShadowWrapper = logical.getWrapper(shadow);

      expectStructure(logicalHostWrapper, {
        firstChild: logicalAWrapper,
        lastChild: logicalAWrapper
      });

      expectStructure(logicalAWrapper, {
        parentNode: logicalHostWrapper
      });

      expectStructure(logicalOldestShadowRootWrapper, {
        firstChild: logicalTextNodeWrapper,
        lastChild: logicalTextNodeWrapper
      });

      expectStructure(logicalTextNodeWrapper, {
        parentNode: logicalOldestShadowRootWrapper
      });

      expectStructure(logicalYoungestShadowRootWrapper, {
        firstChild: logicalShadowWrapper,
        lastChild: logicalShadowWrapper
      });

      expectStructure(logicalShadowWrapper, {
        parentNode: logicalYoungestShadowRootWrapper
      });
    }

    testRender();
    testRender();
  });

  suite('Mutate logical DOM', function() {
    test('removeAllChildNodes - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content>fallback</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeAllChildNodes(logical.getFirstChild(host));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeAllChildNodes(host);
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');
    });

    test('removeAllChildNodes - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>after';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Helloafter');

      logical.removeAllChildNodes(logical.getLastChild(shadowRoot));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeAllChildNodes(shadowRoot);
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');
    });

    test('removeAllChildNodes - mutate shadow fallback', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content select="xxx">fallback</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');

      logical.removeAllChildNodes(logical.getFirstChild(logical.getFirstChild(shadowRoot)));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeAllChildNodes(logical.getFirstChild(shadowRoot));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeAllChildNodes(shadowRoot);
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');
    });

    test('removeChild - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content>fallback</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeChild(logical.getFirstChild(host),
          logical.getFirstChild(logical.getFirstChild(host)));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeChild(host, logical.getFirstChild(host));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');
    });

    test('removeChild - mutate host 2', function() {
      var host = document.createElement('div');
      host.innerHTML = '';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content>fallback</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeChild(host, logical.getLastChild(host));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');

      logical.removeChild(host, logical.getFirstChild(host));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback');
    });

    test('removeChild - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>after';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Helloafter');

      logical.removeChild(logical.getLastChild(shadowRoot),
        logical.getFirstChild(logical.getLastChild(shadowRoot)));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeChild(shadowRoot, logical.getLastChild(shadowRoot));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      logical.removeChild(shadowRoot, logical.getFirstChild(shadowRoot));
      render(host);
      expect(getVisualInnerHtml(host)).to.be('');
    });

    test('setAttribute select', function() {
      // TODO(arv): DOM bindings for select.
      var host = document.createElement('div');
      host.innerHTML = 'HelloWorld';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content select="b">fallback b</content>' +
                             '<content select="a">fallback a</content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('WorldHello');

      logical.getFirstChild(shadowRoot).setAttribute('select', 'xxx');

      render(host);
      expect(getVisualInnerHtml(host)).to.be('fallback bHello');

      logical.getFirstChild(shadowRoot).setAttribute('select', '');

      render(host);
      expect(getVisualInnerHtml(host)).to.be('HelloWorldfallback a');
    });

    test('appendChild - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.appendChild(host, b);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');
    });

    test('appendChild - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.appendChild(shadowRoot, b);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');
    });

    test('insertBefore - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';
      var a = host.firstChild;

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.insertBefore(host, b, a);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');
    });

    test('insertBefore - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';
      var content = shadowRoot.firstChild;

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.insertBefore(shadowRoot, b, content);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');
    });

    test('replaceChild - mutate host', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';
      var a = host.firstChild;

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.replaceChild(host, b, a);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('');
    });

    test('replaceChild - mutate shadow', function() {
      var host = document.createElement('div');
      host.innerHTML = 'Hello';

      var shadowRoot = new JsShadowRoot(host);
      shadowRoot.innerHTML = '<content></content>';
      var content = shadowRoot.firstChild;

      render(host);
      expect(getVisualInnerHtml(host)).to.be('Hello');

      var b = document.createElement('b');
      logical.replaceChild(shadowRoot, b, content);

      render(host);
      expect(getVisualInnerHtml(host)).to.be('');
    });

  });
});<|endoftext|>


<commit_before>var App = function () {
  var drop = document.body;
  var convertRows = document.getElementsByClassName('convert-rows')[0];
  var dropPopup;

  function handleDragOver(e) {
    if (e.preventDefault) {
      e.preventDefault();
    }
    e.dataTransfer.dropEffect = 'copy';
  }

  function handleDragEnter() {
    if (dropPopup) {
      drop.appendChild(dropPopup)
    }
    else {
      dropPopup = document.createElement('div');
      dropPopup.className = 'drop-popup';
      dropPopup.innerHTML = 'Upload your photo';
      drop.appendChild(dropPopup);
    }
    dropPopup.addEventListener('dragleave', handleDragLeave, false);
  }

  function handleDragLeave() {
    drop.removeChild(dropPopup);

  }

  function handleDrop(e) {
    e.stopPropagation();
    e.preventDefault();

    var files = e.dataTransfer.files;
    for (var i = 0; i < files.length; i++) {
      if (/image/.test(files[i].type)) {
        var convertRow = new ConvertRow();
        convertRow.addImage(files[i]);
        convertRows.appendChild(convertRow.element);
      }
    }
    if (dropPopup) {
      drop.removeChild(dropPopup);
    }
    return false;
  }

  function handleFileSelect(e) {
    var files = e.target.files;
    console.log(files);
    if (!files[0].type.match('image.*')) {
      console.log('Image!!');
    }
    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function (theFile) {
      return function (e) {
        // Render thumbnail.
        var span = document.createElement('span');
        span.innerHTML = [''].join('');
        document.getElementById('drop').insertAfter(span, null);
      };
    })(f);

    // Read in the image file as a data URL.
    reader.readAsDataURL(files[0]);
  }

  drop.addEventListener('dragover', handleDragOver, false);
  drop.addEventListener('dragenter', handleDragEnter, false);
  drop.addEventListener('drop', handleDrop.bind(this), false);

};
<commit_msg>Add PopUp and remove.<commit_after>var App = function () {
  var drop = document.body;
  var convertRows = document.getElementsByClassName('convert-rows')[0];
  var dropPopup;

  function handleDragOver(e) {
    if (e.preventDefault) {
      e.preventDefault();
    }
    e.dataTransfer.dropEffect = 'copy';
  }

  function handleDragEnter() {
    if (dropPopup) {
      return;
    }
    dropPopup = document.createElement('div');
    dropPopup.addEventListener('dragleave', handleDragLeave, false);
    dropPopup.className = 'drop-popup';
    dropPopup.innerHTML = 'Upload your photo';
    drop.appendChild(dropPopup);
  }

  function handleDragLeave() {
    drop.removeChild(dropPopup);
    dropPopup = null;
  }

  function handleDrop(e) {
    e.stopPropagation();
    e.preventDefault();

    var files = e.dataTransfer.files;
    for (var i = 0; i < files.length; i++) {
      if (/image/.test(files[i].type)) {
        var convertRow = new ConvertRow();
        convertRow.addImage(files[i]);
        convertRows.appendChild(convertRow.element);
      }
    }
    if (dropPopup) {
      drop.removeChild(dropPopup);
      dropPopup = null;
    }
    return false;
  }

  function handleFileSelect(e) {
    var files = e.target.files;
    console.log(files);
    if (!files[0].type.match('image.*')) {
      console.log('Image!!');
    }
    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function (theFile) {
      return function (e) {
        // Render thumbnail.
        var span = document.createElement('span');
        span.innerHTML = [''].join('');
        document.getElementById('drop').insertAfter(span, null);
      };
    })(f);

    // Read in the image file as a data URL.
    reader.readAsDataURL(files[0]);
  }

  drop.addEventListener('dragover', handleDragOver, false);
  drop.addEventListener('dragenter', handleDragEnter, false);
  drop.addEventListener('drop', handleDrop.bind(this), false);

};
<|endoftext|>


<commit_before>function Triangle(p1, p2, p3) {
  this.p1 = p1;
  this.p2 = p2;
  this.p3 = p3;
}

Triangle.prototype.to3D = function(plane) {
  var p1 = this.p1, p2 = this.p2, p3 = this.p3;
  var ret = null;
  if(!plane) plane = 'xy';
  switch (plane) {
    case 'xy':
      ret = [
        new THREE.Vector3(p1.x, p1.y, 0),
        new THREE.Vector3(p2.x, p2.y, 0),
        new THREE.Vector3(p3.x, p3.y, 0)
      ];
      break;
    case 'yz':
      ret = [
        new THREE.Vector3(0, p1.x, p1.y),
        new THREE.Vector3(0, p2.x, p2.y),
        new THREE.Vector3(0, p3.x, p3.y)
      ];
    case 'zx':
      ret = [
        new THREE.Vector3(p1.y, 0, p1.x),
        new THREE.Vector3(p2.y, 0, p2.x),
        new THREE.Vector3(p3.y, 0, p3.x)
      ];
      break;
  }

  return ret;
}

Triangle.prototype.getMidTriangle = function() {
  var p1 = this.p1, p2 = this.p2, p3 = this.p3;
  var fnMid = function(p, q, axis) {
    var ret;
    if(axis === 'x') {
      return (p.x + q.x) / 2;
    }
    else {
      return (p.y + q.y) / 2;
    }
  };
  var
    s1 = {
      x: fnMid(p1, p2, 'x'),
      y: fnMid(p1, p2, 'y')
    },
    s2 = {
      x: fnMid(p2, p3, 'x'),
      y: fnMid(p2, p3, 'y')
    },
    s3 = {
      x: fnMid(p3, p1, 'x'),
      y: fnMid(p3, p1, 'y')
    };
  return new Triangle(s1, s2, s3);
}

Triangle.prototype.getSerpenskiTriangles = function() {
    var p1 = this.p1, p2 = this.p2, p3 = this.p3;
    var mt = this.getMidTriangle();
    var m1 = mt.p1, m2 = mt.p2, m3 = mt.p3;
    return [
      //triangle 1
      new Triangle(
        {
          x: p1.x, y: p1.y
        },
        {
          x: m1.x, y: m1.y
        },
        {
          x: m3.x, y: m3.y
        }
      ),
      //triangle 2
      new Triangle(
        {
          x: m1.x, y: m1.y
        },
        {
          x: p2.x, y: p2.y
        },
        {
          x: m2.x, y: m2.y
        }
      ),
      //triangle 3
      new Triangle(
        {
          x: m2.x, y: m2.y
        },
        {
          x: p3.x, y: p3.y
        },
        {
          x: m3.x, y: m3.y
        }
      )
    ];
};

Triangle.CreateEquilateral = function(side, offset) {
  var x = 0, y = 0;

  var makePoint = function() {
    return {
      x: x + (offset ? offset.x : 0),
      y: y + (offset ? offset.y : 0)
    };
  }
  var s1 = makePoint();

  x = side/2, y = side * Math.sqrt(3)/2;

  var s2 = makePoint();

  x = side, y = 0;

  var s3 = makePoint();

  return new Triangle(s1, s2, s3);
};

function onPageLoad() {
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(
    45,
    window.innerWidth/window.innerHeight,
    1,
    500
  );
  var renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
  var m1 = new THREE.LineBasicMaterial({ color: 0x0000ff }),
    m2 = new THREE.LineBasicMaterial({ color: 0xff0000 }),
    m3 = new THREE.LineBasicMaterial({ color: 0x00ff00 });
  var g1 = new THREE.Geometry();
  var origin = new THREE.Vector3(0,0,0);
  g1.vertices.push(
    origin,
    new THREE.Vector3(0, 10, 0),
    new THREE.Vector3(0, 20, 0)
  );

  var g2 = new THREE.Geometry();
  g2.vertices.push(
    origin,
    new THREE.Vector3(10, 0, 0),
    new THREE.Vector3(20, 0, 0)
  );

  var g3 = new THREE.Geometry();
  g3.vertices.push(
    origin,
    new THREE.Vector3(0,0, 10),
    new THREE.Vector3(0,0, 20)
  );

  var
    liney = new THREE.Line(g1, m1),
    linex = new THREE.Line(g2, m2),
    linez = new THREE.Line(g3, m3);
  scene.add(liney, linex, linez);
  camera.position.set(-30,30,-30);
  camera.lookAt(new THREE.Vector3(0,10,0));

  var matLine = new THREE.LineBasicMaterial({ color: 0xffaabb });

  var t = new Triangle({x: 0, y:0 }, { x: 5, y: Math.sqrt(3)/2 * 10}, {x: 10, y: 0});

  function plotTriangle(triangle) {
    var pts = triangle.to3D('xy');
    var g = new THREE.Geometry();
    g.vertices.push(
      pts[0], pts[1],
      pts[1], pts[2],
      pts[2], pts[0]
    )
    var line = new THREE.LineSegments(g, matLine);
    scene.add(line);
  }

  function serpenski(level) {
    var t = Triangle.CreateEquilateral(20, {x: 1, y: 1});
    plotTriangle(t);
    // debugger;
    var iterations = 0;
    stack = [t];
    while (iterations < level) {
      var length = stack.length;
      while(length > 0) {
        var triangle = stack.shift();
        var mid = triangle.getMidTriangle();
        plotTriangle(mid);
        stack.push.apply(stack, triangle.getSerpenskiTriangles());
        length--;
      }
      iterations++;
    }
  }

  serpenski(2);

  renderer.render(scene, camera);
}

window.addEventListener('load', onPageLoad, false);
<commit_msg>dummy commit on branch<commit_after>function Triangle(p1, p2, p3) {
  this.p1 = p1;
  this.p2 = p2;
  this.p3 = p3;
}

Triangle.prototype.to3D = function(plane) {
  var p1 = this.p1, p2 = this.p2, p3 = this.p3;
  var ret = null;
  if(!plane) plane = 'xy';
  switch (plane) {
    case 'xy':
      ret = [
        new THREE.Vector3(p1.x, p1.y, 0),
        new THREE.Vector3(p2.x, p2.y, 0),
        new THREE.Vector3(p3.x, p3.y, 0)
      ];
      break;
    case 'yz':
      ret = [
        new THREE.Vector3(0, p1.x, p1.y),
        new THREE.Vector3(0, p2.x, p2.y),
        new THREE.Vector3(0, p3.x, p3.y)
      ];
    case 'zx':
      ret = [
        new THREE.Vector3(p1.y, 0, p1.x),
        new THREE.Vector3(p2.y, 0, p2.x),
        new THREE.Vector3(p3.y, 0, p3.x)
      ];
      break;
  }

  return ret;
}

Triangle.prototype.getMidTriangle = function() {
  var p1 = this.p1, p2 = this.p2, p3 = this.p3;
  var fnMid = function(p, q, axis) {
    var ret;
    if(axis === 'x') {
      return (p.x + q.x) / 2;
    }
    else {
      return (p.y + q.y) / 2;
    }
  };
  var
    s1 = {
      x: fnMid(p1, p2, 'x'),
      y: fnMid(p1, p2, 'y')
    },
    s2 = {
      x: fnMid(p2, p3, 'x'),
      y: fnMid(p2, p3, 'y')
    },
    s3 = {
      x: fnMid(p3, p1, 'x'),
      y: fnMid(p3, p1, 'y')
    };
  return new Triangle(s1, s2, s3);
}

Triangle.prototype.getSerpenskiTriangles = function() {
    var p1 = this.p1, p2 = this.p2, p3 = this.p3;
    var mt = this.getMidTriangle();
    var m1 = mt.p1, m2 = mt.p2, m3 = mt.p3;
    return [
      //triangle 1
      new Triangle(
        {
          x: p1.x, y: p1.y
        },
        {
          x: m1.x, y: m1.y
        },
        {
          x: m3.x, y: m3.y
        }
      ),
      //triangle 2
      new Triangle(
        {
          x: m1.x, y: m1.y
        },
        {
          x: p2.x, y: p2.y
        },
        {
          x: m2.x, y: m2.y
        }
      ),
      //triangle 3
      new Triangle(
        {
          x: m2.x, y: m2.y
        },
        {
          x: p3.x, y: p3.y
        },
        {
          x: m3.x, y: m3.y
        }
      )
    ];
};

Triangle.CreateEquilateral = function(side, offset) {
  var x = 0, y = 0;

  var makePoint = function() {
    return {
      x: x + (offset ? offset.x : 0),
      y: y + (offset ? offset.y : 0)
    };
  }
  var s1 = makePoint();

  x = side/2, y = side * Math.sqrt(3)/2;

  var s2 = makePoint();

  x = side, y = 0;

  var s3 = makePoint();

  return new Triangle(s1, s2, s3);
};

function onPageLoad() {
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(
    45,
    window.innerWidth/window.innerHeight,
    1,
    500
  );
  var renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
  var m1 = new THREE.LineBasicMaterial({ color: 0x0000ff }),
    m2 = new THREE.LineBasicMaterial({ color: 0xff0000 }),
    m3 = new THREE.LineBasicMaterial({ color: 0x00ff00 });
  var g1 = new THREE.Geometry();
  var origin = new THREE.Vector3(0,0,0);
  g1.vertices.push(
    origin,
    new THREE.Vector3(0, 10, 0),
    new THREE.Vector3(0, 20, 0)
  );

  var g2 = new THREE.Geometry();
  g2.vertices.push(
    origin,
    new THREE.Vector3(10, 0, 0),
    new THREE.Vector3(20, 0, 0)
  );

  var g3 = new THREE.Geometry();
  g3.vertices.push(
    origin,
    new THREE.Vector3(0,0, 10),
    new THREE.Vector3(0,0, 20)
  );

  var
    liney = new THREE.Line(g1, m1),
    linex = new THREE.Line(g2, m2),
    linez = new THREE.Line(g3, m3);
  scene.add(liney, linex, linez);
  camera.position.set(-30,30,-30);
  camera.lookAt(new THREE.Vector3(0,10,0));

  var matLine = new THREE.LineBasicMaterial({ color: 0xffaabb });

  var t = new Triangle({x: 0, y:0 }, { x: 5, y: Math.sqrt(3)/2 * 10}, {x: 10, y: 0});

  function plotTriangle(triangle) {
    var pts = triangle.to3D('xy');
    var g = new THREE.Geometry();
    g.vertices.push(
      pts[0], pts[1],
      pts[1], pts[2],
      pts[2], pts[0]
    )
    var line = new THREE.LineSegments(g, matLine);
    scene.add(line);
  }

  function serpenski(level) {
    var t = Triangle.CreateEquilateral(20, {x: 1, y: 1});
    plotTriangle(t);
    // debugger;
    var iterations = 0;
    stack = [t];
    while (iterations < level) {
      var length = stack.length;
      while(length > 0) {
        var triangle = stack.shift();
        var mid = triangle.getMidTriangle();
        plotTriangle(mid);
        stack.push.apply(stack, triangle.getSerpenskiTriangles());
        length--;
      }
      iterations++;
    }
  }

  serpenski(2);

  renderer.render(scene, camera);
  console.log('hello');
}

window.addEventListener('load', onPageLoad, false);
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('paper-icon', 'Integration | Component | paper icon', {
  integration: true
});

test('it renders with tag name', function(assert) {
  assert.expect(1);

  this.render(hbs`{{paper-icon}}`);

  assert.ok(this.$('md-icon').length);
});

test('it renders with classes', function(assert) {
  assert.expect(6);

  this.set('icon', 'foo');
  this.render(hbs`{{paper-icon icon=icon}}`);

  const $component = this.$('md-icon');

  assert.ok($component.hasClass('paper-icon'));
  assert.ok($component.hasClass('material-icons'));
  assert.ok($component.hasClass('foo'));
  assert.ok($component.hasClass('md-default-theme'));

  this.set('icon', 'bar');
  assert.ok($component.hasClass('bar'));
  assert.notOk($component.hasClass('foo'));
});

test('it renders with spin class', function(assert) {
  assert.expect(2);

  this.set('spin', true);
  this.render(hbs`{{paper-icon spin=spin}}`);

  var $component = this.$('md-icon');

  assert.ok($component.hasClass('md-spin'));

  this.set('spin', false);
  assert.notOk($component.hasClass('md-spin'));
});

test('it renders with reverse spin class', function(assert) {
  assert.expect(2);

  this.set('reverseSpin', true);
  this.render(hbs`{{paper-icon reverseSpin=reverseSpin}}`);

  var $component = this.$('md-icon');

  assert.ok($component.hasClass('md-spin-reverse'));

  this.set('reverseSpin', false);
  assert.notOk($component.hasClass('md-spin-reverse'));
});

test('it renders with size class', function(assert) {
  assert.expect(6);

  this.set('size', 'lg');
  this.render(hbs`{{paper-icon size=size}}`);

  var $component = this.$('md-icon');

  assert.ok($component.hasClass('md-lg'));

  this.set('size', 'sm');
  assert.ok($component.hasClass('md-sm'));

  this.set('size', 2);
  assert.ok($component.hasClass('md-2x'));

  this.set('size', 3);
  assert.ok($component.hasClass('md-3x'));

  this.set('size', 4);
  assert.ok($component.hasClass('md-4x'));

  this.set('size', 5);
  assert.ok($component.hasClass('md-5x'));
});

test('it works with positional icon param', function(assert) {
  assert.expect(3);

  this.render(hbs`{{paper-icon "foo"}}`);
  assert.ok(this.$('md-icon').hasClass('foo'));

  this.render(hbs`{{paper-icon "bar"}}`);
  assert.ok(this.$('md-icon').hasClass('bar'));
  assert.notOk(this.$('md-icon').hasClass('foo'));
});
<commit_msg>Update `paper-icon` tests to always include icon and use positional params<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('paper-icon', 'Integration | Component | paper icon', {
  integration: true
});

test('it renders with tag name', function(assert) {
  assert.expect(1);

  this.render(hbs`{{paper-icon icon="check"}}`);

  assert.ok(this.$('md-icon').length);
});

test('it renders with classes', function(assert) {
  assert.expect(6);

  this.set('icon', 'foo');
  this.render(hbs`{{paper-icon icon}}`);

  const $component = this.$('md-icon');

  assert.ok($component.hasClass('paper-icon'));
  assert.ok($component.hasClass('material-icons'));
  assert.ok($component.hasClass('foo'));
  assert.ok($component.hasClass('md-default-theme'));

  this.set('icon', 'bar');
  assert.ok($component.hasClass('bar'));
  assert.notOk($component.hasClass('foo'));
});

test('it renders with spin class', function(assert) {
  assert.expect(2);

  this.set('spin', true);
  this.render(hbs`{{paper-icon "check" spin=spin}}`);

  var $component = this.$('md-icon');

  assert.ok($component.hasClass('md-spin'));

  this.set('spin', false);
  assert.notOk($component.hasClass('md-spin'));
});

test('it renders with reverse spin class', function(assert) {
  assert.expect(2);

  this.set('reverseSpin', true);
  this.render(hbs`{{paper-icon "check" reverseSpin=reverseSpin}}`);

  var $component = this.$('md-icon');

  assert.ok($component.hasClass('md-spin-reverse'));

  this.set('reverseSpin', false);
  assert.notOk($component.hasClass('md-spin-reverse'));
});

test('it renders with size class', function(assert) {
  assert.expect(6);

  this.set('size', 'lg');
  this.render(hbs`{{paper-icon "check" size=size}}`);

  var $component = this.$('md-icon');

  assert.ok($component.hasClass('md-lg'));

  this.set('size', 'sm');
  assert.ok($component.hasClass('md-sm'));

  this.set('size', 2);
  assert.ok($component.hasClass('md-2x'));

  this.set('size', 3);
  assert.ok($component.hasClass('md-3x'));

  this.set('size', 4);
  assert.ok($component.hasClass('md-4x'));

  this.set('size', 5);
  assert.ok($component.hasClass('md-5x'));
});
<|endoftext|>


<commit_before>var Url, QueryString;
/**
 * Url
 *
 * @constructor
 * @param {String} url
 */
Url = function (url) {
    var parsed_url, scheme, host, port, path, query, anchor, params = {},
        parser = /^([^:\/?#]+?:\/\/)*([^\/:?#]*)?(:[^\/?#]*)*([^?#]*)(\?[^#]*)?(#(.*))*/;

    if (!(this instanceof arguments.callee)) {
        return this.toString();
    }

    parsed_url = url.match(parser);

    scheme = parsed_url[1];
    host = parsed_url[2];
    port = parsed_url[3];
    path = parsed_url[4];
    query = parsed_url[5];
    anchor = parsed_url[6];

    scheme = scheme ? scheme.replace('://', '').toLowerCase() : '';
    port = port ? port.replace(':', '') : (scheme === 'https' ? '443' : '80');
    // correct the scheme based on port number
    scheme = (scheme === '' && port === '443') ? 'https' : scheme;

    query = query ? query.replace('?', '') : '';
    anchor = anchor ? anchor.replace('#', '') : '';

    // Fix the host name to include port if non-standard ports were given
    if ((scheme === 'https' && port !== '443') || (scheme === 'http' && port !== '80')) {
        host = host + ':' + port;

    }

    this.scheme = scheme;
    this.host = host;
    this.port = port;
    this.path = path ? path : '/';
	this.query = new QueryString(query);
    this.anchor = anchor ? anchor : '';

    /**
     * Returns the url string
     *
     * @memberOf Url
     * @return {String}
     */
    this.toString = function () {
        return scheme + '://' + this.host + this.path + (this.query ? '?' + this.query : '')  + (this.anchor ? '#' + this.anchor : '');
    };
};
QueryString = function () {
    if (!(this instanceof arguments.callee)) {
        return this.toString();
    }

	this.queryParams = {};
	this.setQueryParams = function (query) {
        var arg_length = arguments.length, i, query_array,
            query_array_length, params = this.queryParams, key_value;
        if (arg_length <= 1) {
            if (typeof query === 'object') {
                // iterate
                for (i in query) {
                    if (query.hasOwnProperty(i)) {
                        params[i] = query[i];
                    }
                }
            } else if (typeof query === 'string') {
                // split string on '&'
                query_array = query.spilt('&');
                // iterate over each of the array items
                query_array_length = query_array.length;
                for (i = 0; i < query_array_length; i++) {
                    // split on '=' to get key, value
                    key_value = query_array[i].split('=');
                    params[key_value[0]] = key_value[1];
                }
            }
        } else {
            for (i = 0; i < arg_length; i += 2) {
                // treat each arg as key, then value
                params[arguments[i]] = arguments[i+1];
            }
        }

		this.queryParams = params;
    };

    /**
     * Returns the url query string
     *
     * @memberOf QueryString
     * @return {String}
     */
    this.toString = function () {
        var query = [], i, params = this.queryParams;
		for (i in params) {
			if (params.hasOwnProperty(i)) {
				query.push(i + '=' + params[i]);
			}
		}
        return query.join('&');
    };

	if (arguments.length > 0) {
		this.setQueryParams(arguments);
	}
};

// Only give to the world if they want it
if (window.Url === undefined) {
	window.Url = Url;
}
<commit_msg>reorganization<commit_after><|endoftext|>


<commit_before>define(function (require, exports, module) {

  const Plugin = require('extplug/Plugin')
  const PlaylistImporter = require('./PlaylistImporter')
  const YouTubeImporter = require('./YouTubeImporter')
  const YTPlaylistService = require('plug/actions/youtube/YouTubePlaylistService')
  const YTImportService = require('plug/actions/youtube/YouTubeImportService')
  const { around } = require('meld')

  const PLAYLIST_URL = 'https://www.youtube.com/playlist?list='
  const CHANNEL_URL = 'https://www.youtube.com/channel/'

  const YouTubeImport = Plugin.extend({
    name: 'YouTube Import',
    description: 'Mostly working YouTube importing functions.',

    enable() {
      this.plAdvice = around(YTPlaylistService.prototype, 'load', joinpoint => {
        let [ username, cb ] = joinpoint.args
        // strip channel URL prefix
        if (username.indexOf(CHANNEL_URL) === 0) {
          username = username.slice(CHANNEL_URL.length)
        }
        // strip URL suffixes like /videos, /playlists
        if (username.indexOf('/') !== -1) {
          username = username.split('/')[0]
        }
        new YouTubeImporter(username).loadAll((err, result) => {
          cb(result)
        })
      })
      this.imAdvice = around(YTImportService.prototype, 'load', joinpoint => {
        let [ playlist, isFaves, cb ] = joinpoint.args
        new PlaylistImporter(playlist).loadAll((err, result) => {
          cb(result)
        })
      })
    },

    disable() {
      this.plAdvice.remove()
      this.imAdvice.remove()
    }
  })

  module.exports = YouTubeImport

})
<commit_msg>allow passing usernames in addition to channel IDs<commit_after>define(function (require, exports, module) {

  const Plugin = require('extplug/Plugin')
  const PlaylistImporter = require('./PlaylistImporter')
  const YouTubeImporter = require('./YouTubeImporter')
  const YTPlaylistService = require('plug/actions/youtube/YouTubePlaylistService')
  const YTImportService = require('plug/actions/youtube/YouTubeImportService')
  const { around } = require('meld')

  const PLAYLIST_URL = 'https://www.youtube.com/playlist?list='
  const CHANNEL_URL = 'https://www.youtube.com/channel/'
  const USER_URL = 'https://www.youtube.com/user/'

  const YouTubeImport = Plugin.extend({
    name: 'YouTube Import',
    description: 'Mostly working YouTube importing functions.',

    enable() {
      this.plAdvice = around(YTPlaylistService.prototype, 'load', joinpoint => {
        let [ username, cb ] = joinpoint.args
        // strip channel URL prefix
        if (username.indexOf(CHANNEL_URL) === 0) {
          username = username.slice(CHANNEL_URL.length)
        }
        if (username.indexOf(USER_URL) === 0) {
          username = username.slice(USER_URL.length)
        }
        // strip URL suffixes like /videos, /playlists
        if (username.indexOf('/') !== -1) {
          username = username.split('/')[0]
        }
        this.resolveChannelId(username, (err, channelId) => {
          new YouTubeImporter(channelId).loadAll((err, result) => {
            cb(result)
          })
        })
      })
      this.imAdvice = around(YTImportService.prototype, 'load', joinpoint => {
        let [ playlist, isFaves, cb ] = joinpoint.args
        new PlaylistImporter(playlist).loadAll((err, result) => {
          cb(result)
        })
      })
    },

    disable() {
      this.plAdvice.remove()
      this.imAdvice.remove()
    },

    resolveChannelId(username, cb) {
      let request = gapi.client.youtube.channels.list({
        part: 'id',
        forUsername: username
      })
      request.execute(res => {
        if (res.items.length > 0) {
          cb(null, res.items[0].id)
        }
        else {
          cb(null, username)
        }
      })
    }
  })

  module.exports = YouTubeImport

})
<|endoftext|>


<commit_before>void function(a,b,c){var d=b.documentElement,e=b.body,f=Number(16),g={id:function(a,b){return(b||document).getElementById(a)},tag:function(a,b){return this.makeArray((b||document).getElementsByTagName(a))},qsa:function(a,b){return this.makeArray((b||document).querySelectorAll(a))},create:function(a,b){var a="!"===a?document.createDocumentFragment():""===a?document.createTextNode(b||""):document.createElement(a);try{b&&(a.className=b)}catch(c){}return a},clone:function(a,b){return a.cloneNode(b||!0)},remove:function(a,b){return(b||a.parentNode).removeChild(a)},setAttr:function(a,b){var d=b.length;if("object"==typeof b){if("object"==typeof b[0]&&"name"in b[0])for(var e=0;d>e;e++)b[e].value!==c&&a.setAttribute(b[e].name,b[e].value);else for(var f in b)b.hasOwnProperty(f)&&b[f]!==c&&a.setAttribute(f,b[f]);return a}},isIgnorable:function(a){return"WBR"===a.nodeName||a.nodeType===Node.COMMENT_NODE},makeArray:function(a){return Array.prototype.slice.call(a)},extend:function(a,b){var c="object"==typeof a||"function"==typeof a||"object"==typeof b;if(c){for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);return a}}},h=b.querySelector("body.manual article.main-content"),i=g.qsa("h2, h3, h4, h5, h6",h),j=g.qsa("div.info, .example, pre");i.forEach(function(a,b){var c=a.lastChild,d=c.nodeValue;a.setAttribute("id","sec-"+b),c&&c.nodeType===Node.COMMENT_NODE&&/\s?\#[\w\_\-]+\s?/.test(d)&&(a.setAttribute("id",d.replace(/\s?\#([\w\_\-]+)\s?/i,"$1")),c.parentNode.removeChild(c))}),j.forEach(function(a,b){a.setAttribute("id","info-"+b)});var k=g.qsa("nav.layout ol ol"),l=1e3,m=new RegExp("/manual/?$","i").test(location.href.replace(location.hash,"")),n=function(){var a;return e.scrollTop=1,a=1==e.scrollTop?e:d,a.scrollTop=0,a}();function o(a){return new RegExp("^"+location.href.replace(location.hash,"").replace(/\/$/,""),"i").test(a)}function p(a,c){var d=a?b.querySelector(a)||null:null,e=c!==!1?function(){location.hash=a}:null;d&&q(d.offsetTop+1.5*f,100,e)}function q(a,b,c){if(0>=b)return void(c&&c());var d=n.scrollTop,e=a-d,f=e/b*10;setTimeout(function(){n.scrollTop=d+f,q(a,b-10,c||null)},10)}k.forEach(function(a){a.addEventListener("click",function(a){var b=a.target&&"A"===a.target.nodeName?a.target:null;b&&!m&&o(b.href)&&(a.preventDefault(),b.hash?p(b.hash):q(0,70,function(){location.hash=""}))},!0)}),void["hashchange","DOMContentLoaded"].forEach(function(b){a.addEventListener(b,function(){setTimeout(function(){p(location.hash,!1)},100)})});var r=b.querySelector("nav.layout"),s=3.5*f;a.addEventListener("scroll",function(){n.scrollTop>=s&&e.getAttribute("data-js-fixed-nav")!==!0?e.setAttribute("data-js-fixed-nav",!0):e.removeAttribute("data-js-fixed-nav")}),void["mousewheel","DOMMouseScroll"].forEach(function(a){b.addEventListener(a,function(a){r.addEventListener("mouseover",function(){a.preventDefault()})})}),a.addEventListener("DOMContentLoaded",function(){var a=r.offsetHeight+2*f;h.style.minHeight=a+"px"});var t=g.qsa(".no-interfere",h);t.forEach(function(a){var b=a.innerHTML,c=g.create("iframe"),d,e,f,h;a.innerHTML="",c.setAttribute("src","/itff.html"),a.appendChild(c),d=c.contentWindow,d.addEventListener("DOMContentLoaded",function(){e=c.contentDocument,ifroot=e.documentElement,f=e.body,h=g.create("div","wrapper"),h.innerHTML=b,f.replaceChild(h,g.id("replacee",e)),d.Han.init(),c.style.height=f.offsetHeight+"px"})}),"undefined"!=typeof hljs&&hljs.initHighlightingOnLoad()}(window,window.document);<commit_msg>for better scrolling anima. and hash positioning<commit_after>void function(a,b,c){var d=Number(16),e=b.documentElement,f=b.body,g={id:function(a,b){return(b||document).getElementById(a)},tag:function(a,b){return this.makeArray((b||document).getElementsByTagName(a))},qsa:function(a,b){return this.makeArray((b||document).querySelectorAll(a))},create:function(a,b){var a="!"===a?document.createDocumentFragment():""===a?document.createTextNode(b||""):document.createElement(a);try{b&&(a.className=b)}catch(c){}return a},clone:function(a,b){return a.cloneNode(b||!0)},remove:function(a,b){return(b||a.parentNode).removeChild(a)},setAttr:function(a,b){var d=b.length;if("object"==typeof b){if("object"==typeof b[0]&&"name"in b[0])for(var e=0;d>e;e++)b[e].value!==c&&a.setAttribute(b[e].name,b[e].value);else for(var f in b)b.hasOwnProperty(f)&&b[f]!==c&&a.setAttribute(f,b[f]);return a}},isIgnorable:function(a){return"WBR"===a.nodeName||a.nodeType===Node.COMMENT_NODE},makeArray:function(a){return Array.prototype.slice.call(a)},extend:function(a,b){var c="object"==typeof a||"function"==typeof a||"object"==typeof b;if(c){for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);return a}}},h=b.querySelector("body.manual article.main-content");g.qsa("h2, h3, h4, h5, h6",h).forEach(function(a,b){var c=a.lastChild,d=c.nodeValue;a.setAttribute("id","sec-"+b),c&&c.nodeType===Node.COMMENT_NODE&&/\s?\#[\w\_\-]+\s?/.test(d)&&(a.setAttribute("id",d.replace(/\s?\#([\w\_\-]+)\s?/i,"$1")),c.parentNode.removeChild(c))}),g.qsa("div.info, .example, pre",h).forEach(function(a,b){a.setAttribute("id","info-"+b)});var i=g.qsa("nav.layout ol ol"),j=1e3,k=new RegExp("/manual/?$","i").test(location.href.replace(location.hash,"")),l=function(){var a;return f.scrollTop=1,a=1==f.scrollTop?f:e,a.scrollTop=0,a}();function m(a){return new RegExp("^"+location.href.replace(location.hash,"").replace(/\/$/,""),"i").test(a)}function n(a,c){var e=a?b.querySelector(a)||null:null,f=c!==!1?function(){location.hash=a}:null;e&&o(e.offsetTop+1.5*d,100,f)}function o(a,b,c){if(0>=b)return void(c&&c());var d=l.scrollTop,e=a-d,f=e/b*10;setTimeout(function(){l.scrollTop=d+f,o(a,b-10,c||null)},10)}i.forEach(function(a){a.addEventListener("click",function(a){var b=a.target&&"A"===a.target.nodeName?a.target:null;b&&!k&&m(b.href)&&(a.preventDefault(),b.hash?n(b.hash):o(0,70,function(){location.hash=""}))},!0)}),void["hashchange","iframeLoaded"].forEach(function(b){a.addEventListener(b,function(){setTimeout(function(){n(location.hash,!1)},100)})});var p=b.querySelector("nav.layout"),q=3.5*d;a.addEventListener("scroll",function(){l.scrollTop>=q&&f.getAttribute("data-js-fixed-nav")!==!0?f.setAttribute("data-js-fixed-nav",!0):f.removeAttribute("data-js-fixed-nav")}),void["mousewheel","DOMMouseScroll"].forEach(function(a){b.addEventListener(a,function(a){p.addEventListener("mouseover",function(){a.preventDefault()})})}),a.addEventListener("DOMContentLoaded",function(){var a=p.offsetHeight+2*d;h.style.minHeight=a+"px"});var r=g.qsa(".no-interfere",h),s=new Event("iframeLoaded");0===r.length&&a.dispatchEvent(s),r.forEach(function(b,c){var d=b.innerHTML,e=g.create("iframe"),f,h,i,j;b.innerHTML="",e.setAttribute("src","/itff.html"),b.appendChild(e),f=e.contentWindow,f.addEventListener("DOMContentLoaded",function(){h=e.contentDocument,ifroot=h.documentElement,i=h.body,j=g.create("div","wrapper"),j.innerHTML=d,i.replaceChild(j,g.id("replacee",h)),f.Han.init(),e.style.height=i.offsetHeight+"px",c+1===r.length&&a.dispatchEvent(s)})}),"undefined"!=typeof hljs&&hljs.initHighlightingOnLoad()}(window,window.document);<|endoftext|>


<commit_before>import * as THREE from '../node_modules/three/build/three.js';
import CANNON from 'cannon';
import Physics from './Physics';

// SCENE, CAMERA, RENDERER
let scene = new THREE.Scene();
let aspect = window.innerWidth / window.innerHeight;
let camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 10000);
camera.position.z = 5;
let renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.domElement.setAttribute('tabIndex', '0');
renderer.domElement.focus();

// LIGHTS
let ambientLight = new THREE.AmbientLight(0x444444, 0.1);
let light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 1000, 0);
scene.add(ambientLight);
scene.add(light);

// FLOOR
let floorGeometry = new THREE.BoxGeometry(5, 1, 5);
let floorMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
let floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.position.set(0, -2.5, 0);
scene.add(floor);

let floorPhysicalShape = new CANNON.Plane();
let floorPhysicalMaterial = new CANNON.Material('floor');
let floorPhysicalBody = new CANNON.Body({
  shape: floorPhysicalShape,
  material: floorPhysicalMaterial
});
floorPhysicalBody.position.set(0, -2, 0);
floorPhysicalBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);

// GAME OBJECTS
let ballGeometry = new THREE.SphereGeometry(1, 32, 32);
let ballMaterial = new THREE.MeshBasicMaterial({color: 0xffff00});
let ball = new THREE.Mesh(ballGeometry, ballMaterial);
scene.add(ball);

let ballPhysicalShape = new CANNON.Sphere(1);
let ballPhysicalMaterial = new CANNON.Material('ball');
let ballPhysicalBody = new CANNON.Body({
  mass: 1,
  shape: ballPhysicalShape,
  material: ballPhysicalMaterial,
  linearDamping: 0.1
});

// PHYSICS
let physics = new Physics();
physics.add(ballPhysicalBody);
physics.add(floorPhysicalBody);

let ballFloorContact = new CANNON.ContactMaterial(ballPhysicalMaterial, floorPhysicalMaterial);
ballFloorContact.contactEquationStiffness = 1e10;
ballFloorContact.contactEquationRegularizationTime = 1;
physics.addContactMaterial(ballFloorContact);

// GAME LOOP
let previousTime;
function render() {
  let time = new Date().getTime();
  let delta = time - previousTime;
  previousTime = time;

  physics.update(delta);

  // UPDATE BALL POSITION
  let ballPosition = ballPhysicalBody.position;
  ball.position.set(ballPosition.x, ballPosition.y, ballPosition.z);

  renderer.render(scene, camera);
  requestAnimationFrame(render);
}
render();
<commit_msg>Increased bounce.<commit_after>import * as THREE from '../node_modules/three/build/three.js';
import CANNON from 'cannon';
import Physics from './Physics';

// SCENE, CAMERA, RENDERER
let scene = new THREE.Scene();
let aspect = window.innerWidth / window.innerHeight;
let camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 10000);
camera.position.z = 5;
let renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.domElement.setAttribute('tabIndex', '0');
renderer.domElement.focus();

// LIGHTS
let ambientLight = new THREE.AmbientLight(0x444444, 0.1);
let light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 1000, 0);
scene.add(ambientLight);
scene.add(light);

// FLOOR
let floorGeometry = new THREE.BoxGeometry(5, 1, 5);
let floorMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
let floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.position.set(0, -2.5, 0);
scene.add(floor);

let floorPhysicalShape = new CANNON.Plane();
let floorPhysicalMaterial = new CANNON.Material('floor');
let floorPhysicalBody = new CANNON.Body({
  shape: floorPhysicalShape,
  material: floorPhysicalMaterial
});
floorPhysicalBody.position.set(0, -2, 0);
floorPhysicalBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);

// GAME OBJECTS
let ballGeometry = new THREE.SphereGeometry(1, 32, 32);
let ballMaterial = new THREE.MeshBasicMaterial({color: 0xffff00});
let ball = new THREE.Mesh(ballGeometry, ballMaterial);
scene.add(ball);

let ballPhysicalShape = new CANNON.Sphere(1);
let ballPhysicalMaterial = new CANNON.Material('ball');
let ballPhysicalBody = new CANNON.Body({
  mass: 1,
  shape: ballPhysicalShape,
  material: ballPhysicalMaterial,
  linearDamping: 0.1
});

// PHYSICS
let physics = new Physics();
physics.add(ballPhysicalBody);
physics.add(floorPhysicalBody);

let ballFloorContact = new CANNON.ContactMaterial(ballPhysicalMaterial, floorPhysicalMaterial);
ballFloorContact.contactEquationStiffness = 1e4;
ballFloorContact.contactEquationRegularizationTime = 1;
ballFloorContact.restitution = 1;
physics.addContactMaterial(ballFloorContact);

// GAME LOOP
let previousTime;
function render() {
  let time = new Date().getTime();
  let delta = time - previousTime;
  previousTime = time;

  physics.update(delta);

  // UPDATE BALL POSITION
  let ballPosition = ballPhysicalBody.position;
  ball.position.set(ballPosition.x, ballPosition.y, ballPosition.z);

  renderer.render(scene, camera);
  requestAnimationFrame(render);
}
render();
<|endoftext|>


<commit_before>const electron = require('electron')
const path = require('path')
const pathExtra = require('path-extra')
const jsonfile = require('jsonfile')

var absPath = path.dirname(`${__dirname}`),
    configFile = pathExtra.datadir('KongDash') + '/config.json'

var {app, ipcMain, BrowserWindow, Menu} = electron

app.setName('KongDash')

let mainWindow, globalConfig = { kong: {}, app: { enableAnimation: true } }

function startMainWindow () {
    mainWindow = new BrowserWindow({
        backgroundColor: '#1A242D',
        width: 1100,
        height: 580,
        center: true,
        title: app.getName(),
        minHeight: 500,
        minWidth: 900,
	    icon: absPath + '/kongdash-256x256.png'
    })
    mainWindow.loadURL('file://' + absPath + '/src/init.html')

    /* Debugging
    mainWindow.webContents.openDevTools();
    //*/

    mainWindow.on('closed', () => {
        mainWindow = null
    })
}

app.on('ready', () => {
    try {
        var config = jsonfile.readFileSync(configFile)
        globalConfig = config

    } catch (ignored) {

    } finally {
        startMainWindow()
    }
})

app.on('activate', () => {
    if (mainWindow === null)
        startMainWindow()
})

app.on('browser-window-created', (e, window) => {
    var menuTemplate = [{
        label: 'File',
        submenu: [{ role: 'quit' }]
    }, {
        label: 'Edit',
        submenu: [{ role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }]
    }, {
        label: 'Window',
        submenu: [{
            label: 'Reload',
            accelerator: 'CmdOrCtrl+R',
            click: (item, focusedWindow) => {
                if (focusedWindow)
                    focusedWindow.reload()
            }
        }, {role: 'togglefullscreen'}]
    }, {
        label: 'Help',
        submenu: [{
            label: 'GitHub Repository',
            click: () => {
                electron.shell.openExternal('https://github.com/ajaysreedhar/kongdash')
            }
        }, {
            label: 'Report Issues',
            click: () => {
                electron.shell.openExternal('https://github.com/ajaysreedhar/kongdash/issues')
            }
        }, {
           type: 'separator'
        }, {
            label: 'About KongDash',
            click: () => {
                electron.shell.openExternal('http:ajaysreedhar.github.io/kongdash')
            }
        }]
    }]

    window.setMenu(Menu.buildFromTemplate(menuTemplate))
})

app.on('window-all-closed', () => {
    if(process.platform !== 'darwin')
        app.quit()
});

ipcMain.on('get-kong-config', (event) => {
    event.returnValue = globalConfig.kong
})

ipcMain.on('get-app-config', (event) => {
    event.returnValue = globalConfig.app
})

ipcMain.on('write-kong-config', (event, arg) => {
    globalConfig.kong = arg;

    jsonfile.writeFile(configFile, globalConfig, function (error) {
        if (error) {
            event.sender.send('write-config-error', {message: 'Could not write configuration file'})
        } else {
            event.sender.send('write-config-success', {})
        }
    })
})

ipcMain.on('write-app-config', (event, arg) => {
    globalConfig.app = arg;

    jsonfile.writeFile(configFile, globalConfig, function (error) {
        if (error) {
            event.sender.send('write-config-error', {message: 'Could not write configuration file'})
        } else {
            event.sender.send('write-config-success', {})
        }
    })
})
<commit_msg>[changed] about url corrected<commit_after>const electron = require('electron')
const path = require('path')
const pathExtra = require('path-extra')
const jsonfile = require('jsonfile')

var absPath = path.dirname(`${__dirname}`),
    configFile = pathExtra.datadir('KongDash') + '/config.json'

var {app, ipcMain, BrowserWindow, Menu} = electron

app.setName('KongDash')

let mainWindow, globalConfig = { kong: {}, app: { enableAnimation: true } }

function startMainWindow () {
    mainWindow = new BrowserWindow({
        backgroundColor: '#1A242D',
        width: 1100,
        height: 580,
        center: true,
        title: app.getName(),
        minHeight: 500,
        minWidth: 900,
	    icon: absPath + '/kongdash-256x256.png'
    })
    mainWindow.loadURL('file://' + absPath + '/src/init.html')

    /* Debugging
    mainWindow.webContents.openDevTools();
    //*/

    mainWindow.on('closed', () => {
        mainWindow = null
    })
}

app.on('ready', () => {
    try {
        var config = jsonfile.readFileSync(configFile)
        globalConfig = config

    } catch (ignored) {

    } finally {
        startMainWindow()
    }
})

app.on('activate', () => {
    if (mainWindow === null)
        startMainWindow()
})

app.on('browser-window-created', (e, window) => {
    var menuTemplate = [{
        label: 'File',
        submenu: [{ role: 'quit' }]
    }, {
        label: 'Edit',
        submenu: [{ role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }]
    }, {
        label: 'Window',
        submenu: [{
            label: 'Reload',
            accelerator: 'CmdOrCtrl+R',
            click: (item, focusedWindow) => {
                if (focusedWindow)
                    focusedWindow.reload()
            }
        }, {role: 'togglefullscreen'}]
    }, {
        label: 'Help',
        submenu: [{
            label: 'GitHub Repository',
            click: () => {
                electron.shell.openExternal('https://github.com/ajaysreedhar/kongdash')
            }
        }, {
            label: 'Report Issues',
            click: () => {
                electron.shell.openExternal('https://github.com/ajaysreedhar/kongdash/issues')
            }
        }, {
           type: 'separator'
        }, {
            label: 'About KongDash',
            click: () => {
                electron.shell.openExternal('https://ajaysreedhar.github.io/kongdash/')
            }
        }]
    }]

    window.setMenu(Menu.buildFromTemplate(menuTemplate))
})

app.on('window-all-closed', () => {
    if(process.platform !== 'darwin')
        app.quit()
});

ipcMain.on('get-kong-config', (event) => {
    event.returnValue = globalConfig.kong
})

ipcMain.on('get-app-config', (event) => {
    event.returnValue = globalConfig.app
})

ipcMain.on('write-kong-config', (event, arg) => {
    globalConfig.kong = arg;

    jsonfile.writeFile(configFile, globalConfig, function (error) {
        if (error) {
            event.sender.send('write-config-error', {message: 'Could not write configuration file'})
        } else {
            event.sender.send('write-config-success', {})
        }
    })
})

ipcMain.on('write-app-config', (event, arg) => {
    globalConfig.app = arg;

    jsonfile.writeFile(configFile, globalConfig, function (error) {
        if (error) {
            event.sender.send('write-config-error', {message: 'Could not write configuration file'})
        } else {
            event.sender.send('write-config-success', {})
        }
    })
})
<|endoftext|>


<commit_before>// --
// Core.UI.RichTextEditor.js - provides all UI functions
// Copyright (C) 2001-2013 OTRS AG, http://otrs.org/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var Core = Core || {};
Core.UI = Core.UI || {};

/**
 * @namespace
 * @exports TargetNS as Core.UI.RichTextEditor
 * @description
 *      Richtext Editor
 * @requires
 *      CKEDITOR
 */
Core.UI.RichTextEditor = (function (TargetNS) {
    var $FormID, TimeOutRTEOnChange;

    /**
     * @function
     * @private
     * @description Check in the window which hidden element has a name same to 'FormID' and return it like a JQuery object
     */
    function CheckFormID() {
        if (typeof $FormID === 'undefined') {
            $FormID = $('input:hidden[name=FormID]');
        }
        return $FormID;
    }

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that will be a rich text editor
     * @return nothing
     *      This function initializes the application and executes the needed functions
     */
    TargetNS.Init = function ($EditorArea) {
        var EditorID = '',
            Editor,
            Instance,
            UserLanguage;

        if (isJQueryObject($EditorArea) && $EditorArea.hasClass('HasCKEInstance')) {
            return false;
        }

        if (isJQueryObject($EditorArea) && $EditorArea.length === 1) {
            EditorID = $EditorArea.attr('id');
        }

        if (EditorID === '') {
            Core.Exception.Throw('RichTextEditor: Need exactly one EditorArea!', 'TypeError');
        }

        // mark the editor textarea as linked with an RTE instance to avoid multiple instances
        $EditorArea.addClass('HasCKEInstance');

        CKEDITOR.on('instanceCreated', function (Editor) {
            CKEDITOR.addCss(Core.Config.Get('RichText.EditingAreaCSS'));

            // Remove the validation error tooltip if content is added to the editor
            Editor.editor.on('change', function(evt) {
                window.clearTimeout(TimeOutRTEOnChange);
                TimeOutRTEOnChange = window.setTimeout(function () {
                    Core.Form.Validate.ValidateElement($(Editor.editor.element.$));
                }, 250);
            });

            // if spell checker is used on paste new content should spell check again
            Editor.editor.on('paste', function(evt) {
                Core.Config.Set('TextIsSpellChecked', false);
            });
            // if spell checker is used on any key new content should spell check again
            Editor.editor.on('key', function(evt) {
                Core.Config.Set('TextIsSpellChecked', false);
            });
        });

        // The format for the language is different between OTRS and CKEditor (see bug#8024)
        // To correct this, we replace "_" with "-" in the language (e.g. zh_CN becomes zh-cn)
        UserLanguage = Core.Config.Get('UserLanguage').replace(/_/, "-");

        Editor = CKEDITOR.replace(EditorID,
        {
            customConfig: '', // avoid loading external config files
            defaultLanguage: UserLanguage,
            language: UserLanguage,
            width: Core.Config.Get('RichText.Width', 620),
            resize_minWidth: Core.Config.Get('RichText.Width', 620),
            height: Core.Config.Get('RichText.Height', 320),
            removePlugins : 'elementspath,scayt,menubutton',
            forcePasteAsPlainText: false,
            format_tags: 'p;h1;h2;h3;h4;h5;h6;pre',
            fontSize_sizes: '8px;10px;12px;16px;18px;20px;22px;24px;26px;28px;30px;',
            extraAllowedContent: 'div table tr td th colgroup col style[*]{*}',
            enterMode: CKEDITOR.ENTER_BR,
            shiftEnterMode: CKEDITOR.ENTER_BR,
            contentsLangDirection: Core.Config.Get('RichText.TextDir', 'ltr'),
            disableNativeSpellChecker: false,
            toolbar: CheckFormID().length ? Core.Config.Get('RichText.Toolbar') : Core.Config.Get('RichText.ToolbarWithoutImage'),
            filebrowserUploadUrl: Core.Config.Get('Baselink'),
            extraPlugins: Core.Config.Get('RichText.SpellChecker') ? 'aspell,splitquote' : 'splitquote',
            entities: false,
            skin: 'bootstrapck'
        });
        if (CheckFormID().length) {
            CKEDITOR.config.action = Core.Config.Get('RichText.PictureUploadAction', 'PictureUpload');
            CKEDITOR.config.formID = CheckFormID().val();
        }
        CKEDITOR.config.spellerPagesServerScript = Core.Config.Get('Baselink');

        // Hack for updating the textarea with the RTE content (bug#5857)
        // Rename the original function to another name, than overwrite the original one
        CKEDITOR.instances[EditorID].updateElementOriginal = CKEDITOR.instances[EditorID].updateElement;
        CKEDITOR.instances[EditorID].updateElement = function() {
            var Data;

            // First call the original function
            CKEDITOR.instances[EditorID].updateElementOriginal();

            // Now check if there is actually any non-whitespace content in the
            //  textarea field. If not, set it to an empty value to make sure
            //  the server side validation works correctly and there is no trash
            //  like '
' stored in the DB.
            Data = this.element.getValue(); // get textarea content

            // only if data contains no image tag,
            // this is important for inline images, we don't want to remove them!
            if ( !Data.match(/<img/) ) {

                // remove tags and whitespace for checking
                Data = Data.replace(/\s+| |<\/?\w+[^>]*\/?>/g, '');
                if (!Data.length) {
                    this.element.setValue(''); // reset textarea
                }
            }
        };

        // Needed for clientside validation of RTE
        CKEDITOR.instances[EditorID].on('blur', function () {
            CKEDITOR.instances[EditorID].updateElement();
            Core.Form.Validate.ValidateElement($EditorArea);
        });

        // needed for client-side validation
        CKEDITOR.instances[EditorID].on('focus', function () {
            if ($EditorArea.attr('class').match(/Error/)) {
                window.setTimeout(function () {
                    CKEDITOR.instances[EditorID].updateElement();
                    Core.Form.Validate.ValidateElement($EditorArea);
                }, 0);
            }
        });

        // mainly needed for client-side validation
        $EditorArea.focus(function () {
            TargetNS.Focus($EditorArea);
            Core.UI.ScrollTo($("label[for=" + $EditorArea.attr('id') + "]"));
        });
    };

    /**
     * @function
     * @return nothing
     *      This function initializes as a rich text editor every textarea element that containing the RichText class
     */
    TargetNS.InitAll = function () {
        $('textarea.RichText').each(function () {
            TargetNS.Init($(this));
        });
    };

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that is a rich text editor
     * @return The rich text editor length
     *      This function return the length for a rich text editor object
     */
    TargetNS.GetRTE = function ($EditorArea) {
        if (isJQueryObject($EditorArea)) {
            var $RTE = $('#cke_' + $EditorArea.attr('id'));
            return ($RTE.length ? $RTE : undefined);
        }
    };

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that is a rich text editor
     * @return nothing
     *      This function updates the linked field for a rich text editor
     */
    TargetNS.UpdateLinkedField = function ($EditorArea) {
        var EditorID = '',
            Data,
            StrippedContent;

        if (isJQueryObject($EditorArea) && $EditorArea.length === 1) {
            EditorID = $EditorArea.attr('id');
        }

        if (EditorID === '') {
            Core.Exception.Throw('RichTextEditor: Need exactly one EditorArea!', 'TypeError');
        }

        Data = CKEDITOR.instances[EditorID].getData();
        StrippedContent = Data.replace(/\s+| |<\/?\w+[^>]*\/?>/g, '');

        if (StrippedContent.length === 0 && !Data.match(/<img/)) {
            $EditorArea.val('');
        }
        else {
            $EditorArea.val(Data);
        }
    };

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that is a rich text editor
     * @return nothing
     *      This function check if a rich text editor is enable in this moment
     */
    TargetNS.IsEnabled = function ($EditorArea) {
        var EditorID = '';

        if (typeof CKEDITOR === 'undefined') {
            return false;
        }

        if (isJQueryObject($EditorArea) && $EditorArea.length) {
            return (CKEDITOR.instances[$EditorArea[0].id] ? true : false);
        }
        return false;
    };

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that is a rich text editor
     * @return nothing
     *      This function check if a rich text editor has the browser focus enabled
     */
    TargetNS.Focus = function ($EditorArea) {
        var EditorID = '';

        if (isJQueryObject($EditorArea) && $EditorArea.length === 1) {
            EditorID = $EditorArea.attr('id');
        }

        if (EditorID === '') {
            Core.Exception.Throw('RichTextEditor: Need exactly one EditorArea!', 'TypeError');
        }

        if (typeof CKEDITOR === 'object') {
            CKEDITOR.instances[EditorID].focus();
        }
        else {
            $EditorArea.focus();
        }
    };

    return TargetNS;
}(Core.UI.RichTextEditor || {}));
<commit_msg>Updated rules for CKEditor ACF. img elements are now allowed, although not inserted via image dialog. This is a workaround for bug#10939.<commit_after>// --
// Core.UI.RichTextEditor.js - provides all UI functions
// Copyright (C) 2001-2013 OTRS AG, http://otrs.org/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var Core = Core || {};
Core.UI = Core.UI || {};

/**
 * @namespace
 * @exports TargetNS as Core.UI.RichTextEditor
 * @description
 *      Richtext Editor
 * @requires
 *      CKEDITOR
 */
Core.UI.RichTextEditor = (function (TargetNS) {
    var $FormID, TimeOutRTEOnChange;

    /**
     * @function
     * @private
     * @description Check in the window which hidden element has a name same to 'FormID' and return it like a JQuery object
     */
    function CheckFormID() {
        if (typeof $FormID === 'undefined') {
            $FormID = $('input:hidden[name=FormID]');
        }
        return $FormID;
    }

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that will be a rich text editor
     * @return nothing
     *      This function initializes the application and executes the needed functions
     */
    TargetNS.Init = function ($EditorArea) {
        var EditorID = '',
            Editor,
            Instance,
            UserLanguage;

        if (isJQueryObject($EditorArea) && $EditorArea.hasClass('HasCKEInstance')) {
            return false;
        }

        if (isJQueryObject($EditorArea) && $EditorArea.length === 1) {
            EditorID = $EditorArea.attr('id');
        }

        if (EditorID === '') {
            Core.Exception.Throw('RichTextEditor: Need exactly one EditorArea!', 'TypeError');
        }

        // mark the editor textarea as linked with an RTE instance to avoid multiple instances
        $EditorArea.addClass('HasCKEInstance');

        CKEDITOR.on('instanceCreated', function (Editor) {
            CKEDITOR.addCss(Core.Config.Get('RichText.EditingAreaCSS'));

            // Remove the validation error tooltip if content is added to the editor
            Editor.editor.on('change', function(evt) {
                window.clearTimeout(TimeOutRTEOnChange);
                TimeOutRTEOnChange = window.setTimeout(function () {
                    Core.Form.Validate.ValidateElement($(Editor.editor.element.$));
                }, 250);
            });

            // if spell checker is used on paste new content should spell check again
            Editor.editor.on('paste', function(evt) {
                Core.Config.Set('TextIsSpellChecked', false);
            });
            // if spell checker is used on any key new content should spell check again
            Editor.editor.on('key', function(evt) {
                Core.Config.Set('TextIsSpellChecked', false);
            });
        });

        // The format for the language is different between OTRS and CKEditor (see bug#8024)
        // To correct this, we replace "_" with "-" in the language (e.g. zh_CN becomes zh-cn)
        UserLanguage = Core.Config.Get('UserLanguage').replace(/_/, "-");

        Editor = CKEDITOR.replace(EditorID,
        {
            customConfig: '', // avoid loading external config files
            defaultLanguage: UserLanguage,
            language: UserLanguage,
            width: Core.Config.Get('RichText.Width', 620),
            resize_minWidth: Core.Config.Get('RichText.Width', 620),
            height: Core.Config.Get('RichText.Height', 320),
            removePlugins : 'elementspath,scayt,menubutton',
            forcePasteAsPlainText: false,
            format_tags: 'p;h1;h2;h3;h4;h5;h6;pre',
            fontSize_sizes: '8px;10px;12px;16px;18px;20px;22px;24px;26px;28px;30px;',
            extraAllowedContent: 'div table tr td th colgroup col img style[*]{*}',
            enterMode: CKEDITOR.ENTER_BR,
            shiftEnterMode: CKEDITOR.ENTER_BR,
            contentsLangDirection: Core.Config.Get('RichText.TextDir', 'ltr'),
            disableNativeSpellChecker: false,
            toolbar: CheckFormID().length ? Core.Config.Get('RichText.Toolbar') : Core.Config.Get('RichText.ToolbarWithoutImage'),
            filebrowserUploadUrl: Core.Config.Get('Baselink'),
            extraPlugins: Core.Config.Get('RichText.SpellChecker') ? 'aspell,splitquote' : 'splitquote',
            entities: false,
            skin: 'bootstrapck'
        });
        if (CheckFormID().length) {
            CKEDITOR.config.action = Core.Config.Get('RichText.PictureUploadAction', 'PictureUpload');
            CKEDITOR.config.formID = CheckFormID().val();
        }
        CKEDITOR.config.spellerPagesServerScript = Core.Config.Get('Baselink');

        // Hack for updating the textarea with the RTE content (bug#5857)
        // Rename the original function to another name, than overwrite the original one
        CKEDITOR.instances[EditorID].updateElementOriginal = CKEDITOR.instances[EditorID].updateElement;
        CKEDITOR.instances[EditorID].updateElement = function() {
            var Data;

            // First call the original function
            CKEDITOR.instances[EditorID].updateElementOriginal();

            // Now check if there is actually any non-whitespace content in the
            //  textarea field. If not, set it to an empty value to make sure
            //  the server side validation works correctly and there is no trash
            //  like '
' stored in the DB.
            Data = this.element.getValue(); // get textarea content

            // only if data contains no image tag,
            // this is important for inline images, we don't want to remove them!
            if ( !Data.match(/<img/) ) {

                // remove tags and whitespace for checking
                Data = Data.replace(/\s+| |<\/?\w+[^>]*\/?>/g, '');
                if (!Data.length) {
                    this.element.setValue(''); // reset textarea
                }
            }
        };

        // Needed for clientside validation of RTE
        CKEDITOR.instances[EditorID].on('blur', function () {
            CKEDITOR.instances[EditorID].updateElement();
            Core.Form.Validate.ValidateElement($EditorArea);
        });

        // needed for client-side validation
        CKEDITOR.instances[EditorID].on('focus', function () {
            if ($EditorArea.attr('class').match(/Error/)) {
                window.setTimeout(function () {
                    CKEDITOR.instances[EditorID].updateElement();
                    Core.Form.Validate.ValidateElement($EditorArea);
                }, 0);
            }
        });

        // mainly needed for client-side validation
        $EditorArea.focus(function () {
            TargetNS.Focus($EditorArea);
            Core.UI.ScrollTo($("label[for=" + $EditorArea.attr('id') + "]"));
        });
    };

    /**
     * @function
     * @return nothing
     *      This function initializes as a rich text editor every textarea element that containing the RichText class
     */
    TargetNS.InitAll = function () {
        $('textarea.RichText').each(function () {
            TargetNS.Init($(this));
        });
    };

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that is a rich text editor
     * @return The rich text editor length
     *      This function return the length for a rich text editor object
     */
    TargetNS.GetRTE = function ($EditorArea) {
        if (isJQueryObject($EditorArea)) {
            var $RTE = $('#cke_' + $EditorArea.attr('id'));
            return ($RTE.length ? $RTE : undefined);
        }
    };

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that is a rich text editor
     * @return nothing
     *      This function updates the linked field for a rich text editor
     */
    TargetNS.UpdateLinkedField = function ($EditorArea) {
        var EditorID = '',
            Data,
            StrippedContent;

        if (isJQueryObject($EditorArea) && $EditorArea.length === 1) {
            EditorID = $EditorArea.attr('id');
        }

        if (EditorID === '') {
            Core.Exception.Throw('RichTextEditor: Need exactly one EditorArea!', 'TypeError');
        }

        Data = CKEDITOR.instances[EditorID].getData();
        StrippedContent = Data.replace(/\s+| |<\/?\w+[^>]*\/?>/g, '');

        if (StrippedContent.length === 0 && !Data.match(/<img/)) {
            $EditorArea.val('');
        }
        else {
            $EditorArea.val(Data);
        }
    };

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that is a rich text editor
     * @return nothing
     *      This function check if a rich text editor is enable in this moment
     */
    TargetNS.IsEnabled = function ($EditorArea) {
        var EditorID = '';

        if (typeof CKEDITOR === 'undefined') {
            return false;
        }

        if (isJQueryObject($EditorArea) && $EditorArea.length) {
            return (CKEDITOR.instances[$EditorArea[0].id] ? true : false);
        }
        return false;
    };

    /**
     * @function
     * @param {jQueryObject} $EditorArea The jQuery object of the element that is a rich text editor
     * @return nothing
     *      This function check if a rich text editor has the browser focus enabled
     */
    TargetNS.Focus = function ($EditorArea) {
        var EditorID = '';

        if (isJQueryObject($EditorArea) && $EditorArea.length === 1) {
            EditorID = $EditorArea.attr('id');
        }

        if (EditorID === '') {
            Core.Exception.Throw('RichTextEditor: Need exactly one EditorArea!', 'TypeError');
        }

        if (typeof CKEDITOR === 'object') {
            CKEDITOR.instances[EditorID].focus();
        }
        else {
            $EditorArea.focus();
        }
    };

    return TargetNS;
}(Core.UI.RichTextEditor || {}));
<|endoftext|>