Skip to content

Instantly share code, notes, and snippets.

@jrop
Created November 13, 2018 16:17
Show Gist options
  • Save jrop/34a2149e499c2c7bb36d3f578b46db3c to your computer and use it in GitHub Desktop.
Save jrop/34a2149e499c2c7bb36d3f578b46db3c to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>TODO (lit-html)</title>
</head>
<body>
<div id="root"></div>
<script type="module">
import {
html,
render
} from "https://unpkg.com/lit-html@0.13.0/lit-html.js?module";
const Todo = (searchValue, items) => {
const onAddItem = () => {
const newItems = items.slice();
newItems.push({ text: searchValue });
renderApp("", newItems);
};
const onSearchKeyPress = e => {
const isEnter = e.code === "Enter";
const newItems = items.slice();
if (isEnter) newItems.push({ text: e.target.value });
const searchValue = isEnter ? "" : e.target.value;
renderApp(searchValue, newItems);
};
const onToggleItem = idx => {
items[idx].done = !Boolean(items[idx].done);
renderApp(searchValue, items);
};
const onRemoveItem = (e, idx) => {
e.stopPropagation();
if (
!confirm("Are you sure you want to remove " + items[idx].text + "?")
)
return;
items.splice(idx, 1);
renderApp(searchValue, items);
};
return html`
<div class="todo">
<h1>TODO</h1>
<input .value="${searchValue}" @keypress="${onSearchKeyPress}" />
<button @click="${onAddItem}">Add</button>
<ul>
${
items.map(
(item, idx) =>
html`
<li
class="${item.done && "done"}"
@click="${() => onToggleItem(idx)}"
>
${item.text}
<button @click="${e => onRemoveItem(e, idx)}">
Remove
</button>
</li>
`
)
}
</ul>
<style>
.todo h1 {
font-weight: 100;
}
.todo ul li {
cursor: pointer;
}
.todo ul li.done {
text-decoration: line-through;
}
</style>
</div>
`;
};
const renderApp = (searchValue, items) =>
render(Todo(searchValue, items), document.getElementById("root"));
renderApp("", []);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment