<commit_before>/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from "react";
import { Link } from "react-router-dom";

import withUser from "HOC/withUser";

import EngineSelect from "./EngineSelect";
import AppSelect from "./AppSelect";
import UserInformation from "./UserInformation";

import { ReactComponent as Logo } from "./logo-2020-round.svg";
import "./Header.scss";
import SmallScreenSwitch from "./SmallScreenSwitch";
import Tooltip from "components/Tooltip";
import translate from "utils/translation";
import Navigation from "./Navigation";

function Header({ user }) {
  return (

      <Link to="/" className="app-banner">
        <Logo className="logo" />
        {translate("APP_VENDOR")} Cockpit
      </Link>

      {user && <Navigation />}

      <SmallScreenSwitch
        smallContent={
          <Tooltip
            position="bottom"
            title={}
          >
            {translate("CAM_WIDGET_HEADER_SMALL_SCREEN_WARNING")}
          </Tooltip>
        }
      />
      <EngineSelect />
      {user && <UserInformation user={user} />}
      <AppSelect user={user} />

  );
}

export default withUser(Header);
<commit_msg>fix(style): hide app banner on login<commit_after>/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from "react";
import { Link } from "react-router-dom";

import withUser from "HOC/withUser";

import EngineSelect from "./EngineSelect";
import AppSelect from "./AppSelect";
import UserInformation from "./UserInformation";

import { ReactComponent as Logo } from "./logo-2020-round.svg";
import "./Header.scss";
import SmallScreenSwitch from "./SmallScreenSwitch";
import Tooltip from "components/Tooltip";
import translate from "utils/translation";
import Navigation from "./Navigation";

function Header({ user }) {
  return (

      {user ? (
        <Link to="/" className="app-banner">
          <Logo className="logo" />
          {translate("APP_VENDOR")} Cockpit
        </Link>
      ) : null}

      {user && <Navigation />}

      <SmallScreenSwitch
        smallContent={
          <Tooltip
            position="bottom"
            title={}
          >
            {translate("CAM_WIDGET_HEADER_SMALL_SCREEN_WARNING")}
          </Tooltip>
        }
      />
      <EngineSelect />
      {user && <UserInformation user={user} />}
      <AppSelect user={user} />

  );
}

export default withUser(Header);
<|endoftext|>


<commit_before>/* SelectList
*  Used by both SingleSelect and MultiSelect controls to render their option lists
*/

import React from 'react';
import { intlShape } from 'react-intl';
import PropTypes from 'prop-types';
import classnames from 'classnames';

import injectIntl from '../InjectIntl';
import DefaultOptionFormatter from './DefaultOptionFormatter';
import css from './Selection.css';

const propTypes = {
  activeId: PropTypes.string,
  controlRef: PropTypes.object,
  cursoredValue: PropTypes.string,
  emptyMessage: PropTypes.string,
  filtered: PropTypes.bool,
  filterRef: PropTypes.object,
  formatter: PropTypes.func,
  id: PropTypes.string,
  intl: intlShape.isRequired,
  label: PropTypes.string,
  list: PropTypes.arrayOf(PropTypes.object),
  maxHeight: PropTypes.string,
  multiple: PropTypes.bool,
  onChoose: PropTypes.func,
  onClickItem: PropTypes.func,
  onFilter: PropTypes.func,
  onFilterKeyDown: PropTypes.func,
  optionAlignment: PropTypes.string,
  rootRef: PropTypes.object,
  searchTerm: PropTypes.string,
  selected: PropTypes.string,
  selectedIndex: PropTypes.number,
  selectedList: PropTypes.arrayOf(PropTypes.object),
  visible: PropTypes.bool,
  width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
};

const defaultProps = {
  formatter: DefaultOptionFormatter,
  maxHeight: '174px',
  optionAlignment: 'outside',
  searchTerm: '',
  filterRef: React.createRef(),
  rootRef: React.createRef(),
};

class SelectList extends React.Component { // eslint-disable-line react/no-deprecated
  constructor(props) {
    super(props);

    this._cursorID = this.initCursorID();
    this.emptyId = `${this.props.id}-empty-message`;
    this.container = this.props.rootRef;
    this.filterField = this.props.filterRef;
    this.optionList = React.createRef();
    this.containerHeight = 0;
    this.getClass = this.getClass.bind(this);
    this.getCursorID = this.getCursorID.bind(this);
    this.scrollToCursor = this.scrollToCursor.bind(this);
    this.initCursorValue = this.initCursorValue.bind(this);
    this.handleOptionClick = this.handleOptionClick.bind(this);
    this.animationCallback = null;
    this.getRootClass = this.getRootClass.bind(this);
    this.renderList = this.renderList.bind(this);
    this.getAlert = this.getAlert.bind(this);

    this._alignmentClass = '';
    switch (props.optionAlignment) {
      case 'outside':
        this._alignmentClass = css.optionOutside;
        break;
      case 'start':
        this._alignmentClass = css.optionStart;
        break;
      case 'end':
        this._alignmentClass = css.optionEnd;
        break;
      case 'center':
        this.alignmentClass = css.optionCentered;
        break;
      default:
        break;
    }
  }

  componentDidMount() {
    if (this.props.selected && !this.props.filtered) {
      this.scrollToCursor(true);
    }
  }

  shouldComponentUpdate(nextProps) {
    if (!this.props.visible && !nextProps.visible) {
      return false;
    }
    return true;
  }

  componentDidUpdate(prevProps) {
    // if listbox is appearing...
    if (!prevProps.visible && this.props.visible) {
      if (this.props.selected) {
        this.scrollToCursor(true);
      }
      if (this.filterField.current) { // filter field not present in 'multiple' mode.
        this.filterField.current.focus();
      }
    } else if (this.props.filtered) {
      this.scrollToCursor();
    }

    // like a good overlay, send focus back to our trigger when we close...
    if (prevProps.visible && !this.props.visible) {
      if (this.props.controlRef.current) {
        this.props.controlRef.current.focus();
      }
    }

    if (this.props.cursoredValue !== prevProps.cursoredValue) {
      this.scrollToCursor();
    }

    if (prevProps.searchTerm !== '' && this.props.searchTerm === '') {
      if (this.props.selected !== '') {
        this.scrollToCursor(true);
      } else {
        this.scrollToCursor();
      }
    }
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.animationCallback);
  }

  initCursorID() {
    if (this.props.selected) {
      return `option-${this.props.selectedIndex}-${this.props.selected}`;
    }

    if (this.props.list.length) {
      return `option-0-${this.props.list[0].value}`;
    }

    return '';
  }

  initCursorValue(props) {
    if (props.selected !== '') {
      if (props.filtered) {
        return props.list[0];
      } else {
        const selectedInd = this.props.list.findIndex(o => o.value === this.props.selected);
        return this.props.list[selectedInd];
      }
    }
    return props.list[0];
  }

  getCursorID() {
    return this._cursorID;
  }

  scrollToCursor(useSelected) {
    if (this.props.list.length > 0) {
      this.animationCallback = requestAnimationFrame(() => {
        let cursored;
        if (useSelected && this.props.selected !== '') {
          if (this.optionList.current) {
            cursored = this.optionList.current.querySelector(`.${css.selected}`);
            if (cursored) {
              this.optionList.current.scrollTop = cursored.offsetTop;
            }
          }
        } else if (this.container.current) {
          cursored = this.container.current.querySelector(`.${css.cursor}`);
          if (cursored) {
            if (cursored.offsetTop > ((this.optionList.current.scrollTop + this.optionList.current.offsetHeight) - 30)) {
              const newScroll = cursored.offsetTop - (this.optionList.current.offsetHeight - cursored.offsetHeight);
              this.optionList.current.scrollTop = newScroll;
            } else if (cursored.offsetTop < this.optionList.current.scrollTop) {
              this.optionList.current.scrollTop = cursored.offsetTop;
            }
          }
        }
      });
    }
  }

  getClass(o) {
    // selected class..
    let selectCriteria;
    if (!this.props.multiple) {
      selectCriteria = o.value === this.props.selected;
    } else {
      selectCriteria = (this.props.selectedList.findIndex(i => i.value === o.value) !== -1);
    }

    return classnames(
      css.option,
      this._alignmentClass,
      { [`${css.cursor}`]: o.value === this.props.cursoredValue },
      { [`${css.selected}`]: selectCriteria },
    );
  }

  getRootClass() {
    return classnames(
      css.selectionListRoot,
      { 'sr-only': !this.props.visible },
    );
  }

  getActionIndicator(o) {
    const selectCriteria = (this.props.selectedList.findIndex(i => i.value === o.value) !== -1);
    const removeMsg = this.props.intl.formatMessage({ id: 'stripes-components.removeSelection' });
    const addMsg = this.props.intl.formatMessage({ id: 'stripes-components.addSelection' });
    return selectCriteria
      ? ➖
      : ✚;
  }

  handleOptionClick(o) {
    this.props.onChoose(o.value, o.label);
    this.props.onClickItem();
  }

  getAlert() {
    if (this.props.list.length === 0) {
      return (
{this.props.emptyMessage}
);
    }
    return null;
  }

  renderList() {
    if (this.props.list.length === 0) {
      return (

          -{this.props.intl.formatMessage({ id: 'stripes-components.selection.emptyList' })}-

      );
    }

    const Formatter = this.props.formatter;

    return this.props.list.map((o, i) => (
      <li
        key={`option-${i}-${o.value}`}
        role="option"
        tabIndex="-1"
        unselectable="on"
        aria-selected={o.value === this.props.selected}
        id={`option-${this.props.id}-${i}-${o.value}`}
        className={this.getClass(o)}
        onKeyDown={this.props.onFilterKeyDown}
        onClick={() => { this.handleOptionClick(o); }}
      >
        <Formatter option={o} searchTerm={this.props.searchTerm} />
        {
          this.props.multiple &&
          this.getActionIndicator(o)
        }

    ));
  }

  // returns the activeId, or if the list is empty, returns the id for the "empty message" list item.
  getActiveId() {
    if (this.props.list.length > 0) {
      return this.props.activeId;
    }
    return this.emptyId;
  }

  render() {
    return (
      <div
        hidden={this.props.visible ? undefined : 'true'}
        className={this.getRootClass()}
        style={{ width: this.props.width }}
        id={`sl-container-${this.props.id}`}
        ref={this.props.rootRef}
      >
        {
          !this.props.multiple &&

            <input
              type="text"
              role="listbox"
              aria-label={this.props.intl.formatMessage(
                { id: 'stripes-components.selection.filterOptionsLabel' },
                { label: this.props.label }
              )}
              placeholder={this.props.intl.formatMessage(
                { id: 'stripes-components.selection.filterOptionsPlaceholder' }
              )}
              onChange={this.props.onFilter}
              value={this.props.searchTerm}
              className={css.selectionFilter}
              ref={this.props.filterRef}
              aria-owns={`sl-${this.props.id}`}
              aria-activedescendant={this.props.activeId}
              onKeyDown={this.props.onFilterKeyDown}
            />

        }
        <ul
          role="listbox"
          className={css.selectionList}
          style={{ maxHeight: this.props.maxHeight }}
          ref={this.optionList}
          id={`sl-${this.props.id}`}
        >
          {this.renderList()}

          {this.getAlert()}

    );
  }
}

