<commit_before>import React from "react";
import { defineMessages, injectIntl, intlShape, FormattedMessage } from "react-intl";
import PropTypes from "prop-types";
import { Tabs, Tab } from "patternfly-react";
import ListView from "./ListView";
import ListItemComponents from "./ListItemComponents";
import DependencyListView from "./DependencyListView";
import EmptyState from "../EmptyState/EmptyState";
import Loading from "../Loading/Loading";
import LabelWithBadge from "./LabelWithBadge";

const messages = defineMessages({
  dependenciesTabTitle: {
    defaultMessage: "Dependencies"
  },
  emptyStateErrorMessage: {
    defaultMessage: "An error occurred while trying to get blueprint contents."
  },
  emptyStateErrorTitle: {
    defaultMessage: "An Error Occurred"
  },
  emptyStateNoResultsMessage: {
    defaultMessage: "Modify your filter criteria to get results."
  },
  emptyStateNoResultsTitle: {
    defaultMessage: "No Results Match the Filter Criteria"
  },
  selectedTabTitle: {
    defaultMessage: "Selected Components"
  }
});

const BlueprintContents = props => {
  const {
    components,
    dependencies,
    handleComponentDetails,
    handleRemoveComponent,
    noEditComponent,
    filterClearValues,
    filterValues,
    errorState,
    fetchingState,
    fetchDetails,
    pastLength,
    undo
  } = props;

  const { formatMessage } = props.intl;

  return (

      {(fetchingState === true && <Loading />) ||
        ((Object.keys(errorState).length > 0 && (
          <EmptyState
            title={formatMessage(messages.emptyStateErrorTitle)}
            message={formatMessage(messages.emptyStateErrorMessage)}
          >

{errorState.message}

            {pastLength > 0 && (
              <button className="btn btn-link btn-lg" type="button" onClick={() => undo()}>
                <FormattedMessage defaultMessage="Undo Last Change" />
              </button>
            )}
          </EmptyState>
        )) ||
          ((components.length === 0 && filterValues.length === 0 &&
{props.children}
) || (
            <Tabs id="blueprint-tabs">
              <Tab
                eventKey="selected-components"
                title={<LabelWithBadge title={formatMessage(messages.selectedTabTitle)} badge={components.length} />}
              >
                {(components.length === 0 && (
                  <EmptyState
                    title={formatMessage(messages.emptyStateNoResultsTitle)}
                    message={formatMessage(messages.emptyStateNoResultsMessage)}
                  >
                    <button className="btn btn-link btn-lg" type="button" onClick={() => filterClearValues([])}>
                      <FormattedMessage defaultMessage="Clear All Filters" />
                    </button>
                  </EmptyState>
                )) || (
                  <ListView className="cmpsr-blueprint__components" stacked>
                    {components.map(listItem => (
                      <ListItemComponents
                        listItemParent="cmpsr-blueprint__components"
                        listItem={listItem}
                        key={listItem.name}
                        handleRemoveComponent={handleRemoveComponent}
                        handleComponentDetails={handleComponentDetails}
                        noEditComponent={noEditComponent}
                        fetchDetails={fetchDetails}
                      />
                    ))}
                  </ListView>
                )}
              </Tab>
              <Tab
                eventKey="dependencies"
                title={
                  <LabelWithBadge title={formatMessage(messages.dependenciesTabTitle)} badge={dependencies.length} />
                }
              >
                {(dependencies.length === 0 && (
                  <EmptyState
                    title={formatMessage(messages.emptyStateNoResultsTitle)}
                    message={formatMessage(messages.emptyStateNoResultsMessage)}
                  >
                    <button className="btn btn-link btn-lg" type="button" onClick={() => filterClearValues([])}>
                      <FormattedMessage defaultMessage="Clear All Filters" />
                    </button>
                  </EmptyState>
                )) || (
                  <DependencyListView
                    className="cmpsr-blueprint__dependencies"
                    listItems={dependencies}
                    handleRemoveComponent={handleRemoveComponent}
                    handleComponentDetails={handleComponentDetails}
                    noEditComponent={noEditComponent}
                    fetchDetails={fetchDetails}
                  />
                )}
              </Tab>
            </Tabs>
          )))}

  );
};

BlueprintContents.propTypes = {
  components: PropTypes.arrayOf(PropTypes.object),
  dependencies: PropTypes.arrayOf(PropTypes.object),
  handleComponentDetails: PropTypes.func,
  handleRemoveComponent: PropTypes.func,
  intl: intlShape.isRequired,
  noEditComponent: PropTypes.bool,
  filterClearValues: PropTypes.func,
  filterValues: PropTypes.arrayOf(PropTypes.object),
  errorState: PropTypes.shape({
    message: PropTypes.string,
    options: PropTypes.object,
    problem: PropTypes.string,
    url: PropTypes.string
  }),
  fetchingState: PropTypes.bool,
  fetchDetails: PropTypes.func,
  children: PropTypes.oneOfType([PropTypes.element, PropTypes.arrayOf(PropTypes.element)]),
  pastLength: PropTypes.number,
  undo: PropTypes.func
};

BlueprintContents.defaultProps = {
  components: [],
  dependencies: [],
  handleComponentDetails: function() {},
  handleRemoveComponent: function() {},
  noEditComponent: false,
  filterClearValues: function() {},
  filterValues: [],
  errorState: {},
  fetchingState: false,
  fetchDetails: function() {},
  children: React.createElement("div"),
  pastLength: 0,
  undo: function() {}
};

export default injectIntl(BlueprintContents);
<commit_msg>updates prop being passed to EmptyState contents<commit_after>import React from "react";
import { defineMessages, injectIntl, intlShape, FormattedMessage } from "react-intl";
import PropTypes from "prop-types";
import { Tabs, Tab } from "patternfly-react";
import ListView from "./ListView";
import ListItemComponents from "./ListItemComponents";
import DependencyListView from "./DependencyListView";
import EmptyState from "../EmptyState/EmptyState";
import Loading from "../Loading/Loading";
import LabelWithBadge from "./LabelWithBadge";

const messages = defineMessages({
  dependenciesTabTitle: {
    defaultMessage: "Dependencies"
  },
  emptyStateErrorMessage: {
    defaultMessage: "An error occurred while trying to get blueprint contents."
  },
  emptyStateErrorTitle: {
    defaultMessage: "An Error Occurred"
  },
  emptyStateNoResultsMessage: {
    defaultMessage: "Modify your filter criteria to get results."
  },
  emptyStateNoResultsTitle: {
    defaultMessage: "No Results Match the Filter Criteria"
  },
  selectedTabTitle: {
    defaultMessage: "Selected Components"
  }
});

const BlueprintContents = props => {
  const {
    components,
    dependencies,
    handleComponentDetails,
    handleRemoveComponent,
    noEditComponent,
    filterClearValues,
    filterValues,
    errorState,
    fetchingState,
    fetchDetails,
    pastLength,
    undo
  } = props;

  const { formatMessage } = props.intl;

  return (

      {(fetchingState === true && <Loading />) ||
        ((Object.keys(errorState).length > 0 && (
          <EmptyState
            title={formatMessage(messages.emptyStateErrorTitle)}
            message={formatMessage(messages.emptyStateErrorMessage)}
          >

{errorState.msg}

            {pastLength > 0 && (
              <button className="btn btn-link btn-lg" type="button" onClick={() => undo()}>
                <FormattedMessage defaultMessage="Undo Last Change" />
              </button>
            )}
          </EmptyState>
        )) ||
          ((components.length === 0 && filterValues.length === 0 &&
{props.children}
) || (
            <Tabs id="blueprint-tabs">
              <Tab
                eventKey="selected-components"
                title={<LabelWithBadge title={formatMessage(messages.selectedTabTitle)} badge={components.length} />}
              >
                {(components.length === 0 && (
                  <EmptyState
                    title={formatMessage(messages.emptyStateNoResultsTitle)}
                    message={formatMessage(messages.emptyStateNoResultsMessage)}
                  >
                    <button className="btn btn-link btn-lg" type="button" onClick={() => filterClearValues([])}>
                      <FormattedMessage defaultMessage="Clear All Filters" />
                    </button>
                  </EmptyState>
                )) || (
                  <ListView className="cmpsr-blueprint__components" stacked>
                    {components.map(listItem => (
                      <ListItemComponents
                        listItemParent="cmpsr-blueprint__components"
                        listItem={listItem}
                        key={listItem.name}
                        handleRemoveComponent={handleRemoveComponent}
                        handleComponentDetails={handleComponentDetails}
                        noEditComponent={noEditComponent}
                        fetchDetails={fetchDetails}
                      />
                    ))}
                  </ListView>
                )}
              </Tab>
              <Tab
                eventKey="dependencies"
                title={
                  <LabelWithBadge title={formatMessage(messages.dependenciesTabTitle)} badge={dependencies.length} />
                }
              >
                {(dependencies.length === 0 && (
                  <EmptyState
                    title={formatMessage(messages.emptyStateNoResultsTitle)}
                    message={formatMessage(messages.emptyStateNoResultsMessage)}
                  >
                    <button className="btn btn-link btn-lg" type="button" onClick={() => filterClearValues([])}>
                      <FormattedMessage defaultMessage="Clear All Filters" />
                    </button>
                  </EmptyState>
                )) || (
                  <DependencyListView
                    className="cmpsr-blueprint__dependencies"
                    listItems={dependencies}
                    handleRemoveComponent={handleRemoveComponent}
                    handleComponentDetails={handleComponentDetails}
                    noEditComponent={noEditComponent}
                    fetchDetails={fetchDetails}
                  />
                )}
              </Tab>
            </Tabs>
          )))}

  );
};

BlueprintContents.propTypes = {
  components: PropTypes.arrayOf(PropTypes.object),
  dependencies: PropTypes.arrayOf(PropTypes.object),
  handleComponentDetails: PropTypes.func,
  handleRemoveComponent: PropTypes.func,
  intl: intlShape.isRequired,
  noEditComponent: PropTypes.bool,
  filterClearValues: PropTypes.func,
  filterValues: PropTypes.arrayOf(PropTypes.object),
  errorState: PropTypes.shape({
    message: PropTypes.string,
    options: PropTypes.object,
    problem: PropTypes.string,
    url: PropTypes.string
  }),
  fetchingState: PropTypes.bool,
  fetchDetails: PropTypes.func,
  children: PropTypes.oneOfType([PropTypes.element, PropTypes.arrayOf(PropTypes.element)]),
  pastLength: PropTypes.number,
  undo: PropTypes.func
};

BlueprintContents.defaultProps = {
  components: [],
  dependencies: [],
  handleComponentDetails: function() {},
  handleRemoveComponent: function() {},
  noEditComponent: false,
  filterClearValues: function() {},
  filterValues: [],
  errorState: {},
  fetchingState: false,
  fetchDetails: function() {},
  children: React.createElement("div"),
  pastLength: 0,
  undo: function() {}
};

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


<commit_before>const React = require('react');
const Radium = require('radium');

const Spin = require('./Spin');

const StyleConstants = require('../constants/Style');

const Icon = require('../components/Icon');

const { buttonTypes } = require('../constants/App');

