Skip to content

Commit

Permalink
feat: useProgress
Browse files Browse the repository at this point in the history
  • Loading branch information
nemo-shen committed Jan 14, 2024
1 parent 8b503e1 commit 6b25e0d
Showing 1 changed file with 50 additions and 1 deletion.
51 changes: 50 additions & 1 deletion packages/core/useProgress/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ export interface UseProgressOptions {
initialValue?: number // 0
maxValue?: number // default 100
onChange?: (currentValue: number) => void
autoIncrementRules?: AutoIncrementRule[]
}

const DEFAULT_AUTO_INCREMENT_DELAY = 1000

interface AutoIncrementRule {
before: number // 多少进度之前
increment: number // 自动增长幅度,默认 1
delay: number // 延迟多久
}

/**
Expand All @@ -14,17 +23,54 @@ export interface UseProgressOptions {
* 7. 提供onChange option,当进度变化时,会将进度返回,开发者可以通过这个callback做其他额外处理
*/
export const useProgress = (options: UseProgressOptions) => {
const { initialValue = 0, maxValue = 100, onChange } = options
const {
initialValue = 0,
maxValue = 100,
autoIncrementRules = [],
onChange,
} = options
const progress = ref(initialValue)

const setProgress = (value: number) => {
progress.value = Math.min(maxValue, Math.max(0, value))
}

const increment = (value: number) => {
progress.value += value
}

const decrement = (value: number) => {
progress.value -= value
}

const reset = () => {
progress.value = initialValue
}

const matchRule = () =>
autoIncrementRules.find((rule) => progress.value <= rule.before) ??
autoIncrementRules[autoIncrementRules.length - 1]

const delay = computed(() => {
const rule = matchRule()
if (rule) {
return rule.delay
}
return DEFAULT_AUTO_INCREMENT_DELAY
})

const timer = ref()

const startAutoIncrement = () => {
timer.value = setTimeout(() => {
if (timer.value) {
clearTimeout(timer.value)
}
const rule = matchRule()
increment(rule.increment)
}, delay.value)
}

watch(progress, (newValue) => {
if (onChange) {
onChange(newValue)
Expand All @@ -36,8 +82,11 @@ export const useProgress = (options: UseProgressOptions) => {
return {
progress,
setProgress,
increment,
decrement,
isComplete,
reset,
startAutoIncrement,
}
}

Expand Down

0 comments on commit 6b25e0d

Please sign in to comment.