@canutin/svelte-currency-input 0.4.0 → 0.5.1

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/README.md CHANGED
@@ -68,6 +68,7 @@ This is more or less what `<CurrencyInput />` looks like under the hood:
68
68
  | disabled | `boolean` | `false` | Marks the inputs as disabled |
69
69
  | placeholder | `number` `null` | `0` | Overrides the default placeholder. Setting the value to a `number` will display it as formatted. Setting it to `null` will not show a placeholder |
70
70
  | isNegativeAllowed | `boolean` | `true` | If `false`, forces formatting only to positive values and ignores `--positive` and `--negative` styling modifiers |
71
+ | fractionDigits | `number` | `2` | Sets `maximumFractionDigits` in [`Intl.NumberFormat()` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#minimumfractiondigits) used for formatting the currency. Supported digits: `0` to `20` |
71
72
 
72
73
  ## Styling
73
74
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@canutin/svelte-currency-input",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "exports": {
5
5
  ".": "./index.js"
6
6
  },
@@ -3,6 +3,7 @@
3
3
  const DEFAULT_CURRENCY = 'USD';
4
4
  const DEFAULT_NAME = 'total';
5
5
  const DEFAULT_VALUE = 0;
6
+ const DEFAULT_FRACTION_DIGITS = 2;
6
7
 
7
8
  export let value: number = DEFAULT_VALUE;
8
9
  export let locale: string = DEFAULT_LOCALE;
@@ -12,6 +13,7 @@
12
13
  export let disabled: boolean = false;
13
14
  export let placeholder: number | null = DEFAULT_VALUE;
14
15
  export let isNegativeAllowed: boolean = true;
16
+ export let fractionDigits: number = DEFAULT_FRACTION_DIGITS;
15
17
 
16
18
  // Formats value as: e.g. $1,523.00 | -$1,523.00
17
19
  const formatCurrency = (
@@ -37,16 +39,18 @@
37
39
  if (!isDeletion && !isModifier && !isArrowKey && isInvalidCharacter) event.preventDefault();
38
40
  };
39
41
 
42
+ const currencyDecimal = new Intl.NumberFormat(locale).format(1.1).charAt(1); // '.' or ','
43
+ const isDecimalComma = currencyDecimal === ','; // Remove currency formatting from `formattedValue` so we can assign it to `value`
44
+ const currencySymbol = formatCurrency(0, 0)
45
+ .replace('0', '') // e.g. '$0' > '$'
46
+ .replace(/\u00A0/, ''); // e.g '0 €' > '€'
47
+
40
48
  // Updates `value` by stripping away the currency formatting
41
49
  const setUnformattedValue = (event: KeyboardEvent) => {
42
50
  // Don't format if the user is typing a `currencyDecimal` point
43
- const currencyDecimal = new Intl.NumberFormat(locale).format(1.1).charAt(1); // '.' or ','
44
51
  if (event.key === currencyDecimal) return;
45
52
 
46
- // If `formattedValue` is ['$', '-$', "-"] we don't need to continue
47
- const currencySymbol = formatCurrency(0, 0)
48
- .replace('0', '') // e.g. '$0' > '$'
49
- .replace(/\u00A0/, ''); // e.g '0 €' > '€'
53
+ // Don't format if `formattedValue` is ['$', '-$', "-"]
50
54
  const ignoreSymbols = [currencySymbol, `-${currencySymbol}`, '-'];
51
55
  const strippedUnformattedValue = formattedValue.replace(' ', '');
52
56
  if (ignoreSymbols.includes(strippedUnformattedValue)) return;
@@ -64,7 +68,6 @@
64
68
  value = 0;
65
69
  } else {
66
70
  // The order of the following operations is *critical*
67
- const isDecimalComma = currencyDecimal === ','; // Remove currency formatting from `formattedValue` so we can assign it to `value`
68
71
  unformattedValue = unformattedValue.replace(isDecimalComma ? /\./g : /\,/g, ''); // Remove all group symbols
69
72
  if (isDecimalComma) unformattedValue = unformattedValue.replace(',', '.'); // If the decimal point is a comma, replace it with a period
70
73
  value = parseFloat(unformattedValue);
@@ -72,11 +75,12 @@
72
75
  };
