<commit_before>define(
  'ephox.snooker.api.TableOperations',

  [
    'ephox.compass.Arr',
    'ephox.peanut.Fun',
    'ephox.perhaps.Option',
    'ephox.scullion.Struct',
    'ephox.snooker.api.Generators',
    'ephox.snooker.api.Structs',
    'ephox.snooker.api.TableContent',
    'ephox.snooker.api.TableLookup',
    'ephox.snooker.model.DetailsList',
    'ephox.snooker.model.RunOperation',
    'ephox.snooker.model.TableMerge',
    'ephox.snooker.model.Transitions',
    'ephox.snooker.model.Warehouse',
    'ephox.snooker.operate.MergingOperations',
    'ephox.snooker.operate.ModificationOperations',
    'ephox.snooker.operate.TransformOperations',
    'ephox.snooker.resize.Adjustments',
    'ephox.sugar.api.Remove',
    'global!parseInt'
  ],

  function (Arr, Fun, Option, Struct, Generators, Structs, TableContent, TableLookup, DetailsList, RunOperation, TableMerge, Transitions, Warehouse, MergingOperations, ModificationOperations, TransformOperations, Adjustments, Remove, parseInt) {
    var prune = function (table) {
      var cells = TableLookup.cells(table);
      if (cells.length === 0) Remove.remove(table);
    };

    var outcome = Struct.immutable('grid', 'cursor');

    var elementFromGrid = function (grid, row, column) {
      return findIn(grid, row, column).orThunk(function () {
        return findIn(grid, 0, 0);
      });
    };

    var findIn = function (grid, row, column) {
      return Option.from(grid[row]).bind(function (r) {
        return Option.from(r[column]);
      });
    };

    var bundle = function (grid, row, column) {
      return outcome(grid, findIn(grid, row, column));
    };

    var insertRowBefore = function (grid, detail, comparator, genWrappers) {
      var example = detail.row();
      var targetIndex = detail.row();
      var newGrid = ModificationOperations.insertRowAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
      return bundle(newGrid, targetIndex, detail.column());
    };

    var insertRowAfter = function (grid, detail, comparator, genWrappers) {
      var example = detail.row();
      var targetIndex = detail.row() + detail.rowspan();
      var newGrid = ModificationOperations.insertRowAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
      return bundle(newGrid, targetIndex, detail.column());
    };

    var insertColumnAfter = function (grid, detail, comparator, genWrappers) {
      var example = detail.column();
      var targetIndex = detail.column() + detail.colspan();
      var newGrid = ModificationOperations.insertColumnAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
      return bundle(newGrid, detail.row(), targetIndex);
    };

    var insertColumnBefore = function (grid, detail, comparator, genWrappers) {
      var example = detail.column();
      var targetIndex = detail.column();
      var newGrid = ModificationOperations.insertColumnAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
      return bundle(newGrid, detail.row(), targetIndex);
    };

    var makeRowHeader = function (grid, detail, comparator, genWrappers) {
      var newGrid = TransformOperations.replaceRow(grid, detail.row(), comparator, genWrappers.replaceOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var makeColumnHeader = function (grid, detail, comparator, genWrappers) {
      var newGrid = TransformOperations.replaceColumn(grid, detail.column(), comparator, genWrappers.replaceOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var unmakeRowHeader = function (grid, detail, comparator, genWrappers) {
      var newGrid =  TransformOperations.replaceRow(grid, detail.row(), comparator, genWrappers.replaceOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var unmakeColumnHeader = function (grid, detail, comparator, genWrappers) {
      var newGrid = TransformOperations.replaceColumn(grid, detail.column(), comparator, genWrappers.replaceOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var splitCellIntoColumns = function (grid, detail, comparator, genWrappers) {
      var newGrid = ModificationOperations.splitCellIntoColumns(grid, detail.row(), detail.column(), comparator, genWrappers.getOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var eraseColumn = function (grid, detail, comparator, _genWrappers) {
      var newGrid = ModificationOperations.deleteColumnAt(grid, detail.column());
      var cursor = elementFromGrid(newGrid, detail.row(), detail.column());
      return outcome(newGrid, cursor);
    };

    var eraseRow = function (grid, detail, comparator, _genWrappers) {
      var newGrid = ModificationOperations.deleteRowAt(grid, detail.row());
      var cursor = elementFromGrid(newGrid, detail.row(), detail.column());
      return outcome(newGrid, cursor);
    };

    var mergeCells = function (grid, mergable, comparator, _genWrappers) {
      var cells = mergable.cells();
      TableContent.merge(cells);
      var newGrid = MergingOperations.merge(grid, mergable.bounds(), comparator, Fun.constant(cells[0]));
      return outcome(newGrid, Option.from(cells[0]));
    };

    var unmergeCells = function (grid, unmergable, comparator, genWrappers) {
      var newGrid = Arr.foldr(unmergable, function (b, cell) {
        return MergingOperations.unmerge(b, cell, comparator, genWrappers.combine(cell));
      }, grid);
      return outcome(newGrid, Option.from(unmergable[0]));
    };

    var pasteCells = function (grid, pasteDetails, comparator, genWrappers) {
      var gridify = function (table, generators) {
        var list = DetailsList.fromTable(table);
        var wh = Warehouse.generate(list);
        return Transitions.toGrid(wh, generators);
      };
      var gridB = gridify(pasteDetails.clipboard(), pasteDetails.generators());
      var startAddress = Structs.address(pasteDetails.row(), pasteDetails.column());
      var mergedGrid = TableMerge.merge(startAddress, grid, gridB, pasteDetails.generators(), comparator);
      return mergedGrid.fold(function () {
        return outcome(grid, Option.some(pasteDetails.element()));
      }, function (nuGrid) {
        var cursor = elementFromGrid(nuGrid, pasteDetails.row(), pasteDetails.column());
        return outcome(nuGrid, cursor);
      });
    };

    // Only column modifications force a resizing. Everything else just tries to preserve the table as is.
    var resize = Adjustments.adjustWidthTo;

    return {
      insertRowBefore: RunOperation.run(insertRowBefore, RunOperation.onCell, Fun.noop, Fun.noop, Generators.modification),
      insertRowAfter:  RunOperation.run(insertRowAfter, RunOperation.onCell, Fun.noop, Fun.noop, Generators.modification),
      insertColumnBefore:  RunOperation.run(insertColumnBefore, RunOperation.onCell, resize, Fun.noop, Generators.modification),
      insertColumnAfter:  RunOperation.run(insertColumnAfter, RunOperation.onCell, resize, Fun.noop, Generators.modification),
      splitCellIntoColumns:  RunOperation.run(splitCellIntoColumns, RunOperation.onCell, resize, Fun.noop, Generators.modification),
      eraseColumn:  RunOperation.run(eraseColumn, RunOperation.onCell, resize, prune, Generators.modification),
      eraseRow:  RunOperation.run(eraseRow, RunOperation.onCell, Fun.noop, prune, Generators.modification),
      makeColumnHeader:  RunOperation.run(makeColumnHeader, RunOperation.onCell, Fun.noop, Fun.noop, Generators.transform('row', 'th')),
      unmakeColumnHeader:  RunOperation.run(unmakeColumnHeader, RunOperation.onCell, Fun.noop, Fun.noop, Generators.transform(null, 'td')),
      makeRowHeader:  RunOperation.run(makeRowHeader, RunOperation.onCell, Fun.noop, Fun.noop, Generators.transform('col', 'th')),
      unmakeRowHeader:  RunOperation.run(unmakeRowHeader, RunOperation.onCell, Fun.noop, Fun.noop, Generators.transform(null, 'td')),
      mergeCells: RunOperation.run(mergeCells, RunOperation.onMergable, Fun.noop, Fun.noop, Generators.merging),
      unmergeCells: RunOperation.run(unmergeCells, RunOperation.onUnmergable, resize, Fun.noop, Generators.merging),
      pasteCells: RunOperation.run(pasteCells, RunOperation.onPaste, resize, Fun.noop, Generators.modification)
    };
  }
);
<commit_msg>TBIO-4190: wire api up to split cell into rows<commit_after>define(
  'ephox.snooker.api.TableOperations',

  [
    'ephox.compass.Arr',
    'ephox.peanut.Fun',
    'ephox.perhaps.Option',
    'ephox.scullion.Struct',
    'ephox.snooker.api.Generators',
    'ephox.snooker.api.Structs',
    'ephox.snooker.api.TableContent',
    'ephox.snooker.api.TableLookup',
    'ephox.snooker.model.DetailsList',
    'ephox.snooker.model.RunOperation',
    'ephox.snooker.model.TableMerge',
    'ephox.snooker.model.Transitions',
    'ephox.snooker.model.Warehouse',
    'ephox.snooker.operate.MergingOperations',
    'ephox.snooker.operate.ModificationOperations',
    'ephox.snooker.operate.TransformOperations',
    'ephox.snooker.resize.Adjustments',
    'ephox.sugar.api.Remove',
    'global!parseInt'
  ],

  function (Arr, Fun, Option, Struct, Generators, Structs, TableContent, TableLookup, DetailsList, RunOperation, TableMerge, Transitions, Warehouse, MergingOperations, ModificationOperations, TransformOperations, Adjustments, Remove, parseInt) {
    var prune = function (table) {
      var cells = TableLookup.cells(table);
      if (cells.length === 0) Remove.remove(table);
    };

    var outcome = Struct.immutable('grid', 'cursor');

    var elementFromGrid = function (grid, row, column) {
      return findIn(grid, row, column).orThunk(function () {
        return findIn(grid, 0, 0);
      });
    };

    var findIn = function (grid, row, column) {
      return Option.from(grid[row]).bind(function (r) {
        return Option.from(r[column]);
      });
    };

    var bundle = function (grid, row, column) {
      return outcome(grid, findIn(grid, row, column));
    };

    var insertRowBefore = function (grid, detail, comparator, genWrappers) {
      var example = detail.row();
      var targetIndex = detail.row();
      var newGrid = ModificationOperations.insertRowAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
      return bundle(newGrid, targetIndex, detail.column());
    };

    var insertRowAfter = function (grid, detail, comparator, genWrappers) {
      var example = detail.row();
      var targetIndex = detail.row() + detail.rowspan();
      var newGrid = ModificationOperations.insertRowAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
      return bundle(newGrid, targetIndex, detail.column());
    };

    var insertColumnAfter = function (grid, detail, comparator, genWrappers) {
      var example = detail.column();
      var targetIndex = detail.column() + detail.colspan();
      var newGrid = ModificationOperations.insertColumnAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
      return bundle(newGrid, detail.row(), targetIndex);
    };

    var insertColumnBefore = function (grid, detail, comparator, genWrappers) {
      var example = detail.column();
      var targetIndex = detail.column();
      var newGrid = ModificationOperations.insertColumnAt(grid, targetIndex, example, comparator, genWrappers.getOrInit);
      return bundle(newGrid, detail.row(), targetIndex);
    };

    var makeRowHeader = function (grid, detail, comparator, genWrappers) {
      var newGrid = TransformOperations.replaceRow(grid, detail.row(), comparator, genWrappers.replaceOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var makeColumnHeader = function (grid, detail, comparator, genWrappers) {
      var newGrid = TransformOperations.replaceColumn(grid, detail.column(), comparator, genWrappers.replaceOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var unmakeRowHeader = function (grid, detail, comparator, genWrappers) {
      var newGrid =  TransformOperations.replaceRow(grid, detail.row(), comparator, genWrappers.replaceOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var unmakeColumnHeader = function (grid, detail, comparator, genWrappers) {
      var newGrid = TransformOperations.replaceColumn(grid, detail.column(), comparator, genWrappers.replaceOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var splitCellIntoColumns = function (grid, detail, comparator, genWrappers) {
      var newGrid = ModificationOperations.splitCellIntoColumns(grid, detail.row(), detail.column(), comparator, genWrappers.getOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var splitCellIntoRows = function (grid, detail, comparator, genWrappers) {
      var newGrid = ModificationOperations.splitCellIntoRows(grid, detail.row(), detail.column(), comparator, genWrappers.getOrInit);
      return bundle(newGrid, detail.row(), detail.column());
    };

    var eraseColumn = function (grid, detail, comparator, _genWrappers) {
      var newGrid = ModificationOperations.deleteColumnAt(grid, detail.column());
      var cursor = elementFromGrid(newGrid, detail.row(), detail.column());
      return outcome(newGrid, cursor);
    };

    var eraseRow = function (grid, detail, comparator, _genWrappers) {
      var newGrid = ModificationOperations.deleteRowAt(grid, detail.row());
      var cursor = elementFromGrid(newGrid, detail.row(), detail.column());
      return outcome(newGrid, cursor);
    };

    var mergeCells = function (grid, mergable, comparator, _genWrappers) {
      var cells = mergable.cells();
      TableContent.merge(cells);
      var newGrid = MergingOperations.merge(grid, mergable.bounds(), comparator, Fun.constant(cells[0]));
      return outcome(newGrid, Option.from(cells[0]));
    };

    var unmergeCells = function (grid, unmergable, comparator, genWrappers) {
      var newGrid = Arr.foldr(unmergable, function (b, cell) {
        return MergingOperations.unmerge(b, cell, comparator, genWrappers.combine(cell));
      }, grid);
      return outcome(newGrid, Option.from(unmergable[0]));
    };

    var pasteCells = function (grid, pasteDetails, comparator, genWrappers) {
      var gridify = function (table, generators) {
        var list = DetailsList.fromTable(table);
        var wh = Warehouse.generate(list);
        return Transitions.toGrid(wh, generators);
      };
      var gridB = gridify(pasteDetails.clipboard(), pasteDetails.generators());
      var startAddress = Structs.address(pasteDetails.row(), pasteDetails.column());
      var mergedGrid = TableMerge.merge(startAddress, grid, gridB, pasteDetails.generators(), comparator);
      return mergedGrid.fold(function () {
        return outcome(grid, Option.some(pasteDetails.element()));
      }, function (nuGrid) {
        var cursor = elementFromGrid(nuGrid, pasteDetails.row(), pasteDetails.column());
        return outcome(nuGrid, cursor);
      });
    };

    // Only column modifications force a resizing. Everything else just tries to preserve the table as is.
    var resize = Adjustments.adjustWidthTo;

    return {
      insertRowBefore: RunOperation.run(insertRowBefore, RunOperation.onCell, Fun.noop, Fun.noop, Generators.modification),
      insertRowAfter:  RunOperation.run(insertRowAfter, RunOperation.onCell, Fun.noop, Fun.noop, Generators.modification),
      insertColumnBefore:  RunOperation.run(insertColumnBefore, RunOperation.onCell, resize, Fun.noop, Generators.modification),
      insertColumnAfter:  RunOperation.run(insertColumnAfter, RunOperation.onCell, resize, Fun.noop, Generators.modification),
      splitCellIntoColumns:  RunOperation.run(splitCellIntoColumns, RunOperation.onCell, resize, Fun.noop, Generators.modification),
      splitCellIntoRows:  RunOperation.run(splitCellIntoRows, RunOperation.onCell, Fun.noop, Fun.noop, Generators.modification),
      eraseColumn:  RunOperation.run(eraseColumn, RunOperation.onCell, resize, prune, Generators.modification),
      eraseRow:  RunOperation.run(eraseRow, RunOperation.onCell, Fun.noop, prune, Generators.modification),
      makeColumnHeader:  RunOperation.run(makeColumnHeader, RunOperation.onCell, Fun.noop, Fun.noop, Generators.transform('row', 'th')),
      unmakeColumnHeader:  RunOperation.run(unmakeColumnHeader, RunOperation.onCell, Fun.noop, Fun.noop, Generators.transform(null, 'td')),
      makeRowHeader:  RunOperation.run(makeRowHeader, RunOperation.onCell, Fun.noop, Fun.noop, Generators.transform('col', 'th')),
      unmakeRowHeader:  RunOperation.run(unmakeRowHeader, RunOperation.onCell, Fun.noop, Fun.noop, Generators.transform(null, 'td')),
      mergeCells: RunOperation.run(mergeCells, RunOperation.onMergable, Fun.noop, Fun.noop, Generators.merging),
      unmergeCells: RunOperation.run(unmergeCells, RunOperation.onUnmergable, resize, Fun.noop, Generators.merging),
      pasteCells: RunOperation.run(pasteCells, RunOperation.onPaste, resize, Fun.noop, Generators.modification)
    };
  }
);
<|endoftext|>


<commit_before>import React from 'react';
import {shallow, mount} from 'enzyme';
import {Provider} from 'react-redux';
import TransitionGroup from 'react/lib/ReactCSSTransitionGroup';
import ConnectNotifications, {Notifications} from '../../src/components/Notifications/Notifications';
import ConnectNotification, {className as notificationClassName} from '../../src/components/Notification/Notification';
import css from '../../src/components/Notifications/Notifications.scss';
import notificationCss from '../../src/components/Notification/Notification.scss';
import {genNotification, genNotifications, mockStore} from '../fixtures';
import STATUS from '../../src/constants';

describe('Notifications', () => {
  // default value for notifications
  const defaultValues = {
    status: null,
    dismissible: true,
    dismissAfter: 5000
  };
  // default className for notifications container
  const className = css['notifications-container'];
  // default transition for notifications
  const transition = {
    enterTimeout: 400,
    leaveTimeout: 400,
    name: {
      enter: notificationCss['notification-enter'],
      enterActive: notificationCss['notification-enter-active'],
      leave: notificationCss['notification-leave'],
      leaveActive: notificationCss['notification-leave-active']
    }
  };
  // default props for Notifications component
  const defaultProps = {
    notifications: []
  };
  // full custom properties object for a Notifications component
  const customProps = {
    notifications: [],
    defaultValues: {
      status: STATUS.info,
      dismissAfter: 3333,
      dismissible: false
    },
    className: 'custom-notification',
    transition: {
      enterTimeout: 333,
      leaveTimeout: 333,
      name: {
        enter: 'custom-notification-enter',
        enterActive: 'custom-notification-enterActive',
        leave: 'custom-notification-leave',
        leaveActive: 'custom-notification-leaveActive'
      }
    },
    notificationClassName: {
      main: 'custom-notification',
      status: function(status) {
        return 'custom-notification-' + status;
      },
      title: 'custom-notification-title',
      icon: 'custom-notification-icon'
    }
  };

  /**
   * Return expected Notifications JSX
   * @param {Object} props
   * @param {Array} notifications an Array of notification object
   * @returns {XML}
   */
  function renderExpectedNotifications(props = {
    className,
    transition,
    notificationClassName
  }, notifications = []) {
    /**
     * Render notifications
     * @returns {XML}
     */
    function renderNotifications() {
      const {status, dismissible, dismissAfter} = defaultValues;
      const {notificationClassName} = props;
      return notifications.map((notification) => {
        return (
          <ConnectNotification key={notification.id} id={notification.id} title={notification.title}
                               message={notification.message}
                               status={notification.status || status}
                               dismissible={notification.dismissible === dismissible}
                               dismissAfter={notification.dismissAfter != null
                      ? notification.dismissAfter
                      : dismissAfter}
                               onAdd={notification.onAdd}
                               onRemove={notification.onRemove}
                               actions={notification.actions}
                               className={notificationClassName}/>
        );
      });
    }

    return (

        <TransitionGroup
          transitionName={props.transition.name}
          transitionEnterTimeout={props.transition.enterTimeout}
          transitionLeaveTimeout={props.transition.leaveTimeout}>
          {renderNotifications()}
        </TransitionGroup>

    );
  }

  it('should mount with default props', () => {
    const wrapper = mount(<Notifications {...defaultProps}/>);
    expect(wrapper.props().defaultValues).toEqual(defaultValues);
    expect(wrapper.props().className).toEqual(className);
    expect(wrapper.props().transition).toEqual(transition);
  });

  it('should mount component with custom props', () => {
    const wrapper = mount(<Notifications {...customProps}/>);
    expect(wrapper.props().defaultValues).toEqual(customProps.defaultValues);
    expect(wrapper.props().className).toEqual(customProps.className);
    expect(wrapper.props().transition).toEqual(customProps.transition);
    expect(wrapper.props().notificationClassName).toEqual(customProps.notificationClassName);
  });

  it('should render no notifications', () => {
    const wrapper = shallow(<Notifications {...defaultProps}/>);
    const expectedElement = shallow(renderExpectedNotifications());
    expect(wrapper.html()).toEqual(expectedElement.html());
    // `equals()` doesn't work in this case, I don't know why so
    // we use `debug()` to check that `TransitionGroup` tag are present
    // because after being rendered, it becomes a `span` tag
    expect(wrapper.debug()).toEqual(expectedElement.debug());
  });

  it('should render notifications with default values for notifications', () => {
    const notification = genNotification();
    delete notification.status;
    delete notification.dismissAfter;
    delete notification.dismissible;
    const store = mockStore({notifications: [notification]});
    const wrapper = mount(
      <Provider store={store}>
        <ConnectNotifications {...defaultProps}/>
      </Provider>
    );
    const props = wrapper.find(ConnectNotification).props();
    const expectedElement = mount(
      <Provider store={store}>
        {renderExpectedNotifications(undefined, [notification])}
      </Provider>
    );
    expect(props.status).toEqual(defaultValues.status);
    expect(props.dismissible).toEqual(defaultValues.dismissible);
    expect(props.dismissAfter).toEqual(defaultValues.dismissAfter);
    expect(wrapper.html()).toEqual(expectedElement.html());
  });

  it('should render notifications', () => {
    const notifications = genNotifications(3);
    const store = mockStore({notifications});
    const wrapper = mount(
      <Provider store={store}>
        <ConnectNotifications {...defaultProps}/>
      </Provider>
    );
    const expectedElement = mount(
      <Provider store={store}>
        {renderExpectedNotifications(undefined, notifications)}
      </Provider>
    );
    expect(wrapper.html()).toEqual(expectedElement.html());
  });
});
<commit_msg>fix test suite : Notifications component<commit_after>import React from 'react';
import {shallow, mount} from 'enzyme';
import {Provider} from 'react-redux';
import TransitionGroup from 'react/lib/ReactCSSTransitionGroup';
import ConnectNotifications, {Notifications} from '../../src/components/Notifications/Notifications';
import ConnectNotification, {
  transition,
  className as notificationClassName
} from '../../src/components/Notification/Notification';
import css from '../../src/components/Notifications/Notifications.scss';
import {genNotification, genNotifications, mockStore} from '../fixtures';
import STATUS from '../../src/constants';

describe('Notifications', () => {
  // default value for notifications
  const defaultValues = {
    status: null,
    dismissible: true,
    dismissAfter: 5000
  };
  // default className for notifications container
  const className = css['notifications-container'];

  // default props for Notifications component
  const defaultProps = {
    notifications: []
  };
  // full custom properties object for a Notifications component
  const customProps = {
    notifications: [],
    defaultValues: {
      status: STATUS.info,
      dismissAfter: 3333,
      dismissible: false
    },
    className: 'custom-notification',
    transition: {
      enterTimeout: 333,
      leaveTimeout: 333,
      name: {
        enter: 'custom-notification-enter',
        enterActive: 'custom-notification-enterActive',
        leave: 'custom-notification-leave',
        leaveActive: 'custom-notification-leaveActive'
      }
    },
    notificationClassName: {
      main: 'custom-notification',
      status: function(status) {
        return 'custom-notification-' + status;
      },
      title: 'custom-notification-title',
      icon: 'custom-notification-icon'
    }
  };

  /**
   * Return expected Notifications JSX
   * @param {Object} props
   * @param {Array} notifications an Array of notification object
   * @returns {XML}
   */
  function renderExpectedNotifications(props = {
    className,
    transition,
    notificationClassName
  }, notifications = []) {
    /**
     * Render notifications
     * @returns {XML}
     */
    function renderNotifications() {
      const {status, dismissible, dismissAfter} = defaultValues;
      const {notificationClassName} = props;
      return notifications.map((notification) => {
        return (
          <ConnectNotification key={notification.id} id={notification.id} title={notification.title}
                               message={notification.message}
                               status={notification.status || status}
                               dismissible={notification.dismissible != null
                                ? notification.dismissible
                                : dismissible}
                               dismissAfter={notification.dismissAfter != null
                                ? notification.dismissAfter
                                : dismissAfter}
                               onAdd={notification.onAdd}
                               onRemove={notification.onRemove}
                               actions={notification.actions}
                               className={notificationClassName}
                               transition={transition}/>
        );
      });
    }
    const {name, enterTimeout, leaveTimeout} = props.transition;
    return (

        <TransitionGroup
          transitionName={name}
          transitionEnterTimeout={enterTimeout}
          transitionLeaveTimeout={leaveTimeout}>
          {renderNotifications()}
        </TransitionGroup>

    );
  }

  it('should mount with default props', () => {
    const wrapper = mount(<Notifications {...defaultProps}/>);
    expect(wrapper.props().defaultValues).toEqual(defaultValues);
    expect(wrapper.props().className).toEqual(className);
  });

  it('should mount component with custom props', () => {
    const wrapper = mount(<Notifications {...customProps}/>);
    expect(wrapper.props().defaultValues).toEqual(customProps.defaultValues);
    expect(wrapper.props().className).toEqual(customProps.className);
    expect(wrapper.props().transition).toEqual(customProps.transition);
    expect(wrapper.props().notificationClassName).toEqual(customProps.notificationClassName);
  });

  it('should render no notifications', () => {
    const wrapper = shallow(<Notifications {...defaultProps}/>);
    const expectedElement = shallow(renderExpectedNotifications());
    expect(wrapper.html()).toEqual(expectedElement.html());
    // `equals()` doesn't work in this case, I don't know why so
    // we use `debug()` to check that `TransitionGroup` tag are present
    // because after being rendered, it becomes a `span` tag
    expect(wrapper.debug()).toEqual(expectedElement.debug());
  });

  it('should render notifications with default values for notifications', () => {
    const notification = genNotification();
    delete notification.status;
    delete notification.dismissAfter;
    delete notification.dismissible;
    const store = mockStore({notifications: [notification]});
    const wrapper = mount(
      <Provider store={store}>
        <ConnectNotifications {...defaultProps}/>
      </Provider>
    );
    const props = wrapper.find(ConnectNotification).props();
    const expectedElement = mount(
      <Provider store={store}>
        {renderExpectedNotifications(undefined, [notification])}
      </Provider>
    );
    expect(props.status).toEqual(defaultValues.status);
    expect(props.dismissible).toEqual(defaultValues.dismissible);
    expect(props.dismissAfter).toEqual(defaultValues.dismissAfter);
    expect(wrapper.html()).toEqual(expectedElement.html());
  });

  it('should render notifications', () => {
    const notifications = genNotifications(3);
    const store = mockStore({notifications});
    const wrapper = mount(
      <Provider store={store}>
        <ConnectNotifications {...defaultProps}/>
      </Provider>
    );
    const expectedElement = mount(
      <Provider store={store}>
        {renderExpectedNotifications(undefined, notifications)}
      </Provider>
    );
    expect(wrapper.html()).toEqual(expectedElement.html());
  });
});
<|endoftext|>


<commit_before>backsplash.Editor = (function(){

var clone = backsplash._clone;

jQuery.fn.backsplash = function(cmd, opts) {

    var res = [];
    var cmd_is_string = typeof(cmd) === "string";

    this.each(function() {
        if (cmd_is_string) {
            var editor = $(this).data('backsplash-editor');
            res.push(editor[cmd + "Method"].call(editor, opts))
        } else {
            var editor = new Editor(this, cmd, opts);
            $(this).data('backsplash-editor', editor);
        }
    })

    return cmd_is_string ? res[0] : this;

}

var Editor = function(elem, opts) {

    var editor = this;

    this.$elem = $(elem);
    this.opts = $.extend({}, this.$elem.data('backsplash'), opts);

    this.selection = []

    $(window).on('keydown.backsplash', $.proxy(this, 'onKeydown'));

    this.tiles = [];
    this.$elem.children().each(function() {

        var $tile = $(this);

        $tile.addClass('backsplash-tile');

        var tile = $tile.data('tile') || {};
        $tile.data('tile', tile);

        tile.$elem = $tile;
        tile.$controls = $('
')
            .appendTo($tile);

        tile.selected = false;
        tile.$selected = $('')
            .on('click.backsplash', function(e) { e.preventDefault() })
            .on('mousedown.backsplash', $.proxy(editor, 'onMousedown'))
            .appendTo(tile.$controls);

        tile.pinned = false;
        tile.$pinned = $('')
            .on('click.backsplash', $.proxy(editor, 'clickPinned'))
            .appendTo(tile.$controls);

        tile.locked = false;
        tile.$locked = $('')
            .on('click.backsplash', $.proxy(editor, 'clickLocked'))
            .appendTo(tile.$controls);

        editor.updateButtons(tile);

        editor.tiles.push(tile);
    })

}

Editor.prototype.clickPinned = function(e) {
    e.preventDefault();
    var tile = $(e.target).closest('.backsplash-tile').data('tile')
    tile.pinned = !tile.pinned;
    this.updateButtons(tile);
    if (!(tile.pinned || tile.locked)) {
        this.restoreBackup(tile, tile.backup);
        this.resetTiles();
    }
}

Editor.prototype.clickLocked = function(e) {
    e.preventDefault();
    var tile = $(e.target).closest('.backsplash-tile').data('tile')
    tile.locked = !tile.locked;
    this.updateButtons(tile);
    if (!(tile.pinned || tile.locked)) {
        this.restoreBackup(tile, tile.backup);
        this.resetTiles();
    }
}

Editor.prototype.updateButtons = function(tile) {

    if (tile.selected) {
        tile.$selected.addClass('active').removeClass('btn-default').addClass('btn-primary')
    } else {
        tile.$selected.removeClass('active').addClass('btn-default').removeClass('btn-primary')
    }

    if (tile.pinned) {
        tile.$pinned.addClass('active').removeClass('btn-default').addClass('btn-warning')
    } else {
        tile.$pinned.removeClass('active').addClass('btn-default').removeClass('btn-warning')
    }

    if (tile.locked) {
        tile.$locked.addClass('active').removeClass('btn-default').addClass('btn-danger')
            .find('span').removeClass('fa-unlock').addClass('fa-lock')
    } else {
        tile.$locked.removeClass('active').addClass('btn-default').removeClass('btn-danger')
            .find('span').removeClass('fa-lock').addClass('fa-unlock')
    }

}

Editor.prototype.resetTile = function(layout, old_tile, opts) {
    var new_tile = layout.add(old_tile, opts);
    old_tile.$elem.css(layout.css(new_tile));
    old_tile.row = new_tile.row;
    old_tile.col = new_tile.col;
}

Editor.prototype.resetTiles = function() {

    var layout = new backsplash.Layout(this.opts);

    for (var i = 0; i < this.tiles.length; i++) {
        this.tiles[i]._first = !i
        if (this.tiles[i].pinned || this.tiles[i].locked) {
            this.resetTile(layout, this.tiles[i])
        }
    }
    for (var i = 0; i < this.tiles.length; i++) {
        if (!(this.tiles[i].pinned || this.tiles[i].locked)) {
            this.resetTile(layout, this.tiles[i], {ignore_position: true})
        }
    }

    return layout;

}

Editor.prototype.restoreBackups = function() {
    for (var i = 0; i < this.tiles.length; i++) {
        if (this.tiles[i].backup) {
            this.restoreBackup(this.tiles[i], this.tiles[i].backup)
        }
    }
    this.resetTiles();
}

Editor.prototype.restoreBackup = function(dst, src) {

    dst.width = src.width
    dst.height = src.height
    dst.row = src.row
    dst.col = src.col
    dst.locked = src.locked
    dst.pinned = false

    this.updateButtons(dst);

    if (dst.row != src.row || dst.col != src.col) {
        dst.$elem.trigger('resized', [dst, this]);
        dst.$elem.trigger('restored', [dst]);
    }

}

Editor.prototype.onKeydown = function(e) {

    switch (e.which) {

        case 114: // r
            this.restoreBackups();
            break;

        case 38: // up
        case 40: // down
            e.preventDefault()
            for (var i = 0; i < this.selection.length; i++) {
                var tile = this.selection[i];
                if (e.metaKey) {
                    tile.height += e.which == 40 ? 1 : -1;
                    tile.$elem.trigger('resized', [tile, this])
                } else {
                    tile.row += e.which == 40 ? 1 : -1;
                    tile.$elem.trigger('moved', [tile])
                }
            }
            this.resetTiles();
            break;

        case 37: // left
        case 39: // right
            e.preventDefault()
            for (var i = 0; i < this.selection.length; i++) {
                var tile = this.selection[i];
                if (e.metaKey) {
                    tile.width += e.which == 39 ? 1 : -1;
                    tile.$elem.trigger('resized', [tile, this])
                } else {
                    tile.col += e.which == 39 ? 1 : -1;
                    tile.$elem.trigger('moved', [tile])
                }
            }
            this.resetTiles();
            break;

        default:
            // console.log('unknown key', e.which, e)
    }

}

Editor.prototype.onMousedown = function(e) {

    e.preventDefault();
    var tile = $(e.target).closest('.backsplash-tile').data('tile')

    this.mousedown = e;
    this.mousedownTile = tile;
    this.mousedownOffset = tile.$elem.offset();
    this.mousedownRow = tile.row;
    this.mousedownCol = tile.col;

    tile.backup = clone(tile.backup || tile)
    tile.pinned = true;

    $(window).on('mouseup.backsplash', $.proxy(this, 'onMouseup'));
    $(window).on('mousemove.backsplash', $.proxy(this, 'onMousemove'));

    if (!e.shiftKey) {
        for (var i = 0; i < this.selection.length; i++) {
            this.selection[i].selected = false;
            this.updateButtons(this.selection[i]);
        }
        this.selection = []
    }
    tile.selected = true;
    this.selection.push(tile);

    this.updateButtons(tile);

    this.resetTiles();

}

Editor.prototype.onMousemove = function(e) {

    e.preventDefault();

    var origin = this.$elem.offset();
    var x = e.pageX - origin.left + this.mousedownOffset.left - this.mousedown.pageX;
    var y = e.pageY - origin.top +this.mousedownOffset.top - this.mousedown.pageY;

    var row = Math.floor(y / (this.opts.tile_size + this.opts.padding) + 0.5);
    var col = Math.floor(x / (this.opts.tile_size + this.opts.padding) + 0.5);

    var tile = this.selection[0];
    var changed = (tile.row != row || tile.col != col);
    tile.row = row;
    tile.col = col;

    if (changed) {
        this.resetTiles();
    }

    this.selection[0].$elem.css({left: x, top: y});

}

Editor.prototype.onMouseup = function(e) {

    e.preventDefault();
    e.stopPropagation()

    $(window).off('mouseup.backsplash');
    $(window).off('mousemove.backsplash');

    if (this.mousedownRow != this.mousedownTile.row || this.mousedownCol != this.mousedownTile.col) {
        this.mousedownTile.$elem.trigger('moved', [this.mousedownTile]);
    }

    this.resetTiles();

    return false;
}

Editor.prototype.resetMethod = function() {
    this.restoreBackups();
}

Editor.prototype.commitMethod = function() {
    var layout = this.resetTiles();
    return this.tilesMethod(layout.linearize());
}

Editor.prototype.tilesMethod = function(tiles) {

    if (tiles) {
        this.tiles = tiles;
        for (var i = 0; i < this.tiles.length; i++) {

            var tile = this.tiles[i];
            tile.$elem.data('tile', tile)

            this.selected = false;
            tile.pinned = false;
            tile.backup = null;
            tile.width = tile.width || 1;
            tile.height = tile.height || 1;

            this.updateButtons(tile);
        }
        this.selection = [];
        this.resetTiles();
    }

    return this.tiles;
}

return Editor;

})();
<commit_msg>Pin only when changed<commit_after>backsplash.Editor = (function(){

var clone = backsplash._clone;

jQuery.fn.backsplash = function(cmd, opts) {

    var res = [];
    var cmd_is_string = typeof(cmd) === "string";

    this.each(function() {
        if (cmd_is_string) {
            var editor = $(this).data('backsplash-editor');
            res.push(editor[cmd + "Method"].call(editor, opts))
        } else {
            var editor = new Editor(this, cmd, opts);
            $(this).data('backsplash-editor', editor);
        }
    })

    return cmd_is_string ? res[0] : this;

}

var Editor = function(elem, opts) {

    var editor = this;

    this.$elem = $(elem);
    this.opts = $.extend({}, this.$elem.data('backsplash'), opts);

    this.selection = []

    $(window).on('keydown.backsplash', $.proxy(this, 'onKeydown'));

    this.tiles = [];
    this.$elem.children().each(function() {

        var $tile = $(this);

        $tile.addClass('backsplash-tile');

        var tile = $tile.data('tile') || {};
        $tile.data('tile', tile);

        tile.$elem = $tile;
        tile.$controls = $('
')
            .appendTo($tile);

        tile.selected = false;
        tile.$selected = $('')
            .on('click.backsplash', function(e) { e.preventDefault() })
            .on('mousedown.backsplash', $.proxy(editor, 'onMousedown'))
            .appendTo(tile.$controls);

        tile.pinned = false;
        tile.$pinned = $('')
            .on('click.backsplash', $.proxy(editor, 'clickPinned'))
            .appendTo(tile.$controls);

        tile.locked = false;
        tile.$locked = $('')
            .on('click.backsplash', $.proxy(editor, 'clickLocked'))
            .appendTo(tile.$controls);

        editor.updateButtons(tile);

        editor.tiles.push(tile);
    })

}

Editor.prototype.clickPinned = function(e) {
    e.preventDefault();
    var tile = $(e.target).closest('.backsplash-tile').data('tile')
    tile.pinned = !tile.pinned;
    this.updateButtons(tile);
    if (!(tile.pinned || tile.locked)) {
        this.restoreBackup(tile, tile.backup);
        this.resetTiles();
    }
}

Editor.prototype.clickLocked = function(e) {
    e.preventDefault();
    var tile = $(e.target).closest('.backsplash-tile').data('tile')
    tile.locked = !tile.locked;
    this.updateButtons(tile);
    if (!(tile.pinned || tile.locked)) {
        this.restoreBackup(tile, tile.backup);
        this.resetTiles();
    }
}

Editor.prototype.updateButtons = function(tile) {

    if (tile.selected) {
        tile.$selected.addClass('active').removeClass('btn-default').addClass('btn-primary')
    } else {
        tile.$selected.removeClass('active').addClass('btn-default').removeClass('btn-primary')
    }

    if (tile.pinned) {
        tile.$pinned.addClass('active').removeClass('btn-default').addClass('btn-warning')
    } else {
        tile.$pinned.removeClass('active').addClass('btn-default').removeClass('btn-warning')
    }

    if (tile.locked) {
        tile.$locked.addClass('active').removeClass('btn-default').addClass('btn-danger')
            .find('span').removeClass('fa-unlock').addClass('fa-lock')
    } else {
        tile.$locked.removeClass('active').addClass('btn-default').removeClass('btn-danger')
            .find('span').removeClass('fa-lock').addClass('fa-unlock')
    }

}

Editor.prototype.resetTile = function(layout, old_tile, opts) {
    var new_tile = layout.add(old_tile, opts);
    old_tile.$elem.css(layout.css(new_tile));
    old_tile.row = new_tile.row;
    old_tile.col = new_tile.col;
}

Editor.prototype.resetTiles = function() {

    var layout = new backsplash.Layout(this.opts);

    for (var i = 0; i < this.tiles.length; i++) {
        this.tiles[i]._first = !i
        if (this.tiles[i].pinned || this.tiles[i].locked) {
            this.resetTile(layout, this.tiles[i])
        }
    }
    for (var i = 0; i < this.tiles.length; i++) {
        if (!(this.tiles[i].pinned || this.tiles[i].locked)) {
            this.resetTile(layout, this.tiles[i], {ignore_position: true})
        }
    }

    return layout;

}

Editor.prototype.restoreBackups = function() {
    for (var i = 0; i < this.tiles.length; i++) {
        if (this.tiles[i].backup) {
            this.restoreBackup(this.tiles[i], this.tiles[i].backup)
        }
    }
    this.resetTiles();
}

Editor.prototype.restoreBackup = function(dst, src) {

    dst.width = src.width
    dst.height = src.height
    dst.row = src.row
    dst.col = src.col
    dst.locked = src.locked
    dst.pinned = false

    this.updateButtons(dst);

    if (dst.row != src.row || dst.col != src.col) {
        dst.$elem.trigger('resized', [dst, this]);
        dst.$elem.trigger('restored', [dst]);
    }

}

Editor.prototype.onKeydown = function(e) {

    switch (e.which) {

        case 114: // r
            this.restoreBackups();
            break;

        case 38: // up
        case 40: // down
            e.preventDefault()
            for (var i = 0; i < this.selection.length; i++) {
                var tile = this.selection[i];
                if (e.metaKey) {
                    tile.height += e.which == 40 ? 1 : -1;
                    tile.$elem.trigger('resized', [tile, this])
                } else {
                    tile.row += e.which == 40 ? 1 : -1;
                    tile.pinned = true;
                    this.updateButtons(tile);
                    tile.$elem.trigger('moved', [tile])
                }
            }
            this.resetTiles();
            break;

        case 37: // left
        case 39: // right
            e.preventDefault()
            for (var i = 0; i < this.selection.length; i++) {
                var tile = this.selection[i];
                if (e.metaKey) {
                    tile.width += e.which == 39 ? 1 : -1;
                    tile.$elem.trigger('resized', [tile, this])
                } else {
                    tile.col += e.which == 39 ? 1 : -1;
                    tile.pinned = true;
                    this.updateButtons(tile);
                    tile.$elem.trigger('moved', [tile])
                }
            }
            this.resetTiles();
            break;

        default:
            // console.log('unknown key', e.which, e)
    }

}

Editor.prototype.onMousedown = function(e) {

    e.preventDefault();
    var tile = $(e.target).closest('.backsplash-tile').data('tile')

    this.mousedown = e;
    this.mousedownTile = tile;
    this.mousedownOffset = tile.$elem.offset();
    this.mousedownRow = tile.row;
    this.mousedownCol = tile.col;

    tile.backup = clone(tile.backup || tile)

    $(window).on('mouseup.backsplash', $.proxy(this, 'onMouseup'));
    $(window).on('mousemove.backsplash', $.proxy(this, 'onMousemove'));

    if (!e.shiftKey) {
        for (var i = 0; i < this.selection.length; i++) {
            this.selection[i].selected = false;
            this.updateButtons(this.selection[i]);
        }
        this.selection = []
    }
    tile.selected = true;
    this.selection.push(tile);

    this.updateButtons(tile);

    this.resetTiles();

}

Editor.prototype.onMousemove = function(e) {

    e.preventDefault();

    var origin = this.$elem.offset();
    var x = e.pageX - origin.left + this.mousedownOffset.left - this.mousedown.pageX;
    var y = e.pageY - origin.top +this.mousedownOffset.top - this.mousedown.pageY;

    var row = Math.floor(y / (this.opts.tile_size + this.opts.padding) + 0.5);
    var col = Math.floor(x / (this.opts.tile_size + this.opts.padding) + 0.5);

    var tile = this.selection[0];
    var changed = (tile.row != row || tile.col != col);
    tile.row = row;
    tile.col = col;

    if (changed) {
        this.resetTiles();
    }

    this.selection[0].$elem.css({left: x, top: y});

}

Editor.prototype.onMouseup = function(e) {

    e.preventDefault();
    e.stopPropagation()

    $(window).off('mouseup.backsplash');
    $(window).off('mousemove.backsplash');

    if (this.mousedownRow != this.mousedownTile.row || this.mousedownCol != this.mousedownTile.col) {
        tile.pinned = true;
        this.updateButtons(tile);
        this.mousedownTile.$elem.trigger('moved', [this.mousedownTile]);
    }

    this.resetTiles();

    return false;
}

Editor.prototype.resetMethod = function() {
    this.restoreBackups();
}

Editor.prototype.commitMethod = function() {
    var layout = this.resetTiles();
    return this.tilesMethod(layout.linearize());
}

Editor.prototype.tilesMethod = function(tiles) {

    if (tiles) {
        this.tiles = tiles;
        for (var i = 0; i < this.tiles.length; i++) {

            var tile = this.tiles[i];
            tile.$elem.data('tile', tile)

            this.selected = false;
            tile.pinned = false;
            tile.backup = null;
            tile.width = tile.width || 1;
            tile.height = tile.height || 1;

            this.updateButtons(tile);
        }
        this.selection = [];
        this.resetTiles();
    }

    return this.tiles;
}

return Editor;

})();
<|endoftext|>


<commit_before>
$(document).ready(function() {

$('.mytoggle button').click(function(){
    var ix = $(this).index();

    $('.barcode-checker').toggle( ix === 0 );
    $('.sioc-checker').toggle( ix === 1 );
      // document.getElementById("barcode-checker").blur();
});

// *******SUBMIT BARCODE BUTTON*******
$('#check').click(function() {
	JsBarcode("#barcode", $('#userInput').val());
	return false;
});
// ********END SUBMIT BARCODE BUTTON******

// ******PREFIX BUTTONS******
$("#ambient").click(function() {
	$("#userInput").val("P-1-A").focus();
});

$("#chilled").click(function() {
	$("#userInput").val("P-1-C").focus();
});

$("#freezer").click(function() {
	$("#userInput").val("P-1-F").focus();
});

$("#bigs").click(function() {
	$("#userInput").val("P-1-B").focus();
});

$("#p-cart").click(function() {
				// if
				// 	(document.getElementById("fcLfocation").value == "ONT4")
				// {$("#userInput").val("rbONT40").focus();}
				// else if
				// 	(document.getElementById("fcLocation").value == "OAK4")
				// {$("#userInput").val("rbOAK40").focus();}
				// else
				// {
					$("#userInput").val("rbLAX6").focus();
				// }
			});

$("#oneway").click(function() {
	$("#userInput").val("sp1WAY").focus();
});

$("#s-cart").click(function() {
	$("#userInput").val("SCFRSH0").focus();
});
// ******END PREFIX BUTTONS******

var newBarcode = function() {
	var windowSize = $(window).width();
    //Convert to boolean
    if ($("#userInput").val().charAt(0) == "P" && $("#userInput").val().charAt(1) == "-" && windowSize > 401)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val().toUpperCase()
    		)
    }
    else if ($("#userInput").val().charAt(0) == "P" && $("#userInput").val().charAt(1) == "-" && windowSize < 400)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val().toUpperCase(), {width: 1}
    		)
    }
    else if ( windowSize < 400)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val(), {width: 1}
    		)
    }
    else {
    	$("#barcode").JsBarcode(
    		$("#userInput").val()
    		)}
    };

//<!--  selecting a random array item
-->

function randomWorkstation(listOfStations)
{
	return listOfStations[Math.floor(Math.random()*listOfStations.length)];
}
// $('#randstation').click(function() {
// 	JsBarcode("#barcode", randomWorkstation(listOfStations));
// });

$(function(){
            var hits = 0; //->variable
    //  binding handler to click event
    $('#randstation').click(function(){
        if  (hits % 2 !== 0)
        {
            JsBarcode("#barcode", randomWorkstation(listOfStations), {lineColor: "teal", background: "mistyrose", text: "Holidays"});
        }
        else
        {
            JsBarcode("#barcode", randomWorkstation(listOfStations), {lineColor: "purple", background: "#ccffff", text: "Happy"});
        }
        hits++;
        return false;
    });
});

$('#drop-ambient').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-AMBIENT", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-AMBIENT");
	}
});

$('#drop-chilled').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-CHILLED", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-CHILLED", {lineColor: ""});
	}
});

$('#drop-freezer').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-FROZEN", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-FROZEN", {lineColor: ""});
	}
});

	$("#userInput").on('input',newBarcode);
	// $("#userInput").on('input',checkISD);
	$("#barcodeType").change(function(){
	$("#userInput").val( defaultValues[$(this).val()] );
	});

    $('#scanner-button').magnificPopup({
    	items: {
    		src: '#scanner-pop',
    		type: 'inline'
    	},
    	closeBtnInside: true
    });

// *********TOGGLE FUNCTION*********
    $('.toggle-switch').click(function(){
    	$(this).toggleClass("amzorng")
    	$(this).next().slideToggle("fast", function(){
    		if($('.toggle-div').is(":visible")){
    			$('#more').text("less");
    		}else{
    			$('#more').text("more");
    		}
    	});
    });
// *********END TOGGLE FUNCTION*********

});

// **********REAL TIME BARCODE*********
// <script>
//     var checkISD = function() {
//     	if ($("#userInput").val().charAt(6) == "8" && $("#userInput").val().charAt(7) == "0" && $("#userInput").val().charAt(8) == "4" && $("#userInput").val().charAt(9) == "" ){
//     		$('#isd').css('visibility', 'visible');
//     	}
//     	else
//     	{
//     		$('#isd').css('visibility', 'hidden');
//     	}
//     }
//     </script>
//  *******END REAL TIME BARCODE******

// **********MOBILE ALERT*********
// if (screen.width <= 400) {
//     $(function() {
//     $("#mobilealert").show();
//   })
// }
// **********END MOBILE ALERT*********

// **********CHECK ISD*********
//     var checkISD = function() {
//     	if ($("#userInput").val().charAt(6) == "8" && $("#userInput").val().charAt(7) == "0" && $("#userInput").val().charAt(8) == "4" && $("#userInput").val().charAt(9) == "" ){
//     		$('#isd').css('visibility', 'visible');
//     	}
//     	else
//     	{
//     		$('#isd').css('visibility', 'hidden');
//     	}
//     }
// **********END CHECK ISD*********

<commit_msg>update to new years message<commit_after>
$(document).ready(function() {

$('.mytoggle button').click(function(){
    var ix = $(this).index();

    $('.barcode-checker').toggle( ix === 0 );
    $('.sioc-checker').toggle( ix === 1 );
      // document.getElementById("barcode-checker").blur();
});

// *******SUBMIT BARCODE BUTTON*******
$('#check').click(function() {
	JsBarcode("#barcode", $('#userInput').val());
	return false;
});
// ********END SUBMIT BARCODE BUTTON******

// ******PREFIX BUTTONS******
$("#ambient").click(function() {
	$("#userInput").val("P-1-A").focus();
});

$("#chilled").click(function() {
	$("#userInput").val("P-1-C").focus();
});

$("#freezer").click(function() {
	$("#userInput").val("P-1-F").focus();
});

$("#bigs").click(function() {
	$("#userInput").val("P-1-B").focus();
});

$("#p-cart").click(function() {
				// if
				// 	(document.getElementById("fcLfocation").value == "ONT4")
				// {$("#userInput").val("rbONT40").focus();}
				// else if
				// 	(document.getElementById("fcLocation").value == "OAK4")
				// {$("#userInput").val("rbOAK40").focus();}
				// else
				// {
					$("#userInput").val("rbLAX6").focus();
				// }
			});

$("#oneway").click(function() {
	$("#userInput").val("sp1WAY").focus();
});

$("#s-cart").click(function() {
	$("#userInput").val("SCFRSH0").focus();
});
// ******END PREFIX BUTTONS******

var newBarcode = function() {
	var windowSize = $(window).width();
    //Convert to boolean
    if ($("#userInput").val().charAt(0) == "P" && $("#userInput").val().charAt(1) == "-" && windowSize > 401)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val().toUpperCase()
    		)
    }
    else if ($("#userInput").val().charAt(0) == "P" && $("#userInput").val().charAt(1) == "-" && windowSize < 400)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val().toUpperCase(), {width: 1}
    		)
    }
    else if ( windowSize < 400)
    {
    	$("#barcode").JsBarcode(
    		$("#userInput").val(), {width: 1}
    		)
    }
    else {
    	$("#barcode").JsBarcode(
    		$("#userInput").val()
    		)}
    };

//<!--  selecting a random array item
-->

function randomWorkstation(listOfStations)
{
	return listOfStations[Math.floor(Math.random()*listOfStations.length)];
}
// $('#randstation').click(function() {
// 	JsBarcode("#barcode", randomWorkstation(listOfStations));
// });

$(function(){
            var hits = 0; //->variable
    //  binding handler to click event
    $('#randstation').click(function(){
        if  (hits % 2 !== 0)
        {
            JsBarcode("#barcode", randomWorkstation(listOfStations), {lineColor: "white", background: "black", text: "New Year"});
        }
        else
        {
            JsBarcode("#barcode", randomWorkstation(listOfStations), {lineColor: "black", background: "white", text: "Happy"});
        }
        hits++;
        return false;
    });
});

$('#drop-ambient').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-AMBIENT", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-AMBIENT");
	}
});

