<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import {
  TouchableNativeFeedback,
  TouchableHighlight,
  StyleSheet,
  View,
  Platform,
  ActivityIndicator,
  Text as NativeText,
} from 'react-native';
import colors from '../config/colors';
import Text from '../text/Text';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import getIconType from '../helpers/getIconType';
import normalize from '../helpers/normalizeText';
import ViewPropTypes from '../config/ViewPropTypes';

const log = () => {
  console.log('please attach method to this component'); //eslint-disable-line no-console
};

const Button = props => {
  const {
    disabled,
    loading,
    loadingRight,
    activityIndicatorStyle,
    buttonStyle,
    borderRadius,
    title,
    onPress,
    icon,
    iconComponent,
    secondary,
    secondary2,
    secondary3,
    primary1,
    primary2,
    backgroundColor,
    color,
    fontSize,
    underlayColor,
    raised,
    textStyle,
    large,
    iconRight,
    fontWeight,
    disabledStyle,
    fontFamily,
    containerViewStyle,
    rounded,
    outline,
    transparent,
    textNumberOfLines,
    textEllipsizeMode,
    allowFontScaling,
    ...attributes
  } = props;
  let { Component, rightIcon, leftIcon } = props;

  let leftIconElement;
  if (!leftIcon && icon) {
    leftIcon = icon;
  }
  if (leftIcon) {
    let Icon;
    if (iconComponent) {
      Icon = iconComponent;
    } else if (!leftIcon.type) {
      Icon = MaterialIcon;
    } else {
      Icon = getIconType(leftIcon.type);
    }
    leftIconElement = (
      <Icon
        {...leftIcon}
        color={leftIcon.color || 'white'}
        size={leftIcon.size || (large ? 26 : 18)}
        style={[styles.icon, leftIcon.style && leftIcon.style]}
      />
    );
  }
  let rightIconElement;
  if (iconRight || rightIcon) {
    if (!rightIcon) {
      rightIcon = iconRight;
    }
    let Icon;
    if (iconComponent) {
      Icon = iconComponent;
    } else if (!rightIcon.type) {
      Icon = MaterialIcon;
    } else {
      Icon = getIconType(rightIcon.type);
    }
    rightIconElement = (
      <Icon
        {...rightIcon}
        color={rightIcon.color || 'white'}
        size={rightIcon.size || (large ? 26 : 18)}
        style={[styles.iconRight, rightIcon.style && rightIcon.style]}
      />
    );
  }
  let loadingElement;
  if (loading) {
    loadingElement = (
      <ActivityIndicator
        animating={true}
        style={[styles.activityIndicatorStyle, activityIndicatorStyle]}
        color={color || 'white'}
        size={(large && 'large') || 'small'}
      />
    );
  }
  if (!Component && Platform.OS === 'ios') {
    Component = TouchableHighlight;
  }
  if (!Component && Platform.OS === 'android') {
    Component = TouchableNativeFeedback;
  }
  if (!Component) {
    Component = TouchableHighlight;
  }

  if (Platform.OS === 'android' && (borderRadius && !attributes.background)) {
    attributes.background = TouchableNativeFeedback.Ripple(
      'ThemeAttrAndroid',
      true
    );
  }

  const baseFont = {
    color: (textStyle && textStyle.color) || color || stylesObject.text.color,
    size: (textStyle && textStyle.fontSize) ||
      fontSize ||
      (!large && stylesObject.smallFont.fontSize) ||
      stylesObject.text.fontSize,
  };

  let textOptions = {};
  if (textNumberOfLines) {
    textOptions.numberOfLines = textNumberOfLines;
    if (textEllipsizeMode) {
      textOptions.ellipsizeMode = textEllipsizeMode;
    }
  }

  return (
    <View
      style={[
        styles.container,
        raised && styles.raised,
        containerViewStyle,
        borderRadius && { borderRadius },
      ]}
    >
      <Component
        underlayColor={underlayColor || 'transparent'}
        onPress={onPress || log}
        disabled={disabled || false}
        {...attributes}
      >
        <View
          style={[
            styles.button,
            secondary && { backgroundColor: colors.secondary },
            secondary2 && { backgroundColor: colors.secondary2 },
            secondary3 && { backgroundColor: colors.secondary3 },
            primary1 && { backgroundColor: colors.primary1 },
            primary2 && { backgroundColor: colors.primary2 },
            backgroundColor && { backgroundColor: backgroundColor },
            borderRadius && { borderRadius },
            !large && styles.small,
            rounded && {
              borderRadius: baseFont.size * 3.8,
              paddingHorizontal: !large
                ? stylesObject.small.padding * 1.5
                : stylesObject.button.padding * 1.5,
            },
            outline && {
              borderWidth: 1,
              backgroundColor: 'transparent',
              borderColor: baseFont.color,
            },
            transparent && {
              borderWidth: 0,
              backgroundColor: 'transparent',
            },
            buttonStyle && buttonStyle,
            disabled && { backgroundColor: colors.disabled },
            disabled && disabledStyle && disabledStyle,
          ]}
        >
          {(icon && !iconRight) || leftIconElement ? leftIconElement : null}
          {loading && !loadingRight && loadingElement}
          <Text
            style={[
              styles.text,
              color && { color },
              !large && styles.smallFont,
              fontSize && { fontSize },
              textStyle && textStyle,
              fontWeight && { fontWeight },
              fontFamily && { fontFamily },
            ]}
            {...textOptions}
            allowFontScaling={allowFontScaling}
          >
            {title}
          </Text>
          {loading && loadingRight && loadingElement}
          {(icon && iconRight) || rightIconElement ? rightIconElement : null}
        </View>
      </Component>
    </View>
  );
};

Button.propTypes = {
  buttonStyle: ViewPropTypes.style,
  title: PropTypes.string,
  onPress: PropTypes.any,
  icon: PropTypes.object,
  leftIcon: PropTypes.object,
  rightIcon: PropTypes.object,
  iconRight: PropTypes.object,
  iconComponent: PropTypes.any,
  secondary: PropTypes.bool,
  secondary2: PropTypes.bool,
  secondary3: PropTypes.bool,
  primary1: PropTypes.bool,
  primary2: PropTypes.bool,
  backgroundColor: PropTypes.string,
  color: PropTypes.string,
  fontSize: PropTypes.any,
  underlayColor: PropTypes.string,
  raised: PropTypes.bool,
  textStyle: NativeText.propTypes.style,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  activityIndicatorStyle: ViewPropTypes.style,
  loadingRight: PropTypes.bool,
  Component: PropTypes.any,
  borderRadius: PropTypes.number,
  large: PropTypes.bool,
  fontWeight: PropTypes.string,
  disabledStyle: ViewPropTypes.style,
  fontFamily: PropTypes.string,
  containerViewStyle: ViewPropTypes.style,
  rounded: PropTypes.bool,
  outline: PropTypes.bool,
  transparent: PropTypes.bool,
  allowFontScaling: PropTypes.bool,
  textNumberOfLines: PropTypes.number,
  textEllipsizeMode: PropTypes.string,
};

const stylesObject = {
  container: {
    backgroundColor: 'transparent',
    marginLeft: 15,
    marginRight: 15,
  },
  button: {
    padding: 19,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  text: {
    color: 'white',
    fontSize: normalize(16),
  },
  icon: {
    marginRight: 10,
  },
  iconRight: {
    marginLeft: 10,
  },
  small: {
    padding: 12,
  },
  smallFont: {
    fontSize: normalize(14),
  },
  activityIndicatorStyle: {
    marginHorizontal: 10,
    height: 0,
  },
  raised: {
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .4)',
        shadowOffset: { height: 1, width: 1 },
        shadowOpacity: 1,
        shadowRadius: 1,
      },
      android: {
        backgroundColor: '#fff',
        elevation: 2,
      },
    }),
  },
};

const styles = StyleSheet.create(stylesObject);

export default Button;
<commit_msg>Fix button borderRadius for android version < 21 (#617)<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import {
  TouchableNativeFeedback,
  TouchableHighlight,
  StyleSheet,
  View,
  Platform,
  ActivityIndicator,
  Text as NativeText,
} from 'react-native';
import colors from '../config/colors';
import Text from '../text/Text';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import getIconType from '../helpers/getIconType';
import normalize from '../helpers/normalizeText';
import ViewPropTypes from '../config/ViewPropTypes';

const log = () => {
  console.log('please attach method to this component'); //eslint-disable-line no-console
};

const Button = props => {
  const {
    disabled,
    loading,
    loadingRight,
    activityIndicatorStyle,
    buttonStyle,
    borderRadius,
    title,
    onPress,
    icon,
    iconComponent,
    secondary,
    secondary2,
    secondary3,
    primary1,
    primary2,
    backgroundColor,
    color,
    fontSize,
    underlayColor,
    raised,
    textStyle,
    large,
    iconRight,
    fontWeight,
    disabledStyle,
    fontFamily,
    containerViewStyle,
    rounded,
    outline,
    transparent,
    textNumberOfLines,
    textEllipsizeMode,
    allowFontScaling,
    ...attributes
  } = props;
  let { Component, rightIcon, leftIcon } = props;

  let leftIconElement;
  if (!leftIcon && icon) {
    leftIcon = icon;
  }
  if (leftIcon) {
    let Icon;
    if (iconComponent) {
      Icon = iconComponent;
    } else if (!leftIcon.type) {
      Icon = MaterialIcon;
    } else {
      Icon = getIconType(leftIcon.type);
    }
    leftIconElement = (
      <Icon
        {...leftIcon}
        color={leftIcon.color || 'white'}
        size={leftIcon.size || (large ? 26 : 18)}
        style={[styles.icon, leftIcon.style && leftIcon.style]}
      />
    );
  }
  let rightIconElement;
  if (iconRight || rightIcon) {
    if (!rightIcon) {
      rightIcon = iconRight;
    }
    let Icon;
    if (iconComponent) {
      Icon = iconComponent;
    } else if (!rightIcon.type) {
      Icon = MaterialIcon;
    } else {
      Icon = getIconType(rightIcon.type);
    }
    rightIconElement = (
      <Icon
        {...rightIcon}
        color={rightIcon.color || 'white'}
        size={rightIcon.size || (large ? 26 : 18)}
        style={[styles.iconRight, rightIcon.style && rightIcon.style]}
      />
    );
  }
  let loadingElement;
  if (loading) {
    loadingElement = (
      <ActivityIndicator
        animating={true}
        style={[styles.activityIndicatorStyle, activityIndicatorStyle]}
        color={color || 'white'}
        size={(large && 'large') || 'small'}
      />
    );
  }
  if (!Component && Platform.OS === 'ios') {
    Component = TouchableHighlight;
  }
  if (!Component && Platform.OS === 'android') {
    Component = TouchableNativeFeedback;
  }
  if (!Component) {
    Component = TouchableHighlight;
  }

  if (Platform.OS === 'android' && (borderRadius && !attributes.background)) {
    if (Platform.Version >= 21) {
      attributes.background = TouchableNativeFeedback.Ripple(
        'ThemeAttrAndroid',
        true
      );
    } else {
      attributes.background = TouchableNativeFeedback.SelectableBackground();
    }
  }

  const baseFont = {
    color: (textStyle && textStyle.color) || color || stylesObject.text.color,
    size: (textStyle && textStyle.fontSize) ||
      fontSize ||
      (!large && stylesObject.smallFont.fontSize) ||
      stylesObject.text.fontSize,
  };

  let textOptions = {};
  if (textNumberOfLines) {
    textOptions.numberOfLines = textNumberOfLines;
    if (textEllipsizeMode) {
      textOptions.ellipsizeMode = textEllipsizeMode;
    }
  }

  return (
    <View
      style={[
        styles.container,
        raised && styles.raised,
        containerViewStyle,
        borderRadius && { borderRadius },
      ]}
    >
      <Component
        underlayColor={underlayColor || 'transparent'}
        onPress={onPress || log}
        disabled={disabled || false}
        {...attributes}
      >
        <View
          style={[
            styles.button,
            secondary && { backgroundColor: colors.secondary },
            secondary2 && { backgroundColor: colors.secondary2 },
            secondary3 && { backgroundColor: colors.secondary3 },
            primary1 && { backgroundColor: colors.primary1 },
            primary2 && { backgroundColor: colors.primary2 },
            backgroundColor && { backgroundColor: backgroundColor },
            borderRadius && { borderRadius },
            !large && styles.small,
            rounded && {
              borderRadius: baseFont.size * 3.8,
              paddingHorizontal: !large
                ? stylesObject.small.padding * 1.5
                : stylesObject.button.padding * 1.5,
            },
            outline && {
              borderWidth: 1,
              backgroundColor: 'transparent',
              borderColor: baseFont.color,
            },
            transparent && {
              borderWidth: 0,
              backgroundColor: 'transparent',
            },
            buttonStyle && buttonStyle,
            disabled && { backgroundColor: colors.disabled },
            disabled && disabledStyle && disabledStyle,
          ]}
        >
          {(icon && !iconRight) || leftIconElement ? leftIconElement : null}
          {loading && !loadingRight && loadingElement}
          <Text
            style={[
              styles.text,
              color && { color },
              !large && styles.smallFont,
              fontSize && { fontSize },
              textStyle && textStyle,
              fontWeight && { fontWeight },
              fontFamily && { fontFamily },
            ]}
            {...textOptions}
            allowFontScaling={allowFontScaling}
          >
            {title}
          </Text>
          {loading && loadingRight && loadingElement}
          {(icon && iconRight) || rightIconElement ? rightIconElement : null}
        </View>
      </Component>
    </View>
  );
};

