Moved things around
Some checks failed
Gitea Actions Demo / build-and-push (push) Failing after 6s

This commit is contained in:
2026-01-21 17:18:58 -05:00
parent a47df7171c
commit a0a059472b
160 changed files with 100 additions and 17 deletions

View File

@@ -0,0 +1,180 @@
<script setup lang="ts">
import { ref, onBeforeUnmount, watch, nextTick, computed } from 'vue'
import { defineProps, defineEmits, defineExpose } from 'vue'
import { getCachedImageUrl, revokeAllImageUrls } from '../../common/imageCache'
import type { RewardStatus } from '@/common/models'
const imageCacheName = 'images-v1'
const props = defineProps<{
childId: string | null
childPoints: number
isParentAuthenticated: boolean
}>()
const emit = defineEmits(['trigger-reward'])
const rewards = ref<RewardStatus[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const scrollWrapper = ref<HTMLDivElement | null>(null)
const rewardRefs = ref<Record<string, HTMLElement | null>>({})
const lastCenteredRewardId = ref<string | null>(null)
const readyRewardId = ref<string | null>(null)
const fetchRewards = async (id: string | number | null) => {
if (!id) {
rewards.value = []
loading.value = false
return
}
loading.value = true
error.value = null
try {
const resp = await fetch(`/api/child/${id}/reward-status`)
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
const data = await resp.json()
rewards.value = data.reward_status
// Fetch images for each reward using shared utility
await Promise.all(rewards.value.map(fetchImage))
} catch (err) {
error.value = err instanceof Error ? err.message : 'Failed to fetch rewards'
console.error('Error fetching rewards:', err)
} finally {
loading.value = false
}
}
const fetchImage = async (reward: RewardStatus) => {
if (!reward.image_id) {
console.log(`No image ID for reward: ${reward.id}`)
return
}
try {
const url = await getCachedImageUrl(reward.image_id, imageCacheName)
reward.image_id = url
} catch (err) {
console.error('Error fetching image for reward', reward.id, err)
}
}
const centerReward = async (rewardId: string) => {
await nextTick()
const wrapper = scrollWrapper.value
const card = rewardRefs.value[rewardId]
if (wrapper && card) {
const wrapperRect = wrapper.getBoundingClientRect()
const cardRect = card.getBoundingClientRect()
const wrapperScrollLeft = wrapper.scrollLeft
const cardCenter = cardRect.left + cardRect.width / 2
const wrapperCenter = wrapperRect.left + wrapperRect.width / 2
const scrollOffset = cardCenter - wrapperCenter
wrapper.scrollTo({
left: wrapperScrollLeft + scrollOffset,
behavior: 'smooth',
})
}
}
const handleRewardClick = async (rewardId: string) => {
await nextTick()
const wrapper = scrollWrapper.value
const card = rewardRefs.value[rewardId]
if (!wrapper || !card) return
const wrapperRect = wrapper.getBoundingClientRect()
const cardRect = card.getBoundingClientRect()
const cardCenter = cardRect.left + cardRect.width / 2
const cardFullyVisible = cardCenter >= wrapperRect.left && cardCenter <= wrapperRect.right
if (!cardFullyVisible || lastCenteredRewardId.value !== rewardId) {
// Center the reward, but don't trigger
await centerReward(rewardId)
lastCenteredRewardId.value = rewardId
readyRewardId.value = rewardId
return
}
// If already centered and visible, trigger the reward
await triggerReward(rewardId)
readyRewardId.value = null
}
const triggerReward = (rewardId: string) => {
const reward = rewards.value.find((rew) => rew.id === rewardId)
if (!reward) return // Don't trigger if not allowed
emit('trigger-reward', reward, reward.points_needed <= 0, reward.redeeming)
}
watch(
() => props.childId,
(newId) => {
fetchRewards(newId)
},
{ immediate: true },
)
watch(
() => props.childPoints,
() => {
rewards.value.forEach((reward) => {
reward.points_needed = Math.max(0, reward.cost - props.childPoints)
})
},
)
function getPendingRewards(): string[] {
return rewards.value.filter((r) => r.redeeming).map((r) => r.id)
}
// revoke created object URLs when component unmounts to avoid memory leaks
onBeforeUnmount(() => {
revokeAllImageUrls()
})
// expose refresh method for parent component
defineExpose({ refresh: () => fetchRewards(props.childId), getPendingRewards })
const isAnyPending = computed(() => rewards.value.some((r) => r.redeeming))
</script>
<template>
<div class="child-list-container">
<h3>Rewards</h3>
<div v-if="loading" class="loading">Loading rewards...</div>
<div v-else-if="error" class="error">Error: {{ error }}</div>
<div v-else-if="rewards.length === 0" class="empty">No rewards available</div>
<div v-else class="scroll-wrapper" ref="scrollWrapper">
<div class="item-scroll">
<div
v-for="r in rewards"
:key="r.id"
class="item-card"
:class="{
ready: readyRewardId === r.id,
disabled: isAnyPending && !r.redeeming,
}"
:ref="(el) => (rewardRefs[r.id] = el)"
@click="() => handleRewardClick(r.id)"
>
<div class="item-name">{{ r.name }}</div>
<img v-if="r.image_id" :src="r.image_id" alt="Reward Image" class="item-image" />
<div class="item-points" :class="{ ready: r.points_needed === 0 }">
<template v-if="r.points_needed === 0"> REWARD READY </template>
<template v-else> {{ r.points_needed }} more points </template>
</div>
<!-- PENDING block if redeeming is true -->
<div v-if="r.redeeming" class="pending-block">PENDING</div>
</div>
</div>
</div>
</div>
</template>
<style scoped></style>

