<commit_before>import React from 'react';
import {mount} from 'enzyme';
import {isTestkitExists, isEnzymeTestkitExists} from '../../testkit/test-common';
import notificationDriverFactory from './Notification.driver';
import {createDriverFactory} from '../test-common';
import {notificationTestkitFactory} from '../../testkit';
import {notificationTestkitFactory as enzymeNotificationTestkitFactory} from '../../testkit/enzyme';

import Notification from './Notification';

const renderNotificationWithProps = (props = {}) => (
  <Notification {...props}>
    <Notification.TextLabel>
      label
    </Notification.TextLabel>
    <Notification.CloseButton/>
  </Notification>
);

describe('Notification', () => {
  const createDriver = createDriverFactory(notificationDriverFactory);

  describe('Visibility', () => {
    it('should verify component exists', () => {
      const driver = createDriver(renderNotificationWithProps());
      expect(driver.exists()).toBeTruthy();
    });

    it('should be visible', () => {
      const driver = createDriver(renderNotificationWithProps({show: true}));
      expect(driver.visible()).toBeTruthy();
    });

    it('should not be visible', () => {
      const driver = createDriver(renderNotificationWithProps({show: false}));
      expect(driver.visible()).toBeFalsy();
    });
  });

  describe('Themes', () => {
    it('should support default theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true}));
      expect(driver.isStandardNotification()).toBeTruthy();
      expect(driver.hasTheme('standard')).toBeTruthy();
    });

    it('should support standard theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'standard'}));
      expect(driver.isStandardNotification()).toBeTruthy();
    });

    it('should support error theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'error'}));
      expect(driver.isErrorNotification()).toBeTruthy();
    });

    it('should support success theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'success'}));
      expect(driver.isSuccessNotification()).toBeTruthy();
    });

    it('should support warning theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'warning'}));
      expect(driver.isWarningNotification()).toBeTruthy();
    });

    it('should support premium theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'premium'}));
      expect(driver.isPremiumNotification()).toBeTruthy();
    });
  });

  describe('Sizes', () => {
    it('should have a default size', () => {
      const driver = createDriver(renderNotificationWithProps({show: true}));
      expect(driver.isSmallSize()).toBeTruthy();
    });

    it('should support standard height', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, size: 'small'}));
      expect(driver.isSmallSize()).toBeTruthy();
    });

    it('should support a big height', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, size: 'big'}));
      expect(driver.isBigSize()).toBeTruthy();
    });
  });

  describe('Content', () => {
    describe('Label', () => {
      it('should show have a text to show', () => {
        const labelText = 'Label Text';
        const driver = createDriver(
          <Notification show>
            <Notification.TextLabel>
              {labelText}
            </Notification.TextLabel>
            <Notification.CloseButton/>
          </Notification>
        );
        expect(driver.getLabelText()).toEqual(labelText);
      });
    });

    describe('Action Button', () => {
      it('should have an action button', () => {
        const actionButtonText = 'Action Button Text';
        const driver = createDriver(
          <Notification show>
            <Notification.TextLabel>
              label
            </Notification.TextLabel>
            <Notification.ActionButton>
              {actionButtonText}
            </Notification.ActionButton>
            <Notification.CloseButton/>
          </Notification>
        );
        expect(driver.getActionButtonText()).toEqual(actionButtonText);
      });

      it('should not have an action button', () => {
        const driver = createDriver(renderNotificationWithProps({show: true}));
        expect(driver.hasActionButton()).toBeFalsy();
      });

      it('should call the supplied onClick handler when clicked', () => {
        const onClickMock = jest.fn();

        const driver = createDriver(
          <Notification show>
            <Notification.TextLabel>
              label
            </Notification.TextLabel>
            <Notification.ActionButton onClick={onClickMock}>
              action
            </Notification.ActionButton>
            <Notification.CloseButton/>
          </Notification>
        );

        driver.clickOnActionButton();

        expect(onClickMock).toBeCalled();
      });
    });

    describe('Close Button', () => {
      it('should have a close button (with action button)', () => {
        const driver = createDriver(renderNotificationWithProps({show: true}));
        expect(driver.hasCloseButton()).toBeTruthy();
      });

      it('should have a close button (without action button)', () => {
        const driver = createDriver(renderNotificationWithProps({show: true}));
        expect(driver.hasActionButton()).toBeFalsy();
        expect(driver.hasCloseButton()).toBeTruthy();
      });
    });
  });

  describe('Type', () => {
    it('should set default type to global and position relative', () => {
      const driver = createDriver(renderNotificationWithProps({show: true}));
      expect(driver.isRelativelyPositioned()).toBeTruthy();
    });

    it('should set the type to global and position relative', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, type: 'global'}));
      expect(driver.isRelativelyPositioned()).toBeTruthy();
    });

    it('should set the type to local and position absolute', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, type: 'local'}));
      expect(driver.isAbsolutePositioned()).toBeTruthy();
    });

    it('should set the type to sticky and position fixed', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, type: 'sticky'}));
      expect(driver.isFixedPositioned()).toBeTruthy();
    });
  });

  describe('Closing', () => {
    let driver;

    beforeEach(() => {
      jest.useFakeTimers();
    });

    describe('Closing when clicking on close button', () => {

      beforeEach(() => {
        driver = createDriver(renderNotificationWithProps({show: true}));
        driver.clickOnCloseButton();
      });

      beforeEach(() => {
        jest.runAllTimers();
      });

      // it('should close the notification', () => {
      //   expect(driver.visible()).toBeFalsy();
      // });

      it('should allow reopening the notification after closed by close button', () => {
        driver.setProps({show: true});
        expect(driver.visible()).toBeTruthy();
      });
    });

    describe('Closing after timeout for local Notification', () => {
      const defaultTimeout = 6000;

      it('should close after default timeout (6s)', () => {
        driver = createDriver(renderNotificationWithProps({show: true, type: 'local'}));
        jest.runAllTimers();

        expect(driver.visible()).toBeFalsy();
        expect(setTimeout.mock.calls.find(call => call[1] === defaultTimeout)).toBeTruthy();
      });

      it('should close after a given timeout', () => {
        const timeout = 132;

        driver = createDriver(renderNotificationWithProps({show: true, type: 'local', timeout}));

        jest.runAllTimers();

        expect(driver.visible()).toBeFalsy();
        expect(setTimeout.mock.calls.find(call => call[1] === timeout)).toBeTruthy();
      });

      it('should be able to show notification again after timeout', () => {
        driver = createDriver(renderNotificationWithProps({show: true, type: 'local'}));

        jest.runAllTimers();
        expect(driver.visible()).toBeFalsy();
        expect(setTimeout.mock.calls.find(call => call[1] === defaultTimeout)).toBeTruthy();
        jest.clearAllTimers();

        driver.setProps({show: true});
        expect(driver.visible()).toBeTruthy();
      });

      it('should close after starting from a closed status', () => {
        driver = createDriver(renderNotificationWithProps({show: false, type: 'local'}));

        jest.runAllTimers();
        expect(driver.visible()).toBeFalsy();
        driver.setProps({show: true});
        expect(driver.visible()).toBeTruthy();
        jest.runAllTimers();
        expect(driver.visible()).toBeFalsy();

        expect(setTimeout.mock.calls.find(call => call[1] === defaultTimeout)).toBeTruthy();
      });
    });

    afterEach(() => {
      jest.clearAllTimers();
    });
  });

  describe('Style', () => {
    it('should accept a z-index', () => {
      const zIndex = 999;
      const driver = createDriver(renderNotificationWithProps({show: true, zIndex}));
      expect(driver.getZIndex()).toEqual(zIndex);
    });
  });

  describe('testkit', () => {
    it('should exist', () => {
      const component = renderNotificationWithProps({show: true});
      expect(isTestkitExists(component, notificationTestkitFactory)).toBeTruthy();
    });
  });

  describe('enzyme testkit', () => {
    it('should exist', () => {
      const component = renderNotificationWithProps({show: true});
      expect(isEnzymeTestkitExists(component, enzymeNotificationTestkitFactory)).toBeTruthy();
    });
  });

  describe('Notification.ActionButton', () => {
    it('should display a Button when passing by default', () => {
      const component = mount(
        <Notification.ActionButton>
          Action Button
        </Notification.ActionButton>
      );

      expect(component.find('Button').length).toEqual(1);
    });

    it('should display a Button when explicitly required', () => {
      const component = mount(
        <Notification.ActionButton type="button">
          Action Button
        </Notification.ActionButton>
      );

      expect(component.find('Button').length).toEqual(1);
    });

    it('should display a TextLink explicitly required', () => {
      const component = mount(
        <Notification.ActionButton type="textLink" link="some link">
          Action Button
        </Notification.ActionButton>
      );

      expect(component.find('TextLink').length).toEqual(1);
    });
  });
});
<commit_msg>add more tests to notification<commit_after>import React from 'react';
import {mount} from 'enzyme';
import {isTestkitExists} from '../../testkit/test-common';
import notificationDriverFactory from './Notification.driver';
import {createDriverFactory} from '../test-common';
import {notificationTestkitFactory} from '../../testkit';
import {notificationTestkitFactory as enzymeNotificationTestkitFactory, buttonTestkitFactory as enzymeButtonTestkitFactory} from '../../testkit/enzyme';

import Notification from './Notification';
import Button from '../../src/Button';

const renderNotificationWithProps = (props = {}) => (
  <Notification {...props}>
    <Notification.TextLabel>
      label
    </Notification.TextLabel>
    <Notification.CloseButton/>
  </Notification>
);

