<commit_before>import _ from 'underscore';
import $ from 'jquery';
import Backbone from 'backbone';
import ListView from 'backbone-virtualized-listview';

import { HeaderView, FooterView } from './header-footer-view.js';

import rowTemplate from './row.jade';
import tableTemplate from './table.jade';
import columnGroupTemplate from './column-group.jade';

const STATE_OPTIONS = ['cols', 'headRows', 'bodyRows', 'footRows', 'events'];
const MODEL_OPTIONS = ['cols', 'headRows', 'footRows'];
const ITEMS_OPTIONS = ['bodyRows'];
const HEADER_OPTIONS = ['cols', 'headRows', 'events'];

function getListTemplate(isStickyHeader) {
  const style = {
    'border-collapse': 'collapse',
    'margin': 0,
  };

  const stickyHeader = isStickyHeader ? {} : null;

  if (stickyHeader) {
    style['table-layout'] = 'fixed';
    stickyHeader.style = _.extend({ position: 'relative' }, style);
  }

  return model => tableTemplate({
    style,
    stickyHeader,
    header: { rows: model.headRows },
    footer: { rows: model.footRows },
    cols: model.cols,
  });
}

function getItems({ bodyRows }) {
  return {
    length: bodyRows.length,
    slice(start, stop) {
      return _.map(bodyRows.slice(start, stop), row => ({ row }))
    },
  };
}

export class TableView extends Backbone.View {
  initialize({
    viewport,
    virtualized = false,
    stickyHeader = false,
  }) {
    this._props = {
      viewport,
      virtualized,
      stickyHeader,
    };

    this._state = {
      cols: [],
      headRows: [],
      bodyRows: [],
      footRows: [],
      events: {},
    };

    this._listView = new ListView({
      virtualized,
      viewport,
    }).set({
      listTemplate: getListTemplate(Boolean(stickyHeader)),
      itemTemplate: rowTemplate,
    });

    this._headerView = new HeaderView({ tableView: this });
    this._footerView = new FooterView({ tableView: this });
  }

  set(state = {}, callback = _.noop) {
    const isSet = key => !_.isUndefined(state[key]);
    const listState = {};

    _.extend(this._state, _.pick(state, STATE_OPTIONS));

    if (_.some(ITEMS_OPTIONS, isSet)) {
      listState.items = getItems(_.pick(this._state, ITEMS_OPTIONS));
    }
    if (isSet('events')) {
      listState.events = this._state.events;
    }

    this._listView.set(listState, callback);

    if (this.$colgroup) {
      this.$colgroup.html(columnGroupTemplate(this._state));
    }

    if (this._headerView) {
      this._headerView.redraw();
    }

    if (this.$stickyHeader) {
      this._adjust();
    }

    return this;
  }

  render(callback = _.noop) {
    this.$el.html(this._listView.render(() => {
      this.$colgroup = this.$('colgroup.column-group');
      this.$colgroup.html(columnGroupTemplate(this._state));

      this._headerView.setElement(this.$('thead.header'));
      this._headerView.render();

      this.$tableContainer = this.$('.table-container');

      if (this._props.stickyHeader) {
        this.$stickyHeader = this.$('.sticky-header');
        this._listView.viewport.on('change', () => this._adjust());
        this._adjust();
      }
      callback();
    }).el);

    return this;
  }

  _adjust() {
    let topVP = this._listView.viewport.getMetrics().outer.top;
    let offset = _.result(this._props.stickyHeader, 'offset', 0);
    let topCur = this.$tableContainer.get(0).getBoundingClientRect().top;

    this.$stickyHeader.css({ top: Math.max(topVP + offset - topCur, 0) });
  }

  remove() {
    this._headerView.remove();
    this._listView.remove();
    super.remove();
  }

  scrollToItem(...args) {
    this._listView.scrollToItem(...args);
  }

  indexOfElement(el) {
    const $elTr = this._listView.$(el).closest('tr', this._listView.$container);
    if ($elTr.length > 0) {
      return $elTr.index() + this._listView.indexFirst;
    }
    return null;
  }

}

<commit_msg>fix stickyheader z-index<commit_after>import _ from 'underscore';
import $ from 'jquery';
import Backbone from 'backbone';
import ListView from 'backbone-virtualized-listview';

import { HeaderView, FooterView } from './header-footer-view.js';

import rowTemplate from './row.jade';
import tableTemplate from './table.jade';
import columnGroupTemplate from './column-group.jade';

const STATE_OPTIONS = ['cols', 'headRows', 'bodyRows', 'footRows', 'events'];
const MODEL_OPTIONS = ['cols', 'headRows', 'footRows'];
const ITEMS_OPTIONS = ['bodyRows'];
const HEADER_OPTIONS = ['cols', 'headRows', 'events'];

function getListTemplate(isStickyHeader) {
  const style = {
    'border-collapse': 'collapse',
    'margin': 0,
  };

  const stickyHeader = isStickyHeader ? {} : null;

  if (stickyHeader) {
    style['table-layout'] = 'fixed';
    stickyHeader.style = _.extend({
      'position': 'relative',
      'z-index': 100,
    }, style);
  }

  return model => tableTemplate({
    style,
    stickyHeader,
    header: { rows: model.headRows },
    footer: { rows: model.footRows },
    cols: model.cols,
  });
}

function getItems({ bodyRows }) {
  return {
    length: bodyRows.length,
    slice(start, stop) {
      return _.map(bodyRows.slice(start, stop), row => ({ row }))
    },
  };
}

export class TableView extends Backbone.View {
  initialize({
    viewport,
    virtualized = false,
    stickyHeader = false,
  }) {
    this._props = {
      viewport,
      virtualized,
      stickyHeader,
    };

    this._state = {
      cols: [],
      headRows: [],
      bodyRows: [],
      footRows: [],
      events: {},
    };

    this._listView = new ListView({
      virtualized,
      viewport,
    }).set({
      listTemplate: getListTemplate(Boolean(stickyHeader)),
      itemTemplate: rowTemplate,
    });

    this._headerView = new HeaderView({ tableView: this });
    this._footerView = new FooterView({ tableView: this });
  }

  set(state = {}, callback = _.noop) {
    const isSet = key => !_.isUndefined(state[key]);
    const listState = {};

    _.extend(this._state, _.pick(state, STATE_OPTIONS));

    if (_.some(ITEMS_OPTIONS, isSet)) {
      listState.items = getItems(_.pick(this._state, ITEMS_OPTIONS));
    }
    if (isSet('events')) {
      listState.events = this._state.events;
    }

    this._listView.set(listState, callback);

    if (this.$colgroup) {
      this.$colgroup.html(columnGroupTemplate(this._state));
    }

    if (this._headerView) {
      this._headerView.redraw();
    }

    if (this.$stickyHeader) {
      this._adjust();
    }

    return this;
  }

  render(callback = _.noop) {
    this.$el.html(this._listView.render(() => {
      this.$colgroup = this.$('colgroup.column-group');
      this.$colgroup.html(columnGroupTemplate(this._state));

      this._headerView.setElement(this.$('thead.header'));
      this._headerView.render();

      this.$tableContainer = this.$('.table-container');

      if (this._props.stickyHeader) {
        this.$stickyHeader = this.$('.sticky-header');
        this._listView.viewport.on('change', () => this._adjust());
        this._adjust();
      }
      callback();
    }).el);

    return this;
  }

  _adjust() {
    let topVP = this._listView.viewport.getMetrics().outer.top;
    let offset = _.result(this._props.stickyHeader, 'offset', 0);
    let topCur = this.$tableContainer.get(0).getBoundingClientRect().top;

    this.$stickyHeader.css({ top: Math.max(topVP + offset - topCur, 0) });
  }

  remove() {
    this._headerView.remove();
    this._listView.remove();
    super.remove();
  }

  scrollToItem(...args) {
    this._listView.scrollToItem(...args);
  }

  indexOfElement(el) {
    const $elTr = this._listView.$(el).closest('tr', this._listView.$container);
    if ($elTr.length > 0) {
      return $elTr.index() + this._listView.indexFirst;
    }
    return null;
  }

}

<|endoftext|>


<commit_before>/**
 * Main entry point for chamel
 */

module.exports = {
    AppBar: require('./AppBar.jsx'),
    //AppCanvas: require('./app-canvas'),
    Checkbox: require('./Checkbox.jsx'),
    DatePicker: require('./date-picker/DatePicker.jsx'),
    Dialog: require('./Dialog.jsx'),
    DialogWindow: require('./DialogWindow.jsx'),
    DropDownIcon: require('./DropDownIcon.jsx'),
    DropDownMenu: require('./DropDownMenu.jsx'),
    Editor: require('./editor/Editor.jsx'),
    EnhancedButton: require('./EnhancedButton.jsx'),
    FlatButton: require('./FlatButton.jsx'),
    //FloatingActionButton: require('./floating-action-button'),
    FontIcon: require('./FontIcon.jsx'),
    IconButton: require('./IconButton.jsx'),
    //Input: require('./Input'),
    LeftNav: require('./LeftNav.jsx'),
    Menu: require('./menu/Menu.jsx'),
    MenuItem: require('./menu/MenuItem.jsx'),
    Mixins: {
        Classable: require('./mixins/classable.jsx'),
        ClickAwayable: require('./mixins/ClickAwayable.jsx'),
        WindowListenable: require('./mixins/WindowListenable.jsx')
    },
    Paper: require('./Paper.jsx'),
    RadioButton: require('./RadioButton.jsx'),
    RadioButtonGroup: require('./RadioButtonGroup.jsx'),
    RaisedButton: require('./RaisedButton.jsx'),
    LinearProgress: require('./progress/LinearProgress.jsx'),
    //Slider: require('./slider'),
    SvgIcon: require('./svg-icons/svg-icon.jsx'),
    Icons: {
        NavigationMenu: require('./svg-icons/navigation-menu.jsx'),
        NavigationChevronLeft: require('./svg-icons/navigation-chevron-left.jsx'),
        NavigationChevronRight: require('./svg-icons/navigation-chevron-right.jsx')
    },
    Tab: require('./tabs/Tab.jsx'),
    Tabs: require('./tabs/Tabs.jsx'),
    Toggle: require('./Toggle.jsx'),
    Snackbar: require('./Snackbar.jsx'),
    TextField: require('./TextField.jsx'),
    TextFieldRich: require('./TextFieldRich.jsx'),
    Toolbar: require('./toolbar/Toolbar.jsx'),
    ToolbarGroup: require('./toolbar/ToolbarGroup.jsx'),
    //Tooltip: require('./tooltip'),
    Utils: {
        CssEvent: require('./utils/CssEvent.jsx'),
        Dom: require('./utils/Dom.jsx'),
        Events: require('./utils/Events.jsx'),
        KeyCode: require('./utils/KeyCode.jsx'),
        KeyLine: require('./utils/KeyLine.jsx')
    }
};
<commit_msg>Added callout in main.js<commit_after>/**
 * Main entry point for chamel
 */

