Skip to content

[QInputNumber] upgrade with additions and formatting #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/qComponents/QInputNumber/QInputNumber.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,46 @@ describe('QInputNumber', () => {
it('data should match snapshot', () => {
expect(Component.data()).toMatchSnapshot();
});

describe('computed', () => {
it('increaseClass', async () => {
const instance = shallowMount(Component);

await instance.setData({
number: '9007199254740992'
});

expect(instance.vm.increaseClass).toEqual(
'q-input-number__button_is-disabled'
);
});

it('decreaseClass', async () => {
const instance = shallowMount(Component);

await instance.setData({
number: '-9007199254740992'
});

expect(instance.vm.decreaseClass).toEqual(
'q-input-number__button_is-disabled'
);
});
});

describe('methods', () => {
it('handleIncreaseClick', () => {
const { vm } = shallowMount(Component);
vm.handleIncreaseClick();

expect(vm.userValue).toEqual(1);
});

it('handleDecreaseClick', () => {
const { vm } = shallowMount(Component);
vm.handleDecreaseClick();

expect(vm.userValue).toEqual(-1);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
exports[`QInputNumber data should match snapshot 1`] = `
Object {
"number": null,
"prevNumber": null,
"userNumber": null,
"prevCaretPosition": 0,
"prevSelectionPos": null,
"prevValue": "",
"userValue": null,
}
`;

Expand All @@ -22,7 +24,7 @@ exports[`QInputNumber should match snapshot 1`] = `
label=""
suffixicon=""
tabindex=""
type="number"
type="text"
value=""
/>

Expand All @@ -44,7 +46,7 @@ exports[`QInputNumber should match snapshot without controls 1`] = `
label=""
suffixicon=""
tabindex=""
type="number"
type="text"
value=""
/>

Expand Down
233 changes: 217 additions & 16 deletions src/qComponents/QInputNumber/src/QInputNumber.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@
/>

<q-input
ref="input"
:value="currentValue"
class="q-input-number__input"
:disabled="isDisabled"
:placeholder="placeholder"
:validate-event="false"
type="number"
@blur="handleBlur"
@focus="handleFocus"
@input="handleChangeInput($event, 'input')"
@change="handleChangeInput($event, 'change')"
@keydown.native="handleKeydown"
@keyup.native="handleKeyup"
/>

<button
Expand Down Expand Up @@ -110,14 +112,41 @@ export default {
validateEvent: {
type: Boolean,
default: true
},
/**
* `String` before number
*/
prefix: {
type: String,
default: null
},
/**
* `String` after number
*/
suffix: {
type: String,
default: null
},
/**
* BCP47 language identifier
*/
localization: {
type: String,
default: null
},
useGrouping: {
type: Boolean,
default: false
}
},

data() {
return {
number: null,
userNumber: null,
prevNumber: null
userValue: null,
prevCaretPosition: 0,
prevValue: '',
prevSelectionPos: null
};
},

Expand Down Expand Up @@ -146,8 +175,28 @@ export default {
return '';
},

localizationTag() {
return this.localization ?? this.$Q?.locale ?? 'en';
},

localeFormat() {
return Intl.NumberFormat(this.localizationTag, {
useGrouping: this.useGrouping,
minimumFractionDigits: this.precision
}).format;
},

currentValue() {
return (this.userNumber ?? this.number ?? '').toString();
let value = this.userValue ?? this.number ?? '';
value = value ? this.getValueWithoutAdditions(value) : value;

const isNumeric = value !== '' && value !== '-';
value = !isNumeric ? value : this.localeFormat(value);

const prefix = (isNumeric && this.prefix) || '';
const suffix = (isNumeric && this.suffix) || '';

return `${prefix}${value}${suffix}`;
}
},

Expand All @@ -161,12 +210,16 @@ export default {
},

methods: {
setCursorPosition(target, position) {
target.setSelectionRange(position, position);
},

handleIncreaseClick() {
const updatedNumber = Math.round((this.number + this.step) * 100) / 100;

if (updatedNumber > this.max) return;

this.userNumber = updatedNumber;
this.userValue = updatedNumber;
this.changesEmmiter(updatedNumber, 'change');
},

Expand All @@ -175,7 +228,7 @@ export default {

if (updatedNumber < this.min) return;

this.userNumber = updatedNumber;
this.userValue = updatedNumber;
this.changesEmmiter(updatedNumber, 'change');
},

Expand All @@ -188,26 +241,176 @@ export default {
this.$emit('focus', event);
},

getLocaleSeparator(type) {
return Intl.NumberFormat(this.localizationTag)
.format(type === 'decimal' ? 1.1 : 11111)
.replace(/\p{Number}/gu, '');
},

checkStringAdditions(value, addition) {
const position = String(value).indexOf(this[addition]);
const expectedPosition =
addition === 'suffix'
? String(value).length - this[addition].length
: 0;

return position === expectedPosition;
},

handleKeydown(event) {
const {
key,
target: { value, selectionStart, selectionEnd }
} = event;

// range selection check
if (selectionStart !== selectionEnd) return;

const prefixLength = this.prefix?.length ?? 0;
const suffixLength = this.suffix?.length ?? 0;

this.prevSelectionPos =
value === '-' ? selectionStart + 1 : selectionStart;

let caretPos = selectionStart;

if (key === 'Backspace' || key === 'Delete') {
const thousandSeparator = this.getLocaleSeparator();
const floatSeparator = this.getLocaleSeparator('decimal');

const valuePart =
key === 'Backspace'
? value[selectionStart - 1]
: value[selectionStart];
const correction = key === 'Backspace' ? -1 : 1;

// move caret if deleted part is separator
if (valuePart === thousandSeparator || valuePart === floatSeparator) {
this.setCursorPosition(event.target, caretPos + correction);
this.prevSelectionPos = caretPos + correction;
this.prevValue = value;
return;
}
}

if (
this.prefix &&
this.checkStringAdditions(value, 'prefix') &&
caretPos < prefixLength
) {
caretPos = prefixLength;
this.setCursorPosition(event.target, caretPos);
this.prevSelectionPos = caretPos;
}

if (
this.suffix &&
this.checkStringAdditions(value, 'suffix') &&
caretPos > value.length - suffixLength
) {
caretPos = value.length - suffixLength;
this.setCursorPosition(event.target, caretPos);
this.prevSelectionPos = caretPos;
}

this.prevValue = value;
},

getFormattedPartsLength(value, caretPos) {
return value.slice(0, caretPos).split(this.getLocaleSeparator()).length;
},

handleKeyup(event) {
const { value, selectionStart, selectionEnd } = event.target;
if (selectionStart !== selectionEnd) return;

const isKeyDelete = event.key === 'Backspace' || event.key === 'Delete';
const correction = isKeyDelete ? -1 : 1;

const caretPos = this.prevSelectionPos + correction;

const prevValueLength = this.getFormattedPartsLength(
this.prevValue,
caretPos
);
const valueLength = this.getFormattedPartsLength(value, caretPos);

// add symbols and then format
if (prevValueLength > valueLength) {
this.setCursorPosition(event.target, caretPos - 1);

// remove symbols and then format
} else if (prevValueLength < valueLength) {
this.setCursorPosition(event.target, caretPos + 1);

// meta keys
} else if (this.prevValue !== value) {
this.setCursorPosition(event.target, caretPos);
}

this.prevSelectionPos = null;
},

parseLocaleNumber(stringNumber) {
return parseFloat(
stringNumber
.replace(new RegExp(`\\${this.getLocaleSeparator()}`, 'g'), '')
.replace(new RegExp(`\\${this.getLocaleSeparator('decimal')}`), '.')
);
},

getSplittedValue(value, addition) {
if (
value &&
this[addition] &&
this.checkStringAdditions(value, addition)
) {
const startCharReg = addition === 'prefix' ? '^' : '';
const endCharReg = addition === 'suffix' ? '$' : '';

return value.replace(
new RegExp(`${startCharReg}${this[addition]}${endCharReg}`, 'g'),
''
);
}

return value;
},

getValueWithoutAdditions(value) {
if (!value) return value;

let splittedValue = this.getSplittedValue(value, 'prefix');
splittedValue = this.getSplittedValue(splittedValue, 'suffix');

return splittedValue;
},

handleChangeInput(value, type) {
if (!value) {
this.userNumber = value;
const splittedValue = this.getValueWithoutAdditions(value);

if (type === 'input' && splittedValue === '-') {
this.userValue = value;
return;
}

if (!splittedValue) {
this.userValue = null;
this.changesEmmiter(null, type);
return;
}

this.processUserValue(value, type);
this.processUserValue(splittedValue, type);
},

processUserValue(value, type) {
const userValue = Number(value);
this.userNumber = null;
const userValue = this.parseLocaleNumber(value);
this.userValue = null;

if (Number.isNaN(userValue) || value > this.max || value < this.min) {
return;
}

this.prevNumber = userValue;

if (type === 'change') {
this.changesEmmiter(userValue, type);
return;
Expand All @@ -220,13 +423,11 @@ export default {
changesEmmiter(value, type) {
let passedData = null;

if (value) {
if (value || value === 0) {
this.number = Number(value.toFixed(this.precision));
passedData = this.number;
}

this.prevNumber = passedData;

if (type === 'change') {
this.$emit('input', passedData);
this.$emit('change', passedData);
Expand Down
Loading