describe('Notification', () => {
  const createDriver = createDriverFactory(notificationDriverFactory);

  describe('Visibility', () => {
    it('should verify component exists', () => {
      const driver = createDriver(renderNotificationWithProps());
      expect(driver.exists()).toBeTruthy();
    });

    it('should be visible', () => {
      const driver = createDriver(renderNotificationWithProps({show: true}));
      expect(driver.visible()).toBeTruthy();
    });

    it('should not be visible', () => {
      const driver = createDriver(renderNotificationWithProps({show: false}));
      expect(driver.visible()).toBeFalsy();
    });
  });

  describe('Themes', () => {
    it('should support default theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true}));
      expect(driver.isStandardNotification()).toBeTruthy();
      expect(driver.hasTheme('standard')).toBeTruthy();
    });

    it('should support standard theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'standard'}));
      expect(driver.isStandardNotification()).toBeTruthy();
    });

    it('should support error theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'error'}));
      expect(driver.isErrorNotification()).toBeTruthy();
    });

    it('should support success theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'success'}));
      expect(driver.isSuccessNotification()).toBeTruthy();
    });

    it('should support warning theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'warning'}));
      expect(driver.isWarningNotification()).toBeTruthy();
    });

    it('should support premium theme', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, theme: 'premium'}));
      expect(driver.isPremiumNotification()).toBeTruthy();
    });
  });

  describe('Sizes', () => {
    it('should have a default size', () => {
      const driver = createDriver(renderNotificationWithProps({show: true}));
      expect(driver.isSmallSize()).toBeTruthy();
    });

    it('should support standard height', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, size: 'small'}));
      expect(driver.isSmallSize()).toBeTruthy();
    });

    it('should support a big height', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, size: 'big'}));
      expect(driver.isBigSize()).toBeTruthy();
    });
  });

  describe('Content', () => {
    describe('Label', () => {
      it('should show have a text to show', () => {
        const labelText = 'Label Text';
        const driver = createDriver(
          <Notification show>
            <Notification.TextLabel>
              {labelText}
            </Notification.TextLabel>
            <Notification.CloseButton/>
          </Notification>
        );
        expect(driver.getLabelText()).toEqual(labelText);
      });
    });

    describe('Action Button', () => {
      it('should have an action button', () => {
        const actionButtonText = 'Action Button Text';
        const driver = createDriver(
          <Notification show>
            <Notification.TextLabel>
              label
            </Notification.TextLabel>
            <Notification.ActionButton>
              {actionButtonText}
            </Notification.ActionButton>
            <Notification.CloseButton/>
          </Notification>
        );
        expect(driver.getActionButtonText()).toEqual(actionButtonText);
      });

      it('should not have an action button', () => {
        const driver = createDriver(renderNotificationWithProps({show: true}));
        expect(driver.hasActionButton()).toBeFalsy();
      });

      it('should call the supplied onClick handler when clicked', () => {
        const onClickMock = jest.fn();

        const driver = createDriver(
          <Notification show>
            <Notification.TextLabel>
              label
            </Notification.TextLabel>
            <Notification.ActionButton onClick={onClickMock}>
              action
            </Notification.ActionButton>
            <Notification.CloseButton/>
          </Notification>
        );

        driver.clickOnActionButton();

        expect(onClickMock).toBeCalled();
      });
    });

    describe('Close Button', () => {
      it('should have a close button (with action button)', () => {
        const driver = createDriver(renderNotificationWithProps({show: true}));
        expect(driver.hasCloseButton()).toBeTruthy();
      });

      it('should have a close button (without action button)', () => {
        const driver = createDriver(renderNotificationWithProps({show: true}));
        expect(driver.hasActionButton()).toBeFalsy();
        expect(driver.hasCloseButton()).toBeTruthy();
      });
    });
  });

  describe('Type', () => {
    it('should set default type to global and position relative', () => {
      const driver = createDriver(renderNotificationWithProps({show: true}));
      expect(driver.isRelativelyPositioned()).toBeTruthy();
    });

    it('should set the type to global and position relative', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, type: 'global'}));
      expect(driver.isRelativelyPositioned()).toBeTruthy();
    });

    it('should set the type to local and position absolute', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, type: 'local'}));
      expect(driver.isAbsolutePositioned()).toBeTruthy();
    });

    it('should set the type to sticky and position fixed', () => {
      const driver = createDriver(renderNotificationWithProps({show: true, type: 'sticky'}));
      expect(driver.isFixedPositioned()).toBeTruthy();
    });
  });

  describe('Closing', () => {
    let driver;

    beforeEach(() => {
      jest.useFakeTimers();
    });

    describe('Closing when clicking on close button', () => {

      beforeEach(() => {
        driver = createDriver(renderNotificationWithProps({show: true}));
        driver.clickOnCloseButton();
      });

      beforeEach(() => {
        jest.runAllTimers();
      });

      // it('should close the notification', () => {
      //   expect(driver.visible()).toBeFalsy();
      // });

      it('should allow reopening the notification after closed by close button', () => {
        driver.setProps({show: true});
        expect(driver.visible()).toBeTruthy();
      });
    });

    describe('Closing after timeout for local Notification', () => {
      const defaultTimeout = 6000;

      it('should close after default timeout (6s)', () => {
        driver = createDriver(renderNotificationWithProps({show: true, type: 'local'}));
        jest.runAllTimers();

        expect(driver.visible()).toBeFalsy();
        expect(setTimeout.mock.calls.find(call => call[1] === defaultTimeout)).toBeTruthy();
      });

      it('should close after a given timeout', () => {
        const timeout = 132;

        driver = createDriver(renderNotificationWithProps({show: true, type: 'local', timeout}));

        jest.runAllTimers();

        expect(driver.visible()).toBeFalsy();
        expect(setTimeout.mock.calls.find(call => call[1] === timeout)).toBeTruthy();
      });

      it('should be able to show notification again after timeout', () => {
        driver = createDriver(renderNotificationWithProps({show: true, type: 'local'}));

        jest.runAllTimers();
        expect(driver.visible()).toBeFalsy();
        expect(setTimeout.mock.calls.find(call => call[1] === defaultTimeout)).toBeTruthy();
        jest.clearAllTimers();

        driver.setProps({show: true});
        expect(driver.visible()).toBeTruthy();
      });

      it('should close after starting from a closed status', () => {
        driver = createDriver(renderNotificationWithProps({show: false, type: 'local'}));

        jest.runAllTimers();
        expect(driver.visible()).toBeFalsy();
        driver.setProps({show: true});
        expect(driver.visible()).toBeTruthy();
        jest.runAllTimers();
        expect(driver.visible()).toBeFalsy();

        expect(setTimeout.mock.calls.find(call => call[1] === defaultTimeout)).toBeTruthy();
      });
    });

    afterEach(() => {
      jest.clearAllTimers();
    });
  });

  describe('Style', () => {
    it('should accept a z-index', () => {
      const zIndex = 999;
      const driver = createDriver(renderNotificationWithProps({show: true, zIndex}));
      expect(driver.getZIndex()).toEqual(zIndex);
    });
  });

  describe('testkit', () => {
    it('should exist', () => {
      const component = renderNotificationWithProps({show: true});
      expect(isTestkitExists(component, notificationTestkitFactory)).toBeTruthy();
    });
  });

  describe('enzyme testkit', () => {
    it('should exist', () => {
      const component = mount(<ControlledNotification/>);

      const enzymeNotificationTestkit = enzymeNotificationTestkitFactory({wrapper: component, dataHook: 'notification_dh'});
      const enzymeButtonTestkit = enzymeButtonTestkitFactory({wrapper: component, dataHook: 'button_dh'});

      expect(enzymeNotificationTestkit.visible()).toBeFalsy();
      expect(enzymeButtonTestkit.exists()).toBeTruthy();

      enzymeButtonTestkit.click();

      expect(enzymeNotificationTestkit.visible()).toBeTruthy();
    });
  });

  describe('Notification.ActionButton', () => {
    it('should display a Button when passing by default', () => {
      const component = mount(
        <Notification.ActionButton>
          Action Button
        </Notification.ActionButton>
      );

      expect(component.find('Button').length).toEqual(1);
    });

    it('should display a Button when explicitly required', () => {
      const component = mount(
        <Notification.ActionButton type="button">
          Action Button
        </Notification.ActionButton>
      );

      expect(component.find('Button').length).toEqual(1);
    });

    it('should display a TextLink explicitly required', () => {
      const component = mount(
        <Notification.ActionButton type="textLink" link="some link">
          Action Button
        </Notification.ActionButton>
      );

      expect(component.find('TextLink').length).toEqual(1);
    });
  });
});

class ControlledNotification extends React.Component {
  constructor(props) {
    super(props);

    this.state = {showNotification: false};
  }

  render() {
    return (
      <div>
        <Button dataHook="button_dh" onClick={() => this.setState({showNotification: !this.state.showNotification})}>
          button
        </Button>
        <Notification dataHook="notification_dh" show={this.state.showNotification}>
          <Notification.TextLabel>
            label
          </Notification.TextLabel>
          <Notification.CloseButton/>
        </Notification>
      </div>
    );
  }
}
<|endoftext|>


<commit_before>import { Notifications, Location, Permissions } from 'expo';
import React from 'react';
import { StyleSheet, StatusBar} from 'react-native';
import { StackNavigator } from 'react-navigation';

import MainTabNavigator from './MainTabNavigator';
import registerForPushNotificationsAsync from '../api/registerForPushNotificationsAsync';
import MapScreen from '../screens/MapScreen';
import ListScreen from '../screens/ListScreen';
import CommentsScreen from '../screens/CommentsScreen';

var ScrollableTabView = require('react-native-scrollable-tab-view');

const RootStackNavigator = StackNavigator(
  {
    Main: {
      screen: MainTabNavigator,
    },
  },
  {
    navigationOptions: () => ({
      headerTitleStyle: {
        fontWeight: 'normal',
      },
    }),
  }
);

export default class RootNavigator extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      latitude: 12,
      longitude: -12,
      errorMessage: null,
      parkingLots: [
        {id: 0, name: 'Lot0', latitude: 37.786000, longitude: -122.40100, distance: '1.0', paid: 'paid'},
        {id: 1, name: 'Lot1', latitude: 37.787000, longitude: -122.40100, distance: '1.1', paid: 'paid'},
        {id: 2, name: 'Lot2', latitude: 37.788000, longitude: -122.40200, distance: '1.2', paid: 'paid'},
        {id: 3, name: 'Lot3', latitude: 37.789000, longitude: -122.40300, distance: '1.3', paid: 'free'},
        {id: 4, name: 'Lot4', latitude: 37.781000, longitude: -122.40400, distance: '1.4', paid: 'free'},
      ],
    }
  }

  componentWillMount() {
    this.retrieveCoordinates();
    var parkingLots = this.state.parkingLots;
    for (var i = 5; i < 200; i++) {
      var lot = {id: i, name: 'Lot' + i, latitude: 37.786000 + 0.001*i, longitude: -122.40100 - 0.001*i, distance: '1.' + i, paid: 'paid'};
      parkingLots.push(lot);
    }
    console.log("RootNav" + this.props.parkingLots);
  }

  retrieveCoordinates() { // gets the coordinate locations for the user
    navigator.geolocation.getCurrentPosition(
          (position) => {
            this.setState({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
              error: null,
            });
          },
          (error) => this.setState({ error: error.message }),
          { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
        );
  }

  render() {
    console.log("OnRootNavigationRender:" + this.state.latitude + " " + this.state.longitude);
    return (
      <ScrollableTabView style={this.props.style} tabBarTextStyle={styles.tabBar} tabBarPosition='overlayBottom' tabBarBackgroundColor='skyblue' tabBarInactiveTextColor='white'>
        <MapScreen tabLabel="Map" latitude={this.state.latitude} longitude={this.state.longitude} parkingLots={this.state.parkingLots} />
        <ListScreen tabLabel="List" latitude={this.state.latitude} longitude={this.state.longitude} parkingLots={this.state.parkingLots} />
        <CommentsScreen tabLabel="Reviews" latitude={this.state.latitude} longitude={this.state.longitude} parkingLots={this.state.parkingLots} />
      </ScrollableTabView>
    );
  }

}

const styles = StyleSheet.create({
  tabBar: {
    fontFamily: 'Roboto',
    fontWeight: '100',
    padding: 5,
  }
});<commit_msg>Closer location, randomize paid/free<commit_after>import { Notifications, Location, Permissions } from 'expo';
import React from 'react';
import { StyleSheet, StatusBar} from 'react-native';
import { StackNavigator } from 'react-navigation';

