<commit_before>dagre.layout = function() {
  // External configuration
  var
      // Nodes to lay out. At minimum must have `width` and `height` attributes.
      nodes = [],
      // Edges to lay out. At mimimum must have `source` and `target` attributes.
      edges = [],
      // How much debug information to include?
      debugLevel = 0,
      timer = createTimer();

  // Phase functions
  var
      acyclic = dagre.layout.acyclic(),
      rank = dagre.layout.rank(),
      order = dagre.layout.order(),
      position = dagre.layout.position();

  // This layout object
  var self = {};

  self.nodes = function(x) {
    if (!arguments.length) return nodes;
    nodes = x;
    return self;
  };

  self.edges = function(x) {
    if (!arguments.length) return edges;
    edges = x;
    return self;
  };

  self.orderIters = function(x) {
    if (!arguments.length) return order.iterations();
    order.iterations(x);
    return self;
  }

  self.nodeSep = function(x) {
    if (!arguments.length) return position.nodeSep();
    position.nodeSep(x);
    return self;
  };

  self.edgeSep = function(x) {
    if (!arguments.length) return position.edgeSep();
    position.edgeSep(x);
    return self;
  }

  self.rankSep = function(x) {
    if (!arguments.length) return position.rankSep();
    position.rankSep(x);
    return self;
  }

  self.posDir = function(x) {
    if (!arguments.length) return position.direction();
    position.direction(x);
    return self;
  }

  self.debugLevel = function(x) {
    if (!arguments.length) return debugLevel;
    debugLevel = x;
    timer.enabled(debugLevel);
    acyclic.debugLevel(x);
    rank.debugLevel(x);
    order.debugLevel(x);
    position.debugLevel(x);
    return self;
  }

  self.run = timer.wrap("Total layout", run);

  return self;

  // Build graph and save mapping of generated ids to original nodes and edges
  function init() {
    var g = dagre.graph();

    var nextId = 0;

    // Tag each node so that we can properly represent relationships when
    // we add edges. Also copy relevant dimension information.
    nodes.forEach(function(u) {
      var id = "id" in u ? u.id : "_N" + nextId++;
      u.dagre = { id: id, width: u.width, height: u.height };
      g.addNode(id, u.dagre);
    });

    edges.forEach(function(e) {
      var source = e.source.dagre.id;
      if (!g.hasNode(source)) {
        throw new Error("Source node for '" + e + "' not in node list");
      }

      var target = e.target.dagre.id;
      if (!g.hasNode(target)) {
        throw new Error("Target node for '" + e + "' not in node list");
      }

      e.dagre = {
        points: []
      };

      // Track edges that aren't self loops - layout does nothing for self
      // loops, so they can be skipped.
      if (source !== target) {
        var id = "id" in e ? e.id : "_E" + nextId++;
        e.dagre.minLen = e.minLen || 1;
        e.dagre.width = e.width || 0;
        e.dagre.height = e.height || 0;
        g.addEdge(id, source, target, e.dagre);
      }
    });

    return g;
  }

  function run () {
    var rankSep = self.rankSep();
    try {
      if (!nodes.length) {
        return;
      }

      // Build internal graph
      var g = init();

      // Make space for edge labels
      g.eachEdge(function(e, s, t, a) {
        a.minLen *= 2;
      });
      self.rankSep(rankSep / 2);

      // Reverse edges to get an acyclic graph, we keep the graph in an acyclic
      // state until the very end.
      acyclic.run(g);

      // Determine the rank for each node. Nodes with a lower rank will appear
      // above nodes of higher rank.
      rank.run(g);

      // Normalize the graph by ensuring that every edge is proper (each edge has
      // a length of 1). We achieve this by adding dummy nodes to long edges,
      // thus shortening them.
      normalize(g);

      // Order the nodes so that edge crossings are minimized.
      order.run(g);

      // Find the x and y coordinates for every node in the graph.
      position.run(g);

      // De-normalize the graph by removing dummy nodes and augmenting the
      // original long edges with coordinate information.
      undoNormalize(g);

      // Reverses points for edges that are in a reversed state.
      fixupEdgePoints(g);

      // Reverse edges that were revered previously to get an acyclic graph.
      acyclic.undo(g);
    } finally {
      self.rankSep(rankSep);
    }
  }

  // Assumes input graph has no self-loops and is otherwise acyclic.
  function normalize(g) {
    g.eachEdge(function(e, source, target) {
      var sourceRank = g.node(source).rank;
      var targetRank = g.node(target).rank;
      if (sourceRank + 1 < targetRank) {
        var prefix = "_D-" + e + "-";
        for (var u = source, rank = sourceRank + 1, i = 0; rank < targetRank; ++rank, ++i) {
          var v = prefix + rank;
          var node = { width: g.edge(e).width,
                       height: g.edge(e).height,
                       edgeId: e,
                       edge: g.edge(e),
                       source: g.source(e),
                       target: g.target(e),
                       index: i,
                       rank: rank,
                       dummy: true };
          g.addNode(v, node);
          g.addEdge(u + " -> " + v, u, v, {});
          u = v;
        }
        g.addEdge(u + " -> " + target, u, target, {});
        g.delEdge(e);
      }
    });
  }

  function undoNormalize(g) {
    var visited = {};

    g.eachNode(function(u, node) {
      if (node.dummy) {
        if (!g.hasEdge(node.edgeId)) {
          g.addEdge(node.edgeId, node.source, node.target, node.edge);
        }
        var points = g.edge(node.edgeId).points;
        points[node.index] = { x: node.x, y: node.y };
        g.delNode(u);
      }
    });
  }

  function fixupEdgePoints(g) {
    g.eachEdge(function(e, s, t, a) { if (a.reversed) a.points.reverse(); });
  }
}
<commit_msg>Simplify property delegation in layout<commit_after>dagre.layout = function() {
  // External configuration
  var
      // Nodes to lay out. At minimum must have `width` and `height` attributes.
      nodes = [],
      // Edges to lay out. At mimimum must have `source` and `target` attributes.
      edges = [],
      // How much debug information to include?
      debugLevel = 0,
      timer = createTimer();

  // Phase functions
  var
      acyclic = dagre.layout.acyclic(),
      rank = dagre.layout.rank(),
      order = dagre.layout.order(),
      position = dagre.layout.position();

  // This layout object
  var self = {};

  self.nodes = function(x) {
    if (!arguments.length) return nodes;
    nodes = x;
    return self;
  };

  self.edges = function(x) {
    if (!arguments.length) return edges;
    edges = x;
    return self;
  };

  self.orderIters = delegateProperty(order.iterations);

  self.nodeSep = delegateProperty(position.nodeSep);
  self.edgeSep = delegateProperty(position.edgeSep);
  self.rankSep = delegateProperty(position.rankSep);
  self.posDir = delegateProperty(position.direction);

  self.debugLevel = function(x) {
    if (!arguments.length) return debugLevel;
    debugLevel = x;
    timer.enabled(debugLevel);
    acyclic.debugLevel(x);
    rank.debugLevel(x);
    order.debugLevel(x);
    position.debugLevel(x);
    return self;
  }

  self.run = timer.wrap("Total layout", run);

  return self;

  // Build graph and save mapping of generated ids to original nodes and edges
  function init() {
    var g = dagre.graph();

    var nextId = 0;

    // Tag each node so that we can properly represent relationships when
    // we add edges. Also copy relevant dimension information.
    nodes.forEach(function(u) {
      var id = "id" in u ? u.id : "_N" + nextId++;
      u.dagre = { id: id, width: u.width, height: u.height };
      g.addNode(id, u.dagre);
    });

    edges.forEach(function(e) {
      var source = e.source.dagre.id;
      if (!g.hasNode(source)) {
        throw new Error("Source node for '" + e + "' not in node list");
      }

      var target = e.target.dagre.id;
      if (!g.hasNode(target)) {
        throw new Error("Target node for '" + e + "' not in node list");
      }

      e.dagre = {
        points: []
      };

      // Track edges that aren't self loops - layout does nothing for self
      // loops, so they can be skipped.
      if (source !== target) {
        var id = "id" in e ? e.id : "_E" + nextId++;
        e.dagre.minLen = e.minLen || 1;
        e.dagre.width = e.width || 0;
        e.dagre.height = e.height || 0;
        g.addEdge(id, source, target, e.dagre);
      }
    });

    return g;
  }

  function run () {
    var rankSep = self.rankSep();
    try {
      if (!nodes.length) {
        return;
      }

      // Build internal graph
      var g = init();

      // Make space for edge labels
      g.eachEdge(function(e, s, t, a) {
        a.minLen *= 2;
      });
      self.rankSep(rankSep / 2);

      // Reverse edges to get an acyclic graph, we keep the graph in an acyclic
      // state until the very end.
      acyclic.run(g);

      // Determine the rank for each node. Nodes with a lower rank will appear
      // above nodes of higher rank.
      rank.run(g);

      // Normalize the graph by ensuring that every edge is proper (each edge has
      // a length of 1). We achieve this by adding dummy nodes to long edges,
      // thus shortening them.
      normalize(g);

      // Order the nodes so that edge crossings are minimized.
      order.run(g);

      // Find the x and y coordinates for every node in the graph.
      position.run(g);

      // De-normalize the graph by removing dummy nodes and augmenting the
      // original long edges with coordinate information.
      undoNormalize(g);

      // Reverses points for edges that are in a reversed state.
      fixupEdgePoints(g);

      // Reverse edges that were revered previously to get an acyclic graph.
      acyclic.undo(g);
    } finally {
      self.rankSep(rankSep);
    }
  }

  // Assumes input graph has no self-loops and is otherwise acyclic.
  function normalize(g) {
    g.eachEdge(function(e, source, target) {
      var sourceRank = g.node(source).rank;
      var targetRank = g.node(target).rank;
      if (sourceRank + 1 < targetRank) {
        var prefix = "_D-" + e + "-";
        for (var u = source, rank = sourceRank + 1, i = 0; rank < targetRank; ++rank, ++i) {
          var v = prefix + rank;
          var node = { width: g.edge(e).width,
                       height: g.edge(e).height,
                       edgeId: e,
                       edge: g.edge(e),
                       source: g.source(e),
                       target: g.target(e),
                       index: i,
                       rank: rank,
                       dummy: true };
          g.addNode(v, node);
          g.addEdge(u + " -> " + v, u, v, {});
          u = v;
        }
        g.addEdge(u + " -> " + target, u, target, {});
        g.delEdge(e);
      }
    });
  }

  function undoNormalize(g) {
    var visited = {};

    g.eachNode(function(u, node) {
      if (node.dummy) {
        if (!g.hasEdge(node.edgeId)) {
          g.addEdge(node.edgeId, node.source, node.target, node.edge);
        }
        var points = g.edge(node.edgeId).points;
        points[node.index] = { x: node.x, y: node.y };
        g.delNode(u);
      }
    });
  }

  function fixupEdgePoints(g) {
    g.eachEdge(function(e, s, t, a) { if (a.reversed) a.points.reverse(); });
  }

  function delegateProperty(f) {
    return function() {
      if (!arguments.length) return f();
      f.apply(null, arguments);
      return self;
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import styled, { createGlobalStyle, withTheme } from 'styled-components'
import { Box, Flex } from '../components/Primitives'
import Navigation from '../components/Navigation'
import Footer from '../components/Footer'
import { useSiteMetadata } from '../utils/hooks'

import 'sanitize.css'

const GlobalStyles = createGlobalStyle`
  html {
    background-color: ${({ theme }) => theme.colors.orange};
    scroll-behavior: smooth;

    @media (prefers-reduced-motion: reduce) {
      scroll-behavior: auto;
    }

    @media print {
      background: none;
    }
  }

  body {
    background-color: transparent;
    background-image: url(/topography_900x900.png);
    background-repeat: repeat;
    background-position: top center;
    background-size: 900px;

    @media (min-resolution: 192dpi) {
      background-image: url(/topography_1800x1800.png)
    }

    @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
      background-image: url(/topography_1200x1200.png);
      background-size: 1200px;
    }

    @media
    (min-width: ${({ theme }) => theme.breakpoints[0]})
    and (min-resolution: 192dpi) {
      background-image: url(/topography_2400x2400.png)
    }
  }

  ::selection {
    background-color: ${({ theme }) => theme.colors.orange} !important;
    color: ${({ theme }) => theme.colors.darkGrey} !important;
  }

  a {
    color: inherit;
    text-decoration: none;
    text-decoration-skip: ink;
    text-decoration-skip-ink: auto;
  }

  @media print {
    nav, footer {
      display: none !important;
    }

    #main-content {
      margin-bottom: 0 !important;
    }
  }
`

const Border = styled(Flex)`
  min-height: 100vh;
  border-color: transparent !important;

  @media print {
    display: block;
    min-height: 0;
    background: transparent;
  }
`

const Content = styled(Box)`
  flex: 1;
  max-width: 100%;
  background-color: ${({ theme }) => theme.colors.white};
`

const Constraint = styled(Flex)`
  flex-flow: column nowrap;
  max-width: 64rem;
  height: 100%;
  margin-right: auto;
  margin-left: auto;
`

const Layout = ({ children, location, theme }) => {
  const { title, description } = useSiteMetadata()

  return (
    <>
      <Helmet htmlAttributes={{ lang: 'en' }}>
        <title>{title}</title>

        <meta name="description" content={description} />
        {/* theming */}
        <meta name="theme-color" content={theme.colors.nearWhite} />
        <meta name="apple-mobile-web-app-title" content="lowmess" />
        <meta name="application-name" content="lowmess" />
        <meta name="msapplication-TileColor" content="{theme.colors.orange}" />
        {/* icons */}
        <link
          rel="apple-touch-icon"
          sizes="180x180"
          href="/apple-touch-icon.png"
        />
        <link
          rel="icon"
          type="image/png"
          href="/favicon-32x32.png"
          sizes="32x32"
        />
        <link
          rel="icon"
          type="image/png"
          href="/favicon-16x16.png"
          sizes="16x16"
        />
        <link
          rel="mask-icon"
          href="/safari-pinned-tab.svg"
          color={theme.colors.orange}
        />
      </Helmet>

      <GlobalStyles />

      <Border border={[3, 4]}>
        <Content
          borderRadius={2}
          py={3}
          px={[3, 4]}
          fontFamily="sans-serif"
          color="darkGrey"
        >
          <Constraint>
            <Navigation location={location} />

            <Box is="main" id="main-content" mb={[5, 6]}>
              {children}
            </Box>

            <Footer />
          </Constraint>
        </Content>
      </Border>
    </>
  )
}

Layout.propTypes = {
  children: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
}

export default withTheme(Layout)
<commit_msg>:art: move background-image to border component<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import styled, { createGlobalStyle, withTheme } from 'styled-components'
import { Box, Flex } from '../components/Primitives'
import Navigation from '../components/Navigation'
import Footer from '../components/Footer'
import { useSiteMetadata } from '../utils/hooks'

import 'sanitize.css'

const GlobalStyles = createGlobalStyle`
  html {
    background-color: ${({ theme }) => theme.colors.orange};
    scroll-behavior: smooth;

    @media (prefers-reduced-motion: reduce) {
      scroll-behavior: auto;
    }

    @media print {
      background: none;
    }
  }

  ::selection {
    background-color: ${({ theme }) => theme.colors.orange} !important;
    color: ${({ theme }) => theme.colors.darkGrey} !important;
  }

  a {
    color: inherit;
    text-decoration: none;
    text-decoration-skip: ink;
    text-decoration-skip-ink: auto;
  }

  @media print {
    nav, footer {
      display: none !important;
    }

    #main-content {
      margin-bottom: 0 !important;
    }
  }
`

const Border = styled(Flex)`
  min-height: 100vh;
  border: ${({ theme }) => theme.borders[3]};
  border-color: transparent !important;
  background-color: transparent;
  background-image: url(/topography_900x900.png);
  background-repeat: repeat;
  background-position: top center;
  background-size: 900px;

  @media (min-resolution: 192dpi) {
    background-image: url(/topography_1800x1800.png);
  }

  @media (min-width: ${({ theme }) => theme.breakpoints[0]}) {
    border: ${({ theme }) => theme.borders[4]};
    background-image: url(/topography_1200x1200.png);
    background-size: 1200px;
  }

  @media (min-width: ${({ theme }) =>
      theme.breakpoints[0]}) and (min-resolution: 192dpi) {
    background-image: url(/topography_2400x2400.png);
  }

  @media print {
    display: block;
    min-height: 0;
    background: none;
  }
`

const Content = styled(Box)`
  flex: 1;
  max-width: 100%;
  background-color: ${({ theme }) => theme.colors.white};
`

const Constraint = styled(Flex)`
  flex-flow: column nowrap;
  max-width: 64rem;
  height: 100%;
  margin-right: auto;
  margin-left: auto;
`

const Layout = ({ children, location, theme }) => {
  const { title, description } = useSiteMetadata()

  return (
    <>
      <Helmet htmlAttributes={{ lang: 'en' }}>
        <title>{title}</title>

        <meta name="description" content={description} />
        {/* theming */}
        <meta name="theme-color" content={theme.colors.nearWhite} />
        <meta name="apple-mobile-web-app-title" content="lowmess" />
        <meta name="application-name" content="lowmess" />
        <meta name="msapplication-TileColor" content="{theme.colors.orange}" />
        {/* icons */}
        <link
          rel="apple-touch-icon"
          sizes="180x180"
          href="/apple-touch-icon.png"
        />
        <link
          rel="icon"
          type="image/png"
          href="/favicon-32x32.png"
          sizes="32x32"
        />
        <link
          rel="icon"
          type="image/png"
          href="/favicon-16x16.png"
          sizes="16x16"
        />
        <link
          rel="mask-icon"
          href="/safari-pinned-tab.svg"
          color={theme.colors.orange}
        />
      </Helmet>

      <GlobalStyles />

      <Border>
        <Content
          borderRadius={2}
          py={3}
          px={[3, 4]}
          fontFamily="sans-serif"
          color="darkGrey"
        >
          <Constraint>
            <Navigation location={location} />

            <Box is="main" id="main-content" mb={[5, 6]}>
              {children}
            </Box>

            <Footer />
          </Constraint>
        </Content>
      </Border>
    </>
  )
}

Layout.propTypes = {
  children: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
}

export default withTheme(Layout)
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Form from 'formsy-react';
import { Container, Button, Label, Segment, Divider } from 'semantic-ui-react';
import { Input } from '../src';

const styles = {
  root: {
    marginTop: 18,
    // padding: '0 24px 24px 24px',
  },

  customErrorLabel: {
    color: '#f00',
    textAling: 'center',
  },
};

export default class InputExamples extends Component {
  state = { formData: null }

  onValidSubmit = (formData) => alert(JSON.stringify(formData));   // eslint-disable-line

  render() {
    const errorLabel = ;

    // Shows errros with the  component
    const inputWithLabel = (
      <Input
        name="inputWithLabel"
        placeholder="Your primary email"
        icon="mail"
        label="Email"
        required
        validations="isEmail"
        validationErrors={{
          isEmail: 'This is not a valid email',
          isDefaultRequiredValue: 'Email is Required',
        }}
        errorLabel={ errorLabel }
        style={ styles.formElement }
      />
    );

    const instantValidation = (
      <Input
        instantValidation
        name="inputWithLabel"
        placeholder="Your primary email"
        label="Email"
        icon="mail"
        instantValidation
        required
        validations="isEmail"
        validationErrors={{
          isEmail: 'This is not a valid email',
          isDefaultRequiredValue: 'Email is Required',
        }}
        errorLabel={ errorLabel }
        style={ styles.formElement }
      />
    );

    const inputWithDefaultValue = (
      <Input
        name="inputWithDefaultValue"
        placeholder="Email"
        defaultValue="john.doe@test.com"
        icon="mail"
        iconPosition="left"
        required
        validations="isEmail"
        validationErrors={{
          isEmail: 'This is not a valid email',
          isDefaultRequiredValue: 'Email is Required',
        }}
        errorLabel={ errorLabel }
        style={ styles.formElement }
      />
    );

    const inputWithCustomErrorLabel = (
      <Input
        name="inputWithCustomErrorLabel"
        placeholder="Password"
        icon="lock"
        iconPosition="left"
        required
        validations="minLength:8"
        validationErrors={{
          minLength: 'Minimin of 8 characters',
          isDefaultRequiredValue: 'Password is Required',
        }}
        errorLabel={
 }
        rootStyle={ styles.formElement }
      />
    );

    return (
      <Container style={ styles.root }>
        <Form
          noValidate
          onValidSubmit={ this.onValidSubmit }
          ref={ref => this.form = ref }
        >
          <Segment>

 Input With Error Label

            { inputWithLabel }
          </Segment>

          <Segment>

 Instant Validation

            { instantValidation }
          </Segment>

          <Segment>

 Input With Custorm Error Label

            { inputWithCustomErrorLabel }
          </Segment>

          <Segment>

 Input With Default Value

            { inputWithDefaultValue }
          </Segment>

          <Divider/>

          <Button
            content="Submit"
            style={ styles.formElement }
            color="orange"
          />
          <Button
            type="button"
            onClick={ () => this.form.reset({
              inputWithDefaultValue: 'john.doe@test.com',
            })}
            content="Reset"
            color="black"
          />
        </Form>
      </Container>
    );
  }
}
<commit_msg>Update InputExamples.js<commit_after>import React, { Component } from 'react';
import Form from 'formsy-react';
import { Container, Button, Label, Segment, Divider } from 'semantic-ui-react';
import { Input } from '../src';

const styles = {
  root: {
    marginTop: 18,
    // padding: '0 24px 24px 24px',
  },

  customErrorLabel: {
    color: '#f00',
    textAlign: 'center',
  },
};

export default class InputExamples extends Component {
  state = { formData: null }

  onValidSubmit = (formData) => alert(JSON.stringify(formData));   // eslint-disable-line

  render() {
    const errorLabel = ;

    // Shows errros with the  component
    const inputWithLabel = (
      <Input
        name="inputWithLabel"
        placeholder="Your primary email"
        icon="mail"
        label="Email"
        required
        validations="isEmail"
        validationErrors={{
          isEmail: 'This is not a valid email',
          isDefaultRequiredValue: 'Email is Required',
        }}
        errorLabel={ errorLabel }
        style={ styles.formElement }
      />
    );

    const instantValidation = (
      <Input
        instantValidation
        name="inputWithLabel"
        placeholder="Your primary email"
        label="Email"
        icon="mail"
        instantValidation
        required
        validations="isEmail"
        validationErrors={{
          isEmail: 'This is not a valid email',
          isDefaultRequiredValue: 'Email is Required',
        }}
        errorLabel={ errorLabel }
        style={ styles.formElement }
      />
    );

    const inputWithDefaultValue = (
      <Input
        name="inputWithDefaultValue"
        placeholder="Email"
        defaultValue="john.doe@test.com"
        icon="mail"
        iconPosition="left"
        required
        validations="isEmail"
        validationErrors={{
          isEmail: 'This is not a valid email',
          isDefaultRequiredValue: 'Email is Required',
        }}
        errorLabel={ errorLabel }
        style={ styles.formElement }
      />
    );

    const inputWithCustomErrorLabel = (
      <Input
        name="inputWithCustomErrorLabel"
        placeholder="Password"
        icon="lock"
        iconPosition="left"
        required
        validations="minLength:8"
        validationErrors={{
          minLength: 'Minimin of 8 characters',
          isDefaultRequiredValue: 'Password is Required',
        }}
        errorLabel={
 }
        rootStyle={ styles.formElement }
      />
    );

    return (
      <Container style={ styles.root }>
        <Form
          noValidate
          onValidSubmit={ this.onValidSubmit }
          ref={ref => this.form = ref }
        >
          <Segment>

 Input With Error Label

            { inputWithLabel }
          </Segment>

          <Segment>

 Instant Validation

            { instantValidation }
          </Segment>

          <Segment>

 Input With Custorm Error Label

            { inputWithCustomErrorLabel }
          </Segment>

          <Segment>

 Input With Default Value

            { inputWithDefaultValue }
          </Segment>

          <Divider/>

          <Button
            content="Submit"
            style={ styles.formElement }
            color="orange"
          />
          <Button
            type="button"
            onClick={ () => this.form.reset({
              inputWithDefaultValue: 'john.doe@test.com',
            })}
            content="Reset"
            color="black"
          />
        </Form>
      </Container>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableHighlight,
} = React;

var Camera = require('react-native-camera'); //require the camera component

var ReactNativeCameraExample = React.createClass({
    getInitialState: function() {
        return ({
            capturedBase64: '',
            type: 'front'
        });
    },

    switchCamera: function() {
        var state = this.state;
        state.type = state.type === Camera.constants.Type.back
          ? Camera.constants.Type.front : Camera.constants.Type.back;
        this.setState(state);
    },

    render: function() {
        var component = this;
        return (
            <View style={styles.container}>
                <Camera style={styles.camera} ref="cam" type={this.state.type} captureTarget={Camera.constants.CaptureTarget.memory}></Camera>
                <Image
                source={{
                    isStatic: true,
                    uri: 'data:image/jpeg;base64,' + component.state.capturedBase64,
                }}
                style={styles.captured}
                />
            <TouchableHighlight style={styles.captureButton} onPress={function() {
                component.refs.cam.capture().then(function(capturedBase64) {
                    console.log(capturedBase64);
                    component.setState({ capturedBase64 });
                    setTimeout(() => component.setState({ capturedBase64: '' }), 5000);
                });
            }}>
                <Text style={{textAlign: 'center'}}>Capture</Text>
            </TouchableHighlight>

            <TouchableHighlight style={styles.switchButton} onPress={this.switchCamera}>
                <Text style={{textAlign: 'center'}}>Switch</Text>
            </TouchableHighlight>
            </View>
        );
    }
});

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    camera: {
        position: 'absolute',
        top: 0, right: 0, bottom: 0, left: 0
    },
    captured: {
        width: 200,
        height: 400
    },
    captureButton: {
        position: 'absolute',
        height: 50,
        left: 50, bottom: 20, right: 50,
        backgroundColor: '#FFFFFF',
        borderRadius: 20,
    },
    switchButton: {
        position: 'absolute',
        height: 50,
        left: 50, top: 20, right: 50,
        backgroundColor: '#FFFFFF',
        borderRadius: 20,
    },
});

AppRegistry.registerComponent('ReactNativeCameraExample', () => ReactNativeCameraExample);
<commit_msg>cleanup and compress captured image to prevent out-of-memory errors in example<commit_after>'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableHighlight,
} = React;

var Camera = require('react-native-camera'); //require the camera component

var ReactNativeCameraExample = React.createClass({
    getInitialState: function() {
        return ({
            capturedBase64: '',
            type: Camera.constants.Type.back
        });
    },

    switchCamera: function() {
        this.setState({ type: this.state.type === Camera.constants.Type.back ? Camera.constants.Type.front : Camera.constants.Type.back });
    },

    render: function() {
        var component = this;
        return (
            <View style={styles.container}>
                <Camera style={styles.camera} ref="cam" type={this.state.type} captureTarget={Camera.constants.CaptureTarget.memory}></Camera>
                <Image
                source={{
                    isStatic: true,
                    uri: 'data:image/jpeg;base64,' + component.state.capturedBase64,
                }}
                style={styles.captured}
                />
            <TouchableHighlight style={styles.captureButton} onPress={function() {
                component.refs.cam.capture({ sampleSize: 10 }).then(function(capturedBase64) {
                    component.setState({ capturedBase64 });
                    setTimeout(() => component.setState({ capturedBase64: '' }), 5000);
                });
            }}>
                <Text style={{textAlign: 'center'}}>Capture</Text>
            </TouchableHighlight>

            <TouchableHighlight style={styles.switchButton} onPress={this.switchCamera}>
                <Text style={{textAlign: 'center'}}>Switch</Text>
            </TouchableHighlight>
            </View>
        );
    }
});

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    camera: {
        position: 'absolute',
        top: 0, right: 0, bottom: 0, left: 0
    },
    captured: {
        width: 200,
        height: 400
    },
    captureButton: {
        position: 'absolute',
        height: 50,
        left: 50, bottom: 20, right: 50,
        backgroundColor: '#FFFFFF',
        borderRadius: 20,
    },
    switchButton: {
        position: 'absolute',
        height: 50,
        left: 50, top: 20, right: 50,
        backgroundColor: '#FFFFFF',
        borderRadius: 20,
    },
});