View File

@@ -0,0 +1,169 @@
<template>
<div class="reward-edit-view">
<h2>{{ isEdit ? 'Edit Reward' : 'Create Reward' }}</h2>
<div v-if="loading" class="loading-message">Loading reward...</div>
<form v-else @submit.prevent="submit" class="reward-form">
<div class="group">
<label>
Reward Name
<input ref="nameInput" v-model="name" type="text" required maxlength="64" />
</label>
</div>
<div class="group">
<label>
Description
<input v-model="description" type="text" maxlength="128" />
</label>
</div>
<div class="group">
<label>
Cost
<input v-model.number="cost" type="number" min="1" max="1000" required />
</label>
</div>
<div class="group">
<label for="reward-image">Image</label>
<ImagePicker
id="reward-image"
v-model="selectedImageId"
:image-type="2"
@add-image="onAddImage"
/>
</div>
<div v-if="error" class="error">{{ error }}</div>
<div class="actions">
<button type="button" @click="handleCancel" :disabled="loading" class="btn btn-secondary">
Cancel
</button>
<button type="submit" :disabled="loading" class="btn btn-primary">
{{ isEdit ? 'Save' : 'Create' }}
</button>
</div>
</form>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ImagePicker from '@/components/utils/ImagePicker.vue'
import '@/assets/edit-forms.css'
const props = defineProps<{ id?: string }>()
const route = useRoute()
const router = useRouter()
const isEdit = computed(() => !!props.id)
const name = ref('')
const description = ref('')
const cost = ref(1)
const selectedImageId = ref<string | null>(null)
const localImageFile = ref<File | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const nameInput = ref<HTMLInputElement | null>(null)
onMounted(async () => {
if (isEdit.value && props.id) {
loading.value = true
try {
const resp = await fetch(`/api/reward/${props.id}`)
if (!resp.ok) throw new Error('Failed to load reward')
const data = await resp.json()
name.value = data.name
description.value = data.description ?? ''
cost.value = Number(data.cost) || 1
selectedImageId.value = data.image_id ?? null
} catch (e) {
error.value = 'Could not load reward.'
} finally {
loading.value = false
await nextTick()
nameInput.value?.focus()
}
} else {
await nextTick()
nameInput.value?.focus()
}
})
function onAddImage({ id, file }: { id: string; file: File }) {
if (id === 'local-upload') {
localImageFile.value = file
}
}
function handleCancel() {
router.back()
}
const submit = async () => {
let imageId = selectedImageId.value
error.value = null
if (!name.value.trim()) {
error.value = 'Reward name is required.'
return
}
if (cost.value < 1) {
error.value = 'Cost must be at least 1.'
return
}
loading.value = true
// If the selected image is a local upload, upload it first
if (imageId === 'local-upload' && localImageFile.value) {
const formData = new FormData()
formData.append('file', localImageFile.value)
formData.append('type', '2')
formData.append('permanent', 'false')
try {
const resp = await fetch('/api/image/upload', {
method: 'POST',
body: formData,
})
if (!resp.ok) throw new Error('Image upload failed')
const data = await resp.json()
imageId = data.id
} catch (err) {
alert('Failed to upload image.')
loading.value = false
return
}
}
// Now update or create the reward
try {
let resp
if (isEdit.value && props.id) {
resp = await fetch(`/api/reward/${props.id}/edit`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: name.value,
description: description.value,
cost: cost.value,
image_id: imageId,
}),
})
} else {
resp = await fetch('/api/reward/add', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: name.value,
description: description.value,
cost: cost.value,
image_id: imageId,
}),
})
}
if (!resp.ok) throw new Error('Failed to save reward')
await router.push({ name: 'RewardView' })
} catch (err) {
alert('Failed to save reward.')
}
loading.value = false
}
</script>
<style scoped></style>

