aboutsummaryrefslogtreecommitdiffstats
path: root/ui/app/components/send/currency-display.js
blob: 332d722ec73499432eefb89a27cd440d44aad50d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const Component = require('react').Component
const h = require('react-hyperscript')
const inherits = require('util').inherits
const Identicon = require('../identicon')
const { conversionUtil } = require('../../conversion-util')

module.exports = CurrencyDisplay

inherits(CurrencyDisplay, Component)
function CurrencyDisplay () {
  Component.call(this)

  this.state = {
    minWidth: null,
    currentScrollWidth: null,
  }
}

function isValidInput (text) {
  const re = /^([1-9]\d*|0)(\.|\.\d*)?$/
  return re.test(text)
}

function resetCaretIfPastEnd (value, event) {
  const caretPosition = event.target.selectionStart

  if (caretPosition > value.length) {
    event.target.setSelectionRange(value.length, value.length)
  }
}

CurrencyDisplay.prototype.render = function () {
  const {
    className,
    primaryCurrency,
    convertedCurrency,
    value = '',
    placeholder = '0',
    conversionRate,
    convertedPrefix = '',
    readOnly = false,
    handleChange,
  } = this.props
  const { minWidth } = this.state

  const convertedValue = conversionUtil(value, {
    fromNumericBase: 'dec',
    fromCurrency: primaryCurrency,
    toCurrency: convertedCurrency,
    conversionRate,
  })

  return h('div.currency-display', {
    className,
  }, [

    h('div.currency-display__primary-row', [

      h('div.currency-display__input-wrapper', [

        h('input.currency-display__input', {
          value: `${value} ${primaryCurrency}`,
          placeholder: `${0} ${primaryCurrency}`,
          readOnly,
          onChange: (event) => {
            let newValue = event.target.value.split(' ')[0]

            if (newValue === '') {
              handleChange('0')
            }
            else if (newValue.match(/^0[1-9]$/)) {
              handleChange(newValue.match(/[1-9]/)[0])
            }
            else if (newValue && !isValidInput(newValue)) {
              event.preventDefault()
            }
            else {
              handleChange(newValue)
            }
          },
          onKeyUp: event => resetCaretIfPastEnd(value, event),
          onClick: event => resetCaretIfPastEnd(value, event),
        }),

      ]),

    ]),

    h('div.currency-display__converted-value', {}, `${convertedPrefix}${convertedValue} ${convertedCurrency}`),

  ])
    
}