module.exports = {
    AppBar: require('./AppBar.jsx'),
    //AppCanvas: require('./app-canvas'),
    Callout: require('./Callout.jsx'),
    Checkbox: require('./Checkbox.jsx'),
    DatePicker: require('./date-picker/DatePicker.jsx'),
    Dialog: require('./Dialog.jsx'),
    DialogWindow: require('./DialogWindow.jsx'),
    DropDownIcon: require('./DropDownIcon.jsx'),
    DropDownMenu: require('./DropDownMenu.jsx'),
    Editor: require('./editor/Editor.jsx'),
    EnhancedButton: require('./EnhancedButton.jsx'),
    FlatButton: require('./FlatButton.jsx'),
    //FloatingActionButton: require('./floating-action-button'),
    FontIcon: require('./FontIcon.jsx'),
    IconButton: require('./IconButton.jsx'),
    //Input: require('./Input'),
    LeftNav: require('./LeftNav.jsx'),
    Menu: require('./menu/Menu.jsx'),
    MenuItem: require('./menu/MenuItem.jsx'),
    Mixins: {
        Classable: require('./mixins/classable.jsx'),
        ClickAwayable: require('./mixins/ClickAwayable.jsx'),
        WindowListenable: require('./mixins/WindowListenable.jsx')
    },
    Paper: require('./Paper.jsx'),
    RadioButton: require('./RadioButton.jsx'),
    RadioButtonGroup: require('./RadioButtonGroup.jsx'),
    RaisedButton: require('./RaisedButton.jsx'),
    LinearProgress: require('./progress/LinearProgress.jsx'),
    //Slider: require('./slider'),
    SvgIcon: require('./svg-icons/svg-icon.jsx'),
    Icons: {
        NavigationMenu: require('./svg-icons/navigation-menu.jsx'),
        NavigationChevronLeft: require('./svg-icons/navigation-chevron-left.jsx'),
        NavigationChevronRight: require('./svg-icons/navigation-chevron-right.jsx')
    },
    Tab: require('./tabs/Tab.jsx'),
    Tabs: require('./tabs/Tabs.jsx'),
    Toggle: require('./Toggle.jsx'),
    Snackbar: require('./Snackbar.jsx'),
    TextField: require('./TextField.jsx'),
    TextFieldRich: require('./TextFieldRich.jsx'),
    Toolbar: require('./toolbar/Toolbar.jsx'),
    ToolbarGroup: require('./toolbar/ToolbarGroup.jsx'),
    //Tooltip: require('./tooltip'),
    Utils: {
        CssEvent: require('./utils/CssEvent.jsx'),
        Dom: require('./utils/Dom.jsx'),
        Events: require('./utils/Events.jsx'),
        KeyCode: require('./utils/KeyCode.jsx'),
        KeyLine: require('./utils/KeyLine.jsx')
    }
};
<|endoftext|>


<commit_before>import * as core from 'core-js';
import {RouteRecognizer} from 'aurelia-route-recognizer';
import {join} from 'aurelia-path';
import {Container} from 'aurelia-dependency-injection';
import {History} from 'aurelia-history';
import {NavigationContext} from './navigation-context';
import {NavigationInstruction} from './navigation-instruction';
import {NavModel} from './nav-model';
import {RouterConfiguration} from './router-configuration';
import {
  processPotential,
  normalizeAbsolutePath,
  createRootedPath,
  resolveUrl} from './util';
import {RouteConfig} from './interfaces';

/**
* The primary class responsible for handling routing and navigation.
*
* @class Router
* @constructor
*/
export class Router {
  container: Container;
  history: History;
  viewPorts: Object = {};
  fallbackOrder: number = 100;
  recognizer: RouteRecognizer = new RouteRecognizer();
  childRecognizer: RouteRecognizer = new RouteRecognizer();
  routes: RouteConfig[] = [];

  /**
  * The [[Router]]'s current base URL, typically based on the [[Router.currentInstruction]].
  */
  baseUrl: string = '';

  /**
  * True if the [[Router]] has been configured.
  */
  isConfigured: boolean = false;

  /**
  * True if the [[Router]] is currently processing a navigation.
  */
  isNavigating: boolean = false;

  /**
  * The navigation models for routes that specified [[RouteConfig.nav]].
  */
  navigation: NavModel[] = [];

  /**
  * The currently active navigation instruction.
  */
  currentInstruction: NavigationInstruction;

  /**
  * @param container The [[Container]] to use when child routers.
  * @param history The [[History]] implementation to delegate navigation requests to.
  */
  constructor(container, history) {
    this.container = container;
    this.history = history;
    this._configuredPromise = new Promise((resolve => {
      this._resolveConfiguredPromise = resolve;
    }));
    this.reset();
  }

  /**
  * Gets a valid undicating whether or not this [[Router]] is the root in the router tree. I.e., it has no parent.
  */
  get isRoot() {
    return false;
  }

  /**
  * Registers a viewPort to be used as a rendering target for activated routes.
  *
  * @param viewPort The viewPort.
  * @param name The name of the viewPort. 'default' if unspecified.
  */
  registerViewPort(viewPort:Object, name?:string) {
    name = name || 'default';
    this.viewPorts[name] = viewPort;
  }

  /**
  * Returns a Promise that resolves when the router is configured.
  */
  ensureConfigured():Promise<void> {
    return this._configuredPromise;
  }

  /**
  * Configures the router.
  *
  * @param callbackOrConfig The [[RouterConfiguration]] or a callback that takes a [[RouterConfiguration]].
  * @chainable
  */
  configure(callbackOrConfig:RouterConfiguration|((config:RouterConfiguration) => RouterConfiguration)):Router {
    this.isConfigured = true;

    if (typeof callbackOrConfig == 'function') {
      var config = new RouterConfiguration();
      callbackOrConfig(config);
      config.exportToRouter(this);
    } else {
      callbackOrConfig.exportToRouter(this);
    }

    this.isConfigured = true;
    this._resolveConfiguredPromise();

    return this;
  }

  /**
  * Navigates to a new location.
  *
  * @param fragment The URL fragment to use as the navigation destination.
  * @param options The navigation options.
  */
  navigate(fragment:string, options?:Object):boolean {
    if (!this.isConfigured && this.parent) {
      return this.parent.navigate(fragment, options);
    }

    return this.history.navigate(resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options);
  }

  /**
  * Navigates to a new location corresponding to the route and params specified. Equivallent to [[Router.generate]] followed
  * by [[Router.navigate]].
  *
  * @param route The name of the route to use when generating the navigation location.
  * @param params The route parameters to be used when populating the route pattern.
  * @param options The navigation options.
  */
  navigateToRoute(route:string, params?:Object, options?:Object):boolean {
    let path = this.generate(route, params);
    return this.navigate(path, options);
  }

  /**
  * Navigates back to the most recent location in history.
  */
  navigateBack() {
    this.history.navigateBack();
  }

  /**
   * Creates a child router of the current router.
   *
   * @param container The [[Container]] to provide to the child router. Uses the current [[Router]]'s [[Container]] if unspecified.
   * @returns {Router} The new child Router.
   */
  createChild(container?:Container):Router {
    var childRouter = new Router(container || this.container.createChild(), this.history);
    childRouter.parent = this;
    return childRouter;
  }

  /**
  * Generates a URL fragment matching the specified route pattern.
  *
  * @param name The name of the route whose pattern should be used to generate the fragment.
  * @param params The route params to be used to populate the route pattern.
  * @returns {string} A string containing the generated URL fragment.
  */
  generate(name:string, params?:Object):string {
    let hasRoute = this.recognizer.hasRoute(name);
    if((!this.isConfigured || !hasRoute) && this.parent){
      return this.parent.generate(name, params);
    }

    if (!hasRoute) {
      throw new Error(`A route with name '${name}' could not be found. Check that \`name: '${name}'\` was specified in the route's config.`);
    }

    let path = this.recognizer.generate(name, params);
    return createRootedPath(path, this.baseUrl, this.history._hasPushState);
  }

  /**
  * Creates a [[NavModel]] for the specified route config.
  *
  * @param config The route config.
  */
  createNavModel(config:RouteConfig):NavModel {
    let navModel = new NavModel(this, 'href' in config ? config.href : config.route);
    navModel.title = config.title;
    navModel.order = config.nav;
    navModel.href = config.href;
    navModel.settings = config.settings;
    navModel.config = config;

    return navModel;
  }

  /**
  * Registers a new route with the router.
  *
  * @param config The [[RouteConfig]].
  * @param navModel The [[NavModel]] to use for the route. May be omitted for single-pattern routes.
  */
  addRoute(config:RouteConfig, navModel?:NavModel) {
    validateRouteConfig(config);

    if (!('viewPorts' in config) && !config.navigationStrategy) {
      config.viewPorts = {
        'default': {
          moduleId: config.moduleId,
          view: config.view
        }
      };
    }

    if (!navModel) {
      navModel = this.createNavModel(config);
    }

    this.routes.push(config);

    let path = config.route;
    if (path.charAt(0) === '/') {
      path = path.substr(1);
    }

    let state = this.recognizer.add({path: path, handler: config});

    if (path) {
      let withChild, settings = config.settings;
      delete config.settings;
      withChild = JSON.parse(JSON.stringify(config));
      config.settings = settings;
      withChild.route = `${path}/*childRoute`;
      withChild.hasChildRouter = true;
      this.childRecognizer.add({
        path: withChild.route,
        handler: withChild
      });

      withChild.navModel = navModel;
      withChild.settings = config.settings;
    }

    config.navModel = navModel;

    if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) {
      if ((!navModel.href && navModel.href != '') && (state.types.dynamics || state.types.stars)) {
          throw new Error('Invalid route config: dynamic routes must specify an href to be included in the navigation model.');
      }

      if (typeof navModel.order != 'number') {
        navModel.order = ++this.fallbackOrder;
      }

      this.navigation.push(navModel);
      this.navigation = this.navigation.sort((a, b) => a.order - b.order);
    }
  }

  /**
  * Gets a value indicating whether or not this [[Router]] or one of its ancestors has a route registered with the specified name.
  *
  * @param name The name of the route to check.
  * @returns {boolean}
  */
  hasRoute(name:string):boolean {
    return !!(this.recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name));
  }

  /**
  * Gets a value indicating whether or not this [[Router]] has a route registered with the specified name.
  *
  * @param name The name of the route to check.
  * @returns {boolean}
  */
  hasOwnRoute(name:string):boolean {
    return this.recognizer.hasRoute(name);
  }

  /**
  * Register a handler to use when the incoming URL fragment doesn't match any registered routes.
  *
  * @param config The moduleId, or a function that selects the moduleId, or a [[RouteConfig]].
  */
  handleUnknownRoutes(config?:string|Function|RouteConfig) {
    var callback = instruction => new Promise((resolve, reject) => {
      function done(inst){
        inst = inst || instruction;
        inst.config.route = inst.params.path;
        resolve(inst);
      }

      if (!config) {
        instruction.config.moduleId = instruction.fragment;
        done(instruction);
      } else if (typeof config == 'string') {
        instruction.config.moduleId = config;
        done(instruction);
      } else if (typeof config == 'function') {
        processPotential(config(instruction), done, reject);
      } else {
        instruction.config = config;
        done(instruction);
      }
    });

    this.catchAllHandler = callback;
  }

  /**
  * Updates the document title using the current navigation instruction.
  */
  updateTitle() {
    if (this.parent) {
      return this.parent.updateTitle();
    }

    this.currentInstruction.navigationContext.updateTitle();
  }

  /**
  * Resets the Router to its original unconfigured state.
  */
  reset() {
    this.fallbackOrder = 100;
    this.recognizer = new RouteRecognizer();
    this.childRecognizer = new RouteRecognizer();
    this.routes = [];
    this.isNavigating = false;
    this.navigation = [];
    this.isConfigured = false;
  }

  refreshBaseUrl() {
    if (this.parent) {
      var baseUrl = this.parent.currentInstruction.getBaseUrl();
      this.baseUrl = this.parent.baseUrl + baseUrl;
    }
  }

  refreshNavigation() {
    var nav = this.navigation;

    for(var i = 0, length = nav.length; i < length; i++) {
      var current = nav[i];
      current.href = createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState);
    }
  }

  createNavigationInstruction(url:string = '', parentInstruction?:NavigationInstruction = null):Promise<NavigationInstruction> {
    let fragment = url;
    let queryString = '';

    let queryIndex = url.indexOf('?');
    if (queryIndex != -1) {
      fragment = url.substr(0, queryIndex);
      queryString = url.substr(queryIndex + 1);
    }

    let results = this.recognizer.recognize(url);
    if (!results || !results.length) {
      results = this.childRecognizer.recognize(url);
    }

    if((!results || !results.length) && this.catchAllHandler) {
      results = [{
        config: {
          navModel: {}
        },
        handler: this.catchAllHandler,
        params: {
          path: fragment
        }
      }];
    }

    if (results && results.length) {
      let first = results[0];
      let instruction = new NavigationInstruction(
        fragment,
        queryString,
        first.params,
        first.queryParams || results.queryParams,
        first.config || first.handler,
        parentInstruction
        );

      if (typeof first.handler === 'function') {
        return evaluateNavigationStrategy(instruction, first.handler, first);
      } else if(first.handler && 'navigationStrategy' in first.handler){
        return evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler);
      }

      return Promise.resolve(instruction);
    }

    return Promise.reject(new Error(`Route not found: ${url}`));
  }

  createNavigationContext(instruction:NavigationInstruction):NavigationContext {
    instruction.navigationContext = new NavigationContext(this, instruction);
    return instruction.navigationContext;
  }
}

