Skip to content

TodoMVC #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions examples/todomvc/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
1 change: 1 addition & 0 deletions examples/todomvc/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
engine-strict=true
13 changes: 13 additions & 0 deletions examples/todomvc/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example

# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock
9 changes: 9 additions & 0 deletions examples/todomvc/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"pluginSearchDirs": ["."],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}
26 changes: 26 additions & 0 deletions examples/todomvc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Todo MVC

An example implementation of the Todo MVC app. It uses SvelteKit's [format actions](https://kit.svelte.dev/docs/form-actions). It uses progressive enhancement, which means the app is still functional without JavaScript - but when it _is_ available, it provides a nicer experience by having optimistic UI updates, for example showing the new TODO item before it actually exists in the database.

## Developing

Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:

```bash
npm run dev

# or start the server and open the app in a new browser tab
npm run dev -- --open
```

## Building

To create a production version of your app:

```bash
npm run build
```

You can preview the production build with `npm run preview`.

> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
28 changes: 28 additions & 0 deletions examples/todomvc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "todomvc",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --plugin-search-dir . --check .",
"format": "prettier --plugin-search-dir . --write ."
},
"devDependencies": {
"@sveltejs/adapter-auto": "^2.0.0",
"@sveltejs/kit": "^1.12.0",
"@sveltejs/package": "^2.0.0",
"prettier": "^2.8.0",
"prettier-plugin-svelte": "^2.8.1",
"publint": "^0.1.9",
"svelte": "^3.57.0",
"svelte-check": "^3.0.1",
"tslib": "^2.4.1",
"typescript": "^4.9.3",
"vite": "^4.0.0"
},
"type": "module"
}
9 changes: 9 additions & 0 deletions examples/todomvc/src/app.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
// and what to do when importing types
declare namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface Platform {}
}
12 changes: 12 additions & 0 deletions examples/todomvc/src/app.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
56 changes: 56 additions & 0 deletions examples/todomvc/src/routes/+page.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import type { Actions, PageServerLoad } from './$types';
import {
addTodo,
clearCompleted,
deleteTodo,
editTodo,
getTodos,
toggleAll,
toggleTodo
} from './db.server';

const wait = async () => {
return new Promise((resolve) => setTimeout(resolve, Math.random() * 1000));
};

export const load = (() => {
return { todos: getTodos() };
}) satisfies PageServerLoad;

export const actions = {
addTodo: async ({ request }) => {
await wait();
const form = await request.formData();
const title = form.get('title') as string;
addTodo(title);
},
deleteTodo: async ({ request }) => {
await wait();
const form = await request.formData();
const id = form.get('id') as string;
deleteTodo(id);
},
editTodo: async ({ request }) => {
await wait();
const form = await request.formData();
const id = form.get('id') as string;
const title = form.get('title') as string;
editTodo(id, title);
},
toggleTodo: async ({ request }) => {
await wait();
const form = await request.formData();
const id = form.get('id') as string;
toggleTodo(id);
},
toggleAll: async ({ request }) => {
await wait();
const form = await request.formData();
const completed = form.get('completed') === 'true';
toggleAll(completed);
},
clearCompleted: async () => {
await wait();
clearCompleted();
}
} satisfies Actions;
182 changes: 182 additions & 0 deletions examples/todomvc/src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
<script lang="ts">
import '../styles.css';
import { enhance } from '$app/forms';
import { page } from '$app/stores';
import type { SubmitFunction } from '@sveltejs/kit';
import type { PageData } from './$types';
import type { Todo } from './db.server';

export let data: PageData;

let inserting: Todo[] = [];
let deleting: Todo[] = [];
let updating: Todo[] = [];

const pending = (todo: Todo) => {
return deleting.includes(todo) || inserting.includes(todo) || updating.includes(todo);
};

$: todos = data.todos
.filter((item) => !deleting.includes(item))
.map((item) => updating.find((u) => u.id === item.id) ?? item)
.concat(inserting);
$: currentFilter = $page.url.searchParams.has('active')
? 'active'
: $page.url.searchParams.has('completed')
? 'completed'
: 'all';
$: filtered =
currentFilter === 'all'
? todos
: currentFilter === 'completed'
? todos.filter((item) => item.completed)
: todos.filter((item) => !item.completed);
$: numActive = todos.filter((item) => !item.completed).length;
$: numCompleted = todos.filter((item) => item.completed).length;