$('#drop-chilled').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-CHILLED", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-CHILLED", {lineColor: ""});
	}
});

$('#drop-freezer').click(function() {
	if ( $(window).width() < 400) {
		JsBarcode("#barcode", "dz-P-FROZEN", {width: 1});
	} else {
		JsBarcode("#barcode", "dz-P-FROZEN", {lineColor: ""});
	}
});

	$("#userInput").on('input',newBarcode);
	// $("#userInput").on('input',checkISD);
	$("#barcodeType").change(function(){
	$("#userInput").val( defaultValues[$(this).val()] );
	});

    $('#scanner-button').magnificPopup({
    	items: {
    		src: '#scanner-pop',
    		type: 'inline'
    	},
    	closeBtnInside: true
    });

// *********TOGGLE FUNCTION*********
    $('.toggle-switch').click(function(){
    	$(this).toggleClass("amzorng")
    	$(this).next().slideToggle("fast", function(){
    		if($('.toggle-div').is(":visible")){
    			$('#more').text("less");
    		}else{
    			$('#more').text("more");
    		}
    	});
    });
// *********END TOGGLE FUNCTION*********

});

// **********REAL TIME BARCODE*********
// <script>
//     var checkISD = function() {
//     	if ($("#userInput").val().charAt(6) == "8" && $("#userInput").val().charAt(7) == "0" && $("#userInput").val().charAt(8) == "4" && $("#userInput").val().charAt(9) == "" ){
//     		$('#isd').css('visibility', 'visible');
//     	}
//     	else
//     	{
//     		$('#isd').css('visibility', 'hidden');
//     	}
//     }
//     </script>
//  *******END REAL TIME BARCODE******

