Repository URL to install this package:
|
Version:
4.0.7 ▾
|
import { observable, action } from 'xmobx/mobx'
import { toNumber, isFunction } from 'exotic'
import {
IncrementerProps,
IncrementerStateType,
InputChangeEvent,
InputFocusEvent,
ChangeHandler,
ClickHandler,
} from './typings'
export class IncrementerState implements IncrementerStateType {
@observable
count: number = 1
@observable
shouldIncrement: boolean = true
@observable
shouldDecrement: boolean = false
@observable
step: number = 1
@observable
maxValue: number = 99
@observable
minValue: number = 1
// === actions ===
@action
update(values: IncrementerProps) {
Object.keys(values).forEach(key => {
if (this[key] !== undefined) {
this[key] = values[key]
// handles state on mounting phase
if (key === 'count') {
if (values[key] > this.minValue && values[key] < this.maxValue) {
this.shouldDecrement = true
}
else if (values[key] === this.maxValue) {
this.shouldIncrement = false
this.shouldDecrement = true
}
}
}
})
}
@action.bound
incrementCount(props: ClickHandler) {
const { event, onValueChange } = props
if (this.count < this.maxValue) {
this.count += this.step
this.shouldDecrement = true
if (isFunction(onValueChange)) {
onValueChange(this)
}
}
if (this.count === this.maxValue) {
this.shouldIncrement = false
event.preventDefault()
}
}
@action.bound
decrementCount(props: ClickHandler) {
const { event, onValueChange } = props
if (this.count > this.minValue) {
this.count -= this.step
this.shouldIncrement = true
if (isFunction(onValueChange)) {
onValueChange(this)
}
}
if (this.count === this.minValue) {
this.shouldDecrement = false
event.preventDefault()
}
}
// === handlers ===
@action.bound
handleChange(props: ChangeHandler) {
const { event, onValueChange } = props
event.preventDefault()
const isValueEmpty = event.target.value === ''
const value = toNumber(event.target.value)
if (isValueEmpty || (value >= this.minValue && value <= this.maxValue)) {
this.count = value
} else if (value === 0) {
this.count = 1
}
this.shouldDecrement = !(this.count <= this.minValue)
this.shouldIncrement = !(this.count >= this.maxValue)
if (isFunction(onValueChange)) {
onValueChange(this)
}
}
@action.bound
handleBlur(event: InputFocusEvent) {
event.preventDefault()
const isValueEmpty = event.target.value === ''
const value = toNumber(event.target.value)
if (isValueEmpty || value <= this.minValue) {
this.count = this.minValue
} else if (value >= this.maxValue) {
this.count = this.maxValue
}
}
}