Button.propTypes = {
  buttonStyle: ViewPropTypes.style,
  title: PropTypes.string,
  onPress: PropTypes.any,
  icon: PropTypes.object,
  leftIcon: PropTypes.object,
  rightIcon: PropTypes.object,
  iconRight: PropTypes.object,
  iconComponent: PropTypes.any,
  secondary: PropTypes.bool,
  secondary2: PropTypes.bool,
  secondary3: PropTypes.bool,
  primary1: PropTypes.bool,
  primary2: PropTypes.bool,
  backgroundColor: PropTypes.string,
  color: PropTypes.string,
  fontSize: PropTypes.any,
  underlayColor: PropTypes.string,
  raised: PropTypes.bool,
  textStyle: NativeText.propTypes.style,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  activityIndicatorStyle: ViewPropTypes.style,
  loadingRight: PropTypes.bool,
  Component: PropTypes.any,
  borderRadius: PropTypes.number,
  large: PropTypes.bool,
  fontWeight: PropTypes.string,
  disabledStyle: ViewPropTypes.style,
  fontFamily: PropTypes.string,
  containerViewStyle: ViewPropTypes.style,
  rounded: PropTypes.bool,
  outline: PropTypes.bool,
  transparent: PropTypes.bool,
  allowFontScaling: PropTypes.bool,
  textNumberOfLines: PropTypes.number,
  textEllipsizeMode: PropTypes.string,
};

const stylesObject = {
  container: {
    backgroundColor: 'transparent',
    marginLeft: 15,
    marginRight: 15,
  },
  button: {
    padding: 19,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  text: {
    color: 'white',
    fontSize: normalize(16),
  },
  icon: {
    marginRight: 10,
  },
  iconRight: {
    marginLeft: 10,
  },
  small: {
    padding: 12,
  },
  smallFont: {
    fontSize: normalize(14),
  },
  activityIndicatorStyle: {
    marginHorizontal: 10,
    height: 0,
  },
  raised: {
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .4)',
        shadowOffset: { height: 1, width: 1 },
        shadowOpacity: 1,
        shadowRadius: 1,
      },
      android: {
        backgroundColor: '#fff',
        elevation: 2,
      },
    }),
  },
};

const styles = StyleSheet.create(stylesObject);

export default Button;
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import {
  TouchableNativeFeedback,
  TouchableHighlight,
  StyleSheet,
  View,
  Platform,
  ActivityIndicator,
  Text as NativeText,
} from 'react-native';
import colors from '../config/colors';
import Text from '../text/Text';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import getIconType from '../helpers/getIconType';
import normalize from '../helpers/normalizeText';

const log = () => {
  console.log('please attach method to this component'); //eslint-disable-line no-console
};

const Button = props => {
  const {
    disabled,
    loading,
    loadingRight,
    activityIndicatorStyle,
    buttonStyle,
    borderRadius,
    title,
    onPress,
    icon,
    iconComponent,
    secondary,
    secondary2,
    secondary3,
    primary1,
    primary2,
    backgroundColor,
    color,
    fontSize,
    underlayColor,
    raised,
    textStyle,
    large,
    iconRight,
    fontWeight,
    disabledStyle,
    fontFamily,
    containerViewStyle,
    ...attributes
  } = props;
  let { Component } = props;

  let iconElement;
  if (icon) {
    let Icon;
    if (iconComponent) {
      Icon = iconComponent;
    } else if (!icon.type) {
      Icon = MaterialIcon;
    } else {
      Icon = getIconType(icon.type);
    }
    iconElement = (
      <Icon
        {...icon}
        color={icon.color || 'white'}
        size={icon.size || (large ? 26 : 18)}
        style={[
          iconRight ? styles.iconRight : styles.icon,
          icon.style && icon.style,
        ]}
      />
    );
  }
  let loadingElement;
  if (loading) {
    loadingElement = (
      <ActivityIndicator
        animating={true}
        style={[styles.activityIndicatorStyle, activityIndicatorStyle]}
        color={color || 'white'}
        size={(large && 'large') || 'small'}
      />
    );
  }
  if (!Component && Platform.OS === 'ios') {
    Component = TouchableHighlight;
  }
  if (!Component && Platform.OS === 'android') {
    Component = TouchableNativeFeedback;
  }
  if (!Component) {
    Component = TouchableHighlight;
  }

  if (borderRadius && !attributes.background) {
    attributes.background = TouchableNativeFeedback.Ripple(
      'ThemeAttrAndroid',
      true
    );
  }

  return (
    <View
      style={[styles.container, raised && styles.raised, containerViewStyle]}
    >
      <Component
        underlayColor={underlayColor || 'transparent'}
        onPress={onPress || log}
        disabled={disabled || false}
        {...attributes}
      >
        <View
          style={[
            styles.button,
            secondary && { backgroundColor: colors.secondary },
            secondary2 && { backgroundColor: colors.secondary2 },
            secondary3 && { backgroundColor: colors.secondary3 },
            primary1 && { backgroundColor: colors.primary1 },
            primary2 && { backgroundColor: colors.primary2 },
            backgroundColor && { backgroundColor: backgroundColor },
            borderRadius && { borderRadius },
            !large && styles.small,
            buttonStyle && buttonStyle,
            disabled && { backgroundColor: colors.disabled },
            disabled && disabledStyle && disabledStyle,
          ]}
        >
          {icon && !iconRight && iconElement}
          {loading && !loadingRight && loadingElement}
          <Text
            style={[
              styles.text,
              color && { color },
              !large && styles.smallFont,
              fontSize && { fontSize },
              textStyle && textStyle,
              fontWeight && { fontWeight },
              fontFamily && { fontFamily },
            ]}
          >
            {title}
          </Text>
          {loading && loadingRight && loadingElement}
          {icon && iconRight && iconElement}
        </View>
      </Component>
    </View>
  );
};

Button.propTypes = {
  buttonStyle: View.propTypes.style,
  title: PropTypes.string,
  onPress: PropTypes.any,
  icon: PropTypes.object,
  iconComponent: PropTypes.any,
  secondary: PropTypes.bool,
  secondary2: PropTypes.bool,
  secondary3: PropTypes.bool,
  primary1: PropTypes.bool,
  primary2: PropTypes.bool,
  backgroundColor: PropTypes.string,
  color: PropTypes.string,
  fontSize: PropTypes.any,
  underlayColor: PropTypes.string,
  raised: PropTypes.bool,
  textStyle: NativeText.propTypes.style,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  activityIndicatorStyle: View.propTypes.style,
  loadingRight: PropTypes.bool,
  Component: PropTypes.any,
  borderRadius: PropTypes.number,
  large: PropTypes.bool,
  iconRight: PropTypes.bool,
  fontWeight: PropTypes.string,
  disabledStyle: View.propTypes.style,
  fontFamily: PropTypes.string,
};

const styles = StyleSheet.create({
  container: {
    marginLeft: 15,
    marginRight: 15,
  },
  button: {
    padding: 19,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  text: {
    color: 'white',
    fontSize: normalize(16),
  },
  icon: {
    marginRight: 10,
  },
  iconRight: {
    marginLeft: 10,
  },
  small: {
    padding: 12,
  },
  smallFont: {
    fontSize: normalize(14),
  },
  activityIndicatorStyle: {
    marginHorizontal: 10,
    height: 0,
  },
  raised: {
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .4)',
        shadowOffset: { height: 1, width: 1 },
        shadowOpacity: 1,
        shadowRadius: 1,
      },
      android: {
        elevation: 2,
      },
    }),
  },
});

export default Button;
<commit_msg>Set ripple as Android only<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import {
  TouchableNativeFeedback,
  TouchableHighlight,
  StyleSheet,
  View,
  Platform,
  ActivityIndicator,
  Text as NativeText,
} from 'react-native';
import colors from '../config/colors';
import Text from '../text/Text';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import getIconType from '../helpers/getIconType';
import normalize from '../helpers/normalizeText';

const log = () => {
  console.log('please attach method to this component'); //eslint-disable-line no-console
};

const Button = props => {
  const {
    disabled,
    loading,
    loadingRight,
    activityIndicatorStyle,
    buttonStyle,
    borderRadius,
    title,
    onPress,
    icon,
    iconComponent,
    secondary,
    secondary2,
    secondary3,
    primary1,
    primary2,
    backgroundColor,
    color,
    fontSize,
    underlayColor,
    raised,
    textStyle,
    large,
    iconRight,
    fontWeight,
    disabledStyle,
    fontFamily,
    containerViewStyle,
    ...attributes
  } = props;
  let { Component } = props;

  let iconElement;
  if (icon) {
    let Icon;
    if (iconComponent) {
      Icon = iconComponent;
    } else if (!icon.type) {
      Icon = MaterialIcon;
    } else {
      Icon = getIconType(icon.type);
    }
    iconElement = (
      <Icon
        {...icon}
        color={icon.color || 'white'}
        size={icon.size || (large ? 26 : 18)}
        style={[
          iconRight ? styles.iconRight : styles.icon,
          icon.style && icon.style,
        ]}
      />
    );
  }
  let loadingElement;
  if (loading) {
    loadingElement = (
      <ActivityIndicator
        animating={true}
        style={[styles.activityIndicatorStyle, activityIndicatorStyle]}
        color={color || 'white'}
        size={(large && 'large') || 'small'}
      />
    );
  }
  if (!Component && Platform.OS === 'ios') {
    Component = TouchableHighlight;
  }
  if (!Component && Platform.OS === 'android') {
    Component = TouchableNativeFeedback;
  }
  if (!Component) {
    Component = TouchableHighlight;
  }

  if (Platform.OS === 'android' && (borderRadius && !attributes.background)) {
    attributes.background = TouchableNativeFeedback.Ripple(
      'ThemeAttrAndroid',
      true
    );
  }

  return (
    <View
      style={[styles.container, raised && styles.raised, containerViewStyle]}
    >
      <Component
        underlayColor={underlayColor || 'transparent'}
        onPress={onPress || log}
        disabled={disabled || false}
        {...attributes}
      >
        <View
          style={[
            styles.button,
            secondary && { backgroundColor: colors.secondary },
            secondary2 && { backgroundColor: colors.secondary2 },
            secondary3 && { backgroundColor: colors.secondary3 },
            primary1 && { backgroundColor: colors.primary1 },
            primary2 && { backgroundColor: colors.primary2 },
            backgroundColor && { backgroundColor: backgroundColor },
            borderRadius && { borderRadius },
            !large && styles.small,
            buttonStyle && buttonStyle,
            disabled && { backgroundColor: colors.disabled },
            disabled && disabledStyle && disabledStyle,
          ]}
        >
          {icon && !iconRight && iconElement}
          {loading && !loadingRight && loadingElement}
          <Text
            style={[
              styles.text,
              color && { color },
              !large && styles.smallFont,
              fontSize && { fontSize },
              textStyle && textStyle,
              fontWeight && { fontWeight },
              fontFamily && { fontFamily },
            ]}
          >
            {title}
          </Text>
          {loading && loadingRight && loadingElement}
          {icon && iconRight && iconElement}
        </View>
      </Component>
    </View>
  );
};