AppRegistry.registerComponent('ReactNativeCameraExample', () => ReactNativeCameraExample);
<|endoftext|>


<commit_before>(function(base, factory) {

    // RequireJS
    if (typeof define === "function" && define.amd) {
        define(factory);

    // CommonJS
    } else if (typeof exports === "object") {
        module.exports = factory();

    // Global Space
    } else {
        base.Composite = factory();
    }

}(this, function() {

    var ComSock = window.ComSock ? window.ComSock : require('comsock');

    if (!ComSock) {
        throw new Error('The Comsock library is required in order to use the Composite library.');
    }

    /**
     * Returns an object that will allow you to connect, send messages, and
     * listen for events upon.
     * @constructor
     */
    function Composite() {
        var _this = this;

        /**
         * comsock Socket
         * @member {ComSock}
         * @private
         */
        this._socket = new ComSock();

        /**
         * Store values to calculate time offset
         * @member {Array}
         * @private
         */
        this._timeOffset = [];

        /**
         * Store last 10 latency values to calculate average
         * @member {Array}
         * @private
         */
        this._latencyStore = [];

        /**
         * Listener event array
         * @member {Array}
         * @private
         */
        this._events = [];

        /**
         * Empty object to avoid new allocations
         * @member {Object}
         * @private
         */
        this._object = {};

        /**
         * Data object to avoid new allocations
         * @member {Object}
         * @property {string} type
         * @private
         */
        this._dataObject = {type: 'data'};

        /**
         * Update object to avoid new allocations
         * @member {Object}
         * @property {string} type
         * @private
         */
        this._updateObject = {type: 'update'};

        // URL Endpoints
        this._joinURL = '/app/join';
        this._updateURL = '/app/update';
        this._dataURL = '/app/data';
        this._syncURL = '/app/sync';
        this._startURL = '/app/start';
        this._stopURL = '/app/stop';
        this._disconnectURL = '/app/disconnect';
        this._pingURL = '/app/ping';

        /**
         * Container indicating if the client is connected to the composite
         * service.
         * @member {boolean}
         * @public
         */
        this.connected = false;

        /**
         * The UUID of the device given from the service, can be used as a way
         * to find the device(s) order.
         * @member {string}
         * @public
         */
        this.uuid = null;

        /**
         * The median time difference between the client's Date.now and the
         * services Date.now.
         * @member {number}
         * @public
         */
        this.timeDifference = null;

        /**
         * The average time it takes to send and recieve a message through
         * composite. Updated periodically throughout the application.
         * @member {number}
         * @public
         */
        this.latency = null;

        /**
         * If the device is the host device. This is determined by order joined,
         * and the first device to join is given host privelages. This is
         * updated during the device_update event as it's possible for the host
         * to drop connection. hosts can trigger the app_start and app_end
         * events.
         * @member {boolean}
         * @public
         */
        this.host = null;

        /**
         * The container for the devices geographic position in the form of
         * [{latitude}, {longitude}]. Location is not captured automatically,
         * and must be implemented manually, and is used for session management
         * @member {Array}
         * @public
         */
        this.location = [];

        /**
         * The session the device is currently a part of. This is set
         * automatically after successfully joining, and is required when
         * broadcasting updates and data.
         * @member {string}
         * @public
         */
        this.session = null; //game uuid

        /**
         * If the app is currently in the start state. This happens
         * automatically after the app_start event and is set to false after
         * the app_end event.
         * @member {boolean}
         * @public
         */
        this.active = false;

        // Listen for browser close
        window.onbeforeunload = function() {
            _this._unload();
            return null;
        };
    }

    /**
     * Send a disconnect event to the server
     * @method
     * @private
     */
    Composite.prototype._unload = function() {
        this._socket.sendMessage(this._object, this._disconnectURL, this._object);
        this._socket.disconnect();
        this.connected = false;
    };

    /**
     * Send a ping to the server
     * @method
     * @private
     */
    Composite.prototype._sendPing = function() {
        this._socket.sendMessage(this._object, this._pingURL, this._object);
    };

    /**
     * Route data received from server to appropriate method
     * @method
     * @private
     * @param {Object} data - Socket payload
     */
    Composite.prototype._handleData = function(data) {
        if (this.timeDifference) data.latency = this._calculateLatency(data);
        switch (data.type) {
            case 'init': this._init(data); break;
            case 'sync': this._sync(data); break;
            case 'join': this._join(data); break;
            case 'start': this._start(data); break;
            case 'stop': this._stop(data); break;
            case 'data': this._data(data); break;
            case 'update': this._update(data); break;
            case 'devices': this._devices(data); break;
            case 'disconnect': this._disconnect(data); break;
        }
    };

    /**
     * Calculate latency from received message using timeDifference
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @returns {number}
     */
    Composite.prototype._calculateLatency = function(data) {
        if (!data.serverTime) return 0;
        var difference = Date.now() - data.serverTime;
        var latency = Math.abs(Math.abs(difference) - Math.abs(this.timeDifference));
        this._updateLatency(latency);
        return latency;
    };

    /**
     * Keep track of 10 most recent messages in order to get an average latency
     * @method
     * @private
     * @param {number} latency
     */
    Composite.prototype._updateLatency = function(latency) {
        this._latencyStore.unshift(latency);
        if (this._latencyStore.length > 10) this._latencyStore.splice(10, 1);

        this.latency = 0;
        for (var i = 0; i < this._latencyStore.length; i++) {
            this.latency += this._latencyStore[i];
        }
        this.latency = Math.floor(this.latency / this._latencyStore.length);
    };

    /**
     * Find this device in the array of all game devices
     * @method
     * @private
     * @param {Array} devices - All game devices
     * @param {boolean} index - Flag to only return the index of the device
     * @returns {number|Array}
     */
    Composite.prototype._findMe = function(devices, index) {
        for (var i = devices.length-1; i > -1; i--) {
            var device = devices[i];
            if (device.uuid === this.uuid) {
                if (index) return i;
                device.me = true;
            }
        }

        return devices;
    };

    /**
     * Received init from server, start syncing time
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#init
     */
    Composite.prototype._init = function(data) {
        this.uuid = data.uuid;
        this.syncTime();
        this._fireEvent('init', data);
    };

    /**
     * App start event from server
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#app_start
     */
    Composite.prototype._start = function(data) {
        this.active = true;
        this._fireEvent('app_start', data.latency);
    };

    /**
     * App end event from server
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#app_end
     */
    Composite.prototype._stop = function(data) {
        this.active = false;
        this._fireEvent('app_end', data.latency);
    };

    /**
     * Received response for joining a game. Either you're entering the game or
     * receiving info about other players.
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#session_joined
     */
    Composite.prototype._join = function(data) {
        var _this = this;

        if (!this.session) {
            this.session = data.id;
            data.player = this._findMe(data.devices, true);
            if (data.player === 0) this.host = true;
            this._fireEvent('session_joined', data);

            setTimeout(function() {
                _this._socket.sendMessage({type: 'devices'}, '/app/' + _this.session, _this._object);
            }, 100);
        }
    };

    /**
     * Received updated list of devices
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#device_update
     */
    Composite.prototype._devices = function(data) {
        data.devices = this._findMe(data.devices);
        if (data.devices[0].me) this.host = true;
        else this.host = false;
        this._fireEvent('device_update', data);
    };

    /**
     * Handle when another player disconnects
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#device_disconnect
     */
    Composite.prototype._disconnect = function(data) {
        this._devices(data);
        this._fireEvent('device_disconnect');
    };

    /**
     * Received session data
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#data
     */
    Composite.prototype._data = function(data) {
        data.data.latency = data.latency;
        data.data.me = data.data.uuid === this.uuid;
        this._fireEvent('data', data.data);
    };

    /**
     * Received session update
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#update
     */
    Composite.prototype._update = function(data) {
        if (data.data.uuid === this.uuid) data.me = true;
        this._fireEvent('update', data);
    };

    /**
     * Received response from server time sync. Calculate the difference in
     * time, and pick the median when 11 responses are stored.
     * @method
     * @private
     * @param {Object} data - Socket payload
     */
    Composite.prototype._sync = function(data) {
        var currentTime = Date.now();
        var latency = Math.round((currentTime - data.time) * 0.5);
        var serverTime = data.serverTime;
        currentTime -= latency;
        this._updateLatency(latency);

        var difference = currentTime - serverTime;
        this._timeOffset.push(difference);

        if (this._timeOffset.length === 11) {
            this._timeOffset.sort(function(a, b) {
               return a - b;
            });

            this.timeDifference = this._timeOffset[5];
            this._timeOffset = null;
            this._fireEvent('synced');
        } else {
            this.syncTime();
        }
    };

    /**
     * Fire event to any outside listeners
     * @method
     * @private
     * @param {string} evt - The event identifier
     * @param {Object} data - Event payload
     */
    Composite.prototype._fireEvent = function(evt, data) {
        var events = this._events;
        for (var i = 0; i < events.length; i++) {
            var e = events[i];
            if (e.evt === evt) e.callback(data);
        }
    };

    /**
     * Connect to the specified server and attach the messageCallback listener
     * @method
     * @public
     * @param {string} url - The url to which the socket connects
     */
    Composite.prototype.connect = function(url) {
        var _this = this;

        this._socket.connect(url);
        this._socket.messageCallback = function(data) {

            if (data.command === 'CONNECTED') {
                this.connected = true;

                // Start ping interval
                setInterval(function() {
                    _this._sendPing();
                }, 250);
            } else if (data.body) {
                this._handleData(JSON.parse(JSON.parse(data.body)));
            }
        }.bind(this);
    };

    /**
     * Trigger the time syncing process
     * @method
     * @public
     */
    Composite.prototype.syncTime = function() {
        if (!this._timeOffset) this._timeOffset = [];
        this._socket.sendMessage({'type': 'sync', time: Date.now()}, this._syncURL, this._object);
    };

    /**
     * Attach an event listener for the specified string
     * @method
     * @public
     * @param {string} evt - The event to bind to
     * @param {Function} callback - The function to register on evt
     */
    Composite.prototype.on = function(evt, callback) {
        var e = {};
        e.evt = evt;
        e.callback = callback;
        this._events.push(e);
    };

    /**
     * Remove event listener
     * @method
     * @public
     * @param {string} evt - The event to unbind from
     * @param {function} callback - The function to unregister
     */
    Composite.prototype.off = function(evt, callback) {
        var events = this._events;
        for (var i = 0; i < events.length; i++) {
            var e = events[i];
            if (e.evt === evt && e.callback === callback) events.splice(i, 1);
        }
    };

    /**
     * Join a game
     * @method
     * @public
     * @param {Object} data - Socket payload
     */
    Composite.prototype.join = function(data) {
        if (!this.uuid) throw new Error('Must wait until connection is established before joining a game.');
        if (!this.location[0]) throw new Error('Composite::location must be set before a game can be joined.');
        data = data || {};
        data.type = data.type || 'exit';
        data.geo = data.geo || this.location;
        data.device = data.device || {};
        data.device.uuid = this.uuid;
        this._socket.sendMessage(data, this._joinURL, this._object);
    };

    /**
     * Send message through the Data channel
     * @method
     * @public
     * @param {Object} data - Socket payload
     */
    Composite.prototype.sendData = function(data) {
        if (!data || !this.session) return;
        data.uuid = this.uuid;
        this._dataObject.data = data;
        this._dataObject.type = 'data';
        this._socket.sendMessage(this._dataObject, '/app/' + this.session, this._object);
    };

    /**
     * Send message through the Update channel
     * @method
     * @public
     * @param {Object} data - Socket payload
     */
    Composite.prototype.sendUpdate = function(data) {
        if (!data || !this.session) return;
        data.uuid = this.uuid;
        this._updateObject.type = 'update';
        this._updateObject.data = data;
        this._socket.sendMessage(this._updateObject, '/app/' + this.session, this._object);
    };

    /**
     * Start the game
     * @method
     * @public
     */
    Composite.prototype.startApp = function() {
        if (this.host) this._socket.sendMessage({type: 'start'}, '/app/' + this.session, this._object);
    };

    /**
     * The game has ended, reopen it so more people can join
     * @method
     * @public
     */
    Composite.prototype.endApp = function() {
        if (this.host) this._socket.sendMessage({type: 'stop'}, '/app/' + this.session, this._object);
    };

    /**
     * Force disconnect
     * @method
     * @public
     */
    Composite.prototype.disconnect = function() {
        this._unload();
    };

    return Composite;
}));
<commit_msg>Update composite.js<commit_after>(function(base, factory) {

    // RequireJS
    if (typeof define === "function" && define.amd) {
        define(factory);

    // CommonJS
    } else if (typeof exports === "object") {
        module.exports = factory();

    // Global Space
    } else {
        base.Composite = factory();
    }

}(this, function() {

    var ComSock = window.ComSock ? window.ComSock : require('comsock');

    if (!ComSock) {
        throw new Error('The Comsock library is required in order to use the Composite library.');
    }

    /**
     * Returns an object that will allow you to connect, send messages, and
     * listen for events upon.
     * @constructor
     */
    function Composite() {
        var _this = this;

        /**
         * comsock Socket
         * @member {ComSock}
         * @private
         */
        this._socket = new ComSock();

        /**
         * Store values to calculate time offset
         * @member {Array}
         * @private
         */
        this._timeOffset = [];

        /**
         * Store last 10 latency values to calculate average
         * @member {Array}
         * @private
         */
        this._latencyStore = [];

        /**
         * Listener event array
         * @member {Array}
         * @private
         */
        this._events = [];

        /**
         * Empty object to avoid new allocations
         * @member {Object}
         * @private
         */
        this._object = {};

        /**
         * Data object to avoid new allocations
         * @member {Object}
         * @property {string} type
         * @private
         */
        this._dataObject = {type: 'data'};

        /**
         * Update object to avoid new allocations
         * @member {Object}
         * @property {string} type
         * @private
         */
        this._updateObject = {type: 'update'};

        // URL Endpoints
        this._joinURL = '/app/join';
        this._updateURL = '/app/update';
        this._dataURL = '/app/data';
        this._syncURL = '/app/sync';
        this._startURL = '/app/start';
        this._stopURL = '/app/stop';
        this._disconnectURL = '/app/disconnect';
        this._pingURL = '/app/ping';

        /**
         * Container indicating if the client is connected to the composite
         * service.
         * @member {boolean}
         * @public
         */
        this.connected = false;

        /**
         * The UUID of the device given from the service, can be used as a way
         * to find the device(s) order.
         * @member {string}
         * @public
         */
        this.uuid = null;

        /**
         * The median time difference between the client's Date.now and the
         * services Date.now.
         * @member {number}
         * @public
         */
        this.timeDifference = null;

        /**
         * The average time it takes to send and recieve a message through
         * composite. Updated periodically throughout the application.
         * @member {number}
         * @public
         */
        this.latency = null;

        /**
         * If the device is the host device. This is determined by order joined,
         * and the first device to join is given host privelages. This is
         * updated during the device_update event as it's possible for the host
         * to drop connection. hosts can trigger the app_start and app_end
         * events.
         * @member {boolean}
         * @public
         */
        this.host = null;

        /**
         * The container for the devices geographic position in the form of
         * [{latitude}, {longitude}]. Location is not captured automatically,
         * and must be implemented manually, and is used for session management
         * @member {Array}
         * @public
         */
        this.location = [];

        /**
         * The session the device is currently a part of. This is set
         * automatically after successfully joining, and is required when
         * broadcasting updates and data.
         * @member {string}
         * @public
         */
        this.session = null; //game uuid

        /**
         * If the app is currently in the start state. This happens
         * automatically after the app_start event and is set to false after
         * the app_end event.
         * @member {boolean}
         * @public
         */
        this.active = false;

        // Listen for browser close
        window.onbeforeunload = function() {
            _this._unload();
            return null;
        };
    }

    /**
     * Send a disconnect event to the server
     * @method
     * @private
     */
    Composite.prototype._unload = function() {
        this._socket.sendMessage(this._object, this._disconnectURL, this._object);
        this._socket.disconnect();
        this.connected = false;
    };

    /**
     * Send a ping to the server
     * @method
     * @private
     */
    Composite.prototype._sendPing = function() {
        this._socket.sendMessage(this._object, this._pingURL, this._object);
    };

    /**
     * Route data received from server to appropriate method
     * @method
     * @private
     * @param {Object} data - Socket payload
     */
    Composite.prototype._handleData = function(data) {
        if (this.timeDifference) data.latency = this._calculateLatency(data);
        switch (data.type) {
            case 'init': this._init(data); break;
            case 'sync': this._sync(data); break;
            case 'join': this._join(data); break;
            case 'start': this._start(data); break;
            case 'stop': this._stop(data); break;
            case 'data': this._data(data); break;
            case 'update': this._update(data); break;
            case 'devices': this._devices(data); break;
            case 'disconnect': this._disconnect(data); break;
        }
    };

    /**
     * Calculate latency from received message using timeDifference
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @returns {number}
     */
    Composite.prototype._calculateLatency = function(data) {
        if (!data.serverTime) return 0;
        var difference = Date.now() - data.serverTime;
        var latency = Math.abs(Math.abs(difference) - Math.abs(this.timeDifference));
        this._updateLatency(latency);
        return latency;
    };

    /**
     * Keep track of 10 most recent messages in order to get an average latency
     * @method
     * @private
     * @param {number} latency
     */
    Composite.prototype._updateLatency = function(latency) {
        this._latencyStore.unshift(latency);
        if (this._latencyStore.length > 10) this._latencyStore.splice(10, 1);

        this.latency = 0;
        for (var i = 0; i < this._latencyStore.length; i++) {
            this.latency += this._latencyStore[i];
        }
        this.latency = Math.floor(this.latency / this._latencyStore.length);
    };

    /**
     * Find this device in the array of all game devices
     * @method
     * @private
     * @param {Array} devices - All game devices
     * @param {boolean} index - Flag to only return the index of the device
     * @returns {number|Array}
     */
    Composite.prototype._findMe = function(devices, index) {
        for (var i = devices.length-1; i > -1; i--) {
            var device = devices[i];
            if (device.uuid === this.uuid) {
                if (index) return i;
                device.me = true;
            }
        }

        return devices;
    };

    /**
     * Received init from server, start syncing time
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#init
     */
    Composite.prototype._init = function(data) {
        this.uuid = data.uuid;
        this.syncTime();
        this._fireEvent('init', data);
    };

    /**
     * App start event from server
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#app_start
     */
    Composite.prototype._start = function(data) {
        this.active = true;
        this._fireEvent('app_start', data.latency);
    };

    /**
     * App end event from server
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#app_end
     */
    Composite.prototype._stop = function(data) {
        this.active = false;
        this._fireEvent('app_end', data.latency);
    };

    /**
     * Received response for joining a game. Either you're entering the game or
     * receiving info about other players.
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#session_joined
     */
    Composite.prototype._join = function(data) {
        var _this = this;

        if (!this.session) {
            this.session = data.id;
            data.player = this._findMe(data.devices, true);
            if (data.player === 0) this.host = true;
            this._fireEvent('session_joined', data);

            setTimeout(function() {
                _this._socket.sendMessage({type: 'devices'}, '/app/' + _this.session, _this._object);
            }, 100);
        }
    };

    /**
     * Received updated list of devices
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#device_update
     */
    Composite.prototype._devices = function(data) {
        data.devices = this._findMe(data.devices);
        if (data.devices[0].me) this.host = true;
        else this.host = false;
        this._fireEvent('device_update', data);
    };

    /**
     * Handle when another player disconnects
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#device_disconnect
     */
    Composite.prototype._disconnect = function(data) {
        this._devices(data);
        this._fireEvent('device_disconnect');
    };

    /**
     * Received session data
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#data
     */
    Composite.prototype._data = function(data) {
        data.data.latency = data.latency;
        data.data.me = data.data.uuid === this.uuid;
        this._fireEvent('data', data.data);
    };

    /**
     * Received session update
     * @method
     * @private
     * @param {Object} data - Socket payload
     * @fires Composite#update
     */
    Composite.prototype._update = function(data) {
        if (data.data.uuid === this.uuid) data.me = true;
        this._fireEvent('update', data);
    };

    /**
     * Received response from server time sync. Calculate the difference in
     * time, and pick the median when 11 responses are stored.
     * @method
     * @private
     * @param {Object} data - Socket payload
     */
    Composite.prototype._sync = function(data) {
        var currentTime = Date.now();
        var latency = Math.round((currentTime - data.time) * 0.5);
        var serverTime = data.serverTime;
        currentTime -= latency;
        this._updateLatency(latency);

        var difference = currentTime - serverTime;
        this._timeOffset.push(difference);

        if (this._timeOffset.length === 11) {
            this._timeOffset.sort(function(a, b) {
               return a - b;
            });

            this.timeDifference = this._timeOffset[5];
            this._timeOffset = null;
            this._fireEvent('synced');
        } else {
            this.syncTime();
        }
    };

    /**
     * Fire event to any outside listeners
     * @method
     * @private
     * @param {string} evt - The event identifier
     * @param {Object} data - Event payload
     */
    Composite.prototype._fireEvent = function(evt, data) {
        var events = this._events;
        for (var i = 0; i < events.length; i++) {
            var e = events[i];
            if (e.evt === evt) e.callback(data);
        }
    };

    /**
     * Connect to the specified server and attach the messageCallback listener
     * @method
     * @public
     * @param {string} url - The url to which the socket connects
     */
    Composite.prototype.connect = function(url) {
        var _this = this;

        this._socket.connect(url);
        this._socket.messageCallback = function(data) {

            if (data.command === 'CONNECTED') {
                this.connected = true;

                // Start ping interval
                setInterval(function() {
                    _this._sendPing();
                }, 250);
            } else if (data.body) {
                this._handleData(JSON.parse(data.body));
            }
        }.bind(this);
    };

    /**
     * Trigger the time syncing process
     * @method
     * @public
     */
    Composite.prototype.syncTime = function() {
        if (!this._timeOffset) this._timeOffset = [];
        this._socket.sendMessage({'type': 'sync', time: Date.now()}, this._syncURL, this._object);
    };

    /**
     * Attach an event listener for the specified string
     * @method
     * @public
     * @param {string} evt - The event to bind to
     * @param {Function} callback - The function to register on evt
     */
    Composite.prototype.on = function(evt, callback) {
        var e = {};
        e.evt = evt;
        e.callback = callback;
        this._events.push(e);
    };

    /**
     * Remove event listener
     * @method
     * @public
     * @param {string} evt - The event to unbind from
     * @param {function} callback - The function to unregister
     */
    Composite.prototype.off = function(evt, callback) {
        var events = this._events;
        for (var i = 0; i < events.length; i++) {
            var e = events[i];
            if (e.evt === evt && e.callback === callback) events.splice(i, 1);
        }
    };

    /**
     * Join a game
     * @method
     * @public
     * @param {Object} data - Socket payload
     */
    Composite.prototype.join = function(data) {
        if (!this.uuid) throw new Error('Must wait until connection is established before joining a game.');
        if (!this.location[0]) throw new Error('Composite::location must be set before a game can be joined.');
        data = data || {};
        data.type = data.type || 'exit';
        data.geo = data.geo || this.location;
        data.device = data.device || {};
        data.device.uuid = this.uuid;
        this._socket.sendMessage(data, this._joinURL, this._object);
    };

    /**
     * Send message through the Data channel
     * @method
     * @public
     * @param {Object} data - Socket payload
     */
    Composite.prototype.sendData = function(data) {
        if (!data || !this.session) return;
        data.uuid = this.uuid;
        this._dataObject.data = data;
        this._dataObject.type = 'data';
        this._socket.sendMessage(this._dataObject, '/app/' + this.session, this._object);
    };

    /**
     * Send message through the Update channel
     * @method
     * @public
     * @param {Object} data - Socket payload
     */
    Composite.prototype.sendUpdate = function(data) {
        if (!data || !this.session) return;
        data.uuid = this.uuid;
        this._updateObject.type = 'update';
        this._updateObject.data = data;
        this._socket.sendMessage(this._updateObject, '/app/' + this.session, this._object);
    };

    /**
     * Start the game
     * @method
     * @public
     */
    Composite.prototype.startApp = function() {
        if (this.host) this._socket.sendMessage({type: 'start'}, '/app/' + this.session, this._object);
    };

    /**
     * The game has ended, reopen it so more people can join
     * @method
     * @public
     */
    Composite.prototype.endApp = function() {
        if (this.host) this._socket.sendMessage({type: 'stop'}, '/app/' + this.session, this._object);
    };

    /**
     * Force disconnect
     * @method
     * @public
     */
    Composite.prototype.disconnect = function() {
        this._unload();
    };

    return Composite;
}));
<|endoftext|>