SelectList.propTypes = propTypes;
SelectList.defaultProps = defaultProps;

export default injectIntl(SelectList);
<commit_msg>Shorten long line<commit_after>/* SelectList
*  Used by both SingleSelect and MultiSelect controls to render their option lists
*/

import React from 'react';
import { intlShape } from 'react-intl';
import PropTypes from 'prop-types';
import classnames from 'classnames';

import injectIntl from '../InjectIntl';
import DefaultOptionFormatter from './DefaultOptionFormatter';
import css from './Selection.css';

const propTypes = {
  activeId: PropTypes.string,
  controlRef: PropTypes.object,
  cursoredValue: PropTypes.string,
  emptyMessage: PropTypes.string,
  filtered: PropTypes.bool,
  filterRef: PropTypes.object,
  formatter: PropTypes.func,
  id: PropTypes.string,
  intl: intlShape.isRequired,
  label: PropTypes.string,
  list: PropTypes.arrayOf(PropTypes.object),
  maxHeight: PropTypes.string,
  multiple: PropTypes.bool,
  onChoose: PropTypes.func,
  onClickItem: PropTypes.func,
  onFilter: PropTypes.func,
  onFilterKeyDown: PropTypes.func,
  optionAlignment: PropTypes.string,
  rootRef: PropTypes.object,
  searchTerm: PropTypes.string,
  selected: PropTypes.string,
  selectedIndex: PropTypes.number,
  selectedList: PropTypes.arrayOf(PropTypes.object),
  visible: PropTypes.bool,
  width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
};

const defaultProps = {
  formatter: DefaultOptionFormatter,
  maxHeight: '174px',
  optionAlignment: 'outside',
  searchTerm: '',
  filterRef: React.createRef(),
  rootRef: React.createRef(),
};

class SelectList extends React.Component { // eslint-disable-line react/no-deprecated
  constructor(props) {
    super(props);

    this._cursorID = this.initCursorID();
    this.emptyId = `${this.props.id}-empty-message`;
    this.container = this.props.rootRef;
    this.filterField = this.props.filterRef;
    this.optionList = React.createRef();
    this.containerHeight = 0;
    this.getClass = this.getClass.bind(this);
    this.getCursorID = this.getCursorID.bind(this);
    this.scrollToCursor = this.scrollToCursor.bind(this);
    this.initCursorValue = this.initCursorValue.bind(this);
    this.handleOptionClick = this.handleOptionClick.bind(this);
    this.animationCallback = null;
    this.getRootClass = this.getRootClass.bind(this);
    this.renderList = this.renderList.bind(this);
    this.getAlert = this.getAlert.bind(this);

    this._alignmentClass = '';
    switch (props.optionAlignment) {
      case 'outside':
        this._alignmentClass = css.optionOutside;
        break;
      case 'start':
        this._alignmentClass = css.optionStart;
        break;
      case 'end':
        this._alignmentClass = css.optionEnd;
        break;
      case 'center':
        this.alignmentClass = css.optionCentered;
        break;
      default:
        break;
    }
  }

  componentDidMount() {
    if (this.props.selected && !this.props.filtered) {
      this.scrollToCursor(true);
    }
  }

  shouldComponentUpdate(nextProps) {
    if (!this.props.visible && !nextProps.visible) {
      return false;
    }
    return true;
  }

  componentDidUpdate(prevProps) {
    // if listbox is appearing...
    if (!prevProps.visible && this.props.visible) {
      if (this.props.selected) {
        this.scrollToCursor(true);
      }
      if (this.filterField.current) { // filter field not present in 'multiple' mode.
        this.filterField.current.focus();
      }
    } else if (this.props.filtered) {
      this.scrollToCursor();
    }

    // like a good overlay, send focus back to our trigger when we close...
    if (prevProps.visible && !this.props.visible) {
      if (this.props.controlRef.current) {
        this.props.controlRef.current.focus();
      }
    }

    if (this.props.cursoredValue !== prevProps.cursoredValue) {
      this.scrollToCursor();
    }

    if (prevProps.searchTerm !== '' && this.props.searchTerm === '') {
      if (this.props.selected !== '') {
        this.scrollToCursor(true);
      } else {
        this.scrollToCursor();
      }
    }
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.animationCallback);
  }

  initCursorID() {
    if (this.props.selected) {
      return `option-${this.props.selectedIndex}-${this.props.selected}`;
    }

    if (this.props.list.length) {
      return `option-0-${this.props.list[0].value}`;
    }

    return '';
  }

  initCursorValue(props) {
    if (props.selected !== '') {
      if (props.filtered) {
        return props.list[0];
      } else {
        const selectedInd = this.props.list.findIndex(o => o.value === this.props.selected);
        return this.props.list[selectedInd];
      }
    }
    return props.list[0];
  }

  getCursorID() {
    return this._cursorID;
  }

  scrollToCursor(useSelected) {
    if (this.props.list.length > 0) {
      this.animationCallback = requestAnimationFrame(() => {
        let cursored;
        if (useSelected && this.props.selected !== '') {
          if (this.optionList.current) {
            cursored = this.optionList.current.querySelector(`.${css.selected}`);
            if (cursored) {
              this.optionList.current.scrollTop = cursored.offsetTop;
            }
          }
        } else if (this.container.current) {
          cursored = this.container.current.querySelector(`.${css.cursor}`);
          if (cursored) {
            if (
              cursored.offsetTop > ((this.optionList.current.scrollTop + this.optionList.current.offsetHeight) - 30)
            ) {
              const newScroll = cursored.offsetTop - (this.optionList.current.offsetHeight - cursored.offsetHeight);
              this.optionList.current.scrollTop = newScroll;
            } else if (cursored.offsetTop < this.optionList.current.scrollTop) {
              this.optionList.current.scrollTop = cursored.offsetTop;
            }
          }
        }
      });
    }
  }

  getClass(o) {
    // selected class..
    let selectCriteria;
    if (!this.props.multiple) {
      selectCriteria = o.value === this.props.selected;
    } else {
      selectCriteria = (this.props.selectedList.findIndex(i => i.value === o.value) !== -1);
    }

    return classnames(
      css.option,
      this._alignmentClass,
      { [`${css.cursor}`]: o.value === this.props.cursoredValue },
      { [`${css.selected}`]: selectCriteria },
    );
  }

  getRootClass() {
    return classnames(
      css.selectionListRoot,
      { 'sr-only': !this.props.visible },
    );
  }

  getActionIndicator(o) {
    const selectCriteria = (this.props.selectedList.findIndex(i => i.value === o.value) !== -1);
    const removeMsg = this.props.intl.formatMessage({ id: 'stripes-components.removeSelection' });
    const addMsg = this.props.intl.formatMessage({ id: 'stripes-components.addSelection' });
    return selectCriteria
      ? ➖
      : ✚;
  }

  handleOptionClick(o) {
    this.props.onChoose(o.value, o.label);
    this.props.onClickItem();
  }

  getAlert() {
    if (this.props.list.length === 0) {
      return (
{this.props.emptyMessage}
);
    }
    return null;
  }

  renderList() {
    if (this.props.list.length === 0) {
      return (

          -{this.props.intl.formatMessage({ id: 'stripes-components.selection.emptyList' })}-

      );
    }

    const Formatter = this.props.formatter;

    return this.props.list.map((o, i) => (
      <li
        key={`option-${i}-${o.value}`}
        role="option"
        tabIndex="-1"
        unselectable="on"
        aria-selected={o.value === this.props.selected}
        id={`option-${this.props.id}-${i}-${o.value}`}
        className={this.getClass(o)}
        onKeyDown={this.props.onFilterKeyDown}
        onClick={() => { this.handleOptionClick(o); }}
      >
        <Formatter option={o} searchTerm={this.props.searchTerm} />
        {
          this.props.multiple &&
          this.getActionIndicator(o)
        }

    ));
  }

  // returns the activeId, or if the list is empty, returns the id for the "empty message" list item.
  getActiveId() {
    if (this.props.list.length > 0) {
      return this.props.activeId;
    }
    return this.emptyId;
  }

  render() {
    return (
      <div
        hidden={this.props.visible ? undefined : 'true'}
        className={this.getRootClass()}
        style={{ width: this.props.width }}
        id={`sl-container-${this.props.id}`}
        ref={this.props.rootRef}
      >
        {
          !this.props.multiple &&

            <input
              type="text"
              role="listbox"
              aria-label={this.props.intl.formatMessage(
                { id: 'stripes-components.selection.filterOptionsLabel' },
                { label: this.props.label }
              )}
              placeholder={this.props.intl.formatMessage(
                { id: 'stripes-components.selection.filterOptionsPlaceholder' }
              )}
              onChange={this.props.onFilter}
              value={this.props.searchTerm}
              className={css.selectionFilter}
              ref={this.props.filterRef}
              aria-owns={`sl-${this.props.id}`}
              aria-activedescendant={this.props.activeId}
              onKeyDown={this.props.onFilterKeyDown}
            />

        }
        <ul
          role="listbox"
          className={css.selectionList}
          style={{ maxHeight: this.props.maxHeight }}
          ref={this.optionList}
          id={`sl-${this.props.id}`}
        >
          {this.renderList()}

          {this.getAlert()}

    );
  }
}