function validateRouteConfig(config:Object) {
  if (typeof config !== 'object') {
    throw new Error('Invalid Route Config');
  }

  if (typeof config.route !== 'string') {
    throw new Error('Invalid Route Config: You must specify a route pattern.');
  }

  if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {
    throw new Error('Invalid Route Config: You must specify a moduleId, redirect, navigationStrategy, or viewPorts.')
  }
}

function evaluateNavigationStrategy(instruction:NavigationInstruction, evaluator:Function, context:Object): Promise<NavigationInstruction> {
  return Promise.resolve(evaluator.call(context, instruction)).then(() => {
    if (!('viewPorts' in instruction.config)) {
      instruction.config.viewPorts = {
        'default': {
          moduleId: instruction.config.moduleId
        }
      };
    }

    return instruction;
  });
}
<commit_msg>docs(router): fix typo in doc comment<commit_after>import * as core from 'core-js';
import {RouteRecognizer} from 'aurelia-route-recognizer';
import {join} from 'aurelia-path';
import {Container} from 'aurelia-dependency-injection';
import {History} from 'aurelia-history';
import {NavigationContext} from './navigation-context';
import {NavigationInstruction} from './navigation-instruction';
import {NavModel} from './nav-model';
import {RouterConfiguration} from './router-configuration';
import {
  processPotential,
  normalizeAbsolutePath,
  createRootedPath,
  resolveUrl} from './util';
import {RouteConfig} from './interfaces';

/**
* The primary class responsible for handling routing and navigation.
*
* @class Router
* @constructor
*/
export class Router {
  container: Container;
  history: History;
  viewPorts: Object = {};
  fallbackOrder: number = 100;
  recognizer: RouteRecognizer = new RouteRecognizer();
  childRecognizer: RouteRecognizer = new RouteRecognizer();
  routes: RouteConfig[] = [];

  /**
  * The [[Router]]'s current base URL, typically based on the [[Router.currentInstruction]].
  */
  baseUrl: string = '';

  /**
  * True if the [[Router]] has been configured.
  */
  isConfigured: boolean = false;

  /**
  * True if the [[Router]] is currently processing a navigation.
  */
  isNavigating: boolean = false;

  /**
  * The navigation models for routes that specified [[RouteConfig.nav]].
  */
  navigation: NavModel[] = [];

  /**
  * The currently active navigation instruction.
  */
  currentInstruction: NavigationInstruction;

  /**
  * @param container The [[Container]] to use when child routers.
  * @param history The [[History]] implementation to delegate navigation requests to.
  */
  constructor(container, history) {
    this.container = container;
    this.history = history;
    this._configuredPromise = new Promise((resolve => {
      this._resolveConfiguredPromise = resolve;
    }));
    this.reset();
  }

  /**
  * Gets a valid indicating whether or not this [[Router]] is the root in the router tree. I.e., it has no parent.
  */
  get isRoot() {
    return false;
  }

  /**
  * Registers a viewPort to be used as a rendering target for activated routes.
  *
  * @param viewPort The viewPort.
  * @param name The name of the viewPort. 'default' if unspecified.
  */
  registerViewPort(viewPort:Object, name?:string) {
    name = name || 'default';
    this.viewPorts[name] = viewPort;
  }

  /**
  * Returns a Promise that resolves when the router is configured.
  */
  ensureConfigured():Promise<void> {
    return this._configuredPromise;
  }

  /**
  * Configures the router.
  *
  * @param callbackOrConfig The [[RouterConfiguration]] or a callback that takes a [[RouterConfiguration]].
  * @chainable
  */
  configure(callbackOrConfig:RouterConfiguration|((config:RouterConfiguration) => RouterConfiguration)):Router {
    this.isConfigured = true;

    if (typeof callbackOrConfig == 'function') {
      var config = new RouterConfiguration();
      callbackOrConfig(config);
      config.exportToRouter(this);
    } else {
      callbackOrConfig.exportToRouter(this);
    }

    this.isConfigured = true;
    this._resolveConfiguredPromise();

    return this;
  }

  /**
  * Navigates to a new location.
  *
  * @param fragment The URL fragment to use as the navigation destination.
  * @param options The navigation options.
  */
  navigate(fragment:string, options?:Object):boolean {
    if (!this.isConfigured && this.parent) {
      return this.parent.navigate(fragment, options);
    }

    return this.history.navigate(resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options);
  }

  /**
  * Navigates to a new location corresponding to the route and params specified. Equivallent to [[Router.generate]] followed
  * by [[Router.navigate]].
  *
  * @param route The name of the route to use when generating the navigation location.
  * @param params The route parameters to be used when populating the route pattern.
  * @param options The navigation options.
  */
  navigateToRoute(route:string, params?:Object, options?:Object):boolean {
    let path = this.generate(route, params);
    return this.navigate(path, options);
  }

  /**
  * Navigates back to the most recent location in history.
  */
  navigateBack() {
    this.history.navigateBack();
  }

  /**
   * Creates a child router of the current router.
   *
   * @param container The [[Container]] to provide to the child router. Uses the current [[Router]]'s [[Container]] if unspecified.
   * @returns {Router} The new child Router.
   */
  createChild(container?:Container):Router {
    var childRouter = new Router(container || this.container.createChild(), this.history);
    childRouter.parent = this;
    return childRouter;
  }

  /**
  * Generates a URL fragment matching the specified route pattern.
  *
  * @param name The name of the route whose pattern should be used to generate the fragment.
  * @param params The route params to be used to populate the route pattern.
  * @returns {string} A string containing the generated URL fragment.
  */
  generate(name:string, params?:Object):string {
    let hasRoute = this.recognizer.hasRoute(name);
    if((!this.isConfigured || !hasRoute) && this.parent){
      return this.parent.generate(name, params);
    }

    if (!hasRoute) {
      throw new Error(`A route with name '${name}' could not be found. Check that \`name: '${name}'\` was specified in the route's config.`);
    }

    let path = this.recognizer.generate(name, params);
    return createRootedPath(path, this.baseUrl, this.history._hasPushState);
  }

  /**
  * Creates a [[NavModel]] for the specified route config.
  *
  * @param config The route config.
  */
  createNavModel(config:RouteConfig):NavModel {
    let navModel = new NavModel(this, 'href' in config ? config.href : config.route);
    navModel.title = config.title;
    navModel.order = config.nav;
    navModel.href = config.href;
    navModel.settings = config.settings;
    navModel.config = config;

    return navModel;
  }

  /**
  * Registers a new route with the router.
  *
  * @param config The [[RouteConfig]].
  * @param navModel The [[NavModel]] to use for the route. May be omitted for single-pattern routes.
  */
  addRoute(config:RouteConfig, navModel?:NavModel) {
    validateRouteConfig(config);

    if (!('viewPorts' in config) && !config.navigationStrategy) {
      config.viewPorts = {
        'default': {
          moduleId: config.moduleId,
          view: config.view
        }
      };
    }

    if (!navModel) {
      navModel = this.createNavModel(config);
    }

    this.routes.push(config);

    let path = config.route;
    if (path.charAt(0) === '/') {
      path = path.substr(1);
    }

    let state = this.recognizer.add({path: path, handler: config});

    if (path) {
      let withChild, settings = config.settings;
      delete config.settings;
      withChild = JSON.parse(JSON.stringify(config));
      config.settings = settings;
      withChild.route = `${path}/*childRoute`;
      withChild.hasChildRouter = true;
      this.childRecognizer.add({
        path: withChild.route,
        handler: withChild
      });

      withChild.navModel = navModel;
      withChild.settings = config.settings;
    }

    config.navModel = navModel;

    if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) {
      if ((!navModel.href && navModel.href != '') && (state.types.dynamics || state.types.stars)) {
          throw new Error('Invalid route config: dynamic routes must specify an href to be included in the navigation model.');
      }

      if (typeof navModel.order != 'number') {
        navModel.order = ++this.fallbackOrder;
      }

      this.navigation.push(navModel);
      this.navigation = this.navigation.sort((a, b) => a.order - b.order);
    }
  }

  /**
  * Gets a value indicating whether or not this [[Router]] or one of its ancestors has a route registered with the specified name.
  *
  * @param name The name of the route to check.
  * @returns {boolean}
  */
  hasRoute(name:string):boolean {
    return !!(this.recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name));
  }

  /**
  * Gets a value indicating whether or not this [[Router]] has a route registered with the specified name.
  *
  * @param name The name of the route to check.
  * @returns {boolean}
  */
  hasOwnRoute(name:string):boolean {
    return this.recognizer.hasRoute(name);
  }

  /**
  * Register a handler to use when the incoming URL fragment doesn't match any registered routes.
  *
  * @param config The moduleId, or a function that selects the moduleId, or a [[RouteConfig]].
  */
  handleUnknownRoutes(config?:string|Function|RouteConfig) {
    var callback = instruction => new Promise((resolve, reject) => {
      function done(inst){
        inst = inst || instruction;
        inst.config.route = inst.params.path;
        resolve(inst);
      }

      if (!config) {
        instruction.config.moduleId = instruction.fragment;
        done(instruction);
      } else if (typeof config == 'string') {
        instruction.config.moduleId = config;
        done(instruction);
      } else if (typeof config == 'function') {
        processPotential(config(instruction), done, reject);
      } else {
        instruction.config = config;
        done(instruction);
      }
    });

    this.catchAllHandler = callback;
  }

  /**
  * Updates the document title using the current navigation instruction.
  */
  updateTitle() {
    if (this.parent) {
      return this.parent.updateTitle();
    }

    this.currentInstruction.navigationContext.updateTitle();
  }

  /**
  * Resets the Router to its original unconfigured state.
  */
  reset() {
    this.fallbackOrder = 100;
    this.recognizer = new RouteRecognizer();
    this.childRecognizer = new RouteRecognizer();
    this.routes = [];
    this.isNavigating = false;
    this.navigation = [];
    this.isConfigured = false;
  }

  refreshBaseUrl() {
    if (this.parent) {
      var baseUrl = this.parent.currentInstruction.getBaseUrl();
      this.baseUrl = this.parent.baseUrl + baseUrl;
    }
  }

  refreshNavigation() {
    var nav = this.navigation;

    for(var i = 0, length = nav.length; i < length; i++) {
      var current = nav[i];
      current.href = createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState);
    }
  }

  createNavigationInstruction(url:string = '', parentInstruction?:NavigationInstruction = null):Promise<NavigationInstruction> {
    let fragment = url;
    let queryString = '';

    let queryIndex = url.indexOf('?');
    if (queryIndex != -1) {
      fragment = url.substr(0, queryIndex);
      queryString = url.substr(queryIndex + 1);
    }

    let results = this.recognizer.recognize(url);
    if (!results || !results.length) {
      results = this.childRecognizer.recognize(url);
    }

    if((!results || !results.length) && this.catchAllHandler) {
      results = [{
        config: {
          navModel: {}
        },
        handler: this.catchAllHandler,
        params: {
          path: fragment
        }
      }];
    }

    if (results && results.length) {
      let first = results[0];
      let instruction = new NavigationInstruction(
        fragment,
        queryString,
        first.params,
        first.queryParams || results.queryParams,
        first.config || first.handler,
        parentInstruction
        );

      if (typeof first.handler === 'function') {
        return evaluateNavigationStrategy(instruction, first.handler, first);
      } else if(first.handler && 'navigationStrategy' in first.handler){
        return evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler);
      }

      return Promise.resolve(instruction);
    }

    return Promise.reject(new Error(`Route not found: ${url}`));
  }

  createNavigationContext(instruction:NavigationInstruction):NavigationContext {
    instruction.navigationContext = new NavigationContext(this, instruction);
    return instruction.navigationContext;
  }
}