class Button extends React.Component {
  static propTypes = {
    actionText: React.PropTypes.string,
    ariaLabel: React.PropTypes.string,
    icon: React.PropTypes.string,
    isActive: React.PropTypes.bool,
    onClick: React.PropTypes.func,
    primaryColor: React.PropTypes.string,
    style: React.PropTypes.object,
    type: React.PropTypes.oneOf(buttonTypes)
  };

  static defaultProps = {
    onClick () {},
    isActive: false,
    primaryColor: StyleConstants.Colors.PRIMARY,
    type: 'primary'
  };

  _isLargeOrMediumWindowSize = () => {
    const windowSize = StyleConstants.getWindowSize();

    return windowSize === 'medium' || windowSize === 'large';
  };

  _hasVisibleChildren = () => {
    let hasVisibleChildren = false;

    if (!this.props.children) {
      return hasVisibleChildren;
    }

    if (!Array.isArray(this.props.children)) {
      return !this.props.children.props || this.props.children.props.className !== 'visuallyHidden';
    }

    this.props.children.forEach((child) => {
      if (child.props && child.props.className !== 'visuallyHidden') {
        hasVisibleChildren = true;
      }
    });

    return hasVisibleChildren;
  };

  render () {
    const styles = this.styles();

    return (
      <button
        aria-label={this.props.ariaLabel}
        onClick={this.props.type === 'disabled' ? null : this.props.onClick}
        style={Object.assign({}, styles.component, styles[this.props.type], this.props.style)}
      >

          {(this.props.icon && !this.props.isActive) && (
            <Icon
              elementProps={{ 'aria-hidden': true }}
              size={20}
              style={styles.icon}
              type={this.props.icon}
            />
          )}
          {this.props.isActive && (
            <Spin direction='counterclockwise'>
              <Icon elementProps={{ 'aria-hidden': true }} size={20} type='spinner' />
            </Spin>
          )}

            {this.props.isActive ? this.props.actionText : this.props.children}

      </button>
    );
  }

  styles = () => {
    return {
      component: Object.assign({
        borderRadius: 2,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: 'transparent',
        boxSizing: 'border-box',
        display: 'inline-block',
        padding: '4px 14px',
        fontSize: StyleConstants.FontSizes.MEDIUM,
        fontFamily: StyleConstants.Fonts.SEMIBOLD,
        cursor: this.props.type === 'disabled' ? 'default' : 'pointer',
        transition: 'all .2s ease-in',
        minWidth: 16,
        position: 'relative'
      }, this.props.style),
      children: {
        justifyContent: 'center',
        display: 'flex',
        alignItems: 'center',
        lineHeight: '20px'
      },
      primary: {
        backgroundColor: this.props.primaryColor,
        borderColor: this.props.primaryColor,
        color: StyleConstants.Colors.WHITE,
        fill: StyleConstants.Colors.WHITE,
        transition: 'all .2s ease-in',

        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -15),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          transition: 'all .2s ease-in'
        }
      },
      primaryOutline: {
        backgroundColor: 'transparent',
        borderColor: this.props.primaryColor,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',

        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: this.props.primaryColor,
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      primaryInverse: {
        backgroundColor: StyleConstants.Colors.WHITE,
        borderColor: StyleConstants.Colors.WHITE,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',

        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.WHITE, -15),
          borderColor: StyleConstants.adjustColor(StyleConstants.Colors.WHITE, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.WHITE, -30),
          borderColor: StyleConstants.adjustColor(StyleConstants.Colors.WHITE, -30),
          transition: 'all .2s ease-in'
        }
      },
      secondary: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.ASH,
        color: StyleConstants.Colors.ASH,
        fill: StyleConstants.Colors.ASH,
        transition: 'all .2s ease-in',
        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: StyleConstants.Colors.ASH,
          borderColor: StyleConstants.Colors.ASH,
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.ASH, -30),
          borderColor: StyleConstants.adjustColor(StyleConstants.Colors.ASH, -30),
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      base: {
        backgroundColor: 'transparent',
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',
        borderColor: 'transparent',
        borderRadius: 2,
        borderWidth: 1,
        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          color: StyleConstants.adjustColor(this.props.primaryColor, -8),
          fill: StyleConstants.adjustColor(this.props.primaryColor, -8),
          transition: 'all .2s ease-in',
          borderColor: StyleConstants.Colors.FOG
        },
        ':active': {
          color: StyleConstants.adjustColor(this.props.primaryColor, -16),
          fill: StyleConstants.adjustColor(this.props.primaryColor, -16),
          transition: 'all .2s ease-in',
          backgroundColor: StyleConstants.Colors.PORCELAIN
        }
      },
      neutral: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.FOG,
        borderRadius: 2,
        borderWidth: 1,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: StyleConstants.Colors.PORCELAIN
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.PORCELAIN, -15)
        }
      },
      disabled: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.FOG,
        color: StyleConstants.Colors.FOG,
        fill: StyleConstants.Colors.FOG
      },
      icon: {
        marginLeft: this._hasVisibleChildren() ? -4 : 0,
        marginRight: this._hasVisibleChildren() ? 5 : 0
      },
      buttonText: {
        marginLeft: (this.props.isActive && this.props.actionText) ? 10 : 0
      }
    };
  };
}

module.exports = Radium(Button);
<commit_msg>remove ariaLabel prop<commit_after>const React = require('react');
const Radium = require('radium');

const Spin = require('./Spin');

const StyleConstants = require('../constants/Style');

const Icon = require('../components/Icon');

const { buttonTypes } = require('../constants/App');

class Button extends React.Component {
  static propTypes = {
    actionText: React.PropTypes.string,
    icon: React.PropTypes.string,
    isActive: React.PropTypes.bool,
    onClick: React.PropTypes.func,
    primaryColor: React.PropTypes.string,
    style: React.PropTypes.object,
    type: React.PropTypes.oneOf(buttonTypes)
  };

  static defaultProps = {
    onClick () {},
    isActive: false,
    primaryColor: StyleConstants.Colors.PRIMARY,
    type: 'primary'
  };

  _isLargeOrMediumWindowSize = () => {
    const windowSize = StyleConstants.getWindowSize();

    return windowSize === 'medium' || windowSize === 'large';
  };

  _hasVisibleChildren = () => {
    let hasVisibleChildren = false;

    if (!this.props.children) {
      return hasVisibleChildren;
    }

    if (!Array.isArray(this.props.children)) {
      return !this.props.children.props || this.props.children.props.className !== 'visuallyHidden';
    }

    this.props.children.forEach((child) => {
      if (child.props && child.props.className !== 'visuallyHidden') {
        hasVisibleChildren = true;
      }
    });

    return hasVisibleChildren;
  };

  render () {
    const styles = this.styles();

    return (
      <button
        onClick={this.props.type === 'disabled' ? null : this.props.onClick}
        style={Object.assign({}, styles.component, styles[this.props.type], this.props.style)}
      >

          {(this.props.icon && !this.props.isActive) && (
            <Icon
              elementProps={{ 'aria-hidden': true }}
              size={20}
              style={styles.icon}
              type={this.props.icon}
            />
          )}
          {this.props.isActive && (
            <Spin direction='counterclockwise'>
              <Icon elementProps={{ 'aria-hidden': true }} size={20} type='spinner' />
            </Spin>
          )}

            {this.props.isActive ? this.props.actionText : this.props.children}

      </button>
    );
  }

  styles = () => {
    return {
      component: Object.assign({
        borderRadius: 2,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: 'transparent',
        boxSizing: 'border-box',
        display: 'inline-block',
        padding: '4px 14px',
        fontSize: StyleConstants.FontSizes.MEDIUM,
        fontFamily: StyleConstants.Fonts.SEMIBOLD,
        cursor: this.props.type === 'disabled' ? 'default' : 'pointer',
        transition: 'all .2s ease-in',
        minWidth: 16,
        position: 'relative'
      }, this.props.style),
      children: {
        justifyContent: 'center',
        display: 'flex',
        alignItems: 'center',
        lineHeight: '20px'
      },
      primary: {
        backgroundColor: this.props.primaryColor,
        borderColor: this.props.primaryColor,
        color: StyleConstants.Colors.WHITE,
        fill: StyleConstants.Colors.WHITE,
        transition: 'all .2s ease-in',

        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -15),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          transition: 'all .2s ease-in'
        }
      },
      primaryOutline: {
        backgroundColor: 'transparent',
        borderColor: this.props.primaryColor,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',

        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: this.props.primaryColor,
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      primaryInverse: {
        backgroundColor: StyleConstants.Colors.WHITE,
        borderColor: StyleConstants.Colors.WHITE,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',

        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.WHITE, -15),
          borderColor: StyleConstants.adjustColor(StyleConstants.Colors.WHITE, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.WHITE, -30),
          borderColor: StyleConstants.adjustColor(StyleConstants.Colors.WHITE, -30),
          transition: 'all .2s ease-in'
        }
      },
      secondary: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.ASH,
        color: StyleConstants.Colors.ASH,
        fill: StyleConstants.Colors.ASH,
        transition: 'all .2s ease-in',
        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: StyleConstants.Colors.ASH,
          borderColor: StyleConstants.Colors.ASH,
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.ASH, -30),
          borderColor: StyleConstants.adjustColor(StyleConstants.Colors.ASH, -30),
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      base: {
        backgroundColor: 'transparent',
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',
        borderColor: 'transparent',
        borderRadius: 2,
        borderWidth: 1,
        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          color: StyleConstants.adjustColor(this.props.primaryColor, -8),
          fill: StyleConstants.adjustColor(this.props.primaryColor, -8),
          transition: 'all .2s ease-in',
          borderColor: StyleConstants.Colors.FOG
        },
        ':active': {
          color: StyleConstants.adjustColor(this.props.primaryColor, -16),
          fill: StyleConstants.adjustColor(this.props.primaryColor, -16),
          transition: 'all .2s ease-in',
          backgroundColor: StyleConstants.Colors.PORCELAIN
        }
      },
      neutral: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.FOG,
        borderRadius: 2,
        borderWidth: 1,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        ':hover': !this._isLargeOrMediumWindowSize() ? null : {
          backgroundColor: StyleConstants.Colors.PORCELAIN
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.PORCELAIN, -15)
        }
      },
      disabled: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.FOG,
        color: StyleConstants.Colors.FOG,
        fill: StyleConstants.Colors.FOG
      },
      icon: {
        marginLeft: this._hasVisibleChildren() ? -4 : 0,
        marginRight: this._hasVisibleChildren() ? 5 : 0
      },
      buttonText: {
        marginLeft: (this.props.isActive && this.props.actionText) ? 10 : 0
      }
    };
  };
}

module.exports = Radium(Button);
<|endoftext|>


<commit_before>/*!
 * TemplateLayout Wef plugin
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */

//requires: cssParser
var parser = wef.fn.cssParser; //TODO: loader
//exports: templateLayout

