Merge branch 'main' into feature/ganttastic

# Conflicts:
#	pnpm-lock.yaml
#	src/main.ts
This commit is contained in:
Dominik Pschenitschni 2022-09-30 19:15:16 +02:00
commit c7a3c18972
No known key found for this signature in database
GPG key ID: B257AC0149F43A77
68 changed files with 1115 additions and 906 deletions

View file

@ -65,7 +65,7 @@
}, },
"devDependencies": { "devDependencies": {
"@4tw/cypress-drag-drop": "2.2.1", "@4tw/cypress-drag-drop": "2.2.1",
"@cypress/vite-dev-server": "3.1.1", "@cypress/vite-dev-server": "3.2.0",
"@cypress/vue": "4.2.0", "@cypress/vue": "4.2.0",
"@faker-js/faker": "7.5.0", "@faker-js/faker": "7.5.0",
"@types/dompurify": "2.3.4", "@types/dompurify": "2.3.4",
@ -76,19 +76,19 @@
"@vitejs/plugin-legacy": "2.2.0", "@vitejs/plugin-legacy": "2.2.0",
"@vitejs/plugin-vue": "3.1.0", "@vitejs/plugin-vue": "3.1.0",
"@vue/eslint-config-typescript": "11.0.2", "@vue/eslint-config-typescript": "11.0.2",
"@vue/test-utils": "2.0.2", "@vue/test-utils": "2.1.0",
"@vue/tsconfig": "0.1.3", "@vue/tsconfig": "0.1.3",
"autoprefixer": "10.4.12", "autoprefixer": "10.4.12",
"browserslist": "4.21.4", "browserslist": "4.21.4",
"caniuse-lite": "1.0.30001412", "caniuse-lite": "1.0.30001412",
"cypress": "10.9.0", "cypress": "10.9.0",
"esbuild": "0.15.9", "esbuild": "0.15.10",
"eslint": "8.24.0", "eslint": "8.24.0",
"eslint-plugin-vue": "9.5.1", "eslint-plugin-vue": "9.5.1",
"express": "4.18.1", "express": "4.18.1",
"happy-dom": "6.0.4", "happy-dom": "6.0.4",
"netlify-cli": "11.8.3", "netlify-cli": "11.8.3",
"postcss": "8.4.16", "postcss": "8.4.17",
"postcss-preset-env": "7.8.2", "postcss-preset-env": "7.8.2",
"rollup": "2.79.1", "rollup": "2.79.1",
"rollup-plugin-visualizer": "5.8.2", "rollup-plugin-visualizer": "5.8.2",

File diff suppressed because it is too large Load diff

View file

@ -36,15 +36,17 @@ import AccountDeleteService from '@/services/accountDelete'
import {useColorScheme} from '@/composables/useColorScheme' import {useColorScheme} from '@/composables/useColorScheme'
import {useBodyClass} from '@/composables/useBodyClass' import {useBodyClass} from '@/composables/useBodyClass'
import {useAuthStore} from './stores/auth'
const store = useStore() const store = useStore()
const authStore = useAuthStore()
const router = useRouter() const router = useRouter()
useBodyClass('is-touch', isTouchDevice()) useBodyClass('is-touch', isTouchDevice())
const keyboardShortcutsActive = computed(() => store.state.keyboardShortcutsActive) const keyboardShortcutsActive = computed(() => store.state.keyboardShortcutsActive)
const authUser = computed(() => store.getters['auth/authUser']) const authUser = computed(() => authStore.authUser)
const authLinkShare = computed(() => store.getters['auth/authLinkShare']) const authLinkShare = computed(() => authStore.authLinkShare)
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
@ -58,7 +60,7 @@ watch(accountDeletionConfirm, async (accountDeletionConfirm) => {
const accountDeletionService = new AccountDeleteService() const accountDeletionService = new AccountDeleteService()
await accountDeletionService.confirm(accountDeletionConfirm) await accountDeletionService.confirm(accountDeletionConfirm)
success({message: t('user.deletion.confirmSuccess')}) success({message: t('user.deletion.confirmSuccess')})
store.dispatch('auth/refreshUserInfo') authStore.refreshUserInfo()
}, { immediate: true }) }, { immediate: true })
// setup password reset redirect // setup password reset redirect

View file

