<commit_before>[
{"id":"layer_new","title":"Nueva capa"},
{"id":"layer_delete","title":"Suprimir capa"},
{"id":"layer_rename","title":"Renombrar capa"},
{"id":"layer_up","title":"Mover la capa hacia arriba"},
{"id":"layer_down","title":"Mover la capa hacia abajo"},
{"id":"tool_clear","title":"Nueva imagen"},
{"id":"tool_open","title":"Abrir imagen"},
{"id":"tool_save","title":"Guardar imagen"},
{"id":"tool_docprops","title":"Propiedades del documento"},
{"id":"tool_source","title":"Editar cdigo fuente"},
{"id":"tool_undo","title":"Deshacer"},
{"id":"tool_redo","title":"Rehacer"},
{"id":"tool_clone","title":"Clonar objeto"},
{"id":"tool_delete","title":"Suprimir objeto"},
{"id":"tool_move_top","title":"Mover arriba"},
{"id":"tool_move_bottom","title":"Mover abajo"},
{"id":"group_opacity","title":"Cambiar la opacidad del objeto seleccionado"},
{"id":"angle","title":"Cambiar el ngulo de rotacin"},
{"id":"tool_clone_multi","title":" Clonar objetos"},
{"id":"tool_delete_multi","title":"Suprimir los objetos seleccionados"},
{"id":"tool_alignleft","title":"Alinear lado izquierdo"},
{"id":"tool_aligncenter","title":"Centrar verticalmente"},
{"id":"tool_alignright","title":"Alinear lado derecho"},
{"id":"tool_aligntop","title":"Alinear parte superior"},
{"id":"tool_alignmiddle","title":"Centrar horizontalmente"},
{"id":"tool_alignbottom","title":"Alinear parte inferior"},
{"id":"align_relative_to","title":"Alinear con respecto a ..."},
{"id":"tool_group","title":"Agrupar objetos"},
{"id":"tool_ungroup","title":"Desagrupar objetos"},
{"id":"rect_width","title":"Cambiar el ancho rectngulo"},
{"id":"rect_height","title":"Cambiar la altura del rectgulo"},
{"id":"rect_rx","title":"Cambiar el radio de las esquinas del rectngulo"},
{"id":"image_width","title":"Cambiar el ancho de la imagen"},
{"id":"image_height","title":"Cambiar la altura de la imagen"},
{"id":"image_url","title":"Modificar URL"},
{"id":"circle_cx","title":"Cambiar la posicin horizonral CX del crculo"},
{"id":"circle_cy","title":"Cambiar la posicin vertical CY del crculo"},
{"id":"circle_r","title":"Cambiar el radio del crculo"},
{"id":"ellipse_cx","title":"Cambiar la posicin horizontal CX de la elipse"},
{"id":"ellipse_cy","title":"Cambiar la posicin vertical CY de la elipse"},
{"id":"ellipse_rx","title":"Cambiar el radio horizontal X de la elipse"},
{"id":"ellipse_ry","title":"Cambiar el radio vertical Y de la elipse"},
{"id":"line_x1","title":"Cambiar la posicin horizontal X del comienzo de la lnea"},
{"id":"line_y1","title":"Cambiar la posicin vertical Y del comienzo de la lnea"},
{"id":"line_x2","title":"Cambiar la posicin horizontal X del final de la lnea"},
{"id":"line_y2","title":"Cambiar la poicin vertical Y del final de la lnea"},
{"id":"tool_bold","title":"Texto en negrita"},
{"id":"tool_italic","title":"Texto en cursiva"},
{"id":"font_family","title":"Tipo de fuente"},
{"id":"font_size","title":"Tamao de la fuente"},
{"id":"text","title":"Modificar el texto"},
{"id":"tool_select","title":"Herramienta de seleccin"},
{"id":"tool_fhpath","title":"Herramienta de lpiz"},
{"id":"tool_line","title":"Trazado de lneas"},
{"id":"tools_rect_show","title":"Cuadrado / Rectngulo"},
{"id":"tools_ellipse_show","title":"Crculo / Elipse"},
{"id":"tool_text","title":"Insertar texto"},
{"id":"tool_path","title":"Herramienta de trazado"},
{"id":"tool_image","title":"Insertar imagen"},
{"id":"tool_zoom","title":"Zoom"},
{"id":"zoom","title":"Cambiar el nivel de zoom"},
{"id":"fill_color","title":"Cambiar el color de relleno"},
{"id":"stroke_color","title":"Cambiar el color del contorno"},
{"id":"stroke_width","title":"Cambiar el grosor del contorno"},
{"id":"stroke_style","title":"Cambiar el estilo del trazo del contorno"},
{"id":"palette","title":"Haga clic para cambiar el color de relleno. Pulse Mays y haga clic para cambiar el color del contorno."},
{"id":"tool_square","title":"Cuadrado"},
{"id":"tool_rect","title":"Rectngulo"},
{"id":"tool_fhrect","title":"Rectngulo a mano alzada"},
{"id":"tool_circle","title":"Crculo"},
{"id":"tool_ellipse","title":"Elipse"},
{"id":"tool_fhellipse","title":"Elipse a mano alzada"},
{"id":"bkgnd_color","title":"Cambiar color de fondo / opacidad"},
{"id":"rwidthLabel","textContent":"Ancho:"},
{"id":"rheightLabel","textContent":"Alto:"},
{"id":"cornerRadiusLabel","textContent":"Radio de la esquina:"},
{"id":"iwidthLabel","textContent":"ancho:"},
{"id":"iheightLabel","textContent":"alto:"},
{"id":"svginfo_width","textContent":"Ancho:"},
{"id":"svginfo_height","textContent":"Alto:"},
{"id":"angleLabel","textContent":"ngulo:"},
{"id":"relativeToLabel","textContent":"en relacin con:"},
{"id":"zoomLabel","textContent":"Zoom:"},
{"id":"layersLabel","textContent":"Capas:"},
{"id":"selectedPredefined","textContent":"Seleccionar predefinido:"},
{"id":"fitToContent","textContent":"Ajustar al contenido"},
{"id":"tool_source_save","textContent":"Aplicar cambios"},
{"id":"tool_docprops_save","textContent":"OK"},
{"id":"tool_docprops_cancel","textContent":"Cancelar"},
{"id":"tool_source_cancel","textContent":"Cancelar"},
{"id":"fit_to_all","textContent":"Ajustar a todo el contenido"},
{"id":"fit_to_layer_content","textContent":"Ajustar al contenido de la capa"},
{"id":"fit_to_sel","textContent":"Ajustar a la seleccin"},
{"id":"fit_to_canvas","textContent":"Ajustar al lienzo"},
{"id":"selected_objects","textContent":"Objetos seleccionados"},
{"id":"largest_object","textContent":"El objeto ms grande"},
{"id":"smallest_object","textContent":"El objeto ms pequeo"},
{"id":"page","textContent":"Pgina"},
{"id":"fill_tool_bottom","textContent":"Relleno:"},
{"id":"stroke_tool_bottom","textContent":"Contorno:"},
{"id":"path_node_x","title":"Cambiar la posicin horizontal X del nodo"},
{"id":"path_node_y","title":"Cambiar la posicin vertical Y del nodo"},
{"id":"seg_type","title":"Cambiar el tipo de segmento"},
{"id":"straight_segments","textContent":"Recta"},
{"id":"curve_segments","textContent":"Curva"},
{"id":"tool_node_clone","title":"Clonar nodo"},
{"id":"tool_node_delete","title":"Suprimir nodo"},
{"id":"selLayerLabel","textContent":"Desplazar objetos a:"},
{"id":"selLayerNames","title":"Mover los objetos seleccionados a otra capa"},
{"id":"sidepanel_handle","title":"Arrastrar hacia la izquierda/derecha para modificar el tamao del panel lateral","textContent":"C a p a s"},
{"id":"tool_wireframe","title":"Modo marco de alambre"},
{"id":"svginfo_image_props","textContent":"Propiedades de la Imagen"},
{"id":"svginfo_title","textContent":"Ttulo"},
{"id":"svginfo_dim","textContent":"Tamao del lienzo"},
{"id":"includedImages","textContent":"Imgenes integradas"},
{"id":"image_opt_embed","textContent":"Integrar imgenes en forma de datos (archivos locales)"},
{"id":"image_opt_ref","textContent":"Usar la referencia del archivo"},
{"id":"svginfo_editor_prefs","textContent":"Preferencias del Editor"},
{"id":"svginfo_lang","textContent":"Idioma"},
{"id":"svginfo_change_background","textContent":"Fondo del editor"},
{"id":"svginfo_bg_note","textContent":"Nota: El fondo no se guardar junto con la imagen."},
{"id":"svginfo_icons","textContent":"Tamao de los iconos"},
{"id":"icon_small","textContent":"Pequeo"},
{"id":"icon_medium","textContent":"Mediano"},
{"id":"icon_large","textContent":"Grande"},
{"id":"icon_xlarge","textContent":"Muy grande"},
{"id":"selected_x","title":"Cambiar la posicin horizontal X"},
{"id":"selected_y","title":"Cambiar la posicin vertical Y"},
{"id":"tool_topath","title":"Convertir a trazado"},
{"id":"tool_reorient","title":"Reorientar el trazado"},
{"id":"tool_node_link","title":"Enlazar puntos de control"},
{"js_strings": {
	"invalidAttrValGiven":"Valor no vlido",
	"noContentToFitTo":"No existe un contenido al que ajustarse.",
	"layer":"Capa",
	"dupeLayerName":"Ya existe una capa con este nombre!",
	"enterUniqueLayerName":"Introduzca otro nombre distinto para la capa.",
	"enterNewLayerName":"Introduzca el nuevo nombre de la capa.",
	"layerHasThatName":"El nombre introducido es el nombre actual de la capa.",
	"QmoveElemsToLayer":"Desplazar los elementos seleccionados a la capa '%s'?",
	"QwantToClear":"Desea borrar el dibujo?\nEl historial de acciones tambin se borrar!",
	"QerrorsRevertToSource":"Existen errores sintcticos en su cdigo fuente SVG.\nDesea volver al cdigo fuente SVG original?",
	"QignoreSourceChanges":"Desea ignorar los cambios realizados sobre el cdigo fuente SVG?",
	"featNotSupported":"Funcin no compatible.",
	"enterNewImgURL":"Introduzca la nueva URL de la imagen.",
	"Aceptar":"OK",
	"cancel":"Cancelar",
	"pathNodeTooltip":"Arrastre el nodo para desplazarlo. Haga doble clic sobre el nodo para cambiar el tipo de segmento.",
	"pathCtrlPtTooltip":"Arrastre el punto de control para ajustar las propiedades de la curva.",
	"key_up":"arriba",
	"key_down":"abajo",
	"key_backspace":"retroceso",
	"key_del":"suprimir"
	}
}
]<commit_msg>Finally fix lang.es.js encoding issues<commit_after>[
{"id":"layer_new","title":"Nueva capa"},
{"id":"layer_delete","title":"Suprimir capa"},
{"id":"layer_rename","title":"Renombrar capa"},
{"id":"layer_up","title":"Mover la capa hacia arriba"},
{"id":"layer_down","title":"Mover la capa hacia abajo"},
{"id":"tool_clear","title":"Nueva imagen"},
{"id":"tool_open","title":"Abrir imagen"},
{"id":"tool_save","title":"Guardar imagen"},
{"id":"tool_docprops","title":"Propiedades del documento"},
{"id":"tool_source","title":"Editar código fuente"},
{"id":"tool_undo","title":"Deshacer"},
{"id":"tool_redo","title":"Rehacer"},
{"id":"tool_clone","title":"Clonar objeto"},
{"id":"tool_delete","title":"Suprimir objeto"},
{"id":"tool_move_top","title":"Mover arriba"},
{"id":"tool_move_bottom","title":"Mover abajo"},
{"id":"group_opacity","title":"Cambiar la opacidad del objeto seleccionado"},
{"id":"angle","title":"Cambiar el ángulo de rotación"},
{"id":"tool_clone_multi","title":" Clonar objetos"},
{"id":"tool_delete_multi","title":"Suprimir los objetos seleccionados"},
{"id":"tool_alignleft","title":"Alinear lado izquierdo"},
{"id":"tool_aligncenter","title":"Centrar verticalmente"},
{"id":"tool_alignright","title":"Alinear lado derecho"},
{"id":"tool_aligntop","title":"Alinear parte superior"},
{"id":"tool_alignmiddle","title":"Centrar horizontalmente"},
{"id":"tool_alignbottom","title":"Alinear parte inferior"},
{"id":"align_relative_to","title":"Alinear con respecto a ..."},
{"id":"tool_group","title":"Agrupar objetos"},
{"id":"tool_ungroup","title":"Desagrupar objetos"},
{"id":"rect_width","title":"Cambiar el ancho rectángulo"},
{"id":"rect_height","title":"Cambiar la altura del rectángulo"},
{"id":"rect_rx","title":"Cambiar el radio de las esquinas del rectángulo"},
{"id":"image_width","title":"Cambiar el ancho de la imagen"},
{"id":"image_height","title":"Cambiar la altura de la imagen"},
{"id":"image_url","title":"Modificar URL"},
{"id":"circle_cx","title":"Cambiar la posición horizonral CX del círculo"},
{"id":"circle_cy","title":"Cambiar la posición vertical CY del círculo"},
{"id":"circle_r","title":"Cambiar el radio del círculo"},
{"id":"ellipse_cx","title":"Cambiar la posición horizontal CX de la elipse"},
{"id":"ellipse_cy","title":"Cambiar la posición vertical CY de la elipse"},
{"id":"ellipse_rx","title":"Cambiar el radio horizontal X de la elipse"},
{"id":"ellipse_ry","title":"Cambiar el radio vertical Y de la elipse"},
{"id":"line_x1","title":"Cambiar la posición horizontal X del comienzo de la línea"},
{"id":"line_y1","title":"Cambiar la posición vertical Y del comienzo de la línea"},
{"id":"line_x2","title":"Cambiar la posición horizontal X del final de la línea"},
{"id":"line_y2","title":"Cambiar la posición vertical Y del final de la línea"},
{"id":"tool_bold","title":"Texto en negrita"},
{"id":"tool_italic","title":"Texto en cursiva"},
{"id":"font_family","title":"Tipo de fuente"},
{"id":"font_size","title":"Tamaño de la fuente"},
{"id":"text","title":"Modificar el texto"},
{"id":"tool_select","title":"Herramienta de selección"},
{"id":"tool_fhpath","title":"Herramienta de lápiz"},
{"id":"tool_line","title":"Trazado de líneas"},
{"id":"tools_rect_show","title":"Cuadrado / Rectángulo"},
{"id":"tools_ellipse_show","title":"Círculo / Elipse"},
{"id":"tool_text","title":"Insertar texto"},
{"id":"tool_path","title":"Herramienta de trazado"},
{"id":"tool_image","title":"Insertar imagen"},
{"id":"tool_zoom","title":"Zoom"},
{"id":"zoom","title":"Cambiar el nivel de zoom"},
{"id":"fill_color","title":"Cambiar el color de relleno"},
{"id":"stroke_color","title":"Cambiar el color del contorno"},
{"id":"stroke_width","title":"Cambiar el grosor del contorno"},
{"id":"stroke_style","title":"Cambiar el estilo del trazo del contorno"},
{"id":"palette","title":"Haga clic para cambiar el color de relleno. Pulse Mayús y haga clic para cambiar el color del contorno."},
{"id":"tool_square","title":"Cuadrado"},
{"id":"tool_rect","title":"Rectángulo"},
{"id":"tool_fhrect","title":"Rectángulo a mano alzada"},
{"id":"tool_circle","title":"Círculo"},
{"id":"tool_ellipse","title":"Elipse"},
{"id":"tool_fhellipse","title":"Elipse a mano alzada"},
{"id":"bkgnd_color","title":"Cambiar color de fondo / opacidad"},
{"id":"rwidthLabel","textContent":"Ancho:"},
{"id":"rheightLabel","textContent":"Alto:"},
{"id":"cornerRadiusLabel","textContent":"Radio de la esquina:"},
{"id":"iwidthLabel","textContent":"ancho:"},
{"id":"iheightLabel","textContent":"alto:"},
{"id":"svginfo_width","textContent":"Ancho:"},
{"id":"svginfo_height","textContent":"Alto:"},
{"id":"angleLabel","textContent":"ángulo:"},
{"id":"relativeToLabel","textContent":"en relación con:"},
{"id":"zoomLabel","textContent":"Zoom:"},
{"id":"layersLabel","textContent":"Capas:"},
{"id":"selectedPredefined","textContent":"Seleccionar predefinido:"},
{"id":"fitToContent","textContent":"Ajustar al contenido"},
{"id":"tool_source_save","textContent":"Aplicar cambios"},
{"id":"tool_docprops_save","textContent":"OK"},
{"id":"tool_docprops_cancel","textContent":"Cancelar"},
{"id":"tool_source_cancel","textContent":"Cancelar"},
{"id":"fit_to_all","textContent":"Ajustar a todo el contenido"},
{"id":"fit_to_layer_content","textContent":"Ajustar al contenido de la capa"},
{"id":"fit_to_sel","textContent":"Ajustar a la selección"},
{"id":"fit_to_canvas","textContent":"Ajustar al lienzo"},
{"id":"selected_objects","textContent":"Objetos seleccionados"},
{"id":"largest_object","textContent":"El objeto más grande"},
{"id":"smallest_object","textContent":"El objeto más pequeño"},
{"id":"page","textContent":"Página"},
{"id":"fill_tool_bottom","textContent":"Relleno:"},
{"id":"stroke_tool_bottom","textContent":"Contorno:"},
{"id":"path_node_x","title":"Cambiar la posición horizontal X del nodo"},
{"id":"path_node_y","title":"Cambiar la posición vertical Y del nodo"},
{"id":"seg_type","title":"Cambiar el tipo de segmento"},
{"id":"straight_segments","textContent":"Recta"},
{"id":"curve_segments","textContent":"Curva"},
{"id":"tool_node_clone","title":"Clonar nodo"},
{"id":"tool_node_delete","title":"Suprimir nodo"},
{"id":"selLayerLabel","textContent":"Desplazar objetos a:"},
{"id":"selLayerNames","title":"Mover los objetos seleccionados a otra capa"},
{"id":"sidepanel_handle","title":"Arrastrar hacia la izquierda/derecha para modificar el tamaño del panel lateral","textContent":"C a p a s"},
{"id":"tool_wireframe","title":"Modo marco de alambre"},
{"id":"svginfo_image_props","textContent":"Propiedades de la Imagen"},
{"id":"svginfo_title","textContent":"Título"},
{"id":"svginfo_dim","textContent":"Tamaño del lienzo"},
{"id":"includedImages","textContent":"Imágenes integradas"},
{"id":"image_opt_embed","textContent":"Integrar imágenes en forma de datos (archivos locales)"},
{"id":"image_opt_ref","textContent":"Usar la referencia del archivo"},
{"id":"svginfo_editor_prefs","textContent":"Preferencias del Editor"},
{"id":"svginfo_lang","textContent":"Idioma"},
{"id":"svginfo_change_background","textContent":"Fondo del editor"},
{"id":"svginfo_bg_note","textContent":"Nota: El fondo no se guardará junto con la imagen."},
{"id":"svginfo_icons","textContent":"Tamaño de los iconos"},
{"id":"icon_small","textContent":"Pequeño"},
{"id":"icon_medium","textContent":"Mediano"},
{"id":"icon_large","textContent":"Grande"},
{"id":"icon_xlarge","textContent":"Muy grande"},
{"id":"selected_x","title":"Cambiar la posición horizontal X"},
{"id":"selected_y","title":"Cambiar la posición vertical Y"},
{"id":"tool_topath","title":"Convertir a trazado"},
{"id":"tool_reorient","title":"Reorientar el trazado"},
{"id":"tool_node_link","title":"Enlazar puntos de control"},
{"js_strings": {
	"invalidAttrValGiven":"Valor no válido",
	"noContentToFitTo":"No existe un contenido al que ajustarse.",
	"layer":"Capa",
	"dupeLayerName":"¡Ya existe una capa con este nombre!",
	"enterUniqueLayerName":"Introduzca otro nombre distinto para la capa.",
	"enterNewLayerName":"Introduzca el nuevo nombre de la capa.",
	"layerHasThatName":"El nombre introducido es el nombre actual de la capa.",
	"QmoveElemsToLayer":"¿Desplazar los elementos seleccionados a la capa '%s'?",
	"QwantToClear":"¿Desea borrar el dibujo?\n¡El historial de acciones también se borrará!",
	"QerrorsRevertToSource":"Existen errores sintácticos en su código fuente SVG.\n¿Desea volver al código fuente SVG original?",
	"QignoreSourceChanges":"¿Desea ignorar los cambios realizados sobre el código fuente SVG?",
	"featNotSupported":"Función no compatible.",
	"enterNewImgURL":"Introduzca la nueva URL de la imagen.",
	"Aceptar":"OK",
	"cancel":"Cancelar",
	"pathNodeTooltip":"Arrastre el nodo para desplazarlo. Haga doble clic sobre el nodo para cambiar el tipo de segmento.",
	"pathCtrlPtTooltip":"Arrastre el punto de control para ajustar las propiedades de la curva.",
	"key_up":"arriba",
	"key_down":"abajo",
	"key_backspace":"retroceso",
	"key_del":"suprimir"
	}
}
]<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Form, Field, reduxForm, propTypes, formValueSelector } from 'redux-form/immutable';
import { FormattedMessage } from 'react-intl';