import MainTabNavigator from './MainTabNavigator';
import registerForPushNotificationsAsync from '../api/registerForPushNotificationsAsync';
import MapScreen from '../screens/MapScreen';
import ListScreen from '../screens/ListScreen';
import CommentsScreen from '../screens/CommentsScreen';

var ScrollableTabView = require('react-native-scrollable-tab-view');

const RootStackNavigator = StackNavigator(
  {
    Main: {
      screen: MainTabNavigator,
    },
  },
  {
    navigationOptions: () => ({
      headerTitleStyle: {
        fontWeight: 'normal',
      },
    }),
  }
);

export default class RootNavigator extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      latitude: 12,
      longitude: -12,
      errorMessage: null,
      parkingLots: [],
    }
  }

  componentWillMount() {
    this.retrieveCoordinates();
    var parkingLots = this.state.parkingLots;
    for (var i = 0; i < 200; i++) {
      var lot = {id: i, name: 'Lot' + i, latitude: 42.2959020 + 0.001*i, longitude: -83.7103320 - 0.001*i, distance: '1.' + i, paid: Math.random() < 0.5? 'paid' : 'free'};
      parkingLots.push(lot);
    }
    console.log("RootNav" + this.props.parkingLots);
  }

  retrieveCoordinates() { // gets the coordinate locations for the user
    navigator.geolocation.getCurrentPosition(
          (position) => {
            this.setState({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
              error: null,
            });
          },
          (error) => this.setState({ error: error.message }),
          { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
        );
  }

  render() {
    console.log("OnRootNavigationRender:" + this.state.latitude + " " + this.state.longitude);
    return (
      <ScrollableTabView style={this.props.style} tabBarTextStyle={styles.tabBar} tabBarPosition='overlayBottom' tabBarBackgroundColor='skyblue' tabBarInactiveTextColor='white'>
        <MapScreen tabLabel="Map" latitude={this.state.latitude} longitude={this.state.longitude} parkingLots={this.state.parkingLots} />
        <ListScreen tabLabel="List" latitude={this.state.latitude} longitude={this.state.longitude} parkingLots={this.state.parkingLots} />
        <CommentsScreen tabLabel="Reviews" latitude={this.state.latitude} longitude={this.state.longitude} parkingLots={this.state.parkingLots} />
      </ScrollableTabView>
    );
  }

}

const styles = StyleSheet.create({
  tabBar: {
    fontFamily: 'Roboto',
    fontWeight: '100',
    padding: 5,
  }
});<|endoftext|>


<commit_before>/*global define*/
'use strict';

define(['angular',], function (angular) {
    var moduleName = 'vtl';
    angular.module(moduleName, [])
        .directive('vtlExample', function () {
            return {
                restrict: 'AE',
                scope: {},
                transclude: true,
                template: '

',
                controller: ['$scope', '$http', function ($scope, $http) {

                    $scope.outputDatasets = [];
                    $scope.inputDatasets = [];
                    $scope.$watch('outputDatasets', function (newValues, oldValues) {
                        // Copy
                        $scope.datasets = $scope.inputDatasets.slice();
                        if (newValues) {
                            var seen = {};
                            var output = newValues, input = $scope.datasets;
                            for (var i = 0; i < input.length; i++) {
                                seen[input[i].name] = true;
                            }
                            for (var i = 0; i < output.length; i++) {
                                if (!seen[output[i].name]) {
                                    $scope.datasets.push(output[i]);
                                }
                            }
                        }
                    });

                    $scope.errors = null;
                    $scope.loading = false;

                    this.execute = function (expression) {

                        $scope.loading = true;
                        $scope.errors = null;

                        var execution = {
                            datasets: $scope.inputDatasets,
                            expression: expression
                        };

                        // Simple GET request example:
                        $http({
                            data: execution,
                            method: 'POST',
                            url: 'https://javavtl.ssbmod.net/vtl/execute2'
                        }).then(function successCallback(response) {
                            $scope.loading = false;
                            $scope.outputDatasets = response.data.datasets;
                        }, function failureCallback(response) {
                            $scope.loading = false;
                            $scope.errors = response.data;
                        });
                    };

                    this.addInput = function (dataset) {
                        $scope.inputDatasets.push(dataset);
                    };

                }],
                link: function (scope, element, attrs, ctrl, transclude) {
                    // Use the function to bind the transcluded content to
                    // isolated scope.
                    transclude(scope, function (clone, scope) {
                        element.find('div').append(clone);
                    });
                }
            };
        });
    return moduleName;
});
<commit_msg>Use staging javavtl server<commit_after>/*global define*/
'use strict';

define(['angular',], function (angular) {
    var moduleName = 'vtl';
    angular.module(moduleName, [])
        .directive('vtlExample', function () {
            return {
                restrict: 'AE',
                scope: {},
                transclude: true,
                template: '

',
                controller: ['$scope', '$http', function ($scope, $http) {

                    $scope.outputDatasets = [];
                    $scope.inputDatasets = [];
                    $scope.$watch('outputDatasets', function (newValues, oldValues) {
                        // Copy
                        $scope.datasets = $scope.inputDatasets.slice();
                        if (newValues) {
                            var seen = {};
                            var output = newValues, input = $scope.datasets;
                            for (var i = 0; i < input.length; i++) {
                                seen[input[i].name] = true;
                            }
                            for (var i = 0; i < output.length; i++) {
                                if (!seen[output[i].name]) {
                                    $scope.datasets.push(output[i]);
                                }
                            }
                        }
                    });

                    $scope.errors = null;
                    $scope.loading = false;

                    this.execute = function (expression) {

                        $scope.loading = true;
                        $scope.errors = null;

                        var execution = {
                            datasets: $scope.inputDatasets,
                            expression: expression
                        };

                        // Simple GET request example:
                        $http({
                            data: execution,
                            method: 'POST',
                            url: 'https://javavtl.staging.ssbmod.net/vtl/execute2'
                        }).then(function successCallback(response) {
                            $scope.loading = false;
                            $scope.outputDatasets = response.data.datasets;
                        }, function failureCallback(response) {
                            $scope.loading = false;
                            $scope.errors = response.data;
                        });
                    };

                    this.addInput = function (dataset) {
                        $scope.inputDatasets.push(dataset);
                    };

                }],
                link: function (scope, element, attrs, ctrl, transclude) {
                    // Use the function to bind the transcluded content to
                    // isolated scope.
                    transclude(scope, function (clone, scope) {
                        element.find('div').append(clone);
                    });
                }
            };
        });
    return moduleName;
});
<|endoftext|>


<commit_before>import external from '../externalModules.js';
import mouseButtonTool from './mouseButtonTool.js';
import touchTool from './touchTool.js';
import drawLinkedTextBox from '../util/drawLinkedTextBox.js';
import toolStyle from '../stateManagement/toolStyle.js';
import toolColors from '../stateManagement/toolColors.js';
import drawHandles from '../manipulators/drawHandles.js';
import { getToolState } from '../stateManagement/toolState.js';
import lineSegDistance from '../util/lineSegDistance.js';

const toolType = 'length';

// /////// BEGIN ACTIVE TOOL ///////
function createNewMeasurement (mouseEventData) {
  // Create the measurement data for this tool with the end handle activated
  const measurementData = {
    visible: true,
    active: true,
    color: undefined,
    handles: {
      start: {
        x: mouseEventData.currentPoints.image.x,
        y: mouseEventData.currentPoints.image.y,
        highlight: true,
        active: false
      },
      end: {
        x: mouseEventData.currentPoints.image.x,
        y: mouseEventData.currentPoints.image.y,
        highlight: true,
        active: true
      },
      textBox: {
        active: false,
        hasMoved: false,
        movesIndependently: false,
        drawnIndependently: true,
        allowedOutsideImage: true,
        hasBoundingBox: true
      }
    }
  };

  return measurementData;
}
// /////// END ACTIVE TOOL ///////

function pointNearTool (element, data, coords) {
  if (data.visible === false) {
    return false;
  }

  return lineSegDistance(element, data.handles.start, data.handles.end, coords) < 25;
}

// /////// BEGIN IMAGE RENDERING ///////
function onImageRendered (e) {
  const eventData = e.detail;

  // If we have no toolData for this element, return immediately as there is nothing to do
  const toolData = getToolState(e.currentTarget, toolType);

  if (!toolData) {
    return;
  }

  const cornerstone = external.cornerstone;
  // We have tool data for this element - iterate over each one and draw it
  const context = eventData.canvasContext.canvas.getContext('2d');
  const { image, element } = eventData;

  context.setTransform(1, 0, 0, 1, 0, 0);

  const lineWidth = toolStyle.getToolWidth();
  const config = length.getConfiguration();
  const imagePlane = cornerstone.metaData.get('imagePlaneModule', image.imageId);
  let rowPixelSpacing;
  let colPixelSpacing;

  if (imagePlane) {
    rowPixelSpacing = imagePlane.rowPixelSpacing || imagePlane.rowImagePixelSpacing;
    colPixelSpacing = imagePlane.columnPixelSpacing || imagePlane.colImagePixelSpacing;
  } else {
    rowPixelSpacing = image.rowPixelSpacing;
    colPixelSpacing = image.columnPixelSpacing;
  }

  for (let i = 0; i < toolData.data.length; i++) {
    context.save();

    // Configurable shadow
    if (config && config.shadow) {
      context.shadowColor = config.shadowColor || '#000000';
      context.shadowOffsetX = config.shadowOffsetX || 1;
      context.shadowOffsetY = config.shadowOffsetY || 1;
    }

    const data = toolData.data[i];

    if (data.visible === false) {
      continue;
    }

    const color = toolColors.getColorIfActive(data);

    // Get the handle positions in canvas coordinates
    const handleStartCanvas = cornerstone.pixelToCanvas(element, data.handles.start);
    const handleEndCanvas = cornerstone.pixelToCanvas(element, data.handles.end);

    // Draw the measurement line
    context.beginPath();
    context.strokeStyle = color;
    context.lineWidth = lineWidth;
    context.moveTo(handleStartCanvas.x, handleStartCanvas.y);
    context.lineTo(handleEndCanvas.x, handleEndCanvas.y);
    context.stroke();

    // Draw the handles
    const handleOptions = {
      drawHandlesIfActive: (config && config.drawHandlesOnHover)
    };

    drawHandles(context, eventData, data.handles, color, handleOptions);

    // Draw the text
    context.fillStyle = color;

    // Set rowPixelSpacing and columnPixelSpacing to 1 if they are undefined (or zero)
    const dx = (data.handles.end.x - data.handles.start.x) * (rowPixelSpacing || 1);
    const dy = (data.handles.end.y - data.handles.start.y) * (colPixelSpacing || 1);

    // Calculate the length, and create the text variable with the millimeters or pixels suffix
    const length = Math.sqrt(dx * dx + dy * dy);

    // Store the length inside the tool for outside access
    data.length = length;

    if (!data.handles.textBox.hasMoved) {
      const coords = {
        x: Math.max(data.handles.start.x, data.handles.end.x)
      };

      // Depending on which handle has the largest x-value,
      // Set the y-value for the text box
      if (coords.x === data.handles.start.x) {
        coords.y = data.handles.start.y;
      } else {
        coords.y = data.handles.end.y;
      }

      data.handles.textBox.x = coords.x;
      data.handles.textBox.y = coords.y;
    }

    // Move the textbox slightly to the right and upwards
    // So that it sits beside the length tool handle
    const xOffset = 10;

    const text = textBoxText(data, rowPixelSpacing, colPixelSpacing);

    drawLinkedTextBox(context, element, data.handles.textBox, text,
      data.handles, textBoxAnchorPoints, color, lineWidth, xOffset, true);
    context.restore();
  }

  function textBoxText (data, rowPixelSpacing, colPixelSpacing) {
    // Set the length text suffix depending on whether or not pixelSpacing is available
    let suffix = ' mm';

    if (!rowPixelSpacing || !colPixelSpacing) {
      suffix = ' pixels';
    }

    return `${data.length.toFixed(2)}${suffix}`;
  }

  function textBoxAnchorPoints (handles) {
    const midpoint = {
      x: (handles.start.x + handles.end.x) / 2,
      y: (handles.start.y + handles.end.y) / 2
    };

    return [handles.start, midpoint, handles.end];
  }
}
// /////// END IMAGE RENDERING ///////

