Polish agent stream spacing, alignment, and metadata

- Centralize horizontal alignment: StreamItemWrapper / contentWrapper own
  the chat rail (paddingHorizontal: 8). Stream items stop setting their
  own outer horizontal padding. Copy icons get negative margins so the
  visible icon sits flush with the rail edges.

- Unify the inline working indicator and assistant turn footer into a
  shared slot (minHeight: 24, paddingBottom: 24). No layout shift on
  streaming -> idle, and both gain breathing room above the composer
  and the next user bubble.

- Equalize the gap on both sides of an assistant message adjacent to a
  tool call (20px each). Drop assistantMessageStylesheet.containerSpacing,
  which was a redundant marginBottom that only fired in one direction
  and duplicated getGapBetween's responsibility.

- Scale up the chevron via transform (size stays 12, viewBox padding no
  longer dominates), iconBadge dimensions unchanged. Tool icon and
  chevron now read as similar visual weight.

- Shared STREAM_METADATA_FONT_SIZE (13) for user message timestamp,
  assistant footer duration/timestamp, and the live elapsed timer.

- formatDuration: one rule for static and live displays - 0-10s as
  X.Xs, 10-60s as Xs, minutes/hours integers only. Drops the `mode`
  parameter.

- formatMessageTimestamp: explicitly carry the resolved hourCycle so
  the runtime applies an OS-level 24h preference when the platform
  exposes it (e.g. AppleICUForce24HourTime on macOS).