<commit_before>/**
 * @fileOverview WebRTC Framework to facilitate the development of Applications that seamless interoperate between each other
 * @author Paulo Chainho <paulo-g-chainho@ptinovacao.pt>
 * @author Steffen Druesedow <Steffen.Druesedow@telekom.de>
 * @author Miguel Seijo Simo <Miguel.Seijo@telekom.de>
 * @author Vasco Amaral <vasco-m-amaral@ptinovacao.pt>
 * @author Kay Haensge <Kay.Haensge@telekom.de>
 * @author Luis Oliveira <luis-f-oliveira@ptinovacao.pt>
 */

/*
 * TODO: State-machine for transitions of IdentityStatus should be described
 * TODO: Questions about MessagingStub-Listeners
 * Why do the addListener and removeListener methods have a Message as second param?
 * What is the purpose? Which message type would it be?
 */

/**
 * @class
 * The Identity represents a user and contains all information needed to support
 * Conversation services including the service endpoint to retrieve the protocol stack
 * (Messaging Stub) that will be used to establish a signalling channel
 * with the Identity domain messaging server.
 *
NOTE: Identities are only created by using the corresponding create-methods of the Idp.
 * This constructor will throw an exception if it is used directly.
 */
function Identity(rtcIdentity, idpRtcIdentity) {
	console.log("idpRtcIdentity", idpRtcIdentity)
	if (rtcIdentity)
		throw "Illegal attempt to create an Identity --> Please use Idp.getInstance().createIdentity(...) instead."

	// We use a string, RTCIdentityAssertion is not available.
	this.rtcIdentity = idpRtcIdentity;
	this.id = new Date().getTime();
	console.log("####################");
	console.log("created new Identiy for: " + this.rtcIdentity + " with id = " + this.id);
	console.trace();
	console.log("####################");
	this.idp = "";
	this.presence = {
		status: IdentityStatus.IDLE
				//app: this.prototype.resolveMyApp()
	};

	// TODO: initialise presence status
	//this.presence.status = IdentityStatus.IDLE; // not initialized yet TODO: do state changes in a central place
	//this.presence.app = this.prototype.resolveMyApp(); // not initialized yet TODO: do state changes in a central place

	//this.status = IdentityStatus.IDLE; // TODO: to be replaced with Identity.presence
	this.context;

	this.sessionId = "";

	this.messagingStubLibUrl = "";
	this.messagingStub;
	this.notificationAddress;
	this.messagingAddress;
	this.credentials;
	this.tone;
	this.avatar;
}
;