SelectList.propTypes = propTypes;
SelectList.defaultProps = defaultProps;

export default injectIntl(SelectList);
<|endoftext|>


<commit_before>
"use strict";

import {Controller as ListController} from './Data/List/Controller';
import {Controller as ItemController} from './Data/Item/Controller';

let registeredModules = {};

class Module {

    constructor(name, defs) {
        this.app = name;
        for (let key in defs) {
            this[key] = defs[key];
        }
    }

    static register(name, definition) {
        let dependencies = definition.depends || [];
        let app = angular.module(name, dependencies);
        let resolve = {Module: () => Module.retrieve(name)};
        /*
            Module: m,
            Model: () => angular.injector([app]).get('Model'),
            Service: () => angular.injector([app]).get('Service')
        };
        */
        registeredModules[name] = registeredModules[name] || {};
        app.config(['$routeProvider', '$translateProvider', function($routeProvider, $translateProvider) {
            if ('list' in definition) {
                registeredModules[name].listUrl = '/:language' + definition.list.url;
                $routeProvider.when('/:language' + definition.list.url, {
                    controller: definition.list.controller || ListController,
                    controllerAs: 'data',
                    templateUrl: definition.list.template || 'monad/src/Data/List/rows.html',
                    resolve
                });
            }
            if ('item' in definition) {
                registeredModules[name].itemUrl = '/:language' + definition.item.url;
                $routeProvider.when('/:language' + definition.item.url, {
                    controller: definition.item.controller || ItemController,
                    controllerAs: 'data',
                    templateUrl: definition.item.template || 'monad/src/Data/Item/update.html',
                    resolve
                });
            }
            if ('texts' in definition) {
                for (let language in definition.texts) {
                    var texts = {};
                    texts[name] = definition.texts[language];
                    $translateProvider.translations(language, texts);
                }
            }
        }]);
        ['Repository', 'Schema', 'Model', 'Controller'].map(key => {
            if (key in definition) {
                registeredModules[name][key] = definition[key];
            }
        });
        return name;
    }

    static retrieve(name) {
        return new Module(name, registeredModules[name] || {});
    }

};

Module.$inject = [];

export {Module};

<commit_msg>cleanup<commit_after>
"use strict";

import {Controller as ListController} from './Data/List/Controller';
import {Controller as ItemController} from './Data/Item/Controller';

let registeredModules = {};

class Module {

    constructor(name, defs) {
        this.app = name;
        for (let key in defs) {
            this[key] = defs[key];
        }
    }

    static register(name, definition) {
        let dependencies = [].concat(definition.depends || [], ['monad.Core']);
        let app = angular.module(name, dependencies);
        let resolve = {Module: () => Module.retrieve(name)};
        registeredModules[name] = registeredModules[name] || {};
        app.config(['$routeProvider', '$translateProvider', function($routeProvider, $translateProvider) {
            if ('list' in definition) {
                registeredModules[name].listUrl = '/:language' + definition.list.url;
                $routeProvider.when('/:language' + definition.list.url, {
                    controller: definition.list.controller || ListController,
                    controllerAs: 'data',
                    templateUrl: definition.list.template || 'monad/src/Data/List/rows.html',
                    resolve
                });
            }
            if ('item' in definition) {
                registeredModules[name].itemUrl = '/:language' + definition.item.url;
                $routeProvider.when('/:language' + definition.item.url, {
                    controller: definition.item.controller || ItemController,
                    controllerAs: 'data',
                    templateUrl: definition.item.template || 'monad/src/Data/Item/update.html',
                    resolve
                });
            }
            if ('texts' in definition) {
                for (let language in definition.texts) {
                    var texts = {};
                    texts[name] = definition.texts[language];
                    $translateProvider.translations(language, texts);
                }
            }
        }]);
        ['Repository', 'Schema', 'Model', 'Controller'].map(key => {
            if (key in definition) {
                registeredModules[name][key] = definition[key];
            }
        });
        return name;
    }

    static retrieve(name) {
        return new Module(name, registeredModules[name] || {});
    }

};

Module.$inject = [];

export {Module};

<|endoftext|>


<commit_before>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _store = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    // meta_data setter/getter
    that.meta_data = function ( value ) {
        // set it just once
//        _assert.is_equal( meta_data.length, 0,
//                          "meta_data already assigned" );

        meta_data = value;
    };

    // get metadata about available datasets
    that.meta_datasets = function () {
        return meta_data;
    };

    // get metadata about views available in a cerain dataset (name perspectives comes from db!)
    that.meta_views = function ( dataset_id ) {
        return meta_data[ dataset_id ]['perspectives'];
    };

    // check if group exists
    that.group_exists = function ( data ) {
        if( find_group( data ) === -1) {
            return false;
        }
        return true;
    };

    // creates a new group and sets an activ group index
    that.create_group = function (data) {
        // create a group for new data collection
        groups.push( group( data ));
        that.active_group( groups.length - 1 );
    };

    // creates a new group or sets an active group index to apropriate group
    that.create_new_group = function ( data ) {
        var found = find_group( data );

        if( found !== -1 ) {
            that.active_group( found );
            return false;
        }

        // create a group for new data collection
        groups.push( group( data ));
        that.active_group( groups.length - 1 );

        return true;
    };

    that.dataset = function () {
        return that.active_group()['dataset'];
    };

    that.view = function () {
        return that.active_group()['view'];
    };

    that.issue = function () {
        return that.active_group()['issue'];
    };

    that.init_basic_sheet = function ( data ) {
        var active_grp = that.active_group();

        // store original version of collection
        active_grp['name'] = data['name'];
        active_grp['basic_rows'] = sheet( data, true );
        // add data to mutable list of sheets
        active_grp['sheets'].push( sheet( data ) );
    };

    that.set_active_columnes = function ( columns ) {
        that.active_sheet()['columns'] = columns;
    };

    that.get_column_from_group = function( id ) {
        var columns = that.active_group()['columns'];
        return columns.filter( function ( col ) {
            return col['key'] === id;
        })[0];
    };

    that.active_columns = function () {
        return that.active_sheet()['columns'];
    };

    that.group_columns = function () {
        return that.active_group()['columns'];
    };

    //TODO not needed
    that.basic_schema = function () {
        var full_schema = that.active_columns();

        return full_schema.filter( function ( element ) {
            return element['basic'] === true;
        });
    };

    that.set_selected = function ( id, state ) {
        var node, rows = that.active_rows();
        var i, len = rows.length;

        for( i = 0; i < len; i += 1 ) {
            node = rows[i];
            if( node['data']['idef'] === id ) {
                node['state']['selected'] = state;
                return;
            }
        }
//        that.active_rows().forEach( function ( node ) {
//            if( node['data']['idef'] === id ) {
//                node['state']['selected'] = true;
//            }
//            else {
//                node['state']['selected'] = false;
//            }
//        });
    };

    that.set_open = function ( id, state ) {
        var node, rows = that.active_rows();
        var i, len = rows.length;

        for( i = 0; i < len; i += 1 ) {
            node = rows[i];
            if( node['data']['idef'] === id ) {
                node['state']['open'] = state;
                return;
            }
        }
    };

    that.set_visible = function ( id, state ) {
        var node, rows = that.active_rows();
        var i, len = rows.length;
        for ( i = 0; i < len; i += 1 ) {
            node = rows[i];
            if ( node['data']['idef'] === id ) {
                node['state']['visible'] = state;
                return;
            }

        }

    };

    that.active_sheet_index = function ( new_active_sheet_num ) {
        if( arguments.length === 0 ) {
            return that.active_group()['active_sheet_number'];
        }
        that.active_group()['active_sheet_number'] = new_active_sheet_num;
    };

    that.active_group_index = function () {
        return active_group_number;
    };

    that.next_sheet_number = function () {
        return that.active_group()['sheets'].length;
    };

    that.max_group_number = function () {
        return groups.length;
    };

    that.active_rows = function () {
        return that.active_sheet()['rows'];
    };

