62 lines
1.6 KiB
TypeScript
62 lines
1.6 KiB
TypeScript
const DRAFT_KEY = "qa-draft";
|
|
const relativeTime = new Intl.RelativeTimeFormat(undefined, {
|
|
numeric: "auto",
|
|
});
|
|
|
|
function getValidDate(dateString: string): Date | null {
|
|
const date = new Date(dateString);
|
|
return Number.isNaN(date.getTime()) ? null : date;
|
|
}
|
|
|
|
export function readQuestionDraft(): string {
|
|
try {
|
|
return localStorage.getItem(DRAFT_KEY) ?? "";
|
|
} catch {
|
|
return "";
|
|
}
|
|
}
|
|
|
|
export function writeQuestionDraft(value: string) {
|
|
try {
|
|
localStorage.setItem(DRAFT_KEY, value);
|
|
} catch {
|
|
// Ignore storage failures.
|
|
}
|
|
}
|
|
|
|
export function clearQuestionDraft() {
|
|
try {
|
|
localStorage.removeItem(DRAFT_KEY);
|
|
} catch {
|
|
// Ignore storage failures.
|
|
}
|
|
}
|
|
|
|
export function formatExactTimestamp(dateString: string): string {
|
|
const date = getValidDate(dateString);
|
|
if (!date) return dateString;
|
|
|
|
return new Intl.DateTimeFormat(undefined, {
|
|
dateStyle: "medium",
|
|
timeStyle: "short",
|
|
}).format(date);
|
|
}
|
|
|
|
export function formatRelativeTimestamp(dateString: string): string {
|
|
const date = getValidDate(dateString);
|
|
if (!date) return dateString;
|
|
|
|
const diffMs = date.getTime() - Date.now();
|
|
const diffMinutes = Math.round(diffMs / 60000);
|
|
const diffHours = Math.round(diffMs / 3600000);
|
|
const diffDays = Math.round(diffMs / 86400000);
|
|
|
|
if (Math.abs(diffMinutes) < 60)
|
|
return relativeTime.format(diffMinutes, "minute");
|
|
if (Math.abs(diffHours) < 24) return relativeTime.format(diffHours, "hour");
|
|
if (Math.abs(diffDays) < 30) return relativeTime.format(diffDays, "day");
|
|
|
|
return new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }).format(
|
|
date,
|
|
);
|
|
}
|