73
76
 
74
77
  const setFormattedValue = () => {
75
- formattedValue = isZero ? '' : formatCurrency(value, 2, 0);
78
+ formattedValue = isZero ? '' : formatCurrency(value, fractionDigits, 0);
76
79
  };
77
80
 
78
81
  let formattedValue = '';
79
- let formattedPlaceholder = placeholder !== null ? formatCurrency(placeholder, 2, 2) : '';
82
+ let formattedPlaceholder =
83
+ placeholder !== null ? formatCurrency(placeholder, fractionDigits, fractionDigits) : '';
80
84
  $: isZero = value === 0;
81
85
  $: isNegative = value < 0;
82
86
  $: value, setFormattedValue();
@@ -19,7 +19,7 @@
19
19
  <CurrencyInput name="total" value={-42069.69} />
20
20
  <CurrencyInput name="rent" />
21
21
  <CurrencyInput name="balance" value={1234.56} isNegativeAllowed={false} placeholder={null} />
22
- <CurrencyInput name="cashflow" value={5678.9} />
22
+ <CurrencyInput name="btc" value={0.87654321} fractionDigits={8} />
23
23
 
24
24
  <CurrencyInput name="amount" value={5678.9} {locale} {currency} />
25
25
  <CurrencyInput name="loss" value={97532.95} disabled={true} {locale} {currency} />
@@ -1,4 +1,9 @@
1
- import { expect, test } from '@playwright/test';
1
+ import { expect, test, type Page } from '@playwright/test';
2
+
3
+ const isMacOs = process.platform === 'darwin';
4
+ const selectAll = async (page: Page) => {
5
+ isMacOs ? await page.keyboard.press('Meta+A') : await page.keyboard.press('Control+A');
6
+ };
2
7
 