(function () {
    var templateLayout = {
        name:"templateLayout",
        version:"0.0.1",
        description:"W3C CSS Template Layout Module",
        authors:["Pablo Escalada <uo1398@uniovies>"],
        licenses:["MIT"], //TODO: Licenses
        constants:{
            DISPLAY_MODEL:"display-model",
            SITUATED:"situated"
        },

        init:function () {
            root = new Template("", "", "");
            document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
                console.log(e.data.selectorText, e.data.declaration);
                lastEvent = e;
                //TODO populate TemplateDOM
                var model = e.data.declaration.property == this.constants.DISPLAY_MODEL ? e.data.declaration.valueText : "";
                var situation = e.data.declaration.property == this.constants.SITUATED ? e.data.declaration.valueText : "";
                this.add(e.data.selectorText, model, situation);

            }, false);
            return templateLayout;
        },
        add:function (selector, model, situated) {
            //no situated
            if (situated == "") {
                root.add(new Template(selector, model, situated));
            } else {
                throw "Operation not implemented";
                //situated
                //root.search(function (template) {}).add(new Template(selector, model, situated));
            }

        },
        getLastEvent:function () {
            return lastEvent;
        }
    };

    var lastEvent = null;
    var root = null;

    wef.plugins.register("templateLayout", templateLayout);
})();

function Template(selectorText, model, situated) {
    this.selectorText = selectorText;
    this.model = model;
    this.situated = situated;
}
Template.prototype = {
    childTemplates:{},
    model:"",
    selectorText:"",
    situated:"",
    situation:"",
    isContainer:function () {
        return true;
    },
    add:function (child) {
        this.childTemplates[child.selectorText] = child;
    }
};<commit_msg>Cleaning...<commit_after>/*!
 * TemplateLayout Wef plugin
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */

//requires: cssParser
var parser = wef.fn.cssParser; //TODO: loader
//exports: templateLayout

(function () {
    var templateLayout = {
        name:"templateLayout",
        version:"0.0.1",
        description:"W3C CSS Template Layout Module",
        authors:["Pablo Escalada <uo1398@uniovies>"],
        licenses:["MIT"], //TODO: Licenses
        constants:{
            DISPLAY:"display-model",
            SITUATION:"situated"
        },

        init:function () {
            root = new Template("", "", "");
            document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
                console.log(e.data.selectorText, e.data.declaration);
                lastEvent = e;
                //TODO store them
                //buffer.add(e.data.selectorText, e.data.declaration);
                //TODO populate TemplateDOM
                //var model = e.data.declaration.property == this.constants.DISPLAY ? e.data.declaration.valueText : "";
                //var situation = e.data.declaration.property == this.constants.SITUATION ? e.data.declaration.valueText : "";
                //this.add(e.data.selectorText, model, situation);

            }, false);
            return templateLayout;
        },

        //testing purposes
        getLastEvent:function () {
            return lastEvent;
        }
    };

    var lastEvent = null;

    wef.plugins.register("templateLayout", templateLayout);
})();

function Template(selectorText, model, situated) {
    this.selectorText = selectorText;
    this.model = model;
    this.situated = situated;
}
Template.prototype = {
    model:"",
    selectorText:"",
    situated:""
};<|endoftext|>


<commit_before>var cache = {},
	Mask = {

		/**
		 * @arg template - {template{string} | maskDOM{array}}
		 * @arg model - template values
		 * @arg container - optional, - place to renderDOM, @default - DocumentFragment
		 * @return container {@default DocumentFragment}
		 */
		render: function (template, model, container, cntx) {
			//////try {
			if (typeof template === 'string') {
				template = this.compile(template);
			}
			return Builder.build(template, model, container, cntx);
			//////} catch (e) {
			//////	console.error('maskJS', e.message, template);
			//////}
			//////return null;
		},
		/**
		 *@arg template - string to be parsed into maskDOM
		 *@arg serializeDOM - build raw maskDOM json, without template functions - used for storing compiled template
		 *@return maskDOM
		 */
		compile: function (template, serializeOnly) {
			if (hasOwnProp.call(cache, template)){
				/** if Object doesnt contains property that check is faster
					then "!=null" http://jsperf.com/not-in-vs-null/2 */
				return cache[template];
			}

			/** remove unimportant whitespaces */
			var T = new Template(template.replace(regexpTabsAndNL, '').replace(regexpMultipleSpaces, ' '));
			if (serializeOnly === true) {
				T.serialize = true;
			}

			return (cache[template] = Parser.parse(T));

		},
		registerHandler: function (tagName, TagHandler) {
			CustomTags.all[tagName] = TagHandler;
		},
		getHandler: function (tagName) {
			return tagName != null ? CustomTags.all[tagName] : CustomTags.all;
		},
		registerUtility: function (utilityName, fn) {
			ValueUtilities[utilityName] = fn;
		},
		serialize: function (template) {
			return Parser.cleanObject(this.compile(template, true));
		},
		deserialize: function (serialized) {
			var i, key, attr;
			if (serialized instanceof Array) {
				for (i = 0; i < serialized.length; i++) {
					this.deserialize(serialized[i]);
				}
				return serialized;
			}
			if (serialized.content != null) {
				if (serialized.content.template != null) {
					serialized.content = Parser.toFunction(serialized.content.template);
				}
				return serialized;
			}
			if (serialized.attr != null) {
				attr = serialized.attr;
				for (key in attr) {
					if (hasOwnProp.call(attr, key) === true){
						if (attr[key].template == null) {
							continue;
						}
						attr[key] = Parser.toFunction(attr[key].template);
					}
				}
			}
			if (serialized.nodes != null) {
				this.deserialize(serialized.nodes);
			}
			return serialized;
		},
		ICustomTag: ICustomTag,
		ValueUtils: ValueUtilities
	};

/** Obsolete - to keep backwards compatiable */
Mask.renderDom = Mask.render;
<commit_msg>[++] mask.clearCache(key)<commit_after>var cache = {},
	Mask = {

		/**
		 * @arg template - {template{string} | maskDOM{array}}
		 * @arg model - template values
		 * @arg container - optional, - place to renderDOM, @default - DocumentFragment
		 * @return container {@default DocumentFragment}
		 */
		render: function (template, model, container, cntx) {
			//////try {
			if (typeof template === 'string') {
				template = this.compile(template);
			}
			return Builder.build(template, model, container, cntx);
			//////} catch (e) {
			//////	console.error('maskJS', e.message, template);
			//////}
			//////return null;
		},
		/**
		 *@arg template - string to be parsed into maskDOM
		 *@arg serializeDOM - build raw maskDOM json, without template functions - used for storing compiled template
		 *@return maskDOM
		 */
		compile: function (template, serializeOnly) {
			if (hasOwnProp.call(cache, template)){
				/** if Object doesnt contains property that check is faster
					then "!=null" http://jsperf.com/not-in-vs-null/2 */
				return cache[template];
			}

			/** remove unimportant whitespaces */
			var T = new Template(template.replace(regexpTabsAndNL, '').replace(regexpMultipleSpaces, ' '));
			if (serializeOnly === true) {
				T.serialize = true;
			}

			return (cache[template] = Parser.parse(T));

		},
		registerHandler: function (tagName, TagHandler) {
			CustomTags.all[tagName] = TagHandler;
		},
		getHandler: function (tagName) {
			return tagName != null ? CustomTags.all[tagName] : CustomTags.all;
		},
		registerUtility: function (utilityName, fn) {
			ValueUtilities[utilityName] = fn;
		},
		serialize: function (template) {
			return Parser.cleanObject(this.compile(template, true));
		},
		deserialize: function (serialized) {
			var i, key, attr;
			if (serialized instanceof Array) {
				for (i = 0; i < serialized.length; i++) {
					this.deserialize(serialized[i]);
				}
				return serialized;
			}
			if (serialized.content != null) {
				if (serialized.content.template != null) {
					serialized.content = Parser.toFunction(serialized.content.template);
				}
				return serialized;
			}
			if (serialized.attr != null) {
				attr = serialized.attr;
				for (key in attr) {
					if (hasOwnProp.call(attr, key) === true){
						if (attr[key].template == null) {
							continue;
						}
						attr[key] = Parser.toFunction(attr[key].template);
					}
				}
			}
			if (serialized.nodes != null) {
				this.deserialize(serialized.nodes);
			}
			return serialized;
		},
		clearCache: function(key){
			if (typeof key === 'string'){
				delete cache[key];
			}else{
				cache = {};
			}
		},
		ICustomTag: ICustomTag,
		ValueUtils: ValueUtilities
	};

/** Obsolete - to keep backwards compatiable */
Mask.renderDom = Mask.render;
<|endoftext|>


<commit_before>/**
 * Created by sam on 13.11.2016.
 */

const spawnSync = require('child_process').spawnSync;
const path = require('path');
const resolve = path.resolve;
const fs = require('fs');

function dependencyGraph(cwd) {
  const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
  const r = spawnSync(npm, ['ls', '--prod', '--json'], {
    cwd: cwd
  });
  if (!r.stdout) {
    console.error(cwd, r.error);
    return {};
  }
  return JSON.parse(r.stdout.toString());
}

function gitHead(cwd) {
  if (!fs.existsSync(cwd + '/.git')) {
    return null;
  }
  const r = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], {
    cwd: cwd
  });
  if (!r.stdout) {
    console.error(cwd, r.error);
    return {};
  }
  return r.stdout.toString().trim();
}

function resolveModules() {
  const reg = fs.readFileSync('../phovea_registry.js').toString();
  const regex = /import '(.*)\/phovea_registry.js'/g;
  const modules = [];
  var r;
  while ((r = regex.exec(reg)) !== null) {
    modules.push(r[1]);
  }
  return modules;
}

function cleanupDependency(d) {
  return d;
}

function resolveUeber() {
  console.log('resolve parent');
  const ueberDeps = dependencyGraph('..').dependencies;
  const modules = new Set(resolveModules());

  const resolveModule = (m) => {
    console.log('resolve', m);
    const pkg = require(`../${m}/package.json`);
    const head = gitHead('../' + m);
    return {
      name: pkg.name,
      version: pkg.version,
      resolved: head ? `${pkg.repository.url}#${head}` : pkg.version,
      dependencies: deps(pkg.dependencies)
    };
  };
  const deps = (deps) => {
    const r = {};
    Object.keys(deps).forEach((d) => {
      if (d in ueberDeps) {
        r[d] = cleanupDependency(ueberDeps[d]);
        delete ueberDeps[d];
      } else if (modules.has(d)) {
        modules.delete(d);
        r[d] = resolveModule(d);
      } else {
        r[d] = '-> link';
      }
    });
    return r;
  };

  // self =
  const root = path.basename(process.cwd());
  console.log(root);

  modules.delete(root);
  const base = resolveModule(root);
  base.extraDependencies = {};
  while (modules.size > 0) {
    let m = Array.from(modules.keys())[0];
    modules.delete(m);
    base.extraDependencies[m] = resolveModule(m);
  }
  return base;
}

function resolveSingle() {
  console.log('resolve self');
  const self = dependencyGraph('.');
  const pkg = require(`./package.json`);
  const head = gitHead('.');
  const deps = {};
  Object.keys(self.dependencies).forEach((d) => {
    deps[d] = cleanupDependency(self.dependencies[d]);
  });
  return {
    name: self.name,
    version: pkg.version,
    resolved: head ? `${pkg.repository.url}#${head}` : pkg.version,
    dependencies: deps,
    extraDependencies: {}
  };
}