function validateRouteConfig(config:Object) {
  if (typeof config !== 'object') {
    throw new Error('Invalid Route Config');
  }

  if (typeof config.route !== 'string') {
    throw new Error('Invalid Route Config: You must specify a route pattern.');
  }

  if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {
    throw new Error('Invalid Route Config: You must specify a moduleId, redirect, navigationStrategy, or viewPorts.')
  }
}

function evaluateNavigationStrategy(instruction:NavigationInstruction, evaluator:Function, context:Object): Promise<NavigationInstruction> {
  return Promise.resolve(evaluator.call(context, instruction)).then(() => {
    if (!('viewPorts' in instruction.config)) {
      instruction.config.viewPorts = {
        'default': {
          moduleId: instruction.config.moduleId
        }
      };
    }

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


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { Route } from 'react-router';
import App from './handlers/app';

const routes = (
  <Route path="/" component={App}></Route>
);

export default routes;<commit_msg>react router only controls logged in users<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { Route } from 'react-router';
import App from './handlers/app';

const routes = (
  <Route path='app' component={App} />
);

export default routes;<|endoftext|>


<commit_before>var SpanSummary = function() {

  var html = `
    Spans

Nothing to see here.  Move along.

            Start
            Finish
            Project
            Tasks
            Hours
            Time
            Actions

`;

  var spanTemplate = `

`;

  var spansContainer;
  var nonContentContainer;
  var timeFormatter;
  var roundDecimal;
  var padder;
  var spanMap = {};

  var init = function() {
    getDependencies();
    build();
    addBehavior();
  };

  var getDependencies = function() {
    timeFormatter = new TimeFormatter12Hr();
    roundDecimal = Rounder.roundDecimal;
    padder = new Padder();
  };

  var build = function() {
    var renderTo = jQuery('#SpanSummary');
    renderTo.html(html);
    spansContainer = renderTo.find('tbody');
    noContentContainer = renderTo.find('.no_content_container');
  };

  var addBehavior = function() {
    App.dispatcher.subscribe('DATE_CHANGED', onDateChanged);
    App.dispatcher.subscribe('SPAN_SAVED', onSpanSaved);
    App.dispatcher.subscribe('SPAN_DELETED', onSpanDeleted);
  };

  var onDateChanged = function(data) {
    noContentContainer.show();
    spansContainer.empty();
    spanMap = {};
    jQuery.each(data.spans, function(index, span) {
      addSpan(span)
    });
  };

  var onSpanSaved = function(data) {
    var span = data.span;
    var container = spanMap[span.guid];
    if (container)
      populateSpan(span, container);
    else
      addSpan(span);
    spansContainer.find('.selected').removeClass('selected');
  };

  var addSpan = function(span) {
    noContentContainer.hide();
    var container = jQuery(spanTemplate).prependTo(spansContainer);
    spanMap[span.guid] = container;
    populateSpan(span, container);
  };

  var populateSpan = function(span, container) {
    var elapsed = (span.finish - span.start)/1000/60/60;
    var elapsedDecimal = roundDecimal(elapsed, 2)
    var elapsedHours = Math.floor(elapsed);
    var elapsedMinutes = padder.twoDigit(Math.floor((elapsed % 1) * 60));

    container.find('.edit').data('guid', span.guid).click(editSpan);
    container.find('.delete').data('guid', span.guid).click(deleteSpan);
    container.find('.repeat').data('guid', span.guid).click(repeatSpan);

    container.find('.start').text(timeFormatter.format(span.start));
    container.find('.finish').text(timeFormatter.format(span.finish));
    container.find('.project').text(span.project);
    container.find('.time').text(elapsedHours + ':' + elapsedMinutes);
    container.find('.hours').text(elapsedDecimal);

    var taskContainer = container.find('ul');
    taskContainer.empty();
    jQuery.each(span.tasks, function(index, task) {
      var li = jQuery('
')
        .appendTo(taskContainer)
        .text(task);
    });
  };

  var editSpan = function() {
    var el = jQuery(this);
    var guid = el.data('guid');
    App.dispatcher.publish('EDIT_SPAN_REQUESTED', guid);
    spansContainer.find('tr').removeClass('selected');
    el.closest('tr').addClass('selected');
  };

  var deleteSpan = function() {
    var guid = jQuery(this).data('guid');
    App.dispatcher.publish('DELETE_SPAN_REQUESTED', guid);
  };

  var repeatSpan = function() {
    var guid = jQuery(this).data('guid');
    App.dispatcher.publish('REPEAT_SPAN_REQUESTED', guid);
  };

  var onSpanDeleted = function(data) {
    var guid = data.span.guid;
    spanMap[guid].remove();
    delete(spanMap[guid]);
    if (spansContainer.children().length == 0)
      noContentContainer.show();
  };

  init();

};
<commit_msg>Adding filtering to span summary.<commit_after>var SpanSummary = function() {

  var html = `
    Spans

Nothing to see here.  Move along.

      <input type="text" placeholder="filter" class="filter" />

            Start
            Finish
            Project
            Tasks
            Hours
            Time
            Actions

`;

  var spanTemplate = `

`;

  var spansContainer;
  var nonContentContainer;
  var contentContainer;
  var timeFormatter;
  var roundDecimal;
  var padder;
  var spanMap = {};

  var init = function() {
    getDependencies();
    build();
    addBehavior();
  };

  var getDependencies = function() {
    timeFormatter = new TimeFormatter12Hr();
    roundDecimal = Rounder.roundDecimal;
    padder = new Padder();
  };

  var build = function() {
    var renderTo = jQuery('#SpanSummary');
    renderTo.html(html);
    spansContainer = renderTo.find('tbody');
    noContentContainer = renderTo.find('.no_content_container');
    contentContainer = renderTo.find('content_container');
  };

  var addBehavior = function() {
    App.dispatcher.subscribe('DATE_CHANGED', onDateChanged);
    App.dispatcher.subscribe('SPAN_SAVED', onSpanSaved);
    App.dispatcher.subscribe('SPAN_DELETED', onSpanDeleted);
    jQuery('#SpanSummary input.filter').keyup(onFilterChange);
  };

  var onDateChanged = function(data) {
    noContentContainer.show();
    spansContainer.empty();
    spanMap = {};
    jQuery.each(data.spans, function(index, span) {
      addSpan(span)
    });
  };

  var onSpanSaved = function(data) {
    var span = data.span;
    var container = spanMap[span.guid];
    if (container)
      populateSpan(span, container);
    else
      addSpan(span);
    spansContainer.find('.selected').removeClass('selected');
  };

  var addSpan = function(span) {
    noContentContainer.hide();
    contentContainer.show();
    var container = jQuery(spanTemplate).prependTo(spansContainer);
    spanMap[span.guid] = container;
    populateSpan(span, container);
  };

  var populateSpan = function(span, container) {
    var elapsed = (span.finish - span.start)/1000/60/60;
    var elapsedDecimal = roundDecimal(elapsed, 2)
    var elapsedHours = Math.floor(elapsed);
    var elapsedMinutes = padder.twoDigit(Math.floor((elapsed % 1) * 60));

    container.find('.edit').data('guid', span.guid).click(editSpan);
    container.find('.delete').data('guid', span.guid).click(deleteSpan);
    container.find('.repeat').data('guid', span.guid).click(repeatSpan);

    container.find('.start').text(timeFormatter.format(span.start));
    container.find('.finish').text(timeFormatter.format(span.finish));
    container.find('.project').text(span.project);
    container.find('.time').text(elapsedHours + ':' + elapsedMinutes);
    container.find('.hours').text(elapsedDecimal);

    var taskContainer = container.find('ul');
    taskContainer.empty();
    jQuery.each(span.tasks, function(index, task) {
      var li = jQuery('
')
        .appendTo(taskContainer)
        .text(task);
    });
  };

  var editSpan = function() {
    var el = jQuery(this);
    var guid = el.data('guid');
    App.dispatcher.publish('EDIT_SPAN_REQUESTED', guid);
    spansContainer.find('tr').removeClass('selected');
    el.closest('tr').addClass('selected');
  };

  var deleteSpan = function() {
    var guid = jQuery(this).data('guid');
    App.dispatcher.publish('DELETE_SPAN_REQUESTED', guid);
  };

  var repeatSpan = function() {
    var guid = jQuery(this).data('guid');
    App.dispatcher.publish('REPEAT_SPAN_REQUESTED', guid);
  };

  var onSpanDeleted = function(data) {
    var guid = data.span.guid;
    spanMap[guid].remove();
    delete(spanMap[guid]);
    if (spansContainer.children().length == 0)
      noContentContainer.show();
  };

  var onFilterChange = function() {
    spansContainer.find('tr').show();

    var projectText = jQuery(this).val().toLowerCase();
    if (projectText == '')
      return;

    var re = new RegExp(projectText.split('').join('.*'));

    spansContainer.find('tr').each(function(index, tr) {
      tr = jQuery(tr);
      var project = tr.find('.project').text().toLowerCase();
      if (!re.test(project))
        tr.hide();
    });
  };

  init();

};
<|endoftext|>


<commit_before>import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
    App,
    Chat,
    Home,
    Widgets,
    About,
    Login,
    LoginSuccess,
    Survey,
    NotFound,
    Pagination,
    Hello,
    Product,
    CustomerOrder,
    Customer,
    AddNewCustomAttribute,
    AddGwpByExcel,
    Order,
    OrderDetailCancelDetail,
    AccountEdit,
    AccountSetting,
    ProductBestSeller,
    ProductExclusive,
    ProductManageCustomAttribute,
    ProductHotItem,
    AddParentProduct,
    OrderDetailEditDetail,
    AddProduct,
    Marketing,
    MarketingAddNewGwp,
    MarketingAddNewCampaign,
    MasterBrandAndMember,
    MarketingCampaignInfo,
    GetDiscountAmountOff,
    BuyItem,
    DiscountPercentOff,
    BuyFirststTime,
    SpecificGroup,
    AddNewCampaignByPercent,
    AddNewCampaignByAmount,
    AddNewCartRule,

  } from 'containers';

export default (store) => {
  const requireLogin = (nextState, replace, cb) => {
    function checkAuth() {
      const { auth: { user }} = store.getState();
      if (!user) {
        // oops, not logged in, so can't be here!
        replace('/');
      }
      cb();
    }

    if (!isAuthLoaded(store.getState())) {
      store.dispatch(loadAuth()).then(checkAuth);
    } else {
      checkAuth();
    }
  };

  /**
   * Please keep routes in alphabetical order
   */
  return (
    <Route path="/" component={App}>
      { /* Home (main) route */ }
      <IndexRoute component={Home}/>

      { /* Routes requiring login */ }
      <Route onEnter={requireLogin}>
        <Route path="chat" component={Chat}/>
        <Route path="loginSuccess" component={LoginSuccess}/>
      </Route>

      { /* Routes */ }
      <Route path="about" component={About}/>
      <Route path="login" component={Login}/>
      <Route path="pagination" component={Pagination}/>
      <Route path="survey" component={Survey}/>
      <Route path="widgets" component={Widgets}/>
      <Route path="hello" component={Hello}/>
      <Route path="product" component={Product}/>
      <Route path="product/exclusive" component={ProductExclusive}/>
      <Route path="product/bestseller" component={ProductBestSeller}/>
      <Route path="product/hotitem" component={ProductHotItem}/>
      <Route path="customer" component={Customer}/>
      <Route path="customer/order" component={CustomerOrder}/>
      <Route path="customattribute" component={AddNewCustomAttribute}/>
      <Route path="addgwpbyexcel" component={AddGwpByExcel}/>
      <Route path="orders" component={Order}/>
      <Route path="orders/canceldetail" component={OrderDetailCancelDetail}/>
      <Route path="accountsetting" component={AccountSetting}/>
      <Route path="accountedit" component={AccountEdit}/>
      <Route path="product/managecustomattribute" component={ProductManageCustomAttribute}/>
      <Route path="parentproduct/add" component={AddParentProduct}/>
      <Route path="orderdetailcanceldetai/edit" component={OrderDetailEditDetail}/>
      <Route path="marketing/addnewgwp" component={MarketingAddNewGwp}/>
      <Route path="product/add" component={AddProduct}/>
      <Route path="marketing" component={Marketing}/>
      <Route path="marketing/addnewcampaign" component={MarketingAddNewCampaign}/>
      <Route path="marketing/masterbandandmember" component={MasterBrandAndMember}/>
      <Route path="marketing/setcampaign" component={MarketingAddNewCampaign}/>
      <Route path="marketing/campaign/info" component={MarketingCampaignInfo}/>
      <Route path="marketing/addnewcampaign/getdiscountamountoff" component={GetDiscountAmountOff}/>
      <Route path="marketing/addnewcampaign/buyitem" component={BuyItem}/>
      <Route path="marketing/addnewcampaign/discountpercentoff" component={DiscountPercentOff}/>
      <Route path="marketing/addnewcampaign/buyfirststtime" component={BuyFirststTime}/>
      <Route path="marketing/specificgroup" component={SpecificGroup}/>
      <Route path="marketing/addnewcartrulebypercent" component={AddNewCartRuleByPercent}/>
      <Route path="marketing/addnewcartrule" component={AddNewCartRule}/>
      <Route path="marketing/addnewcartrulebyamount" component={AddNewCartRuleByAmount}/>

      { /* Catch all route */ }
      <Route path="*" component={NotFound} status={404} />
    </Route>
  );
};
<commit_msg>Fix Name Add new cart rule in route<commit_after>import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
    App,
    Chat,
    Home,
    Widgets,
    About,
    Login,
    LoginSuccess,
    Survey,
    NotFound,
    Pagination,
    Hello,
    Product,
    CustomerOrder,
    Customer,
    AddNewCustomAttribute,
    AddGwpByExcel,
    Order,
    OrderDetailCancelDetail,
    AccountEdit,
    AccountSetting,
    ProductBestSeller,
    ProductExclusive,
    ProductManageCustomAttribute,
    ProductHotItem,
    AddParentProduct,
    OrderDetailEditDetail,
    AddProduct,
    Marketing,
    MarketingAddNewGwp,
    MarketingAddNewCampaign,
    MasterBrandAndMember,
    MarketingCampaignInfo,
    GetDiscountAmountOff,
    BuyItem,
    DiscountPercentOff,
    BuyFirststTime,
    SpecificGroup,
    AddNewCartRuleByPercent,
    AddNewCartRuleByAmount,
    AddNewCartRule,

  } from 'containers';

export default (store) => {
  const requireLogin = (nextState, replace, cb) => {
    function checkAuth() {
      const { auth: { user }} = store.getState();
      if (!user) {
        // oops, not logged in, so can't be here!
        replace('/');
      }
      cb();
    }

    if (!isAuthLoaded(store.getState())) {
      store.dispatch(loadAuth()).then(checkAuth);
    } else {
      checkAuth();
    }
  };

  /**
   * Please keep routes in alphabetical order
   */
  return (
    <Route path="/" component={App}>
      { /* Home (main) route */ }
      <IndexRoute component={Home}/>

      { /* Routes requiring login */ }
      <Route onEnter={requireLogin}>
        <Route path="chat" component={Chat}/>
        <Route path="loginSuccess" component={LoginSuccess}/>
      </Route>

      { /* Routes */ }
      <Route path="about" component={About}/>
      <Route path="login" component={Login}/>
      <Route path="pagination" component={Pagination}/>
      <Route path="survey" component={Survey}/>
      <Route path="widgets" component={Widgets}/>
      <Route path="hello" component={Hello}/>
      <Route path="product" component={Product}/>
      <Route path="product/exclusive" component={ProductExclusive}/>
      <Route path="product/bestseller" component={ProductBestSeller}/>
      <Route path="product/hotitem" component={ProductHotItem}/>
      <Route path="customer" component={Customer}/>
      <Route path="customer/order" component={CustomerOrder}/>
      <Route path="customattribute" component={AddNewCustomAttribute}/>
      <Route path="addgwpbyexcel" component={AddGwpByExcel}/>
      <Route path="orders" component={Order}/>
      <Route path="orders/canceldetail" component={OrderDetailCancelDetail}/>
      <Route path="accountsetting" component={AccountSetting}/>
      <Route path="accountedit" component={AccountEdit}/>
      <Route path="product/managecustomattribute" component={ProductManageCustomAttribute}/>
      <Route path="parentproduct/add" component={AddParentProduct}/>
      <Route path="orderdetailcanceldetai/edit" component={OrderDetailEditDetail}/>
      <Route path="marketing/addnewgwp" component={MarketingAddNewGwp}/>
      <Route path="product/add" component={AddProduct}/>
      <Route path="marketing" component={Marketing}/>
      <Route path="marketing/addnewcampaign" component={MarketingAddNewCampaign}/>
      <Route path="marketing/masterbandandmember" component={MasterBrandAndMember}/>
      <Route path="marketing/setcampaign" component={MarketingAddNewCampaign}/>
      <Route path="marketing/campaign/info" component={MarketingCampaignInfo}/>
      <Route path="marketing/addnewcampaign/getdiscountamountoff" component={GetDiscountAmountOff}/>
      <Route path="marketing/addnewcampaign/buyitem" component={BuyItem}/>
      <Route path="marketing/addnewcampaign/discountpercentoff" component={DiscountPercentOff}/>
      <Route path="marketing/addnewcampaign/buyfirststtime" component={BuyFirststTime}/>
      <Route path="marketing/specificgroup" component={SpecificGroup}/>
      <Route path="marketing/addnewcartrulebypercent" component={AddNewCartRuleByPercent}/>
      <Route path="marketing/addnewcartrule" component={AddNewCartRule}/>
      <Route path="marketing/addnewcartrulebyamount" component={AddNewCartRuleByAmount}/>

      { /* Catch all route */ }
      <Route path="*" component={NotFound} status={404} />
    </Route>
  );
};
<|endoftext|>


<commit_before>export default function(){
  var functions = arguments;

  //convert all string arguments into field accessors
  var i = 0, l = functions.length;
  while (i < l) {
    if (typeof(functions[i]) === 'string' || typeof(functions[i]) === 'number'){
      functions[i] = (function(str){ return function(d){ return d[str] }; })(functions[i])
    }
    i++;
  }

   //return composition of functions
  return function(d) {
    var i=0, l = functions.length;
    while (i++ < l) d = functions[i-1].call(this, d);
    return d;
  };
};
<commit_msg>adds not<commit_after>function ƒ(){
  var functions = arguments;

  //convert all string arguments into field accessors
  var i = 0, l = functions.length;
  while (i < l) {
    if (typeof(functions[i]) === 'string' || typeof(functions[i]) === 'number'){
      functions[i] = (function(str){ return function(d){ return d[str] }; })(functions[i])
    }
    i++;
  }

   //return composition of functions
  return function(d) {
    var i=0, l = functions.length;
    while (i++ < l) d = functions[i-1].call(this, d);
    return d;
  };
};

f.not = function(d){ return !d }

export default ƒ<|endoftext|>


<commit_before>var React = require('react'),
  ReactRouter = require('react-router'),
  Route = ReactRouter.Route,
  IndexRoute = ReactRouter.IndexRoute,
  Wrapper = require('./wrapper'),
  Settings = require('./app/settings'),
  About = require('./statics/About'),
  Team = require('./statics/Team'),
  Projects = require('./statics/Projects'),
  Jobs = require('./statics/Jobs'),
  Donate = require('./statics/Donate'),
  Help = require('./statics/Help'),
  PostSinglePage = require('./post/PostSinglePage'),
  Edit = require('./user/edit'),
  Feed = require('./user/feed'),
  Replies = require('./user/replies'),
  Followers = require('./user/UserFollowersList'),
  Followed = require('./user/UserFollowedList'),
  Wallet = require('./user/wallet'),
  MessagesUser = require('./messages/MessagesUser').default,
  MessagesCategory = require('./messages/MessagesCategory').default,
  Write = require('./post/newPost/NewPost').default;

import Page from './feed/Page';
import UserProfile from './user/UserProfile';
import Profile from './user/profile';
import Posts from './user/posts';
import { Trending, Hot, Votes, Responses, Active, Created, Cashout } from './feed/PathMatching';

export default (
  <Route path="/" component={Wrapper}>
    <IndexRoute component={Page} />
    <Route path="/settings" component={Settings} />

    <Route path="/about" component={About} />
    <Route path="/team" component={Team} />
    <Route path="/projects" component={Projects} />
    <Route path="/jobs" component={Jobs} />
    <Route path="/donate" component={Donate} />
    <Route path="/help" component={Help} />

    <Route path="/trending(/:category)" component={Trending} />
    <Route path="/hot(/:category)" component={Hot} />
    <Route path="/cashout(/:category)" component={Cashout} />
    <Route path="/created(/:category)" component={Created} />
    <Route path="/active(/:category)" component={Active} />
    <Route path="/responses(/:category)" component={Responses} />
    <Route path="/votes(/:category)" component={Votes} />

    <Route path="/write" component={Write} />

    <Route path="/messages/@:username" component={MessagesUser} />
    <Route path="/messages/:category" component={MessagesCategory} />

    <Route component={UserProfile}>
      <Route path="/profile/edit" component={Edit} />
      <Route path="/@:name/posts" component={Posts} />
      <Route path="/@:name/feed" component={Feed} />
      <Route path="/@:name/replies" component={Replies} />
      <Route path="/@:name/followers" component={Followers} />
      <Route path="/@:name/followed" component={Followed} />
      <Route path="/@:name/wallet" component={Wallet} />
      <Route path="/@:name" component={Profile} />
    </Route>

    <Route path="/:category/@:author/:permlink" component={ PostSinglePage } />
  </Route>
);
<commit_msg>fix imports to es6<commit_after>var React = require('react'),
  ReactRouter = require('react-router'),
  Route = ReactRouter.Route,
  IndexRoute = ReactRouter.IndexRoute,
  Wrapper = require('./wrapper'),
  Settings = require('./app/settings'),
  About = require('./statics/About'),
  Team = require('./statics/Team'),
  Projects = require('./statics/Projects'),
  Jobs = require('./statics/Jobs'),
  Donate = require('./statics/Donate'),
  Help = require('./statics/Help'),
  PostSinglePage = require('./post/PostSinglePage'),
  Edit = require('./user/edit'),
  Replies = require('./user/replies'),
  Followers = require('./user/UserFollowersList'),
  Followed = require('./user/UserFollowedList'),
  Wallet = require('./user/wallet'),
  MessagesUser = require('./messages/MessagesUser').default,
  MessagesCategory = require('./messages/MessagesCategory').default,
  Write = require('./post/newPost/NewPost').default;

import Page from './feed/Page';
import UserProfile from './user/UserProfile';
import Profile from './user/profile';
import UserProfilePosts from './user/posts';
import UserProfileFeed from './user/feed';
import { Trending, Hot, Votes, Responses, Active, Created, Cashout } from './feed/PathMatching';

export default (
  <Route path="/" component={Wrapper}>
    <IndexRoute component={Page} />
    <Route path="/settings" component={Settings} />

    <Route path="/about" component={About} />
    <Route path="/team" component={Team} />
    <Route path="/projects" component={Projects} />
    <Route path="/jobs" component={Jobs} />
    <Route path="/donate" component={Donate} />
    <Route path="/help" component={Help} />

    <Route path="/trending(/:category)" component={Trending} />
    <Route path="/hot(/:category)" component={Hot} />
    <Route path="/cashout(/:category)" component={Cashout} />
    <Route path="/created(/:category)" component={Created} />
    <Route path="/active(/:category)" component={Active} />
    <Route path="/responses(/:category)" component={Responses} />
    <Route path="/votes(/:category)" component={Votes} />

    <Route path="/write" component={Write} />

    <Route path="/messages/@:username" component={MessagesUser} />
    <Route path="/messages/:category" component={MessagesCategory} />

    <Route component={UserProfile}>
      <Route path="/profile/edit" component={Edit} />
      <Route path="/@:name/posts" component={UserProfilePosts} />
      <Route path="/@:name/feed" component={UserProfileFeed} />
      <Route path="/@:name/replies" component={Replies} />
      <Route path="/@:name/followers" component={Followers} />
      <Route path="/@:name/followed" component={Followed} />
      <Route path="/@:name/wallet" component={Wallet} />
      <Route path="/@:name" component={Profile} />
    </Route>

    <Route path="/:category/@:author/:permlink" component={ PostSinglePage } />
  </Route>
);
<|endoftext|>


<commit_before>define([
    'jquery',
    '/customize/application_config.js',
    '/common/cryptpad-common.js',
    '/customize/header.js',
], function ($, Config, Cryptpad) {

    window.APP = {
        Cryptpad: Cryptpad,
    };

    var Messages = Cryptpad.Messages;

    $(function () {
        var $main = $('#mainBlock');

        $(window).click(function () {
            $('.cryptpad-dropdown').hide();
        });

        // main block is hidden in case javascript is disabled
        $main.removeClass('hidden');

        // Make sure we don't display non-translated content (empty button)
        $main.find('#data').removeClass('hidden');

        if (Cryptpad.isLoggedIn()) {
            if (window.location.pathname === '/') {
                window.location = '/drive/';
            }

            var name = localStorage[Cryptpad.userNameKey] || sessionStorage[Cryptpad.userNameKey];
            var $loggedInBlock = $main.find('#loggedIn');
            var $hello = $loggedInBlock.find('#loggedInHello');
            var $logout = $loggedInBlock.find('#loggedInLogOut');

            if (name) {
                $hello.text(Messages._getKey('login_hello', [name]));
            } else {
                $hello.text(Messages.login_helloNoName);
            }
            $('#buttons').find('.nologin').hide();

            $logout.click(function () {
                Cryptpad.logout(function () {
                    window.location.reload();
                });
            });

            $loggedInBlock.removeClass('hidden');
        }
        else {
            $main.find('#userForm').removeClass('hidden');
            $('#name').focus();
        }

        var displayCreateButtons = function () {
            var $parent = $('#buttons');
            var options = [];
            var $container = $('<div>', {'class': 'dropdown-bar'}).appendTo($parent);
            Config.availablePadTypes.forEach(function (el) {
                if (el === 'drive') { return; }
                if (!Cryptpad.isLoggedIn() && Config.registeredOnlyTypes &&
                    Config.registeredOnlyTypes.indexOf(el) !== -1) { return; }
                options.push({
                    tag: 'a',
                    attributes: {
                        'class': 'newdoc',
                        'href': '/' + el + '/',
                        'target': '_blank'
                    },
                    content: Messages['button_new' + el] // Pretty name of the language value
                });
            });
            var dropdownConfig = {
                text: Messages.login_makeAPad, // Button initial text
                options: options, // Entries displayed in the menu
                container: $container
            };
            var $block = Cryptpad.createDropdown(dropdownConfig);
            $block.find('button').addClass('btn').addClass('btn-primary');
            $block.appendTo($parent);
        };

        /* Log in UI */
        var Login;
        // deferred execution to avoid unnecessary asset loading
        var loginReady = function (cb) {
            if (Login) {
                if (typeof(cb) === 'function') { cb(); }
                return;
            }
            require([
                '/common/login.js',
            ], function (_Login) {
                Login = Login || _Login;
                if (typeof(cb) === 'function') { cb(); }
            });
        };

        var $uname = $('#name').on('focus', loginReady);

        var $passwd = $('#password')
        // background loading of login assets
        .on('focus', loginReady)
        // enter key while on password field clicks signup
        .on('keyup', function (e) {
            if (e.which !== 13) { return; } // enter
            $('button.login').click();
        });

        $('button.login').click(function () {
            // setTimeout 100ms to remove the keyboard on mobile devices before the loading screen pops up
            window.setTimeout(function () {
                Cryptpad.addLoadingScreen(Messages.login_hashing);
                // We need a setTimeout(cb, 0) otherwise the loading screen is only displayed after hashing the password
                window.setTimeout(function () {
                    loginReady(function () {
                        var uname = $uname.val();
                        var passwd = $passwd.val();
                        Login.loginOrRegister(uname, passwd, false, function (err, result) {
                            if (!err) {
                                var proxy = result.proxy;

                                // successful validation and user already exists
                                // set user hash in localStorage and redirect to drive
                                if (proxy && !proxy.login_name) {
                                    proxy.login_name = result.userName;
                                }

                                proxy.edPrivate = result.edPrivate;
                                proxy.edPublic = result.edPublic;

                                Cryptpad.whenRealtimeSyncs(result.realtime, function () {
                                    Cryptpad.login(result.userHash, result.userName, function () {
                                        document.location.href = '/drive/';
                                    });
                                });
                                return;
                            }
                            switch (err) {
                                case 'NO_SUCH_USER':
                                    Cryptpad.removeLoadingScreen(function () {
                                        Cryptpad.alert(Messages.login_noSuchUser);
                                    });
                                    break;
                                case 'INVAL_USER':
                                    Cryptpad.removeLoadingScreen(function () {
                                        Cryptpad.alert(Messages.login_invalUser);
                                    });
                                    break;
                                case 'INVAL_PASS':
                                    Cryptpad.removeLoadingScreen(function () {
                                        Cryptpad.alert(Messages.login_invalPass);
                                    });
                                    break;
                                default: // UNHANDLED ERROR
                                    Cryptpad.errorLoadingScreen(Messages.login_unhandledError);
                            }
                        });
                    });
                }, 0);
            }, 100);
        });
        /* End Log in UI */

        var addButtonHandlers = function () {
            $('button.register').click(function () {
                var username = $('#name').val();
                var passwd = $('#password').val();
                sessionStorage.login_user = username;
                sessionStorage.login_pass = passwd;
                document.location.href = '/register/';
            });
            $('button.gotodrive').click(function () {
                document.location.href = '/drive/';
            });

            $('button#loggedInLogout').click(function () {
                $('#user-menu .logout').click();
            });
        };

        displayCreateButtons();

        addButtonHandlers();
        console.log("ready");
    });
});
<commit_msg>add a return<commit_after>define([
    'jquery',
    '/customize/application_config.js',
    '/common/cryptpad-common.js',
    '/customize/header.js',
], function ($, Config, Cryptpad) {

    window.APP = {
        Cryptpad: Cryptpad,
    };

    var Messages = Cryptpad.Messages;

    $(function () {
        var $main = $('#mainBlock');

        $(window).click(function () {
            $('.cryptpad-dropdown').hide();
        });

        // main block is hidden in case javascript is disabled
        $main.removeClass('hidden');

        // Make sure we don't display non-translated content (empty button)
        $main.find('#data').removeClass('hidden');

        if (Cryptpad.isLoggedIn()) {
            if (window.location.pathname === '/') {
                window.location = '/drive/';
                return;
            }

            var name = localStorage[Cryptpad.userNameKey] || sessionStorage[Cryptpad.userNameKey];
            var $loggedInBlock = $main.find('#loggedIn');
            var $hello = $loggedInBlock.find('#loggedInHello');
            var $logout = $loggedInBlock.find('#loggedInLogOut');

            if (name) {
                $hello.text(Messages._getKey('login_hello', [name]));
            } else {
                $hello.text(Messages.login_helloNoName);
            }
            $('#buttons').find('.nologin').hide();

            $logout.click(function () {
                Cryptpad.logout(function () {
                    window.location.reload();
                });
            });

            $loggedInBlock.removeClass('hidden');
        }
        else {
            $main.find('#userForm').removeClass('hidden');
            $('#name').focus();
        }

        var displayCreateButtons = function () {
            var $parent = $('#buttons');
            var options = [];
            var $container = $('<div>', {'class': 'dropdown-bar'}).appendTo($parent);
            Config.availablePadTypes.forEach(function (el) {
                if (el === 'drive') { return; }
                if (!Cryptpad.isLoggedIn() && Config.registeredOnlyTypes &&
                    Config.registeredOnlyTypes.indexOf(el) !== -1) { return; }
                options.push({
                    tag: 'a',
                    attributes: {
                        'class': 'newdoc',
                        'href': '/' + el + '/',
                        'target': '_blank'
                    },
                    content: Messages['button_new' + el] // Pretty name of the language value
                });
            });
            var dropdownConfig = {
                text: Messages.login_makeAPad, // Button initial text
                options: options, // Entries displayed in the menu
                container: $container
            };
            var $block = Cryptpad.createDropdown(dropdownConfig);
            $block.find('button').addClass('btn').addClass('btn-primary');
            $block.appendTo($parent);
        };

        /* Log in UI */
        var Login;
        // deferred execution to avoid unnecessary asset loading
        var loginReady = function (cb) {
            if (Login) {
                if (typeof(cb) === 'function') { cb(); }
                return;
            }
            require([
                '/common/login.js',
            ], function (_Login) {
                Login = Login || _Login;
                if (typeof(cb) === 'function') { cb(); }
            });
        };

        var $uname = $('#name').on('focus', loginReady);

        var $passwd = $('#password')
        // background loading of login assets
        .on('focus', loginReady)
        // enter key while on password field clicks signup
        .on('keyup', function (e) {
            if (e.which !== 13) { return; } // enter
            $('button.login').click();
        });

        $('button.login').click(function () {
            // setTimeout 100ms to remove the keyboard on mobile devices before the loading screen pops up
            window.setTimeout(function () {
                Cryptpad.addLoadingScreen(Messages.login_hashing);
                // We need a setTimeout(cb, 0) otherwise the loading screen is only displayed after hashing the password
                window.setTimeout(function () {
                    loginReady(function () {
                        var uname = $uname.val();
                        var passwd = $passwd.val();
                        Login.loginOrRegister(uname, passwd, false, function (err, result) {
                            if (!err) {
                                var proxy = result.proxy;

                                // successful validation and user already exists
                                // set user hash in localStorage and redirect to drive
                                if (proxy && !proxy.login_name) {
                                    proxy.login_name = result.userName;
                                }

                                proxy.edPrivate = result.edPrivate;
                                proxy.edPublic = result.edPublic;

                                Cryptpad.whenRealtimeSyncs(result.realtime, function () {
                                    Cryptpad.login(result.userHash, result.userName, function () {
                                        document.location.href = '/drive/';
                                    });
                                });
                                return;
                            }
                            switch (err) {
                                case 'NO_SUCH_USER':
                                    Cryptpad.removeLoadingScreen(function () {
                                        Cryptpad.alert(Messages.login_noSuchUser);
                                    });
                                    break;
                                case 'INVAL_USER':
                                    Cryptpad.removeLoadingScreen(function () {
                                        Cryptpad.alert(Messages.login_invalUser);
                                    });
                                    break;
                                case 'INVAL_PASS':
                                    Cryptpad.removeLoadingScreen(function () {
                                        Cryptpad.alert(Messages.login_invalPass);
                                    });
                                    break;
                                default: // UNHANDLED ERROR
                                    Cryptpad.errorLoadingScreen(Messages.login_unhandledError);
                            }
                        });
                    });
                }, 0);
            }, 100);
        });
        /* End Log in UI */

        var addButtonHandlers = function () {
            $('button.register').click(function () {
                var username = $('#name').val();
                var passwd = $('#password').val();
                sessionStorage.login_user = username;
                sessionStorage.login_pass = passwd;
                document.location.href = '/register/';
            });
            $('button.gotodrive').click(function () {
                document.location.href = '/drive/';
            });

            $('button#loggedInLogout').click(function () {
                $('#user-menu .logout').click();
            });
        };

        displayCreateButtons();

        addButtonHandlers();
        console.log("ready");
    });
});
<|endoftext|>


<commit_before>module.exports = Element = (function() {
    // Element are Vertex or Edge
    function Element(obj) {
        this._obj = obj;
    }

    Element.prototype.addProperty = function(k, v) {
        this._obj[k] = v;
        return this;
    };

    Element.prototype.setProperty = function (k, v) {
        this._obj[k] = v;
        return this;
    };

    return Element;

})();
<commit_msg>Add more property methods<commit_after>module.exports = Element = (function() {
    // Element are Vertex or Edge
    function Element(obj) {
        this._obj = obj;
    }

    Element.prototype.setProperty = function (k, v) {
        this._obj[k] = v;
        return this;
    };

    Element.prototype.setProperties = function (properties) {
        for (var key in properties) {
            this.setProperty(key, properties[key]);
        }
        return this;
    };

    /*
     * Titan specific method
     *
     * Use this instead of setProperty() when setting the value of an indexed
     * property.
     */
    Element.prototype.addProperty = function(k, v) {
        this._obj[k] = v;
        return this;
    };

    /*
     * Titan specific method
     *
     * Use this instead of setProperties() when setting the values of indexed
     * properties.
     */
    Element.prototype.addProperties = function (properties) {
        for (var key in properties) {
            this.addProperty(key, properties[key]);
        }
        return this;
    };

    return Element;

})();
<|endoftext|>


<commit_before>import componentWrapper from './component-wrapper';
import mergeDeep from './utils/mergeDeep';
import isSwissElement from './utils/isSwissElement';
import SwissController from './swiss-controller';

const swissController = new SwissController();

const element = (...args) => {
  let options = {
    element: 'div'
  };
  let styles = {};

  args.forEach((prop, i) => {
    if(typeof prop === 'string') {
      if(i === 0) {
        options.element = prop;
      } else if(i === 1) {
        options.className = prop;
      }
    }
    if(typeof prop !== 'object') {
      return;
    }
    let dStyles = prop;
    if(isSwissElement(prop)) {
      dStyles = swissController.getStylesByUniqueId(prop.swissUniqueString);
    }
    styles = mergeDeep(styles, dStyles);
  })

  options.styles = styles;
  return componentWrapper(options, swissController);
}

export default element;
<commit_msg>fixed merging multiple swiss elements<commit_after>import componentWrapper from './component-wrapper';
import mergeDeep from './utils/mergeDeep';
import isSwissElement from './utils/isSwissElement';
import SwissController from './swiss-controller';

const swissController = new SwissController();

const element = (...args) => {
  let options = {
    element: 'div'
  };
  let styles = {};

  args.forEach((prop, i) => {
    if(typeof prop === 'string') {
      if(i === 0) {
        options.element = prop;
      } else if(i === 1) {
        options.className = prop;
      }
    }
    let dStyles = prop;
    if(isSwissElement(prop)) {
      dStyles = swissController.getStylesByUniqueId(prop.swissUniqueString);
    } else if(typeof prop !== 'object') {
      return;
    }

    styles = mergeDeep(styles, dStyles);
  })

  options.styles = styles;
  return componentWrapper(options, swissController);
}

export default element;
<|endoftext|>


<commit_before>/**
 * Describe a synchronous benchmark
 */
export type SynchronousBenchmark =
{
  name: string;
  setUp?: () => void;
  tearDown?: () => void;
  run: () => mixed;
}

/**
 * Describe an asynchronous benchmark
 */
export type ASynchronousBenchmark =
{
  name: string;
  setUp?: () => void;
  tearDown?: () => void;
  startRunning : () => Promise;
}

/**
 * Supported benchmarking styles
 */
export type Benchmark = SynchronousBenchmark | ASynchronousBenchmark;

/**
 * Result of running one benchmark
 */
export type BenchmarkResult =
{
  name: string;
  opsPerSample: number;
  numSamples: number;
  timingSamples: Array<number>;
  memorySamples: Array<number>;
}

/**
 * Options controlling how benchmarks are run
 */
export type BenchmarkingOptions =
{
}

/**
 * Result of running a suite of benchmarks
 */
export type BenchmarkSuiteResult =
{
  name: string;
  options: BenchmarkingOptions;
  startTime: Array<number>;
  results: Array<BenchmarkResult>;
}

/**
 * Start the process of running a suite of benchmarks
 */
export function startBenchmarking(
  name: String,
  benchmarkSuite: Array<Benchmark>,
  options: BenchmarkingOptions
) : Promise {
  return new Promise((resolve: resolveFn, reject: rejectFn) => {
    const suiteResult : BenchmarkSuiteResult = {
      name,
      options,
      startTime: Date.now(),
      results: []
    };
    scheduleNextBenchmark(resolve, reject, benchmarkSuite, suiteResult);
  });
}

type resolveFn = (value:mixed) => void;

type rejectFn = (value:mixed) => void;

/**
 * Schedule a benchmark to be run at a later time
 */
function scheduleNextBenchmark(
  resolve: resolveFn,
  reject: rejectFn,
  benchmarkSuite: Array<Benchmark>,
  suiteResult: BenchmarkSuiteResult
) : void {
  setImmediate(runBenchmark, resolve, reject, benchmarkSuite, suiteResult);
}

/**
 * Start the process of running a single benchmark
 */
function runBenchmark(
  resolve: resolveFn,
  reject: rejectFn,
  benchmarkSuite: Array<Benchmark>,
  suiteResult: BenchmarkSuiteResult
) : void {

  const benchmark = benchmarkSuite.shift();

  // if there are no more benchmarks, stop
  if (!benchmark) {
    resolve(suiteResult);
    return;
  }

  if (!benchmark.name) {
    reject(new Error(
    `"${benchmark.name} does not provide a name`
    ));
    return;
  }

  const initialResult:BenchmarkResult = {
    name: benchmark.name,
    opsPerSample: 100,
    numSamples: 20,
    timingSamples: [],
    memorySamples: []
  };

  const Err = setUpBenchmark(benchmark);
  if (Err) {
    reject(Err);
    return;
  }

  const resolveBenchmark = (finalResult: BenchmarkResult) => {
    suiteResult.results.push(finalResult);
    scheduleNextBenchmark(resolve, reject, benchmarkSuite, suiteResult);
  };

  scheduleNextSample(resolveBenchmark, reject, benchmark, initialResult);
}

/**
 *  Setup benchmark resources before running
 */
function setupBenchmark(benchmark: Benchmark): Error | false {
  if (benchmark.setUp) {
    try {
      benchmark.setUp();
    } catch (e) {
      return e;
    }
  }
  return false;
}

/**
 * Schedule sample collection
 */
function scheduleNextSample(
  resolve: resolveFn,
  reject: rejectFn,
  benchmark: ASynchronousBenchmark,
  result: BenchmarkResult
): void {
  if (isSamplingComplete(result)) {
    const Err = tearDownBenchmark(benchmark);
    if (Err) {
      reject(Err);
    } else {
      resolve(result);
    }
    return;
  }
  if (benchmark.run) {
    setImmediate(
      collectSynchronousSample,
      resolve,
      reject,
      benchmark,
      result
    );
  } else if (benchmark.startRunning) {
    setImmediate(
      collectAsynchronousSample,
      resolve,
      reject,
      benchmark,
      result
    );
  } else {
    reject(new Error(
    `"${benchmark.name} does not provide a run or startRunning function`
    ));
  }
}

/**
 * Does the result contain all required samples?
 */
function isSamplingComplete(result: BenchmarkResult) {
  return result.timingSamples.length >= result.numSamples;
}

/**
 *  release benchmark resources after running
 */
function tearDownBenchmark(benchmark: Benchmark): Error | false {
  if (benchmark.tearDown) {
    try {
      benchmark.tearDown();
    } catch (e) {
      return e;
    }
  }
  return false;
}

/**
 * Run an asynchronous benchmark for the desired number of operations and capture
 * the results
 */
function collectAsynchronousSample(
  resolve: resolveFn,
  reject: rejectFn,
  benchmark: ASynchronousBenchmark,
  result: BenchmarkResult
): void {
  const promises = new Array(result.opsPerSample);

  cleanUpMemory();

  const startMemory = getStartMemory();
  const startTime = getStartTime();

  // run the benchmark function and collect promises
  for (let i = 0; i < result.opsPerSample; i++) {
    promises[i] = benchmark.startRunning();
  }

  // take measurements when all promises have been resolved
  Promise.all(promises).then(() => {

    const elapsedTime = getTimeElapsed(startTime);
    const memoryUsed = getMemoryUsed(startMemory);

    recordSample(result, elapsedTime, memoryUsed);

    scheduleNextSample(resolve, reject, benchmark, result);
  });
}

/**
 * Run a synchronous benchmark for the desired number of operations and capture
 * the results
 */
function collectSynchronousSample(
  resolve: resolveFn,
  reject: rejectFn,
  benchmark: SynchronousBenchmark,
  result: BenchmarkResult
) {
  cleanUpMemory();

  const startMemory = getStartMemory();
  const startTime = getStartTime();

  // run the benchmark function
  for (let i = 0; i < result.opsPerSample; i++) {
    benchmark.run();
  }

  const elapsedTime = getTimeElapsed(startTime);
  const memoryUsed = getMemoryUsed(startMemory);

  recordSample(result, elapsedTime, memoryUsed);

  scheduleNextSample(resolve, reject, benchmark, result);
}

/**
 * Record a sample memory and time into a benchmark result
 */
function recordSample(benchmarkResult, elapsedTime, memoryUsed) {
  benchmarkResult.timingSamples.push(elapsedTime);
  benchmarkResult.memorySamples.push(memoryUsed);
}

/**
 * Read the current time, using the highest resolution timer at our disposal
 */
function getStartTime() {
  return process.hrtime();
}

/**
 * Convert an array from process.hrtime into an integer microseconds number
 */
function convertHrTimeToMicroseconds(hrTime) {
  const microsecondsPerSecond = 1000000;
  const microsecondsPerNanoSecond = 1000;
  return Math.round(
    hrTime[0] * microsecondsPerSecond + hrTime[1] / microsecondsPerNanoSecond
  );
}

/**
 * Determine how much time has passed in microseconds since an initial reading was taken
 */
function getTimeElapsed(startTime) {
  const elapsed = process.hrtime(startTime);
  return convertHrTimeToMicroseconds(elapsed);
}

/**
 * Read the current memory usage
 */
function getStartMemory() {
  return process.memoryUsage();
}

/**
 * Determine how much memory has been used since an initial reading was taken
 */
function getMemoryUsed(startMemory) {
  const memory = process.memoryUsage();
  return memory.heapUsed - startMemory.heapUsed;
}

/**
 * Put memory into a stable state if we can to avoid triggering gc during a
 * sample run
 */
function cleanUpMemory() {
  if (global.gc) {
    global.gc();
  }
}
<commit_msg>Fix typo in setup benchmark; fix incorrect units in microtime conversion<commit_after>/**
 * Describe a synchronous benchmark
 */
export type SynchronousBenchmark =
{
  name: string;
  setUp?: () => void;
  tearDown?: () => void;
  run: () => mixed;
}

/**
 * Describe an asynchronous benchmark
 */
export type ASynchronousBenchmark =
{
  name: string;
  setUp?: () => void;
  tearDown?: () => void;
  startRunning : () => Promise;
}

/**
 * Supported benchmarking styles
 */
export type Benchmark = SynchronousBenchmark | ASynchronousBenchmark;

/**
 * Result of running one benchmark
 */
export type BenchmarkResult =
{
  name: string;
  opsPerSample: number;
  numSamples: number;
  timingSamples: Array<number>;
  memorySamples: Array<number>;
}

/**
 * Options controlling how benchmarks are run
 */
export type BenchmarkingOptions =
{
}

/**
 * Result of running a suite of benchmarks
 */
export type BenchmarkSuiteResult =
{
  name: string;
  options: BenchmarkingOptions;
  startTime: Array<number>;
  results: Array<BenchmarkResult>;
}

/**
 * Start the process of running a suite of benchmarks
 */
export function startBenchmarking(
  name: String,
  benchmarkSuite: Array<Benchmark>,
  options: BenchmarkingOptions
) : Promise {
  return new Promise((resolve: resolveFn, reject: rejectFn) => {
    const suiteResult : BenchmarkSuiteResult = {
      name,
      options,
      startTime: Date.now(),
      results: []
    };
    scheduleNextBenchmark(resolve, reject, benchmarkSuite, suiteResult);
  });
}

type resolveFn = (value:mixed) => void;

type rejectFn = (value:mixed) => void;

/**
 * Schedule a benchmark to be run at a later time
 */
function scheduleNextBenchmark(
  resolve: resolveFn,
  reject: rejectFn,
  benchmarkSuite: Array<Benchmark>,
  suiteResult: BenchmarkSuiteResult
) : void {
  setImmediate(runBenchmark, resolve, reject, benchmarkSuite, suiteResult);
}

/**
 * Start the process of running a single benchmark
 */
function runBenchmark(
  resolve: resolveFn,
  reject: rejectFn,
  benchmarkSuite: Array<Benchmark>,
  suiteResult: BenchmarkSuiteResult
) : void {

  const benchmark = benchmarkSuite.shift();

  // if there are no more benchmarks, stop
  if (!benchmark) {
    resolve(suiteResult);
    return;
  }

  if (!benchmark.name) {
    reject(new Error(
    `"${benchmark.name} does not provide a name`
    ));
    return;
  }

  const initialResult:BenchmarkResult = {
    name: benchmark.name,
    opsPerSample: 100,
    numSamples: 20,
    timingSamples: [],
    memorySamples: []
  };

  const Err = setupBenchmark(benchmark);
  if (Err) {
    reject(Err);
    return;
  }

  const resolveBenchmark = (finalResult: BenchmarkResult) => {
    suiteResult.results.push(finalResult);
    scheduleNextBenchmark(resolve, reject, benchmarkSuite, suiteResult);
  };

  scheduleNextSample(resolveBenchmark, reject, benchmark, initialResult);
}

/**
 *  Setup benchmark resources before running
 */
function setupBenchmark(benchmark: Benchmark): Error | false {
  if (benchmark.setUp) {
    try {
      benchmark.setUp();
    } catch (e) {
      return e;
    }
  }
  return false;
}

/**
 * Schedule sample collection
 */
function scheduleNextSample(
  resolve: resolveFn,
  reject: rejectFn,
  benchmark: ASynchronousBenchmark,
  result: BenchmarkResult
): void {
  if (isSamplingComplete(result)) {
    const Err = tearDownBenchmark(benchmark);
    if (Err) {
      reject(Err);
    } else {
      resolve(result);
    }
    return;
  }
  if (benchmark.run) {
    setImmediate(
      collectSynchronousSample,
      resolve,
      reject,
      benchmark,
      result
    );
  } else if (benchmark.startRunning) {
    setImmediate(
      collectAsynchronousSample,
      resolve,
      reject,
      benchmark,
      result
    );
  } else {
    reject(new Error(
    `"${benchmark.name} does not provide a run or startRunning function`
    ));
  }
}

/**
 * Does the result contain all required samples?
 */
function isSamplingComplete(result: BenchmarkResult) {
  return result.timingSamples.length >= result.numSamples;
}

/**
 *  release benchmark resources after running
 */
function tearDownBenchmark(benchmark: Benchmark): Error | false {
  if (benchmark.tearDown) {
    try {
      benchmark.tearDown();
    } catch (e) {
      return e;
    }
  }
  return false;
}

/**
 * Run an asynchronous benchmark for the desired number of operations and capture
 * the results
 */
function collectAsynchronousSample(
  resolve: resolveFn,
  reject: rejectFn,
  benchmark: ASynchronousBenchmark,
  result: BenchmarkResult
): void {
  const promises = new Array(result.opsPerSample);

  cleanUpMemory();

  const startMemory = getStartMemory();
  const startTime = getStartTime();

  // run the benchmark function and collect promises
  for (let i = 0; i < result.opsPerSample; i++) {
    promises[i] = benchmark.startRunning();
  }

  // take measurements when all promises have been resolved
  Promise.all(promises).then(() => {

    const elapsedTime = getTimeElapsed(startTime);
    const memoryUsed = getMemoryUsed(startMemory);

    recordSample(result, elapsedTime, memoryUsed);

    scheduleNextSample(resolve, reject, benchmark, result);
  });
}

/**
 * Run a synchronous benchmark for the desired number of operations and capture
 * the results
 */
function collectSynchronousSample(
  resolve: resolveFn,
  reject: rejectFn,
  benchmark: SynchronousBenchmark,
  result: BenchmarkResult
) {
  cleanUpMemory();

  const startMemory = getStartMemory();
  const startTime = getStartTime();

  // run the benchmark function
  for (let i = 0; i < result.opsPerSample; i++) {
    benchmark.run();
  }

  const elapsedTime = getTimeElapsed(startTime);
  const memoryUsed = getMemoryUsed(startMemory);

  recordSample(result, elapsedTime, memoryUsed);

  scheduleNextSample(resolve, reject, benchmark, result);
}

/**
 * Record a sample memory and time into a benchmark result
 */
function recordSample(benchmarkResult, elapsedTime, memoryUsed) {
  benchmarkResult.timingSamples.push(elapsedTime);
  benchmarkResult.memorySamples.push(memoryUsed);
}

/**
 * Read the current time, using the highest resolution timer at our disposal
 */
function getStartTime() {
  return process.hrtime();
}

/**
 * Convert an array from process.hrtime into an integer microseconds number
 */
function convertHrTimeToMicroseconds(hrTime) {
  const microSecondsPerSecond = 1000000;
  const nanoSecondsPerMicroSecond = 1000;
  return Math.round(
    hrTime[0] * microSecondsPerSecond + hrTime[1] / nanoSecondsPerMicroSecond
  );
}

/**
 * Determine how much time has passed in microseconds since an initial reading was taken
 */
function getTimeElapsed(startTime) {
  const elapsed = process.hrtime(startTime);
  return convertHrTimeToMicroseconds(elapsed);
}

/**
 * Read the current memory usage
 */
function getStartMemory() {
  return process.memoryUsage();
}

/**
 * Determine how much memory has been used since an initial reading was taken
 */
function getMemoryUsed(startMemory) {
  const memory = process.memoryUsage();
  return memory.heapUsed - startMemory.heapUsed;
}

/**
 * Put memory into a stable state if we can to avoid triggering gc during a
 * sample run
 */
function cleanUpMemory() {
  if (global.gc) {
    global.gc();
  }
}
<|endoftext|>


<commit_before>import { call, put, select, takeEvery } from 'redux-saga/effects';

import { types, setFileURL } from '../reducer/storage.actions';

import rsf from '../rsf';

const filePath = 'test.png'

function* syncFileUrl() {
  try {
    const url = yield call(rsf.getDownloadURL, filePath);
    yield put(setFileURL(url));
  }
  catch(error) {
    console.error(error);
  }
}

function* sendFileSaga(action) {
  const file = yield select(state => state.storage.file);
  const task = yield call(rsf.upload, filePath, file);

  yield syncFileUrl();
}

export default function* rootSaga() {
  yield [
    takeEvery(types.SEND_FILE, sendFileSaga),
  ];

  yield syncFileUrl()
}
<commit_msg>Update example.<commit_after>import { call, put, select, takeEvery } from 'redux-saga/effects';

import { types, setFileURL } from '../reducer/storage.actions';

import rsf from '../rsf';

const filePath = 'test.png'

function* syncFileUrl() {
  try {
    const url = yield call(rsf.getDownloadURL, filePath);
    yield put(setFileURL(url));
  }
  catch(error) {
    console.error(error);
  }
}

function* sendFileSaga(action) {
  const file = yield select(state => state.storage.file);
  const task = yield call(rsf.upload, filePath, file);

  task.on('state_changed', snapshot => {
    const pct = snapshot.bytesTransferred * 100 / snapshot.totalBytes
    console.log(`${pct}%`);
  })

  // Wait for upload to complete
  yield task

  yield syncFileUrl();
}

export default function* rootSaga() {
  yield [
    takeEvery(types.SEND_FILE, sendFileSaga),
  ];

  yield syncFileUrl()
}
<|endoftext|>