@ -71,7 +71,6 @@
<script lang="ts" setup> <script lang="ts" setup>
import {computed, ref, watch} from 'vue' import {computed, ref, watch} from 'vue'
import {useStore} from '@/store'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import flatPickr from 'vue-flatpickr-component' import flatPickr from 'vue-flatpickr-component'
@ -81,8 +80,9 @@ import Popup from '@/components/misc/popup.vue'
import {DATE_RANGES} from '@/components/date/dateRanges' import {DATE_RANGES} from '@/components/date/dateRanges'
import BaseButton from '@/components/base/BaseButton.vue' import BaseButton from '@/components/base/BaseButton.vue'
import DatemathHelp from '@/components/date/datemathHelp.vue' import DatemathHelp from '@/components/date/datemathHelp.vue'
import {useAuthStore} from '@/stores/auth'
const store = useStore() const authStore = useAuthStore()
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const emit = defineEmits(['update:modelValue']) const emit = defineEmits(['update:modelValue'])
@ -93,7 +93,7 @@ const props = defineProps({
}) })
// FIXME: This seems to always contain the default value - that breaks the picker // FIXME: This seems to always contain the default value - that breaks the picker
const weekStart = computed<number>(() => store.state.auth.settings.weekStart ?? 0) const weekStart = computed(() => authStore.settings.weekStart ?? 0)
const flatPickerConfig = computed(() => ({ const flatPickerConfig = computed(() => ({
altFormat: t('date.altFormatLong'), altFormat: t('date.altFormatLong'),
altInput: true, altInput: true,

View file

@ -93,7 +93,6 @@
<script setup lang="ts"> <script setup lang="ts">
import {ref, computed, onMounted, nextTick} from 'vue' import {ref, computed, onMounted, nextTick} from 'vue'
import {useStore} from '@/store' import {useStore} from '@/store'
import {useRouter} from 'vue-router'
import {QUICK_ACTIONS_ACTIVE} from '@/store/mutation-types' import {QUICK_ACTIONS_ACTIVE} from '@/store/mutation-types'
import {RIGHTS as Rights} from '@/constants/rights' import {RIGHTS as Rights} from '@/constants/rights'
@ -109,12 +108,14 @@ import MenuButton from '@/components/home/MenuButton.vue'
import {getListTitle} from '@/helpers/getListTitle' import {getListTitle} from '@/helpers/getListTitle'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'
import {useAuthStore} from '@/stores/auth'
const store = useStore() const store = useStore()
const authStore = useAuthStore()
const configStore = useConfigStore() const configStore = useConfigStore()
const userInfo = computed(() => store.state.auth.info) const userInfo = computed(() => authStore.info)
const userAvatar = computed(() => store.state.auth.avatarUrl) const userAvatar = computed(() => authStore.avatarUrl)
const currentList = computed(() => store.state.currentList) const currentList = computed(() => store.state.currentList)
const background = computed(() => store.state.background) const background = computed(() => store.state.background)
const imprintUrl = computed(() => configStore.legal.imprintUrl) const imprintUrl = computed(() => configStore.legal.imprintUrl)
@ -134,11 +135,8 @@ onMounted(async () => {
listTitle.value.style.setProperty('--nav-username-width', `${usernameWidth}px`) listTitle.value.style.setProperty('--nav-username-width', `${usernameWidth}px`)
}) })
const router = useRouter()
function logout() { function logout() {
store.dispatch('auth/logout') authStore.logout()
router.push({name: 'user.login'})
} }
function openQuickActions() { function openQuickActions() {

View file

@ -70,6 +70,7 @@ import {useLabelStore} from '@/stores/labels'
import Navigation from '@/components/home/navigation.vue' import Navigation from '@/components/home/navigation.vue'
import QuickActions from '@/components/quick-actions/quick-actions.vue' import QuickActions from '@/components/quick-actions/quick-actions.vue'
import BaseButton from '@/components/base/BaseButton.vue' import BaseButton from '@/components/base/BaseButton.vue'
import {useAuthStore} from '@/stores/auth'
function useRouteWithModal() { function useRouteWithModal() {
const router = useRouter() const router = useRouter()
@ -165,13 +166,15 @@ watch(() => route.name as string, (routeName) => {
function useRenewTokenOnFocus() { function useRenewTokenOnFocus() {
const router = useRouter() const router = useRouter()
const authStore = useAuthStore()
const userInfo = computed(() => store.state.auth.info)
const authenticated = computed(() => store.state.auth.authenticated) const userInfo = computed(() => authStore.info)
const authenticated = computed(() => authStore.authenticated)
// Try renewing the token every time vikunja is loaded initially // Try renewing the token every time vikunja is loaded initially
// (When opening the browser the focus event is not fired) // (When opening the browser the focus event is not fired)
store.dispatch('auth/renewToken') authStore.renewToken()
// Check if the token is still valid if the window gets focus again to maybe renew it // Check if the token is still valid if the window gets focus again to maybe renew it
useEventListener('focus', () => { useEventListener('focus', () => {
@ -184,14 +187,14 @@ function useRenewTokenOnFocus() {
// If the token expiry is negative, it is already expired and we have no choice but to redirect // If the token expiry is negative, it is already expired and we have no choice but to redirect
// the user to the login page // the user to the login page
if (expiresIn < 0) { if (expiresIn < 0) {
store.dispatch('auth/checkAuth') authStore.checkAuth()
router.push({name: 'user.login'}) router.push({name: 'user.login'})
return return
} }
// Check if the token is valid for less than 60 hours and renew if thats the case // Check if the token is valid for less than 60 hours and renew if thats the case
if (expiresIn < 60 * 3600) { if (expiresIn < 60 * 3600) {
store.dispatch('auth/renewToken') authStore.renewToken()
console.debug('renewed token') console.debug('renewed token')
} }
}) })

View file

@ -102,6 +102,8 @@ import {calculateDayInterval} from '@/helpers/time/calculateDayInterval'
import {calculateNearestHours} from '@/helpers/time/calculateNearestHours' import {calculateNearestHours} from '@/helpers/time/calculateNearestHours'
import {closeWhenClickedOutside} from '@/helpers/closeWhenClickedOutside' import {closeWhenClickedOutside} from '@/helpers/closeWhenClickedOutside'
import {createDateFromString} from '@/helpers/time/createDateFromString' import {createDateFromString} from '@/helpers/time/createDateFromString'
import {mapState} from 'pinia'
import {useAuthStore} from '@/stores/auth'
export default defineComponent({ export default defineComponent({
name: 'datepicker', name: 'datepicker',
@ -145,6 +147,9 @@ export default defineComponent({
}, },
}, },
computed: { computed: {
...mapState(useAuthStore, {
weekStart: (state) => state.settings.weekStart,
}),
flatPickerConfig() { flatPickerConfig() {
return { return {
altFormat: this.$t('date.altFormatLong'), altFormat: this.$t('date.altFormatLong'),
@ -154,7 +159,7 @@ export default defineComponent({
time_24hr: true, time_24hr: true,
inline: true, inline: true,
locale: { locale: {
firstDayOfWeek: this.$store.state.auth.settings.weekStart, firstDayOfWeek: this.weekStart,
}, },
} }
}, },

View file

@ -1,6 +1,6 @@
<template> <template>
<dropdown> <dropdown>
<template v-if="isSavedFilter"> <template v-if="isSavedFilter(list)">
<dropdown-item <dropdown-item
:to="{ name: 'filter.settings.edit', params: { listId: list.id } }" :to="{ name: 'filter.settings.edit', params: { listId: list.id } }"
icon="pen" icon="pen"
@ -78,7 +78,7 @@
<script setup lang="ts"> <script setup lang="ts">
import {ref, computed, watchEffect, type PropType} from 'vue' import {ref, computed, watchEffect, type PropType} from 'vue'
import {getSavedFilterIdFromListId} from '@/helpers/savedFilter' import {isSavedFilter} from '@/helpers/savedFilter'
import Dropdown from '@/components/misc/dropdown.vue' import Dropdown from '@/components/misc/dropdown.vue'
import DropdownItem from '@/components/misc/dropdown-item.vue' import DropdownItem from '@/components/misc/dropdown-item.vue'
import TaskSubscription from '@/components/misc/subscription.vue' import TaskSubscription from '@/components/misc/subscription.vue'
@ -100,5 +100,4 @@ watchEffect(() => {
const configStore = useConfigStore() const configStore = useConfigStore()
const backgroundsEnabled = computed(() => configStore.enabledBackgroundProviders?.length > 0) const backgroundsEnabled = computed(() => configStore.enabledBackgroundProviders?.length > 0)
const isSavedFilter = computed(() => getSavedFilterIdFromListId(props.list.id) > 0)
</script> </script>

View file

@ -30,10 +30,7 @@
<ButtonLink class="api-config__change-button" @click="() => (configureApi = true)">{{ $t('apiConfig.change') }}</ButtonLink> <ButtonLink class="api-config__change-button" @click="() => (configureApi = true)">{{ $t('apiConfig.change') }}</ButtonLink>
</div> </div>
<message variant="success" v-if="successMsg !== '' && errorMsg === ''" class="mt-2"> <message variant="danger" v-if="errorMsg !== ''" class="mt-2">
{{ successMsg }}
</message>
<message variant="danger" v-if="errorMsg !== '' && successMsg === ''" class="mt-2">
{{ errorMsg }} {{ errorMsg }}
</message> </message>
</div> </div>
@ -74,7 +71,6 @@ watch(() => props.configureOpen, (value) => {
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const errorMsg = ref('') const errorMsg = ref('')
const successMsg = ref('')
async function setApiUrl() { async function setApiUrl() {
if (apiUrl.value === '') { if (apiUrl.value === '') {
@ -99,7 +95,6 @@ async function setApiUrl() {
emit('foundApi', apiUrl.value) emit('foundApi', apiUrl.value)
} catch (e) { } catch (e) {
// Still not found, url is still invalid // Still not found, url is still invalid
successMsg.value = ''
errorMsg.value = t('apiConfig.error', {domain: apiDomain.value}) errorMsg.value = t('apiConfig.error', {domain: apiDomain.value})
} }
} }

View file

@ -2,34 +2,39 @@
<div :class="{'is-inline': isInline}" class="user"> <div :class="{'is-inline': isInline}" class="user">
<img <img
:height="avatarSize" :height="avatarSize"
:src="user.getAvatarUrl(avatarSize)" :src="getAvatarUrl(user, avatarSize)"
:width="avatarSize" :width="avatarSize"
alt="" alt=""
class="avatar" class="avatar"
v-tooltip="user.getDisplayName()"/> v-tooltip="getDisplayName(user)"/>
<span class="username" v-if="showUsername">{{ user.getDisplayName() }}</span> <span class="username" v-if="showUsername">{{ getDisplayName(user) }}</span>
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type {PropType} from 'vue'
import {getAvatarUrl, getDisplayName} from '@/models/user'
import type {IUser} from '@/modelTypes/IUser'
defineProps({ defineProps({
user: { user: {
type: Object as PropType<IUser>,
required: true, required: true,
type: Object,
}, },
showUsername: { showUsername: {
required: false,
type: Boolean, type: Boolean,
required: false,
default: true, default: true,
}, },
avatarSize: { avatarSize: {
required: false,
type: Number, type: Number,
required: false,
default: 50, default: 50,
}, },
isInline: { isInline: {
required: false,
type: Boolean, type: Boolean,
required: false,
default: false, default: false,
}, },
}) })

View file

@ -24,7 +24,7 @@
<div class="detail"> <div class="detail">
<div> <div>
<span class="has-text-weight-bold mr-1" v-if="n.notification.doer"> <span class="has-text-weight-bold mr-1" v-if="n.notification.doer">
{{ n.notification.doer.getDisplayName() }} {{ getDisplayName(n.notification.doer) }}
</span> </span>
<BaseButton @click="() => to(n, index)()"> <BaseButton @click="() => to(n, index)()">
{{ n.toText(userInfo) }} {{ n.toText(userInfo) }}
@ -48,19 +48,20 @@
<script lang="ts" setup> <script lang="ts" setup>
import {computed, onMounted, onUnmounted, ref} from 'vue' import {computed, onMounted, onUnmounted, ref} from 'vue'
import {useRouter} from 'vue-router'
import NotificationService from '@/services/notification' import NotificationService from '@/services/notification'
import BaseButton from '@/components/base/BaseButton.vue' import BaseButton from '@/components/base/BaseButton.vue'
import User from '@/components/misc/user.vue' import User from '@/components/misc/user.vue'
import { NOTIFICATION_NAMES as names, type INotification} from '@/modelTypes/INotification' import { NOTIFICATION_NAMES as names, type INotification} from '@/modelTypes/INotification'
import {closeWhenClickedOutside} from '@/helpers/closeWhenClickedOutside' import {closeWhenClickedOutside} from '@/helpers/closeWhenClickedOutside'
import {useStore} from '@/store'
import {useRouter} from 'vue-router'
import {formatDateLong, formatDateSince} from '@/helpers/time/formatDate' import {formatDateLong, formatDateSince} from '@/helpers/time/formatDate'
import {getDisplayName} from '@/models/user'
import {useAuthStore} from '@/stores/auth'
const LOAD_NOTIFICATIONS_INTERVAL = 10000 const LOAD_NOTIFICATIONS_INTERVAL = 10000
const store = useStore() const authStore = useAuthStore()
const router = useRouter() const router = useRouter()
const allNotifications = ref<INotification[]>([]) const allNotifications = ref<INotification[]>([])
@ -73,7 +74,7 @@ const unreadNotifications = computed(() => {
const notifications = computed(() => { const notifications = computed(() => {
return allNotifications.value ? allNotifications.value.filter(n => n.name !== '') : [] return allNotifications.value ? allNotifications.value.filter(n => n.name !== '') : []
}) })
const userInfo = computed(() => store.state.auth.info) const userInfo = computed(() => authStore.info)
let interval: number let interval: number

View file

@ -73,6 +73,7 @@ import {PREFIXES} from '@/modules/parseTaskText'
import {useListStore} from '@/stores/lists' import {useListStore} from '@/stores/lists'
import {useNamespaceStore} from '@/stores/namespaces' import {useNamespaceStore} from '@/stores/namespaces'
import {useLabelStore} from '@/stores/labels' import {useLabelStore} from '@/stores/labels'
import {useTaskStore} from '@/stores/tasks'
const TYPE_LIST = 'list' const TYPE_LIST = 'list'
const TYPE_TASK = 'task' const TYPE_TASK = 'task'
@ -412,7 +413,8 @@ export default defineComponent({
return return
} }
const task = await this.$store.dispatch('tasks/createNewTask', { const taskStore = useTaskStore()
const task = await taskStore.createNewTask({
title: this.query, title: this.query,
listId: this.currentList.id, listId: this.currentList.id,
}) })

View file

@ -93,7 +93,7 @@
<p class="mb-2"> <p class="mb-2">
<i18n-t keypath="list.share.links.sharedBy" scope="global"> <i18n-t keypath="list.share.links.sharedBy" scope="global">
<strong>{{ s.sharedBy.getDisplayName() }}</strong> <strong>{{ getDisplayName(s.sharedBy) }}</strong>
</i18n-t> </i18n-t>
</p> </p>
@ -201,6 +201,7 @@ import LinkShareService from '@/services/linkShare'
import {useCopyToClipboard} from '@/composables/useCopyToClipboard' import {useCopyToClipboard} from '@/composables/useCopyToClipboard'
import {success} from '@/message' import {success} from '@/message'
import {getDisplayName} from '@/models/user'
import type {ListView} from '@/types/ListView' import type {ListView} from '@/types/ListView'
import {LIST_VIEWS} from '@/types/ListView' import {LIST_VIEWS} from '@/types/ListView'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'

View file

@ -28,7 +28,7 @@
<tbody> <tbody>
<tr :key="s.id" v-for="s in sharables"> <tr :key="s.id" v-for="s in sharables">
<template v-if="shareType === 'user'"> <template v-if="shareType === 'user'">
<td>{{ s.getDisplayName() }}</td> <td>{{ getDisplayName(s) }}</td>
<td> <td>
<template v-if="s.id === userInfo.id"> <template v-if="s.id === userInfo.id">
<b class="is-success">{{ $t('list.share.userTeam.you') }}</b> <b class="is-success">{{ $t('list.share.userTeam.you') }}</b>
@ -139,7 +139,6 @@ export default {name: 'userTeamShare'}
<script setup lang="ts"> <script setup lang="ts">
import {ref, reactive, computed, shallowReactive, type Ref} from 'vue' import {ref, reactive, computed, shallowReactive, type Ref} from 'vue'
import type {PropType} from 'vue' import type {PropType} from 'vue'
import {useStore} from '@/store'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import UserNamespaceService from '@/services/userNamespace' import UserNamespaceService from '@/services/userNamespace'
@ -151,7 +150,7 @@ import UserListModel from '@/models/userList'
import type {IUserList} from '@/modelTypes/IUserList' import type {IUserList} from '@/modelTypes/IUserList'
import UserService from '@/services/user' import UserService from '@/services/user'
import UserModel from '@/models/user' import UserModel, { getDisplayName } from '@/models/user'
import type {IUser} from '@/modelTypes/IUser' import type {IUser} from '@/modelTypes/IUser'
import TeamNamespaceService from '@/services/teamNamespace' import TeamNamespaceService from '@/services/teamNamespace'
@ -171,6 +170,7 @@ import {RIGHTS} from '@/constants/rights'
import Multiselect from '@/components/input/multiselect.vue' import Multiselect from '@/components/input/multiselect.vue'
import Nothing from '@/components/misc/nothing.vue' import Nothing from '@/components/misc/nothing.vue'
import {success} from '@/message' import {success} from '@/message'
import {useAuthStore} from '@/stores/auth'
const props = defineProps({ const props = defineProps({
type: { type: {
@ -208,8 +208,8 @@ const sharables = ref([])
const showDeleteModal = ref(false) const showDeleteModal = ref(false)
const store = useStore() const authStore = useAuthStore()
const userInfo = computed(() => store.state.auth.info) const userInfo = computed(() => authStore.info)
function createShareTypeNameComputed(count: number) { function createShareTypeNameComputed(count: number) {
return computed(() => { return computed(() => {
@ -365,7 +365,7 @@ async function toggleType(sharable) {
const found = ref([]) const found = ref([])
const currentUserId = computed(() => store.state.auth.info.id) const currentUserId = computed(() => authStore.info.id)
async function find(query: string) { async function find(query: string) {
if (query === '') { if (query === '') {
found.value = [] found.value = []

View file

@ -41,17 +41,18 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import {ref, watch, unref, computed} from 'vue' import {computed, ref, unref, watch} from 'vue'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useStore} from '@/store' import {debouncedWatch, type MaybeRef, tryOnMounted, useWindowSize} from '@vueuse/core'
import {tryOnMounted, debouncedWatch, useWindowSize, type MaybeRef} from '@vueuse/core'
import QuickAddMagic from '@/components/tasks/partials/quick-add-magic.vue' import QuickAddMagic from '@/components/tasks/partials/quick-add-magic.vue'
import {LOADING, LOADING_MODULE} from '@/store/mutation-types' import type {ITask} from '@/modelTypes/ITask'
import {parseSubtasksViaIndention} from '@/helpers/parseSubtasksViaIndention'
function cleanupTitle(title: string) { import TaskRelationService from '@/services/taskRelation'
return title.replace(/^((\* |\+ |- )(\[ \] )?)/g, '') import TaskRelationModel from '@/models/taskRelation'
} import {RELATION_KIND} from '@/types/IRelationKind'
import {useAuthStore} from '@/stores/auth'
import {useTaskStore} from '@/stores/tasks'
function useAutoHeightTextarea(value: MaybeRef<string>) { function useAutoHeightTextarea(value: MaybeRef<string>) {
const textarea = ref<HTMLInputElement>() const textarea = ref<HTMLInputElement>()
@ -134,7 +135,8 @@ const newTaskTitle = ref('')
const newTaskInput = useAutoHeightTextarea(newTaskTitle) const newTaskInput = useAutoHeightTextarea(newTaskTitle)
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const store = useStore() const authStore = useAuthStore()
const taskStore = useTaskStore()
const errorMessage = ref('') const errorMessage = ref('')
@ -147,7 +149,7 @@ function resetEmptyTitleError(e) {
} }
} }
const loading = computed(() => store.state[LOADING] && store.state[LOADING_MODULE] === 'tasks') const loading = computed(() => taskStore.isLoading)
async function addTask() { async function addTask() {
if (newTaskTitle.value === '') { if (newTaskTitle.value === '') {
errorMessage.value = t('list.create.addTitleRequired') errorMessage.value = t('list.create.addTitleRequired')
@ -160,24 +162,56 @@ async function addTask() {
} }
const taskTitleBackup = newTaskTitle.value const taskTitleBackup = newTaskTitle.value
const newTasks = newTaskTitle.value.split(/[\r\n]+/).map(async uncleanedTitle => { const createdTasks: ITask[] = []
const title = cleanupTitle(uncleanedTitle) const tasksToCreate = parseSubtasksViaIndention(newTaskTitle.value)
const newTasks = tasksToCreate.map(async ({title}) => {
if (title === '') { if (title === '') {
return return
} }
const task = await store.dispatch('tasks/createNewTask', { const task = await taskStore.createNewTask({
title, title,
listId: store.state.auth.settings.defaultListId, listId: authStore.settings.defaultListId,
position: props.defaultPosition, position: props.defaultPosition,
}) })
emit('taskAdded', task) createdTasks.push(task)
return task return task
}) })
try { try {
newTaskTitle.value = '' newTaskTitle.value = ''
await Promise.all(newTasks) await Promise.all(newTasks)
const taskRelationService = new TaskRelationService()
const relations = tasksToCreate.map(async t => {
const createdTask = createdTasks.find(ct => ct.title === t.title)
if (typeof createdTask === 'undefined') {
return
}
if (t.parent === null) {
emit('taskAdded', createdTask)
return
}
const createdParentTask = createdTasks.find(ct => ct.title === t.parent)
if (typeof createdTask === 'undefined' || typeof createdParentTask === 'undefined') {
return
}
const rel = await taskRelationService.create(new TaskRelationModel({
taskId: createdTask.id,
otherTaskId: createdParentTask.id,
relationKind: RELATION_KIND.PARENTTASK,
}))
createdTask.relatedTasks[RELATION_KIND.PARENTTASK] = [createdParentTask]
// we're only emitting here so that the relation shows up in the task list
emit('taskAdded', createdTask)
return rel
})
await Promise.all(relations)
} catch (e: any) { } catch (e: any) {
newTaskTitle.value = taskTitleBackup newTaskTitle.value = taskTitleBackup
if (e?.message === 'NO_LIST') { if (e?.message === 'NO_LIST') {

View file

@ -17,7 +17,7 @@
<div :key="c.id" class="media comment" v-for="c in comments"> <div :key="c.id" class="media comment" v-for="c in comments">
<figure class="media-left is-hidden-mobile"> <figure class="media-left is-hidden-mobile">
<img <img
:src="c.author.getAvatarUrl(48)" :src="getAvatarUrl(c.author, 48)"
alt="" alt=""
class="image is-avatar" class="image is-avatar"
height="48" height="48"
@ -27,13 +27,13 @@
<div class="media-content"> <div class="media-content">
<div class="comment-info"> <div class="comment-info">
<img <img
:src="c.author.getAvatarUrl(20)" :src="getAvatarUrl(c.author, 20)"
alt="" alt=""
class="image is-avatar d-print-none" class="image is-avatar d-print-none"
height="20" height="20"
width="20" width="20"
/> />
<strong>{{ c.author.getDisplayName() }}</strong>&nbsp; <strong>{{ getDisplayName(c.author) }}</strong>&nbsp;
<span v-tooltip="formatDateLong(c.created)" class="has-text-grey"> <span v-tooltip="formatDateLong(c.created)" class="has-text-grey">
{{ formatDateSince(c.created) }} {{ formatDateSince(c.created) }}
</span> </span>
@ -153,7 +153,6 @@
<script setup lang="ts"> <script setup lang="ts">
import {ref, reactive, computed, shallowReactive, watch, nextTick} from 'vue' import {ref, reactive, computed, shallowReactive, watch, nextTick} from 'vue'
import {useStore} from '@/store'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import Editor from '@/components/input/AsyncEditor' import Editor from '@/components/input/AsyncEditor'
@ -167,7 +166,9 @@ import type {ITask} from '@/modelTypes/ITask'
import {uploadFile} from '@/helpers/attachments' import {uploadFile} from '@/helpers/attachments'
import {success} from '@/message' import {success} from '@/message'
import {formatDateLong, formatDateSince} from '@/helpers/time/formatDate' import {formatDateLong, formatDateSince} from '@/helpers/time/formatDate'
import {getAvatarUrl, getDisplayName} from '@/models/user'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'
import {useAuthStore} from '@/stores/auth'
const props = defineProps({ const props = defineProps({
taskId: { taskId: {
@ -180,8 +181,8 @@ const props = defineProps({
}) })
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const store = useStore()
const configStore = useConfigStore() const configStore = useConfigStore()
const authStore = useAuthStore()
const comments = ref<ITaskComment[]>([]) const comments = ref<ITaskComment[]>([])
@ -196,8 +197,8 @@ const newComment = reactive(new TaskCommentModel())
const saved = ref<ITask['id'] | null>(null) const saved = ref<ITask['id'] | null>(null)
const saving = ref<ITask['id'] | null>(null) const saving = ref<ITask['id'] | null>(null)
const userAvatar = computed(() => store.state.auth.info.getAvatarUrl(48)) const userAvatar = computed(() => getAvatarUrl(authStore.info, 48))
const currentUserId = computed(() => store.state.auth.info.id) const currentUserId = computed(() => authStore.info.id)
const enabled = computed(() => configStore.taskCommentsEnabled) const enabled = computed(() => configStore.taskCommentsEnabled)
const actions = computed(() => { const actions = computed(() => {
if (!props.canWrite) { if (!props.canWrite) {

View file

@ -3,7 +3,7 @@
<time :datetime="formatISO(task.created)" v-tooltip="formatDateLong(task.created)"> <time :datetime="formatISO(task.created)" v-tooltip="formatDateLong(task.created)">
<i18n-t keypath="task.detail.created" scope="global"> <i18n-t keypath="task.detail.created" scope="global">
<span>{{ formatDateSince(task.created) }}</span> <span>{{ formatDateSince(task.created) }}</span>
{{ task.createdBy.getDisplayName() }} {{ getDisplayName(task.createdBy) }}
</i18n-t> </i18n-t>
</time> </time>
<template v-if="+new Date(task.created) !== +new Date(task.updated)"> <template v-if="+new Date(task.created) !== +new Date(task.updated)">
@ -30,6 +30,7 @@
import {computed, toRefs, type PropType} from 'vue' import {computed, toRefs, type PropType} from 'vue'
import type {ITask} from '@/modelTypes/ITask' import type {ITask} from '@/modelTypes/ITask'
import {formatISO, formatDateLong, formatDateSince} from '@/helpers/time/formatDate' import {formatISO, formatDateLong, formatDateSince} from '@/helpers/time/formatDate'
import {getDisplayName} from '@/models/user'
const props = defineProps({ const props = defineProps({
task: { task: {

View file

@ -38,13 +38,13 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import {ref, shallowReactive, computed, watch, onMounted, onBeforeUnmount, type PropType} from 'vue' import {ref, shallowReactive, computed, watch, onMounted, onBeforeUnmount, toRef, type PropType} from 'vue'
import {useStore} from '@/store'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import flatPickr from 'vue-flatpickr-component' import flatPickr from 'vue-flatpickr-component'
import TaskService from '@/services/task' import TaskService from '@/services/task'
import type {ITask} from '@/modelTypes/ITask' import type {ITask} from '@/modelTypes/ITask'
import {useAuthStore} from '@/stores/auth'
const props = defineProps({ const props = defineProps({
modelValue: { modelValue: {
@ -55,7 +55,7 @@ const props = defineProps({
const emit = defineEmits(['update:modelValue']) const emit = defineEmits(['update:modelValue'])
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const store = useStore() const authStore = useAuthStore()
const taskService = shallowReactive(new TaskService()) const taskService = shallowReactive(new TaskService())
const task = ref<ITask>() const task = ref<ITask>()
@ -63,12 +63,12 @@ const task = ref<ITask>()
// We're saving the due date seperately to prevent null errors in very short periods where the task is null. // We're saving the due date seperately to prevent null errors in very short periods where the task is null.
const dueDate = ref<Date>() const dueDate = ref<Date>()
const lastValue = ref<Date>() const lastValue = ref<Date>()
const changeInterval = ref<number>() const changeInterval = ref<ReturnType<typeof setInterval>>()
watch( watch(
() => props.modelValue, toRef(props, 'modelValue'),
(value) => { (value) => {
task.value = value task.value = { ...value }
dueDate.value = value.dueDate dueDate.value = value.dueDate
lastValue.value = value.dueDate lastValue.value = value.dueDate
}, },
@ -103,7 +103,7 @@ const flatPickerConfig = computed(() => ({
time_24hr: true, time_24hr: true,
inline: true, inline: true,
locale: { locale: {
firstDayOfWeek: store.state.auth.settings.weekStart, firstDayOfWeek: authStore.settings.weekStart,
}, },
})) }))
@ -123,9 +123,10 @@ async function updateDueDate() {
return return
} }
// FIXME: direct prop manipulation const newTask = await taskService.update({
task.value.dueDate = new Date(dueDate.value) ...task.value,
const newTask = await taskService.update(task.value) dueDate: new Date(dueDate.value),
})
lastValue.value = newTask.dueDate lastValue.value = newTask.dueDate
task.value = newTask task.value = newTask
emit('update:modelValue', newTask) emit('update:modelValue', newTask)

View file

@ -32,11 +32,12 @@
<script setup lang="ts"> <script setup lang="ts">
import {ref,computed, watch, type PropType} from 'vue' import {ref,computed, watch, type PropType} from 'vue'
import {useStore} from '@/store'
import Editor from '@/components/input/AsyncEditor' import Editor from '@/components/input/AsyncEditor'
import type {ITask} from '@/modelTypes/ITask' import type {ITask} from '@/modelTypes/ITask'
import {useTaskStore} from '@/stores/tasks'
import TaskModel from '@/models/task'
const props = defineProps({ const props = defineProps({
@ -55,14 +56,14 @@ const props = defineProps({
const emit = defineEmits(['update:modelValue']) const emit = defineEmits(['update:modelValue'])
const task = ref<ITask>({description: ''}) const task = ref<ITask>(new TaskModel())
const saved = ref(false) const saved = ref(false)
// Since loading is global state, this variable ensures we're only showing the saving icon when saving the description. // Since loading is global state, this variable ensures we're only showing the saving icon when saving the description.
const saving = ref(false) const saving = ref(false)
const store = useStore() const taskStore = useTaskStore()
const loading = computed(() => store.state.loading) const loading = computed(() => taskStore.isLoading)
watch( watch(
() => props.modelValue, () => props.modelValue,
@ -77,7 +78,7 @@ async function save() {
try { try {
// FIXME: don't update state from internal. // FIXME: don't update state from internal.
task.value = await store.dispatch('tasks/update', task.value) task.value = await taskStore.update(task.value)
emit('update:modelValue', task.value) emit('update:modelValue', task.value)
saved.value = true saved.value = true

View file

@ -29,7 +29,6 @@
<script setup lang="ts"> <script setup lang="ts">
import {ref, shallowReactive, watch, type PropType} from 'vue' import {ref, shallowReactive, watch, type PropType} from 'vue'
import {useStore} from '@/store'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import User from '@/components/misc/user.vue' import User from '@/components/misc/user.vue'
@ -39,7 +38,9 @@ import BaseButton from '@/components/base/BaseButton.vue'
import {includesById} from '@/helpers/utils' import {includesById} from '@/helpers/utils'
import ListUserService from '@/services/listUsers' import ListUserService from '@/services/listUsers'
import {success} from '@/message' import {success} from '@/message'
import type { IUser } from '@/modelTypes/IUser' import {useTaskStore} from '@/stores/tasks'
import type {IUser} from '@/modelTypes/IUser'
const props = defineProps({ const props = defineProps({
taskId: { taskId: {
@ -60,7 +61,7 @@ const props = defineProps({
}) })
const emit = defineEmits(['update:modelValue']) const emit = defineEmits(['update:modelValue'])
const store = useStore() const taskStore = useTaskStore()
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const listUserService = shallowReactive(new ListUserService()) const listUserService = shallowReactive(new ListUserService())
@ -79,13 +80,13 @@ watch(
) )
async function addAssignee(user: IUser) { async function addAssignee(user: IUser) {
await store.dispatch('tasks/addAssignee', {user: user, taskId: props.taskId}) await taskStore.addAssignee({user: user, taskId: props.taskId})
emit('update:modelValue', assignees.value) emit('update:modelValue', assignees.value)
success({message: t('task.assignee.assignSuccess')}) success({message: t('task.assignee.assignSuccess')})
} }
async function removeAssignee(user: IUser) { async function removeAssignee(user: IUser) {
await store.dispatch('tasks/removeAssignee', {user: user, taskId: props.taskId}) await taskStore.removeAssignee({user: user, taskId: props.taskId})
// Remove the assignee from the list // Remove the assignee from the list
for (const a in assignees.value) { for (const a in assignees.value) {

View file

@ -40,7 +40,6 @@
<script setup lang="ts"> <script setup lang="ts">
import {type PropType, ref, computed, shallowReactive, watch} from 'vue' import {type PropType, ref, computed, shallowReactive, watch} from 'vue'
import {useStore} from '@/store'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import LabelModel from '@/models/label' import LabelModel from '@/models/label'
@ -49,8 +48,9 @@ import {success} from '@/message'
import BaseButton from '@/components/base/BaseButton.vue' import BaseButton from '@/components/base/BaseButton.vue'
import Multiselect from '@/components/input/multiselect.vue' import Multiselect from '@/components/input/multiselect.vue'
import type { ILabel } from '@/modelTypes/ILabel' import type {ILabel} from '@/modelTypes/ILabel'
import { useLabelStore } from '@/stores/labels' import {useLabelStore} from '@/stores/labels'
import {useTaskStore} from '@/stores/tasks'
const props = defineProps({ const props = defineProps({
modelValue: { modelValue: {
@ -69,7 +69,6 @@ const props = defineProps({
const emit = defineEmits(['update:modelValue']) const emit = defineEmits(['update:modelValue'])
const store = useStore()
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const labelTaskService = shallowReactive(new LabelTaskService()) const labelTaskService = shallowReactive(new LabelTaskService())
@ -87,6 +86,7 @@ watch(
}, },
) )
const taskStore = useTaskStore()
const labelStore = useLabelStore() const labelStore = useLabelStore()
const foundLabels = computed(() => labelStore.filterLabelsByQuery(labels.value, query.value)) const foundLabels = computed(() => labelStore.filterLabelsByQuery(labels.value, query.value))
@ -97,17 +97,13 @@ function findLabel(newQuery: string) {
} }
async function addLabel(label: ILabel, showNotification = true) { async function addLabel(label: ILabel, showNotification = true) {
const bubble = () => {
emit('update:modelValue', labels.value)
}
if (props.taskId === 0) { if (props.taskId === 0) {
bubble() emit('update:modelValue', labels.value)
return return
} }
await store.dispatch('tasks/addLabel', {label, taskId: props.taskId}) await taskStore.addLabel({label, taskId: props.taskId})
bubble() emit('update:modelValue', labels.value)
if (showNotification) { if (showNotification) {
success({message: t('task.label.addSuccess')}) success({message: t('task.label.addSuccess')})
} }
@ -115,7 +111,7 @@ async function addLabel(label: ILabel, showNotification = true) {
async function removeLabel(label: ILabel) { async function removeLabel(label: ILabel) {
if (props.taskId !== 0) { if (props.taskId !== 0) {
await store.dispatch('tasks/removeLabel', {label, taskId: props.taskId}) await taskStore.removeLabel({label, taskId: props.taskId})
} }
for (const l in labels.value) { for (const l in labels.value) {

View file

@ -38,7 +38,6 @@
<script setup lang="ts"> <script setup lang="ts">
import {ref, computed, type PropType} from 'vue' import {ref, computed, type PropType} from 'vue'
import {useStore} from '@/store'
import {useRouter} from 'vue-router' import {useRouter} from 'vue-router'
import BaseButton from '@/components/base/BaseButton.vue' import BaseButton from '@/components/base/BaseButton.vue'
@ -48,6 +47,7 @@ import {useCopyToClipboard} from '@/composables/useCopyToClipboard'
import type {ITask} from '@/modelTypes/ITask' import type {ITask} from '@/modelTypes/ITask'
import ColorBubble from '@/components/misc/colorBubble.vue' import ColorBubble from '@/components/misc/colorBubble.vue'
import {useTaskStore} from '@/stores/tasks'
const props = defineProps({ const props = defineProps({
task: { task: {
@ -72,8 +72,8 @@ async function copyUrl() {
await copy(absoluteURL) await copy(absoluteURL)
} }
const store = useStore() const taskStore = useTaskStore()
const loading = computed(() => store.state.loading) const loading = computed(() => taskStore.isLoading)
const textIdentifier = computed(() => props.task?.getTextIdentifier() || '') const textIdentifier = computed(() => props.task?.getTextIdentifier() || '')
@ -93,7 +93,7 @@ async function save(title: string) {
try { try {
saving.value = true saving.value = true
const newTask = await store.dispatch('tasks/update', { const newTask = await taskStore.update({
...props.task, ...props.task,
title, title,
}) })

View file

@ -78,6 +78,7 @@ import type {ITask} from '@/modelTypes/ITask'
import {formatDateLong, formatISO, formatDateSince} from '@/helpers/time/formatDate' import {formatDateLong, formatISO, formatDateSince} from '@/helpers/time/formatDate'
import {colorIsDark} from '@/helpers/color/colorIsDark' import {colorIsDark} from '@/helpers/color/colorIsDark'
import {useTaskStore} from '@/stores/tasks'
export default defineComponent({ export default defineComponent({
name: 'kanban-card', name: 'kanban-card',
@ -121,7 +122,7 @@ export default defineComponent({
this.loadingInternal = true this.loadingInternal = true
try { try {
const done = !task.done const done = !task.done
await this.$store.dispatch('tasks/update', { await useTaskStore().update({
...task, ...task,
done, done,
}) })

View file

@ -149,7 +149,6 @@
import {ref, reactive, shallowReactive, watch, computed, type PropType} from 'vue' import {ref, reactive, shallowReactive, watch, computed, type PropType} from 'vue'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useRoute} from 'vue-router' import {useRoute} from 'vue-router'
import {useStore} from '@/store'
import TaskService from '@/services/task' import TaskService from '@/services/task'
import TaskModel from '@/models/task' import TaskModel from '@/models/task'
@ -167,6 +166,7 @@ import Fancycheckbox from '@/components/input/fancycheckbox.vue'
import {useNamespaceStore} from '@/stores/namespaces' import {useNamespaceStore} from '@/stores/namespaces'
import {error, success} from '@/message' import {error, success} from '@/message'
import {useTaskStore} from '@/stores/tasks'
const props = defineProps({ const props = defineProps({
taskId: { taskId: {
@ -190,7 +190,7 @@ const props = defineProps({
}, },
}) })
const store = useStore() const taskStore = useTaskStore()
const namespaceStore = useNamespaceStore() const namespaceStore = useNamespaceStore()
const route = useRoute() const route = useRoute()
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
@ -344,7 +344,7 @@ async function createAndRelateTask(title: string) {
} }
async function toggleTaskDone(task: ITask) { async function toggleTaskDone(task: ITask) {
await store.dispatch('tasks/update', task) await taskStore.update(task)
// Find the task in the list and update it so that it is correctly strike through // Find the task in the list and update it so that it is correctly strike through
Object.entries(relatedTasks.value).some(([kind, tasks]) => { Object.entries(relatedTasks.value).some(([kind, tasks]) => {

View file

@ -119,6 +119,7 @@ import {formatDateSince, formatISO, formatDateLong} from '@/helpers/time/formatD
import ColorBubble from '@/components/misc/colorBubble.vue' import ColorBubble from '@/components/misc/colorBubble.vue'
import {useListStore} from '@/stores/lists' import {useListStore} from '@/stores/lists'
import {useNamespaceStore} from '@/stores/namespaces' import {useNamespaceStore} from '@/stores/namespaces'
import {useTaskStore} from '@/stores/tasks'
export default defineComponent({ export default defineComponent({
name: 'singleTaskInList', name: 'singleTaskInList',
@ -208,7 +209,7 @@ export default defineComponent({
async markAsDone(checked: boolean) { async markAsDone(checked: boolean) {
const updateFunc = async () => { const updateFunc = async () => {
const task = await this.$store.dispatch('tasks/update', this.task) const task = await useTaskStore().update(this.task)
this.task = task this.task = task
this.$emit('task-updated', task) this.$emit('task-updated', task)
this.$message.success({ this.$message.success({

View file

@ -2,6 +2,7 @@ import {ref, shallowReactive, watch, computed} from 'vue'
import {useRoute} from 'vue-router' import {useRoute} from 'vue-router'
import TaskCollectionService from '@/services/taskCollection' import TaskCollectionService from '@/services/taskCollection'
import type { ITask } from '@/modelTypes/ITask'
// FIXME: merge with DEFAULT_PARAMS in filters.vue // FIXME: merge with DEFAULT_PARAMS in filters.vue
export const getDefaultParams = () => ({ export const getDefaultParams = () => ({
@ -70,7 +71,7 @@ export function useTaskList(listId, sortByDefault = SORT_BY_DEFAULT) {
const loading = computed(() => taskCollectionService.loading) const loading = computed(() => taskCollectionService.loading)
const totalPages = computed(() => taskCollectionService.totalPages) const totalPages = computed(() => taskCollectionService.totalPages)
const tasks = ref([]) const tasks = ref<ITask[]>([])
async function loadTasks() { async function loadTasks() {
tasks.value = [] tasks.value = []
tasks.value = await taskCollectionService.getAll(...getAllTasksParams.value) tasks.value = await taskCollectionService.getAll(...getAllTasksParams.value)
@ -81,10 +82,10 @@ export function useTaskList(listId, sortByDefault = SORT_BY_DEFAULT) {
watch(() => route.query, (query) => { watch(() => route.query, (query) => {
const { page: pageQueryValue, search: searchQuery } = query const { page: pageQueryValue, search: searchQuery } = query
if (searchQuery !== undefined) { if (searchQuery !== undefined) {
search.value = searchQuery search.value = searchQuery as string
} }
if (pageQueryValue !== undefined) { if (pageQueryValue !== undefined) {
page.value = parseInt(pageQueryValue) page.value = Number(pageQueryValue)
} }
}, { immediate: true }) }, { immediate: true })

View file

@ -2,7 +2,7 @@ import AttachmentModel from '@/models/attachment'
import type {IAttachment} from '@/modelTypes/IAttachment' import type {IAttachment} from '@/modelTypes/IAttachment'
import AttachmentService from '@/services/attachment' import AttachmentService from '@/services/attachment'
import { store } from '@/store' import {useTaskStore} from '@/stores/tasks'
export function uploadFile(taskId: number, file: File, onSuccess: (url: string) => void) { export function uploadFile(taskId: number, file: File, onSuccess: (url: string) => void) {
const attachmentService = new AttachmentService() const attachmentService = new AttachmentService()
@ -22,7 +22,7 @@ export async function uploadFiles(
console.debug(`Uploaded attachments for task ${taskId}, response was`, response) console.debug(`Uploaded attachments for task ${taskId}, response was`, response)
response.success?.map((attachment: IAttachment) => { response.success?.map((attachment: IAttachment) => {
store.dispatch('tasks/addTaskAttachment', { useTaskStore().addTaskAttachment({
taskId, taskId,
attachment, attachment,
}) })

View file

@ -0,0 +1,109 @@
import {describe, it, expect} from 'vitest'
import {parseSubtasksViaIndention} from '@/helpers/parseSubtasksViaIndention'
describe('Parse Subtasks via Relation', () => {
it('Should not return a parent for a single task', () => {
const tasks = parseSubtasksViaIndention('single task')
expect(tasks).to.have.length(1)
expect(tasks[0].parent).toBeNull()
})
it('Should not return a parent for multiple tasks without indention', () => {
const tasks = parseSubtasksViaIndention(`task one
task two`)
expect(tasks).to.have.length(2)
expect(tasks[0].parent).toBeNull()
expect(tasks[1].parent).toBeNull()
})
it('Should return a parent for two tasks with indention', () => {
const tasks = parseSubtasksViaIndention(`parent task
sub task`)
expect(tasks).to.have.length(2)
expect(tasks[0].parent).toBeNull()
expect(tasks[0].title).to.eq('parent task')
expect(tasks[1].parent).to.eq('parent task')
expect(tasks[1].title).to.eq('sub task')
})
it('Should return a parent for multiple subtasks', () => {
const tasks = parseSubtasksViaIndention(`parent task
sub task one
sub task two`)
expect(tasks).to.have.length(3)
expect(tasks[0].parent).toBeNull()
expect(tasks[0].title).to.eq('parent task')
expect(tasks[1].title).to.eq('sub task one')
expect(tasks[1].parent).to.eq('parent task')
expect(tasks[2].title).to.eq('sub task two')
expect(tasks[2].parent).to.eq('parent task')
})
it('Should work with multiple indention levels', () => {
const tasks = parseSubtasksViaIndention(`parent task
sub task
sub sub task`)
expect(tasks).to.have.length(3)
expect(tasks[0].parent).toBeNull()
expect(tasks[0].title).to.eq('parent task')
expect(tasks[1].title).to.eq('sub task')
expect(tasks[1].parent).to.eq('parent task')
expect(tasks[2].title).to.eq('sub sub task')
expect(tasks[2].parent).to.eq('sub task')
})
it('Should work with multiple indention levels and multiple tasks', () => {
const tasks = parseSubtasksViaIndention(`parent task
sub task
sub sub task one
sub sub task two`)
expect(tasks).to.have.length(4)
expect(tasks[0].parent).toBeNull()
expect(tasks[0].title).to.eq('parent task')
expect(tasks[1].title).to.eq('sub task')
expect(tasks[1].parent).to.eq('parent task')
expect(tasks[2].title).to.eq('sub sub task one')
expect(tasks[2].parent).to.eq('sub task')
expect(tasks[3].title).to.eq('sub sub task two')
expect(tasks[3].parent).to.eq('sub task')
})
it('Should work with multiple indention levels and multiple tasks', () => {
const tasks = parseSubtasksViaIndention(`parent task
sub task
sub sub task one
sub sub sub task
sub sub task two`)
expect(tasks).to.have.length(5)
expect(tasks[0].parent).toBeNull()
expect(tasks[0].title).to.eq('parent task')
expect(tasks[1].title).to.eq('sub task')
expect(tasks[1].parent).to.eq('parent task')
expect(tasks[2].title).to.eq('sub sub task one')
expect(tasks[2].parent).to.eq('sub task')
expect(tasks[3].title).to.eq('sub sub sub task')
expect(tasks[3].parent).to.eq('sub sub task one')
expect(tasks[4].title).to.eq('sub sub task two')
expect(tasks[4].parent).to.eq('sub task')
})
it('Should return a parent for multiple subtasks with special stuff', () => {
const tasks = parseSubtasksViaIndention(`* parent task
* sub task one
sub task two`)
expect(tasks).to.have.length(3)
expect(tasks[0].parent).toBeNull()
expect(tasks[0].title).to.eq('parent task')
expect(tasks[1].title).to.eq('sub task one')
expect(tasks[1].parent).to.eq('parent task')
expect(tasks[2].title).to.eq('sub task two')
expect(tasks[2].parent).to.eq('parent task')
})
it('Should not break when the first line is indented', () => {
const tasks = parseSubtasksViaIndention(' single task')
expect(tasks).to.have.length(1)
expect(tasks[0].parent).toBeNull()
})
})

View file

@ -0,0 +1,48 @@
export interface TaskWithParent {
title: string,
parent: string | null,
}
function cleanupTitle(title: string) {
return title.replace(/^((\* |\+ |- )(\[ \] )?)/g, '')
}
const spaceRegex = /^ */
/**
* @param taskTitles should be multiple lines of task tiles with indention to declare their parent/subtask
* relation between each other.
*/
export function parseSubtasksViaIndention(taskTitles: string): TaskWithParent[] {
const titles = taskTitles.split(/[\r\n]+/)
return titles.map((title, index) => {
const task: TaskWithParent = {
title: cleanupTitle(title),
parent: null,
}
if (index === 0) {
return task
}
const matched = spaceRegex.exec(title)
const matchedSpaces = matched ? matched[0].length : 0
if (matchedSpaces > 0) {
// Go up the tree to find the first task with less indention than the current one
let pi = 1
let parentSpaces = 0
do {
task.parent = cleanupTitle(titles[index - pi])
pi++
const parentMatched = spaceRegex.exec(task.parent)
parentSpaces = parentMatched ? parentMatched[0].length : 0
} while (parentSpaces >= matchedSpaces)
task.title = cleanupTitle(title.replace(spaceRegex, ''))
task.parent = task.parent.replace(spaceRegex, '')
}
return task
})
}

View file

@ -8,3 +8,7 @@ export function getSavedFilterIdFromListId(listId: IList['id']) {
} }
return filterId return filterId
} }
export function isSavedFilter(list: IList) {
return getSavedFilterIdFromListId(list.id) > 0
}

View file

@ -1,8 +1,8 @@
import {createApp} from 'vue' import {createApp} from 'vue'
import App from './App.vue' import pinia from './pinia'
import router from './router' import router from './router'
import {createPinia} from 'pinia' import App from './App.vue'
import {error, success} from './message' import {error, success} from './message'
@ -105,7 +105,6 @@ if (window.SENTRY_ENABLED) {
import('./sentry').then(sentry => sentry.default(app, router)) import('./sentry').then(sentry => sentry.default(app, router))
} }
const pinia = createPinia()
app.use(pinia) app.use(pinia)
app.use(store, key) // pass the injection key app.use(store, key) // pass the injection key

View file

@ -1,11 +1,21 @@
import type {IAbstract} from './IAbstract' import type {IAbstract} from './IAbstract'
import type {IUserSettings} from './IUserSettings' import type {IUserSettings} from './IUserSettings'
export const AUTH_TYPES = {
'UNKNOWN': 0,
'USER': 1,
'LINK_SHARE': 2,
} as const
type AuthType = typeof AUTH_TYPES[keyof typeof AUTH_TYPES]
export interface IUser extends IAbstract { export interface IUser extends IAbstract {
id: number id: number
email: string email: string
username: string username: string
name: string name: string
exp: number
type: AuthType
created: Date created: Date
updated: Date updated: Date

View file

@ -11,4 +11,5 @@ export interface IUserSettings extends IAbstract {
defaultListId: undefined | IList['id'] defaultListId: undefined | IList['id']
weekStart: 0 | 1 | 2 | 3 | 4 | 5 | 6 weekStart: 0 | 1 | 2 | 3 | 4 | 5 | 6
timezone: string timezone: string
language: string
} }

View file

@ -9,8 +9,6 @@ import type {ITask} from '@/modelTypes/ITask'
import type {INamespace} from '@/modelTypes/INamespace' import type {INamespace} from '@/modelTypes/INamespace'
import type {ISubscription} from '@/modelTypes/ISubscription' import type {ISubscription} from '@/modelTypes/ISubscription'
import {getSavedFilterIdFromListId} from '@/helpers/savedFilter'
export default class ListModel extends AbstractModel<IList> implements IList { export default class ListModel extends AbstractModel<IList> implements IList {
id = 0 id = 0
title = '' title = ''
@ -52,12 +50,4 @@ export default class ListModel extends AbstractModel<IList> implements IList {
this.created = new Date(this.created) this.created = new Date(this.created)
this.updated = new Date(this.updated) this.updated = new Date(this.updated)
} }
isSavedFilter() {
return this.getSavedFilterId() > 0
}
getSavedFilterId() {
return getSavedFilterIdFromListId(this.id)
}
} }

View file

@ -1,12 +1,13 @@
import AbstractModel from './abstractModel' import AbstractModel from './abstractModel'
import {parseDateOrNull} from '@/helpers/parseDateOrNull' import {parseDateOrNull} from '@/helpers/parseDateOrNull'
import UserModel from '@/models/user' import UserModel, {getDisplayName} from '@/models/user'
import TaskModel from '@/models/task' import TaskModel from '@/models/task'
import TaskCommentModel from '@/models/taskComment' import TaskCommentModel from '@/models/taskComment'
import ListModel from '@/models/list' import ListModel from '@/models/list'
import TeamModel from '@/models/team' import TeamModel from '@/models/team'
import {NOTIFICATION_NAMES, type INotification} from '@/modelTypes/INotification' import {NOTIFICATION_NAMES, type INotification} from '@/modelTypes/INotification'
import type { IUser } from '@/modelTypes/IUser'
export default class NotificationModel extends AbstractModel<INotification> implements INotification { export default class NotificationModel extends AbstractModel<INotification> implements INotification {
id = 0 id = 0
@ -61,14 +62,14 @@ export default class NotificationModel extends AbstractModel<INotification> impl
this.readAt = parseDateOrNull(this.readAt) this.readAt = parseDateOrNull(this.readAt)
} }
toText(user = null) { toText(user: IUser | null = null) {
let who = '' let who = ''
switch (this.name) { switch (this.name) {
case NOTIFICATION_NAMES.TASK_COMMENT: case NOTIFICATION_NAMES.TASK_COMMENT:
return `commented on ${this.notification.task.getTextIdentifier()}` return `commented on ${this.notification.task.getTextIdentifier()}`
case NOTIFICATION_NAMES.TASK_ASSIGNED: case NOTIFICATION_NAMES.TASK_ASSIGNED:
who = `${this.notification.assignee.getDisplayName()}` who = `${getDisplayName(this.notification.assignee)}`
if (user !== null && user.id === this.notification.assignee.id) { if (user !== null && user.id === this.notification.assignee.id) {
who = 'you' who = 'you'
@ -80,7 +81,7 @@ export default class NotificationModel extends AbstractModel<INotification> impl
case NOTIFICATION_NAMES.LIST_CREATED: case NOTIFICATION_NAMES.LIST_CREATED:
return `created ${this.notification.list.title}` return `created ${this.notification.list.title}`
case NOTIFICATION_NAMES.TEAM_MEMBER_ADDED: case NOTIFICATION_NAMES.TEAM_MEMBER_ADDED:
who = `${this.notification.member.getDisplayName()}` who = `${getDisplayName(this.notification.member)}`
if (user !== null && user.id === this.notification.member.id) { if (user !== null && user.id === this.notification.member.id) {
who = 'you' who = 'you'

View file

@ -1,18 +1,32 @@
import AbstractModel from './abstractModel' import AbstractModel from './abstractModel'
import UserSettingsModel from '@/models/userSettings' import UserSettingsModel from '@/models/userSettings'
import type { IUser } from '@/modelTypes/IUser' import { AUTH_TYPES, type IUser } from '@/modelTypes/IUser'
import type { IUserSettings } from '@/modelTypes/IUserSettings' import type { IUserSettings } from '@/modelTypes/IUserSettings'
export function getAvatarUrl(user: IUser, size = 50) {
return `${window.API_URL}/avatar/${user.username}?size=${size}`
}
export function getDisplayName(user: IUser) {
if (user.name !== '') {
return user.name
}
return user.username
}
export default class UserModel extends AbstractModel<IUser> implements IUser { export default class UserModel extends AbstractModel<IUser> implements IUser {
id = 0 id = 0
email = '' email = ''
username = '' username = ''
name = '' name = ''
exp = 0
type = AUTH_TYPES.UNKNOWN
created: Date = null created: Date
updated: Date = null updated: Date
settings: IUserSettings = null settings: IUserSettings
constructor(data: Partial<IUser> = {}) { constructor(data: Partial<IUser> = {}) {
super() super()
@ -21,20 +35,6 @@ export default class UserModel extends AbstractModel<IUser> implements IUser {
this.created = new Date(this.created) this.created = new Date(this.created)
this.updated = new Date(this.updated) this.updated = new Date(this.updated)
if (this.settings !== null) { this.settings = new UserSettingsModel(this.settings || {})
this.settings = new UserSettingsModel(this.settings)
}
}
getAvatarUrl(size = 50) {
return `${window.API_URL}/avatar/${this.username}?size=${size}`
}
getDisplayName() {
if (this.name !== '') {
return this.name
}
return this.username
} }
} }

View file

@ -1,8 +1,7 @@
import AbstractModel from './abstractModel' import AbstractModel from './abstractModel'
import type {IUserSettings} from '@/modelTypes/IUserSettings' import type {IUserSettings} from '@/modelTypes/IUserSettings'
import type {IList} from '@/modelTypes/IList' import {getCurrentLanguage} from '@/i18n'
export default class UserSettingsModel extends AbstractModel<IUserSettings> implements IUserSettings { export default class UserSettingsModel extends AbstractModel<IUserSettings> implements IUserSettings {
name = '' name = ''
@ -10,11 +9,12 @@ export default class UserSettingsModel extends AbstractModel<IUserSettings> impl
discoverableByName = false discoverableByName = false
discoverableByEmail = false discoverableByEmail = false
overdueTasksRemindersEnabled = true overdueTasksRemindersEnabled = true
defaultListId: undefined | IList['id'] = undefined defaultListId = undefined
weekStart: IUserSettings['weekStart'] = 0 weekStart = 0 as IUserSettings['weekStart']
timezone = '' timezone = ''
language = getCurrentLanguage()
constructor(data: Partial<IUserSettings>) { constructor(data: Partial<IUserSettings> = {}) {
super() super()
this.assignData(data) this.assignData(data)
} }

5
src/pinia.ts Normal file
View file

@ -0,0 +1,5 @@
import {createPinia} from 'pinia'
const pinia = createPinia()
export default pinia

View file

@ -1,7 +1,6 @@
import { createRouter, createWebHistory } from 'vue-router' import { createRouter, createWebHistory } from 'vue-router'
import type { RouteLocation } from 'vue-router' import type { RouteLocation } from 'vue-router'
import {saveLastVisited} from '@/helpers/saveLastVisited' import {saveLastVisited} from '@/helpers/saveLastVisited'
import {store} from '@/store'
import {saveListView, getListView} from '@/helpers/saveListView' import {saveListView, getListView} from '@/helpers/saveListView'
import {parseDateOrString} from '@/helpers/time/parseDateOrString' import {parseDateOrString} from '@/helpers/time/parseDateOrString'
@ -9,6 +8,7 @@ import {getNextWeekDate} from '@/helpers/time/getNextWeekDate'
import {setTitle} from '@/helpers/setTitle' import {setTitle} from '@/helpers/setTitle'
import {useListStore} from '@/stores/lists' import {useListStore} from '@/stores/lists'
import {useAuthStore} from '@/stores/auth'
import HomeComponent from '../views/Home.vue' import HomeComponent from '../views/Home.vue'
import NotFoundComponent from '../views/404.vue' import NotFoundComponent from '../views/404.vue'
@ -464,10 +464,8 @@ const router = createRouter({
}) })
export function getAuthForRoute(route: RouteLocation) { export function getAuthForRoute(route: RouteLocation) {
const authUser = store.getters['auth/authUser'] const authStore = useAuthStore()
const authLinkShare = store.getters['auth/authLinkShare'] if (authStore.authUser || authStore.authLinkShare) {
if (authUser || authLinkShare) {
return return
} }

View file

@ -13,9 +13,7 @@ import {
MENU_ACTIVE, MENU_ACTIVE,
QUICK_ACTIONS_ACTIVE, QUICK_ACTIONS_ACTIVE,
} from './mutation-types' } from './mutation-types'
import auth from './modules/auth'
import kanban from './modules/kanban' import kanban from './modules/kanban'
import tasks from './modules/tasks'
import ListModel from '@/models/list' import ListModel from '@/models/list'
@ -23,6 +21,8 @@ import ListService from '../services/list'
import {checkAndSetApiUrl} from '@/helpers/checkAndSetApiUrl' import {checkAndSetApiUrl} from '@/helpers/checkAndSetApiUrl'
import type { RootStoreState, StoreState } from './types' import type { RootStoreState, StoreState } from './types'
import pinia from '@/pinia'
import {useAuthStore} from '@/stores/auth'
export const key: InjectionKey<Store<StoreState>> = Symbol() export const key: InjectionKey<Store<StoreState>> = Symbol()
@ -34,9 +34,7 @@ export function useStore () {
export const store = createStore<RootStoreState>({ export const store = createStore<RootStoreState>({
strict: import.meta.env.DEV, strict: import.meta.env.DEV,
modules: { modules: {
auth,
kanban, kanban,
tasks,
}, },
state: () => ({ state: () => ({
loading: false, loading: false,
@ -131,9 +129,10 @@ export const store = createStore<RootStoreState>({
commit(CURRENT_LIST, list) commit(CURRENT_LIST, list)
}, },
async loadApp({dispatch}) { async loadApp() {
await checkAndSetApiUrl(window.API_URL) await checkAndSetApiUrl(window.API_URL)
await dispatch('auth/checkAuth') const authStore = useAuthStore(pinia)
await authStore.checkAuth()
}, },
}, },
}) })

View file

@ -4,6 +4,7 @@ import type { IList } from '@/modelTypes/IList'
import type { IAttachment } from '@/modelTypes/IAttachment' import type { IAttachment } from '@/modelTypes/IAttachment'
import type { ILabel } from '@/modelTypes/ILabel' import type { ILabel } from '@/modelTypes/ILabel'
import type { INamespace } from '@/modelTypes/INamespace' import type { INamespace } from '@/modelTypes/INamespace'
import type { IUser } from '@/modelTypes/IUser'
export interface RootStoreState { export interface RootStoreState {
loading: boolean, loading: boolean,
@ -22,29 +23,16 @@ export interface AttachmentState {
attachments: IAttachment[], attachments: IAttachment[],
} }
export const AUTH_TYPES = {
'UNKNOWN': 0,
'USER': 1,
'LINK_SHARE': 2,
} as const
export interface Info {
id: number // what kind of id is this?
type: typeof AUTH_TYPES[keyof typeof AUTH_TYPES],
getAvatarUrl: () => string
settings: IUserSettings
name: string
email: string
exp: any
}
export interface AuthState { export interface AuthState {
authenticated: boolean, authenticated: boolean,
isLinkShareAuth: boolean, isLinkShareAuth: boolean,
info: Info | null, info: IUser | null,
needsTotpPasscode: boolean, needsTotpPasscode: boolean,
avatarUrl: string, avatarUrl: string,
lastUserInfoRefresh: Date | null, lastUserInfoRefresh: Date | null,
settings: IUserSettings, settings: IUserSettings,
isLoading: boolean,
isLoadingGeneralSettings: boolean
} }
export interface ConfigState { export interface ConfigState {
@ -106,7 +94,9 @@ export interface NamespaceState {
isLoading: boolean, isLoading: boolean,
} }
export interface TaskState {} export interface TaskState {
isLoading: boolean,
}
export type StoreState = RootStoreState & { export type StoreState = RootStoreState & {

View file

@ -1,38 +1,35 @@
import type { Module } from 'vuex' import {defineStore, acceptHMRUpdate} from 'pinia'
import {HTTPFactory, AuthenticatedHTTPFactory} from '@/http-common' import {HTTPFactory, AuthenticatedHTTPFactory} from '@/http-common'
import {i18n, getCurrentLanguage, saveLanguage} from '@/i18n' import {i18n, getCurrentLanguage, saveLanguage} from '@/i18n'
import {objectToSnakeCase} from '@/helpers/case' import {objectToSnakeCase} from '@/helpers/case'
import {LOADING} from '../mutation-types' import UserModel, { getAvatarUrl } from '@/models/user'
import UserModel from '@/models/user'
import UserSettingsService from '@/services/userSettings' import UserSettingsService from '@/services/userSettings'
import {getToken, refreshToken, removeToken, saveToken} from '@/helpers/auth' import {getToken, refreshToken, removeToken, saveToken} from '@/helpers/auth'
import {setLoading} from '@/store/helper' import {setLoadingPinia} from '@/store/helper'
import {success} from '@/message' import {success} from '@/message'
import {redirectToProvider} from '@/helpers/redirectToProvider' import {redirectToProvider} from '@/helpers/redirectToProvider'
import type { RootStoreState, AuthState, Info} from '@/store/types' import {AUTH_TYPES, type IUser} from '@/modelTypes/IUser'
import {AUTH_TYPES} from '@/store/types' import type {AuthState} from '@/store/types'
import type { IUserSettings } from '@/modelTypes/IUserSettings' import type {IUserSettings} from '@/modelTypes/IUserSettings'
import router from '@/router' import router from '@/router'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'
import UserSettingsModel from '@/models/userSettings'
import {store} from '@/store'
function defaultSettings(settings: Partial<IUserSettings>) { export const useAuthStore = defineStore('auth', {
if (typeof settings.weekStart === 'undefined' || settings.weekStart === '') { state: () : AuthState => ({
settings.weekStart = 0
}
return settings
}
const authStore : Module<AuthState, RootStoreState> = {
namespaced: true,
state: () => ({
authenticated: false, authenticated: false,
isLinkShareAuth: false, isLinkShareAuth: false,
info: null,
needsTotpPasscode: false, needsTotpPasscode: false,
info: null,
avatarUrl: '', avatarUrl: '',
settings: new UserSettingsModel(),
lastUserInfoRefresh: null, lastUserInfoRefresh: null,
settings: {}, // should be IUserSettings isLoading: false,
isLoadingGeneralSettings: false,
}), }),
getters: { getters: {
authUser(state) { authUser(state) {
@ -48,47 +45,56 @@ const authStore : Module<AuthState, RootStoreState> = {
) )
}, },
}, },
mutations: { actions: {
info(state, info: Info) { setIsLoading(isLoading: boolean) {
state.info = info this.isLoading = isLoading
},
setIsLoadingGeneralSettings(isLoading: boolean) {
this.isLoadingGeneralSettings = isLoading
},
setUser(info: IUser | null) {
this.info = info
if (info !== null) { if (info !== null) {
state.avatarUrl = info.getAvatarUrl() this.reloadAvatar()
if (info.settings) { if (info.settings) {
state.settings = defaultSettings(info.settings) this.settings = new UserSettingsModel(info.settings)
} }
state.isLinkShareAuth = info.id < 0 this.isLinkShareAuth = info.id < 0
} }
}, },
setUserSettings(state, settings: IUserSettings) { setUserSettings(settings: IUserSettings) {
state.settings = defaultSettings(settings) this.settings = new UserSettingsModel(settings)
const info = state.info !== null ? state.info : {} as Info this.info = new UserModel({
info.name = settings.name ...this.info !== null ? this.info : {},
state.info = info name: settings.name,
})
}, },
authenticated(state, authenticated: boolean) { setAuthenticated(authenticated: boolean) {
state.authenticated = authenticated this.authenticated = authenticated
}, },
isLinkShareAuth(state, isLinkShareAuth: boolean) { setIsLinkShareAuth(isLinkShareAuth: boolean) {
state.isLinkShareAuth = isLinkShareAuth this.isLinkShareAuth = isLinkShareAuth
}, },
needsTotpPasscode(state, needsTotpPasscode: boolean) { setNeedsTotpPasscode(needsTotpPasscode: boolean) {
state.needsTotpPasscode = needsTotpPasscode this.needsTotpPasscode = needsTotpPasscode
}, },
reloadAvatar(state) { reloadAvatar() {
if (!state.info) return if (!this.info) return
state.avatarUrl = `${state.info.getAvatarUrl()}&=${+new Date()}` this.avatarUrl = `${getAvatarUrl(this.info)}&=${+new Date()}`
}, },
lastUserRefresh(state) { updateLastUserRefresh() {
state.lastUserInfoRefresh = new Date() this.lastUserInfoRefresh = new Date()
}, },
},
actions: {
// Logs a user in with a set of credentials. // Logs a user in with a set of credentials.
async login(ctx, credentials) { async login(credentials) {
const HTTP = HTTPFactory() const HTTP = HTTPFactory()
ctx.commit(LOADING, true, {root: true}) store.commit('loading', true)
this.setIsLoading(true)
// Delete an eventually preexisting old token // Delete an eventually preexisting old token
removeToken() removeToken()
@ -99,30 +105,32 @@ const authStore : Module<AuthState, RootStoreState> = {
saveToken(response.data.token, true) saveToken(response.data.token, true)
// Tell others the user is autheticated // Tell others the user is autheticated
ctx.dispatch('checkAuth') this.checkAuth()
} catch (e) { } catch (e) {
if ( if (
e.response && e.response &&
e.response.data.code === 1017 && e.response.data.code === 1017 &&
!credentials.totpPasscode !credentials.totpPasscode
) { ) {
ctx.commit('needsTotpPasscode', true) this.setNeedsTotpPasscode(true)
} }
throw e throw e
} finally { } finally {
ctx.commit(LOADING, false, {root: true}) store.commit('loading', false)
this.setIsLoading(false)
} }
}, },
// Registers a new user and logs them in. // Registers a new user and logs them in.
// Not sure if this is the right place to put the logic in, maybe a seperate js component would be better suited. // Not sure if this is the right place to put the logic in, maybe a seperate js component would be better suited.
async register(ctx, credentials) { async register(credentials) {
const HTTP = HTTPFactory() const HTTP = HTTPFactory()
ctx.commit(LOADING, true, {root: true}) store.commit('loading', true)
this.setIsLoading(true)
try { try {
await HTTP.post('register', credentials) await HTTP.post('register', credentials)
return ctx.dispatch('login', credentials) return this.login(credentials)
} catch (e) { } catch (e) {
if (e.response?.data?.message) { if (e.response?.data?.message) {
throw e.response.data throw e.response.data
@ -130,13 +138,15 @@ const authStore : Module<AuthState, RootStoreState> = {
throw e throw e
} finally { } finally {
ctx.commit(LOADING, false, {root: true}) store.commit('loading', false)
this.setIsLoading(false)
} }
}, },
async openIdAuth(ctx, {provider, code}) { async openIdAuth({provider, code}) {
const HTTP = HTTPFactory() const HTTP = HTTPFactory()
ctx.commit(LOADING, true, {root: true}) store.commit('loading', true)
this.setIsLoading(true)
const data = { const data = {
code: code, code: code,
@ -150,28 +160,32 @@ const authStore : Module<AuthState, RootStoreState> = {
saveToken(response.data.token, true) saveToken(response.data.token, true)
// Tell others the user is autheticated // Tell others the user is autheticated
ctx.dispatch('checkAuth') this.checkAuth()
} finally { } finally {
ctx.commit(LOADING, false, {root: true}) store.commit('loading', false)
this.setIsLoading(false)
} }
}, },
async linkShareAuth(ctx, {hash, password}) { async linkShareAuth({hash, password}) {
const HTTP = HTTPFactory() const HTTP = HTTPFactory()
const response = await HTTP.post('/shares/' + hash + '/auth', { const response = await HTTP.post('/shares/' + hash + '/auth', {
password: password, password: password,
}) })
saveToken(response.data.token, false) saveToken(response.data.token, false)
ctx.dispatch('checkAuth') this.checkAuth()
return response.data return response.data
}, },
// Populates user information from jwt token saved in local storage in store // Populates user information from jwt token saved in local storage in store
checkAuth(ctx) { checkAuth() {
// This function can be called from multiple places at the same time and shortly after one another. // This function can be called from multiple places at the same time and shortly after one another.
// To prevent hitting the api too frequently or race conditions, we check at most once per minute. // To prevent hitting the api too frequently or race conditions, we check at most once per minute.
if (ctx.state.lastUserInfoRefresh !== null && ctx.state.lastUserInfoRefresh > (new Date()).setMinutes((new Date()).getMinutes() + 1)) { if (
this.lastUserInfoRefresh !== null &&
this.lastUserInfoRefresh > (new Date()).setMinutes((new Date()).getMinutes() + 1)
) {
return return
} }
@ -185,17 +199,17 @@ const authStore : Module<AuthState, RootStoreState> = {
const info = new UserModel(JSON.parse(atob(base64))) const info = new UserModel(JSON.parse(atob(base64)))
const ts = Math.round((new Date()).getTime() / 1000) const ts = Math.round((new Date()).getTime() / 1000)
authenticated = info.exp >= ts authenticated = info.exp >= ts
ctx.commit('info', info) this.setUser(info)
if (authenticated) { if (authenticated) {
ctx.dispatch('refreshUserInfo') this.refreshUserInfo()
} }
} }
ctx.commit('authenticated', authenticated) this.setAuthenticated(authenticated)
if (!authenticated) { if (!authenticated) {
ctx.commit('info', null) this.setUser(null)
ctx.dispatch('redirectToProviderIfNothingElseIsEnabled') this.redirectToProviderIfNothingElseIsEnabled()
} }
}, },
@ -211,7 +225,7 @@ const authStore : Module<AuthState, RootStoreState> = {
} }
}, },
async refreshUserInfo({state, commit, dispatch}) { async refreshUserInfo() {
const jwt = getToken() const jwt = getToken()
if (!jwt) { if (!jwt) {
return return
@ -220,19 +234,27 @@ const authStore : Module<AuthState, RootStoreState> = {
const HTTP = AuthenticatedHTTPFactory() const HTTP = AuthenticatedHTTPFactory()
try { try {
const response = await HTTP.get('user') const response = await HTTP.get('user')
const info = new UserModel(response.data) const info = new UserModel({
info.type = state.info.type ...response.data,
info.email = state.info.email ...(this.info?.type && {type: this.info?.type}),
info.exp = state.info.exp ...(this.info?.email && {email: this.info?.email}),
...(this.info?.exp && {exp: this.info?.exp}),
})
commit('info', info) this.setUser(info)
commit('lastUserRefresh') this.updateLastUserRefresh()
if (info.type === AUTH_TYPES.USER && (typeof info.settings.language === 'undefined' || info.settings.language === '')) { if (
info.type === AUTH_TYPES.USER &&
(
typeof info.settings.language === 'undefined' ||
info.settings.language === ''
)
) {
// save current language // save current language
await dispatch('saveUserSettings', { await this.saveUserSettings({
settings: { settings: {
...state.settings, ...this.settings,
language: getCurrentLanguage(), language: getCurrentLanguage(),
}, },
showMessage: false, showMessage: false,
@ -242,23 +264,28 @@ const authStore : Module<AuthState, RootStoreState> = {
return info return info
} catch (e) { } catch (e) {
if(e?.response?.data?.message === 'invalid or expired jwt') { if(e?.response?.data?.message === 'invalid or expired jwt') {
dispatch('logout') this.logout()
return return
} }
throw new Error('Error while refreshing user info:', {cause: e}) throw new Error('Error while refreshing user info:', {cause: e})
} }
}, },
async saveUserSettings(ctx, payload) { async saveUserSettings({
const {settings} = payload settings,
const showMessage = payload.showMessage ?? true showMessage = true,
}: {
settings: IUserSettings
showMessage : boolean
}) {
const userSettingsService = new UserSettingsService() const userSettingsService = new UserSettingsService()
const cancel = setLoading(ctx, 'general-settings') // FIXME
const cancel = setLoadingPinia(this, this.setIsLoadingGeneralSettings)
try { try {
saveLanguage(settings.language) saveLanguage(settings.language)
await userSettingsService.update(settings) await userSettingsService.update(settings)
ctx.commit('setUserSettings', {...settings}) this.setUserSettings({...settings})
if (showMessage) { if (showMessage) {
success({message: i18n.global.t('user.settings.general.savedSuccess')}) success({message: i18n.global.t('user.settings.general.savedSuccess')})
} }
@ -270,34 +297,38 @@ const authStore : Module<AuthState, RootStoreState> = {
}, },
// Renews the api token and saves it to local storage // Renews the api token and saves it to local storage
renewToken(ctx) { renewToken() {
// FIXME: Timeout to avoid race conditions when authenticated as a user (=auth token in localStorage) and as a // FIXME: Timeout to avoid race conditions when authenticated as a user (=auth token in localStorage) and as a
// link share in another tab. Without the timeout both the token renew and link share auth are executed at // link share in another tab. Without the timeout both the token renew and link share auth are executed at
// the same time and one might win over the other. // the same time and one might win over the other.
setTimeout(async () => { setTimeout(async () => {
if (!ctx.state.authenticated) { if (!this.authenticated) {
return return
} }
try { try {
await refreshToken(!ctx.state.isLinkShareAuth) await refreshToken(!this.isLinkShareAuth)
ctx.dispatch('checkAuth') this.checkAuth()
} catch (e) { } catch (e) {
// Don't logout on network errors as the user would then get logged out if they don't have // Don't logout on network errors as the user would then get logged out if they don't have
// internet for a short period of time - such as when the laptop is still reconnecting // internet for a short period of time - such as when the laptop is still reconnecting
if (e?.request?.status) { if (e?.request?.status) {
ctx.dispatch('logout') this.logout()
} }
} }
}, 5000) }, 5000)
}, },
logout(ctx) {
logout() {
removeToken() removeToken()
window.localStorage.clear() // Clear all settings and history we might have saved in local storage. window.localStorage.clear() // Clear all settings and history we might have saved in local storage.
router.push({name: 'user.login'}) router.push({name: 'user.login'})
ctx.dispatch('checkAuth') this.checkAuth()
}, },
}, },
} })
export default authStore // support hot reloading
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useAuthStore, import.meta.hot))
}

View file

@ -80,7 +80,7 @@ export const useLabelStore = defineStore('label', {
return return
} }
const cancel = setLoadingPinia(useLabelStore, this.setIsLoading) const cancel = setLoadingPinia(this)
try { try {
const labels = await getAllLabels() const labels = await getAllLabels()
@ -92,7 +92,7 @@ export const useLabelStore = defineStore('label', {
}, },
async deleteLabel(label: ILabel) { async deleteLabel(label: ILabel) {
const cancel = setLoadingPinia(useLabelStore) const cancel = setLoadingPinia(this)
const labelService = new LabelService() const labelService = new LabelService()
try { try {
@ -106,7 +106,7 @@ export const useLabelStore = defineStore('label', {
}, },
async updateLabel(label: ILabel) { async updateLabel(label: ILabel) {
const cancel = setLoadingPinia(useLabelStore) const cancel = setLoadingPinia(this)
const labelService = new LabelService() const labelService = new LabelService()
try { try {
@ -120,11 +120,11 @@ export const useLabelStore = defineStore('label', {
}, },
async createLabel(label: ILabel) { async createLabel(label: ILabel) {
const cancel = setLoadingPinia(useLabelStore) const cancel = setLoadingPinia(this)
const labelService = new LabelService() const labelService = new LabelService()
try { try {
const newLabel = await labelService.create(label) const newLabel = await labelService.create(label) as ILabel
this.setLabel(newLabel) this.setLabel(newLabel)
return newLabel return newLabel
} finally { } finally {

View file

@ -87,7 +87,7 @@ export const useListStore = defineStore('list', {
}, },
async createList(list: IList) { async createList(list: IList) {
const cancel = setLoadingPinia(useListStore) const cancel = setLoadingPinia(this)
const listService = new ListService() const listService = new ListService()
try { try {
@ -103,7 +103,7 @@ export const useListStore = defineStore('list', {
}, },
async updateList(list: IList) { async updateList(list: IList) {
const cancel = setLoadingPinia(useListStore) const cancel = setLoadingPinia(this)
const listService = new ListService() const listService = new ListService()
try { try {
@ -139,7 +139,7 @@ export const useListStore = defineStore('list', {
}, },
async deleteList(list: IList) { async deleteList(list: IList) {
const cancel = setLoadingPinia(useListStore) const cancel = setLoadingPinia(this)
const listService = new ListService() const listService = new ListService()
try { try {

View file

@ -1,4 +1,4 @@
import type { Module } from 'vuex' import {defineStore, acceptHMRUpdate} from 'pinia'
import router from '@/router' import router from '@/router'
import {formatISO} from 'date-fns' import {formatISO} from 'date-fns'
@ -7,8 +7,8 @@ import TaskAssigneeService from '@/services/taskAssignee'
import LabelTaskService from '@/services/labelTask' import LabelTaskService from '@/services/labelTask'
import UserService from '@/services/user' import UserService from '@/services/user'
import {HAS_TASKS} from '../mutation-types' import {HAS_TASKS} from '../store/mutation-types'
import {setLoading} from '../helper' import {setLoadingPinia} from '../store/helper'
import {getQuickAddMagicMode} from '@/helpers/quickAddMagicMode' import {getQuickAddMagicMode} from '@/helpers/quickAddMagicMode'
import {parseTaskText} from '@/modules/parseTaskText' import {parseTaskText} from '@/modules/parseTaskText'
@ -20,15 +20,16 @@ import LabelModel from '@/models/label'
import type {ILabel} from '@/modelTypes/ILabel' import type {ILabel} from '@/modelTypes/ILabel'
import type {ITask} from '@/modelTypes/ITask' import type {ITask} from '@/modelTypes/ITask'
import type { IUser } from '@/modelTypes/IUser' import type {IUser} from '@/modelTypes/IUser'
import type { IAttachment } from '@/modelTypes/IAttachment' import type {IAttachment} from '@/modelTypes/IAttachment'
import type { IList } from '@/modelTypes/IList' import type {IList} from '@/modelTypes/IList'
import type { RootStoreState, TaskState } from '@/store/types' import type {TaskState} from '@/store/types'
import {useLabelStore} from '@/stores/labels' import {useLabelStore} from '@/stores/labels'
import {useListStore} from '@/stores/lists' import {useListStore} from '@/stores/lists'
import {useAttachmentStore} from '@/stores/attachments' import {useAttachmentStore} from '@/stores/attachments'
import {playPop} from '@/helpers/playPop' import {playPop} from '@/helpers/playPop'
import {store} from '@/store'
// IDEA: maybe use a small fuzzy search here to prevent errors // IDEA: maybe use a small fuzzy search here to prevent errors
function findPropertyByValue(object, key, value) { function findPropertyByValue(object, key, value) {
@ -43,7 +44,7 @@ function validateUsername(users: IUser[], username: IUser['username']) {
} }
// Check if the label exists // Check if the label exists
function validateLabel(labels: ILabel[], label: ILabel) { function validateLabel(labels: ILabel[], label: string) {
return findPropertyByValue(labels, 'title', label) return findPropertyByValue(labels, 'title', label)
} }
@ -58,7 +59,7 @@ async function addLabelToTask(task: ITask, label: ILabel) {
return response return response
} }
async function findAssignees(parsedTaskAssignees) { async function findAssignees(parsedTaskAssignees: string[]) {
if (parsedTaskAssignees.length <= 0) { if (parsedTaskAssignees.length <= 0) {
return [] return []
} }
@ -74,30 +75,31 @@ async function findAssignees(parsedTaskAssignees) {
} }
const tasksStore : Module<TaskState, RootStoreState>= { export const useTaskStore = defineStore('task', {
namespaced: true, state: () : TaskState => ({
state: () => ({}), isLoading: false,
}),
actions: { actions: {
async loadTasks(ctx, params) { async loadTasks(params) {
const taskService = new TaskService() const taskService = new TaskService()
const cancel = setLoading(ctx, 'tasks') const cancel = setLoadingPinia(this)
try { try {
const tasks = await taskService.getAll({}, params) const tasks = await taskService.getAll({}, params)
ctx.commit(HAS_TASKS, tasks.length > 0, {root: true}) store.commit(HAS_TASKS, tasks.length > 0)
return tasks return tasks
} finally { } finally {
cancel() cancel()
} }
}, },
async update(ctx, task: ITask) { async update(task: ITask) {
const cancel = setLoading(ctx, 'tasks') const cancel = setLoadingPinia(this)
const taskService = new TaskService() const taskService = new TaskService()
try { try {
const updatedTask = await taskService.update(task) const updatedTask = await taskService.update(task)
ctx.commit('kanban/setTaskInBucket', updatedTask, {root: true}) store.commit('kanban/setTaskInBucket', updatedTask)
if (task.done) { if (task.done) {
playPop() playPop()
} }
@ -107,23 +109,23 @@ const tasksStore : Module<TaskState, RootStoreState>= {
} }
}, },
async delete(ctx, task: ITask) { async delete(task: ITask) {
const taskService = new TaskService() const taskService = new TaskService()
const response = await taskService.delete(task) const response = await taskService.delete(task)
ctx.commit('kanban/removeTaskInBucket', task, {root: true}) store.commit('kanban/removeTaskInBucket', task)
return response return response
}, },
// Adds a task attachment in store. // Adds a task attachment in store.
// This is an action to be able to commit other mutations // This is an action to be able to commit other mutations
addTaskAttachment(ctx, { addTaskAttachment({
taskId, taskId,
attachment, attachment,
}: { }: {
taskId: ITask['id'] taskId: ITask['id']
attachment: IAttachment attachment: IAttachment
}) { }) {
const t = ctx.rootGetters['kanban/getTaskById'](taskId) const t = store.getters['kanban/getTaskById'](taskId)
if (t.task !== null) { if (t.task !== null) {
const attachments = [ const attachments = [
...t.task.attachments, ...t.task.attachments,
@ -137,24 +139,25 @@ const tasksStore : Module<TaskState, RootStoreState>= {
attachments, attachments,
}, },
} }
ctx.commit('kanban/setTaskInBucketByIndex', newTask, {root: true}) store.commit('kanban/setTaskInBucketByIndex', newTask)
} }
const attachmentStore = useAttachmentStore() const attachmentStore = useAttachmentStore()
attachmentStore.add(attachment) attachmentStore.add(attachment)
}, },
async addAssignee(ctx, { async addAssignee({
user, user,
taskId, taskId,
}: { }: {
user: IUser, user: IUser,
taskId: ITask['id'] taskId: ITask['id']
}) { }) {
const taskAssignee = new TaskAssigneeModel({userId: user.id, taskId: taskId})
const taskAssigneeService = new TaskAssigneeService() const taskAssigneeService = new TaskAssigneeService()
const r = await taskAssigneeService.create(taskAssignee) const r = await taskAssigneeService.create(new TaskAssigneeModel({
const t = ctx.rootGetters['kanban/getTaskById'](taskId) userId: user.id,
taskId: taskId,
}))
const t = store.getters['kanban/getTaskById'](taskId)
if (t.task === null) { if (t.task === null) {
// Don't try further adding a label if the task is not in kanban // Don't try further adding a label if the task is not in kanban
// Usually this means the kanban board hasn't been accessed until now. // Usually this means the kanban board hasn't been accessed until now.
@ -163,33 +166,32 @@ const tasksStore : Module<TaskState, RootStoreState>= {
return r return r
} }
const assignees = [ store.commit('kanban/setTaskInBucketByIndex', {
...t.task.assignees,
user,
]
ctx.commit('kanban/setTaskInBucketByIndex', {
...t, ...t,
task: { task: {
...t.task, ...t.task,
assignees, assignees: [
...t.task.assignees,
user,
],
}, },
}, {root: true}) })
return r return r
}, },
async removeAssignee(ctx, { async removeAssignee({
user, user,
taskId, taskId,
}: { }: {
user: IUser, user: IUser,
taskId: ITask['id'] taskId: ITask['id']
}) { }) {
const taskAssignee = new TaskAssigneeModel({userId: user.id, taskId: taskId})
const taskAssigneeService = new TaskAssigneeService() const taskAssigneeService = new TaskAssigneeService()
const response = await taskAssigneeService.delete(taskAssignee) const response = await taskAssigneeService.delete(new TaskAssigneeModel({
const t = ctx.rootGetters['kanban/getTaskById'](taskId) userId: user.id,
taskId: taskId,
}))
const t = store.getters['kanban/getTaskById'](taskId)
if (t.task === null) { if (t.task === null) {
// Don't try further adding a label if the task is not in kanban // Don't try further adding a label if the task is not in kanban
// Usually this means the kanban board hasn't been accessed until now. // Usually this means the kanban board hasn't been accessed until now.
@ -200,29 +202,30 @@ const tasksStore : Module<TaskState, RootStoreState>= {
const assignees = t.task.assignees.filter(({ id }) => id !== user.id) const assignees = t.task.assignees.filter(({ id }) => id !== user.id)
ctx.commit('kanban/setTaskInBucketByIndex', { store.commit('kanban/setTaskInBucketByIndex', {
...t, ...t,
task: { task: {
...t.task, ...t.task,
assignees, assignees,
}, },
}, {root: true}) })
return response return response
}, },
async addLabel(ctx, { async addLabel({
label, label,
taskId, taskId,
} : { } : {
label: ILabel, label: ILabel,
taskId: ITask['id'] taskId: ITask['id']
}) { }) {
const labelTask = new LabelTaskModel({taskId, labelId: label.id})
const labelTaskService = new LabelTaskService() const labelTaskService = new LabelTaskService()
const r = await labelTaskService.create(labelTask) const r = await labelTaskService.create(new LabelTaskModel({
const t = ctx.rootGetters['kanban/getTaskById'](taskId) taskId,
labelId: label.id,
}))
const t = store.getters['kanban/getTaskById'](taskId)
if (t.task === null) { if (t.task === null) {
// Don't try further adding a label if the task is not in kanban // Don't try further adding a label if the task is not in kanban
// Usually this means the kanban board hasn't been accessed until now. // Usually this means the kanban board hasn't been accessed until now.
@ -231,28 +234,30 @@ const tasksStore : Module<TaskState, RootStoreState>= {
return r return r
} }
const labels = [ store.commit('kanban/setTaskInBucketByIndex', {
...t.task.labels,
label,
]
ctx.commit('kanban/setTaskInBucketByIndex', {
...t, ...t,
task: { task: {
...t.task, ...t.task,
labels, labels: [
...t.task.labels,
label,
],
}, },
}, {root: true}) })
return r return r
}, },
async removeLabel(ctx, {label, taskId}) { async removeLabel(
const labelTask = new LabelTaskModel({taskId, labelId: label.id}) {label, taskId}:
{label: ILabel, taskId: ITask['id']},
) {
const labelTaskService = new LabelTaskService() const labelTaskService = new LabelTaskService()
const response = await labelTaskService.delete(labelTask) const response = await labelTaskService.delete(new LabelTaskModel({
const t = ctx.rootGetters['kanban/getTaskById'](taskId) taskId, labelId:
label.id,
}))
const t = store.getters['kanban/getTaskById'](taskId)
if (t.task === null) { if (t.task === null) {
// Don't try further adding a label if the task is not in kanban // Don't try further adding a label if the task is not in kanban
// Usually this means the kanban board hasn't been accessed until now. // Usually this means the kanban board hasn't been accessed until now.
@ -264,19 +269,22 @@ const tasksStore : Module<TaskState, RootStoreState>= {
// Remove the label from the list // Remove the label from the list
const labels = t.task.labels.filter(({ id }) => id !== label.id) const labels = t.task.labels.filter(({ id }) => id !== label.id)
ctx.commit('kanban/setTaskInBucketByIndex', { store.commit('kanban/setTaskInBucketByIndex', {
...t, ...t,
task: { task: {
...t.task, ...t.task,
labels, labels,
}, },
}, {root: true}) })
return response return response
}, },
// Do everything that is involved in finding, creating and adding the label to the task // Do everything that is involved in finding, creating and adding the label to the task
async addLabelsToTask(_, { task, parsedLabels }) { async addLabelsToTask(
{ task, parsedLabels }:
{ task: ITask, parsedLabels: string[] },
) {
if (parsedLabels.length <= 0) { if (parsedLabels.length <= 0) {
return task return task
} }
@ -299,10 +307,9 @@ const tasksStore : Module<TaskState, RootStoreState>= {
return task return task
}, },
findListId(_, { list: listName, listId }: { findListId(
list: string, { list: listName, listId }:
listId: IList['id'] { list: string, listId: IList['id'] }) {
}) {
let foundListId = null let foundListId = null
// Uses the following ways to get the list id of the new task: // Uses the following ways to get the list id of the new task:
@ -320,7 +327,7 @@ const tasksStore : Module<TaskState, RootStoreState>= {
// 3. Otherwise use the id from the route parameter // 3. Otherwise use the id from the route parameter
if (typeof router.currentRoute.value.params.listId !== 'undefined') { if (typeof router.currentRoute.value.params.listId !== 'undefined') {
foundListId = parseInt(router.currentRoute.value.params.listId) foundListId = Number(router.currentRoute.value.params.listId)
} }
// 4. If none of the above worked, reject the promise with an error. // 4. If none of the above worked, reject the promise with an error.
@ -331,7 +338,7 @@ const tasksStore : Module<TaskState, RootStoreState>= {
return foundListId return foundListId
}, },
async createNewTask(ctx, { async createNewTask({
title, title,
bucketId, bucketId,
listId, listId,
@ -339,10 +346,10 @@ const tasksStore : Module<TaskState, RootStoreState>= {
} : } :
Partial<ITask>, Partial<ITask>,
) { ) {
const cancel = setLoading(ctx, 'tasks') const cancel = setLoadingPinia(this)
const parsedTask = parseTaskText(title, getQuickAddMagicMode()) const parsedTask = parseTaskText(title, getQuickAddMagicMode())
const foundListId = await ctx.dispatch('findListId', { const foundListId = await this.findListId({
list: parsedTask.list, list: parsedTask.list,
listId: listId || 0, listId: listId || 0,
}) })
@ -369,7 +376,7 @@ const tasksStore : Module<TaskState, RootStoreState>= {
const taskService = new TaskService() const taskService = new TaskService()
const createdTask = await taskService.create(task) const createdTask = await taskService.create(task)
const result = await ctx.dispatch('addLabelsToTask', { const result = await this.addLabelsToTask({
task: createdTask, task: createdTask,
parsedLabels: parsedTask.labels, parsedLabels: parsedTask.labels,
}) })
@ -377,6 +384,9 @@ const tasksStore : Module<TaskState, RootStoreState>= {
return result return result
}, },
}, },
} })
export default tasksStore // support hot reloading
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useTaskStore, import.meta.hot))
}

View file

@ -74,16 +74,18 @@ import {useDateTimeSalutation} from '@/composables/useDateTimeSalutation'
import {useListStore} from '@/stores/lists' import {useListStore} from '@/stores/lists'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'
import {useNamespaceStore} from '@/stores/namespaces' import {useNamespaceStore} from '@/stores/namespaces'
import {useAuthStore} from '@/stores/auth'
const welcome = useDateTimeSalutation() const welcome = useDateTimeSalutation()
const store = useStore() const store = useStore()
const authStore = useAuthStore()
const configStore = useConfigStore() const configStore = useConfigStore()
const namespaceStore = useNamespaceStore() const namespaceStore = useNamespaceStore()
const listStore = useListStore() const listStore = useListStore()
const listHistory = computed(() => { const listHistory = computed(() => {
// If we don't check this, it tries to load the list background right after logging out // If we don't check this, it tries to load the list background right after logging out
if(!store.state.auth.authenticated) { if(!authStore.authenticated) {
return [] return []
} }
@ -93,13 +95,13 @@ const listHistory = computed(() => {
}) })
const migratorsEnabled = computed(() => configStore.availableMigrators?.length > 0) const migratorsEnabled = computed(() => configStore.availableMigrators?.length > 0)
const userInfo = computed(() => store.state.auth.info) const userInfo = computed(() => authStore.info)
const hasTasks = computed(() => store.state.hasTasks) const hasTasks = computed(() => store.state.hasTasks)
const defaultListId = computed(() => store.state.auth.settings.defaultListId) const defaultListId = computed(() => authStore.settings.defaultListId)
const defaultNamespaceId = computed(() => namespaceStore.namespaces?.[0]?.id || 0) const defaultNamespaceId = computed(() => namespaceStore.namespaces?.[0]?.id || 0)
const hasLists = computed(() => namespaceStore.namespaces?.[0]?.lists.length > 0) const hasLists = computed(() => namespaceStore.namespaces?.[0]?.lists.length > 0)
const loading = computed(() => store.state.loading && store.state.loadingModule === 'tasks') const loading = computed(() => store.state.loading && store.state.loadingModule === 'tasks')
const deletionScheduledAt = computed(() => parseDateOrNull(store.state.auth.info?.deletionScheduledAt)) const deletionScheduledAt = computed(() => parseDateOrNull(authStore.info?.deletionScheduledAt))
// This is to reload the tasks list after adding a new task through the global task add. // This is to reload the tasks list after adding a new task through the global task add.
// FIXME: Should use vuex (somehow?) // FIXME: Should use vuex (somehow?)

View file

@ -119,10 +119,10 @@ import ColorPicker from '@/components/input/colorPicker.vue'
import LabelModel from '@/models/label' import LabelModel from '@/models/label'
import type {ILabel} from '@/modelTypes/ILabel' import type {ILabel} from '@/modelTypes/ILabel'
import {useAuthStore} from '@/stores/auth'
import {useLabelStore} from '@/stores/labels' import {useLabelStore} from '@/stores/labels'
import { useTitle } from '@/composables/useTitle' import { useTitle } from '@/composables/useTitle'
import { useStore } from '@/store'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
@ -134,25 +134,23 @@ const labelToDelete = ref<ILabel>(null)
useTitle(() => t('label.title')) useTitle(() => t('label.title'))
const store = useStore() const authStore = useAuthStore()
const userInfo = computed(() => store.state.auth.info) const userInfo = computed(() => authStore.info)
const labelStore = useLabelStore() const labelStore = useLabelStore()
labelStore.loadAllLabels() labelStore.loadAllLabels()
// Alphabetically sort the labels // Alphabetically sort the labels
const labels = computed(() => Object.values(labelStore.labels).sort((f, s) => f.title > s.title ? 1 : -1)) const labels = computed(() => Object.values(labelStore.labels).sort((f, s) => f.title > s.title ? 1 : -1))
const loading = computed(() =>labelStore.isLoading) const loading = computed(() => labelStore.isLoading)
function deleteLabel(label: ILabel) { function deleteLabel(label: ILabel) {
showDeleteModal.value = false showDeleteModal.value = false
isLabelEdit.value = false isLabelEdit.value = false
const labelStore = useLabelStore()
return labelStore.deleteLabel(label) return labelStore.deleteLabel(label)
} }
function editLabelSubmit() { function editLabelSubmit() {
const labelStore = useLabelStore()
return labelStore.updateLabel(labelEditLabel.value) return labelStore.updateLabel(labelEditLabel.value)
} }

View file

@ -42,9 +42,9 @@
<script setup lang="ts"> <script setup lang="ts">
import {ref, computed} from 'vue' import {ref, computed} from 'vue'
import flatPickr from 'vue-flatpickr-component' import flatPickr from 'vue-flatpickr-component'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useStore} from '@/store'
import {useAuthStore} from '@/stores/auth'
import ListWrapper from './ListWrapper.vue' import ListWrapper from './ListWrapper.vue'
import GanttChart from '@/components/tasks/gantt-chart.vue' import GanttChart from '@/components/tasks/gantt-chart.vue'
@ -70,7 +70,7 @@ const dateFrom = computed(() => range.value?.split(' to ')[0] ?? defaultFrom)
const dateTo = computed(() => range.value?.split(' to ')[1] ?? defaultTo) const dateTo = computed(() => range.value?.split(' to ')[1] ?? defaultTo)
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const store = useStore() const authStore = useAuthStore()
const flatPickerConfig = computed(() => ({ const flatPickerConfig = computed(() => ({
altFormat: t('date.altFormatShort'), altFormat: t('date.altFormatShort'),
altInput: true, altInput: true,
@ -78,7 +78,7 @@ const flatPickerConfig = computed(() => ({
enableTime: false, enableTime: false,
mode: 'range', mode: 'range',
locale: { locale: {
firstDayOfWeek: store.state.auth.settings.weekStart, firstDayOfWeek: authStore.settings.weekStart,
}, },
})) }))
</script> </script>

View file

@ -1,7 +1,7 @@
<template> <template>
<ListWrapper class="list-kanban" :list-id="listId" viewName="kanban"> <ListWrapper class="list-kanban" :list-id="listId" viewName="kanban">
<template #header> <template #header>
<div class="filter-container" v-if="isSavedFilter"> <div class="filter-container" v-if="isSavedFilter(list)">
<div class="items"> <div class="items">
<filter-popup <filter-popup
v-model="params" v-model="params"
@ -239,6 +239,8 @@ import {getCollapsedBucketState, saveCollapsedBucketState} from '@/helpers/saveC
import {calculateItemPosition} from '../../helpers/calculateItemPosition' import {calculateItemPosition} from '../../helpers/calculateItemPosition'
import KanbanCard from '@/components/tasks/partials/kanban-card.vue' import KanbanCard from '@/components/tasks/partials/kanban-card.vue'
import DropdownItem from '@/components/misc/dropdown-item.vue' import DropdownItem from '@/components/misc/dropdown-item.vue'
import {isSavedFilter} from '@/helpers/savedFilter'
import {useTaskStore} from '@/stores/tasks'
const DRAG_OPTIONS = { const DRAG_OPTIONS = {
// sortable options // sortable options
@ -324,9 +326,6 @@ export default defineComponent({
}) })
}, },
isSavedFilter() {
return this.list.isSavedFilter && !this.list.isSavedFilter()
},
loadBucketParameter() { loadBucketParameter() {
return { return {
listId: this.listId, listId: this.listId,
@ -356,6 +355,8 @@ export default defineComponent({
}, },
methods: { methods: {
isSavedFilter,
loadBuckets() { loadBuckets() {
const {listId, params} = this.loadBucketParameter const {listId, params} = this.loadBucketParameter
@ -433,7 +434,8 @@ export default defineComponent({
) )
try { try {
await this.$store.dispatch('tasks/update', newTask) const taskStore = useTaskStore()
await taskStore.update(newTask)
// Make sure the first and second task don't both get position 0 assigned // Make sure the first and second task don't both get position 0 assigned
if(newTaskIndex === 0 && taskAfter !== null && taskAfter.kanbanPosition === 0) { if(newTaskIndex === 0 && taskAfter !== null && taskAfter.kanbanPosition === 0) {
@ -445,7 +447,7 @@ export default defineComponent({
taskAfterAfter !== null ? taskAfterAfter.kanbanPosition : null, taskAfterAfter !== null ? taskAfterAfter.kanbanPosition : null,
) )
await this.$store.dispatch('tasks/update', newTaskAfter) await taskStore.update(newTaskAfter)
} }
} finally { } finally {
this.taskUpdating[task.id] = false this.taskUpdating[task.id] = false
@ -464,7 +466,7 @@ export default defineComponent({
} }
this.newTaskError[bucketId] = false this.newTaskError[bucketId] = false
const task = await this.$store.dispatch('tasks/createNewTask', { const task = await useTaskStore().createNewTask({
title: this.newTaskText, title: this.newTaskText,
bucketId, bucketId,
listId: this.listId, listId: this.listId,

View file

@ -3,7 +3,7 @@
<template #header> <template #header>
<div <div
class="filter-container" class="filter-container"
v-if="list.isSavedFilter && !list.isSavedFilter()" v-if="!isSavedFilter(list)"
> >
<div class="items"> <div class="items">
<div class="search"> <div class="search">
@ -58,7 +58,7 @@
> >
<add-task <add-task
@taskAdded="updateTaskList" @taskAdded="updateTaskList"
ref="addTask" ref="addTaskRef"
:default-position="firstNewPosition" :default-position="firstNewPosition"
/> />
</template> </template>
@ -76,7 +76,7 @@
v-if="tasks && tasks.length > 0" v-if="tasks && tasks.length > 0"
> >
<draggable <draggable
v-bind="dragOptions" v-bind="DRAG_OPTIONS"
v-model="tasks" v-model="tasks"
group="tasks" group="tasks"
@start="() => drag = true" @start="() => drag = true"
@ -94,7 +94,7 @@
<single-task-in-list <single-task-in-list
:show-list-color="false" :show-list-color="false"
:disabled="!canWrite" :disabled="!canWrite"
:can-mark-as-done="canWrite || (list.isSavedFilter && list.isSavedFilter())" :can-mark-as-done="canWrite || isSavedFilter(list)"
:the-task="t" :the-task="t"
@taskUpdated="updateTasks" @taskUpdated="updateTasks"
> >
@ -114,7 +114,7 @@
</template> </template>
</draggable> </draggable>
</div> </div>
<edit-task <EditTask
v-if="isTaskEdit" v-if="isTaskEdit"
class="taskedit mt-0" class="taskedit mt-0"
:title="$t('list.list.editTask')" :title="$t('list.list.editTask')"
@ -135,25 +135,35 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { ref, toRef, defineComponent } from 'vue' export default { name: 'List' }
</script>
<script setup lang="ts">
import {ref, computed, toRef, nextTick, onMounted, type PropType} from 'vue'
import draggable from 'zhyswan-vuedraggable'
import {useRoute, useRouter} from 'vue-router'
import ListWrapper from './ListWrapper.vue'
import BaseButton from '@/components/base/BaseButton.vue' import BaseButton from '@/components/base/BaseButton.vue'
import ButtonLink from '@/components/misc/ButtonLink.vue' import ButtonLink from '@/components/misc/ButtonLink.vue'
import ListWrapper from './ListWrapper.vue'
import EditTask from '@/components/tasks/edit-task.vue' import EditTask from '@/components/tasks/edit-task.vue'
import AddTask from '@/components/tasks/add-task.vue' import AddTask from '@/components/tasks/add-task.vue'
import SingleTaskInList from '@/components/tasks/partials/singleTaskInList.vue' import SingleTaskInList from '@/components/tasks/partials/singleTaskInList.vue'
import { useTaskList } from '@/composables/taskList'
import {RIGHTS as Rights} from '@/constants/rights'
import FilterPopup from '@/components/list/partials/filter-popup.vue' import FilterPopup from '@/components/list/partials/filter-popup.vue'
import {HAS_TASKS} from '@/store/mutation-types'
import Nothing from '@/components/misc/nothing.vue' import Nothing from '@/components/misc/nothing.vue'
import Pagination from '@/components/misc/pagination.vue' import Pagination from '@/components/misc/pagination.vue'
import {ALPHABETICAL_SORT} from '@/components/list/partials/filters.vue' import {ALPHABETICAL_SORT} from '@/components/list/partials/filters.vue'
import draggable from 'zhyswan-vuedraggable' import {useStore} from '@/store'
import {calculateItemPosition} from '../../helpers/calculateItemPosition' import {HAS_TASKS} from '@/store/mutation-types'
import {useTaskList} from '@/composables/taskList'
import {RIGHTS as Rights} from '@/constants/rights'
import {calculateItemPosition} from '@/helpers/calculateItemPosition'
import type {ITask} from '@/modelTypes/ITask' import type {ITask} from '@/modelTypes/ITask'
import {isSavedFilter} from '@/helpers/savedFilter'
import {useTaskStore} from '@/stores/tasks'
import type {IList} from '@/modelTypes/IList'
function sortTasks(tasks: ITask[]) { function sortTasks(tasks: ITask[]) {
if (tasks === null || Array.isArray(tasks) && tasks.length === 0) { if (tasks === null || Array.isArray(tasks) && tasks.length === 0) {
@ -173,153 +183,140 @@ function sortTasks(tasks: ITask[]) {
}) })
} }
export default defineComponent({ const props = defineProps({
name: 'List',
props: {
listId: { listId: {
type: Number, type: Number as PropType<IList['id']>,
required: true, required: true,
}, },
}, })
data() { const ctaVisible = ref(false)
return { const showTaskSearch = ref(false)
ctaVisible: false,
showTaskSearch: false,
drag: false, const drag = ref(false)
dragOptions: { const DRAG_OPTIONS = {
animation: 100, animation: 100,
ghostClass: 'ghost', ghostClass: 'ghost',
}, } as const
}
},
components: {
BaseButton,
ListWrapper,
Nothing,
FilterPopup,
SingleTaskInList,
EditTask,
AddTask,
draggable,
Pagination,
ButtonLink,
},
setup(props) {
const taskEditTask = ref(null)
const isTaskEdit = ref(false)
// This function initializes the tasks page and loads the first page of tasks const taskEditTask = ref<ITask | null>(null)
// function beforeLoad() { const isTaskEdit = ref(false)
// taskEditTask.value = null
// isTaskEdit.value = false
// }
const taskList = useTaskList(toRef(props, 'listId'), { const {
position: 'asc', tasks,
}) loading,
totalPages,
currentPage,
loadTasks,
searchTerm,
params,
// sortByParam,
} = useTaskList(toRef(props, 'listId'), {position: 'asc' })
return {
taskEditTask, const isAlphabeticalSorting = computed(() => {
isTaskEdit, return params.value.sort_by.find(sortBy => sortBy === ALPHABETICAL_SORT) !== undefined
...taskList, })
}
}, const firstNewPosition = computed(() => {
computed: { if (tasks.value.length === 0) {
isAlphabeticalSorting() {
return this.params.sort_by.find( sortBy => sortBy === ALPHABETICAL_SORT ) !== undefined
},
firstNewPosition() {
if (this.tasks.length === 0) {
return 0 return 0
} }
return calculateItemPosition(null, this.tasks[0].position) return calculateItemPosition(null, tasks.value[0].position)
}, })
canWrite() {
return this.list.maxRight > Rights.READ && this.list.id > 0 const taskStore = useTaskStore()
}, const store = useStore()
list() { const list = computed(() => store.state.currentList)
return this.$store.state.currentList
}, const canWrite = computed(() => {
}, return list.value.maxRight > Rights.READ && list.value.id > 0
mounted() { })
this.$nextTick(() => (this.ctaVisible = true))
}, onMounted(async () => {
methods: { await nextTick()
searchTasks() { ctaVisible.value = true
})
const route = useRoute()
const router = useRouter()
function searchTasks() {
// Only search if the search term changed // Only search if the search term changed
if (this.$route.query === this.searchTerm) { if (route.query as unknown as string === searchTerm.value) {
return return
} }
this.$router.push({ router.push({
name: 'list.list', name: 'list.list',
query: {search: this.searchTerm}, query: {search: searchTerm.value},
}) })
}, }
hideSearchBar() {
function hideSearchBar() {
// This is a workaround. // This is a workaround.
// When clicking on the search button, @blur from the input is fired. If we // When clicking on the search button, @blur from the input is fired. If we
// would then directly hide the whole search bar directly, no click event // would then directly hide the whole search bar directly, no click event
// from the button gets fired. To prevent this, we wait 200ms until we hide // from the button gets fired. To prevent this, we wait 200ms until we hide
// everything so the button has a chance of firing the search event. // everything so the button has a chance of firing the search event.
setTimeout(() => { setTimeout(() => {
this.showTaskSearch = false showTaskSearch.value = false
}, 200) }, 200)
}, }
focusNewTaskInput() {
this.$refs.addTask.focusTaskInput() const addTaskRef = ref<typeof AddTask | null>(null)
}, function focusNewTaskInput() {
updateTaskList(task: ITask) { addTaskRef.value?.focusTaskInput()
if ( this.isAlphabeticalSorting ) { }
function updateTaskList(task: ITask) {
if (isAlphabeticalSorting.value ) {
// reload tasks with current filter and sorting // reload tasks with current filter and sorting
this.loadTasks(1, undefined, undefined, true) loadTasks(1, undefined, undefined, true)
} }
else { else {
this.tasks = [ tasks.value = [
task, task,
...this.tasks, ...tasks.value,
] ]
} }
this.$store.commit(HAS_TASKS, true) store.commit(HAS_TASKS, true)
}, }
editTask(id: ITask['id']) {
this.taskEditTask = {...this.tasks.find(t => t.id === parseInt(id))} function editTask(id: ITask['id']) {
this.isTaskEdit = true taskEditTask.value = {...tasks.value.find(t => t.id === Number(id))}
}, isTaskEdit.value = true
updateTasks(updatedTask: ITask) { }
for (const t in this.tasks) {
if (this.tasks[t].id === updatedTask.id) { function updateTasks(updatedTask: ITask) {
this.tasks[t] = updatedTask for (const t in tasks.value) {
if (tasks.value[t].id === updatedTask.id) {
tasks.value[t] = updatedTask
break break
} }
} }
// FIXME: Use computed // FIXME: Use computed
sortTasks(this.tasks) sortTasks(tasks.value)
}, }
async saveTaskPosition(e) { async function saveTaskPosition(e) {
this.drag = false drag.value = false
const task = this.tasks[e.newIndex] const task = tasks.value[e.newIndex]
const taskBefore = this.tasks[e.newIndex - 1] ?? null const taskBefore = tasks.value[e.newIndex - 1] ?? null
const taskAfter = this.tasks[e.newIndex + 1] ?? null const taskAfter = tasks.value[e.newIndex + 1] ?? null
const newTask = { const newTask = {
...task, ...task,
position: calculateItemPosition(taskBefore !== null ? taskBefore.position : null, taskAfter !== null ? taskAfter.position : null), position: calculateItemPosition(taskBefore !== null ? taskBefore.position : null, taskAfter !== null ? taskAfter.position : null),
} }
const updatedTask = await this.$store.dispatch('tasks/update', newTask) const updatedTask = await taskStore.update(newTask)
this.tasks[e.newIndex] = updatedTask tasks.value[e.newIndex] = updatedTask
}, }
},
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View file

@ -41,6 +41,7 @@ import CreateEdit from '@/components/misc/create-edit.vue'
import LinkSharing from '@/components/sharing/linkSharing.vue' import LinkSharing from '@/components/sharing/linkSharing.vue'
import userTeam from '@/components/sharing/userTeam.vue' import userTeam from '@/components/sharing/userTeam.vue'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'
import {useAuthStore} from '@/stores/auth'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
@ -52,10 +53,11 @@ const title = computed(() => list.value?.title
useTitle(title) useTitle(title)
const store = useStore() const store = useStore()
const authStore = useAuthStore()
const configStore = useConfigStore() const configStore = useConfigStore()
const linkSharingEnabled = computed(() => configStore.linkSharingEnabled) const linkSharingEnabled = computed(() => configStore.linkSharingEnabled)
const userIsAdmin = computed(() => 'owner' in list.value && list.value.owner.id === store.state.auth.info.id) const userIsAdmin = computed(() => 'owner' in list.value && list.value.owner.id === authStore.info.id)
async function loadList(listId: number) { async function loadList(listId: number) {
const listService = new ListService() const listService = new ListService()

View file

@ -26,20 +26,21 @@ export default { name: 'namespace-setting-share' }
<script lang="ts" setup> <script lang="ts" setup>
import {ref, computed, watchEffect} from 'vue' import {ref, computed, watchEffect} from 'vue'
import {useStore} from '@/store'
import {useRoute} from 'vue-router' import {useRoute} from 'vue-router'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useTitle} from '@vueuse/core'
import NamespaceService from '@/services/namespace' import NamespaceService from '@/services/namespace'
import NamespaceModel from '@/models/namespace' import NamespaceModel from '@/models/namespace'
import CreateEdit from '@/components/misc/create-edit.vue' import CreateEdit from '@/components/misc/create-edit.vue'
import manageSharing from '@/components/sharing/userTeam.vue' import manageSharing from '@/components/sharing/userTeam.vue'
import {useTitle} from '@/composables/useTitle'
import {useAuthStore} from '@/stores/auth'
import type {INamespace} from '@/modelTypes/INamespace'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const namespace = ref() const namespace = ref<INamespace>()
const title = computed(() => namespace.value?.title const title = computed(() => namespace.value?.title
? t('namespace.share.title', { namespace: namespace.value.title }) ? t('namespace.share.title', { namespace: namespace.value.title })
@ -47,8 +48,8 @@ const title = computed(() => namespace.value?.title
) )
useTitle(title) useTitle(title)
const store = useStore() const authStore = useAuthStore()
const userIsAdmin = computed(() => 'owner' in namespace.value && namespace.value.owner.id === store.state.auth.info.id) const userIsAdmin = computed(() => 'owner' in namespace.value && namespace.value.owner.id === authStore.info.id)
async function loadNamespace(namespaceId: number) { async function loadNamespace(namespaceId: number) {
if (!namespaceId) return if (!namespaceId) return

View file

@ -42,12 +42,14 @@ import {useTitle} from '@vueuse/core'
import Message from '@/components/misc/message.vue' import Message from '@/components/misc/message.vue'
import {LOGO_VISIBLE} from '@/store/mutation-types' import {LOGO_VISIBLE} from '@/store/mutation-types'
import {LIST_VIEWS, type ListView} from '@/types/ListView' import {LIST_VIEWS, type ListView} from '@/types/ListView'
import {useAuthStore} from '@/stores/auth'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
useTitle(t('sharing.authenticating')) useTitle(t('sharing.authenticating'))
function useAuth() { function useAuth() {
const store = useStore() const store = useStore()
const authStore = useAuthStore()
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
@ -56,7 +58,7 @@ function useAuth() {
const errorMessage = ref('') const errorMessage = ref('')
const password = ref('') const password = ref('')
const authLinkShare = computed(() => store.getters['auth/authLinkShare']) const authLinkShare = computed(() => authStore.authLinkShare)
async function authenticate() { async function authenticate() {
authenticateWithPassword.value = false authenticateWithPassword.value = false
@ -72,7 +74,7 @@ function useAuth() {
loading.value = true loading.value = true
try { try {
const {list_id: listId} = await store.dispatch('auth/linkShareAuth', { const {list_id: listId} = await authStore.linkShareAuth({
hash: route.params.share, hash: route.params.share,
password: password.value, password: password.value,
}) })

View file

@ -59,8 +59,12 @@ import {DATE_RANGES} from '@/components/date/dateRanges'
import {LOADING, LOADING_MODULE} from '@/store/mutation-types' import {LOADING, LOADING_MODULE} from '@/store/mutation-types'
import LlamaCool from '@/assets/llama-cool.svg?component' import LlamaCool from '@/assets/llama-cool.svg?component'
import type {ITask} from '@/modelTypes/ITask' import type {ITask} from '@/modelTypes/ITask'
import {useAuthStore} from '@/stores/auth'
import {useTaskStore} from '@/stores/tasks'
const store = useStore() const store = useStore()
const authStore = useAuthStore()
const taskStore = useTaskStore()
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
@ -104,7 +108,7 @@ const pageTitle = computed(() => {
}) })
}) })
const hasTasks = computed(() => tasks.value && tasks.value.length > 0) const hasTasks = computed(() => tasks.value && tasks.value.length > 0)
const userAuthenticated = computed(() => store.state.auth.authenticated) const userAuthenticated = computed(() => authStore.authenticated)
const loading = computed(() => store.state[LOADING] && store.state[LOADING_MODULE] === 'tasks') const loading = computed(() => store.state[LOADING] && store.state[LOADING_MODULE] === 'tasks')
interface dateStrings { interface dateStrings {
@ -178,7 +182,7 @@ async function loadPendingTasks(from: string, to: string) {
} }
} }
tasks.value = await store.dispatch('tasks/loadTasks', params) tasks.value = await taskStore.loadTasks(params)
} }
// FIXME: this modification should happen in the store // FIXME: this modification should happen in the store

View file

@ -464,6 +464,7 @@ import type {IList} from '@/modelTypes/IList'
import {colorIsDark} from '@/helpers/color/colorIsDark' import {colorIsDark} from '@/helpers/color/colorIsDark'
import {useNamespaceStore} from '@/stores/namespaces' import {useNamespaceStore} from '@/stores/namespaces'
import {useAttachmentStore} from '@/stores/attachments' import {useAttachmentStore} from '@/stores/attachments'
import {useTaskStore} from '@/stores/tasks'
function scrollIntoView(el) { function scrollIntoView(el) {
if (!el) { if (!el) {
@ -696,7 +697,8 @@ export default defineComponent({
task.endDate = task.dueDate task.endDate = task.dueDate
} }
this.task = await this.$store.dispatch('tasks/update', task)
this.task = await useTaskStore().update(task)
if (!showNotification) { if (!showNotification) {
return return
@ -728,7 +730,7 @@ export default defineComponent({
}, },
async deleteTask() { async deleteTask() {
await this.$store.dispatch('tasks/delete', this.task) await useTaskStore().delete(this.task)
this.$message.success({message: this.$t('task.detail.deleteSuccess')}) this.$message.success({message: this.$t('task.detail.deleteSuccess')})
this.$router.push({name: 'list.index', params: {listId: this.task.listId}}) this.$router.push({name: 'list.index', params: {listId: this.task.listId}})
}, },

View file

@ -85,7 +85,7 @@
<table class="table has-actions is-striped is-hoverable is-fullwidth"> <table class="table has-actions is-striped is-hoverable is-fullwidth">
<tbody> <tbody>
<tr :key="m.id" v-for="m in team?.members"> <tr :key="m.id" v-for="m in team?.members">
<td>{{ m.getDisplayName() }}</td> <td>{{ getDisplayName(m) }}</td>
<td> <td>
<template v-if="m.id === userInfo.id"> <template v-if="m.id === userInfo.id">
<b class="is-success">You</b> <b class="is-success">You</b>
@ -163,9 +163,10 @@
<script lang="ts" setup> <script lang="ts" setup>
import {computed, ref} from 'vue' import {computed, ref} from 'vue'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useRoute, useRouter} from 'vue-router'
import Editor from '@/components/input/AsyncEditor' import Editor from '@/components/input/AsyncEditor'
import {useStore} from '@/store' import Multiselect from '@/components/input/multiselect.vue'
import TeamService from '@/services/team' import TeamService from '@/services/team'
import TeamMemberService from '@/services/teamMember' import TeamMemberService from '@/services/teamMember'
@ -173,15 +174,16 @@ import UserService from '@/services/user'
import {RIGHTS as Rights} from '@/constants/rights' import {RIGHTS as Rights} from '@/constants/rights'
import Multiselect from '@/components/input/multiselect.vue'
import {useRoute, useRouter} from 'vue-router'
import {useTitle} from '@/composables/useTitle' import {useTitle} from '@/composables/useTitle'
import {success} from '@/message' import {success} from '@/message'
import {getDisplayName} from '@/models/user'
import {useAuthStore} from '@/stores/auth'
import type {ITeam} from '@/modelTypes/ITeam' import type {ITeam} from '@/modelTypes/ITeam'
import type {IUser} from '@/modelTypes/IUser' import type {IUser} from '@/modelTypes/IUser'
import type {ITeamMember} from '@/modelTypes/ITeamMember' import type {ITeamMember} from '@/modelTypes/ITeamMember'
const store = useStore() const authStore = useAuthStore()
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
@ -193,7 +195,7 @@ const userIsAdmin = computed(() => {
team.value.maxRight > Rights.READ team.value.maxRight > Rights.READ
) )
}) })
const userInfo = computed(() => store.state.auth.info) const userInfo = computed(() => authStore.info)
const teamService = ref<TeamService>(new TeamService()) const teamService = ref<TeamService>(new TeamService())
const teamMemberService = ref<TeamMemberService>(new TeamMemberService()) const teamMemberService = ref<TeamMemberService>(new TeamMemberService())

View file

@ -38,14 +38,15 @@
<script setup lang="ts"> <script setup lang="ts">
import {ref, computed, reactive} from 'vue' import {ref, computed, reactive} from 'vue'
import DataExportService from '@/services/dataExport' import DataExportService from '@/services/dataExport'
import {store} from '@/store' import {useAuthStore} from '@/stores/auth'
const dataExportService = reactive(new DataExportService()) const dataExportService = reactive(new DataExportService())
const password = ref('') const password = ref('')
const errPasswordRequired = ref(false) const errPasswordRequired = ref(false)
const passwordInput = ref(null) const passwordInput = ref(null)
const isLocalUser = computed(() => store.state.auth.info?.isLocalUser) const authStore = useAuthStore()
const isLocalUser = computed(() => authStore.info?.isLocalUser)
function download() { function download() {
if (password.value === '' && isLocalUser.value) { if (password.value === '' && isLocalUser.value) {

View file

@ -116,6 +116,7 @@ import {getLastVisited, clearLastVisited} from '../../helpers/saveLastVisited'
import Password from '@/components/input/password.vue' import Password from '@/components/input/password.vue'
import { setTitle } from '@/helpers/setTitle' import { setTitle } from '@/helpers/setTitle'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'
import {useAuthStore} from '@/stores/auth'
export default defineComponent({ export default defineComponent({
components: { components: {
@ -173,8 +174,11 @@ export default defineComponent({
}, },
...mapStateVuex({ ...mapStateVuex({
loading: LOADING, loading: LOADING,
needsTotpPasscode: state => state.auth.needsTotpPasscode, }),
authenticated: state => state.auth.authenticated,
...mapState(useAuthStore, {
needsTotpPasscode: state => state.needsTotpPasscode,
authenticated: state => state.authenticated,
}), }),
...mapState(useConfigStore, { ...mapState(useConfigStore, {
@ -224,8 +228,9 @@ export default defineComponent({
} }
try { try {
await this.$store.dispatch('auth/login', credentials) const authStore = useAuthStore()
this.$store.commit('auth/needsTotpPasscode', false) await authStore.login(credentials)
authStore.setNeedsTotpPasscode(false)
} catch (e) { } catch (e) {
if (e.response?.data.code === 1017 && !this.credentials.totpPasscode) { if (e.response?.data.code === 1017 && !this.credentials.totpPasscode) {
return return

View file

@ -22,6 +22,7 @@ import {useI18n} from 'vue-i18n'
import {getErrorText} from '@/message' import {getErrorText} from '@/message'
import Message from '@/components/misc/message.vue' import Message from '@/components/misc/message.vue'
import {clearLastVisited, getLastVisited} from '@/helpers/saveLastVisited' import {clearLastVisited, getLastVisited} from '@/helpers/saveLastVisited'
import {useAuthStore} from '@/stores/auth'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
@ -29,6 +30,7 @@ const router = useRouter()
const route = useRoute() const route = useRoute()
const store = useStore() const store = useStore()
const authStore = useAuthStore()
const loading = computed(() => store.state.loading) const loading = computed(() => store.state.loading)
const errorMessage = ref('') const errorMessage = ref('')
@ -65,7 +67,7 @@ async function authenticateWithCode() {
} }
try { try {
await store.dispatch('auth/openIdAuth', { await authStore.openIdAuth({
provider: route.params.provider, provider: route.params.provider,
code: route.query.code, code: route.query.code,
}) })

View file

@ -77,11 +77,14 @@ import {store} from '@/store'
import Message from '@/components/misc/message.vue' import Message from '@/components/misc/message.vue'
import {isEmail} from '@/helpers/isEmail' import {isEmail} from '@/helpers/isEmail'
import Password from '@/components/input/password.vue' import Password from '@/components/input/password.vue'
import {useAuthStore} from '@/stores/auth'
const authStore = useAuthStore()
// FIXME: use the `beforeEnter` hook of vue-router // FIXME: use the `beforeEnter` hook of vue-router
// Check if the user is already logged in, if so, redirect them to the homepage // Check if the user is already logged in, if so, redirect them to the homepage
onBeforeMount(() => { onBeforeMount(() => {
if (store.state.auth.authenticated) { if (authStore.authenticated) {
router.push({name: 'home'}) router.push({name: 'home'})
} }
}) })
@ -126,7 +129,7 @@ async function submit() {
} }
try { try {
await store.dispatch('auth/register', toRaw(credentials)) await authStore.register(toRaw(credentials))
} catch (e) { } catch (e) {
errorMessage.value = e.message errorMessage.value = e.message
} }

View file

@ -19,19 +19,21 @@
<script setup lang="ts"> <script setup lang="ts">
import {computed} from 'vue' import {computed} from 'vue'
import { store } from '@/store'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useTitle } from '@/composables/useTitle' import { useTitle } from '@/composables/useTitle'
import { useConfigStore } from '@/stores/config' import { useConfigStore } from '@/stores/config'
import { useAuthStore } from '@/stores/auth'
const { t } = useI18n({useScope: 'global'}) const { t } = useI18n({useScope: 'global'})
useTitle(() => t('user.settings.title')) useTitle(() => t('user.settings.title'))
const configStore = useConfigStore() const configStore = useConfigStore()
const authStore = useAuthStore()
const totpEnabled = computed(() => configStore.totpEnabled) const totpEnabled = computed(() => configStore.totpEnabled)
const caldavEnabled = computed(() => configStore.caldavEnabled) const caldavEnabled = computed(() => configStore.caldavEnabled)
const migratorsEnabled = computed(() => configStore.migratorsEnabled) const migratorsEnabled = computed(() => configStore.migratorsEnabled)
const isLocalUser = computed(() => store.state.auth.info?.isLocalUser) const isLocalUser = computed(() => authStore.info?.isLocalUser)
const navigationItems = computed(() => { const navigationItems = computed(() => {
const items = [ const items = [

View file

@ -64,17 +64,17 @@ export default { name: 'user-settings-avatar' }
<script setup lang="ts"> <script setup lang="ts">
import {computed, ref, shallowReactive} from 'vue' import {computed, ref, shallowReactive} from 'vue'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useStore} from '@/store'
import {Cropper} from 'vue-advanced-cropper' import {Cropper} from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css' import 'vue-advanced-cropper/dist/style.css'
import AvatarService from '@/services/avatar' import AvatarService from '@/services/avatar'
import AvatarModel from '@/models/avatar' import AvatarModel from '@/models/avatar'
import { useTitle } from '@/composables/useTitle' import {useTitle} from '@/composables/useTitle'
import { success } from '@/message' import {success} from '@/message'
import {useAuthStore} from '@/stores/auth'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const store = useStore() const authStore = useAuthStore()
const AVATAR_PROVIDERS = computed(() => ({ const AVATAR_PROVIDERS = computed(() => ({
default: t('misc.default'), default: t('misc.default'),
@ -102,7 +102,7 @@ avatarStatus()
async function updateAvatarStatus() { async function updateAvatarStatus() {
await avatarService.update(new AvatarModel({avatarProvider: avatarProvider.value})) await avatarService.update(new AvatarModel({avatarProvider: avatarProvider.value}))
success({message: t('user.settings.avatar.statusUpdateSuccess')}) success({message: t('user.settings.avatar.statusUpdateSuccess')})
store.commit('auth/reloadAvatar') authStore.reloadAvatar()
} }
const cropper = ref() const cropper = ref()
@ -121,7 +121,7 @@ async function uploadAvatar() {
const blob = await new Promise(resolve => canvas.toBlob(blob => resolve(blob))) const blob = await new Promise(resolve => canvas.toBlob(blob => resolve(blob)))
await avatarService.create(blob) await avatarService.create(blob)
success({message: t('user.settings.avatar.setSuccess')}) success({message: t('user.settings.avatar.setSuccess')})
store.commit('auth/reloadAvatar') authStore.reloadAvatar()
} finally { } finally {
loading.value = false loading.value = false
isCropAvatar.value = false isCropAvatar.value = false

View file

@ -68,7 +68,6 @@
<script lang="ts" setup> <script lang="ts" setup>
import {computed, ref, shallowReactive} from 'vue' import {computed, ref, shallowReactive} from 'vue'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useStore} from '@/store'
import {CALDAV_DOCS} from '@/urls' import {CALDAV_DOCS} from '@/urls'
import {useTitle} from '@/composables/useTitle' import {useTitle} from '@/composables/useTitle'
@ -80,6 +79,7 @@ import CaldavTokenService from '@/services/caldavToken'
import { formatDateShort } from '@/helpers/time/formatDate' import { formatDateShort } from '@/helpers/time/formatDate'
import type {ICaldavToken} from '@/modelTypes/ICaldavToken' import type {ICaldavToken} from '@/modelTypes/ICaldavToken'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'
import {useAuthStore} from '@/stores/auth'
const copy = useCopyToClipboard() const copy = useCopyToClipboard()
@ -105,10 +105,10 @@ async function deleteToken(token: ICaldavToken) {
success(r) success(r)
} }
const store = useStore() const authStore = useAuthStore()
const configStore = useConfigStore() const configStore = useConfigStore()
const username = computed(() => store.state.auth.info?.username) const username = computed(() => authStore.info?.username)
const caldavUrl = computed(() => `${configStore.apiBase}/dav/principals/${username.value}/`) const caldavUrl = computed(() => `${configStore.apiBase}/dav/principals/${username.value}/`)
const caldavEnabled = computed(() => configStore.caldavEnabled) const caldavEnabled = computed(() => configStore.caldavEnabled)
const isLocalUser = computed(() => store.state.auth.info?.isLocalUser) const isLocalUser = computed(() => authStore.info?.isLocalUser)
</script> </script>

View file

@ -44,22 +44,22 @@ export default {name: 'user-settings-data-export'}
<script setup lang="ts"> <script setup lang="ts">
import {ref, computed, shallowReactive} from 'vue' import {ref, computed, shallowReactive} from 'vue'
import {useStore} from '@/store'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import DataExportService from '@/services/dataExport' import DataExportService from '@/services/dataExport'
import { useTitle } from '@/composables/useTitle' import {useTitle} from '@/composables/useTitle'
import {success} from '@/message' import {success} from '@/message'
import {useAuthStore} from '@/stores/auth'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const store = useStore() const authStore = useAuthStore()
useTitle(() => `${t('user.export.title')} - ${t('user.settings.title')}`) useTitle(() => `${t('user.export.title')} - ${t('user.settings.title')}`)
const dataExportService = shallowReactive(new DataExportService()) const dataExportService = shallowReactive(new DataExportService())
const password = ref('') const password = ref('')
const errPasswordRequired = ref(false) const errPasswordRequired = ref(false)
const isLocalUser = computed(() => store.state.auth.info?.isLocalUser) const isLocalUser = computed(() => authStore.info?.isLocalUser)
const passwordInput = ref() const passwordInput = ref()
async function requestDataExport() { async function requestDataExport() {

View file

@ -88,7 +88,6 @@ export default { name: 'user-settings-deletion' }
<script setup lang="ts"> <script setup lang="ts">
import {ref, shallowReactive, computed} from 'vue' import {ref, shallowReactive, computed} from 'vue'
import {useStore} from '@/store'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import AccountDeleteService from '@/services/accountDelete' import AccountDeleteService from '@/services/accountDelete'
@ -96,6 +95,7 @@ import {parseDateOrNull} from '@/helpers/parseDateOrNull'
import {formatDateShort, formatDateSince} from '@/helpers/time/formatDate' import {formatDateShort, formatDateSince} from '@/helpers/time/formatDate'
import {useTitle} from '@/composables/useTitle' import {useTitle} from '@/composables/useTitle'
import {success} from '@/message' import {success} from '@/message'
import {useAuthStore} from '@/stores/auth'
import {useConfigStore} from '@/stores/config' import {useConfigStore} from '@/stores/config'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
@ -105,11 +105,11 @@ const accountDeleteService = shallowReactive(new AccountDeleteService())
const password = ref('') const password = ref('')
const errPasswordRequired = ref(false) const errPasswordRequired = ref(false)
const store = useStore() const authStore = useAuthStore()
const configStore = useConfigStore() const configStore = useConfigStore()
const userDeletionEnabled = computed(() => configStore.userDeletionEnabled) const userDeletionEnabled = computed(() => configStore.userDeletionEnabled)
const deletionScheduledAt = computed(() => parseDateOrNull(store.state.auth.info?.deletionScheduledAt)) const deletionScheduledAt = computed(() => parseDateOrNull(authStore.info?.deletionScheduledAt))
const passwordInput = ref() const passwordInput = ref()
async function deleteAccount() { async function deleteAccount() {
@ -133,7 +133,7 @@ async function cancelDeletion() {
await accountDeleteService.cancel(password.value) await accountDeleteService.cancel(password.value)
success({message: t('user.deletion.scheduledCancelSuccess')}) success({message: t('user.deletion.scheduledCancelSuccess')})
store.dispatch('auth/refreshUserInfo') authStore.refreshUserInfo()
password.value = '' password.value = ''
} }
</script> </script>

View file

@ -43,18 +43,18 @@ export default { name: 'user-settings-update-email' }
<script setup lang="ts"> <script setup lang="ts">
import {reactive, computed, shallowReactive} from 'vue' import {reactive, computed, shallowReactive} from 'vue'
import {useI18n} from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useStore} from '@/store'
import EmailUpdateService from '@/services/emailUpdate' import EmailUpdateService from '@/services/emailUpdate'
import EmailUpdateModel from '@/models/emailUpdate' import EmailUpdateModel from '@/models/emailUpdate'
import {success} from '@/message' import {success} from '@/message'
import {useTitle} from '@/composables/useTitle' import {useTitle} from '@/composables/useTitle'
import {useAuthStore} from '@/stores/auth'
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
useTitle(() => `${t('user.settings.updateEmailTitle')} - ${t('user.settings.title')}`) useTitle(() => `${t('user.settings.updateEmailTitle')} - ${t('user.settings.title')}`)
const store = useStore() const authStore = useAuthStore()
const isLocalUser = computed(() => store.state.auth.info?.isLocalUser) const isLocalUser = computed(() => authStore.info?.isLocalUser)
const emailUpdate = reactive(new EmailUpdateModel()) const emailUpdate = reactive(new EmailUpdateModel())
const emailUpdateService = shallowReactive(new EmailUpdateService()) const emailUpdateService = shallowReactive(new EmailUpdateService())

View file

@ -149,6 +149,7 @@
<script lang="ts"> <script lang="ts">
import {defineComponent} from 'vue' import {defineComponent} from 'vue'
import { useListStore } from '@/stores/lists' import { useListStore } from '@/stores/lists'
import { useAuthStore } from '@/stores/auth'
export default defineComponent({ export default defineComponent({
name: 'user-settings-general', name: 'user-settings-general',
@ -227,7 +228,8 @@ const playSoundWhenDone = ref(getPlaySoundWhenDoneSetting())
const quickAddMagicMode = ref(getQuickAddMagicMode()) const quickAddMagicMode = ref(getQuickAddMagicMode())
const store = useStore() const store = useStore()
const settings = ref({...store.state.auth.settings}) const authStore = useAuthStore()
const settings = ref({...authStore.settings})
const id = ref(createRandomID()) const id = ref(createRandomID())
const availableLanguageOptions = ref( const availableLanguageOptions = ref(
Object.entries(availableLanguages) Object.entries(availableLanguages)
@ -236,13 +238,13 @@ const availableLanguageOptions = ref(
) )
watch( watch(
() => store.state.auth.settings, () => authStore.settings,
() => { () => {
// Only setting if we don't have values set yet to avoid overriding edited values // Only setting if we don't have values set yet to avoid overriding edited values
if (!objectIsEmpty(settings.value)) { if (!objectIsEmpty(settings.value)) {
return return
} }
settings.value = {...store.state.auth.settings} settings.value = {...authStore.settings}
}, },
{immediate: true}, {immediate: true},
) )
@ -265,7 +267,7 @@ async function updateSettings() {
localStorage.setItem(playSoundWhenDoneKey, playSoundWhenDone.value ? 'true' : 'false') localStorage.setItem(playSoundWhenDoneKey, playSoundWhenDone.value ? 'true' : 'false')
setQuickAddMagicMode(quickAddMagicMode.value) setQuickAddMagicMode(quickAddMagicMode.value)
await store.dispatch('auth/saveUserSettings', { await authStore.saveUserSettings({
settings: {...settings.value}, settings: {...settings.value},
}) })
} }

View file

@ -57,24 +57,24 @@ export default {name: 'user-settings-password-update'}
<script setup lang="ts"> <script setup lang="ts">
import {ref, reactive, shallowReactive, computed} from 'vue' import {ref, reactive, shallowReactive, computed} from 'vue'
import { useI18n } from 'vue-i18n' import {useI18n} from 'vue-i18n'
import {useStore} from '@/store'
import PasswordUpdateService from '@/services/passwordUpdateService' import PasswordUpdateService from '@/services/passwordUpdateService'
import PasswordUpdateModel from '@/models/passwordUpdate' import PasswordUpdateModel from '@/models/passwordUpdate'
import {useTitle} from '@/composables/useTitle' import {useTitle} from '@/composables/useTitle'
import {success, error} from '@/message' import {success, error} from '@/message'
import {useAuthStore} from '@/stores/auth'
const passwordUpdateService = shallowReactive(new PasswordUpdateService()) const passwordUpdateService = shallowReactive(new PasswordUpdateService())
const passwordUpdate = reactive(new PasswordUpdateModel()) const passwordUpdate = reactive(new PasswordUpdateModel())
const passwordConfirm = ref('') const passwordConfirm = ref('')
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
const store = useStore()
useTitle(() => `${t('user.settings.newPasswordTitle')} - ${t('user.settings.title')}`) useTitle(() => `${t('user.settings.newPasswordTitle')} - ${t('user.settings.title')}`)
const isLocalUser = computed(() => store.state.auth.info?.isLocalUser) const authStore = useAuthStore()
const isLocalUser = computed(() => authStore.info?.isLocalUser)
async function updatePassword() { async function updatePassword() {
if (passwordConfirm.value !== passwordUpdate.newPassword) { if (passwordConfirm.value !== passwordUpdate.newPassword) {