Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 52 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,12 @@
"@nextcloud/logger": "^3.0.2",
"@nextcloud/router": "^3.0.1",
"@nextcloud/sharing": "^0.3.0",
"@vuepic/vue-datepicker": "^11.0.3",
"@vuepic/vue-datepicker": "^12.0.1",
"@vueuse/components": "^14.0.0",
"@vueuse/core": "^14.0.0",
"blurhash": "^2.0.5",
"clone": "^2.1.2",
"date-fns": "^4.1.0",
"debounce": "^3.0.0",
"dompurify": "^3.3.0",
"emoji-mart-vue-fast": "^15.0.5",
Expand Down
96 changes: 66 additions & 30 deletions src/components/NcDateTimePicker/NcDateTimePicker.vue
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,7 @@ export default {
</docs>

<script setup lang="ts">
import type {
// The accepted model value
ModelValue as LibraryModelValue,
// The emitted object for time picker
TimeObj as LibraryTimeObject,
VueDatePickerProps,
} from '@vuepic/vue-datepicker'
import type { Locale } from 'date-fns'

import {
mdiCalendarBlank,
Expand All @@ -189,14 +183,20 @@ import {
getDayNamesMin,
getFirstDay,
} from '@nextcloud/l10n'
import VueDatePicker from '@vuepic/vue-datepicker'
import { VueDatePicker } from '@vuepic/vue-datepicker'
import { computed, useTemplateRef } from 'vue'
import { ref } from 'vue'
import { watch } from 'vue'
import NcIconSvgWrapper from '../NcIconSvgWrapper/NcIconSvgWrapper.vue'
import NcTimezonePicker from '../NcTimezonePicker/NcTimezonePicker.vue'
import { t } from '../../l10n.ts'
import { logger } from '../../utils/logger.ts'
import NcButton from '../NcButton/index.ts'

type LibraryFormatOptions = VueDatePickerProps['format']
type VueDatePickerProps = InstanceType<typeof VueDatePicker>['$props']
type LibraryFormatOptions = NonNullable<VueDatePickerProps['formats']>['input']
type LibraryModelValue = VueDatePickerProps['modelValue']
type LibraryTimeObject = NonNullable<VueDatePickerProps['minTime']>

/**
* The preselected IANA time zone ID for the time zone picker,
Expand Down Expand Up @@ -332,6 +332,9 @@ const emit = defineEmits<{
const targetElement = useTemplateRef('target')
const pickerInstance = useTemplateRef('picker')

const localeObject = ref<Locale>()
watch(() => props.locale, loadLocale, { immediate: true })

/**
* Mapping of the model-value prop to the format expected by the library.
* We do not directly pass the prop and adjust the interface to not transparently wrap the library.
Expand Down Expand Up @@ -359,7 +362,7 @@ const value = computed<LibraryModelValue>(() => {
hours: time.getHours(),
minutes: time.getMinutes(),
seconds: time.getSeconds(),
} satisfies LibraryTimeObject
}
} else if (props.type === 'time-range') {
const time = [props.modelValue].flat()
if (time.length !== 2) {
Expand All @@ -373,7 +376,7 @@ const value = computed<LibraryModelValue>(() => {
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds(),
} as LibraryTimeObject))
}))
} else if (props.type.endsWith('-range')) {
if (props.modelValue === undefined) {
const start = new Date()
Expand Down Expand Up @@ -446,7 +449,7 @@ const realFormat = computed<LibraryFormatOptions>(() => {
return undefined
})

const pickerType = computed(() => ({
const pickerType = computed<Partial<VueDatePickerProps>>(() => ({
timePicker: props.type === 'time' || props.type === 'time-range',
yearPicker: props.type === 'year',
monthPicker: props.type === 'month',
Expand All @@ -457,10 +460,13 @@ const pickerType = computed(() => ({
// but its not covered by our component interface (props / events) documentation so just disabled for now.
partialRange: false,
},
enableTimePicker: !(props.type === 'date' || props.type === 'date-range'),
flow: props.type === 'datetime'
? ['calendar', 'time'] as ['calendar', 'time']
: undefined,
timeConfig: {
enableTimePicker: !(props.type === 'date' || props.type === 'date-range'),
},
...(props.type === 'datetime'
? { flow: { steps: ['calendar', 'time'] as ['calendar', 'time'] } }
: {}
),
}))

/**
Expand All @@ -469,7 +475,7 @@ const pickerType = computed(() => ({
* @param value The value emitted from the underlying library
*/
function onUpdateModelValue(value: LibraryModelValue): void {
if (value === null) {
if (value === null || value === undefined) {
return emit('update:modelValue', null)
}

Expand Down Expand Up @@ -508,18 +514,27 @@ function onUpdateModelValue(value: LibraryModelValue): void {
*/
function formatLibraryTime(time: LibraryTimeObject): Date {
const date = new Date()
date.setHours(time.hours)
date.setMinutes(time.minutes)
date.setSeconds(time.seconds)
date.setHours(toNumber(time.hours))
date.setMinutes(toNumber(time.minutes))
if (time.seconds) {
date.setSeconds(toNumber(time.seconds))
}
return date

/**
* @param value - The value to convert to a number
*/
function toNumber(value: string | number): number {
return typeof value === 'number' ? value : Number.parseInt(value)
}
}

// Localization

const weekStart = getFirstDay()

// day names must be ordered based on week start
const dayNames = [...getDayNamesMin()]
// see https://github.com/Vuepic/vue-datepicker/issues/1159
for (let i = 0; i < weekStart; i++) {
dayNames.push(dayNames.shift() as string)
}
Expand Down Expand Up @@ -587,31 +602,52 @@ function selectDate() {
function cancelSelection() {
pickerInstance.value!.closeMenu()
}

/**
* Load the locale object from date-fns dynamically.
*
* @param locale - The locale to load
*/
async function loadLocale(locale: string) {
try {
const { default: dateFnLocale } = await import(`date-fns/locale/${locale}`)
localeObject.value = dateFnLocale
} catch (error) {
if (locale.includes('-')) {
locale = locale.split('-')[0]!
logger.debug('Try loading fallback locale for NcDateTimePicker', { locale })
await loadLocale(locale)
} else {
logger.error('Failed to load locale for NcDateTimePicker', { locale, error })
}
}
}
</script>

<template>
<div class="vue-date-time-picker__wrapper">
<VueDatePicker
ref="picker"
:aria-labels
:action-row="{
selectBtnLabel: t('Pick'),
cancelBtnLabel: t('Cancel'),
nowBtnLabel: t('Now'),
}"
:auto-apply="!confirm"
class="vue-date-time-picker"
:class="{ 'vue-date-time-picker--clearable': clearable }"
:cancel-text="t('Cancel')"
:clearable
:day-names
:placeholder="placeholder ?? placeholderFallback"
:format="realFormat"
:locale
:formats="{ input: realFormat }"
:input-attrs="{ clearable }"
:locale="localeObject"
:minutes-increment="minuteStep"
:model-value="value"
:now-button-label="t('Now')"
:select-text="t('Pick')"
six-weeks="fair"
:teleport="appendToBody ? (targetElement || undefined) : false"
text-input
:week-num-name
:week-numbers="showWeekNumber ? { type: 'iso' } : undefined"
:week-numbers="showWeekNumber ? { type: 'iso', label: weekNumName } : undefined"
:week-start
v-bind="pickerType"
@update:model-value="onUpdateModelValue">
Expand Down Expand Up @@ -763,7 +799,7 @@ function cancelSelection() {

// make the bottom page toggle stand out better
:deep(.dp__btn.dp__button.dp__button_bottom) {
color: var(--color-primary-element-light);
color: var(--color-primary-element-light-text);
background-color: var(--color-primary-element-light);
}

Expand Down
Loading