Button.propTypes = {
  buttonStyle: View.propTypes.style,
  title: PropTypes.string,
  onPress: PropTypes.any,
  icon: PropTypes.object,
  iconComponent: PropTypes.any,
  secondary: PropTypes.bool,
  secondary2: PropTypes.bool,
  secondary3: PropTypes.bool,
  primary1: PropTypes.bool,
  primary2: PropTypes.bool,
  backgroundColor: PropTypes.string,
  color: PropTypes.string,
  fontSize: PropTypes.any,
  underlayColor: PropTypes.string,
  raised: PropTypes.bool,
  textStyle: NativeText.propTypes.style,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  activityIndicatorStyle: View.propTypes.style,
  loadingRight: PropTypes.bool,
  Component: PropTypes.any,
  borderRadius: PropTypes.number,
  large: PropTypes.bool,
  iconRight: PropTypes.bool,
  fontWeight: PropTypes.string,
  disabledStyle: View.propTypes.style,
  fontFamily: PropTypes.string,
};

const styles = StyleSheet.create({
  container: {
    marginLeft: 15,
    marginRight: 15,
  },
  button: {
    padding: 19,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  text: {
    color: 'white',
    fontSize: normalize(16),
  },
  icon: {
    marginRight: 10,
  },
  iconRight: {
    marginLeft: 10,
  },
  small: {
    padding: 12,
  },
  smallFont: {
    fontSize: normalize(14),
  },
  activityIndicatorStyle: {
    marginHorizontal: 10,
    height: 0,
  },
  raised: {
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .4)',
        shadowOffset: { height: 1, width: 1 },
        shadowOpacity: 1,
        shadowRadius: 1,
      },
      android: {
        elevation: 2,
      },
    }),
  },
});

export default Button;
<|endoftext|>


<commit_before>define(function(require, exports, module) {
  "use strict";

  var cc = require("./cc");
  var fn = require("./fn");
  var utils  = require("./utils");
  var extend = require("../common/extend");
  var slice = [].slice;

  var BufferSource = (function() {
    var bufSrcId = 0;
    var cache = {};
    function BufferSource(source, id) {
      this.bufSrcId = bufSrcId++;

      // binary data format
      //  0 command
      //  1
      //  2 bufSrcId
      //  3
      //  4 (not use)
      //  5
      //  6 channels
      //  7
      //  8 sampleRate
      //  9
      // 10
      // 11
      // 12 numFrames
      // 13
      // 14
      // 15
      // 16.. samples

      var uint8 = new Uint8Array(C.BUFSRC_HEADER_SIZE + source.samples.length * 4);
      var int16 = new Uint16Array(uint8.buffer);
      var int32 = new Uint32Array(uint8.buffer);
      var f32   = new Float32Array(uint8.buffer);
      int16[0] = C.BINARY_CMD_SET_BUFSRC;
      int16[1] = this.bufSrcId;
      int16[3] = source.numChannels;
      int32[2] = source.sampleRate;
      int32[3] = source.numFrames;
      f32.set(source.samples, 4);
      cc.lang.sendToServer(uint8);

      if (id) {
        cache[id] = this;
      }
    }
    BufferSource.prototype.bind = function(buffer, startFrame, numFrames) {
      cc.lang.pushToTimeline([
        "/b_bind", buffer.bufnum, this.bufSrcId, startFrame, numFrames
      ]);
    };
    BufferSource.get = function(id) {
      return cache[id];
    };
    BufferSource.reset = function() {
      cache = {};
    };
    return BufferSource;
  })();

  var Buffer = (function() {
    var bufnum = 0;
    function Buffer(frames, channels) {
      this.klassName = "Buffer";

      this.bufnum     = bufnum++;
      this.frames     = frames  |0;
      this.channels   = channels|0;

      cc.lang.pushToTimeline([
        "/b_new", this.bufnum, this.frames, this.channels
      ]);
    }
    extend(Buffer, cc.Object);

    Buffer.prototype.free = function() {
      cc.lang.pushToTimeline([
        "/b_free", this.bufnum
      ]);
      return this;
    };

    Buffer.prototype.zero = function() {
      cc.lang.pushToTimeline([
        "/b_zero", this.bufnum
      ]);
      return this;
    };

    Buffer.prototype.set = function() {
      var args = slice.call(arguments);
      if (args.length) {
        cc.lang.pushToTimeline([
          "/b_set", this.bufnum, args
        ]);
      }
      return this;
    };
    Buffer.prototype.setn = Buffer.prototype.set;

    var calcFlag = function(normalize, asWavetable, clearFirst) {
      return (normalize ? 1 : 0) + (asWavetable ? 2 : 0) + (clearFirst ? 4 : 0);
    };

    Buffer.prototype.sine1 = fn(function(amps, normalize, asWavetable, clearFirst) {
      amps = utils.asArray(amps);
      var flags = calcFlag(normalize, asWavetable, clearFirst);
      cc.lang.pushToTimeline(
        ["/b_gen", this.bufnum, "sine1", flags].concat(amps)
      );
      return this;
    }).defaults("amps=[],normalize=true,asWavetable=true,clearFirst=true").build();

    Buffer.prototype.sine2 = fn(function(freqs, amps, normalize, asWavetable, clearFirst) {
      freqs = utils.asArray(freqs);
      amps  = utils.asArray(amps);
      var flags = calcFlag(normalize, asWavetable, clearFirst);
      var len = Math.max(freqs.length, amps.length) * 2;
      cc.lang.pushToTimeline(
        ["/b_gen", this.bufnum, "sine2", flags].concat(utils.lace([freqs, amps], len))
      );
      return this;
    }).defaults("freqs=[],amps=[],normalize=true,asWavetable=true,clearFirst=true").build();

    Buffer.prototype.sine3 = fn(function(freqs, amps, phases, normalize, asWavetable, clearFirst) {
      freqs  = utils.asArray(freqs);
      amps   = utils.asArray(amps);
      phases = utils.asArray(phases);
      var flags = calcFlag(normalize, asWavetable, clearFirst);
      var len = Math.max(freqs.length, amps.length, phases.length) * 3;
      cc.lang.pushToTimeline(
        ["/b_gen", this.bufnum, "sine3", flags].concat(utils.lace([freqs, amps, phases], len))
      );
      return this;
    }).defaults("freqs=[],amps=[],phases=[],normalize=true,asWavetable=true,clearFirst=true").build();

    Buffer.prototype.cheby = fn(function(amplitudes, normalize, asWavetable, clearFirst) {
      amplitudes = utils.asArray(amplitudes);
      var flags = calcFlag(normalize, asWavetable, clearFirst);
      cc.lang.pushToTimeline(
        ["/b_gen", this.bufnum, "cheby", flags].concat(amplitudes)
      );
      return this;
    }).defaults("amplitudes=[],normalize=true,asWavetable=true,clearFirst=true").build();

    Buffer.prototype.asUGenInput = function() {
      return this.bufnum;
    };

    return Buffer;
  })();

  cc.global.Buffer = fn(function(numFrames, numChannels, source) {
    if (Array.isArray(numFrames)) {
      numFrames = new Float32Array(numFrames);
    }
    if (numFrames instanceof Float32Array) {
      source = {
        sampleRate : cc.lang.sampleRate,
        numChannels: 1,
        numFrames  : numFrames.length,
        samples    : numFrames
      };
      numFrames   = source.numFrames;
      numChannels = source.numChannels;
    }
    var buffer = new Buffer(numFrames, numChannels);
    if (source) {
      new BufferSource(source).bind(buffer, 0, -1);
    }
    return buffer;
  }).defaults("numFrames=0,numChannels=1,source").build();

  cc.global.Buffer.read = fn(function(path, startFrame, numFrames) {
    if (typeof path !== "string") {
      throw new TypeError("Buffer.Read: path should be a string.");
    }
    var bufSrc = BufferSource.get(path);
    var buffer = new Buffer();
    if (bufSrc) {
      bufSrc.bind(buffer, startFrame, numFrames);
    } else {
      cc.lang.requestBuffer(path, function(result) {
        if (result) {
          new BufferSource(result, path).bind(buffer, startFrame, numFrames);
        }
      });
    }
    return buffer;
  }).defaults("path,startFrame=0,numFrames=-1").build();

  cc.instanceOfBuffer = function(obj) {
    return obj instanceof Buffer;
  };

  cc.resetBuffer = function() {
    BufferSource.reset();
  };

  module.exports = {
    BufferSource: BufferSource,
    Buffer      : Buffer
  };

});
<commit_msg>Added Buffer#asString<commit_after>define(function(require, exports, module) {
  "use strict";

  var cc = require("./cc");
  var fn = require("./fn");
  var utils  = require("./utils");
  var extend = require("../common/extend");
  var slice = [].slice;

  var BufferSource = (function() {
    var bufSrcId = 0;
    var cache = {};
    function BufferSource(source, id) {
      this.bufSrcId = bufSrcId++;

      // binary data format
      //  0 command
      //  1
      //  2 bufSrcId
      //  3
      //  4 (not use)
      //  5
      //  6 channels
      //  7
      //  8 sampleRate
      //  9
      // 10
      // 11
      // 12 numFrames
      // 13
      // 14
      // 15
      // 16.. samples

      var uint8 = new Uint8Array(C.BUFSRC_HEADER_SIZE + source.samples.length * 4);
      var int16 = new Uint16Array(uint8.buffer);
      var int32 = new Uint32Array(uint8.buffer);
      var f32   = new Float32Array(uint8.buffer);
      int16[0] = C.BINARY_CMD_SET_BUFSRC;
      int16[1] = this.bufSrcId;
      int16[3] = source.numChannels;
      int32[2] = source.sampleRate;
      int32[3] = source.numFrames;
      f32.set(source.samples, 4);
      cc.lang.sendToServer(uint8);

      if (id) {
        cache[id] = this;
      }
    }
    BufferSource.prototype.bind = function(buffer, startFrame, numFrames) {
      cc.lang.pushToTimeline([
        "/b_bind", buffer.bufnum, this.bufSrcId, startFrame, numFrames
      ]);
    };
    BufferSource.get = function(id) {
      return cache[id];
    };
    BufferSource.reset = function() {
      cache = {};
    };
    return BufferSource;
  })();

  var Buffer = (function() {
    var bufnum = 0;
    function Buffer(frames, channels) {
      this.klassName = "Buffer";

      this.bufnum     = bufnum++;
      this.frames     = frames  |0;
      this.channels   = channels|0;
      this.sampleRate = cc.lang.sampleRate;
      this.path       = null;

      cc.lang.pushToTimeline([
        "/b_new", this.bufnum, this.frames, this.channels
      ]);
    }
    extend(Buffer, cc.Object);

    Buffer.prototype.free = function() {
      cc.lang.pushToTimeline([
        "/b_free", this.bufnum
      ]);
      return this;
    };

    Buffer.prototype.zero = function() {
      cc.lang.pushToTimeline([
        "/b_zero", this.bufnum
      ]);
      return this;
    };

    Buffer.prototype.set = function() {
      var args = slice.call(arguments);
      if (args.length) {
        cc.lang.pushToTimeline([
          "/b_set", this.bufnum, args
        ]);
      }
      return this;
    };
    Buffer.prototype.setn = Buffer.prototype.set;

    var calcFlag = function(normalize, asWavetable, clearFirst) {
      return (normalize ? 1 : 0) + (asWavetable ? 2 : 0) + (clearFirst ? 4 : 0);
    };

    Buffer.prototype.sine1 = fn(function(amps, normalize, asWavetable, clearFirst) {
      amps = utils.asArray(amps);
      var flags = calcFlag(normalize, asWavetable, clearFirst);
      cc.lang.pushToTimeline(
        ["/b_gen", this.bufnum, "sine1", flags].concat(amps)
      );
      return this;
    }).defaults("amps=[],normalize=true,asWavetable=true,clearFirst=true").build();

    Buffer.prototype.sine2 = fn(function(freqs, amps, normalize, asWavetable, clearFirst) {
      freqs = utils.asArray(freqs);
      amps  = utils.asArray(amps);
      var flags = calcFlag(normalize, asWavetable, clearFirst);
      var len = Math.max(freqs.length, amps.length) * 2;
      cc.lang.pushToTimeline(
        ["/b_gen", this.bufnum, "sine2", flags].concat(utils.lace([freqs, amps], len))
      );
      return this;
    }).defaults("freqs=[],amps=[],normalize=true,asWavetable=true,clearFirst=true").build();

    Buffer.prototype.sine3 = fn(function(freqs, amps, phases, normalize, asWavetable, clearFirst) {
      freqs  = utils.asArray(freqs);
      amps   = utils.asArray(amps);
      phases = utils.asArray(phases);
      var flags = calcFlag(normalize, asWavetable, clearFirst);
      var len = Math.max(freqs.length, amps.length, phases.length) * 3;
      cc.lang.pushToTimeline(
        ["/b_gen", this.bufnum, "sine3", flags].concat(utils.lace([freqs, amps, phases], len))
      );
      return this;
    }).defaults("freqs=[],amps=[],phases=[],normalize=true,asWavetable=true,clearFirst=true").build();

    Buffer.prototype.cheby = fn(function(amplitudes, normalize, asWavetable, clearFirst) {
      amplitudes = utils.asArray(amplitudes);
      var flags = calcFlag(normalize, asWavetable, clearFirst);
      cc.lang.pushToTimeline(
        ["/b_gen", this.bufnum, "cheby", flags].concat(amplitudes)
      );
      return this;
    }).defaults("amplitudes=[],normalize=true,asWavetable=true,clearFirst=true").build();

    Buffer.prototype.asUGenInput = function() {
      return this.bufnum;
    };

    Buffer.prototype.asString = function() {
      return "Buffer(" + this.bufnum + ", " + this.frames + ", " + this.channels + ", " + this.sampleRate + ", " + this.path + ")";
    };

    return Buffer;
  })();

  cc.global.Buffer = fn(function(numFrames, numChannels, source) {
    if (Array.isArray(numFrames)) {
      numFrames = new Float32Array(numFrames);
    }
    if (numFrames instanceof Float32Array) {
      source = {
        sampleRate : cc.lang.sampleRate,
        numChannels: 1,
        numFrames  : numFrames.length,
        samples    : numFrames
      };
      numFrames   = source.numFrames;
      numChannels = source.numChannels;
    }
    var buffer = new Buffer(numFrames, numChannels);
    if (source) {
      new BufferSource(source).bind(buffer, 0, -1);
    }
    return buffer;
  }).defaults("numFrames=0,numChannels=1,source").build();

  cc.global.Buffer.read = fn(function(path, startFrame, numFrames) {
    if (typeof path !== "string") {
      throw new TypeError("Buffer.Read: path should be a string.");
    }
    var bufSrc = BufferSource.get(path);
    var buffer = new Buffer();
    if (bufSrc) {
      bufSrc.bind(buffer, startFrame, numFrames);
    } else {
      cc.lang.requestBuffer(path, function(result) {
        if (result) {
          buffer.sampleRate = result.sampleRate;
          buffer.path       = path;
          new BufferSource(result, path).bind(buffer, startFrame, numFrames);
        }
      });
    }
    return buffer;
  }).defaults("path,startFrame=0,numFrames=-1").build();

  cc.instanceOfBuffer = function(obj) {
    return obj instanceof Buffer;
  };

  cc.resetBuffer = function() {
    BufferSource.reset();
  };

  module.exports = {
    BufferSource: BufferSource,
    Buffer      : Buffer
  };

});
<|endoftext|>


