From de8a93da3b04ac49907e0374638734e84b67f6c8 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 | 13 ++++++++++ .../components/amount-input/component-test.ts | 24 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/ember-amount-input/src/components/amount-input.ts b/ember-amount-input/src/components/amount-input.ts index 5349f343..1b197dff 100644 --- a/ember-amount-input/src/components/amount-input.ts +++ b/ember-amount-input/src/components/amount-input.ts @@ -5,6 +5,7 @@ import './amount-input.css'; const KEY_CODE_E = 69; const KEY_CODE_FULLSTOP = 190; const KEY_CODE_COMMA = 188; +const KEY_CODE_MINUS = 189; export interface AmountInputArgs { /** @@ -130,9 +131,21 @@ export default class AmountInput extends Component { @action onKeyDown(event: KeyboardEvent): boolean { + const isMinus = event.keyCode === KEY_CODE_MINUS || event.key === '-'; + if (event.keyCode === KEY_CODE_E) { event.preventDefault(); return false; + } else if (isMinus) { + const { target } = event; + if ( + target instanceof HTMLInputElement && + target.value !== '' && + target.selectionStart !== 0 + ) { + 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/amount-input/component-test.ts b/test-app/tests/integration/components/amount-input/component-test.ts index 9a8485d1..8a16adcb 100644 --- a/test-app/tests/integration/components/amount-input/component-test.ts +++ b/test-app/tests/integration/components/amount-input/component-test.ts @@ -222,4 +222,28 @@ module('Integration | Component | amount-input', function (hooks) { }); }); }); + + test('should not 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'); + + await typeIn('input', '1000-'); + await blur('input'); + + assert.dom('input').hasValue('1000'); + }); });