// components
import Container from '../../components/Container';
import FormGroup from '../../components/Form/FormGroup';
import FormField from '../../components/Form/FormField';
import Label from '../../components/Label';
import { CheckBox } from '../../components/Input';
import Button from '../../components/Button';
import H1 from '../../components/H1';
import { ErrorMessage, WarningMessage } from '../../components/FormMessages';
import messages from './messages';
import Captcha from './captcha';

import { register } from './actions';

const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
const refRegex = /^[0-9a-f]{8}$/i;

const validate = (values) => {
  const errors = {};
  if (!values.get('email')) {
    errors.email = 'Required';
  } else if (!emailRegex.test(values.get('email'))) {
    errors.email = 'Invalid email address.';
  } else if (values.get('email').length >= 256) {
    errors.email = 'Email address must be less than 256 characters.';
  }
  if (!values.get('captchaResponse')) {
    errors.captchaResponse = 'Required';
  }

  const referral = values.get('referral') || '';
  if (!refRegex.test(referral)) {
    if (!values.has('defaultRef') && referral.length === 0) {
      errors.referral = 'Referral code is required';
    } else if (referral.length > 0) {
      errors.referral = 'Referral code must have 8 letters';
    }
  }

  if (!values.get('terms')) {
    errors.captchaResponse = 'Required';
  }

  return errors;
};