/**
 * resolveMyApp
 *
 * @returns AppType ... private function to resolve the type of Application used by the user
 *
 */
Identity.prototype.resolveMyApp = function () {
	// TODO: to check what kind of App is used:
	//     - Case is Web App running in a mobile browser it should return AppType.MOBILE_WEB_APP
	//     - Case is Mobile Web App running in a pc browser it should return AppType.WEB_APP

};

/**
 * This method downloads a messaging stub and keeps a reference to it in a local
 * attribute, if not already done before. That means the download will only be performed once.
 * After download it invokes the given callback with a reference to the downloaded MessagingStub.
 *
 * @param callback {callback(MessagingStub)} callback that is invoked with messagingStub as param; if download failed then the stub param is empty
 */
Identity.prototype.resolve = function (callback) {
	var that = this;
	console.log("resolving identity: " + this.rtcIdentity);
	if (!this.messagingStub.impl) {
		// not resolved yet --> let's ask Idp for a stub with the same downloadUri
		var knownStub = Idp.getInstance().getResolvedStub(this.messagingStubLibUrl);
		if (knownStub) {
			this.messagingStub = knownStub;
			callback(this.messagingStub);
			return;
		}

		console.log("downloading Messaging stub from: " + this.messagingStubLibUrl);
		// apply require.js config; remove ".js" extension from path
		require.config({
			paths: {
				"stub": this.messagingStubLibUrl.substring(0, this.messagingStubLibUrl.length - 3)
			},
			// hand-over the connectURL as configuration to the stub module
			config: {
				"stub": {
					"connectURL": that.connectURL
				}
			}
		});
		require(["stub"], function (stubImpl) {
			// assign the new messagingStub object to the "impl" field of the container stub
			that.messagingStub.setImpl(stubImpl);
			that.messagingStub.message = "stub downloaded from: " + that.messagingStubLibUrl;
			// return container-stub in callback
			callback(that.messagingStub);
		});
	}
	else {
		console.log(this.rtcIdentity + ": no need to download stub from: " + this.messagingStubLibUrl);
		callback(this.messagingStub);
	}
};

