Countdown
A wall-clock-difference-driven countdown: no drift across background switches or timer throttling; controlled display and uncontrolled self-advance modes; format tokens DD / HH / mm / ss / S. The instance methods start / pause / reset are exposed via a LhCountdownHandle handle.
Spec source:
lh-ui-core/specs/countdown.json· Golden cases:lh-ui-core/cases/countdown.json(10 entries, translated into XCTest, runnable on the macOS host)
Basic usage
Uncontrolled mode: pass time (total duration in ms) and autoStart (default true) starts it on mount. The remaining time is computed as "target wall clock − now" and clamped to ≥ 0, without accumulating subtraction — even if the App is suspended in the background and throttled, returning to the foreground corrects it once against the wall-clock difference, with no accumulated drift.
LhCountdown(time: 60_000) // Reaches zero after 60 seconds
LhCountdown(time: 3600_000, format: "HH:mm:ss") // 1 hourFormatting
Format-string tokens are case-sensitive: DD (days), HH (hours), mm (minutes), ss (seconds), and S (milliseconds, zero-padded to three digits); other characters render as literals. When DD is absent, HH carries the total number of hours (may exceed 24); negative values clamp to zero.
| Format | Remaining 86401500ms | Remaining 181810000ms |
|---|---|---|
HH:mm:ss (default) | 00:00:01 | 50:30:10 |
DD天HH:mm:ss.S | 01天00:00:01.500 | 02天02:30:10 |
LhCountdown(value: 86401500, format: "DD天HH:mm:ss.S") // Controlled display: 01天00:00:01.500
LhCountdown(time: 90_000, millisecond: true, format: "ss.S") // Millisecond digit is best refreshed frame-by-frameStepping
When millisecond is true, it refreshes frame-by-frame (about 16ms); otherwise it steps every 250ms. If the format string contains the S millisecond token, enabling millisecond is recommended — otherwise the millisecond digit only advances once every 250ms.
Controlled and uncontrolled
Passing value makes it controlled: the component does not drive itself and displays the external value (advancing and the finish callback are the caller's responsibility); passing time makes it uncontrolled: with autoStart it runs itself on mount, reporting the remaining milliseconds through onChange on every step, and fires onFinish once when it reaches zero.
@State private var remaining = 3665000
// Note: onChange must be passed explicitly (a trailing closure would bind to the content slot)
LhCountdown(value: remaining, onChange: { remaining = $0 })Methods and handle
LhCountdownHandle exposes start (resumes from the pause point; no effect when disabled) / pause (remembers the remaining time) / reset (returns to the time total duration and can restart per autoStart). Disabling (disabled) grays the component out and pauses the countdown.
@State private var handle = LhCountdownHandle()
LhCountdown(time: 100_000, autoStart: false, handle: handle) {
LhButton(lhOnClick: { handle.start() }, type: .primary, text: "Start")
}API
Props
| Prop | Description | Type | Default |
|---|---|---|---|
value | Remaining milliseconds (controlled display; once passed, the component does not drive itself) | Int? | nil |
time | Uncontrolled total duration (milliseconds) | Int | 0 |
format | Format string (DD/HH/mm/ss/S tokens; other characters render as literals) | String | "HH:mm:ss" |
autoStart | Whether to start automatically on mount in uncontrolled mode | Bool | true |
millisecond | Frame-by-frame refresh (16ms; otherwise a 250ms step) | Bool | false |
disabled | Disabled: grays out and pauses the countdown | Bool | false |
ariaLabel | Accessibility name (falls back to the formatted text when unset) | String? | nil |
handle | Handle (start / pause / reset; no effect in controlled mode) | LhCountdownHandle? | nil |
onChange | Remaining-milliseconds change (fired on every uncontrolled step; controlled write-back goes through the same event) | ((Int) -> Void)? | nil |
onFinish | Fired once when the countdown reaches zero | (() -> Void)? | nil |
content | Extra content (default slot, rendered after the digits) | @ViewBuilder | — |
LhCountdownHandle
| Method | Description |
|---|---|
start() | Resumes from the pause point (no effect when disabled or already at zero) |
pause() | Pauses and remembers the remaining time |
reset(time:autoStart:) | Returns to the total duration and can restart per autoStart |
engine | Internal state machine (wall-clock-difference-driven; nil in controlled mode) |
Format tokens
| Token | Value |
|---|---|
DD | Whole days (when present, HH only carries 0-23) |
HH | Hours; without DD, carries the total number of hours (may exceed 24) |
mm | Minutes (0-59) |
ss | Seconds (0-59) |
S | Milliseconds (0-999, zero-padded to three digits) |
Token Reference
| Token | Purpose |
|---|---|
countdown.digitMinWidth | Minimum width of digit positions for tabular figures (anti-jitter) |
typography.fontSize.base | Font size |
typography.fontWeight.primary | Font weight (mapped to Font.Weight on this end) |
color.text.primary | Digit text color |
color.text.secondary | Separator literal text color (weakened) |
color.text.disabled | Disabled-state text color |
Golden Case Mapping
| case id | Assertion | Local test |
|---|---|---|
renders-formatted-remaining | The controlled value renders as HH:mm:ss with the default format | testRendersFormattedRemaining |
negative-clamps-to-zero | Negative values clamp to all zeros | testNegativeClampsToZero |
hours-over-24-without-dd | Without DD, HH carries the total number of hours | testHoursOver24WithoutDd |
dd-format-splits-days | DD splits by days and zero-pads milliseconds to three digits | testDdFormatSplitsDays |
uncontrolled-autostart-ticks | Uncontrolled autoStart runs itself on mount and fires onChange | testUncontrolledAutostartTicks |
finish-emits-once-at-zero | Reaching zero fires onFinish once and then stops the ticker | testFinishEmitsOnceAtZero |
controlled-does-not-self-drive | Controlled mode does not drive itself | testControlledDoesNotSelfDrive |
autostart-false-waits-for-start | autoStart=false waits for start() to begin counting | testAutostartFalseWaitsForStart |
disabled-pauses-and-greys | Disabled grays out and stops driving (color.text.disabled) | testDisabledPausesAndGreys |
aria-role-timer | The accessibility name falls back to the formatted text | testAriaLabelFallbackToFormattedText |
Plus dedicated tests: testTokenValuesArePositionalAndZeroPadded / testTokenizeThenRenderMatchesFormat / testEnabledAppearanceUsesTokens / testDarkColorsComeFromDarkTokens / testStepInterval / testResetRestoresTotalAndOptionallyRestarts / testPauseFreezesRemaining / testHandleMethodsOperateEngine / testAttachWithDisabledPausesImmediately / testCountdownViewInitAcceptsControlledValue.
swift test --filter LhCountdownTests # Runs on the macOS host, no simulator required