// **********MOBILE ALERT*********
// if (screen.width <= 400) {
//     $(function() {
//     $("#mobilealert").show();
//   })
// }
// **********END MOBILE ALERT*********

// **********CHECK ISD*********
//     var checkISD = function() {
//     	if ($("#userInput").val().charAt(6) == "8" && $("#userInput").val().charAt(7) == "0" && $("#userInput").val().charAt(8) == "4" && $("#userInput").val().charAt(9) == "" ){
//     		$('#isd').css('visibility', 'visible');
//     	}
//     	else
//     	{
//     		$('#isd').css('visibility', 'hidden');
//     	}
//     }
// **********END CHECK ISD*********

<|endoftext|>


<commit_before>'use strict';
/* Spider */
// -- Object ------------------------------------------------------
var Spider, exports;
Spider = (function(width, height, canvasId) {

  function Spider(width, height, canvasId) {
    this.width     = width;
    this.height    = height;
    this.names     = ['webgl', 'experimental-webgl', 'webkit-3d', 'moz-webgl'];
    this.canvasId  = canvasId;
    this.gl        = null;
    this.buffer    = null;
  }

Spider.prototype.startWeb = function() {
    var canvas = document.getElementById(this.canvasId);
    var i = 0;
    while ((this.gl == null) && (i < this.names.length)) {
      try {
        this.gl = canvas.getContext(this.names[i]);
      } catch (e) {
        console.log(e);
      };
      i++;
    }
  };

  Spider.prototype.createBuffer = function() {
    this.gl.createBuffer();
  };

  Spider.prototype.isStarted = function() {
    if (this.gl == null) {return false;}
    else {return true;}
  };

  Spider.prototype.clear = function() {
    if (this.isStarted()) {
      this.gl.clear(this.gl.COLOR_BUFFER_BIT);
      this.gl.viewport(0, 0, this.width, this.height);
    }
  },

  Spider.prototype.changeColor = function(color) {
    if (this.isStarted()) {
      this.gl.clearColor(color[0], color[1], color[2], color[3]);
      this.clear(this.gl);
    }
  };

  Spider.prototype.hex2rgb = function(hex, opacity) {
    hex = hex.replace('#','');
    var r = parseInt(hex.substring(0,2), 16);
    var g = parseInt(hex.substring(2,4), 16);
    var b = parseInt(hex.substring(4,6), 16);
    return [r/255,g/255,b/255,opacity];
  };

  Spider.prototype.addShader = function(Shader) {
    this.gl.bindBuffer(this.gl.ARRAY_BUFFER, Shader.getVertexBuffer());
    this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(Shader.getVertices()), this.gl.STATIC_DRAW);
    this.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);

    this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, Shader.getIndexBuffer());
    this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(Shader.getIndices()), this.gl.STATIC_DRAW);
    this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, null);
  }