const warn = (values) => {
  const warnings = {};
  values.get('email');
  return warnings;
};

/* eslint-disable react/prop-types */
const renderCheckBox = ({ input, label, type, meta: { touched, error, warning } }) => (
  <FormGroup>

      <CheckBox {...input} placeholder={label} type={type} />
      <FormattedMessage {...messages.terms.agree} /> {label}

    {touched && ((error && <ErrorMessage error={error} />) || (warning && <WarningMessage warning={warning} />))}
  </FormGroup>
);
/* eslint-enable react/prop-types */

export class RegisterPage extends React.Component { // eslint-disable-line react/prefer-stateless-function

  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(values) {
    this.props.register({
      email: values.get('email'),
      captchaResponse: values.get('captchaResponse'),
      origin: window.location.origin,
      referral: values.get('referral') || values.get('defaultRef'),
    });
  }

  render() {
    const { error, invalid, submitting, handleSubmit, asyncValidating, defaultRefCode } = this.props;
    const termsLink = (<FormattedMessage {...messages.terms} />);
    return (
      <Container>

Register a new account!

          <Form
            onSubmit={handleSubmit(this.handleSubmit)}
          >
            <Field name="email" type="email" component={FormField} label="E-mail" autoFocus />
            <Field
              name="referral"
              type="text"
              component={FormField}
              label={defaultRefCode ? 'Referral code (optional)' : 'Referral code'}
            />
            <Field name="captchaResponse" component={Captcha} error={error ? error.message : null} />
            {error && <ErrorMessage error={error.message} />}
            <Field
              name="terms"
              type="checkbox"
              component={renderCheckBox}
              label={termsLink}
            />
            <Button type="submit" disabled={submitting || (invalid && (!error || !error.valid)) || asyncValidating} size="large">
              { (!submitting) ? 'Register' : 'Please wait ...' }
            </Button>
          </Form>

      </Container>
    );
  }
}

RegisterPage.propTypes = {
  ...propTypes,
  input: PropTypes.any,
  defaultRefCode: PropTypes.string,
};

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    register: (payload) => dispatch(register(payload)),
  };
}

const valueSelector = formValueSelector('register');

// Which props do we want to inject, given the global state?
const mapStateToProps = (state, props) => ({
  initialValues: {
    referral: props.params.refCode,
  },
  defaultRefCode: valueSelector(state, 'defaultRef'),
});

// Wrap the component to inject dispatch and state into it
export default connect(mapStateToProps, mapDispatchToProps)(
  reduxForm({
    form: 'register',
    validate,
    warn,
  })(RegisterPage)
);
<commit_msg>Upd refCode length error message<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Form, Field, reduxForm, propTypes, formValueSelector } from 'redux-form/immutable';
import { FormattedMessage } from 'react-intl';

// components
import Container from '../../components/Container';
import FormGroup from '../../components/Form/FormGroup';
import FormField from '../../components/Form/FormField';
import Label from '../../components/Label';
import { CheckBox } from '../../components/Input';
import Button from '../../components/Button';
import H1 from '../../components/H1';
import { ErrorMessage, WarningMessage } from '../../components/FormMessages';
import messages from './messages';
import Captcha from './captcha';

import { register } from './actions';

const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
const refRegex = /^[0-9a-f]{8}$/i;

const validate = (values) => {
  const errors = {};
  if (!values.get('email')) {
    errors.email = 'Required';
  } else if (!emailRegex.test(values.get('email'))) {
    errors.email = 'Invalid email address.';
  } else if (values.get('email').length >= 256) {
    errors.email = 'Email address must be less than 256 characters.';
  }
  if (!values.get('captchaResponse')) {
    errors.captchaResponse = 'Required';
  }

  const referral = values.get('referral') || '';
  if (!refRegex.test(referral)) {
    if (!values.has('defaultRef') && referral.length === 0) {
      errors.referral = 'Referral code is required';
    } else if (referral.length > 0) {
      errors.referral = 'Referral code must have 8 characters';
    }
  }

  if (!values.get('terms')) {
    errors.captchaResponse = 'Required';
  }

  return errors;
};

const warn = (values) => {
  const warnings = {};
  values.get('email');
  return warnings;
};

/* eslint-disable react/prop-types */
const renderCheckBox = ({ input, label, type, meta: { touched, error, warning } }) => (
  <FormGroup>

      <CheckBox {...input} placeholder={label} type={type} />
      <FormattedMessage {...messages.terms.agree} /> {label}

    {touched && ((error && <ErrorMessage error={error} />) || (warning && <WarningMessage warning={warning} />))}
  </FormGroup>
);
/* eslint-enable react/prop-types */

export class RegisterPage extends React.Component { // eslint-disable-line react/prefer-stateless-function

  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(values) {
    this.props.register({
      email: values.get('email'),
      captchaResponse: values.get('captchaResponse'),
      origin: window.location.origin,
      referral: values.get('referral') || values.get('defaultRef'),
    });
  }

  render() {
    const { error, invalid, submitting, handleSubmit, asyncValidating, defaultRefCode } = this.props;
    const termsLink = (<FormattedMessage {...messages.terms} />);
    return (
      <Container>

Register a new account!

          <Form
            onSubmit={handleSubmit(this.handleSubmit)}
          >
            <Field name="email" type="email" component={FormField} label="E-mail" autoFocus />
            <Field
              name="referral"
              type="text"
              component={FormField}
              label={defaultRefCode ? 'Referral code (optional)' : 'Referral code'}
            />
            <Field name="captchaResponse" component={Captcha} error={error ? error.message : null} />
            {error && <ErrorMessage error={error.message} />}
            <Field
              name="terms"
              type="checkbox"
              component={renderCheckBox}
              label={termsLink}
            />
            <Button type="submit" disabled={submitting || (invalid && (!error || !error.valid)) || asyncValidating} size="large">
              { (!submitting) ? 'Register' : 'Please wait ...' }
            </Button>
          </Form>

      </Container>
    );
  }
}

RegisterPage.propTypes = {
  ...propTypes,
  input: PropTypes.any,
  defaultRefCode: PropTypes.string,
};

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    register: (payload) => dispatch(register(payload)),
  };
}

const valueSelector = formValueSelector('register');

// Which props do we want to inject, given the global state?
const mapStateToProps = (state, props) => ({
  initialValues: {
    referral: props.params.refCode,
  },
  defaultRefCode: valueSelector(state, 'defaultRef'),
});

// Wrap the component to inject dispatch and state into it
export default connect(mapStateToProps, mapDispatchToProps)(
  reduxForm({
    form: 'register',
    validate,
    warn,
  })(RegisterPage)
);
<|endoftext|>