//    that.active_pending_nodes = function () {
//        return that.active_sheet()['pending_nodes'];
//    };

    that.active_basic_changed = function ( value ) {
        that.active_group()['basic_changed'] = value;
    };

    that.active_filtered = function () {
        return that.active_sheet()['filtered'];
    };

    that.active_sorted = function () {
        return that.active_sheet()['sorted'];
    };

    that.set_sorted = function ( is_sorted ) {
        that.active_sheet()['sorted'] = is_sorted;
    }

    // active sheet getter / setter
    that.active_sheet = function ( value ) {
        var active_grp = that.active_group();

        if( arguments.length === 0 ) {
            return active_grp['sheets'][active_grp['active_sheet_number']];
        }

        active_grp['active_sheet_number'] = value;
    };

    // active group getter / setter
    that.active_group = function ( value ) {
        var num;
        if( arguments.length === 0 ) {
            return groups[ active_group_number ];

        }else if ( typeof value === 'number' ){

            active_group_number = value;

        }else if ( typeof value === 'object' &&
            typeof value.dataset === 'string' &&
            typeof value.view === 'string' ){

                num = find_group( value );
                if ( num === -1 ) {
                return -1
                }else{
                    active_group_number = num;
                }
        }
    };

    that.active_group_name = function () {
        return that.active_group()['name'];
    };

    that.add_data = function ( new_data ) {
        var rows = that.active_rows();

        new_data
            .map( function ( row ) {
                return {
                    data: row,
                    state: { open: false, selected: false, visible: true }
                };
            })
            .forEach( function ( e ) {
                rows.push( e );
            });
    };

    that.add_new_sheet = function ( sheet ) {
        var active_grp = that.active_group();
        var next_sheet_number = that.next_sheet_number() ;

        active_grp['sheets'].push( sheet );
        that.active_sheet_index( next_sheet_number );
    };

    that.get_all_groups = function () {
        return groups;
    };

    // check if column exists in active_sheet
    that.is_column_in_active_sheet = function( key ){
        var i;
        var cols = that.active_columns();

        for( i = 0; i < cols.length; i += 1 ) {
            if( cols[i]['key'] === key ){
                    return true;
            }
        }
        return false;
    };

    that.get_group = function ( group ) {
        return groups[group];
    };

    that.get_sheet = function ( group, sheet ) {
        return groups[group]['sheets'][sheet];
    };

    that.remove_active_group = function() {
        if (groups.length === 1){
            return false;
        }
        groups.splice ( that.active_group_index(), 1 );
        if (that.active_group_index() !== 0){
            active_group_number = that.active_group_index()-1;
        }
        return true;
    }

    that.remove_active_sheet = function () {
        var active_grp = that.active_group();
        var active_group_sheets = active_grp['sheets'];
        var active_sheet_num = that.active_sheet_index();
        if (groups.length === 1 && active_group_sheets.length === 1 ){
            return false;
        }
        active_group_sheets.splice(active_sheet_num, 1 );
        if (active_group_sheets.length === 0 ){
            that.remove_active_group();
        }else if (active_sheet_num !== 0 ) {
                active_grp['active_sheet_number'] = active_sheet_num - 1  ;
            }
        return true;
    };

    that.active_sheet_name = function (sheet_name) {
        if( arguments.length === 0 ) {
            return that.active_sheet()['name'];
        }
        that.active_sheet()['name'] = sheet_name;
    };

    that.reset_sheet = function () {
        var active_sheet = that.active_sheet();
        var basic_rows = $.extend( true, [], that.active_group()['basic_rows'] );
        var total = active_sheet['rows']['total'];

        active_sheet['rows'] = basic_rows;
        active_sheet['rows']['total'] = total;
    };

    that.next_sheet_name = function () {
        var next_num=1;
        var sheet_name;
        that.active_group()['sheets'].forEach( function (sheet, sheet_num){
            if ( sheet['name'].indexOf('Arkusz') !== -1 ) {
                sheet_name = sheet['name'].split(' ');
                if ( sheet_name[1] >= next_num ){
                    next_num = sheet_name[1];
                    next_num++;
                   };
            }
        });

        return 'Arkusz ' + next_num;
    };

    that.get_info = function ( id ) {
        var node = that.active_rows().filter( function ( e ) {
                return e['idef'] === id;
                })
                .pop();

        return node['data']['info'];
    };

    that.get_all_sheets_num = function () {
        var groups = that.get_all_groups();
        var num = 0;
        groups.forEach( function ( group ){
            num += group['sheets'].length;
        });
        return num;
    };

    that.restore_state = function ( state ) {
        groups = state;
        active_group_number = 0;
        that.active_sheet_index( 0 );
    };

// P R I V A T E   I N T E R F A C E
    // data about available datasets and their views
    var meta_data = [];

    // a store for a sheets tab in the GUI
    var groups = [];
    var active_group_number = null;

    // returns group id if it exists or -1 if there is no such a group
    function find_group( data ) {
        var i;

        for( i = 0; i < groups.length; i += 1 ) {
            if( data['dataset'] === groups[i]['dataset'] &&
                data['view'] === groups[i]['view'] &&
                data['issue'] === groups[i]['issue'] ) {

                return i;
            }
        }

        return -1;
    }

// O B J E C T   F A C T O R I E S
    // a single sheet
    function sheet( data, basic ) {
        var cols = that.active_group()['columns'].filter( function ( e ) {
                    return e['basic'] === true;
                });
        var rows = data['rows'].map( function ( row ) {
                                    return {
                                        data: row,
                                        state: {
                                            open: false,
                                            selected: false,
                                            visible: true
                                        }
                                    };
                                });

        // if total present in collection move it to special position
        if( rows[ rows.length - 1 ]['data']['idef'].indexOf( '9999' ) !== -1 ) {
            rows['total'] = rows.pop();
        }

        if( !!basic ) {
            return rows;
        }

        return {
            'columns': cols,
            'rows': rows,
            'name': data['name'],
            'filtered': false,
            'sorted': false
        };
    }

    // list of all sheets of the same dataset/view/issue
    function group( data ) {
        return {
            'name': null,
            'dataset': data['dataset'].toString(),
            'view': ( data['view'] || data['perspective'] ).toString(),
            'issue': data['issue'].toString(),
            'columns': data['columns'],
            'active_sheet_number': 0,
            'sheets': [],
            'basic_rows': null,
            'basic_changed': false
        };
    }

    return that;

}) ();
<commit_msg>fix store.get_info bug<commit_after>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _store = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    // meta_data setter/getter
    that.meta_data = function ( value ) {
        // set it just once
//        _assert.is_equal( meta_data.length, 0,
//                          "meta_data already assigned" );

        meta_data = value;
    };

    // get metadata about available datasets
    that.meta_datasets = function () {
        return meta_data;
    };

    // get metadata about views available in a cerain dataset (name perspectives comes from db!)
    that.meta_views = function ( dataset_id ) {
        return meta_data[ dataset_id ]['perspectives'];
    };

    // check if group exists
    that.group_exists = function ( data ) {
        if( find_group( data ) === -1) {
            return false;
        }
        return true;
    };

    // creates a new group and sets an activ group index
    that.create_group = function (data) {
        // create a group for new data collection
        groups.push( group( data ));
        that.active_group( groups.length - 1 );
    };

    // creates a new group or sets an active group index to apropriate group
    that.create_new_group = function ( data ) {
        var found = find_group( data );

        if( found !== -1 ) {
            that.active_group( found );
            return false;
        }

        // create a group for new data collection
        groups.push( group( data ));
        that.active_group( groups.length - 1 );

        return true;
    };

    that.dataset = function () {
        return that.active_group()['dataset'];
    };

    that.view = function () {
        return that.active_group()['view'];
    };

    that.issue = function () {
        return that.active_group()['issue'];
    };

    that.init_basic_sheet = function ( data ) {
        var active_grp = that.active_group();

        // store original version of collection
        active_grp['name'] = data['name'];
        active_grp['basic_rows'] = sheet( data, true );
        // add data to mutable list of sheets
        active_grp['sheets'].push( sheet( data ) );
    };

    that.set_active_columnes = function ( columns ) {
        that.active_sheet()['columns'] = columns;
    };

    that.get_column_from_group = function( id ) {
        var columns = that.active_group()['columns'];
        return columns.filter( function ( col ) {
            return col['key'] === id;
        })[0];
    };

    that.active_columns = function () {
        return that.active_sheet()['columns'];
    };

    that.group_columns = function () {
        return that.active_group()['columns'];
    };

    //TODO not needed
    that.basic_schema = function () {
        var full_schema = that.active_columns();

        return full_schema.filter( function ( element ) {
            return element['basic'] === true;
        });
    };

    that.set_selected = function ( id, state ) {
        var node, rows = that.active_rows();
        var i, len = rows.length;

        for( i = 0; i < len; i += 1 ) {
            node = rows[i];
            if( node['data']['idef'] === id ) {
                node['state']['selected'] = state;
                return;
            }
        }
//        that.active_rows().forEach( function ( node ) {
//            if( node['data']['idef'] === id ) {
//                node['state']['selected'] = true;
//            }
//            else {
//                node['state']['selected'] = false;
//            }
//        });
    };

    that.set_open = function ( id, state ) {
        var node, rows = that.active_rows();
        var i, len = rows.length;

        for( i = 0; i < len; i += 1 ) {
            node = rows[i];
            if( node['data']['idef'] === id ) {
                node['state']['open'] = state;
                return;
            }
        }
    };

    that.set_visible = function ( id, state ) {
        var node, rows = that.active_rows();
        var i, len = rows.length;
        for ( i = 0; i < len; i += 1 ) {
            node = rows[i];
            if ( node['data']['idef'] === id ) {
                node['state']['visible'] = state;
                return;
            }

        }

    };

    that.active_sheet_index = function ( new_active_sheet_num ) {
        if( arguments.length === 0 ) {
            return that.active_group()['active_sheet_number'];
        }
        that.active_group()['active_sheet_number'] = new_active_sheet_num;
    };

    that.active_group_index = function () {
        return active_group_number;
    };

    that.next_sheet_number = function () {
        return that.active_group()['sheets'].length;
    };

    that.max_group_number = function () {
        return groups.length;
    };

    that.active_rows = function () {
        return that.active_sheet()['rows'];
    };

