chore: clean up

This commit is contained in:
Dominik Pschenitschni 2022-10-17 23:20:52 +02:00
parent abebd55e0f
commit 975ff6f20b
Signed by: dpschen
GPG Key ID: B257AC0149F43A77
9 changed files with 132 additions and 168 deletions

View File

@ -9,7 +9,7 @@
</template>
<script lang="ts">
import Flatpickr from 'flatpickr';
import Flatpickr from 'flatpickr'
import 'flatpickr/dist/flatpickr.css'
// FIXME: Not sure how to alias these correctly
@ -20,18 +20,22 @@ type Options = Flatpickr.Options.Options
type DateOption = Flatpickr.Options.DateOption
function camelToKebab(string: string) {
return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
};
function arrayify<T extends unknown>(obj: T) {
return obj instanceof Array ? obj : [obj];
return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}
function nullify<T extends unknown>(value: T) {
return (value && (value as unknown[]).length) ? value : null;
function arrayify<T = unknown>(obj: T) {
return obj instanceof Array
? obj
: [obj]
}
function cloneObject<T extends {}>(obj: T): T {
function nullify<T = unknown>(value: T) {
return (value && (value as unknown[]).length)
? value
: null
}
function cloneObject<T = Record<string, unknown>>(obj: T): T {
return Object.assign({}, obj)
}
@ -56,13 +60,13 @@ const excludedEvents = [
] as HookKey[]
// Keep a copy of all events for later use
const allEvents = includedEvents.concat(excludedEvents);
const allEvents = includedEvents.concat(excludedEvents)
export default {inheritAttrs: false}
</script>
<script setup lang="ts">
import {computed, onBeforeUnmount, onMounted, ref, toRefs, useAttrs, watch, watchEffect, type PropType} from 'vue';
import {computed, onBeforeUnmount, onMounted, ref, toRefs, useAttrs, watch, watchEffect, type PropType} from 'vue'
const props = defineProps({
modelValue: {
@ -85,23 +89,23 @@ const props = defineProps({
type: Object as PropType<Options>,
default: () => ({
wrap: false,
defaultDate: null
})
defaultDate: null,
}),
},
events: {
type: Array as PropType<HookKey[]>,
default: () => includedEvents
default: () => includedEvents,
},
disabled: {
type: Boolean,
default: false
}
default: false,
},
})
const emit = defineEmits([
'blur',
'update:modelValue',
...allEvents.map(camelToKebab)
...allEvents.map(camelToKebab),
])
const {modelValue, config, disabled} = toRefs(props)
@ -110,12 +114,12 @@ const {modelValue, config, disabled} = toRefs(props)
const attrs = useAttrs()
const root = ref<HTMLInputElement | null>(null)
let fp = ref<Flatpickr.Instance | null>(null)
const fp = ref<Flatpickr.Instance | null>(null)
const safeConfig = ref<Options>(cloneObject(props.config))
onMounted(() => {
// Don't mutate original object on parent component
let newConfig = cloneObject(props.config);
const newConfig = cloneObject(props.config)
if (
fp.value || // Return early if flatpickr is already loaded
@ -126,7 +130,7 @@ onMounted(() => {
props.events.forEach((hook) => {
// Respect global callbacks registered via setDefault() method
const globalCallbacks = Flatpickr.defaultConfig[hook] || [];
const globalCallbacks = Flatpickr.defaultConfig[hook] || []
// Inject our own method along with user callback
const localCallback: Hook = (...args) => emit(camelToKebab(hook), ...args)
@ -134,9 +138,9 @@ onMounted(() => {
// Overwrite with merged array
newConfig[hook] = arrayify(newConfig[hook] || []).concat(
globalCallbacks,
localCallback
);
});
localCallback,
)
})
// Watch for value changed by date-picker itself and notify parent component
const onChange: Hook = (dates) => emit('update:modelValue', dates)
@ -147,7 +151,7 @@ onMounted(() => {
// newConfig['onClose'] = arrayify(newConfig['onClose'] || []).concat(onClose)
// Set initial date without emitting any event
newConfig.defaultDate = props.modelValue || newConfig.defaultDate;
newConfig.defaultDate = props.modelValue || newConfig.defaultDate
safeConfig.value = newConfig
@ -156,11 +160,11 @@ onMounted(() => {
* Bind on parent element if wrap is true
*/
const element = props.config.wrap
? root.value.parentNode as ParentNode
? root.value.parentNode
: root.value
// Init flatpickr
fp.value = Flatpickr(element, safeConfig.value);
fp.value = Flatpickr(element, safeConfig.value)
})
onBeforeUnmount(() => fp.value?.destroy())
@ -171,9 +175,9 @@ watch(config, () => {
// Notice: we are looping through all events
// This also means that new callbacks can not be passed once component has been initialized
allEvents.forEach((hook) => {
delete safeConfig.value?.[hook];
});
fp.value.set(safeConfig.value);
delete safeConfig.value?.[hook]
})
fp.value.set(safeConfig.value)
// Passing these properties in `set()` method will cause flatpickr to trigger some callbacks
const configCallbacks = ['locale', 'showMonths'] as (keyof Options)[]
@ -181,14 +185,14 @@ watch(config, () => {
// Workaround: Allow to change locale dynamically
configCallbacks.forEach(name => {
if (typeof safeConfig.value?.[name] !== 'undefined' && fp.value) {
fp.value.set(name, safeConfig.value[name]);
fp.value.set(name, safeConfig.value[name])
}
});
})
}, {deep:true})
const fpInput = computed(() => {
if (!fp.value) return
return fp.value.altInput || fp.value.input;
return fp.value.altInput || fp.value.input
})
/**
@ -196,7 +200,7 @@ const fpInput = computed(() => {
* (is required by many validation libraries)
*/
function onBlur(event: Event) {
emit('blur', nullify((event.target as HTMLInputElement).value));
emit('blur', nullify((event.target as HTMLInputElement).value))
}
watchEffect(() => fpInput.value?.addEventListener('blur', onBlur))
@ -207,9 +211,9 @@ onBeforeUnmount(() => fpInput.value?.removeEventListener('blur', onBlur))
*/
watchEffect(() => {
if (disabled.value) {
fpInput.value?.setAttribute('disabled', '');
fpInput.value?.setAttribute('disabled', '')
} else {
fpInput.value?.removeAttribute('disabled');
fpInput.value?.removeAttribute('disabled')
}
})
@ -220,11 +224,11 @@ watch(
modelValue,
newValue => {
// Prevent updates if v-model value is same as input's current value
if (!root.value || newValue === nullify(root.value.value)) return;
if (!root.value || newValue === nullify(root.value.value)) return
// Make sure we have a flatpickr instanceand
// Notify flatpickr instance that there is a change in value
fp.value?.setDate(newValue, true);
fp.value?.setDate(newValue, true)
},
{deep: true}
{deep: true},
)
</script>

View File

@ -41,7 +41,7 @@
</template>
<script setup lang="ts">
import {computed, ref, watch, watchEffect, shallowReactive, type CSSProperties} from 'vue'
import {computed, ref, watch, watchEffect, shallowReactive} from 'vue'
import {useRouter} from 'vue-router'
import {format, parse} from 'date-fns'
import dayjs from 'dayjs'
@ -51,9 +51,11 @@ import cloneDeep from 'lodash.clonedeep'
import {useDayjsLanguageSync} from '@/i18n'
import TaskCollectionService from '@/services/taskCollection'
import TaskService from '@/services/task'
import TaskModel, { getHexColor } from '@/models/task'
import TaskModel, {getHexColor} from '@/models/task'
import {colorIsDark} from '@/helpers/color/colorIsDark'
import {isoToKebabDate} from '@/helpers/time/isoToKebabDate'
import {parseKebabDate} from '@/helpers/time/parseKebabDate'
import {RIGHTS} from '@/constants/rights'
import type {ITask} from '@/modelTypes/ITask'
@ -70,14 +72,8 @@ import Loading from '@/components/misc/loading.vue'
import TaskForm from '@/components/tasks/TaskForm.vue'
import {useBaseStore} from '@/stores/base'
import { error, success } from '@/message'
import {error, success} from '@/message'
export type DateRange = {
dateFrom: string,
dateTo: string,
}
// export interface GanttChartProps extends DateRange {
export interface GanttChartProps {
listId: IList['id']
showTasksWithoutDates: boolean
@ -85,8 +81,6 @@ export interface GanttChartProps {
dateTo: string,
}
// export const DATE_FORMAT = 'yyyy-LL-dd HH:mm'
const DAYJS_ISO_DATE_FORMAT = 'YYYY-MM-DD'
const props = withDefaults(defineProps<GanttChartProps>(), {
@ -94,8 +88,7 @@ const props = withDefaults(defineProps<GanttChartProps>(), {
})
// setup dayjs for vue-ganttastic
const dayjsLanguageLoading = ref(false)
// const dayjsLanguageLoading = useDayjsLanguageSync(dayjs)
const dayjsLanguageLoading = useDayjsLanguageSync(dayjs)
dayjs.extend(isToday)
extendDayjs()
@ -126,26 +119,18 @@ watch(
ganttBars.value = []
tasks.value.forEach(t => ganttBars.value.push(transformTaskToGanttBar(t)))
},
{deep: true}
{deep: true},
)
type DateKebab = `${string}-${string}-${string}`
type DateISO = string
const DATE_FORMAT_KEBAB = 'yyyy-LL-dd'
function isoToKebabDate(isoDate: DateISO) {
return format(new Date(isoDate), DATE_FORMAT_KEBAB) as DateKebab
}
const now = new Date()
const defaultStartDate = new Date(now)
const defaultEndDate = new Date(now.setDate(now.getDate() + 7))
const today = new Date(new Date(props.dateFrom).setHours(0,0,0,0))
const defaultTaskStartDate = new Date(today)
const defaultTaskEndDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7, 23,59,0,0)
function transformTaskToGanttBar(t: ITask) {
const black = 'var(--grey-800)'
console.log(t)
return [{
startDate: isoToKebabDate(t.startDate ? t.startDate.toISOString() : defaultStartDate.toISOString()),
endDate: isoToKebabDate(t.endDate ? t.endDate.toISOString() : defaultEndDate.toISOString()),
startDate: isoToKebabDate(t.startDate ? t.startDate.toISOString() : defaultTaskStartDate.toISOString()),
endDate: isoToKebabDate(t.endDate ? t.endDate.toISOString() : defaultTaskEndDate.toISOString()),
ganttBarConfig: {
id: String(t.id),
label: t.title,
@ -162,13 +147,13 @@ function transformTaskToGanttBar(t: ITask) {
// FIXME: unite with other filter params types
interface GetAllTasksParams {
sort_by: ('start_date' | 'done' | 'id')[],
order_by: ('asc' | 'asc' | 'desc')[],
filter_by: 'start_date'[],
filter_comparator: ('greater_equals' | 'less_equals')[],
filter_value: [string, string] // [dateFrom, dateTo],
filter_concat: 'and',
filter_include_nulls: boolean,
sort_by: ('start_date' | 'done' | 'id')[],
order_by: ('asc' | 'asc' | 'desc')[],
filter_by: 'start_date'[],
filter_comparator: ('greater_equals' | 'less_equals')[],
filter_value: [string, string] // [dateFrom, dateTo],
filter_concat: 'and',
filter_include_nulls: boolean,
}
async function getAllTasks(params: GetAllTasksParams, page = 1): Promise<ITask[]> {
@ -202,7 +187,6 @@ async function loadTasks({
}
const loadedTasks = await getAllTasks(params)
loadedTasks.forEach(t => tasks.value.set(t.id, t))
}
@ -216,8 +200,8 @@ async function createTask(title: ITask['title']) {
const newTask = await taskService.create(new TaskModel({
title,
listId: props.listId,
startDate: defaultStartDate,
endDate: defaultEndDate,
startDate: defaultTaskStartDate.toISOString(),
endDate: defaultTaskEndDate.toISOString(),
}))
tasks.value.set(newTask.id, newTask)
@ -233,41 +217,23 @@ async function updateTask(e: {
if (!task) return
const startDate = parse(e.bar.startDate, 'yyyy-MM-dd', new Date())
const endDate = parse(e.bar.endDate, 'yyyy-MM-dd', new Date())
const oldTask = cloneDeep(task)
const newTask: ITask = {
...task,
startDate,
endDate,
startDate: new Date(parseKebabDate(e.bar.startDate).setHours(0,0,0,0)),
endDate: new Date(parseKebabDate(e.bar.endDate).setHours(23,59,0,0)),
}
const newTaskCopy = cloneDeep(task)
tasks.value.set(newTask.id, newTask)
// try {
const updatedTask = await taskService.update(newTask)
// tasks.value.set(updatedTask.id, updatedTask)
success('Saved')
// } catch(e: any) {
// error('Saved')
// tasks.value.set(task.id, oldTask)
// }
// for (let [idStr, currentTask] of tasks.value) {
// const id: ITask['id'] = Number(idStr)
// }
// ganttBars.value.map(gantBar => {
// return Number(gantBar[0].ganttBarConfig.id) === task.id
// ? transformTaskToGanttBar(updatedTask)
// : gantBar
// })
try {
const updatedTask = await taskService.update(newTask)
tasks.value.set(updatedTask.id, updatedTask)
success('Saved')
} catch(e: any) {
error('Something went wrong saving the task')
tasks.value.set(task.id, oldTask)
}
}
function openTask(e: {
@ -310,11 +276,11 @@ function dayIsToday(label: string): boolean {
}
.g-gantt-row-label {
display: none;
display: none !important;
}
.g-upper-timeunit, .g-timeunit {
background: var(--white);
background: var(--white) !important;
font-family: $vikunja-font;
}
@ -326,7 +292,7 @@ function dayIsToday(label: string): boolean {
.g-timeunit .timeunit-wrapper {
padding: 0.5rem 0;
font-size: 1rem;
font-size: 1rem !important;
display: flex;
flex-direction: column;
align-items: center;
@ -345,13 +311,13 @@ function dayIsToday(label: string): boolean {
}
.g-timeaxis {
height: auto;
box-shadow: none;
height: auto !important;
box-shadow: none !important;
}
.g-gantt-row > .g-gantt-row-bars-container {
border-bottom: none;
border-top: none;
border-bottom: none !important;
border-top: none !important;
}
.g-gantt-row:nth-child(odd) {
@ -365,10 +331,10 @@ function dayIsToday(label: string): boolean {
&-handle-left,
&-handle-right {
width: 6px;
height: 75%;
opacity: .75;
border-radius: $radius;
width: 6px !important;
height: 75% !important;
opacity: .75 !important;
border-radius: $radius !important;
margin-top: 4px;
}
}

1
src/constants/date.ts Normal file
View File

@ -0,0 +1 @@
export const DATEFNS_DATE_FORMAT_KEBAB = 'yyyy-LL-dd'

View File

@ -0,0 +1,8 @@
import {format} from 'date-fns'
import {DATEFNS_DATE_FORMAT_KEBAB} from '@/constants/date'
import type {DateISO} from '@/types/DateISO'
import type {DateKebab} from '@/types/DateKebab'
export function isoToKebabDate(isoDate: DateISO) {
return format(new Date(isoDate), DATEFNS_DATE_FORMAT_KEBAB) as DateKebab
}

View File

@ -349,9 +349,7 @@ const getMonthFromText = (text: string, date: Date) => {
const getDateFromInterval = (interval: number): Date => {
const newDate = new Date()
newDate.setDate(newDate.getDate() + interval)
newDate.setHours(calculateNearestHours(newDate))
newDate.setMinutes(0)
newDate.setSeconds(0)
newDate.setHours(calculateNearestHours(newDate), 0, 0)
return newDate
}

View File

@ -0,0 +1,7 @@
import {parse} from 'date-fns'
import {DATEFNS_DATE_FORMAT_KEBAB} from '@/constants/date'
import type {DateKebab} from '@/types/DateKebab'
export function parseKebabDate(date: DateKebab): Date {
return parse(date, DATEFNS_DATE_FORMAT_KEBAB, new Date())
}

7
src/types/DateISO.ts Normal file
View File

@ -0,0 +1,7 @@
/**
* Returns a date as a string value in ISO format.
* same format as `new Date().toISOString()`
*/
export type DateISO = string
new Date().toISOString()

4
src/types/DateKebab.ts Normal file
View File

@ -0,0 +1,4 @@
/**
* Date in Format 2022-12-10
*/
export type DateKebab = `${string}-${string}-${string}`

View File

@ -26,14 +26,11 @@
<template #default>
<div class="gantt-chart-container">
<card :padding="false" class="has-overflow">
<pre>{{dateRange}}</pre>
<pre>{{new Date(dateRange.dateFrom).toISOString()}}</pre>
<pre>{{new Date(dateRange.dateTo).toISOString()}}</pre>
<gantt-chart
:list-id="filters.listId"
:date-from="filters.dateFrom"
:date-to="filters.dateTo"
:show-tasks-without-dates="showTasksWithoutDates"
:show-tasks-without-dates="filters.showTasksWithoutDates"
/>
</card>
</div>
@ -42,13 +39,12 @@
</template>
<script setup lang="ts">
import {computed, reactive, ref, watch, type PropType} from 'vue'
import {computed, reactive, ref, watch} from 'vue'
import Foo from '@/components/misc/flatpickr/Flatpickr.vue'
// import type FlatPickr from 'vue-flatpickr-component'
import type Flatpickr from 'flatpickr'
import {useI18n} from 'vue-i18n'
import {format} from 'date-fns'
import {useRoute, useRouter, type LocationQuery, type RouteLocationNormalized, type RouteLocationRaw} from 'vue-router'
import {useRoute, useRouter, type RouteLocationNormalized, type RouteLocationRaw} from 'vue-router'
import cloneDeep from 'lodash.clonedeep'
import {useAuthStore} from '@/stores/auth'
@ -56,24 +52,13 @@ import ListWrapper from './ListWrapper.vue'
import Fancycheckbox from '@/components/input/fancycheckbox.vue'
import {createAsyncComponent} from '@/helpers/createAsyncComponent'
import GanttChart from '@/components/tasks/gantt-chart.vue'
import type { IList } from '@/modelTypes/IList'
import {isoToKebabDate} from '@/helpers/time/isoToKebabDate'
export type DateKebab = `${string}-${string}-${string}`
export type DateISO = string
export type DateRange = {
dateFrom: string
dateTo: string
}
export interface GanttParams {
listId: IList['id']
dateFrom: DateKebab
dateTo: DateKebab
showTasksWithoutDates: boolean
route: RouteLocationNormalized,
}
import type {IList} from '@/modelTypes/IList'
import type {DateISO} from '@/types/DateISO'
import type {DateKebab} from '@/types/DateKebab'
// convenient internal filter object
export interface GanttFilter {
listId: IList['id']
dateFrom: DateISO
@ -83,9 +68,9 @@ export interface GanttFilter {
type Options = Flatpickr.Options.Options
// const GanttChart = createAsyncComponent(() => import('@/components/tasks/gantt-chart.vue'))
const GanttChart = createAsyncComponent(() => import('@/components/tasks/gantt-chart.vue'))
const props = defineProps<GanttParams>()
const props = defineProps<{route: RouteLocationNormalized}>()
const router = useRouter()
const route = useRoute()
@ -124,11 +109,6 @@ function parseBooleanProp(booleanProp: string) {
: Boolean(booleanProp)
}
const DATE_FORMAT_KEBAB = 'yyyy-LL-dd'
function isoToKebabDate(isoDate: DateISO) {
return format(new Date(isoDate), DATE_FORMAT_KEBAB) as DateKebab
}
const DEFAULT_SHOW_TASKS_WITHOUT_DATES = false
const DEFAULT_DATEFROM_DAY_OFFSET = -15
@ -145,8 +125,6 @@ function getDefaultDateTo() {
}
function routeToFilter(route: RouteLocationNormalized): GanttFilter {
console.log('parseDateProp', parseDateProp(route.query.dateTo as DateKebab))
console.log(parseDateProp(route.query.dateTo as DateKebab))
return {
listId: Number(route.params.listId as string),
dateFrom: parseDateProp(route.query.dateFrom as DateKebab) || getDefaultDateFrom(),
@ -174,13 +152,13 @@ function filterToRoute(filters: GanttFilter): RouteLocationRaw {
return {
name: 'list.gantt',
params: {listId: filters.listId},
query
query,
}
}
const filters: GanttFilter = reactive(routeToFilter(route))
watch(() => JSON.parse(JSON.stringify(props.route)) as RouteLocationNormalized, (route, oldRoute) => {
watch(() => cloneDeep(props.route), (route, oldRoute) => {
if (route.name !== oldRoute.name) {
return
}
@ -200,19 +178,15 @@ watch(
await router.push(newRouteFullPath)
}
},
{flush: "post"}
// only apply new route after all filters have changed in component cycle
{flush: 'post'},
)
const dateRange = computed(() => ({
dateFrom: filters.dateFrom,
dateTo: filters.dateTo,
}))
const flatPickerEl = ref<typeof FlatPickr | null>(null)
const flatPickerDateRange = computed({
const flatPickerEl = ref<typeof Foo | null>(null)
const flatPickerDateRange = computed<Date[]>({
get: () => ([
filters.dateFrom,
filters.dateTo
new Date(filters.dateFrom),
new Date(filters.dateTo),
]),
set(newVal) {
const [dateFrom, dateTo] = newVal.map((date) => date?.toISOString())
@ -221,11 +195,9 @@ const flatPickerDateRange = computed({
if (!dateTo) return
Object.assign(filters, {dateFrom, dateTo})
}
},
})
const ISO_DATE_FORMAT = "YYYY-MM-DDTHH:mm:ssZ[Z]"
const initialDateRange = [filters.dateFrom, filters.dateTo]
const {t} = useI18n({useScope: 'global'})
@ -233,8 +205,6 @@ const authStore = useAuthStore()
const flatPickerConfig = computed<Options>(() => ({
altFormat: t('date.altFormatShort'),
altInput: true,
// dateFornat: ISO_DATE_FORMAT,
// dateFormat: 'Y-m-d',
defaultDate: initialDateRange,
enableTime: false,
mode: 'range',
@ -287,7 +257,6 @@ const flatPickerConfig = computed<Options>(() => ({
.label {
font-size: .9rem;
padding-left: .4rem;
}
}
}