<commit_before>svgEditor.readLang({
	lang: "fr",
	dir : "ltr",
	common: {
		"ok": "OK",
		"cancel": "Annuler",
		"key_backspace": "Suppr.",
		"key_del": "Retour Arr.",
		"key_down": "Bas",
		"key_up": "Haut",
		"more_opts": "Plus d'options",
		"url": "URL",
		"width": "Largeur",
		"height": "Hauteur"
	},
	misc: {
		"powered_by": "Propulsé par"
	},
	ui: {
		"toggle_stroke_tools": "Montrer/Cacher plus d'outils de Contour",
		"palette_info": "Cliquer pour changer la couleur de remplissage, Maj-Clic pour changer la couleur de contour",
		"zoom_level": "Changer le niveau de zoom",
		"panel_drag": "Tirer vers la gauche/droite pour redimentionner le panneau"
	},
	properties: {
		"id": "Identifier l'élément",
		"fill_color": "Changer la couleur de remplissage",
		"stroke_color": "Changer la couleur du contour",
		"stroke_style": "Changer le style du contour",
		"stroke_width": "Changer la largeur du contour de 1, Shift-Click pour changer la largeur de 0.1",
		"pos_x": "Changer la position horizontale X",
		"pos_y": "Changer la position verticale Y",
		"linecap_butt": "Terminaison : Sur le nœud",
		"linecap_round": "Terminaison : Arrondie",
		"linecap_square": "Terminaison : Carrée",
		"linejoin_bevel": "Raccord : Biseauté",
		"linejoin_miter": "Raccord : Droit",
		"linejoin_round": "Raccord : Arrondi",
		"angle": "Changer l'angle de rotation",
		"blur": "Changer la valeur du flou gaussien",
		"opacity": "Changer l'opacité de l'élément sélectionné",
		"circle_cx": "Changer la position horizontale cx du cercle",
		"circle_cy": "Changer la position verticale cy du cercle",
		"circle_r": "Changer le rayon du cercle",
		"ellipse_cx": "Changer la position horizontale cx de l'ellipse",
		"ellipse_cy": "Changer la position verticale cy de l'ellipse",
		"ellipse_rx": "Changer le rayon horizontal x de l'ellipse",
		"ellipse_ry": "Changer le rayon vertical y de l'ellipse",
		"line_x1": "Changer la position horizontale x de début de la ligne",
		"line_x2": "Changer la position horizontale x de fin de la ligne",
		"line_y1": "Changer la position verticale y de début de la ligne",
		"line_y2": "Changer la position verticale y de fin de la ligne",
		"rect_height": "Changer la hauteur du rectangle",
		"rect_width": "Changer la largeur du rectangle",
		"corner_radius": "Changer le rayon des coins du rectangle",
		"image_width": "Changer la largeur de l'image",
		"image_height": "Changer la hauteur de l'image",
		"image_url": "Modifier l'URL",
		"node_x": "Changer la positon horizontale x du nœud",
		"node_y": "Changer la position verticale y du nœud",
		"seg_type": "Changer le type du Segment",
		"straight_segments": "Droit",
		"curve_segments": "Courbe",
		"text_contents": "Changer le contenu du texte",
		"font_family": "Changer la famille de police",
		"font_size": "Changer la taille de la police",
		"bold": "Texte en gras",
		"italic": "Texte en italique"
	},
	tools: {
		"main_menu": "Menu principal",
		"bkgnd_color_opac": "Changer la couleur d'arrière-plan / l'opacité",
		"connector_no_arrow": "Sans flèches",
		"fitToContent": "Ajuster au contenu",
		"fit_to_all": "Ajuster au contenu de tous les calques",
		"fit_to_canvas": "Ajuster au canevas",
		"fit_to_layer_content": "Ajuster au contenu du calque",
		"fit_to_sel": "Ajuster à la sélection",
		"align_relative_to": "Aligner par rapport à ...",
		"relativeTo": "Relativement à:",
		"Page": "Page",
		"largest_object": "Plus gros objet",
		"selected_objects": "Objets sélectionnés",
		"smallest_object": "Plus petit objet",
		"new_doc": "Nouvelle image",
		"open_doc": "Ouvrir une image",
		"export_png": "Exporter au format PNG",
		"save_doc": "Enregistrer l'image",
		"import_doc": "Importer un objet SVG",
		"align_to_page": "Aligner l'élément relativement à la Page",
		"align_bottom": "Aligner le bas des objets",
		"align_center": "Centrer verticalement",
		"align_left": "Aligner les côtés gauches",
		"align_middle": "Centrer horizontalement",
		"align_right": "Aligner les côtés droits",
		"align_top": "Aligner le haut des objets",
		"mode_select": "Outil de sélection",
		"mode_fhpath": "Crayon à main levée",
		"mode_line": "Tracer des lignes",
		"mode_connect": "Connecter deux objets",
		"mode_rect": "Outil rectangle",
		"mode_square": "Outils carré",
		"mode_fhrect": "Rectangle main levée",
		"mode_ellipse": "Ellipse",
		"mode_circle": "Cercle",
		"mode_fhellipse": "Ellipse main levée",
		"mode_path": "Dessiner un tracé",
		"mode_shapelib": "Bibliothèque d'images",
		"mode_text": "Outil Texte",
		"mode_image": "Outil Image",
		"mode_zoom": "Zoom",
		"mode_eyedropper": "Outil Pipette",
		"no_embed": "NOTE: Cette image ne peut être incorporée en tant que données. Le contenu affiché sera celui de l'image située à cette adresse",
		"undo": "Annuler l'action",
		"redo": "Refaire l'action",
		"tool_source": "Modifier la source",
		"wireframe_mode": "Mode Fil de Fer",
		"toggle_grid": "Montrer/cacher la grille",
		"clone": "Cloner élement(s)",
		"del": "Supprimer élement(s)",
		"group": "Grouper les éléments",
		"make_link": "Créer (hyper)lien",
		"set_link_url": "Définir le lien URL (laisser vide pour supprimer)",
		"to_path": "Convertir en tracé",
		"reorient_path": "Réorienter le tracé",
		"ungroup": "Dégrouper les éléments",
		"docprops": "Propriétés du document",
		"imagelib": "Bibliothèque d'images",
		"move_bottom": "Déplacer vers le bas",
		"move_top": "Déplacer vers le haut",
		"node_clone": "Cloner le nœud",
		"node_delete": "Supprimer le nœud",
		"node_link": "Rendre les points de contrôle solidaires",
		"add_subpath": "Ajouter un tracé secondaire",
		"openclose_path": "Ouvrir/Fermer sous-chemin",
		"source_save": "Appliquer Modifications",
		"cut": "Couper",
		"copy": "Copier",
		"paste": "Coller",
		"paste_in_place": "Coller sur place",
		"Retour Arr.": "Supprimer",
		"move_front": "Placer au premier plan",
		"move_up": "Placer plus près",
		"move_down": "Placer au dernier plan",
		"move_back": "Placer plus au fond"
	},
	layers: {
		"layer":"Calque",
		"layers": "Calques",
		"del": "Supprimer le calque",
		"move_down": "Descendre le calque",
		"new": "Nouveau calque",
		"rename": "Renommer le calque",
		"move_up": "Monter le calque",
		"dupe": "Dupliquer calque",
		"merge_down": "Fusionner vers le bas",
		"merge_all": "Tout fusionner",
		"move_elems_to": "Déplacer éléments vers:",
		"move_selected": "Déplacer les éléments sélectionnés vers un autre calque"
	},
	config: {
		"image_props": "Propriétés de l'Image",
		"doc_title": "Titre",
		"doc_dims": "Dimensions du canevas",
		"included_images": "Images incorporées",
		"image_opt_embed": "Incorporer les images en tant que données (fichiers locaux)",
		"image_opt_ref": "Utiliser la référence des images ",
		"editor_prefs": "Préférences de l'Éditeur",
		"icon_size": "Taille des icônes",
		"language": "Langue",
		"background": "Toile de fond de l'Éditeur",
		"editor_img_url": "Image URL",
		"editor_bg_note": "Note: La toile de fond n'est pas sauvegardée avec l'image.",
		"icon_large": "Grande",
		"icon_medium": "Moyenne",
		"icon_small": "Petite",
		"icon_xlarge": "Super-Grande",
		"select_predefined": "Sélectionner prédéfinis:",
		"units_and_rulers": "Unités & Règles",
		"show_rulers": "Afficher les règles",
		"base_unit": "Unité de mesure:",
		"grid": "Grille",
		"snapping_onoff": "Épingler oui/non",
		"snapping_stepsize": "Snapping Step-Size:",
		"grid_color": "Couleur de la grille"
	},
	shape_cats: {
		"basic": "Basique",
		"object": "Objets",
		"symbol": "Symboles",
		"arrow": "Flèches",
		"flowchart": "Diagramme de flux",
		"animal": "Animaux",
		"game": "Cartes & Echecs",
		"dialog_balloon": "Bulles de dialogue",
		"electronics": "Electronique",
		"math": "Mathématiques",
		"music": "Musique",
		"misc": "Divers",
		"raphael_1": "raphaeljs.com ensemble 1",
		"raphael_2": "raphaeljs.com ensemble 2"
	},
	imagelib: {
		"select_lib": "Choisir une image dans la bibliothèque",
		"show_list": "Liste de la bibliotèque d'images",
		"import_single": "Importation simple",
		"import_multi": "Importation multiple",
		"open": "Ouvrir en tant que nouveau document"
	},
	notification: {
		"invalidAttrValGiven":"Valeur fournie invalide",
		"noContentToFitTo":"Il n'y a pas de contenu auquel ajuster",
		"dupeLayerName":"Il existe déjà un calque de ce nom !",
		"enterUniqueLayerName":"Veuillez entrer un nom (unique) pour le calque",
		"enterNewLayerName":"Veuillez entrer le nouveau nom du calque",
		"layerHasThatName":"Le calque porte déjà ce nom",
		"QmoveElemsToLayer":"Déplacer les éléments sélectionnés vers le calque '%s' ?",
		"QwantToClear":"Voulez-vous effacer le dessin ?\nL'historique de vos actions sera également effacé !",
		"QwantToOpen":"Voulez-vous ouvrir un nouveau document?\nVous perderez l'historique de vos modifications!",
		"QerrorsRevertToSource":"Il y a des erreurs d'analyse syntaxique dans votre code-source SVG.\nRevenir au code-source SVG avant modifications ?",
		"QignoreSourceChanges":"Ignorer les modifications faites à la source SVG ?",
		"featNotSupported":"Fonction non supportée",
		"enterNewImgURL":"Entrer la nouvelle URL de l'image",
		"defsFailOnSave": "NOTE : À cause d'un bug de votre navigateur, cette image peut être affichée de façon incorrecte (dégradés ou éléments manquants). Cependant, une fois enregistrée, elle sera correcte.",
		"loadingImage":"Chargement de l'image, veuillez patienter...",
		"saveFromBrowser": "Selectionner \"Enregistrer sous...\" dans votre navigateur pour sauvegarder l'image en tant que fichier %s.",
		"noteTheseIssues": "Notez également les problèmes suivants : ",
		"unsavedChanges": "Il y a des changements non sauvegardés.",
		"enterNewLinkURL": "Entrez la nouvel hyperlien URL",
		"errorLoadingSVG": "Erreur: Impossible de charger le document SVG",
		"URLloadFail": "Impossible de charger l'URL",
		"retrieving": "Récupère \"%s\"..."
	}
});
<commit_msg>82,84,141 à 145<commit_after>svgEditor.readLang({
	lang: "fr",
	dir : "ltr",
	common: {
		"ok": "OK",
		"cancel": "Annuler",
		"key_backspace": "Suppr.",
		"key_del": "Retour Arr.",
		"key_down": "Bas",
		"key_up": "Haut",
		"more_opts": "Plus d'options",
		"url": "URL",
		"width": "Largeur",
		"height": "Hauteur"
	},
	misc: {
		"powered_by": "Propulsé par"
	},
	ui: {
		"toggle_stroke_tools": "Montrer/Cacher plus d'outils de Contour",
		"palette_info": "Cliquer pour changer la couleur de remplissage, Maj-Clic pour changer la couleur de contour",
		"zoom_level": "Changer le niveau de zoom",
		"panel_drag": "Tirer vers la gauche/droite pour redimentionner le panneau"
	},
	properties: {
		"id": "Identifier l'élément",
		"fill_color": "Changer la couleur de remplissage",
		"stroke_color": "Changer la couleur du contour",
		"stroke_style": "Changer le style du contour",
		"stroke_width": "Changer la largeur du contour de 1, Shift-Click pour changer la largeur de 0.1",
		"pos_x": "Changer la position horizontale X",
		"pos_y": "Changer la position verticale Y",
		"linecap_butt": "Terminaison : Sur le nœud",
		"linecap_round": "Terminaison : Arrondie",
		"linecap_square": "Terminaison : Carrée",
		"linejoin_bevel": "Raccord : Biseauté",
		"linejoin_miter": "Raccord : Droit",
		"linejoin_round": "Raccord : Arrondi",
		"angle": "Changer l'angle de rotation",
		"blur": "Changer la valeur du flou gaussien",
		"opacity": "Changer l'opacité de l'élément sélectionné",
		"circle_cx": "Changer la position horizontale cx du cercle",
		"circle_cy": "Changer la position verticale cy du cercle",
		"circle_r": "Changer le rayon du cercle",
		"ellipse_cx": "Changer la position horizontale cx de l'ellipse",
		"ellipse_cy": "Changer la position verticale cy de l'ellipse",
		"ellipse_rx": "Changer le rayon horizontal x de l'ellipse",
		"ellipse_ry": "Changer le rayon vertical y de l'ellipse",
		"line_x1": "Changer la position horizontale x de début de la ligne",
		"line_x2": "Changer la position horizontale x de fin de la ligne",
		"line_y1": "Changer la position verticale y de début de la ligne",
		"line_y2": "Changer la position verticale y de fin de la ligne",
		"rect_height": "Changer la hauteur du rectangle",
		"rect_width": "Changer la largeur du rectangle",
		"corner_radius": "Changer le rayon des coins du rectangle",
		"image_width": "Changer la largeur de l'image",
		"image_height": "Changer la hauteur de l'image",
		"image_url": "Modifier l'URL",
		"node_x": "Changer la positon horizontale x du nœud",
		"node_y": "Changer la position verticale y du nœud",
		"seg_type": "Changer le type du Segment",
		"straight_segments": "Droit",
		"curve_segments": "Courbe",
		"text_contents": "Changer le contenu du texte",
		"font_family": "Changer la famille de police",
		"font_size": "Changer la taille de la police",
		"bold": "Texte en gras",
		"italic": "Texte en italique"
	},
	tools: {
		"main_menu": "Menu principal",
		"bkgnd_color_opac": "Changer la couleur d'arrière-plan / l'opacité",
		"connector_no_arrow": "Sans flèches",
		"fitToContent": "Ajuster au contenu",
		"fit_to_all": "Ajuster au contenu de tous les calques",
		"fit_to_canvas": "Ajuster au canevas",
		"fit_to_layer_content": "Ajuster au contenu du calque",
		"fit_to_sel": "Ajuster à la sélection",
		"align_relative_to": "Aligner par rapport à ...",
		"relativeTo": "Relativement à:",
		"Page": "Page",
		"largest_object": "Objet plus gros ",
		"selected_objects": "Objets sélectionnés",
		"smallest_object": "Objet plus petit",
		"new_doc": "Nouvelle image",
		"open_doc": "Ouvrir une image",
		"export_png": "Exporter au format PNG",
		"save_doc": "Enregistrer l'image",
		"import_doc": "Importer un objet SVG",
		"align_to_page": "Aligner l'élément relativement à la Page",
		"align_bottom": "Aligner le bas des objets",
		"align_center": "Centrer verticalement",
		"align_left": "Aligner les côtés gauches",
		"align_middle": "Centrer horizontalement",
		"align_right": "Aligner les côtés droits",
		"align_top": "Aligner le haut des objets",
		"mode_select": "Outil de sélection",
		"mode_fhpath": "Crayon à main levée",
		"mode_line": "Tracer des lignes",
		"mode_connect": "Connecter deux objets",
		"mode_rect": "Outil rectangle",
		"mode_square": "Outils carré",
		"mode_fhrect": "Rectangle main levée",
		"mode_ellipse": "Ellipse",
		"mode_circle": "Cercle",
		"mode_fhellipse": "Ellipse main levée",
		"mode_path": "Dessiner un tracé",
		"mode_shapelib": "Bibliothèque d'images",
		"mode_text": "Outil Texte",
		"mode_image": "Outil Image",
		"mode_zoom": "Zoom",
		"mode_eyedropper": "Outil Pipette",
		"no_embed": "NOTE: Cette image ne peut être incorporée en tant que données. Le contenu affiché sera celui de l'image située à cette adresse",
		"undo": "Annuler l'action",
		"redo": "Refaire l'action",
		"tool_source": "Modifier la source",
		"wireframe_mode": "Mode Fil de Fer",
		"toggle_grid": "Montrer/cacher la grille",
		"clone": "Cloner élement(s)",
		"del": "Supprimer élement(s)",
		"group": "Grouper les éléments",
		"make_link": "Créer hyperlien",
		"set_link_url": "Définir le lien URL (laisser vide pour supprimer)",
		"to_path": "Convertir en tracé",
		"reorient_path": "Réorienter le tracé",
		"ungroup": "Dégrouper les éléments",
		"docprops": "Propriétés du document",
		"imagelib": "Bibliothèque d'images",
		"move_bottom": "Déplacer vers le bas",
		"move_top": "Déplacer vers le haut",
		"node_clone": "Cloner le nœud",
		"node_delete": "Supprimer le nœud",
		"node_link": "Rendre les points de contrôle solidaires",
		"add_subpath": "Ajouter un tracé secondaire",
		"openclose_path": "Ouvrir/Fermer sous-chemin",
		"source_save": "Appliquer Modifications",
		"cut": "Couper",
		"copy": "Copier",
		"paste": "Coller",
		"paste_in_place": "Coller sur place",
		"Retour Arr.": "Supprimer",
		"move_front": "Placer au premier plan",
		"move_up": "Avancer d'un plan",
		"move_down": "Placer en arrière plan",
		"move_back": "Reculer d'un plan"
	},
	layers: {
		"layer":"Calque",
		"layers": "Calques",
		"del": "Supprimer le calque",
		"move_down": "Descendre le calque",
		"new": "Nouveau calque",
		"rename": "Renommer le calque",
		"move_up": "Monter le calque",
		"dupe": "Dupliquer calque",
		"merge_down": "Fusionner vers le bas",
		"merge_all": "Tout fusionner",
		"move_elems_to": "Déplacer éléments vers:",
		"move_selected": "Déplacer les éléments sélectionnés vers un autre calque"
	},
	config: {
		"image_props": "Propriétés de l'Image",
		"doc_title": "Titre",
		"doc_dims": "Dimensions du canevas",
		"included_images": "Images incorporées",
		"image_opt_embed": "Incorporer les images en tant que données (fichiers locaux)",
		"image_opt_ref": "Utiliser la référence des images ",
		"editor_prefs": "Préférences de l'Éditeur",
		"icon_size": "Taille des icônes",
		"language": "Langue",
		"background": "Toile de fond de l'Éditeur",
		"editor_img_url": "Image URL",
		"editor_bg_note": "Note: La toile de fond n'est pas sauvegardée avec l'image.",
		"icon_large": "Grande",
		"icon_medium": "Moyenne",
		"icon_small": "Petite",
		"icon_xlarge": "Super-Grande",
		"select_predefined": "Sélectionner prédéfinis:",
		"units_and_rulers": "Unités & Règles",
		"show_rulers": "Afficher les règles",
		"base_unit": "Unité de mesure:",
		"grid": "Grille",
		"snapping_onoff": "Épingler oui/non",
		"snapping_stepsize": "Snapping Step-Size:",
		"grid_color": "Couleur de la grille"
	},
	shape_cats: {
		"basic": "Basique",
		"object": "Objets",
		"symbol": "Symboles",
		"arrow": "Flèches",
		"flowchart": "Diagramme de flux",
		"animal": "Animaux",
		"game": "Cartes & Echecs",
		"dialog_balloon": "Bulles de dialogue",
		"electronics": "Electronique",
		"math": "Mathématiques",
		"music": "Musique",
		"misc": "Divers",
		"raphael_1": "raphaeljs.com ensemble 1",
		"raphael_2": "raphaeljs.com ensemble 2"
	},
	imagelib: {
		"select_lib": "Choisir une image dans la bibliothèque",
		"show_list": "Liste de la bibliotèque d'images",
		"import_single": "Importation simple",
		"import_multi": "Importation multiple",
		"open": "Ouvrir en tant que nouveau document"
	},
	notification: {
		"invalidAttrValGiven":"Valeur fournie invalide",
		"noContentToFitTo":"Il n'y a pas de contenu auquel ajuster",
		"dupeLayerName":"Il existe déjà un calque de ce nom !",
		"enterUniqueLayerName":"Veuillez entrer un nom (unique) pour le calque",
		"enterNewLayerName":"Veuillez entrer le nouveau nom du calque",
		"layerHasThatName":"Le calque porte déjà ce nom",
		"QmoveElemsToLayer":"Déplacer les éléments sélectionnés vers le calque '%s' ?",
		"QwantToClear":"Voulez-vous effacer le dessin ?\nL'historique de vos actions sera également effacé !",
		"QwantToOpen":"Voulez-vous ouvrir un nouveau document?\nVous perderez l'historique de vos modifications!",
		"QerrorsRevertToSource":"Il y a des erreurs d'analyse syntaxique dans votre code-source SVG.\nRevenir au code-source SVG avant modifications ?",
		"QignoreSourceChanges":"Ignorer les modifications faites à la source SVG ?",
		"featNotSupported":"Fonction non supportée",
		"enterNewImgURL":"Entrer la nouvelle URL de l'image",
		"defsFailOnSave": "NOTE : À cause d'un bug de votre navigateur, cette image peut être affichée de façon incorrecte (dégradés ou éléments manquants). Cependant, une fois enregistrée, elle sera correcte.",
		"loadingImage":"Chargement de l'image, veuillez patienter...",
		"saveFromBrowser": "Selectionner \"Enregistrer sous...\" dans votre navigateur pour sauvegarder l'image en tant que fichier %s.",
		"noteTheseIssues": "Notez également les problèmes suivants : ",
		"unsavedChanges": "Il y a des changements non sauvegardés.",
		"enterNewLinkURL": "Entrez la nouvel hyperlien URL",
		"errorLoadingSVG": "Erreur: Impossible de charger le document SVG",
		"URLloadFail": "Impossible de charger l'URL",
		"retrieving": "Récupère \"%s\"..."
	}
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

/**
 * Module dependencies
 */

// Node.js core.
const fs = require('fs');
const path = require('path');

// Public node modules.
const request = require('request');
const winston = require('winston');

// Logger.
const logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      level: 'debug',
      colorize: 'level'
    })
  ]
});