// Module exports
const length = mouseButtonTool({
  createNewMeasurement,
  onImageRendered,
  pointNearTool,
  toolType
});

const lengthTouch = touchTool({
  createNewMeasurement,
  onImageRendered,
  pointNearTool,
  toolType
});

export {
  length,
  lengthTouch
};
<commit_msg>Fix x and y distances<commit_after>import external from '../externalModules.js';
import mouseButtonTool from './mouseButtonTool.js';
import touchTool from './touchTool.js';
import drawLinkedTextBox from '../util/drawLinkedTextBox.js';
import toolStyle from '../stateManagement/toolStyle.js';
import toolColors from '../stateManagement/toolColors.js';
import drawHandles from '../manipulators/drawHandles.js';
import { getToolState } from '../stateManagement/toolState.js';
import lineSegDistance from '../util/lineSegDistance.js';

const toolType = 'length';

// /////// BEGIN ACTIVE TOOL ///////
function createNewMeasurement (mouseEventData) {
  // Create the measurement data for this tool with the end handle activated
  const measurementData = {
    visible: true,
    active: true,
    color: undefined,
    handles: {
      start: {
        x: mouseEventData.currentPoints.image.x,
        y: mouseEventData.currentPoints.image.y,
        highlight: true,
        active: false
      },
      end: {
        x: mouseEventData.currentPoints.image.x,
        y: mouseEventData.currentPoints.image.y,
        highlight: true,
        active: true
      },
      textBox: {
        active: false,
        hasMoved: false,
        movesIndependently: false,
        drawnIndependently: true,
        allowedOutsideImage: true,
        hasBoundingBox: true
      }
    }
  };

  return measurementData;
}
// /////// END ACTIVE TOOL ///////

function pointNearTool (element, data, coords) {
  if (data.visible === false) {
    return false;
  }

  return lineSegDistance(element, data.handles.start, data.handles.end, coords) < 25;
}

// /////// BEGIN IMAGE RENDERING ///////
function onImageRendered (e) {
  const eventData = e.detail;

  // If we have no toolData for this element, return immediately as there is nothing to do
  const toolData = getToolState(e.currentTarget, toolType);

  if (!toolData) {
    return;
  }

  const cornerstone = external.cornerstone;
  // We have tool data for this element - iterate over each one and draw it
  const context = eventData.canvasContext.canvas.getContext('2d');
  const { image, element } = eventData;

  context.setTransform(1, 0, 0, 1, 0, 0);

  const lineWidth = toolStyle.getToolWidth();
  const config = length.getConfiguration();
  const imagePlane = cornerstone.metaData.get('imagePlaneModule', image.imageId);
  let rowPixelSpacing;
  let colPixelSpacing;

  if (imagePlane) {
    rowPixelSpacing = imagePlane.rowPixelSpacing || imagePlane.rowImagePixelSpacing;
    colPixelSpacing = imagePlane.columnPixelSpacing || imagePlane.colImagePixelSpacing;
  } else {
    rowPixelSpacing = image.rowPixelSpacing;
    colPixelSpacing = image.columnPixelSpacing;
  }

  for (let i = 0; i < toolData.data.length; i++) {
    context.save();

    // Configurable shadow
    if (config && config.shadow) {
      context.shadowColor = config.shadowColor || '#000000';
      context.shadowOffsetX = config.shadowOffsetX || 1;
      context.shadowOffsetY = config.shadowOffsetY || 1;
    }

    const data = toolData.data[i];

    if (data.visible === false) {
      continue;
    }

    const color = toolColors.getColorIfActive(data);

    // Get the handle positions in canvas coordinates
    const handleStartCanvas = cornerstone.pixelToCanvas(element, data.handles.start);
    const handleEndCanvas = cornerstone.pixelToCanvas(element, data.handles.end);

    // Draw the measurement line
    context.beginPath();
    context.strokeStyle = color;
    context.lineWidth = lineWidth;
    context.moveTo(handleStartCanvas.x, handleStartCanvas.y);
    context.lineTo(handleEndCanvas.x, handleEndCanvas.y);
    context.stroke();

    // Draw the handles
    const handleOptions = {
      drawHandlesIfActive: (config && config.drawHandlesOnHover)
    };

    drawHandles(context, eventData, data.handles, color, handleOptions);

    // Draw the text
    context.fillStyle = color;

    // Set rowPixelSpacing and columnPixelSpacing to 1 if they are undefined (or zero)
    const dx = (data.handles.end.x - data.handles.start.x) * (colPixelSpacing || 1);
    const dy = (data.handles.end.y - data.handles.start.y) * (rowPixelSpacing || 1);

    // Calculate the length, and create the text variable with the millimeters or pixels suffix
    const length = Math.sqrt(dx * dx + dy * dy);

    // Store the length inside the tool for outside access
    data.length = length;

    if (!data.handles.textBox.hasMoved) {
      const coords = {
        x: Math.max(data.handles.start.x, data.handles.end.x)
      };

      // Depending on which handle has the largest x-value,
      // Set the y-value for the text box
      if (coords.x === data.handles.start.x) {
        coords.y = data.handles.start.y;
      } else {
        coords.y = data.handles.end.y;
      }

      data.handles.textBox.x = coords.x;
      data.handles.textBox.y = coords.y;
    }

    // Move the textbox slightly to the right and upwards
    // So that it sits beside the length tool handle
    const xOffset = 10;

    const text = textBoxText(data, rowPixelSpacing, colPixelSpacing);

    drawLinkedTextBox(context, element, data.handles.textBox, text,
      data.handles, textBoxAnchorPoints, color, lineWidth, xOffset, true);
    context.restore();
  }

  function textBoxText (data, rowPixelSpacing, colPixelSpacing) {
    // Set the length text suffix depending on whether or not pixelSpacing is available
    let suffix = ' mm';

    if (!rowPixelSpacing || !colPixelSpacing) {
      suffix = ' pixels';
    }

    return `${data.length.toFixed(2)}${suffix}`;
  }

  function textBoxAnchorPoints (handles) {
    const midpoint = {
      x: (handles.start.x + handles.end.x) / 2,
      y: (handles.start.y + handles.end.y) / 2
    };

    return [handles.start, midpoint, handles.end];
  }
}
// /////// END IMAGE RENDERING ///////

// Module exports
const length = mouseButtonTool({
  createNewMeasurement,
  onImageRendered,
  pointNearTool,
  toolType
});

const lengthTouch = touchTool({
  createNewMeasurement,
  onImageRendered,
  pointNearTool,
  toolType
});

export {
  length,
  lengthTouch
};
<|endoftext|>


<commit_before>var helpers = clientApp.helpers || {};