<commit_before>/**
 * @fileOverview Bar Chart
 */
import React, { PropTypes, Component } from 'react';
import Layer from '../container/Layer';
import Tooltip from '../component/Tooltip';
import Rectangle from '../shape/Rectangle';
import { getPercentValue, getBandSizeOfScale, getAnyElementOfObject } from '../util/DataUtils';
import { getPresentationAttributes, findChildByType, findAllByType,
  validateWidthHeight, filterEventAttributes } from '../util/ReactUtils';
import generateCategoricalChart from './generateCategoricalChart';
import Cell from '../component/Cell';
import Bar from '../cartesian/Bar';
import pureRender from '../util/PureRender';
import { getTicksOfAxis, getStackedDataOfItem } from '../util/CartesianUtils';
import AnimationDecorator from '../util/AnimationDecorator';

@AnimationDecorator
@pureRender
class BarChart extends Component {

  static displayName = 'BarChart';

  static propTypes = {
    layout: PropTypes.oneOf(['horizontal', 'vertical']),
    dataStartIndex: PropTypes.number,
    dataEndIndex: PropTypes.number,
    data: PropTypes.array,
    isTooltipActive: PropTypes.bool,
    activeTooltipIndex: PropTypes.number,
    xAxisMap: PropTypes.object,
    yAxisMap: PropTypes.object,
    offset: PropTypes.object,
    graphicalItems: PropTypes.array,
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node,
    ]),
    stackGroups: PropTypes.object,
    barCategoryGap: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    barGap: PropTypes.number,
    barSize: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    // used internally
    isComposed: PropTypes.bool,
    animationId: PropTypes.number,
  };

  static defaultProps = {
    barCategoryGap: '10%',
    barGap: 4,
  };

  /**
   * Compose the data of each group
   * @param  {Object} item        An instance of Bar
   * @param  {Array}  barPosition The offset and size of each bar
   * @param  {Object} xAxis       The configuration of x-axis
   * @param  {Object} yAxis       The configuration of y-axis
   * @param  {Object} offset      The offset of main part in the svg element
   * @param  {Array} stackedData  The stacked data of a bar item
   * @return {Array} Composed data
   */
  getComposedData(item, barPosition, xAxis, yAxis, offset, stackedData) {
    const { layout, dataStartIndex, dataEndIndex } = this.props;
    const { dataKey, children, minPointSize } = item.props;
    const pos = barPosition[dataKey];
    const data = this.props.data.slice(dataStartIndex, dataEndIndex + 1);
    const xTicks = getTicksOfAxis(xAxis);
    const yTicks = getTicksOfAxis(yAxis);
    const baseValue = this.getBaseValue(xAxis, yAxis);
    const hasStack = stackedData && stackedData.length;
    const cells = findAllByType(children, Cell);

    return data.map((entry, index) => {
      const value = stackedData ? stackedData[dataStartIndex + index] : [baseValue, entry[dataKey]];
      let x;
      let y;
      let width;
      let height;

      if (layout === 'horizontal') {
        x = xTicks[index].coordinate + pos.offset;
        y = yAxis.scale(xAxis.orientation === 'top' ? value[0] : value[1]);
        width = pos.size;
        height = xAxis.orientation === 'top' ?
                yAxis.scale(value[1]) - yAxis.scale(value[0]) :
                yAxis.scale(value[0]) - yAxis.scale(value[1]);
        if (Math.abs(minPointSize) > 0 && Math.abs(height) < Math.abs(minPointSize)) {
          const delta = Math.sign(height || minPointSize) * (Math.abs(minPointSize) - Math.abs(height));

          y -= delta;
          height += delta;
        }
      } else {
        x = xAxis.scale(yAxis.orientation === 'left' ? value[0] : value[1]);
        y = yTicks[index].coordinate + pos.offset;
        width = yAxis.orientation === 'left' ?
                xAxis.scale(value[1]) - xAxis.scale(value[0]) :
                xAxis.scale(value[0]) - xAxis.scale(value[1]);
        height = pos.size;

        if (Math.abs(minPointSize) > 0 && Math.abs(width) < Math.abs(minPointSize)) {
          const delta = Math.sign(width || minPointSize) * (Math.abs(minPointSize) - Math.abs(width));
          width += delta;
        }
      }

      return {
        ...entry,
        x, y, width, height, value: stackedData ? value : value[1],
        ...(cells && cells[index] && cells[index].props),
      };
    });
  }

  getBaseValue(xAxis, yAxis) {
    const { layout } = this.props;
    const numberAxis = layout === 'horizontal' ? yAxis : xAxis;
    const domain = numberAxis.scale.domain();

    if (numberAxis.type === 'number') {
      return Math.max(Math.min(domain[0], domain[1]), 0);
    }

    return domain[0];
  }

  /**
   * Calculate the size of each bar and the gap between two bars
   * @param  {Number}   bandSize  The size of each category
   * @param  {sizeList} sizeList  The size of all groups
   * @return {Number} The size of each bar and the gap between two bars
   */
  getBarPosition(bandSize, sizeList) {
    const { barGap, barCategoryGap } = this.props;
    const len = sizeList.length;
    let result;

    // whether or not is barSize setted by user
    if (sizeList[0].barSize === +sizeList[0].barSize) {
      let sum = sizeList.reduce((res, entry) => (res + entry.barSize || 0), 0);
      sum += (len - 1) * barGap;
      const offset = ((bandSize - sum) / 2) >> 0;
      let prev = { offset: offset - barGap, size: 0 };

      result = sizeList.reduce((res, entry) => {
        const newRes = {
          ...res,
          [entry.dataKey]: {
            offset: prev.offset + prev.size + barGap,
            size: entry.barSize,
          },
        };

        prev = newRes[entry.dataKey];

        if (entry.stackList && entry.stackList.length) {
          entry.stackList.forEach(key => {
            newRes[key] = newRes[entry.dataKey];
          });
        }
        return newRes;
      }, {});
    } else {
      const offset = getPercentValue(barCategoryGap, bandSize, 0, true);
      const size = (bandSize - 2 * offset - (len - 1) * barGap) / len >> 0;

      result = sizeList.reduce((res, entry, i) => {
        const newRes = {
          ...res,
          [entry.dataKey]: {
            offset: offset + (size + barGap) * i,
            size,
          },
        };

        if (entry.stackList && entry.stackList.length) {
          entry.stackList.forEach(key => {
            newRes[key] = newRes[entry.dataKey];
          });
        }
        return newRes;
      }, {});
    }

    return result;
  }

  /**
   * Calculate the size of all groups
   * @param  {Object} stackGroups The items grouped by axisId and stackId
   * @return {Object} The size of all groups
   */
  getSizeList(stackGroups) {
    const { layout, barSize } = this.props;
    const result = {};
    const numericAxisIds = Object.keys(stackGroups);

    for (let i = 0, len = numericAxisIds.length; i < len; i++) {
      const sgs = stackGroups[numericAxisIds[i]].stackGroups;
      const stackIds = Object.keys(sgs);

      for (let j = 0, sLen = stackIds.length; j < sLen; j++) {
        const { items, numericAxisId, cateAxisId } = sgs[stackIds[j]];

        const barItems = items.filter(item => item.type.displayName === 'Bar');

        if (barItems && barItems.length) {
          const { dataKey } = barItems[0].props;
          const cateId = barItems[0].props[cateAxisId];

          if (!result[cateId]) {
            result[cateId] = [];
          }

          result[cateId].push({
            dataKey,
            stackList: barItems.slice(1).map(item => item.props.dataKey),
            barSize: barItems[0].props.barSize || barSize,
          });
        }
      }
    }

    return result;
  }

  renderCursor(xAxisMap, yAxisMap, offset) {
    const { children, isTooltipActive, layout, activeTooltipIndex } = this.props;
    const tooltipItem = findChildByType(children, Tooltip);

    if (!tooltipItem || !tooltipItem.props.cursor || !isTooltipActive ||
      activeTooltipIndex < 0) { return null; }

    const axisMap = layout === 'horizontal' ? xAxisMap : yAxisMap;
    const axis = getAnyElementOfObject(axisMap);
    const ticks = getTicksOfAxis(axis);

    if (!ticks || !ticks[activeTooltipIndex]) { return null; }

    const start = ticks[activeTooltipIndex].coordinate;
    const bandSize = axis.scale.bandwidth();
    const cursorProps = {
      fill: '#f1f1f1',
      ...getPresentationAttributes(tooltipItem.props.cursor),
      x: layout === 'horizontal' ? start : offset.left + 0.5,
      y: layout === 'horizontal' ? offset.top + 0.5 : start,
      width: layout === 'horizontal' ? bandSize : offset.width - 1,
      height: layout === 'horizontal' ? offset.height - 1 : bandSize,
    };

    return React.isValidElement(tooltipItem.props.cursor) ?
      React.cloneElement(tooltipItem.props.cursor, cursorProps) :
      React.createElement(Rectangle, { ...cursorProps, className: 'recharts-bar-cursor' });
  }

  /**
   * Draw the main part of bar chart
   * @param  {Array} items     All the instance of Bar
   * @param  {Object} xAxisMap The configuration of all x-axis
   * @param  {Object} yAxisMap The configuration of all y-axis
   * @param  {Object} offset   The offset of main part in the svg element
   * @param  {Object} stackGroups The items grouped by axisId and stackId
   * @return {ReactComponent}  All the instances of Bar
   */
  renderItems(items, xAxisMap, yAxisMap, offset, stackGroups) {
    if (!items || !items.length) { return null; }

    const { layout } = this.props;
    const sizeList = this.getSizeList(stackGroups);
    const { animationId } = this.props;

    const barPositionMap = {};

    return items.map((child, i) => {
      const { xAxisId, yAxisId } = child.props;
      const numericAxisId = layout === 'horizontal' ? yAxisId : xAxisId;
      const cateAxisId = layout === 'horizontal' ? xAxisId : yAxisId;
      const cateAxis = layout === 'horizontal' ? xAxisMap[xAxisId] : yAxisMap[yAxisId];
      const bandSize = getBandSizeOfScale(cateAxis.scale);
      const barPosition = barPositionMap[cateAxisId] ||
        this.getBarPosition(bandSize, sizeList[cateAxisId]);
      const stackedData = stackGroups && stackGroups[numericAxisId] &&
        stackGroups[numericAxisId].hasStack &&
        getStackedDataOfItem(child, stackGroups[numericAxisId].stackGroups);

      return React.cloneElement(child, {
        key: `bar-${i}`,
        ...filterEventAttributes(this.props),
        layout,
        animationId,
        data: this.getComposedData(
          child, barPosition, xAxisMap[xAxisId], yAxisMap[yAxisId], offset, stackedData
        ),
      });
    }, this);
  }

  render() {
    const { isComposed, graphicalItems, xAxisMap, yAxisMap, offset, stackGroups } = this.props;

    return (
      <Layer className="recharts-bar-graphical">
        {!isComposed && this.renderCursor(xAxisMap, yAxisMap, offset)}
        {this.renderItems(graphicalItems, xAxisMap, yAxisMap, offset, stackGroups)}
      </Layer>
    );
  }
}