function generate() {
  console.log('building buildInfo');
  const isUeberContext = fs.existsSync('../phovea_registry.js');
  if (isUeberContext) {
    return resolveUeber();
  } else {
    return resolveSingle();
  }
}

const IS_WINDOWS = process.platform === 'win32';

function tmpdir() {
  if (IS_WINDOWS) {
    return process.env.TEMP || process.env.TMP ||
           (process.env.SystemRoot || process.env.windir) + '\\temp';
  } else {
    return process.env.TMPDIR || process.env.TMP || process.env.TEMP || '/tmp';
  }
}

module.exports.generate = generate;
module.exports.tmpFile = function() {
  const s = generate();
  const file = `${tmpdir()}/buildInfo${Math.random().toString(36).slice(-8)}.txt`;
  fs.writeFileSync(file, JSON.stringify(s, null, ' '));
  return file;
}

if (require.main === module) {
  fs.writeFile('deps.json', JSON.stringify(generate(), null, ' '));
}
<commit_msg>fix cornercase if there are no dependencies in buildInfo<commit_after>/**
 * Created by sam on 13.11.2016.
 */

const spawnSync = require('child_process').spawnSync;
const path = require('path');
const resolve = path.resolve;
const fs = require('fs');

function dependencyGraph(cwd) {
  const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
  const r = spawnSync(npm, ['ls', '--prod', '--json'], {
    cwd: cwd
  });
  if (!r.stdout) {
    console.error(cwd, r.error);
    return {};
  }
  return JSON.parse(r.stdout.toString());
}

function gitHead(cwd) {
  if (!fs.existsSync(cwd + '/.git')) {
    return null;
  }
  const r = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], {
    cwd: cwd
  });
  if (!r.stdout) {
    console.error(cwd, r.error);
    return {};
  }
  return r.stdout.toString().trim();
}

function resolveModules() {
  const reg = fs.readFileSync('../phovea_registry.js').toString();
  const regex = /import '(.*)\/phovea_registry.js'/g;
  const modules = [];
  var r;
  while ((r = regex.exec(reg)) !== null) {
    modules.push(r[1]);
  }
  return modules;
}

function cleanupDependency(d) {
  return d;
}

function resolveUeber() {
  console.log('resolve parent');
  const ueberDeps = dependencyGraph('..').dependencies;
  const modules = new Set(resolveModules());

  const resolveModule = (m) => {
    console.log('resolve', m);
    const pkg = require(`../${m}/package.json`);
    const head = gitHead('../' + m);
    return {
      name: pkg.name,
      version: pkg.version,
      resolved: head ? `${pkg.repository.url}#${head}` : pkg.version,
      dependencies: deps(pkg.dependencies)
    };
  };
  const deps = (deps) => {
    const r = {};
    Object.keys(deps).forEach((d) => {
      if (d in ueberDeps) {
        r[d] = cleanupDependency(ueberDeps[d]);
        delete ueberDeps[d];
      } else if (modules.has(d)) {
        modules.delete(d);
        r[d] = resolveModule(d);
      } else {
        r[d] = '-> link';
      }
    });
    return r;
  };

  // self =
  const root = path.basename(process.cwd());
  console.log(root);

  modules.delete(root);
  const base = resolveModule(root);
  base.extraDependencies = {};
  while (modules.size > 0) {
    let m = Array.from(modules.keys())[0];
    modules.delete(m);
    base.extraDependencies[m] = resolveModule(m);
  }
  return base;
}

function resolveSingle() {
  console.log('resolve self');
  const self = dependencyGraph('.');
  const pkg = require(`./package.json`);
  const head = gitHead('.');
  const deps = {};
  Object.keys(self.dependencies || {}).forEach((d) => {
    deps[d] = cleanupDependency(self.dependencies[d]);
  });
  return {
    name: self.name,
    version: pkg.version,
    resolved: head ? `${pkg.repository.url}#${head}` : pkg.version,
    dependencies: deps,
    extraDependencies: {}
  };
}

function generate() {
  console.log('building buildInfo');
  const isUeberContext = fs.existsSync('../phovea_registry.js');
  if (isUeberContext) {
    return resolveUeber();
  } else {
    return resolveSingle();
  }
}

const IS_WINDOWS = process.platform === 'win32';

function tmpdir() {
  if (IS_WINDOWS) {
    return process.env.TEMP || process.env.TMP ||
           (process.env.SystemRoot || process.env.windir) + '\\temp';
  } else {
    return process.env.TMPDIR || process.env.TMP || process.env.TEMP || '/tmp';
  }
}

module.exports.generate = generate;
module.exports.tmpFile = function() {
  const s = generate();
  const file = `${tmpdir()}/buildInfo${Math.random().toString(36).slice(-8)}.txt`;
  fs.writeFileSync(file, JSON.stringify(s, null, ' '));
  return file;
}

if (require.main === module) {
  fs.writeFile('deps.json', JSON.stringify(generate(), null, ' '));
}
<|endoftext|>