/**
 *
 * This method subscribes to add a listener to receive status information (CONTEXT message type) from the user associated to this Identity.
 * The Signalling on the fly concept is also used to ensure cross domain Presence management interoperability
 * by calling the Identiy.resolve() function
 * @param subscriber :
 *            Identity ... The identity of the subscriber
 * @param type :
 *            SubscriptionType ... The subscription type
 *
 */
Identity.prototype.subscribe = function (subscriber) {
	// TODO: get messagingStub by invoking Identity.resolve() function, add Identity as messagingStub listener (including the subscription contextId)  and send SUBSCRIBE message through the MessagingStub
	this.context = guid(); //check this
	that = this;
	var from = subscriber.rtcIdentity;
	var to = this.rtcIdentity;
	console.log("Identity to subscribe", to);
	console.log("Identity subscriber", subscriber);

	console.log("Identity subscribe");
	this.resolve(function (stub) {

		//message.contextId = guid();
		stub.addListener(that.onMessage(that), "presence." + to, that.context);
		stub.sendMessage(MessageFactory.createSubscribeMessage(from, to, ""));
	});
};

/**
 *
 * This method removes a listener previously added with "subscribe()"  function to receive status information
 * (CONTEXT message type) from the user associated to this Identity
 * @param subscriber :
 *            Identity ... The identity of the subscriber
 * @param type :
 *            SubscriptionType ... The subscription type
 *
 */