return Spider;
})();

// -- Export -------------------------------------------------------------------
exports = module.exports = Spider;
<commit_msg>changed name to Aubengine<commit_after><|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var request = require('request')

// # of tries for application-under-test webserver to start up on specified port
// We test once per second
var HTTP_CHECK_RETRIES = 10

// Port on which the application-under-test webserver should bind to on localhost.
// Sauce Connector will tunnel from this to Sauce Cloud for Selenium tests
var HTTP_PORT = 8031

// Read & parse a JSON file
function getJson(filename, cb) {
  fs.readFile(filename, function(err, data) {
    if (err) return cb(err, null)
    try {
      var json = JSON.parse(data)
      cb(null, json)
    } catch(e) {
      cb(e, null)
    }
  })
}

// `npm install` has succeeded at this point.
// We run `npm test` and assuming that has passed,
// then we start the Sauce test process.
// If `npm test` fails, we don't bother with the overhead of running the Sauce tests.
function test(ctx, cb) {
  console.log("SAUCE test")
  var startPhaseDone = false
  var tsh = ctx.shellWrap("npm test")
  // Run
  ctx.forkProc(ctx.workingDir, tsh.cmd, tsh.args, function(exitCode) {
    if (exitCode !== 0) {
      return cb(exitCode)
    } else {
      ctx.striderMessage("npm test success - trying Sauce tests...")
      // Parse package.json so we can run the start script directly.
      // This is important because `npm start` will fork a subprocess a la shell
      // which means we cannot track the PID and shut it down later.
      getJson(path.join(ctx.workingDir, "package.json"), npmTestPassed)
    }
  })
  function npmTestPassed(err, packageJson) {
    if (err || packageJson.scripts === undefined || packageJson.scripts.start === undefined) {
      striderMessage("could not read package.json to find start command - failing test")
      return cb(1)
    }
    // `npm test` succeeded, so we go through the Sauce tests.

    // Start the app, suggesting a port via PORT environment variable
    var tsh = ctx.shellWrap(packageJson.scripts.start)
    var serverProc = ctx.forkProc({
      args:tsh.args,
      cmd:tsh.cmd,
      cwd:ctx.workingDir,
      env:{PORT:HTTP_PORT},
    }, function(exitCode) {
      // Could perhaps be backgrounding itself. This should be avoided.
      if (exitCode !== 0 && !startPhaseDone) {
        // If we haven't already called back with completion,
        // and `npm start` exits with non-zero exit code,
        // call back with error and mark done.
        ctx.striderMessage("npm start failed - failing test")
        startPhaseDone = true
        return cb(exitCode)
      }
    })

    // The project webserver should be available via HTTP once started.
    // This section implements a check which will attempt to make a HTTP request for /
    // expecting a 200 response code. It will try HTTP_CHECK_RETRIES times, waiting 1 second
    // between checks. If it fails after HTTP_CHECK_RETRIES times, the server process will be killed
    // and the test failed.
    var tries = 0
    ctx.striderMessage("Waiting for webserver to come up on localhost:" + HTTP_PORT)
    var intervalId = setInterval(function() {
      // Check for http status 200 on http://localhost:HTTP_PORT/
      request("http://localhost:"+HTTP_PORT+"/", function(err, response) {
        if (startPhaseDone) {
          clearInterval(intervalId)
          return
        }
        if (!err && response.statusCode == 200) {
          ctx.striderMessage("Got HTTP 200 on localhost:" + HTTP_PORT + " indicating server is up")
          startPhaseDone = true
          clearInterval(intervalId)
          serverUp()
        } else {
          tries++
          console.log("Error on localhost:%d: %s", HTTP_PORT, err)
          if (tries >= HTTP_CHECK_RETRIES) {
            var msg = ("HTTP 200 check on localhost:" + HTTP_PORT + " failed after " + tries
              + " retries, server not up - failing test")
            ctx.striderMessage(msg)
            clearInterval(intervalId)
            startPhaseDone = true
            return cb(1)
          }
        }
      })
    }, 1000)

    // Start the Sauce Connector. Returns childProcess object.
    function startConnector(username, apiKey, cb) {
      var jarPath = path.join(__dirname, "thirdparty", "Sauce-Connect.jar")
      var jsh = ctx.shellWrap("java -jar " + jarPath + " " + username + " " + apiKey)

      ctx.striderMessage("Starting Sauce Connector")
      return ctx.forkProc(__dirname, jsh.cmd, jsh.args, cb)
    }

    // Server is up, start Sauce Connector and run the tests via `npm sauce` invocations
    function serverUp() {
      var done = false
      var connectorProc = startConnector(process.env.SAUCE_USERNAME, process.env.SAUCE_ACCESS_KEY,
        function(exitCode) {
        console.log("Connector exited with code: %d", exitCode)
        if (!done) {
          ctx.striderMessage("Error starting Sauce Connector - failing test")
          ctx.striderMessage("Shutting down server")
          serverProc.kill("SIGKILL")
          done = true
          return cb(1)
        }
      })

      // Wait until connector outputs "You may start your tests"
      // before executing Sauce tests
      connectorProc.stdout.on('data', function(data) {
        if (/Connected! You may start your tests./.exec(data) !== null) {
          var saucesh = ctx.shellWrap("npm run-script sauce")
          //: TODO this should be a loop, executing `npm run-script sauce` for each
          // browser/OS combo specified for the project.
          var sauceProc = ctx.forkProc({
            args: saucesh.args,
            cmd: saucesh.cmd,
            cwd: ctx.workingDir,
            // TODO: Read Sauce creds from Strider per-project storage.
            env: {
              SAUCE_USERNAME:process.env.SAUCE_USERNAME,
              SAUCE_ACCESS_KEY:process.env.SAUCE_ACCESS_KEY
            }
          }, function(code) {
            ctx.striderMessage("npm run-script sauce exited with code " + code)
            if (!done) {
              done = true
              ctx.striderMessage("Shutting down Sauce Connector")
              connectorProc.kill("SIGINT")
              ctx.striderMessage("Shutting down server")
              serverProc.kill()
              // Give Sauce Connector & server 5 seconds to gracefully stop before sending SIGKILL
              setTimeout(function() {
                connectorProc.kill("SIGKILL")
                serverProc.kill("SIGKILL")
                return cb(code)
              }, 5000)
            }
          })
        }
      })
    }
  }
}

