<commit_before>import * as React from 'react';
import { expect } from 'chai';
import { stub, spy } from 'sinon';
import { act, describeConformance, createClientRender, fireEvent, screen } from 'test/utils';
import Rating, { ratingClasses as classes } from '@mui/material/Rating';

describe('<Rating />', () => {
  const render = createClientRender();

  describeConformance(<Rating />, () => ({
    classes,
    inheritComponent: 'span',
    render,
    muiName: 'MuiRating',
    testVariantProps: { variant: 'foo' },
    testDeepOverrides: { slotName: 'label', slotClassName: classes.label },
    testStateOverrides: { prop: 'size', value: 'small', styleKey: 'sizeSmall' },
    refInstanceof: window.HTMLSpanElement,
    skip: ['componentProp', 'componentsProp'],
  }));

  it('should render', () => {
    const { container } = render(<Rating />);

    expect(container.firstChild).to.have.class(classes.root);
  });

  it('should round the value to the provided precision', () => {
    const { container } = render(<Rating name="rating-test" value={3.9} precision={0.2} />);

    expect(container.querySelector('input[name="rating-test"]:checked')).to.have.property(
      'value',
      '4',
    );
  });

  it('should handle mouse hover correctly', () => {
    const { container } = render(<Rating />);
    stub(container.firstChild, 'getBoundingClientRect').callsFake(() => ({
      left: 0,
      right: 100,
    }));
    stub(container.firstChild.firstChild, 'getBoundingClientRect').callsFake(() => ({
      width: 20,
    }));
    fireEvent.mouseMove(container.firstChild, {
      clientX: 19,
    });
    expect(container.querySelectorAll(`.${classes.iconHover}`).length).to.equal(1);
    fireEvent.mouseMove(container.firstChild, {
      clientX: 21,
    });
    expect(container.querySelectorAll(`.${classes.iconHover}`).length).to.equal(2);
  });

  it('should clear the rating', () => {
    const handleChange = spy();
    const { container } = render(<Rating name="rating-test" onChange={handleChange} value={2} />);

    fireEvent.click(container.querySelector('input[name="rating-test"][value="2"]'), {
      clientX: 1,
    });

    expect(handleChange.callCount).to.equal(1);
    expect(handleChange.args[0][1]).to.deep.equal(null);
  });

  it('should select the rating', () => {
    const handleChange = spy();
    const { container } = render(<Rating name="rating-test" onChange={handleChange} value={2} />);
    fireEvent.click(container.querySelector('input[name="rating-test"][value="3"]'));
    expect(handleChange.callCount).to.equal(1);
    expect(handleChange.args[0][1]).to.deep.equal(3);
    const checked = container.querySelector('input[name="rating-test"]:checked');
    expect(checked.value).to.equal('2');
  });

  it('should change the value to null', () => {
    const handleChange = spy();
    render(<Rating name="rating-test" onChange={handleChange} value={2} />);
    fireEvent.click(document.querySelector('#rating-test-empty'));
    expect(handleChange.args[0][1]).to.equal(null);
  });

  it('should select the empty input if value is null', () => {
    const { container } = render(<Rating name="rating-test" value={null} />);
    const input = container.querySelector('#rating-test-empty');
    const checked = container.querySelector('input[name="rating-test"]:checked');
    expect(input).to.equal(checked);
    expect(input.value).to.equal('');
  });

  it('should support a defaultValue', () => {
    const { container } = render(<Rating defaultValue={3} name="rating-test" />);
    let checked;
    checked = container.querySelector('input[name="rating-test"]:checked');
    expect(checked.value).to.equal('3');

    fireEvent.click(container.querySelector('input[name="rating-test"][value="2"]'));
    checked = container.querySelector('input[name="rating-test"]:checked');
    expect(checked.value).to.equal('2');
  });

  it('has a customization point for the label of the empty value when it is active', () => {
    const { container } = render(
      <Rating classes={{ labelEmptyValueActive: 'customized' }} name="" value={null} />,
    );

    expect(container.querySelector('.customized')).to.equal(null);

    act(() => {
      const noValueRadio = screen.getAllByRole('radio').find((radio) => {
        return radio.checked;
      });

      noValueRadio.focus();
    });

    expect(container.querySelector('.customized')).to.have.tagName('label');
  });

  describe('prop: readOnly', () => {
    it('renders a role="img"', () => {
      render(<Rating readOnly value={2} />);

      expect(screen.getByRole('img')).toHaveAccessibleName('2 Stars');
    });

    it('can be labelled with getLabelText', () => {
      render(<Rating getLabelText={(value) => `Stars: ${value}`} readOnly value={2} />);

      expect(screen.getByRole('img')).toHaveAccessibleName('Stars: 2');
    });
  });

  describe('<form> integration', () => {
    before(function beforeHook() {
      if (/jsdom/.test(window.navigator.userAgent)) {
        // JSDOM has issues with form validation for certain elements.
        // We could adress them individually but that doesn't add much value if we already have a working environment.
        this.skip();
      }
    });

    [
      {
        ratingProps: { name: 'rating', defaultValue: 2 },
        formData: [['rating', '2']],
      },
      {
        ratingProps: { name: 'rating', defaultValue: 2, disabled: true },
        formData: [],
      },
      {
        ratingProps: { name: 'rating', defaultValue: 2, readOnly: true },
        // native <input type="radio" /> and our Radio/Checkbox don't implement readOnly as well
        formData: [],
      },
      {
        ratingProps: { name: 'rating', required: true },
        // FIXME: `Rating` does not implement `required`.
        //        Native <input type="radio" /> would not pass validation
        // formData: undefined,
        formData: [['rating', '']],
      },
    ].forEach((testData, testNumber) => {
      it(`submits the expected form data #${testNumber + 1}`, () => {
        /**
         * @type FormData
         */
        let data;
        const handleSubmit = spy((event) => {
          // Prevent navigation
          event.preventDefault();
          // populate FormData with the submitted form
          data = new FormData(event.target);
        });
        render(
          <form onSubmit={handleSubmit}>
            <Rating {...testData.ratingProps} />
            <button type="submit" />
          </form>,
        );
        const submitter = document.querySelector('button[type="submit"]');

        act(() => {
          // form.submit() would not run form validation
          submitter.click();
        });

        if (testData.formData === undefined) {
          expect(handleSubmit.callCount).to.equal(0);
        } else {
          expect(Array.from(data.entries())).to.deep.equal(testData.formData);
        }
      });
    });
  });
});
<commit_msg>[test] Add internal test for uniqe `name` in `Rating` (#29329)<commit_after>import * as React from 'react';
import { expect } from 'chai';
import { stub, spy } from 'sinon';
import { act, describeConformance, createClientRender, fireEvent, screen } from 'test/utils';
import Rating, { ratingClasses as classes } from '@mui/material/Rating';

describe('<Rating />', () => {
  const render = createClientRender();

  describeConformance(<Rating />, () => ({
    classes,
    inheritComponent: 'span',
    render,
    muiName: 'MuiRating',
    testVariantProps: { variant: 'foo' },
    testDeepOverrides: { slotName: 'label', slotClassName: classes.label },
    testStateOverrides: { prop: 'size', value: 'small', styleKey: 'sizeSmall' },
    refInstanceof: window.HTMLSpanElement,
    skip: ['componentProp', 'componentsProp'],
  }));

  it('should render', () => {
    const { container } = render(<Rating />);

    expect(container.firstChild).to.have.class(classes.root);
  });

  it('should round the value to the provided precision', () => {
    const { container } = render(<Rating name="rating-test" value={3.9} precision={0.2} />);

    expect(container.querySelector('input[name="rating-test"]:checked')).to.have.property(
      'value',
      '4',
    );
  });

  it('should handle mouse hover correctly', () => {
    const { container } = render(<Rating />);
    stub(container.firstChild, 'getBoundingClientRect').callsFake(() => ({
      left: 0,
      right: 100,
    }));
    stub(container.firstChild.firstChild, 'getBoundingClientRect').callsFake(() => ({
      width: 20,
    }));
    fireEvent.mouseMove(container.firstChild, {
      clientX: 19,
    });
    expect(container.querySelectorAll(`.${classes.iconHover}`).length).to.equal(1);
    fireEvent.mouseMove(container.firstChild, {
      clientX: 21,
    });
    expect(container.querySelectorAll(`.${classes.iconHover}`).length).to.equal(2);
  });

  it('should clear the rating', () => {
    const handleChange = spy();
    const { container } = render(<Rating name="rating-test" onChange={handleChange} value={2} />);

    fireEvent.click(container.querySelector('input[name="rating-test"][value="2"]'), {
      clientX: 1,
    });

    expect(handleChange.callCount).to.equal(1);
    expect(handleChange.args[0][1]).to.deep.equal(null);
  });

  it('should select the rating', () => {
    const handleChange = spy();
    const { container } = render(<Rating name="rating-test" onChange={handleChange} value={2} />);
    fireEvent.click(container.querySelector('input[name="rating-test"][value="3"]'));
    expect(handleChange.callCount).to.equal(1);
    expect(handleChange.args[0][1]).to.deep.equal(3);
    const checked = container.querySelector('input[name="rating-test"]:checked');
    expect(checked.value).to.equal('2');
  });

  it('should change the value to null', () => {
    const handleChange = spy();
    render(<Rating name="rating-test" onChange={handleChange} value={2} />);
    fireEvent.click(document.querySelector('#rating-test-empty'));
    expect(handleChange.args[0][1]).to.equal(null);
  });

  it('should select the empty input if value is null', () => {
    const { container } = render(<Rating name="rating-test" value={null} />);
    const input = container.querySelector('#rating-test-empty');
    const checked = container.querySelector('input[name="rating-test"]:checked');
    expect(input).to.equal(checked);
    expect(input.value).to.equal('');
  });

  it('should support a defaultValue', () => {
    const { container } = render(<Rating defaultValue={3} name="rating-test" />);
    let checked;
    checked = container.querySelector('input[name="rating-test"]:checked');
    expect(checked.value).to.equal('3');

    fireEvent.click(container.querySelector('input[name="rating-test"][value="2"]'));
    checked = container.querySelector('input[name="rating-test"]:checked');
    expect(checked.value).to.equal('2');
  });

  it('has a customization point for the label of the empty value when it is active', () => {
    const { container } = render(
      <Rating classes={{ labelEmptyValueActive: 'customized' }} name="" value={null} />,
    );

    expect(container.querySelector('.customized')).to.equal(null);

    act(() => {
      const noValueRadio = screen.getAllByRole('radio').find((radio) => {
        return radio.checked;
      });

      noValueRadio.focus();
    });

    expect(container.querySelector('.customized')).to.have.tagName('label');
  });

  // Internal test that only applies if Rating is implemented using `input[type"radio"]`
  // It ensures that keyboard navigation for Arrow and TAB keys is handled by the browser
  it('should ensure a `name`', () => {
    render(<Rating value={null} />);

    const [arbitraryRadio, ...radios] = document.querySelectorAll('input[type="radio"]');
    // `name` **property** will always be a string even if the **attribute** is omitted
    expect(arbitraryRadio.name).not.to.equal('');
    // all input[type="radio"] have the same name
    expect(new Set(radios.map((radio) => radio.name))).to.have.length(1);
  });

  describe('prop: readOnly', () => {
    it('renders a role="img"', () => {
      render(<Rating readOnly value={2} />);

      expect(screen.getByRole('img')).toHaveAccessibleName('2 Stars');
    });

    it('can be labelled with getLabelText', () => {
      render(<Rating getLabelText={(value) => `Stars: ${value}`} readOnly value={2} />);

      expect(screen.getByRole('img')).toHaveAccessibleName('Stars: 2');
    });
  });

  describe('<form> integration', () => {
    before(function beforeHook() {
      if (/jsdom/.test(window.navigator.userAgent)) {
        // JSDOM has issues with form validation for certain elements.
        // We could adress them individually but that doesn't add much value if we already have a working environment.
        this.skip();
      }
    });

    [
      {
        ratingProps: { name: 'rating', defaultValue: 2 },
        formData: [['rating', '2']],
      },
      {
        ratingProps: { name: 'rating', defaultValue: 2, disabled: true },
        formData: [],
      },
      {
        ratingProps: { name: 'rating', defaultValue: 2, readOnly: true },
        // native <input type="radio" /> and our Radio/Checkbox don't implement readOnly as well
        formData: [],
      },
      {
        ratingProps: { name: 'rating', required: true },
        // FIXME: `Rating` does not implement `required`.
        //        Native <input type="radio" /> would not pass validation
        // formData: undefined,
        formData: [['rating', '']],
      },
    ].forEach((testData, testNumber) => {
      it(`submits the expected form data #${testNumber + 1}`, () => {
        /**
         * @type FormData
         */
        let data;
        const handleSubmit = spy((event) => {
          // Prevent navigation
          event.preventDefault();
          // populate FormData with the submitted form
          data = new FormData(event.target);
        });
        render(
          <form onSubmit={handleSubmit}>
            <Rating {...testData.ratingProps} />
            <button type="submit" />
          </form>,
        );
        const submitter = document.querySelector('button[type="submit"]');

        act(() => {
          // form.submit() would not run form validation
          submitter.click();
        });

        if (testData.formData === undefined) {
          expect(handleSubmit.callCount).to.equal(0);
        } else {
          expect(Array.from(data.entries())).to.deep.equal(testData.formData);
        }
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

// This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js

// It only supports their simplest configuration (hot updates on same server).
// It makes some opinionated choices on top, like adding a syntax error overlay
// that looks similar to our console output. The error overlay is inspired by:
// https://github.com/glenjamin/webpack-hot-middleware

var ansiHTML = require('ansi-html');
var SockJS = require('sockjs-client');
var stripAnsi = require('strip-ansi');
var url = require('url');
var formatWebpackMessages = require('./formatWebpackMessages');
var Entities = require('html-entities').AllHtmlEntities;
var entities = new Entities();

// Color scheme inspired by https://github.com/glenjamin/webpack-hot-middleware
var colors = {
  reset: ['transparent', 'transparent'],
  black: '181818',
  red: 'E36049',
  green: 'B3CB74',
  yellow: 'FFD080',
  blue: '7CAFC2',
  magenta: '7FACCA',
  cyan: 'C3C2EF',
  lightgrey: 'EBE7E3',
  darkgrey: '6D7891'
};
ansiHTML.setColors(colors);

function createOverlayIframe(onIframeLoad) {
  var iframe = document.createElement('iframe');
  iframe.id = 'react-dev-utils-webpack-hot-dev-client-overlay';
  iframe.src = 'about:blank';
  iframe.style.position = 'fixed';
  iframe.style.left = 0;
  iframe.style.top = 0;
  iframe.style.right = 0;
  iframe.style.bottom = 0;
  iframe.style.width = '100vw';
  iframe.style.height = '100vh';
  iframe.style.border = 'none';
  iframe.style.zIndex = 9999999999;
  iframe.onload = onIframeLoad;
  return iframe;
}

function addOverlayDivTo(iframe) {
  var div =  iframe.contentDocument.createElement('div');
  div.id = 'react-dev-utils-webpack-hot-dev-client-overlay-div';
  div.style.position = 'fixed';
  div.style.left = 0;
  div.style.top = 0;
  div.style.right = 0;
  div.style.bottom = 0;
  div.style.width = '100vw';
  div.style.height = '100vh';
  div.style.backgroundColor = 'black';
  div.style.color = '#E8E8E8';
  div.style.fontFamily = 'Menlo, Consolas, monospace';
  div.style.fontSize = 'large';
  div.style.padding = '2rem';
  div.style.lineHeight = '1.2';
  div.style.whiteSpace = 'pre-wrap';
  div.style.overflow = 'auto';
  iframe.contentDocument.body.appendChild(div);
  return div;
}

var overlayIframe = null;
var overlayDiv = null;
var lastOnOverlayDivReady = null;

function ensureOverlayDivExists(onOverlayDivReady) {
  if (overlayDiv) {
    // Everything is ready, call the callback right away.
    onOverlayDivReady(overlayDiv);
    return;
  }

  // Creating an iframe may be asynchronous so we'll schedule the callback.
  // In case of multiple calls, last callback wins.
  lastOnOverlayDivReady = onOverlayDivReady;

  if (overlayIframe) {
    // We're already creating it.
    return;
  }

  // Create iframe and, when it is ready, a div inside it.
  overlayIframe = createOverlayIframe(function onIframeLoad() {
    overlayDiv = addOverlayDivTo(overlayIframe);
    // Now we can talk!
    lastOnOverlayDivReady(overlayDiv);
  });

  // Zalgo alert: onIframeLoad() will be called either synchronouly
  // or asynchronously depending on the browser.
  // We delay adding it so `overlayIframe` is set when `onIframeLoad` fires.
  document.body.appendChild(overlayIframe);
}

function showErrorOverlay(message) {
  ensureOverlayDivExists(function onOverlayDivReady(overlayDiv) {
    // Make it look similar to our terminal.
    overlayDiv.innerHTML =
      'Failed to compile.

' +
      ansiHTML(entities.encode(message));
  });
}

// Connect to WebpackDevServer via a socket.
var connection = new SockJS(url.format({
  protocol: window.location.protocol,
  hostname: window.location.hostname,
  port: window.location.port,
  // Hardcoded in WebpackDevServer
  pathname: '/sockjs-node'
}));
// Note: unlike WebpackDevServer's built-in client,
// we don't handle disconnect. If connection fails,
// just leave it instead of spamming the console.

// Remember some state related to hot module replacement.
var isFirstCompilation = true;
var mostRecentCompilationHash = null;
var hasCompileErrors = false;

function clearOutdatedErrors() {
  // Clean up outdated compile errors, if any.
  if (hasCompileErrors && typeof console.clear === 'function') {
    console.clear();
  }
}

// Successful compilation.
function handleSuccess() {
  clearOutdatedErrors();

  var isHotUpdate = !isFirstCompilation;
  isFirstCompilation = false;
  hasCompileErrors = false;

  // Attempt to apply hot updates or reload.
  if (isHotUpdate) {
    tryApplyUpdates();
  }
}

// Compilation with warnings (e.g. ESLint).
function handleWarnings(warnings) {
  clearOutdatedErrors();

  var isHotUpdate = !isFirstCompilation;
  isFirstCompilation = false;
  hasCompileErrors = false;

  function printWarnings() {
    // Print warnings to the console.
    for (var i = 0; i < warnings.length; i++) {
      console.warn(stripAnsi(warnings[i]));
    }
  }

  // Attempt to apply hot updates or reload.
  if (isHotUpdate) {
    tryApplyUpdates(function onSuccessfulHotUpdate() {
      // Only print warnings if we aren't refreshing the page.
      // Otherwise they'll disappear right away anyway.
      printWarnings();
    });
  } else {
    // Print initial warnings immediately.
    printWarnings();
  }
}

// Compilation with errors (e.g. syntax error or missing modules).
function handleErrors(errors) {
  clearOutdatedErrors();

  isFirstCompilation = false;
  hasCompileErrors = true;

  // "Massage" webpack messages.
  var formatted = formatWebpackMessages({
    errors: errors,
    warnings: []
  });

  // Only show the first error.
  showErrorOverlay(formatted.errors[0]);

  // Also log them to the console.
  for (var i = 0; i < formatted.errors.length; i++) {
    console.error(stripAnsi(formatted.errors[i]));
  }

  // Do not attempt to reload now.
  // We will reload on next success instead.
}

// There is a newer version of the code available.
function handleAvailableHash(hash) {
  // Update last known compilation hash.
  mostRecentCompilationHash = hash;
}

// Handle messages from the server.
connection.onmessage = function(e) {
  var message = JSON.parse(e.data);
  switch (message.type) {
  case 'hash':
    handleAvailableHash(message.data);
    break;
  case 'ok':
    handleSuccess();
    break;
  case 'warnings':
    handleWarnings(message.data);
    break;
  case 'errors':
    handleErrors(message.data);
    break;
  default:
    // Do nothing.
  }
}

// Is there a newer version of this code available?
function isUpdateAvailable() {
  /* globals __webpack_hash__ */
  // __webpack_hash__ is the hash of the current compilation.
  // It's a global variable injected by Webpack.
  return mostRecentCompilationHash !== __webpack_hash__;
}

// Webpack disallows updates in other states.
function canApplyUpdates() {
  return module.hot.status() === 'idle';
}

// Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdates(onHotUpdateSuccess) {
  if (!module.hot) {
    // HotModuleReplacementPlugin is not in Webpack configuration.
    window.location.reload();
    return;
  }

  if (!isUpdateAvailable() || !canApplyUpdates()) {
    return;
  }

  // https://webpack.github.io/docs/hot-module-replacement.html#check
  module.hot.check(/* autoApply */true, function(err, updatedModules) {
    if (err || !updatedModules) {
      window.location.reload();
      return;
    }

    if (typeof onHotUpdateSuccess === 'function') {
      // Maybe we want to do something.
      onHotUpdateSuccess();
    }

    if (isUpdateAvailable()) {
      // While we were updating, there was a new update! Do it again.
      tryApplyUpdates();
    }
  });
};
<commit_msg>Add an unobtrusive log when server disconnects<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

// This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js

// It only supports their simplest configuration (hot updates on same server).
// It makes some opinionated choices on top, like adding a syntax error overlay
// that looks similar to our console output. The error overlay is inspired by:
// https://github.com/glenjamin/webpack-hot-middleware

var ansiHTML = require('ansi-html');
var SockJS = require('sockjs-client');
var stripAnsi = require('strip-ansi');
var url = require('url');
var formatWebpackMessages = require('./formatWebpackMessages');
var Entities = require('html-entities').AllHtmlEntities;
var entities = new Entities();

// Color scheme inspired by https://github.com/glenjamin/webpack-hot-middleware
var colors = {
  reset: ['transparent', 'transparent'],
  black: '181818',
  red: 'E36049',
  green: 'B3CB74',
  yellow: 'FFD080',
  blue: '7CAFC2',
  magenta: '7FACCA',
  cyan: 'C3C2EF',
  lightgrey: 'EBE7E3',
  darkgrey: '6D7891'
};
ansiHTML.setColors(colors);

function createOverlayIframe(onIframeLoad) {
  var iframe = document.createElement('iframe');
  iframe.id = 'react-dev-utils-webpack-hot-dev-client-overlay';
  iframe.src = 'about:blank';
  iframe.style.position = 'fixed';
  iframe.style.left = 0;
  iframe.style.top = 0;
  iframe.style.right = 0;
  iframe.style.bottom = 0;
  iframe.style.width = '100vw';
  iframe.style.height = '100vh';
  iframe.style.border = 'none';
  iframe.style.zIndex = 9999999999;
  iframe.onload = onIframeLoad;
  return iframe;
}

function addOverlayDivTo(iframe) {
  var div =  iframe.contentDocument.createElement('div');
  div.id = 'react-dev-utils-webpack-hot-dev-client-overlay-div';
  div.style.position = 'fixed';
  div.style.left = 0;
  div.style.top = 0;
  div.style.right = 0;
  div.style.bottom = 0;
  div.style.width = '100vw';
  div.style.height = '100vh';
  div.style.backgroundColor = 'black';
  div.style.color = '#E8E8E8';
  div.style.fontFamily = 'Menlo, Consolas, monospace';
  div.style.fontSize = 'large';
  div.style.padding = '2rem';
  div.style.lineHeight = '1.2';
  div.style.whiteSpace = 'pre-wrap';
  div.style.overflow = 'auto';
  iframe.contentDocument.body.appendChild(div);
  return div;
}

var overlayIframe = null;
var overlayDiv = null;
var lastOnOverlayDivReady = null;

function ensureOverlayDivExists(onOverlayDivReady) {
  if (overlayDiv) {
    // Everything is ready, call the callback right away.
    onOverlayDivReady(overlayDiv);
    return;
  }

  // Creating an iframe may be asynchronous so we'll schedule the callback.
  // In case of multiple calls, last callback wins.
  lastOnOverlayDivReady = onOverlayDivReady;

  if (overlayIframe) {
    // We're already creating it.
    return;
  }

  // Create iframe and, when it is ready, a div inside it.
  overlayIframe = createOverlayIframe(function onIframeLoad() {
    overlayDiv = addOverlayDivTo(overlayIframe);
    // Now we can talk!
    lastOnOverlayDivReady(overlayDiv);
  });

  // Zalgo alert: onIframeLoad() will be called either synchronouly
  // or asynchronously depending on the browser.
  // We delay adding it so `overlayIframe` is set when `onIframeLoad` fires.
  document.body.appendChild(overlayIframe);
}

function showErrorOverlay(message) {
  ensureOverlayDivExists(function onOverlayDivReady(overlayDiv) {
    // Make it look similar to our terminal.
    overlayDiv.innerHTML =
      'Failed to compile.

' +
      ansiHTML(entities.encode(message));
  });
}

// Connect to WebpackDevServer via a socket.
var connection = new SockJS(url.format({
  protocol: window.location.protocol,
  hostname: window.location.hostname,
  port: window.location.port,
  // Hardcoded in WebpackDevServer
  pathname: '/sockjs-node'
}));

// Unlike WebpackDevServer client, we won't try to reconnect
// to avoid spamming the console. Disconnect usually happens
// when developer stops the server.
connection.onclose = function() {
  console.info(
    'The development server has disconnected.\nRefresh the page if necessary.'
  );
};

// Remember some state related to hot module replacement.
var isFirstCompilation = true;
var mostRecentCompilationHash = null;
var hasCompileErrors = false;

function clearOutdatedErrors() {
  // Clean up outdated compile errors, if any.
  if (hasCompileErrors && typeof console.clear === 'function') {
    console.clear();
  }
}

// Successful compilation.
function handleSuccess() {
  clearOutdatedErrors();

  var isHotUpdate = !isFirstCompilation;
  isFirstCompilation = false;
  hasCompileErrors = false;

  // Attempt to apply hot updates or reload.
  if (isHotUpdate) {
    tryApplyUpdates();
  }
}

// Compilation with warnings (e.g. ESLint).
function handleWarnings(warnings) {
  clearOutdatedErrors();

  var isHotUpdate = !isFirstCompilation;
  isFirstCompilation = false;
  hasCompileErrors = false;

  function printWarnings() {
    // Print warnings to the console.
    for (var i = 0; i < warnings.length; i++) {
      console.warn(stripAnsi(warnings[i]));
    }
  }

  // Attempt to apply hot updates or reload.
  if (isHotUpdate) {
    tryApplyUpdates(function onSuccessfulHotUpdate() {
      // Only print warnings if we aren't refreshing the page.
      // Otherwise they'll disappear right away anyway.
      printWarnings();
    });
  } else {
    // Print initial warnings immediately.
    printWarnings();
  }
}

// Compilation with errors (e.g. syntax error or missing modules).
function handleErrors(errors) {
  clearOutdatedErrors();

  isFirstCompilation = false;
  hasCompileErrors = true;

  // "Massage" webpack messages.
  var formatted = formatWebpackMessages({
    errors: errors,
    warnings: []
  });

  // Only show the first error.
  showErrorOverlay(formatted.errors[0]);

  // Also log them to the console.
  for (var i = 0; i < formatted.errors.length; i++) {
    console.error(stripAnsi(formatted.errors[i]));
  }

  // Do not attempt to reload now.
  // We will reload on next success instead.
}

// There is a newer version of the code available.
function handleAvailableHash(hash) {
  // Update last known compilation hash.
  mostRecentCompilationHash = hash;
}

// Handle messages from the server.
connection.onmessage = function(e) {
  var message = JSON.parse(e.data);
  switch (message.type) {
  case 'hash':
    handleAvailableHash(message.data);
    break;
  case 'ok':
    handleSuccess();
    break;
  case 'warnings':
    handleWarnings(message.data);
    break;
  case 'errors':
    handleErrors(message.data);
    break;
  default:
    // Do nothing.
  }
}

// Is there a newer version of this code available?
function isUpdateAvailable() {
  /* globals __webpack_hash__ */
  // __webpack_hash__ is the hash of the current compilation.
  // It's a global variable injected by Webpack.
  return mostRecentCompilationHash !== __webpack_hash__;
}

// Webpack disallows updates in other states.
function canApplyUpdates() {
  return module.hot.status() === 'idle';
}

// Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdates(onHotUpdateSuccess) {
  if (!module.hot) {
    // HotModuleReplacementPlugin is not in Webpack configuration.
    window.location.reload();
    return;
  }

  if (!isUpdateAvailable() || !canApplyUpdates()) {
    return;
  }

  // https://webpack.github.io/docs/hot-module-replacement.html#check
  module.hot.check(/* autoApply */true, function(err, updatedModules) {
    if (err || !updatedModules) {
      window.location.reload();
      return;
    }

    if (typeof onHotUpdateSuccess === 'function') {
      // Maybe we want to do something.
      onHotUpdateSuccess();
    }

    if (isUpdateAvailable()) {
      // While we were updating, there was a new update! Do it again.
      tryApplyUpdates();
    }
  });
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import gql from 'graphql-tag';
import { Query } from 'react-apollo';

const gqlQuery = gql`
  {
    rates(currency: "USD") {
      currency
      rate
    }
  }
`;

export default class C5 extends Component {
  static propTypes = {

  };

  render() {
    return (

Here is a sample graphql query to get USD exchange rate:

        <Query query={gqlQuery}>
          {({ loading, error, data }) => {
            if (loading) return
Loading...
;
            if (error) return
Error :(
;

            return data.rates.map(({ currency, rate }) => (

{`${currency}: ${rate}`}

            ));
          }}
        </Query>

    );
  }
}
<commit_msg>Code clean.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 con terra GmbH (info@conterra.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import ClusterFeatureLayer from "./ClusterFeatureLayer";
import Collection from "esri/core/Collection";
import Sublayer from "esri/layers/support/Sublayer";

export default class ClusterFeatureLayerTypeFactory {

    constructor() {
        this._clusterLayers = [];
    }

    create(options) {
        let opt = options.options;
        let popupTemplate = options.popupTemplate;
        if (options.layers) {
            this.layers = [];
            options.layers.forEach((layer) => {
                layer.sublayers.forEach((children) => {
                    let sublayer = new Sublayer({
                        layerId: layer.id,
                        sublayerId: children.id,
                        layerUrl: layer.url,
                        title: children.title || "",
                        visible: children.visible || true
                    });
                    this.layers.push(sublayer);
                });
            })
        }
        let layer = this.layer = new ClusterFeatureLayer({
            sublayers: new Collection(this.layers),
            _layerId: "clusterlayer",
            _objectIdField: opt.objectIdField || "objectid",
            _clusterDistance: opt.clusterDistance || 50,
            _spiderfyingDistance: opt.spiderfyingDistance || 5,
            _maxClusterScale: opt.maxClusterScale || 1,
            _showClusterArea: opt.showClusterArea || false,
            _options: opt,
            _serverRequester: this._serverRequester,
            _mapWidgetModel: this.mapWidgetModel,
            _popupTemplate: popupTemplate,
            _clusterSymbolProvider: this.clusterSymbolProvider,
            _featureSymbolProvider: this.featureSymbolProvider,
            _eventService: this.eventService
        });
        this._clusterLayers.push(layer);
        return {instance: layer};
    }

    setMapWidgetModel(mapWidgetModel, properties) {
        this.mapWidgetModel = mapWidgetModel;
        this._clusterLayers.forEach((clusterLayer) => {
            clusterLayer.setMapWidgetModel(mapWidgetModel);
        })
    }
}
<commit_msg>Add layer titles to ClusterFeatureLayer sublayers<commit_after>/*
 * Copyright (C) 2018 con terra GmbH (info@conterra.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import ClusterFeatureLayer from "./ClusterFeatureLayer";
import Collection from "esri/core/Collection";
import Sublayer from "esri/layers/support/Sublayer";

export default class ClusterFeatureLayerTypeFactory {

    constructor() {
        this._clusterLayers = [];
    }

    create(options) {
        let opt = options.options;
        let popupTemplate = options.popupTemplate;
        if (options.layers) {
            this.layers = [];
            options.layers.forEach((layer) => {
                layer.sublayers.forEach((children) => {
                    let sublayer = new Sublayer({
                        layerId: layer.id,
                        sublayerId: children.id,
                        layerUrl: layer.url,
                        title: children.title || children.id,
                        visible: children.visible || true
                    });
                    this.layers.push(sublayer);
                });
            });
        }
        let layer = this.layer = new ClusterFeatureLayer({
            title: options.title,
            sublayers: new Collection(this.layers),
            legendEnabled: false,
            _layerId: "clusterlayer",
            _objectIdField: opt.objectIdField || "objectid",
            _clusterDistance: opt.clusterDistance || 50,
            _spiderfyingDistance: opt.spiderfyingDistance || 5,
            _maxClusterScale: opt.maxClusterScale || 1,
            _showClusterArea: opt.showClusterArea || false,
            _options: opt,
            _serverRequester: this._serverRequester,
            _mapWidgetModel: this.mapWidgetModel,
            _popupTemplate: popupTemplate,
            _clusterSymbolProvider: this.clusterSymbolProvider,
            _featureSymbolProvider: this.featureSymbolProvider,
            _eventService: this.eventService
        });
        this._clusterLayers.push(layer);
        return {instance: layer};
    }

    setMapWidgetModel(mapWidgetModel, properties) {
        this.mapWidgetModel = mapWidgetModel;
        this._clusterLayers.forEach((clusterLayer) => {
            clusterLayer.setMapWidgetModel(mapWidgetModel);
        })
    }
}
<|endoftext|>


<commit_before>module.exports = function (wallaby) {
  process.env.NODE_PATH += `:${require('path').join(wallaby.localProjectDir, 'node_modules')}`;
  return {
    files: [
      {pattern: 'test/**/*.spec.js*', ignore: true},
      {pattern: 'test/**/*.js'},
      {pattern: 'src/**', instrument: true},
      {pattern: 'src/**/*.spec.js*', ignore: true},
      {pattern: 'target/**/*.json', instrument: false},
      {pattern: 'templates/**', instrument: false},
      {pattern: 'index.js', instrument: true},
      {pattern: 'package.json', instrument: false}
    ],

    tests: [
      {pattern: 'test/**/*.spec.js*'},
      {pattern: 'src/**/*.spec.js*'},
    ],

    compilers: {
      '**/*.js*': wallaby.compilers.babel()
    },

    testFramework: 'mocha',

    setup(wallaby) {
      const mocha = wallaby.testFramework;
      mocha.timeout(30000);
      require('../../lib/ignore-extensions');
      require('../../lib/setup-dom');
    },

    env: {
      type: 'node',
      params: {
        env: `SRC_PATH=./src;NODE_ENV=test`
      }
    },
    workers: {
      initial: 1,
      regular: 1
    }
  };
};
<commit_msg>remove wallaby's setup-dom - it will be handled by project's tests<commit_after>module.exports = function (wallaby) {
  process.env.NODE_PATH += `:${require('path').join(wallaby.localProjectDir, 'node_modules')}`;
  return {
    files: [
      {pattern: 'test/**/*.spec.js*', ignore: true},
      {pattern: 'test/**/*.js'},
      {pattern: 'src/**', instrument: true},
      {pattern: 'src/**/*.spec.js*', ignore: true},
      {pattern: 'target/**/*.json', instrument: false},
      {pattern: 'templates/**', instrument: false},
      {pattern: 'index.js', instrument: true},
      {pattern: 'package.json', instrument: false}
    ],

    tests: [
      {pattern: 'test/**/*.spec.js*'},
      {pattern: 'src/**/*.spec.js*'},
    ],

    compilers: {
      '**/*.js*': wallaby.compilers.babel()
    },

    testFramework: 'mocha',

    setup(wallaby) {
      const mocha = wallaby.testFramework;
      mocha.timeout(30000);
      require('../../lib/ignore-extensions');
    },

    env: {
      type: 'node',
      params: {
        env: `SRC_PATH=./src;NODE_ENV=test`
      }
    },
    workers: {
      initial: 1,
      regular: 1
    }
  };
};
<|endoftext|>


<commit_before>const environment = require('./environment')

const config = environment.toWebpackConfig()
config.devtool = 'cheap-module-source-map'

module.exports = config
<commit_msg>Let's try it without source maps<commit_after>const environment = require('./environment')

const config = environment.toWebpackConfig()

module.exports = config
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var webpack = require('webpack');
var path = require('path');
var env = require('./env.js');

/**
 * Manage files in ./src/_app/
 */

var appConfig = {
  entry: path.resolve(__dirname, './../src/_app/main.js'),

  output: {
    filename: path.resolve(__dirname, './../dst/_app/[name].js'),
    chunkFilename: path.resolve(__dirname, './../dst/_app/[id].bundle.js')
  }
};

/**
 * Manage files in ./src/_assets/js/
 */

var assetConfig = {
  entry: path.resolve(__dirname, './../src/_assets/scripts/main.js'),

  output: {
    filename: path.resolve(__dirname, './../dst/_assets/scripts/[name].js'),
    chunkFilename: path.resolve(__dirname, './../dst/_assets/scripts/[id].bundle.js')
  }
};

/**
 * Create shared configs
 */

var configs = [appConfig, assetConfig];

_.each(configs, function (cfg) {
  cfg.debug = env.ENV === 'local';

  cfg.module = {
    loaders: [{
      test: /\.js$/,
      exclude: [/_vendor/, /node_modules/],
      loader: 'babel-loader'
    }]
  };

  cfg.devtool = '#inline-source-map';

  cfg.resolve = {
    modulesDirectories: ['_vendor', 'node_modules']
  };
});

/**
 * Set production options
 */

var isLocal = env.ENV !== 'production' && env.ENV !== 'staging';

if(!isLocal) {
  _.each(configs, function (cfg) {
    cfg.plugins = cfg.plugins || [];
    cfg.plugins = cfg.plugins.concat([
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        mangle: {
          except: ['require', 'export', '$super']
        },
        compress: {
          warnings: false,
          sequences: true,
          dead_code: true,
          conditionals: true,
          booleans: true,
          unused: true,
          if_return: true,
          join_vars: true,
          drop_console: true
        },
        sourceMap: true
      })
    ]);
  });
}

/**
 * Export app and asset configs
 */

module.exports = configs;
<commit_msg>Fix when.js incompatibility with webpack<commit_after>'use strict';

var _ = require('lodash');
var webpack = require('webpack');
var path = require('path');
var env = require('./env.js');

/**
 * Manage files in ./src/_app/
 */

var appConfig = {
  entry: path.resolve(__dirname, './../src/_app/main.js'),

  output: {
    filename: path.resolve(__dirname, './../dst/_app/[name].js'),
    chunkFilename: path.resolve(__dirname, './../dst/_app/[id].bundle.js')
  }
};

/**
 * Manage files in ./src/_assets/js/
 */

var assetConfig = {
  entry: path.resolve(__dirname, './../src/_assets/scripts/main.js'),

  output: {
    filename: path.resolve(__dirname, './../dst/_assets/scripts/[name].js'),
    chunkFilename: path.resolve(__dirname, './../dst/_assets/scripts/[id].bundle.js')
  }
};

/**
 * Create shared configs
 */

var configs = [appConfig, assetConfig];

_.each(configs, function (cfg) {
  cfg.debug = env.ENV === 'local';

  cfg.module = {
    loaders: [{
      test: /\.js$/,
      exclude: [/_vendor/, /node_modules/],
      loader: 'babel-loader'
    }]
  };

  cfg.devtool = '#inline-source-map';

  cfg.plugins = [
    new webpack.IgnorePlugin(/vertx/)
  ];

  cfg.resolve = {
    modulesDirectories: ['_vendor', 'node_modules']
  };
});

/**
 * Set production options
 */

var isLocal = env.ENV !== 'production' && env.ENV !== 'staging';

if(!isLocal) {
  _.each(configs, function (cfg) {
    cfg.plugins = cfg.plugins || [];
    cfg.plugins = cfg.plugins.concat([
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        mangle: {
          except: ['require', 'export', '$super']
        },
        compress: {
          warnings: false,
          sequences: true,
          dead_code: true,
          conditionals: true,
          booleans: true,
          unused: true,
          if_return: true,
          join_vars: true,
          drop_console: true
        },
        sourceMap: true
      })
    ]);
  });
}

/**
 * Export app and asset configs
 */

module.exports = configs;
<|endoftext|>


<commit_before>

!function( $ ) {
	"use strict"

	$.fn.alert = {
		show: function(selector) {
			var $selector = $(selector);
			var $panel = $(".alert-global-panel", $selector);
			if ($(".alert-info, .alert-warning, .alert-error, .alert-success" , $panel).size() > 0) {
				$panel.animate({ top: 0 }, 500);

				if ($(".alert-info, .alert-warning, .alert-error", $panel).size() == 0) {
					$panel.delay(3000).animate({ top: -$panel.outerHeight() });
				}
			}
		},
		hide: function(selector) {
			var $selector = $(selector);
			var $panel = $(".alert-global-panel", $selector);
			if ($(".alert-info, .alert-warning, .alert-error, .alert-success" , $panel).size() > 0) {
				$panel.css({ top: -$panel.outerHeight() });
			}
		},
		reset: function(selector) {
			$.fn.alert.hide(selector);
			$.fn.alert.show(selector);
		},
		close: function(event) {
			var $panel = $(event.target).closest(".alert-global-panel");
			if ($(".alert-info, .alert-warning, .alert-error, .alert-success" , $panel).size() > 0) {
				$panel.stop(true).animate({ top: -$panel.outerHeight() });
			}
			event.preventDefault();
		}
	};
}( window.jQuery )<commit_msg>en cas de message de succès, possibilité de fermer le panel juste avec un clic n'importe où dans le panel<commit_after>

!function( $ ) {
	"use strict"

	$.fn.alert = {
		show: function(selector) {
			var $selector = $(selector);
			var $panel = $(".alert-global-panel", $selector);
			$panel.off("click.alert");
			if ($(".alert-info, .alert-warning, .alert-error, .alert-success" , $panel).size() > 0) {
				$panel.animate({ top: 0 }, 500);

				if ($(".alert-info, .alert-warning, .alert-error", $panel).size() == 0) {
					$panel.on("click.alert", function(event) { $.fn.alert.close(event); });
					$panel.delay(3000).animate({ top: -$panel.outerHeight() });
				}
			}
		},
		hide: function(selector) {
			var $selector = $(selector);
			var $panel = $(".alert-global-panel", $selector);
			if ($(".alert-info, .alert-warning, .alert-error, .alert-success" , $panel).size() > 0) {
				$panel.css({ top: -$panel.outerHeight() });
			}
		},
		reset: function(selector) {
			$.fn.alert.hide(selector);
			$.fn.alert.show(selector);
		},
		close: function(event) {
			var $panel = $(event.target).closest(".alert-global-panel");
			if ($(".alert-info, .alert-warning, .alert-error, .alert-success" , $panel).size() > 0) {
				$panel.stop(true).animate({ top: -$panel.outerHeight() });
			}
			event.preventDefault();
		}
	};
}( window.jQuery )<|endoftext|>


<commit_before>// Copyright (c) 2012 Jonathan Penn (http://cocoamanifest.net/)

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

UIAutoMonkey = {

  config: {
    numberOfEvents: 1000,
    delayBetweenEvents: 0.05,    // In seconds

    // Events are triggered based on the relative weights here. The event with
    // this highest number gets triggered the most.
    //
    // If you want to add your own "events", check out the event method
    // definitions below.
    eventWeights: {
      tap: 50,
      drag: 1,
      flick: 1,
      orientation: 1,
      clickVolumeUp: 1,
      clickVolumeDown: 1,
      lock: 1
    },

    // Probability that touch events will have these different properties
    touchProbability: {
      multipleTaps: 0.05,
      multipleTouches: 0.05,
      longPress: 0.05
    }
  },

  // --- --- --- ---
  // Event Methods
  //
  // Any event probability in the hash above corresponds to a related event method
  // below. So, a "tap" probability will trigger a "tapEvent" method.
  //
  // If you want to add your own events, just add a probability to the hash
  // above and then add a corresponding method below. Boom!
  //
  // Each event method can call any other method on this UIAutoMonkey object.
  // All the methods at the end are helpers at your disposal and feel free to
  // add your own.

  tapEvent: function() {
    this.target().tapWithOptions(
      { x: this.randomX(), y: this.randomY() },
      {
        tapCount: this.randomTapCount(),
        touchCount: this.randomTouchCount(),
        duration: this.randomTapDuration()
      }
    );
  },

  dragEvent: function() {
    this.target().dragFromToForDuration(
      { x: this.randomX(), y: this.randomY() },
      { x: this.randomX(), y: this.randomY() },
      0.5
    );
  },

  flickEvent: function() {
    this.target().flickFromTo(
      { x: this.randomX(), y: this.randomY() },
      { x: this.randomX(), y: this.randomY() }
    );
  },

  orientationEvent: function() {
    var orientations = [
      UIA_DEVICE_ORIENTATION_PORTRAIT,
      UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN,
      UIA_DEVICE_ORIENTATION_LANDSCAPELEFT,
      UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT
    ];

    var i = Math.floor(Math.random() * 10) % orientations.length;
    var newOrientation = orientations[i];
    this.target().setDeviceOrientation(newOrientation);
    this.delay(0.9);
  },

  clickVolumeUpEvent: function() {
    this.target().clickVolumeUp();
  },

  clickVolumeDownEvent: function() {
    this.target().clickVolumeUp();
  },

  lockEvent: function() {
    this.target().lockForDuration(Math.random() * 3);
  },

  // --- --- --- ---
  // Helper methods
  //

  RELEASE_THE_MONKEY: function() {
    // Called at the bottom of this script to, you know...
    //
    // RELEASE THE MONKEY!

    for(var i = 0; i < this.config.numberOfEvents; i++) {
      this.triggerRandomEvent();
      this.delay();
    }
  },

  triggerRandomEvent: function() {
    var name = this.chooseEventName();
    // Find the event method based on the name of the event
    var event = this[name + "Event"];
    event.apply(this);
  },

  target: function() {
    // Return the local target.
    return UIATarget.localTarget();
  },

  delay: function(seconds) {
    // Delay the target by `seconds` (can be a fraction)
    // Defaults to setting in configuration
    seconds = seconds || this.config.delayBetweenEvents;
    this.target().delay(seconds);
  },

  chooseEventName: function() {
    // Randomly chooses an event name from the `eventsWeight` dictionary
    // based on the given weights.
    var calculatedEventWeights = [];
    var totalWeight = 0;
    var events = this.config.eventWeights;
    for (event in events) {
      if (events.hasOwnProperty(event)) {
        calculatedEventWeights.push({
          weight: events[event]+totalWeight,
          event: event
        });
        totalWeight += events[event];
      }
    }

    var chosenWeight = Math.random() * 1000 % totalWeight;

    for (var i = 0; i < calculatedEventWeights.length; i++) {
      if (chosenWeight < calculatedEventWeights[i].weight) {
        return calculatedEventWeights[i].event;
      }
    }

    throw "No even was chosen!";
  },

  randomX: function() {
    // Returns a random X coordinate within the screen rectangle
    var range = this.target().rect().size.width - 1;
    return Math.floor(Math.random() * 10000) % range + 1;
  },

  randomY: function() {
    // Returns a random Y coordinate within the screen rectangle
    var range = this.target().rect().size.height - 1;
    return Math.floor(Math.random() * 10000) % range + 1;
  },

  randomTapCount: function() {
    // Calculates a tap count for tap events based on touch probabilities
    if (this.config.touchProbability.multipleTaps > Math.random()) {
      return Math.floor(Math.random() * 10) % 3 + 1;
    }
    else return 1;
  },

  randomTouchCount: function() {
    // Calculates a touch count for tap events based on touch probabilities
    if (this.config.touchProbability.multipleTouches > Math.random()) {
      return Math.floor(Math.random() * 10) % 3 + 1;
    }
    else return 1;
  },

  randomTapDuration: function() {
    // Calculates whether or not a tap should be a long press based on
    // touch probabilities
    if (this.config.touchProbability.longPress > Math.random()) {
      return 0.5;
    }
    else return 0;
  },

  randomRadians: function() {
    // Returns a random radian value
    return Math.random() * 10 % (3.14159 * 2);
  }
};

UIAutoMonkey.RELEASE_THE_MONKEY();
<commit_msg>DEATH TO WHITESPACE!<commit_after>// Copyright (c) 2012 Jonathan Penn (http://cocoamanifest.net/)

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

UIAutoMonkey = {

  config: {
    numberOfEvents: 1000,
    delayBetweenEvents: 0.05,    // In seconds

    // Events are triggered based on the relative weights here. The event with
    // this highest number gets triggered the most.
    //
    // If you want to add your own "events", check out the event method
    // definitions below.
    eventWeights: {
      tap: 50,
      drag: 1,
      flick: 1,
      orientation: 1,
      clickVolumeUp: 1,
      clickVolumeDown: 1,
      lock: 1
    },

    // Probability that touch events will have these different properties
    touchProbability: {
      multipleTaps: 0.05,
      multipleTouches: 0.05,
      longPress: 0.05
    }
  },

  // --- --- --- ---
  // Event Methods
  //
  // Any event probability in the hash above corresponds to a related event method
  // below. So, a "tap" probability will trigger a "tapEvent" method.
  //
  // If you want to add your own events, just add a probability to the hash
  // above and then add a corresponding method below. Boom!
  //
  // Each event method can call any other method on this UIAutoMonkey object.
  // All the methods at the end are helpers at your disposal and feel free to
  // add your own.

  tapEvent: function() {
    this.target().tapWithOptions(
      { x: this.randomX(), y: this.randomY() },
      {
        tapCount: this.randomTapCount(),
        touchCount: this.randomTouchCount(),
        duration: this.randomTapDuration()
      }
    );
  },

  dragEvent: function() {
    this.target().dragFromToForDuration(
      { x: this.randomX(), y: this.randomY() },
      { x: this.randomX(), y: this.randomY() },
      0.5
    );
  },

  flickEvent: function() {
    this.target().flickFromTo(
      { x: this.randomX(), y: this.randomY() },
      { x: this.randomX(), y: this.randomY() }
    );
  },

  orientationEvent: function() {
    var orientations = [
      UIA_DEVICE_ORIENTATION_PORTRAIT,
      UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN,
      UIA_DEVICE_ORIENTATION_LANDSCAPELEFT,
      UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT
    ];

    var i = Math.floor(Math.random() * 10) % orientations.length;
    var newOrientation = orientations[i];
    this.target().setDeviceOrientation(newOrientation);
    this.delay(0.9);
  },

  clickVolumeUpEvent: function() {
    this.target().clickVolumeUp();
  },

  clickVolumeDownEvent: function() {
    this.target().clickVolumeUp();
  },

  lockEvent: function() {
    this.target().lockForDuration(Math.random() * 3);
  },

  // --- --- --- ---
  // Helper methods
  //

  RELEASE_THE_MONKEY: function() {
    // Called at the bottom of this script to, you know...
    //
    // RELEASE THE MONKEY!

    for(var i = 0; i < this.config.numberOfEvents; i++) {
      this.triggerRandomEvent();
      this.delay();
    }
  },

  triggerRandomEvent: function() {
    var name = this.chooseEventName();
    // Find the event method based on the name of the event
    var event = this[name + "Event"];
    event.apply(this);
  },

  target: function() {
    // Return the local target.
    return UIATarget.localTarget();
  },

  delay: function(seconds) {
    // Delay the target by `seconds` (can be a fraction)
    // Defaults to setting in configuration
    seconds = seconds || this.config.delayBetweenEvents;
    this.target().delay(seconds);
  },

  chooseEventName: function() {
    // Randomly chooses an event name from the `eventsWeight` dictionary
    // based on the given weights.
    var calculatedEventWeights = [];
    var totalWeight = 0;
    var events = this.config.eventWeights;
    for (event in events) {
      if (events.hasOwnProperty(event)) {
        calculatedEventWeights.push({
          weight: events[event]+totalWeight,
          event: event
        });
        totalWeight += events[event];
      }
    }

    var chosenWeight = Math.random() * 1000 % totalWeight;

    for (var i = 0; i < calculatedEventWeights.length; i++) {
      if (chosenWeight < calculatedEventWeights[i].weight) {
        return calculatedEventWeights[i].event;
      }
    }

    throw "No even was chosen!";
  },

  randomX: function() {
    // Returns a random X coordinate within the screen rectangle
    var range = this.target().rect().size.width - 1;
    return Math.floor(Math.random() * 10000) % range + 1;
  },

  randomY: function() {
    // Returns a random Y coordinate within the screen rectangle
    var range = this.target().rect().size.height - 1;
    return Math.floor(Math.random() * 10000) % range + 1;
  },

  randomTapCount: function() {
    // Calculates a tap count for tap events based on touch probabilities
    if (this.config.touchProbability.multipleTaps > Math.random()) {
      return Math.floor(Math.random() * 10) % 3 + 1;
    }
    else return 1;
  },

  randomTouchCount: function() {
    // Calculates a touch count for tap events based on touch probabilities
    if (this.config.touchProbability.multipleTouches > Math.random()) {
      return Math.floor(Math.random() * 10) % 3 + 1;
    }
    else return 1;
  },

  randomTapDuration: function() {
    // Calculates whether or not a tap should be a long press based on
    // touch probabilities
    if (this.config.touchProbability.longPress > Math.random()) {
      return 0.5;
    }
    else return 0;
  },

  randomRadians: function() {
    // Returns a random radian value
    return Math.random() * 10 % (3.14159 * 2);
  }
};

UIAutoMonkey.RELEASE_THE_MONKEY();
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

function onRequest(context) {
// var log = new Log("device-view.js");
    var deviceType = context["uriParams"]["deviceType"];
    var deviceId = request.getParameter("id");
    var deviceViewData = {};
    var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];

    if (deviceType && deviceId) {
        var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
        var response = deviceModule.viewDevice(deviceType, deviceId);
        if (response["status"] == "success") {
            deviceViewData["deviceFound"] = true;
            deviceViewData["isAuthorized"] = true;

            var filteredDeviceData = response["content"];

// creating deviceView information model from filtered device data
            var viewModel = {};
            if (filteredDeviceData["type"]) {
                viewModel["type"] = filteredDeviceData["type"];
                viewModel.isNotWindows = true;
            }
            if (filteredDeviceData["deviceIdentifier"]) {
                viewModel["deviceIdentifier"] = filteredDeviceData["deviceIdentifier"];
            }
            if (filteredDeviceData["name"]) {
                viewModel["name"] = filteredDeviceData["name"];
            }
            if (filteredDeviceData["enrolmentInfo"]) {
                if (filteredDeviceData["enrolmentInfo"]["status"]) {
                    viewModel["status"] = filteredDeviceData["enrolmentInfo"]["status"];
                    viewModel.isActive = false ;
                    viewModel.isNotRemoved = true;
                    if (filteredDeviceData["enrolmentInfo"]["status"]== "ACTIVE") {
                        viewModel.isActive = true ;
                    }
                    if (filteredDeviceData["enrolmentInfo"]["status"]== "REMOVED") {
                        viewModel.isNotRemoved = false ;
                    }
                }
                if (filteredDeviceData["enrolmentInfo"]["owner"]) {
                    viewModel["owner"] = filteredDeviceData["enrolmentInfo"]["owner"];
                }
                if (filteredDeviceData["enrolmentInfo"]["ownership"]) {
                    viewModel["ownership"] = filteredDeviceData["enrolmentInfo"]["ownership"];
                }
            }
            if (filteredDeviceData["initialDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = true;
                if (filteredDeviceData["initialDeviceInfo"]["IMEI"]) {
                    viewModel["imei"] = filteredDeviceData["initialDeviceInfo"]["IMEI"];
                }
                if (!filteredDeviceData["latestDeviceInfo"]) {
                    if (filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"]) {
                        if (filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"] != "0") {
                            viewModel["osBuildDate"] = new Date(filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"] * 1000);
                        }
                    }
                    if (filteredDeviceData["initialDeviceInfo"]["LATITUDE"] && filteredDeviceData["initialDeviceInfo"]["LONGITUDE"]) {
                        viewModel["location"] = {};
                        viewModel["location"]["latitude"] = filteredDeviceData["initialDeviceInfo"]["LATITUDE"];
                        viewModel["location"]["longitude"] = filteredDeviceData["initialDeviceInfo"]["LONGITUDE"];
                    }
                    if (filteredDeviceData["initialDeviceInfo"]["VENDOR"] && filteredDeviceData["initialDeviceInfo"]["DEVICE_MODEL"]) {
                        viewModel["vendor"] = filteredDeviceData["initialDeviceInfo"]["VENDOR"];
                        viewModel["model"] = filteredDeviceData["initialDeviceInfo"]["DEVICE_MODEL"];
                    }
                    if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]) {
                        if (deviceType == "android") {
                            viewModel["BatteryLevel"] = {};
                            viewModel["BatteryLevel"]["value"] = filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["BATTERY_LEVEL"];

                            viewModel["internalMemory"] = {};
                            viewModel["internalMemory"]["total"] = Math.
                                round(filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_TOTAL_MEMORY"] * 100) / 100;
                            if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_TOTAL_MEMORY"] != 0) {
                                viewModel["internalMemory"]["usage"] = Math.
                                    round((filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_TOTAL_MEMORY"] -
                                        filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_AVAILABLE_MEMORY"])
                                        / filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_TOTAL_MEMORY"] * 10000) / 100;
                            } else {
                                viewModel["internalMemory"]["usage"] = 0;
                            }

                            viewModel["externalMemory"] = {};
                            viewModel["externalMemory"]["total"] = Math.
                                round(filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_TOTAL_MEMORY"] * 100) / 100;
                            if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_TOTAL_MEMORY"] != 0) {
                                viewModel["externalMemory"]["usage"] = Math.
                                    round((filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_TOTAL_MEMORY"] -
                                        filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_AVAILABLE_MEMORY"])
                                        / filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_TOTAL_MEMORY"] * 10000) / 100;
                            } else {
                                viewModel["externalMemory"]["usage"] = 0;
                            }
                        } else if (deviceType == "ios") {
                            viewModel["BatteryLevel"] = {};
                            viewModel["BatteryLevel"]["value"] = Math. round(filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["BatteryLevel"] * 10000) / 100;

                            viewModel["internalMemory"] = {};
                            viewModel["internalMemory"]["total"] = Math.
                                round(filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["DeviceCapacity"] * 100) / 100;
                            if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["DeviceCapacity"] != 0) {
                                viewModel["internalMemory"]["usage"] = Math.
                                    round((filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["DeviceCapacity"] -
                                        filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["AvailableDeviceCapacity"])
                                        / filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["DeviceCapacity"] * 10000) / 100;
                            } else {
                                viewModel["internalMemory"]["usage"] = 0;
                            }
                        }
                    }
                }
            }
            if (filteredDeviceData["latestDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = true;
                if (filteredDeviceData["latestDeviceInfo"]["osBuildDate"]) {
                    if (filteredDeviceData["latestDeviceInfo"]["osBuildDate"] != "0") {
                        viewModel["osBuildDate"] = new Date(filteredDeviceData["latestDeviceInfo"]["osBuildDate"] * 1000);
                    }
                }
                if (filteredDeviceData["latestDeviceInfo"]["location"]["latitude"] &&
                    filteredDeviceData["latestDeviceInfo"]["location"]["longitude"]) {
                    viewModel["location"] = {};
                    viewModel["location"]["latitude"] = filteredDeviceData["latestDeviceInfo"]["location"]["latitude"];
                    viewModel["location"]["longitude"] = filteredDeviceData["latestDeviceInfo"]["location"]["longitude"];
                    viewModel["location"]["updatedTime"] = filteredDeviceData["latestDeviceInfo"]["location"]["updatedTime"];
                }
                if (filteredDeviceData["latestDeviceInfo"]["vendor"] && filteredDeviceData["latestDeviceInfo"]["deviceModel"]) {
                    viewModel["vendor"] = filteredDeviceData["latestDeviceInfo"]["vendor"];
                    viewModel["model"] = filteredDeviceData["latestDeviceInfo"]["deviceModel"];
                }
                if (filteredDeviceData["latestDeviceInfo"]["updatedTime"]) {
                    viewModel["lastUpdatedTime"] = filteredDeviceData["latestDeviceInfo"]["updatedTime"].
                    substr(0, filteredDeviceData["latestDeviceInfo"]["updatedTime"].indexOf("+"));
                }
                viewModel["BatteryLevel"] = {};
                viewModel["BatteryLevel"]["value"] = filteredDeviceData["latestDeviceInfo"]["batteryLevel"];

                viewModel["cpuUsage"] = {};
                viewModel["cpuUsage"]["value"] = filteredDeviceData["latestDeviceInfo"]["cpuUsage"];

                viewModel["ramUsage"] = {};
                if (filteredDeviceData["latestDeviceInfo"]["totalRAMMemory"] != 0) {
                    viewModel["ramUsage"]["value"] = Math.
                        round((filteredDeviceData["latestDeviceInfo"]["totalRAMMemory"] -
                            filteredDeviceData["latestDeviceInfo"]["availableRAMMemory"])
                            / filteredDeviceData["latestDeviceInfo"]["totalRAMMemory"] * 10000) / 100;
                } else {
                    viewModel["ramUsage"]["value"] = 0;
                }

                viewModel["internalMemory"] = {};
                viewModel["internalMemory"]["total"] = Math.
                    round(filteredDeviceData["latestDeviceInfo"]["internalTotalMemory"] * 100) / 100;
                if (filteredDeviceData["latestDeviceInfo"]["internalTotalMemory"] != 0) {
                    viewModel["internalMemory"]["usage"] = Math.
                        round((filteredDeviceData["latestDeviceInfo"]["internalTotalMemory"] -
                            filteredDeviceData["latestDeviceInfo"]["internalAvailableMemory"])
                            / filteredDeviceData["latestDeviceInfo"]["internalTotalMemory"] * 10000) / 100;
                } else {
                    viewModel["internalMemory"]["usage"] = 0;
                }

                viewModel["externalMemory"] = {};
                viewModel["externalMemory"]["total"] = Math.
                    round(filteredDeviceData["latestDeviceInfo"]["externalTotalMemory"] * 100) / 100;
                if (filteredDeviceData["latestDeviceInfo"]["externalTotalMemory"] != 0) {
                    viewModel["externalMemory"]["usage"] = Math.
                        round((filteredDeviceData["latestDeviceInfo"]["externalTotalMemory"] -
                            filteredDeviceData["latestDeviceInfo"]["externalAvailableMemory"])
                            / filteredDeviceData["latestDeviceInfo"]["externalTotalMemory"] * 10000) / 100;
                } else {
                    viewModel["externalMemory"]["usage"] = 0;
                }
            }
            if (!filteredDeviceData["initialDeviceInfo"] && !filteredDeviceData["latestDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = false;
            }
            viewModel.locationHistory = stringify(filteredDeviceData["locationHistory"]);
            deviceViewData["device"] = viewModel;
        } else if (response["status"] == "unauthorized") {
            deviceViewData["deviceFound"] = true;
            deviceViewData["isAuthorized"] = false;
        } else if (response["status"] == "notFound") {
            deviceViewData["deviceFound"] = false;
        }
    } else {
        deviceViewData["deviceFound"] = false;
    }

    var autoCompleteParams = [
        {"name" : "deviceId", "value" : deviceId}
    ];

    var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
    var permissions = userModule.getUIPermissions();
    deviceViewData["autoCompleteParams"] = autoCompleteParams;
    deviceViewData["permissions"] = permissions;

    deviceViewData["portalUrl"] = devicemgtProps['portalURL'];
    deviceViewData["isCloud"] = devicemgtProps['isCloud'];
    deviceViewData["anchor"] = encodeURI(JSON.stringify({ "device" : { "id" : deviceId, "type" : deviceType}}));
    return deviceViewData;
}
<commit_msg>Showing the used internal memory in the device vitals strip<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

function onRequest(context) {
// var log = new Log("device-view.js");
    var deviceType = context["uriParams"]["deviceType"];
    var deviceId = request.getParameter("id");
    var deviceViewData = {};
    var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];

    if (deviceType && deviceId) {
        var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
        var response = deviceModule.viewDevice(deviceType, deviceId);
        if (response["status"] == "success") {
            deviceViewData["deviceFound"] = true;
            deviceViewData["isAuthorized"] = true;

            var filteredDeviceData = response["content"];

// creating deviceView information model from filtered device data
            var viewModel = {};
            if (filteredDeviceData["type"]) {
                viewModel["type"] = filteredDeviceData["type"];
                viewModel.isNotWindows = true;
            }
            if (filteredDeviceData["deviceIdentifier"]) {
                viewModel["deviceIdentifier"] = filteredDeviceData["deviceIdentifier"];
            }
            if (filteredDeviceData["name"]) {
                viewModel["name"] = filteredDeviceData["name"];
            }
            if (filteredDeviceData["enrolmentInfo"]) {
                if (filteredDeviceData["enrolmentInfo"]["status"]) {
                    viewModel["status"] = filteredDeviceData["enrolmentInfo"]["status"];
                    viewModel.isActive = false ;
                    viewModel.isNotRemoved = true;
                    if (filteredDeviceData["enrolmentInfo"]["status"]== "ACTIVE") {
                        viewModel.isActive = true ;
                    }
                    if (filteredDeviceData["enrolmentInfo"]["status"]== "REMOVED") {
                        viewModel.isNotRemoved = false ;
                    }
                }
                if (filteredDeviceData["enrolmentInfo"]["owner"]) {
                    viewModel["owner"] = filteredDeviceData["enrolmentInfo"]["owner"];
                }
                if (filteredDeviceData["enrolmentInfo"]["ownership"]) {
                    viewModel["ownership"] = filteredDeviceData["enrolmentInfo"]["ownership"];
                }
            }
            if (filteredDeviceData["initialDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = true;
                if (filteredDeviceData["initialDeviceInfo"]["IMEI"]) {
                    viewModel["imei"] = filteredDeviceData["initialDeviceInfo"]["IMEI"];
                }
                if (!filteredDeviceData["latestDeviceInfo"]) {
                    if (filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"]) {
                        if (filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"] != "0") {
                            viewModel["osBuildDate"] = new Date(filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"] * 1000);
                        }
                    }
                    if (filteredDeviceData["initialDeviceInfo"]["LATITUDE"] && filteredDeviceData["initialDeviceInfo"]["LONGITUDE"]) {
                        viewModel["location"] = {};
                        viewModel["location"]["latitude"] = filteredDeviceData["initialDeviceInfo"]["LATITUDE"];
                        viewModel["location"]["longitude"] = filteredDeviceData["initialDeviceInfo"]["LONGITUDE"];
                    }
                    if (filteredDeviceData["initialDeviceInfo"]["VENDOR"] && filteredDeviceData["initialDeviceInfo"]["DEVICE_MODEL"]) {
                        viewModel["vendor"] = filteredDeviceData["initialDeviceInfo"]["VENDOR"];
                        viewModel["model"] = filteredDeviceData["initialDeviceInfo"]["DEVICE_MODEL"];
                    }
                    if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]) {
                        if (deviceType == "android") {
                            viewModel["BatteryLevel"] = {};
                            viewModel["BatteryLevel"]["value"] = filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["BATTERY_LEVEL"];

                            viewModel["internalMemory"] = {};
                            viewModel["internalMemory"]["total"] = Math.
                                round(filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_TOTAL_MEMORY"] * 100) / 100;
                            if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_TOTAL_MEMORY"] != 0) {
                                viewModel["internalMemory"]["usage"] = filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_TOTAL_MEMORY"] -
                                            filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["INTERNAL_AVAILABLE_MEMORY"];
                            } else {
                                viewModel["internalMemory"]["usage"] = 0;
                            }

                            viewModel["externalMemory"] = {};
                            viewModel["externalMemory"]["total"] = Math.
                                round(filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_TOTAL_MEMORY"] * 100) / 100;
                            if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_TOTAL_MEMORY"] != 0) {
                                viewModel["externalMemory"]["usage"] = Math.
                                    round((filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_TOTAL_MEMORY"] -
                                        filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_AVAILABLE_MEMORY"])
                                        / filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["EXTERNAL_TOTAL_MEMORY"] * 10000) / 100;
                            } else {
                                viewModel["externalMemory"]["usage"] = 0;
                            }
                        } else if (deviceType == "ios") {
                            viewModel["BatteryLevel"] = {};
                            viewModel["BatteryLevel"]["value"] = Math. round(filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["BatteryLevel"] * 10000) / 100;

                            viewModel["internalMemory"] = {};
                            viewModel["internalMemory"]["total"] = Math.
                                round(filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["DeviceCapacity"] * 100) / 100;
                            if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["DeviceCapacity"] != 0) {
                                viewModel["internalMemory"]["usage"] = Math.
                                    round((filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["DeviceCapacity"] -
                                        filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["AvailableDeviceCapacity"])
                                        / filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["DeviceCapacity"] * 10000) / 100;
                            } else {
                                viewModel["internalMemory"]["usage"] = 0;
                            }
                        }
                    }
                }
            }
            if (filteredDeviceData["latestDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = true;
                if (filteredDeviceData["latestDeviceInfo"]["osBuildDate"]) {
                    if (filteredDeviceData["latestDeviceInfo"]["osBuildDate"] != "0") {
                        viewModel["osBuildDate"] = new Date(filteredDeviceData["latestDeviceInfo"]["osBuildDate"] * 1000);
                    }
                }
                if (filteredDeviceData["latestDeviceInfo"]["location"]["latitude"] &&
                    filteredDeviceData["latestDeviceInfo"]["location"]["longitude"]) {
                    viewModel["location"] = {};
                    viewModel["location"]["latitude"] = filteredDeviceData["latestDeviceInfo"]["location"]["latitude"];
                    viewModel["location"]["longitude"] = filteredDeviceData["latestDeviceInfo"]["location"]["longitude"];
                    viewModel["location"]["updatedTime"] = filteredDeviceData["latestDeviceInfo"]["location"]["updatedTime"];
                }
                if (filteredDeviceData["latestDeviceInfo"]["vendor"] && filteredDeviceData["latestDeviceInfo"]["deviceModel"]) {
                    viewModel["vendor"] = filteredDeviceData["latestDeviceInfo"]["vendor"];
                    viewModel["model"] = filteredDeviceData["latestDeviceInfo"]["deviceModel"];
                }
                if (filteredDeviceData["latestDeviceInfo"]["updatedTime"]) {
                    viewModel["lastUpdatedTime"] = filteredDeviceData["latestDeviceInfo"]["updatedTime"].
                    substr(0, filteredDeviceData["latestDeviceInfo"]["updatedTime"].indexOf("+"));
                }
                viewModel["BatteryLevel"] = {};
                viewModel["BatteryLevel"]["value"] = filteredDeviceData["latestDeviceInfo"]["batteryLevel"];

                viewModel["cpuUsage"] = {};
                viewModel["cpuUsage"]["value"] = filteredDeviceData["latestDeviceInfo"]["cpuUsage"];

                viewModel["ramUsage"] = {};
                if (filteredDeviceData["latestDeviceInfo"]["totalRAMMemory"] != 0) {
                    viewModel["ramUsage"]["value"] = Math.
                        round((filteredDeviceData["latestDeviceInfo"]["totalRAMMemory"] -
                            filteredDeviceData["latestDeviceInfo"]["availableRAMMemory"])
                            / filteredDeviceData["latestDeviceInfo"]["totalRAMMemory"] * 10000) / 100;
                } else {
                    viewModel["ramUsage"]["value"] = 0;
                }

                viewModel["internalMemory"] = {};
                viewModel["internalMemory"]["total"] = Math.
                    round(filteredDeviceData["latestDeviceInfo"]["internalTotalMemory"] * 100) / 100;
                if (filteredDeviceData["latestDeviceInfo"]["internalTotalMemory"] != 0) {
                    viewModel["internalMemory"]["usage"] = filteredDeviceData["latestDeviceInfo"]["internalTotalMemory"] -
                                filteredDeviceData["latestDeviceInfo"]["internalAvailableMemory"];
                } else {
                    viewModel["internalMemory"]["usage"] = 0;
                }

                viewModel["externalMemory"] = {};
                viewModel["externalMemory"]["total"] = Math.
                    round(filteredDeviceData["latestDeviceInfo"]["externalTotalMemory"] * 100) / 100;
                if (filteredDeviceData["latestDeviceInfo"]["externalTotalMemory"] != 0) {
                    viewModel["externalMemory"]["usage"] = Math.
                        round((filteredDeviceData["latestDeviceInfo"]["externalTotalMemory"] -
                            filteredDeviceData["latestDeviceInfo"]["externalAvailableMemory"])
                            / filteredDeviceData["latestDeviceInfo"]["externalTotalMemory"] * 10000) / 100;
                } else {
                    viewModel["externalMemory"]["usage"] = 0;
                }
            }
            if (!filteredDeviceData["initialDeviceInfo"] && !filteredDeviceData["latestDeviceInfo"]) {
                viewModel["deviceInfoAvailable"] = false;
            }
            viewModel.locationHistory = stringify(filteredDeviceData["locationHistory"]);
            deviceViewData["device"] = viewModel;
        } else if (response["status"] == "unauthorized") {
            deviceViewData["deviceFound"] = true;
            deviceViewData["isAuthorized"] = false;
        } else if (response["status"] == "notFound") {
            deviceViewData["deviceFound"] = false;
        }
    } else {
        deviceViewData["deviceFound"] = false;
    }

    var autoCompleteParams = [
        {"name" : "deviceId", "value" : deviceId}
    ];

    var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
    var permissions = userModule.getUIPermissions();
    deviceViewData["autoCompleteParams"] = autoCompleteParams;
    deviceViewData["permissions"] = permissions;

    deviceViewData["portalUrl"] = devicemgtProps['portalURL'];
    deviceViewData["isCloud"] = devicemgtProps['isCloud'];
    deviceViewData["anchor"] = encodeURI(JSON.stringify({ "device" : { "id" : deviceId, "type" : deviceType}}));
    return deviceViewData;
}
<|endoftext|>