/**
 * `$ strapi logout`
 *
 * Logout your account from the Strapi Studio.
 */

module.exports = function () {

  // Make the logout request to the Studio.
  request({
    method: 'POST',
    preambleCRLF: true,
    postambleCRLF: true,
    json: true,
    uri: 'http://studio.strapi.io/logout'
  },

  // Callback.
  function (err) {
    const HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];

    // Stop if there is an error.
    if (err) {
      logger.error(err);
      process.exit(1);
    }

    // Try to access the `.strapirc` at $HOME.
    fs.access(path.resolve(HOME, '.strapirc'), fs.F_OK | fs.R_OK | fs.W_OK, function (err) {
      if (err) {
        logger.error('You are not logged in.');
      } else {
        const config = JSON.parse(fs.readFileSync(path.resolve(HOME, '.strapirc'), 'utf8'));

        delete config.email;
        delete config.token;

        fs.writeFileSync(path.resolve(HOME, '.strapirc'), JSON.stringify(config), 'utf8');
        logger.info('Your machine is not linked to the Strapi Studio anymore.');
        process.exit(0);
      }
    });
  });
};
<commit_msg>Remove useless request when logout via the CLI<commit_after>#!/usr/bin/env node

'use strict';

/**
 * Module dependencies
 */

// Node.js core.
const fs = require('fs');
const path = require('path');

// Public node modules.
const winston = require('winston');

// Logger.
const logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      level: 'debug',
      colorize: 'level'
    })
  ]
});

/**
 * `$ strapi logout`
 *
 * Logout your account from the Strapi Studio.
 */

module.exports = function () {
  const HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];

  // Try to access the `.strapirc` at $HOME.
  fs.access(path.resolve(HOME, '.strapirc'), fs.F_OK | fs.R_OK | fs.W_OK, function (err) {
    if (err) {
      logger.error('You are not logged in.');
    } else {
      const config = JSON.parse(fs.readFileSync(path.resolve(HOME, '.strapirc'), 'utf8'));

      delete config.email;
      delete config.token;

      fs.writeFileSync(path.resolve(HOME, '.strapirc'), JSON.stringify(config), 'utf8');
      logger.info('Your machine is not linked to the Strapi Studio anymore.');
      process.exit(0);
    }
  });
};
<|endoftext|>


<commit_before>/*
 *	Factlink
 *	A simple proxy server which will proxy requests.
 *
 *	Used for implementing Factlink JavaScript on client-sites.
 */

/* jslint node: true */

// The actual server
var server = require('express').createServer();
server.configure(function (){
        server.set('views', __dirname + '/views');
});

/**
 *	We execute our requests using Restler
 *  because it follows redirects if needed
 */
var restler = require('restler');

var fs = require('fs');
config_path = process.env.CONFIG_PATH || '../config/';
global.config = require('./read_config').read_conf(config_path,fs,server.settings.env);

var PROXY_URL   = "http://"+global.config.proxy.hostname+':'+global.config.proxy.port;
var STATIC_URL  = "http://"+global.config['static'].hostname+':'+global.config['static'].port;

var API_LOCATION = global.config.core.hostname + ':'+global.config.core.port;
var LIB_LOCATION = global.config['static'].hostname +':'+global.config['static'].port + "/lib";

console.info(LIB_LOCATION);
console.info(STATIC_URL);

var PORT         = parseInt(global.config.proxy.port,10);

// Use Jade as templating engine
server.set('view engine', 'jade');

/**
 * Add base url and inject proxy.js, and return the proxied site
 */
function injectFactlinkJs(html_in,site, scrollto, modus){

  console.info('injectFactlinkJs: modus: ' + modus);

	var html = html_in.replace(/<head[^>]*>/i, '$&<base href="' + site + '" />');
    var set_urls = '<script>'+
             'window.FACTLINK_PROXY_URL = "' + PROXY_URL + '";'+
             'window.FACTLINK_STATIC_URL = "' + STATIC_URL + '";'+
             'window.FACTLINK_API_LOCATION = "' + API_LOCATION + '";'+
             'window.FACTLINK_LIB_LOCATION = "' + LIB_LOCATION + '";'+
             'window.FACTLINK_MODUS = "' + modus + '";'+
             'window.FACTLINK_REAL_URL = "' + site + '";';
    if (scrollto !== undefined && !isNaN(parseInt(scrollto,10))){
        set_urls+='window.FACTLINK_SCROLL_TO = ' + parseInt(scrollto,10) + ';';
    }
    set_urls+='</script>';
    load_proxy_js = '<script src="' + STATIC_URL + '/proxy/scripts/proxy.js?' + Number(new Date()) + '"></script>';
	html = html.replace(/<\/head>/i, set_urls + load_proxy_js + '$&');
	return html;
}

