Merge branch 'features/custom-calendar-creation-refactor' into features/custom-calendar-creation
This commit is contained in:
@@ -2,93 +2,26 @@
|
||||
import { useCalendar } from '@/stores/CalendarStore'
|
||||
import { computed, type Component, type ComputedRef } from 'vue'
|
||||
|
||||
import { PhMagnifyingGlass } from '@phosphor-icons/vue'
|
||||
// import { PhMagnifyingGlass } from '@phosphor-icons/vue'
|
||||
import MonthlyLayout from './state/monthly/Layout.vue'
|
||||
import CenturyLayout from './state/centennially/Layout.vue'
|
||||
import DecadeLayout from './state/decennially/Layout.vue'
|
||||
import YearLayout from './state/yearly/Layout.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const worldId = route.params.id
|
||||
import type { Calendar } from '~/models/CalendarConfig'
|
||||
import type { Category } from '~/models/Category'
|
||||
|
||||
const { setCalendarId, setMonths, setDefaultDate, currentConfig, selectedDate, jumpToDate } = useCalendar()
|
||||
const { setEvents, setCategories } = useCalendarEvents()
|
||||
const { setCharacters } = useCharacters()
|
||||
const props = defineProps<{
|
||||
calendarData: Calendar,
|
||||
categories: Category[]
|
||||
}>()
|
||||
|
||||
const { months } = storeToRefs(useCalendar())
|
||||
const { setActiveCalendar } = useCalendar()
|
||||
setActiveCalendar(props.calendarData, props.categories)
|
||||
|
||||
const { data: calendar, pending: calPending, refresh: calRefresh } = await useLazyFetch(`/api/calendars/query?world_id=${worldId}`)
|
||||
const { data: characters, pending: charPending, refresh: charRefresh } = await useLazyFetch(`/api/characters/query?world_id=${worldId}`)
|
||||
const { data: categories, pending: categoryPending, refresh: categoryRefresh } = await useLazyFetch(`/api/calendars/categories/query`)
|
||||
const { currentConfig, jumpToDate, selectedDate } = useCalendar()
|
||||
|
||||
if (!calendar.value) {
|
||||
await calRefresh()
|
||||
} else {
|
||||
if (calendar.value?.data?.id) {
|
||||
setCalendarId(calendar.value?.data?.id)
|
||||
}
|
||||
if (calendar.value?.data?.months) {
|
||||
setMonths(calendar.value?.data?.months)
|
||||
}
|
||||
if (calendar.value?.data?.months) {
|
||||
setMonths(calendar.value?.data?.months)
|
||||
}
|
||||
if (calendar.value?.data?.today) {
|
||||
setDefaultDate(calendar.value?.data?.today)
|
||||
}
|
||||
if (calendar.value?.data?.events) {
|
||||
setEvents(calendar.value?.data?.events)
|
||||
}
|
||||
}
|
||||
|
||||
if (!categories.value) {
|
||||
await categoryRefresh()
|
||||
} else {
|
||||
if (categories.value?.data) {
|
||||
setCategories(categories.value?.data)
|
||||
}
|
||||
}
|
||||
|
||||
if (!characters.value) {
|
||||
await charRefresh()
|
||||
} else {
|
||||
if (characters.value?.data) {
|
||||
setCharacters(characters.value?.data)
|
||||
}
|
||||
}
|
||||
|
||||
watch(calPending, (newStatus) => {
|
||||
if (!newStatus) {
|
||||
if (calendar.value?.data?.id) {
|
||||
setCalendarId(calendar.value?.data?.id)
|
||||
}
|
||||
if (calendar.value?.data?.months) {
|
||||
setMonths(calendar.value?.data?.months)
|
||||
}
|
||||
if (calendar.value?.data?.today) {
|
||||
setDefaultDate(calendar.value?.data?.today)
|
||||
}
|
||||
if (calendar.value?.data?.events) {
|
||||
setEvents(calendar.value?.data?.events)
|
||||
}
|
||||
}
|
||||
})
|
||||
watch(categoryPending, (newStatus) => {
|
||||
if (!newStatus) {
|
||||
if (categories.value?.data) {
|
||||
setCategories(categories.value?.data)
|
||||
}
|
||||
}
|
||||
})
|
||||
watch(charPending, (newStatus) => {
|
||||
if (!newStatus) {
|
||||
if (characters.value?.data) {
|
||||
setCharacters(characters.value?.data)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const progressPercent = computed(() => 100 / [charPending.value, calPending.value, categoryPending.value].filter(Boolean).length)
|
||||
// const { setCharacters } = useCharacters()
|
||||
|
||||
const currentViewComponent: ComputedRef<Component> = computed<Component>(() => {
|
||||
switch (currentConfig.viewType) {
|
||||
@@ -107,42 +40,22 @@ const currentViewComponent: ComputedRef<Component> = computed<Component>(() => {
|
||||
}
|
||||
})
|
||||
|
||||
const { setCurrentMenu } = useUiStore()
|
||||
|
||||
onMounted(() => {
|
||||
jumpToDate(selectedDate)
|
||||
|
||||
setCurrentMenu([
|
||||
{
|
||||
phIcon: shallowRef(PhMagnifyingGlass),
|
||||
tooltip: 'Recherche avancée',
|
||||
action: 'event-search'
|
||||
}
|
||||
])
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-full w-full relative">
|
||||
<TransitionGroup name="screen">
|
||||
<div v-if="calPending || charPending || categoryPending" class="h-full w-full grid place-items-center">
|
||||
<div class="flex flex-col items-center w-1/2">
|
||||
<UiProgress :model-value="progressPercent" />
|
||||
<p class="text-lg mt-2">Chargement en cours…</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="months.length > 0" class="h-full grid grid-rows-[auto,1fr]">
|
||||
<CalendarMenu />
|
||||
<div class="h-full grid grid-rows-[auto,1fr]">
|
||||
<CalendarMenu />
|
||||
|
||||
<KeepAlive>
|
||||
<component :is="currentViewComponent"/>
|
||||
</KeepAlive>
|
||||
<component :is="currentViewComponent" />
|
||||
|
||||
<LazyCalendarSearch />
|
||||
<LazyCalendarFormUpdateEvent />
|
||||
<LazyCalendarFormDeleteEvent />
|
||||
</div>
|
||||
</TransitionGroup>
|
||||
<CalendarSearch />
|
||||
<CalendarFormUpdateEvent />
|
||||
<CalendarFormDeleteEvent />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -8,9 +8,8 @@ const props = defineProps<{
|
||||
tileDate: RPGDate
|
||||
}>()
|
||||
|
||||
const { areDatesIdentical } = useCalendar()
|
||||
const { revealEditEventModal, revealDeleteEventModal } = useCalendarEvents()
|
||||
const { lastActiveEvent } = storeToRefs(useCalendarEvents())
|
||||
const { areDatesIdentical, revealEditEventModal, revealDeleteEventModal } = useCalendar()
|
||||
const { lastActiveEvent } = storeToRefs(useCalendar())
|
||||
|
||||
const spansMultipleDays = computed(() => Boolean(props.event.startDate && props.event.endDate))
|
||||
const isStartEvent = computed(() => spansMultipleDays.value && areDatesIdentical(props.tileDate, props.event.startDate))
|
||||
|
||||
@@ -14,9 +14,8 @@ import {
|
||||
PhEye
|
||||
} from '@phosphor-icons/vue'
|
||||
|
||||
const { defaultDate, getFormattedDateTitle, jumpToDate, getRelativeString } = useCalendar()
|
||||
const { revealEditEventModal, revealDeleteEventModal } = useCalendarEvents()
|
||||
const { lastActiveEvent } = storeToRefs(useCalendarEvents())
|
||||
const { defaultDate, getFormattedDateTitle, jumpToDate, getRelativeString, revealEditEventModal, revealDeleteEventModal } = useCalendar()
|
||||
const { lastActiveEvent } = storeToRefs(useCalendar())
|
||||
|
||||
const props = defineProps<{
|
||||
event: CalendarEvent
|
||||
@@ -136,7 +135,7 @@ function deployDeleteModal() {
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<menu class="absolute top-4 right-4">
|
||||
<menu class="absolute top-4 right-4" :class="cn({ 'top-6': event.hidden })">
|
||||
<UiPopover v-model:open="commandMenuOpened">
|
||||
<UiPopoverTrigger as-child>
|
||||
<UiButton size="icon" variant="ghost">
|
||||
|
||||
@@ -29,7 +29,9 @@ const { revealAdvancedSearch } = useCalendar()
|
||||
</UiButton>
|
||||
</li>
|
||||
<li>
|
||||
<CalendarSwitch />
|
||||
<ClientOnly>
|
||||
<CalendarSwitch />
|
||||
</ClientOnly>
|
||||
</li>
|
||||
</menu>
|
||||
</div>
|
||||
|
||||
@@ -16,7 +16,7 @@ interface DirectionLabels {
|
||||
futureFar: string
|
||||
}
|
||||
|
||||
const { currentConfig, decrementMonth, incrementMonth, decrementYear, incrementYear } =
|
||||
const { currentConfig, decrementViewMonth, incrementViewMonth, decrementViewYear, incrementViewYear } =
|
||||
useCalendar()
|
||||
|
||||
const activeDirectionLabels: ComputedRef<DirectionLabels> = computed(() => {
|
||||
@@ -59,20 +59,20 @@ const activeDirectionLabels: ComputedRef<DirectionLabels> = computed(() => {
|
||||
function toPastFar(): void {
|
||||
switch (currentConfig.viewType) {
|
||||
case 'month':
|
||||
decrementYear()
|
||||
decrementViewYear()
|
||||
break
|
||||
|
||||
case 'year':
|
||||
decrementYear(10)
|
||||
decrementViewYear(10)
|
||||
break
|
||||
|
||||
case 'decade':
|
||||
decrementYear(100)
|
||||
decrementViewYear(100)
|
||||
break
|
||||
|
||||
case 'century':
|
||||
default:
|
||||
decrementYear(1000)
|
||||
decrementViewYear(1000)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -80,20 +80,20 @@ function toPastFar(): void {
|
||||
function toPastNear(): void {
|
||||
switch (currentConfig.viewType) {
|
||||
case 'month':
|
||||
decrementMonth()
|
||||
decrementViewMonth()
|
||||
break
|
||||
|
||||
case 'year':
|
||||
decrementYear()
|
||||
decrementViewYear()
|
||||
break
|
||||
|
||||
case 'decade':
|
||||
decrementYear(10)
|
||||
decrementViewYear(10)
|
||||
break
|
||||
|
||||
case 'century':
|
||||
default:
|
||||
decrementYear(100)
|
||||
decrementViewYear(100)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -101,20 +101,20 @@ function toPastNear(): void {
|
||||
function toFutureNear(): void {
|
||||
switch (currentConfig.viewType) {
|
||||
case 'month':
|
||||
incrementMonth()
|
||||
incrementViewMonth()
|
||||
break
|
||||
|
||||
case 'year':
|
||||
incrementYear()
|
||||
incrementViewYear()
|
||||
break
|
||||
|
||||
case 'decade':
|
||||
incrementYear(10)
|
||||
incrementViewYear(10)
|
||||
break
|
||||
|
||||
case 'century':
|
||||
default:
|
||||
incrementYear(100)
|
||||
incrementViewYear(100)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -122,20 +122,20 @@ function toFutureNear(): void {
|
||||
function toFutureFar(): void {
|
||||
switch (currentConfig.viewType) {
|
||||
case 'month':
|
||||
incrementYear()
|
||||
incrementViewYear()
|
||||
break
|
||||
|
||||
case 'year':
|
||||
incrementYear(10)
|
||||
incrementViewYear(10)
|
||||
break
|
||||
|
||||
case 'decade':
|
||||
incrementYear(100)
|
||||
incrementViewYear(100)
|
||||
break
|
||||
|
||||
case 'century':
|
||||
default:
|
||||
incrementYear(1000)
|
||||
incrementViewYear(1000)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
<script lang="ts" setup>
|
||||
import { type RPGDate } from '@/models/Date'
|
||||
import { useCalendar } from '@/stores/CalendarStore'
|
||||
import { useCalendarEvents } from '@/stores/EventStore'
|
||||
|
||||
import { PhArrowLineLeft, PhArrowLineRight } from '@phosphor-icons/vue'
|
||||
|
||||
const { currentDate, currentConfig, jumpToDate } = useCalendar()
|
||||
const { getRelativeEventFromDate } = useCalendarEvents()
|
||||
const { currentDate, currentConfig, jumpToDate, getRelativeEventFromDate } = useCalendar()
|
||||
|
||||
function handleGotoPreviousEventPage(position: 'next' | 'prev' = 'next') {
|
||||
let fromDate: RPGDate
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
<script lang="ts" setup>
|
||||
import { useCalendar } from '@/stores/CalendarStore'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const { defaultDate, areDatesIdentical } = useCalendar()
|
||||
const { defaultDate, areDatesIdentical, jumpToDefaultDate, getFormattedDateTitle } = useCalendar()
|
||||
const { selectedDate } = storeToRefs(useCalendar())
|
||||
const { jumpToDefaultDate, getFormattedDateTitle } = useCalendar()
|
||||
|
||||
const defaultDateFormatted: string = getFormattedDateTitle(defaultDate, true)
|
||||
|
||||
|
||||
44
components/calendar/dialog/Create.vue
Normal file
44
components/calendar/dialog/Create.vue
Normal file
@@ -0,0 +1,44 @@
|
||||
<script lang="ts" setup>
|
||||
import { PhX } from '@phosphor-icons/vue';
|
||||
import type { World } from '~/models/World';
|
||||
|
||||
defineProps<{
|
||||
world: World,
|
||||
modalState?: boolean
|
||||
}>()
|
||||
|
||||
const calendarSkeletonName = ref<string>('')
|
||||
|
||||
function onChangedName(newName: string) {
|
||||
calendarSkeletonName.value = newName
|
||||
}
|
||||
|
||||
const emit = defineEmits(['on-close'])
|
||||
|
||||
function handleClose() {
|
||||
emit('on-close')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UiAlertDialog :open="modalState">
|
||||
<UiAlertDialogContent class="grid grid-rows-[auto_1fr_auto] items-start min-h-[66vh] max-w-4xl gap-6">
|
||||
<UiAlertDialogTitle>
|
||||
<span class="text-2xl">
|
||||
<strong class="font-bold">{{ world.name }}</strong>
|
||||
<span class="opacity-30"> — </span>
|
||||
<span v-if="calendarSkeletonName">
|
||||
{{ calendarSkeletonName }}
|
||||
</span>
|
||||
<span v-else>Nouveau calendrier</span>
|
||||
</span>
|
||||
</UiAlertDialogTitle>
|
||||
|
||||
<UiButton size="icon" variant="ghost" class="absolute top-4 right-4" title="Fermer la fenêtre" @click="handleClose">
|
||||
<PhX size="20" />
|
||||
</UiButton>
|
||||
|
||||
<CalendarFormCreate @on-changed-name="onChangedName" @on-close="handleClose" />
|
||||
</UiAlertDialogContent>
|
||||
</UiAlertDialog>
|
||||
</template>
|
||||
@@ -1,27 +1,17 @@
|
||||
<script lang="ts" setup>
|
||||
import type { Calendar } from '~/models/CalendarConfig';
|
||||
|
||||
import { PhAlarm, PhCalendarDots, PhWrench } from '@phosphor-icons/vue';
|
||||
import { PhAlarm, PhCalendarDots, PhCircleNotch, PhWrench } from '@phosphor-icons/vue';
|
||||
|
||||
const defaultSkeleton: Calendar = { name: '', today: { day: 1, month: 0, year: 0 }, months: [], events: []}
|
||||
|
||||
const calendarSkeleton = ref<Calendar>({ ...defaultSkeleton })
|
||||
|
||||
async function handleSubmit() {
|
||||
await $fetch(`/api/calendars/create`, { method: 'POST', body: {...calendarSkeleton.value, worldId: 1 } })
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
calendarSkeleton.value = { ...defaultSkeleton }
|
||||
})
|
||||
|
||||
type FormTabs = 'global' | 'months' | 'today' | 'seasons'
|
||||
type FormTabs = 'global' | 'months' | 'today'
|
||||
const activeTab = ref<FormTabs>('global')
|
||||
|
||||
/**
|
||||
* === Months list handling ===
|
||||
*/
|
||||
|
||||
/**
|
||||
* === Current date ===
|
||||
*/
|
||||
@@ -35,20 +25,49 @@ watch(calendarSkeleton.value.months, () => {
|
||||
* === Form Validation ===
|
||||
*/
|
||||
|
||||
/**
|
||||
* Whether the skeleton has valid month data
|
||||
*/
|
||||
/** Whether the skeleton has valid month data */
|
||||
const validSkeletonMonths = computed(() => calendarSkeleton.value.months.length > 0)
|
||||
|
||||
/**
|
||||
* Whether the skeleton has a valid name
|
||||
*/
|
||||
/** Whether the skeleton has a valid name */
|
||||
const validSkeletonGeneral = computed(() => calendarSkeleton.value.name)
|
||||
|
||||
/**
|
||||
* Whether all the data checks above are a-ok
|
||||
*/
|
||||
/** Whether all the data checks above are a-ok */
|
||||
const validSkeleton = computed(() => validSkeletonGeneral.value && validSkeletonMonths.value)
|
||||
|
||||
/** Send the data to the store for validation */
|
||||
const isCreatingCalendar = ref<boolean>(false)
|
||||
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
isCreatingCalendar.value = true
|
||||
await $fetch(`/api/calendars/create`, { method: 'POST', body: {...calendarSkeleton.value, worldId: 1 } })
|
||||
|
||||
emit('on-close')
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
} finally {
|
||||
isCreatingCalendar.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* === Watch for name changes to display above ===
|
||||
*/
|
||||
const emit = defineEmits<{
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
(e: 'on-changed-name', calendarName: string): void
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
(e: 'on-close'): void
|
||||
}>()
|
||||
|
||||
/** Hook to emit a debounced event for the changed skeleton name */
|
||||
const handleNameChange = useDebounceFn(() => {
|
||||
emit('on-changed-name', calendarSkeleton.value.name)
|
||||
}, 400)
|
||||
|
||||
function handleFormCancel() {
|
||||
emit('on-close')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -74,12 +93,6 @@ const validSkeleton = computed(() => validSkeletonGeneral.value && validSkeleton
|
||||
Aujourd'hui
|
||||
</div>
|
||||
</UiTabsTrigger>
|
||||
<!-- <UiTabsTrigger value="seasons" class="font-bold">
|
||||
<div class="flex items-center gap-1">
|
||||
<PhLeaf size="18" weight="fill" />
|
||||
Saisons
|
||||
</div>
|
||||
</UiTabsTrigger> -->
|
||||
</UiTabsList>
|
||||
<UiTabsContent value="global">
|
||||
<input
|
||||
@@ -90,6 +103,7 @@ const validSkeleton = computed(() => validSkeletonGeneral.value && validSkeleton
|
||||
required
|
||||
placeholder="Titre"
|
||||
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"
|
||||
@input="handleNameChange"
|
||||
>
|
||||
</UiTabsContent>
|
||||
<UiTabsContent value="months">
|
||||
@@ -98,11 +112,18 @@ const validSkeleton = computed(() => validSkeletonGeneral.value && validSkeleton
|
||||
<UiTabsContent value="today">
|
||||
<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" :disabled="!validSkeleton">
|
||||
<footer class="flex justify-end gap-2 mt-6">
|
||||
<UiButton type="button" variant="destructive" @click="handleFormCancel">
|
||||
Annuler
|
||||
</UiButton>
|
||||
|
||||
<UiButton type="submit" :disabled="!validSkeleton || isCreatingCalendar">
|
||||
<Transition name="fade">
|
||||
<PhCircleNotch v-if="isCreatingCalendar" size="20" class="opacity-50 animate-spin"/>
|
||||
</Transition>
|
||||
|
||||
Créer
|
||||
</UiButton>
|
||||
</footer>
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
import type { RPGDate } from '~/models/Date';
|
||||
import { PhAlarm, PhCircleNotch, PhEye, PhEyeClosed, PhMapPinArea, PhTag } from '@phosphor-icons/vue'
|
||||
|
||||
const { eventSkeleton, operationInProgress } = storeToRefs(useCalendarEvents())
|
||||
const { resetSkeleton, submitSkeleton, cancelLatestRequest } = useCalendarEvents()
|
||||
const { eventSkeleton, operationInProgress } = storeToRefs(useCalendar())
|
||||
const { resetSkeleton, submitSkeleton, cancelLatestRequest } = useCalendar()
|
||||
const popoverOpen = ref(false)
|
||||
const isLoading = ref(false)
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
<script lang="ts" setup>
|
||||
import { PhCircleNotch } from '@phosphor-icons/vue';
|
||||
|
||||
const { isDeleteEventModalOpen } = storeToRefs(useCalendarEvents())
|
||||
|
||||
const { resetSkeleton, deleteEventFromSkeleton, cancelLatestRequest } = useCalendarEvents()
|
||||
const { eventSkeleton, lastActiveEvent } = storeToRefs(useCalendarEvents())
|
||||
const { resetSkeleton, deleteEventFromSkeleton, cancelLatestRequest } = useCalendar()
|
||||
const { isDeleteEventModalOpen, eventSkeleton, lastActiveEvent } = storeToRefs(useCalendar())
|
||||
|
||||
const isLoading = ref(false)
|
||||
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
import { PhAlarm, PhCircleNotch, PhEye, PhEyeClosed, PhMapPinArea, PhPencilSimpleLine, PhTag } from '@phosphor-icons/vue'
|
||||
import { VisuallyHidden } from 'radix-vue'
|
||||
|
||||
const { isEditEventModalOpen } = storeToRefs(useCalendarEvents())
|
||||
|
||||
const { resetSkeleton, updateEventFromSkeleton, cancelLatestRequest } = useCalendarEvents()
|
||||
const { eventSkeleton, lastActiveEvent } = storeToRefs(useCalendarEvents())
|
||||
const { resetSkeleton, updateEventFromSkeleton, cancelLatestRequest } = useCalendar()
|
||||
const { eventSkeleton, lastActiveEvent, isEditEventModalOpen } = storeToRefs(useCalendar())
|
||||
|
||||
const isLoading = ref(false)
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ watch(modelBuffer.value, () => {
|
||||
model.value = [ ...modelBuffer.value ]
|
||||
})
|
||||
|
||||
const { categories: availableCategories } = useCalendarEvents()
|
||||
const { categories: availableCategories } = useCalendar()
|
||||
|
||||
const searchTerm = ref<string>('')
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ const props = defineProps<{
|
||||
|
||||
const model = defineModel<Category>()
|
||||
|
||||
const { categories: availableCategories } = useCalendarEvents()
|
||||
const { categories: availableCategories } = useCalendar()
|
||||
|
||||
const searchTerm = ref<string>('')
|
||||
|
||||
|
||||
@@ -8,8 +8,6 @@ import {
|
||||
isCalendarEvent,
|
||||
type CalendarEvent,
|
||||
} from '~/models/CalendarEvent'
|
||||
import { useCharacters } from '@/stores/CharacterStore'
|
||||
import { useCalendarEvents } from '@/stores/EventStore'
|
||||
import { capitalize } from '@/utils/Strings'
|
||||
import { useMagicKeys, useScroll, useStorage, whenever } from '@vueuse/core'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
@@ -27,8 +25,7 @@ import {
|
||||
import SearchList from './lists/SearchList.vue'
|
||||
import type { Category } from '~/models/Category'
|
||||
|
||||
const { isAdvancedSearchOpen } = storeToRefs(useCalendar())
|
||||
const { allEvents } = storeToRefs(useCalendarEvents())
|
||||
const { isAdvancedSearchOpen, allEvents } = storeToRefs(useCalendar())
|
||||
const { characters } = storeToRefs(useCharacters())
|
||||
|
||||
const searchQuery = ref<string>('')
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { RPGDate } from '@/models/Date'
|
||||
import type { CalendarEvent } from '@/models/CalendarEvent'
|
||||
import { useCalendar } from '@/stores/CalendarStore'
|
||||
|
||||
import { PhArrowSquareOut, PhHourglassMedium, PhAlarm, PhMapPinArea, PhEye } from '@phosphor-icons/vue'
|
||||
|
||||
@@ -14,9 +13,7 @@ defineEmits<{
|
||||
(e: 'query:date-jump', payload: RPGDate): void
|
||||
}>()
|
||||
|
||||
const { getRelativeString } = useCalendar()
|
||||
|
||||
const { defaultDate, getFormattedDateTitle } = useCalendar()
|
||||
const { getRelativeString, defaultDate, getFormattedDateTitle } = useCalendar()
|
||||
|
||||
const dateDifference: string = getRelativeString(defaultDate, props.event.startDate)
|
||||
const dateDuration: string | null = props.event.endDate
|
||||
@@ -48,18 +45,32 @@ const dateDuration: string | null = props.event.endDate
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-1">
|
||||
<div class="flex gap-2 items-center justify-between mb-1">
|
||||
<template v-if="!event.endDate">
|
||||
<p class="col-span-2 font-semibold text-sm opacity-75">
|
||||
<p class="font-semibold text-sm opacity-75">
|
||||
{{ getFormattedDateTitle(event.startDate, true) }}
|
||||
</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p class="col-span-2 font-semibold text-sm opacity-75">
|
||||
<p class="font-semibold text-sm opacity-75">
|
||||
Du {{ getFormattedDateTitle(event.startDate, true) }} au
|
||||
{{ getFormattedDateTitle(event.endDate, true) }}
|
||||
</p>
|
||||
</template>
|
||||
<div v-if="event.hidden" class="flex justify-end">
|
||||
<UiTooltipProvider :delay-duration="250">
|
||||
<UiTooltip>
|
||||
<UiTooltipTrigger as-child>
|
||||
<UiBadge class="flex gap-1 border-[1px] border-slate-900 hover:bg-slate-300 hover:opacity-100">
|
||||
<PhEye size="16" weight="fill" /> Évènement privé
|
||||
</UiBadge>
|
||||
</UiTooltipTrigger>
|
||||
<UiTooltipContent>
|
||||
<p>Cet évènement est uniquement visible pour vous</p>
|
||||
</UiTooltipContent>
|
||||
</UiTooltip>
|
||||
</UiTooltipProvider>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-1 flex gap-x-2 items-center">
|
||||
@@ -100,18 +111,5 @@ const dateDuration: string | null = props.event.endDate
|
||||
{{ event.description }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<UiTooltipProvider v-if="event.hidden" :delay-duration="250">
|
||||
<UiTooltip>
|
||||
<UiTooltipTrigger as-child>
|
||||
<UiBadge class="absolute -top-2 left-2 flex gap-1 border-[1px] border-slate-900 hover:bg-slate-300 hover:opacity-100">
|
||||
<PhEye size="16" weight="fill" /> Évènement privé
|
||||
</UiBadge>
|
||||
</UiTooltipTrigger>
|
||||
<UiTooltipContent>
|
||||
<p>Cet évènement est uniquement visible pour vous</p>
|
||||
</UiTooltipContent>
|
||||
</UiTooltip>
|
||||
</UiTooltipProvider>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
<script lang="ts" setup>
|
||||
import type { RPGDate } from '@/models/Date'
|
||||
import type { CalendarEvent } from '@/models/CalendarEvent'
|
||||
import { useCalendar } from '@/stores/CalendarStore'
|
||||
import { useCalendarEvents } from '@/stores/EventStore'
|
||||
import { useElementBounding } from '@vueuse/core'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed, ref, type ComputedRef } from 'vue'
|
||||
@@ -18,8 +16,7 @@ const calendarTile = ref()
|
||||
const calendarEventsList = ref()
|
||||
|
||||
const { defaultDate, selectDate, areDatesIdentical } = useCalendar()
|
||||
const { selectedDate } = storeToRefs(useCalendar())
|
||||
const { currentEvents } = storeToRefs(useCalendarEvents())
|
||||
const { selectedDate, currentEvents } = storeToRefs(useCalendar())
|
||||
|
||||
/**
|
||||
* All events with a startDate / endDate that starts or ends on the tile
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useCalendar } from '@/stores/CalendarStore'
|
||||
import { useThrottleFn } from '@vueuse/core'
|
||||
|
||||
const { currentDate, decrementMonth, incrementMonth } = useCalendar()
|
||||
const { currentDate, decrementViewMonth, incrementViewMonth } = useCalendar()
|
||||
const { currentMonthData } = storeToRefs(useCalendar())
|
||||
|
||||
function handleWheel(e: WheelEvent) {
|
||||
@@ -15,24 +15,26 @@ function handleWheel(e: WheelEvent) {
|
||||
}
|
||||
|
||||
const moveCalendarLeft = useThrottleFn(() => {
|
||||
decrementMonth()
|
||||
decrementViewMonth()
|
||||
}, 100)
|
||||
|
||||
const moveCalendarRight = useThrottleFn(() => {
|
||||
incrementMonth()
|
||||
incrementViewMonth()
|
||||
}, 100)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid grid-cols-10" @wheel="handleWheel">
|
||||
<CalendarStateMonthlyDayTile
|
||||
v-for="day in currentMonthData.days"
|
||||
:key="`layout-month-grid-${day}`"
|
||||
:date="{
|
||||
day: day,
|
||||
month: currentDate.currentMonth,
|
||||
year: currentDate.currentYear
|
||||
}"
|
||||
/>
|
||||
<template v-if="currentMonthData">
|
||||
<CalendarStateMonthlyDayTile
|
||||
v-for="day in currentMonthData?.days"
|
||||
:key="`layout-month-grid-${day}`"
|
||||
:date="{
|
||||
day: day,
|
||||
month: currentDate.currentMonth,
|
||||
year: currentDate.currentYear
|
||||
}"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,21 +1,16 @@
|
||||
<script lang="ts" setup>
|
||||
import type { RPGDate } from '@/models/Date'
|
||||
import { useCalendar } from '@/stores/CalendarStore'
|
||||
import { useCalendarEvents } from '@/stores/EventStore'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed, type ComputedRef } from 'vue'
|
||||
|
||||
const { currentDate, defaultDate, selectDate } = useCalendar()
|
||||
const { selectedDate } = storeToRefs(useCalendar())
|
||||
const { currentEvents } = storeToRefs(useCalendarEvents())
|
||||
const { currentDate, defaultDate, selectDate, areDatesIdentical } = useCalendar()
|
||||
const { selectedDate, currentEvents } = storeToRefs(useCalendar())
|
||||
|
||||
const props = defineProps<{
|
||||
monthNumber: number
|
||||
dayNumber: number
|
||||
}>()
|
||||
|
||||
const { areDatesIdentical } = useCalendar()
|
||||
|
||||
const tileDate: ComputedRef<RPGDate> = computed(() => {
|
||||
return {
|
||||
day: props.dayNumber,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useCalendar } from '@/stores/CalendarStore'
|
||||
import { useThrottleFn } from '@vueuse/core'
|
||||
|
||||
const { decrementYear, incrementYear } = useCalendar()
|
||||
const { decrementViewYear, incrementViewYear } = useCalendar()
|
||||
const { sortedMonths: months } = storeToRefs(useCalendar())
|
||||
|
||||
function handleWheel(e: WheelEvent) {
|
||||
@@ -15,11 +15,11 @@ function handleWheel(e: WheelEvent) {
|
||||
}
|
||||
|
||||
const moveCalendarLeft = useThrottleFn(() => {
|
||||
decrementYear()
|
||||
decrementViewYear()
|
||||
}, 100)
|
||||
|
||||
const moveCalendarRight = useThrottleFn(() => {
|
||||
incrementYear()
|
||||
incrementViewYear()
|
||||
}, 100)
|
||||
</script>
|
||||
|
||||
|
||||
@@ -2,15 +2,11 @@
|
||||
import { PhHouse, PhList } from '@phosphor-icons/vue'
|
||||
import type { SidebarMenuActionType } from './SidebarProps';
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
const isHome = computed<boolean>(() => {
|
||||
return route.fullPath === '/'
|
||||
})
|
||||
|
||||
const { revealAdvancedSearch } = useCalendar()
|
||||
const { currentMenu } = storeToRefs(useUiStore())
|
||||
|
||||
const user = useSupabaseUser()
|
||||
|
||||
function handleMenuItemAction(actionType: SidebarMenuActionType) {
|
||||
if (actionType === 'event-search') {
|
||||
revealAdvancedSearch()
|
||||
@@ -27,8 +23,8 @@ function handleMenuItemAction(actionType: SidebarMenuActionType) {
|
||||
</UiButton>
|
||||
</li>
|
||||
|
||||
<li v-if="!isHome">
|
||||
<UiTooltipProvider :delay-duration="100">
|
||||
<template v-if="!user">
|
||||
<UiTooltipProvider :delay-duration="50">
|
||||
<UiTooltip>
|
||||
<UiTooltipTrigger as-child>
|
||||
<UiButton variant="ghost" size="icon" class="rounded-full" as-child>
|
||||
@@ -37,15 +33,15 @@ function handleMenuItemAction(actionType: SidebarMenuActionType) {
|
||||
</RouterLink>
|
||||
</UiButton>
|
||||
</UiTooltipTrigger>
|
||||
<UiTooltipContent :side="'right'">
|
||||
<UiTooltipContent :side="'right'" :side-offset="6">
|
||||
<p>Retourner aux outils</p>
|
||||
</UiTooltipContent>
|
||||
</UiTooltip>
|
||||
</UiTooltipProvider>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<li v-for="(item, i) in currentMenu" :key="i">
|
||||
<UiTooltipProvider :delay-duration="100">
|
||||
<UiTooltipProvider :delay-duration="50">
|
||||
<UiTooltip>
|
||||
<UiTooltipTrigger as-child>
|
||||
<UiButton v-if="item.to" variant="ghost" size="icon" class="rounded-full" as-child>
|
||||
@@ -57,7 +53,7 @@ function handleMenuItemAction(actionType: SidebarMenuActionType) {
|
||||
<component :is="item.phIcon" size="24" weight="fill" />
|
||||
</UiButton>
|
||||
</UiTooltipTrigger>
|
||||
<UiTooltipContent :side="'right'">
|
||||
<UiTooltipContent :side="'right'" :side-offset="6">
|
||||
<p>{{ item.tooltip }}</p>
|
||||
</UiTooltipContent>
|
||||
</UiTooltip>
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { ShallowRef } from "vue"
|
||||
export type SidebarMenuActionType = "event-search"
|
||||
|
||||
export interface SidebarMenuItem {
|
||||
phIcon: ShallowRef
|
||||
phIcon: ShallowRef // use shallowRef to build phIcon
|
||||
tooltip: string
|
||||
action?: SidebarMenuActionType
|
||||
to?: string
|
||||
|
||||
0
components/ui/alert-dialog/AlertDialogClose.vue
Normal file
0
components/ui/alert-dialog/AlertDialogClose.vue
Normal file
@@ -2,7 +2,7 @@ import { z } from "zod"
|
||||
|
||||
export interface RPGDate {
|
||||
day: number
|
||||
month: number | string
|
||||
month: number
|
||||
year: number
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ export default defineNuxtConfig({
|
||||
],
|
||||
css: ['~/assets/main.css'],
|
||||
|
||||
supabase: {
|
||||
redirect: false
|
||||
},
|
||||
|
||||
postcss: {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
@@ -28,8 +32,5 @@ export default defineNuxtConfig({
|
||||
preference: 'dark',
|
||||
fallback: 'dark',
|
||||
},
|
||||
supabase: {
|
||||
redirect: false
|
||||
},
|
||||
eslint: {}
|
||||
})
|
||||
|
||||
40
pages/i/calendar/[id].vue
Normal file
40
pages/i/calendar/[id].vue
Normal file
@@ -0,0 +1,40 @@
|
||||
<script lang="ts" setup>
|
||||
import { PhCircleNotch } from '@phosphor-icons/vue';
|
||||
import type { Calendar } from '~/models/CalendarConfig';
|
||||
import type { Category } from '~/models/Category';
|
||||
|
||||
useHead({
|
||||
title: 'Calendrier'
|
||||
})
|
||||
definePageMeta({
|
||||
middleware: ['auth-guard']
|
||||
})
|
||||
|
||||
const user = useSupabaseUser()
|
||||
// Redirect user back home when they log out on the page
|
||||
watch(user, (n, _o) => {
|
||||
if (!n) {
|
||||
navigateTo('/')
|
||||
}
|
||||
})
|
||||
|
||||
const route = useRoute()
|
||||
const id = route.params.id
|
||||
|
||||
const { data: calendarData, pending: calPending } = useLazyFetch('/api/calendars/query', { key: `calendar-${id}`, query: { id, full: true } })
|
||||
const { data: catData, pending: catPending } = useLazyFetch('/api/calendars/categories/query', { key: `categories-${id}` })
|
||||
|
||||
const cal = computed<Calendar>(() => calendarData?.value?.data as Calendar)
|
||||
const categories = computed<Category[]>(() => catData?.value?.data as Category[])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="calPending || catPending" class="h-full w-full grid place-items-center">
|
||||
<div class="grid gap-2 justify-items-center opacity-50">
|
||||
<p>Chargement du calendrier</p>
|
||||
<PhCircleNotch size="50" class="animate-spin"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Calendar v-else-if="cal && categories" :calendar-data="cal" :categories />
|
||||
</template>
|
||||
@@ -20,9 +20,6 @@ watch(user, (n, _o) => {
|
||||
navigateTo('/')
|
||||
}
|
||||
})
|
||||
|
||||
const { setCurrentMenu } = useUiStore()
|
||||
setCurrentMenu([])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
<script lang="ts" setup>
|
||||
import type { RealtimeChannel } from '@supabase/supabase-js'
|
||||
import { PhPlus } from '@phosphor-icons/vue';
|
||||
import type { World } from '~/models/World';
|
||||
import type { Calendar } from '~/models/CalendarConfig';
|
||||
|
||||
const supabase = useSupabaseClient()
|
||||
const route = useRoute()
|
||||
const id = route.params.id
|
||||
|
||||
const { data: res, pending } = await useFetch(`/api/worlds/query`, { query: { id, full: true } })
|
||||
const { data: res, pending } = await useFetch('/api/worlds/query', { query: { id, full: true } })
|
||||
|
||||
const world = res.value?.data as World
|
||||
const world = ref<World>(res.value?.data as World)
|
||||
|
||||
useHead({
|
||||
title: 'Profil'
|
||||
@@ -25,10 +28,65 @@ watch(user, (n, _o) => {
|
||||
}
|
||||
})
|
||||
|
||||
const { setCurrentMenu } = useUiStore()
|
||||
setCurrentMenu([])
|
||||
const alertModalOpened = ref<boolean>(false)
|
||||
|
||||
const modalOpened = ref<boolean>(false)
|
||||
function handleDialogClose() {
|
||||
alertModalOpened.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* === Calendar subscriptions ===
|
||||
*/
|
||||
|
||||
/** Active calendar channel */
|
||||
let calendarChannel: RealtimeChannel
|
||||
|
||||
/** Handles calendar insertion realtime events */
|
||||
function handleInsertedCalendar(newCalendar: Calendar) {
|
||||
try {
|
||||
world.value.calendars?.push(newCalendar)
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}
|
||||
|
||||
/** Handles calendar deletion realtime events */
|
||||
function handleDeletedCalendar(id: number) {
|
||||
try {
|
||||
world.value.calendars?.splice(world.value.calendars.findIndex(c => c.id === id))
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
calendarChannel = supabase.channel('custom-insert-channel')
|
||||
.on(
|
||||
'postgres_changes',
|
||||
{ event: '*', schema: 'public', table: 'calendars' },
|
||||
(payload) => {
|
||||
switch (payload.eventType) {
|
||||
case 'INSERT':
|
||||
handleInsertedCalendar(payload.new as Calendar)
|
||||
break
|
||||
|
||||
case 'DELETE':
|
||||
handleDeletedCalendar(payload.old.id)
|
||||
break
|
||||
|
||||
default:
|
||||
console.log('Unknown event has been triggered. This should not happen unless Supabase added one somehow.')
|
||||
break
|
||||
}
|
||||
}
|
||||
)
|
||||
.subscribe()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
// Unsubscribe from realtime
|
||||
supabase.removeChannel(calendarChannel)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -53,11 +111,11 @@ const modalOpened = ref<boolean>(false)
|
||||
<UiTooltipProvider :delay-duration="250">
|
||||
<UiTooltip>
|
||||
<UiTooltipTrigger as-child>
|
||||
<UiButton size="icon" class="rounded-full h-8 w-8" @click="() => modalOpened = true">
|
||||
<UiButton size="icon" class="rounded-full h-8 w-8" @click="() => alertModalOpened = true">
|
||||
<PhPlus size="17"/>
|
||||
</UiButton>
|
||||
</UiTooltipTrigger>
|
||||
<UiTooltipContent>
|
||||
<UiTooltipContent :side-offset="10">
|
||||
<p>Ajouter un calendrier</p>
|
||||
</UiTooltipContent>
|
||||
</UiTooltip>
|
||||
@@ -69,7 +127,7 @@ const modalOpened = ref<boolean>(false)
|
||||
<UiCard
|
||||
v-if="calendar"
|
||||
class="w-full transition-all text-slate-100 bg-slate-900 border-slate-700 hover:bg-slate-700 dark:hover:bg-slate-800 dark:border-slate-900 dark:focus-within:outline-slate-900"
|
||||
:link="`/i/world/${world.id}/calendar`"
|
||||
:link="`/i/calendar/${calendar.id}`"
|
||||
>
|
||||
<UiCardHeader>
|
||||
<UiCardTitle>{{ calendar.name }}</UiCardTitle>
|
||||
@@ -88,18 +146,8 @@ const modalOpened = ref<boolean>(false)
|
||||
</template>
|
||||
</Spacing>
|
||||
</section>
|
||||
|
||||
<UiAlertDialog v-model:open="modalOpened">
|
||||
<UiAlertDialogContent class="grid grid-rows-[auto_1fr_auto] items-start min-h-[66vh] max-w-4xl gap-6">
|
||||
<UiAlertDialogTitle>
|
||||
<span class="text-2xl">
|
||||
<strong class="font-bold">{{ world.name }}</strong> — Nouveau calendrier
|
||||
</span>
|
||||
</UiAlertDialogTitle>
|
||||
|
||||
<CalendarFormCreate />
|
||||
</UiAlertDialogContent>
|
||||
</UiAlertDialog>
|
||||
</template>
|
||||
|
||||
<CalendarDialogCreate :world :modal-state="alertModalOpened" @on-close="handleDialogClose" />
|
||||
</main>
|
||||
</template>
|
||||
@@ -1,20 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
useHead({
|
||||
title: 'Calendrier'
|
||||
})
|
||||
definePageMeta({
|
||||
middleware: ['auth-guard']
|
||||
})
|
||||
|
||||
const user = useSupabaseUser()
|
||||
// Redirect user back home when they log out on the page
|
||||
watch(user, (n, _o) => {
|
||||
if (!n) {
|
||||
navigateTo('/')
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Calendar />
|
||||
</template>
|
||||
@@ -2,9 +2,6 @@
|
||||
useHead({
|
||||
title: 'Dashboard'
|
||||
})
|
||||
|
||||
const { setCurrentMenu } = useUiStore()
|
||||
setCurrentMenu([])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { serverSupabaseClient } from "#supabase/server";
|
||||
import { z } from 'zod'
|
||||
import type { Category } from "~/models/Category";
|
||||
|
||||
const querySchema = z.object({
|
||||
id: z.number({ coerce: true }).positive().int().optional(),
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const client = await serverSupabaseClient(event)
|
||||
const query = await getValidatedQuery(event, querySchema.parse)
|
||||
|
||||
setHeader(event, 'Cache-Control', 'public, max-age=3600, s-maxage=7200')
|
||||
|
||||
const output = client
|
||||
.from('calendar_event_categories')
|
||||
@@ -11,5 +19,9 @@ export default defineEventHandler(async (event) => {
|
||||
name
|
||||
`)
|
||||
|
||||
if (query.id) {
|
||||
return output.eq('id', query.id).limit(1).single<Category>()
|
||||
}
|
||||
|
||||
return output.returns<Category[]>()
|
||||
})
|
||||
|
||||
@@ -25,7 +25,7 @@ export default defineEventHandler(async (event) => {
|
||||
.from('calendar_events')
|
||||
.delete()
|
||||
.eq('id', params.id)
|
||||
.single<CalendarEvent>()
|
||||
.maybeSingle<CalendarEvent>()
|
||||
|
||||
if (error) throw error
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from 'zod'
|
||||
import type { CalendarEvent } from "~/models/CalendarEvent";
|
||||
|
||||
const querySchema = z.object({
|
||||
world_id: z.number({ coerce: true }).positive().int()
|
||||
calendarId: z.number({ coerce: true }).positive().int()
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
@@ -17,11 +17,15 @@ export default defineEventHandler(async (event) => {
|
||||
title,
|
||||
description,
|
||||
location,
|
||||
world_calendars (id, world_id)
|
||||
startDate:start_date,
|
||||
endDate:end_date,
|
||||
wiki,
|
||||
category:calendar_event_categories!calendar_events_category_fkey (*),
|
||||
secondaryCategories:calendar_event_categories!calendar_event_categories_links (*)
|
||||
`)
|
||||
|
||||
if (query.world_id) {
|
||||
output.eq('world_calendars.world_id', query.world_id)
|
||||
if (query.calendarId) {
|
||||
output.eq('calendar_id', query.calendarId)
|
||||
}
|
||||
|
||||
return output.returns<CalendarEvent[]>()
|
||||
|
||||
41
server/api/calendars/months/[id].delete.ts
Normal file
41
server/api/calendars/months/[id].delete.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { z } from 'zod'
|
||||
import { serverSupabaseClient } from "#supabase/server"
|
||||
import type { CalendarMonth } from "~/models/CalendarMonth"
|
||||
|
||||
const paramsSchema = z.object({
|
||||
id: z.number({ coerce: true }).positive().int()
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const client = await serverSupabaseClient(event)
|
||||
|
||||
const { data: params, error: paramsError} = await getValidatedRouterParams(event, paramsSchema.safeParse)
|
||||
|
||||
if (paramsError) {
|
||||
throw createError({
|
||||
cause: 'Utilisateur',
|
||||
fatal: false,
|
||||
message: "L'identifiant de l'évènement est manquant ou mal renseigné.",
|
||||
status: 401,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const { data, error } = await client
|
||||
.from('calendar_months')
|
||||
.delete()
|
||||
.eq('id', params.id)
|
||||
.maybeSingle<CalendarMonth>()
|
||||
|
||||
if (error) throw error
|
||||
|
||||
return data
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
cause: 'Serveur',
|
||||
status: 500,
|
||||
fatal: false,
|
||||
message: 'Une erreur inconnue est survenue.'
|
||||
})
|
||||
}
|
||||
})
|
||||
68
server/api/calendars/months/[id].patch.ts
Normal file
68
server/api/calendars/months/[id].patch.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { z } from 'zod'
|
||||
import { serverSupabaseClient } from "#supabase/server"
|
||||
import { calendarMonthSchema, type CalendarMonth } from "~/models/CalendarMonth"
|
||||
|
||||
const paramsSchema = z.object({
|
||||
id: z.number({ coerce: true }).positive().int()
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const client = await serverSupabaseClient(event)
|
||||
|
||||
const { data: params, error: paramsError} = await getValidatedRouterParams(event, paramsSchema.safeParse)
|
||||
const { data: bodyData, error: bodyError } = await readValidatedBody(event, body => calendarMonthSchema.safeParse(body))
|
||||
|
||||
if (paramsError) {
|
||||
console.log(paramsError)
|
||||
throw createError({
|
||||
cause: 'Utilisateur',
|
||||
fatal: false,
|
||||
message: "L'identifiant du mois est manquant ou mal renseigné.",
|
||||
status: 401,
|
||||
})
|
||||
}
|
||||
|
||||
if (bodyError) {
|
||||
console.log(bodyData)
|
||||
throw createError({
|
||||
cause: 'Utilisateur',
|
||||
fatal: false,
|
||||
message: "Le schéma de la requête n'est pas complet ou mal renseigné.",
|
||||
status: 401,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const { data, error } = await client
|
||||
.from('calendar_months')
|
||||
.update(
|
||||
{
|
||||
name: bodyData?.name,
|
||||
days: bodyData.days,
|
||||
position: bodyData?.position,
|
||||
calendar_id: bodyData.calendar_id,
|
||||
} as never
|
||||
)
|
||||
.eq('id', params.id)
|
||||
.select(`
|
||||
id,
|
||||
name,
|
||||
days,
|
||||
position,
|
||||
calendar_id
|
||||
`)
|
||||
.single<CalendarMonth>()
|
||||
|
||||
if (error) throw error
|
||||
|
||||
return data
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
throw createError({
|
||||
cause: 'Serveur',
|
||||
status: 500,
|
||||
fatal: false,
|
||||
message: 'Une erreur inconnue est survenue.'
|
||||
})
|
||||
}
|
||||
})
|
||||
50
server/api/calendars/months/create.post.ts
Normal file
50
server/api/calendars/months/create.post.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { serverSupabaseClient } from "#supabase/server";
|
||||
import { calendarMonthSchema, type CalendarMonth } from "~/models/CalendarMonth"
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const client = await serverSupabaseClient(event)
|
||||
const { data: bodyData, error: schemaError } = await readValidatedBody(event, body => calendarMonthSchema.safeParse(body))
|
||||
|
||||
if (schemaError) {
|
||||
console.log(schemaError)
|
||||
throw createError({
|
||||
cause: 'Utilisateur',
|
||||
fatal: false,
|
||||
message: "Le schéma de la requête n'est pas complet ou mal renseigné.",
|
||||
status: 401,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const { data, error } = await client
|
||||
.from('calendar_months')
|
||||
.insert(
|
||||
{
|
||||
name: bodyData?.name,
|
||||
days: bodyData.days,
|
||||
position: bodyData?.position,
|
||||
calendar_id: bodyData.calendar_id,
|
||||
} as never
|
||||
)
|
||||
.select(`
|
||||
id,
|
||||
name,
|
||||
days,
|
||||
position,
|
||||
calendar_id
|
||||
`)
|
||||
.single<CalendarMonth>()
|
||||
|
||||
if (error) throw error
|
||||
|
||||
return data
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
throw createError({
|
||||
cause: 'Serveur',
|
||||
status: 500,
|
||||
fatal: false,
|
||||
message: 'Une erreur inconnue est survenue.'
|
||||
})
|
||||
}
|
||||
})
|
||||
28
server/api/calendars/months/query.get.ts
Normal file
28
server/api/calendars/months/query.get.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { serverSupabaseClient } from "#supabase/server";
|
||||
import { z } from 'zod'
|
||||
import type { CalendarMonth } from "~/models/CalendarMonth";
|
||||
|
||||
const querySchema = z.object({
|
||||
calendarId: z.number({ coerce: true }).positive().int()
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const client = await serverSupabaseClient(event)
|
||||
const query = await getValidatedQuery(event, querySchema.parse)
|
||||
|
||||
const output = client
|
||||
.from('calendar_months')
|
||||
.select(`
|
||||
id,
|
||||
name,
|
||||
days,
|
||||
position,
|
||||
calendar_id
|
||||
`)
|
||||
|
||||
if (query.calendarId) {
|
||||
output.eq('calendar_id', query.calendarId)
|
||||
}
|
||||
|
||||
return output.returns<CalendarMonth[]>()
|
||||
})
|
||||
@@ -3,36 +3,53 @@ import { z } from 'zod'
|
||||
import type { Calendar } from "~/models/CalendarConfig";
|
||||
|
||||
const querySchema = z.object({
|
||||
world_id: z.number({ coerce: true }).positive().int()
|
||||
id: z.number({ coerce: true }).positive().int().optional(),
|
||||
full: z.boolean({ coerce: true }).optional()
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const client = await serverSupabaseClient(event)
|
||||
const query = await getValidatedQuery(event, querySchema.parse)
|
||||
|
||||
const output = client
|
||||
.from('calendars')
|
||||
.select(`
|
||||
id,
|
||||
name,
|
||||
today,
|
||||
months:calendar_months (*),
|
||||
events:calendar_events (
|
||||
id,
|
||||
title,
|
||||
description,
|
||||
location,
|
||||
hidden,
|
||||
startDate:start_date,
|
||||
endDate:end_date,
|
||||
wiki,
|
||||
category:calendar_event_categories!calendar_events_category_fkey (*),
|
||||
secondaryCategories:calendar_event_categories!calendar_event_categories_links (*)
|
||||
)
|
||||
`)
|
||||
.eq('world_id', query.world_id)
|
||||
.limit(1)
|
||||
.single<Calendar>()
|
||||
setHeader(event, 'Cache-Control', 'public, max-age=3600, s-maxage=7200')
|
||||
|
||||
return output
|
||||
const partialFields = `
|
||||
id,
|
||||
name,
|
||||
today,
|
||||
months:calendar_months (*)
|
||||
`
|
||||
|
||||
const fullFields = `
|
||||
id,
|
||||
name,
|
||||
today,
|
||||
months:calendar_months (*),
|
||||
events:calendar_events (
|
||||
id,
|
||||
title,
|
||||
description,
|
||||
location,
|
||||
hidden,
|
||||
startDate:start_date,
|
||||
endDate:end_date,
|
||||
wiki,
|
||||
category:calendar_event_categories!calendar_events_category_fkey (*),
|
||||
secondaryCategories:calendar_event_categories!calendar_event_categories_links (*)
|
||||
)
|
||||
`
|
||||
|
||||
let output
|
||||
|
||||
if (query.full) {
|
||||
output = client.from('calendars').select(fullFields)
|
||||
} else {
|
||||
output = client.from('calendars').select(partialFields)
|
||||
}
|
||||
|
||||
if (query.id) {
|
||||
return output.eq('id', query.id).limit(1).single<Calendar>()
|
||||
}
|
||||
|
||||
return output.returns<Calendar[]>()
|
||||
})
|
||||
|
||||
@@ -3,7 +3,7 @@ import { serverSupabaseClient } from "#supabase/server";
|
||||
import type { Character } from "~/models/Characters";
|
||||
|
||||
const querySchema = z.object({
|
||||
world_id: z.number({ coerce: true }).positive().int()
|
||||
worldId: z.number({ coerce: true }).positive().int()
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
@@ -23,8 +23,8 @@ export default defineEventHandler(async (event) => {
|
||||
secondaryCategories:character_categories!character_categories_links (*)
|
||||
`)
|
||||
|
||||
if (query.world_id) {
|
||||
output.eq('world_id', query.world_id)
|
||||
if (query.worldId) {
|
||||
output.eq('world_id', query.worldId)
|
||||
}
|
||||
|
||||
return output.returns<Character[]>()
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import {
|
||||
type RPGDate,
|
||||
type RPGDateOrder,
|
||||
import type {
|
||||
RPGDate,
|
||||
RPGDateOrder,
|
||||
} from '@/models/Date'
|
||||
import { useLocalStorage, useUrlSearchParams } from '@vueuse/core'
|
||||
import { defineStore, skipHydrate } from 'pinia'
|
||||
import { computed, ref, type ComputedRef, type Ref } from 'vue'
|
||||
import { useUrlSearchParams } from '@vueuse/core'
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref, type ComputedRef } from 'vue'
|
||||
import type { Calendar } from '~/models/CalendarConfig'
|
||||
import type { CalendarEvent } from '~/models/CalendarEvent'
|
||||
import type { CalendarMonth } from '~/models/CalendarMonth'
|
||||
import type { Category } from '~/models/Category'
|
||||
|
||||
type CalendarViewType = 'month' | 'year' | 'decade' | 'century'
|
||||
|
||||
@@ -22,50 +25,75 @@ type CalendarCurrentDate = {
|
||||
}
|
||||
|
||||
export const useCalendar = defineStore('calendar', () => {
|
||||
const route = useRoute()
|
||||
const isCalendarView: boolean = route.name === 'i-world-id-calendar'
|
||||
|
||||
/**
|
||||
* Static calendar config
|
||||
* This shouldn't change
|
||||
*/
|
||||
const currentConfig: Ref<CalendarCurrentConfig> = ref({
|
||||
const currentConfig = ref<CalendarCurrentConfig>({
|
||||
viewType: 'month'
|
||||
})
|
||||
const viewTypeOptions: Set<CalendarViewType> = new Set<CalendarViewType>([
|
||||
const viewTypeOptions = new Set<CalendarViewType>([
|
||||
'month',
|
||||
'year'
|
||||
])
|
||||
|
||||
const calendarId = ref<number>(0)
|
||||
const activeCalendar = ref<{ id: number; name: string; today: RPGDate} | null>(null)
|
||||
|
||||
function setCalendarId(data: number) {
|
||||
calendarId.value = data
|
||||
}
|
||||
/**
|
||||
* Month list (queried from API)
|
||||
*/
|
||||
const months: Ref<CalendarMonth[]> = ref<CalendarMonth[]>([])
|
||||
const months = ref<CalendarMonth[]>([])
|
||||
|
||||
function setMonths(data: CalendarMonth[]) {
|
||||
months.value = data
|
||||
function setActiveCalendar(calendarData: Calendar, categoryData: Category[]) {
|
||||
try {
|
||||
if (!calendarData.id) return
|
||||
|
||||
activeCalendar.value = {
|
||||
id: calendarData.id,
|
||||
name: calendarData.name,
|
||||
today: calendarData.today
|
||||
}
|
||||
|
||||
setDefaultDate(activeCalendar.value.today)
|
||||
selectDate(activeCalendar.value.today)
|
||||
|
||||
if (!params.day) {
|
||||
params.day = defaultDate.value.day.toString()
|
||||
}
|
||||
if (!params.month) {
|
||||
params.month = defaultDate.value.month.toString()
|
||||
}
|
||||
if (!params.year) {
|
||||
params.year = defaultDate.value.year.toString()
|
||||
}
|
||||
|
||||
months.value = calendarData.months
|
||||
|
||||
baseEvents.value = calendarData.events
|
||||
categories.value = categoryData
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}
|
||||
|
||||
const params = useUrlSearchParams('history', {
|
||||
write: false
|
||||
})
|
||||
|
||||
/**
|
||||
* Sorted month data using the raw months
|
||||
*/
|
||||
const sortedMonths = computed<CalendarMonth[]>(() => months.value.sort((a, b) => a.position - b.position))
|
||||
const monthsPerYear = computed(() => months.value.length)
|
||||
const daysPerYear = computed(() => months.value.reduce((acc, o) => acc + o.days, 0))
|
||||
const monthsPerYear = computed<number>(() => months.value.length)
|
||||
const daysPerYear = computed<number>(() => months.value.reduce((acc, o) => acc + o.days, 0))
|
||||
|
||||
// Default date settings (current day in the world)
|
||||
// The base setting is the first day / month of year 0
|
||||
const defaultDay: Ref<number> = ref<number>(1)
|
||||
const defaultMonth: Ref<number> = ref<number>(0)
|
||||
const defaultYear: Ref<number> = ref<number>(0)
|
||||
const defaultDay = ref<number>(1)
|
||||
const defaultMonth = ref<number>(0)
|
||||
const defaultYear = ref<number>(0)
|
||||
|
||||
// Object representation
|
||||
const defaultDate: ComputedRef<RPGDate> = computed(() => {
|
||||
const defaultDate = computed<RPGDate>(() => {
|
||||
return {
|
||||
day: defaultDay.value,
|
||||
month: defaultMonth.value,
|
||||
@@ -73,42 +101,12 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
}
|
||||
})
|
||||
|
||||
// Set initial value for url search params
|
||||
// The route needs to be check because it should proc the params on anything BUT the calendar route
|
||||
let initialParams: { day?: string, month?: string, year?: string } = {}
|
||||
|
||||
if (isCalendarView) {
|
||||
initialParams = {
|
||||
day: defaultDate.value.day.toString(),
|
||||
month: defaultDate.value.month.toString(),
|
||||
year: defaultDate.value.year.toString()
|
||||
}
|
||||
}
|
||||
|
||||
// Get date from URL params
|
||||
const params = useUrlSearchParams('history', {
|
||||
write: false,
|
||||
initialValue: initialParams,
|
||||
})
|
||||
|
||||
/**
|
||||
* Sets the new defaultDate (aka the "today" value from the calendar)
|
||||
*
|
||||
* @param date The new data to set as defaultDate
|
||||
*/
|
||||
function setDefaultDate(date: RPGDate) {
|
||||
function setDefaultDate(date: RPGDate): void {
|
||||
defaultDay.value = date.day
|
||||
defaultMonth.value = date.month
|
||||
defaultYear.value = date.year
|
||||
}
|
||||
|
||||
// Everytime the defaultDate changes / is set, we should update the params in the URL
|
||||
watch(defaultDate, () => {
|
||||
params.day = String(defaultDate.value.day)
|
||||
params.month = String(defaultDate.value.month)
|
||||
params.year = String(defaultDate.value.year)
|
||||
})
|
||||
|
||||
const currentDay = computed<number>(() => {
|
||||
return Number(params.day)
|
||||
})
|
||||
@@ -160,20 +158,13 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
|
||||
const currentRPGDate = computed<RPGDate>(() => {
|
||||
return {
|
||||
day: currentDate.currentDay.value,
|
||||
month: currentDate.currentMonth.value,
|
||||
year: currentDate.currentYear.value,
|
||||
day: currentDay.value,
|
||||
month: currentMonth.value,
|
||||
year: currentYear.value,
|
||||
}
|
||||
})
|
||||
|
||||
const selectedDate = useLocalStorage<RPGDate>('selected-date', currentRPGDate.value, { deep: true })
|
||||
|
||||
// Same check as above, for selectedDate history
|
||||
if (isCalendarView) {
|
||||
params.day = selectedDate.value.day.toString()
|
||||
params.month = selectedDate.value.month.toString()
|
||||
params.year = selectedDate.value.year.toString()
|
||||
}
|
||||
const selectedDate = ref<RPGDate>({...defaultDate.value})
|
||||
|
||||
/**
|
||||
* Check whether the current viewType is active
|
||||
@@ -199,14 +190,14 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
/**
|
||||
* Moves the current date forward one month
|
||||
*/
|
||||
function incrementMonth(): void {
|
||||
function incrementViewMonth(): void {
|
||||
let newValue = Number(params.month) + 1
|
||||
|
||||
// If the new value would exceed the max number of month per year
|
||||
if (newValue >= monthsPerYear.value) {
|
||||
newValue = 0
|
||||
// Increment the year
|
||||
incrementYear()
|
||||
incrementViewYear()
|
||||
}
|
||||
|
||||
params.month = newValue.toString()
|
||||
@@ -215,26 +206,26 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
/**
|
||||
* Moves the current date backward one month
|
||||
*/
|
||||
function decrementMonth(): void {
|
||||
function decrementViewMonth(): void {
|
||||
let newValue = Number(params.month) - 1
|
||||
|
||||
// If the new value would go below 0
|
||||
if (newValue < 0) {
|
||||
newValue = monthsPerYear.value - 1
|
||||
// Decrement the year
|
||||
decrementYear()
|
||||
decrementViewYear()
|
||||
}
|
||||
|
||||
params.month = newValue.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the previous month number
|
||||
* Get the previous month number of the calendar view
|
||||
*
|
||||
* @param monthNumber Initial month
|
||||
* @returns The previous month number in the year
|
||||
*/
|
||||
function getPreviousMonth(monthNumber: number): number {
|
||||
function getPreviousViewMonth(monthNumber: number): number {
|
||||
const target: number = monthNumber - 1
|
||||
|
||||
if (target < 0) {
|
||||
@@ -245,12 +236,12 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the following month number
|
||||
* Get the following month number of the calendar view
|
||||
*
|
||||
* @param monthNumber Initial month
|
||||
* @returns The next month number in the year
|
||||
*/
|
||||
function getNextMonth(monthNumber: number): number {
|
||||
function getNextViewMonth(monthNumber: number): number {
|
||||
const target: number = monthNumber + 1
|
||||
|
||||
if (target + 1 > monthsPerYear.value) {
|
||||
@@ -261,9 +252,9 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the current date to a particular month
|
||||
* Moves the current view to a particular month
|
||||
*/
|
||||
function setMonth(target: number): void {
|
||||
function setViewMonth(target: number): void {
|
||||
// If the target is outside the month bounds
|
||||
if (target < 0 || target >= monthsPerYear.value) {
|
||||
return
|
||||
@@ -273,18 +264,18 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the current date forward one year
|
||||
* Moves the current view forward one year
|
||||
*/
|
||||
function incrementYear(inc: number = 1): void {
|
||||
function incrementViewYear(inc: number = 1): void {
|
||||
const newValue = Number(params.year) + inc
|
||||
|
||||
params.year = newValue.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the current date backward one year
|
||||
* Moves the current view backward one year
|
||||
*/
|
||||
function decrementYear(inc: number = 1): void {
|
||||
function decrementViewYear(inc: number = 1): void {
|
||||
const newValue = Number(params.year) - inc
|
||||
|
||||
params.year = newValue.toString()
|
||||
@@ -308,7 +299,7 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
/**
|
||||
* State for advanced search modal
|
||||
*/
|
||||
const isAdvancedSearchOpen: Ref<boolean> = ref<boolean>(false)
|
||||
const isAdvancedSearchOpen = ref<boolean>(false)
|
||||
|
||||
function revealAdvancedSearch() {
|
||||
isAdvancedSearchOpen.value = true
|
||||
@@ -577,9 +568,9 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
const currentMonth = sortedMonths.value[datePivot.month]
|
||||
dateAcc.day = currentMonth.days - datePivot.day
|
||||
if (direction === 'future') {
|
||||
datePivot.month = getNextMonth(datePivot.month)
|
||||
datePivot.month = getNextViewMonth(datePivot.month)
|
||||
} else {
|
||||
datePivot.month = getPreviousMonth(datePivot.month)
|
||||
datePivot.month = getPreviousViewMonth(datePivot.month)
|
||||
}
|
||||
datePivot.day = 1
|
||||
|
||||
@@ -622,11 +613,263 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
}
|
||||
}
|
||||
|
||||
const baseEvents = ref<CalendarEvent[]>([])
|
||||
const categories = ref<Category[]>([])
|
||||
|
||||
// Order base events by dates
|
||||
const allEvents = computed<CalendarEvent[]>(() => [...baseEvents.value].sort((a, b) => compareDates(a.startDate, b.startDate, 'desc')))
|
||||
|
||||
// Gets all current event in its default state
|
||||
const currentEvents = ref<CalendarEvent[]>([])
|
||||
|
||||
// Watch for currentDate or events' list changes
|
||||
// This is deep because we're watching an array, and changes need to trigger and mutations like .push and .splice
|
||||
watch([currentRPGDate, allEvents], () => {
|
||||
currentEvents.value = computeCurrentEvents()
|
||||
}, { deep: true, immediate: true })
|
||||
|
||||
/**
|
||||
* Determines if the event can appear in the front end
|
||||
*
|
||||
* This function takes into consideration the viewType of the calendar config
|
||||
*
|
||||
* @param event The event to analyze
|
||||
* @returns Whether the event should appear in the current view
|
||||
*/
|
||||
function shouldEventBeDisplayed(event: CalendarEvent): boolean {
|
||||
const isEventOnCurrentScreen =
|
||||
(event.startDate.year === currentRPGDate.value.year &&
|
||||
event.startDate.month === currentRPGDate.value.month) ||
|
||||
(event.endDate &&
|
||||
event.endDate.year === currentRPGDate.value.year &&
|
||||
event.endDate.month === currentRPGDate.value.month)
|
||||
|
||||
switch (currentConfig.value.viewType) {
|
||||
case 'month':
|
||||
return !!isEventOnCurrentScreen
|
||||
|
||||
case 'year':
|
||||
return event.startDate.year === currentRPGDate.value.year
|
||||
|
||||
case 'decade':
|
||||
return (
|
||||
event.startDate.year >= currentRPGDate.value.year &&
|
||||
event.startDate.year <= currentRPGDate.value.year + 10
|
||||
)
|
||||
|
||||
case 'century':
|
||||
return (
|
||||
event.startDate.year >= currentRPGDate.value.year &&
|
||||
event.startDate.year <= currentRPGDate.value.year + 100
|
||||
)
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches all the current events for the current view
|
||||
*
|
||||
* @returns A list of events that can appear in the current view
|
||||
*/
|
||||
function computeCurrentEvents(): CalendarEvent[] {
|
||||
return [...allEvents.value].filter((event) => shouldEventBeDisplayed(event))
|
||||
}
|
||||
|
||||
/**
|
||||
* From a base event, gets the next or previous one in the timeline
|
||||
*
|
||||
* @param event The event at a given position in the data
|
||||
* @param position Whether we should get the next or previous event
|
||||
* @returns The next event in chronological order
|
||||
*/
|
||||
function getRelativeEventFromEvent(
|
||||
event: CalendarEvent,
|
||||
position: 'next' | 'prev' = 'next',
|
||||
initialIsEnd: boolean = false
|
||||
): { event: CalendarEvent; targetDate: RPGDate } {
|
||||
let dateToParse: RPGDate // Day value of the date that the user interacted with
|
||||
|
||||
if (initialIsEnd && event.endDate) {
|
||||
dateToParse = event.endDate
|
||||
} else {
|
||||
dateToParse = event.startDate
|
||||
}
|
||||
|
||||
return getRelativeEventFromDate(dateToParse, position)
|
||||
}
|
||||
|
||||
/**
|
||||
* From a date, gets the next or previous event in the timeline
|
||||
*
|
||||
* @param date The starting date from which to get the next event
|
||||
* @param position Whether we should get the next or previous event
|
||||
* @returns The next event in chronological order
|
||||
*/
|
||||
function getRelativeEventFromDate(
|
||||
date: RPGDate,
|
||||
position: 'next' | 'prev' = 'next'
|
||||
): { event: CalendarEvent; targetDate: RPGDate } {
|
||||
const pivotValue = convertDateToDays(date)
|
||||
let t: { eventData: CalendarEvent; distance: number; targetKey: 'startDate' | 'endDate' }[] = []
|
||||
|
||||
// Loop over all event once to convert the structure to a usable one
|
||||
for (let i = 0; i < allEvents.value.length; i++) {
|
||||
const e: CalendarEvent = allEvents.value[i]
|
||||
|
||||
// Estimate distance from pivot
|
||||
const startDateDays: number = convertDateToDays(e.startDate)
|
||||
const startDistance: number = startDateDays - pivotValue
|
||||
|
||||
// Push startDate to comparator array
|
||||
t.push({
|
||||
eventData: e,
|
||||
distance: startDistance,
|
||||
targetKey: 'startDate'
|
||||
})
|
||||
|
||||
// Check the same things for endDate
|
||||
if (e.endDate) {
|
||||
const endDateDays: number = convertDateToDays(e.endDate)
|
||||
const endDistance: number = endDateDays - pivotValue
|
||||
|
||||
// Push optional endDate to comparator array
|
||||
t.push({
|
||||
eventData: e,
|
||||
distance: endDistance,
|
||||
targetKey: 'endDate'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Based on the direction, either ignore negative distance (past) or positive distance (future)
|
||||
t = t.filter((i) => {
|
||||
return position === 'next' ? i.distance > 0 : i.distance < 0
|
||||
})
|
||||
|
||||
if (!t.length) {
|
||||
throw new Error(
|
||||
"Aucun évènement suivant ou précédent trouvé ; Peut-être l'évènement se situe au début ou à la fin du calendrier ?"
|
||||
)
|
||||
}
|
||||
|
||||
// Get event with remaining minimum distance
|
||||
const closestEvent = t.reduce((a, b) => {
|
||||
return Math.abs(b.distance) < Math.abs(a.distance) ? b : a
|
||||
})
|
||||
|
||||
return {
|
||||
event: closestEvent.eventData,
|
||||
targetDate: closestEvent.eventData[closestEvent.targetKey]!
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* State for event modal edition
|
||||
*/
|
||||
const isEditEventModalOpen = ref<boolean>(false)
|
||||
|
||||
function revealEditEventModal() {
|
||||
isEditEventModalOpen.value = true
|
||||
}
|
||||
|
||||
/**
|
||||
* State for event modal edition
|
||||
*/
|
||||
const isDeleteEventModalOpen = ref<boolean>(false)
|
||||
|
||||
function revealDeleteEventModal() {
|
||||
isDeleteEventModalOpen.value = true
|
||||
}
|
||||
|
||||
/**
|
||||
* EVENT CREATION FUNCTIONS
|
||||
*/
|
||||
const lastActiveEvent = ref<CalendarEvent | null>()
|
||||
const isCreatingEvent = ref<boolean>(false)
|
||||
const isUpdatingEvent = ref<boolean>(false)
|
||||
const isDeletingEvent = ref<boolean>(false)
|
||||
const operationInProgress = computed<boolean>(() => isCreatingEvent.value || isUpdatingEvent.value || isDeletingEvent.value)
|
||||
let abortController: AbortController | null = null
|
||||
|
||||
/**
|
||||
* Dummy event to hold creation data
|
||||
*/
|
||||
const eventSkeleton = ref<CalendarEvent>({ title: '', startDate: defaultDate.value })
|
||||
|
||||
/**
|
||||
* Resets the dummy event data
|
||||
*/
|
||||
function resetSkeleton() {
|
||||
eventSkeleton.value = { title: '', startDate: defaultDate.value }
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits the skeleton event and creates a real event from its data
|
||||
*
|
||||
* We assume it's been sanitized by the caller
|
||||
*/
|
||||
async function submitSkeleton() {
|
||||
abortController = new AbortController()
|
||||
isCreatingEvent.value = true
|
||||
|
||||
try {
|
||||
const res = await $fetch('/api/calendars/events/create', { method: 'POST', body: { event : eventSkeleton.value, calendarId: activeCalendar.value?.id }, signal: abortController.signal })
|
||||
|
||||
baseEvents.value.push(res)
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
} finally {
|
||||
abortController = null
|
||||
isCreatingEvent.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function updateEventFromSkeleton() {
|
||||
abortController = new AbortController()
|
||||
isUpdatingEvent.value = true
|
||||
|
||||
try {
|
||||
const res = await $fetch(`/api/calendars/events/${eventSkeleton.value.id}`, { method: 'PATCH', body: { event : eventSkeleton.value, calendarId: activeCalendar.value?.id }, signal: abortController.signal })
|
||||
|
||||
const eventIndex = baseEvents.value.findIndex(e => e.id === eventSkeleton.value.id)
|
||||
baseEvents.value[eventIndex] = res
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
} finally {
|
||||
abortController = null
|
||||
isUpdatingEvent.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteEventFromSkeleton() {
|
||||
abortController = new AbortController()
|
||||
isDeletingEvent.value = true
|
||||
|
||||
try {
|
||||
await $fetch(`/api/calendars/events/${eventSkeleton.value.id}`, { method: 'DELETE', signal: abortController.signal })
|
||||
|
||||
const eventIndex = baseEvents.value.findIndex(e => e.id === eventSkeleton.value.id)
|
||||
baseEvents.value.splice(eventIndex, 1)
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
} finally {
|
||||
abortController = null
|
||||
isDeletingEvent.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function cancelLatestRequest() {
|
||||
if (abortController) {
|
||||
abortController.abort()
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
calendarId,
|
||||
setCalendarId,
|
||||
setActiveCalendar,
|
||||
activeCalendar,
|
||||
months,
|
||||
setMonths,
|
||||
sortedMonths,
|
||||
daysPerYear,
|
||||
monthsPerYear,
|
||||
@@ -635,18 +878,17 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
currentDate,
|
||||
currentRPGDate,
|
||||
currentMonthData,
|
||||
defaultDate,
|
||||
setDefaultDate,
|
||||
selectedDate: skipHydrate(selectedDate),
|
||||
defaultDate: defaultDate,
|
||||
selectedDate: selectedDate,
|
||||
selectDate,
|
||||
params,
|
||||
incrementMonth,
|
||||
decrementMonth,
|
||||
setMonth,
|
||||
getPreviousMonth,
|
||||
getNextMonth,
|
||||
incrementYear,
|
||||
decrementYear,
|
||||
incrementViewMonth,
|
||||
decrementViewMonth,
|
||||
setViewMonth,
|
||||
getPreviousViewMonth,
|
||||
getNextViewMonth,
|
||||
incrementViewYear,
|
||||
decrementViewYear,
|
||||
jumpToDate,
|
||||
jumpToDefaultDate,
|
||||
getFormattedDateTitle,
|
||||
@@ -661,5 +903,26 @@ export const useCalendar = defineStore('calendar', () => {
|
||||
areDatesIdentical,
|
||||
compareDates,
|
||||
getRelativeString,
|
||||
baseEvents,
|
||||
allEvents,
|
||||
categories,
|
||||
currentEvents,
|
||||
getRelativeEventFromDate,
|
||||
getRelativeEventFromEvent,
|
||||
cancelLatestRequest,
|
||||
isCreatingEvent,
|
||||
isUpdatingEvent,
|
||||
isDeletingEvent,
|
||||
operationInProgress,
|
||||
eventSkeleton,
|
||||
resetSkeleton,
|
||||
submitSkeleton,
|
||||
lastActiveEvent,
|
||||
updateEventFromSkeleton,
|
||||
deleteEventFromSkeleton,
|
||||
isEditEventModalOpen,
|
||||
revealEditEventModal,
|
||||
isDeleteEventModalOpen,
|
||||
revealDeleteEventModal
|
||||
}
|
||||
})
|
||||
|
||||
@@ -6,13 +6,23 @@ import type { Category } from '~/models/Category'
|
||||
import { useCalendar } from './CalendarStore'
|
||||
|
||||
export const useCalendarEvents = defineStore('calendar-events', () => {
|
||||
const { currentDate, defaultDate, currentConfig, convertDateToDays, compareDates } = useCalendar()
|
||||
const { calendarId } = storeToRefs(useCalendar())
|
||||
const { activeCalendar, defaultDate, currentConfig, convertDateToDays, compareDates } = useCalendar()
|
||||
const { currentRPGDate } = storeToRefs(useCalendar())
|
||||
|
||||
const baseEvents = ref<CalendarEvent[]>([])
|
||||
|
||||
function setEvents(data: CalendarEvent[]) {
|
||||
baseEvents.value = data
|
||||
async function fetchCalendarEvents(calendarId: number) {
|
||||
try {
|
||||
const res = await $fetch('/api/calendars/events/query', { query: { calendarId } })
|
||||
|
||||
const eventData = res.data as CalendarEvent[]
|
||||
|
||||
if (!eventData.length) return
|
||||
|
||||
baseEvents.value = eventData
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}
|
||||
|
||||
const categories = ref<Category[]>([])
|
||||
@@ -31,7 +41,7 @@ export const useCalendarEvents = defineStore('calendar-events', () => {
|
||||
|
||||
// Watch for currentDate or events' list changes
|
||||
// This is deep because we're watching an array, and changes need to trigger and mutations like .push and .splice
|
||||
watch([currentDate, allEvents], () => {
|
||||
watch([currentRPGDate, allEvents], () => {
|
||||
currentEvents.value = computeCurrentEvents()
|
||||
}, { deep: true, immediate: true })
|
||||
|
||||
@@ -45,29 +55,29 @@ export const useCalendarEvents = defineStore('calendar-events', () => {
|
||||
*/
|
||||
function shouldEventBeDisplayed(event: CalendarEvent): boolean {
|
||||
const isEventOnCurrentScreen =
|
||||
(event.startDate.year === currentDate.currentYear &&
|
||||
event.startDate.month === currentDate.currentMonth) ||
|
||||
(event.startDate.year === currentRPGDate.value.day &&
|
||||
event.startDate.month === currentRPGDate.value.month) ||
|
||||
(event.endDate &&
|
||||
event.endDate.year === currentDate.currentYear &&
|
||||
event.endDate.month === currentDate.currentMonth)
|
||||
event.endDate.year === currentRPGDate.value.year &&
|
||||
event.endDate.month === currentRPGDate.value.month)
|
||||
|
||||
switch (currentConfig.viewType) {
|
||||
case 'month':
|
||||
return isEventOnCurrentScreen!
|
||||
|
||||
case 'year':
|
||||
return event.startDate.year === currentDate.currentYear
|
||||
return event.startDate.year === currentRPGDate.value.year
|
||||
|
||||
case 'decade':
|
||||
return (
|
||||
event.startDate.year >= currentDate.currentYear &&
|
||||
event.startDate.year <= currentDate.currentYear + 10
|
||||
event.startDate.year >= currentRPGDate.value.year &&
|
||||
event.startDate.year <= currentRPGDate.value.year + 10
|
||||
)
|
||||
|
||||
case 'century':
|
||||
return (
|
||||
event.startDate.year >= currentDate.currentYear &&
|
||||
event.startDate.year <= currentDate.currentYear + 100
|
||||
event.startDate.year >= currentRPGDate.value.year &&
|
||||
event.startDate.year <= currentRPGDate.value.year + 100
|
||||
)
|
||||
|
||||
default:
|
||||
@@ -222,7 +232,7 @@ export const useCalendarEvents = defineStore('calendar-events', () => {
|
||||
isCreatingEvent.value = true
|
||||
|
||||
try {
|
||||
const res = await $fetch('/api/calendars/events/create', { method: 'POST', body: { event : eventSkeleton.value, calendarId: calendarId.value }, signal: abortController.signal })
|
||||
const res = await $fetch('/api/calendars/events/create', { method: 'POST', body: { event : eventSkeleton.value, calendarId: activeCalendar?.id }, signal: abortController.signal })
|
||||
|
||||
baseEvents.value.push(res)
|
||||
} catch (err) {
|
||||
@@ -238,7 +248,7 @@ export const useCalendarEvents = defineStore('calendar-events', () => {
|
||||
isUpdatingEvent.value = true
|
||||
|
||||
try {
|
||||
const res = await $fetch(`/api/calendars/events/${eventSkeleton.value.id}`, { method: 'PATCH', body: { event : eventSkeleton.value, calendarId: calendarId.value }, signal: abortController.signal })
|
||||
const res = await $fetch(`/api/calendars/events/${eventSkeleton.value.id}`, { method: 'PATCH', body: { event : eventSkeleton.value, calendarId: activeCalendar?.id }, signal: abortController.signal })
|
||||
|
||||
const eventIndex = baseEvents.value.findIndex(e => e.id === eventSkeleton.value.id)
|
||||
baseEvents.value[eventIndex] = res
|
||||
@@ -275,7 +285,7 @@ export const useCalendarEvents = defineStore('calendar-events', () => {
|
||||
|
||||
return {
|
||||
allEvents,
|
||||
setEvents,
|
||||
fetchCalendarEvents,
|
||||
categories,
|
||||
setCategories,
|
||||
currentEvents,
|
||||
|
||||
@@ -160,6 +160,9 @@ alter table public.calendar_events enable row level security;
|
||||
alter table public.calendar_event_categories enable row level security;
|
||||
alter table public.calendar_event_categories_links enable row level security;
|
||||
|
||||
-- Add realtime
|
||||
alter publication supabase_realtime add table calendars;
|
||||
|
||||
-- User policies
|
||||
create policy "Allow logged-in read access" on public.users for select using ( auth.role() = 'authenticated' );
|
||||
create policy "Allow individual insert access" on public.users for insert with check ( auth.uid() = id );
|
||||
@@ -192,42 +195,110 @@ create policy "Allow individual update access for GMs" on public.calendars for u
|
||||
);
|
||||
|
||||
-- Month policies
|
||||
create policy "Allow individual read access for GMs" on public.calendar_months for select using (
|
||||
create policy "Allow GMs to see their calendar's months"
|
||||
on public.calendar_months
|
||||
for select
|
||||
using (
|
||||
exists (
|
||||
select 1 from calendars
|
||||
where calendars.id = calendar_months.calendar_id
|
||||
select 1
|
||||
from public.calendars c
|
||||
join public.worlds w on w.id = c.world_id
|
||||
where
|
||||
c.id = calendar_months.calendar_id
|
||||
and w.gm_id = auth.uid()
|
||||
)
|
||||
);
|
||||
create policy "Allow individual insert access for GMs" on public.calendar_months for insert with check (
|
||||
create policy "Allow GMs to add months on their calendars"
|
||||
on public.calendar_months
|
||||
for insert
|
||||
with check (
|
||||
exists (
|
||||
select 1 from calendars
|
||||
where calendars.id = calendar_months.calendar_id
|
||||
select 1
|
||||
from public.calendars c
|
||||
join public.worlds w on w.id = c.world_id
|
||||
where
|
||||
c.id = calendar_months.calendar_id
|
||||
and w.gm_id = auth.uid()
|
||||
)
|
||||
);
|
||||
create policy "Allow individual update access for GMs" on public.calendar_months for update with check (
|
||||
create policy "Allow GMs to update their calendar's months"
|
||||
on public.calendar_months
|
||||
for update
|
||||
using (
|
||||
exists (
|
||||
select 1 from calendars
|
||||
where calendars.id = calendar_months.calendar_id
|
||||
select 1
|
||||
from public.calendars c
|
||||
join public.worlds w on w.id = c.world_id
|
||||
where
|
||||
c.id = calendar_months.calendar_id
|
||||
and w.gm_id = auth.uid()
|
||||
)
|
||||
);
|
||||
create policy "Allow GMs to delete their calendar's months"
|
||||
on public.calendar_months
|
||||
for delete
|
||||
using (
|
||||
exists (
|
||||
select 1
|
||||
from public.calendars c
|
||||
join public.worlds w on w.id = c.world_id
|
||||
where
|
||||
c.id = calendar_months.calendar_id
|
||||
and w.gm_id = auth.uid()
|
||||
)
|
||||
);
|
||||
|
||||
-- Event policies
|
||||
create policy "Allow individual read access for GMs" on public.calendar_events for select using (
|
||||
create policy "Allow GMs to see their events"
|
||||
on public.calendar_events
|
||||
for select
|
||||
using (
|
||||
exists (
|
||||
select 1 from calendars
|
||||
where calendars.id = calendar_events.calendar_id
|
||||
select 1
|
||||
from public.calendars c
|
||||
join public.worlds w on w.id = c.world_id
|
||||
where
|
||||
c.id = calendar_events.calendar_id
|
||||
and w.gm_id = auth.uid()
|
||||
)
|
||||
);
|
||||
create policy "Allow individual insert access for GMs" on public.calendar_events for insert with check (
|
||||
create policy "Allow GMs to add their events"
|
||||
on public.calendar_events
|
||||
for insert
|
||||
with check (
|
||||
exists (
|
||||
select 1 from calendars
|
||||
where calendars.id = calendar_events.calendar_id
|
||||
select 1
|
||||
from public.calendars c
|
||||
join public.worlds w on w.id = c.world_id
|
||||
where
|
||||
c.id = calendar_events.calendar_id
|
||||
and w.gm_id = auth.uid()
|
||||
)
|
||||
);
|
||||
create policy "Allow individual update access for GMs" on public.calendar_events for update with check (
|
||||
create policy "Allow GMs to update their events"
|
||||
on public.calendar_events
|
||||
for update
|
||||
using (
|
||||
exists (
|
||||
select 1 from calendars
|
||||
where calendars.id = calendar_events.calendar_id
|
||||
select 1
|
||||
from public.calendars c
|
||||
join public.worlds w on w.id = c.world_id
|
||||
where
|
||||
c.id = calendar_events.calendar_id
|
||||
and w.gm_id = auth.uid()
|
||||
)
|
||||
);
|
||||
create policy "Allow GMs to delete their events"
|
||||
on public.calendar_events
|
||||
for delete
|
||||
using (
|
||||
exists (
|
||||
select 1
|
||||
from public.calendars c
|
||||
join public.worlds w on w.id = c.world_id
|
||||
where
|
||||
c.id = calendar_events.calendar_id
|
||||
and w.gm_id = auth.uid()
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user