//    that.active_pending_nodes = function () {
//        return that.active_sheet()['pending_nodes'];
//    };

    that.active_basic_changed = function ( value ) {
        that.active_group()['basic_changed'] = value;
    };

    that.active_filtered = function () {
        return that.active_sheet()['filtered'];
    };

    that.active_sorted = function () {
        return that.active_sheet()['sorted'];
    };

    that.set_sorted = function ( is_sorted ) {
        that.active_sheet()['sorted'] = is_sorted;
    }

    // active sheet getter / setter
    that.active_sheet = function ( value ) {
        var active_grp = that.active_group();

        if( arguments.length === 0 ) {
            return active_grp['sheets'][active_grp['active_sheet_number']];
        }

        active_grp['active_sheet_number'] = value;
    };

    // active group getter / setter
    that.active_group = function ( value ) {
        var num;
        if( arguments.length === 0 ) {
            return groups[ active_group_number ];

        }else if ( typeof value === 'number' ){

            active_group_number = value;

        }else if ( typeof value === 'object' &&
            typeof value.dataset === 'string' &&
            typeof value.view === 'string' ){

                num = find_group( value );
                if ( num === -1 ) {
                return -1
                }else{
                    active_group_number = num;
                }
        }
    };

    that.active_group_name = function () {
        return that.active_group()['name'];
    };

    that.add_data = function ( new_data ) {
        var rows = that.active_rows();

        new_data
            .map( function ( row ) {
                return {
                    data: row,
                    state: { open: false, selected: false, visible: true }
                };
            })
            .forEach( function ( e ) {
                rows.push( e );
            });
    };

    that.add_new_sheet = function ( sheet ) {
        var active_grp = that.active_group();
        var next_sheet_number = that.next_sheet_number() ;

        active_grp['sheets'].push( sheet );
        that.active_sheet_index( next_sheet_number );
    };

    that.get_all_groups = function () {
        return groups;
    };

    // check if column exists in active_sheet
    that.is_column_in_active_sheet = function( key ){
        var i;
        var cols = that.active_columns();

        for( i = 0; i < cols.length; i += 1 ) {
            if( cols[i]['key'] === key ){
                    return true;
            }
        }
        return false;
    };

    that.get_group = function ( group ) {
        return groups[group];
    };

    that.get_sheet = function ( group, sheet ) {
        return groups[group]['sheets'][sheet];
    };

    that.remove_active_group = function() {
        if (groups.length === 1){
            return false;
        }
        groups.splice ( that.active_group_index(), 1 );
        if (that.active_group_index() !== 0){
            active_group_number = that.active_group_index()-1;
        }
        return true;
    }

    that.remove_active_sheet = function () {
        var active_grp = that.active_group();
        var active_group_sheets = active_grp['sheets'];
        var active_sheet_num = that.active_sheet_index();
        if (groups.length === 1 && active_group_sheets.length === 1 ){
            return false;
        }
        active_group_sheets.splice(active_sheet_num, 1 );
        if (active_group_sheets.length === 0 ){
            that.remove_active_group();
        }else if (active_sheet_num !== 0 ) {
                active_grp['active_sheet_number'] = active_sheet_num - 1  ;
            }
        return true;
    };

    that.active_sheet_name = function (sheet_name) {
        if( arguments.length === 0 ) {
            return that.active_sheet()['name'];
        }
        that.active_sheet()['name'] = sheet_name;
    };

    that.reset_sheet = function () {
        var active_sheet = that.active_sheet();
        var basic_rows = $.extend( true, [], that.active_group()['basic_rows'] );
        var total = active_sheet['rows']['total'];

        active_sheet['rows'] = basic_rows;
        active_sheet['rows']['total'] = total;
    };

    that.next_sheet_name = function () {
        var next_num=1;
        var sheet_name;
        that.active_group()['sheets'].forEach( function (sheet, sheet_num){
            if ( sheet['name'].indexOf('Arkusz') !== -1 ) {
                sheet_name = sheet['name'].split(' ');
                if ( sheet_name[1] >= next_num ){
                    next_num = sheet_name[1];
                    next_num++;
                   };
            }
        });

        return 'Arkusz ' + next_num;
    };

    that.get_info = function ( id ) {
        var node = that.active_rows().filter( function ( e ) {
                return e['data']['idef'] === id;
                })
                .pop();

        return node['data']['info'];
    };

    that.get_all_sheets_num = function () {
        var groups = that.get_all_groups();
        var num = 0;
        groups.forEach( function ( group ){
            num += group['sheets'].length;
        });
        return num;
    };

    that.restore_state = function ( state ) {
        groups = state;
        active_group_number = 0;
        that.active_sheet_index( 0 );
    };

// P R I V A T E   I N T E R F A C E
    // data about available datasets and their views
    var meta_data = [];

    // a store for a sheets tab in the GUI
    var groups = [];
    var active_group_number = null;

    // returns group id if it exists or -1 if there is no such a group
    function find_group( data ) {
        var i;

        for( i = 0; i < groups.length; i += 1 ) {
            if( data['dataset'] === groups[i]['dataset'] &&
                data['view'] === groups[i]['view'] &&
                data['issue'] === groups[i]['issue'] ) {

                return i;
            }
        }

        return -1;
    }

// O B J E C T   F A C T O R I E S
    // a single sheet
    function sheet( data, basic ) {
        var cols = that.active_group()['columns'].filter( function ( e ) {
                    return e['basic'] === true;
                });
        var rows = data['rows'].map( function ( row ) {
                                    return {
                                        data: row,
                                        state: {
                                            open: false,
                                            selected: false,
                                            visible: true
                                        }
                                    };
                                });

        // if total present in collection move it to special position
        if( rows[ rows.length - 1 ]['data']['idef'].indexOf( '9999' ) !== -1 ) {
            rows['total'] = rows.pop();
        }

        if( !!basic ) {
            return rows;
        }

        return {
            'columns': cols,
            'rows': rows,
            'name': data['name'],
            'filtered': false,
            'sorted': false
        };
    }

    // list of all sheets of the same dataset/view/issue
    function group( data ) {
        return {
            'name': null,
            'dataset': data['dataset'].toString(),
            'view': ( data['view'] || data['perspective'] ).toString(),
            'issue': data['issue'].toString(),
            'columns': data['columns'],
            'active_sheet_number': 0,
            'sheets': [],
            'basic_rows': null,
            'basic_changed': false
        };
    }

    return that;

}) ();
<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function() {

var IMPORT_LINK_TYPE = 'import';

// highlander object for parsing a document tree

var componentParser = {
  selectors: [
    'link[rel=' + IMPORT_LINK_TYPE + ']',
    'link[rel=stylesheet]',
    'script[src]',
    'script',
    'style',
    'element'
  ],
  map: {
    link: 'parseLink',
    script: 'parseScript',
    element: 'parseElement',
    style: 'parseStyle'
  },
  parsed: {},
  parse: function(inDocument) {
    // TODO(sorvell): parse each document only once.
    // We should be able to mark documents that have been parsed.
    // A loading issue is preventing us from doing that, so temporarily
    // use a url cache.
    var url = inDocument.URL || inDocument._URL;
    if (inDocument && !this.parsed[url]) {
      this.parsed[url] = true;
      // upgrade all upgradeable static elements, anything dynamically
      // created should be caught by a watchDOM() observer
      document.upgradeElements(inDocument);
      // all parsable elements in inDocument (depth-first pre-order traversal)
      var elts = inDocument.querySelectorAll(cp.selectors);
      // for each parsable node type in inDocument, call the parsing method
      // to it's local name
      forEach(elts, function(e) {
        //console.log(map[e.localName] + ":", path.nodeUrl(e));
        cp[cp.map[e.localName]](e);
      });
    }
  },
  parseLink: function(inLinkElt) {
    // rel=components
    if (isDocumentLink(inLinkElt)) {
      cp.parse(inLinkElt.__resource);
    } else if (!inMainDocument(inLinkElt) && inLinkElt.parentNode &&
      !isElementElementChild(inLinkElt)) {
      document.head.appendChild(inLinkElt);
    }
  },
  parseScript: function(inScriptElt) {
    // ignore scripts in primary document, they are already loaded
    if (inMainDocument(inScriptElt)) {
      return;
    }
    // ignore scripts inside <element>
    if (isElementElementChild(inScriptElt)) {
      return;
    }
    // otherwise, evaluate now
    var code = inScriptElt.__resource || inScriptElt.textContent;
    if (code) {
      eval.call(window, code);
    }
  },
  parseStyle: function(inStyleElt) {
    if (!isElementElementChild(inStyleElt)) {
      document.querySelector('head').appendChild(inStyleElt);
    }
  },
  parseElement: function(inElementElt) {
    new HTMLElementElement(inElementElt);
  }
};

var cp = componentParser;

function inMainDocument(inElt) {
  return inElt.ownerDocument === document ||
    // TODO(sjmiles): ShadowDOMPolyfill intrusion
    inElt.ownerDocument.impl === document;
}

function isDocumentLink(inElt) {
  return (inElt.localName === 'link'
      && inElt.getAttribute('rel') === IMPORT_LINK_TYPE);
}

function isElementElementChild(inElt) {
  if (inElt.parentNode && inElt.parentNode.localName === 'element') {
    return true;
  }
}

var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);

