// src/lib/taskStore.svelte.js
import { showSuccess, showError } from './notificationStore.svelte.js';
import { withLoading } from './loadingStore.svelte.js';
// Initialize tasks state
export const tasks = $state([]);
export async function loadTasks() {
return withLoading('tasks', async () => {
try {
const savedTasks = localStorage.getItem('kanban-tasks');
if (savedTasks) {
const parsedTasks = JSON.parse(savedTasks);
if (!Array.isArray(parsedTasks)) {
throw new Error('Invalid task data structure');
}
// Clear existing tasks and add new ones
tasks.length = 0;
tasks.push(...parsedTasks);
} else {
// Load default tasks if nothing in storage
tasks.push(
{ id: 1, title: 'Learn Svelte 5', description: 'Study the new Runes API', status: 'todo', createdAt: new Date().toISOString() },
{ id: 2, title: 'Design components', description: '', status: 'todo', createdAt: new Date().toISOString() },
{ id: 3, title: 'Build Kanban board', description: 'Create the main layout', status: 'inprogress', createdAt: new Date().toISOString() },
{ id: 4, title: 'Setup project', description: 'Initialize SvelteKit', status: 'done', createdAt: new Date().toISOString() }
);
}
} catch (error) {
console.error('Failed to load tasks:', error);
showError(`Failed to load tasks: ${error.message}`);
// Add at least one task as a fallback
tasks.length = 0;
tasks.push(
{ id: 1, title: 'Learn Svelte 5', description: 'Study the new Runes API', status: 'todo', createdAt: new Date().toISOString() }
);
}
});
}
export async function saveTasks() {
try {
localStorage.setItem('kanban-tasks', JSON.stringify(tasks));
return true;
} catch (error) {
console.error('Failed to save tasks:', error);
showError(`Failed to save changes: ${error.message}`);
return false;
}
}
// Initialize task loading and set up auto-save
$effect.root(() => {
// Load tasks on initialization
if (typeof window !== 'undefined') {
loadTasks();
}
// Save tasks whenever they change
$effect(() => {
if (typeof window !== 'undefined' && tasks.length > 0) {
saveTasks();
}
});
});
// Derive filtered task lists
const todoTasks = $derived(tasks.filter(task => task.status === 'todo'));
const inProgressTasks = $derived(tasks.filter(task => task.status === 'inprogress'));
const doneTasks = $derived(tasks.filter(task => task.status === 'done'));
// Getter functions for derived state
export const getTodoTasks = () => todoTasks;
export const getInProgressTasks = () => inProgressTasks;
export const getDoneTasks = () => doneTasks;
export const getTotalTasks = () => tasks.length;
// Tracking for the latest task (for notifications)
const latestTask = $derived(
tasks.length > 0
? [...tasks].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))[0]
: null
);
export const getLatestTask = () => latestTask;
export async function addTask(title, description = '') {
return withLoading('addTask', async () => {
try {
const newTask = {
id: Date.now(),
title,
description,
status: 'todo',
createdAt: new Date().toISOString()
};
tasks.push(newTask);
await saveTasks();
showSuccess(`Task "${title}" added successfully!`);
return newTask;
} catch (error) {
showError(`Failed to add task: ${error.message}`);
throw error;
}
});
}
export async function updateTaskStatus(id, newStatus) {
return withLoading('moveTask', async () => {
try {
const taskIndex = tasks.findIndex(task => task.id === id);
if (taskIndex === -1) {
throw new Error('Task not found');
}
const oldStatus = tasks[taskIndex].status;
const title = tasks[taskIndex].title;
if (oldStatus !== newStatus) {
tasks[taskIndex].status = newStatus;
tasks[taskIndex].updatedAt = new Date().toISOString();
await saveTasks();
showSuccess(`Task "${title}" moved to ${formatStatus(newStatus)}`);
}
return true;
} catch (error) {
showError(`Failed to move task: ${error.message}`);
throw error;
}
});
}
export async function deleteTask(id) {
return withLoading('deleteTask', async () => {
try {
const taskIndex = tasks.findIndex(task => task.id === id);
if (taskIndex === -1) {
throw new Error('Task not found');
}
const title = tasks[taskIndex].title;
tasks.splice(taskIndex, 1);
await saveTasks();
showSuccess(`Task "${title}" deleted`);
return true;
} catch (error) {
showError(`Failed to delete task: ${error.message}`);
throw error;
}
});
}
// Helper function to format status for display
function formatStatus(status) {
switch (status) {
case 'todo': return 'To Do';
case 'inprogress': return 'In Progress';
case 'done': return 'Done';
default: return status;
}
}