export default generateCategoricalChart(BarChart, Bar);
export { BarChart };
<commit_msg>linter fix<commit_after>/**
 * @fileOverview Bar Chart
 */
import React, { PropTypes, Component } from 'react';
import Layer from '../container/Layer';
import Tooltip from '../component/Tooltip';
import Rectangle from '../shape/Rectangle';
import { getPercentValue, getBandSizeOfScale, getAnyElementOfObject } from '../util/DataUtils';
import { getPresentationAttributes, findChildByType, findAllByType,
  validateWidthHeight, filterEventAttributes } from '../util/ReactUtils';
import generateCategoricalChart from './generateCategoricalChart';
import Cell from '../component/Cell';
import Bar from '../cartesian/Bar';
import pureRender from '../util/PureRender';
import { getTicksOfAxis, getStackedDataOfItem } from '../util/CartesianUtils';
import AnimationDecorator from '../util/AnimationDecorator';

@AnimationDecorator
@pureRender
class BarChart extends Component {

  static displayName = 'BarChart';

  static propTypes = {
    layout: PropTypes.oneOf(['horizontal', 'vertical']),
    dataStartIndex: PropTypes.number,
    dataEndIndex: PropTypes.number,
    data: PropTypes.array,
    isTooltipActive: PropTypes.bool,
    activeTooltipIndex: PropTypes.number,
    xAxisMap: PropTypes.object,
    yAxisMap: PropTypes.object,
    offset: PropTypes.object,
    graphicalItems: PropTypes.array,
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node,
    ]),
    stackGroups: PropTypes.object,
    barCategoryGap: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    barGap: PropTypes.number,
    barSize: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    // used internally
    isComposed: PropTypes.bool,
    animationId: PropTypes.number,
  };

  static defaultProps = {
    barCategoryGap: '10%',
    barGap: 4,
  };

  /**
   * Compose the data of each group
   * @param  {Object} item        An instance of Bar
   * @param  {Array}  barPosition The offset and size of each bar
   * @param  {Object} xAxis       The configuration of x-axis
   * @param  {Object} yAxis       The configuration of y-axis
   * @param  {Object} offset      The offset of main part in the svg element
   * @param  {Array} stackedData  The stacked data of a bar item
   * @return {Array} Composed data
   */
  getComposedData(item, barPosition, xAxis, yAxis, offset, stackedData) {
    const { layout, dataStartIndex, dataEndIndex } = this.props;
    const { dataKey, children, minPointSize } = item.props;
    const pos = barPosition[dataKey];
    const data = this.props.data.slice(dataStartIndex, dataEndIndex + 1);
    const xTicks = getTicksOfAxis(xAxis);
    const yTicks = getTicksOfAxis(yAxis);
    const baseValue = this.getBaseValue(xAxis, yAxis);
    const hasStack = stackedData && stackedData.length;
    const cells = findAllByType(children, Cell);

    return data.map((entry, index) => {
      const value = stackedData ? stackedData[dataStartIndex + index] : [baseValue, entry[dataKey]];
      let x;
      let y;
      let width;
      let height;

      if (layout === 'horizontal') {
        x = xTicks[index].coordinate + pos.offset;
        y = yAxis.scale(xAxis.orientation === 'top' ? value[0] : value[1]);
        width = pos.size;
        height = xAxis.orientation === 'top' ?
                yAxis.scale(value[1]) - yAxis.scale(value[0]) :
                yAxis.scale(value[0]) - yAxis.scale(value[1]);
        if (Math.abs(minPointSize) > 0 && Math.abs(height) < Math.abs(minPointSize)) {
          const delta = Math.sign(height || minPointSize) *
            (Math.abs(minPointSize) - Math.abs(height));

          y -= delta;
          height += delta;
        }
      } else {
        x = xAxis.scale(yAxis.orientation === 'left' ? value[0] : value[1]);
        y = yTicks[index].coordinate + pos.offset;
        width = yAxis.orientation === 'left' ?
                xAxis.scale(value[1]) - xAxis.scale(value[0]) :
                xAxis.scale(value[0]) - xAxis.scale(value[1]);
        height = pos.size;

        if (Math.abs(minPointSize) > 0 && Math.abs(width) < Math.abs(minPointSize)) {
          const delta = Math.sign(width || minPointSize) *
            (Math.abs(minPointSize) - Math.abs(width));
          width += delta;
        }
      }

      return {
        ...entry,
        x, y, width, height, value: stackedData ? value : value[1],
        ...(cells && cells[index] && cells[index].props),
      };
    });
  }

  getBaseValue(xAxis, yAxis) {
    const { layout } = this.props;
    const numberAxis = layout === 'horizontal' ? yAxis : xAxis;
    const domain = numberAxis.scale.domain();

    if (numberAxis.type === 'number') {
      return Math.max(Math.min(domain[0], domain[1]), 0);
    }

    return domain[0];
  }

  /**
   * Calculate the size of each bar and the gap between two bars
   * @param  {Number}   bandSize  The size of each category
   * @param  {sizeList} sizeList  The size of all groups
   * @return {Number} The size of each bar and the gap between two bars
   */
  getBarPosition(bandSize, sizeList) {
    const { barGap, barCategoryGap } = this.props;
    const len = sizeList.length;
    let result;

    // whether or not is barSize setted by user
    if (sizeList[0].barSize === +sizeList[0].barSize) {
      let sum = sizeList.reduce((res, entry) => (res + entry.barSize || 0), 0);
      sum += (len - 1) * barGap;
      const offset = ((bandSize - sum) / 2) >> 0;
      let prev = { offset: offset - barGap, size: 0 };

      result = sizeList.reduce((res, entry) => {
        const newRes = {
          ...res,
          [entry.dataKey]: {
            offset: prev.offset + prev.size + barGap,
            size: entry.barSize,
          },
        };

        prev = newRes[entry.dataKey];

        if (entry.stackList && entry.stackList.length) {
          entry.stackList.forEach(key => {
            newRes[key] = newRes[entry.dataKey];
          });
        }
        return newRes;
      }, {});
    } else {
      const offset = getPercentValue(barCategoryGap, bandSize, 0, true);
      const size = (bandSize - 2 * offset - (len - 1) * barGap) / len >> 0;

      result = sizeList.reduce((res, entry, i) => {
        const newRes = {
          ...res,
          [entry.dataKey]: {
            offset: offset + (size + barGap) * i,
            size,
          },
        };

        if (entry.stackList && entry.stackList.length) {
          entry.stackList.forEach(key => {
            newRes[key] = newRes[entry.dataKey];
          });
        }
        return newRes;
      }, {});
    }

    return result;
  }

  /**
   * Calculate the size of all groups
   * @param  {Object} stackGroups The items grouped by axisId and stackId
   * @return {Object} The size of all groups
   */
  getSizeList(stackGroups) {
    const { layout, barSize } = this.props;
    const result = {};
    const numericAxisIds = Object.keys(stackGroups);

    for (let i = 0, len = numericAxisIds.length; i < len; i++) {
      const sgs = stackGroups[numericAxisIds[i]].stackGroups;
      const stackIds = Object.keys(sgs);

      for (let j = 0, sLen = stackIds.length; j < sLen; j++) {
        const { items, numericAxisId, cateAxisId } = sgs[stackIds[j]];

        const barItems = items.filter(item => item.type.displayName === 'Bar');

        if (barItems && barItems.length) {
          const { dataKey } = barItems[0].props;
          const cateId = barItems[0].props[cateAxisId];

          if (!result[cateId]) {
            result[cateId] = [];
          }

          result[cateId].push({
            dataKey,
            stackList: barItems.slice(1).map(item => item.props.dataKey),
            barSize: barItems[0].props.barSize || barSize,
          });
        }
      }
    }

    return result;
  }

  renderCursor(xAxisMap, yAxisMap, offset) {
    const { children, isTooltipActive, layout, activeTooltipIndex } = this.props;
    const tooltipItem = findChildByType(children, Tooltip);

    if (!tooltipItem || !tooltipItem.props.cursor || !isTooltipActive ||
      activeTooltipIndex < 0) { return null; }

    const axisMap = layout === 'horizontal' ? xAxisMap : yAxisMap;
    const axis = getAnyElementOfObject(axisMap);
    const ticks = getTicksOfAxis(axis);

    if (!ticks || !ticks[activeTooltipIndex]) { return null; }

    const start = ticks[activeTooltipIndex].coordinate;
    const bandSize = axis.scale.bandwidth();
    const cursorProps = {
      fill: '#f1f1f1',
      ...getPresentationAttributes(tooltipItem.props.cursor),
      x: layout === 'horizontal' ? start : offset.left + 0.5,
      y: layout === 'horizontal' ? offset.top + 0.5 : start,
      width: layout === 'horizontal' ? bandSize : offset.width - 1,
      height: layout === 'horizontal' ? offset.height - 1 : bandSize,
    };

    return React.isValidElement(tooltipItem.props.cursor) ?
      React.cloneElement(tooltipItem.props.cursor, cursorProps) :
      React.createElement(Rectangle, { ...cursorProps, className: 'recharts-bar-cursor' });
  }

  /**
   * Draw the main part of bar chart
   * @param  {Array} items     All the instance of Bar
   * @param  {Object} xAxisMap The configuration of all x-axis
   * @param  {Object} yAxisMap The configuration of all y-axis
   * @param  {Object} offset   The offset of main part in the svg element
   * @param  {Object} stackGroups The items grouped by axisId and stackId
   * @return {ReactComponent}  All the instances of Bar
   */
  renderItems(items, xAxisMap, yAxisMap, offset, stackGroups) {
    if (!items || !items.length) { return null; }

    const { layout } = this.props;
    const sizeList = this.getSizeList(stackGroups);
    const { animationId } = this.props;

    const barPositionMap = {};

    return items.map((child, i) => {
      const { xAxisId, yAxisId } = child.props;
      const numericAxisId = layout === 'horizontal' ? yAxisId : xAxisId;
      const cateAxisId = layout === 'horizontal' ? xAxisId : yAxisId;
      const cateAxis = layout === 'horizontal' ? xAxisMap[xAxisId] : yAxisMap[yAxisId];
      const bandSize = getBandSizeOfScale(cateAxis.scale);
      const barPosition = barPositionMap[cateAxisId] ||
        this.getBarPosition(bandSize, sizeList[cateAxisId]);
      const stackedData = stackGroups && stackGroups[numericAxisId] &&
        stackGroups[numericAxisId].hasStack &&
        getStackedDataOfItem(child, stackGroups[numericAxisId].stackGroups);

      return React.cloneElement(child, {
        key: `bar-${i}`,
        ...filterEventAttributes(this.props),
        layout,
        animationId,
        data: this.getComposedData(
          child, barPosition, xAxisMap[xAxisId], yAxisMap[yAxisId], offset, stackedData
        ),
      });
    }, this);
  }

  render() {
    const { isComposed, graphicalItems, xAxisMap, yAxisMap, offset, stackGroups } = this.props;

    return (
      <Layer className="recharts-bar-graphical">
        {!isComposed && this.renderCursor(xAxisMap, yAxisMap, offset)}
        {this.renderItems(graphicalItems, xAxisMap, yAxisMap, offset, stackGroups)}
      </Layer>
    );
  }
}

