Skip to content

Commit

Permalink
fix(input-number): add logic
Browse files Browse the repository at this point in the history
  • Loading branch information
koory1st committed Nov 24, 2023
1 parent f513358 commit dff5017
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
51 changes: 49 additions & 2 deletions packages/input-number/src/lib/input-number.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
export let value = '';
/** @type {number | null} */
export let precision = null;
export let max = Infinity;
export let min = -Infinity;
const dispatch = createEventDispatcher();
$: classString = a2s(['svel-input-number', $$props.class]);
$: decreaseClass = a2s(['svel-input-number__decrease']);
Expand All @@ -23,8 +27,9 @@
$: controlsAtRight = controls && controlsPosition === 'right';
let inputRef;
let dataCurrentValue = value;
$: dataCurrentValue = value;
$: dataUserInput = null;
let dataUserInput = null;
function getDisplayValue(dataCurrentValue, dataUserInput) {
if (dataUserInput !== null) {
Expand All @@ -44,6 +49,42 @@
}
$: displayValue = getDisplayValue(dataCurrentValue, dataUserInput);
function setCurrentValue(v, emitChange) {
const oldVal = dataCurrentValue;
const newVal = verifyValue(v);
if (!emitChange && !isNull(newVal)) {
value = newVal;
return;
}
if (oldVal === newVal) return;
dataUserInput = null;
if (!isNull(newVal)) {
value = newVal;
}
dispatch('change', { newVal, oldVal });
// todo: validateEvent
dataCurrentValue = newVal;
}
function verifyValue(v, update) {
if (max < min) {
throw new Error('[InputNumber] min should not be greater than max.');
}
let newVal = Number(value);
if (isNull(value) || Number.isNaN(newVal)) {
return null;
}
}
function handleInput(v) {
dataUserInput = v;
const newVal = value === '' ? null : Number(value);
dispatch('input', newVal);
setCurrentValue(newVal, false);
}
</script>

<div class={classString}>
Expand All @@ -65,5 +106,11 @@
</SvelIcon>
</span>
{/if}
<SvelInput bind:this={inputRef} bind:value={displayValue} {placeholder} type="number" />
<SvelInput
bind:this={inputRef}
bind:value={displayValue}
on:input={handleInput}
{placeholder}
type="number"
/>
</div>
1 change: 1 addition & 0 deletions packages/utils/src/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { isNull } from './is_null.js';
export { isNumber } from './is_number.js';
export { isUndefined } from './is_undefined.js';

0 comments on commit dff5017

Please sign in to comment.