@commercetools-uikit/money-input 0.0.0-canary-2021830134526

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 commercetools GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,275 @@
1
+ <!-- THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -->
2
+ <!-- This file is created by the `yarn generate-readme` script. -->
3
+
4
+ # MoneyInput
5
+
6
+ ## Description
7
+
8
+ A controlled input component for money values with validation states.
9
+
10
+ ## Installation
11
+
12
+ ```
13
+ yarn add @commercetools-uikit/money-input
14
+ ```
15
+
16
+ ```
17
+ npm --save install @commercetools-uikit/money-input
18
+ ```
19
+
20
+ Additionally install the peer dependencies (if not present)
21
+
22
+ ```
23
+ yarn add react react-dom react-intl
24
+ ```
25
+
26
+ ```
27
+ npm --save install react react-dom react-intl
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ```jsx
33
+ import MoneyInput from '@commercetools-uikit/money-input';
34
+
35
+ const Example = () => (
36
+ <MoneyInput
37
+ value={{ amount: '1.00', currencyCode: 'EUR' }}
38
+ onChange={
39
+ (/** event */) => {
40
+ // alert(event.target.name, event.target.value)
41
+ }
42
+ }
43
+ currencies={['EUR', 'USD']}
44
+ />
45
+ );
46
+
47
+ export default Example;
48
+ ```
49
+
50
+ ## Properties
51
+
52
+ | Props | Type | Required | Default | Description |
53
+ | ----------------------- | -------------------------------------------------------------------------------------------------- | :------: | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
54
+ | `id` | `string` | | | Used as HTML id property. An id is auto-generated when it is not specified. |
55
+ | `autoComplete` | `string` | | | Used as HTML `autocomplete` property |
56
+ | `name` | `string` | | | The prefix used to create a HTML `name` property for the amount input field (`${name}.amount`) and the currency dropdown (`${name}.currencyCode`). |
57
+ | `value` | `object` | ✅ | | Value of the input. Consists of the currency code and an amount. `amount` is a string representing the amount. A dot has to be used as the decimal separator. |
58
+ | `value.amount` | `string` | ✅ | | |
59
+ | `value.currencyCode` | `string` | ✅ | | |
60
+ | `currencies` | Array of `string` | | `[]` | List of possible currencies. When not provided or empty, the component renders a label with the value's currency instead of a dropdown. |
61
+ | `placeholder` | `string` | | | Placeholder text for the input |
62
+ | `onBlur` | `func` | | | Called when input is blurred |
63
+ | `onFocus` | `func` | | | Called when input is focused |
64
+ | `isDisabled` | `bool` | | | Indicates that the input cannot be modified (e.g not authorized, or changes currently saving). |
65
+ | `isReadOnly` | `bool` | | | Indicates that the field is displaying read-only content |
66
+ | `isAutofocussed` | `bool` | | | Focus the input on initial render |
67
+ | `onChange` | `custom` | | | Called with the event of the input or dropdown when either the currency or the amount have changed.&#xA;<br />&#xA;Signature: `(event) => void` |
68
+ | `menuPortalTarget` | `SafeHTMLElement` | | | Dom element to portal the currency select menu to |
69
+ | `menuPortalZIndex` | `number` | | `1` | z-index value for the currency select menu portal |
70
+ | `menuShouldBlockScroll` | `bool` | | | whether the menu should block scroll while open |
71
+ | `hasError` | `bool` | | | Indicates that input has errors |
72
+ | `hasWarning` | `bool` | | | Control to indicate on the input if there are selected values that are potentially invalid |
73
+ | `hasHighPrecisionBadge` | `bool` | | | Shows high precision badge in case current value uses high precision. |
74
+ | `horizontalConstraint` | `enum`<br/>Possible values:<br/>`3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 'scale', 'auto'` | | `'scale'` | Horizontal size limit of the input fields. |
75
+
76
+ ## Static methods
77
+
78
+ ### `MoneyInput.convertToMoneyValue`
79
+
80
+ The `convertToMoneyValue` function will turn a MoneyInput value into a [`MoneyValue`](https://docs.commercetools.com/http-api-types#money) the API can handle. It automatically converts to `centPrecision` or `highPrecision` types when the number of supplied fraction digits exceeds the number of fraction digits used by the currency.
81
+ If you want to forbid `highPrecision`, then the form's validation needs to add an error when it sees a `highPrecision` price. See example below.
82
+
83
+ Here are examples of `centPrecision` and `highPrecision` prices.
84
+
85
+ ```js
86
+ // 42.00 €
87
+ {
88
+ "type": "centPrecision",
89
+ "currencyCode": "EUR",
90
+ "centAmount": 4200,
91
+ "fractionDigits": 2
92
+ }
93
+ ```
94
+
95
+ ```js
96
+ // 0.0123456 €
97
+ {
98
+ "type": "highPrecision",
99
+ "currencyCode": "EUR",
100
+ "centAmount": 1,
101
+ "preciseAmount": 123456,
102
+ "fractionDigits": 7
103
+ }
104
+ ```
105
+
106
+ ### `MoneyInput.parseMoneyValue`
107
+
108
+ The `parseMoneyValue` function will turn a [`MoneyValue`](https://docs.commercetools.com/http-api-types#money) into a value the MoneyInput component can handle `({ amount, currencyCode })`.
109
+
110
+ ### `MoneyInput.isEmpty`
111
+
112
+ The `isEmpty` function will return `true` when the passed `MoneyInput` value is empty (either has no currency or no amount, or does not exist at all).
113
+
114
+ ```js
115
+ MoneyInput.isEmpty({ amount: '', currencyCode: 'EUR' }); // -> true
116
+ MoneyInput.isEmpty({ amount: '5', currencyCode: '' }); // -> true
117
+ MoneyInput.isEmpty(); // -> true
118
+
119
+ MoneyInput.isEmpty({ amount: '5', currencyCode: 'EUR' }); // -> false
120
+ ```
121
+
122
+ ### `MoneyInput.isTouched`
123
+
124
+ The `isTouched` function will return `true` when all input elements were touched (currency dropdown and amount input).
125
+
126
+ ```js
127
+ MoneyInput.isTouched({ amount: true, currencyCode: true }); // -> true
128
+
129
+ MoneyInput.isTouched({ amount: true }); // -> false
130
+ MoneyInput.isTouched({ currencyCode: true }); // -> false
131
+ MoneyInput.isTouched({ amount: false, currencyCode: false }); // -> false
132
+ MoneyInput.isTouched({}); // -> false
133
+ ```
134
+
135
+ ### `MoneyInput.getCurrencyDropdownId`
136
+
137
+ **`getCurrencyDropdownId(idPrefix)`**
138
+
139
+ Returns the `id` of the currency dropdown. This is useful in case you want to create a label for the input field. You can use it as
140
+
141
+ ```js
142
+ MoneyInput.getCurrencyDropdownId('price');
143
+ // -> "price.currencyCode"
144
+ ```
145
+
146
+ ### `MoneyInput.getAmountInputId(idPrefix)`
147
+
148
+ Returns the `id` of the amount input. This is useful in case you want to create a label for the input field. You can use it as
149
+
150
+ ```js
151
+ MoneyInput.getAmountInputId('price');
152
+ // -> "price.amount"
153
+ ```
154
+
155
+ ### `MoneyInput.isHighPrecision`
156
+
157
+ The `isHighPrecision` function will return `true` when a `MoneyInput` value is passed for which the number of fraction digits of the amount exceeds the number of fraction digits the supplied currency usually uses.
158
+
159
+ The function may not be called with empty money values. It will throw in those cases.
160
+
161
+ ```js
162
+ MoneyInput.isHighPrecision({ amount: '2.00', currencyCode: 'EUR' }, 'en'); // -> false
163
+ MoneyInput.isHighPrecision({ amount: '2.001', currencyCode: 'EUR' }, 'en'); // -> true
164
+ MoneyInput.isHighPrecision({ amount: '2.001', currencyCode: 'EUR' }, 'de'); // -> false
165
+ MoneyInput.isHighPrecision({ amount: '2,001', currencyCode: 'EUR' }, 'de'); // -> true
166
+ MoneyInput.isHighPrecision({ amount: '', currencyCode: 'EUR' }, 'en'); // -> throws
167
+ ```
168
+
169
+ ## Examples
170
+
171
+ Here's an example of how `MoneyInput` would be used inside a form.
172
+
173
+ ```jsx
174
+ import { IntlProvider } from 'react-intl';
175
+ import { Formik } from 'formik';
176
+ import omitEmpty from 'omit-empty-es';
177
+ import { ErrorMessage } from '@commercetools-uikit/messages';
178
+ import MoneyInput from '@commercetools-uikit/money-input';
179
+
180
+ const currencies = ['EUR', 'USD', 'AED', 'KWD'];
181
+
182
+ // the existing document, e.g. from the database
183
+ const doc = {
184
+ somePrice: {
185
+ type: 'centPrecision',
186
+ currencyCode: 'EUR',
187
+ centAmount: 4200,
188
+ fractionDigits: 2,
189
+ },
190
+ };
191
+
192
+ // A function to convert a document to form values.
193
+ const docToFormValues = (aDoc) => ({
194
+ // The parseMoneyValue function will turn a MoneyValue into a
195
+ // value the MoneyInput component can handle ({ amount, currencyCode })
196
+ somePrice: MoneyInput.parseMoneyValue(aDoc.somePrice),
197
+ });
198
+
199
+ // a function to convert form values back to a document
200
+ const formValuesToDoc = (formValues, locale) => ({
201
+ // The convertToMoneyValue function will turn a MoneyInput
202
+ // value into a value the API can handle
203
+ // It automatically converts to centPrecision or highPrecision
204
+ // depending on the number of supplied fraction digits and the
205
+ // used currency code.
206
+ // If you want to forbid highPrecision, then the form's validation
207
+ // needs to add an error when it sees a highPrecision price.
208
+ // See example below
209
+ somePrice: MoneyInput.convertToMoneyValue(formValues.somePrice, locale),
210
+ });
211
+
212
+ const validate = (formValues, locale) => {
213
+ const errors = { somePrice: {} };
214
+ const moneyValue = MoneyInput.convertToMoneyValue(
215
+ formValues.somePrice,
216
+ locale
217
+ );
218
+ // convertToMoneyValue returns null whenever the value is invalid
219
+ if (!moneyValue) {
220
+ errors.somePrice.missing = true;
221
+ } else if (moneyValue.type === 'highPrecision') {
222
+ // This form does not allow highPrecision prices
223
+ errors.somePrice.highPrecision = true;
224
+ }
225
+ return omitEmpty(errors);
226
+ };
227
+ const initialValues = docToFormValues(doc);
228
+
229
+ return (
230
+ <Formik
231
+ initialValues={initialValues}
232
+ validate={validate}
233
+ onSubmit={(formValues) => {
234
+ // doc will contain "somePrice" holding a MoneyValue,
235
+ // ready to be consumed by the API
236
+ const nextDoc = formValuesToDoc(formValues);
237
+ console.log(nextDoc);
238
+ }}
239
+ render={({
240
+ values,
241
+ errors,
242
+ touched,
243
+ setFieldValue,
244
+ setFieldTouched,
245
+ handleSubmit,
246
+ isSubmitting,
247
+ }) => (
248
+ <form onSubmit={handleSubmit}>
249
+ <MoneyInput
250
+ value={values.somePrice}
251
+ currencies={currencies}
252
+ onBlur={() => setFieldTouched('somePrice')}
253
+ isDisabled={isSubmitting}
254
+ onChange={(value) => setFieldValue('somePrice', value)}
255
+ hasError={
256
+ MoneyInput.isTouched(touched.somePrice) && Boolean(errors.somePrice)
257
+ }
258
+ horizontalConstraint={10}
259
+ />
260
+ {touched.somePrice && errors.somePrice && errors.somePrice.missing && (
261
+ <ErrorMessage>This field is required!</ErrorMessage>
262
+ )}
263
+ {touched.somePrice &&
264
+ errors.somePrice &&
265
+ errors.somePrice.highPrecision && (
266
+ <ErrorMessage>
267
+ High precision prices are not supported here!
268
+ </ErrorMessage>
269
+ )}
270
+ <button type="submit">Submit</button>
271
+ </form>
272
+ )}
273
+ />
274
+ );
275
+ ```