function handleProxyRequest(res, site, scrollto, modus, form_hash){

  console.info('handleProxyRequest: modus: ' + modus);

  errorhandler = function(data) {
		console.error("Failed on: " + site);

		res.render('something_went_wrong', {
			layout: false,
			locals: {
				static_url: STATIC_URL,
				proxy_url: PROXY_URL,
				site: site
			}
		});
	};

  if (modus != "addToFact") {
    modus = "default";
  }

  // add protocol http:// if no protocol is defined:
	protocol_regex = new RegExp("^(?=.*://)");
	http_regex = new RegExp("^(?=http(s?)://)","i");
	if (http_regex.test(site) === false) {
	  if (protocol_regex.test(site) === false) {
	    site = "http://" + site;
	  }else {
	    errorhandler({});
	    return;
    }
	}

  console.info("Serving: " + site);

	var request = restler.get(site , form_hash);

	request.on('complete', function(data) {
		res.write( injectFactlinkJs(data, site, scrollto, modus) );
		res.end();
	});

	request.on("error", errorhandler);
}

/**
 *	Regular get requests
 */
server.get('/parse', function(req, res) {
	console.info("\nGET /parse");
	var site = req.query.url;
  var scrollto = req.query.scrollto;
  var modus = req.query.factlinkModus;

  console.info('pre handleProxyRequest: modus: ' + modus);

  handleProxyRequest(res, site, scrollto, modus, {});
});

/**
 * Handling forms
 * --------------
 * Forms get posted with a hidden 'factlinkFormUrl' field,
 * which is added by the proxy (in proxy.js). This is the 'action' URL which
 * the form normally submits its form to.
 *
 */
server.get('/submit', function(req, res) {
	var form_hash = req.query;

  var modus = form_hash.factlinkModus;
	delete form_hash.factlinkModus;

	var site = form_hash.factlinkFormUrl;
  delete form_hash.factlinkFormUrl;

  handleProxyRequest(res, site, undefined, modus, {'query':form_hash});
});

function create_url(base,query){
    var url;
    var key;
    url = base;
    var is_first = true;
    for( key in query ){
        if (query.hasOwnProperty(key)){
            if (is_first === true) {
                url += '?';
                is_first = false;
            } else {
                url += '&';
            }
            url += encodeURIComponent(key);
            url += '=';
            url += encodeURIComponent(query[key]);
        }
    }
    return url;
}

function render_page(pagename) {
  return function(req, res) {
      var header_url = create_url(PROXY_URL + "/header",req.query);
      var parse_url = create_url(PROXY_URL + "/parse",req.query);
	  res.render(pagename, {
		  layout: false,
		  locals: {
			  static_url: STATIC_URL,
			  proxy_url: PROXY_URL,
			  core_url: API_LOCATION,
			  page_url: req.query.url,
			  header_url: header_url,
			  parse_url: parse_url
		  }
	  });
  };
}

/**
 *	Render the header with the url bar
 */
server.get('/header', render_page('header'));
server.get('/', render_page('index'));

server.listen(PORT);
console.info('\nStarted Factlink proxy on port ' + PORT);<commit_msg>Better injection in CAPITAL head<commit_after>/*
 *	Factlink
 *	A simple proxy server which will proxy requests.
 *
 *	Used for implementing Factlink JavaScript on client-sites.
 */

/* jslint node: true */

// The actual server
var server = require('express').createServer();
server.configure(function (){
        server.set('views', __dirname + '/views');
});

/**
 *	We execute our requests using Restler
 *  because it follows redirects if needed
 */
var restler = require('restler');

var fs = require('fs');
config_path = process.env.CONFIG_PATH || '../config/';
global.config = require('./read_config').read_conf(config_path,fs,server.settings.env);

var PROXY_URL   = "http://"+global.config.proxy.hostname+':'+global.config.proxy.port;
var STATIC_URL  = "http://"+global.config['static'].hostname+':'+global.config['static'].port;

var API_LOCATION = global.config.core.hostname + ':'+global.config.core.port;
var LIB_LOCATION = global.config['static'].hostname +':'+global.config['static'].port + "/lib";

console.info(LIB_LOCATION);
console.info(STATIC_URL);

var PORT         = parseInt(global.config.proxy.port,10);

// Use Jade as templating engine
server.set('view engine', 'jade');

/**
 * Add base url and inject proxy.js, and return the proxied site
 */
function injectFactlinkJs(html_in,site, scrollto, modus){

	var html = html_in.replace(/<head[^>]*>/i, '$&<base href="' + site + '" />');
    var set_urls = '<script>'+
             'window.FACTLINK_PROXY_URL = "' + PROXY_URL + '";'+
             'window.FACTLINK_STATIC_URL = "' + STATIC_URL + '";'+
             'window.FACTLINK_API_LOCATION = "' + API_LOCATION + '";'+
             'window.FACTLINK_LIB_LOCATION = "' + LIB_LOCATION + '";'+
             'window.FACTLINK_MODUS = "' + modus + '";'+
             'window.FACTLINK_REAL_URL = "' + site + '";';
    if (scrollto !== undefined && !isNaN(parseInt(scrollto,10))){
        set_urls+='window.FACTLINK_SCROLL_TO = ' + parseInt(scrollto,10) + ';';
    }
    set_urls+='</script>';
    load_proxy_js = '<script src="' + STATIC_URL + '/proxy/scripts/proxy.js?' + Number(new Date()) + '"></script>';
	html = html.replace(/<\/head>/i, set_urls + load_proxy_js + '$&');
	return html;
}

function handleProxyRequest(res, site, scrollto, modus, form_hash){

  errorhandler = function(data) {
		console.error("Failed on: " + site);

		res.render('something_went_wrong', {
			layout: false,
			locals: {
				static_url: STATIC_URL,
				proxy_url: PROXY_URL,
				site: site
			}
		});
	};

  if (modus != "addToFact") {
    modus = "default";
  }

  // add protocol http:// if no protocol is defined:
	protocol_regex = new RegExp("^(?=.*://)");
	http_regex = new RegExp("^(?=http(s?)://)","i");
	if (http_regex.test(site) === false) {
	  if (protocol_regex.test(site) === false) {
	    site = "http://" + site;
	  }else {
	    errorhandler({});
	    return;
    }
	}

  console.info("Serving: " + site);

	var request = restler.get(site , form_hash);

	request.on('complete', function(data) {
		res.write( injectFactlinkJs(data, site, scrollto, modus) );
		res.end();
	});

	request.on("error", errorhandler);
}

/**
 *	Regular get requests
 */
server.get('/parse', function(req, res) {
	console.info("\nGET /parse");
	var site = req.query.url;
  var scrollto = req.query.scrollto;
  var modus = req.query.factlinkModus;

  handleProxyRequest(res, site, scrollto, modus, {});
});

/**
 * Handling forms
 * --------------
 * Forms get posted with a hidden 'factlinkFormUrl' field,
 * which is added by the proxy (in proxy.js). This is the 'action' URL which
 * the form normally submits its form to.
 *
 */
server.get('/submit', function(req, res) {
	var form_hash = req.query;

  var modus = form_hash.factlinkModus;
	delete form_hash.factlinkModus;

	var site = form_hash.factlinkFormUrl;
  delete form_hash.factlinkFormUrl;

  handleProxyRequest(res, site, undefined, modus, {'query':form_hash});
});

function create_url(base,query){
    var url;
    var key;
    url = base;
    var is_first = true;
    for( key in query ){
        if (query.hasOwnProperty(key)){
            if (is_first === true) {
                url += '?';
                is_first = false;
            } else {
                url += '&';
            }
            url += encodeURIComponent(key);
            url += '=';
            url += encodeURIComponent(query[key]);
        }
    }
    return url;
}

function render_page(pagename) {
  return function(req, res) {
      var header_url = create_url(PROXY_URL + "/header",req.query);
      var parse_url = create_url(PROXY_URL + "/parse",req.query);
	  res.render(pagename, {
		  layout: false,
		  locals: {
			  static_url: STATIC_URL,
			  proxy_url: PROXY_URL,
			  core_url: API_LOCATION,
			  page_url: req.query.url,
			  header_url: header_url,
			  parse_url: parse_url
		  }
	  });
  };
}

/**
 *	Render the header with the url bar
 */
server.get('/header', render_page('header'));
server.get('/', render_page('index'));

server.listen(PORT);
console.info('\nStarted Factlink proxy on port ' + PORT);<|endoftext|>


<commit_before>// Survex 3d file mangler
const fs = require('fs');

function Svx3dEditor ( dataStream ) {

	var source    = new Buffer( dataStream );  // file data as arrrayBuffer
	var pos       = 0;	         // file position

	// read file header
	readLF(); // Survex 3D Image File
	var version   = readLF(); // 3d version
	var title     = readLF(); // Title
	readLF(); // Date

	console.log( "title: ", title) ;

	this.handleVx( source, pos, Number( version.charAt( 1 ) ) );

	return;

	function readLF () { // read until Line feed

		var bytes = new Uint8Array( source, 0 );

		var lfString = [];
		var b;

		do {

			b = bytes[ pos++ ];
			lfString.push( b );

		} while ( b != 0x0a && b != 0x00 )

		var s = String.fromCharCode.apply( null, lfString ).trim();

		console.log( s  );

		return s;
	}
}

Svx3dEditor.prototype.constructor = Svx3dEditor;

