Adding Task Counters and Stats to Your Kanban Board
Introduction to Task Counters and Stats
Welcome to the fifth lesson of our "Building A Kanban Board" course! So far, we've built a functional Kanban board with the ability to display tasks, add new tasks, and move tasks between columns. Our application is already quite useful, but we can enhance it further by adding visual indicators that show how many tasks are in each column and the total number of tasks on our board.
Task counters and statistics are important features in any task management application. They provide users with a quick overview of their workload and progress without requiring them to manually count tasks. For example, seeing that you have 10 tasks in the "To Do" column, 3 in "In Progress," and 15 in "Done" immediately tells you about your current workload and overall progress.
Lesson Objectives
In this lesson, we'll enhance our Kanban board by:
Adding a counter to each column that shows the number of tasks it contains
Creating a stats bar that displays the total number of tasks on the board
Ensuring these counters update automatically when tasks are added or moved
We'll build on the components we've already created and leverage Svelte's reactivity system to keep our counters in sync with the underlying data. By the end of this lesson, your Kanban board will not only be functional but also informative, providing users with valuable insights at a glance.
Let's start by enhancing our task store to track the total number of tasks!
Enhancing the Task Store with Total Count
In our previous lessons, we created a task store that maintains our tasks and provides derived values for filtering tasks by status. Now, we'll add a new derived value to track the total number of tasks across all statuses.
Let's look at the enhanced version of our taskStore.svelte.js file:
JavaScript
// Create initial state with $stateexport const tasks = $state([ { id: 1, title: 'Learn Svelte 5', description: 'Study the new Runes API', status: 'todo' }, { id: 2, title: 'Design components', description: '', status: 'todo' }, { id: 3, title: 'Build Kanban board', description: 'Create the main layout', status: 'inprogress' }, { id: 4, title: 'Setup project', description: 'Initialize SvelteKit', status: 'done' }]);// Derive filtered tasks for each columnconst 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'));const totalTasks = $derived(tasks.length);export const getTodoTasks = () => todoTasks;export const getInProgressTasks = () => inProgressTasks;export const getDoneTasks = () => doneTasks;export const getTotalTasks = () => totalTasks;// Function to add a new taskexport function addTask(title, description = '') { const newTask = { id: Date.now(), title, description, status: 'todo' }; tasks.push(newTask); return newTask;}// Function to update task statusexport function updateTaskStatus(id, newStatus) { const taskIndex = tasks.findIndex(task => task.id === id); if (taskIndex !== -1) { tasks[taskIndex].status = newStatus; }}
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Tracking Total Task Count
The key additions to our task store are:
A new derived value totalTasks that simply returns the length of our tasks array:
const totalTasks = $derived(tasks.length);
A new accessor function getTotalTasks that returns this derived value:
export const getTotalTasks = () => totalTasks;
This is a simple but powerful enhancement. The totalTasks derived value will automatically update whenever tasks are added, removed, or modified, thanks to Svelte's reactivity system. By exporting a getter function, we maintain a consistent interface for accessing our state, which makes our code more maintainable and easier to understand.
Leveraging Svelte's Reactivity
The beauty of derived values is that they're computed automatically based on their dependencies. In this case, totalTasks depends on the length of the tasks array, so it will update automatically whenever tasks are added or removed. This means we don't have to manually update a counter whenever we modify our tasks; Svelte handles that for us.
Now that we have a way to track the total number of tasks, let's update our Column component to display the number of tasks it contains.
Implementing Column Task Counters
Now that our task store can provide the count of tasks in each status category, let's update our Column component to display these counts. This will give users a quick visual indication of how many tasks are in each column.
Here's the updated code for our Column.svelte component:
We've also made some other styling improvements, such as adding a hover effect to the column and making it responsive for smaller screens.
Using the New Render Syntax
Another significant change is the use of the {@render children?.()} syntax instead of directly including the child elements. This is a new feature in Svelte 5 that allows us to pass a function as a prop that returns content to be rendered. The ?.() syntax is a safe call operator that ensures we don't get an error if children is undefined.
This approach gives us more flexibility in how we compose our components. Instead of passing individual tasks as props or using slots, we can pass a function that generates the content we want to display. This is particularly useful for complex components like our Kanban board, where each column might have different content based on the current state of our application.
Now that we've updated our Column component to display task counts, let's create a new component to display overall statistics for our Kanban board.
Creating the StatsBar Component
Now that we have counters for individual columns, let's create a new component to display overall statistics for our Kanban board. This will give users a high-level overview of their tasks without requiring them to add up the counts from each column.
Here's the code for our new StatsBar.svelte component:
This component is designed to be simple and focused on a single responsibility: displaying overall statistics for our Kanban board. Currently, it only shows the total number of tasks, but it's structured in a way that makes it easy to add more statistics in the future if needed.
The design uses a pill-shaped background with a light blue color to make it stand out from other elements on the page without being too distracting. The use of different font weights for the label and value creates a clear visual hierarchy that makes the information easy to scan.
Now that we have our StatsBar component, let's see how to integrate it into our application and connect all the components together.
Using Snippets for Cleaner Code
Now that we have our Column component updated to display task counts and our new StatsBar component, let's update our Board component to use these enhancements. We'll also take advantage of Svelte 5's snippet feature to make our code cleaner and more maintainable.
Here's the updated code for our Board.svelte component:
Snippets are a new feature in Svelte 5 that allow you to define reusable pieces of markup that can be rendered in multiple places. They're similar to components, but they're defined inline and can access the parent component's scope. This makes them ideal for situations like this, where we have a pattern that repeats with slight variations.
In our case, we're using a snippet to define how to render the tasks in each column. This reduces duplication and makes our code more maintainable. If we need to change how tasks are rendered, we only need to update the snippet in one place, rather than in three separate places.
The {@render} syntax is used to render a snippet with specific parameters. In our case, we're passing the tasks for each column and the corresponding status. The snippet then uses these parameters to render the appropriate TaskCard components.
Integrating the StatsBar into the Main Page
Now, let's update our main page component to include the StatsBar:
This integration provides a complete overview of the task management system, with both individual column counts and overall statistics. The StatsBar component is placed prominently at the top, ensuring users can quickly assess their workload.
By leveraging Svelte's reactivity and new features like snippets, we've created a more dynamic and maintainable Kanban board. Users can now enjoy a more informative and visually appealing interface, enhancing their task management experience.
With these enhancements, your Kanban board is not only functional but also provides valuable insights at a glance. Keep exploring and building upon these concepts to create even more powerful applications!
Summary
In this lesson, we've enhanced our Kanban board with visual indicators that provide users with valuable insights about their tasks at a glance. Here's what we've accomplished:
Extended our task store by adding a derived totalTasks value and a getTotalTasks() function that automatically updates when tasks are added or moved
Enhanced the Column component with a visual counter showing the number of tasks in each column
Created a StatsBar component that displays the total number of tasks on the board
Implemented Svelte 5 snippets to reduce code duplication and improve maintainability when rendering task cards
These additions transform our Kanban board from a purely functional tool to an informative dashboard that helps users quickly understand their workload distribution without manually counting tasks.
By leveraging Svelte's reactivity system, we've ensured that all counters update automatically whenever tasks are added, moved, or removed. This creates a seamless user experience where the UI is always in sync with the underlying data.
Our implementation demonstrates the power of derived values in Svelte - simply declaring dependencies allows the framework to handle the complex task of keeping everything updated, making our code both simpler and more robust.