module.exports = function(ctx, cb) {

  ctx.addDetectionRule({
    filename:"package.json",
    jsonKeyExists:"scripts.sauce",
    language:"node.js",
    framework:null,
    hasSauce:true,
    prepare:"npm install",
    test:test
  })

  console.log("strider-sauce extension loaded")
  cb(null, null)
}
<commit_msg>use npmCmd wrapper from context. use a constant for http check interval.<commit_after>var fs = require('fs')
var path = require('path')
var request = require('request')

// # of tries for application-under-test webserver to start up on specified port
// We test once per second
var HTTP_CHECK_RETRIES = 10

// Interval in between HTTP checks in ms
var HTTP_CHECK_INTERVAL = 1000

// Port on which the application-under-test webserver should bind to on localhost.
// Sauce Connector will tunnel from this to Sauce Cloud for Selenium tests
var HTTP_PORT = 8031

// Read & parse a JSON file
function getJson(filename, cb) {
  fs.readFile(filename, function(err, data) {
    if (err) return cb(err, null)
    try {
      var json = JSON.parse(data)
      cb(null, json)
    } catch(e) {
      cb(e, null)
    }
  })
}

// `npm install` has succeeded at this point.
// We run `npm test` and assuming that has passed,
// then we start the Sauce test process.
// If `npm test` fails, we don't bother with the overhead of running the Sauce tests.
function test(ctx, cb) {
  console.log("SAUCE test")
  var startPhaseDone = false
  var tsh = ctx.shellWrap(ctx.npmCmd + " test")
  // Run
  ctx.forkProc(ctx.workingDir, tsh.cmd, tsh.args, function(exitCode) {
    if (exitCode !== 0) {
      return cb(exitCode)
    } else {
      ctx.striderMessage("npm test success - trying Sauce tests...")
      // Parse package.json so we can run the start script directly.
      // This is important because `npm start` will fork a subprocess a la shell
      // which means we cannot track the PID and shut it down later.
      getJson(path.join(ctx.workingDir, "package.json"), npmTestPassed)
    }
  })
  function npmTestPassed(err, packageJson) {
    if (err || packageJson.scripts === undefined || packageJson.scripts.start === undefined) {
      striderMessage("could not read package.json to find start command - failing test")
      return cb(1)
    }
    // `npm test` succeeded, so we go through the Sauce tests.

    // Start the app, suggesting a port via PORT environment variable
    var tsh = ctx.shellWrap(packageJson.scripts.start)
    var serverProc = ctx.forkProc({
      args:tsh.args,
      cmd:tsh.cmd,
      cwd:ctx.workingDir,
      env:{PORT:HTTP_PORT},
    }, function(exitCode) {
      // Could perhaps be backgrounding itself. This should be avoided.
      if (exitCode !== 0 && !startPhaseDone) {
        // If we haven't already called back with completion,
        // and `npm start` exits with non-zero exit code,
        // call back with error and mark done.
        ctx.striderMessage("npm start failed - failing test")
        startPhaseDone = true
        return cb(exitCode)
      }
    })

    // The project webserver should be available via HTTP once started.
    // This section implements a check which will attempt to make a HTTP request for /
    // expecting a 200 response code. It will try HTTP_CHECK_RETRIES times, waiting 1 second
    // between checks. If it fails after HTTP_CHECK_RETRIES times, the server process will be killed
    // and the test failed.
    var tries = 0
    ctx.striderMessage("Waiting for webserver to come up on localhost:" + HTTP_PORT)
    var intervalId = setInterval(function() {
      // Check for http status 200 on http://localhost:HTTP_PORT/
      request("http://localhost:"+HTTP_PORT+"/", function(err, response) {
        if (startPhaseDone) {
          clearInterval(intervalId)
          return
        }
        if (!err && response.statusCode == 200) {
          ctx.striderMessage("Got HTTP 200 on localhost:" + HTTP_PORT + " indicating server is up")
          startPhaseDone = true
          clearInterval(intervalId)
          serverUp()
        } else {
          tries++
          console.log("Error on localhost:%d: %s", HTTP_PORT, err)
          if (tries >= HTTP_CHECK_RETRIES) {
            var msg = ("HTTP 200 check on localhost:" + HTTP_PORT + " failed after " + tries
              + " retries, server not up - failing test")
            ctx.striderMessage(msg)
            clearInterval(intervalId)
            startPhaseDone = true
            return cb(1)
          }
        }
      })
    }, HTTP_CHECK_INTERVAL)

    // Start the Sauce Connector. Returns childProcess object.
    function startConnector(username, apiKey, cb) {
      var jarPath = path.join(__dirname, "thirdparty", "Sauce-Connect.jar")
      var jsh = ctx.shellWrap("java -jar " + jarPath + " " + username + " " + apiKey)

      ctx.striderMessage("Starting Sauce Connector")
      return ctx.forkProc(__dirname, jsh.cmd, jsh.args, cb)
    }

    // Server is up, start Sauce Connector and run the tests via `npm sauce` invocations
    function serverUp() {
      var done = false
      var connectorProc = startConnector(process.env.SAUCE_USERNAME, process.env.SAUCE_ACCESS_KEY,
        function(exitCode) {
        console.log("Connector exited with code: %d", exitCode)
        if (!done) {
          ctx.striderMessage("Error starting Sauce Connector - failing test")
          ctx.striderMessage("Shutting down server")
          serverProc.kill("SIGKILL")
          done = true
          return cb(1)
        }
      })

      // Wait until connector outputs "You may start your tests"
      // before executing Sauce tests
      connectorProc.stdout.on('data', function(data) {
        if (/Connected! You may start your tests./.exec(data) !== null) {
          var saucesh = ctx.shellWrap(ctx.npmCmd + " run-script sauce")
          //: TODO this should be a loop, executing `npm run-script sauce` for each
          // browser/OS combo specified for the project.
          var sauceProc = ctx.forkProc({
            args: saucesh.args,
            cmd: saucesh.cmd,
            cwd: ctx.workingDir,
            // TODO: Read Sauce creds from Strider per-project storage.
            env: {
              SAUCE_USERNAME:process.env.SAUCE_USERNAME,
              SAUCE_ACCESS_KEY:process.env.SAUCE_ACCESS_KEY
            }
          }, function(code) {
            ctx.striderMessage("npm run-script sauce exited with code " + code)
            if (!done) {
              done = true
              ctx.striderMessage("Shutting down Sauce Connector")
              connectorProc.kill("SIGINT")
              ctx.striderMessage("Shutting down server")
              serverProc.kill()
              // Give Sauce Connector & server 5 seconds to gracefully stop before sending SIGKILL
              setTimeout(function() {
                connectorProc.kill("SIGKILL")
                serverProc.kill("SIGKILL")
                return cb(code)
              }, 5000)
            }
          })
        }
      })
    }
  }
}