3
8
  test.describe('CurrencyInput', () => {
4
9
  test('Default behavior is correct', async ({ page }) => {
@@ -73,8 +78,8 @@ test.describe('CurrencyInput', () => {
73
78
  'formatted-rent': '',
74
79
  balance: '1234.56',
75
80
  'formatted-balance': '$1,234.56',
76
- cashflow: '5678.9',
77
- 'formatted-cashflow': '$5,678.9',
81
+ btc: '0.87654321',
82
+ 'formatted-btc': '$0.87654321',
78
83
  amount: '5678.9',
79
84
  'formatted-amount': '€ 5.678,9',
80
85
  cost: '-42069.69',
@@ -139,7 +144,6 @@ test.describe('CurrencyInput', () => {
139
144
  test("Incorrect characters can't be entered", async ({ page }) => {
140
145
  await page.goto('/');
141
146
 
142
- const isMacOs = process.platform === 'darwin';
143
147
  const rentUnformattedInput = page.locator('.currencyInput__unformatted[name=rent]');
144
148
  const rentFormattedInput = page.locator('.currencyInput__formatted[name="formatted-rent"]');
145
149
 
@@ -162,10 +166,8 @@ test.describe('CurrencyInput', () => {
162
166
  await expect(rentFormattedInput).toHaveValue('$420.69');
163
167
  await expect(rentUnformattedInput).toHaveValue('420.69');
164
168
 
165
- // Select all
166
- isMacOs ? await page.keyboard.press('Meta+A') : await page.keyboard.press('Control+A');
167
-
168
169
  // Check "Backspace" works
170
+ await selectAll(page);
169
171
  await page.keyboard.press('Backspace');
170
172
  await expect(rentUnformattedInput).toHaveValue('0');
171
173
  await expect(rentFormattedInput).toHaveValue('');
@@ -175,10 +177,8 @@ test.describe('CurrencyInput', () => {
175
177
  await expect(rentFormattedInput).toHaveValue('-$420.69');
176
178
  await expect(rentUnformattedInput).toHaveValue('-420.69');
177
179
 
178
- // Select all
179
- isMacOs ? await page.keyboard.press('Meta+A') : await page.keyboard.press('Control+A');
180
-
181
180
  // Check "Delete" also works
181
+ await selectAll(page);
182
182
  await page.keyboard.press('Delete');
183
183
  await expect(rentUnformattedInput).toHaveValue('0');
184
184
  await expect(rentFormattedInput).toHaveValue('');
@@ -204,6 +204,27 @@ test.describe('CurrencyInput', () => {
204
204
  await expect(deficitFormattedInput).toHaveAttribute('placeholder', '€ 1.234,56'); // The space is `%A0`, not `%20`
205
205
  });
206
206
 
207
+ test('Fraction digits can be overriden', async ({ page }) => {
208
+ await page.goto('/');
209
+
210
+ const btcUnformattedInput = page.locator('.currencyInput__unformatted[name=btc]');
211
+ const btcFormattedInput = page.locator('.currencyInput__formatted[name="formatted-btc"]');
212
+
213
+ await expect(btcUnformattedInput).toHaveValue('0.87654321');
214
+ await expect(btcFormattedInput).toHaveValue('$0.87654321');
215
+ await expect(btcFormattedInput).toHaveAttribute('placeholder', '$0.00000000');
216
+
217
+ await btcFormattedInput.focus();
218
+ await selectAll(page);
219
+ await page.keyboard.press('Backspace');
220
+ await expect(btcUnformattedInput).toHaveValue('0');
221
+ await expect(btcFormattedInput).toHaveValue('');
222
+
223
+ await page.keyboard.type('-0.987654321');
224
+ await expect(btcUnformattedInput).toHaveValue('-0.987654321');
225
+ await expect(btcFormattedInput).toHaveValue('-$0.98765432');
226
+ });
227
+
207
228
  test.skip('Updating chained inputs have the correct behavior', async () => {
208
229
  // TODO
209
230
  });
@@ -1,106 +0,0 @@
1
- <script>export let value = 0;
2
- export let locale = 'en-US';
3
- export let currency = 'USD';
4
- export let name = 'total';
5
- export let required = false;
6
- export let disabled = false;
7
- export let isNegativeAllowed = true;
8
- let formattedValue = '';
9
- $: isZero = value === 0;
10
- $: isNegative = value < 0;
11
- $: value, applyFormatting();
12
- // Formats value as: e.g. $1,523.00 | -$1,523.00
13
- const formatCurrency = (value, maximumFractionDigits, minimumFractionDigits) => {
14
- return new Intl.NumberFormat(locale, {
15
- currency: currency,
16
- style: 'currency',
17
- maximumFractionDigits: maximumFractionDigits || 0,
18
- minimumFractionDigits: minimumFractionDigits || 0
19
- }).format(value);
20
- };
21
- const placeholder = formatCurrency(0, 2, 2); // e.g. '$0.00'
22
- const currencySymbol = formatCurrency(0, 0)
23
- .replace('0', '') // e.g. '$0' > '$'
24
- .replace(/\u00A0/, ''); // e.g '0 €' > '€'
25
- const currencyDecimal = new Intl.NumberFormat(locale).format(1.1).charAt(1); // '.' or ','
26
- // Updates `value` by stripping away the currency formatting
27
- const setValue = (event) => {
28
- // Don't format if the user is typing a currencyDecimal point
29
- if (event?.key === currencyDecimal)
30
- return;
31
- // If `formattedValue` is ['$', '-$', "-"] we don't need to continue
32
- const ignoreSymbols = [currencySymbol, `-${currencySymbol}`, '-'];
33
- const strippedUnformattedValue = formattedValue.replace(' ', '');
34
- if (ignoreSymbols.includes(strippedUnformattedValue))
35
- return;
36
- // Remove all characters that arent: numbers, commas, periods (or minus signs if `isNegativeAllowed`)
37
- let unformattedValue = isNegativeAllowed
38
- ? formattedValue.replace(/[^0-9,.-]/g, '')
39
- : formattedValue.replace(/[^0-9,.]/g, '');
40
- // Reverse the value when minus is pressed
41
- if (isNegativeAllowed && event?.key === '-')
42
- value = value * -1;
43
- // Finally set the value
44
- if (Number.isNaN(parseFloat(unformattedValue))) {
45
- value = 0;
46
- }
47
- else {
48
- // The order of the following operations is *critical*
49
- const isDecimalComma = currencyDecimal === ','; // Remove currency formatting from `formattedValue` so we can assign it to `value`
50
- unformattedValue = unformattedValue.replace(isDecimalComma ? /\./g : /\,/g, ''); // Remove all group symbols
51
- if (isDecimalComma)
52
- unformattedValue = unformattedValue.replace(',', '.'); // If the decimal point is a comma, replace it with a period
53
- value = parseFloat(unformattedValue);
54
- }
55
- };
56
- const applyFormatting = () => {
57
- formattedValue = isZero ? '' : formatCurrency(value, 2, 0);
58
- };
59
- </script>
60
-
61
- <div class="currencyInput">
62
- <input class="currencyInput__unformatted" type="hidden" {name} {disabled} bind:value />
63
- <input
64
- class="
65
- currencyInput__formatted
66
- {isNegativeAllowed && !isZero && !isNegative && 'currencyInput__formatted--positive'}
67
- {isZero && 'currencyInput__formatted--zero'}
68
- {isNegativeAllowed && isNegative && 'currencyInput__formatted--negative'}
69
- "
70
- type="text"
71
- inputmode="numeric"
72
- name={`formatted-${name}`}
73
- required={required && !isZero}
74
- {placeholder}
75
- {disabled}
76
- bind:value={formattedValue}
77
- on:keyup={setValue}
78
- />
79
- </div>
80
-
81
- <style>
82
- input.currencyInput__formatted {
83
- border: 1px solid #e2e2e2;
84
- padding: 10px;
85
- box-sizing: border-box;
86
- }
87
-
88
- input.currencyInput__formatted--zero {
89
- color: #333;
90
- }
91
-
92
- input.currencyInput__formatted--positive {
93
- color: #00a36f;
94
- }
95
-
96
- input.currencyInput__formatted--negative {
97
- color: #e75258;
98
- }
99
-
100
- input.currencyInput__formatted:disabled {
101
- color: #999;
102
- background-color: #e2e2e2;
103
- pointer-events: none;
104
- cursor: default;
105
- }
106
- </style>
@@ -1,22 +0,0 @@
1
- import { SvelteComponentTyped } from "svelte";
2
- declare const __propDef: {
3
- props: {
4
- value?: number | undefined;
5
- locale?: string | undefined;
6
- currency?: string | undefined;
7
- name?: string | undefined;
8
- required?: boolean | undefined;
9
- disabled?: boolean | undefined;
10
- isNegativeAllowed?: boolean | undefined;
11
- };
12
- events: {
13
- [evt: string]: CustomEvent<any>;
14
- };
15
- slots: {};
16
- };
17
- export declare type CurrencyInputProps = typeof __propDef.props;
18
- export declare type CurrencyInputEvents = typeof __propDef.events;
19
- export declare type CurrencyInputSlots = typeof __propDef.slots;
20
- export default class CurrencyInput extends SvelteComponentTyped<CurrencyInputProps, CurrencyInputEvents, CurrencyInputSlots> {
21
- }
22
- export {};
package/package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Canutin
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/package/README.md DELETED
@@ -1,118 +0,0 @@
1
- # svelte-currency-input
2
-
3
- A form input that converts numbers to localized currency formats as you type
4
-
5
- [<img width="1059" alt="image" src="https://user-images.githubusercontent.com/1434675/190315136-c1d310ab-0ef1-441d-a80c-2b3727d74f59.png">](https://svelte.dev/repl/d8f7d22e5b384555b430f62b157ac503?version=3.50.1)
6
-
7
- <p align="center">
8
- 👩‍💻 Play with it on <a href="https://svelte.dev/repl/d8f7d22e5b384555b430f62b157ac503?version=3.50.1" target="_blank">REPL</a> &nbsp;—&nbsp; 💵 See it in a <a href="https://github.com/Canutin/desktop/blob/master/sveltekit/src/lib/components/FormCurrency.svelte" target="_blank">real project</a>!
9
- </p>
10
-
11
- ---
12
-
13
- ## Features
14
-
15
- - Formats **positive** and **negative** values
16
- - Leverages [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) for **localizing** currency denominations and masking the input
17
- - Simple [API](#api)
18
- - Minimal [default styling](https://github.com/canutin/svelte-currency-input/blob/main/src/lib/CurrencyInput.svelte#L88-L118), easy to [customize](#styling)
19
-
20
- ## Usage
21
-
22
- ```bash
23
- npm install svelte-currency-input --save
24
- ```
25
-
26
- ```html
27
- <script lang="ts">
28
- import CurrencyInput from '@canutin/svelte-currency-input';
29
- </script>
30
-
31
- <CurrencyInput name="total" value={-420.69} locale="nl-NL" currency="EUR" />
32
- ```
33
-
34
- ## How it works
35
-
36
- When the form is submitted you get _unformatted_ or _formatted_ values from two `<input />`'s.
37
- This is more or less what `<CurrencyInput />` looks like under the hood:
38
-
39
- ```html
40
- <div class="currencyInput">
41
- <!-- Unformatted value -->
42
- <input
43
- class="currencyInput__unformatted"
44
- type="hidden"
45
- name="total"
46
- value="-420.69"
47
- />
48
-
49
- <!-- Formatted value -->
50
- <input
51
- class="currencyInput__formatted"
52
- type="text"
53
- name="formatted-total"
54
- value="€ -420,69"
55
- />
56
- </div>
57
- ```
58
-
59
- ## API
60
-
61
- | Option | Type | Default | Description |
62
- | ----------------- | --------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
63
- | value | `number` | `undefined` | Initial value. If left `undefined` a formatted value of `0` is visible as a placeholder |
64
- | locale | `string` | `en-US` | Overrides default locale. [Examples](https://gist.github.com/ncreated/9934896) |
65
- | currency | `string` | `USD` | Overrides default currency. [Examples](https://github.com/datasets/currency-codes/blob/master/data/codes-all.csv) |
66
- | name | `string` | `total` | Applies the name to the [input fields](#how-it-works) for _unformatted_ (e.g `[name=total]`) and _formatted_ (e.g. `[name=formatted-total]`) values |
67
- | required | `boolean` | `false` | Marks the inputs as required |
68
- | disabled | `boolean` | `false` | Marks the inputs as disabled |
69
- | isNegativeAllowed | `boolean` | `true` | If `false`, forces formatting only to positive values and ignores `--positive` and `--negative` styling modifiers |
70
-
71
- ## Styling
72
-
73
- The [default styles](https://github.com/canutin/svelte-currency-input/blob/main/src/lib/CurrencyInput.svelte#L88-L118) use [BEM naming conventions](https://getbem.com/naming/). To override the default styles apply your styles as shown below:
74
-
75
- ```html
76
- <div class="my-currency-input">
77
- <CurrencyInput name="total" value="{420.69}" />
78
- </div>
79
-
80
- <style>
81
- /* Container */
82
- div.my-currency-input :global(div.currencyInput) { /* ... */ }
83
-
84
- /* Formatted input */
85
- div.my-currency-input :global(input.currencyInput__formatted) { /* ... */ }
86
-
87
- /* Formatted input when the it's disabled */
88
- div.my-currency-input :global(input.currencyInput__formatted:disabled) { /* ... */ }
89
-
90
- /* Formatted input when the value is zero */
91
- div.my-currency-input :global(input.currencyInput__formatted--zero) { /* ... */ }
92
-
93
- /* Formatted input when the value is positive */
94
- div.my-currency-input :global(input.currencyInput__formatted--positive) { /* ... */ }
95
-
96
- /* Formatted input when the value is negative */
97
- div.my-currency-input :global(input.currencyInput__formatted--negative) { /* ... */ }
98
- </style>
99
- ```
100
-
101
- ## Contributing
102
-
103
- Here's ways in which you can contribute:
104
-
105
- - Found a bug? Open a [new issue](https://github.com/canutin/svelte-currency-input/issues/new)
106
- - Browse our [existing issues](https://github.com/canutin/svelte-currency-input/issues)
107
- - Submit a [pull request](https://github.com/canutin/svelte-currency-input/pulls)
108
-
109
- ## Developing
110
-
111
- This package was generated with [SvelteKit](https://kit.svelte.dev/). Install dependencies with `npm install`, then start a development server:
112
-
113
- ```bash
114
- npm run dev
115
-
116
- # or start the server and open the app in a new browser tab
117
- npm run dev -- --open
118
- ```
@@ -1,2 +0,0 @@
1
- import CurrencyInput from './CurrencyInput.svelte';
2
- export default CurrencyInput;
package/package/index.js DELETED
@@ -1,2 +0,0 @@
1
- import CurrencyInput from './CurrencyInput.svelte';
2
- export default CurrencyInput;
@@ -1,51 +0,0 @@
1
- {
2
- "name": "@canutin/svelte-currency-input",
3
- "version": "0.0.0-development",
4
- "exports": {
5
- "./package.json": "./package.json",
6
- ".": "./index.js",
7
- "./CurrencyInput.svelte": "./CurrencyInput.svelte"
8
- },
9
- "devDependencies": {
10
- "@playwright/test": "^1.25.0",
11
- "@sveltejs/adapter-auto": "next",
12
- "@sveltejs/kit": "next",
13
- "@sveltejs/package": "next",
14
- "@typescript-eslint/eslint-plugin": "^5.27.0",
15
- "@typescript-eslint/parser": "^5.27.0",
16
- "eslint": "^8.16.0",
17
- "eslint-config-prettier": "^8.3.0",
18
- "eslint-plugin-svelte3": "^4.0.0",
19
- "prettier": "^2.6.2",
20
- "prettier-plugin-svelte": "^2.7.0",
21
- "semantic-release": "^19.0.5",
22
- "svelte": "^3.44.0",
23
- "svelte-check": "^2.7.1",
24
- "svelte-preprocess": "^4.10.6",
25
- "tslib": "^2.3.1",
26
- "typescript": "^4.7.4",
27
- "vite": "^3.1.0"
28
- },
29
- "type": "module",
30
- "description": "A form input that converts numbers to currencies as you type in localized formats",
31
- "keywords": [
32
- "svelte",
33
- "currency",
34
- "money",
35
- "input",
36
- "i18n",
37
- "positive",
38
- "negative"
39
- ],
40
- "repository": {
41
- "type": "git",
42
- "url": "git+https://github.com/canutin/svelte-currency-input.git"
43
- },
44
- "author": "Fernando Maclen <hello@fernando.is>",
45
- "license": "MIT",
46
- "bugs": {
47
- "url": "https://github.com/canutin/svelte-currency-input/issues"
48
- },
49
- "homepage": "https://github.com/canutin/svelte-currency-input#readme",
50
- "svelte": "./index.js"
51
- }