@canutin/svelte-currency-input 0.5.1 → 0.5.2

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.
@@ -0,0 +1,123 @@
1
+ <script>const DEFAULT_LOCALE = 'en-US';
2
+ const DEFAULT_CURRENCY = 'USD';
3
+ const DEFAULT_NAME = 'total';
4
+ const DEFAULT_VALUE = 0;
5
+ const DEFAULT_FRACTION_DIGITS = 2;
6
+ export let value = DEFAULT_VALUE;
7
+ export let locale = DEFAULT_LOCALE;
8
+ export let currency = DEFAULT_CURRENCY;
9
+ export let name = DEFAULT_NAME;
10
+ export let required = false;
11
+ export let disabled = false;
12
+ export let placeholder = DEFAULT_VALUE;
13
+ export let isNegativeAllowed = true;
14
+ export let fractionDigits = DEFAULT_FRACTION_DIGITS;
15
+ // Formats value as: e.g. $1,523.00 | -$1,523.00
16
+ const formatCurrency = (value, maximumFractionDigits, minimumFractionDigits) => {
17
+ return new Intl.NumberFormat(locale, {
18
+ currency: currency,
19
+ style: 'currency',
20
+ maximumFractionDigits: maximumFractionDigits || 0,
21
+ minimumFractionDigits: minimumFractionDigits || 0
22
+ }).format(value);
23
+ };
24
+ // Checks if the key pressed is allowed
25
+ const handleKeyDown = (event) => {
26
+ const isDeletion = event.key === 'Backspace' || event.key === 'Delete';
27
+ const isModifier = event.metaKey || event.altKey || event.ctrlKey;
28
+ const isArrowKey = event.key === 'ArrowLeft' || event.key === 'ArrowRight';
29
+ const isInvalidCharacter = !/^\d|,|\.|-$/g.test(event.key); // Keys that are not a digit, comma, period or minus sign
30
+ if (!isDeletion && !isModifier && !isArrowKey && isInvalidCharacter)
31
+ event.preventDefault();
32
+ };
33
+ const currencyDecimal = new Intl.NumberFormat(locale).format(1.1).charAt(1); // '.' or ','
34
+ const isDecimalComma = currencyDecimal === ','; // Remove currency formatting from `formattedValue` so we can assign it to `value`
35
+ const currencySymbol = formatCurrency(0, 0)
36
+ .replace('0', '') // e.g. '$0' > '$'
37
+ .replace(/\u00A0/, ''); // e.g '0 €' > '€'
38
+ // Updates `value` by stripping away the currency formatting
39
+ const setUnformattedValue = (event) => {
40
+ // Don't format if the user is typing a `currencyDecimal` point
41
+ if (event.key === currencyDecimal)
42
+ return;
43
+ // Don't format if `formattedValue` is ['$', '-$', "-"]
44
+ const ignoreSymbols = [currencySymbol, `-${currencySymbol}`, '-'];
45
+ const strippedUnformattedValue = formattedValue.replace(' ', '');
46
+ if (ignoreSymbols.includes(strippedUnformattedValue))
47
+ return;
48
+ // Remove all characters that arent: numbers, commas, periods (or minus signs if `isNegativeAllowed`)
49
+ let unformattedValue = isNegativeAllowed
50
+ ? formattedValue.replace(/[^0-9,.-]/g, '')
51
+ : formattedValue.replace(/[^0-9,.]/g, '');
52
+ // Reverse the value when minus is pressed
53
+ if (isNegativeAllowed && event.key === '-')
54
+ value = value * -1;
55
+ // Finally set the value
56
+ if (Number.isNaN(parseFloat(unformattedValue))) {
57
+ value = 0;
58
+ }
59
+ else {
60
+ // The order of the following operations is *critical*
61
+ unformattedValue = unformattedValue.replace(isDecimalComma ? /\./g : /\,/g, ''); // Remove all group symbols
62
+ if (isDecimalComma)
63
+ unformattedValue = unformattedValue.replace(',', '.'); // If the decimal point is a comma, replace it with a period
64
+ value = parseFloat(unformattedValue);
65
+ }
66
+ };
67
+ const setFormattedValue = () => {
68
+ formattedValue = isZero ? '' : formatCurrency(value, fractionDigits, 0);
69
+ };
70
+ let formattedValue = '';
71
+ let formattedPlaceholder = placeholder !== null ? formatCurrency(placeholder, fractionDigits, fractionDigits) : '';
72
+ $: isZero = value === 0;
73
+ $: isNegative = value < 0;
74
+ $: value, setFormattedValue();
75
+ </script>
76
+
77
+ <div class="currencyInput">
78
+ <input class="currencyInput__unformatted" type="hidden" {name} {disabled} bind:value />
79
+ <input
80
+ class="
81
+ currencyInput__formatted
82
+ {isNegativeAllowed && !isZero && !isNegative && 'currencyInput__formatted--positive'}
83
+ {isZero && 'currencyInput__formatted--zero'}
84
+ {isNegativeAllowed && isNegative && 'currencyInput__formatted--negative'}
85
+ "
86
+ type="text"
87
+ inputmode="numeric"
88
+ name={`formatted-${name}`}
89
+ required={required && !isZero}
90
+ placeholder={formattedPlaceholder}
91
+ {disabled}
92
+ bind:value={formattedValue}
93
+ on:keydown={handleKeyDown}
94
+ on:keyup={setUnformattedValue}
95
+ />
96
+ </div>
97
+
98
+ <style>
99
+ input.currencyInput__formatted {
100
+ border: 1px solid #e2e2e2;
101
+ padding: 10px;
102
+ box-sizing: border-box;
103
+ }
104
+
105
+ input.currencyInput__formatted--zero {
106
+ color: #333;
107
+ }
108
+
109
+ input.currencyInput__formatted--positive {
110
+ color: #00a36f;
111
+ }
112
+
113
+ input.currencyInput__formatted--negative {
114
+ color: #e75258;
115
+ }
116
+
117
+ input.currencyInput__formatted:disabled {
118
+ color: #999;
119
+ background-color: #e2e2e2;
120
+ pointer-events: none;
121
+ cursor: default;
122
+ }
123
+ </style>
@@ -0,0 +1,24 @@
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
+ placeholder?: number | null | undefined;
11
+ isNegativeAllowed?: boolean | undefined;
12
+ fractionDigits?: number | undefined;
13
+ };
14
+ events: {
15
+ [evt: string]: CustomEvent<any>;
16
+ };
17
+ slots: {};
18
+ };
19
+ export declare type CurrencyInputProps = typeof __propDef.props;
20
+ export declare type CurrencyInputEvents = typeof __propDef.events;
21
+ export declare type CurrencyInputSlots = typeof __propDef.slots;
22
+ export default class CurrencyInput extends SvelteComponentTyped<CurrencyInputProps, CurrencyInputEvents, CurrencyInputSlots> {
23
+ }
24
+ export {};
File without changes
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import CurrencyInput from './CurrencyInput.svelte';
2
+ export default CurrencyInput;
package/package.json CHANGED
@@ -1,57 +1,51 @@
1
1
  {
2
- "name": "@canutin/svelte-currency-input",
3
- "version": "0.5.1",
4
- "exports": {
5
- ".": "./index.js"
6
- },
7
- "scripts": {
8
- "dev": "vite dev",
9
- "build": "svelte-kit sync && svelte-package",
10
- "test": "playwright test",
11
- "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
12
- "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
13
- "lint": "prettier --check . && eslint .",
14
- "format": "prettier --write ."
15
- },
16
- "devDependencies": {
17
- "@playwright/test": "^1.25.0",
18
- "@sveltejs/adapter-auto": "next",
19
- "@sveltejs/kit": "next",
20
- "@sveltejs/package": "next",
21
- "@typescript-eslint/eslint-plugin": "^5.27.0",
22
- "@typescript-eslint/parser": "^5.27.0",
23
- "eslint": "^8.16.0",
24
- "eslint-config-prettier": "^8.3.0",
25
- "eslint-plugin-svelte3": "^4.0.0",
26
- "prettier": "^2.6.2",
27
- "prettier-plugin-svelte": "^2.7.0",
28
- "semantic-release": "^19.0.5",
29
- "svelte": "^3.44.0",
30
- "svelte-check": "^2.7.1",
31
- "svelte-preprocess": "^4.10.6",
32
- "tslib": "^2.3.1",
33
- "typescript": "^4.7.4",
34
- "vite": "^3.1.0"
35
- },
36
- "type": "module",
37
- "description": "A form input that converts numbers to currencies as you type in localized formats",
38
- "keywords": [
39
- "svelte",
40
- "currency",
41
- "money",
42
- "input",
43
- "i18n",
44
- "positive",
45
- "negative"
46
- ],
47
- "repository": {
48
- "type": "git",
49
- "url": "git+https://github.com/canutin/svelte-currency-input.git"
50
- },
51
- "author": "Fernando Maclen <hello@fernando.is>",
52
- "license": "MIT",
53
- "bugs": {
54
- "url": "https://github.com/canutin/svelte-currency-input/issues"
55
- },
56
- "homepage": "https://github.com/canutin/svelte-currency-input#readme"
2
+ "name": "@canutin/svelte-currency-input",
3
+ "version": "0.5.2",
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"
57
51
  }