module.exports = function(ctx, cb) {

  ctx.addDetectionRule({
    filename:"package.json",
    jsonKeyExists:"scripts.sauce",
    language:"node.js",
    framework:null,
    hasSauce:true,
    prepare:ctx.npmCmd + " install",
    test:test
  })

  console.log("strider-sauce extension loaded")
  cb(null, null)
}
<|endoftext|>


<commit_before><commit_msg>theme: change moon icon to the same theme as the sun<commit_after><|endoftext|>


<commit_before>markers = new Meteor.Collection("clinics");
/*

    A GEO TAGGING COMMUNITY
    []

    Allow users to join agencies and be tracked
    independently in each. Present the user a way
    to select the agency they are in after logging in.

    Agencies act as a a list of markers that cannot be modified by
    its members. Members can send their own geocoding location and timestamps to
    agencies for their personal tracking and agencies can send sms messages
    if the user opts in.

        Agency

        {
          _id: <mongo_id>,
          title: <string>,
          owner: <mongo_id:users._id>
        }

        **Field 'access' might refer to a simple string,
        integer or another mongo id inside another collection;
        but controls the visibility of the marker. Wether its public,
        private to the user (default for users) or inside of the groups
        the user has the ability to post markers to.

        Marker
        {
            _id: <mongo_id>,
            title: <>,
            owner: <users._id || agencies.id>,
            address: <string>,
            access: <**>,
            loc : [<float>,<float>]

        }

    If users have accounts at the same agency that are different
    'types' (i.e. user/marker admin) then show entries for each

    Admin accounts can add points that are viewable by everyone.

    Users can add points inside of their own account, and inside of
    groups
*/