const addTodo: SubmitFunction = ({ data, form }) => {
const todo = {
title: data.get('title') as string,
completed: false,
id: 'temporary-' + Math.random()
};
form.reset();
inserting.push(todo);
inserting = inserting;
return async ({ result, update }) => {
if (result.type === 'success') {
await update();
}
inserting = inserting.filter((item) => item !== todo);
};
};

const toggleTodo: SubmitFunction = ({ data: formData }) => {
const todo = data.todos.find((item) => item.id === formData.get('id'))!;
const updated = { ...todo, completed: !todo.completed };
updating.push(updated);
updating = updating;
return async ({ result, update }) => {
if (result.type === 'success') {
await update();
}
updating = updating.filter((item) => item !== updated);
};
};

const editTodo: SubmitFunction = ({ data: formData }) => {
const todo = data.todos.find((item) => item.id === formData.get('id'))!;
const updated = { ...todo, title: formData.get('title') as string };
updating.push(updated);
updating = updating;
return async ({ result, update }) => {
if (result.type === 'success') {
await update();
}
updating = updating.filter((item) => item !== updated);
};
};

const deleteTodo: SubmitFunction = ({ data: formData }) => {
const todo = data.todos.find((item) => item.id === formData.get('id'))!;
deleting.push(todo);
deleting = deleting;
return async ({ result, update }) => {
if (result.type === 'success') {
await update();
}
deleting = deleting.filter((item) => item !== todo);
};
};
</script>

<svelte:head>
<title>Todos</title>
<meta name="description" content="A todo list app" />
</svelte:head>

<section class="todoapp">
<header class="header">
<h1>todos</h1>
<form method="post" action="?/addTodo" use:enhance={addTodo}>
<input
name="title"
class="new-todo"
placeholder="What needs to be done?"
autofocus
required
/>
</form>
</header>

{#if todos.length > 0}
<section class="main">
<form method="post" action="?/toggleAll">
<input type="hidden" name="completed" value={numCompleted === todos.length ? '' : 'true'} />
<button
id="toggle-all"
class="toggle-all {numCompleted === todos.length ? 'checked' : ''}"
aria-label="Mark all as {numCompleted === todos.length ? 'not done' : 'done'}"
/>
</form>

<ul class="todo-list">
{#each filtered as todo (todo.id + (pending(todo) ? 'pending' : ''))}
<li class:completed={todo.completed} class:pending={pending(todo)}>
<form action="?/toggleTodo" method="post" use:enhance={toggleTodo}>
<input type="hidden" name="id" value={todo.id} />
<input type="hidden" name="completed" value={todo.completed ? '' : 'true'} />
<button
class="toggle"
disabled={pending(todo)}
aria-label="Mark todo as {todo.completed ? 'not done' : 'done'}"
/>
</form>

<form class="text" action="?/editTodo" method="post" use:enhance={editTodo}>
<input type="hidden" name="id" value={todo.id} />
<input
aria-label="Edit todo"
type="text"
name="title"
class="edit"
value={todo.title}
readonly={todo.completed || pending(todo)}
required
/>
<button class="save" aria-label="Save todo" />
</form>

<form action="?/deleteTodo" method="post" use:enhance={deleteTodo}>
<input type="hidden" name="id" value={todo.id} />
<button class="destroy" aria-label="Delete todo" disabled={pending(todo)} />
</form>
</li>
{/each}
</ul>

<footer class="footer">
<span class="todo-count">
<strong>{numActive}</strong>
{numActive === 1 ? 'item' : 'items'} left
</span>

<ul class="filters">
<li><a class:selected={currentFilter === 'all'} href="/">All</a></li>
<li>
<a class:selected={currentFilter === 'active'} href="/?active">Active</a>
</li>
<li>
<a class:selected={currentFilter === 'completed'} href="/?completed">Completed</a>
</li>
</ul>

{#if numCompleted}
<form method="post" action="?/clearCompleted" use:enhance>
<button class="clear-completed"> Clear completed </button>
</form>
{/if}
</footer>
</section>
{/if}
</section>
Loading