Identity.prototype.unsubscribe = function (subscriber, type) {
	// TODO: get messagingStub by invoking Identity.resolve() function and send BYE message through the MessagingStub
	this.messagingStub.sendMessage(MessageFactory.createUnsubscribeMessage(message));
};

/**
 * To set Identity status and to publish it by sending a CONTEXT message to address "rtcIdentity.presence"
 *
 * @param status :
 *            String ... The status to set
 *
 */

Identity.prototype.setStatus = function (status, login) {
	//var message = new Object();
	//message.contextId = this.context;

	//from = identity.rtcIdentity;
	//to = this.rtcIdentity;
	var that = this;
	console.log("Identity SetStatus: ", status);

	this.presence.status = status;// TODO: change to that.presence.status = status;
	this.messagingStub.sendMessage(MessageFactory.createContextMessage(that.rtcIdentity, "", status, login, that.sessionId));
	// TODO: check status transitions according to IdentityStatus state machine
	// TODO: Send a CONTEXT message to address "rtcIdentity.presence"
};

/**getPresence
 * To set Identity presence and to publish it by sending a CONTEXT message to address "rtcIdentity.presence"
 *
 * @param presence :
 *            String ... The presence to set
 *
 */

Identity.prototype.setPresence = function (presence) {

	var that = this;
	that.presence.status = presence;

	// TODO: check status transitions according to IdentityStatus state machine
	// TODO: Send a CONTEXT message to address "rtcIdentity.presence"
};