package/.eslintignore DELETED
@@ -1,13 +0,0 @@
1
- .DS_Store
2
- node_modules
3
- /build
4
- /.svelte-kit
5
- /package
6
- .env
7
- .env.*
8
- !.env.example
9
-
10
- # Ignore files for PNPM, NPM and YARN
11
- pnpm-lock.yaml
12
- package-lock.json
13
- yarn.lock
package/.eslintrc.cjs DELETED
@@ -1,20 +0,0 @@
1
- module.exports = {
2
- root: true,
3
- parser: '@typescript-eslint/parser',
4
- extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
5
- plugins: ['svelte3', '@typescript-eslint'],
6
- ignorePatterns: ['*.cjs'],
7
- overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
8
- settings: {
9
- 'svelte3/typescript': () => require('typescript')
10
- },
11
- parserOptions: {
12
- sourceType: 'module',
13
- ecmaVersion: 2020
14
- },
15
- env: {
16
- browser: true,
17
- es2017: true,
18
- node: true
19
- }
20
- };
package/.gitattributes DELETED
@@ -1,2 +0,0 @@
1
- # Auto detect text files and perform LF normalization
2
- * text=auto
@@ -1,28 +0,0 @@
1
- name: Test, build & release
2
-
3
- on:
4
- push:
5
- branches: [main, master]
6
-
7
- jobs:
8
- Publish:
9
- name: Release
10
- runs-on: ubuntu-latest
11
- steps:
12
- - uses: actions/checkout@v2
13
- - uses: actions/setup-node@v2
14
- with:
15
- node-version: '16.x'
16
- - name: Install dependencies
17
- run: npm ci
18
- - name: Install Playwright Browsers
19
- run: npx playwright install --with-deps
20
- - name: Run Playwright tests
21
- run: npm test
22
- env:
23
- NODE_ENV: CI
24
- - name: Run semantic release
25
- run: npx semantic-release --branches main
26
- env:
27
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
28
- NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -1,23 +0,0 @@
1
- name: Integration tests
2
-
3
- on:
4
- pull_request:
5
- branches: [main, master]
6
-
7
- jobs:
8
- Playwright:
9
- timeout-minutes: 60
10
- runs-on: ubuntu-latest
11
- steps:
12
- - uses: actions/checkout@v2
13
- - uses: actions/setup-node@v2
14
- with:
15
- node-version: '16.x'
16
- - name: Install dependencies
17
- run: npm ci
18
- - name: Install Playwright Browsers
19
- run: npx playwright install --with-deps
20
- - name: Run Playwright tests
21
- run: npm test
22
- env:
23
- NODE_ENV: CI
package/.prettierignore DELETED
@@ -1,14 +0,0 @@
1
- .DS_Store
2
- node_modules
3
- /build
4
- /.svelte-kit
5
- /package
6
- .env
7
- .env.*
8
- !.env.example
9
- README.md
10
-
11
- # Ignore files for PNPM, NPM and YARN
12
- pnpm-lock.yaml
13
- package-lock.json
14
- yarn.lock
package/.prettierrc DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "useTabs": true,
3
- "singleQuote": true,
4
- "trailingComma": "none",
5
- "printWidth": 100,
6
- "pluginSearchDirs": ["."],
7
- "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
8
- }
@@ -1,33 +0,0 @@
1
- import { type PlaywrightTestConfig, devices } from '@playwright/test';
2
-
3
- const isEnvCI = process.env.NODE_ENV === 'CI';
4
-
5
- const enableMultipleBrowsers = [
6
- {
7
- name: 'chromium',
8
- use: { ...devices['Desktop Chrome'] }
9
- },
10
- {
11
- name: 'firefox',
12
- use: { ...devices['Desktop Firefox'] }
13
- },
14
- {
15
- name: 'webkit',
16
- use: { ...devices['Desktop Safari'] }
17
- }
18
- ];
19
-
20
- const config: PlaywrightTestConfig = {
21
- webServer: {
22
- command: 'npm run dev',
23
- port: 5173
24
- },
25
- retries: isEnvCI ? 3 : 0,
26
- use: {
27
- trace: isEnvCI ? 'off' : 'retain-on-failure',
28
- screenshot: isEnvCI ? 'off' : 'only-on-failure'
29
- },
30
- projects: isEnvCI ? enableMultipleBrowsers : undefined
31
- };
32
-
33
- export default config;
package/src/app.d.ts DELETED
@@ -1,11 +0,0 @@
1
- /// <reference types="@sveltejs/kit" />
2
-
3
- // See https://kit.svelte.dev/docs/types#app
4
- // for information about these interfaces
5
- // and what to do when importing types
6
- declare namespace App {
7
- // interface Locals {}
8
- // interface PageData {}
9
- // interface PageError {}
10
- // interface Platform {}
11
- }
package/src/app.html DELETED
@@ -1,12 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="utf-8" />
5
- <link rel="icon" href="%sveltekit.assets%/favicon.png" />
6
- <meta name="viewport" content="width=device-width, initial-scale=1" />
7
- %sveltekit.head%
8
- </head>
9
- <body>
10
- <div>%sveltekit.body%</div>
11
- </body>
12
- </html>
@@ -1,135 +0,0 @@
1
- <script lang="ts">
2
- const DEFAULT_LOCALE = 'en-US';
3
- const DEFAULT_CURRENCY = 'USD';
4
- const DEFAULT_NAME = 'total';
5
- const DEFAULT_VALUE = 0;
6
- const DEFAULT_FRACTION_DIGITS = 2;
7
-
8
- export let value: number = DEFAULT_VALUE;
9
- export let locale: string = DEFAULT_LOCALE;
10
- export let currency: string = DEFAULT_CURRENCY;
11
- export let name: string = DEFAULT_NAME;
12
- export let required: boolean = false;
13
- export let disabled: boolean = false;
14
- export let placeholder: number | null = DEFAULT_VALUE;
15
- export let isNegativeAllowed: boolean = true;
16
- export let fractionDigits: number = DEFAULT_FRACTION_DIGITS;
17
-
18
- // Formats value as: e.g. $1,523.00 | -$1,523.00
19
- const formatCurrency = (
20
- value: number,
21
- maximumFractionDigits?: number,
22
- minimumFractionDigits?: number
23
- ) => {
24
- return new Intl.NumberFormat(locale, {
25
- currency: currency,
26
- style: 'currency',
27
- maximumFractionDigits: maximumFractionDigits || 0,
28
- minimumFractionDigits: minimumFractionDigits || 0
29
- }).format(value);
30
- };
31
-
32
- // Checks if the key pressed is allowed
33
- const handleKeyDown = (event: KeyboardEvent) => {
34
- const isDeletion = event.key === 'Backspace' || event.key === 'Delete';
35
- const isModifier = event.metaKey || event.altKey || event.ctrlKey;
36
- const isArrowKey = event.key === 'ArrowLeft' || event.key === 'ArrowRight';
37
- const isInvalidCharacter = !/^\d|,|\.|-$/g.test(event.key); // Keys that are not a digit, comma, period or minus sign
38
-
39
- if (!isDeletion && !isModifier && !isArrowKey && isInvalidCharacter) event.preventDefault();
40
- };
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
-
48
- // Updates `value` by stripping away the currency formatting
49
- const setUnformattedValue = (event: KeyboardEvent) => {
50
- // Don't format if the user is typing a `currencyDecimal` point
51
- if (event.key === currencyDecimal) return;
52
-
53
- // Don't format if `formattedValue` is ['$', '-$', "-"]
54
- const ignoreSymbols = [currencySymbol, `-${currencySymbol}`, '-'];
55
- const strippedUnformattedValue = formattedValue.replace(' ', '');
56
- if (ignoreSymbols.includes(strippedUnformattedValue)) return;
57
-
58
- // Remove all characters that arent: numbers, commas, periods (or minus signs if `isNegativeAllowed`)
59
- let unformattedValue = isNegativeAllowed
60
- ? formattedValue.replace(/[^0-9,.-]/g, '')
61
- : formattedValue.replace(/[^0-9,.]/g, '');
62
-
63
- // Reverse the value when minus is pressed
64
- if (isNegativeAllowed && event.key === '-') value = value * -1;
65
-
66
- // Finally set the value
67
- if (Number.isNaN(parseFloat(unformattedValue))) {
68
- value = 0;
69
- } else {
70
- // The order of the following operations is *critical*
71
- unformattedValue = unformattedValue.replace(isDecimalComma ? /\./g : /\,/g, ''); // Remove all group symbols
72
- if (isDecimalComma) unformattedValue = unformattedValue.replace(',', '.'); // If the decimal point is a comma, replace it with a period
73
- value = parseFloat(unformattedValue);
74
- }
75
- };
76
-
77
- const setFormattedValue = () => {
78
- formattedValue = isZero ? '' : formatCurrency(value, fractionDigits, 0);
79
- };
80
-
81
- let formattedValue = '';
82
- let formattedPlaceholder =
83
- placeholder !== null ? formatCurrency(placeholder, fractionDigits, fractionDigits) : '';
84
- $: isZero = value === 0;
85
- $: isNegative = value < 0;
86
- $: value, setFormattedValue();
87
- </script>
88
-
89
- <div class="currencyInput">
90
- <input class="currencyInput__unformatted" type="hidden" {name} {disabled} bind:value />
91
- <input
92
- class="
93
- currencyInput__formatted
94
- {isNegativeAllowed && !isZero && !isNegative && 'currencyInput__formatted--positive'}
95
- {isZero && 'currencyInput__formatted--zero'}
96
- {isNegativeAllowed && isNegative && 'currencyInput__formatted--negative'}
97
- "
98
- type="text"
99
- inputmode="numeric"
100
- name={`formatted-${name}`}
101
- required={required && !isZero}
102
- placeholder={formattedPlaceholder}
103
- {disabled}
104
- bind:value={formattedValue}
105
- on:keydown={handleKeyDown}
106
- on:keyup={setUnformattedValue}
107
- />
108
- </div>
109
-
110
- <style>
111
- input.currencyInput__formatted {
112
- border: 1px solid #e2e2e2;
113
- padding: 10px;
114
- box-sizing: border-box;
115
- }
116
-
117
- input.currencyInput__formatted--zero {
118
- color: #333;
119
- }
120
-
121
- input.currencyInput__formatted--positive {
122
- color: #00a36f;
123
- }
124
-
125
- input.currencyInput__formatted--negative {
126
- color: #e75258;
127
- }
128
-
129
- input.currencyInput__formatted:disabled {
130
- color: #999;
131
- background-color: #e2e2e2;
132
- pointer-events: none;
133
- cursor: default;
134
- }
135
- </style>
@@ -1,161 +0,0 @@
1
- <script lang="ts">
2
- import CurrencyInput from '$lib/CurrencyInput.svelte';
3
-
4
- const locale = 'nl-NL';
5
- const currency = 'EUR';
6
-
7
- let output: string;
8
- const handleSubmit = (event: Event) => {
9
- event.preventDefault();
10
- // Get the form data
11
- const data = new FormData(event.target as HTMLFormElement);
12
- // Pretty-print the data as JSON
13
- output = JSON.stringify(Object.fromEntries(data.entries()), null, 2);
14
- };
15
- </script>
16
-
17
- <form class="demoForm" on:submit={handleSubmit}>
18
- <div class="demoForm__container">
19
- <CurrencyInput name="total" value={-42069.69} />
20
- <CurrencyInput name="rent" />
21
- <CurrencyInput name="balance" value={1234.56} isNegativeAllowed={false} placeholder={null} />
22
- <CurrencyInput name="btc" value={0.87654321} fractionDigits={8} />
23
-
24
- <CurrencyInput name="amount" value={5678.9} {locale} {currency} />
25
- <CurrencyInput name="loss" value={97532.95} disabled={true} {locale} {currency} />
26
- <CurrencyInput name="cost" value={-42069.69} {locale} {currency} />
27
- <CurrencyInput
28
- name="deficit"
29
- placeholder={1234.56}
30
- isNegativeAllowed={false}
31
- {locale}
32
- {currency}
33
- />
34
- </div>
35
-
36
- <nav class="demoForm__output">
37
- <button type="submit" class="demoForm__submit">Submit form</button>
38
-
39
- <pre class="demoForm__pre {!output && 'demoForm__pre--placeholder'}">{output
40
- ? output
41
- : 'Submit form to see a JSON output of the values'}</pre>
42
- </nav>
43
-
44
- <nav class="demoForm__nav">
45
- <a class="demoForm__a" href="https://github.com/canutin/svelte-currency-input" target="_blank"
46
- >GitHub repository</a
47
- >
48
- <a
49
- class="demoForm__a"
50
- href="https://github.com/canutin/svelte-currency-input/issues"
51
- target="_blank">Known issues</a
52
- >
53
- <a
54
- class="demoForm__a"
55
- href="https://github.com/canutin/svelte-currency-input#contributing"
56
- target="_blank">Contribute</a
57
- >
58
- <a
59
- class="demoForm__a"
60
- href="https://www.npmjs.com/package/@canutin/svelte-currency-input"
61
- target="_blank">NPM</a
62
- >
63
- </nav>
64
- </form>
65
-
66
- <style>
67
- /* Overriding the styles of the <CurrencyInput /> component */
68
- form.demoForm :global(input.currencyInput__formatted) {
69
- width: 100%;
70
- font-family: monospace;
71
- font-size: 13px;
72
- }
73
-
74
- /* Styles for demo presentation (you can ignore these) */
75
- :global(body) {
76
- --gap: 64px;
77
-
78
- font-family: sans-serif;
79
- box-sizing: border-box;
80
- height: 100vh;
81
- margin: 0;
82
- background-color: #eaeaea;
83
- display: flex;
84
- align-items: center;
85
- justify-content: center;
86
- place-items: center;
87
- padding: var(--gap);
88
- }
89
-
90
- form.demoForm {
91
- display: flex;
92
- flex-direction: column;
93
- row-gap: var(--gap);
94
- }
95
-
96
- div.demoForm__container {
97
- display: grid;
98
- grid-template-columns: repeat(4, 1fr);
99
- align-items: center;
100
- justify-content: center;
101
- gap: calc(var(--gap) / 2);
102
- height: max-content;
103
- }
104
-
105
- nav.demoForm__nav {
106
- font-size: 13px;
107
- display: flex;
108
- column-gap: 16px;
109
- justify-content: center;
110
- }
111
-
112
- a.demoForm__a {
113
- color: #333;
114
- text-decoration: none;
115
- border-bottom-width: 1px;
116
- border-bottom-color: #ccc;
117
- border-bottom-style: solid;
118
- }
119
-
120
- a.demoForm__a:visited {
121
- color: #666;
122
- }
123
-
124
- a.demoForm__a:hover {
125
- color: #000;
126
- border-bottom-color: transparent;
127
- }
128
-
129
- nav.demoForm__output {
130
- display: grid;
131
- grid-template-columns: max-content auto;
132
- column-gap: calc(var(--gap) / 2);
133
- }
134
-
135
- pre.demoForm__pre {
136
- background-color: #f4f4f4;
137
- padding: 10px;
138
- margin: 0;
139
- color: #666;
140
- box-sizing: border-box;
141
- }
142
-
143
- pre.demoForm__pre--placeholder {
144
- font-family: sans-serif;
145
- font-size: 13px;
146
- }
147
-
148
- button.demoForm__submit {
149
- border: none;
150
- background-color: #333;
151
- color: #fff;
152
- padding: 10px;
153
- font-size: 13px;
154
- cursor: pointer;
155
- height: max-content;
156
- }
157
-
158
- button.demoForm__submit:hover {
159
- background-color: #000;
160
- }
161
- </style>
Binary file
package/svelte.config.js DELETED
@@ -1,15 +0,0 @@
1
- import adapter from '@sveltejs/adapter-auto';
2
- import preprocess from 'svelte-preprocess';
3
-
4
- /** @type {import('@sveltejs/kit').Config} */
5
- const config = {
6
- // Consult https://github.com/sveltejs/svelte-preprocess
7
- // for more information about preprocessors
8
- preprocess: preprocess(),
9
-
10
- kit: {
11
- adapter: adapter()
12
- }
13
- };
14
-
15
- export default config;
@@ -1,231 +0,0 @@
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
- };
7
-
8
- test.describe('CurrencyInput', () => {
9
- test('Default behavior is correct', async ({ page }) => {
10
- await page.goto('/');
11
-
12
- // Test field with "zero" value
13
- const rentUnformattedInput = page.locator('.currencyInput__unformatted[name=rent]');
14
- const rentFormattedInput = page.locator('.currencyInput__formatted[name="formatted-rent"]');
15
- await expect(rentUnformattedInput).not.toBeDisabled();
16
- await expect(rentUnformattedInput).toHaveAttribute('type', 'hidden');
17
- await expect(rentUnformattedInput).toHaveValue('0');
18
- await expect(rentFormattedInput).not.toBeDisabled();
19
- await expect(rentFormattedInput).toHaveValue('');
20
- await expect(rentFormattedInput).toHaveAttribute('type', 'text');
21
- await expect(rentFormattedInput).toHaveAttribute('placeholder', '$0.00');
22
- await expect(rentFormattedInput).not.toHaveClass(/currencyInput__formatted--positive/);
23
- await expect(rentFormattedInput).not.toHaveClass(/currencyInput__formatted--negative/);
24
- await expect(rentFormattedInput).toHaveClass(/currencyInput__formatted--zero/);
25
-
26
- // Test field with "positive" value
27
- const amountUnformattedInput = page.locator('.currencyInput__unformatted[name=amount]');
28
- const amountFormattedInput = page.locator('.currencyInput__formatted[name="formatted-amount"]');
29
- await expect(amountUnformattedInput).not.toBeDisabled();
30
- await expect(amountUnformattedInput).toHaveAttribute('type', 'hidden');
31
- await expect(amountUnformattedInput).toHaveValue('5678.9');
32
- await expect(amountFormattedInput).not.toBeDisabled();
33
- await expect(amountFormattedInput).toHaveValue('€ 5.678,9');
34
- await expect(amountFormattedInput).toHaveAttribute('type', 'text');
35
- await expect(amountFormattedInput).toHaveAttribute('placeholder', '€ 0,00');
36
- await expect(amountFormattedInput).toHaveClass(/currencyInput__formatted--positive/);
37
- await expect(amountFormattedInput).not.toHaveClass(/currencyInput__formatted--negative/);
38
- await expect(amountFormattedInput).not.toHaveClass(/currencyInput__formatted--zero/);
39
-
40
- // Test field with "negative" value
41
- const totalUnformattedInput = page.locator('.currencyInput__unformatted[name=total]');
42
- const totalFormattedInput = page.locator('.currencyInput__formatted[name="formatted-total"]');
43
- await expect(amountUnformattedInput).not.toBeDisabled();
44
- await expect(totalUnformattedInput).toHaveAttribute('type', 'hidden');
45
- await expect(totalUnformattedInput).toHaveValue('-42069.69');
46
- await expect(totalFormattedInput).not.toBeDisabled();
47
- await expect(totalFormattedInput).toHaveValue('-$42,069.69');
48
- await expect(totalFormattedInput).toHaveAttribute('type', 'text');
49
- await expect(totalFormattedInput).toHaveAttribute('placeholder', '$0.00');
50
- await expect(totalFormattedInput).not.toHaveClass(/currencyInput__formatted--positive/);
51
- await expect(totalFormattedInput).toHaveClass(/currencyInput__formatted--negative/);
52
- await expect(totalFormattedInput).not.toHaveClass(/currencyInput__formatted--zero/);
53
-
54
- // Test field that is "disabled"
55
- const lossUnformattedInput = page.locator('.currencyInput__unformatted[name=loss]');
56
- const lossFormattedInput = page.locator('.currencyInput__formatted[name="formatted-loss"]');
57
- await expect(lossUnformattedInput).toBeDisabled();
58
- await expect(lossUnformattedInput).toHaveAttribute('type', 'hidden');
59
- await expect(lossUnformattedInput).toHaveValue('97532.95');
60
- await expect(lossFormattedInput).toHaveValue('€ 97.532,95');
61
- await expect(lossFormattedInput).toBeDisabled();
62
- await expect(lossFormattedInput).toHaveAttribute('type', 'text');
63
- await expect(lossFormattedInput).toHaveAttribute('placeholder', '€ 0,00');
64
- await expect(lossFormattedInput).toHaveClass(/currencyInput__formatted--positive/);
65
- await expect(lossFormattedInput).not.toHaveClass(/currencyInput__formatted--negative/);
66
- await expect(lossFormattedInput).not.toHaveClass(/currencyInput__formatted--zero/);
67
-
68
- // Submitting a form returns the correct values
69
- const demoSubmitForm = page.locator('button.demoForm__submit');
70
- const demoOutput = page.locator('pre.demoForm__pre');
71
- await demoSubmitForm.click();
72
- expect(await demoOutput.textContent()).toMatch(
73
- JSON.stringify(
74
- {
75
- total: '-42069.69',
76
- 'formatted-total': '-$42,069.69',
77
- rent: '0',
78
- 'formatted-rent': '',
79
- balance: '1234.56',
80
- 'formatted-balance': '$1,234.56',
81
- btc: '0.87654321',
82
- 'formatted-btc': '$0.87654321',
83
- amount: '5678.9',
84
- 'formatted-amount': '€ 5.678,9',
85
- cost: '-42069.69',
86
- 'formatted-cost': '€ -42.069,69',
87
- deficit: '0',
88
- 'formatted-deficit': ''
89
- },
90
- null,
91
- 2
92
- )
93
- );
94
- });
95
-
96
- test('Updating an input has the correct behavior', async ({ page }) => {
97
- await page.goto('/');
98
-
99
- const rentUnformattedInput = page.locator('.currencyInput__unformatted[name=rent]');
100
- const rentFormattedInput = page.locator('.currencyInput__formatted[name="formatted-rent"]');
101
-
102
- // Check the there is no value in the input
103
- await expect(rentUnformattedInput).toHaveValue('0');
104
- await expect(rentFormattedInput).toHaveValue('');
105
-
106
- await rentFormattedInput.focus();
107
- await page.keyboard.type('420.69');
108
- await expect(rentFormattedInput).toHaveValue('$420.69');
109
- await expect(rentUnformattedInput).toHaveValue('420.69');
110
- await expect(rentFormattedInput).toHaveClass(/currencyInput__formatted--positive/);
111
- await expect(rentFormattedInput).not.toHaveClass(/currencyInput__formatted--negative/);
112
- await expect(rentFormattedInput).not.toHaveClass(/currencyInput__formatted--zero/);
113
-
114
- // Use arrow keys to go back to the first character
115
- for (let i = 0; i < '$420.69'.length; i++) await page.keyboard.press('ArrowLeft');
116
- await page.keyboard.type('-');
117
- await expect(rentFormattedInput).toHaveValue('-$420.69');
118
- await expect(rentUnformattedInput).toHaveValue('-420.69');
119
- await expect(rentFormattedInput).not.toHaveClass(/currencyInput__formatted--positive/);
120
- await expect(rentFormattedInput).toHaveClass(/currencyInput__formatted--negative/);
121
- await expect(rentFormattedInput).not.toHaveClass(/currencyInput__formatted--zero/);
122
-
123
- // Use right arrow keys to position cusror at the end of the input
124
- for (let i = 0; i < '$420.69'.length; i++) await page.keyboard.press('ArrowRight');
125
- // Delete the number but keep the currency symbol and sign
126
- for (let i = 1; i < '420.69'.length; i++) await page.keyboard.press('Backspace');
127
- await expect(rentFormattedInput).toHaveValue('-$');
128
- // FIXME: at this point the hidden value should be set to 0 but without formatting `rentFormattedInput`
129
- await expect(rentUnformattedInput).toHaveValue('-4');
130
-
131
- await page.keyboard.press('Backspace');
132
- await expect(rentFormattedInput).toHaveValue('-');
133
- // FIXME: at this point the hidden value should be set to 0 but without formatting `rentFormattedInput
134
- await expect(rentUnformattedInput).toHaveValue('-4');
135
-
136
- await page.keyboard.type('69.42');
137
- await expect(rentFormattedInput).toHaveValue('-$69.42');
138
- await expect(rentUnformattedInput).toHaveValue('-69.42');
139
-
140
- for (let i = 0; i < '-$69.42'.length; i++) await page.keyboard.press('Backspace');
141
- await expect(rentUnformattedInput).toHaveValue('0');
142
- });
143
-
144
- test("Incorrect characters can't be entered", async ({ page }) => {
145
- await page.goto('/');
146
-
147
- const rentUnformattedInput = page.locator('.currencyInput__unformatted[name=rent]');
148
- const rentFormattedInput = page.locator('.currencyInput__formatted[name="formatted-rent"]');
149
-
150
- // Check the there is no value in the input
151
- await expect(rentUnformattedInput).toHaveValue('0');
152
- await expect(rentFormattedInput).toHaveValue('');
153
-
154
- // Check typing letters doesn't do anything
155
- await rentFormattedInput.focus();
156
- await page.keyboard.type('abc');
157
- await expect(rentUnformattedInput).toHaveValue('0');
158
- await expect(rentFormattedInput).toHaveValue('');
159
-
160
- // Check keyboard combinations don't do anything
161
- await page.keyboard.press('Shift+A');
162
- await expect(rentFormattedInput).toHaveValue('');
163
-
164
- // Check keyboard shortcuts are allowed
165
- await page.keyboard.type('420.69');
166
- await expect(rentFormattedInput).toHaveValue('$420.69');
167
- await expect(rentUnformattedInput).toHaveValue('420.69');
168
-
169
- // Check "Backspace" works
170
- await selectAll(page);
171
- await page.keyboard.press('Backspace');
172
- await expect(rentUnformattedInput).toHaveValue('0');
173
- await expect(rentFormattedInput).toHaveValue('');
174
-
175
- // Add data to the field again
176
- await page.keyboard.type('-420.69');
177
- await expect(rentFormattedInput).toHaveValue('-$420.69');
178
- await expect(rentUnformattedInput).toHaveValue('-420.69');
179
-
180
- // Check "Delete" also works
181
- await selectAll(page);
182
- await page.keyboard.press('Delete');
183
- await expect(rentUnformattedInput).toHaveValue('0');
184
- await expect(rentFormattedInput).toHaveValue('');
185
- });
186
-
187
- test('Placeholders can be overriden', async ({ page }) => {
188
- await page.goto('/');
189
-
190
- // Default placeholder
191
- const rentFormattedInput = page.locator('.currencyInput__formatted[name="formatted-rent"]');
192
- await expect(rentFormattedInput).toHaveAttribute('placeholder', '$0.00');
193
-
194
- // Null placeholder
195
- const balanceFormattedInput = page.locator(
196
- '.currencyInput__formatted[name="formatted-balance"]'
197
- );
198
- await expect(balanceFormattedInput).toHaveAttribute('placeholder', '');
199
-
200
- // Overriden placeholder
201
- const deficitFormattedInput = page.locator(
202
- '.currencyInput__formatted[name="formatted-deficit"]'
203
- );
204
- await expect(deficitFormattedInput).toHaveAttribute('placeholder', '€ 1.234,56'); // The space is `%A0`, not `%20`
205
- });
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
-
228
- test.skip('Updating chained inputs have the correct behavior', async () => {
229
- // TODO
230
- });
231
- });
package/tsconfig.json DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "extends": "./.svelte-kit/tsconfig.json",
3
- "compilerOptions": {
4
- "allowJs": true,
5
- "checkJs": true,
6
- "esModuleInterop": true,
7
- "forceConsistentCasingInFileNames": true,
8
- "resolveJsonModule": true,
9
- "skipLibCheck": true,
10
- "sourceMap": true,
11
- "strict": true
12
- }
13
- // Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
14
- //
15
- // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
16
- // from the referenced tsconfig.json - TypeScript does not merge them in
17
- }
package/vite.config.ts DELETED
@@ -1,8 +0,0 @@
1
- import { sveltekit } from '@sveltejs/kit/vite';
2
- import type { UserConfig } from 'vite';
3
-
4
- const config: UserConfig = {
5
- plugins: [sveltekit()]
6
- };
7
-
8
- export default config;