// bootstrap parsing

// IE shim for CustomEvent
if (typeof window.CustomEvent !== 'function') {
  window.CustomEvent = function(inType) {
     var e = document.createEvent('HTMLEvents');
     e.initEvent(inType, true, true);
     return e;
  };
}

function bootstrap() {
  // go async so call stack can unwind
  setTimeout(function() {
    // install auto-upgrader on main document
    document.watchDOM(document.body);
    // parse document
    componentParser.parse(document);
    // TODO(sjmiles): ShadowDOM polyfill pollution
    var doc = window.ShadowDOMPolyfill ?
          ShadowDOMPolyfill.wrap(document)
              : document;
    // notify system
    doc.body.dispatchEvent(
      new CustomEvent('WebComponentsReady', {bubbles: true})
    );
  }, 0);
}

// TODO(sjmiles): 'window' has no wrappability under ShadowDOM polyfill, so
// we are forced to split into two versions

if (window.HTMLImports) {
  document.addEventListener('HTMLImportsLoaded', bootstrap);
} else {
  window.addEventListener('load', bootstrap);
}

})();<commit_msg>simplified parse deduping<commit_after>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function() {

var IMPORT_LINK_TYPE = 'import';

// highlander object for parsing a document tree

var componentParser = {
  selectors: [
    'link[rel=' + IMPORT_LINK_TYPE + ']',
    'link[rel=stylesheet]',
    'script[src]',
    'script',
    'style',
    'element'
  ],
  map: {
    link: 'parseLink',
    script: 'parseScript',
    element: 'parseElement',
    style: 'parseStyle'
  },
  parse: function(inDocument) {
    if (!inDocument.__parsed) {
      // only parse once
      inDocument.__parsed = true;
      // upgrade all upgradeable static elements, anything dynamically
      // created should be caught by a watchDOM() observer
      document.upgradeElements(inDocument);
      // all parsable elements in inDocument (depth-first pre-order traversal)
      var elts = inDocument.querySelectorAll(cp.selectors);
      // for each parsable node type in inDocument, call the parsing method
      // to it's local name
      forEach(elts, function(e) {
        //console.log(map[e.localName] + ":", path.nodeUrl(e));
        cp[cp.map[e.localName]](e);
      });
    }
  },
  parseLink: function(inLinkElt) {
    // rel=components
    if (isDocumentLink(inLinkElt)) {
      cp.parse(inLinkElt.__resource);
    } else if (!inMainDocument(inLinkElt) && inLinkElt.parentNode &&
      !isElementElementChild(inLinkElt)) {
      document.head.appendChild(inLinkElt);
    }
  },
  parseScript: function(inScriptElt) {
    // ignore scripts in primary document, they are already loaded
    if (inMainDocument(inScriptElt)) {
      return;
    }
    // ignore scripts inside <element>
    if (isElementElementChild(inScriptElt)) {
      return;
    }
    // otherwise, evaluate now
    var code = inScriptElt.__resource || inScriptElt.textContent;
    if (code) {
      eval.call(window, code);
    }
  },
  parseStyle: function(inStyleElt) {
    if (!isElementElementChild(inStyleElt)) {
      document.querySelector('head').appendChild(inStyleElt);
    }
  },
  parseElement: function(inElementElt) {
    new HTMLElementElement(inElementElt);
  }
};

var cp = componentParser;

function inMainDocument(inElt) {
  return inElt.ownerDocument === document ||
    // TODO(sjmiles): ShadowDOMPolyfill intrusion
    inElt.ownerDocument.impl === document;
}

function isDocumentLink(inElt) {
  return (inElt.localName === 'link'
      && inElt.getAttribute('rel') === IMPORT_LINK_TYPE);
}

function isElementElementChild(inElt) {
  if (inElt.parentNode && inElt.parentNode.localName === 'element') {
    return true;
  }
}

var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);

// bootstrap parsing

// IE shim for CustomEvent
if (typeof window.CustomEvent !== 'function') {
  window.CustomEvent = function(inType) {
     var e = document.createEvent('HTMLEvents');
     e.initEvent(inType, true, true);
     return e;
  };
}

function bootstrap() {
  // go async so call stack can unwind
  setTimeout(function() {
    // install auto-upgrader on main document
    document.watchDOM(document.body);
    // parse document
    componentParser.parse(document);
    // TODO(sjmiles): ShadowDOM polyfill pollution
    var doc = window.ShadowDOMPolyfill ?
          ShadowDOMPolyfill.wrap(document)
              : document;
    // notify system
    doc.body.dispatchEvent(
      new CustomEvent('WebComponentsReady', {bubbles: true})
    );
  }, 0);
}

// TODO(sjmiles): 'window' has no wrappability under ShadowDOM polyfill, so
// we are forced to split into two versions

if (window.HTMLImports) {
  document.addEventListener('HTMLImportsLoaded', bootstrap);
} else {
  window.addEventListener('load', bootstrap);
}

})();<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function() {

// TODO(sjmiles): ShadowDOM polyfill pollution
var sdocument = window.wrap ? wrap(document) : document;

// highlander object for parsing a document tree

var componentParser = {
  selectors: [
    'link[rel=component]',
    'link[rel=stylesheet]',
    'script[src]',
    'script',
    'style',
    'element'
  ],
  map: {
    link: 'parseLink',
    script: 'parseScript',
    element: 'parseElement',
    style: 'parseStyle'
  },
  parse: function(inDocument) {
    if (inDocument) {
      // upgrade everything
      document.upgradeElements(inDocument);
      // all parsable elements in inDocument (depth-first pre-order traversal)
      var elts = inDocument.querySelectorAll(cp.selectors);
      // for each parsable node type in inDocument, call the parsing method
      // to it's local name
      forEach(elts, function(e) {
        //console.log(map[e.localName] + ":", path.nodeUrl(e));
        cp[cp.map[e.localName]](e);
      });
      // upgrade everything
      document.upgradeElements(inDocument);
    }
  },
  parseLink: function(inLinkElt) {
    // rel=components
    if (this.isDocumentLink(inLinkElt)) {
      cp.parse(inLinkElt.__resource);
    } else {
      // rel=stylesheet
      // inject into main body
    }
  },
  isDocumentLink: function(inElt) {
    return (inElt.localName === 'link'
        && inElt.getAttribute('rel') === 'component');
  },
  parseScript: function(inScriptElt) {
    // ignore scripts in primary document, they are already loaded
    if (inScriptElt.ownerDocument === sdocument) {
      return;
    }
    // ignore scripts inside <element>
    if (inScriptElt.parentNode.localName === 'element') {
      return;
    }
    // otherwise, evaluate now
    var code = inScriptElt.__resource || inScriptElt.textContent;
    if (code) {
      eval(code);
    }
  },
  parseStyle: function(inStyleElt) {
    document.querySelector("head").appendChild(inStyleElt);
  },
  parseElement: function(inElementElt) {
    new HTMLElementElement(inElementElt);
  }
};

var cp = componentParser;

var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);

// bootstrap parsing

function bootstrap() {
  // go async so call stack can unwind
  setTimeout(function() {
    // parse document
    componentParser.parse(document);
    // notify system
    sdocument.body.dispatchEvent(
      new CustomEvent('WebComponentsReady', {bubbles: true})
    );
  }, 0);
}

