Skip to content
Snippets Groups Projects
Commit 1b53409b authored by Konrad Mohrfeldt's avatar Konrad Mohrfeldt :koala:
Browse files

feat: add utility functions for reactive (relative) dates

parent 9587c2c0
No related branches found
No related tags found
No related merge requests found
import { computedAsync } from '@vueuse/core'
import { formatDistanceToNow, formatISO, parseISO } from 'date-fns'
import DateFnEnUsLocale from 'date-fns/locale/en-US'
import DOMPurify from 'dompurify'
import { cloneDeep, isEqual } from 'lodash'
import {
computed,
......@@ -14,10 +18,13 @@ import {
watch,
watchEffect,
} from 'vue'
import { formatISO, parseISO } from 'date-fns'
import DOMPurify from 'dompurify'
import { useStore } from 'vuex'
import { Show } from '@/types'
import { useI18n } from '@/i18n'
const dateFnLocales = {
de: () => import('date-fns/locale/de'),
}
export function computedIter<T>(fn: ComputedGetter<Iterable<T>>): ComputedRef<T[]> {
return computed(() => Array.from(fn()))
......@@ -239,3 +246,27 @@ export function computedDebounced<T>(
return shallowReadonly(debouncedValue)
}
export function useDateFnLocale(language: MaybeRefOrGetter<string>) {
return computedAsync(async () => {
const localeString = toValue(language) as keyof typeof dateFnLocales
let locale: Locale = DateFnEnUsLocale
if (localeString in dateFnLocales) {
locale = (await dateFnLocales[localeString]()).default
}
return locale
}, DateFnEnUsLocale)
}
export function useRelativeDistanceToNow(
date: MaybeRefOrGetter<Date | null | undefined>,
options: { includeSeconds?: boolean; addSuffix?: boolean } = {},
) {
const { locale: appLocale } = useI18n()
const dateFnLocale = useDateFnLocale(appLocale)
return computedAsync(async () => {
const dateValue = toValue(date)
if (!dateValue) return ''
return formatDistanceToNow(dateValue, { locale: dateFnLocale.value, ...options })
}, '')
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment