Skip to content

Commit

Permalink
fix(NcDateTime): When relative time is disabled return a string and n…
Browse files Browse the repository at this point in the history
…ot the reference to it

The `.value` call was missing in case of disabled relative time. This causes the string to be quoted (because of stringification of the computed value).
To prevent similar issues the file is now migrated to Typescript, also fixed some other issues discovered by type checking.

Signed-off-by: Ferdinand Thiessen <[email protected]>
  • Loading branch information
susnux committed Apr 12, 2024
1 parent 87631ef commit 557b1ec
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 21 deletions.
5 changes: 3 additions & 2 deletions src/components/NcDateTime/NcDateTime.vue
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,13 @@ h4 {
<template>
<span class="nc-datetime"
:data-timestamp="timestamp"
:title="formattedFullTime">{{ formattedTime }}</span>
:title="formattedFullTime"
v-text="formattedTime" />
</template>

<script>
import { computed } from 'vue'
import { useFormatDateTime } from '../../composables/useFormatDateTime.js'
import { useFormatDateTime } from '../../composables/useFormatDateTime.ts'
export default {
name: 'NcDateTime',
Expand Down
2 changes: 1 addition & 1 deletion src/composables/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@

export * from './useIsFullscreen/index.js'
export * from './useIsMobile/index.js'
export * from './useFormatDateTime.js'
export * from './useFormatDateTime.ts'
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
*/

import { getCanonicalLocale } from '@nextcloud/l10n'
import { computed, onUnmounted, ref, onMounted, watch, unref } from 'vue'
import { computed, onUnmounted, ref, onMounted, watch, unref, type Ref } from 'vue'
import { t } from '../l10n.js'

const FEW_SECONDS_AGO = {
Expand All @@ -30,6 +30,23 @@ const FEW_SECONDS_AGO = {
narrow: t('sec. ago'), // FOR TRANSLATORS: If possible in your language an even shorter version of 'a few seconds ago'
}

interface FormatDateOptions {
/**
* The format used for displaying, or if relative time is used the format used for the title
*/
format?: Intl.DateTimeFormatOptions
/**
* Ignore seconds when displaying the relative time and just show `a few seconds ago`
*/
ignoreSeconds?: boolean
/**
* Wether to display the timestamp as time from now
*/
relativeTime?: false | 'long' | 'short' | 'narrow'
}

type MaybeRef<T> = T | Ref<T>

/**
* Composable for formatting time stamps using current users locale
*
Expand All @@ -39,35 +56,40 @@ const FEW_SECONDS_AGO = {
* @param {boolean} opts.ignoreSeconds Ignore seconds when displaying the relative time and just show `a few seconds ago`
* @param {false | 'long' | 'short' | 'narrow'} opts.relativeTime Wether to display the timestamp as time from now (optional)
*/
export function useFormatDateTime(timestamp = Date.now(), opts = {}) {
export function useFormatDateTime(
timestamp: MaybeRef<Date|number> = Date.now(),
opts: MaybeRef<FormatDateOptions> = {},
) {
// Current time as Date.now is not reactive
const currentTime = ref(Date.now())
// The interval ID for the window
let intervalId = null
let intervalId: number|undefined

const options = ref({
timeStyle: 'medium',
dateStyle: 'short',
relativeTime: 'long',
format: {
timeStyle: 'medium',
dateStyle: 'short',
} as Intl.DateTimeFormatOptions,
relativeTime: 'long' as const,
ignoreSeconds: false,
...unref(opts),
})
const wrappedOptions = computed(() => ({ ...unref(opts), ...options.value }))
const wrappedOptions = computed<Required<FormatDateOptions>>(() => ({ ...unref(opts), ...options.value }))

/** ECMA Date object of the timestamp */
const date = computed(() => new Date(unref(timestamp)))

const formattedFullTime = computed(() => {
const formattedFullTime = computed<string>(() => {
const formatter = new Intl.DateTimeFormat(getCanonicalLocale(), wrappedOptions.value.format)
return formatter.format(date.value)
})

/** Time string formatted for main text */
const formattedTime = computed(() => {
const formattedTime = computed<string>(() => {
if (wrappedOptions.value.relativeTime !== false) {
const formatter = new Intl.RelativeTimeFormat(getCanonicalLocale(), { numeric: 'auto', style: wrappedOptions.value.relativeTime })

const diff = date.value - currentTime.value
const diff = date.value.getTime() - currentTime.value
const seconds = diff / 1000
if (Math.abs(seconds) <= 90) {
if (wrappedOptions.value.ignoreSeconds) {
Expand Down Expand Up @@ -98,22 +120,22 @@ export function useFormatDateTime(timestamp = Date.now(), opts = {}) {
}
return formatter.format(Math.round(days / 365), 'year')
}
return formattedFullTime
return formattedFullTime.value
})

// Set or clear interval if relative time is dis/enabled
watch([wrappedOptions], (opts) => {
watch([wrappedOptions], () => {
window.clearInterval(intervalId)
intervalId = undefined
if (opts.relativeTime) {
intervalId = window.setInterval(() => { currentTime.value = new Date() }, 1000)
if (wrappedOptions.value.relativeTime) {
intervalId = window.setInterval(() => { currentTime.value = Date.now() }, 1000)
}
})

// Start the interval for setting the current time if relative time is enabled
onMounted(() => {
if (wrappedOptions.value.relativeTime !== false) {
intervalId = window.setInterval(() => { currentTime.value = new Date() }, 1000)
intervalId = window.setInterval(() => { currentTime.value = Date.now() }, 1000)
}
})

Expand Down
2 changes: 1 addition & 1 deletion tests/unit/composables/useFormatDateTime.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
*
*/

import { useFormatDateTime } from '../../../src/composables/useFormatDateTime.js'
import { useFormatDateTime } from '../../../src/composables/useFormatDateTime.ts'
import { isRef, nextTick, ref } from 'vue'

describe('useFormatDateTime composable', () => {
Expand Down
4 changes: 2 additions & 2 deletions vite.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ const entryPoints = {
return acc
}, {}),

...globSync('src/composables/*/index.js').reduce((acc, item) => {
...globSync(['src/composables/*/index.js', 'src/composables/*/index.ts']).reduce((acc, item) => {
const name = item
.replace('/index.js', '')
.replace(/\/index\.[jt]s/, '')
.replace('src/composables/', 'Composables/')
acc[name] = join(__dirname, item)
return acc
Expand Down

0 comments on commit 557b1ec

Please sign in to comment.