feat(timer-picker):optimizing the now button logic (#695)

* feat(NTimePicker): NTimePicker optimization now logic

* feat: optimization

* Update src/time-picker/src/utils.ts

Co-authored-by: 07akioni <07akioni2@gmail.com>
This commit is contained in:
XieZongChen 2021-07-28 11:44:26 -05:00 committed by GitHub
parent 4da8ea9e16
commit 966918ad57
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 57 additions and 12 deletions

View File

@ -4,6 +4,7 @@
### Feats
- `n-time-picker` optimization the now button logic, closes [#401](https://github.com/TuSimple/naive-ui/issues/401).
### Fixes
- Fix `n-message`'s `destroyAll` method doesn't work.

View File

@ -4,6 +4,7 @@
### Feats
- `n-time-picker` 优化此刻按钮逻辑, 关闭 [#401](https://github.com/TuSimple/naive-ui/issues/401)
### Fixes
- 修复 `n-message``destroyAll` 方法不生效

View File

@ -58,7 +58,7 @@ import {
timePickerInjectionKey
} from './interface'
import { happensIn } from 'seemly'
import { isTimeInStep } from './utils'
import { findSimilarTime, isTimeInStep } from './utils'
// validate hours, minutes, seconds prop
function validateUnits (value: MaybeArray<number>, max: number): boolean {
@ -479,17 +479,29 @@ export default defineComponent({
}
function handleNowClick (): void {
const now = new Date()
if (!mergedValueRef.value) doChange(getTime(now))
else {
const newValue = setSeconds(
setMinutes(
setHours(mergedValueRef.value, getHours(now)),
getMinutes(now)
),
getSeconds(now)
)
doChange(getTime(newValue))
const getNowTime = {
hours: getHours,
minutes: getMinutes,
seconds: getSeconds
}
const [mergeHours, mergeMinutes, mergeSeconds] = (
['hours', 'minutes', 'seconds'] as const
).map((i) =>
!props[i] || isTimeInStep(getNowTime[i](now), i, props[i])
? getNowTime[i](now)
: findSimilarTime(getNowTime[i](now), i, props[i])
)
const newValue = setSeconds(
setMinutes(
setHours(
mergedValueRef.value ? mergedValueRef.value : getTime(now),
mergeHours
),
mergeMinutes
),
mergeSeconds
)
doChange(getTime(newValue))
}
function handleConfirmClick (): void {
deriveInputValue()

View File

@ -1,4 +1,4 @@
import { MaybeArray } from '../../_utils'
import { MaybeArray, throwError } from '../../_utils'
export const time = {
hours: [
@ -184,3 +184,34 @@ export function isTimeInStep (
return stepOrList.includes(value)
}
}
export function findSimilarTime (
value: number,
type: 'hours' | 'minutes' | 'seconds',
stepOrList: MaybeArray<number> | undefined
): number {
const list = getTimeUnits(time[type], stepOrList).map(Number)
let lowerBound, upperBound
for (let i = 0; i < list.length; ++i) {
const v = list[i]
if (v === value) return v
else if (v > value) {
upperBound = v
break
}
lowerBound = v
}
if (lowerBound === undefined) {
if (!upperBound) {
throwError(
'time-picker',
"Please set 'hours' or 'minutes' or 'seconds' props"
)
}
return upperBound
}
if (upperBound === undefined) {
return lowerBound
}
return upperBound - value > value - lowerBound ? lowerBound : upperBound
}