feat(Calendar): implement component (#2618)

Co-authored-by: Benjamin Canac <canacb1@gmail.com>
This commit is contained in:
Alex
2024-11-26 16:24:20 +05:00
committed by GitHub
parent 86f2b4856c
commit 2e9aeb5f05
40 changed files with 10278 additions and 18 deletions

View File

@@ -0,0 +1,165 @@
<script lang="ts">
import { tv, type VariantProps } from 'tailwind-variants'
import type { CalendarRootProps, CalendarRootEmits, RangeCalendarRootEmits, DateRange, CalendarCellTriggerProps } from 'radix-vue'
import type { DateValue } from '@internationalized/date'
import type { AppConfig } from '@nuxt/schema'
import _appConfig from '#build/app.config'
import theme from '#build/ui/calendar'
const appConfig = _appConfig as AppConfig & { ui: { calendar: Partial<typeof theme> } }
const calendar = tv({ extend: tv(theme), ...(appConfig.ui?.calendar || {}) })
type CalendarVariants = VariantProps<typeof calendar>
type CalendarModelValue<R extends boolean = false, M extends boolean = false> = R extends true
? DateRange
: M extends true
? DateValue[]
: DateValue
export interface CalendarProps<R extends boolean, M extends boolean> extends Omit<CalendarRootProps, 'modelValue' | 'defaultValue' | 'dir' | 'locale' | 'calendarLabel' | 'multiple'> {
/**
* The element or component this component should render as.
* @defaultValue 'div'
*/
as?: any
color?: CalendarVariants['color']
size?: CalendarVariants['size']
/** Whether or not a range of dates can be selected */
range?: R & boolean
/** Whether or not multiple dates can be selected */
multiple?: M & boolean
/** Show month controls */
monthControls?: boolean
/** Show year controls */
yearControls?: boolean
defaultValue?: CalendarModelValue<R, M>
modelValue?: CalendarModelValue<R, M>
class?: any
ui?: Partial<typeof calendar.slots>
}
export interface CalendarEmits<R extends boolean, M extends boolean> extends Omit<CalendarRootEmits & RangeCalendarRootEmits, 'update:modelValue'> {
'update:modelValue': [date: CalendarModelValue<R, M>]
}
export interface CalendarSlots {
'heading': (props: { value: string }) => any
'day': (props: Pick<CalendarCellTriggerProps, 'day'>) => any
'week-day': (props: { day: string }) => any
}
</script>
<script setup lang="ts" generic="R extends boolean = false, M extends boolean = false">
import { computed } from 'vue'
import { useForwardPropsEmits } from 'radix-vue'
import { Calendar as SingleCalendar, RangeCalendar } from 'radix-vue/namespaced'
import { reactiveOmit } from '@vueuse/core'
import { useLocale } from '../composables/useLocale'
import UButton from './Button.vue'
const props = withDefaults(defineProps<CalendarProps<R, M>>(), {
fixedWeeks: true,
monthControls: true,
yearControls: true
})
const emits = defineEmits<CalendarEmits<R, M>>()
defineSlots<CalendarSlots>()
const { code: locale, dir, t } = useLocale()
const rootProps = useForwardPropsEmits(reactiveOmit(props, 'range', 'modelValue', 'defaultValue', 'color', 'size', 'monthControls', 'yearControls', 'class', 'ui'), emits)
const ui = computed(() => calendar({
color: props.color,
size: props.size
}))
function paginateYear(date: DateValue, sign: -1 | 1) {
if (sign === -1) {
return date.subtract({ years: 1 })
}
return date.add({ years: 1 })
}
const Calendar = computed(() => props.range ? RangeCalendar : SingleCalendar)
</script>
<template>
<Calendar.Root
v-slot="{ weekDays, grid }"
v-bind="rootProps"
:model-value="(modelValue as CalendarModelValue<true & false>)"
:default-value="(defaultValue as CalendarModelValue<true & false>)"
:locale="locale"
:dir="dir"
:class="ui.root({ class: [props.class, props.ui?.root] })"
>
<Calendar.Header :class="ui.header({ class: props.ui?.header })">
<Calendar.Prev v-if="props.yearControls" :prev-page="(date: DateValue) => paginateYear(date, -1)" :aria-label="t('calendar.prevYear')" as-child>
<UButton :icon="appConfig.ui.icons.chevronDoubleLeft" :size="props.size" color="neutral" variant="ghost" />
</Calendar.Prev>
<Calendar.Prev v-if="props.monthControls" :aria-label="t('calendar.prevMonth')" as-child>
<UButton :icon="appConfig.ui.icons.chevronLeft" :size="props.size" color="neutral" variant="ghost" />
</Calendar.Prev>
<Calendar.Heading v-slot="{ headingValue }" :class="ui.heading({ class: props.ui?.heading })">
<slot name="heading" :value="headingValue">
{{ headingValue }}
</slot>
</Calendar.Heading>
<Calendar.Next v-if="props.monthControls" :aria-label="t('calendar.nextMonth')" as-child>
<UButton :icon="appConfig.ui.icons.chevronRight" :size="props.size" color="neutral" variant="ghost" />
</Calendar.Next>
<Calendar.Next v-if="props.yearControls" :next-page="(date: DateValue) => paginateYear(date, 1)" :aria-label="t('calendar.nextYear')" as-child>
<UButton :icon="appConfig.ui.icons.chevronDoubleRight" :size="props.size" color="neutral" variant="ghost" />
</Calendar.Next>
</Calendar.Header>
<div :class="ui.body({ class: props.ui?.body })">
<Calendar.Grid
v-for="month in grid"
:key="month.value.toString()"
:class="ui.grid({ class: props.ui?.grid })"
>
<Calendar.GridHead>
<Calendar.GridRow :class="ui.gridWeekDaysRow({ class: props.ui?.gridWeekDaysRow })">
<Calendar.HeadCell
v-for="day in weekDays"
:key="day"
:class="ui.headCell({ class: props.ui?.headCell })"
>
<slot name="week-day" :day="day">
{{ day }}
</slot>
</Calendar.HeadCell>
</Calendar.GridRow>
</Calendar.GridHead>
<Calendar.GridBody :class="ui.gridBody({ class: props.ui?.gridBody })">
<Calendar.GridRow
v-for="(weekDates, index) in month.rows"
:key="`weekDate-${index}`"
:class="ui.gridRow({ class: props.ui?.gridRow })"
>
<Calendar.Cell
v-for="weekDate in weekDates"
:key="weekDate.toString()"
:date="weekDate"
:class="ui.cell({ class: props.ui?.cell })"
>
<Calendar.CellTrigger
:day="weekDate"
:month="month.value"
:class="ui.cellTrigger({ class: props.ui?.cellTrigger })"
>
<slot name="day" :day="weekDate">
{{ weekDate.day }}
</slot>
</Calendar.CellTrigger>
</Calendar.Cell>
</Calendar.GridRow>
</Calendar.GridBody>
</Calendar.Grid>
</div>
</Calendar.Root>
</template>

View File

@@ -107,7 +107,7 @@ export interface InputMenuProps<T extends MaybeArrayOfArrayItem<I>, I extends Ma
/** The controlled value of the Combobox. Can be binded-with with `v-model`. */
modelValue?: SelectModelValue<T, V, M>
/** Whether multiple options can be selected or not. */
multiple?: M
multiple?: M & boolean
}
export type InputMenuEmits<T, V, M extends boolean> = Omit<ComboboxRootEmits<T>, 'update:modelValue'> & {
@@ -167,11 +167,9 @@ const searchTerm = defineModel<string>('searchTerm', { default: '' })
const appConfig = useAppConfig()
const { t } = useLocale()
const rootProps = useForwardPropsEmits(reactivePick(props, 'as', 'modelValue', 'defaultValue', 'selectedValue', 'open', 'defaultOpen', 'resetSearchTermOnBlur'), emits)
const rootProps = useForwardPropsEmits(reactivePick(props, 'as', 'modelValue', 'defaultValue', 'selectedValue', 'open', 'defaultOpen', 'multiple', 'resetSearchTermOnBlur'), emits)
const contentProps = toRef(() => defu(props.content, { side: 'bottom', sideOffset: 8, position: 'popper' }) as ComboboxContentProps)
const arrowProps = toRef(() => props.arrow as ComboboxArrowProps)
// This is a hack due to generic boolean casting (see https://github.com/nuxt/ui/issues/2541)
const multiple = toRef(() => typeof props.multiple === 'string' ? true : props.multiple)
const { emitFormBlur, emitFormChange, emitFormInput, size: formGroupSize, color, id, name, highlight, disabled } = useFormField<InputProps>(props)
const { orientation, size: buttonGroupSize } = useButtonGroup<InputProps>(props)
@@ -189,7 +187,7 @@ const ui = computed(() => inputMenu({
highlight: highlight.value,
leading: isLeading.value || !!props.avatar || !!slots.leading,
trailing: isTrailing.value || !!slots.trailing,
multiple: multiple.value,
multiple: props.multiple,
buttonGroup: orientation.value
}))
@@ -336,7 +334,6 @@ defineExpose({
v-model:search-term="searchTerm"
:name="name"
:disabled="disabled"
:multiple="multiple"
:display-value="displayValue"
:filter-function="() => rootItems"
:class="ui.root({ class: [props.class, props.ui?.root] })"

View File

@@ -99,7 +99,7 @@ export interface SelectMenuProps<T extends MaybeArrayOfArrayItem<I>, I extends M
/** The controlled value of the Combobox. Can be binded-with with `v-model`. */
modelValue?: SelectModelValue<T, V, M>
/** Whether multiple options can be selected or not. */
multiple?: M
multiple?: M & boolean
}
export type SelectMenuEmits<T, V, M extends boolean> = Omit<ComboboxRootEmits<T>, 'update:modelValue'> & {
@@ -160,12 +160,10 @@ const searchTerm = defineModel<string>('searchTerm', { default: '' })
const appConfig = useAppConfig()
const { t } = useLocale()
const rootProps = useForwardPropsEmits(reactivePick(props, 'modelValue', 'defaultValue', 'selectedValue', 'open', 'defaultOpen', 'resetSearchTermOnBlur'), emits)
const rootProps = useForwardPropsEmits(reactivePick(props, 'modelValue', 'defaultValue', 'selectedValue', 'open', 'defaultOpen', 'multiple', 'resetSearchTermOnBlur'), emits)
const contentProps = toRef(() => defu(props.content, { side: 'bottom', sideOffset: 8, position: 'popper' }) as ComboboxContentProps)
const arrowProps = toRef(() => props.arrow as ComboboxArrowProps)
const searchInputProps = toRef(() => defu(props.searchInput, { placeholder: 'Search...', variant: 'none' }) as InputProps)
// This is a hack due to generic boolean casting (see https://github.com/nuxt/ui/issues/2541)
const multiple = toRef(() => typeof props.multiple === 'string' ? true : props.multiple)
const [DefineCreateItemTemplate, ReuseCreateItemTemplate] = createReusableTemplate()
@@ -187,7 +185,7 @@ const ui = computed(() => selectMenu({
}))
function displayValue(value: T | T[]): string {
if (multiple.value && Array.isArray(value)) {
if (props.multiple && Array.isArray(value)) {
return value.map(v => displayValue(v)).filter(Boolean).join(', ')
}
@@ -307,7 +305,6 @@ function onUpdateOpen(value: boolean) {
as-child
:name="name"
:disabled="disabled"
:multiple="multiple"
:display-value="() => searchTerm"
:filter-function="() => rootItems"
@update:model-value="onUpdate"

View File

@@ -10,6 +10,12 @@ export default defineLocale({
noData: 'لا توجد بيانات',
create: 'إنشاء "{label}"'
},
calendar: {
prevYear: 'السنة السابقة',
nextYear: 'السنة المقبلة',
prevMonth: 'الشهر السابق',
nextMonth: 'الشهر المقبل'
},
inputNumber: {
increment: 'زيادة',
decrement: 'تقليل'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Žádná data',
create: 'Vytvořit "{label}"'
},
calendar: {
prevYear: 'Předchozí rok',
nextYear: 'Další rok',
prevMonth: 'Předchozí měsíc',
nextMonth: 'Další měsíc'
},
inputNumber: {
increment: 'Zvýšit',
decrement: 'Snížit'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Keine Daten',
create: '"{label}" erstellen'
},
calendar: {
prevYear: 'Vorheriges Jahr',
nextYear: 'Nächstes Jahr',
prevMonth: 'Vorheriger Monat',
nextMonth: 'Nächster Monat'
},
inputNumber: {
increment: 'Erhöhen',
decrement: 'Verringern'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'No data',
create: 'Create "{label}"'
},
calendar: {
prevYear: 'Previous year',
nextYear: 'Next year',
prevMonth: 'Previous month',
nextMonth: 'Next month'
},
inputNumber: {
increment: 'Increment',
decrement: 'Decrement'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Sin datos',
create: 'Crear "{label}"'
},
calendar: {
prevYear: 'A o anterior',
nextYear: 'A o siguiente',
prevMonth: 'Mes anterior',
nextMonth: 'Mes siguiente'
},
inputNumber: {
increment: 'Incremento',
decrement: 'Decremento'

View File

@@ -10,6 +10,12 @@ export default defineLocale({
noData: 'داده‌ای موجود نیست',
create: 'ایجاد "{label}"'
},
calendar: {
prevYear: 'سال گذشته',
nextYear: 'سال آینده',
prevMonth: 'ماه گذشته',
nextMonth: 'ماه آینده'
},
inputNumber: {
increment: 'افزایش',
decrement: 'کاهش'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Aucune donnée',
create: 'Créer "{label}"'
},
calendar: {
prevYear: 'Année précédente',
nextYear: 'Année suivante',
prevMonth: 'Mois précédent',
nextMonth: 'Mois suivant'
},
inputNumber: {
increment: 'Augmenter',
decrement: 'Diminuer'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Nessun dato',
create: 'Crea "{label}"'
},
calendar: {
prevYear: 'Anno precedente',
nextYear: 'Anno successivo',
prevMonth: 'Mese precedente',
nextMonth: 'Mese successivo'
},
inputNumber: {
increment: 'Aumenta',
decrement: 'Diminuisci'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: '데이터가 없습니다.',
create: '"{label}" 생성'
},
calendar: {
prevYear: '이전 해',
nextYear: '다음 해',
prevMonth: '이전 달',
nextMonth: '다음 달'
},
inputNumber: {
increment: '증가',
decrement: '감소'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Geen gegevens',
create: '"{label}" creëren'
},
calendar: {
prevYear: 'Vorig jaar',
nextYear: 'Volgend jaar',
prevMonth: 'Vorige maand',
nextMonth: 'Volgende maand'
},
inputNumber: {
increment: 'Verhogen',
decrement: 'Verlagen'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Brak danych',
create: 'Utwórz "{label}"'
},
calendar: {
prevYear: 'Poprzedni rok',
nextYear: 'Przyszły rok',
prevMonth: 'Poprzedni miesiąc',
nextMonth: 'Przyszły miesiąc'
},
inputNumber: {
increment: 'Zwiększ',
decrement: 'Zmniejsz'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Нет данных',
create: 'Создать "{label}"'
},
calendar: {
prevYear: 'Предыдущий год',
nextYear: 'Следующий год',
prevMonth: 'Предыдущий месяц',
nextMonth: 'Следующий месяц'
},
inputNumber: {
increment: 'Увеличить',
decrement: 'Уменьшить'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: 'Veri yok',
create: '"{label}" oluştur'
},
calendar: {
prevYear: 'Önceki yıl',
nextYear: 'Sonraki yıl',
prevMonth: 'Önceki ay',
nextMonth: 'Sonraki ay'
},
inputNumber: {
increment: 'Arttır',
decrement: 'Azalt'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: '没有数据',
create: '创建 "{label}"'
},
calendar: {
prevYear: '去年',
nextYear: '明年',
prevMonth: '上个月',
nextMonth: '下个月'
},
inputNumber: {
increment: '增加',
decrement: '减少'

View File

@@ -9,6 +9,12 @@ export default defineLocale({
noData: '沒有資料',
create: '創建 "{label}"'
},
calendar: {
prevYear: '去年',
nextYear: '明年',
prevMonth: '上个月',
nextMonth: '下个月'
},
inputNumber: {
increment: '增加',
decrement: '减少'

View File

@@ -6,6 +6,7 @@ export * from '../components/AvatarGroup.vue'
export * from '../components/Badge.vue'
export * from '../components/Breadcrumb.vue'
export * from '../components/Button.vue'
export * from '../components/Calendar.vue'
export * from '../components/Card.vue'
export * from '../components/Carousel.vue'
export * from '../components/Checkbox.vue'

View File

@@ -4,6 +4,12 @@ export type Messages = {
noData: string
create: string
}
calendar: {
prevYear: string
nextYear: string
prevMonth: string
nextMonth: string
}
inputNumber: {
increment: string
decrement: string

64
src/theme/calendar.ts Normal file
View File

@@ -0,0 +1,64 @@
import type { ModuleOptions } from '../module'
export default (options: Required<ModuleOptions>) => ({
slots: {
root: '',
header: 'flex items-center justify-between',
body: 'flex flex-col space-y-4 pt-4 sm:flex-row sm:space-x-4 sm:space-y-0',
heading: 'text-center font-medium truncate mx-auto',
grid: 'w-full border-collapse select-none space-y-1 focus:outline-none',
gridRow: 'grid grid-cols-7',
gridWeekDaysRow: 'mb-1 grid w-full grid-cols-7',
gridBody: 'grid',
headCell: 'rounded-[calc(var(--ui-radius)*1.5)]',
cell: 'relative text-center',
cellTrigger: ['m-0.5 relative flex items-center justify-center rounded-full whitespace-nowrap focus-visible:ring-2 focus:outline-none data-disabled:text-[var(--ui-text-muted)] data-unavailable:line-through data-unavailable:text-[var(--ui-text-muted)] data-unavailable:pointer-events-none data-[selected]:text-[var(--ui-bg)] data-today:font-semibold', options.theme.transitions && 'transition']
},
variants: {
color: {
...Object.fromEntries((options.theme.colors || []).map((color: string) => [color, {
headCell: `text-[var(--ui-${color})]`,
cellTrigger: `focus-visible:ring-[var(--ui-${color})] data-[selected]:bg-[var(--ui-${color})] data-today:not-data-[selected]:text-[var(--ui-${color})] data-[highlighted]:bg-[var(--ui-${color})]/20 hover:not-data-[selected]:bg-[var(--ui-${color})]/20`
}])),
neutral: {
headCell: 'text-[var(--ui-bg-inverted)]',
cellTrigger: 'focus-visible:ring-[var(--ui-border-inverted)] data-[selected]:bg-[var(--ui-bg-inverted)] data-today:not-data-[selected]:text-[var(--ui-bg-inverted)] data-[highlighted]:bg-[var(--ui-bg-inverted)]/20 hover:not-data-[selected]:bg-[var(--ui-bg-inverted)]/10'
}
},
size: {
xs: {
heading: 'text-xs',
cell: 'text-xs',
headCell: 'text-[10px]',
cellTrigger: 'size-7',
body: 'space-y-2 pt-2'
},
sm: {
heading: 'text-xs',
headCell: 'text-xs',
cell: 'text-xs',
cellTrigger: 'size-7'
},
md: {
heading: 'text-sm',
headCell: 'text-xs',
cell: 'text-sm',
cellTrigger: 'size-8'
},
lg: {
heading: 'text-md',
headCell: 'text-md',
cellTrigger: 'size-9 text-md'
},
xl: {
heading: 'text-lg',
headCell: 'text-lg',
cellTrigger: 'size-10 text-lg'
}
}
},
defaultVariants: {
size: 'md',
color: 'primary'
}
})

View File

@@ -6,6 +6,7 @@ export { default as badge } from './badge'
export { default as breadcrumb } from './breadcrumb'
export { default as button } from './button'
export { default as buttonGroup } from './button-group'
export { default as calendar } from './calendar'
export { default as card } from './card'
export { default as carousel } from './carousel'
export { default as checkbox } from './checkbox'