/**
 * To set Identity context and to publish it by sending a CONTEXT message to address "rtcIdentity.context"
 *
 * @param context :
 *            String ... The context to set
 *
 */

Identity.prototype.setContext = function (context) {

	this.context = context;
	this.messagingStub.sendMessage(MessageFactory.createContextMessage());
	// TODO: Send a CONTEXT message to address "rtcIdentity.context"
};

/**
 * getStatus
 *
 * @returns IdentityStatus ... gets the presence status attribute for this Identity
 *
 */
Identity.prototype.getStatus = function () {
// TODO: change to return this.presence.status;
	return this.presence.status;
};

/**
 * getPresence
 *
 * @returns Presence ... gets the presence  attribute for this Identity
 *
 */
Identity.prototype.getPresence = function () {
	return this.presence;
};

/**
 * sendMessage
 *
 * @sendmessage ...sendMessage
 *
 */

Identity.prototype.sendMessage = function (message) {
	this.messagingStub.sendMessage(message);
};

/**
 * getContext
 *
 * @returns ContextData ... gets the context attribute for this Identity
 *
 */
Identity.prototype.getContext = function () {
	return this.context;
};

/**
 * getMessagingStubDownloadUrl
 *
 * @returns URL ... gets the URL to download the MessagingStub for this Identity
 *
 */
Identity.prototype.getMessagingStubDownloadUrl = function () {
	//will be needed to the Idp
	return this.messagingStubDownloadUrl;
};

/**
 *
 * OnLastMessagingListerner is invoked by the MessagingStub as soon as the last listener has un-subscribed.
 * We use this callback to disconnect and unload the MessagingStub.
 *
 */
Identity.prototype.onLastMessagingListener = function () {
	if (this.messagingStub)
		this.messagingStub.disconnect();
	// "undefine" messagingStub
	delete this.messagingStub;
};

/**@ignore
 * Simple function to load an external Javascript file at runtime.
 * TODO: This might be a security risk, because the file is executed immediately.
 * @param url ... url of the file to be loaded
 */
