impr: restructure src/lib
This commit is contained in:
376 files changed
+1000
-1033
No files matched your search
@@ -0,0 +1,85 @@
|
||||
<script lang="ts" module>
|
||||
export function formatRelativeDate(
|
||||
date: Date,
|
||||
options: Intl.RelativeTimeFormatOptions,
|
||||
locale?: string,
|
||||
relativeTo?: Date,
|
||||
) {
|
||||
try {
|
||||
const now = relativeTo?.getTime() ?? Date.now()
|
||||
|
||||
const diffInMillis = now - date.getTime()
|
||||
|
||||
const thresholds = [
|
||||
{ unit: 'second', threshold: 1000 },
|
||||
{ unit: 'minute', threshold: 60 * 1000 },
|
||||
{ unit: 'hour', threshold: 60 * 60 * 1000 },
|
||||
{ unit: 'day', threshold: 24 * 60 * 60 * 1000 },
|
||||
{ unit: 'week', threshold: 7 * 24 * 60 * 60 * 1000 },
|
||||
{ unit: 'month', threshold: 30 * 24 * 60 * 60 * 1000 },
|
||||
{ unit: 'year', threshold: 365 * 24 * 60 * 60 * 1000 },
|
||||
]
|
||||
|
||||
for (let i = thresholds.length - 1; i >= 0; i--) {
|
||||
if (diffInMillis >= thresholds[i].threshold) {
|
||||
const value = Math.round(diffInMillis / thresholds[i].threshold)
|
||||
|
||||
let language = locale ?? 'en'
|
||||
|
||||
if (settings.absoluteDates) {
|
||||
const rtf = new Intl.DateTimeFormat(language, {
|
||||
...options,
|
||||
timeStyle: 'short',
|
||||
dateStyle: 'short',
|
||||
})
|
||||
return rtf.format(date)
|
||||
} else {
|
||||
const rtf = new Intl.RelativeTimeFormat(language, options)
|
||||
return rtf.format(-value, thresholds[i].unit as 'second')
|
||||
}
|
||||
}
|
||||
}
|
||||
return 'Now'
|
||||
} catch {
|
||||
return 'Invalid Date'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { locale } from '$lib/app/i18n'
|
||||
import { settings } from '$lib/settings.svelte'
|
||||
|
||||
const toLocaleDateString = (date: Date): string => {
|
||||
try {
|
||||
return date.toLocaleString()
|
||||
} catch {
|
||||
return 'Invalid Date'
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
date: Date
|
||||
relativeTo?: Date | undefined
|
||||
options?: Intl.RelativeTimeFormatOptions
|
||||
style?: string
|
||||
class?: string
|
||||
}
|
||||
|
||||
let {
|
||||
date,
|
||||
relativeTo = undefined,
|
||||
options = {
|
||||
numeric: 'always',
|
||||
style: 'narrow',
|
||||
},
|
||||
style = '',
|
||||
class: clazz = '',
|
||||
}: Props = $props()
|
||||
|
||||
let dateTime = $derived(toLocaleDateString(date))
|
||||
</script>
|
||||
|
||||
<time datetime={dateTime} title={dateTime} class={clazz} {style}>
|
||||
{formatRelativeDate(date, options, $locale, relativeTo)}
|
||||
</time>
|
||||
Reference in new issue
Block a user