agencies = new Meteor.Collection("agencies");

Meteor.startup(function(){
      geocoder = new google.maps.Geocoder();
});

Template.add_marker.events({
    'click input.add_marker' : function(evt,tmpl){
    /*

        ADD NEW marker
            1) Geocode Address
            2) Store data to database for marker.

    */
        var record ={};
        // use tmpl.data??
        console.log('in add marker event');
        var geo_term=tmpl.find(".marker_address").value;
        record.name = tmpl.find(".marker_name").value;
        record.type = tmpl.find(".marker_type").value;
        record.visibility = tmpl.find(".marker_type").marker_visiblity;
        console.log(record);
        if(typeof geocoder != 'undefined'){
            geocoder.geocode({'address':geo_term},function(results,status){
                results = results[0];
                if(status == google.maps.GeocoderStatus.OK){
                    map.setCenter(results.geometry.location);
                    record.loc = [results.geometry.location.jb,results.geometry.location.kb];
                    markers.insert(record);
                    lookForMarkers([results.geometry.location.jb,results.geometry.location.kb]);
                    //document.getElementById('.marker_address').value = '';
                }else{
                /*
                    Would you like to insert this marker anyway?
                */
                    alert('Could not geocode location.. please check for internet connection');
                    // show input fields..
                }
            });
            /*

                ALSO STORE A USER token of some sort so they might
                have secure access

            */

            // From here let server build the marker and update client.
            $('#marker_add').hide();

            // show the button to add another marker
            $('.markerAddShow').show();
            console.log('Its all here lets make an insert. and probably hide something...');

            // remove fields from session to avoid accidental field duplication/reentry
        }else{
            // ask to insert a location without a geocoder?
            alert('Gmaps does not seem to be loaded');

        }
    }
});

Template.map.events({
    'dblclick div#map_canvas' : function(evt,tmpl){
        placeNavMarker(map.center,undefined,function(){alert("Did you want to place a marker here?")});

    }

});

Template.markers.events({
    'click input.del_marker' : function(evt,tmpl){
        markers.remove({_id:tmpl.data._id});
        // refresh the overlays
        // eventually use SESSION variable to keep track of how to filter the markers
        // based on the user settings/permissions etc.
        lookForMarkers();

    },
    'click a.edit_marker' :function(evt,tmpl){
        console.log('edit');
        // probably use the index to look for the term eventually...
        var latlng = new google.maps.LatLng(tmpl.data.loc[0], tmpl.data.loc[1]);

        map.setCenter(latlng);
//        console.log(tmpl.data.loc[0]);
    }
});

Template.loggedInMenu.rendered = function(){
                $('div#social').hide();
                $('div#marker_add').hide();
                $('div#user_settings').hide();
                $('div#the_markers').hide();
                $('div#marker_edit').hide();

}

Template.loggedInMenu.marker_index = function(evt,tmpl){
// get User. something to filter this find
    return markers.find({},{});
}