Identity.prototype.loadJSfile = function (url) {
	var fileref = document.createElement('script');
	fileref.setAttribute("type", "text/javascript");
	fileref.setAttribute("src", url);
	if (typeof fileref != "undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);
};

Identity.prototype.onMessage = function (message) {
	console.log("MESSAGES-->", message)
	switch (message.type) {
		case MessageType.CONTEXT:
			this.setStatus(message.identityPresence.status);
			break;
		case MessageType.ACCEPTED:
			break;
		case MessageType.NOT_ACCEPTED:
			break;
		case MessageType.CANCEL:
			break;
		default:
			break;
	}

}<commit_msg>add random suffix to download uri<commit_after>/**
 * @fileOverview WebRTC Framework to facilitate the development of Applications that seamless interoperate between each other
 * @author Paulo Chainho <paulo-g-chainho@ptinovacao.pt>
 * @author Steffen Druesedow <Steffen.Druesedow@telekom.de>
 * @author Miguel Seijo Simo <Miguel.Seijo@telekom.de>
 * @author Vasco Amaral <vasco-m-amaral@ptinovacao.pt>
 * @author Kay Haensge <Kay.Haensge@telekom.de>
 * @author Luis Oliveira <luis-f-oliveira@ptinovacao.pt>
 */

/*
 * TODO: State-machine for transitions of IdentityStatus should be described
 * TODO: Questions about MessagingStub-Listeners
 * Why do the addListener and removeListener methods have a Message as second param?
 * What is the purpose? Which message type would it be?
 */

/**
 * @class
 * The Identity represents a user and contains all information needed to support
 * Conversation services including the service endpoint to retrieve the protocol stack
 * (Messaging Stub) that will be used to establish a signalling channel
 * with the Identity domain messaging server.
 *
NOTE: Identities are only created by using the corresponding create-methods of the Idp.
 * This constructor will throw an exception if it is used directly.
 */
function Identity(rtcIdentity, idpRtcIdentity) {
	console.log("idpRtcIdentity", idpRtcIdentity)
	if (rtcIdentity)
		throw "Illegal attempt to create an Identity --> Please use Idp.getInstance().createIdentity(...) instead."

	// We use a string, RTCIdentityAssertion is not available.
	this.rtcIdentity = idpRtcIdentity;
	this.id = new Date().getTime();
	console.log("####################");
	console.log("created new Identiy for: " + this.rtcIdentity + " with id = " + this.id);
	console.trace();
	console.log("####################");
	this.idp = "";
	this.presence = {
		status: IdentityStatus.IDLE
				//app: this.prototype.resolveMyApp()
	};

	// TODO: initialise presence status
	//this.presence.status = IdentityStatus.IDLE; // not initialized yet TODO: do state changes in a central place
	//this.presence.app = this.prototype.resolveMyApp(); // not initialized yet TODO: do state changes in a central place

	//this.status = IdentityStatus.IDLE; // TODO: to be replaced with Identity.presence
	this.context;

	this.sessionId = "";

	this.messagingStubLibUrl = "";
	this.messagingStub;
	this.notificationAddress;
	this.messagingAddress;
	this.credentials;
	this.tone;
	this.avatar;
}
;

/**
 * resolveMyApp
 *
 * @returns AppType ... private function to resolve the type of Application used by the user
 *
 */
Identity.prototype.resolveMyApp = function () {
	// TODO: to check what kind of App is used:
	//     - Case is Web App running in a mobile browser it should return AppType.MOBILE_WEB_APP
	//     - Case is Mobile Web App running in a pc browser it should return AppType.WEB_APP

};

/**
 * This method downloads a messaging stub and keeps a reference to it in a local
 * attribute, if not already done before. That means the download will only be performed once.
 * After download it invokes the given callback with a reference to the downloaded MessagingStub.
 *
 * @param callback {callback(MessagingStub)} callback that is invoked with messagingStub as param; if download failed then the stub param is empty
 */
Identity.prototype.resolve = function (callback) {
	var that = this;
	console.log("resolving identity: " + this.rtcIdentity);
	if (!this.messagingStub.impl) {
		// not resolved yet --> let's ask Idp for a stub with the same downloadUri
		var knownStub = Idp.getInstance().getResolvedStub(this.messagingStubLibUrl);
		if (knownStub) {
			this.messagingStub = knownStub;
			callback(this.messagingStub);
			return;
		}

		console.log("downloading Messaging stub from: " + this.messagingStubLibUrl);
		// apply require.js config; remove ".js" extension from path
		require.config({
			paths: {
				"stub": this.messagingStubLibUrl.substring(0, this.messagingStubLibUrl.length - 3)
			},
			// hand-over the connectURL as configuration to the stub module
			config: {
				"stub": {
					"connectURL": that.connectURL
				}
			},
			urlArgs: "r=" +  (new Date()).getTime()
		});
		require(["stub"], function (stubImpl) {
			// assign the new messagingStub object to the "impl" field of the container stub
			that.messagingStub.setImpl(stubImpl);
			that.messagingStub.message = "stub downloaded from: " + that.messagingStubLibUrl;
			// return container-stub in callback
			callback(that.messagingStub);
		});
	}
	else {
		console.log(this.rtcIdentity + ": no need to download stub from: " + this.messagingStubLibUrl);
		callback(this.messagingStub);
	}
};

/**
 *
 * This method subscribes to add a listener to receive status information (CONTEXT message type) from the user associated to this Identity.
 * The Signalling on the fly concept is also used to ensure cross domain Presence management interoperability
 * by calling the Identiy.resolve() function
 * @param subscriber :
 *            Identity ... The identity of the subscriber
 * @param type :
 *            SubscriptionType ... The subscription type
 *
 */
Identity.prototype.subscribe = function (subscriber) {
	// TODO: get messagingStub by invoking Identity.resolve() function, add Identity as messagingStub listener (including the subscription contextId)  and send SUBSCRIBE message through the MessagingStub
	this.context = guid(); //check this
	that = this;
	var from = subscriber.rtcIdentity;
	var to = this.rtcIdentity;
	console.log("Identity to subscribe", to);
	console.log("Identity subscriber", subscriber);

	console.log("Identity subscribe");
	this.resolve(function (stub) {

		//message.contextId = guid();
		stub.addListener(that.onMessage(that), "presence." + to, that.context);
		stub.sendMessage(MessageFactory.createSubscribeMessage(from, to, ""));
	});
};

/**
 *
 * This method removes a listener previously added with "subscribe()"  function to receive status information
 * (CONTEXT message type) from the user associated to this Identity
 * @param subscriber :
 *            Identity ... The identity of the subscriber
 * @param type :
 *            SubscriptionType ... The subscription type
 *
 */
Identity.prototype.unsubscribe = function (subscriber, type) {
	// TODO: get messagingStub by invoking Identity.resolve() function and send BYE message through the MessagingStub
	this.messagingStub.sendMessage(MessageFactory.createUnsubscribeMessage(message));
};

/**
 * To set Identity status and to publish it by sending a CONTEXT message to address "rtcIdentity.presence"
 *
 * @param status :
 *            String ... The status to set
 *
 */

Identity.prototype.setStatus = function (status, login) {
	//var message = new Object();
	//message.contextId = this.context;

	//from = identity.rtcIdentity;
	//to = this.rtcIdentity;
	var that = this;
	console.log("Identity SetStatus: ", status);

	this.presence.status = status;// TODO: change to that.presence.status = status;
	this.messagingStub.sendMessage(MessageFactory.createContextMessage(that.rtcIdentity, "", status, login, that.sessionId));
	// TODO: check status transitions according to IdentityStatus state machine
	// TODO: Send a CONTEXT message to address "rtcIdentity.presence"
};

/**getPresence
 * To set Identity presence and to publish it by sending a CONTEXT message to address "rtcIdentity.presence"
 *
 * @param presence :
 *            String ... The presence to set
 *
 */

Identity.prototype.setPresence = function (presence) {

	var that = this;
	that.presence.status = presence;

	// TODO: check status transitions according to IdentityStatus state machine
	// TODO: Send a CONTEXT message to address "rtcIdentity.presence"
};

/**
 * To set Identity context and to publish it by sending a CONTEXT message to address "rtcIdentity.context"
 *
 * @param context :
 *            String ... The context to set
 *
 */

Identity.prototype.setContext = function (context) {

	this.context = context;
	this.messagingStub.sendMessage(MessageFactory.createContextMessage());
	// TODO: Send a CONTEXT message to address "rtcIdentity.context"
};

/**
 * getStatus
 *
 * @returns IdentityStatus ... gets the presence status attribute for this Identity
 *
 */
Identity.prototype.getStatus = function () {
// TODO: change to return this.presence.status;
	return this.presence.status;
};

/**
 * getPresence
 *
 * @returns Presence ... gets the presence  attribute for this Identity
 *
 */
Identity.prototype.getPresence = function () {
	return this.presence;
};

/**
 * sendMessage
 *
 * @sendmessage ...sendMessage
 *
 */

Identity.prototype.sendMessage = function (message) {
	this.messagingStub.sendMessage(message);
};

/**
 * getContext
 *
 * @returns ContextData ... gets the context attribute for this Identity
 *
 */
Identity.prototype.getContext = function () {
	return this.context;
};

/**
 * getMessagingStubDownloadUrl
 *
 * @returns URL ... gets the URL to download the MessagingStub for this Identity
 *
 */
Identity.prototype.getMessagingStubDownloadUrl = function () {
	//will be needed to the Idp
	return this.messagingStubDownloadUrl;
};

/**
 *
 * OnLastMessagingListerner is invoked by the MessagingStub as soon as the last listener has un-subscribed.
 * We use this callback to disconnect and unload the MessagingStub.
 *
 */
Identity.prototype.onLastMessagingListener = function () {
	if (this.messagingStub)
		this.messagingStub.disconnect();
	// "undefine" messagingStub
	delete this.messagingStub;
};

/**@ignore
 * Simple function to load an external Javascript file at runtime.
 * TODO: This might be a security risk, because the file is executed immediately.
 * @param url ... url of the file to be loaded
 */
Identity.prototype.loadJSfile = function (url) {
	var fileref = document.createElement('script');
	fileref.setAttribute("type", "text/javascript");
	fileref.setAttribute("src", url);
	if (typeof fileref != "undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);
};

Identity.prototype.onMessage = function (message) {
	console.log("MESSAGES-->", message)
	switch (message.type) {
		case MessageType.CONTEXT:
			this.setStatus(message.identityPresence.status);
			break;
		case MessageType.ACCEPTED:
			break;
		case MessageType.NOT_ACCEPTED:
			break;
		case MessageType.CANCEL:
			break;
		default:
			break;
	}

}<|endoftext|>