export default generateCategoricalChart(BarChart, Bar);
export { BarChart };
<|endoftext|>


<commit_before>var ngColumn = function (config, $scope, grid, domUtilityService, $templateCache, $utils) {
    var self = this,
        colDef = config.colDef,
        delay = 500,
        clicks = 0,
        timer = null;
    self.colDef = config.colDef;
    self.width = colDef.width;
    self.groupIndex = 0;
    self.isGroupedBy = false;
    self.minWidth = !colDef.minWidth ? 50 : colDef.minWidth;
    self.maxWidth = !colDef.maxWidth ? 9000 : colDef.maxWidth;

    // TODO: Use the column's definition for enabling cell editing
    // self.enableCellEdit = config.enableCellEdit || colDef.enableCellEdit;
    self.enableCellEdit = colDef.enableCellEdit !== undefined ? colDef.enableCellEdit : (config.enableCellEdit || config.enableCellEditOnFocus);

    self.cellEditableCondition = colDef.cellEditableCondition || config.cellEditableCondition || 'true';

    self.headerRowHeight = config.headerRowHeight;

    // Use colDef.displayName as long as it's not undefined, otherwise default to the field name
    self.displayName = (colDef.displayName === undefined) ? colDef.field : colDef.displayName;

    self.index = config.index;
    self.isAggCol = config.isAggCol;
    self.cellClass = colDef.cellClass;
    self.sortPriority = undefined;
    self.cellFilter = colDef.cellFilter ? colDef.cellFilter : "";
    self.field = colDef.field;
    self.aggLabelFilter = colDef.aggLabelFilter || colDef.cellFilter;
    self.visible = $utils.isNullOrUndefined(colDef.visible) || colDef.visible;
    self.sortable = false;
    self.resizable = false;
    self.pinnable = false;
    self.pinned = (config.enablePinning && colDef.pinned);
    self.originalIndex = config.originalIndex == null ? self.index : config.originalIndex;
    self.groupable = $utils.isNullOrUndefined(colDef.groupable) || colDef.groupable;
    if (config.enableSort) {
        self.sortable = $utils.isNullOrUndefined(colDef.sortable) || colDef.sortable;
    }
    if (config.enableResize) {
        self.resizable = $utils.isNullOrUndefined(colDef.resizable) || colDef.resizable;
    }
    if (config.enablePinning) {
        self.pinnable = $utils.isNullOrUndefined(colDef.pinnable) || colDef.pinnable;
    }
    self.sortDirection = undefined;
    self.sortingAlgorithm = colDef.sortFn;
    self.headerClass = colDef.headerClass;
    self.cursor = self.sortable ? 'pointer' : 'default';
    self.headerCellTemplate = colDef.headerCellTemplate || $templateCache.get('headerCellTemplate.html');
    self.cellTemplate = colDef.cellTemplate || $templateCache.get('cellTemplate.html').replace(CUSTOM_FILTERS, self.cellFilter ? "|" + self.cellFilter : "");
    if(self.enableCellEdit) {
        self.cellEditTemplate = colDef.cellEditTemplate || $templateCache.get('cellEditTemplate.html');
        self.editableCellTemplate = colDef.editableCellTemplate || $templateCache.get('editableCellTemplate.html');
    }
    if (colDef.cellTemplate && !TEMPLATE_REGEXP.test(colDef.cellTemplate)) {
        self.cellTemplate = $templateCache.get(colDef.cellTemplate) || $.ajax({
            type: "GET",
            url: colDef.cellTemplate,
            async: false
        }).responseText;
    }
    if (self.enableCellEdit && colDef.editableCellTemplate && !TEMPLATE_REGEXP.test(colDef.editableCellTemplate)) {
        self.editableCellTemplate = $templateCache.get(colDef.editableCellTemplate) || $.ajax({
            type: "GET",
            url: colDef.editableCellTemplate,
            async: false
        }).responseText;
    }
    if (colDef.headerCellTemplate && !TEMPLATE_REGEXP.test(colDef.headerCellTemplate)) {
        self.headerCellTemplate = $templateCache.get(colDef.headerCellTemplate) || $.ajax({
            type: "GET",
            url: colDef.headerCellTemplate,
            async: false
        }).responseText;
    }
    self.colIndex = function () {
        var classes = self.pinned ? "pinned " : "";
        classes += "col" + self.index + " colt" + self.index;
        if (self.cellClass) {
            classes += " " + self.cellClass;
        }
        return classes;
    };
    self.groupedByClass = function() {
        return self.isGroupedBy ? "ngGroupedByIcon" : "ngGroupIcon";
    };
    self.toggleVisible = function() {
        self.visible = !self.visible;
    };
    self.showSortButtonUp = function() {
        return self.sortable ? self.sortDirection === DESC : self.sortable;
    };
    self.showSortButtonDown = function() {
        return self.sortable ? self.sortDirection === ASC : self.sortable;
    };
    self.noSortVisible = function() {
        return !self.sortDirection;
    };
    var gotUserSortDirection = false;
    self.sort = function(evt) {
        if (!self.sortable) {
            return true; // column sorting is disabled, do nothing
        }
        var dir;
        if(self.colDef.sortDirection && !gotUserSortDirection){
            dir = self.sortDirection === ASC ? ASC : DESC;
        } else {
            dir = self.sortDirection === ASC ? DESC : ASC;
        }
        self.sortDirection = dir;
        config.sortCallback(self, evt);
        return false;
    };
    self.gripClick = function() {
        clicks++; //count clicks
        if (clicks === 1) {
            timer = setTimeout(function() {
                //Here you can add a single click action.
                clicks = 0; //after action performed, reset counter
            }, delay);
        } else {
            clearTimeout(timer); //prevent single-click action
            config.resizeOnDataCallback(self); //perform double-click action
            clicks = 0; //after action performed, reset counter
        }
    };
    self.gripOnMouseDown = function(event) {
        $scope.isColumnResizing = true;
        if (event.ctrlKey && !self.pinned) {
            self.toggleVisible();
            domUtilityService.BuildStyles($scope, grid);
            return true;
        }
        event.target.parentElement.style.cursor = 'col-resize';
        self.startMousePosition = event.clientX;
        self.origWidth = self.width;
        $(document).mousemove(self.onMouseMove);
        $(document).mouseup(self.gripOnMouseUp);
        return false;
    };
    self.onMouseMove = function(event) {
        var diff = event.clientX - self.startMousePosition;
        var newWidth = diff + self.origWidth;
        self.width = (newWidth < self.minWidth ? self.minWidth : (newWidth > self.maxWidth ? self.maxWidth : newWidth));
        $scope.hasUserChangedGridColumnWidths = true;
        domUtilityService.BuildStyles($scope, grid);
        return false;
    };
    self.gripOnMouseUp = function (event) {
        $(document).off('mousemove', self.onMouseMove);
        $(document).off('mouseup', self.gripOnMouseUp);
        event.target.parentElement.style.cursor = 'default';
        domUtilityService.digest($scope);
        $scope.isColumnResizing = false;
        return false;
    };
    self.copy = function() {
        var ret = new ngColumn(config, $scope, grid, domUtilityService, $templateCache, $utils);
        ret.isClone = true;
        ret.orig = self;
        return ret;
    };
    self.setVars = function (fromCol) {
        self.orig = fromCol;
        self.width = fromCol.width;
        self.groupIndex = fromCol.groupIndex;
        self.isGroupedBy = fromCol.isGroupedBy;
        self.displayName = fromCol.displayName;
        self.index = fromCol.index;
        self.isAggCol = fromCol.isAggCol;
        self.cellClass = fromCol.cellClass;
        self.cellFilter = fromCol.cellFilter;
        self.field = fromCol.field;
        self.aggLabelFilter = fromCol.aggLabelFilter;
        self.visible = fromCol.visible;
        self.sortable = fromCol.sortable;
        self.resizable = fromCol.resizable;
        self.pinnable = fromCol.pinnable;
        self.pinned = fromCol.pinned;
        self.originalIndex = fromCol.originalIndex;
        self.sortDirection = fromCol.sortDirection;
        self.sortingAlgorithm = fromCol.sortingAlgorithm;
        self.headerClass = fromCol.headerClass;
        self.headerCellTemplate = fromCol.headerCellTemplate;
        self.cellTemplate = fromCol.cellTemplate;
        self.cellEditTemplate = fromCol.cellEditTemplate;
    };
};
<commit_msg>Update column.js<commit_after>var ngColumn = function (config, $scope, grid, domUtilityService, $templateCache, $utils) {
    var self = this,
        colDef = config.colDef,
        delay = 500,
        clicks = 0,
        timer = null;
    self.colDef = config.colDef;
    self.width = colDef.width;
    self.groupIndex = 0;
    self.isGroupedBy = false;
    self.minWidth = !colDef.minWidth ? 50 : colDef.minWidth;
    self.maxWidth = !colDef.maxWidth ? 9000 : colDef.maxWidth;

    // TODO: Use the column's definition for enabling cell editing
    // self.enableCellEdit = config.enableCellEdit || colDef.enableCellEdit;
    self.enableCellEdit = colDef.enableCellEdit !== undefined ? colDef.enableCellEdit : (config.enableCellEdit || config.enableCellEditOnFocus);

    self.cellEditableCondition = colDef.cellEditableCondition || config.cellEditableCondition || 'true';

    self.headerRowHeight = config.headerRowHeight;

    // Use colDef.displayName as long as it's not undefined, otherwise default to the field name
    self.displayName = (colDef.displayName === undefined) ? colDef.field : colDef.displayName;

    self.index = config.index;
    self.isAggCol = config.isAggCol;
    self.cellClass = colDef.cellClass;
    self.sortPriority = undefined;
    self.cellFilter = colDef.cellFilter ? colDef.cellFilter : "";
    self.field = colDef.field;
    self.aggLabelFilter = colDef.aggLabelFilter || colDef.cellFilter;
    self.visible = $utils.isNullOrUndefined(colDef.visible) || colDef.visible;
    self.sortable = false;
    self.resizable = false;
    self.pinnable = false;
    self.pinned = (config.enablePinning && colDef.pinned);
    self.originalIndex = config.originalIndex == null ? self.index : config.originalIndex;
    self.groupable = $utils.isNullOrUndefined(colDef.groupable) || colDef.groupable;
    if (config.enableSort) {
        self.sortable = $utils.isNullOrUndefined(colDef.sortable) || colDef.sortable;
    }
    if (config.enableResize) {
        self.resizable = $utils.isNullOrUndefined(colDef.resizable) || colDef.resizable;
    }
    if (config.enablePinning) {
        self.pinnable = $utils.isNullOrUndefined(colDef.pinnable) || colDef.pinnable;
    }
    self.sortDirection = undefined;
    self.sortingAlgorithm = colDef.sortFn;
    self.headerClass = colDef.headerClass;
    self.cursor = self.sortable ? 'pointer' : 'default';
    self.headerCellTemplate = colDef.headerCellTemplate || $templateCache.get('headerCellTemplate.html');
    self.cellTemplate = colDef.cellTemplate || $templateCache.get('cellTemplate.html').replace(CUSTOM_FILTERS, self.cellFilter ? "|" + self.cellFilter : "");
    if(self.enableCellEdit) {
        self.cellEditTemplate = colDef.cellEditTemplate || $templateCache.get('cellEditTemplate.html');
        self.editableCellTemplate = colDef.editableCellTemplate || $templateCache.get('editableCellTemplate.html');
    }
    if (colDef.cellTemplate && !TEMPLATE_REGEXP.test(colDef.cellTemplate)) {
        self.cellTemplate = $templateCache.get(colDef.cellTemplate) || $.ajax({
            type: "GET",
            url: colDef.cellTemplate,
            async: false
        }).responseText;
    }
    if (self.enableCellEdit && colDef.editableCellTemplate && !TEMPLATE_REGEXP.test(colDef.editableCellTemplate)) {
        self.editableCellTemplate = $templateCache.get(colDef.editableCellTemplate) || $.ajax({
            type: "GET",
            url: colDef.editableCellTemplate,
            async: false
        }).responseText;
    }
    if (colDef.headerCellTemplate && !TEMPLATE_REGEXP.test(colDef.headerCellTemplate)) {
        self.headerCellTemplate = $templateCache.get(colDef.headerCellTemplate) || $.ajax({
            type: "GET",
            url: colDef.headerCellTemplate,
            async: false
        }).responseText;
    }
    self.colIndex = function () {
        var classes = self.pinned ? "pinned " : "";
        classes += "col" + self.index + " colt" + self.index;
        if (self.cellClass) {
            classes += " " + self.cellClass;
        }
        return classes;
    };
    self.groupedByClass = function() {
        return self.isGroupedBy ? "ngGroupedByIcon" : "ngGroupIcon";
    };
    self.toggleVisible = function() {
        self.visible = !self.visible;
    };
    self.showSortButtonUp = function() {
        return self.sortable ? self.sortDirection === DESC : self.sortable;
    };
    self.showSortButtonDown = function() {
        return self.sortable ? self.sortDirection === ASC : self.sortable;
    };
    self.noSortVisible = function() {
        return !self.sortDirection;
    };
    var gotUserSortDirection = false;
    self.sort = function(evt) {
        if (!self.sortable) {
            return true; // column sorting is disabled, do nothing
        }
        var dir;
        if(self.colDef.sortDirection && !gotUserSortDirection){
            dir = self.sortDirection === ASC ? ASC : DESC;
            gotUserSortDirection = true;
        } else {
            dir = self.sortDirection === ASC ? DESC : ASC;
        }
        self.sortDirection = dir;
        config.sortCallback(self, evt);
        return false;
    };
    self.gripClick = function() {
        clicks++; //count clicks
        if (clicks === 1) {
            timer = setTimeout(function() {
                //Here you can add a single click action.
                clicks = 0; //after action performed, reset counter
            }, delay);
        } else {
            clearTimeout(timer); //prevent single-click action
            config.resizeOnDataCallback(self); //perform double-click action
            clicks = 0; //after action performed, reset counter
        }
    };
    self.gripOnMouseDown = function(event) {
        $scope.isColumnResizing = true;
        if (event.ctrlKey && !self.pinned) {
            self.toggleVisible();
            domUtilityService.BuildStyles($scope, grid);
            return true;
        }
        event.target.parentElement.style.cursor = 'col-resize';
        self.startMousePosition = event.clientX;
        self.origWidth = self.width;
        $(document).mousemove(self.onMouseMove);
        $(document).mouseup(self.gripOnMouseUp);
        return false;
    };
    self.onMouseMove = function(event) {
        var diff = event.clientX - self.startMousePosition;
        var newWidth = diff + self.origWidth;
        self.width = (newWidth < self.minWidth ? self.minWidth : (newWidth > self.maxWidth ? self.maxWidth : newWidth));
        $scope.hasUserChangedGridColumnWidths = true;
        domUtilityService.BuildStyles($scope, grid);
        return false;
    };
    self.gripOnMouseUp = function (event) {
        $(document).off('mousemove', self.onMouseMove);
        $(document).off('mouseup', self.gripOnMouseUp);
        event.target.parentElement.style.cursor = 'default';
        domUtilityService.digest($scope);
        $scope.isColumnResizing = false;
        return false;
    };
    self.copy = function() {
        var ret = new ngColumn(config, $scope, grid, domUtilityService, $templateCache, $utils);
        ret.isClone = true;
        ret.orig = self;
        return ret;
    };
    self.setVars = function (fromCol) {
        self.orig = fromCol;
        self.width = fromCol.width;
        self.groupIndex = fromCol.groupIndex;
        self.isGroupedBy = fromCol.isGroupedBy;
        self.displayName = fromCol.displayName;
        self.index = fromCol.index;
        self.isAggCol = fromCol.isAggCol;
        self.cellClass = fromCol.cellClass;
        self.cellFilter = fromCol.cellFilter;
        self.field = fromCol.field;
        self.aggLabelFilter = fromCol.aggLabelFilter;
        self.visible = fromCol.visible;
        self.sortable = fromCol.sortable;
        self.resizable = fromCol.resizable;
        self.pinnable = fromCol.pinnable;
        self.pinned = fromCol.pinned;
        self.originalIndex = fromCol.originalIndex;
        self.sortDirection = fromCol.sortDirection;
        self.sortingAlgorithm = fromCol.sortingAlgorithm;
        self.headerClass = fromCol.headerClass;
        self.headerCellTemplate = fromCol.headerCellTemplate;
        self.cellTemplate = fromCol.cellTemplate;
        self.cellEditTemplate = fromCol.cellEditTemplate;
    };
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { IntlProvider, addLocaleData } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config';
import { LocaleProvider, Layout } from 'antd';
import enUS from 'antd/lib/locale-provider/en_US';
import { getAvailableLocale } from './translations';

import {
  getIsLoaded,
  getAuthenticatedUser,
  getAuthenticatedUserName,
  getLocale,
  getUsedLocale,
} from './reducers';

import { login, logout } from './auth/authActions';
import { getFollowing } from './user/userActions';
import { getRate, getRewardFund, getTrendingTopics } from './app/appActions';
import * as reblogActions from './app/Reblog/reblogActions';
import Topnav from './components/Navigation/Topnav';
import Transfer from './wallet/Transfer';

@withRouter
@connect(
  state => ({
    loaded: getIsLoaded(state),
    user: getAuthenticatedUser(state),
    username: getAuthenticatedUserName(state),
    usedLocale: getUsedLocale(state),
    locale: getLocale(state),
  }),
  {
    login,
    logout,
    getFollowing,
    getRate,
    getRewardFund,
    getTrendingTopics,
    getRebloggedList: reblogActions.getRebloggedList,
  },
)
export default class Wrapper extends React.PureComponent {
  static propTypes = {
    route: PropTypes.shape().isRequired,
    loaded: PropTypes.bool.isRequired,
    user: PropTypes.shape().isRequired,
    locale: PropTypes.string.isRequired,
    usedLocale: PropTypes.string.isRequired,
    history: PropTypes.shape().isRequired,
    username: PropTypes.string,
    login: PropTypes.func,
    logout: PropTypes.func,
    getFollowing: PropTypes.func,
    getRewardFund: PropTypes.func,
    getRebloggedList: PropTypes.func,
    getRate: PropTypes.func,
    getTrendingTopics: PropTypes.func,
  };

  static defaultProps = {
    username: '',
    login: () => {},
    logout: () => {},
    getFollowing: () => {},
    getRewardFund: () => {},
    getRebloggedList: () => {},
    getRate: () => {},
    getTrendingTopics: () => {},
  };

  static fetchData(store) {
    return store.dispatch(login());
  }

  constructor(props) {
    super(props);

    this.state = {
      translations: global.translations,
    };

    this.loadLocale = this.loadLocale.bind(this);
    this.handleMenuItemClick = this.handleMenuItemClick.bind(this);
  }

  componentDidMount() {
    const { loaded, locale, usedLocale } = this.props;

    this.props.login().then(() => this.props.getFollowing());
    this.props.getRewardFund();
    this.props.getRebloggedList();
    this.props.getRate();
    this.props.getTrendingTopics();

    if (usedLocale !== getAvailableLocale(locale) && loaded) {
      this.loadLocale(locale);
    }
  }

  componentWillReceiveProps(nextProps) {
    const { usedLocale } = this.props;

    if (usedLocale !== getAvailableLocale(nextProps.locale) && nextProps.loaded) {
      this.loadLocale(nextProps.locale);
    }
  }

  loadLocale(locale) {
    const availableLocale = getAvailableLocale(locale);

    const localeDataPromise = import(`react-intl/locale-data/${availableLocale}`);
    const translationsPromise = import(`./locales/${availableLocale}.json`);

    Promise.all([localeDataPromise, translationsPromise]).then(([localeData, translations]) => {
      addLocaleData(localeData);
      this.setState({
        translations,
      });
    });
  }

  handleMenuItemClick(key) {
    switch (key) {
      case 'logout':
        this.props.logout();
        break;
      case 'activity':
        this.props.history.push('/activity');
        break;
      case 'replies':
        this.props.history.push('/replies');
        break;
      case 'bookmarks':
        this.props.history.push('/bookmarks');
        break;
      case 'drafts':
        this.props.history.push('/drafts');
        break;
      case 'settings':
        this.props.history.push('/settings');
        break;
      case 'feed':
        this.props.history.push('/');
        break;
      case 'news':
        this.props.history.push('/trending');
        break;
      case 'wallet':
        this.props.history.push('/wallet');
        break;
      case 'my-profile':
        this.props.history.push(`/@${this.props.username}`);
        break;
      default:
        break;
    }
  }

  render() {
    const { user, usedLocale } = this.props;
    const { translations } = this.state;

    return (
      <IntlProvider key={usedLocale} locale={usedLocale} messages={translations}>
        <LocaleProvider locale={enUS}>
          <Layout>
            <Layout.Header style={{ position: 'fixed', width: '100%', zIndex: 5 }}>
              <Topnav username={user.name} onMenuItemClick={this.handleMenuItemClick} />
            </Layout.Header>

              {renderRoutes(this.props.route.routes)}
              <Transfer />

          </Layout>
        </LocaleProvider>
      </IntlProvider>
    );
  }
}
<commit_msg>Fix for 'User is not Authenticated' promise error (#1348)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { IntlProvider, addLocaleData } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config';
import { LocaleProvider, Layout } from 'antd';
import enUS from 'antd/lib/locale-provider/en_US';
import Cookie from 'js-cookie';
import { getAvailableLocale } from './translations';
import {
  getIsLoaded,
  getAuthenticatedUser,
  getAuthenticatedUserName,
  getLocale,
  getUsedLocale,
} from './reducers';
import { login, logout } from './auth/authActions';
import { getFollowing } from './user/userActions';
import { getRate, getRewardFund, getTrendingTopics } from './app/appActions';
import * as reblogActions from './app/Reblog/reblogActions';
import Topnav from './components/Navigation/Topnav';
import Transfer from './wallet/Transfer';

@withRouter
@connect(
  state => ({
    loaded: getIsLoaded(state),
    user: getAuthenticatedUser(state),
    username: getAuthenticatedUserName(state),
    usedLocale: getUsedLocale(state),
    locale: getLocale(state),
  }),
  {
    login,
    logout,
    getFollowing,
    getRate,
    getRewardFund,
    getTrendingTopics,
    getRebloggedList: reblogActions.getRebloggedList,
  },
)
export default class Wrapper extends React.PureComponent {
  static propTypes = {
    route: PropTypes.shape().isRequired,
    loaded: PropTypes.bool.isRequired,
    user: PropTypes.shape().isRequired,
    locale: PropTypes.string.isRequired,
    usedLocale: PropTypes.string.isRequired,
    history: PropTypes.shape().isRequired,
    username: PropTypes.string,
    login: PropTypes.func,
    logout: PropTypes.func,
    getFollowing: PropTypes.func,
    getRewardFund: PropTypes.func,
    getRebloggedList: PropTypes.func,
    getRate: PropTypes.func,
    getTrendingTopics: PropTypes.func,
  };

  static defaultProps = {
    username: '',
    login: () => {},
    logout: () => {},
    getFollowing: () => {},
    getRewardFund: () => {},
    getRebloggedList: () => {},
    getRate: () => {},
    getTrendingTopics: () => {},
  };

  static fetchData(store) {
    return store.dispatch(login());
  }

  constructor(props) {
    super(props);

    this.state = {
      translations: global.translations,
    };

    this.loadLocale = this.loadLocale.bind(this);
    this.handleMenuItemClick = this.handleMenuItemClick.bind(this);
  }

  componentDidMount() {
    const { loaded, locale, usedLocale } = this.props;

    if (Cookie.get('access_token')) {
      this.props.login().then(() => this.props.getFollowing());
    }

    this.props.getRewardFund();
    this.props.getRebloggedList();
    this.props.getRate();
    this.props.getTrendingTopics();

    if (usedLocale !== getAvailableLocale(locale) && loaded) {
      this.loadLocale(locale);
    }
  }

  componentWillReceiveProps(nextProps) {
    const { usedLocale } = this.props;

    if (usedLocale !== getAvailableLocale(nextProps.locale) && nextProps.loaded) {
      this.loadLocale(nextProps.locale);
    }
  }

  loadLocale(locale) {
    const availableLocale = getAvailableLocale(locale);

    const localeDataPromise = import(`react-intl/locale-data/${availableLocale}`);
    const translationsPromise = import(`./locales/${availableLocale}.json`);

    Promise.all([localeDataPromise, translationsPromise]).then(([localeData, translations]) => {
      addLocaleData(localeData);
      this.setState({
        translations,
      });
    });
  }

  handleMenuItemClick(key) {
    switch (key) {
      case 'logout':
        this.props.logout();
        break;
      case 'activity':
        this.props.history.push('/activity');
        break;
      case 'replies':
        this.props.history.push('/replies');
        break;
      case 'bookmarks':
        this.props.history.push('/bookmarks');
        break;
      case 'drafts':
        this.props.history.push('/drafts');
        break;
      case 'settings':
        this.props.history.push('/settings');
        break;
      case 'feed':
        this.props.history.push('/');
        break;
      case 'news':
        this.props.history.push('/trending');
        break;
      case 'wallet':
        this.props.history.push('/wallet');
        break;
      case 'my-profile':
        this.props.history.push(`/@${this.props.username}`);
        break;
      default:
        break;
    }
  }

  render() {
    const { user, usedLocale } = this.props;
    const { translations } = this.state;

    return (
      <IntlProvider key={usedLocale} locale={usedLocale} messages={translations}>
        <LocaleProvider locale={enUS}>
          <Layout>
            <Layout.Header style={{ position: 'fixed', width: '100%', zIndex: 5 }}>
              <Topnav username={user.name} onMenuItemClick={this.handleMenuItemClick} />
            </Layout.Header>

              {renderRoutes(this.props.route.routes)}
              <Transfer />

          </Layout>
        </LocaleProvider>
      </IntlProvider>
    );
  }
}
<|endoftext|>


<commit_before>"use strict"

/**
 * Manage backend websocket connection
 */
define([ 'rz_config', 'util', 'model/diff', 'model/util', 'socketio'], function(rz_config, util, model_diff, model_util, io) {

    var ws_server_url = 'http://' + rz_config.rz_server_host + ':'
                        + rz_config.rz_server_port
                        + '/graph'; // socketio namespace

    var rz_mesh_graph_ref;

    /**
     * @param init_spec: expected to contain a graph:graph mapping
     */
    function init(init_spec) {

        var socket = io.connect(ws_server_url, {
            'reconnectionDelay': 3000,
        });

        util.assert(undefined != init_spec.graph, 'unable to init ws connection, graph undefined');
        rz_mesh_graph_ref = init_spec.graph;

        // wire up event handlers
        socket.on('connect', on_connect);
        socket.on('disconnect', on_disconnect);
        socket.on('error', on_error);
        socket.on('diff_commit__topo', ws_diff_merge__topo);
        socket.on('diff_commit__attr', ws_diff_merge__attr);
    }

    function on_connect() {
        console.log('ws: connection established: endpoint: ' + ws_server_url);
    }

    function on_disconnect() {
        // TODO: call when possible
    }

    function on_error(err) {
        console.log('ws: error: ' + err);
    }

    /**
     * Handle websocket incoming Topo_Diffs
     *
     * @param topo_diff_cr: Topo_Diff commit result object
     */
    function ws_diff_merge__topo(topo_diff_spec_raw, topo_diff_cr) {

        // adapt from wire format, no need to do the same for id_sets
        var node_set_add = topo_diff_spec_raw.node_set_add.map(model_util.adapt_format_read_node)
        var link_ptr_set = topo_diff_spec_raw.link_set_add.map(model_util.adapt_format_read_link_ptr)

        var topo_diff_spec = { node_set_add: node_set_add,
                               link_set_add: link_ptr_set,
                               node_id_set_rm: topo_diff_spec_raw.node_id_set_rm,
                               link_id_set_rm: topo_diff_spec_raw.link_id_set_rm };

        // [!] note: this is not a pure Topo_Diff object in the sense it contain a link_ptr_set,
        // not a resolved link object set
        var topo_diff = model_diff.new_topo_diff(topo_diff_spec); // run through validation

        console.log('ws: rx: ws_diff_merge__topo, committing wire-adapted topo_diff:', topo_diff);

        rz_mesh_graph_ref.commit_diff__topo(topo_diff_spec);
    }

    /**
     * Handle websocket incoming Attr_Diffs
     *
     * @param attr_diff_cr: Attr_Diff commit result object
     */
    function ws_diff_merge__attr(attr_diff_spec, attr_diff_cr) {
        var attr_diff = model_diff.new_attr_diff_from_spec(attr_diff_spec); // run through validation
        console.log('ws: rx: ws_diff_merge__attr, committing wire-adapted topo_diff:', attr_diff);
        rz_mesh_graph_ref.commit_diff__attr(attr_diff);
    }

    return {
        init : init
    };

});
<commit_msg>rz_mesh.js: attempt to actively disconnect on 'beforeunload' event<commit_after>"use strict"

/**
 * Manage backend websocket connection
 */
define([ 'rz_config', 'util', 'model/diff', 'model/util', 'socketio'], function(rz_config, util, model_diff, model_util, io) {

    var ws_server_url = 'http://' + rz_config.rz_server_host + ':'
                        + rz_config.rz_server_port
                        + '/graph'; // socketio namespace

    var socket;
    var rz_mesh_graph_ref;

    /**
     * @param init_spec: expected to contain a graph:graph mapping
     */
    function init(init_spec) {

        socket = io.connect(ws_server_url, {
            'reconnectionDelay': 3000,
        });

        util.assert(undefined != init_spec.graph, 'unable to init ws connection, graph undefined');
        rz_mesh_graph_ref = init_spec.graph;

        // wire up event handlers
        socket.on('connect', on_connect);
        socket.on('disconnect', on_disconnect);
        socket.on('error', on_error);
        socket.on('diff_commit__topo', ws_diff_merge__topo);
        socket.on('diff_commit__attr', ws_diff_merge__attr);

        // attempt to actively disconnect on tab/window close
        // ref: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers.onbeforeunload
        window.addEventListener("beforeunload", function(e){
            socket.close();
            console.log('ws: connection closed on \'beforeunload\' event'); // no one will ever see this but still
        });
    }

    function on_connect() {
        console.log('ws: connection established: endpoint: ' + ws_server_url);
    }

    function on_disconnect() {
        console.log('ws: connection closed on peer disconnect, endpoint: ' + ws_server_url);
    }

    function on_error(err) {
        console.log('ws: error: ' + err);
    }

    /**
     * Handle websocket incoming Topo_Diffs
     *
     * @param topo_diff_cr: Topo_Diff commit result object
     */
    function ws_diff_merge__topo(topo_diff_spec_raw, topo_diff_cr) {

        // adapt from wire format, no need to do the same for id_sets
        var node_set_add = topo_diff_spec_raw.node_set_add.map(model_util.adapt_format_read_node)
        var link_ptr_set = topo_diff_spec_raw.link_set_add.map(model_util.adapt_format_read_link_ptr)

        var topo_diff_spec = { node_set_add: node_set_add,
                               link_set_add: link_ptr_set,
                               node_id_set_rm: topo_diff_spec_raw.node_id_set_rm,
                               link_id_set_rm: topo_diff_spec_raw.link_id_set_rm };

        // [!] note: this is not a pure Topo_Diff object in the sense it contain a link_ptr_set,
        // not a resolved link object set
        var topo_diff = model_diff.new_topo_diff(topo_diff_spec); // run through validation

        console.log('ws: rx: ws_diff_merge__topo, committing wire-adapted topo_diff:', topo_diff);

        rz_mesh_graph_ref.commit_diff__topo(topo_diff_spec);
    }

    /**
     * Handle websocket incoming Attr_Diffs
     *
     * @param attr_diff_cr: Attr_Diff commit result object
     */
    function ws_diff_merge__attr(attr_diff_spec, attr_diff_cr) {
        var attr_diff = model_diff.new_attr_diff_from_spec(attr_diff_spec); // run through validation
        console.log('ws: rx: ws_diff_merge__attr, committing wire-adapted topo_diff:', attr_diff);
        rz_mesh_graph_ref.commit_diff__attr(attr_diff);
    }

    return {
        init : init
    };

});
<|endoftext|>


<commit_before>(function() {

	"use strict";

	var viewModelFactory = modules.PoeticRivals.factories.viewModel;

	viewModelFactory.IndexablePoem = function(JSON, indexId, jqTemplate) {

			var vm = this;

			viewModelFactory.Indexable.call(vm, JSON, indexId, jqTemplate, jqButtonsTemplate);

			var updateJqTemplate = function() {
				var commentatorUsernameLink = vm.jqTemplate.find('.commentator-username'),
					newCommentatorUsernameLinkHref = commentatorUsernameLink.attr("href").replace(/\/poems\/(\d)+/, "/userss/" + vm.commentator.id);

				commentatorUsernameLink.html(vm.commentator.username);
				commentatorUsernameLink.attr("href", newCommentatorUsernameLinkHref);

				vm.jqTemplate.find('.commentator-role').html(vm.commentator.rendered_role)
				vm.jqTemplate.find('.created-at-date').html(vm.created_at_date);
				vm.jqTemplate.find('.created-at-time').html(vm.created_at_time);
				vm.jqTemplate.find('.updated-at-date').html(vm.updated_at_date);
				vm.jqTemplate.find('.updated-at-time').html(vm.updated_at_time);
				vm.jqTemplate.find('.comment').html(vm.rendered_comment);
			};

			vm.updateJqTemplate = updateJqTemplate;

		}

})();<commit_msg>finished implementing viewModel.IndexableCommentary<commit_after>(function() {

	"use strict";

	var viewModelFactory = modules.PoeticRivals.factories.viewModel;

	viewModelFactory.IndexablePoem = function(JSON, indexId, jqTemplate) {

			var vm = this;

			viewModelFactory.Indexable.call(vm, JSON, indexId, jqTemplate, jqButtonsTemplate);

			var updateJqTemplate = function() {
				var commentatorUsernameLink = vm.jqTemplate.find('.commentator-username'),
					newCommentatorUsernameLinkHref = commentatorUsernameLink.attr("href").replace(/\/poems\/(\d)+/, "/userss/" + vm.commentator.id);

				commentatorUsernameLink.html(vm.commentator.username);
				commentatorUsernameLink.attr("href", newCommentatorUsernameLinkHref);

				vm.jqTemplate.find('.commentator-role').html(vm.commentator.rendered_role)
				vm.jqTemplate.find('.created-at-date').html(vm.created_at_date);
				vm.jqTemplate.find('.created-at-time').html(vm.created_at_time);
				vm.jqTemplate.find('.updated-at-date').html(vm.updated_at_date);
				vm.jqTemplate.find('.updated-at-time').html(vm.updated_at_time);
				vm.jqTemplate.find('.comment').html(vm.rendered_comment);
			};

			var updatejqButtonsTemplate = function() {
				var editButtonForm = vm.jqButtonsTemplate.find('[method]="get"'),
					deleteButtonForm = vm.jqButtonsTemplate.find('[method]="post"'),
					newEditButtonFormAction = editButtonForm.attr("action").replace(/\/commentaries\/(\d)+/, "/commentaries/" + vm.id),
					newDeleteButtonFormAction = deleteButtonForm.attr("action").replace(/\/commentaries\/(\d)+/, "/commentaries/" + vm.id);

				editButtonForm.attr("action", newEditButtonFormAction);
				deleteButtonForm.attr("action", newDeleteButtonFormAction);
			}

			var renderButtons = function() {
				vm.jqButtonsTemplate.appendTo('#' + vm.indexId);
			};

			vm.updateJqTemplate = updateJqTemplate,
			vm.updateJqButtonsTemplate = updatejqButtonsTemplate,
			vm.renderButtons = renderButtons;

		}

})();<|endoftext|>