Template.content.rendered = function(){
// IF MOBILE .. attempt to detect screen orientation/load different css to do horizontal nav
// versus vertical
  var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|iemobile|BlackBerry)/);

  if(navigator.geolocation){
         navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  }else{
  // allow for editing anyway?
    alert('no geo location?');
  }
  // if no map can be created then we are working offline...
}

/* TODO
Template.settings.events({

    'click input.update' : function(evt,tmpl){

    }
});*/
/* BEGIN GMAPS

 TO Eventually support hiding /showing markers quickly in gmaps.. trying to get that to work properly..

 */
currentMarkers = [];

function lookForMarkers(theBox){
// set ceter of map to the marker you just created
    c = markers.find({}, {fields: {_id: 1}}).fetch();
    console.log(currentMarkers.length);
    //console.log(c);
    if(typeof c != 'undefined')
    c.filter(function (arr){
        // make new nat lav
        console.log(arr['loc']);
        /*
         Backwards support.. remove when releasing.. Supports the
         appropriate way of storing lat/long for geo queries.
        */
        if(typeof arr['loc'] != 'undefined'){
            var co = new google.maps.LatLng(arr['loc'][0], arr['loc'][1]);

            placeNavMarker(co,undefined,function(){alert(arr['name'] + ' ' + arr['type']);});
        }else if(typeof arr['x'] != 'undefined' && typeof arr['y'] != 'undefined'){
            var co = new google.maps.LatLng(arr['x'], arr['y']);
            placeNavMarker(co);
        }
        }
    );
}

function createMap (latLng) {
    console.log('making map');
    var mapOptions = {
        disableDoubleClick: true,
        streetViewControl: false,
        scrollwheel: false,
        zoom: 15,
        center: latLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    lookForMarkers();
};

function successFunction(success) {
  var navLatLng = new google.maps.LatLng(success.coords.latitude, success.coords.longitude);
  // annoying...
  createMap(navLatLng);
  // send it true option to use different marker
  placeNavMarker(navLatLng,true);
  lookForMarkers([navLatLng.jb,navLatLng.kb]);
}

function errorFunction(success) {
    var latlng = new google.maps.LatLng(37.808631, -122.474470);
    createMap(latlng);
    placeNavMarker(navLatLng);
//  addAutocomplete();
}

function placeNavMarker (latLng,image,clickCallBack) {

    if(typeof image == 'undefined')
        var image = "lodging.png";
    else{
        // dont show this marker for the geocoded location
        var image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
    }
    // this map is not always there>>>?
    var new_marker = new google.maps.Marker({
      position: latLng,
      map: map,
      icon: image
    });
    if(typeof clickCallBack == 'function')
        google.maps.event.addListener(new_marker,"click",clickCallBack);
    currentMarkers.push( new_marker );
}<commit_msg>changed show/hide flow in menu, create events for logged in menu<commit_after>markers = new Meteor.Collection("clinics");
/*

    A GEO TAGGING COMMUNITY
    []

    Allow users to join agencies and be tracked
    independently in each. Present the user a way
    to select the agency they are in after logging in.

    Agencies act as a a list of markers that cannot be modified by
    its members. Members can send their own geocoding location and timestamps to
    agencies for their personal tracking and agencies can send sms messages
    if the user opts in.

        Agency

        {
          _id: <mongo_id>,
          title: <string>,
          owner: <mongo_id:users._id>
        }

        **Field 'access' might refer to a simple string,
        integer or another mongo id inside another collection;
        but controls the visibility of the marker. Wether its public,
        private to the user (default for users) or inside of the groups
        the user has the ability to post markers to.

        Marker
        {
            _id: <mongo_id>,
            title: <>,
            owner: <users._id || agencies.id>,
            address: <string>,
            access: <**>,
            loc : [<float>,<float>]

        }

    If users have accounts at the same agency that are different
    'types' (i.e. user/marker admin) then show entries for each

    Admin accounts can add points that are viewable by everyone.

    Users can add points inside of their own account, and inside of
    groups
*/

agencies = new Meteor.Collection("agencies");

Meteor.startup(function(){
      geocoder = new google.maps.Geocoder();
});

Template.add_marker.events({
    'click input.add_marker' : function(evt,tmpl){
    /*

        ADD NEW marker
            1) Geocode Address
            2) Store data to database for marker.

    */
        var record ={};
        // use tmpl.data??
        console.log('in add marker event');
        var geo_term=tmpl.find(".marker_address").value;
        record.name = tmpl.find(".marker_name").value;
        record.type = tmpl.find(".marker_type").value;
        record.visibility = tmpl.find(".marker_type").marker_visiblity;
        console.log(record);
        if(typeof geocoder != 'undefined'){
            geocoder.geocode({'address':geo_term},function(results,status){
                results = results[0];
                if(status == google.maps.GeocoderStatus.OK){
                    map.setCenter(results.geometry.location);
                    record.loc = [results.geometry.location.jb,results.geometry.location.kb];
                    markers.insert(record);
                    lookForMarkers([results.geometry.location.jb,results.geometry.location.kb]);
                    //document.getElementById('.marker_address').value = '';
                }else{
                /*
                    Would you like to insert this marker anyway?
                */
                    alert('Could not geocode location.. please check for internet connection');
                    // show input fields..
                }
            });
            /*

                ALSO STORE A USER token of some sort so they might
                have secure access

            */

            // From here let server build the marker and update client.
            $('#marker_add').hide();

            // show the button to add another marker
            $('.markerAddShow').show();
            console.log('Its all here lets make an insert. and probably hide something...');

            // remove fields from session to avoid accidental field duplication/reentry
        }else{
            // ask to insert a location without a geocoder?
            alert('Gmaps does not seem to be loaded');

        }
    }
});

Template.map.events({
    'dblclick div#map_canvas' : function(evt,tmpl){
        placeNavMarker(map.center,undefined,function(){alert("Did you want to place a marker here?")});

    }

});

Template.markers.events({
    'click input.del_marker' : function(evt,tmpl){
        markers.remove({_id:tmpl.data._id});
        // refresh the overlays
        // eventually use SESSION variable to keep track of how to filter the markers
        // based on the user settings/permissions etc.
        lookForMarkers();

    },
    'click a.edit_marker' :function(evt,tmpl){
        console.log('edit');
        // probably use the index to look for the term eventually...
        var latlng = new google.maps.LatLng(tmpl.data.loc[0], tmpl.data.loc[1]);

        map.setCenter(latlng);
//        console.log(tmpl.data.loc[0]);
    }
});

var hideMenus = function(){

}

Template.loggedInMenu.events({
    'click .agencyAdd' : function(evt,tmpl){
        Template.loggedInMenu.rendered();
        $('div#agency_new').show();

    },
    'click .showMarkers' : function(evt,tmpl){
        Template.loggedInMenu.rendered();
        $('div#the_markers').show();

    },

    'click .markerEditShow': function(evt,tmpl){
        Template.loggedInMenu.rendered();
        $('div#marker_edit').show();
    },'click .markerAddShow': function(evt,tmpl){
        Template.loggedInMenu.rendered();
        $('div#marker_add').show();
    },
    'click .settingsShow': function(evt,tmpl){
        Template.loggedInMenu.rendered();
        console.log('showing settings');
        $('div#user_settings').show();
    },

});

Template.loggedInMenu.marker_index = function(evt,tmpl){
// get User. something to filter this find
    return markers.find({},{});
}

Template.loggedInMenu.rendered = function(evt,tmpl){

    $('div#marker_add').hide();
    $('div#user_settings').hide();
    $('div#the_markers').hide();
    $('div#marker_edit').hide();
    $('div#agency_new').hide();

}

Template.content.rendered = function(){
// IF MOBILE .. attempt to detect screen orientation/load different css to do horizontal nav
// versus vertical
  var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|iemobile|BlackBerry)/);

  //

  if(navigator.geolocation){
         navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  }else{
  // allow for editing anyway?
    alert('no geo location?');
  }
  // if no map can be created then we are working offline...
}

/* TODO
Template.settings.events({

    'click input.update' : function(evt,tmpl){

    }
});*/
/* BEGIN GMAPS

 TO Eventually support hiding /showing markers quickly in gmaps.. trying to get that to work properly..

 */
currentMarkers = [];

function lookForMarkers(theBox){
// set ceter of map to the marker you just created
    c = markers.find({}, {fields: {_id: 1}}).fetch();
    console.log(currentMarkers.length);
    //console.log(c);
    if(typeof c != 'undefined')
    c.filter(function (arr){
        // make new nat lav
        console.log(arr['loc']);
        /*
         Backwards support.. remove when releasing.. Supports the
         appropriate way of storing lat/long for geo queries.
        */
        if(typeof arr['loc'] != 'undefined'){
            var co = new google.maps.LatLng(arr['loc'][0], arr['loc'][1]);

            placeNavMarker(co,undefined,function(){alert(arr['name'] + ' ' + arr['type']);});
        }else if(typeof arr['x'] != 'undefined' && typeof arr['y'] != 'undefined'){
            var co = new google.maps.LatLng(arr['x'], arr['y']);
            placeNavMarker(co);
        }
        }
    );
}

function createMap (latLng) {
    console.log('making map');
    var mapOptions = {
        disableDoubleClick: true,
        streetViewControl: false,
        scrollwheel: false,
        zoom: 15,
        center: latLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    lookForMarkers();
};

function successFunction(success) {
  var navLatLng = new google.maps.LatLng(success.coords.latitude, success.coords.longitude);
  // annoying...
  createMap(navLatLng);
  // send it true option to use different marker
  placeNavMarker(navLatLng,true);
  lookForMarkers([navLatLng.jb,navLatLng.kb]);
}

function errorFunction(success) {
    var latlng = new google.maps.LatLng(37.808631, -122.474470);
    createMap(latlng);
    placeNavMarker(navLatLng);
//  addAutocomplete();
}

function placeNavMarker (latLng,image,clickCallBack) {

    if(typeof image == 'undefined')
        var image = "lodging.png";
    else{
        // dont show this marker for the geocoded location
        var image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
    }
    // this map is not always there>>>?
    var new_marker = new google.maps.Marker({
      position: latLng,
      map: map,
      icon: image
    });
    if(typeof clickCallBack == 'function')
        google.maps.event.addListener(new_marker,"click",clickCallBack);
    currentMarkers.push( new_marker );
}<|endoftext|>


<commit_before>import React from 'react';

export default (props) => {
  return (

  )
}
<commit_msg>google map funcitonal component<commit_after>import React from 'react';
import { GoogleMapLoader, GoogleMap } from 'react-google-maps';

export default (props) => {
  return (
    <GoogleMapLoader
      containerElement= { <div style={{height: '100%'}}> </div> }
      googleMapElement= {
          <GoogleMap defaultZoom={12} defaultCenter={{lat: props.lat, lng: props.lon}}
      }
      />
  )
}
<|endoftext|>