Svx3dEditor.prototype.handleVx = function ( source, pos, version ) {

	var cmd         = [];
	var legs        = [];
	var label       = "";
	var readLabel;
	var fileFlags   = 0;

	var data       = new Uint8Array( source, 0 );
	var dataLength = data.length;
	var i;

	// init cmd handler table withh  error handler for unsupported records or invalid records

	for ( i = 0; i < 256; i++ ) {

		cmd[ i ] = function ( e ) { console.log ( 'unhandled command: ', e.toString( 16 ) ); return false; };

	}

	if ( version === 8 ) {
		// v8 dispatch table start

		cmd[ 0x00 ] = cmd_STYLE;
		cmd[ 0x01 ] = cmd_STYLE;
		cmd[ 0x02 ] = cmd_STYLE;
		cmd[ 0x03 ] = cmd_STYLE;
		cmd[ 0x04 ] = cmd_STYLE;

		cmd[ 0x0f ] = cmd_MOVE;
		cmd[ 0x10 ] = cmd_DATE_NODATE;
		cmd[ 0x11 ] = cmd_DATEV8_1;
		cmd[ 0x12 ] = cmd_DATEV8_2;
		cmd[ 0x13 ] = cmd_DATEV8_3;

		cmd[ 0x1F ] = cmd_ERROR;

		cmd[ 0x30 ] = cmd_XSECT16;
		cmd[ 0x31 ] = cmd_XSECT16;

		cmd[ 0x32 ] = cmd_XSECT32;
		cmd[ 0x33 ] = cmd_XSECT32;

		for ( i = 0x40; i < 0x80; i++ ) {

			cmd[ i ] = cmd_LINE;

		}

		for ( i = 0x80; i < 0x100; i++ ) {

			cmd[ i ] = cmd_LABEL;

		}

		// dispatch table end

		readLabel = readLabelV8;

		// v8 file wide flags after header
		fileFlags = data[ pos++ ];

	} else {

		// dispatch table for v7 format

		for ( i = 0x01; i < 0x0f; i++ ) {

			cmd[ i ] = cmd_TRIM_PLUS;

		}

		cmd[ 0x0f ] = cmd_MOVE;

		for ( i = 0x10; i < 0x20; i++ ) {

			cmd[ i ] = cmd_TRIM;

		}

		cmd[ 0x00 ] = cmd_STOP;
		cmd[ 0x20 ] = cmd_DATE_V7;
		cmd[ 0x21 ] = cmd_DATE2_V7;
		cmd[ 0x24 ] = cmd_DATE_NODATE;
		cmd[ 0x22 ] = cmd_ERROR;

		cmd[ 0x30 ] = cmd_XSECT16;
		cmd[ 0x31 ] = cmd_XSECT16;

		cmd[ 0x32 ] = cmd_XSECT32;
		cmd[ 0x33 ] = cmd_XSECT32;

		for ( i = 0x40; i < 0x80; i++ ) {

			cmd[ i ] = cmd_LABEL;

		}

		for ( i = 0x80; i < 0xc0; i++ ) {

			cmd[ i ] = cmd_LINE;

		}
		// dispatch table end

		readLabel = readLabelV7;

	}

	if ( version === 6 ) {

		cmd[ 0x20 ] = cmd_DATE_V4;
		cmd[ 0x21 ] = cmd_DATE2_V4;

	}

	// common record iterator
	// loop though data, handling record types as required.

	var endHeader = pos; // temp fix for header gen

	var fd;
	var start = pos;
	var move = false;
	var lastMove = 0;

	var cave;
	var caves = {};

	while ( pos < dataLength ) {

		start = pos;

		if ( cmd[ data[ pos ] ]( data[ pos++ ] ) ) {

			caveName = label.split( "." )[ 1 ];

			// open a new file for this cave
//			console.log( "s", label.split( "." )[1] );

			if ( caveName !== undefined ) {

				if ( caves[ caveName ] === undefined ) {

			//		console.log("cave: ", cave );

					fd = writeHeader( caveName + ".3d", caveName );

					caves[ caveName ] = {
						fd: fd,
						lastLabel: null
					};

				} else {

					fd = caves[ caveName ].fd;

				}

				cave = caves[ caveName ];

			}

			if ( move ) {

				move = false;
				lastMove = start;

			} else {

				if ( lastMove ) {

					start = lastMove;
					lastMove = 0;

				}

				if ( cave ) {

					//	console.log(" write @ ", start, " len ", pos - start );
					cave.lastLabel = label;

					fs.writeSync( fd, source, start, pos - start );

				}

				lastMove = 0;

			}

		}

	}

	// close all cave files

	for ( name in caves ) {

			fs.closeSync( caves[ name ].fd );

	}

	console.log ( "l : ", dataLength, " pos: ", pos, " start: ", start );
	return;

	function writeHeader( name, title ) {

		var fd = fs.openSync( name, 'w' );
		var lf = new Buffer( [ 0x0a ] );

		fs.writeSync( fd, source, 0, endHeader );
/*
		fs.writeSync( fd, "Survex 3D Image File");
		fs.writeSync( fd, lf );

		fs.writeSync( fd, "v8");
		fs.writeSync( fd, lf );

		fs.writeSync( fd, title );
		fs.writeSync( fd, lf );

		fs.writeSync( fd, "@1371300355" );
		fs.writeSync( fd, lf );

		fs.writeSync( fd, new Buffer( [ 0x00 ] ) );
*/
		return fd;
	}

	function readLabelV7 () {
		// find length of label and read label = v3 - v7 .3d format

		var len = 0;
		var l;

		switch ( data[ pos ] ) {

			case 0xfe:

				l = new DataView( source, pos );

				len = l.getUint16( 0, true ) + data[ pos ];
				pos += 2;

				break;

			case 0xff:

				l = new DataView( source, pos );

				len = l.getUint32( 0, true );
				pos +=4;

				break;

			default:

				len = data[ pos++ ];
		}

		if ( len === 0 ) return false; // no label

		var db = [];

		for ( var i = 0; i < len; i++ ) {

			db.push( data[ pos++ ] );

		}

		label = label + String.fromCharCode.apply( null, db  );

		return true;

	}

	function readLabelV8 ( flags ) {

		if ( flags & 0x20 )  return false; // no label change

		var oldCaveName = label.split( "." )[1];
		var oldLabel    = label;

		var startOfCmd = pos - 1;

		var b = data[ pos++ ];
		var add = 0;
		var del = 0;

		if ( b !== 0 ) {

			// handle 4b= bit del/add codes
			del = b >> 4;   // left most 4 bits
			add = b & 0x0f; // right most 4 bits

		} else {

			// handle 8 bit and 32 bit del/add codes
			b = data[ pos++ ];

			if ( b !== 0xff ) {

				del = b;

			} else {

				var l = new DataView( source, pos );

				del = l.getUint32( 0, true );
				pos +=4;

			}

			b = data[ pos++ ];

			if ( b !== 0xff ) {

				add = b;

			} else {

				var l = new DataView( source, pos );

				add = l.getUint32( 0, true );
				pos +=4;

			}
		}

		if ( add === 0 && del === 0 ) return;

		if ( del ) label = label.slice( 0, -del );

		if ( add ) {

			var db = [];

			for ( var i = 0; i < add; i++ ) {

				db.push( data[pos++] );

			}

			label = label + String.fromCharCode.apply( null, db );

		}

		var caveName = label.split( "." )[ 1 ];

		if ( caves[ caveName ] === undefined ) {

			var cmd = data[ start ];
			var b1  = data[ start + 1 ];
			var b2  = data[ start + 2 ];
			var b3  = data[ start + 3 ];
			var b4  = data[ start + 4 ];

			if ( b1 === 0 ) { // 8 bit encoding (ignoreing 32bit encoding for now)

				source[ start + 2 ] = 0; // patch last label to remove deletion of previous label
				console.log( " fixed ", caveName, " - ", data[ start + 2 ] );
			}

			console.log( "fl: ", cmd, "[ ", b1, " - ", b2, " - ", b3 , " - ", b4, "]" );

		} else if ( add && caveName != oldCaveName ) {

			var cave = caves[ caveName ];

			//console.log( "XXX: ", cave.lastLabel );

		//	console.log(" oc: ", oldCaveName, " nc: ", caveName );

			// insert fake record to correct label buffer

			var newCmd = [];

			newCmd.push( 0xA0 ); // anonymouus label
			newCmd.push( 0x00 );
			newCmd.push( cave.lastLabel.length );
			newCmd.push( oldLabel.length );

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

				newCmd.push( 0x58 );

			}

			// fake coordinates

			for ( var i = 0; i < 12; i++ ) {

				newCmd.push( 0x00 );

			}

			fs.writeSync( cave.fd, new Buffer( newCmd ), 0, newCmd.length );

		}

		return true;

	}

	function cmd_STOP ( c ) {

		if ( label ) label = "";

		return true;

	}

	function cmd_TRIM_PLUS ( c ) { // v7 and previous

		label = label.slice( 0, -16 );

		if ( label.charAt( label.length - 1 ) == ".") label = label.slice( 0, -1 ); // strip trailing "."

		var parts = label.split( "." );

		parts.splice( -( c ) );
		label = parts.join( "." );

		if ( label ) label = label + ".";

		return true;

	}

	function cmd_TRIM ( c ) {  // v7 and previous

		var trim = c - 15;

		label = label.slice( 0, -trim );

		return true;

	}

	function cmd_DATE_V4 ( c ) {

		pos += 4;

		return true;

	}

	function cmd_DATE_V7 ( c ) {

		pos += 2;

		return true;

	}

	function cmd_DATE2_V4 ( c ) {

		pos += 8;

		return true;

	}

	function cmd_DATE2_V7 ( c ) {

		pos += 3;

		return true;

	}

	function cmd_STYLE ( c ) {

		return true;

	}

	function cmd_DATEV8_1 ( c ) {

		pos += 2;

		return true;

	}

	function cmd_DATEV8_2 ( c ) {

		pos += 3;

		return true;

	}

	function cmd_DATEV8_3 ( c ) {

		pos += 4;

		return true;
	}

	function cmd_DATE_NODATE ( c ) {

		return true;

	}

	function cmd_LINE ( c ) {

		var flags = c & 0x3f;

		readLabel( flags );

		readCoordinates( flags );

		return true;

	}

	function cmd_MOVE ( c ) {

		readCoordinates( 0x00 )
		move = true;
		return true;

	}

	function cmd_ERROR ( c ) {

		pos += 20;

		return true;

	}

	function cmd_LABEL ( c ) {

		var flags = c & 0x7f;

		readLabel( 0 );

		readCoordinates( flags );

/*
		if ( c & 0x04 ) {

			var station = label.split( "." );

			// get survey path by removing last component of station name
			station.pop();

		}
*/
		return true;

	}

	function cmd_XSECT16 ( c ) {

		var flags = c & 0x01;

		readLabel( flags );

		pos += 8;

		return commonXSECT( flags );

	}

	function cmd_XSECT32 ( c ) {

		var flags = c & 0x01;

		readLabel( flags );

		pos += 16;

		return commonXSECT( flags );

	}

	function commonXSECT( flags ) {

//		var station = label.split( "." );
//		station.pop();

		return true;

	}

	function readCoordinates ( flags ) {

		pos += 12;

		return true;

	}

}

var buffer = fs.readFileSync( "Peak_Master.3d");

var e = new Svx3dEditor( buffer );

// EOF<commit_msg>wip .3d disector<commit_after>// Survex 3d file mangler
const fs = require('fs');

function Svx3dEditor ( dataStream ) {

	var source    = new Buffer( dataStream );  // file data as RW arrrayBuffer
	var pos       = 0;	         // file position

	// read file header
	readLF(); // Survex 3D Image File
	var version   = readLF(); // 3d version
	var title     = readLF(); // Title
	readLF(); // Date

	console.log( "title: ", title) ;

	this.handleVx( source, pos, Number( version.charAt( 1 ) ) );

	return;

	function readLF () { // read until Line feed

		var bytes = new Uint8Array( source, 0 );

		var lfString = [];
		var b;

		do {

			b = bytes[ pos++ ];
			lfString.push( b );

		} while ( b != 0x0a && b != 0x00 )

		var s = String.fromCharCode.apply( null, lfString ).trim();

		console.log( s  );

		return s;
	}
}

Svx3dEditor.prototype.constructor = Svx3dEditor;

