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';
12 import cx from 'classnames';
18 export const ValuePropType = React.PropTypes.shape({
19 base: React.PropTypes.number,
20 value: React.PropTypes.string,
23 const DIGITS = '0123456789abcdefghijklmnopqrstuvwxyz';
26 * Convert from `value` to `base`.
28 function fromValue(value: ?Value, base: number): string {
31 } else if (value.base === base) {
34 return convert(value.value, value.base, base);
37 export default class Field extends React.Component {
39 base: React.PropTypes.number,
40 onValueChange: React.PropTypes.func.required,
43 static defaultProps = {
49 if (props.base < 2 || props.base > DIGITS.length) {
51 `base prop must be between 2..${DIGITS.length}`
54 this.state = {copySucceeded: false};
57 _isValid(value: string): boolean {
58 const validator = new RegExp(
59 `^[${DIGITS.slice(0, this.props.base)}]*$`
61 return validator.test(value.trim().toLowerCase());
64 _onChange = event => {
65 const value = event.currentTarget.value;
66 if (this._isValid(value)) {
67 this.props.onValueChange({
68 base: this.props.base,
75 React.findDOMNode(this._input).select();
77 // May throw a SecurityError.
80 copySucceeded: document.execCommand('copy'),
82 setTimeout(() => this.setState({copySucceeded: false}), 750);
83 } catch(error) { // eslint-disable-line no-empty
85 this.setState({copySucceeded: false});
90 // Would check `document.queryCommandSupported('copy')` here, but that
92 // - https://code.google.com/p/chromium/issues/detail?id=476508
93 // - https://github.com/w3c/clipboard-apis/issues/4
96 className="hextrapolate-copy"
97 onClick={this._onCopy}
98 title="Copy to Clipboard">
105 const classNames = cx({
106 'hextrapolate-copy-status': true,
107 'hextrapolate-copy-success': this.state.copySucceeded,
109 return <span className={classNames}>✓</span>;
113 React.findDOMNode(this._input).focus();
118 <span className="hextrapolate-field">
120 onChange={this._onChange}
121 ref={ref => this._input = ref}
123 value={fromValue(this.props.value, this.props.base)}