Работаю над календарем на главной. Сейчас прила работает

This commit is contained in:
Alexander Andreev 2026-01-03 16:44:34 +03:00
parent 860078f149
commit 6f0b484c90

View File

@ -7,8 +7,10 @@
<p>Loading habits...</p>
</div>
<div v-else-if="todayHabits.length > 0" class="habits-list">
<div v-for="habit in todayHabits" :key="habit.id" class="habit-card">
<div v-else-if="processedHabits.length > 0" class="habits-list">
<div v-for="habit in processedHabits" :key="habit.id" class="habit-card">
<div class="habit-details">
<div class="habit-header">
<span class="habit-name">{{ habit.name }}</span>
<button
v-if="!isCompleteToday(habit)"
@ -20,6 +22,17 @@
</button>
<span v-else class="completed-text"> Done!</span>
</div>
<div class="calendar-grid">
<div
v-for="day in calendarDays"
:key="day.getTime()"
:class="['calendar-cell', getDayStatus(habit, day)]"
>
<span class="date-label">{{ formatDate(day) }}</span>
</div>
</div>
</div>
</div>
</div>
<div v-else class="empty-state">
@ -35,34 +48,117 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ref, computed, onMounted, watch } from 'vue';
// --- Type Definitions ---
interface Habit {
id: number;
name: string;
daysOfWeek: number[];
daysOfWeek: number[]; // 0 = Sunday, 6 = Saturday
completions: { id: number; date: string }[];
createdAt: string;
}
// Internal type for easier lookup
interface HabitWithCompletionSet extends Habit {
completionDates: Set<number>; // Set of timestamps for O(1) lookup
createdAtTimestamp: number;
}
// --- Composables ---
const { user, isAuthenticated } = useAuth();
const api = useApi();
// --- State ---
const allHabits = ref<Habit[]>([]);
const loading = ref(true);
const completing = ref<number | null>(null);
const dayMap = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const todayIndex = new Date().getDay(); // 0 for Sunday, 1 for Monday...
// --- Helpers: Date Normalization & Formatting ---
/**
* Normalizes a date to the start of the day in UTC.
* This is CRITICAL for consistent date comparisons across timezones.
* @param date The date to normalize.
* @returns A new Date object set to 00:00:00 UTC.
*/
const normalizeDateUTC = (date: Date): Date => {
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
};
const today = normalizeDateUTC(new Date());
const todayHabits = computed(() => {
return allHabits.value.filter(h => h.daysOfWeek.includes(todayIndex));
const formatDate = (date: Date): string => {
// Format: "3 янв."
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
};
// --- Computed Properties ---
const processedHabits = computed((): HabitWithCompletionSet[] => {
const todayDayIndex = today.getUTCDay(); // 0 = Sunday, 1 = Monday...
return allHabits.value
.filter(h => h.daysOfWeek.includes(todayDayIndex)) // Only show habits active today
.map(habit => ({
...habit,
// Pre-calculate a Set of completion timestamps for fast O(1) lookups
completionDates: new Set(habit.completions.map(c => normalizeDateUTC(new Date(c.date)).getTime())),
createdAtTimestamp: normalizeDateUTC(new Date(habit.createdAt)).getTime(),
}));
});
const getTodayString = () => new Date().toISOString().split('T')[0];
const calendarDays = computed(() => {
const dates = [];
const currentDayOfWeek = today.getUTCDay(); // 0 = Sun, 1 = Mon...
// Adjust so Monday is 0 and Sunday is 6
const adjustedDay = currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1;
const isCompleteToday = (habit: Habit) => {
const today = getTodayString();
return habit.completions.some(c => c.date.startsWith(today));
// Start date is the Monday of the previous week
const startDate = normalizeDateUTC(new Date(today));
startDate.setUTCDate(startDate.getUTCDate() - adjustedDay - 7);
for (let i = 0; i < 14; i++) {
const d = new Date(startDate);
d.setUTCDate(d.getUTCDate() + i);
dates.push(d);
}
return dates;
});
// --- Methods: Status and Actions ---
const getDayStatus = (habit: HabitWithCompletionSet, date: Date): string => {
const normalizedDate = normalizeDateUTC(date);
const normalizedTimestamp = normalizedDate.getTime();
const dayIndex = normalizedDate.getUTCDay(); // 0 = Sunday
// Rule a) FUTURE
if (normalizedTimestamp > today.getTime()) {
return 'NEUTRAL';
}
// Rule b) BEFORE_CREATED
if (normalizedTimestamp < habit.createdAtTimestamp) {
return 'NEUTRAL';
}
// Rule c) NOT_SCHEDULED
const isActiveDay = habit.daysOfWeek.includes(dayIndex);
if (!isActiveDay) {
return 'NEUTRAL';
}
// Rule d) COMPLETED
if (habit.completionDates.has(normalizedTimestamp)) {
return 'COMPLETED';
}
// Rule e) MISSED
// All previous conditions failed, and we know date <= today.
// Therefore, if it's an active day that wasn't completed, it was missed.
return 'MISSED';
};
const isCompleteToday = (habit: HabitWithCompletionSet) => {
return habit.completionDates.has(today.getTime());
};
const fetchHabits = async () => {
@ -71,7 +167,7 @@ const fetchHabits = async () => {
allHabits.value = await api<Habit[]>('/habits');
} catch (error) {
console.error("Failed to fetch habits:", error);
allHabits.value = []; // Clear habits on error
allHabits.value = [];
} finally {
loading.value = false;
}
@ -89,13 +185,12 @@ const completeHabit = async (habitId: number) => {
}
};
// --- Lifecycle ---
onMounted(() => {
// We only fetch habits if the user is authenticated.
// The redirect logic is handled by the middleware/layout now.
if (isAuthenticated.value) {
fetchHabits();
}
// Watch for auth state changes to fetch habits after login
watch(isAuthenticated, (isAuth) => {
if (isAuth && allHabits.value.length === 0) {
fetchHabits();
@ -113,21 +208,28 @@ onMounted(() => {
.habits-list {
display: flex;
flex-direction: column;
gap: 15px;
gap: 20px;
margin-top: 20px;
}
.habit-card {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
text-align: left;
}
.habit-details {
width: 100%;
}
.habit-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
.habit-name {
font-size: 1.1em;
font-size: 1.2em;
font-weight: bold;
}
.complete-btn {
padding: 8px 12px;
@ -136,6 +238,7 @@ onMounted(() => {
background-color: #88c0d0;
color: #2e3440;
cursor: pointer;
flex-shrink: 0;
}
.completed-text {
color: #a3be8c;
@ -149,4 +252,36 @@ onMounted(() => {
margin-top: 10px;
display: inline-block;
}
/* Calendar Grid Styles */
.calendar-grid {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px; /* Slightly more gap */
}
.calendar-cell {
width: 100%;
aspect-ratio: 1 / 1;
border-radius: 4px;
display: flex;
justify-content: center;
align-items: center;
}
.date-label {
font-size: 0.75em;
color: #4c566a;
}
.calendar-cell.COMPLETED .date-label,
.calendar-cell.MISSED .date-label {
color: white;
}
.calendar-cell.NEUTRAL {
background-color: #eceff4; /* Gray */
}
.calendar-cell.COMPLETED {
background-color: #a3be8c; /* Green */
}
.calendar-cell.MISSED {
background-color: #bf616a; /* Red */
}
</style>