Svx3dEditor.prototype.handleVx = function ( source, pos, version ) {

	var cmd         = [];
	var legs        = [];
	var label       = "";
	var readLabel;
	var fileFlags   = 0;

	var data       = new Uint8Array( source, 0 );
	var dataLength = data.length;
	var i;

	// init cmd handler table withh  error handler for unsupported records or invalid records

	for ( i = 0; i < 256; i++ ) {

		cmd[ i ] = function ( e ) { console.log ( 'unhandled command: ', e.toString( 16 ) ); return false; };

	}

	if ( version === 8 ) {
		// v8 dispatch table start

		cmd[ 0x00 ] = cmd_STYLE;
		cmd[ 0x01 ] = cmd_STYLE;
		cmd[ 0x02 ] = cmd_STYLE;
		cmd[ 0x03 ] = cmd_STYLE;
		cmd[ 0x04 ] = cmd_STYLE;

		cmd[ 0x0f ] = cmd_MOVE;
		cmd[ 0x10 ] = cmd_DATE_NODATE;
		cmd[ 0x11 ] = cmd_DATEV8_1;
		cmd[ 0x12 ] = cmd_DATEV8_2;
		cmd[ 0x13 ] = cmd_DATEV8_3;

		cmd[ 0x1F ] = cmd_ERROR;

		cmd[ 0x30 ] = cmd_XSECT16;
		cmd[ 0x31 ] = cmd_XSECT16;

		cmd[ 0x32 ] = cmd_XSECT32;
		cmd[ 0x33 ] = cmd_XSECT32;

		for ( i = 0x40; i < 0x80; i++ ) {

			cmd[ i ] = cmd_LINE;

		}

		for ( i = 0x80; i < 0x100; i++ ) {

			cmd[ i ] = cmd_LABEL;

		}

		// dispatch table end

		readLabel = readLabelV8;

		// v8 file wide flags after header
		fileFlags = data[ pos++ ];

	} else {

		// dispatch table for v7 format

		for ( i = 0x01; i < 0x0f; i++ ) {

			cmd[ i ] = cmd_TRIM_PLUS;

		}

		cmd[ 0x0f ] = cmd_MOVE;

		for ( i = 0x10; i < 0x20; i++ ) {

			cmd[ i ] = cmd_TRIM;

		}

		cmd[ 0x00 ] = cmd_STOP;
		cmd[ 0x20 ] = cmd_DATE_V7;
		cmd[ 0x21 ] = cmd_DATE2_V7;
		cmd[ 0x24 ] = cmd_DATE_NODATE;
		cmd[ 0x22 ] = cmd_ERROR;

		cmd[ 0x30 ] = cmd_XSECT16;
		cmd[ 0x31 ] = cmd_XSECT16;

		cmd[ 0x32 ] = cmd_XSECT32;
		cmd[ 0x33 ] = cmd_XSECT32;

		for ( i = 0x40; i < 0x80; i++ ) {

			cmd[ i ] = cmd_LABEL;

		}

		for ( i = 0x80; i < 0xc0; i++ ) {

			cmd[ i ] = cmd_LINE;

		}
		// dispatch table end

		readLabel = readLabelV7;

	}

	if ( version === 6 ) {

		cmd[ 0x20 ] = cmd_DATE_V4;
		cmd[ 0x21 ] = cmd_DATE2_V4;

	}

	// common record iterator
	// loop though data, handling record types as required.

	var fd;
	var start = pos;
	var move = false;
	var lastMove = 0;

	var cave;
	var caves = {};
	var newCmd;

	while ( pos < dataLength ) {

		start = pos;

		newCmd = null;

		if ( cmd[ data[ pos ] ]( data[ pos++ ] ) ) {

			caveName = label.split( "." )[ 1 ];

			if ( caveName !== undefined ) {

				if ( caves[ caveName ] === undefined ) {

					fd = writeHeader( caveName + ".3d", caveName );

					caves[ caveName ] = {
						fd: fd,
						lastLabel: null
					};

				}

			}

			cave = caves[ caveName ];

			if ( move ) {

				// defer move until we know which file it is destined for
				move = false;
				lastMove = start;

			} else {

				if ( cave ) {

					if ( lastMove ) {

						// write deferred move
						fs.writeSync( cave.fd, source, lastMove, start - lastMove );
						lastMove = 0;

					}
					//	console.log(" write @ ", start, " len ", pos - start );
					cave.lastLabel = label;

					if ( newCmd === null ) {

						fs.writeSync( cave.fd, source, start, pos - start );

					} else {

						// replace command with new command to correct initial label
						fs.writeSync( cave.fd, new Buffer( newCmd ), 0, newCmd.length );	// new LINE with new LABEL

					}

				}

			}

		}

	}

	// close all cave files

	for ( name in caves ) {

		cave = caves[ name ];

		newCmd = [];

		newCmd.push( 0xA0 ); // anonymous label
		newCmd.push( 0x00 );
		newCmd.push( cave.lastLabel.length );
		newCmd.push( 0x00 );

		// fake coordinates

		for ( var i = 0; i < 6; i++ ) {

			newCmd.push( 0xCA );
			newCmd.push( 0xFE );

		}

		fs.writeSync( cave.fd, new Buffer( newCmd ), 0, newCmd.length );

		fs.writeSync( cave.fd, new Buffer( [ 0x00 ] ), 0, 1 ); // style = NORMAL
		fs.writeSync( cave.fd, new Buffer( [ 0x00 ] ), 0, 1 ); // EOF

		fs.closeSync( cave.fd );

	}

	console.log ( "END l : ", dataLength, " pos: ", pos, " start: ", start );

	return;

	function writeHeader( name, title ) {

		var fd = fs.openSync( name, 'w' );
		var lf = new Buffer( [ 0x0a ] );

		fs.writeSync( fd, "Survex 3D Image File\n");
		fs.writeSync( fd, "v8\n");
		fs.writeSync( fd, title + "\n" );
		fs.writeSync( fd, "@1371300355\n" );

		fs.writeSync( fd, new Buffer( [ 0x00 ] ), 0, 1 );

		return fd;
	}

	function readLabelV7 () {
		// find length of label and read label = v3 - v7 .3d format

		var len = 0;
		var l;

		switch ( data[ pos ] ) {

			case 0xfe:

				l = new DataView( source, pos );

				len = l.getUint16( 0, true ) + data[ pos ];
				pos += 2;

				break;

			case 0xff:

				l = new DataView( source, pos );

				len = l.getUint32( 0, true );
				pos +=4;

				break;

			default:

				len = data[ pos++ ];
		}

		if ( len === 0 ) return false; // no label

		var db = [];

		for ( var i = 0; i < len; i++ ) {

			db.push( data[ pos++ ] );

		}

		label = label + String.fromCharCode.apply( null, db  );

		return true;

	}

	function readLabelV8 ( flags ) {

		if ( flags & 0x20 )  return false; // no label change

		var oldCaveName = label.split( "." )[1];
		var oldLabel    = label;

		var startOfCmd = pos - 1;

		var b = data[ pos++ ];
		var add = 0;
		var del = 0;
		var i;

		if ( b !== 0 ) {

			// handle 4b= bit del/add codes
			del = b >> 4;   // left most 4 bits
			add = b & 0x0f; // right most 4 bits

		} else {

			// handle 8 bit and 32 bit del/add codes
			b = data[ pos++ ];

			if ( b !== 0xff ) {

				del = b;

			} else {

				var l = new DataView( source, pos );

				del = l.getUint32( 0, true );
				pos +=4;

			}

			b = data[ pos++ ];

			if ( b !== 0xff ) {

				add = b;

			} else {

				var l = new DataView( source, pos );

				add = l.getUint32( 0, true );
				pos +=4;

			}
		}

		if ( add === 0 && del === 0 ) return;

		if ( del ) label = label.slice( 0, -del );

		if ( add ) {

			var db = [];

			for ( i = 0; i < add; i++ ) {

				db.push( data[pos++] );

			}

			label = label + String.fromCharCode.apply( null, db );

		}

		var caveName = label.split( "." )[ 1 ];

		if ( caves[ caveName ] === undefined ) {

			// insert new label and add coordinates
			newCmd = [];

			newCmd.push( data[ startOfCmd ] );
			newCmd.push( 0x00 ); 			// 4 bit coding
			newCmd.push( 0x00 );			// delete label count
			newCmd.push( label.length );	// add label count

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

				newCmd.push(  label.charCodeAt( i ) );

			}

			// copy xyz coordinates following the orignal command

			for ( i = 0; i < 12; i++ ) {

				newCmd.push( data[ pos + i ] );

			}

		} else if ( add && caveName != oldCaveName ) {

			var cave = caves[ caveName ];

		//	console.log(" oc: ", oldCaveName, " nc: ", caveName );

			// insert fake record to correct label buffer

			newCmd = [];

			newCmd.push( 0xA0 ); // anonymouus label
			newCmd.push( 0x00 );
			newCmd.push( cave.lastLabel.length );
			newCmd.push( oldLabel.length );

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

				newCmd.push(  oldLabel.charCodeAt( i ) );

			}

			// fake coordinates

			for ( i = 0; i < 6; i++ ) {

				newCmd.push( 0xDE );
				newCmd.push( 0xAD );

			}

			fs.writeSync( cave.fd, new Buffer( newCmd ), 0, newCmd.length );

			newCmd = null; // don't replace current command'

		}

		return true;

	}

	function cmd_STOP ( c ) {

		if ( label ) label = "";

		return true;

	}

	function cmd_TRIM_PLUS ( c ) { // v7 and previous

		label = label.slice( 0, -16 );

		if ( label.charAt( label.length - 1 ) == ".") label = label.slice( 0, -1 ); // strip trailing "."

		var parts = label.split( "." );

		parts.splice( -( c ) );
		label = parts.join( "." );

		if ( label ) label = label + ".";

		return true;

	}

	function cmd_TRIM ( c ) {  // v7 and previous

		var trim = c - 15;

		label = label.slice( 0, -trim );

		return true;

	}

	function cmd_DATE_V4 ( c ) {

		pos += 4;

		return true;

	}

	function cmd_DATE_V7 ( c ) {

		pos += 2;

		return true;

	}

	function cmd_DATE2_V4 ( c ) {

		pos += 8;

		return true;

	}

	function cmd_DATE2_V7 ( c ) {

		pos += 3;

		return true;

	}

	function cmd_STYLE ( c ) {

		return true;

	}

	function cmd_DATEV8_1 ( c ) {

		pos += 2;

		return true;

	}

	function cmd_DATEV8_2 ( c ) {

		pos += 3;

		return true;

	}

	function cmd_DATEV8_3 ( c ) {

		pos += 4;

		return true;
	}

	function cmd_DATE_NODATE ( c ) {

		return true;

	}

	function cmd_LINE ( c ) {

		var flags = c & 0x3f;

		readLabel( flags );

		readCoordinates( flags );

		return true;

	}

	function cmd_MOVE ( c ) {

		readCoordinates( 0x00 )
		move = true;
		return true;

	}

	function cmd_ERROR ( c ) {

		pos += 20;

		return true;

	}

	function cmd_LABEL ( c ) {

		var flags = c & 0x7f;

		readLabel( 0 );

		readCoordinates( flags );

/*
		if ( c & 0x04 ) {

			var station = label.split( "." );

			// get survey path by removing last component of station name
			station.pop();

		}
*/
		return true;

	}

	function cmd_XSECT16 ( c ) {

		var flags = c & 0x01;

		readLabel( flags );

		pos += 8;

		return commonXSECT( flags );

	}

	function cmd_XSECT32 ( c ) {

		var flags = c & 0x01;

		readLabel( flags );

		pos += 16;

		return commonXSECT( flags );

	}

	function commonXSECT( flags ) {

//		var station = label.split( "." );
//		station.pop();

		return true;

	}

	function readCoordinates ( flags ) {

		pos += 12;

		return true;

	}

}

var buffer = fs.readFileSync( "Peak_Master.3d");

var e = new Svx3dEditor( buffer );

// EOF<|endoftext|>