// TODO(sjmiles):
// 'window' has wrappability under ShadowDOM polyfill, so
// we are forced to split into two version
// !webComponents && ShadowDOM will not work
if (window.webComponents) {
  sdocument.addEventListener('WebComponentsLoaded', bootstrap);
} else {
  window.addEventListener('load', bootstrap);
}

})();<commit_msg>shim CustomEvent constructor for IE<commit_after>/*
 * Copyright 2013 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function() {

// TODO(sjmiles): ShadowDOM polyfill pollution
var sdocument = window.wrap ? wrap(document) : document;

// highlander object for parsing a document tree

var componentParser = {
  selectors: [
    'link[rel=component]',
    'link[rel=stylesheet]',
    'script[src]',
    'script',
    'style',
    'element'
  ],
  map: {
    link: 'parseLink',
    script: 'parseScript',
    element: 'parseElement',
    style: 'parseStyle'
  },
  parse: function(inDocument) {
    if (inDocument) {
      // upgrade everything
      document.upgradeElements(inDocument);
      // all parsable elements in inDocument (depth-first pre-order traversal)
      var elts = inDocument.querySelectorAll(cp.selectors);
      // for each parsable node type in inDocument, call the parsing method
      // to it's local name
      forEach(elts, function(e) {
        //console.log(map[e.localName] + ":", path.nodeUrl(e));
        cp[cp.map[e.localName]](e);
      });
      // upgrade everything
      document.upgradeElements(inDocument);
    }
  },
  parseLink: function(inLinkElt) {
    // rel=components
    if (this.isDocumentLink(inLinkElt)) {
      cp.parse(inLinkElt.__resource);
    } else {
      // rel=stylesheet
      // inject into main body
    }
  },
  isDocumentLink: function(inElt) {
    return (inElt.localName === 'link'
        && inElt.getAttribute('rel') === 'component');
  },
  parseScript: function(inScriptElt) {
    // ignore scripts in primary document, they are already loaded
    if (inScriptElt.ownerDocument === sdocument) {
      return;
    }
    // ignore scripts inside <element>
    if (inScriptElt.parentNode.localName === 'element') {
      return;
    }
    // otherwise, evaluate now
    var code = inScriptElt.__resource || inScriptElt.textContent;
    if (code) {
      eval(code);
    }
  },
  parseStyle: function(inStyleElt) {
    document.querySelector("head").appendChild(inStyleElt);
  },
  parseElement: function(inElementElt) {
    new HTMLElementElement(inElementElt);
  }
};

var cp = componentParser;

var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);

// bootstrap parsing

// IE shim for CustomEvent
if (typeof CustomEvent !== 'function') {
  var CustomEvent = function(inType) {
     var e = document.createEvent('HTMLEvents');
     e.initEvent(inType, true, true);
     return e;
  };
}

function bootstrap() {
  // go async so call stack can unwind
  setTimeout(function() {
    // parse document
    componentParser.parse(document);
    // notify system
    sdocument.body.dispatchEvent(
      new CustomEvent('WebComponentsReady', {bubbles: true})
    );
  }, 0);
}

// TODO(sjmiles):
// 'window' has wrappability under ShadowDOM polyfill, so
// we are forced to split into two version
// !webComponents && ShadowDOM will not work
if (window.webComponents) {
  sdocument.addEventListener('WebComponentsLoaded', bootstrap);
} else {
  window.addEventListener('load', bootstrap);
}

})();<|endoftext|>


<commit_before>import * as ACTIONS from 'constants/action_types';
import Lbryio from 'lbryio';
import { doNotify, MODALS } from 'lbry-redux';
import { selectUnclaimedRewards } from 'redux/selectors/rewards';
import { selectUserIsRewardApproved } from 'redux/selectors/user';
import rewards from 'rewards';

export function doRewardList() {
  return dispatch => {
    dispatch({
      type: ACTIONS.FETCH_REWARDS_STARTED,
    });

    Lbryio.call('reward', 'list', { multiple_rewards_per_type: true })
      .then(userRewards => {
        dispatch({
          type: ACTIONS.FETCH_REWARDS_COMPLETED,
          data: { userRewards },
        });
      })
      .catch(() => {
        dispatch({
          type: ACTIONS.FETCH_REWARDS_COMPLETED,
          data: { userRewards: [] },
        });
      });
  };
}

export function doClaimRewardType(rewardType) {
  return (dispatch, getState) => {
    const state = getState();
    const unclaimedRewards = selectUnclaimedRewards(state);
    const reward = unclaimedRewards.find(ur => ur.reward_type === rewardType);
    const userIsRewardApproved = selectUserIsRewardApproved(state);

    if (!reward || reward.transaction_id) {
      // already claimed or doesn't exist, do nothing
      return;
    }

    if (!userIsRewardApproved && rewardType !== rewards.TYPE_CONFIRM_EMAIL) {
      const action = doNotify({
        id: MODALS.REWARD_APPROVAL_REQUIRED,
        isError: false,
      });
      dispatch(action);

      return;
    }

    dispatch({
      type: ACTIONS.CLAIM_REWARD_STARTED,
      data: { reward },
    });

    const success = successReward => {
      dispatch({
        type: ACTIONS.CLAIM_REWARD_SUCCESS,
        data: {
          reward: successReward,
        },
      });
      if (successReward.reward_type === rewards.TYPE_NEW_USER) {
        const action = doNotify({
          id: MODALS.FIRST_REWARD,
          isError: false,
        });
        dispatch(action);
      }
    };

    const failure = error => {
      dispatch({
        type: ACTIONS.CLAIM_REWARD_FAILURE,
        data: { reward, error },
      });
    };

    rewards.claimReward(rewardType).then(success, failure);
  };
}

export function doClaimEligiblePurchaseRewards() {
  return (dispatch, getState) => {
    const state = getState();
    const unclaimedRewards = selectUnclaimedRewards(state);
    const userIsRewardApproved = selectUserIsRewardApproved(state);

    if (!userIsRewardApproved || !Lbryio.enabled) {
      return;
    }

    if (unclaimedRewards.find(ur => ur.reward_type === rewards.TYPE_FIRST_STREAM)) {
      dispatch(doClaimRewardType(rewards.TYPE_FIRST_STREAM));
    } else {
      [rewards.TYPE_MANY_DOWNLOADS, rewards.TYPE_FEATURED_DOWNLOAD].forEach(type => {
        dispatch(doClaimRewardType(type));
      });
    }
  };
}

export function doClaimRewardClearError(reward) {
  return dispatch => {
    dispatch({
      type: ACTIONS.CLAIM_REWARD_CLEAR_ERROR,
      data: { reward },
    });
  };
}
<commit_msg>implement failSilently option in doClaimRewardType and set true in doClaimEligiblePurchaseRewards<commit_after>import * as ACTIONS from 'constants/action_types';
import Lbryio from 'lbryio';
import { doNotify, MODALS } from 'lbry-redux';
import { selectUnclaimedRewards } from 'redux/selectors/rewards';
import { selectUserIsRewardApproved } from 'redux/selectors/user';
import rewards from 'rewards';

export function doRewardList() {
  return dispatch => {
    dispatch({
      type: ACTIONS.FETCH_REWARDS_STARTED,
    });

    Lbryio.call('reward', 'list', { multiple_rewards_per_type: true })
      .then(userRewards => {
        dispatch({
          type: ACTIONS.FETCH_REWARDS_COMPLETED,
          data: { userRewards },
        });
      })
      .catch(() => {
        dispatch({
          type: ACTIONS.FETCH_REWARDS_COMPLETED,
          data: { userRewards: [] },
        });
      });
  };
}

export function doClaimRewardType(rewardType, options) {
  return (dispatch, getState) => {
    const state = getState();
    const unclaimedRewards = selectUnclaimedRewards(state);
    const reward = unclaimedRewards.find(ur => ur.reward_type === rewardType);
    const userIsRewardApproved = selectUserIsRewardApproved(state);

    if (!reward || reward.transaction_id) {
      // already claimed or doesn't exist, do nothing
      return;
    }

    if (!userIsRewardApproved && rewardType !== rewards.TYPE_CONFIRM_EMAIL) {
      const action = doNotify({
        id: MODALS.REWARD_APPROVAL_REQUIRED,
        isError: false,
      });
      dispatch(action);

      return;
    }

    dispatch({
      type: ACTIONS.CLAIM_REWARD_STARTED,
      data: { reward },
    });

    const success = successReward => {
      dispatch({
        type: ACTIONS.CLAIM_REWARD_SUCCESS,
        data: {
          reward: successReward,
        },
      });
      if (successReward.reward_type === rewards.TYPE_NEW_USER) {
        const action = doNotify({
          id: MODALS.FIRST_REWARD,
          isError: false,
        });
        dispatch(action);
      }
    };

    const failure = error => {
      dispatch({
        type: ACTIONS.CLAIM_REWARD_FAILURE,
        data: {
          reward,
          error: !options || !options.failSilently ? error : undefined,
        },
      });
    };

    rewards.claimReward(rewardType).then(success, failure);
  };
}

export function doClaimEligiblePurchaseRewards() {
  return (dispatch, getState) => {
    const state = getState();
    const unclaimedRewards = selectUnclaimedRewards(state);
    const userIsRewardApproved = selectUserIsRewardApproved(state);

    if (!userIsRewardApproved || !Lbryio.enabled) {
      return;
    }

    if (unclaimedRewards.find(ur => ur.reward_type === rewards.TYPE_FIRST_STREAM)) {
      dispatch(doClaimRewardType(rewards.TYPE_FIRST_STREAM));
    } else {
      [rewards.TYPE_MANY_DOWNLOADS, rewards.TYPE_FEATURED_DOWNLOAD].forEach(type => {
        dispatch(doClaimRewardType(type, { failSilently: true }));
      });
    }
  };
}

export function doClaimRewardClearError(reward) {
  return dispatch => {
    dispatch({
      type: ACTIONS.CLAIM_REWARD_CLEAR_ERROR,
      data: { reward },
    });
  };
}
<|endoftext|>


<commit_before>import {COMMENT, RULESET, DECLARATION} from './Enum.js'
import {abs, trim, from, sizeof, strlen, substr, append, prepend, replace} from './Utility.js'
import {node, scan, peek, caret, slice, alloc, dealloc, token, attoken, delimiter, whitespace, identifier} from './Tokenizer.js'

/**
 * @param {string} value
 * @return {string[]}
 */
export function compile (value) {
	return dealloc(parse('', [alloc(value)], [], [''], []))
}

/**
 * @param {string} value
 * @param {number[]} points
 * @param {string[]} declarations
 * @param {string[]} rules
 * @param {string[]} rulesets
 * @return {object}
 */
export function parse (value, points, declarations, rules, rulesets) {
	var index = 0
	var offset = 0
	var length = 0
	var scanning = 1
	var previous = 0
	var character = 0
	var atrule = 0
	var ampersand = 1
	var variable = 1
	var type = ''
	var props = rules
	var children = rulesets
	var temporary = type

	while (scanning)
		switch (previous = character, character = scan()) {
			// [ ]
			case 91: ++character
			// ( )
			case 40: ++character
			// " '
			case 34: case 39:
				temporary += delimiter(character)
				break
			// \t \n \s
			case 9: case 10: case 32:
				temporary += variable ? whitespace(previous) : from(character)
				break
			// /
			case 47:
				token(peek(0)) > 2 ? append(comment(scan()), rulesets) : temporary += from(47)
				break
			// {
			case 123 * variable:
				points[index++] = strlen(temporary) * ampersand
			// } ; \0
			case 125 * variable: case 59: case 0:
				switch (character) {
					// \0 }
					case 0: case 125: --scanning
					// ;
					case 59 + offset:
						variable = 1
						if (length > 0)
							append(declaration(temporary, length), declarations)
						break
					// rule/at-rule
					default:
						append(ruleset(temporary, points, index, offset, rules, type, props = [], children = []), rulesets)

						if (character !== 59)
							if (offset === 0)
								parse(temporary, points, children, props, rulesets)
							else if (attoken(atrule))
								parse(temporary, points, children, [''], children)
							else if (parse(value, points, props = [], rules, children), sizeof(props))
								prepend(ruleset(value, points, 0, 0, rules, type, rules, props), children)
				}

				index = length = offset = 0, ampersand = 1, type = temporary = ''
				break
			// -
			case 45:
				switch (previous) {
					case 45:
						variable = 0
				}
			default:
				switch (temporary += from(character), character) {
					// &
					case 38 * variable:
						ampersand = offset > 0 ? 1 : -1, temporary += from(12)
						break
					// :
					case 58:
						length = strlen(temporary) - 1
						break
					// @
					case 64 * variable:
						atrule = peek(0), offset = strlen(type = temporary += identifier(caret())), character++
						break
					// ,
					case 44 * variable:
						points[index++] = (strlen(temporary) - 1) * ampersand, ampersand = 1
						break
				}
		}

	return rulesets
}

