From 1b63560800c90e9214c1be2254a26169e3138526 Mon Sep 17 00:00:00 2001 From: Antoine Moues Date: Thu, 11 Apr 2024 14:27:35 +0200 Subject: [PATCH] feat: prevent minus sign typing --- .../src/components/amount-input.ts | 19 ++++++++ .../tests/integration/components/.DS_Store | Bin 0 -> 6148 bytes .../components/amount-input/component-test.ts | 41 ++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 test-app/tests/integration/components/.DS_Store diff --git a/ember-amount-input/src/components/amount-input.ts b/ember-amount-input/src/components/amount-input.ts index 5349f343..02bb33aa 100644 --- a/ember-amount-input/src/components/amount-input.ts +++ b/ember-amount-input/src/components/amount-input.ts @@ -5,6 +5,8 @@ import './amount-input.css'; const KEY_CODE_E = 69; const KEY_CODE_FULLSTOP = 190; const KEY_CODE_COMMA = 188; +const KEY_CODE_MINUS = 189; +const KEY_MINUS = '-'; export interface AmountInputArgs { /** @@ -27,6 +29,11 @@ export interface AmountInputArgs { */ inputId?: string; + /** + * Specifies if the input value should be restricted to integer only + */ + integerOnly?: boolean; + /** * Specifies the minimum value for the input field */ @@ -102,6 +109,13 @@ export default class AmountInput extends Component { return this.argOrDefault('inputId', 'amount-input'); } + /** + * Specifies if the input value should be restricted to integer only + */ + get integerOnly(): boolean { + return this.argOrDefault('integerOnly', false); + } + /** * Specifies the number of decimals to use for the amount value. * Can be >= 0. @@ -130,9 +144,14 @@ export default class AmountInput extends Component { @action onKeyDown(event: KeyboardEvent): boolean { + const isMinus = event.keyCode === KEY_CODE_MINUS || event.key === KEY_MINUS; + if (event.keyCode === KEY_CODE_E) { event.preventDefault(); return false; + } else if (this.integerOnly && isMinus) { + event.preventDefault(); + return false; } else if ( this.numberOfDecimal === 0 && [KEY_CODE_FULLSTOP, KEY_CODE_COMMA].includes(event.keyCode) diff --git a/test-app/tests/integration/components/.DS_Store b/test-app/tests/integration/components/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0(hbs` + + `); + + assert.dom('input').hasValue(''); + + await fillIn('input', '-1000'); + await blur('input'); + + assert.dom('input').hasValue('-1000'); + }); + + test('should prevent negative values', async function (this: TestContext, assert) { + this.value = 1; + + await render(hbs` + + `); + + assert.dom('input').hasValue('1'); + + await typeIn('input', '-1000'); + await blur('input'); + + assert.dom('input').hasValue('1000'); + }); + }); });