Added exercises; Lists improvements #20

Merged
robin merged 2 commits from dev into main 2026-09-04 12:31:29 +02:00
20 changed files with 752 additions and 86 deletions
+7 -7
View File
@@ -5,7 +5,7 @@ import {
createListApi, createListApi,
getListItemsApi, getListItemsApi,
createListItemApi, createListItemApi,
updateListItemApi, updateListItemTitleApi,
setListItemCompletedApi, setListItemCompletedApi,
addUserToListApi, addUserToListApi,
removeUserFromListApi, removeUserFromListApi,
@@ -77,7 +77,7 @@ describe('lists API', () => {
expect(result).toEqual(mockItems) expect(result).toEqual(mockItems)
}) })
it('setListItemCompletedApi sends POST to /lists/items/{id}', async () => { it('setListItemCompletedApi sends POST to /lists/items/{id}/complete', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce({ const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce({
ok: true, ok: true,
status: 204, status: 204,
@@ -87,7 +87,7 @@ describe('lists API', () => {
await setListItemCompletedApi('item-1', { is_completed: true }) await setListItemCompletedApi('item-1', { is_completed: true })
expect(fetchMock).toHaveBeenCalledWith( expect(fetchMock).toHaveBeenCalledWith(
`${API_BASE_URL}/lists/items/item-1`, `${API_BASE_URL}/lists/items/item-1/complete`,
expect.objectContaining({ method: 'POST' }), expect.objectContaining({ method: 'POST' }),
) )
}) })
@@ -137,18 +137,18 @@ describe('lists API', () => {
expect(result).toEqual(mockItem) expect(result).toEqual(mockItem)
}) })
it('updateListItemApi sends PUT to /lists/items', async () => { it('updateListItemTitleApi sends POST to /lists/items/{id}/title', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce({ const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce({
ok: true, ok: true,
status: 204, status: 204,
} as unknown as Response) } as unknown as Response)
global.fetch = fetchMock global.fetch = fetchMock
await updateListItemApi({ list_item_id: 'item-1', is_completed: true }) await updateListItemTitleApi('item-1', { title: 'Free-range eggs' })
expect(fetchMock).toHaveBeenCalledWith( expect(fetchMock).toHaveBeenCalledWith(
`${API_BASE_URL}/lists/items`, `${API_BASE_URL}/lists/items/item-1/title`,
expect.objectContaining({ method: 'PUT' }), expect.objectContaining({ method: 'POST' }),
) )
}) })
+23
View File
@@ -0,0 +1,23 @@
import { apiClient } from '@/api/client'
import { extractErrorMessage } from '@/api/http'
import type { PaginatedExercises } from '@/types/exercise'
export interface GetExercisesParams {
page?: number
count?: number
}
export async function getExercisesApi(
params: GetExercisesParams = {},
): Promise<PaginatedExercises> {
const query = new URLSearchParams()
if (params.page !== undefined) query.set('page', String(params.page))
if (params.count !== undefined) query.set('count', String(params.count))
const queryString = query.toString()
const response = await apiClient.get(`/exercises${queryString ? `?${queryString}` : ''}`)
if (!response.ok) {
throw new Error(await extractErrorMessage(response, 'Failed to load exercises'))
}
return response.json()
}
+12 -9
View File
@@ -5,8 +5,8 @@ import type {
ListItem, ListItem,
CreateListPayload, CreateListPayload,
CreateListItemPayload, CreateListItemPayload,
UpdateListItemPayload,
SetListItemCompletedPayload, SetListItemCompletedPayload,
SetListItemTitlePayload,
AddUserToListPayload, AddUserToListPayload,
RemoveUserFromListPayload, RemoveUserFromListPayload,
} from '@/types/list' } from '@/types/list'
@@ -43,23 +43,26 @@ export async function createListItemApi(payload: CreateListItemPayload): Promise
return response.json() return response.json()
} }
export async function updateListItemApi(payload: UpdateListItemPayload): Promise<void> {
const response = await apiClient.put('/lists/items', payload)
if (!response.ok) {
throw new Error(await extractErrorMessage(response, 'Failed to update list item'))
}
}
export async function setListItemCompletedApi( export async function setListItemCompletedApi(
itemId: string, itemId: string,
payload: SetListItemCompletedPayload, payload: SetListItemCompletedPayload,
): Promise<void> { ): Promise<void> {
const response = await apiClient.post(`/lists/items/${itemId}`, payload) const response = await apiClient.post(`/lists/items/${itemId}/complete`, payload)
if (!response.ok) { if (!response.ok) {
throw new Error(await extractErrorMessage(response, 'Failed to update list item status')) throw new Error(await extractErrorMessage(response, 'Failed to update list item status'))
} }
} }
export async function updateListItemTitleApi(
itemId: string,
payload: SetListItemTitlePayload,
): Promise<void> {
const response = await apiClient.post(`/lists/items/${itemId}/title`, payload)
if (!response.ok) {
throw new Error(await extractErrorMessage(response, 'Failed to update list item title'))
}
}
export async function addUserToListApi(payload: AddUserToListPayload): Promise<void> { export async function addUserToListApi(payload: AddUserToListPayload): Promise<void> {
const response = await apiClient.post('/lists/user', payload) const response = await apiClient.post('/lists/user', payload)
if (!response.ok) { if (!response.ok) {
+18
View File
@@ -19,6 +19,24 @@ const listsStore = useListsStore()
listsStore.pendingCount listsStore.pendingCount
}}</span> }}</span>
</RouterLink> </RouterLink>
<RouterLink to="/exercises" class="nav-item" active-class="is-active">
<svg
class="nav-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="1" y="9" width="3" height="6" rx="1" />
<rect x="4.5" y="7" width="2" height="10" rx="1" />
<line x1="6.5" y1="12" x2="17.5" y2="12" />
<rect x="17.5" y="7" width="2" height="10" rx="1" />
<rect x="20" y="9" width="3" height="6" rx="1" />
</svg>
<span class="nav-label">Exercises</span>
</RouterLink>
<RouterLink to="/account" class="nav-item" active-class="is-active"> <RouterLink to="/account" class="nav-item" active-class="is-active">
<svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <svg class="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="3.2" /> <circle cx="12" cy="12" r="3.2" />
+51
View File
@@ -0,0 +1,51 @@
<script setup lang="ts">
import BaseModal from '@/components/BaseModal.vue'
withDefaults(
defineProps<{
title: string
description: string
confirmLabel?: string
}>(),
{
confirmLabel: 'Delete',
},
)
const emit = defineEmits<{
close: []
confirm: []
}>()
function handleClose() {
emit('close')
}
function handleConfirm() {
emit('confirm')
}
</script>
<template>
<BaseModal :title="title" title-id="confirm-delete-modal-title" @close="handleClose">
<p class="modal-description">{{ description }}</p>
<template #footer>
<button type="button" class="btn btn-secondary cancel-btn" @click="handleClose">
Cancel
</button>
<button type="button" class="btn btn-danger confirm-delete-btn" @click="handleConfirm">
{{ confirmLabel }}
</button>
</template>
</BaseModal>
</template>
<style scoped>
.modal-description {
font-size: 0.85rem;
color: var(--c-text-soft);
margin-bottom: 1.25rem;
line-height: 1.4;
}
</style>
+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import type { LocalListItem } from '@/database/db'
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue'
const props = defineProps<{
item: LocalListItem
}>()
const emit = defineEmits<{
close: []
confirm: []
}>()
function handleClose() {
emit('close')
}
function handleConfirm() {
emit('confirm')
}
</script>
<template>
<ConfirmDeleteModal
:title="`Delete &quot;${props.item.title}&quot;?`"
description="Are you sure you want to delete this item? This action cannot be undone."
confirm-label="Delete item"
@close="handleClose"
@confirm="handleConfirm"
/>
</template>
+8 -29
View File
@@ -1,8 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import type { LocalList } from '@/database/db' import type { LocalList } from '@/database/db'
import BaseModal from '@/components/BaseModal.vue' import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue'
defineProps<{ const props = defineProps<{
list: LocalList list: LocalList
}>() }>()
@@ -21,32 +21,11 @@ function handleConfirm() {
</script> </script>
<template> <template>
<BaseModal <ConfirmDeleteModal
:title="`Delete &quot;${list.name}&quot;?`" :title="`Delete &quot;${props.list.name}&quot;?`"
title-id="delete-modal-title" description="Are you sure you want to delete this list? This action cannot be undone and all items in this list will be deleted."
confirm-label="Delete list"
@close="handleClose" @close="handleClose"
> @confirm="handleConfirm"
<p class="modal-description"> />
Are you sure you want to delete this list? This action cannot be undone and all items in this
list will be deleted.
</p>
<template #footer>
<button type="button" class="btn btn-secondary cancel-btn" @click="handleClose">
Cancel
</button>
<button type="button" class="btn btn-danger confirm-delete-btn" @click="handleConfirm">
Delete list
</button>
</template>
</BaseModal>
</template> </template>
<style scoped>
.modal-description {
font-size: 0.85rem;
color: var(--c-text-soft);
margin-bottom: 1.25rem;
line-height: 1.4;
}
</style>
+112
View File
@@ -0,0 +1,112 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { Exercise } from '@/types/exercise'
import { EQUIPMENT_LABELS, LOAD_LABELS, METRIC_LABELS } from '@/types/exercise'
const props = defineProps<{ exercise: Exercise }>()
const emit = defineEmits<{
select: [id: string]
}>()
const equipmentLabels = computed(
() => props.exercise.equipment?.map((equipment) => EQUIPMENT_LABELS[equipment]) ?? [],
)
const loadLabel = computed(() =>
props.exercise.load !== undefined ? LOAD_LABELS[props.exercise.load] : null,
)
const metricLabel = computed(() =>
props.exercise.metric !== undefined ? METRIC_LABELS[props.exercise.metric] : null,
)
function handleClick() {
emit('select', props.exercise.id)
}
</script>
<template>
<button type="button" class="exercise-card card" @click="handleClick">
<div class="exercise-card-main">
<h3>{{ exercise.name }}</h3>
<p v-if="exercise.notes" class="notes">{{ exercise.notes }}</p>
<div v-if="loadLabel || metricLabel || equipmentLabels.length > 0" class="tags">
<span v-if="loadLabel" class="tag tag-accent">{{ loadLabel }}</span>
<span v-if="metricLabel" class="tag tag-accent">{{ metricLabel }}</span>
<span v-for="equipment in equipmentLabels" :key="equipment" class="tag">{{
equipment
}}</span>
</div>
</div>
<span class="chevron"></span>
</button>
</template>
<style scoped>
.exercise-card {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 0.85rem 1rem;
color: inherit;
background-color: var(--c-bg-soft);
font: inherit;
text-align: left;
cursor: pointer;
transition: border-color 0.15s ease-in-out;
}
.exercise-card:hover {
border-color: var(--c-border-hover);
}
.exercise-card-main {
flex: 1;
min-width: 0;
}
.exercise-card-main h3 {
font-size: 1.02rem;
margin-bottom: 0.2rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.notes {
font-size: 0.8rem;
color: var(--c-text-soft);
margin-bottom: 0.4rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.tag {
font-size: 0.68rem;
font-weight: 500;
padding: 0.15rem 0.5rem;
border-radius: 999px;
background-color: var(--c-bg-mute);
color: var(--c-text-soft);
}
.tag-accent {
background-color: var(--c-accent-bg);
color: var(--c-accent-strong);
}
.chevron {
flex-shrink: 0;
color: var(--c-text-soft);
font-size: 1.3rem;
line-height: 1;
padding-right: 0.25rem;
}
</style>
+37 -6
View File
@@ -3,6 +3,7 @@ import { ref } from 'vue'
import type { LocalListItem } from '@/database/db' import type { LocalListItem } from '@/database/db'
import { useListsStore } from '@/stores/lists' import { useListsStore } from '@/stores/lists'
import { useDismissableMenu } from '@/composables/useDismissableMenu' import { useDismissableMenu } from '@/composables/useDismissableMenu'
import DeleteListItemModal from '@/components/DeleteListItemModal.vue'
const props = defineProps<{ item: LocalListItem }>() const props = defineProps<{ item: LocalListItem }>()
@@ -16,6 +17,7 @@ const editedTitle = ref(props.item.title)
// diffing against the live (possibly just-changed) prop and overwriting the // diffing against the live (possibly just-changed) prop and overwriting the
// remote edit with the untouched original text. // remote edit with the untouched original text.
const originalTitle = ref(props.item.title) const originalTitle = ref(props.item.title)
const showDeleteModal = ref(false)
const { const {
isOpen: isMenuOpen, isOpen: isMenuOpen,
containerRef: menuContainerRef, containerRef: menuContainerRef,
@@ -27,6 +29,7 @@ function toggleCompleted() {
} }
function startEditing() { function startEditing() {
isMenuOpen.value = false
editedTitle.value = props.item.title editedTitle.value = props.item.title
originalTitle.value = props.item.title originalTitle.value = props.item.title
isEditing.value = true isEditing.value = true
@@ -35,15 +38,22 @@ function startEditing() {
function saveTitle() { function saveTitle() {
const title = editedTitle.value.trim() const title = editedTitle.value.trim()
if (title && title !== originalTitle.value) { if (title && title !== originalTitle.value) {
listsStore.updateListItem(props.item.id, { title }) listsStore.updateListItemTitle(props.item.id, title)
} }
isEditing.value = false isEditing.value = false
} }
function handleDelete(event: Event) { function handleOpenDelete() {
event.preventDefault()
event.stopPropagation()
isMenuOpen.value = false isMenuOpen.value = false
showDeleteModal.value = true
}
function handleCloseDelete() {
showDeleteModal.value = false
}
function handleConfirmDelete() {
showDeleteModal.value = false
listsStore.deleteListItem(props.item.id) listsStore.deleteListItem(props.item.id)
} }
</script> </script>
@@ -68,7 +78,7 @@ function handleDelete(event: Event) {
@keyup.escape="isEditing = false" @keyup.escape="isEditing = false"
@blur="saveTitle" @blur="saveTitle"
/> />
<span v-else class="title" @click="startEditing">{{ item.title }}</span> <span v-else class="title" @click="toggleCompleted">{{ item.title }}</span>
<span v-if="item.pendingSync" class="pending-dot" title="Not yet synced"></span> <span v-if="item.pendingSync" class="pending-dot" title="Not yet synced"></span>
@@ -90,11 +100,25 @@ function handleDelete(event: Event) {
</button> </button>
<div v-if="isMenuOpen" class="submenu-dropdown card" role="menu"> <div v-if="isMenuOpen" class="submenu-dropdown card" role="menu">
<button type="button" class="submenu-item" role="menuitem" @click="startEditing">
<svg
class="submenu-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M17 3a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L17 3z" />
</svg>
<span>Edit title</span>
</button>
<button <button
type="button" type="button"
class="submenu-item submenu-item-danger" class="submenu-item submenu-item-danger"
role="menuitem" role="menuitem"
@click="handleDelete" @click="handleOpenDelete"
> >
<svg <svg
class="submenu-icon" class="submenu-icon"
@@ -116,6 +140,13 @@ function handleDelete(event: Event) {
</button> </button>
</div> </div>
</div> </div>
<DeleteListItemModal
v-if="showDeleteModal"
:item="item"
@close="handleCloseDelete"
@confirm="handleConfirmDelete"
/>
</li> </li>
</template> </template>
@@ -0,0 +1,79 @@
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import ConfirmDeleteModal from '../ConfirmDeleteModal.vue'
describe('ConfirmDeleteModal', () => {
it('renders title, description, and default confirm label', () => {
const wrapper = mount(ConfirmDeleteModal, {
props: {
title: 'Delete "Groceries"?',
description: 'Are you sure?',
},
})
expect(wrapper.text()).toContain('Delete "Groceries"?')
expect(wrapper.text()).toContain('Are you sure?')
expect(wrapper.find('.confirm-delete-btn').text()).toBe('Delete')
expect(wrapper.find('.cancel-btn').text()).toBe('Cancel')
})
it('renders a custom confirm label', () => {
const wrapper = mount(ConfirmDeleteModal, {
props: {
title: 'Delete "Apples"?',
description: 'Are you sure?',
confirmLabel: 'Delete item',
},
})
expect(wrapper.find('.confirm-delete-btn').text()).toBe('Delete item')
})
it('emits confirm event when Delete button is clicked', async () => {
const wrapper = mount(ConfirmDeleteModal, {
props: {
title: 'Delete "Groceries"?',
description: 'Are you sure?',
},
})
await wrapper.find('.confirm-delete-btn').trigger('click')
expect(wrapper.emitted('confirm')).toBeTruthy()
})
it('emits close event when Cancel button is clicked', async () => {
const wrapper = mount(ConfirmDeleteModal, {
props: {
title: 'Delete "Groceries"?',
description: 'Are you sure?',
},
})
await wrapper.find('.cancel-btn').trigger('click')
expect(wrapper.emitted('close')).toBeTruthy()
})
it('emits close event when close icon button is clicked', async () => {
const wrapper = mount(ConfirmDeleteModal, {
props: {
title: 'Delete "Groceries"?',
description: 'Are you sure?',
},
})
await wrapper.find('.close-btn').trigger('click')
expect(wrapper.emitted('close')).toBeTruthy()
})
it('emits close event when clicking overlay background', async () => {
const wrapper = mount(ConfirmDeleteModal, {
props: {
title: 'Delete "Groceries"?',
description: 'Are you sure?',
},
})
await wrapper.find('.modal-overlay').trigger('click')
expect(wrapper.emitted('close')).toBeTruthy()
})
})
@@ -0,0 +1,50 @@
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import DeleteListItemModal from '../DeleteListItemModal.vue'
import type { LocalListItem } from '@/database/db'
describe('DeleteListItemModal', () => {
const sampleItem: LocalListItem = {
id: 'item-1',
list_id: 'list-1',
title: 'Apples',
is_completed: false,
created_at: '2026-08-21T00:00:00.000Z',
modified_at: '2026-08-21T00:00:00.000Z',
}
it('renders modal with item title and confirmation prompt', () => {
const wrapper = mount(DeleteListItemModal, {
props: {
item: sampleItem,
},
})
expect(wrapper.text()).toContain('Delete "Apples"?')
expect(wrapper.text()).toContain('Are you sure you want to delete this item?')
expect(wrapper.find('.confirm-delete-btn').text()).toBe('Delete item')
expect(wrapper.find('.cancel-btn').text()).toBe('Cancel')
})
it('emits confirm event when Delete button is clicked', async () => {
const wrapper = mount(DeleteListItemModal, {
props: {
item: sampleItem,
},
})
await wrapper.find('.confirm-delete-btn').trigger('click')
expect(wrapper.emitted('confirm')).toBeTruthy()
})
it('emits close event when Cancel button is clicked', async () => {
const wrapper = mount(DeleteListItemModal, {
props: {
item: sampleItem,
},
})
await wrapper.find('.cancel-btn').trigger('click')
expect(wrapper.emitted('close')).toBeTruthy()
})
})
+67 -3
View File
@@ -47,7 +47,39 @@ describe('ListItemRow', () => {
expect(wrapper.find('.submenu-dropdown').exists()).toBe(false) expect(wrapper.find('.submenu-dropdown').exists()).toBe(false)
}) })
it('deletes item when Delete item is clicked in submenu', async () => { it('toggles completed state when the title text is clicked', async () => {
const wrapper = mount(ListItemRow, {
props: {
item: sampleItem,
},
})
const listsStore = useListsStore()
const toggleSpy = vi.spyOn(listsStore, 'setListItemCompleted').mockResolvedValue()
await wrapper.find('.title').trigger('click')
expect(toggleSpy).toHaveBeenCalledWith('item-1', true)
})
it('opens the title editor via the Edit title submenu item', async () => {
const wrapper = mount(ListItemRow, {
props: {
item: sampleItem,
},
})
await wrapper.find('.menu-trigger-btn').trigger('click')
const editBtn = wrapper.find('.submenu-item:not(.submenu-item-danger)')
expect(editBtn.text()).toContain('Edit title')
await editBtn.trigger('click')
expect(wrapper.find('.title-input').exists()).toBe(true)
expect(wrapper.find('.submenu-dropdown').exists()).toBe(false)
})
it('opens a confirmation modal when Delete item is clicked in submenu', async () => {
const wrapper = mount(ListItemRow, { const wrapper = mount(ListItemRow, {
props: { props: {
item: sampleItem, item: sampleItem,
@@ -61,10 +93,42 @@ describe('ListItemRow', () => {
await wrapper.find('.menu-trigger-btn').trigger('click') await wrapper.find('.menu-trigger-btn').trigger('click')
expect(wrapper.find('.submenu-dropdown').exists()).toBe(true) expect(wrapper.find('.submenu-dropdown').exists()).toBe(true)
// 2nd click: delete item // 2nd click: opens confirmation modal, doesn't delete yet
await wrapper.find('.submenu-item-danger').trigger('click') await wrapper.find('.submenu-item-danger').trigger('click')
expect(deleteSpy).toHaveBeenCalledWith('item-1')
expect(wrapper.find('.submenu-dropdown').exists()).toBe(false) expect(wrapper.find('.submenu-dropdown').exists()).toBe(false)
expect(deleteSpy).not.toHaveBeenCalled()
const modal = wrapper.findComponent({ name: 'DeleteListItemModal' })
expect(modal.exists()).toBe(true)
expect(modal.text()).toContain('Delete "Apples"?')
// Confirm deletion in modal
await modal.find('.confirm-delete-btn').trigger('click')
expect(deleteSpy).toHaveBeenCalledWith('item-1')
expect(wrapper.findComponent({ name: 'DeleteListItemModal' }).exists()).toBe(false)
})
it('cancels item deletion when cancel is clicked in confirmation modal', async () => {
const wrapper = mount(ListItemRow, {
props: {
item: sampleItem,
},
})
const listsStore = useListsStore()
const deleteSpy = vi.spyOn(listsStore, 'deleteListItem').mockResolvedValue()
await wrapper.find('.menu-trigger-btn').trigger('click')
await wrapper.find('.submenu-item-danger').trigger('click')
const modal = wrapper.findComponent({ name: 'DeleteListItemModal' })
expect(modal.exists()).toBe(true)
await modal.find('.cancel-btn').trigger('click')
expect(deleteSpy).not.toHaveBeenCalled()
expect(wrapper.findComponent({ name: 'DeleteListItemModal' }).exists()).toBe(false)
}) })
}) })
+2 -2
View File
@@ -4,8 +4,8 @@ import type {
ListItem, ListItem,
CreateListPayload, CreateListPayload,
CreateListItemPayload, CreateListItemPayload,
UpdateListItemPayload,
SetListItemCompletedPayload, SetListItemCompletedPayload,
SetListItemTitlePayload,
} from '@/types/list' } from '@/types/list'
export interface LocalList extends List { export interface LocalList extends List {
@@ -36,7 +36,7 @@ interface SyncQueueEntryBase {
type SyncOperationPayloads = { type SyncOperationPayloads = {
createList: CreateListPayload createList: CreateListPayload
createListItem: CreateListItemPayload createListItem: CreateListItemPayload
updateListItem: UpdateListItemPayload updateListItemTitle: SetListItemTitlePayload
setListItemCompleted: SetListItemCompletedPayload setListItemCompleted: SetListItemCompletedPayload
deleteList: DeleteListPayload deleteList: DeleteListPayload
deleteListItem: DeleteListItemPayload deleteListItem: DeleteListItemPayload
+6
View File
@@ -18,6 +18,12 @@ const router = createRouter({
meta: { requiresAuth: true }, meta: { requiresAuth: true },
props: true, props: true,
}, },
{
path: '/exercises',
name: 'exercises',
component: () => import('../views/ExercisesView.vue'),
meta: { requiresAuth: true },
},
{ {
path: '/login', path: '/login',
name: 'login', name: 'login',
+7 -8
View File
@@ -109,7 +109,7 @@ const listsApiMocks = vi.hoisted(() => ({
createListApi: vi.fn<() => Promise<unknown>>(), createListApi: vi.fn<() => Promise<unknown>>(),
getListItemsApi: vi.fn<() => Promise<unknown>>(), getListItemsApi: vi.fn<() => Promise<unknown>>(),
createListItemApi: vi.fn<() => Promise<unknown>>(), createListItemApi: vi.fn<() => Promise<unknown>>(),
updateListItemApi: vi.fn<() => Promise<unknown>>(), updateListItemTitleApi: vi.fn<() => Promise<unknown>>(),
setListItemCompletedApi: vi.fn<() => Promise<unknown>>(), setListItemCompletedApi: vi.fn<() => Promise<unknown>>(),
addUserToListApi: vi.fn<() => Promise<unknown>>(), addUserToListApi: vi.fn<() => Promise<unknown>>(),
removeUserFromListApi: vi.fn<() => Promise<unknown>>(), removeUserFromListApi: vi.fn<() => Promise<unknown>>(),
@@ -211,29 +211,28 @@ describe('useListsStore', () => {
expect(store.error).toBe('Network error') expect(store.error).toBe('Network error')
}) })
it('updates a list item locally and pushes the change to the server', async () => { it('updates a list item title locally and pushes the change via the dedicated endpoint', async () => {
listsApiMocks.createListItemApi.mockResolvedValueOnce({ listsApiMocks.createListItemApi.mockResolvedValueOnce({
id: 'server-item-2', id: 'server-item-2',
list_id: '', list_id: '',
title: 'Eggs', title: 'Eggs',
is_completed: false, is_completed: false,
}) })
listsApiMocks.updateListItemApi.mockResolvedValueOnce(undefined) listsApiMocks.updateListItemTitleApi.mockResolvedValueOnce(undefined)
const store = useListsStore() const store = useListsStore()
await store.createListItem('list-1', 'Eggs') await store.createListItem('list-1', 'Eggs')
await store.sync() await store.sync()
const created = store.listItems.find((entry) => entry.title === 'Eggs')! const created = store.listItems.find((entry) => entry.title === 'Eggs')!
await store.updateListItem(created.id, { is_completed: true }) await store.updateListItemTitle(created.id, 'Free-range eggs')
await store.sync() await store.sync()
expect(listsApiMocks.updateListItemApi).toHaveBeenCalledWith({ expect(listsApiMocks.updateListItemTitleApi).toHaveBeenCalledWith(created.id, {
list_item_id: created.id, title: 'Free-range eggs',
is_completed: true,
}) })
const updated = store.listItems.find((entry) => entry.id === created.id) const updated = store.listItems.find((entry) => entry.id === created.id)
expect(updated?.is_completed).toBe(true) expect(updated?.title).toBe('Free-range eggs')
expect(updated?.pendingSync).toBe(false) expect(updated?.pendingSync).toBe(false)
}) })
+9 -13
View File
@@ -13,7 +13,7 @@ import {
createListApi, createListApi,
getListItemsApi, getListItemsApi,
createListItemApi, createListItemApi,
updateListItemApi, updateListItemTitleApi,
setListItemCompletedApi, setListItemCompletedApi,
addUserToListApi, addUserToListApi,
removeUserFromListApi, removeUserFromListApi,
@@ -180,12 +180,9 @@ export const useListsStore = defineStore('lists', () => {
return localItem return localItem
} }
async function updateListItem( async function updateListItemTitle(itemId: string, title: string) {
itemId: string,
changes: { title?: string; is_completed?: boolean },
) {
const patch = { const patch = {
...changes, title,
modified_at: new Date().toISOString(), modified_at: new Date().toISOString(),
pendingSync: true, pendingSync: true,
} }
@@ -193,8 +190,8 @@ export const useListsStore = defineStore('lists', () => {
const existingItem = listItems.value.find((entry) => entry.id === itemId) const existingItem = listItems.value.find((entry) => entry.id === itemId)
if (existingItem) Object.assign(existingItem, patch) if (existingItem) Object.assign(existingItem, patch)
await enqueue({ await enqueue({
type: 'updateListItem', type: 'updateListItemTitle',
payload: { list_item_id: itemId, ...changes }, payload: { title },
localListItemId: itemId, localListItemId: itemId,
}) })
scheduleSync() scheduleSync()
@@ -357,11 +354,10 @@ export const useListsStore = defineStore('lists', () => {
} }
break break
} }
case 'updateListItem': { case 'updateListItemTitle': {
await updateListItemApi(entry.payload) if (!entry.localListItemId) break
if (entry.localListItemId) { await updateListItemTitleApi(entry.localListItemId, entry.payload)
await markListItemSynced(entry.localListItemId) await markListItemSynced(entry.localListItemId)
}
break break
} }
case 'setListItemCompleted': { case 'setListItemCompleted': {
@@ -570,7 +566,7 @@ export const useListsStore = defineStore('lists', () => {
refresh, refresh,
createList, createList,
createListItem, createListItem,
updateListItem, updateListItemTitle,
setListItemCompleted, setListItemCompleted,
addUserToList, addUserToList,
removeUserFromList, removeUserFromList,
+62
View File
@@ -0,0 +1,62 @@
export enum Equipment {
Unknown = 0,
Floor = 1,
Rings = 2,
PullUpBar = 3,
ParallelBars = 4,
LowBar = 5,
Parallettes = 6,
ResistanceBand = 7,
}
export enum Load {
Unknown = 0,
Bodyweight = 1,
External = 2,
}
export enum Metric {
Unknown = 0,
Reps = 1,
Seconds = 2,
}
export const EQUIPMENT_LABELS: Record<Equipment, string> = {
[Equipment.Unknown]: 'Unknown',
[Equipment.Floor]: 'Floor',
[Equipment.Rings]: 'Rings',
[Equipment.PullUpBar]: 'Pull-up bar',
[Equipment.ParallelBars]: 'Parallel bars',
[Equipment.LowBar]: 'Low bar',
[Equipment.Parallettes]: 'Parallettes',
[Equipment.ResistanceBand]: 'Resistance band',
}
export const LOAD_LABELS: Record<Load, string> = {
[Load.Unknown]: 'Unknown',
[Load.Bodyweight]: 'Bodyweight',
[Load.External]: 'External',
}
export const METRIC_LABELS: Record<Metric, string> = {
[Metric.Unknown]: 'Unknown',
[Metric.Reps]: 'Reps',
[Metric.Seconds]: 'Seconds',
}
export interface Exercise {
id: string
name: string
notes?: string
equipment?: Equipment[]
load?: Load
metric?: Metric
tags?: string[]
modified_at?: string
}
export interface PaginatedExercises {
data: Exercise[]
total: number
count: number
}
+4 -6
View File
@@ -25,16 +25,14 @@ export interface CreateListItemPayload {
title: string title: string
} }
export interface UpdateListItemPayload {
list_item_id: string
title?: string
is_completed?: boolean
}
export interface SetListItemCompletedPayload { export interface SetListItemCompletedPayload {
is_completed: boolean is_completed: boolean
} }
export interface SetListItemTitlePayload {
title: string
}
export interface AddUserToListPayload { export interface AddUserToListPayload {
list_id: string list_id: string
email: string email: string
+157
View File
@@ -0,0 +1,157 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { getExercisesApi } from '@/api/exercises'
import type { Exercise } from '@/types/exercise'
import ExerciseCard from '@/components/ExerciseCard.vue'
const PAGE_SIZE = 20
const exercises = ref<Exercise[]>([])
const page = ref(1)
const total = ref(0)
const isLoading = ref(false)
const error = ref('')
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE)))
const showPagination = computed(() => totalPages.value > 1)
onMounted(() => {
void loadExercises()
})
async function loadExercises() {
error.value = ''
isLoading.value = true
try {
const response = await getExercisesApi({ page: page.value, count: PAGE_SIZE })
exercises.value = response.data
total.value = response.total
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to load exercises'
} finally {
isLoading.value = false
}
}
async function goToPage(target: number) {
if (target < 1 || target > totalPages.value || target === page.value || isLoading.value) {
return
}
page.value = target
await loadExercises()
}
// No workout/workout-template flow exists yet to receive a selection; this
// is the attachment point future "add exercise to workout" UI will use.
function handleSelectExercise() {}
</script>
<template>
<main class="page">
<h1>Exercises</h1>
<p v-if="error" class="banner banner-error">{{ error }}</p>
<p v-if="isLoading && exercises.length === 0" class="loading-text">Loading exercises</p>
<ul v-else-if="exercises.length > 0" class="exercises">
<li v-for="exercise in exercises" :key="exercise.id">
<ExerciseCard :exercise="exercise" @select="handleSelectExercise" />
</li>
</ul>
<div v-else class="empty-state">
<p>No exercises yet</p>
</div>
<div v-if="showPagination" class="pagination">
<button
type="button"
class="page-btn"
:disabled="page <= 1 || isLoading"
aria-label="Previous page"
@click="goToPage(page - 1)"
>
</button>
<span class="pagination-info mono-num"
>Page {{ page }} of {{ totalPages }} · {{ total }} total</span
>
<button
type="button"
class="page-btn"
:disabled="page >= totalPages || isLoading"
aria-label="Next page"
@click="goToPage(page + 1)"
>
</button>
</div>
</main>
</template>
<style scoped>
h1 {
font-size: 1.4rem;
margin-bottom: 1rem;
}
.loading-text,
.empty-state {
color: var(--c-text-soft);
font-size: 0.9rem;
}
.empty-state {
text-align: center;
padding: 3rem 1rem;
}
.exercises {
display: flex;
flex-direction: column;
gap: 0.6rem;
list-style: none;
padding: 0;
margin: 0;
}
.pagination {
display: flex;
align-items: center;
justify-content: center;
gap: 0.75rem;
margin-top: 1.25rem;
}
.pagination-info {
font-size: 0.78rem;
color: var(--c-text-soft);
}
.page-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
padding: 0;
background: none;
border: 1px solid var(--c-border);
border-radius: var(--radius-sm);
color: var(--c-text);
font-size: 1rem;
line-height: 1;
cursor: pointer;
}
.page-btn:hover:not(:disabled) {
border-color: var(--c-border-hover);
color: var(--c-heading);
}
.page-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
</style>
+9 -2
View File
@@ -121,7 +121,7 @@ describe('ListDetailView', () => {
expect(wrapper.findComponent({ name: 'DeleteListModal' }).exists()).toBe(false) expect(wrapper.findComponent({ name: 'DeleteListModal' }).exists()).toBe(false)
}) })
it('allows deleting list items via two clicks on item row menu', async () => { it('allows deleting list items via menu and confirmation modal', async () => {
const listsStore = useListsStore() const listsStore = useListsStore()
const deleteItemSpy = vi.spyOn(listsStore, 'deleteListItem').mockResolvedValue() const deleteItemSpy = vi.spyOn(listsStore, 'deleteListItem').mockResolvedValue()
const sampleList: LocalList = { const sampleList: LocalList = {
@@ -156,9 +156,16 @@ describe('ListDetailView', () => {
const deleteItemBtn = itemRow.find('.submenu-item-danger') const deleteItemBtn = itemRow.find('.submenu-item-danger')
expect(deleteItemBtn.exists()).toBe(true) expect(deleteItemBtn.exists()).toBe(true)
// 2nd click: delete item // 2nd click: opens confirmation modal
await deleteItemBtn.trigger('click') await deleteItemBtn.trigger('click')
const modal = itemRow.findComponent({ name: 'DeleteListItemModal' })
expect(modal.exists()).toBe(true)
expect(deleteItemSpy).not.toHaveBeenCalled()
// Confirm deletion in modal
await modal.find('.confirm-delete-btn').trigger('click')
expect(deleteItemSpy).toHaveBeenCalledWith('item-1') expect(deleteItemSpy).toHaveBeenCalledWith('item-1')
}) })
}) })