2 * Copyright 2015-present Greg Hurrell. All rights reserved.
3 * Licensed under the terms of the MIT license.
10 import React from 'react';
11 import convert from './convert';
13 const DIGITS = '0123456789abcdef';
16 * Convert from canonical (hexadecimal) value to `base`.
18 function fromValue(value: string, base: number): string {
22 return convert(value, 16, base);
26 * Convert from `base` value to canonical (hexadecimal) value.
28 function toValue(value: string, base: number): string {
32 return convert(value, base, 16);
35 export default class Field extends React.Component {
37 base: React.PropTypes.number,
38 onValueChange: React.PropTypes.func.required,
39 value: React.PropTypes.string.required,
41 static defaultProps = {
47 if (props.base < 2 || props.base > DIGITS.length) {
49 `base prop must be between 2..${DIGITS.length}`
54 _isValid(value: string): boolean {
55 const validator = new RegExp(
56 `^[${DIGITS.slice(0, this.props.base)}]*$`
58 return validator.test(value.trim().toLowerCase());
61 _onChange = event => {
62 const value = event.currentTarget.value;
63 if (this._isValid(value)) {
64 this.props.onValueChange(toValue(value, this.props.base));
71 onChange={this._onChange}
73 value={fromValue(this.props.value, this.props.base)}