Added day selection and revamped modal structure

This commit is contained in:
Alexis
2024-08-17 11:33:42 +02:00
parent 0d57c70719
commit 7244120219
7 changed files with 243 additions and 112 deletions

View File

@@ -1,9 +1,9 @@
<script lang="ts" setup>
import type { Calendar } from '~/models/CalendarConfig';
import { PhAlarm, PhCalendarBlank, PhCalendarDots, PhLeaf, PhWrench } from '@phosphor-icons/vue';
import { PhAlarm, PhCalendarDots, PhWrench } from '@phosphor-icons/vue';
const defaultSkeleton: Calendar = { name: '', today: { day: 1, month: 1, year: 0 }, months: [], events: []}
const defaultSkeleton: Calendar = { name: '', today: { day: 1, month: 0, year: 0 }, months: [], events: []}
const calendarSkeleton = ref<Calendar>({ ...defaultSkeleton })
@@ -16,7 +16,7 @@ onMounted(() => {
})
type FormTabs = 'global' | 'months' | 'today' | 'seasons'
const activeTab = ref<FormTabs>('months')
const activeTab = ref<FormTabs>('global')
/**
* === Months list handling ===
@@ -25,16 +25,37 @@ const activeTab = ref<FormTabs>('months')
/**
* === Current date ===
*/
function setTodayMonth(e: string) {
calendarSkeleton.value.today.month = e
}
// If the months data change, just reset today's month
// This is a failsafe mainly because of 1) month positions and 2) month names
watch(calendarSkeleton.value.months, () => {
calendarSkeleton.value.today.month = 0
}, { deep: true })
/**
* === Form Validation ===
*/
/**
* Whether the skeleton has valid month data
*/
const validSkeletonMonths = computed(() => calendarSkeleton.value.months.length > 0)
/**
* Whether the skeleton has a valid name
*/
const validSkeletonGeneral = computed(() => calendarSkeleton.value.name)
/**
* Whether all the data checks above are a-ok
*/
const validSkeleton = computed(() => validSkeletonGeneral.value && validSkeletonMonths.value)
</script>
<template>
<template v-if="calendarSkeleton">
<form class="h-full grid grid-rows-[auto_1fr_auto]" @submit.prevent="handleSubmit">
<form class="h-full grid grid-rows-[1fr_auto]" @submit.prevent="handleSubmit">
<UiTabs v-model:model-value="activeTab">
<UiTabsList class="grid w-full grid-cols-4">
<UiTabsList class="grid w-full grid-cols-3 mb-4">
<UiTabsTrigger value="global" class="font-bold">
<div class="flex items-center gap-1">
<PhWrench size="18" weight="fill" />
@@ -53,12 +74,12 @@ function setTodayMonth(e: string) {
Aujourd'hui
</div>
</UiTabsTrigger>
<UiTabsTrigger value="seasons" class="font-bold">
<!-- <UiTabsTrigger value="seasons" class="font-bold">
<div class="flex items-center gap-1">
<PhLeaf size="18" weight="fill" />
Saisons
</div>
</UiTabsTrigger>
</UiTabsTrigger> -->
</UiTabsList>
<UiTabsContent value="global">
<input
@@ -68,58 +89,20 @@ function setTodayMonth(e: string) {
name="new-calendar-name"
required
placeholder="Titre"
class="w-full -my-1 py-1 -mx-1 px-1 text-lg border-b-[1px] bg-transparent focus-visible:outline-none focus-visible:border-blue-600"
class="w-full -my-1 py-2 -mx-1 px-1 text-xl border-b-[1px] bg-transparent focus-visible:outline-none focus-visible:border-blue-600"
>
</UiTabsContent>
<UiTabsContent value="months">
<p class="text-lg mb-2 font-semibold">Liste des mois disponibles</p>
<CalendarInputMonthList v-model:model-value="calendarSkeleton.months" />
</UiTabsContent>
<UiTabsContent value="today">
<p class="text-lg mb-2 font-semibold">Date d'aujourd'hui</p>
<div class="grid grid-cols-12 gap-2">
<div class="col-span-2">
<UiInput id="new-month-current-day" v-model="calendarSkeleton.today.day" type="number" name="newMonthCurrentDay" placeholder="Jour" min="1" step="1" class="invalid:border-red-600" />
</div>
<div class="col-span-4">
<UiDropdownMenu>
<UiDropdownMenuTrigger as-child :disabled="calendarSkeleton.months.length < 1">
<UiButton size="sm" variant="secondary" class="w-full h-full">
<PhCalendarBlank size="18" weight="fill" />
<template v-if="calendarSkeleton.months.length < 1">
Aucun mois disponible
</template>
<template v-else>
Choisir le mois
</template>
</UiButton>
</UiDropdownMenuTrigger>
<UiDropdownMenuContent :side="'bottom'" :collision-padding="30">
<UiDropdownMenuLabel>Mois disponibles</UiDropdownMenuLabel>
<UiDropdownMenuSeparator />
<UiDropdownMenuItem
v-for="m in calendarSkeleton.months"
:key="m.name"
@click="setTodayMonth(m.name)"
>
{{ m.name }}
</UiDropdownMenuItem>
</UiDropdownMenuContent>
</UiDropdownMenu>
</div>
<div class="col-span-2">
<UiInput id="new-month-current-day" v-model="calendarSkeleton.today.year" type="number" name="newMonthCurrentYear" placeholder="Année" step="1" class="invalid:border-red-600" />
</div>
</div>
<CalendarInputTodaySelect v-model:model-value="calendarSkeleton.today" :available-months="calendarSkeleton.months"/>
</UiTabsContent>
<UiTabsContent value="seasons" />
</UiTabs>
<footer class="text-right mt-6">
<UiButton type="submit">
<UiButton type="submit" :disabled="!validSkeleton">
Créer
</UiButton>
</footer>

View File

@@ -1,10 +1,13 @@
<script lang="ts" setup>
import { cn } from '~/lib/utils';
import { useSortable } from '@vueuse/integrations/useSortable';
import type { CalendarMonth } from '~/models/CalendarMonth';
import { PhList, PhPlus, PhTrash } from '@phosphor-icons/vue';
const model = defineModel<CalendarMonth[]>({ required: true })
/**
* Input value for new month's name
*/
@@ -12,7 +15,8 @@ const monthName: Ref<string | undefined> = ref<string>()
const monthNameRef = ref<HTMLInputElement>()
const { focused: monthNameFocused } = useFocus(monthNameRef)
const validMonthNameDatatypes = ['string']
const validMonthName = computed(() => validMonthNameDatatypes.includes(typeof monthName.value))
const monthNameIsTaken = computed(() => model.value.find(m => m.name === monthName.value))
const validMonthName = computed(() => validMonthNameDatatypes.includes(typeof monthName.value) && !monthNameIsTaken.value)
/**
* Input value for new month's number of days
@@ -20,14 +24,17 @@ const validMonthName = computed(() => validMonthNameDatatypes.includes(typeof mo
const monthDays: Ref<number | undefined> = ref<number>()
const monthDaysRef = ref<HTMLInputElement>()
const validMonthDaysDatatypes = ['number']
const validMonthDays = computed(() => validMonthDaysDatatypes.includes(typeof monthDays.value))
const validMonthDays = computed(() => validMonthDaysDatatypes.includes(typeof monthDays.value) && monthDays.value && monthDays.value >= 12)
const validNewMonth = computed(() => validMonthDays.value && validMonthName.value)
function addMonthToCalendar() {
console.log(monthDays.value, monthName.value)
/**
* Add current month input data to the model list
*/
function addMonthToModel(): void {
if (!monthDays.value || !monthName.value) return
// Create month object to add
const monthToInsert: CalendarMonth = {
name: monthName.value,
days: monthDays.value,
@@ -36,81 +43,92 @@ function addMonthToCalendar() {
model.value.push(monthToInsert)
// Reset form state
monthName.value = ''
monthNameFocused.value = true
}
function removeMonthFromCalendar(index: number) {
/**
* Remove a specific month from the model
*
* @param index Index position of the month in the model
*/
function removeMonthFromModel(index: number) {
if (isNaN(index)) return
model.value.splice(index, 1)
}
// Sortable
// Sortable setup
const monthSortableList = ref<HTMLElement | null>(null)
useSortable(monthSortableList, model.value, { animation: 150 })
useSortable(monthSortableList, model.value, { animation: 150, handle: ".handle" })
</script>
<template>
<div class="grid md:grid-cols-12 gap-4 items-center">
<div class="md:col-start-2 md:col-span-5">
<UiInput id="new-month-name" ref="monthNameRef" v-model="monthName" type="text" name="newMonthName" placeholder="Nom du mois" />
<UiInput id="new-month-name" ref="monthNameRef" v-model="monthName" type="text" name="newMonthName" placeholder="Nom du mois" :class="cn({ 'border-red-600': monthNameIsTaken })"/>
</div>
<div class="md:col-span-5">
<UiInput id="new-month-days" ref="monthDaysRef" v-model="monthDays" type="number" name="newMonthName" placeholder="Nombre de jours" min="0" step="1" class="invalid:border-red-600" />
</div>
<div class="md:col-span-1">
<UiButton size="icon" class="rounded-full h-8 w-8" :disabled="!validNewMonth" @click.prevent="addMonthToCalendar">
<UiButton size="icon" class="rounded-full h-8 w-8" :disabled="!validNewMonth" @click.prevent="addMonthToModel">
<PhPlus size="17"/>
</UiButton>
</div>
<div class="md:col-span-full">
<div class="md:grid md:grid-cols-12 md:gap-4 md:items-center">
<div class="hidden md:block col-span-1">
<ul class="grid gap-y-4 justify-center">
<li v-for="(m, i) in model" :key="`num-${m.name}`">
<UiButton size="icon" variant="secondary" class="h-8 w-8 rounded-full">
<span class="font-bold text-sm">{{ i + 1 }}</span>
</UiButton>
</li>
</ul>
</div>
<div class="md:col-span-11">
<ul ref="monthSortableList" class="grid gap-y-2">
<li v-for="(m, i) in model" :key="m.name" class="grid md:grid-cols-12 gap-4 md:items-center text-slate-900 bg-slate-200 rounded-md">
<div class="md:col-span-1 text-right duration-200 ease-out transition transform origin-top-right">
<UiButton type="button" variant="ghost" size="icon" class="handle rounded-full h-8 w-8">
<PhList size="17" />
<div class="border-[1px] dark:border-slate-800 p-4 rounded-sm" :class="model.length ? 'md:grid md:grid-cols-12 md:gap-4 md:items-center' : ''">
<div v-if="model.length" class="hidden md:block col-span-1">
<ul class="grid gap-y-4 justify-center">
<li v-for="(m, i) in model" :key="`num-${m.name}`">
<UiButton size="icon" variant="secondary" class="h-8 w-8 rounded-full">
<span class="font-bold text-sm">{{ i + 1 }}</span>
</UiButton>
</div>
<div class="md:col-span-3">
<div class="font-bold md:pl-2">
{{ m.name }}
</div>
</div>
<div class="md:col-span-2">
<UiInput :id="`month-days-n${i}`" v-model="m.days" class="bg-transparent border-none" type="number" :name="`monthDays-n${i}`" placeholder="Nombre de jours" min="0" />
</div>
<div class="md:col-span-1">
jour(s)
</div>
<div class="md:col-start-12">
<UiTooltipProvider>
<UiTooltip>
<UiTooltipTrigger as-child>
<UiButton type="button" variant="ghost" size="icon" class="rounded-full h-8 w-8" @click="removeMonthFromCalendar(i)">
<PhTrash size="17" />
</UiButton>
</UiTooltipTrigger>
<UiTooltipContent>
<p>Supprimer {{ m.name }} du calendrier</p>
</UiTooltipContent>
</UiTooltip>
</UiTooltipProvider>
</div>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="md:col-span-11">
<ul ref="monthSortableList" class="grid gap-y-2" :class="model.length ? 'visible' : 'absolute invisible'">
<template v-if="model.length">
<li v-for="(m, i) in model" :key="m.name" class="grid md:grid-cols-12 gap-4 md:items-center text-slate-900 bg-slate-200 rounded-md">
<div class="md:col-span-1 text-right duration-200 ease-out transition transform origin-top-right">
<UiButton type="button" variant="ghost" size="icon" class="handle rounded-full h-8 w-8">
<PhList size="17" />
</UiButton>
</div>
<div class="md:col-span-3">
<div class="font-bold md:pl-2">
{{ m.name }}
</div>
</div>
<div class="md:col-span-2">
<UiInput :id="`month-days-n${i}`" v-model="m.days" class="bg-transparent border-none" type="number" :name="`monthDays-n${i}`" placeholder="Nombre de jours" min="0" />
</div>
<div class="md:col-span-1">
jour(s)
</div>
<div class="md:col-start-12">
<UiTooltipProvider>
<UiTooltip>
<UiTooltipTrigger as-child>
<UiButton type="button" variant="ghost" size="icon" class="rounded-full h-8 w-8" @click="removeMonthFromModel(i)">
<PhTrash size="17" />
</UiButton>
</UiTooltipTrigger>
<UiTooltipContent>
<p>Supprimer {{ m.name }} du calendrier</p>
</UiTooltipContent>
</UiTooltip>
</UiTooltipProvider>
</div>
</li>
</template>
</ul>
</div>
<template v-if="!model.length">
<p class="col-span-12 text-lg text-center italic opacity-50">Aucun mois pour l'instant</p>
</template>
</div>
</div>
</div>

View File

@@ -0,0 +1,69 @@
<script lang="ts" setup>
import type { CalendarMonth } from '~/models/CalendarMonth';
import type { RPGDate } from '~/models/Date';
import { PhCalendarBlank } from '@phosphor-icons/vue';
const model = defineModel<RPGDate>({ required: true })
const props = defineProps<{
availableMonths: CalendarMonth[]
}>()
/**
*
* @param e The name of today's month
*/
function setTodayMonth(e: string) {
model.value.month = e
}
// When the model changes, get the month index from the month name
watch(model.value, (n, _o) => {
// If the month value is already an index, return early
if (!isNaN(+model.value.month)) return
const monthId = props.availableMonths.findIndex((m) => m.name === n.month)
if (monthId !== -1) {
model.value.month = monthId + 1
}
})
</script>
<template>
<div class="flex gap-2 items-stretch">
<UiInput id="new-month-current-day" v-model="model.day" type="number" name="newMonthCurrentDay" placeholder="Jour" min="1" step="1" class="invalid:border-red-600" />
<UiDropdownMenu>
<UiDropdownMenuTrigger as-child :disabled="props.availableMonths.length < 1">
<UiButton size="sm" variant="secondary">
<PhCalendarBlank size="18" weight="fill" />
<template v-if="props.availableMonths.length < 1">
Aucun mois disponible
</template>
<template v-else-if="model.month && typeof model.month === 'number'">
{{ props.availableMonths[model.month - 1].name }}
</template>
<template v-else>
Choisir le mois
</template>
</UiButton>
</UiDropdownMenuTrigger>
<UiDropdownMenuContent :side="'bottom'" :collision-padding="30">
<UiDropdownMenuLabel>Mois disponibles</UiDropdownMenuLabel>
<UiDropdownMenuSeparator />
<UiDropdownMenuItem
v-for="m in props.availableMonths"
:key="m.name"
@click="setTodayMonth(m.name)"
>
{{ m.name }}
</UiDropdownMenuItem>
</UiDropdownMenuContent>
</UiDropdownMenu>
<UiInput id="new-month-current-day" v-model="model.year" type="number" name="newMonthCurrentYear" placeholder="Année" step="1" class="invalid:border-red-600" />
</div>
</template>

View File

@@ -1,6 +1,6 @@
import { z } from 'zod'
import type { CalendarEvent } from "./CalendarEvent"
import { type CalendarMonth } from "./CalendarMonth"
import { calendarMonthSchema, type CalendarMonth } from "./CalendarMonth"
import { dateSchema, type RPGDate } from "./Date"
export interface CalendarConfig {
@@ -19,5 +19,6 @@ export const postCalendarSchema = z.object({
name: z.string(),
today: dateSchema.optional().nullable(),
color: z.string().optional().nullable(),
months: z.array(calendarMonthSchema).min(1),
worldId: z.number().int(),
})

View File

@@ -10,5 +10,6 @@ export interface CalendarMonth {
export const calendarMonthSchema = z.object({
name: z.string().max(64),
days: z.number().int().min(12),
calendarId: z.number().int()
position: z.number().int().optional().nullable(),
calendar_id: z.number().int().optional().nullable()
})

View File

@@ -90,10 +90,10 @@ const modalOpened = ref<boolean>(false)
</section>
<UiAlertDialog v-model:open="modalOpened">
<UiAlertDialogContent class="grid grid-rows-[auto_1fr_auto] items-start min-h-[66vh] max-w-4xl">
<UiAlertDialogContent class="grid grid-rows-[auto_1fr_auto] items-start min-h-[66vh] max-w-4xl gap-6">
<UiAlertDialogTitle>
<span class="text-2xl">
Créer un calendrier
<strong class="font-bold">{{ world.name }}</strong> Nouveau calendrier
</span>
</UiAlertDialogTitle>

View File

@@ -1,5 +1,6 @@
import { serverSupabaseClient } from "#supabase/server";
// import type { Calendar} from "~/models/CalendarConfig";
import type { Calendar} from "~/models/CalendarConfig";
import { postCalendarSchema } from "~/models/CalendarConfig";
export default defineEventHandler(async (event) => {
@@ -7,7 +8,6 @@ export default defineEventHandler(async (event) => {
const { data: bodyData, error: schemaError } = await readValidatedBody(event, body => postCalendarSchema.safeParse(body))
if (schemaError) {
console.log(bodyData)
console.log(schemaError)
throw createError({
cause: 'Utilisateur',
@@ -17,7 +17,8 @@ export default defineEventHandler(async (event) => {
})
}
let calendarObject: any
// Store calendarId for rollback / links
let calendarId: number | null = null
// First insert the calendar
try {
@@ -33,10 +34,68 @@ export default defineEventHandler(async (event) => {
)
.select(`id`)
.single()
console.log(data)
if (data?.id) {
calendarId = data.id
}
if (error) throw error
} catch (err) {
console.log(err)
throw createError({
cause: 'Serveur',
fatal: false,
message: "Une erreur inconnue s'est produite pendant la création du calendrier.",
status: 500,
})
}
// Setup months data
for (let i = 0; i < bodyData.months.length; i++) {
bodyData.months[i].calendar_id = calendarId
bodyData.months[i].position = i
}
// Bulk insert the months
try {
const { error } = await client
.from('calendar_months')
.insert(bodyData.months as never)
if (error) throw error
} catch (err) {
// If we found an error, rollback the calendar
if (calendarId) {
await client
.from('calendars')
.delete()
.eq('id', calendarId)
.single()
}
throw createError({
cause: 'Serveur',
fatal: false,
message: "Une erreur inconnue s'est produite pendant la création des mois du calendrier.",
status: 500,
})
}
if (calendarId) {
try {
return client
.from('calendars')
.select("*")
.eq('id', calendarId)
.limit(1)
.single<Calendar>()
} catch (err) {
throw createError({
cause: 'Serveur',
fatal: false,
message: "Impossible de récupérer les données du calendrier créé.",
status: 500,
})
}
}
})