Notes
A notes app with filters, search, an editor and undo, the same screen in every framework.
// Vanilla: the create* factories the elements are built on.
import createButton from "material/components/button";
import createButtonGroup from "material/components/button-group";
import createCard from "material/components/card";
import createChips from "material/components/chips";
import createDialog from "material/components/dialog";
import createBottomSheet from "material/components/bottom-sheet";
import createExtendedFab from "material/components/extended-fab";
import createIconButton from "material/components/icon-button";
import createSearch from "material/components/search";
import createSnackbar from "material/components/snackbar";
import createTextField from "material/components/text-field";
import { DEFAULTS, LABELS, ADD_ICON, DELETE_ICON, GRID_ICON, LIST_ICON, PIN_ICON, labelOf, status, visible, type LabelId, type Note, type State } from "./shared";
const s: State = { ...DEFAULTS, notes: DEFAULTS.notes.map((n) => ({ ...n, labels: [...n.labels] })) };
/** What a chips or button-group change carries, whichever shape the payload takes. */
const asStrings = (value: string | string[] | null): string[] => (Array.isArray(value) ? value : value ? [value] : []);
const narrow = matchMedia("(max-width: 600px)").matches;
const app = document.getElementById("app")!;
const shell = Object.assign(document.createElement("section"), { className: "notes" });
// The bar: search on the left, the view toggle on the right.
const bar = Object.assign(document.createElement("div"), { className: "notes__bar" });
const search = createSearch({ placeholder: "Search notes" });
search.on("input", ({ value }: { value: string }) => {
s.query = value;
render();
});
const views = createButtonGroup({
kind: "connected",
selection: "single",
required: true,
buttons: [
{ icon: GRID_ICON, ariaLabel: "Grid view", value: "grid", selected: s.view === "grid" },
{ icon: LIST_ICON, ariaLabel: "List view", value: "list", selected: s.view === "list" },
],
});
views.on("change", ({ value }: { value: string | string[] | null }) => {
s.view = asStrings(value)[0] === "list" ? "list" : "grid";
render();
});
bar.append(search.element, views.element);
// The label filter, above the grid. Its own value is the one source of truth,
// so a card chip and this row agree.
const filters = createChips({ chips: LABELS.map(({ value, text }) => ({ type: "filter" as const, label: text, value, selected: s.filter.includes(value) })) });
filters.on("change", ({ value }: { value: string | string[] | null }) => {
s.filter = asStrings(value) as LabelId[];
render();
});
const statusLine = Object.assign(document.createElement("output"), { className: "notes__status" });
statusLine.setAttribute("role", "status");
const pinned = Object.assign(document.createElement("section"), { className: "notes__section" });
const rest = Object.assign(document.createElement("section"), { className: "notes__section" });
// One card. Its chips carry the note's labels; clicking one filters by it.
const card = (note: Note): ReturnType<typeof createCard> => {
const pin = createIconButton({
icon: PIN_ICON,
toggle: true,
selected: note.pinned,
ariaLabel: `Pin ${note.title}`,
});
pin.on("change", () => {
note.pinned = !note.pinned;
render();
});
const chips =
note.labels.length > 0
? createChips({
chips: note.labels.map((id) => ({ type: "filter" as const, label: labelOf(id), value: id, selected: s.filter.includes(id) })),
})
: null;
if (chips) {
chips.on("change", ({ value }: { value: string | string[] | null }) => {
s.filter = asStrings(value) as LabelId[];
render();
});
}
const open = createButton({ text: "Open", variant: "text", ariaLabel: `Open ${note.title}` });
open.on("click", () => editorOpen(note));
const remove = createIconButton({ icon: DELETE_ICON, ariaLabel: `Delete ${note.title}` });
remove.on("click", () => deleteNote(note));
const actions = Object.assign(document.createElement("div"), { className: "notes__card-actions" });
actions.append(open.element, remove.element);
return createCard({
header: { title: note.title, action: pin.element },
content: { children: [Object.assign(document.createElement("p"), { textContent: note.text }), ...(chips ? [chips.element] : [])] },
actions: { actions: [actions] },
});
};
// The editor: a dialog on a wide frame, a bottom sheet on a narrow one, the same
// content in either.
const fields = Object.assign(document.createElement("div"), { className: "notes__fields" });
const titleField = createTextField({ label: "Title" });
const textField = createTextField({ label: "Note", type: "multiline" });
let editorChips = createChips({ chips: [] });
let editorLabels: LabelId[] = [];
const setEditorChips = (labels: LabelId[]): void => {
editorLabels = [...labels];
const next = createChips({ chips: LABELS.map(({ value, text }) => ({ type: "filter" as const, label: text, value, selected: labels.includes(value) })) });
next.on("change", ({ value }: { value: string | string[] | null }) => {
editorLabels = asStrings(value) as LabelId[];
});
editorChips.element.replaceWith(next.element);
editorChips = next;
};
fields.append(titleField.element, textField.element, editorChips.element);
let editing: Note | null = null;
// The dialog's own buttons close it; these handlers only apply the edit.
const save = (): void => {
if (!editing) return;
editing.title = titleField.getValue();
editing.text = textField.getValue();
editing.labels = [...editorLabels];
if (!s.notes.includes(editing)) s.notes = [...s.notes, editing];
if (narrow) editor.close();
render();
};
// On a narrow frame the sheet takes the same buttons the dialog configures.
const sheetActions = Object.assign(document.createElement("div"), { className: "notes__editor-actions" });
const sheetButton = (text: string, variant: string | undefined, run: () => void) => {
const button = createButton(variant ? { text, variant } : { text });
button.on("click", () => run());
return button;
};
const sheetClose = (): void => {
editor.close();
};
const dialog = narrow
? null
: createDialog({
title: "Edit note",
buttons: [
{ text: "Delete", variant: "outlined", onClick: () => { if (editing && s.notes.includes(editing)) deleteNote(editing); } },
{ text: "Cancel", variant: "text" },
{ text: "Save", onClick: () => save() },
],
});
const editor = narrow
? createBottomSheet({ title: "Edit note", variant: "modal", content: fields })
: dialog!;
if (dialog) (dialog as unknown as { structure: { content: HTMLElement } }).structure.content.append(fields);
if (narrow) {
sheetActions.append(
sheetButton("Delete", "outlined", () => {
if (!editing) return;
if (s.notes.includes(editing)) deleteNote(editing);
else editor.close();
}).element,
sheetButton("Cancel", "text", sheetClose).element,
sheetButton("Save", undefined, () => save()).element,
);
fields.append(sheetActions);
}
// The factory dialog shows its content until it has been opened once; the
// element the other variants use hides itself. Keep the factory one out of the
// accessibility tree until it opens, the same as theirs.
editor.element.hidden = true;
editor.on("close", () => (editor.element.hidden = true));
const editorOpen = (note: Note | null): void => {
editing = note ?? { id: crypto.randomUUID(), title: "", text: "", labels: [], pinned: false };
editor.setTitle(note ? "Edit note" : "New note");
titleField.setValue(editing.title);
textField.setValue(editing.text);
setEditorChips(editing.labels);
editor.element.hidden = false;
editor.open();
};
const fab = createExtendedFab({ icon: ADD_ICON, text: "New note", ariaLabel: "New note" });
fab.on("click", () => editorOpen(null));
// Deleting shows the snackbar; Undo puts the note back where it was. The factory
// snackbar joins the top layer, as the element always does: it shows in place and
// hides on the popover's own timer. Unlike the element's, the factory toast stays
// exposed in the accessibility tree until it has been shown once, so it is also
// kept out of it until then (reported to the material team).
const snackbar = createSnackbar({ message: "Note deleted", action: "Undo", duration: 4000, dismissible: true, layer: "top" });
snackbar.element.style.display = "none";
snackbar.on("close", () => (snackbar.element.style.display = "none"));
let lastDeleted: { note: Note; at: number } | null = null;
const deleteNote = (note: Note): void => {
lastDeleted = { note, at: s.notes.indexOf(note) };
s.notes = s.notes.filter((n) => n !== note);
if (editor.isOpen?.()) editor.close();
render();
snackbar.element.style.display = "";
snackbar.show();
};
snackbar.on("action", () => {
if (!lastDeleted) return;
s.notes = [...s.notes.slice(0, lastDeleted.at), lastDeleted.note, ...s.notes.slice(lastDeleted.at)];
lastDeleted = null;
render();
});
const grid = (notes: Note[]): HTMLElement => {
const el = Object.assign(document.createElement("div"), { className: `notes__grid ${s.view}` });
el.append(...notes.map((note) => card(note).element));
return el;
};
const render = (): void => {
const shown = visible(s);
statusLine.textContent = status(s);
filters.setValue(s.filter);
const pinnedNotes = shown.filter((n) => n.pinned);
const otherNotes = shown.filter((n) => !n.pinned);
pinned.hidden = pinnedNotes.length === 0;
pinned.replaceChildren(Object.assign(document.createElement("h2"), { textContent: "Pinned" }), grid(pinnedNotes));
// One empty state for the page, as the other variants: the message shows only
// when nothing at all matches, and the Notes section hides when every visible
// note is pinned.
if (shown.length === 0) {
rest.hidden = false;
rest.replaceChildren(Object.assign(document.createElement("p"), { className: "notes__empty", textContent: "No notes match." }));
} else {
rest.hidden = otherNotes.length === 0;
rest.replaceChildren(Object.assign(document.createElement("h2"), { textContent: "Notes" }), grid(otherNotes));
}
};
shell.append(bar, filters.element, statusLine, pinned, rest, fab.element, editor.element, snackbar.element);
app.append(shell);
render();
// The state every variant of this example shares, the notes it starts from, and
// how the state is described. check.ts drives it, and check-examples compares
// what each framework shows.
export type LabelId = "ideas" | "shopping" | "work" | "travel";
export const LABELS: { value: LabelId; text: string }[] = [
{ value: "ideas", text: "Ideas" },
{ value: "shopping", text: "Shopping" },
{ value: "work", text: "Work" },
{ value: "travel", text: "Travel" },
];
export interface Note {
id: string;
title: string;
text: string;
labels: LabelId[];
pinned: boolean;
}
export const SEED_NOTES: Note[] = [
{ id: "sauce", title: "Pasta sauce", text: "Fry garlic in olive oil, add torn tomatoes, simmer twenty minutes. Basil at the end.", labels: ["ideas"], pinned: false },
{ id: "groceries", title: "Weekend groceries", text: "Bread, oat milk, lemons, coffee, the good chocolate.", labels: ["shopping"], pinned: false },
{ id: "meeting", title: "Meeting points", text: "Roadmap, hiring plan, support queue. Write down every decision.", labels: ["work"], pinned: true },
{ id: "packing", title: "Packing list", text: "Two shirts, one warm layer, charger, toothbrush, passport.", labels: ["travel", "shopping"], pinned: true },
{ id: "gifts", title: "Gift ideas", text: "A plant for the balcony, a cookbook for the baker, ink for the letter writer.", labels: ["ideas"], pinned: false },
{ id: "walk", title: "City walk route", text: "Bridge, old square, river bank, market on the way back.", labels: ["travel"], pinned: false },
{ id: "priorities", title: "Week priorities", text: "Ship the release notes, review the open pulls, plan Friday morning.", labels: ["work"], pinned: false },
{ id: "prompts", title: "Story prompts", text: "A lighthouse that answers letters. A market that only opens at dusk.", labels: ["ideas"], pinned: false },
{ id: "borrow", title: "Books to borrow", text: "The gardening one, the poetry anthology, the train atlas.", labels: ["shopping"], pinned: false },
{ id: "repairs", title: "Flat repairs", text: "Fix the kitchen drawer, replace the hall bulb, defrost the freezer.", labels: ["work"], pinned: false },
{ id: "sourdough", title: "Sourdough steps", text: "Feed the starter tonight, shape in the morning, bake with steam.", labels: ["ideas"], pinned: false },
];
export interface State {
notes: Note[];
filter: LabelId[];
query: string;
view: "grid" | "list";
}
export const DEFAULTS: State = {
notes: SEED_NOTES.map((note) => ({ ...note, labels: [...note.labels] })),
filter: [],
query: "",
view: "grid",
};
export const labelOf = (id: LabelId): string => LABELS.find((l) => l.value === id)!.text;
/** The notes the grid shows: the filter's labels, then the search's words. */
export const visible = (s: State): Note[] =>
s.notes.filter(
(n) =>
(s.filter.length === 0 || n.labels.some((l) => s.filter.includes(l))) &&
(s.query === "" || `${n.title} ${n.text}`.toLowerCase().includes(s.query.toLowerCase())),
);
export const status = (s: State): string => `Showing ${visible(s).length} of ${s.notes.length} notes.`;
// The icons the interface uses, as the components take them: Material Symbols
// (Apache 2.0, fonts.google.com/icons), the same files scripts/icons.ts fetches.
export const ADD_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-440H240q-17 0-28.5-11.5T200-480q0-17 11.5-28.5T240-520h200v-200q0-17 11.5-28.5T480-760q17 0 28.5 11.5T520-720v200h200q17 0 28.5 11.5T760-480q0 17-11.5 28.5T720-440H520v200q0 17-11.5 28.5T480-200q-17 0-28.5-11.5T440-240v-200Z"/></svg>';
export const PIN_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40v280Zm-286 80h252l-46-46v-314H400v314l-46 46Zm126 0Z"/></svg>';
export const DELETE_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M280-120q-33 0-56.5-23.5T200-200v-520q-17 0-28.5-11.5T160-760q0-17 11.5-28.5T200-800h160q0-17 11.5-28.5T400-840h160q17 0 28.5 11.5T600-800h160q17 0 28.5 11.5T800-760q0 17-11.5 28.5T760-720v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM428.5-291.5Q440-303 440-320v-280q0-17-11.5-28.5T400-640q-17 0-28.5 11.5T360-600v280q0 17 11.5 28.5T400-280q17 0 28.5-11.5Zm160 0Q600-303 600-320v-280q0-17-11.5-28.5T560-640q-17 0-28.5 11.5T520-600v280q0 17 11.5 28.5T560-280q17 0 28.5-11.5ZM280-720v520-520Z"/></svg>';
export const GRID_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M120-520v-320h320v320H120Zm0 400v-320h320v320H120Zm400-400v-320h320v320H520Zm0 400v-320h320v320H520Z"/></svg>';
export const LIST_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M360-680v-80h480v80H360Zm0 240v-80h480v80H360Zm0 240v-80h480v80H360ZM200-680q-17 0-28.5-11.5T160-720q0-17 11.5-28.5T200-760q17 0 28.5 11.5T240-720q0 17-11.5 28.5T200-680Zm0 240q-17 0-28.5-11.5T160-480q0-17 11.5-28.5T200-520q17 0 28.5 11.5T240-480q0 17-11.5 28.5T200-440Zm0 240q-17 0-28.5-11.5T160-240q0-17 11.5-28.5T200-280q17 0 28.5 11.5T240-240q0 17-11.5 28.5T200-200Z"/></svg>';
// Web components: the elements themselves, no framework.
import "material/elements/css";
import { defineAll } from "material/elements";
import { DEFAULTS, LABELS, ADD_ICON, DELETE_ICON, GRID_ICON, LIST_ICON, PIN_ICON, labelOf, status, visible, type LabelId, type Note, type State } from "./shared";
defineAll();
const s: State = { ...DEFAULTS, notes: DEFAULTS.notes.map((n) => ({ ...n, labels: [...n.labels] })) };
const narrow = matchMedia("(max-width: 600px)").matches;
const app = document.getElementById("app")!;
const shell = Object.assign(document.createElement("section"), { className: "notes" });
// The bar: search on the left, the view toggle on the right.
const bar = Object.assign(document.createElement("div"), { className: "notes__bar" });
const search = document.createElement("m-search");
search.setAttribute("placeholder", "Search notes");
search.addEventListener("input", (e) => {
s.query = (e as CustomEvent<{ value: string }>).detail.value;
render();
});
const views = document.createElement("m-button-group");
views.setAttribute("kind", "connected");
views.setAttribute("selection", "single");
views.setAttribute("required", "true");
for (const [value, icon, label] of [["grid", GRID_ICON, "Grid view"], ["list", LIST_ICON, "List view"]] as const) {
const item = document.createElement("m-button-group-item");
item.setAttribute("icon", icon);
item.setAttribute("value", value);
item.setAttribute("aria-label", label);
if (s.view === value) item.setAttribute("selected", "");
views.append(item);
}
views.addEventListener("change", (e) => {
s.view = (e as CustomEvent<{ value: string }>).detail.value === "list" ? "list" : "grid";
render();
});
bar.append(search, views);
// The label filter, above the grid. Its chips are declared once; after that its
// own value is the one source of truth, so a card chip and this row agree.
const filters = document.createElement("m-chips");
for (const { value, text } of LABELS) {
const chip = document.createElement("m-chip");
chip.setAttribute("label", text);
chip.setAttribute("value", value);
filters.append(chip);
}
filters.addEventListener("change", (e) => {
s.filter = (e as CustomEvent<{ value: string[] }>).detail.value as LabelId[];
render();
});
const statusLine = Object.assign(document.createElement("output"), { className: "notes__status" });
statusLine.setAttribute("role", "status");
const pinned = Object.assign(document.createElement("section"), { className: "notes__section" });
const rest = Object.assign(document.createElement("section"), { className: "notes__section" });
// One card. Its chips carry the note's labels; clicking one filters by it.
const card = (note: Note): HTMLElement => {
const el = document.createElement("m-card");
el.setAttribute("headline", note.title);
const pin = document.createElement("m-icon-button");
pin.setAttribute("slot", "header-action");
pin.setAttribute("toggle", "");
if (note.pinned) pin.setAttribute("selected", "");
pin.setAttribute("icon", PIN_ICON);
pin.setAttribute("aria-label", `Pin ${note.title}`);
pin.addEventListener("change", () => {
note.pinned = !note.pinned;
render();
});
el.append(pin);
const preview = Object.assign(document.createElement("p"), { textContent: note.text });
el.append(preview);
if (note.labels.length > 0) {
const chips = document.createElement("m-chips");
for (const id of note.labels) {
const chip = document.createElement("m-chip");
chip.setAttribute("label", labelOf(id));
chip.setAttribute("value", id);
if (s.filter.includes(id)) chip.setAttribute("selected", "");
chips.append(chip);
}
chips.addEventListener("change", (e) => {
s.filter = (e as CustomEvent<{ value: string[] }>).detail.value as LabelId[];
render();
});
el.append(chips);
}
const actions = document.createElement("div");
actions.setAttribute("slot", "actions");
actions.className = "notes__card-actions";
const open = document.createElement("m-button");
open.setAttribute("variant", "text");
open.setAttribute("aria-label", `Open ${note.title}`);
open.textContent = "Open";
open.addEventListener("click", () => editNote(note));
const remove = document.createElement("m-icon-button");
remove.setAttribute("icon", DELETE_ICON);
remove.setAttribute("aria-label", `Delete ${note.title}`);
remove.addEventListener("click", () => deleteNote(note));
actions.append(open, remove);
el.append(actions);
return el;
};
// The editor: a dialog on a wide frame, a bottom sheet on a narrow one, the same
// content in either.
const fields = Object.assign(document.createElement("div"), { className: "notes__fields" });
const titleField = document.createElement("m-text-field");
titleField.setAttribute("label", "Title");
const textField = document.createElement("m-text-field");
textField.setAttribute("label", "Note");
textField.setAttribute("multiline", "");
// The editor's label chips: a fresh element each time the editor opens, so its
// selection starts from the note being edited.
let editorChips: HTMLElement & { value: string } = document.createElement("m-chips") as HTMLElement & { value: string };
let editorLabels: LabelId[] = [];
const setEditorChips = (labels: LabelId[]): void => {
editorLabels = [...labels];
const next = document.createElement("m-chips") as HTMLElement & { value: string };
for (const { value, text } of LABELS) {
const chip = document.createElement("m-chip");
chip.setAttribute("label", text);
chip.setAttribute("value", value);
if (labels.includes(value)) chip.setAttribute("selected", "");
next.append(chip);
}
next.addEventListener("change", (e) => {
editorLabels = (e as CustomEvent<{ value: string[] }>).detail.value as LabelId[];
});
editorChips.replaceWith(next);
editorChips = next;
};
fields.append(titleField, textField, editorChips);
const editorActions = Object.assign(document.createElement("div"), { className: "notes__editor-actions" });
const editorDelete = document.createElement("m-button");
editorDelete.setAttribute("variant", "outlined");
editorDelete.textContent = "Delete";
editorDelete.addEventListener("click", () => {
// A note that was never saved is discarded; there is nothing to delete or undo.
if (!editing) return;
if (s.notes.includes(editing)) deleteNote(editing);
else editorClose();
});
const editorCancel = document.createElement("m-button");
editorCancel.setAttribute("variant", "text");
editorCancel.textContent = "Cancel";
const editorSave = document.createElement("m-button");
editorSave.textContent = "Save";
editorActions.append(editorDelete, editorCancel, editorSave);
let editing: Note | null = null;
const editor = (narrow ? document.createElement("m-bottom-sheet") : document.createElement("m-dialog")) as HTMLElement & { open: boolean };
if (narrow) editor.setAttribute("modal", "");
const editorOpen = (note: Note | null): void => {
editing = note ?? { id: crypto.randomUUID(), title: "", text: "", labels: [], pinned: false };
editor.setAttribute("headline", note ? "Edit note" : "New note");
titleField.value = editing.title;
textField.value = editing.text;
setEditorChips(editing.labels);
editor.open = true;
};
const editorClose = (): void => {
editor.open = false;
};
editorCancel.addEventListener("click", editorClose);
editor.addEventListener("close", editorClose);
editorSave.addEventListener("click", () => {
editing!.title = String(titleField.value || "");
editing!.text = String(textField.value || "");
editing!.labels = [...editorLabels];
if (!s.notes.includes(editing!)) s.notes = [...s.notes, editing!];
editorClose();
render();
});
const editNote = (note: Note): void => editorOpen(note);
const newNote = (): void => editorOpen(null);
const fab = document.createElement("m-extended-fab");
fab.setAttribute("icon", ADD_ICON);
fab.setAttribute("aria-label", "New note");
fab.textContent = "New note";
fab.addEventListener("click", newNote);
// Deleting shows the snackbar; Undo puts the note back where it was.
const snackbar = document.createElement("m-snackbar");
snackbar.setAttribute("message", "Note deleted");
snackbar.setAttribute("action", "Undo");
snackbar.setAttribute("duration", "4000");
snackbar.setAttribute("dismissible", "");
let lastDeleted: { note: Note; at: number } | null = null;
const deleteNote = (note: Note): void => {
lastDeleted = { note, at: s.notes.indexOf(note) };
s.notes = s.notes.filter((n) => n !== note);
editorClose();
render();
snackbar.show();
};
snackbar.addEventListener("action", () => {
if (!lastDeleted) return;
s.notes = [...s.notes.slice(0, lastDeleted.at), lastDeleted.note, ...s.notes.slice(lastDeleted.at)];
lastDeleted = null;
render();
});
const grid = (notes: Note[]): HTMLElement => {
const el = Object.assign(document.createElement("div"), { className: `notes__grid ${s.view}` });
el.append(...notes.map(card));
return el;
};
const render = (): void => {
const shown = visible(s);
statusLine.textContent = status(s);
filters.value = s.filter.join(",");
const pinnedNotes = shown.filter((n) => n.pinned);
const otherNotes = shown.filter((n) => !n.pinned);
pinned.hidden = pinnedNotes.length === 0;
pinned.replaceChildren(
Object.assign(document.createElement("h2"), { textContent: "Pinned" }),
grid(pinnedNotes),
);
// One empty state for the page: the message shows only when nothing at all
// matches, and the Notes section hides when every visible note is pinned.
if (shown.length === 0) {
rest.hidden = false;
rest.replaceChildren(Object.assign(document.createElement("p"), { className: "notes__empty", textContent: "No notes match." }));
} else {
rest.hidden = otherNotes.length === 0;
rest.replaceChildren(
Object.assign(document.createElement("h2"), { textContent: "Notes" }),
grid(otherNotes),
);
}
};
if (narrow) {
editor.append(fields, editorActions);
} else {
editor.append(fields);
editorActions.setAttribute("slot", "actions");
editor.append(editorActions);
}
shell.append(bar, filters, statusLine, pinned, rest, fab, editor, snackbar);
app.append(shell);
render();
// The state every variant of this example shares, the notes it starts from, and
// how the state is described. check.ts drives it, and check-examples compares
// what each framework shows.
export type LabelId = "ideas" | "shopping" | "work" | "travel";
export const LABELS: { value: LabelId; text: string }[] = [
{ value: "ideas", text: "Ideas" },
{ value: "shopping", text: "Shopping" },
{ value: "work", text: "Work" },
{ value: "travel", text: "Travel" },
];
export interface Note {
id: string;
title: string;
text: string;
labels: LabelId[];
pinned: boolean;
}
export const SEED_NOTES: Note[] = [
{ id: "sauce", title: "Pasta sauce", text: "Fry garlic in olive oil, add torn tomatoes, simmer twenty minutes. Basil at the end.", labels: ["ideas"], pinned: false },
{ id: "groceries", title: "Weekend groceries", text: "Bread, oat milk, lemons, coffee, the good chocolate.", labels: ["shopping"], pinned: false },
{ id: "meeting", title: "Meeting points", text: "Roadmap, hiring plan, support queue. Write down every decision.", labels: ["work"], pinned: true },
{ id: "packing", title: "Packing list", text: "Two shirts, one warm layer, charger, toothbrush, passport.", labels: ["travel", "shopping"], pinned: true },
{ id: "gifts", title: "Gift ideas", text: "A plant for the balcony, a cookbook for the baker, ink for the letter writer.", labels: ["ideas"], pinned: false },
{ id: "walk", title: "City walk route", text: "Bridge, old square, river bank, market on the way back.", labels: ["travel"], pinned: false },
{ id: "priorities", title: "Week priorities", text: "Ship the release notes, review the open pulls, plan Friday morning.", labels: ["work"], pinned: false },
{ id: "prompts", title: "Story prompts", text: "A lighthouse that answers letters. A market that only opens at dusk.", labels: ["ideas"], pinned: false },
{ id: "borrow", title: "Books to borrow", text: "The gardening one, the poetry anthology, the train atlas.", labels: ["shopping"], pinned: false },
{ id: "repairs", title: "Flat repairs", text: "Fix the kitchen drawer, replace the hall bulb, defrost the freezer.", labels: ["work"], pinned: false },
{ id: "sourdough", title: "Sourdough steps", text: "Feed the starter tonight, shape in the morning, bake with steam.", labels: ["ideas"], pinned: false },
];
export interface State {
notes: Note[];
filter: LabelId[];
query: string;
view: "grid" | "list";
}
export const DEFAULTS: State = {
notes: SEED_NOTES.map((note) => ({ ...note, labels: [...note.labels] })),
filter: [],
query: "",
view: "grid",
};
export const labelOf = (id: LabelId): string => LABELS.find((l) => l.value === id)!.text;
/** The notes the grid shows: the filter's labels, then the search's words. */
export const visible = (s: State): Note[] =>
s.notes.filter(
(n) =>
(s.filter.length === 0 || n.labels.some((l) => s.filter.includes(l))) &&
(s.query === "" || `${n.title} ${n.text}`.toLowerCase().includes(s.query.toLowerCase())),
);
export const status = (s: State): string => `Showing ${visible(s).length} of ${s.notes.length} notes.`;
// The icons the interface uses, as the components take them: Material Symbols
// (Apache 2.0, fonts.google.com/icons), the same files scripts/icons.ts fetches.
export const ADD_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-440H240q-17 0-28.5-11.5T200-480q0-17 11.5-28.5T240-520h200v-200q0-17 11.5-28.5T480-760q17 0 28.5 11.5T520-720v200h200q17 0 28.5 11.5T760-480q0 17-11.5 28.5T720-440H520v200q0 17-11.5 28.5T480-200q-17 0-28.5-11.5T440-240v-200Z"/></svg>';
export const PIN_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40v280Zm-286 80h252l-46-46v-314H400v314l-46 46Zm126 0Z"/></svg>';
export const DELETE_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M280-120q-33 0-56.5-23.5T200-200v-520q-17 0-28.5-11.5T160-760q0-17 11.5-28.5T200-800h160q0-17 11.5-28.5T400-840h160q17 0 28.5 11.5T600-800h160q17 0 28.5 11.5T800-760q0 17-11.5 28.5T760-720v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM428.5-291.5Q440-303 440-320v-280q0-17-11.5-28.5T400-640q-17 0-28.5 11.5T360-600v280q0 17 11.5 28.5T400-280q17 0 28.5-11.5Zm160 0Q600-303 600-320v-280q0-17-11.5-28.5T560-640q-17 0-28.5 11.5T520-600v280q0 17 11.5 28.5T560-280q17 0 28.5-11.5ZM280-720v520-520Z"/></svg>';
export const GRID_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M120-520v-320h320v320H120Zm0 400v-320h320v320H120Zm400-400v-320h320v320H520Zm0 400v-320h320v320H520Z"/></svg>';
export const LIST_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M360-680v-80h480v80H360Zm0 240v-80h480v80H360Zm0 240v-80h480v80H360ZM200-680q-17 0-28.5-11.5T160-720q0-17 11.5-28.5T200-760q17 0 28.5 11.5T240-720q0 17-11.5 28.5T200-680Zm0 240q-17 0-28.5-11.5T160-480q0-17 11.5-28.5T200-520q17 0 28.5 11.5T240-480q0 17-11.5 28.5T200-440Zm0 240q-17 0-28.5-11.5T160-240q0-17 11.5-28.5T200-280q17 0 28.5 11.5T240-240q0 17-11.5 28.5T200-200Z"/></svg>';
// React: material/react wraps the same elements.
import { useRef, useState } from "react";
import type { SnackbarElement } from "material/elements";
import { BottomSheet, Button, ButtonGroup, ButtonGroupItem, Card, Chip, Chips, Dialog, ExtendedFab, IconButton, Search, Snackbar, TextField } from "material/react";
import { DEFAULTS, LABELS, ADD_ICON, DELETE_ICON, GRID_ICON, LIST_ICON, PIN_ICON, labelOf, status, visible, type LabelId, type Note, type State } from "./shared";
const narrow = matchMedia("(max-width: 600px)").matches;
type Draft = { note: Note | null; title: string; text: string; labels: LabelId[] };
export default function Notes() {
const [s, setS] = useState<State>(DEFAULTS);
const [draft, setDraft] = useState<Draft | null>(null);
const snackbar = useRef<SnackbarElement | null>(null);
const deleted = useRef<{ note: Note; at: number } | null>(null);
const open = (note: Note | null): void =>
setDraft(note ? { note, title: note.title, text: note.text, labels: [...note.labels] } : { note: null, title: "", text: "", labels: [] });
const save = (): void => {
if (!draft) return;
if (draft.note) {
const edited = draft.note;
setS((prev) => ({
...prev,
notes: prev.notes.map((n) => (n === edited ? { ...n, title: draft.title, text: draft.text, labels: [...draft.labels] } : n)),
}));
} else {
const note: Note = { id: crypto.randomUUID(), title: draft.title, text: draft.text, labels: [...draft.labels], pinned: false };
setS((prev) => ({ ...prev, notes: [...prev.notes, note] }));
}
setDraft(null);
};
const remove = (note: Note): void => {
deleted.current = { note, at: s.notes.indexOf(note) };
setS((prev) => ({ ...prev, notes: prev.notes.filter((n) => n !== note) }));
setDraft(null);
snackbar.current?.show();
};
const undo = (): void => {
const gone = deleted.current;
if (!gone) return;
deleted.current = null;
setS((prev) => ({ ...prev, notes: [...prev.notes.slice(0, gone.at), gone.note, ...prev.notes.slice(gone.at)] }));
};
const shown = visible(s);
const pinnedNotes = shown.filter((n) => n.pinned);
const otherNotes = shown.filter((n) => !n.pinned);
const noteCard = (note: Note) => (
<Card key={note.id} headline={note.title}>
<IconButton
slot="header-action"
toggle
selected={note.pinned}
icon={PIN_ICON}
ariaLabel={`Pin ${note.title}`}
onChange={() => setS((prev) => ({ ...prev, notes: prev.notes.map((n) => (n === note ? { ...n, pinned: !n.pinned } : n)) }))}
/>
<p>{note.text}</p>
{note.labels.length > 0 && (
<Chips value={s.filter.join(",")} onChange={(e) => setS((prev) => ({ ...prev, filter: e.detail.value as LabelId[] }))}>
{note.labels.map((id) => (
<Chip key={id} label={labelOf(id)} value={id} />
))}
</Chips>
)}
<div slot="actions" className="notes__card-actions">
<Button variant="text" ariaLabel={`Open ${note.title}`} onClick={() => open(note)}>Open</Button>
<IconButton icon={DELETE_ICON} ariaLabel={`Delete ${note.title}`} onClick={() => remove(note)} />
</div>
</Card>
);
const grid = (notes: Note[]) => <div className={`notes__grid ${s.view}`}>{notes.map(noteCard)}</div>;
const editorBody = (
<div className="notes__fields">
<TextField label="Title" value={draft?.title ?? ""} onInput={(e) => setDraft((d) => (d ? { ...d, title: e.detail.value } : d))} />
<TextField label="Note" type="multiline" value={draft?.text ?? ""} onInput={(e) => setDraft((d) => (d ? { ...d, text: e.detail.value } : d))} />
<Chips value={(draft?.labels ?? []).join(",")} onChange={(e) => setDraft((d) => (d ? { ...d, labels: e.detail.value as LabelId[] } : d))}>
{LABELS.map(({ value, text }) => (
<Chip key={value} label={text} value={value} />
))}
</Chips>
</div>
);
const editorButtons = (
<>
<Button variant="outlined" onClick={() => (draft?.note ? remove(draft.note) : setDraft(null))}>Delete</Button>
<Button variant="text" onClick={() => setDraft(null)}>Cancel</Button>
<Button onClick={save}>Save</Button>
</>
);
// The dialog slots its actions; the sheet has only its content.
const editorActions = (
<div slot="actions" className="notes__editor-actions">
{editorButtons}
</div>
);
const sheetActions = <div className="notes__editor-actions">{editorButtons}</div>;
return (
<section className="notes">
<div className="notes__bar">
<Search placeholder="Search notes" onInput={(e) => setS((prev) => ({ ...prev, query: e.detail.value }))} />
<ButtonGroup kind="connected" selection="single" required value={s.view} onChange={(e) => setS((prev) => ({ ...prev, view: e.detail.value === "list" ? "list" : "grid" }))}>
<ButtonGroupItem icon={GRID_ICON} value="grid" ariaLabel="Grid view" />
<ButtonGroupItem icon={LIST_ICON} value="list" ariaLabel="List view" />
</ButtonGroup>
</div>
<Chips value={s.filter.join(",")} onChange={(e) => setS((prev) => ({ ...prev, filter: e.detail.value as LabelId[] }))}>
{LABELS.map(({ value, text }) => (
<Chip key={value} label={text} value={value} />
))}
</Chips>
<output className="notes__status" role="status">{status(s)}</output>
{shown.length === 0 ? (
<p className="notes__empty">No notes match.</p>
) : (
<>
{pinnedNotes.length > 0 && (
<section className="notes__section">
<h2>Pinned</h2>
{grid(pinnedNotes)}
</section>
)}
{otherNotes.length > 0 && (
<section className="notes__section">
<h2>Notes</h2>
{grid(otherNotes)}
</section>
)}
</>
)}
<ExtendedFab icon={ADD_ICON} ariaLabel="New note" onClick={() => open(null)}>New note</ExtendedFab>
{narrow ? (
<BottomSheet open={draft !== null} title={draft?.note ? "Edit note" : "New note"} onClose={() => setDraft(null)}>
{editorBody}
{sheetActions}
</BottomSheet>
) : (
<Dialog open={draft !== null} headline={draft?.note ? "Edit note" : "New note"} onClose={() => setDraft(null)}>
{editorBody}
{editorActions}
</Dialog>
)}
<Snackbar message="Note deleted" action="Undo" duration="4000" dismissible onAction={undo} ref={snackbar} />
</section>
);
}
// The state every variant of this example shares, the notes it starts from, and
// how the state is described. check.ts drives it, and check-examples compares
// what each framework shows.
export type LabelId = "ideas" | "shopping" | "work" | "travel";
export const LABELS: { value: LabelId; text: string }[] = [
{ value: "ideas", text: "Ideas" },
{ value: "shopping", text: "Shopping" },
{ value: "work", text: "Work" },
{ value: "travel", text: "Travel" },
];
export interface Note {
id: string;
title: string;
text: string;
labels: LabelId[];
pinned: boolean;
}
export const SEED_NOTES: Note[] = [
{ id: "sauce", title: "Pasta sauce", text: "Fry garlic in olive oil, add torn tomatoes, simmer twenty minutes. Basil at the end.", labels: ["ideas"], pinned: false },
{ id: "groceries", title: "Weekend groceries", text: "Bread, oat milk, lemons, coffee, the good chocolate.", labels: ["shopping"], pinned: false },
{ id: "meeting", title: "Meeting points", text: "Roadmap, hiring plan, support queue. Write down every decision.", labels: ["work"], pinned: true },
{ id: "packing", title: "Packing list", text: "Two shirts, one warm layer, charger, toothbrush, passport.", labels: ["travel", "shopping"], pinned: true },
{ id: "gifts", title: "Gift ideas", text: "A plant for the balcony, a cookbook for the baker, ink for the letter writer.", labels: ["ideas"], pinned: false },
{ id: "walk", title: "City walk route", text: "Bridge, old square, river bank, market on the way back.", labels: ["travel"], pinned: false },
{ id: "priorities", title: "Week priorities", text: "Ship the release notes, review the open pulls, plan Friday morning.", labels: ["work"], pinned: false },
{ id: "prompts", title: "Story prompts", text: "A lighthouse that answers letters. A market that only opens at dusk.", labels: ["ideas"], pinned: false },
{ id: "borrow", title: "Books to borrow", text: "The gardening one, the poetry anthology, the train atlas.", labels: ["shopping"], pinned: false },
{ id: "repairs", title: "Flat repairs", text: "Fix the kitchen drawer, replace the hall bulb, defrost the freezer.", labels: ["work"], pinned: false },
{ id: "sourdough", title: "Sourdough steps", text: "Feed the starter tonight, shape in the morning, bake with steam.", labels: ["ideas"], pinned: false },
];
export interface State {
notes: Note[];
filter: LabelId[];
query: string;
view: "grid" | "list";
}
export const DEFAULTS: State = {
notes: SEED_NOTES.map((note) => ({ ...note, labels: [...note.labels] })),
filter: [],
query: "",
view: "grid",
};
export const labelOf = (id: LabelId): string => LABELS.find((l) => l.value === id)!.text;
/** The notes the grid shows: the filter's labels, then the search's words. */
export const visible = (s: State): Note[] =>
s.notes.filter(
(n) =>
(s.filter.length === 0 || n.labels.some((l) => s.filter.includes(l))) &&
(s.query === "" || `${n.title} ${n.text}`.toLowerCase().includes(s.query.toLowerCase())),
);
export const status = (s: State): string => `Showing ${visible(s).length} of ${s.notes.length} notes.`;
// The icons the interface uses, as the components take them: Material Symbols
// (Apache 2.0, fonts.google.com/icons), the same files scripts/icons.ts fetches.
export const ADD_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-440H240q-17 0-28.5-11.5T200-480q0-17 11.5-28.5T240-520h200v-200q0-17 11.5-28.5T480-760q17 0 28.5 11.5T520-720v200h200q17 0 28.5 11.5T760-480q0 17-11.5 28.5T720-440H520v200q0 17-11.5 28.5T480-200q-17 0-28.5-11.5T440-240v-200Z"/></svg>';
export const PIN_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40v280Zm-286 80h252l-46-46v-314H400v314l-46 46Zm126 0Z"/></svg>';
export const DELETE_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M280-120q-33 0-56.5-23.5T200-200v-520q-17 0-28.5-11.5T160-760q0-17 11.5-28.5T200-800h160q0-17 11.5-28.5T400-840h160q17 0 28.5 11.5T600-800h160q17 0 28.5 11.5T800-760q0 17-11.5 28.5T760-720v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM428.5-291.5Q440-303 440-320v-280q0-17-11.5-28.5T400-640q-17 0-28.5 11.5T360-600v280q0 17 11.5 28.5T400-280q17 0 28.5-11.5Zm160 0Q600-303 600-320v-280q0-17-11.5-28.5T560-640q-17 0-28.5 11.5T520-600v280q0 17 11.5 28.5T560-280q17 0 28.5-11.5ZM280-720v520-520Z"/></svg>';
export const GRID_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M120-520v-320h320v320H120Zm0 400v-320h320v320H120Zm400-400v-320h320v320H520Zm0 400v-320h320v320H520Z"/></svg>';
export const LIST_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M360-680v-80h480v80H360Zm0 240v-80h480v80H360Zm0 240v-80h480v80H360ZM200-680q-17 0-28.5-11.5T160-720q0-17 11.5-28.5T200-760q17 0 28.5 11.5T240-720q0 17-11.5 28.5T200-680Zm0 240q-17 0-28.5-11.5T160-480q0-17 11.5-28.5T200-520q17 0 28.5 11.5T240-480q0 17-11.5 28.5T200-440Zm0 240q-17 0-28.5-11.5T160-240q0-17 11.5-28.5T200-280q17 0 28.5 11.5T240-240q0 17-11.5 28.5T200-200Z"/></svg>';
// Vue: material/vue wraps the same elements; v-model binds their live state.
import { defineComponent, ref } from "vue";
import { MBottomSheet, MButton, MButtonGroup, MButtonGroupItem, MCard, MChip, MChips, MDialog, MExtendedFab, MIconButton, MSearch, MSnackbar, MTextField } from "material/vue";
import { DEFAULTS, LABELS, ADD_ICON, DELETE_ICON, GRID_ICON, LIST_ICON, PIN_ICON, labelOf, status, visible, type LabelId, type Note, type State } from "./shared";
export default defineComponent({
components: { MBottomSheet, MButton, MButtonGroup, MButtonGroupItem, MCard, MChip, MChips, MDialog, MExtendedFab, MIconButton, MSearch, MSnackbar, MTextField },
setup() {
const s = ref<State>({ ...DEFAULTS, notes: DEFAULTS.notes.map((n) => ({ ...n, labels: [...n.labels] })) });
const draft = ref<{ note: Note | null; title: string; text: string; labels: LabelId[] } | null>(null);
const snackbar = ref<{ element?: { show: () => void } } | null>(null);
let deleted: { note: Note; at: number } | null = null;
const narrow = matchMedia("(max-width: 600px)").matches;
const open = (note: Note | null) =>
(draft.value = note
? { note, title: note.title, text: note.text, labels: [...note.labels] }
: { note: null, title: "", text: "", labels: [] });
const save = () => {
const d = draft.value;
if (!d) return;
if (d.note) {
d.note.title = d.title;
d.note.text = d.text;
d.note.labels = [...d.labels];
s.value = { ...s.value };
} else {
s.value = { ...s.value, notes: [...s.value.notes, { id: crypto.randomUUID(), title: d.title, text: d.text, labels: [...d.labels], pinned: false }] };
}
draft.value = null;
};
const remove = (note: Note) => {
deleted = { note, at: s.value.notes.indexOf(note) };
s.value = { ...s.value, notes: s.value.notes.filter((n) => n !== note) };
draft.value = null;
snackbar.value?.element?.show();
};
const undo = () => {
if (!deleted) return;
const { note, at } = deleted;
deleted = null;
s.value = { ...s.value, notes: [...s.value.notes.slice(0, at), note, ...s.value.notes.slice(at)] };
};
const setFilter = (value: string[]) => (s.value = { ...s.value, filter: value as LabelId[] });
const pin = (note: Note) => (s.value = { ...s.value, notes: s.value.notes.map((n) => (n === note ? { ...n, pinned: !n.pinned } : n)) });
const shownCount = () => visible(s.value).length;
const pinnedNotes = () => visible(s.value).filter((n) => n.pinned);
const otherNotes = () => visible(s.value).filter((n) => !n.pinned);
return { s, draft, snackbar, narrow, LABELS, ADD_ICON, DELETE_ICON, GRID_ICON, LIST_ICON, PIN_ICON, labelOf, status, shownCount, pinnedNotes, otherNotes, open, save, remove, undo, setFilter, pin };
},
template: `
<section class="notes">
<div class="notes__bar">
<MSearch placeholder="Search notes" @input="s = { ...s, query: $event.detail.value }" />
<MButtonGroup kind="connected" selection="single" required :value="s.view" @change="s = { ...s, view: $event.detail.value === 'list' ? 'list' : 'grid' }">
<MButtonGroupItem :icon="GRID_ICON" value="grid" ariaLabel="Grid view" />
<MButtonGroupItem :icon="LIST_ICON" value="list" ariaLabel="List view" />
</MButtonGroup>
</div>
<MChips :value="s.filter.join(',')" @change="setFilter($event.detail.value)">
<MChip v-for="l in LABELS" :key="l.value" :label="l.text" :value="l.value" />
</MChips>
<output class="notes__status" role="status">{{ status(s) }}</output>
<p v-if="shownCount() === 0" class="notes__empty">No notes match.</p>
<template v-else>
<section v-if="pinnedNotes().length > 0" class="notes__section">
<h2>Pinned</h2>
<div :class="'notes__grid ' + s.view">
<MCard v-for="note in pinnedNotes()" :key="note.id" :headline="note.title">
<MIconButton slot="header-action" toggle :selected="note.pinned" :icon="PIN_ICON" :aria-label="'Pin ' + note.title" @change="pin(note)" />
<p>{{ note.text }}</p>
<MChips v-if="note.labels.length > 0" :value="s.filter.join(',')" @change="setFilter($event.detail.value)">
<MChip v-for="id in note.labels" :key="id" :label="labelOf(id)" :value="id" />
</MChips>
<div slot="actions" class="notes__card-actions">
<MButton variant="text" :aria-label="'Open ' + note.title" @click="open(note)">Open</MButton>
<MIconButton :icon="DELETE_ICON" :aria-label="'Delete ' + note.title" @click="remove(note)" />
</div>
</MCard>
</div>
</section>
<section v-if="otherNotes().length > 0" class="notes__section">
<h2>Notes</h2>
<div :class="'notes__grid ' + s.view">
<MCard v-for="note in otherNotes()" :key="note.id" :headline="note.title">
<MIconButton slot="header-action" toggle :selected="note.pinned" :icon="PIN_ICON" :aria-label="'Pin ' + note.title" @change="pin(note)" />
<p>{{ note.text }}</p>
<MChips v-if="note.labels.length > 0" :value="s.filter.join(',')" @change="setFilter($event.detail.value)">
<MChip v-for="id in note.labels" :key="id" :label="labelOf(id)" :value="id" />
</MChips>
<div slot="actions" class="notes__card-actions">
<MButton variant="text" :aria-label="'Open ' + note.title" @click="open(note)">Open</MButton>
<MIconButton :icon="DELETE_ICON" :aria-label="'Delete ' + note.title" @click="remove(note)" />
</div>
</MCard>
</div>
</section>
</template>
<MExtendedFab :icon="ADD_ICON" ariaLabel="New note" @click="open(null)">New note</MExtendedFab>
<MDialog v-if="!narrow" :open="draft !== null" :headline="draft && draft.note ? 'Edit note' : 'New note'" @close="draft = null">
<div class="notes__fields">
<MTextField label="Title" :value="draft ? draft.title : ''" @input="draft && (draft = { ...draft, title: $event.detail.value })" />
<MTextField label="Note" type="multiline" :value="draft ? draft.text : ''" @input="draft && (draft = { ...draft, text: $event.detail.value })" />
<MChips :value="draft ? draft.labels.join(',') : ''" @change="draft && (draft = { ...draft, labels: $event.detail.value })">
<MChip v-for="l in LABELS" :key="l.value" :label="l.text" :value="l.value" />
</MChips>
</div>
<div slot="actions" class="notes__editor-actions">
<MButton variant="outlined" @click="draft && (draft.note ? remove(draft.note) : (draft = null))">Delete</MButton>
<MButton variant="text" @click="draft = null">Cancel</MButton>
<MButton @click="save()">Save</MButton>
</div>
</MDialog>
<MBottomSheet v-else :open="draft !== null" :title="draft && draft.note ? 'Edit note' : 'New note'" @close="draft = null">
<div class="notes__fields">
<MTextField label="Title" :value="draft ? draft.title : ''" @input="draft && (draft = { ...draft, title: $event.detail.value })" />
<MTextField label="Note" type="multiline" :value="draft ? draft.text : ''" @input="draft && (draft = { ...draft, text: $event.detail.value })" />
<MChips :value="draft ? draft.labels.join(',') : ''" @change="draft && (draft = { ...draft, labels: $event.detail.value })">
<MChip v-for="l in LABELS" :key="l.value" :label="l.text" :value="l.value" />
</MChips>
</div>
<div class="notes__editor-actions">
<MButton variant="outlined" @click="draft && (draft.note ? remove(draft.note) : (draft = null))">Delete</MButton>
<MButton variant="text" @click="draft = null">Cancel</MButton>
<MButton @click="save()">Save</MButton>
</div>
</MBottomSheet>
<MSnackbar ref="snackbar" message="Note deleted" action="Undo" duration="4000" dismissible @action="undo" />
</section>`,
});
// The state every variant of this example shares, the notes it starts from, and
// how the state is described. check.ts drives it, and check-examples compares
// what each framework shows.
export type LabelId = "ideas" | "shopping" | "work" | "travel";
export const LABELS: { value: LabelId; text: string }[] = [
{ value: "ideas", text: "Ideas" },
{ value: "shopping", text: "Shopping" },
{ value: "work", text: "Work" },
{ value: "travel", text: "Travel" },
];
export interface Note {
id: string;
title: string;
text: string;
labels: LabelId[];
pinned: boolean;
}
export const SEED_NOTES: Note[] = [
{ id: "sauce", title: "Pasta sauce", text: "Fry garlic in olive oil, add torn tomatoes, simmer twenty minutes. Basil at the end.", labels: ["ideas"], pinned: false },
{ id: "groceries", title: "Weekend groceries", text: "Bread, oat milk, lemons, coffee, the good chocolate.", labels: ["shopping"], pinned: false },
{ id: "meeting", title: "Meeting points", text: "Roadmap, hiring plan, support queue. Write down every decision.", labels: ["work"], pinned: true },
{ id: "packing", title: "Packing list", text: "Two shirts, one warm layer, charger, toothbrush, passport.", labels: ["travel", "shopping"], pinned: true },
{ id: "gifts", title: "Gift ideas", text: "A plant for the balcony, a cookbook for the baker, ink for the letter writer.", labels: ["ideas"], pinned: false },
{ id: "walk", title: "City walk route", text: "Bridge, old square, river bank, market on the way back.", labels: ["travel"], pinned: false },
{ id: "priorities", title: "Week priorities", text: "Ship the release notes, review the open pulls, plan Friday morning.", labels: ["work"], pinned: false },
{ id: "prompts", title: "Story prompts", text: "A lighthouse that answers letters. A market that only opens at dusk.", labels: ["ideas"], pinned: false },
{ id: "borrow", title: "Books to borrow", text: "The gardening one, the poetry anthology, the train atlas.", labels: ["shopping"], pinned: false },
{ id: "repairs", title: "Flat repairs", text: "Fix the kitchen drawer, replace the hall bulb, defrost the freezer.", labels: ["work"], pinned: false },
{ id: "sourdough", title: "Sourdough steps", text: "Feed the starter tonight, shape in the morning, bake with steam.", labels: ["ideas"], pinned: false },
];
export interface State {
notes: Note[];
filter: LabelId[];
query: string;
view: "grid" | "list";
}
export const DEFAULTS: State = {
notes: SEED_NOTES.map((note) => ({ ...note, labels: [...note.labels] })),
filter: [],
query: "",
view: "grid",
};
export const labelOf = (id: LabelId): string => LABELS.find((l) => l.value === id)!.text;
/** The notes the grid shows: the filter's labels, then the search's words. */
export const visible = (s: State): Note[] =>
s.notes.filter(
(n) =>
(s.filter.length === 0 || n.labels.some((l) => s.filter.includes(l))) &&
(s.query === "" || `${n.title} ${n.text}`.toLowerCase().includes(s.query.toLowerCase())),
);
export const status = (s: State): string => `Showing ${visible(s).length} of ${s.notes.length} notes.`;
// The icons the interface uses, as the components take them: Material Symbols
// (Apache 2.0, fonts.google.com/icons), the same files scripts/icons.ts fetches.
export const ADD_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-440H240q-17 0-28.5-11.5T200-480q0-17 11.5-28.5T240-520h200v-200q0-17 11.5-28.5T480-760q17 0 28.5 11.5T520-720v200h200q17 0 28.5 11.5T760-480q0 17-11.5 28.5T720-440H520v200q0 17-11.5 28.5T480-200q-17 0-28.5-11.5T440-240v-200Z"/></svg>';
export const PIN_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40v280Zm-286 80h252l-46-46v-314H400v314l-46 46Zm126 0Z"/></svg>';
export const DELETE_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M280-120q-33 0-56.5-23.5T200-200v-520q-17 0-28.5-11.5T160-760q0-17 11.5-28.5T200-800h160q0-17 11.5-28.5T400-840h160q17 0 28.5 11.5T600-800h160q17 0 28.5 11.5T800-760q0 17-11.5 28.5T760-720v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM428.5-291.5Q440-303 440-320v-280q0-17-11.5-28.5T400-640q-17 0-28.5 11.5T360-600v280q0 17 11.5 28.5T400-280q17 0 28.5-11.5Zm160 0Q600-303 600-320v-280q0-17-11.5-28.5T560-640q-17 0-28.5 11.5T520-600v280q0 17 11.5 28.5T560-280q17 0 28.5-11.5ZM280-720v520-520Z"/></svg>';
export const GRID_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M120-520v-320h320v320H120Zm0 400v-320h320v320H120Zm400-400v-320h320v320H520Zm0 400v-320h320v320H520Z"/></svg>';
export const LIST_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M360-680v-80h480v80H360Zm0 240v-80h480v80H360Zm0 240v-80h480v80H360ZM200-680q-17 0-28.5-11.5T160-720q0-17 11.5-28.5T200-760q17 0 28.5 11.5T240-720q0 17-11.5 28.5T200-680Zm0 240q-17 0-28.5-11.5T160-480q0-17 11.5-28.5T200-520q17 0 28.5 11.5T240-480q0 17-11.5 28.5T200-440Zm0 240q-17 0-28.5-11.5T160-240q0-17 11.5-28.5T200-280q17 0 28.5 11.5T240-240q0 17-11.5 28.5T200-200Z"/></svg>';
<!-- Svelte: material/svelte wraps the same elements; bind: keeps their live state. -->
<script lang="ts">
import { BottomSheet, Button, ButtonGroup, ButtonGroupItem, Card, Chip, Chips, Dialog, ExtendedFab, IconButton, Search, Snackbar, TextField } from "material/svelte";
import { DEFAULTS, LABELS, ADD_ICON, DELETE_ICON, GRID_ICON, LIST_ICON, PIN_ICON, labelOf, status, visible, type LabelId, type Note, type State } from "./shared";
const narrow = matchMedia("(max-width: 600px)").matches;
let s = $state<State>({ ...DEFAULTS, notes: DEFAULTS.notes.map((n) => ({ ...n, labels: [...n.labels] })) });
let draft = $state<{ note: Note | null; title: string; text: string; labels: LabelId[] } | null>(null);
let snackbar = $state<{ element?: { show: () => void } } | null>(null);
let deleted: { note: Note; at: number } | null = null;
const open = (note: Note | null) =>
(draft = note
? { note, title: note.title, text: note.text, labels: [...note.labels] }
: { note: null, title: "", text: "", labels: [] });
const save = () => {
const d = draft;
if (!d) return;
if (d.note) {
d.note.title = d.title;
d.note.text = d.text;
d.note.labels = [...d.labels];
s = { ...s };
} else {
s = { ...s, notes: [...s.notes, { id: crypto.randomUUID(), title: d.title, text: d.text, labels: [...d.labels], pinned: false }] };
}
draft = null;
};
const remove = (note: Note) => {
deleted = { note, at: s.notes.indexOf(note) };
s = { ...s, notes: s.notes.filter((n) => n !== note) };
draft = null;
snackbar?.element?.show();
};
const undo = () => {
if (!deleted) return;
const { note, at } = deleted;
deleted = null;
s = { ...s, notes: [...s.notes.slice(0, at), note, ...s.notes.slice(at)] };
};
const setFilter = (value: string[]) => (s = { ...s, filter: value as LabelId[] });
const pin = (note: Note) => (s = { ...s, notes: s.notes.map((n) => (n === note ? { ...n, pinned: !n.pinned } : n)) });
const shownCount = $derived(visible(s).length);
const pinnedNotes = $derived(visible(s).filter((n) => n.pinned));
const otherNotes = $derived(visible(s).filter((n) => !n.pinned));
</script>
<section class="notes">
<div class="notes__bar">
<Search placeholder="Search notes" oninput={(e) => (s = { ...s, query: e.detail.value })} />
<ButtonGroup kind="connected" selection="single" required value={s.view} onchange={(e) => (s = { ...s, view: e.detail.value === "list" ? "list" : "grid" })}>
<ButtonGroupItem icon={GRID_ICON} value="grid" ariaLabel="Grid view" />
<ButtonGroupItem icon={LIST_ICON} value="list" ariaLabel="List view" />
</ButtonGroup>
</div>
<Chips value={s.filter.join(",")} onchange={(e) => setFilter(e.detail.value)}>
{#each LABELS as l (l.value)}
<Chip label={l.text} value={l.value} />
{/each}
</Chips>
<output class="notes__status" role="status">{status(s)}</output>
{#if shownCount === 0}
<p class="notes__empty">No notes match.</p>
{:else}
{#if pinnedNotes.length > 0}
<section class="notes__section">
<h2>Pinned</h2>
<div class="notes__grid {s.view}">
{#each pinnedNotes as note (note.id)}
<Card headline={note.title}>
{#snippet headerAction()}
<IconButton toggle selected={note.pinned} icon={PIN_ICON} ariaLabel={`Pin ${note.title}`} onchange={() => pin(note)} />
{/snippet}
<p>{note.text}</p>
{#if note.labels.length > 0}
<Chips value={s.filter.join(",")} onchange={(e) => setFilter(e.detail.value)}>
{#each note.labels as id (id)}
<Chip label={labelOf(id)} value={id} />
{/each}
</Chips>
{/if}
{#snippet actions()}
<div class="notes__card-actions">
<Button variant="text" ariaLabel={`Open ${note.title}`} onclick={() => open(note)}>Open</Button>
<IconButton icon={DELETE_ICON} ariaLabel={`Delete ${note.title}`} onclick={() => remove(note)} />
</div>
{/snippet}
</Card>
{/each}
</div>
</section>
{/if}
{#if otherNotes.length > 0}
<section class="notes__section">
<h2>Notes</h2>
<div class="notes__grid {s.view}">
{#each otherNotes as note (note.id)}
<Card headline={note.title}>
{#snippet headerAction()}
<IconButton toggle selected={note.pinned} icon={PIN_ICON} ariaLabel={`Pin ${note.title}`} onchange={() => pin(note)} />
{/snippet}
<p>{note.text}</p>
{#if note.labels.length > 0}
<Chips value={s.filter.join(",")} onchange={(e) => setFilter(e.detail.value)}>
{#each note.labels as id (id)}
<Chip label={labelOf(id)} value={id} />
{/each}
</Chips>
{/if}
{#snippet actions()}
<div class="notes__card-actions">
<Button variant="text" ariaLabel={`Open ${note.title}`} onclick={() => open(note)}>Open</Button>
<IconButton icon={DELETE_ICON} ariaLabel={`Delete ${note.title}`} onclick={() => remove(note)} />
</div>
{/snippet}
</Card>
{/each}
</div>
</section>
{/if}
{/if}
<ExtendedFab icon={ADD_ICON} ariaLabel="New note" onclick={() => open(null)}>New note</ExtendedFab>
{#if narrow}
<BottomSheet open={draft !== null} title={draft?.note ? "Edit note" : "New note"} onclose={() => (draft = null)}>
<div class="notes__fields">
<TextField label="Title" value={draft?.title ?? ""} oninput={(e) => draft && (draft = { ...draft, title: e.detail.value })} />
<TextField label="Note" type="multiline" value={draft?.text ?? ""} oninput={(e) => draft && (draft = { ...draft, text: e.detail.value })} />
<Chips value={draft?.labels.join(",") ?? ""} onchange={(e) => draft && (draft = { ...draft, labels: e.detail.value as LabelId[] })}>
{#each LABELS as l (l.value)}
<Chip label={l.text} value={l.value} />
{/each}
</Chips>
</div>
<div class="notes__editor-actions">
<Button variant="outlined" onclick={() => (draft?.note ? remove(draft.note) : (draft = null))}>Delete</Button>
<Button variant="text" onclick={() => (draft = null)}>Cancel</Button>
<Button onclick={save}>Save</Button>
</div>
</BottomSheet>
{:else}
<Dialog open={draft !== null} headline={draft?.note ? "Edit note" : "New note"} onclose={() => (draft = null)}>
<div class="notes__fields">
<TextField label="Title" value={draft?.title ?? ""} oninput={(e) => draft && (draft = { ...draft, title: e.detail.value })} />
<TextField label="Note" type="multiline" value={draft?.text ?? ""} oninput={(e) => draft && (draft = { ...draft, text: e.detail.value })} />
<Chips value={draft?.labels.join(",") ?? ""} onchange={(e) => draft && (draft = { ...draft, labels: e.detail.value as LabelId[] })}>
{#each LABELS as l (l.value)}
<Chip label={l.text} value={l.value} />
{/each}
</Chips>
</div>
{#snippet actions()}
<div class="notes__editor-actions">
<Button variant="outlined" onclick={() => (draft?.note ? remove(draft.note) : (draft = null))}>Delete</Button>
<Button variant="text" onclick={() => (draft = null)}>Cancel</Button>
<Button onclick={save}>Save</Button>
</div>
{/snippet}
</Dialog>
{/if}
<Snackbar bind:this={snackbar} message="Note deleted" action="Undo" duration="4000" dismissible onaction={undo} />
</section>
// The state every variant of this example shares, the notes it starts from, and
// how the state is described. check.ts drives it, and check-examples compares
// what each framework shows.
export type LabelId = "ideas" | "shopping" | "work" | "travel";
export const LABELS: { value: LabelId; text: string }[] = [
{ value: "ideas", text: "Ideas" },
{ value: "shopping", text: "Shopping" },
{ value: "work", text: "Work" },
{ value: "travel", text: "Travel" },
];
export interface Note {
id: string;
title: string;
text: string;
labels: LabelId[];
pinned: boolean;
}
export const SEED_NOTES: Note[] = [
{ id: "sauce", title: "Pasta sauce", text: "Fry garlic in olive oil, add torn tomatoes, simmer twenty minutes. Basil at the end.", labels: ["ideas"], pinned: false },
{ id: "groceries", title: "Weekend groceries", text: "Bread, oat milk, lemons, coffee, the good chocolate.", labels: ["shopping"], pinned: false },
{ id: "meeting", title: "Meeting points", text: "Roadmap, hiring plan, support queue. Write down every decision.", labels: ["work"], pinned: true },
{ id: "packing", title: "Packing list", text: "Two shirts, one warm layer, charger, toothbrush, passport.", labels: ["travel", "shopping"], pinned: true },
{ id: "gifts", title: "Gift ideas", text: "A plant for the balcony, a cookbook for the baker, ink for the letter writer.", labels: ["ideas"], pinned: false },
{ id: "walk", title: "City walk route", text: "Bridge, old square, river bank, market on the way back.", labels: ["travel"], pinned: false },
{ id: "priorities", title: "Week priorities", text: "Ship the release notes, review the open pulls, plan Friday morning.", labels: ["work"], pinned: false },
{ id: "prompts", title: "Story prompts", text: "A lighthouse that answers letters. A market that only opens at dusk.", labels: ["ideas"], pinned: false },
{ id: "borrow", title: "Books to borrow", text: "The gardening one, the poetry anthology, the train atlas.", labels: ["shopping"], pinned: false },
{ id: "repairs", title: "Flat repairs", text: "Fix the kitchen drawer, replace the hall bulb, defrost the freezer.", labels: ["work"], pinned: false },
{ id: "sourdough", title: "Sourdough steps", text: "Feed the starter tonight, shape in the morning, bake with steam.", labels: ["ideas"], pinned: false },
];
export interface State {
notes: Note[];
filter: LabelId[];
query: string;
view: "grid" | "list";
}
export const DEFAULTS: State = {
notes: SEED_NOTES.map((note) => ({ ...note, labels: [...note.labels] })),
filter: [],
query: "",
view: "grid",
};
export const labelOf = (id: LabelId): string => LABELS.find((l) => l.value === id)!.text;
/** The notes the grid shows: the filter's labels, then the search's words. */
export const visible = (s: State): Note[] =>
s.notes.filter(
(n) =>
(s.filter.length === 0 || n.labels.some((l) => s.filter.includes(l))) &&
(s.query === "" || `${n.title} ${n.text}`.toLowerCase().includes(s.query.toLowerCase())),
);
export const status = (s: State): string => `Showing ${visible(s).length} of ${s.notes.length} notes.`;
// The icons the interface uses, as the components take them: Material Symbols
// (Apache 2.0, fonts.google.com/icons), the same files scripts/icons.ts fetches.
export const ADD_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-440H240q-17 0-28.5-11.5T200-480q0-17 11.5-28.5T240-520h200v-200q0-17 11.5-28.5T480-760q17 0 28.5 11.5T520-720v200h200q17 0 28.5 11.5T760-480q0 17-11.5 28.5T720-440H520v200q0 17-11.5 28.5T480-200q-17 0-28.5-11.5T440-240v-200Z"/></svg>';
export const PIN_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40v280Zm-286 80h252l-46-46v-314H400v314l-46 46Zm126 0Z"/></svg>';
export const DELETE_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M280-120q-33 0-56.5-23.5T200-200v-520q-17 0-28.5-11.5T160-760q0-17 11.5-28.5T200-800h160q0-17 11.5-28.5T400-840h160q17 0 28.5 11.5T600-800h160q17 0 28.5 11.5T800-760q0 17-11.5 28.5T760-720v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM428.5-291.5Q440-303 440-320v-280q0-17-11.5-28.5T400-640q-17 0-28.5 11.5T360-600v280q0 17 11.5 28.5T400-280q17 0 28.5-11.5Zm160 0Q600-303 600-320v-280q0-17-11.5-28.5T560-640q-17 0-28.5 11.5T520-600v280q0 17 11.5 28.5T560-280q17 0 28.5-11.5ZM280-720v520-520Z"/></svg>';
export const GRID_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M120-520v-320h320v320H120Zm0 400v-320h320v320H120Zm400-400v-320h320v320H520Zm0 400v-320h320v320H520Z"/></svg>';
export const LIST_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M360-680v-80h480v80H360Zm0 240v-80h480v80H360Zm0 240v-80h480v80H360ZM200-680q-17 0-28.5-11.5T160-720q0-17 11.5-28.5T200-760q17 0 28.5 11.5T240-720q0 17-11.5 28.5T200-680Zm0 240q-17 0-28.5-11.5T160-480q0-17 11.5-28.5T200-520q17 0 28.5 11.5T240-480q0 17-11.5 28.5T200-440Zm0 240q-17 0-28.5-11.5T160-240q0-17 11.5-28.5T200-280q17 0 28.5 11.5T240-240q0 17-11.5 28.5T200-200Z"/></svg>';
/** @jsxImportSource solid-js — this file's JSX is Solid's, not React's; tsc reads it. */
// Solid: material/solid wraps the same elements.
import { createSignal, For, Show } from "solid-js";
import { BottomSheet, Button, ButtonGroup, ButtonGroupItem, Card, Chip, Chips, Dialog, ExtendedFab, IconButton, Search, Snackbar, TextField } from "material/solid";
import { DEFAULTS, LABELS, ADD_ICON, DELETE_ICON, GRID_ICON, LIST_ICON, PIN_ICON, labelOf, status, visible, type LabelId, type Note, type State } from "./shared";
const narrow = matchMedia("(max-width: 600px)").matches;
interface Draft {
note: Note | null;
title: string;
text: string;
labels: LabelId[];
}
export default function Notes() {
const [s, setS] = createSignal<State>({ ...DEFAULTS, notes: DEFAULTS.notes.map((n) => ({ ...n, labels: [...n.labels] })) });
const [draft, setDraft] = createSignal<Draft | null>(null);
const [snackbar, setSnackbar] = createSignal<{ show: () => void } | null>(null);
let deleted: { note: Note; at: number } | null = null;
const open = (note: Note | null): void => {
setDraft(note ? { note, title: note.title, text: note.text, labels: [...note.labels] } : { note: null, title: "", text: "", labels: [] });
};
const save = (): void => {
const d = draft();
if (!d) return;
if (d.note) {
setS((prev) => ({ ...prev, notes: prev.notes.map((n) => (n === d.note ? { ...n, title: d.title, text: d.text, labels: [...d.labels] } : n)) }));
} else {
setS((prev) => ({ ...prev, notes: [...prev.notes, { id: crypto.randomUUID(), title: d.title, text: d.text, labels: [...d.labels], pinned: false }] }));
}
setDraft(null);
};
const remove = (note: Note): void => {
deleted = { note, at: s().notes.indexOf(note) };
setS((prev) => ({ ...prev, notes: prev.notes.filter((n) => n !== note) }));
setDraft(null);
snackbar()?.show();
};
const asStrings = (value: string | string[] | null): string[] => (Array.isArray(value) ? value : value ? [value] : []);
const undo = (): void => {
if (!deleted) return;
const { note, at } = deleted;
deleted = null;
setS((prev) => ({ ...prev, notes: [...prev.notes.slice(0, at), note, ...prev.notes.slice(at)] }));
};
const setFilter = (value: string | string[] | null): void => {
setS((prev) => ({ ...prev, filter: asStrings(value) as LabelId[] }));
};
const pin = (note: Note): void => {
setS((prev) => ({ ...prev, notes: prev.notes.map((n) => (n === note ? { ...n, pinned: !n.pinned } : n)) }));
};
const shownCount = () => visible(s()).length;
const pinnedNotes = () => visible(s()).filter((n) => n.pinned);
const otherNotes = () => visible(s()).filter((n) => !n.pinned);
const noteCard = (note: Note) => (
<Card headline={note.title}>
<IconButton
slot="header-action"
toggle
selected={note.pinned}
icon={PIN_ICON}
ariaLabel={`Pin ${note.title}`}
onChange={() => pin(note)}
/>
<p>{note.text}</p>
<Show when={note.labels.length > 0}>
<Chips value={s().filter.join(",")} onChange={(e) => setFilter(e.detail.value)}>
<For each={note.labels}>{(id) => <Chip label={labelOf(id)} value={id} />}</For>
</Chips>
</Show>
<div slot="actions" class="notes__card-actions">
<Button variant="text" ariaLabel={`Open ${note.title}`} onClick={() => open(note)}>Open</Button>
<IconButton icon={DELETE_ICON} ariaLabel={`Delete ${note.title}`} onClick={() => remove(note)} />
</div>
</Card>
);
const grid = (notes: Note[]) => <div class={`notes__grid ${s().view}`}>{notes.map(noteCard)}</div>;
const editorFields = (
<div class="notes__fields">
<TextField label="Title" value={draft()?.title ?? ""} onInput={(e) => setDraft((d) => (d ? { ...d, title: e.detail.value } : d))} />
<TextField label="Note" type="multiline" value={draft()?.text ?? ""} onInput={(e) => setDraft((d) => (d ? { ...d, text: e.detail.value } : d))} />
<Chips value={(draft()?.labels ?? []).join(",")} onChange={(e) => setDraft((d) => (d ? { ...d, labels: asStrings(e.detail.value) as LabelId[] } : d))}>
<For each={LABELS}>{(l) => <Chip label={l.text} value={l.value} />}</For>
</Chips>
</div>
);
const editorButtons = (
<>
<Button variant="outlined" onClick={() => (draft()?.note ? remove(draft()!.note!) : setDraft(null))}>Delete</Button>
<Button variant="text" onClick={() => setDraft(null)}>Cancel</Button>
<Button onClick={save}>Save</Button>
</>
);
return (
<section class="notes">
<div class="notes__bar">
<Search placeholder="Search notes" onInput={(e) => setS((prev) => ({ ...prev, query: e.detail.value }))} />
<ButtonGroup kind="connected" selection="single" required value={s().view} onChange={(e) => setS((prev) => ({ ...prev, view: e.detail.value === "list" ? "list" : "grid" }))}>
<ButtonGroupItem icon={GRID_ICON} value="grid" ariaLabel="Grid view" />
<ButtonGroupItem icon={LIST_ICON} value="list" ariaLabel="List view" />
</ButtonGroup>
</div>
<Chips value={s().filter.join(",")} onChange={(e) => setFilter(e.detail.value)}>
<For each={LABELS}>{(l) => <Chip label={l.text} value={l.value} />}</For>
</Chips>
<output class="notes__status" role="status">{status(s())}</output>
<Show
when={shownCount() > 0}
fallback={<p class="notes__empty">No notes match.</p>}
>
<Show when={pinnedNotes().length > 0}>
<section class="notes__section">
<h2>Pinned</h2>
{grid(pinnedNotes())}
</section>
</Show>
<Show when={otherNotes().length > 0}>
<section class="notes__section">
<h2>Notes</h2>
{grid(otherNotes())}
</section>
</Show>
</Show>
<ExtendedFab icon={ADD_ICON} ariaLabel="New note" onClick={() => open(null)}>New note</ExtendedFab>
<Show
when={narrow}
fallback={
<Dialog open={draft() !== null} headline={draft()?.note ? "Edit note" : "New note"} onClose={() => setDraft(null)}>
{editorFields}
<div slot="actions" class="notes__editor-actions">
{editorButtons}
</div>
</Dialog>
}
>
<BottomSheet open={draft() !== null} title={draft()?.note ? "Edit note" : "New note"} onClose={() => setDraft(null)}>
{editorFields}
<div class="notes__editor-actions">{editorButtons}</div>
</BottomSheet>
</Show>
<Snackbar ref={setSnackbar} message="Note deleted" action="Undo" duration="4000" dismissible onAction={undo} />
</section>
);
}
// The state every variant of this example shares, the notes it starts from, and
// how the state is described. check.ts drives it, and check-examples compares
// what each framework shows.
export type LabelId = "ideas" | "shopping" | "work" | "travel";
export const LABELS: { value: LabelId; text: string }[] = [
{ value: "ideas", text: "Ideas" },
{ value: "shopping", text: "Shopping" },
{ value: "work", text: "Work" },
{ value: "travel", text: "Travel" },
];
export interface Note {
id: string;
title: string;
text: string;
labels: LabelId[];
pinned: boolean;
}
export const SEED_NOTES: Note[] = [
{ id: "sauce", title: "Pasta sauce", text: "Fry garlic in olive oil, add torn tomatoes, simmer twenty minutes. Basil at the end.", labels: ["ideas"], pinned: false },
{ id: "groceries", title: "Weekend groceries", text: "Bread, oat milk, lemons, coffee, the good chocolate.", labels: ["shopping"], pinned: false },
{ id: "meeting", title: "Meeting points", text: "Roadmap, hiring plan, support queue. Write down every decision.", labels: ["work"], pinned: true },
{ id: "packing", title: "Packing list", text: "Two shirts, one warm layer, charger, toothbrush, passport.", labels: ["travel", "shopping"], pinned: true },
{ id: "gifts", title: "Gift ideas", text: "A plant for the balcony, a cookbook for the baker, ink for the letter writer.", labels: ["ideas"], pinned: false },
{ id: "walk", title: "City walk route", text: "Bridge, old square, river bank, market on the way back.", labels: ["travel"], pinned: false },
{ id: "priorities", title: "Week priorities", text: "Ship the release notes, review the open pulls, plan Friday morning.", labels: ["work"], pinned: false },
{ id: "prompts", title: "Story prompts", text: "A lighthouse that answers letters. A market that only opens at dusk.", labels: ["ideas"], pinned: false },
{ id: "borrow", title: "Books to borrow", text: "The gardening one, the poetry anthology, the train atlas.", labels: ["shopping"], pinned: false },
{ id: "repairs", title: "Flat repairs", text: "Fix the kitchen drawer, replace the hall bulb, defrost the freezer.", labels: ["work"], pinned: false },
{ id: "sourdough", title: "Sourdough steps", text: "Feed the starter tonight, shape in the morning, bake with steam.", labels: ["ideas"], pinned: false },
];
export interface State {
notes: Note[];
filter: LabelId[];
query: string;
view: "grid" | "list";
}
export const DEFAULTS: State = {
notes: SEED_NOTES.map((note) => ({ ...note, labels: [...note.labels] })),
filter: [],
query: "",
view: "grid",
};
export const labelOf = (id: LabelId): string => LABELS.find((l) => l.value === id)!.text;
/** The notes the grid shows: the filter's labels, then the search's words. */
export const visible = (s: State): Note[] =>
s.notes.filter(
(n) =>
(s.filter.length === 0 || n.labels.some((l) => s.filter.includes(l))) &&
(s.query === "" || `${n.title} ${n.text}`.toLowerCase().includes(s.query.toLowerCase())),
);
export const status = (s: State): string => `Showing ${visible(s).length} of ${s.notes.length} notes.`;
// The icons the interface uses, as the components take them: Material Symbols
// (Apache 2.0, fonts.google.com/icons), the same files scripts/icons.ts fetches.
export const ADD_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-440H240q-17 0-28.5-11.5T200-480q0-17 11.5-28.5T240-520h200v-200q0-17 11.5-28.5T480-760q17 0 28.5 11.5T520-720v200h200q17 0 28.5 11.5T760-480q0 17-11.5 28.5T720-440H520v200q0 17-11.5 28.5T480-200q-17 0-28.5-11.5T440-240v-200Z"/></svg>';
export const PIN_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40v280Zm-286 80h252l-46-46v-314H400v314l-46 46Zm126 0Z"/></svg>';
export const DELETE_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M280-120q-33 0-56.5-23.5T200-200v-520q-17 0-28.5-11.5T160-760q0-17 11.5-28.5T200-800h160q0-17 11.5-28.5T400-840h160q17 0 28.5 11.5T600-800h160q17 0 28.5 11.5T800-760q0 17-11.5 28.5T760-720v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM428.5-291.5Q440-303 440-320v-280q0-17-11.5-28.5T400-640q-17 0-28.5 11.5T360-600v280q0 17 11.5 28.5T400-280q17 0 28.5-11.5Zm160 0Q600-303 600-320v-280q0-17-11.5-28.5T560-640q-17 0-28.5 11.5T520-600v280q0 17 11.5 28.5T560-280q17 0 28.5-11.5ZM280-720v520-520Z"/></svg>';
export const GRID_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M120-520v-320h320v320H120Zm0 400v-320h320v320H120Zm400-400v-320h320v320H520Zm0 400v-320h320v320H520Z"/></svg>';
export const LIST_ICON = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" fill="currentColor" aria-hidden="true"><path d="M360-680v-80h480v80H360Zm0 240v-80h480v80H360Zm0 240v-80h480v80H360ZM200-680q-17 0-28.5-11.5T160-720q0-17 11.5-28.5T200-760q17 0 28.5 11.5T240-720q0 17-11.5 28.5T200-680Zm0 240q-17 0-28.5-11.5T160-480q0-17 11.5-28.5T200-520q17 0 28.5 11.5T240-480q0 17-11.5 28.5T200-440Zm0 240q-17 0-28.5-11.5T160-240q0-17 11.5-28.5T200-280q17 0 28.5 11.5T240-240q0 17-11.5 28.5T200-200Z"/></svg>';