$.fn.video_gallery = function (result, index) {
  if (result.visible) {
    var visible = eval(result.visible);
    if (!visible) return;
  }

  var contentKeys = Object.keys(result.contents);

  if (result.label) $(this).appendLabel(result.label);
  var gallerySelector = 'gallery-' + index;
  $(this).append('

');
  $(this).appendVideoTools();

  var blobsArray = getGalleryVideos(result.contents, work_url);

  var leftItems = 'left-blobs-' + index;
  var rightItems = 'right-blobs-' + index;
  renderVideoGalleryBlobList(index, contentKeys, result, leftItems, 'left', blobsArray);

  var blobsContainerSelector = 'gallery-' + index + '-blobs-container';
  $('.' + gallerySelector).append('

');

  renderVideoGalleryBlobList(index, contentKeys, result, rightItems, 'right', blobsArray);
  $('.' + rightItems).addClass('gallery-item-list-right di-none');

  var videoContainerLeft = 'video-container-left-' + index;
  var videoContainerRight = 'video-container-right-' + index;
  $('#' + blobsContainerSelector).append('

');
  $('#' + blobsContainerSelector).append('

');

  for (let i = 0; i < blobsArray.length; i++) {
    $('#' + videoContainerRight).append('

');
    $('#' + videoContainerLeft).append('

');
    for (let j = 0; j < blobsArray[i].length; j++) {
      var leftClone = blobsArray[i][j].clone();
      var rightClone = blobsArray[i][j].clone();
      $('#video-container-right-' + index + ' > div:nth-child(' + (i+1) + ')').append($(rightClone));
      $('#video-container-left-' + index + ' > div:nth-child(' + (i+1) + ')').append($(leftClone));
    }
  }
  $('#video-container-right-' + index + ' > div:not(:first-child)').addClass('di-none');
  $('#video-container-left-' + index + ' > div:not(:first-child)').addClass('di-none');

  var allSrc = getAllSrc(blobsArray);
  $('.' + gallerySelector).setVideoGalleryMinHeight(allSrc);
  if (blobsArray.length > 1) $('.' + leftItems).appendVideoCompare(index, rightItems, videoContainerRight);
}

// Set gallery min-height to avoid jump loops.
$.fn.setVideoGalleryMinHeight = function (sources) {
  var minHeight;
  var selector = $(this);
  if (!Array.isArray(sources)) {
    sources = Object.keys(sources).map(function (e) {
      return sources[e];
    });
  }
  for (let i = 0; i < sources.length; i++) {
    let tmpVideo = document.createElement('video');
    tmpVideo.src = sources[i];
    $(tmpVideo).on("loadedmetadata", function () {
      minHeight = parseInt(selector.css('min-height'));
      var videoHeight = $(this)[0].videoHeight;
      if (minHeight < videoHeight) {
        minHeight = videoHeight < 580 ? videoHeight : 580;
        selector.css({ minHeight: minHeight + 20 + 'px' });
      }
    });
  }
};

function getGalleryVideos(contentArray, work_url) {
  var allSrc = [];
  var keys = Object.keys(contentArray);
  for (var i = 0; i < keys.length; i++) {
    var blobSetContent = contentArray[keys[i]];
    if (eval(blobSetContent.visible)) {
      var videoField = blobSetContent.video;
      var repeat = blobSetContent.repeat !== undefined ? checkRepeat(blobSetContent.repeat) : 1;
      var blobs = [];
      for (var idx = 0; idx < repeat; idx++) {
        blobs = [];
        if (typeof (videoField) === 'string') {
          var video = '<video src=' + work_url + (videoField.indexOf("'") == -1 ? videoField : eval(videoField)) + ' class=gallery-video draggable=false controls></video>';
          blobs.push($(video));
        } else if (typeof (videoField) === 'object') {
          for (var k = 0; k < videoField.length; k++) {
            var video = '<video src=' + work_url + (videoField[k].indexOf("'") == -1 ? videoField[k] : eval(videoField[k])) + ' class=gallery-video draggable=false controls></video>';
            blobs.push($(video));
          }
        }
        allSrc.push(blobs);
      }
    }
  }
  return allSrc;
}

function renderVideoGalleryBlobList(index, contentKeys, result, itemSelector, side, blobsArray) {
  $('.gallery-' + index).append('

');
  $('.' + itemSelector).append('

');
  var contents = result.contents;
  var firstVisibleBlob = true;
  var itemIndex = 0;
  for (let i = 0; i < contentKeys.length; i++) {
    if (eval(contents[contentKeys[i]].visible)) {
      if (firstVisibleBlob) {
        helpers.addToStorage('gallery-' + index + '-' + side, itemIndex);
        firstVisibleBlob = false;
      }
      var line = contents[contentKeys[i]];
      var repeat = line.repeat != undefined ? checkRepeat(line.repeat) : 1;
      for (var idx = 0; idx < repeat; idx++) {
        var text = getEvalText(contentKeys[i]);
        var spanId = 'gallery-' + index + '-item-' + side + '-' + i + '-' + idx;
        $('#gallery-' + index + '-blobList-' + side).append('' + eval(text) + '');
        $('#' + spanId).videoHover(index, side, itemIndex);
        itemIndex++;
      }
    }
  }
  $('#gallery-' + index + '-blobList-' + side).mouseOutVideo(index, side, blobsArray);
  $('.' + itemSelector + ' span:first-child').addClass('gallery-item-selected');
}

$.fn.videoHover = function (galleryIndex, side, id) {
  var videoSelector = '.gallery-' + galleryIndex + '-blob-' + side;
  var selector = '#video-container-' + side + '-' + galleryIndex;
  $(this).mouseover(function () {
    $(selector + ' > div').addClass('di-none');
    $(selector + ' > div:nth-child(' + (id+1) + ')').removeClass('di-none');
  });
  $(this).on('click', function () {
    $('#gallery-' + galleryIndex + '-blobList-' + side + ' > .gallery-item-selected').toggleClass('gallery-item-selected');
    $(this).toggleClass('gallery-item-selected');
    helpers.addToStorage('gallery-' + galleryIndex + '-' + side, id);
  });
}

$.fn.mouseOutVideo = function (galleryIndex, side, blobsArray) {
  var selector = '#video-container-' + side + '-' + galleryIndex;
  $(this).mouseout(function (event) {
    e = event.toElement || event.relatedTarget;
    if (e != null && (e.parentNode == this || e == this)) {
      return;
    }
    var selectedSrc = helpers.getFromStorage('gallery-' + galleryIndex + '-' + side);
    $(selector + ' > div').addClass('di-none');
    $(selector + ' > div:nth-child(' + (selectedSrc + 1) + ')').removeClass('di-none');
  });
}

$.fn.appendVideoCompare = function (galleryIndex, rightItems, videoContainerRight) {
  $(this).append('
<input type=checkbox id=compare-btn-gallery-' + galleryIndex + '>Compare
');
  $('#compare-btn-gallery-' + galleryIndex).on('click', function () {
    if ($(this).is(':checked')) {
      $('#video-container-left-' + galleryIndex).css({ 'flex-basis': '50%' });
      $('#video-container-right-' + galleryIndex).css({ 'flex-basis': '50%' });
      $('#gallery-' + galleryIndex + '-blobs-container').addClass('blobs-wrapper-compare');
    } else {
      $('#video-container-left-' + galleryIndex).css({ 'flex-basis': "" });
      $('#video-container-right-' + galleryIndex).css({ 'flex-basis': "" });
      $('#gallery-' + galleryIndex + '-blobs-container').removeClass('blobs-wrapper-compare');
    }
    $('#' + videoContainerRight).toggleClass('di-none');
    $('.gallery-' + galleryIndex).toggleClass('space-between');
    $('.' + rightItems).toggleClass('di-none');
  });
}

$.fn.appendVideoTools = function() {
  $('

')
  .appendTo($(this))
  .append('')
  .append('');

  var videoGallery = $(this);
  var playPauseBtn = $('.play-pause-btn', this);

  $('.play-pause-btn', this).click(function () {
    if($(this).hasClass('pause-to-play')) $('video', videoGallery).playVideos();
    else if ($(this).hasClass('play-to-pause')) $('video', videoGallery).pauseVideos();

    $(this).toggleClass('play-to-pause pause-to-play');
  });

  $('.stop-btn', this).click(function() {
    $('video', videoGallery).stopVideos();
    playPauseBtn.attr('class', 'play-pause-btn pause-to-play');
  });
}

$.fn.playVideos = function() {
  $(this).each(function() {
    $(this)[0].play();
  });
}

$.fn.pauseVideos = function() {
  $(this).each(function () {
    $(this)[0].pause();
  });
}

$.fn.stopVideos = function() {
  $(this).each(function () {
    $(this)[0].pause();
    $(this)[0].currentTime = 0;
  });
}
<commit_msg>[ClientApp/Video sound] Gallery videos muted by default except the ones on display<commit_after>var helpers = clientApp.helpers || {};

$.fn.video_gallery = function (result, index) {
  if (result.visible) {
    var visible = eval(result.visible);
    if (!visible) return;
  }

  var contentKeys = Object.keys(result.contents);

  if (result.label) $(this).appendLabel(result.label);
  var gallerySelector = 'gallery-' + index;
  $(this).append('

');
  $(this).appendVideoTools();

  var blobsArray = getGalleryVideos(result.contents, work_url);

  var leftItems = 'left-blobs-' + index;
  var rightItems = 'right-blobs-' + index;
  renderVideoGalleryBlobList(index, contentKeys, result, leftItems, 'left', blobsArray);

  var blobsContainerSelector = 'gallery-' + index + '-blobs-container';
  $('.' + gallerySelector).append('

');

  renderVideoGalleryBlobList(index, contentKeys, result, rightItems, 'right', blobsArray);
  $('.' + rightItems).addClass('gallery-item-list-right di-none');

  var videoContainerLeft = 'video-container-left-' + index;
  var videoContainerRight = 'video-container-right-' + index;
  $('#' + blobsContainerSelector).append('

');
  $('#' + blobsContainerSelector).append('

');

  for (let i = 0; i < blobsArray.length; i++) {
    $('#' + videoContainerLeft).append('

');
    $('#' + videoContainerRight).append('

');
    for (let j = 0; j < blobsArray[i].length; j++) {
      var leftClone = blobsArray[i][j].clone();
      var rightClone = blobsArray[i][j].clone();
      $('#' + videoContainerLeft + ' > div:nth-child(' + (i+1) + ')').append($(leftClone));
      $('#' + videoContainerRight + ' > div:nth-child(' + (i+1) + ')').append($(rightClone));
    }
  }
  $('#' + videoContainerLeft).initVideoProps();
  $('#' + videoContainerRight).initVideoProps();

  var allSrc = getAllSrc(blobsArray);
  $('.' + gallerySelector).setVideoGalleryMinHeight(allSrc);
  if (blobsArray.length > 1) $('.' + leftItems).appendVideoCompare(index, rightItems, videoContainerRight);
}

$.fn.initVideoProps = function () {
  $(' div:first-child > video', this).on('loadedmetadata', function() {
    $(this).prop('muted', false);
  });
  $(' > div:not(:first-child)', this).addClass('di-none');
}

// Set gallery min-height to avoid jump loops.
$.fn.setVideoGalleryMinHeight = function (sources) {
  var minHeight;
  var selector = $(this);
  if (!Array.isArray(sources)) {
    sources = Object.keys(sources).map(function (e) {
      return sources[e];
    });
  }
  for (let i = 0; i < sources.length; i++) {
    let tmpVideo = document.createElement('video');
    tmpVideo.src = sources[i];
    $(tmpVideo).on("loadedmetadata", function () {
      minHeight = parseInt(selector.css('min-height'));
      var videoHeight = $(this)[0].videoHeight;
      if (minHeight < videoHeight) {
        minHeight = videoHeight < 580 ? videoHeight : 580;
        selector.css({ minHeight: minHeight + 20 + 'px' });
      }
    });
  }
};

function getGalleryVideos(contentArray, work_url) {
  var allSrc = [];
  var keys = Object.keys(contentArray);
  for (var i = 0; i < keys.length; i++) {
    var blobSetContent = contentArray[keys[i]];
    var visibleField = blobSetContent.hasOwnProperty('visible');
    if (!visibleField || (visibleField && eval(blobSetContent.visible))) {
      var videoField = blobSetContent.video;
      var repeat = blobSetContent.repeat !== undefined ? checkRepeat(blobSetContent.repeat) : 1;
      var blobs = [];
      for (var idx = 0; idx < repeat; idx++) {
        blobs = [];
        if (typeof (videoField) === 'string') {
          var video = '<video src=' + work_url + (videoField.indexOf("'") == -1 ? videoField : eval(videoField)) + ' class=gallery-video draggable=false controls muted></video>';
          blobs.push($(video));
        } else if (typeof (videoField) === 'object') {
          for (var k = 0; k < videoField.length; k++) {
            var video = '<video src=' + work_url + (videoField[k].indexOf("'") == -1 ? videoField[k] : eval(videoField[k])) + ' class=gallery-video draggable=false controls muted></video>';
            blobs.push($(video));
          }
        }
        allSrc.push(blobs);
      }
    }
  }
  return allSrc;
}

function renderVideoGalleryBlobList(index, contentKeys, result, itemSelector, side, blobsArray) {
  $('.gallery-' + index).append('

');
  $('.' + itemSelector).append('

');
  var contents = result.contents;
  var firstVisibleBlob = true;
  var itemIndex = 0;
  for (let i = 0; i < contentKeys.length; i++) {
    var visibleField = contents[contentKeys[i]].hasOwnProperty('visible');
    if (!visibleField || (visibleField && eval(contents[contentKeys[i]].visible))) {
      if (firstVisibleBlob) {
        helpers.addToStorage('gallery-' + index + '-' + side, itemIndex);
        firstVisibleBlob = false;
      }
      var line = contents[contentKeys[i]];
      var repeat = line.repeat != undefined ? checkRepeat(line.repeat) : 1;
      for (var idx = 0; idx < repeat; idx++) {
        var text = getEvalText(contentKeys[i]);
        var spanId = 'gallery-' + index + '-item-' + side + '-' + i + '-' + idx;
        $('#gallery-' + index + '-blobList-' + side).append('' + eval(text) + '');
        $('#' + spanId).videoHover(index, side, itemIndex);
        itemIndex++;
      }
    }
  }
  $('#gallery-' + index + '-blobList-' + side).mouseOutVideo(index, side, blobsArray);
  $('.' + itemSelector + ' span:first-child').addClass('gallery-item-selected');
}

$.fn.videoHover = function (galleryIndex, side, id) {
  var videoSelector = '.gallery-' + galleryIndex + '-blob-' + side;
  var selector = '#video-container-' + side + '-' + galleryIndex;
  $(this).mouseover(function () {
    $(selector + ' > div').addClass('di-none');
    $(selector + ' video').prop('muted', true);
    $(selector + ' > div:nth-child(' + (id+1) + ')').removeClass('di-none');
    $(selector + ' > div:nth-child(' + (id + 1) + ') > video').prop('muted', false);
  });
  $(this).on('click', function () {
    $('#gallery-' + galleryIndex + '-blobList-' + side + ' > .gallery-item-selected').toggleClass('gallery-item-selected');
    $(this).toggleClass('gallery-item-selected');
    helpers.addToStorage('gallery-' + galleryIndex + '-' + side, id);
  });
}

$.fn.mouseOutVideo = function (galleryIndex, side, blobsArray) {
  var selector = '#video-container-' + side + '-' + galleryIndex;
  $(this).mouseout(function (event) {
    e = event.toElement || event.relatedTarget;
    if (e != null && (e.parentNode == this || e == this)) {
      return;
    }
    var selectedSrc = helpers.getFromStorage('gallery-' + galleryIndex + '-' + side);
    $(selector + ' > div').addClass('di-none');
    $(selector + ' video').prop('volume', 0);
    $(selector + ' > div:nth-child(' + (selectedSrc + 1) + ')').removeClass('di-none');
    $(selector + ' > div:nth-child(' + (selectedSrc + 1) + ') video').prop('volume', 1);
  });
}

$.fn.appendVideoCompare = function (galleryIndex, rightItems, videoContainerRight) {
  $(this).append('
<input type=checkbox id=compare-btn-gallery-' + galleryIndex + '>Compare
');
  $('#compare-btn-gallery-' + galleryIndex).on('click', function () {
    if ($(this).is(':checked')) {
      $('#video-container-left-' + galleryIndex).css({ 'flex-basis': '50%' });
      $('#video-container-right-' + galleryIndex).css({ 'flex-basis': '50%' });
      $('#gallery-' + galleryIndex + '-blobs-container').addClass('blobs-wrapper-compare');
    } else {
      $('#video-container-left-' + galleryIndex).css({ 'flex-basis': "" });
      $('#video-container-right-' + galleryIndex).css({ 'flex-basis': "" });
      $('#gallery-' + galleryIndex + '-blobs-container').removeClass('blobs-wrapper-compare');
    }
    $('#' + videoContainerRight).toggleClass('di-none');
    $('.gallery-' + galleryIndex).toggleClass('space-between');
    $('.' + rightItems).toggleClass('di-none');
  });
}

$.fn.appendVideoTools = function() {
  $('

')
  .appendTo($(this))
  .append('')
  .append('');

  var videoGallery = $(this);
  var playPauseBtn = $('.play-pause-btn', this);

  $('.play-pause-btn', this).click(function () {
    if($(this).hasClass('pause-to-play')) $('video', videoGallery).playVideos();
    else if ($(this).hasClass('play-to-pause')) $('video', videoGallery).pauseVideos();

    $(this).toggleClass('play-to-pause pause-to-play');
  });

  $('.stop-btn', this).click(function() {
    $('video', videoGallery).stopVideos();
    playPauseBtn.attr('class', 'play-pause-btn pause-to-play');
  });
}

$.fn.playVideos = function() {
  $(this).each(function() {
    $(this)[0].play();
  });
}

$.fn.pauseVideos = function() {
  $(this).each(function () {
    $(this)[0].pause();
  });
}

$.fn.stopVideos = function() {
  $(this).each(function () {
    $(this)[0].pause();
    $(this)[0].currentTime = 0;
  });
}
<|endoftext|>


<commit_before>/**************************
 * Author : Robert Hoffmann
 * License: MIT
 * Date   : 14/01/12
 * Version: 1.0
 **************************
 * CallBack Usage
 *
 * jQuery(selector).basicTicker(["Some text 1", "Some text 2", "Some text 3"], 2000, function(ele) {
 *      alert("All done");
 * });
 *
 **************************
 * EvenHandler Usage
 *
 * Instead of using the callBack as shown above,
 * you can also subscribe to the eventHandler
 *
 * jQuery(selector).bind("ticker:done", function(e){
 *     alert("All done");
 * });
 *
 **************************/
(function($, undefined) {
    $.fn.basicTicker = function(data, duration, callBack) {
        callBack = callBack || function(e) { };

        if (!$.isArray(data)) {
            return this;
        }

        var that = this;

        // replace fadeIn/Out with slideUp/Down, Show/Hide, etc ...
        function tick(data) {
            var item = data.splice(0, 1)[0];

            that
                .text(item)
                .fadeIn(duration)
                .fadeOut(duration, function() {
                    if (data.length > 0) {
                        tick(data, duration);
                    }
                    else {
                        callBack(that);
                        $(that).triggerHandler("ticker:done");
                    }
                });
        }

        tick(data);
        return that;
    };
})(jQuery);<commit_msg>Fixed empty data<commit_after>/**************************
 * Author : Robert Hoffmann
 * License: MIT
 * Date   : 14/01/12
 * Version: 1.0
 **************************
 * CallBack Usage
 *
 * jQuery(selector).basicTicker(["Some text 1", "Some text 2", "Some text 3"], 2000, function(ele) {
 *      alert("All done");
 * });
 *
 **************************
 * EvenHandler Usage
 *
 * Instead of using the callBack as shown above,
 * you can also subscribe to the eventHandler
 *
 * jQuery(selector).bind("ticker:done", function(e){
 *     alert("All done");
 * });
 *
 **************************/
(function($, undefined) {
    $.fn.basicTicker = function(data, duration, callBack) {
        callBack = callBack || function() {};

        if (!$.isArray(data) || data.length === 0) {
            return this;
        }

        var that = this;

        // replace fadeIn/Out with slideUp/Down, Show/Hide, etc ...
        function tick(items) {
            var item = items.splice(0, 1)[0];

            that
                .text(item)
                .fadeIn(duration)
                .fadeOut(duration, function() {
                    if (items.length > 0) {
                        tick(data, duration);
                    }
                    else {
                        callBack(that);
                        $(that).triggerHandler("ticker:done");
                    }
                });
        }

        tick(data);
        return that;
    };
})(jQuery);<|endoftext|>


<commit_before>var $ = require('jquery');
var LayerDefinitionModel = require('../../../../../javascripts/cartodb3/data/layer-definition-model');
var ConfigModel = require('../../../../../javascripts/cartodb3/data/config-model');
var EditorWidgetView = require('../../../../../javascripts/cartodb3/editor/widgets/widget-view');
var WidgetDefinitionModel = require('../../../../../javascripts/cartodb3/data/widget-definition-model');
var WidgetsService = require('../../../../../javascripts/cartodb3/editor/widgets/widgets-service');
var FactoryModals = require('../../factories/modals');

describe('editor/widgets/widget-view', function () {
  var model;
  var view;
  var layer;
  var stackLayoutModel;

  beforeEach(function () {
    jasmine.clock().install();

    var configModel = new ConfigModel({
      base_url: '/u/pepe'
    });
    model = new WidgetDefinitionModel({
      type: 'formula',
      title: 'AVG districts homes',
      column: 'areas',
      operation: 'avg',
      layer_id: 'l-1'
    }, {
      configModel: configModel,
      mapId: 'm-123'
    });

    layer = new LayerDefinitionModel({
      id: 'l-1',
      options: {
        type: 'CartoDB',
        color: 'red',
        name: 'layerrr'
      }
    }, {
      parse: true,
      configModel: configModel
    });

    stackLayoutModel = jasmine.createSpyObj('stackLayoutModel', ['nextStep']);

    spyOn(EditorWidgetView.prototype, '_renameWidget');

    view = new EditorWidgetView({
      modals: FactoryModals.createModalService(),
      userActions: {},
      model: model,
      layer: layer,
      stackLayoutModel: stackLayoutModel,
      querySchemaModel: {}
    });

    view.render();
  });

  afterEach(function () {
    jasmine.clock().uninstall();
    view.remove();
  });

  it('should have no leaks', function () {
    expect(view).toHaveNoLeaks();
  });

  it('should contain js-widgetItem class', function () {
    expect(view.$el.hasClass('js-widgetItem')).toBeTruthy();
  });

  it('should add a data attribute with the model cid', function () {
    expect(view.$el.data('model-cid')).toBe(model.cid);
  });

  it('should render correctly', function () {
    expect(view.$el.text()).toContain('AVG districts home');
    expect(view.$('.SelectorLayer-letter').length).toBe(1);
    expect(view.$('.js-toggle-menu').length).toBe(1);
    expect(view.$el.text()).toContain('layerrr');
  });

  it('should show context menu', function () {
    view.$('.js-toggle-menu').click();
    expect(view._contextMenuFactory.getContextMenu().$('[data-val="rename-widget"]').length).toBe(1);
    expect(view._contextMenuFactory.getContextMenu().$('[data-val="delete-widget"]').length).toBe(1);
    document.body.removeChild(view._contextMenuFactory.getContextMenu().el);
  });

  it('should rename', function () {
    var e = $.Event('keyup');
    e.which = 13;

    view.$('.js-toggle-menu').click();
    view._contextMenuFactory.getContextMenu().$('[data-val="rename-widget"]').click();
    view.$('.js-input').val('foo').trigger('keyup');
    view.$('.js-input').trigger(e);
    expect(EditorWidgetView.prototype._renameWidget).toHaveBeenCalled();
  });

  describe('when clicking on remove', function () {
    it('should remove widget with WidgetsService', function () {
      spyOn(WidgetsService, 'removeWidget');
      view.$('.js-toggle-menu').click();
      view._contextMenuFactory.getContextMenu().$('[data-val="delete-widget"]').click();
      expect(WidgetsService.removeWidget).toHaveBeenCalledWith(model);
    });
  });

  it('should edit widget with WidgetsService', function () {
    spyOn(WidgetsService, 'editWidget');
    view.$('.js-title').trigger('click');
    jasmine.clock().tick(201);
    expect(WidgetsService.editWidget).toHaveBeenCalledWith(model);
  });
});
<commit_msg>fix tests<commit_after>var $ = require('jquery');
var LayerDefinitionModel = require('../../../../../javascripts/cartodb3/data/layer-definition-model');
var ConfigModel = require('../../../../../javascripts/cartodb3/data/config-model');
var EditorWidgetView = require('../../../../../javascripts/cartodb3/editor/widgets/widget-view');
var WidgetDefinitionModel = require('../../../../../javascripts/cartodb3/data/widget-definition-model');
var WidgetsService = require('../../../../../javascripts/cartodb3/editor/widgets/widgets-service');
var FactoryModals = require('../../factories/modals');

describe('editor/widgets/widget-view', function () {
  var model;
  var view;
  var layer;
  var stackLayoutModel;

  beforeEach(function () {
    jasmine.clock().install();

    var configModel = new ConfigModel({
      base_url: '/u/pepe'
    });
    model = new WidgetDefinitionModel({
      type: 'formula',
      title: 'AVG districts homes',
      column: 'areas',
      operation: 'avg',
      layer_id: 'l-1'
    }, {
      configModel: configModel,
      mapId: 'm-123'
    });

    layer = new LayerDefinitionModel({
      id: 'l-1',
      options: {
        type: 'CartoDB',
        color: 'red',
        name: 'layerrr'
      }
    }, {
      parse: true,
      configModel: configModel
    });

    stackLayoutModel = jasmine.createSpyObj('stackLayoutModel', ['nextStep']);

    spyOn(EditorWidgetView.prototype, '_renameWidget');

    view = new EditorWidgetView({
      modals: FactoryModals.createModalService(),
      userActions: {},
      model: model,
      layer: layer,
      stackLayoutModel: stackLayoutModel,
      querySchemaModel: {}
    });

    view.render();
  });

  afterEach(function () {
    jasmine.clock().uninstall();
    view.remove();
  });

  it('should have no leaks', function () {
    expect(view).toHaveNoLeaks();
  });

  it('should contain js-widgetItem class', function () {
    expect(view.$el.hasClass('js-widgetItem')).toBeTruthy();
  });

  it('should add a data attribute with the model cid', function () {
    expect(view.$el.data('model-cid')).toBe(model.cid);
  });

  it('should render correctly', function () {
    expect(view.$el.text()).toContain('AVG districts home');
    expect(view.$('.CDB-SelectorLayer-letter').length).toBe(1);
    expect(view.$('.js-toggle-menu').length).toBe(1);
    expect(view.$el.text()).toContain('layerrr');
  });

  it('should show context menu', function () {
    view.$('.js-toggle-menu').click();
    expect(view._contextMenuFactory.getContextMenu().$('[data-val="rename-widget"]').length).toBe(1);
    expect(view._contextMenuFactory.getContextMenu().$('[data-val="delete-widget"]').length).toBe(1);
    document.body.removeChild(view._contextMenuFactory.getContextMenu().el);
  });

  it('should rename', function () {
    var e = $.Event('keyup');
    e.which = 13;

    view.$('.js-toggle-menu').click();
    view._contextMenuFactory.getContextMenu().$('[data-val="rename-widget"]').click();
    view.$('.js-input').val('foo').trigger('keyup');
    view.$('.js-input').trigger(e);
    expect(EditorWidgetView.prototype._renameWidget).toHaveBeenCalled();
  });

  describe('when clicking on remove', function () {
    it('should remove widget with WidgetsService', function () {
      spyOn(WidgetsService, 'removeWidget');
      view.$('.js-toggle-menu').click();
      view._contextMenuFactory.getContextMenu().$('[data-val="delete-widget"]').click();
      expect(WidgetsService.removeWidget).toHaveBeenCalledWith(model);
    });
  });

  it('should edit widget with WidgetsService', function () {
    spyOn(WidgetsService, 'editWidget');
    view.$('.js-title').trigger('click');
    jasmine.clock().tick(201);
    expect(WidgetsService.editWidget).toHaveBeenCalledWith(model);
  });
});
<|endoftext|>


<commit_before>/**
 * Shopware 5
 * Copyright (c) shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    Article
 * @subpackage Detail
 * @version    $Id$
 * @author shopware AG
 */

/**
 * Shopware UI - Article variants - Detail.
 * The detail component is an extension of the Enlight.app.Window. It displayed when the
 * user clicks the pencil action column in the variant listing to edit the selected
 * variant over the detail page.
 *
 * @link http://www.shopware.de/
 * @license http://www.shopware.de/license
 * @package Article
 * @subpackage Variants
 */
//{namespace name=backend/article/view/main}
//{block name="backend/article/view/variant/progress"}
Ext.define('Shopware.apps.Article.view.variant.Progress', {
    /**
     * Define that the order main window is an extension of the enlight application window
     * @string
     */
    extend:'Enlight.app.Window',
    /**
     * Set base css class prefix and module individual css class for css styling
     * @string
     */
    cls:Ext.baseCSSPrefix + 'article-variant-progress-window',
    /**
     * List of short aliases for class names. Most useful for defining xtypes for widgets.
     * @string
     */
    alias:'widget.article-variant-progress-window',
    /**
     * Set no border for the window
     * @boolean
     */
    border:false,
    /**
     * True to automatically show the component upon creation.
     * @boolean
     */
    autoShow:true,
    /**
     * Set border layout for the window
     * @string
     */
    layout:'anchor',
    /**
     * Define window width
     * @integer
     */
    width:420,
    /**
     * Define window height
     * @integer
     */
    height:255,
    /**
     * True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button and disallow maximizing the window.
     * @boolean
     */
    maximizable:false,

    /**
     * True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button and disallow minimizing the window.
     * @boolean
     */
    minimizable:false,

    footerButton: true,

    /**
     * A flag which causes the object to attempt to restore the state of internal properties from a saved state on startup.
     */
    stateful:true,

    modal: true,

    cancelProcess: false,
    inProcess: false,

    /**
     * Contains the batch size for each request of the generation.
     */
    batchSize: 50,

    /**
     * The unique id for this object to use for state management purposes.
     */
    stateId:'shopware-article-variant-progress-window',

    /**
     * Contains all snippets for the component
     * @object
     */
    snippets: {
        growlMessage: '{s name=growl_message}Article{/s}',
        title:'{s name=progress/title}Variant generation{/s}',
        process: '{s name=progress/message}[0] of [1] variants created...{/s}',
        errorMessage: '{s name=progress/error_message}An error has occurred while generate the article variants:{/s}',
        errorTitle: '{s name=progress/error_title}Error{/s}',
        generationType: '{s name=progress/generate_type}Merging{/s}',
        types: {
            overrideType: '{s name=progress/override_type}Override{/s}',
            mergeType: '{s name=progress/merge_type}Merge{/s}'
        },
        notice: '{s name=progress/notice}The current selection of groups and options will create [0] possible variants.

This process will take about [1] minutes depending on your system resources.
Do you want to continue?{/s}'
    },

    bodyPadding: 10,
    /**
     * The initComponent template method is an important initialization step for a Component.
     * It is intended to be implemented by each subclass of Ext.Component to provide any needed constructor logic.
     * The initComponent method of the class being created is called first,
     * with each initComponent method up the hierarchy to Ext.Component being called thereafter.
     * This makes it easy to implement and, if needed, override the constructor logic of the Component at any step in the hierarchy.
     * The initComponent method must contain a call to callParent in order to ensure that the parent class' initComponent method is also called.
     *
     * @return void
     */
    initComponent:function () {
        var me = this;
        me.items = me.createItems();
        me.title = me.snippets.title;
        me.callParent(arguments);
    },

    /**
     * Creates the items for the progress window.
     */
    createItems: function() {
        var me = this, defaultValue = 2;

        if (me.groupsChanged) {
            defaultValue = 1;
        }
        if (!Ext.isNumeric(me.batchSize)) {
            me.batchSize = 50;
        }

        me.progressField = Ext.create('Ext.form.field.Display', {
            value: Ext.String.format(me.snippets.process, 0, me.configurator.get('totalCount')),
            anchor: '100%',
            margin: '10 0',
            style: 'text-align: center;'
        });

        me.typeComboBox = Ext.create('Ext.form.field.ComboBox', {
            name: 'type',
            queryMode: 'local',
            margin: '0 0 10',
            anchor: '100%',
            valueField: 'id',
            labelWidth: 120,
            editable: false,
            disabled: me.groupsChanged,
            fieldLabel: me.snippets.generationType,
            displayField: 'name',
            value: defaultValue,
            store: new Ext.data.SimpleStore({
                fields:['id', 'name'],
                data: [
                    [1, me.snippets.types.overrideType],
                    [2, me.snippets.types.mergeType]
                ]
            })
        });

        me.cancelButton = Ext.create('Ext.button.Button', {
            text: 'Cancel',
            anchor: '50%',
            cls: 'secondary',
            margin: '0 10 0 0',
            handler: function() {
                me.cancelProcess = true;
                me.startButton.setDisabled(false);
                if (me.inProcess) {
                    me.inProcess = false;
                    me.fireEvent('variantsGenerated', me.article, me);
                } else {
                    me.destroy();
                }
            }
        });

        me.startButton = Ext.create('Ext.button.Button', {
            text: 'Start',
            anchor: '50%',
            cls: 'primary',
            handler: function() {
                me.inProcess = true;
                if (!Ext.isNumeric(me.batchSize)) {
                    me.batchSize = 50;
                }
                me.startButton.setDisabled(true);
                me.startVariantGenerator(me.configurator, 0, me.batchSize, me.article);
            }
        });

        var totalTime = me.configurator.get('totalCount') / me.batchSize * 1.5 / 60;
        totalTime = Ext.Number.toFixed(totalTime, 0);

        var notice = Ext.create('Ext.container.Container', {
            html: Ext.String.format(me.snippets.notice, me.configurator.get('totalCount'), totalTime),
            style: 'color: #999; font-style: italic; margin: 0 0 15px 0; text-align: center;',
            anchor: '100%'
        });

        return [ me.typeComboBox, notice, me.progressField, me.cancelButton, me.startButton ];
    },

    /**
     * Internal helper function which used for a queue process in the variant   generation.
     * The function uses the passed model with an offset and limit to create in each queue
     * run for example 50 variants.
     * @param model
     * @param offset
     * @param limit
     * @param article
     */
    startVariantGenerator: function(model, offset, limit, article) {
        var me = this;

        model.set('offset', offset);
        model.set('limit', limit);
        model.set('mergeType', me.typeComboBox.getValue());
        model.setDirty();
        model.save({
            success: function(record, operation) {
                var doneVariants = Ext.Array.min([offset + limit, model.get('totalCount')]);
                var progress = doneVariants / model.get('totalCount');
                progress = Ext.Number.toFixed(progress, 2);

                me.progressField.setValue(Ext.String.format(me.snippets.process, doneVariants, model.get('totalCount')));

                //if the last variant was created we can hide the window and reload the listing
                if (offset + limit >= model.get('totalCount') || me.cancelProcess) {
                    me.inProcess = false;
                    me.startButton.setDisabled(false);
                    me.fireEvent('variantsGenerated', article, me);
                } else {
                    //otherwise we have to call this function recursive with the next offset
                    offset = offset + limit;
                    me.startVariantGenerator(model, offset, limit, article);
                }
            },
            failure: function(record, operation) {
                var rawData = record.getProxy().getReader().rawData,
                    message = '
' + rawData.message;

                me.inProcess = false;
                Shopware.Notification.createGrowlMessage(me.snippets.errorTitle, me.snippets.errorMessage + message, me.snippets.growlMessage);
            }
        });

    }
});
//{/block}
<commit_msg>SW-19364 - Fix missing snippet usage<commit_after>/**
 * Shopware 5
 * Copyright (c) shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    Article
 * @subpackage Detail
 * @version    $Id$
 * @author shopware AG
 */

/**
 * Shopware UI - Article variants - Detail.
 * The detail component is an extension of the Enlight.app.Window. It displayed when the
 * user clicks the pencil action column in the variant listing to edit the selected
 * variant over the detail page.
 *
 * @link http://www.shopware.de/
 * @license http://www.shopware.de/license
 * @package Article
 * @subpackage Variants
 */
//{namespace name=backend/article/view/main}
//{block name="backend/article/view/variant/progress"}
Ext.define('Shopware.apps.Article.view.variant.Progress', {
    /**
     * Define that the order main window is an extension of the enlight application window
     * @string
     */
    extend:'Enlight.app.Window',
    /**
     * Set base css class prefix and module individual css class for css styling
     * @string
     */
    cls:Ext.baseCSSPrefix + 'article-variant-progress-window',
    /**
     * List of short aliases for class names. Most useful for defining xtypes for widgets.
     * @string
     */
    alias:'widget.article-variant-progress-window',
    /**
     * Set no border for the window
     * @boolean
     */
    border:false,
    /**
     * True to automatically show the component upon creation.
     * @boolean
     */
    autoShow:true,
    /**
     * Set border layout for the window
     * @string
     */
    layout:'anchor',
    /**
     * Define window width
     * @integer
     */
    width:420,
    /**
     * Define window height
     * @integer
     */
    height:255,
    /**
     * True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button and disallow maximizing the window.
     * @boolean
     */
    maximizable:false,

    /**
     * True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button and disallow minimizing the window.
     * @boolean
     */
    minimizable:false,

    footerButton: true,

    /**
     * A flag which causes the object to attempt to restore the state of internal properties from a saved state on startup.
     */
    stateful:true,

    modal: true,

    cancelProcess: false,
    inProcess: false,

    /**
     * Contains the batch size for each request of the generation.
     */
    batchSize: 50,

    /**
     * The unique id for this object to use for state management purposes.
     */
    stateId:'shopware-article-variant-progress-window',

    /**
     * Contains all snippets for the component
     * @object
     */
    snippets: {
        growlMessage: '{s name=growl_message}Article{/s}',
        title:'{s name=progress/title}Variant generation{/s}',
        process: '{s name=progress/message}[0] of [1] variants created...{/s}',
        errorMessage: '{s name=progress/error_message}An error has occurred while generate the article variants:{/s}',
        errorTitle: '{s name=progress/error_title}Error{/s}',
        generationType: '{s name=progress/generate_type}Merging{/s}',
        types: {
            overrideType: '{s name=progress/override_type}Override{/s}',
            mergeType: '{s name=progress/merge_type}Merge{/s}'
        },
        notice: '{s name=progress/notice}The current selection of groups and options will create [0] possible variants.

This process will take about [1] minutes depending on your system resources.
Do you want to continue?{/s}'
    },

    bodyPadding: 10,
    /**
     * The initComponent template method is an important initialization step for a Component.
     * It is intended to be implemented by each subclass of Ext.Component to provide any needed constructor logic.
     * The initComponent method of the class being created is called first,
     * with each initComponent method up the hierarchy to Ext.Component being called thereafter.
     * This makes it easy to implement and, if needed, override the constructor logic of the Component at any step in the hierarchy.
     * The initComponent method must contain a call to callParent in order to ensure that the parent class' initComponent method is also called.
     *
     * @return void
     */
    initComponent:function () {
        var me = this;
        me.items = me.createItems();
        me.title = me.snippets.title;
        me.callParent(arguments);
    },

    /**
     * Creates the items for the progress window.
     */
    createItems: function() {
        var me = this, defaultValue = 2;

        if (me.groupsChanged) {
            defaultValue = 1;
        }
        if (!Ext.isNumeric(me.batchSize)) {
            me.batchSize = 50;
        }

        me.progressField = Ext.create('Ext.form.field.Display', {
            value: Ext.String.format(me.snippets.process, 0, me.configurator.get('totalCount')),
            anchor: '100%',
            margin: '10 0',
            style: 'text-align: center;'
        });

        me.typeComboBox = Ext.create('Ext.form.field.ComboBox', {
            name: 'type',
            queryMode: 'local',
            margin: '0 0 10',
            anchor: '100%',
            valueField: 'id',
            labelWidth: 120,
            editable: false,
            disabled: me.groupsChanged,
            fieldLabel: me.snippets.generationType,
            displayField: 'name',
            value: defaultValue,
            store: new Ext.data.SimpleStore({
                fields:['id', 'name'],
                data: [
                    [1, me.snippets.types.overrideType],
                    [2, me.snippets.types.mergeType]
                ]
            })
        });

        me.cancelButton = Ext.create('Ext.button.Button', {
            text: '{s name=progress/cancel}{/s}',
            anchor: '50%',
            cls: 'secondary',
            margin: '0 10 0 0',
            handler: function() {
                me.cancelProcess = true;
                me.startButton.setDisabled(false);
                if (me.inProcess) {
                    me.inProcess = false;
                    me.fireEvent('variantsGenerated', me.article, me);
                } else {
                    me.destroy();
                }
            }
        });

        me.startButton = Ext.create('Ext.button.Button', {
            text: '{s name=progress/start}{/s}',
            anchor: '50%',
            cls: 'primary',
            handler: function() {
                me.inProcess = true;
                if (!Ext.isNumeric(me.batchSize)) {
                    me.batchSize = 50;
                }
                me.startButton.setDisabled(true);
                me.startVariantGenerator(me.configurator, 0, me.batchSize, me.article);
            }
        });

        var totalTime = me.configurator.get('totalCount') / me.batchSize * 1.5 / 60;
        totalTime = Ext.Number.toFixed(totalTime, 0);

        var notice = Ext.create('Ext.container.Container', {
            html: Ext.String.format(me.snippets.notice, me.configurator.get('totalCount'), totalTime),
            style: 'color: #999; font-style: italic; margin: 0 0 15px 0; text-align: center;',
            anchor: '100%'
        });

        return [ me.typeComboBox, notice, me.progressField, me.cancelButton, me.startButton ];
    },

    /**
     * Internal helper function which used for a queue process in the variant   generation.
     * The function uses the passed model with an offset and limit to create in each queue
     * run for example 50 variants.
     * @param model
     * @param offset
     * @param limit
     * @param article
     */
    startVariantGenerator: function(model, offset, limit, article) {
        var me = this;

        model.set('offset', offset);
        model.set('limit', limit);
        model.set('mergeType', me.typeComboBox.getValue());
        model.setDirty();
        model.save({
            success: function(record, operation) {
                var doneVariants = Ext.Array.min([offset + limit, model.get('totalCount')]);
                var progress = doneVariants / model.get('totalCount');
                progress = Ext.Number.toFixed(progress, 2);

                me.progressField.setValue(Ext.String.format(me.snippets.process, doneVariants, model.get('totalCount')));

                //if the last variant was created we can hide the window and reload the listing
                if (offset + limit >= model.get('totalCount') || me.cancelProcess) {
                    me.inProcess = false;
                    me.startButton.setDisabled(false);
                    me.fireEvent('variantsGenerated', article, me);
                } else {
                    //otherwise we have to call this function recursive with the next offset
                    offset = offset + limit;
                    me.startVariantGenerator(model, offset, limit, article);
                }
            },
            failure: function(record, operation) {
                var rawData = record.getProxy().getReader().rawData,
                    message = '
' + rawData.message;

                me.inProcess = false;
                Shopware.Notification.createGrowlMessage(me.snippets.errorTitle, me.snippets.errorMessage + message, me.snippets.growlMessage);
            }
        });

    }
});
//{/block}
<|endoftext|>


<commit_before>import { FetchRequest } from '../api/requests';
import {
  FetchActiveTasksForRequest,
  FetchTaskHistoryForRequest,
  FetchDeploysForRequest,
  FetchRequestHistory,
} from '../api/history';
import { FetchTaskCleanups, FetchScheduledTasksForRequest } from '../api/tasks';
import { FetchRequestUtilization } from '../api/utilization';

export const refresh = (requestId, location) => (dispatch, getState) => {
  const requiredPromises = Promise.all([
    dispatch(FetchRequest.trigger(requestId)),
    dispatch(FetchRequestHistory.trigger(requestId, 5, 1))
  ])

  dispatch(FetchActiveTasksForRequest.trigger(requestId));
  dispatch(FetchTaskCleanups.trigger());

  const { taskHistoryPage, taskHistoryCount } = location.query;
  if (taskHistoryPage == null || taskHistoryPage == 1) {
  console.log(taskHistoryPage)
    dispatch(FetchTaskHistoryForRequest.trigger(requestId, taskHistoryCount == null ? 10 : taskHistoryCount, taskHistoryPage == null ? 1 : taskHistoryPage));
  }

  dispatch(FetchDeploysForRequest.trigger(requestId, 5, 1));
  dispatch(FetchScheduledTasksForRequest.trigger(requestId));
  dispatch(FetchRequestUtilization.trigger(requestId, [404]))

  return requiredPromises;
}<commit_msg>remove console log<commit_after>import { FetchRequest } from '../api/requests';
import {
  FetchActiveTasksForRequest,
  FetchTaskHistoryForRequest,
  FetchDeploysForRequest,
  FetchRequestHistory,
} from '../api/history';
import { FetchTaskCleanups, FetchScheduledTasksForRequest } from '../api/tasks';
import { FetchRequestUtilization } from '../api/utilization';

export const refresh = (requestId, location) => (dispatch, getState) => {
  const requiredPromises = Promise.all([
    dispatch(FetchRequest.trigger(requestId)),
    dispatch(FetchRequestHistory.trigger(requestId, 5, 1))
  ])

  dispatch(FetchActiveTasksForRequest.trigger(requestId));
  dispatch(FetchTaskCleanups.trigger());

  const { taskHistoryPage, taskHistoryCount } = location.query;
  if (taskHistoryPage == null || taskHistoryPage == 1) {
    dispatch(FetchTaskHistoryForRequest.trigger(requestId, taskHistoryCount == null ? 10 : taskHistoryCount, taskHistoryPage == null ? 1 : taskHistoryPage));
  }

  dispatch(FetchDeploysForRequest.trigger(requestId, 5, 1));
  dispatch(FetchScheduledTasksForRequest.trigger(requestId));
  dispatch(FetchRequestUtilization.trigger(requestId, [404]))

  return requiredPromises;
}<|endoftext|>