<commit_before>//concat config
module.exports = function(grunt) {

    var custom = grunt.option('custom');

    var FILES = {
        base: ['src/vizabi.js',
            'src/base/utils.js',
            'src/base/promise.js',
            'src/base/class.js',
            'src/base/data.js',
            'src/base/events.js',
            'src/base/intervals.js',
            'src/base/layout.js',
            'src/base/model.js',
            'src/base/component.js',
            'src/base/tool.js'
        ],
        components: ['.tmp/templates.js',
            'src/components/**/*.js'
        ],
        models: ['src/models/**/*.js'],
        tools: ['src/tools/**/*.js'],
        readers: ['src/readers/**/*.js'],
        plugins: ['src/plugins/**/*.js'],
        templates: ['src/components/**/*.html','src/tools/**/*.html'],
        custom: ['src/vizabi_prefs/'+custom+'.js']
    }

    var FILES_COMPONENTS = ['.tmp/templates.js',
        'src/components/_gapminder/timeslider/*.js'
    ];

    var BUILD_FILES = ([]).concat(FILES.base)
                     .concat(FILES.components)
                     .concat(FILES.models)
                     .concat(FILES.readers)
                     .concat(FILES.tools)
                     .concat(FILES.plugins);

    if(custom) {
        BUILD_FILES = BUILD_FILES.concat(FILES.custom);
    }

    return {
        options: {
            stripBanners: true,
            banner: '/* VIZABI - http://www.gapminder.org - <%= grunt.template.today("yyyy-mm-dd") %> */\n\n'
        },

        templates: {
            options: {
                process: function(src, filepath) {
                    var content = src.replace(/'/g, '\"')
                        .replace(/(\r\n|\n|\r)/gm, " ")
                        .replace(/\s+/g, " ")
                        .replace(/<!--[\s\S]*?-->/g, "");
                    return "(function() {" +
                        "var root = this;" +
                        "var s = root.document.createElement('script');" +
                        "s.type = 'text/template';" +
                        "s.setAttribute('id', '" + filepath + "');" +
                        "s.innerHTML = '" + content + "';" +
                        "root.document.body.appendChild(s);" +
                        "}).call(this);";
                }
            },
            src: FILES.templates,
            dest: '.tmp/templates.js',
        },

        full: {
            options: {
                sourceMap: true
            },
            src: BUILD_FILES,
            dest: 'dist/vizabi.js',
        }
    };
};<commit_msg>Minor folder name fix for custom build<commit_after>//concat config
module.exports = function(grunt) {

    var custom = grunt.option('custom');

    var FILES = {
        base: ['src/vizabi.js',
            'src/base/utils.js',
            'src/base/promise.js',
            'src/base/class.js',
            'src/base/data.js',
            'src/base/events.js',
            'src/base/intervals.js',
            'src/base/layout.js',
            'src/base/model.js',
            'src/base/component.js',
            'src/base/tool.js'
        ],
        components: ['.tmp/templates.js',
            'src/components/**/*.js'
        ],
        models: ['src/models/**/*.js'],
        tools: ['src/tools/**/*.js'],
        readers: ['src/readers/**/*.js'],
        plugins: ['src/plugins/**/*.js'],
        templates: ['src/components/**/*.html','src/tools/**/*.html'],
        custom: ['src/vizabi_custom/'+custom+'.js']
    }

    var FILES_COMPONENTS = ['.tmp/templates.js',
        'src/components/_gapminder/timeslider/*.js'
    ];

    var BUILD_FILES = ([]).concat(FILES.base)
                     .concat(FILES.components)
                     .concat(FILES.models)
                     .concat(FILES.readers)
                     .concat(FILES.tools)
                     .concat(FILES.plugins);

    if(custom) {
        BUILD_FILES = BUILD_FILES.concat(FILES.custom);
    }

    return {
        options: {
            stripBanners: true,
            banner: '/* VIZABI - http://www.gapminder.org - <%= grunt.template.today("yyyy-mm-dd") %> */\n\n'
        },

        templates: {
            options: {
                process: function(src, filepath) {
                    var content = src.replace(/'/g, '\"')
                        .replace(/(\r\n|\n|\r)/gm, " ")
                        .replace(/\s+/g, " ")
                        .replace(/<!--[\s\S]*?-->/g, "");
                    return "(function() {" +
                        "var root = this;" +
                        "var s = root.document.createElement('script');" +
                        "s.type = 'text/template';" +
                        "s.setAttribute('id', '" + filepath + "');" +
                        "s.innerHTML = '" + content + "';" +
                        "root.document.body.appendChild(s);" +
                        "}).call(this);";
                }
            },
            src: FILES.templates,
            dest: '.tmp/templates.js',
        },

        full: {
            options: {
                sourceMap: true
            },
            src: BUILD_FILES,
            dest: 'dist/vizabi.js',
        }
    };
};<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import styled from 'styled-components'
import EntityListApp from 'tocco-entity-list/src/main'
import {viewPersistor} from 'tocco-util'

const StyledListApp = styled.div`
  width: 100%;
`

const SubGrid = props => {
  const formBase = `${props.detailFormName}_${props.formField.path}`
  const id = `${props.appId}-subgrid-${props.entityName}-${props.entityKey}-${props.formField.reverseRelation}`

  return (
    <StyledListApp>
      <EntityListApp
        id={id}
        entityName={props.formField.targetEntity}
        formName={formBase}
        limit={props.limit}
        searchFormType={props.showSearchForm ? 'simple_advanced' : 'none'}
        navigationStrategy={props.navigationStrategy}
        showLink={true}
        onRowClick={e => {
          if (props.onRowClick) {
            props.onRowClick({
              id: e.id,
              gridName: props.formField.path,
              relationName: props.formField.path
            })
          }
        }}
        onNavigateToCreate={() => {
          props.navigateToCreate(props.formField.path)
        }}
        parent={{
          key: props.entityKey,
          reverseRelationName: props.formField.reverseRelation,
          model: props.entityName,
          relationName: props.formField.path
        }}
        emitAction={props.emitAction}
        store={viewPersistor.viewInfoSelector(id).store}
        onStoreCreate={store => {
          viewPersistor.persistViewInfo(id, {store})
        }}
        scrollBehaviour="inline"
        tableMinHeight="300px"
        locale={props.locale}
        modifyFormDefinition={props.modifyFormDefinition}
        actionAppComponent={props.actionAppComponent}
        reportIds={props.reportIds}
      />
    </StyledListApp>
  )
}

SubGrid.defaultProps = {
  limit: 5
}

SubGrid.propTypes = {
  entityKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  entityName: PropTypes.string.isRequired,
  detailFormName: PropTypes.string.isRequired,
  formField: PropTypes.shape({
    path: PropTypes.string,
    targetEntity: PropTypes.string,
    reverseRelation: PropTypes.string
  }).isRequired,
  onRowClick: PropTypes.func,
  navigateToCreate: PropTypes.func.isRequired,
  showSubGridsCreateButton: PropTypes.bool,
  appId: PropTypes.string,
  showSearchForm: PropTypes.bool,
  limit: PropTypes.number,
  emitAction: PropTypes.func.isRequired,
  navigationStrategy: PropTypes.objectOf(PropTypes.func),
  locale: PropTypes.string,
  modifyFormDefinition: PropTypes.func,
  actionAppComponent: PropTypes.func,
  reportIds: PropTypes.arrayOf(PropTypes.string)
}

export default SubGrid
<commit_msg>fix(entity-detail): fix view persistor in sub grid<commit_after>import PropTypes from 'prop-types'
import styled from 'styled-components'
import EntityListApp from 'tocco-entity-list/src/main'
import {viewPersistor} from 'tocco-util'

const StyledListApp = styled.div`
  width: 100%;
`

const SubGrid = props => {
  const formBase = `${props.detailFormName}_${props.formField.path}`
  // eslint-disable-next-line max-len
  const id = `${props.appId}-subgrid-${props.entityName}-${props.entityKey}-${props.formField.targetEntity}-${props.formField.reverseRelation}`

  return (
    <StyledListApp>
      <EntityListApp
        id={id}
        entityName={props.formField.targetEntity}
        formName={formBase}
        limit={props.limit}
        searchFormType={props.showSearchForm ? 'simple_advanced' : 'none'}
        navigationStrategy={props.navigationStrategy}
        showLink={true}
        onRowClick={e => {
          if (props.onRowClick) {
            props.onRowClick({
              id: e.id,
              gridName: props.formField.path,
              relationName: props.formField.path
            })
          }
        }}
        onNavigateToCreate={() => {
          props.navigateToCreate(props.formField.path)
        }}
        parent={{
          key: props.entityKey,
          reverseRelationName: props.formField.reverseRelation,
          model: props.entityName,
          relationName: props.formField.path
        }}
        emitAction={props.emitAction}
        store={viewPersistor.viewInfoSelector(id).store}
        onStoreCreate={store => {
          viewPersistor.persistViewInfo(id, {store})
        }}
        scrollBehaviour="inline"
        tableMinHeight="300px"
        locale={props.locale}
        modifyFormDefinition={props.modifyFormDefinition}
        actionAppComponent={props.actionAppComponent}
        reportIds={props.reportIds}
      />
    </StyledListApp>
  )
}

SubGrid.defaultProps = {
  limit: 5
}

SubGrid.propTypes = {
  entityKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  entityName: PropTypes.string.isRequired,
  detailFormName: PropTypes.string.isRequired,
  formField: PropTypes.shape({
    path: PropTypes.string,
    targetEntity: PropTypes.string,
    reverseRelation: PropTypes.string
  }).isRequired,
  onRowClick: PropTypes.func,
  navigateToCreate: PropTypes.func.isRequired,
  showSubGridsCreateButton: PropTypes.bool,
  appId: PropTypes.string,
  showSearchForm: PropTypes.bool,
  limit: PropTypes.number,
  emitAction: PropTypes.func.isRequired,
  navigationStrategy: PropTypes.objectOf(PropTypes.func),
  locale: PropTypes.string,
  modifyFormDefinition: PropTypes.func,
  actionAppComponent: PropTypes.func,
  reportIds: PropTypes.arrayOf(PropTypes.string)
}

export default SubGrid
<|endoftext|>


<commit_before>/** Parse json file following the specified format below to be stored in the site database.
* This parser will also make use of the schema to check the legibility of the data that is going to be
* passed into the database as well as the availability in the database( check if the module is available in database)

* Note that Academic Cohort will reference graduation requirement and focus area through their ID.
* Focus Area can be easily referenced through their name.
* However, graduation requirement requires both the cohort name and the requirement name to ensure uniqueness of document.
* Thus, for ease of referencing, graduation requirement document will be created together with the creation of academic cohort.

* Finally, make sure that the focus area and the module DB is available and populated before running this script.

* The information in the json file to be parsed should be stored in the following manner :
  { "data":[{
              "cohortName": "AY xxxx/xxxx",
              "uniqueGradRequirement": [
                  {
                    "requirementName": "requirement 1",
                    "requirementModules": ["module1", "module2", "module3"]
                  },
                  {
                    "requirementName": "requirement 2",
                    "requirementModules": ["module1", "module2", "module3"]
                  }
                ],
              "repeatedGradRequirement": "none",
              "cohortFocusArea": ["fa1","fa2","fa3"]
            },
            {
              "cohortName": "AY yyyy/yyyy",
              "uniqueGradRequirement": "none",
              "repeatedGradRequirement": [
              {
                /// this cohort should have existed in the DB
                "cohortName": "AY xxxx/xxxx",
                "graduationRequirement": ["requirement 2"]
              }],
              "cohortFocusArea": ["fa1","fa2","fa3"]
            }
          ]
}
*/

// import DB pointer in case required.
import {GraduationRequirements} from '../database-controller/graduation-requirement/graduationRequirement';
import { AcademicCohort } from '../database-controller/AcademicCohort/acadCohort';
// import method to insert new graduation requirement methods
import { createNewGradRequirement,
         insertNewGradRequirementModuleData } from '../database-controller/graduation-requirement/methods';
// import method to insert new academic cohort methods
import { createNewCohort,
         updateCohortGradRequirementIDs,
         getCohortByName,
         updateCohortFocusAreaIDs} from '../database-controller/AcademicCohort/methods';
// import method to get focus area id from their name.
import { getFocusAreaIDByName } from '../database-controller/focus-area/methods';
//import method to check availability of module in module database
import { findModuleAvailability } from '../database-controller/module/methods';

const gradRequirementFile = 'GraduationRequirement.json';

export const populateAcadCohortCollection = function() {
//make sure to only run this script on server side.
  if(Meteor.isServer){
    AcademicCohort.remove({});
    GraduationRequirements.remove({});

    // get data
    const jsonFile = JSON.parse(Assets.getText(gradRequirementFile));
    const acadCohortData = jsonFile["data"];

    for(var i = 0; i< acadCohortData.length; i++){

      let currentCohort = acadCohortData[i];
      let currentCohortName = currentCohort["cohortName"];
      let newCohortID = createNewCohort(currentCohortName);
      let gradRequirementIDs = [];

      // see if there is any unique graduation requirement
      if (currentCohort["uniqueGradRequirement"] != "none"){
        /// if there is , insert to grad requirement DB
        for(var j = 0; j < currentCohort["uniqueGradRequirement"].length; j++){
          let currentNewRequirement = currentCohort["uniqueGradRequirement"][j];
          let newRequirementID = createNewGradRequirement(currentNewRequirement["requirementName"],
                                                         currentNewRequirement["requirementModules"],
                                                         currentNewRequirement["requirementMCs"]);
          console.log(currentNewRequirement + ":" + newRequirementID);
          /// store ID to array
          gradRequirementIDs.push(newRequirementID);
        }
      }

      /// else find the equivalent grad requirement
      if (currentCohort["repeatedGradRequirement"] != "none"){
        for(var j = 0; j < currentCohort["repeatedGradRequirement"].length; j++){
          let referencedCohort = currentCohort["repeatedGradRequirement"][j]["cohortName"];
          let referencedGradIDDocument = getCohortByName(referencedCohort)["cohortGradRequirementID"];

          let requirementList = currentCohort["repeatedGradRequirement"][j]["graduationRequirement"];

          for(var k = 0; k < requirementList.length ; k++ ){
            currentRequirementName = requirementList[k];
            let matchingDocument = GraduationRequirements.findOne({$and:[{requirementName:currentRequirementName},{_id:{$in:referencedGradIDDocument}}]});
            gradRequirementIDs.push(matchingDocument["_id"]);
          }
        }
      }
  ////////////////////////////////////// FOCUS AREA /////////////////////////////////////////////////////////////////
      // check for focus area
      // its safe to assume that every cohort will always have focus area
      const focusAreaIDs = [];
      let currentFocusAreaList = currentCohort["cohortFocusArea"];
      if (currentFocusAreaList != "none"){
        for(var j = 0; j < currentFocusAreaList.length ; j++){
          // current focus area is the name! we need to obtain the ID!
          let currentFocusArea = currentFocusAreaList[j];
          let currentFocusAreaID = getFocusAreaIDByName(currentFocusArea);

          if(currentFocusAreaID === ''){
            console.log("cannot find matching document for focus Area named: " + currentFocusArea);
          } else {
            focusAreaIDs.push(currentFocusAreaID);
          }

        }

        updateCohortFocusAreaIDs(currentCohortName,focusAreaIDs)
        updateCohortGradRequirementIDs(currentCohortName,gradRequirementIDs);
      }

    }
  }
}<commit_msg>Delete bad naming convention file<commit_after><|endoftext|>


<commit_before>export default theme => ({
  container: {
    background: theme.colorSubscriptionContainerBackground,
    border: theme.colorSubscriptionContainerBorder,
    margin: [0, 0, 20, -20],
    padding: 20,
    'border-radius': theme.borderRadius,
    pointerEvents: 'none',
    height: 'auto',
  },
  titleContainer: {
    display: 'flex',
  },
  title: {
    'font-weight': 'bold',
    color: theme.colorSubscriptionContainerTitle,
  },
  actionButton: {
    background: theme.colorSubscriptionContainerActionButtonBackground,
    color: theme.colorSubscriptionContainerActionButtonColor,
    'margin-left': 'auto',
    'border-radius': theme.borderRadiusSmall,
    padding: [2, 4],
    'font-size': 12,
    pointerEvents: 'initial',
  },
  content: {
    opacity: 0.5,
    'margin-top': 20,
    '& > :last-child': {
      'margin-bottom': 0,
    },
  },
});
<commit_msg>give upgrade account button a bit more padding<commit_after>export default theme => ({
  container: {
    background: theme.colorSubscriptionContainerBackground,
    border: theme.colorSubscriptionContainerBorder,
    margin: [0, 0, 20, -20],
    padding: 20,
    'border-radius': theme.borderRadius,
    pointerEvents: 'none',
    height: 'auto',
  },
  titleContainer: {
    display: 'flex',
  },
  title: {
    'font-weight': 'bold',
    color: theme.colorSubscriptionContainerTitle,
  },
  actionButton: {
    background: theme.colorSubscriptionContainerActionButtonBackground,
    color: theme.colorSubscriptionContainerActionButtonColor,
    'margin-left': 'auto',
    'border-radius': theme.borderRadiusSmall,
    padding: [4, 8],
    'font-size': 12,
    pointerEvents: 'initial',
  },
  content: {
    opacity: 0.5,
    'margin-top': 20,
    '& > :last-child': {
      'margin-bottom': 0,
    },
  },
});
<|endoftext|>


<commit_before>'use strict';

const	EventEmitter	= require('events').EventEmitter,
	topLogPrefix	= 'larvitfiles: dataWriter.js: ',
	DbMigration	= require('larvitdbmigration'),
	lUtils	= new (require('larvitutils'))(),
	amsync	= require('larvitamsync'),
	async	= require('async');

function DataWriter(options, cb) {
	const	that	= this;

	that.readyInProgress	= false;
	that.isReady	= false;

	for (const key of Object.keys(options)) {
		that[key]	= options[key];
	}

	that.emitter	= new EventEmitter();

	that.listenToQueue(cb);
}

DataWriter.prototype.listenToQueue = function listenToQueue(retries, cb) {
	const	logPrefix	= topLogPrefix + 'listenToQueue() - ',
		that	= this,
		options	= {'exchange': that.exchangeName},
		tasks	= [];

	let	listenMethod;

	if (typeof retries === 'function') {
		cb	= retries;
		retries	= 0;
	}

	if (typeof cb !== 'function') {
		cb	= function () {};
	}

	if (retries === undefined) {
		retries = 0;
	}

	tasks.push(function (cb) {
		if (that.mode === 'master') {
			listenMethod	= 'consume';
			options.exclusive	= true;	// It is important no other client tries to sneak
			// out messages from us, and we want "consume"
			// since we want the queue to persist even if this
			// minion goes offline.
		} else if (that.mode === 'slave' || that.mode === 'noSync') {
			listenMethod = 'subscribe';
		} else {
			const	err	= new Error('Invalid that.mode. Must be either "master", "slave" or "noSync"');
			that.log.error(logPrefix + err.message);
			return cb(err);
		}

		that.log.info(logPrefix + 'listenMethod: ' + listenMethod);

		cb();
	});

	tasks.push(function (cb) {
		that.intercom.ready(cb);
	});

	tasks.push(function (cb) {
		that.intercom.ready(function (err) {
			if (err) {
				that.log.error(logPrefix + 'intercom.ready() err: ' + err.message);
				return;
			}

			that.intercom[listenMethod](options, function (message, ack, deliveryTag) {
				that.ready(function (err) {
					ack(err); // Ack first, if something goes wrong we log it and handle it manually

					if (err) {
						that.log.error(logPrefix + 'intercom.' + listenMethod + '() - that.ready() returned err: ' + err.message);
						return;
					}

					if (typeof message !== 'object') {
						that.log.error(logPrefix + 'intercom.' + listenMethod + '() - Invalid message received, is not an object! deliveryTag: "' + deliveryTag + '"');
						return;
					}

					if (typeof that[message.action] === 'function') {
						that[message.action](message.params, deliveryTag, message.uuid);
					} else {
						that.log.warn(logPrefix + 'intercom.' + listenMethod + '() - Unknown message.action received: "' + message.action + '"');
					}
				});
			}, cb);
		});
	});

	// Run the ready function
	tasks.push(function (cb) {
		that.ready(cb);
	});

	async.series(tasks, cb);
};

// This is ran before each incoming message on the queue is handeled
DataWriter.prototype.ready = function ready(retries, cb) {
	const	logPrefix	= topLogPrefix + 'ready() - ',
		that	= this,
		tasks	= [];

	if (typeof retries === 'function') {
		cb	= retries;
		retries	= 0;
	}

	if (typeof cb !== 'function') {
		cb	= function () {};
	}

	if (retries === undefined) {
		retries	= 0;
	}

	if (that.isReady === true) return cb();

	if (that.readyInProgress === true) {
		that.emitter.on('ready', cb);
		return;
	}

	that.readyInProgress = true;

	tasks.push(function (cb) {
		if (that.mode === 'slave') {
			that.log.verbose(logPrefix + 'that.mode: "' + that.mode + '", so read');
			amsync.mariadb({
				'exchange':	that.exchangeName + '_dataDump',
				'intercom':	that.intercom
			}, cb);
		} else {
			cb();
		}
	});

	// Migrate database
	tasks.push(function (cb) {
		const	options	= {};

		let	dbMigration;

		options.dbType	= 'mariadb';
		options.dbDriver	= that.db;
		options.tableName	= 'larvitfiles_db_version';
		options.migrationScriptsPath	= __dirname + '/dbmigration';
		options.storagePath	= that.storagePath;
		dbMigration	= new DbMigration(options);

		dbMigration.run(function (err) {
			if (err) {
				that.log.error(logPrefix + 'Database error: ' + err.message);
			}

			cb(err);
		});
	});

	async.series(tasks, function (err) {
		if (err) return;

		that.isReady	= true;
		that.emitter.emit('ready');

		if (that.mode === 'both' || that.mode === 'master') {
			that.runDumpServer(cb);
		} else {
			cb();
		}
	});
};

DataWriter.prototype.rm = function rm(params, deliveryTag, msgUuid) {
	const	logPrefix	= topLogPrefix + 'rm() - ',
		that	= this,
		options	= params.data,
		tasks	= [];

	if (options.uuid === undefined) {
		const err = new Error('No uuid set, can not remove file');
		that.log.info(logPrefix + err.message);
		return cb(err);
	}

	tasks.push(function (cb) {
		const uuiBuffer = lUtils.uuidToBuffer(options.uuid);

		if ( ! uuiBuffer) {
			const err = new Error('Not a valid uuid: ' + options.uuid	);
			that.log.info(logPrefix + err.message);
			return cb(err);
		}

		that.db.query('DELETE FROM larvitfiles_files_metadata WHERE fileUuid = ?', [uuiBuffer], cb);
	});

	tasks.push(function (cb) {
		const uuiBuffer = lUtils.uuidToBuffer(options.uuid);

		if ( ! uuiBuffer) {
			const err = new Error('Not a valid uuid: ' + options.uuid	);
			that.log.info(logPrefix + err.message);
			return cb(err);
		}

		that.db.query('DELETE FROM larvitfiles_files WHERE uuid = ?', [uuiBuffer], cb);
	});

	async.series(tasks, function (err) {
		that.emitter.emit(msgUuid, err);
	});
};

DataWriter.prototype.runDumpServer = function runDumpServer(cb) {
	const	that	= this,
		options	= {
			'exchange':	that.exchangeName + '_dataDump',
			'host':	that.amsync ? that.amsync.host : null,
			'minPort':	that.amsync ? that.amsync.minPort : null,
			'maxPort':	that.amsync ? that.amsync.maxPort : null
		},
		args	= [];

	if (that.db.conf.host) {
		args.push('-h');
		args.push(that.db.conf.host);
	}

	args.push('-u');
	args.push(that.db.conf.user);

	if (that.db.conf.password) {
		args.push('-p' + db.conf.password);
	}

	args.push('--single-transaction');
	args.push('--hex-blob');
	args.push(that.db.conf.database);

	// Tables
	args.push('larvitfiles_db_version');
	args.push('larvitfiles_files');
	args.push('larvitfiles_files_metadata');

	options.dataDumpCmd = {
		'command':	'mysqldump',
		'args':	args
	};

	options['Content-Type']	= 'application/sql';
	options.intercom	= that.intercom;

	new amsync.SyncServer(options, cb);
};

DataWriter.prototype.save = function save(params, deliveryTag, msgUuid) {
	const	logPrefix	= topLogPrefix + 'save() - ',
		that	= this,
		options	= params.data,
		tasks	= [];

	if (options.slug === undefined) {
		const err = new Error('Slug must be set to save to database');
		that.log.info(logPrefix + err.message);
		return cb(err);
	}

	// Check validity of slug and uuid
	tasks.push(function (cb) {
		that.db.query('SELECT uuid FROM larvitfiles_files WHERE slug = ?', [options.slug], function (err, rows) {
			let	uuid	= null;

			if (err) return cb(err);

			if (rows.length === 1) {
				uuid = lUtils.formatUuid(rows[0].uuid);
			}

			if (uuid !== null && uuid !== options.uuid) {
				const	err	= new Error('Slug "' + options.slug + '" is take by another file');
				that.log.info(logPrefix + err.message);
				return cb(err);
			}

			cb();
		});
	});

	// Insert into files
	tasks.push(function (cb) {
		const	uuiBuffer = lUtils.uuidToBuffer(options.uuid);

		if ( ! uuiBuffer) {
			const err = new Error('Not a valid uuid: ' + options.uuid	);
			that.log.info(logPrefix + err.message);
			return cb(err);
		}

		that.db.query('INSERT INTO larvitfiles_files VALUES(?,?) ON DUPLICATE KEY UPDATE slug = VALUES(slug)', [uuiBuffer, options.slug], cb);
	});

	// Delete metadata
	tasks.push(function (cb) {
		const	uuiBuffer = lUtils.uuidToBuffer(options.uuid);

		if ( ! uuiBuffer) {
			const err = new Error('Not a valid uuid: ' + options.uuid	);
			that.log.info(logPrefix + err.message);
			return cb(err);
		}

		that.db.query('DELETE FROM larvitfiles_files_metadata WHERE fileUuid = ?;', [uuiBuffer], cb);
	});

	// Insert metadata
	tasks.push(function (cb) {
		const	dbFields	= [];

		let	sql	= 'INSERT INTO larvitfiles_files_metadata VALUES';

		for (const name of Object.keys(options.metadata)) {
			if ( ! (options.metadata[name] instanceof Array)) {
				options.metadata[name] = [options.metadata[name]];
			}

			for (let i = 0; options.metadata[name][i] !== undefined; i ++) {
				const	uuiBuffer = lUtils.uuidToBuffer(options.uuid);

				if (uuiBuffer) {
					sql += '(?,?,?),';
					dbFields.push(uuiBuffer);
					dbFields.push(name);
					dbFields.push(options.metadata[name][i]);
				} else {
					that.log.info(logPrefix + 'Invalid uuid, skipping');
				}
			}
		}

		if (dbFields.length === 0) {
			return cb();
		}

		sql = sql.substring(0, sql.length - 1) + ';';
		that.db.query(sql, dbFields, cb);
	});

	async.series(tasks, function (err) {
		that.emitter.emit(msgUuid, err);
	});
};

exports = module.exports = DataWriter;<commit_msg>Use instance of SyncClient instead of calling mariadb directly<commit_after>'use strict';

const	EventEmitter	= require('events').EventEmitter,
	topLogPrefix	= 'larvitfiles: dataWriter.js: ',
	DbMigration	= require('larvitdbmigration'),
	lUtils	= new (require('larvitutils'))(),
	amsync	= require('larvitamsync'),
	async	= require('async');

function DataWriter(options, cb) {
	const	that	= this;

	that.readyInProgress	= false;
	that.isReady	= false;

	for (const key of Object.keys(options)) {
		that[key]	= options[key];
	}

	that.emitter	= new EventEmitter();

	that.listenToQueue(cb);
}

DataWriter.prototype.listenToQueue = function listenToQueue(retries, cb) {
	const	logPrefix	= topLogPrefix + 'listenToQueue() - ',
		that	= this,
		options	= {'exchange': that.exchangeName},
		tasks	= [];

	let	listenMethod;

	if (typeof retries === 'function') {
		cb	= retries;
		retries	= 0;
	}

	if (typeof cb !== 'function') {
		cb	= function () {};
	}

	if (retries === undefined) {
		retries = 0;
	}

	tasks.push(function (cb) {
		if (that.mode === 'master') {
			listenMethod	= 'consume';
			options.exclusive	= true;	// It is important no other client tries to sneak
			// out messages from us, and we want "consume"
			// since we want the queue to persist even if this
			// minion goes offline.
		} else if (that.mode === 'slave' || that.mode === 'noSync') {
			listenMethod = 'subscribe';
		} else {
			const	err	= new Error('Invalid that.mode. Must be either "master", "slave" or "noSync"');
			that.log.error(logPrefix + err.message);
			return cb(err);
		}

		that.log.info(logPrefix + 'listenMethod: ' + listenMethod);

		cb();
	});

	tasks.push(function (cb) {
		that.intercom.ready(cb);
	});

	tasks.push(function (cb) {
		that.intercom.ready(function (err) {
			if (err) {
				that.log.error(logPrefix + 'intercom.ready() err: ' + err.message);
				return;
			}

			that.intercom[listenMethod](options, function (message, ack, deliveryTag) {
				that.ready(function (err) {
					ack(err); // Ack first, if something goes wrong we log it and handle it manually

					if (err) {
						that.log.error(logPrefix + 'intercom.' + listenMethod + '() - that.ready() returned err: ' + err.message);
						return;
					}

					if (typeof message !== 'object') {
						that.log.error(logPrefix + 'intercom.' + listenMethod + '() - Invalid message received, is not an object! deliveryTag: "' + deliveryTag + '"');
						return;
					}

					if (typeof that[message.action] === 'function') {
						that[message.action](message.params, deliveryTag, message.uuid);
					} else {
						that.log.warn(logPrefix + 'intercom.' + listenMethod + '() - Unknown message.action received: "' + message.action + '"');
					}
				});
			}, cb);
		});
	});

	// Run the ready function
	tasks.push(function (cb) {
		that.ready(cb);
	});

	async.series(tasks, cb);
};

// This is ran before each incoming message on the queue is handeled
DataWriter.prototype.ready = function ready(retries, cb) {
	const	logPrefix	= topLogPrefix + 'ready() - ',
		that	= this,
		tasks	= [];

	if (typeof retries === 'function') {
		cb	= retries;
		retries	= 0;
	}

	if (typeof cb !== 'function') {
		cb	= function () {};
	}

	if (retries === undefined) {
		retries	= 0;
	}

	if (that.isReady === true) return cb();

	if (that.readyInProgress === true) {
		that.emitter.on('ready', cb);
		return;
	}

	that.readyInProgress = true;

	tasks.push(function (cb) {
		if (that.mode === 'slave') {
			that.log.verbose(logPrefix + 'that.mode: "' + that.mode + '", so read');
			new amsync.SyncClient({
				'exchange':	that.exchangeName + '_dataDump',
				'intercom':	that.intercom
			}, cb);
		} else {
			cb();
		}
	});

	// Migrate database
	tasks.push(function (cb) {
		const	options	= {};

		let	dbMigration;

		options.dbType	= 'mariadb';
		options.dbDriver	= that.db;
		options.tableName	= 'larvitfiles_db_version';
		options.migrationScriptsPath	= __dirname + '/dbmigration';
		options.storagePath	= that.storagePath;
		dbMigration	= new DbMigration(options);

		dbMigration.run(function (err) {
			if (err) {
				that.log.error(logPrefix + 'Database error: ' + err.message);
			}

			cb(err);
		});
	});

	async.series(tasks, function (err) {
		if (err) return;

		that.isReady	= true;
		that.emitter.emit('ready');

		if (that.mode === 'both' || that.mode === 'master') {
			that.runDumpServer(cb);
		} else {
			cb();
		}
	});
};

DataWriter.prototype.rm = function rm(params, deliveryTag, msgUuid) {
	const	logPrefix	= topLogPrefix + 'rm() - ',
		that	= this,
		options	= params.data,
		tasks	= [];

	if (options.uuid === undefined) {
		const err = new Error('No uuid set, can not remove file');
		that.log.info(logPrefix + err.message);
		return cb(err);
	}

	tasks.push(function (cb) {
		const uuiBuffer = lUtils.uuidToBuffer(options.uuid);

		if ( ! uuiBuffer) {
			const err = new Error('Not a valid uuid: ' + options.uuid	);
			that.log.info(logPrefix + err.message);
			return cb(err);
		}

		that.db.query('DELETE FROM larvitfiles_files_metadata WHERE fileUuid = ?', [uuiBuffer], cb);
	});

	tasks.push(function (cb) {
		const uuiBuffer = lUtils.uuidToBuffer(options.uuid);

		if ( ! uuiBuffer) {
			const err = new Error('Not a valid uuid: ' + options.uuid	);
			that.log.info(logPrefix + err.message);
			return cb(err);
		}

		that.db.query('DELETE FROM larvitfiles_files WHERE uuid = ?', [uuiBuffer], cb);
	});

	async.series(tasks, function (err) {
		that.emitter.emit(msgUuid, err);
	});
};

DataWriter.prototype.runDumpServer = function runDumpServer(cb) {
	const	that	= this,
		options	= {
			'exchange':	that.exchangeName + '_dataDump',
			'host':	that.amsync ? that.amsync.host : null,
			'minPort':	that.amsync ? that.amsync.minPort : null,
			'maxPort':	that.amsync ? that.amsync.maxPort : null
		},
		args	= [];

	if (that.db.conf.host) {
		args.push('-h');
		args.push(that.db.conf.host);
	}

	args.push('-u');
	args.push(that.db.conf.user);

	if (that.db.conf.password) {
		args.push('-p' + db.conf.password);
	}

	args.push('--single-transaction');
	args.push('--hex-blob');
	args.push(that.db.conf.database);

	// Tables
	args.push('larvitfiles_db_version');
	args.push('larvitfiles_files');
	args.push('larvitfiles_files_metadata');

	options.dataDumpCmd = {
		'command':	'mysqldump',
		'args':	args
	};

	options['Content-Type']	= 'application/sql';
	options.intercom	= that.intercom;

	new amsync.SyncServer(options, cb);
};

DataWriter.prototype.save = function save(params, deliveryTag, msgUuid) {
	const	logPrefix	= topLogPrefix + 'save() - ',
		that	= this,
		options	= params.data,
		tasks	= [];

	if (options.slug === undefined) {
		const err = new Error('Slug must be set to save to database');
		that.log.info(logPrefix + err.message);
		return cb(err);
	}

	// Check validity of slug and uuid
	tasks.push(function (cb) {
		that.db.query('SELECT uuid FROM larvitfiles_files WHERE slug = ?', [options.slug], function (err, rows) {
			let	uuid	= null;

			if (err) return cb(err);

			if (rows.length === 1) {
				uuid = lUtils.formatUuid(rows[0].uuid);
			}

			if (uuid !== null && uuid !== options.uuid) {
				const	err	= new Error('Slug "' + options.slug + '" is take by another file');
				that.log.info(logPrefix + err.message);
				return cb(err);
			}

			cb();
		});
	});

	// Insert into files
	tasks.push(function (cb) {
		const	uuiBuffer = lUtils.uuidToBuffer(options.uuid);

		if ( ! uuiBuffer) {
			const err = new Error('Not a valid uuid: ' + options.uuid	);
			that.log.info(logPrefix + err.message);
			return cb(err);
		}

		that.db.query('INSERT INTO larvitfiles_files VALUES(?,?) ON DUPLICATE KEY UPDATE slug = VALUES(slug)', [uuiBuffer, options.slug], cb);
	});

	// Delete metadata
	tasks.push(function (cb) {
		const	uuiBuffer = lUtils.uuidToBuffer(options.uuid);

		if ( ! uuiBuffer) {
			const err = new Error('Not a valid uuid: ' + options.uuid	);
			that.log.info(logPrefix + err.message);
			return cb(err);
		}

		that.db.query('DELETE FROM larvitfiles_files_metadata WHERE fileUuid = ?;', [uuiBuffer], cb);
	});

	// Insert metadata
	tasks.push(function (cb) {
		const	dbFields	= [];

		let	sql	= 'INSERT INTO larvitfiles_files_metadata VALUES';

		for (const name of Object.keys(options.metadata)) {
			if ( ! (options.metadata[name] instanceof Array)) {
				options.metadata[name] = [options.metadata[name]];
			}

			for (let i = 0; options.metadata[name][i] !== undefined; i ++) {
				const	uuiBuffer = lUtils.uuidToBuffer(options.uuid);

				if (uuiBuffer) {
					sql += '(?,?,?),';
					dbFields.push(uuiBuffer);
					dbFields.push(name);
					dbFields.push(options.metadata[name][i]);
				} else {
					that.log.info(logPrefix + 'Invalid uuid, skipping');
				}
			}
		}

		if (dbFields.length === 0) {
			return cb();
		}

		sql = sql.substring(0, sql.length - 1) + ';';
		that.db.query(sql, dbFields, cb);
	});

	async.series(tasks, function (err) {
		that.emitter.emit(msgUuid, err);
	});
};

exports = module.exports = DataWriter;<|endoftext|>


<commit_before>// Checks for Depracated database objects that only have a [url] instead of [{url:"",...}]
var UpToDate = function(db_object_to_check){
	if(typeof db_object_to_check === 'string'){ // NOT up to date
		return false;
	}
	else if(typeof db_object_to_check === 'object'){ // YES up to date
		if(typeof db_object_to_check.url !== 'undefined' && typeof db_object_to_check.caption !== 'undefined'){
			return true;
		}
		else{
			return false;
		}
	}
	else{
		return false;
	}
};

var processURL = function(i){

	/* for(var i = 0;i<imageDB.length;i++){ */
	var img = "";

	if(typeof imageDB[i] === 'string'){ // is it the depracated database style
		img = imageDB[i] ? imageDB[i] : ""; // is there something actually there at that place in the database? No? Then just put ""
	}
	else if(typeof imageDB[i] === 'object'){ // or the updated one with .properties?
		img = imageDB[i].url;
	}
	// determine whether image or html5 video by its END extension
	var element = "";
	var extension = img.substr(img.lastIndexOf('.')+1);
	switch(extension){ // if its an image file
		case 'jpg':
		case 'jpeg':
		case 'bmp':
		case 'tif':
		case 'gif':
			element = ""; // placeholder img element with no source

			console.log("pushed item");
			break;
		case 'gifv': // if its an html5 video file
		case 'webm':
		case 'mp4':
		case 'mov':
		case 'avi':
		case 'mpeg':
			element = "<video autoplay loop id='"+i+"' src='"+img+"'></video>";
			break;
		default:
			element = ""; // put in placeholder image object with no source
			// But if there's a video extension anywhere in the url, then go back to being a video:

			$(['mp4','webm','gifv']).each(function(x,item){
				if(img.indexOf(item)>=0){ // does the url contain a video extension?
					element = "<video autoplay loop id='"+i+"' src='"+img+"'></video>"
				}
			});
			break;
	}

	return element;
};

var processCaption = function(image){

	var caption = "";
	var outputhtml = "";

	if(UpToDate(image)){
		caption = image.caption;
		if(/<[a-z][\s\S]*>/i.test(caption)){
			caption = caption.replace("<","<").replace(">",">");
		}
	}
	else{
		caption = image;
	}

	return caption;

};

var getCaption = function(item){
	if(UpToDate(item)){
		return item.caption;
	}
	else{
		return item;
	}
}

var validImageCheck = function(src){
	var valid = true;
	var img = new Image(src);
	img.onerror = function(){
		valid = false;
	};
	return valid;
};<commit_msg>work incomplete on zoom functionality<commit_after>// Checks for Depracated database objects that only have a [url] instead of [{url:"",...}]
var UpToDate = function(db_object_to_check){
	if(typeof db_object_to_check === 'string'){ // NOT up to date
		return false;
	}
	else if(typeof db_object_to_check === 'object'){ // YES up to date
		if(typeof db_object_to_check.url !== 'undefined' && typeof db_object_to_check.caption !== 'undefined'){
			return true;
		}
		else{
			return false;
		}
	}
	else{
		return false;
	}
};

var widerThanTall = function(img){
	if(img.width > img.height){
		return true;
	}
	else{
		return false;
	}
}

var processURL = function(i){

	/* for(var i = 0;i<imageDB.length;i++){ */
	var img = "";

	if(typeof imageDB[i] === 'string'){ // is it the depracated database style
		img = imageDB[i] ? imageDB[i] : ""; // is there something actually there at that place in the database? No? Then just put ""
	}
	else if(typeof imageDB[i] === 'object'){ // or the updated one with .properties?
		img = imageDB[i].url;
	}
	// determine whether image or html5 video by its END extension
	var element = "";
	var extension = img.substr(img.lastIndexOf('.')+1);
	switch(extension){ // if its an image file
		case 'jpg':
		case 'jpeg':
		case 'bmp':
		case 'tif':
		case 'gif':
			element = ""; // placeholder img element with no source

			console.log("pushed item");
			break;
		case 'gifv': // if its an html5 video file
		case 'webm':
		case 'mp4':
		case 'mov':
		case 'avi':
		case 'mpeg':
			element = "<video autoplay loop id='"+i+"' src='"+img+"'></video>";
			break;
		default:
			element = ""; // put in placeholder image object with no source
			// But if there's a video extension anywhere in the url, then go back to being a video:

			$(['mp4','webm','gifv']).each(function(x,item){
				if(img.indexOf(item)>=0){ // does the url contain a video extension?
					element = "<video autoplay loop id='"+i+"' src='"+img+"'></video>"
				}
			});
			break;
	}

	return element;
};

var processCaption = function(image){

	var caption = "";
	var outputhtml = "";

	if(UpToDate(image)){
		caption = image.caption;
		if(/<[a-z][\s\S]*>/i.test(caption)){
			caption = caption.replace("<","<").replace(">",">");
		}
	}
	else{
		caption = image;
	}

	return caption;

};

var getCaption = function(item){
	if(UpToDate(item)){
		return item.caption;
	}
	else{
		return item;
	}
}

var validImageCheck = function(src){
	var valid = true;
	var img = new Image(src);
	img.onerror = function(){
		valid = false;
	};
	return valid;
};

var bgPositionToObject = function(element){
	var position = $(element).css('background-position').replace('px','').replace('px','').replace('%','').replace('%','').split(' ');

	return {x:parseInt(position[0]),y:parseInt(position[1])};
}<|endoftext|>


<commit_before>(function(µ,SMOD,GMOD,HMOD,SC){

	var gui=require("MorgasGui");
	var Concat=require("concat-with-sourcemaps");

	SC=SC({
		dependencyParser:require.bind(null,"Morgas/dependencyParser"),
		morgasModuleRegister:"Morgas.ModuleRegister",
		morgasModuleDependencies:"Morgas.ModuleDependencies",
		morgasGuiModuleRegister:"Morgas.gui.ModuleRegister",
		morgasGuiModuleDependencies:"Morgas.gui.ModuleDependencies",
		DependencyResolver:"DepRes",
		File:"File"
	});

	var normalizePath=function(path){return path.replace(/\\/g,"/");};
	var morgasJsFile=normalizePath(new SC.File(µ.dirname).changePath("Morgas.js").getAbsolutePath());

	module.exports=function(files,relativeTo)
	{
		relativeTo=SC.File.stringToFile(relativeTo);

		var replaceDirs=[[normalizePath(µ.dirname)+"/","/morgas/"],[normalizePath(gui.dirname)+"/","/morgas/gui/"],[normalizePath(process.cwd())+"/","../../"]];

		var parser=(new SC.dependencyParser()).addSources(files)
		.addModuleRegister(SC.morgasModuleRegister,µ.dirname).addModuleDependencies(SC.morgasModuleDependencies,µ.dirname)
		.addModuleRegister(SC.morgasGuiModuleRegister,gui.dirname).addModuleDependencies(SC.morgasGuiModuleDependencies,gui.dirname);

		return function(param)
		{
			var file=relativeTo.clone();
			file.changePath.apply(file,param.path);
			return file.exists()
			.then(function()
			{
				return parser.parse()
				.then(function(result)
				{
					var resolver=new SC.DependencyResolver(result.fileDependencies);
					var files=resolver.resolve([morgasJsFile,normalizePath(file.getAbsolutePath())]);
					return Promise.all(files.map(f=>SC.File.stringToFile(f).read().then(data=>[f,data])))
					.then(function(fileContents)
					{
						var concat=new Concat(true,param.path.join("/"),"\n/********************/\n");
						for (var fileContent of fileContents)
						{
							var name=fileContent[0];
							var data=fileContent[1];
							replaceDirs.forEach(p=>name=String.prototype.replace.apply(name,p));
							concat.add(name,data);
						}
						return concat.content+"\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + new Buffer(concat.sourceMap).toString("base64")
					});
				})
				//.then(files=>files.join("\n/********************/\n"));
			},()=>param.status=404)

		}
	}

})(Morgas,Morgas.setModule,Morgas.getModule,Morgas.hasModule,Morgas.shortcut);<commit_msg>serve dependencies<commit_after>(function(µ,SMOD,GMOD,HMOD,SC){

	var gui=require("MorgasGui");
	var Concat=require("concat-with-sourcemaps");

	SC=SC({
		dependencyParser:require.bind(null,"Morgas/dependencyParser"),
		morgasModuleRegister:"Morgas.ModuleRegister",
		morgasModuleDependencies:"Morgas.ModuleDependencies",
		morgasGuiModuleRegister:"Morgas.gui.ModuleRegister",
		morgasGuiModuleDependencies:"Morgas.gui.ModuleDependencies",
		DependencyResolver:"DepRes",
		File:"File"
	});

	var normalizePath=function(path){return path.replace(/\\/g,"/");};
	var morgasJsFile=normalizePath(new SC.File(µ.dirname).changePath("Morgas.js").getAbsolutePath());

	module.exports=function(files,relativeTo)
	{
		relativeTo=SC.File.stringToFile(relativeTo);

		var replaceDirs=[[normalizePath(µ.dirname)+"/","/morgas/"],[normalizePath(gui.dirname)+"/","/morgas/gui/"],[normalizePath(process.cwd())+"/","../../"]];

		var parser=(new SC.dependencyParser()).addSources(files)
		.addModuleRegister(SC.morgasModuleRegister,µ.dirname).addModuleDependencies(SC.morgasModuleDependencies,µ.dirname)
		.addModuleRegister(SC.morgasGuiModuleRegister,gui.dirname).addModuleDependencies(SC.morgasGuiModuleDependencies,gui.dirname);

		return function(param)
		{
			if(param.path.length==0) return parser.parse();

			var file=relativeTo.clone();
			file.changePath.apply(file,param.path);
			return file.exists()
			.then(function()
			{
				return parser.parse()
				.then(function(result)
				{
					var resolver=new SC.DependencyResolver(result.fileDependencies);
					var files=resolver.resolve([morgasJsFile,normalizePath(file.getAbsolutePath())]);
					return Promise.all(files.map(f=>SC.File.stringToFile(f).read().then(data=>[f,data])))
					.then(function(fileContents)
					{
						var concat=new Concat(true,param.path.join("/"),"\n/********************/\n");
						for (var fileContent of fileContents)
						{
							var name=fileContent[0];
							var data=fileContent[1];
							replaceDirs.forEach(p=>name=String.prototype.replace.apply(name,p));
							concat.add(name,data);
						}
						return concat.content+"\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + new Buffer(concat.sourceMap).toString("base64")
					});
				})
				//.then(files=>files.join("\n/********************/\n"));
			},()=>param.status=404)
		}
	}

})(Morgas,Morgas.setModule,Morgas.getModule,Morgas.hasModule,Morgas.shortcut);<|endoftext|>


<commit_before>var React = require('react/addons');
var classNames = require('classnames');
var blacklist = require('blacklist');

module.exports = React.createClass({
	displayName: 'ElementalButton',
	propTypes: {
		className: React.PropTypes.string,
		href: React.PropTypes.string,
		onClick: React.PropTypes.func,
		size: React.PropTypes.string,
		submit: React.PropTypes.bool,
		type: React.PropTypes.string
	},
	getDefaultProps() {
		return {
			type: 'default'
		};
	},
	render() {
		// classes
		var componentClass = classNames(
			'Button',
			'Button--' + this.props.type,
			this.props.size ? 'Button--' + this.props.size : null,
			this.props.className
		);

		// props
		var props = blacklist(this.props, ['type', 'size', 'className']);
		props.className = componentClass;

		var tag = 'a';

		if (!props.href) {
			tag = 'button';
			props.type = this.props.submit ? 'submit' : 'button';
		}

		return React.createElement(
			tag,
			props,
			this.props.children
		);
	}
});<commit_msg>define possible button types<commit_after>var React = require('react/addons');
var classNames = require('classnames');
var blacklist = require('blacklist');

var BUTTON_TYPES = [
	'default',
	'default-primary',
	'default-success',
	'default-warning',
	'default-danger',
	'primary',
	'success',
	'warning',
	'danger',
	'link',
	'link-cancel'
]

module.exports = React.createClass({
	displayName: 'ElementalButton',
	propTypes: {
		className: React.PropTypes.string,
		href: React.PropTypes.string,
		onClick: React.PropTypes.func,
		size: React.PropTypes.string,
		submit: React.PropTypes.bool,
		type: React.PropTypes.oneOf(BUTTON_TYPES)
	},
	getDefaultProps() {
		return {
			type: 'default'
		};
	},
	render() {
		// classes
		var componentClass = classNames(
			'Button',
			'Button--' + this.props.type,
			this.props.size ? 'Button--' + this.props.size : null,
			this.props.className
		);

		// props
		var props = blacklist(this.props, ['type', 'size', 'className']);
		props.className = componentClass;

		var tag = 'a';

		if (!props.href) {
			tag = 'button';
			props.type = this.props.submit ? 'submit' : 'button';
		}

		return React.createElement(
			tag,
			props,
			this.props.children
		);
	}
});<|endoftext|>