/**
 * @param {number} type
 * @return {object}
 */
export function comment (type) {
	var index = caret() - 2
	var offset = type === 42 ? 2 : 1
	var temporary = trim(from(peek(0))) || from(type)
	var character = 0

	while (character = scan())
		if (character === 10 && type === 47)
			break
		else if (character === 42 && type === 42 && peek(0) !== 42 && scan() === 47)
			break

	return node(temporary, COMMENT, temporary, substr(temporary = slice(index, caret()), 2, strlen(temporary) - offset))
}

/**
 * @param {string} value
 * @param {number[]} points
 * @param {number} index
 * @param {number} offset
 * @param {string[]} rules
 * @param {string} type
 * @param {string[]} props
 * @param {string[]} children
 * @return {object}
 */
export function ruleset (value, points, index, offset, rules, type, props, children) {
	var post = offset - 1
	var root = offset === 0 ? rules : ['']
	var size = sizeof(root)

	for (var i = 0, j = 0, k = 0; i < index; ++i)
		for (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)
			if (z = trim(j > 0 ? root[x] + ' ' + y : replace(y, /&\f/g, root[x])))
				props[k++] = z

	return node(value, offset === 0 ? RULESET : type, props, children)
}

/**
 * @param {string} value
 * @param {number} length
 * @return {object}
 */
export function declaration (value, length) {
	return node(value, DECLARATION, substr(value, 0, length), substr(value, length + 1, strlen(value)))
}
<commit_msg>propose amendments<commit_after>import {COMMENT, RULESET, DECLARATION} from './Enum.js'
import {abs, trim, from, sizeof, strlen, substr, append, prepend, replace} from './Utility.js'
import {node, scan, peek, caret, slice, alloc, dealloc, token, attoken, delimiter, whitespace, identifier} from './Tokenizer.js'

/**
 * @param {string} value
 * @return {string[]}
 */
export function compile (value) {
	return dealloc(parse('', [alloc(value)], [], [''], []))
}

/**
 * @param {string} value
 * @param {number[]} points
 * @param {string[]} declarations
 * @param {string[]} rules
 * @param {string[]} rulesets
 * @return {object}
 */
export function parse (value, points, declarations, rules, rulesets) {
	var index = 0
	var offset = 0
	var length = 0
	var scanning = 1
	var previous = 0
	var character = 0
	var atrule = 0
	var variable = 1
	var ampersand = 1
	var type = ''
	var props = rules
	var children = rulesets
	var temporary = type

	while (scanning)
		switch (previous = character, character = scan()) {
			// [ ]
			case 91: ++character
			// ( )
			case 40: ++character
			// " '
			case 34: case 39:
				temporary += delimiter(character)
				break
			// \t \n \s
			case 9: case 10: case 32:
				temporary += variable ? whitespace(previous) : from(character)
				break
			// /
			case 47:
				token(peek(0)) > 2 ? append(comment(scan()), rulesets) : temporary += from(47)
				break
			// {
			case 123 * variable:
				points[index++] = strlen(temporary) * ampersand
			// } ; \0
			case 125 * variable: case 59: case 0:
				switch (character) {
					// \0 }
					case 0: case 125: --scanning
					// ;
					case 59 + offset:
						if (length > 0)
							append(declaration(temporary, length), declarations)
						break
					// rule/at-rule
					default:
						append(ruleset(temporary, points, index, offset, rules, type, props = [], children = []), rulesets)

						if (character !== 59)
							if (offset === 0)
								parse(temporary, points, children, props, rulesets)
							else if (attoken(atrule))
								parse(temporary, points, children, [''], children)
							else if (parse(value, points, props = [], rules, children), sizeof(props))
								prepend(ruleset(value, points, 0, 0, rules, type, rules, props), children)
				}

				index = length = offset = 0, variable = ampersand = 1, type = temporary = ''
				break
			// -
			case 45:
				if (previous === 45)
					variable = 0
			// :
			case 58:
				length = strlen(temporary)
			default:
				switch (temporary += from(character), character * variable) {
					// &
					case 38 * variable:
						ampersand = offset > 0 ? 1 : -1, temporary += from(12)
						break
					// @
					case 64 * variable:
						atrule = peek(0), offset = strlen(type = temporary += identifier(caret())), character++
						break
					// ,
					case 44 * variable:
						points[index++] = (strlen(temporary) - 1) * ampersand, ampersand = 1
						break
				}
		}

	return rulesets
}

/**
 * @param {number} type
 * @return {object}
 */
export function comment (type) {
	var index = caret() - 2
	var offset = type === 42 ? 2 : 1
	var temporary = trim(from(peek(0))) || from(type)
	var character = 0

	while (character = scan())
		if (character === 10 && type === 47)
			break
		else if (character === 42 && type === 42 && peek(0) !== 42 && scan() === 47)
			break

	return node(temporary, COMMENT, temporary, substr(temporary = slice(index, caret()), 2, strlen(temporary) - offset))
}

/**
 * @param {string} value
 * @param {number[]} points
 * @param {number} index
 * @param {number} offset
 * @param {string[]} rules
 * @param {string} type
 * @param {string[]} props
 * @param {string[]} children
 * @return {object}
 */
export function ruleset (value, points, index, offset, rules, type, props, children) {
	var post = offset - 1
	var root = offset === 0 ? rules : ['']
	var size = sizeof(root)

	for (var i = 0, j = 0, k = 0; i < index; ++i)
		for (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)
			if (z = trim(j > 0 ? root[x] + ' ' + y : replace(y, /&\f/g, root[x])))
				props[k++] = z

	return node(value, offset === 0 ? RULESET : type, props, children)
}

/**
 * @param {string} value
 * @param {number} length
 * @return {object}
 */
export function declaration (value, length) {
	return node(value, DECLARATION, substr(value, 0, length), substr(value, length + 1, strlen(value)))
}
<|endoftext|>


<commit_before>import BaseModule from '../base'
import { isEmpty } from 'lodash'
import { NETWORKS } from '@config'
import NetworkModel from '@/models/network'
import Client from '@/services/client'

export default new BaseModule(NetworkModel, {
  getters: {
    feeStatisticsByType: (_, __, ___, rootGetters) => type => {
      const currentNetwork = rootGetters['session/session']

      if (!currentNetwork) {
        throw new Error('[network/feeStatisticsByType] No active network.')
      }

      if (currentNetwork.apiVersion === 1) {
        throw new Error('[network/feeStatisticsByType] Supported only by v2 networks.')
      }

      const { feeStatistics } = currentNetwork
      const data = feeStatistics.find(transactionType => transactionType.type === type)
      return data ? data.fees : []
    }
  },

  mutations: {
    SET_ALL (state, value) {
      state.all = value
    }
  },

  actions: {
    load ({ commit, getters }) {
      if (!isEmpty(getters.all)) return

      commit('SET_ALL', NETWORKS)
    },

    async updateNetworkConfig ({ dispatch, getters }, networkId) {
      const network = getters['byId'](networkId)
      const response = await Client.fetchNetworkConfig(network.server, network.apiVersion)

      if (response) {
        const result = dispatch('update', {
          ...network,
          ...response
        })

        return result
      }
    }
  }
})
<commit_msg>fix: use the network from the session when getting the fees (#323)<commit_after>import BaseModule from '../base'
import { isEmpty } from 'lodash'
import { NETWORKS } from '@config'
import NetworkModel from '@/models/network'
import Client from '@/services/client'

export default new BaseModule(NetworkModel, {
  getters: {
    feeStatisticsByType: (_, __, ___, rootGetters) => type => {
      const currentNetwork = rootGetters['session/network']

      if (!currentNetwork) {
        throw new Error('[network/feeStatisticsByType] No active network.')
      }

      if (currentNetwork.apiVersion === 1) {
        throw new Error('[network/feeStatisticsByType] Supported only by v2 networks.')
      }

      const { feeStatistics } = currentNetwork
      const data = feeStatistics.find(transactionType => transactionType.type === type)
      return data ? data.fees : []
    }
  },

  mutations: {
    SET_ALL (state, value) {
      state.all = value
    }
  },

  actions: {
    load ({ commit, getters }) {
      if (!isEmpty(getters.all)) return

      commit('SET_ALL', NETWORKS)
    },

    async updateNetworkConfig ({ dispatch, getters }, networkId) {
      const network = getters['byId'](networkId)
      const response = await Client.fetchNetworkConfig(network.server, network.apiVersion)

      if (response) {
        const result = dispatch('update', {
          ...network,
          ...response
        })

        return result
      }
    }
  }
})
<|endoftext|>