This commit is contained in:
Mohamed Boudra
2026-05-15 13:30:57 +07:00
parent 57db997028
commit 37bb168204
4 changed files with 88 additions and 108 deletions
@@ -44,6 +44,7 @@ import {
CompactionMarker, CompactionMarker,
LiveElapsed, LiveElapsed,
MessageOuterSpacingProvider, MessageOuterSpacingProvider,
STREAM_METADATA_FONT_SIZE,
type InlinePathTarget, type InlinePathTarget,
} from "./message"; } from "./message";
import { PlanCard } from "./plan-card"; import { PlanCard } from "./plan-card";
@@ -325,7 +326,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
return tightGap; return tightGap;
} }
if (isToolSequenceItem(item) && belowItem.kind === "assistant_message") { if (isToolSequenceItem(item) && belowItem.kind === "assistant_message") {
return looseGap; return tightGap;
} }
if (isSameAssistantBlockGroup({ item, other: belowItem })) { if (isSameAssistantBlockGroup({ item, other: belowItem })) {
return assistantBlockGap; return assistantBlockGap;
@@ -908,7 +909,7 @@ function InlineWorkingIndicatorSlot({
inFlightTurnStartedAt: Date | null; inFlightTurnStartedAt: Date | null;
}) { }) {
return ( return (
<View style={stylesheet.inlineTurnFooter} testID="turn-working-indicator"> <View style={stylesheet.turnFooterSlot} testID="turn-working-indicator">
<WorkingIndicator variant="inline" inFlightTurnStartedAt={inFlightTurnStartedAt} /> <WorkingIndicator variant="inline" inFlightTurnStartedAt={inFlightTurnStartedAt} />
</View> </View>
); );
@@ -940,11 +941,13 @@ function TurnCopyButtonSlot({ strategy, items, startIndex }: TurnCopyButtonSlotP
[strategy, items, startIndex], [strategy, items, startIndex],
); );
return ( return (
<AssistantTurnFooter <View style={stylesheet.turnFooterSlot}>
getContent={getContent} <AssistantTurnFooter
startedAt={header?.startedAt} getContent={getContent}
durationMs={header?.durationMs} startedAt={header?.startedAt}
/> durationMs={header?.durationMs}
/>
</View>
); );
} }
@@ -1244,6 +1247,7 @@ const stylesheet = StyleSheet.create((theme) => ({
width: "100%", width: "100%",
maxWidth: MAX_CONTENT_WIDTH, maxWidth: MAX_CONTENT_WIDTH,
alignSelf: "center", alignSelf: "center",
paddingHorizontal: theme.spacing[2],
}, },
listContentContainer: { listContentContainer: {
paddingVertical: 0, paddingVertical: 0,
@@ -1264,6 +1268,7 @@ const stylesheet = StyleSheet.create((theme) => ({
width: "100%", width: "100%",
maxWidth: MAX_CONTENT_WIDTH, maxWidth: MAX_CONTENT_WIDTH,
alignSelf: "center", alignSelf: "center",
paddingHorizontal: theme.spacing[2],
}, },
emptyState: { emptyState: {
flex: 1, flex: 1,
@@ -1282,37 +1287,35 @@ const stylesheet = StyleSheet.create((theme) => ({
alignItems: "center", alignItems: "center",
justifyContent: "flex-start", justifyContent: "flex-start",
marginTop: theme.spacing[4], marginTop: theme.spacing[4],
paddingLeft: 3,
paddingRight: 3,
paddingTop: theme.spacing[3], paddingTop: theme.spacing[3],
paddingBottom: theme.spacing[2], paddingBottom: theme.spacing[2],
gap: theme.spacing[2], gap: theme.spacing[2],
}, },
inlineTurnFooter: { turnFooterSlot: {
flexDirection: "row",
alignItems: "center",
alignSelf: "flex-start", alignSelf: "flex-start",
marginTop: theme.spacing[2], minHeight: 24,
padding: theme.spacing[2], marginTop: theme.spacing[1],
paddingTop: 0, paddingBottom: theme.spacing[6],
}, },
inlineWorkingIndicatorFrame: { inlineWorkingIndicatorFrame: {
height: 18, height: 24,
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
justifyContent: "flex-start", justifyContent: "flex-start",
gap: theme.spacing[2], gap: theme.spacing[3],
}, },
workingElapsed: { workingElapsed: {
color: theme.colors.foregroundMuted, color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm, fontSize: STREAM_METADATA_FONT_SIZE,
fontVariant: ["tabular-nums"], fontVariant: ["tabular-nums"],
}, },
workingIndicatorBubble: { workingIndicatorBubble: {
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
gap: theme.spacing[2], gap: theme.spacing[3],
paddingHorizontal: 0,
paddingVertical: theme.spacing[1], paddingVertical: theme.spacing[1],
paddingLeft: theme.spacing[2],
borderRadius: theme.borderRadius.full, borderRadius: theme.borderRadius.full,
backgroundColor: "transparent", backgroundColor: "transparent",
borderWidth: 0, borderWidth: 0,
@@ -1322,6 +1325,7 @@ const stylesheet = StyleSheet.create((theme) => ({
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
gap: theme.spacing[1], gap: theme.spacing[1],
transform: [{ translateY: 1 }],
}, },
workingDot: { workingDot: {
width: 6, width: 6,
+19 -37
View File
@@ -187,6 +187,10 @@ const WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS = `
`; `;
let webToolCallShimmerRegistered = false; let webToolCallShimmerRegistered = false;
const SCROLL_EDGE_EPSILON = 0.5; const SCROLL_EDGE_EPSILON = 0.5;
// Font size for stream metadata (timestamps, durations, live elapsed timer).
// Lives between theme.fontSize.xs (12) and theme.fontSize.sm (14); no token.
export const STREAM_METADATA_FONT_SIZE = 13;
type ScrollAxis = "x" | "y"; type ScrollAxis = "x" | "y";
function ensureWebToolCallShimmerKeyframes() { function ensureWebToolCallShimmerKeyframes() {
@@ -318,7 +322,6 @@ const userMessageStylesheet = StyleSheet.create((theme) => ({
container: { container: {
flexDirection: "row", flexDirection: "row",
justifyContent: "flex-end", justifyContent: "flex-end",
paddingHorizontal: theme.spacing[2],
...(isWeb ? { userSelect: "text" as const } : {}), ...(isWeb ? { userSelect: "text" as const } : {}),
}, },
content: { content: {
@@ -393,6 +396,7 @@ const userMessageStylesheet = StyleSheet.create((theme) => ({
}, },
copyButton: { copyButton: {
padding: theme.spacing[1], padding: theme.spacing[1],
marginRight: -theme.spacing[1],
}, },
trailingRow: { trailingRow: {
alignSelf: "flex-end", alignSelf: "flex-end",
@@ -409,7 +413,7 @@ const userMessageStylesheet = StyleSheet.create((theme) => ({
}, },
timestampText: { timestampText: {
color: theme.colors.foregroundMuted, color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.xs, fontSize: STREAM_METADATA_FONT_SIZE,
}, },
})); }));
@@ -562,20 +566,20 @@ const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
gap: theme.spacing[2], gap: theme.spacing[2],
paddingVertical: theme.spacing[1],
}, },
copyButton: { copyButton: {
alignSelf: "center", alignSelf: "center",
padding: theme.spacing[1], padding: theme.spacing[1],
paddingTop: theme.spacing[1], paddingTop: theme.spacing[1],
marginTop: 0, marginTop: 0,
marginLeft: -theme.spacing[1],
}, },
labelWrapper: { labelWrapper: {
position: "relative", position: "relative",
}, },
labelSizer: { labelSizer: {
color: theme.colors.foregroundMuted, color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.xs, fontSize: STREAM_METADATA_FONT_SIZE,
opacity: 0, opacity: 0,
}, },
labelOverlay: { labelOverlay: {
@@ -583,7 +587,7 @@ const assistantTurnFooterStylesheet = StyleSheet.create((theme) => ({
top: 0, top: 0,
left: 0, left: 0,
color: theme.colors.foregroundMuted, color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.xs, fontSize: STREAM_METADATA_FONT_SIZE,
}, },
})); }));
@@ -699,7 +703,7 @@ export const LiveElapsed = memo(function LiveElapsed({
return ( return (
<Text style={style} testID={testID}> <Text style={style} testID={testID}>
{formatDuration(elapsedMs, { mode: "live" })} {formatDuration(elapsedMs)}
</Text> </Text>
); );
}); });
@@ -712,13 +716,11 @@ interface AssistantMessageProps {
serverId?: string; serverId?: string;
client?: DaemonClient | null; client?: DaemonClient | null;
toast?: ToastApi | null; toast?: ToastApi | null;
disableOuterSpacing?: boolean;
spacing?: "default" | "compactTop" | "compactBottom" | "compactBoth"; spacing?: "default" | "compactTop" | "compactBottom" | "compactBoth";
} }
export const assistantMessageStylesheet = StyleSheet.create((theme) => ({ export const assistantMessageStylesheet = StyleSheet.create((theme) => ({
container: { container: {
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[3], paddingVertical: theme.spacing[3],
...(isWeb ? { userSelect: "text" as const } : {}), ...(isWeb ? { userSelect: "text" as const } : {}),
}, },
@@ -728,9 +730,6 @@ export const assistantMessageStylesheet = StyleSheet.create((theme) => ({
containerCompactBottom: { containerCompactBottom: {
paddingBottom: 0, paddingBottom: 0,
}, },
containerSpacing: {
marginBottom: theme.spacing[4],
},
// Used in custom markdownRules for path chip styling // Used in custom markdownRules for path chip styling
pathChip: { pathChip: {
backgroundColor: theme.colors.surface2, backgroundColor: theme.colors.surface2,
@@ -1259,9 +1258,9 @@ export const TurnCopyButton = memo(function TurnCopyButton({
? turnCopyButtonStylesheet.iconHoveredColor.color ? turnCopyButtonStylesheet.iconHoveredColor.color
: turnCopyButtonStylesheet.iconColor.color; : turnCopyButtonStylesheet.iconColor.color;
return copied ? ( return copied ? (
<Check size={18} color={iconColor} /> <Check size={16} color={iconColor} />
) : ( ) : (
<Copy size={18} color={iconColor} /> <Copy size={16} color={iconColor} />
); );
}} }}
</Pressable> </Pressable>
@@ -1270,7 +1269,7 @@ export const TurnCopyButton = memo(function TurnCopyButton({
const expandableBadgeStylesheet = StyleSheet.create((theme) => ({ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
container: { container: {
marginHorizontal: -6, marginHorizontal: -13,
}, },
containerSpacing: { containerSpacing: {
marginBottom: theme.spacing[1], marginBottom: theme.spacing[1],
@@ -1341,8 +1340,8 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
flex: 1, flex: 1,
}, },
chevron: { chevron: {
marginLeft: theme.spacing[1],
flexShrink: 0, flexShrink: 0,
transform: [{ scale: 1.3 }],
}, },
openFileButton: { openFileButton: {
marginLeft: theme.spacing[1], marginLeft: theme.spacing[1],
@@ -1355,7 +1354,7 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
height: 14, height: 14,
}, },
chevronExpanded: { chevronExpanded: {
transform: [{ rotate: "90deg" }], transform: [{ scale: 1.3 }, { rotate: "90deg" }],
}, },
detailWrapper: { detailWrapper: {
borderBottomLeftRadius: theme.borderRadius.lg, borderBottomLeftRadius: theme.borderRadius.lg,
@@ -1660,13 +1659,8 @@ export const AssistantMessage = memo(function AssistantMessage({
serverId, serverId,
client, client,
toast, toast,
disableOuterSpacing,
spacing = "default", spacing = "default",
}: AssistantMessageProps) { }: AssistantMessageProps) {
const resolvedDisableOuterSpacing = useDisableOuterSpacing(
disableOuterSpacing ?? spacing !== "default",
);
const markdownParser = useMemo(() => { const markdownParser = useMemo(() => {
const parser = MarkdownIt({ typographer: true, linkify: true }); const parser = MarkdownIt({ typographer: true, linkify: true });
const defaultValidateLink = parser.validateLink.bind(parser); const defaultValidateLink = parser.validateLink.bind(parser);
@@ -1943,9 +1937,8 @@ export const AssistantMessage = memo(function AssistantMessage({
assistantMessageStylesheet.containerCompactTop, assistantMessageStylesheet.containerCompactTop,
(spacing === "compactBottom" || spacing === "compactBoth") && (spacing === "compactBottom" || spacing === "compactBoth") &&
assistantMessageStylesheet.containerCompactBottom, assistantMessageStylesheet.containerCompactBottom,
!resolvedDisableOuterSpacing && assistantMessageStylesheet.containerSpacing,
], ],
[spacing, resolvedDisableOuterSpacing], [spacing],
); );
return ( return (
@@ -1976,7 +1969,6 @@ interface SpeakMessageProps {
const speakMessageStylesheet = StyleSheet.create((theme) => ({ const speakMessageStylesheet = StyleSheet.create((theme) => ({
container: { container: {
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[3], paddingVertical: theme.spacing[3],
}, },
containerSpacing: { containerSpacing: {
@@ -2041,7 +2033,6 @@ interface ActivityLogProps {
const activityLogStylesheet = StyleSheet.create((theme) => ({ const activityLogStylesheet = StyleSheet.create((theme) => ({
pressable: { pressable: {
marginHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius.md, borderRadius: theme.borderRadius.md,
overflow: "hidden", overflow: "hidden",
}, },
@@ -2610,7 +2601,7 @@ function renderExpandableBadgeIconSlot({
}): ReactNode { }): ReactNode {
if (showChevron) { if (showChevron) {
return ( return (
<ThemedChevronRightIcon size={14} style={chevronStyle} uniProps={foregroundColorMapping} /> <ThemedChevronRightIcon size={12} style={chevronStyle} uniProps={foregroundColorMapping} />
); );
} }
return iconNode; return iconNode;
@@ -2735,7 +2726,6 @@ const ExpandableBadge = memo(function ExpandableBadge({
const resolvedDisableOuterSpacing = useDisableOuterSpacing(disableOuterSpacing); const resolvedDisableOuterSpacing = useDisableOuterSpacing(disableOuterSpacing);
const [isHovered, setIsHovered] = useState(false); const [isHovered, setIsHovered] = useState(false);
const [isOpenFileHovered, setIsOpenFileHovered] = useState(false); const [isOpenFileHovered, setIsOpenFileHovered] = useState(false);
const [isIconHovered, setIsIconHovered] = useState(false);
const [isPressed, setIsPressed] = useState(false); const [isPressed, setIsPressed] = useState(false);
const isInteractive = Boolean(onToggle); const isInteractive = Boolean(onToggle);
const hasDetailContent = Boolean(renderDetails); const hasDetailContent = Boolean(renderDetails);
@@ -2763,8 +2753,6 @@ const ExpandableBadge = memo(function ExpandableBadge({
); );
const handleOpenFileHoverIn = useCallback(() => setIsOpenFileHovered(true), []); const handleOpenFileHoverIn = useCallback(() => setIsOpenFileHovered(true), []);
const handleOpenFileHoverOut = useCallback(() => setIsOpenFileHovered(false), []); const handleOpenFileHoverOut = useCallback(() => setIsOpenFileHovered(false), []);
const handleIconHoverIn = useCallback(() => setIsIconHovered(true), []);
const handleIconHoverOut = useCallback(() => setIsIconHovered(false), []);
const nativeGradientIdRef = useRef( const nativeGradientIdRef = useRef(
`shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`, `shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
@@ -2961,7 +2949,7 @@ const ExpandableBadge = memo(function ExpandableBadge({
const ThemedIcon = useMemo(() => (icon ? withUnistyles(icon) : null), [icon]); const ThemedIcon = useMemo(() => (icon ? withUnistyles(icon) : null), [icon]);
const iconNode = renderExpandableBadgeIcon({ isError, isActive, ThemedIcon }); const iconNode = renderExpandableBadgeIcon({ isError, isActive, ThemedIcon });
const iconSlotNode = renderExpandableBadgeIconSlot({ const iconSlotNode = renderExpandableBadgeIconSlot({
showChevron: isInteractive && isHovered && !isIconHovered, showChevron: isInteractive && isHovered,
chevronStyle, chevronStyle,
iconNode, iconNode,
}); });
@@ -2989,13 +2977,7 @@ const ExpandableBadge = memo(function ExpandableBadge({
style={pressableStyle} style={pressableStyle}
> >
<View style={expandableBadgeStylesheet.headerRow}> <View style={expandableBadgeStylesheet.headerRow}>
<View <View style={expandableBadgeStylesheet.iconBadge}>{iconSlotNode}</View>
style={expandableBadgeStylesheet.iconBadge}
onPointerEnter={isWeb ? handleIconHoverIn : undefined}
onPointerLeave={isWeb ? handleIconHoverOut : undefined}
>
{iconSlotNode}
</View>
<ExpandableBadgeLabelRow <ExpandableBadgeLabelRow
label={label} label={label}
labelStyle={labelStyle} labelStyle={labelStyle}
+11 -15
View File
@@ -2,36 +2,32 @@ import { describe, it, expect } from "vitest";
import { formatDuration, formatMessageTimestamp } from "./time"; import { formatDuration, formatMessageTimestamp } from "./time";
describe("formatDuration", () => { describe("formatDuration", () => {
it("renders static durations as integers", () => { it("renders 0-10s with one decimal", () => {
expect(formatDuration(5_600)).toBe("5s"); expect(formatDuration(0)).toBe("0.0s");
expect(formatDuration(0)).toBe("0s"); expect(formatDuration(5_600)).toBe("5.6s");
expect(formatDuration(9_900)).toBe("9.9s");
}); });
it("renders 10s-60s as whole seconds", () => { it("renders 10s-60s as whole seconds", () => {
expect(formatDuration(47_000)).toBe("47s");
expect(formatDuration(10_400)).toBe("10s"); expect(formatDuration(10_400)).toBe("10s");
expect(formatDuration(12_340)).toBe("12s");
expect(formatDuration(47_000)).toBe("47s");
}); });
it("renders minutes and remainder seconds", () => { it("renders minutes and remainder seconds without decimals", () => {
expect(formatDuration(75_230)).toBe("1m 15s");
expect(formatDuration(132_000)).toBe("2m 12s"); expect(formatDuration(132_000)).toBe("2m 12s");
expect(formatDuration(120_000)).toBe("2m"); expect(formatDuration(120_000)).toBe("2m");
}); });
it("renders hours and remainder minutes", () => { it("renders hours and remainder minutes without decimals", () => {
expect(formatDuration(3_900_000)).toBe("1h 5m"); expect(formatDuration(3_900_000)).toBe("1h 5m");
expect(formatDuration(3_600_000)).toBe("1h"); expect(formatDuration(3_600_000)).toBe("1h");
}); });
it("guards against negative and NaN", () => { it("guards against negative and NaN", () => {
expect(formatDuration(-1)).toBe("0s"); expect(formatDuration(-1)).toBe("0.0s");
expect(formatDuration(Number.NaN)).toBe("0s"); expect(formatDuration(Number.NaN)).toBe("0.0s");
});
it("keeps one decimal for live durations", () => {
expect(formatDuration(5_600, { mode: "live" })).toBe("5.6s");
expect(formatDuration(12_340, { mode: "live" })).toBe("12.3s");
expect(formatDuration(75_230, { mode: "live" })).toBe("1m 15.2s");
expect(formatDuration(0, { mode: "live" })).toBe("0.0s");
}); });
}); });
+35 -37
View File
@@ -44,17 +44,32 @@ function isSameLocalDay(a: Date, b: Date): boolean {
); );
} }
// Cached Intl formatter. Explicitly carrying `hourCycle` from the resolved
// options is what makes the runtime respect the user's OS-level 12h/24h
// preference rather than the locale's default cycle.
let cachedTimeFormatter: Intl.DateTimeFormat | null = null;
function getTimeFormatter(): Intl.DateTimeFormat {
if (cachedTimeFormatter) return cachedTimeFormatter;
const resolved = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
}).resolvedOptions();
cachedTimeFormatter = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
hourCycle: resolved.hourCycle,
});
return cachedTimeFormatter;
}
/** /**
* Format a chat-message timestamp for hover-revealed UI. * Format a chat-message timestamp for hover-revealed UI.
* - Same day: "10:11 PM" * - Same day: "10:11 PM" or "22:11" depending on user preference
* - Within ~6 days: "Wednesday 10:11 PM" * - Within ~6 days: "Wednesday 10:11 PM"
* - Older: "14 May 2026, 10:11 PM" * - Older: "14 May 2026, 10:11 PM"
*/ */
export function formatMessageTimestamp(date: Date, now: Date = new Date()): string { export function formatMessageTimestamp(date: Date, now: Date = new Date()): string {
const time = date.toLocaleTimeString(undefined, { const time = getTimeFormatter().format(date);
hour: "numeric",
minute: "2-digit",
});
if (isSameLocalDay(date, now)) { if (isSameLocalDay(date, now)) {
return time; return time;
@@ -75,47 +90,30 @@ export function formatMessageTimestamp(date: Date, now: Date = new Date()): stri
return `${dateLabel}, ${time}`; return `${dateLabel}, ${time}`;
} }
type DurationFormatMode = "static" | "live";
/** /**
* Format a duration as a compact human-readable string. * Format a duration as a compact human-readable string.
* - Static: integer units only * - 0-10s: one decimal ("3.4s")
* - Live: always keep one decimal in the smallest displayed unit * - 10s-60s: whole seconds ("47s")
* - Minutes/hours: integers only ("2m 12s", "1h 5m")
*/ */
export function formatDuration( export function formatDuration(durationMs: number): string {
durationMs: number,
options?: { mode?: DurationFormatMode },
): string {
const mode = options?.mode ?? "static";
if (!Number.isFinite(durationMs) || durationMs < 0) { if (!Number.isFinite(durationMs) || durationMs < 0) {
return mode === "live" ? "0.0s" : "0s"; return "0.0s";
} }
const totalSeconds = durationMs / 1000; const totalSeconds = durationMs / 1000;
if (mode === "live") { if (totalSeconds < 10) {
if (totalSeconds < 60) { return `${totalSeconds.toFixed(1)}s`;
return `${totalSeconds.toFixed(1)}s`;
}
if (totalSeconds < 60 * 60) {
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds - minutes * 60;
return `${minutes}m ${seconds.toFixed(1)}s`;
}
const hours = Math.floor(totalSeconds / (60 * 60));
const minutes = (totalSeconds - hours * 60 * 60) / 60;
return `${hours}h ${minutes.toFixed(1)}m`;
} }
if (totalSeconds < 60) {
const wholeSeconds = Math.floor(totalSeconds); return `${Math.floor(totalSeconds)}s`;
if (wholeSeconds < 60) {
return `${wholeSeconds}s`;
} }
const minutes = Math.floor(wholeSeconds / 60); const totalMinutes = Math.floor(totalSeconds / 60);
if (minutes < 60) { if (totalMinutes < 60) {
const seconds = wholeSeconds % 60; const seconds = Math.floor(totalSeconds) % 60;
return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`; return seconds === 0 ? `${totalMinutes}m` : `${totalMinutes}m ${seconds}s`;
} }
const hours = Math.floor(minutes / 60); const hours = Math.floor(totalMinutes / 60);
const remMinutes = minutes % 60; const remMinutes = totalMinutes % 60;
return remMinutes === 0 ? `${hours}h` : `${hours}h ${remMinutes}m`; return remMinutes === 0 ? `${hours}h` : `${hours}h ${remMinutes}m`;
} }