View File

@@ -0,0 +1,112 @@
<template>
<div class="reward-view">
<MessageBlock v-if="rewardCountRef === 0" message="No rewards">
<span> <button class="round-btn" @click="createReward">Create</button> a reward </span>
</MessageBlock>
<ItemList
v-else
fetchUrl="/api/reward/list"
itemKey="rewards"
:itemFields="REWARD_FIELDS"
imageField="image_id"
deletable
@clicked="(reward: Reward) => $router.push({ name: 'EditReward', params: { id: reward.id } })"
@delete="confirmDeleteReward"
@loading-complete="(count) => (rewardCountRef = count)"
:getItemClass="(item) => `reward`"
>
<template #item="{ item }">
<img v-if="item.image_url" :src="item.image_url" />
<span class="name">{{ item.name }}</span>
<span class="value">{{ item.cost }} pts</span>
</template>
</ItemList>
<FloatingActionButton aria-label="Create Reward" @click="createReward" />
<DeleteModal
:show="showConfirm"
message="Are you sure you want to delete this reward?"
@confirm="deleteReward"
@cancel="showConfirm = false"
/>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import ItemList from '../shared/ItemList.vue'
import MessageBlock from '@/components/shared/MessageBlock.vue'
import '@/assets/button-shared.css'
import FloatingActionButton from '../shared/FloatingActionButton.vue'
import DeleteModal from '../shared/DeleteModal.vue'
import type { Reward } from '@/common/models'
import { REWARD_FIELDS } from '@/common/models'
import '@/assets/view-shared.css'
const $router = useRouter()
const showConfirm = ref(false)
const rewardToDelete = ref<string | null>(null)
const rewardListRef = ref()
const rewardCountRef = ref<number>(-1)
function confirmDeleteReward(rewardId: string) {
rewardToDelete.value = rewardId
showConfirm.value = true
}
const deleteReward = async () => {
if (!rewardToDelete.value) return
try {
const resp = await fetch(`/api/reward/${rewardToDelete.value}`, {
method: 'DELETE',
})
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
// Refresh the reward list after successful delete
rewardListRef.value?.refresh()
} catch (err) {
console.error('Failed to delete reward:', err)
} finally {
showConfirm.value = false
rewardToDelete.value = null
}
}
const createReward = () => {
$router.push({ name: 'CreateReward' })
}
</script>
<style scoped>
.reward-view {
display: flex;
flex-direction: column;
align-items: center;
flex: 1 1 auto;
width: 100%;
height: 100%;
padding: 0;
min-height: 0;
}
.name {
flex: 1;
text-align: left;
font-weight: 600;
}
.value {
min-width: 60px;
text-align: right;
font-weight: 600;
}
:deep(.reward) {
border-color: var(--list-item-border-reward);
background: var(--list-item-bg-reward);
}
</style>